<commit_before>self.port.on("showLoading", function (oMediathek) {
	setLayer("#loadingLayer");
});

self.port.on("showNoMediathek", function (oMediathek) {
	setLayer("#noMediathekLayer");
});

self.port.on("showURLs", function (oVideoURLs) {
	var node = $("#selectionLayer");
	node.html("");

	if (oVideoURLs == null) {
		node.html("Beim Finden der Video-Dateien ist leider ein Fehler aufgetreten.")
		return;
	}

	for (var i = 0; i < oVideoURLs.length; i++) {
		var btn = $("<button class='btn btn-primary btn-download'>" + oVideoURLs[i].desc + " (" + round(oVideoURLs[i].fs / 1024 / 1024) + " mb)</button>");

		//This (complex) ways is needed because otherwise the data would just be
		//referenced, not copied - this would result in problems because of iterating
		(function (oURL) {
			btn.click(function () {
					self.port.emit("URLSelected", {url: oURL.url, name: oURL.desc});
			});
		})(oVideoURLs[i]);

		node.append(btn);
	}

	setLayer("#selectionLayer");
});

function setLayer (sLayerId) {
	$("div").hide();
	$(sLayerId).show();
}

function round(iVal) {
	return Math.round(iVal * 100) / 100;
}
<commit_msg>Correction of spelling mistake<commit_after>self.port.on("showLoading", function (oMediathek) {
	setLayer("#loadingLayer");
});

self.port.on("showNoMediathek", function (oMediathek) {
	setLayer("#noMediathekLayer");
});

self.port.on("showURLs", function (oVideoURLs) {
	var node = $("#selectionLayer");
	node.html("");

	if (oVideoURLs == null) {
		node.html("Beim Suchen der Video-Dateien ist leider ein Fehler aufgetreten.")
		return;
	}

	for (var i = 0; i < oVideoURLs.length; i++) {
		var btn = $("<button class='btn btn-primary btn-download'>" + oVideoURLs[i].desc + " (" + round(oVideoURLs[i].fs / 1024 / 1024) + " mb)</button>");

		//This (complex) ways is needed because otherwise the data would just be
		//referenced, not copied - this would result in problems because of iterating
		(function (oURL) {
			btn.click(function () {
					self.port.emit("URLSelected", {url: oURL.url, name: oURL.desc});
			});
		})(oVideoURLs[i]);

		node.append(btn);
	}

	setLayer("#selectionLayer");
});

function setLayer (sLayerId) {
	$("div").hide();
	$(sLayerId).show();
}

function round(iVal) {
	return Math.round(iVal * 100) / 100;
}
<|endoftext|>


<commit_before>/**
 * Created by jtun02 on 15/4/22.
 */

var Q = (function() {
    var qs = (location.search.length > 0 ? decodeURIComponent(location.search.substring(1)) : '');

    var args = {};

    var items = qs.split('&');
    var item = null,
        key = null,
        value = null;

    for (var i = 0; i < items.length; i ++) {
        item = items[i].split('=');
        key = decodeURIComponent(item[0]);
        value = decodeURIComponent(item[1]);
        args[key] = value;
    }
    return args;
})();

//常用
var commons = {
    //正则
    Regexp : {},
    //实用方法  Practical Method
    PraMethod: {},

    TempMethod: {}
};
//手机号码正则表达式
commons.Regexp.mRep = /^0?(13[0-9]|15[0123456789]|17[0-9]|18[0123456789]|14[57])[0-9]{8}$/;
commons.Regexp.eRep = /^([a-zA-Z0-9\._-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
commons.Regexp.ticket = /^[1-9]\d*$/;
//分页
commons.PraMethod.pagination = function(arr, count) {
    var result = [];
    var i;
    var len = arr.length;
    var num = Math.ceil(len / count);

    for(i = 0; i < num; i++)
    {
        var child = [];
        var next = i +1;
        if(next*count < len)
        {
            child = arr.slice(i*count,next*count);
        }
        else
        {
            child = arr.slice(i*count,arr.length);
        }
        result.push(child);
        if(child.length == 0)
        {
            break;
        }
    }
    return result;
};

//函数
commons.PraMethod.isFunction = function(callback) {
    if (Object.prototype.toString.call(callback).slice(8, -1) == 'Function') {
        return true;
    }
    return false;
};

//微信浏览器
commons.PraMethod.isWeichatBro = function() {
    var device = navigator.userAgent.toLowerCase();
    if (/mobile/.test(device) && /micromessenger/.test(device)) {
        return true;
    }
    return false;
};

//分享到微博
/**
 *
 * @param sns : sina or tencent
 * @param para {title:String(分享title), desc:String(分享内容), url:String(分享地址), pic:String(图片地址)}
 * @constructor
 */
commons.PraMethod.shareToWeibo = function(sns, para) {

    var _pre = sns == 'sina' ?
        'http://v.t.sina.com.cn/share/share.php?searchPic=false&' :
        'http://v.t.qq.com/share/share.php?';

    var link = _pre + 'title=' +
        _e(para.title) +
        _e(para.desc) +
        '&url=' + _e(para.url) +
        (sns == 'sina' ?
        '&content=utf-8&sourceUrl=' + _e(para.url) + '&pic=' + _e(para.picurl) :
        '&pic=' + _e(para.picurl));

    window.open(link, 'newwindow','height=400,width=400,top=100,left=100');

    function _e(t) {
        return encodeURIComponent(t)
    }
};

//浏览器种类
commons.PraMethod.transitionEvent = function() {
    var t;
    var el = document.createElement('fakeelement');
    var transitions = {
        'transition':'transitionend',
        'OTransition':'oTransitionEnd',
        'MozTransition':'transitionend',
        'WebkitTransition':'webkitTransitionEnd'
    };

    var animations = {
        'animation':'animationend',
        'OAnimation':'oAnimationEnd',
        'MozAnimation':'animationend',
        'WebkitAnimation':'webkitAnimationEnd'
    };

    var e = {};

    for(t in transitions){
        if( el.style[t] !== undefined ){
            e.tr = transitions[t];
        }
    }

    for(t in animations) {
        if (el.style[t] !== undefined) {
            e.ani = animations[t];
        }
    }

    return e;
};

//local storage
commons.PraMethod.localStorage = function(key, obj) {
    var l = window.localStorage;
    if (typeof key != 'string') {
        throw new Error('wrong key !!!');
    }

    if (obj) {
        l.removeItem(key);
        if (obj == true) {
            return;
        }
        if (typeof obj != 'object') {
            l.setItem(key, obj);
        } else {
            l.setItem(key, JSON.stringify(obj));
        }
    }
    else {
        var ls = undefined;
        try {
            ls = JSON.parse(l.getItem(key));
        } catch (err) {
            ls = l.getItem(key);
        }
        return ls;
    }
};

/**
 *
 * @param range :jquery|zepto
 * @param onloading :function
 * @param onfinishload :function
 * @constructor
 */
//页面加载loading
commons.PraMethod.ImgLoader = function(range, onloading, onfinishload) {
    this.total = 0;
    this.imgs = [];
    this.current = 0;
    this.range = range || $('body');
    this.onloading = onloading;
    this.onfinishload = onfinishload;
};
commons.PraMethod.ImgLoader.prototype.init = function() {
    var self = this;

    function imgload() {
        if (self.current == self.total) {
            typeof self.onfinishload == 'function' && self.onfinishload();
            return;
        }
        if (self.current > self.total) return;
        typeof self.onloading == 'function' && self.onloading(self.current, self.total);
    }

    self.range.find('img').each(function() {
        var i = new Image();
        i.src = $(this).attr('src');
        if (/(.jpg|.png|.gif)/gi.test(i.src)) {
            self.imgs.push(i);
        }
    });
    self.total = self.imgs.length;
    self.imgs.forEach(function(item, index, array) {
        if (item.complete) {
            self.current += 1;
            imgload();
        }
        else {
            item.onload = function(e) {
                self.current += 1;
                imgload();
            };
            item.onerror = function() {
                self.current += 1;
                imgload();
                throw new Error(item.src + ' was not found');
            };
        }
    });
};

//身份证号验证
commons.PraMethod.IDvf = function(_n) {

    var _nx = ('7－9－10－5－8－4－2－1－6－3－7－9－10－5－8－4－2').split('－');
    var _an = _n.split('');
    var _vf = ('1－0－X－9－8－7－6－5－4－3－2').split('－');
    var _sum = 0;

    var _r = /^(\d{17}(\d|X|x))$/;

    if (_n.length != 18) {
        return false;
    }

    if (!_r.test(_n)) {
        return false;
    }

    for (var i = 0; i < _nx.length; i++) {
        _sum += _nx[i]*_an[i];
    }

    if (_an[17].toUpperCase() == _vf[_sum%11]) {

        return true;
    }

    return false;
};

//base64
commons.PraMethod.base64 = (function() {
    var base64 = {};
    base64.map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
    base64.decode = function(s){
        s += '';
        var len = s.length;
        if((len === 0) || (len % 4 !== 0)){
            return s;
        }

        var pads = 0;
        if(s.charAt(len - 1) === base64.map[64]){
            pads++;
            if(s.charAt(len - 2) === base64.map[64]){
                pads++;
            }
            len -= 4;
        }

        var i, b, map = base64.map, x = [];
        for(i = 0; i < len; i += 4){
            b = (map.indexOf(s.charAt(i)) << 18) | (map.indexOf(s.charAt(i + 1)) << 12) | (map.indexOf(s.charAt(i + 2)) << 6) | map.indexOf(s.charAt(i + 3));
            x.push(String.fromCharCode(b >> 16, (b >> 8) & 0xff, b & 0xff));
        }

        switch(pads){
            case 1:
                b = (map.indexOf(s.charAt(i)) << 18) | (map.indexOf(s.charAt(i)) << 12) | (map.indexOf(s.charAt(i)) << 6);
                x.push(String.fromCharCode(b >> 16, (b >> 8) & 0xff));
                break;
            case 2:
                b = (map.indexOf(s.charAt(i)) << 18) | (map.indexOf(s.charAt(i)) << 12);
                x.push(String.fromCharCode(b >> 16));
                break;
        }
        return unescape(x.join(''));
    };

    base64.encode = function(s){
        if(!s){
            return;
        }

        s += '';
        if(s.length === 0){
            return s;
        }
        s = escape(s);

        var i, b, x = [], map = base64.map, padchar = map[64];
        var len = s.length - s.length % 3;

        for(i = 0; i < len; i += 3){
            b = (s.charCodeAt(i) << 16) | (s.charCodeAt(i+1) << 8) | s.charCodeAt(i+2);
            x.push(map.charAt(b >> 18));
            x.push(map.charAt((b >> 12) & 0x3f));
            x.push(map.charAt((b >> 6) & 0x3f));
            x.push(map.charAt(b & 0x3f));
        }

        switch(s.length - len){
            case 1:
                b = s.charCodeAt(i) << 16;
                x.push(map.charAt(b >> 18) + map.charAt((b >> 12) & 0x3f) + padchar + padchar);
                break;
            case 2:
                b = (s.charCodeAt(i) << 16) | (s.charCodeAt(i + 1) << 8);
                x.push(map.charAt(b >> 18) + map.charAt((b >> 12) & 0x3f) + map.charAt((b >> 6) & 0x3f) + padchar);
                break;
        }
        return x.join('');
    };

    return base64;
})();

commons.PraMethod.Base64 = function () {

    // private property
    var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    // public method for encoding
    this.encode = function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
        input = _utf8_encode(input);
        while (i < input.length) {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
            output = output +
                _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
                _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
        }
        return output;
    }

    // public method for decoding
    this.decode = function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < input.length) {
            enc1 = _keyStr.indexOf(input.charAt(i++));
            enc2 = _keyStr.indexOf(input.charAt(i++));
            enc3 = _keyStr.indexOf(input.charAt(i++));
            enc4 = _keyStr.indexOf(input.charAt(i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }
        output = _utf8_decode(output);
        return output;
    }

    // private method for UTF-8 encoding
    var _utf8_encode = function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            } else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            } else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }
        return utftext;
    }

    // private method for UTF-8 decoding
    var _utf8_decode = function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while ( i < utftext.length ) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
}

commons.TempMethod.imgLayout = function(ele) {
    var imgs = document.querySelectorAll(ele);
    [].forEach.call(imgs, function(img, index, array) {

        if (img.complete) {
            console.log('complete');
            ol(img);
        } else {
            img.onload = function() {
                console.log('load');
                ol(img);
            }
        }

    });

    function ol(img) {
        img.removeAttribute('width');
        img.removeAttribute('height');
        var nh = img.naturalHeight,
            nw = img.naturalWidth;
        if (nh > nw) {
            $(img).attr('width','100%')
        } else {
            $(img).attr('height','100%');
        }
    }
};<commit_msg>other-common<commit_after>/**
 * Created by jtun02 on 15/4/22.
 */

var Q = (function() {
    var qs = (location.search.length > 0 ? decodeURIComponent(location.search.substring(1)) : '');

    var args = {};

    var items = qs.split('&');
    var item = null,
        key = null,
        value = null;

    for (var i = 0; i < items.length; i ++) {
        item = items[i].split('=');
        key = decodeURIComponent(item[0]);
        value = decodeURIComponent(item[1]);
        args[key] = value;
    }
    return args;
})();

//常用
var commons = {
    //正则
    Regexp : {},
    //实用方法  Practical Method
    PraMethod: {},

    TempMethod: {}
};
//手机号码正则表达式
commons.Regexp.mRep = /^0?(13[0-9]|15[0123456789]|17[0-9]|18[0123456789]|14[57])[0-9]{8}$/;
commons.Regexp.eRep = /^([a-zA-Z0-9\._-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
commons.Regexp.ticket = /^[1-9]\d*$/;
//分页
commons.PraMethod.pagination = function(arr, count) {
    var result = [];
    var i;
    var len = arr.length;
    var num = Math.ceil(len / count);

    for(i = 0; i < num; i++)
    {
        var child = [];
        var next = i +1;
        if(next*count < len)
        {
            child = arr.slice(i*count,next*count);
        }
        else
        {
            child = arr.slice(i*count,arr.length);
        }
        result.push(child);
        if(child.length == 0)
        {
            break;
        }
    }
    return result;
};

//函数
commons.PraMethod.isFunction = function(callback) {
    if (Object.prototype.toString.call(callback).slice(8, -1) == 'Function') {
        return true;
    }
    return false;
};

//微信浏览器
commons.PraMethod.isWeichatBro = function() {
    var device = navigator.userAgent.toLowerCase();
    if (/mobile/.test(device) && /micromessenger/.test(device)) {
        return true;
    }
    return false;
};

//分享到微博
/**
 *
 * @param sns : sina or tencent
 * @param para {title:String(分享title), desc:String(分享内容), url:String(分享地址), pic:String(图片地址)}
 * @constructor
 */
commons.PraMethod.shareToWeibo = function(sns, para) {

    var _pre = sns == 'sina' ?
        'http://v.t.sina.com.cn/share/share.php?searchPic=false&' :
        'http://v.t.qq.com/share/share.php?';

    var link = _pre + 'title=' +
        _e(para.title) +
        _e(para.desc) +
        '&url=' + _e(para.url) +
        (sns == 'sina' ?
        '&content=utf-8&sourceUrl=' + _e(para.url) + '&pic=' + _e(para.picurl) :
        '&pic=' + _e(para.picurl));

    window.open(link, 'newwindow','height=400,width=400,top=100,left=100');

    function _e(t) {
        return encodeURIComponent(t)
    }
};

//浏览器种类
commons.PraMethod.transitionEvent = function() {
    var t;
    var el = document.createElement('fakeelement');
    var transitions = {
        'transition':'transitionend',
        'OTransition':'oTransitionEnd',
        'MozTransition':'transitionend',
        'WebkitTransition':'webkitTransitionEnd'
    };

    var animations = {
        'animation':'animationend',
        'OAnimation':'oAnimationEnd',
        'MozAnimation':'animationend',
        'WebkitAnimation':'webkitAnimationEnd'
    };

    var e = {};

    for(t in transitions){
        if( el.style[t] !== undefined ){
            e.tr = transitions[t];
        }
    }

    for(t in animations) {
        if (el.style[t] !== undefined) {
            e.ani = animations[t];
        }
    }

    return e;
};

//local storage
commons.PraMethod.localStorage = function(key, obj) {
    var l = window.localStorage;
    if (typeof key != 'string') {
        throw new Error('wrong key !!!');
    }

    if (obj !== undefined && obj !== null) {
        l.removeItem(key);
        if (obj === true) {
            return;
        }
        if (typeof obj != 'object') {
            l.setItem(key, obj);
        } else {
            l.setItem(key, JSON.stringify(obj));
        }
    }
    else {
        var ls = undefined;
        try {
            ls = JSON.parse(l.getItem(key));
        } catch (err) {
            ls = l.getItem(key);
        }
        return ls;
    }
};

/**
 *
 * @param range :jquery|zepto
 * @param onloading :function
 * @param onfinishload :function
 * @constructor
 */
//页面加载loading
commons.PraMethod.ImgLoader = function(range, onloading, onfinishload) {
    this.total = 0;
    this.imgs = [];
    this.current = 0;
    this.range = range || $('body');
    this.onloading = onloading;
    this.onfinishload = onfinishload;
};
commons.PraMethod.ImgLoader.prototype.init = function() {
    var self = this;

    function imgload() {
        if (self.current == self.total) {
            typeof self.onfinishload == 'function' && self.onfinishload();
            return;
        }
        if (self.current > self.total) return;
        typeof self.onloading == 'function' && self.onloading(self.current, self.total);
    }

    self.range.find('img').each(function() {
        var i = new Image();
        i.src = $(this).attr('src');
        if (/(.jpg|.png|.gif)/gi.test(i.src)) {
            self.imgs.push(i);
        }
    });
    self.total = self.imgs.length;
    self.imgs.forEach(function(item, index, array) {
        if (item.complete) {
            self.current += 1;
            imgload();
        }
        else {
            item.onload = function(e) {
                self.current += 1;
                imgload();
            };
            item.onerror = function() {
                self.current += 1;
                imgload();
                throw new Error(item.src + ' was not found');
            };
        }
    });
};

//身份证号验证
commons.PraMethod.IDvf = function(_n) {

    var _nx = ('7－9－10－5－8－4－2－1－6－3－7－9－10－5－8－4－2').split('－');
    var _an = _n.split('');
    var _vf = ('1－0－X－9－8－7－6－5－4－3－2').split('－');
    var _sum = 0;

    var _r = /^(\d{17}(\d|X|x))$/;

    if (_n.length != 18) {
        return false;
    }

    if (!_r.test(_n)) {
        return false;
    }

    for (var i = 0; i < _nx.length; i++) {
        _sum += _nx[i]*_an[i];
    }

    if (_an[17].toUpperCase() == _vf[_sum%11]) {

        return true;
    }

    return false;
};

//base64
commons.PraMethod.base64 = (function() {
    var base64 = {};
    base64.map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
    base64.decode = function(s){
        s += '';
        var len = s.length;
        if((len === 0) || (len % 4 !== 0)){
            return s;
        }

        var pads = 0;
        if(s.charAt(len - 1) === base64.map[64]){
            pads++;
            if(s.charAt(len - 2) === base64.map[64]){
                pads++;
            }
            len -= 4;
        }

        var i, b, map = base64.map, x = [];
        for(i = 0; i < len; i += 4){
            b = (map.indexOf(s.charAt(i)) << 18) | (map.indexOf(s.charAt(i + 1)) << 12) | (map.indexOf(s.charAt(i + 2)) << 6) | map.indexOf(s.charAt(i + 3));
            x.push(String.fromCharCode(b >> 16, (b >> 8) & 0xff, b & 0xff));
        }

        switch(pads){
            case 1:
                b = (map.indexOf(s.charAt(i)) << 18) | (map.indexOf(s.charAt(i)) << 12) | (map.indexOf(s.charAt(i)) << 6);
                x.push(String.fromCharCode(b >> 16, (b >> 8) & 0xff));
                break;
            case 2:
                b = (map.indexOf(s.charAt(i)) << 18) | (map.indexOf(s.charAt(i)) << 12);
                x.push(String.fromCharCode(b >> 16));
                break;
        }
        return unescape(x.join(''));
    };

    base64.encode = function(s){
        if(!s){
            return;
        }

        s += '';
        if(s.length === 0){
            return s;
        }
        s = escape(s);

        var i, b, x = [], map = base64.map, padchar = map[64];
        var len = s.length - s.length % 3;

        for(i = 0; i < len; i += 3){
            b = (s.charCodeAt(i) << 16) | (s.charCodeAt(i+1) << 8) | s.charCodeAt(i+2);
            x.push(map.charAt(b >> 18));
            x.push(map.charAt((b >> 12) & 0x3f));
            x.push(map.charAt((b >> 6) & 0x3f));
            x.push(map.charAt(b & 0x3f));
        }

        switch(s.length - len){
            case 1:
                b = s.charCodeAt(i) << 16;
                x.push(map.charAt(b >> 18) + map.charAt((b >> 12) & 0x3f) + padchar + padchar);
                break;
            case 2:
                b = (s.charCodeAt(i) << 16) | (s.charCodeAt(i + 1) << 8);
                x.push(map.charAt(b >> 18) + map.charAt((b >> 12) & 0x3f) + map.charAt((b >> 6) & 0x3f) + padchar);
                break;
        }
        return x.join('');
    };

    return base64;
})();

commons.PraMethod.Base64 = function () {

    // private property
    var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    // public method for encoding
    this.encode = function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
        input = _utf8_encode(input);
        while (i < input.length) {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
            output = output +
                _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
                _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
        }
        return output;
    }

    // public method for decoding
    this.decode = function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < input.length) {
            enc1 = _keyStr.indexOf(input.charAt(i++));
            enc2 = _keyStr.indexOf(input.charAt(i++));
            enc3 = _keyStr.indexOf(input.charAt(i++));
            enc4 = _keyStr.indexOf(input.charAt(i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }
        output = _utf8_decode(output);
        return output;
    }

    // private method for UTF-8 encoding
    var _utf8_encode = function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            } else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            } else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }
        return utftext;
    }

    // private method for UTF-8 decoding
    var _utf8_decode = function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while ( i < utftext.length ) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
}

commons.TempMethod.imgLayout = function(ele) {
    var imgs = document.querySelectorAll(ele);
    [].forEach.call(imgs, function(img, index, array) {

        if (img.complete) {
            console.log('complete');
            ol(img);
        } else {
            img.onload = function() {
                console.log('load');
                ol(img);
            }
        }

    });

    function ol(img) {
        img.removeAttribute('width');
        img.removeAttribute('height');
        var nh = img.naturalHeight,
            nw = img.naturalWidth;
        if (nh > nw) {
            $(img).attr('width','100%')
        } else {
            $(img).attr('height','100%');
        }
    }
};<|endoftext|>


<commit_before>'use strict';

(function() {
  var app = angular.module('upsConsole', [
    'upsConsole.services',
    'ngResource',
    'ngRoute',
    'ui.bootstrap',
    'ups.directives',
    'patternfly.notification',
    'hljs'
  ]);

  /**
   * Snippet extracted from Keycloak examples
   */
  var auth = {};

  angular.element(document).ready(function () {
    var keycloakAuth = new Keycloak('keycloak.json');
    auth.loggedIn = false;

    keycloakAuth.init({ onLoad: 'login-required' }).success(function () {
      auth.loggedIn = true;
      auth.authz = keycloakAuth;
      auth.logoutUrl = keycloakAuth.authServerUrl + '/realms/aerogear/tokens/logout?redirect_uri=' + window.location.href;
      app.factory('Auth', function () {
        return auth;
      });
      angular.bootstrap(document, ['upsConsole']);
    }).error(function () {
      window.location.reload();
    });

  });

  app.factory('Auth', function () {
    return auth;
  });

  app.config(function ($routeProvider) {

    $routeProvider
      .when('/applications', {
        templateUrl: 'views/applications.html',
        controller: 'ApplicationController',
        resolve: {
          applications: function (pushApplication) {
            return pushApplication.query().$promise;
          }
        },
        section: 'applications',
        crumb: {
          id: 'apps',
          label: 'Applications'
        }
      })
      .when('/detail/:applicationId', {
        templateUrl: 'views/detail.html',
        controller: 'DetailController',
        resolve: {
          application: function ($route, pushApplication) {
            return pushApplication.get({appId: $route.current.params.applicationId}).$promise;
          },
          counts: function ($route, pushApplication) {
            return pushApplication.count({appId: $route.current.params.applicationId}).$promise;
          }
        },
        section: 'applications',
        crumb: {
          id: 'app-detail',
          parent: 'apps',
          label: '$ application.name ? application.name : "Current Application"'
        }
      })
      .when('/:applicationId/installations/:variantId', {
        templateUrl: 'views/installation.html',
        controller: 'InstallationController',
        section: 'applications',
        crumb: {
          parent: 'app-detail',
          label: '$ variant.name ? variant.name : "Registering Installations"'
        }
      })
      .when('/example/:applicationId/:variantType/:variantId', {
        templateUrl: 'views/example.html',
        controller: 'ExampleController',
        section: 'applications',
        crumb: {
          parent: 'app-detail',
          label: 'Example'
        }
      })
      .when('/example/:applicationId/:variantType', {
        templateUrl: 'views/example.html',
        controller: 'ExampleController',
        section: 'applications',
        crumb: {
          parent: 'app-detail',
          label: 'Example'
        }
      })
      .when('/compose', {
        templateUrl: 'views/compose-app.html',
        controller: 'PreComposeController',
        resolve: {
          applications: function (pushApplication) {
            return pushApplication.query({}).$promise;
          }
        },
        section: 'compose',
        crumb: {
          label: 'Send Push'
        }
      })
      .when('/compose/:applicationId', {
        templateUrl: 'views/compose.html',
        controller: 'ComposeController',
        section: 'compose',
        crumb: {
          parent: 'app-detail',
          label: 'Send Push'
        }
      })
      .when('/dashboard', {
        templateUrl: 'views/dashboard.html',
        controller: 'DashboardController',
        resolve: {
          totals: function (dashboard) {
            return dashboard.totals({}).$promise;
          },
          warnings: function (dashboard) {
            return dashboard.warnings({}).$promise;
          },
          topThree: function (dashboard) {
            return dashboard.topThree({}).$promise;
          }
        },
        section: 'dashboard',
        crumb: {
          id: 'dash',
          label: 'Dashboard'
        }
      })
      .when('/activity/:applicationId', {
        templateUrl: 'views/notification.html',
        controller: 'ActivityController',
        section: 'dashboard',
        crumb: {
          id: 'activity',
          parent: 'dash',
          label: '$ application.name ? application.name : "Current Application"'
        }
      })
      .when('/activity/:applicationId/:variantId', {
        templateUrl: 'views/notification.html',
        controller: 'ActivityController',
        section: 'dashboard',
        crumb: {
          parent: 'activity',
          label: '$ variant.name ? variant.name : "Current variant"'
        }
      })
      .otherwise({
        redirectTo: '/dashboard'
      });
  });

  app.factory('authInterceptor', function ($q, Auth) {
    return {
      request: function (config) {
        var deferred = $q.defer();

        if (config.url === 'rest/sender') {
          return config;
        }

        if (Auth.authz.token) {
          Auth.authz.updateToken(5).success(function () {
            config.headers = config.headers || {};
            config.headers.Authorization = 'Bearer ' + Auth.authz.token;

            deferred.resolve(config);
          }).error(function () {
            deferred.reject('Failed to refresh token');
          });
        }
        return deferred.promise;
      }
    };
  });

  app.config(function ($httpProvider) {
    //$httpProvider.responseInterceptors.push('errorInterceptor');
    $httpProvider.interceptors.push('authInterceptor');

  });

})();<commit_msg>fix error messages shown during logout AGPUSH-761<commit_after>'use strict';

(function() {
  var app = angular.module('upsConsole', [
    'upsConsole.services',
    'ngResource',
    'ngRoute',
    'ui.bootstrap',
    'ups.directives',
    'patternfly.notification',
    'hljs'
  ]);

  /**
   * Snippet extracted from Keycloak examples
   */
  var auth = {};

  angular.element(document).ready(function () {
    var keycloakAuth = new Keycloak('keycloak.json');
    auth.loggedIn = false;

    keycloakAuth.init({ onLoad: 'login-required' }).success(function () {
      auth.loggedIn = true;
      auth.authz = keycloakAuth;
      auth.logoutUrl = keycloakAuth.authServerUrl + '/realms/aerogear/tokens/logout?redirect_uri=' + window.location.href;
      app.factory('Auth', function () {
        return auth;
      });
      angular.bootstrap(document, ['upsConsole']);
    }).error(function () {
      window.location.reload();
    });

  });

  app.factory('Auth', function () {
    return auth;
  });

  app.config(function ($routeProvider) {

    $routeProvider
      .when('/applications', {
        templateUrl: 'views/applications.html',
        controller: 'ApplicationController',
        resolve: {
          applications: function (pushApplication) {
            return pushApplication.query().$promise;
          }
        },
        section: 'applications',
        crumb: {
          id: 'apps',
          label: 'Applications'
        }
      })
      .when('/detail/:applicationId', {
        templateUrl: 'views/detail.html',
        controller: 'DetailController',
        resolve: {
          application: function ($route, pushApplication) {
            return pushApplication.get({appId: $route.current.params.applicationId}).$promise;
          },
          counts: function ($route, pushApplication) {
            return pushApplication.count({appId: $route.current.params.applicationId}).$promise;
          }
        },
        section: 'applications',
        crumb: {
          id: 'app-detail',
          parent: 'apps',
          label: '$ application.name ? application.name : "Current Application"'
        }
      })
      .when('/:applicationId/installations/:variantId', {
        templateUrl: 'views/installation.html',
        controller: 'InstallationController',
        section: 'applications',
        crumb: {
          parent: 'app-detail',
          label: '$ variant.name ? variant.name : "Registering Installations"'
        }
      })
      .when('/example/:applicationId/:variantType/:variantId', {
        templateUrl: 'views/example.html',
        controller: 'ExampleController',
        section: 'applications',
        crumb: {
          parent: 'app-detail',
          label: 'Example'
        }
      })
      .when('/example/:applicationId/:variantType', {
        templateUrl: 'views/example.html',
        controller: 'ExampleController',
        section: 'applications',
        crumb: {
          parent: 'app-detail',
          label: 'Example'
        }
      })
      .when('/compose', {
        templateUrl: 'views/compose-app.html',
        controller: 'PreComposeController',
        resolve: {
          applications: function (pushApplication) {
            return pushApplication.query({}).$promise;
          }
        },
        section: 'compose',
        crumb: {
          label: 'Send Push'
        }
      })
      .when('/compose/:applicationId', {
        templateUrl: 'views/compose.html',
        controller: 'ComposeController',
        section: 'compose',
        crumb: {
          parent: 'app-detail',
          label: 'Send Push'
        }
      })
      .when('/dashboard', {
        templateUrl: 'views/dashboard.html',
        controller: 'DashboardController',
        resolve: {
          totals: function (dashboard) {
            return dashboard.totals({}).$promise;
          },
          warnings: function (dashboard) {
            return dashboard.warnings({}).$promise;
          },
          topThree: function (dashboard) {
            return dashboard.topThree({}).$promise;
          }
        },
        section: 'dashboard',
        crumb: {
          id: 'dash',
          label: 'Dashboard'
        }
      })
      .when('/activity/:applicationId', {
        templateUrl: 'views/notification.html',
        controller: 'ActivityController',
        section: 'dashboard',
        crumb: {
          id: 'activity',
          parent: 'dash',
          label: '$ application.name ? application.name : "Current Application"'
        }
      })
      .when('/activity/:applicationId/:variantId', {
        templateUrl: 'views/notification.html',
        controller: 'ActivityController',
        section: 'dashboard',
        crumb: {
          parent: 'activity',
          label: '$ variant.name ? variant.name : "Current variant"'
        }
      })
      .otherwise({
        redirectTo: '/dashboard'
      });
  });

  app.factory('authInterceptor', function ($q, Auth) {
    return {
      request: function (config) {
        var deferred = $q.defer();

        if (config.url === 'rest/sender') {
          return config;
        }

        if (Auth.authz && Auth.authz.token) {
          Auth.authz.updateToken(5).success(function () {
            config.headers = config.headers || {};
            config.headers.Authorization = 'Bearer ' + Auth.authz.token;

            deferred.resolve(config);
          }).error(function () {
            deferred.reject('Failed to refresh token');
          });
        }
        return deferred.promise;
      }
    };
  });

  app.config(function ($httpProvider) {
    //$httpProvider.responseInterceptors.push('errorInterceptor');
    $httpProvider.interceptors.push('authInterceptor');

  });

})();<|endoftext|>


<commit_before>var m = require('mithril');
var dialog = require('./dialog');
var partial = require('chessground').util.partial;

var baseUrl = 'https://lichess.org/study/';

module.exports = {
  ctrl: function(data, currentChapter) {
    var open = m.prop(false);
    return {
      open: open,
      toggle: function() {
        open(!open());
      },
      studyId: data.id,
      chapter: currentChapter,
      isPublic: function() {
        return data.visibility === 'public';
      }
    }
  },
  view: function(ctrl) {
    if (!ctrl.open()) return;
    var studyId = ctrl.studyId;
    var chapter = ctrl.chapter();
    return dialog.form({
      onClose: function() {
        ctrl.open(false);
      },
      content: [
        m('h2', 'Share & export'),
        m('form.material.form', [
          m('div.form-group', [
            m('input.has-value.autoselect', {
              readonly: true,
              value: baseUrl + studyId
            }),
            m('label.control-label', 'Study URL'),
            m('i.bar')
          ]),
          m('div.form-group', [
            m('input.has-value.autoselect', {
              readonly: true,
              value: baseUrl + studyId + '#' + chapter.id
            }),
            m('label.control-label', 'Current chapter URL'),
            m('i.bar')
          ]),
          m('div.form-group', [
            m('input.has-value.autoselect', {
              readonly: true,
              disabled: !ctrl.isPublic(),
              value: ctrl.isPublic() ? '' : 'Only public studies can be embedded.'
            }),
            m('a.form-help.text', {
              href: '/developers#embed-study',
              target: '_blank',
              'data-icon': ''
            }, 'Read more about embedding a study chapter'),
            m('label.control-label', 'Embed current chapter'),
            m('i.bar')
          ]),
          m('div.downloads', [
            m('a.button.text.hint--top', {
              'data-icon': 'x',
              href: '/study/' + studyId + '.pgn'
            }, 'Study PGN'),
            m('a.button.text.hint--top', {
              'data-icon': 'x',
              href: '/study/' + studyId + '/' + chapter.id + '.pgn'
            }, 'Current chapter PGN')
          ])
        ])
      ]
    });
  }
};
<commit_msg>study share doc<commit_after>var m = require('mithril');
var dialog = require('./dialog');
var partial = require('chessground').util.partial;

var baseUrl = 'https://lichess.org/study/';

module.exports = {
  ctrl: function(data, currentChapter) {
    var open = m.prop(false);
    return {
      open: open,
      toggle: function() {
        open(!open());
      },
      studyId: data.id,
      chapter: currentChapter,
      isPublic: function() {
        return data.visibility === 'public';
      }
    }
  },
  view: function(ctrl) {
    if (!ctrl.open()) return;
    var studyId = ctrl.studyId;
    var chapter = ctrl.chapter();
    return dialog.form({
      onClose: function() {
        ctrl.open(false);
      },
      content: [
        m('h2', 'Share & export'),
        m('form.material.form', [
          m('div.form-group', [
            m('input.has-value.autoselect', {
              readonly: true,
              value: baseUrl + studyId
            }),
            m('label.control-label', 'Study URL'),
            m('i.bar')
          ]),
          m('div.form-group', [
            m('input.has-value.autoselect', {
              readonly: true,
              value: baseUrl + studyId + '#' + chapter.id
            }),
            m('p.form-help.text', {
              'data-icon': ''
            }, 'Paste this in a forum post to embed the chapter.'),
            m('label.control-label', 'Current chapter URL'),
            m('i.bar')
          ]),
          m('div.form-group', [
            m('input.has-value.autoselect', {
              readonly: true,
              disabled: !ctrl.isPublic(),
              value: ctrl.isPublic() ? '' : 'Only public studies can be embedded.'
            }),
            m('a.form-help.text', {
              href: '/developers#embed-study',
              target: '_blank',
              'data-icon': ''
            }, 'Read more about embedding a study chapter'),
            m('label.control-label', 'Embed current chapter in your website or blog'),
            m('i.bar')
          ]),
          m('div.downloads', [
            m('a.button.text.hint--top', {
              'data-icon': 'x',
              href: '/study/' + studyId + '.pgn'
            }, 'Study PGN'),
            m('a.button.text.hint--top', {
              'data-icon': 'x',
              href: '/study/' + studyId + '/' + chapter.id + '.pgn'
            }, 'Current chapter PGN')
          ])
        ])
      ]
    });
  }
};
<|endoftext|>


<commit_before>var async = require('async');
var changeCase = require('change-case');
require('colors');

function runTest(testName, testObject, callback) {
  let runList = [];
  let specialFunctions = ['beforeAll'];
  let availableFunctions = testObject._jsonInterface.filter((x) => x.type === 'function').map((x) => x.name);
  let testFunctions = testObject._jsonInterface.filter((x) => specialFunctions.indexOf(x.name) < 0 && x.type === 'function');

  if (availableFunctions.indexOf("beforeAll")) {
    runList.push({name: 'beforeAll', type: 'internal', constant: false});
  }

  for (let func of testFunctions) {
    runList.push({name: func.name, type: 'test', constant: func.constant});
  }

  console.log("#" + testName);
  async.eachOfLimit(runList, 1, function(func, index, next) {
    let method = testObject.methods[func.name].apply(testObject.methods[func.name], []);
    if (func.constant) {
      method.call().then((result) => {
        if (result) {
          // TODO: should instead be returned in a callback, the caller can
          // decide how to handle the output (so works both in console and
          // browser)
          console.log("\t✓ ".green.bold + changeCase.sentenceCase(func.name).grey);
        } else {
          console.log("\t✘ ".bold.red + changeCase.sentenceCase(func.name).red);
        }
        next();
      });
    } else {
      method.send().then(() => {
        next();
      });
    }
  }, function() {
    console.log("1 passing".green);
    console.log("1 failing".red);
  });
}

module.exports = {
  runTest: runTest
}
<commit_msg>track passing/failing tests<commit_after>var async = require('async');
var changeCase = require('change-case');
require('colors');

function runTest(testName, testObject, callback) {
  let runList = [];
  let specialFunctions = ['beforeAll'];
  let availableFunctions = testObject._jsonInterface.filter((x) => x.type === 'function').map((x) => x.name);
  let testFunctions = testObject._jsonInterface.filter((x) => specialFunctions.indexOf(x.name) < 0 && x.type === 'function');

  if (availableFunctions.indexOf("beforeAll")) {
    runList.push({name: 'beforeAll', type: 'internal', constant: false});
  }

  for (let func of testFunctions) {
    runList.push({name: func.name, type: 'test', constant: func.constant});
  }

  let passingNum = 0, failureNum = 0;

  console.log(("#" + testName).green);
  async.eachOfLimit(runList, 1, function(func, index, next) {
    let method = testObject.methods[func.name].apply(testObject.methods[func.name], []);
    if (func.constant) {
      method.call().then((result) => {
        if (result) {
          // TODO: should instead be returned in a callback, the caller can
          // decide how to handle the output (so works both in console and
          // browser)
          console.log("\t✓ ".green.bold + changeCase.sentenceCase(func.name).grey);
          passingNum += 1;
        } else {
          console.log("\t✘ ".bold.red + changeCase.sentenceCase(func.name).red);
          failureNum += 1;
        }
        next();
      });
    } else {
      method.send().then(() => {
        next();
      });
    }
  }, function() {
    if (passingNum > 0) {
      console.log((passingNum + " passing").green);
    }
    if (failureNum > 0) {
      console.log((failureNum + " failing").red);
    }
  });
}

module.exports = {
  runTest: runTest
}
<|endoftext|>


<commit_before>"use strict";
const path = require("path");
const fs = require("fs");
const jsYAML = require("js-yaml");
const { Minimatch } = require("minimatch");
const { describe, specify, before } = require("mocha-sugar-free");
const { readManifest, getPossibleTestFilePaths, stripPrefix } = require("./wpt-manifest-utils.js");
const startWPTServer = require("./start-wpt-server.js");

const validReasons = new Set([
  "fail",
  "timeout",
  "flaky",
  "mutates-globals",
  "needs-node10"
]);

const hasNode10 = Number(process.versions.node.split(".")[0]) >= 10;

const manifestFilename = path.resolve(__dirname, "wpt-manifest.json");
const manifest = readManifest(manifestFilename);
const possibleTestFilePaths = getPossibleTestFilePaths(manifest);

const toRunFilename = path.resolve(__dirname, "to-run.yaml");
const toRunString = fs.readFileSync(toRunFilename, { encoding: "utf-8" });
const toRunDocs = jsYAML.safeLoadAll(toRunString, { filename: toRunFilename });

const minimatchers = new Map();

checkToRun();

let wptServerURL;
const runSingleWPT = require("./run-single-wpt.js")(() => wptServerURL);
before({ timeout: 30 * 1000 }, () => {
  return startWPTServer({ toUpstream: false }).then(url => {
    wptServerURL = url;
  });
});

describe("web-platform-tests", () => {
  for (const toRunDoc of toRunDocs) {
    describe(toRunDoc.DIR, () => {
      for (const testFilePath of possibleTestFilePaths) {
        if (testFilePath.startsWith(toRunDoc.DIR + "/")) {
          const matchingPattern = expectationsInDoc(toRunDoc).find(pattern => {
            const matcher = minimatchers.get(toRunDoc.DIR + "/" + pattern);
            return matcher.match(testFilePath);
          });

          const testFile = stripPrefix(testFilePath, toRunDoc.DIR + "/");
          const reason = matchingPattern && toRunDoc[matchingPattern][0];
          const shouldSkip = ["timeout", "flaky", "mutates-globals"].includes(reason);
          const expectFail = (reason === "fail") ||
                             (reason === "needs-node10" && !hasNode10);

          if (matchingPattern && shouldSkip) {
            specify.skip(`[${reason}] ${testFile}`);
          } else {
            runSingleWPT(testFilePath, testFile, expectFail);
          }
        }
      }
    });
  }
});

function checkToRun() {
  let lastDir = "";
  for (const doc of toRunDocs) {
    if (doc.DIR.startsWith("/")) {
      throw new Error(`DIR entries must not start with a slash: saw "${doc.DIR}"`);
    }
    if (doc.DIR.endsWith("/")) {
      throw new Error(`DIR entries must not end with a slash: saw "${doc.DIR}"`);
    }

    if (doc.DIR < lastDir) {
      throw new Error(`Bad lexicographical directory sorting in to-run.yaml: ${doc.DIR} should come before ${lastDir}`);
    }
    lastDir = doc.DIR;

    let lastPattern = "";
    for (const pattern of expectationsInDoc(doc)) {
      if (pattern.startsWith("/")) {
        throw new Error(`Expectation patterns must not start with a slash: saw "${pattern}"`);
      }

      if (pattern < lastPattern) {
        throw new Error("Bad lexicographical expectation pattern sorting in to-run.yaml: " + pattern +
                        " should come before " + lastPattern);
      }
      lastPattern = pattern;

      const reason = doc[pattern][0];
      if (!validReasons.has(reason)) {
        throw new Error(`Bad reason "${reason}" for expectation ${pattern}`);
      }

      const matcher = new Minimatch(doc.DIR + "/" + pattern);
      if (!possibleTestFilePaths.some(filename => matcher.match(filename))) {
        throw new Error(`Expectation pattern "${pattern}" does not match any test files`);
      }
      minimatchers.set(doc.DIR + "/" + pattern, matcher);
    }
  }
}

function expectationsInDoc(doc) {
  const keys = Object.keys(doc);
  keys.shift(); // get rid of the DIR key
  return keys;
}
<commit_msg>Add [expected fail] to test output<commit_after>"use strict";
const path = require("path");
const fs = require("fs");
const jsYAML = require("js-yaml");
const { Minimatch } = require("minimatch");
const { describe, specify, before } = require("mocha-sugar-free");
const { readManifest, getPossibleTestFilePaths, stripPrefix } = require("./wpt-manifest-utils.js");
const startWPTServer = require("./start-wpt-server.js");

const validReasons = new Set([
  "fail",
  "timeout",
  "flaky",
  "mutates-globals",
  "needs-node10"
]);

const hasNode10 = Number(process.versions.node.split(".")[0]) >= 10;

const manifestFilename = path.resolve(__dirname, "wpt-manifest.json");
const manifest = readManifest(manifestFilename);
const possibleTestFilePaths = getPossibleTestFilePaths(manifest);

const toRunFilename = path.resolve(__dirname, "to-run.yaml");
const toRunString = fs.readFileSync(toRunFilename, { encoding: "utf-8" });
const toRunDocs = jsYAML.safeLoadAll(toRunString, { filename: toRunFilename });

const minimatchers = new Map();

checkToRun();

let wptServerURL;
const runSingleWPT = require("./run-single-wpt.js")(() => wptServerURL);
before({ timeout: 30 * 1000 }, () => {
  return startWPTServer({ toUpstream: false }).then(url => {
    wptServerURL = url;
  });
});

describe("web-platform-tests", () => {
  for (const toRunDoc of toRunDocs) {
    describe(toRunDoc.DIR, () => {
      for (const testFilePath of possibleTestFilePaths) {
        if (testFilePath.startsWith(toRunDoc.DIR + "/")) {
          const matchingPattern = expectationsInDoc(toRunDoc).find(pattern => {
            const matcher = minimatchers.get(toRunDoc.DIR + "/" + pattern);
            return matcher.match(testFilePath);
          });

          const testFile = stripPrefix(testFilePath, toRunDoc.DIR + "/");
          const reason = matchingPattern && toRunDoc[matchingPattern][0];
          const shouldSkip = ["timeout", "flaky", "mutates-globals"].includes(reason);
          const expectFail = (reason === "fail") ||
                             (reason === "needs-node10" && !hasNode10);

          if (matchingPattern && shouldSkip) {
            specify.skip(`[${reason}] ${testFile}`);
          } else if (expectFail) {
            runSingleWPT(testFilePath, `[expected fail] ${testFile}`, expectFail);
          } else {
            runSingleWPT(testFilePath, testFile, expectFail);
          }
        }
      }
    });
  }
});

function checkToRun() {
  let lastDir = "";
  for (const doc of toRunDocs) {
    if (doc.DIR.startsWith("/")) {
      throw new Error(`DIR entries must not start with a slash: saw "${doc.DIR}"`);
    }
    if (doc.DIR.endsWith("/")) {
      throw new Error(`DIR entries must not end with a slash: saw "${doc.DIR}"`);
    }

    if (doc.DIR < lastDir) {
      throw new Error(`Bad lexicographical directory sorting in to-run.yaml: ${doc.DIR} should come before ${lastDir}`);
    }
    lastDir = doc.DIR;

    let lastPattern = "";
    for (const pattern of expectationsInDoc(doc)) {
      if (pattern.startsWith("/")) {
        throw new Error(`Expectation patterns must not start with a slash: saw "${pattern}"`);
      }

      if (pattern < lastPattern) {
        throw new Error("Bad lexicographical expectation pattern sorting in to-run.yaml: " + pattern +
                        " should come before " + lastPattern);
      }
      lastPattern = pattern;

      const reason = doc[pattern][0];
      if (!validReasons.has(reason)) {
        throw new Error(`Bad reason "${reason}" for expectation ${pattern}`);
      }

      const matcher = new Minimatch(doc.DIR + "/" + pattern);
      if (!possibleTestFilePaths.some(filename => matcher.match(filename))) {
        throw new Error(`Expectation pattern "${pattern}" does not match any test files`);
      }
      minimatchers.set(doc.DIR + "/" + pattern, matcher);
    }
  }
}

function expectationsInDoc(doc) {
  const keys = Object.keys(doc);
  keys.shift(); // get rid of the DIR key
  return keys;
}
<|endoftext|>


<commit_before>var Fs = require('fs');
var Jison = require('jison');

function loadFile(path, callback) {
	Fs.readFile(path, 'utf8', function (err, data) {
		if (err) {
			throw Error(err.toString());
		} else {
			callback(data + '\n');
		}
	});
}

function saveFile(path, data) {
	Fs.writeFile(path, data, function (err) {
		if (err) {
			throw Error('problem saving to ' + path);
		}
	});
}

var source = {};
var loaded = 0;

loadFile('./lexer.js', function (data) {
	source.lexer = data;
	run();
});

loadFile('./grammar.js', function (data) {
	source.grammar = data;
	run();
});

loadFile('./yy.js', function (data) {
	source.yy = data;
	run();
});

loadFile('./scope.js', function (data) {
	source.scope = data;
	run()
});

loadFile('./helpers.js', function (data) {
	source.helpers = data;
	run();
});

function run() {
	loaded++;

	if (loaded === 5) {
		var parser = new Jison.Parser(require('./grammar.js').grammar);
		source.parser = parser.generate({
			moduleType: 'js'
		});

		var file = 'var Arthur = (function(){var exports = {};function require(path) {switch(path) {case \'./helpers.js\':return exports;break;case \'./scope.js\':return exports;break;}}';

		file += 'var helpers = (function(exports, require) {' + source.helpers + '})(exports, require);';
		file += 'var yy = (function(exports, require) {' + source.scope + '})(exports, require);';
		file += 'var lexer = (function(exports, require) {' + source.lexer + '})(exports, require);';
		file += 'var yy = (function(exports, require) {' + source.yy + '})(exports, require);';
		file += source.parser;

		file += 'parser.yy = exports.yy; return {parse: function (code, opts) {opts = opts || {}; parser.lexer = new exports.lexer(); var root = parser.parse(code + \'\\n\');return root.compile(opts).trim();}};})();';
		file += 'if(typeof exports!==\'undefined\'&&typeof require!==\'undefined\'){ exports.parse = function () { return Arthur.parse.apply(Arthur,arguments); }; }';

		saveFile('../bin/arthur.js', file);
	}
}<commit_msg>move build.js out of src folder<commit_after><|endoftext|>


<commit_before>// ==UserScript== //

// @name ALM Extra

// @namespace http://www.plosone.org

// @description Test

// @include *

// ==/UserScript==

// test

<script src="http://code.jquery.com/jquery-2.1.1.min.js">

$('#article-metrics').append(
    $('<div>').html('Hello World'),
);

<commit_msg>restrict by url<commit_after>// ==UserScript== //

// @name ALM Extra

// @namespace http://www.plosone.org

// @description Test

// @include http://www.plosone.org

// ==/UserScript==

<script src="http://code.jquery.com/jquery-2.1.1.min.js">

$('#article-metrics').append(
    $('<div>').html('Hello World'),
);

<|endoftext|>


<commit_before>/*
 * Copyright 2009-2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE.txt or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

var copy = require('dryice').copy;
var path = require('path');
var fs = require('fs');

var gcliHome = __dirname;

/**
 * The main() function is called at the bottom of this file to ensure all the
 * globals are setup properly.
 */
function main() {
  var args = process.argv;
  if (args.length < 3 || args[2] === 'standard') {
    buildStandard();
  }
  else if (args[2] === 'firefox') {
    buildFirefox(args[3]);
  }
  else {
    console.error('Error: Unknown target: \'' + args[2] + '\'');
    process.exit(1);
  }
}

/**
 * There are 2 important ways to build GCLI.
 * The first is for use within a normal web page.
 * It has compressed and uncompressed versions of the output script file.
 */
function buildStandard() {
  console.log('Building standard outputs to built/gcli[-uncompressed].js');

  if (!path.existsSync(gcliHome + '/built')) {
    fs.mkdirSync(gcliHome + '/built', 0755);
  }

  var project = copy.createCommonJsProject({
    roots: [ gcliHome + '/lib' ]
  });
  var sources = copy.createDataObject();

  copy({
    source: copy.source.commonjs({
      project: project,
      // This list of dependencies should be the same as in index.html
      require: [ 'gcli/index', 'demo/index', 'gclitest/index' ]
    }),
    filter: copy.filter.moduleDefines,
    dest: sources
  });
  copy({
    source: { root: project, include: /.*\.png$|.*\.gif$/ },
    filter: copy.filter.base64,
    dest: sources
  });
  console.log(project.report());

  // Create a GraphML dependency report. Directions:
  // - Install yEd (http://www.yworks.com/en/products_yed_about.htm)
  // - Load gcli/built/gcli.graphml
  // - Resize the nodes (Tools->Fit Node to Label)
  // - Apply a layout (Layout->Hierarchical)
  console.log('Outputting dependency graph to built/gcli.graphml\n');
  if (project.getDependencyGraphML) {
    copy({
      source: { value:project.getDependencyGraphML() },
      dest: 'built/gcli.graphml',
    });
  }

  // Create the output scripts, compressed and uncompressed
  copy({ source: 'index.html', filter: tweakIndex, dest: 'built/index.html' });
  copy({ source: 'scripts/es5-shim.js', dest: 'built/es5-shim.js' });
  copy({
    source: [ copy.getMiniRequire(), sources ],
    dest: 'built/gcli-uncompressed.js'
  });
  try {
    copy({
      source: [ copy.getMiniRequire(), sources ],
      filter: copy.filter.uglifyjs,
      dest: 'built/gcli.js'
    });
  }
  catch (ex) {
    console.log('ERROR: Uglify compression fails on windows/linux. ' +
        'Skipping creation of built/gcli.js\n');
  }
}

/**
 * Build the Javascript JSM files for Firefox
 * It consists of 1 output file: gcli.jsm
 */
function buildFirefox(destDir) {
  console.log('Building Firefox outputs to ' + (destDir || 'built/ff') + '.\n');

  if (!destDir) {
    if (!path.existsSync(gcliHome + '/built')) {
      fs.mkdirSync(gcliHome + '/built', 0755);
    }
    if (!path.existsSync(gcliHome + '/built/ff')) {
      fs.mkdirSync(gcliHome + '/built/ff', 0755);
    }
  }

  var jsmDir = '/browser/devtools/webconsole';
  var winCssDir = '/browser/themes/winstripe/browser/devtools';
  var pinCssDir = '/browser/themes/pinstripe/browser/devtools';
  var gnomeCssDir = '/browser/themes/gnomestripe/browser/devtools';
  var propsDir = '/browser/locales/en-US/chrome/browser';

  if (destDir) {
    var fail = false;
    if (!path.existsSync(destDir + jsmDir)) {
      console.error('Missing path for JSM: ' + destDir + jsmDir);
      fail = true;
    }
    if (!path.existsSync(destDir + winCssDir)) {
      console.error('Missing path for Windows CSS: ' + destDir + winCssDir);
      fail = true;
    }
    if (!path.existsSync(destDir + pinCssDir)) {
      console.error('Missing path for Mac CSS: ' + destDir + pinCssDir);
      fail = true;
    }
    if (!path.existsSync(destDir + gnomeCssDir)) {
      console.error('Missing path for Gnome CSS: ' + destDir + gnomeCssDir);
      fail = true;
    }
    if (!path.existsSync(destDir + propsDir)) {
      console.error('Missing path for l10n string: ' + destDir + propsDir);
      fail = true;
    }
    if (fail) {
      process.exit(1);
    }
  }

  var project = copy.createCommonJsProject({
    roots: [ gcliHome + '/mozilla', gcliHome + '/lib' ],
    ignores: [
      'text!gcli/ui/inputter.css',
      'text!gcli/ui/menu.css',
      'text!gcli/ui/arg_fetch.css'
    ]
  });

  // Package the JavaScript
  copy({
    source: [
      'mozilla/build/prefix-gcli.jsm',
      'mozilla/build/console.js',
      copy.getMiniRequire(),
      copy.source.commonjs({
        project: project,
        // This list of dependencies should be the same as in suffix-gcli.jsm
        require: [ 'gcli/index' ]
      }),
      'mozilla/build/suffix-gcli.jsm'
    ],
    filter: copy.filter.moduleDefines,
    dest: (destDir ? destDir + jsmDir : 'built/ff') + '/gcli.jsm'
  });

  // Package the CSS
  var css = copy.createDataObject();
  copy({
    source: [
      'mozilla/build/license-block.txt',
      { value: '\n/* From: $GCLI/mozilla/gcli/ui/gcliterm.css */' },
      'mozilla/gcli/ui/gcliterm.css',
      { value: '\n/* From: $GCLI/lib/gcli/ui/arg_fetch.css */' },
      'lib/gcli/ui/arg_fetch.css',
      { value: '\n/* From: $GCLI/lib/gcli/ui/hinter.css */' },
      'lib/gcli/ui/hinter.css',
      { value: '\n/* From: $GCLI/lib/gcli/ui/menu.css */' },
      'lib/gcli/ui/menu.css',
      { value: '\n/* From: $GCLI/lib/gcli/ui/inputter.css */' },
      'lib/gcli/ui/inputter.css'
    ],
    filter: removeNonMozPrefixes,
    dest: css
  });
  copy({
    source: css,
    dest: (destDir ? destDir + winCssDir : 'built/ff') + '/gcli.css'
  });
  copy({
    source: css,
    dest: (destDir ? destDir + pinCssDir : 'built/ff') + '/gcli.css'
  });
  copy({
    source: css,
    dest: (destDir ? destDir + gnomeCssDir : 'built/ff') + '/gcli.css'
  });

  // Package the i18n strings
  copy({
    source: 'lib/gcli/nls/strings.js',
    filter: tweakI18nStrings,
    dest: (destDir ? destDir + propsDir : 'built/ff') + '/gcli.properties'
  });

  console.log(project.report());
}

/**
 * Filter index.html to:
 * - Make links relative, we flatten out the scripts directory
 * - Replace require.js with the built GCLI script file
 * - Remove the RequireJS configuration
 */
function tweakIndex(data) {
  return data
      .replace(/scripts\/es5-shim.js/, 'es5-shim.js')
      .replace(/scripts\/require.js/, 'gcli-uncompressed.js')
      .replace(/\s*require\([^;]*;\n/, '');
}

/**
 * Regular expression that removes the header/footer from a nls strings file.
 * If/when we revert to RequireJS formatted strings files, we'll need to update
 * this.
 * See lib/gcli/nls/strings.js for an example
 */
var outline = /root: {([^}]*)}/;

/**
 * Regex to match a set of single line comments followed by a name:value
 * We run this to fund the list of strings once we've used 'outline' to get the
 * main body.
 * See lib/gcli/nls/strings.js for an example
 */
var singleString = /((\s*\/\/.*\n)+)\s*([A-z.]+):\s*'(.*)',?\n/g;

/**
 * Filter to turn GCLIs l18n script file into a Firefox l10n strings file
 */
function tweakI18nStrings(data) {
  // Rip off the CommonJS header/footer
  var results = outline.exec(data);
  if (!results) {
    console.error('Mismatch in lib/gcli/nls/strings.js');
    process.exit(1);
  }
  // Remove the trailing spaces
  var data = results[1].replace(/ *$/, '');
  // Convert each of the string definitions
  data = data.replace(singleString, function(m, note, x, name, value) {
    note = note.replace(/\n? *\/\/ */g, ' ')
               .replace(/^ /, '')
               .replace(/\n$/, '');
    note = 'LOCALIZATION NOTE (' + name + '): ' + note;
    var lines = '# ' + wordWrap(note, 77).join('\n# ') + '\n';
    // Unescape JavaScript strings so they're property values
    value = value.replace(/\\\\/g, '\\')
                 .replace(/\\'/g, '\'');
    return lines + name + '=' + value + '\n\n';
  });

  return '# LOCALIZATION NOTE These strings are used inside the Web Console\n' +
         '# command line which is available from the Web Developer sub-menu\n' +
         '# -> \'Web Console\'.\n' +
         '# The correct localization of this file might be to keep it in' +
         '# English, or another language commonly spoken among web developers.' +
         '# You want to make that choice consistent across the developer tools.' +
         '# A good criteria is the language in which you\'d find the best' +
         '# documentation on web development on the web.\n' +
         '\n' + data;
}

/**
 * Return an input string split into lines of a given length
 */
function wordWrap(input, length) {
  // LOOK! Over there! Is it an airplane?
  var wrapper = new RegExp('.{0,' + (length - 1) + '}([ $|\\s$]|$)', 'g');
  return input.match(wrapper).slice(0, -1).map(function(s) {
    return s.replace(/ $/, '');
  });
}

/**
 * Hack to remove the '-vendorprefix' definitions. This currently works to
 * remove -webkit, -ie and -op from CSS values (but not CSS properties).
 */
function removeNonMozPrefixes(data) {
  return data.replace(/\n?\s*[-a-z]*:\s*-(webkit|op|ie)[-a-z]*\s*;[ \t]*/g, '');
}

// Now everything is defined properly, start working
main();
<commit_msg>Minor Tweak: Default destDir to $FIREFOX_HOME if available<commit_after>/*
 * Copyright 2009-2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE.txt or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

var copy = require('dryice').copy;
var path = require('path');
var fs = require('fs');

var gcliHome = __dirname;

/**
 * The main() function is called at the bottom of this file to ensure all the
 * globals are setup properly.
 */
function main() {
  var args = process.argv;
  if (args.length < 3 || args[2] === 'standard') {
    buildStandard();
  }
  else if (args[2] === 'firefox') {
    buildFirefox(args[3]);
  }
  else {
    console.error('Error: Unknown target: \'' + args[2] + '\'');
    process.exit(1);
  }
}

/**
 * There are 2 important ways to build GCLI.
 * The first is for use within a normal web page.
 * It has compressed and uncompressed versions of the output script file.
 */
function buildStandard() {
  console.log('Building standard outputs to built/gcli[-uncompressed].js');

  if (!path.existsSync(gcliHome + '/built')) {
    fs.mkdirSync(gcliHome + '/built', 0755);
  }

  var project = copy.createCommonJsProject({
    roots: [ gcliHome + '/lib' ]
  });
  var sources = copy.createDataObject();

  copy({
    source: copy.source.commonjs({
      project: project,
      // This list of dependencies should be the same as in index.html
      require: [ 'gcli/index', 'demo/index', 'gclitest/index' ]
    }),
    filter: copy.filter.moduleDefines,
    dest: sources
  });
  copy({
    source: { root: project, include: /.*\.png$|.*\.gif$/ },
    filter: copy.filter.base64,
    dest: sources
  });
  console.log(project.report());

  // Create a GraphML dependency report. Directions:
  // - Install yEd (http://www.yworks.com/en/products_yed_about.htm)
  // - Load gcli/built/gcli.graphml
  // - Resize the nodes (Tools->Fit Node to Label)
  // - Apply a layout (Layout->Hierarchical)
  console.log('Outputting dependency graph to built/gcli.graphml\n');
  if (project.getDependencyGraphML) {
    copy({
      source: { value:project.getDependencyGraphML() },
      dest: 'built/gcli.graphml',
    });
  }

  // Create the output scripts, compressed and uncompressed
  copy({ source: 'index.html', filter: tweakIndex, dest: 'built/index.html' });
  copy({ source: 'scripts/es5-shim.js', dest: 'built/es5-shim.js' });
  copy({
    source: [ copy.getMiniRequire(), sources ],
    dest: 'built/gcli-uncompressed.js'
  });
  try {
    copy({
      source: [ copy.getMiniRequire(), sources ],
      filter: copy.filter.uglifyjs,
      dest: 'built/gcli.js'
    });
  }
  catch (ex) {
    console.log('ERROR: Uglify compression fails on windows/linux. ' +
        'Skipping creation of built/gcli.js\n');
  }
}

/**
 * Build the Javascript JSM files for Firefox
 * It consists of 1 output file: gcli.jsm
 */
function buildFirefox(destDir) {
  if (!destDir && process.env.FIREFOX_HOME) {
    destDir = process.env.FIREFOX_HOME;
  }
  console.log('Building Firefox outputs to ' + (destDir || 'built/ff') + '.\n');

  if (!destDir) {
    if (!path.existsSync(gcliHome + '/built')) {
      fs.mkdirSync(gcliHome + '/built', 0755);
    }
    if (!path.existsSync(gcliHome + '/built/ff')) {
      fs.mkdirSync(gcliHome + '/built/ff', 0755);
    }
  }

  var jsmDir = '/browser/devtools/webconsole';
  var winCssDir = '/browser/themes/winstripe/browser/devtools';
  var pinCssDir = '/browser/themes/pinstripe/browser/devtools';
  var gnomeCssDir = '/browser/themes/gnomestripe/browser/devtools';
  var propsDir = '/browser/locales/en-US/chrome/browser';

  if (destDir) {
    var fail = false;
    if (!path.existsSync(destDir + jsmDir)) {
      console.error('Missing path for JSM: ' + destDir + jsmDir);
      fail = true;
    }
    if (!path.existsSync(destDir + winCssDir)) {
      console.error('Missing path for Windows CSS: ' + destDir + winCssDir);
      fail = true;
    }
    if (!path.existsSync(destDir + pinCssDir)) {
      console.error('Missing path for Mac CSS: ' + destDir + pinCssDir);
      fail = true;
    }
    if (!path.existsSync(destDir + gnomeCssDir)) {
      console.error('Missing path for Gnome CSS: ' + destDir + gnomeCssDir);
      fail = true;
    }
    if (!path.existsSync(destDir + propsDir)) {
      console.error('Missing path for l10n string: ' + destDir + propsDir);
      fail = true;
    }
    if (fail) {
      process.exit(1);
    }
  }

  var project = copy.createCommonJsProject({
    roots: [ gcliHome + '/mozilla', gcliHome + '/lib' ],
    ignores: [
      'text!gcli/ui/inputter.css',
      'text!gcli/ui/menu.css',
      'text!gcli/ui/arg_fetch.css'
    ]
  });

  // Package the JavaScript
  copy({
    source: [
      'mozilla/build/prefix-gcli.jsm',
      'mozilla/build/console.js',
      copy.getMiniRequire(),
      copy.source.commonjs({
        project: project,
        // This list of dependencies should be the same as in suffix-gcli.jsm
        require: [ 'gcli/index' ]
      }),
      'mozilla/build/suffix-gcli.jsm'
    ],
    filter: copy.filter.moduleDefines,
    dest: (destDir ? destDir + jsmDir : 'built/ff') + '/gcli.jsm'
  });

  // Package the CSS
  var css = copy.createDataObject();
  copy({
    source: [
      'mozilla/build/license-block.txt',
      { value: '\n/* From: $GCLI/mozilla/gcli/ui/gcliterm.css */' },
      'mozilla/gcli/ui/gcliterm.css',
      { value: '\n/* From: $GCLI/lib/gcli/ui/arg_fetch.css */' },
      'lib/gcli/ui/arg_fetch.css',
      { value: '\n/* From: $GCLI/lib/gcli/ui/hinter.css */' },
      'lib/gcli/ui/hinter.css',
      { value: '\n/* From: $GCLI/lib/gcli/ui/menu.css */' },
      'lib/gcli/ui/menu.css',
      { value: '\n/* From: $GCLI/lib/gcli/ui/inputter.css */' },
      'lib/gcli/ui/inputter.css'
    ],
    filter: removeNonMozPrefixes,
    dest: css
  });
  copy({
    source: css,
    dest: (destDir ? destDir + winCssDir : 'built/ff') + '/gcli.css'
  });
  copy({
    source: css,
    dest: (destDir ? destDir + pinCssDir : 'built/ff') + '/gcli.css'
  });
  copy({
    source: css,
    dest: (destDir ? destDir + gnomeCssDir : 'built/ff') + '/gcli.css'
  });

  // Package the i18n strings
  copy({
    source: 'lib/gcli/nls/strings.js',
    filter: tweakI18nStrings,
    dest: (destDir ? destDir + propsDir : 'built/ff') + '/gcli.properties'
  });

  console.log(project.report());
}

/**
 * Filter index.html to:
 * - Make links relative, we flatten out the scripts directory
 * - Replace require.js with the built GCLI script file
 * - Remove the RequireJS configuration
 */
function tweakIndex(data) {
  return data
      .replace(/scripts\/es5-shim.js/, 'es5-shim.js')
      .replace(/scripts\/require.js/, 'gcli-uncompressed.js')
      .replace(/\s*require\([^;]*;\n/, '');
}

/**
 * Regular expression that removes the header/footer from a nls strings file.
 * If/when we revert to RequireJS formatted strings files, we'll need to update
 * this.
 * See lib/gcli/nls/strings.js for an example
 */
var outline = /root: {([^}]*)}/;

/**
 * Regex to match a set of single line comments followed by a name:value
 * We run this to fund the list of strings once we've used 'outline' to get the
 * main body.
 * See lib/gcli/nls/strings.js for an example
 */
var singleString = /((\s*\/\/.*\n)+)\s*([A-z.]+):\s*'(.*)',?\n/g;

/**
 * Filter to turn GCLIs l18n script file into a Firefox l10n strings file
 */
function tweakI18nStrings(data) {
  // Rip off the CommonJS header/footer
  var results = outline.exec(data);
  if (!results) {
    console.error('Mismatch in lib/gcli/nls/strings.js');
    process.exit(1);
  }
  // Remove the trailing spaces
  var data = results[1].replace(/ *$/, '');
  // Convert each of the string definitions
  data = data.replace(singleString, function(m, note, x, name, value) {
    note = note.replace(/\n? *\/\/ */g, ' ')
               .replace(/^ /, '')
               .replace(/\n$/, '');
    note = 'LOCALIZATION NOTE (' + name + '): ' + note;
    var lines = '# ' + wordWrap(note, 77).join('\n# ') + '\n';
    // Unescape JavaScript strings so they're property values
    value = value.replace(/\\\\/g, '\\')
                 .replace(/\\'/g, '\'');
    return lines + name + '=' + value + '\n\n';
  });

  return '# LOCALIZATION NOTE These strings are used inside the Web Console\n' +
         '# command line which is available from the Web Developer sub-menu\n' +
         '# -> \'Web Console\'.\n' +
         '# The correct localization of this file might be to keep it in' +
         '# English, or another language commonly spoken among web developers.' +
         '# You want to make that choice consistent across the developer tools.' +
         '# A good criteria is the language in which you\'d find the best' +
         '# documentation on web development on the web.\n' +
         '\n' + data;
}

/**
 * Return an input string split into lines of a given length
 */
function wordWrap(input, length) {
  // LOOK! Over there! Is it an airplane?
  var wrapper = new RegExp('.{0,' + (length - 1) + '}([ $|\\s$]|$)', 'g');
  return input.match(wrapper).slice(0, -1).map(function(s) {
    return s.replace(/ $/, '');
  });
}

/**
 * Hack to remove the '-vendorprefix' definitions. This currently works to
 * remove -webkit, -ie and -op from CSS values (but not CSS properties).
 */
function removeNonMozPrefixes(data) {
  return data.replace(/\n?\s*[-a-z]*:\s*-(webkit|op|ie)[-a-z]*\s*;[ \t]*/g, '');
}

// Now everything is defined properly, start working
main();
<|endoftext|>


<commit_before>console.log($('script[src="../js/commits.js"]').data(path));
var url = 'https://api.github.com/repos/trivium-io/trivium/commits?path=src/io/trivium/extension/task/ConsoleLogger.java';
$.ajax({type:'GET',
        url:url,
        success: function(data){
    var str="

message	date	author	link

";
    for(var idx=0;idx<data.length;idx++){
      var one = data[idx];
      var d = one.commit.author.date.substr(0,10);
      var t = one.commit.author.date.substr(11,10);
      str+="
"+one.commit.message+"	"
          +d+" "+t+"	"
          +one.commit.author.name+"	"
          +""+one.sha.substr(0,7)+"
";
    }
    str+="

";
    $('#changes').html(str);
}});
<commit_msg>new task format<commit_after>console.log($('script[src="../js/commits.js"]').data('path'));
var url = 'https://api.github.com/repos/trivium-io/trivium/commits?path=src/io/trivium/extension/task/ConsoleLogger.java';
$.ajax({type:'GET',
        url:url,
        success: function(data){
    var str="

message	date	author	link

";
    for(var idx=0;idx<data.length;idx++){
      var one = data[idx];
      var d = one.commit.author.date.substr(0,10);
      var t = one.commit.author.date.substr(11,10);
      str+="
"+one.commit.message+"	"
          +d+" "+t+"	"
          +one.commit.author.name+"	"
          +""+one.sha.substr(0,7)+"
";
    }
    str+="

";
    document.write(str);
}});
<|endoftext|>