<commit_before>/*exported recommendVersion*/

var fontOptionsEle;
var fs;
var ajaxMethod;
var ajaxUrl;
var message = {};
var recommendLoaded = false;
var recommendInner = document.getElementById('story-recommend');
var recommendVersion;
var thirdPartAPIUrl = 'http://120.27.47.77:8091/getRtCmd?siteId=5002&num=20&itemId=' + FTStoryid;
var thirdPartData = [];

recommendVersion = GetCookie('ab001') || '';
if (recommendVersion === '') {
    recommendVersion = (Math.random() > 0)? '-001': '-002';
    SetCookie('ab001',recommendVersion,'','/');
}

/**
 * Switch to local mode or remote mode.
 */
if (/127\.0|localhost|192\.168/.test(window.location.href)) {
	ajaxMethod = 'GET';
	ajaxUrl = '/api/page/recommend.json';
} else {
	ajaxMethod = 'POST';
	ajaxUrl = '/eaclient/apijson.php';
}

/**
 * The FTC API communication
 */
var ftc_api = {
    server_url: '',
    method: 'POST',

    call: function(message, success, failed) {
        var xhr = new XMLHttpRequest();

        try {
            if(this.server_url === '') {
                throw 'The server address is empty!';
            }

            xhr.open(this.method, encodeURI(this.server_url), true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.onreadystatechange = function() {
                if(xhr.readyState === 4){
                    if(xhr.status === 200){
                        if(typeof success === 'function') {
                            success(xhr.responseText);
                        }
                    } else {
                        if(typeof failed === 'function') {
                            failed(xhr.status);
                        }
                    }
                }
            };
            xhr.send(JSON.stringify(message));

        } catch (e) {
            console.log(xhr.status);
            console.log(e.message);
        }
    }
};

ftc_api.method = ajaxMethod;
ftc_api.server_url = ajaxUrl;

/**
 * Global recommendation payload
 */
function recommendationPayload(datalist){
    var maxItem = 8;
    var itemCount = 0;
    var itemHTML = '';
    var eventAction = 'Click' + recommendVersion;

    for (var i=0; i<datalist.length; i++) {
        var itemClass = 'XL3 L3 M6 S6 P12';
        var itemHeadline = datalist[i].cheadline;
        var itemImage = datalist[i].piclink;
        var itemId = datalist[i].storyid;
        var itemT = datalist[i].t;
        if(itemT === undefined || itemT === null) {itemT = '';}
        var itemTop = '';
        var itemTopClass = 'PT';
        if (itemCount % 4 === 0) {
            itemTopClass += ' XLT LT';
        }
        if (itemCount % 2 === 0) {
            itemTopClass += ' MT ST';
        }
        if (itemTopClass !== '' && itemCount >0) {
            itemTop = '

';
        }

        var link = '/story/'+itemId+'?tcode=smartrecommend&ulu-rcmd=' + thirdPartData[itemId];

        if (itemCount<maxItem && itemImage && itemImage !== '') {

            itemHTML += itemTop + '

'+itemHeadline+'

';
            itemCount += 1;
        }
    }

    recommendInner.innerHTML = itemHTML;
    document.getElementById('story-recommend-container').style.display = 'block';
    loadImages();
    recommendLoaded = true;
}

/**
 * Get ftc recommend stories
 */
function getFtcRecommendSuccess(data) {
    data = JSON.parse(data);
    if (data.body.oelement.errorcode === '0') {
        if (data.body.odatalist && data.body.odatalist.length > 0) {
            recommendationPayload(data.body.odatalist);
            ga('send','event','Recommend Story API', 'Success' + recommendVersion, '', {'nonInteraction':1});
        } else {
            ga('send','event','Recommend Story API', 'No Data' + recommendVersion, '', {'nonInteraction':1});
        }
    } else {
        ga('send','event','Recommend Story API', 'Parse Fail' + recommendVersion, data.body.oelement.errorcode, {'nonInteraction':1});
    }
}

function getFtcRecommendFailed(){
    console.log('Request failed!');
    ga('send','event','Recommend Story API', 'Request Fail' + recommendVersion, '', {'nonInteraction':1});
}

/**
 * Playload thirdpart recommend stories
 */
function getThirdPartRecommendSuccess(data) {
    data = JSON.parse(data);
    if (data.body.oelement.errorcode === '0') {
        if (data.body.odatalist && data.body.odatalist.length > 0) {
            recommendationPayload(data.body.odatalist);
            ga('send','event','Recommend Story API', 'Success' + recommendVersion, '', {'nonInteraction':1});
        } else {
            ga('send','event','Recommend Story API', 'No Data' + recommendVersion, '', {'nonInteraction':1});
        }
    } else {
        ga('send','event','Recommend Story API', 'Parse Fail' + recommendVersion, data.body.oelement.errorcode, {'nonInteraction':1});
    }
}

function getThirdPartRecommendFailed(){
    console.log('Request failed!');
    ga('send','event','Recommend Story API', 'Request Fail' + recommendVersion, '', {'nonInteraction':1});
}

/* jshint unused: true */
/*exported getRec */
function getRec(data) {

    if(typeof data === 'object') {
        if(data.length > 0){
            var ids = '';
            var split = '';
            for(var i = 0; i < data.length; i++){
                var tmpKey = data[i].id;
                var tmpVal = data[i].parameter;
                ids += split + tmpKey;
                split = ',';
                thirdPartData[tmpKey] = tmpVal;
            }

            message.head = {};
            message.head.transactiontype = '10002';
            message.head.source = 'web';
            message.body = {};
            message.body.ielement = {};
            message.body.ielement.storyid = ids;
            message.body.ielement.withpic = 1;

            ftc_api.call(message, getThirdPartRecommendSuccess, getThirdPartRecommendFailed);
        } else {
            ga('send','event','Recommend Story API', 'No Data' + recommendVersion, '', {'nonInteraction':1});
        }
    } else {
        ga('send','event','Recommend Story API', 'Request Fail' + recommendVersion, '', {'nonInteraction':1});
    }
}

// A & B Test
if(recommendVersion === '-001'){
    message.head = {};
    message.head.transactiontype = '61008';
    message.head.source = 'web';
    message.body = {};
    message.body.ielement = {};
    message.body.ielement.storyid = '';

    ga('send','event','Recommend Story API', 'Load' + recommendVersion, '', {'nonInteraction':1});
    ftc_api.call(message, getFtcRecommendSuccess, getFtcRecommendFailed);
} else {
    var s = document.createElement('script');
    s.type = 'text/javascript';
    s.async = !0;
    s.src = thirdPartAPIUrl + '&callback=getRec&v=' + new Date().getTime();
    var d = document.getElementsByTagName('script')[0];
    d.parentNode.insertBefore(s, d);
    ga('send','event','Recommend Story API', 'Load' + recommendVersion, '', {'nonInteraction':1});
    // The rest work jump to getRec
}

//set font
fontOptionsEle = document.getElementById('font-options');

//fontOptionsDivs = fontOptionsEle.querySelectorAll('div');

//click to change font size and set cookie (fs)
//Dom Delegate doesn't work here on iOS
fontOptionsEle.onclick = function (e) {
    var currentClass = e.target.className || '';
    var selectedClass;
    var storyContainerClass = document.querySelector('.story-container').className;
    if (currentClass.indexOf('selected') <0) {
        if (fontOptionsEle.querySelector('.selected')) {
            selectedClass = fontOptionsEle.querySelector('.selected').className || '';
        } else {
            selectedClass = '';
        }
        selectedClass = selectedClass.replace(/ selected/g, '');
        if (fontOptionsEle.querySelector('.selected')) {
            fontOptionsEle.querySelector('.selected').className = selectedClass;
        }
        e.target.className = currentClass + ' selected';
        /* jshint ignore:start */
        SetCookie('fs',currentClass,'','/');
        /* jshint ignore:end */
        storyContainerClass = storyContainerClass.replace(/ (normal|bigger|biggest|smaller|smallest)/g,'');
        document.querySelector('.story-container').className = storyContainerClass + ' ' + currentClass;
        stickyBottomPrepare();
        stickyAdsPrepare();
        setResizeClass();
    }
};

//click to change font size and set cookie (fs)
// delegate.on('click', '.font-options div', function(){
//     var currentClass = this.className || '';
//     var selectedClass;
//     var storyContainerClass = document.querySelector('.story-container').className;
//     if (currentClass.indexOf('selected') <0) {
//         selectedClass = fontOptionsEle.querySelector('.selected').className;
//         selectedClass = selectedClass.replace(/ selected/g, '');
//         fontOptionsEle.querySelector('.selected').className = selectedClass;
//         this.className = currentClass + ' selected';
//         /* jshint ignore:start */
//         SetCookie('fs',currentClass,'','/');
//         /* jshint ignore:end */
//         storyContainerClass = storyContainerClass.replace(/ (normal|bigger|biggest|smaller|smallest)/g,'');
//         document.querySelector('.story-container').className = storyContainerClass + ' ' + currentClass;
//         stickyBottomPrepare();
//         stickyAdsPrepare();
//         setResizeClass();
//     }
// });

//set font by getting user cookie (fs)
/* jshint ignore:start */
fs = GetCookie('fs');
/* jshint ignore:end */
if (typeof fs === 'string' && fs !== null && fs !== '' && document.getElementById('font-options') && document.querySelector('.story-container')) {
    document.getElementById('font-options').querySelector('.' + fs.replace(/ /g, '.')).className = fs + ' selected';
    document.querySelector('.story-container').className = document.querySelector('.story-container').className + ' ' + fs;
    setResizeClass();
} else {
    document.getElementById('font-setting').querySelector('.normal').className = 'normal selected';
}

/* jshint ignore:start */
// var bpage=0;
// function viewhistory() {
//     var username=GetCookie("USER_NAME"),
//         unixday=Math.round(new Date().getTime()/1000),
//         viewstart=GetCookie ("viewstart"),
//         clearhistory=0,
//         v,
//         k,
//         barrierversion,
//         ie6,
//         isIE;
//     if (typeof storyid==="string" && storyid!=="" && (username===''||username===null) && (location.href.match(/\/story\/[0-9]{9}$/g)!==null||location.href.indexOf("barrierversion")>0)) {

//         if (viewstart===null || viewstart==="") {
//             viewstart=unixday;
//             SetCookie("viewstart",unixday,86400*100,"/");
//         } else if (unixday-viewstart>=30*86400) {
//             DeleteCookie ("viewstart");
//             DeleteCookie ("viewhistory");
//             SetCookie("viewstart",unixday,86400*100,"/");
//             clearhistory=1;
//         }

//         v=GetCookie ("viewhistory");
//         if (v===null || clearhistory===1) {
//             v="";
//         }
//         v=v.replace(storyid,"").replace(/[\|]+/g,"|");
//         v=v+"|"+storyid;
//         v=v.replace(/^\|+/g,"").replace(/^[0-9]{1,8}\|/g,"");
//         if (v.length>=120) {
//             v=v.replace(/^[0-9]+\|/g,"");
//         }
//         DeleteCookie ("viewhistory");
//         SetCookie("viewhistory",v,86400*100,"/");
//         if (v.length>=50  && (document.referrer.indexOf("ftchinese.com")>=0 ||location.href.indexOf("barrierversion")>0)) {
//             bpage=1;
//             if (location.href.indexOf("ftchinese.com")>=0) {

//                 //if(i<0.3){bpage=2}else if(i<0.5){bpage=3}
//                 if (v.length>=100) {bpage=3;}
//                 k=GetCookie("bp");
//                 if (k!==null&&k!==""&&k>=2){bpage=k;}
//                 barrierversion=paravalue(window.location.href,"barrierversion");
//                 if (barrierversion!==null && barrierversion!==""){bpage=parseInt(barrierversion,0);}
//                 //如果是IE6，则不弹出全屏模式，但是一定让他登录才能看文章
//                 ie6=!!window.ActiveXObject&&!window.XMLHttpRequest;
//                 isIE=!!window.ActiveXObject;
//                 if (ie6 && v.length>=100) {
//                     bpage=6;
//                     $.get("/m/marketing/reg.html", function(data){
//                         $("#bodytext p").slice(2).remove();
//                         $("#bodytext p").eq(1).after(data.replace(/5篇以上文章/g,"10篇以上文章")+"
友好提示：我们注意到您还在使用IE6浏览，这会带来安全隐患。建议您升级到更高的版本，或使用最新的FireFox或Chrome等浏览器。
");
//                     });
//                 } else if (isIE && v.length>=100) {
//                     $.get("/m/marketing/reg.html", function(data){
//                         $("#bodytext p").slice(2).remove();
//                         $("#bodytext p").eq(1).after(data.replace(/5篇以上文章/g,"10篇以上文章"));
//                     });
//                 } else if (bpage>=2 && v.length>=100 && $(window).width()>1024 && (window.Modernizr === undefined || !window.Modernizr.touch)) {
//                     $.get("/m/marketing/reg"+bpage+".html", function(data){
//                     if (data.indexOf("用户名或电子邮件")>0) {
//                         $("#bodytext").html(data);
//                         $("#rail-content").empty();
//                         $(".story_list,#top590x60,#commentheader,#logincomment,#nologincomment,.commentcontainer,#sharelinks,.announce").remove();
//                         SetCookie("bp",bpage,86400*100,"/");
//                         }
//                     });
//                 } else {
//                     $.get("/m/marketing/reg.html", function(data){
//                         $("#bodytext p").eq(1).after(data);
//                     });
//                 }
//             }
//         }
//     }
// }
/* jshint ignore:end */<commit_msg>typo in ab test<commit_after>/*exported recommendVersion*/

var fontOptionsEle;
var fs;
var ajaxMethod;
var ajaxUrl;
var message = {};
var recommendLoaded = false;
var recommendInner = document.getElementById('story-recommend');
var recommendVersion;
var thirdPartAPIUrl = 'http://120.27.47.77:8091/getRtCmd?siteId=5002&num=20&itemId=' + FTStoryid;
var thirdPartData = [];

recommendVersion = GetCookie('ab001') || '';
if (recommendVersion === '') {
    recommendVersion = (Math.random() > 0.5)? '-001': '-002';
    SetCookie('ab001',recommendVersion,'','/');
}

/**
 * Switch to local mode or remote mode.
 */
if (/127\.0|localhost|192\.168/.test(window.location.href)) {
	ajaxMethod = 'GET';
	ajaxUrl = '/api/page/recommend.json';
} else {
	ajaxMethod = 'POST';
	ajaxUrl = '/eaclient/apijson.php';
}

/**
 * The FTC API communication
 */
var ftc_api = {
    server_url: '',
    method: 'POST',

    call: function(message, success, failed) {
        var xhr = new XMLHttpRequest();

        try {
            if(this.server_url === '') {
                throw 'The server address is empty!';
            }

            xhr.open(this.method, encodeURI(this.server_url), true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.onreadystatechange = function() {
                if(xhr.readyState === 4){
                    if(xhr.status === 200){
                        if(typeof success === 'function') {
                            success(xhr.responseText);
                        }
                    } else {
                        if(typeof failed === 'function') {
                            failed(xhr.status);
                        }
                    }
                }
            };
            xhr.send(JSON.stringify(message));

        } catch (e) {
            console.log(xhr.status);
            console.log(e.message);
        }
    }
};

ftc_api.method = ajaxMethod;
ftc_api.server_url = ajaxUrl;

/**
 * Global recommendation payload
 */
function recommendationPayload(datalist){
    var maxItem = 8;
    var itemCount = 0;
    var itemHTML = '';
    var eventAction = 'Click' + recommendVersion;

    for (var i=0; i<datalist.length; i++) {
        var itemClass = 'XL3 L3 M6 S6 P12';
        var itemHeadline = datalist[i].cheadline;
        var itemImage = datalist[i].piclink;
        var itemId = datalist[i].storyid;
        var itemT = datalist[i].t;
        if(itemT === undefined || itemT === null) {itemT = '';}
        var itemTop = '';
        var itemTopClass = 'PT';
        if (itemCount % 4 === 0) {
            itemTopClass += ' XLT LT';
        }
        if (itemCount % 2 === 0) {
            itemTopClass += ' MT ST';
        }
        if (itemTopClass !== '' && itemCount >0) {
            itemTop = '

';
        }

        var link = '/story/'+itemId+'?tcode=smartrecommend&ulu-rcmd=' + thirdPartData[itemId];

        if (itemCount<maxItem && itemImage && itemImage !== '') {

            itemHTML += itemTop + '

'+itemHeadline+'

';
            itemCount += 1;
        }
    }

    recommendInner.innerHTML = itemHTML;
    document.getElementById('story-recommend-container').style.display = 'block';
    loadImages();
    recommendLoaded = true;
}

/**
 * Get ftc recommend stories
 */
function getFtcRecommendSuccess(data) {
    data = JSON.parse(data);
    if (data.body.oelement.errorcode === '0') {
        if (data.body.odatalist && data.body.odatalist.length > 0) {
            recommendationPayload(data.body.odatalist);
            ga('send','event','Recommend Story API', 'Success' + recommendVersion, '', {'nonInteraction':1});
        } else {
            ga('send','event','Recommend Story API', 'No Data' + recommendVersion, '', {'nonInteraction':1});
        }
    } else {
        ga('send','event','Recommend Story API', 'Parse Fail' + recommendVersion, data.body.oelement.errorcode, {'nonInteraction':1});
    }
}

function getFtcRecommendFailed(){
    console.log('Request failed!');
    ga('send','event','Recommend Story API', 'Request Fail' + recommendVersion, '', {'nonInteraction':1});
}

/**
 * Playload thirdpart recommend stories
 */
function getThirdPartRecommendSuccess(data) {
    data = JSON.parse(data);
    if (data.body.oelement.errorcode === '0') {
        if (data.body.odatalist && data.body.odatalist.length > 0) {
            recommendationPayload(data.body.odatalist);
            ga('send','event','Recommend Story API', 'Success' + recommendVersion, '', {'nonInteraction':1});
        } else {
            ga('send','event','Recommend Story API', 'No Data' + recommendVersion, '', {'nonInteraction':1});
        }
    } else {
        ga('send','event','Recommend Story API', 'Parse Fail' + recommendVersion, data.body.oelement.errorcode, {'nonInteraction':1});
    }
}

function getThirdPartRecommendFailed(){
    console.log('Request failed!');
    ga('send','event','Recommend Story API', 'Request Fail' + recommendVersion, '', {'nonInteraction':1});
}

/* jshint unused: true */
/*exported getRec */
function getRec(data) {

    if(typeof data === 'object') {
        if(data.length > 0){
            var ids = '';
            var split = '';
            for(var i = 0; i < data.length; i++){
                var tmpKey = data[i].id;
                var tmpVal = data[i].parameter;
                ids += split + tmpKey;
                split = ',';
                thirdPartData[tmpKey] = tmpVal;
            }

            message.head = {};
            message.head.transactiontype = '10002';
            message.head.source = 'web';
            message.body = {};
            message.body.ielement = {};
            message.body.ielement.storyid = ids;
            message.body.ielement.withpic = 1;

            ftc_api.call(message, getThirdPartRecommendSuccess, getThirdPartRecommendFailed);
        } else {
            ga('send','event','Recommend Story API', 'No Data' + recommendVersion, '', {'nonInteraction':1});
        }
    } else {
        ga('send','event','Recommend Story API', 'Request Fail' + recommendVersion, '', {'nonInteraction':1});
    }
}

// A & B Test
if(recommendVersion === '-001'){
    message.head = {};
    message.head.transactiontype = '61008';
    message.head.source = 'web';
    message.body = {};
    message.body.ielement = {};
    message.body.ielement.storyid = '';

    ga('send','event','Recommend Story API', 'Load' + recommendVersion, '', {'nonInteraction':1});
    ftc_api.call(message, getFtcRecommendSuccess, getFtcRecommendFailed);
} else {
    var s = document.createElement('script');
    s.type = 'text/javascript';
    s.async = !0;
    s.src = thirdPartAPIUrl + '&callback=getRec&v=' + new Date().getTime();
    var d = document.getElementsByTagName('script')[0];
    d.parentNode.insertBefore(s, d);
    ga('send','event','Recommend Story API', 'Load' + recommendVersion, '', {'nonInteraction':1});
    // The rest work jump to getRec
}

//set font
fontOptionsEle = document.getElementById('font-options');

//fontOptionsDivs = fontOptionsEle.querySelectorAll('div');

//click to change font size and set cookie (fs)
//Dom Delegate doesn't work here on iOS
fontOptionsEle.onclick = function (e) {
    var currentClass = e.target.className || '';
    var selectedClass;
    var storyContainerClass = document.querySelector('.story-container').className;
    if (currentClass.indexOf('selected') <0) {
        if (fontOptionsEle.querySelector('.selected')) {
            selectedClass = fontOptionsEle.querySelector('.selected').className || '';
        } else {
            selectedClass = '';
        }
        selectedClass = selectedClass.replace(/ selected/g, '');
        if (fontOptionsEle.querySelector('.selected')) {
            fontOptionsEle.querySelector('.selected').className = selectedClass;
        }
        e.target.className = currentClass + ' selected';
        /* jshint ignore:start */
        SetCookie('fs',currentClass,'','/');
        /* jshint ignore:end */
        storyContainerClass = storyContainerClass.replace(/ (normal|bigger|biggest|smaller|smallest)/g,'');
        document.querySelector('.story-container').className = storyContainerClass + ' ' + currentClass;
        stickyBottomPrepare();
        stickyAdsPrepare();
        setResizeClass();
    }
};

//click to change font size and set cookie (fs)
// delegate.on('click', '.font-options div', function(){
//     var currentClass = this.className || '';
//     var selectedClass;
//     var storyContainerClass = document.querySelector('.story-container').className;
//     if (currentClass.indexOf('selected') <0) {
//         selectedClass = fontOptionsEle.querySelector('.selected').className;
//         selectedClass = selectedClass.replace(/ selected/g, '');
//         fontOptionsEle.querySelector('.selected').className = selectedClass;
//         this.className = currentClass + ' selected';
//         /* jshint ignore:start */
//         SetCookie('fs',currentClass,'','/');
//         /* jshint ignore:end */
//         storyContainerClass = storyContainerClass.replace(/ (normal|bigger|biggest|smaller|smallest)/g,'');
//         document.querySelector('.story-container').className = storyContainerClass + ' ' + currentClass;
//         stickyBottomPrepare();
//         stickyAdsPrepare();
//         setResizeClass();
//     }
// });

//set font by getting user cookie (fs)
/* jshint ignore:start */
fs = GetCookie('fs');
/* jshint ignore:end */
if (typeof fs === 'string' && fs !== null && fs !== '' && document.getElementById('font-options') && document.querySelector('.story-container')) {
    document.getElementById('font-options').querySelector('.' + fs.replace(/ /g, '.')).className = fs + ' selected';
    document.querySelector('.story-container').className = document.querySelector('.story-container').className + ' ' + fs;
    setResizeClass();
} else {
    document.getElementById('font-setting').querySelector('.normal').className = 'normal selected';
}

/* jshint ignore:start */
// var bpage=0;
// function viewhistory() {
//     var username=GetCookie("USER_NAME"),
//         unixday=Math.round(new Date().getTime()/1000),
//         viewstart=GetCookie ("viewstart"),
//         clearhistory=0,
//         v,
//         k,
//         barrierversion,
//         ie6,
//         isIE;
//     if (typeof storyid==="string" && storyid!=="" && (username===''||username===null) && (location.href.match(/\/story\/[0-9]{9}$/g)!==null||location.href.indexOf("barrierversion")>0)) {

//         if (viewstart===null || viewstart==="") {
//             viewstart=unixday;
//             SetCookie("viewstart",unixday,86400*100,"/");
//         } else if (unixday-viewstart>=30*86400) {
//             DeleteCookie ("viewstart");
//             DeleteCookie ("viewhistory");
//             SetCookie("viewstart",unixday,86400*100,"/");
//             clearhistory=1;
//         }

//         v=GetCookie ("viewhistory");
//         if (v===null || clearhistory===1) {
//             v="";
//         }
//         v=v.replace(storyid,"").replace(/[\|]+/g,"|");
//         v=v+"|"+storyid;
//         v=v.replace(/^\|+/g,"").replace(/^[0-9]{1,8}\|/g,"");
//         if (v.length>=120) {
//             v=v.replace(/^[0-9]+\|/g,"");
//         }
//         DeleteCookie ("viewhistory");
//         SetCookie("viewhistory",v,86400*100,"/");
//         if (v.length>=50  && (document.referrer.indexOf("ftchinese.com")>=0 ||location.href.indexOf("barrierversion")>0)) {
//             bpage=1;
//             if (location.href.indexOf("ftchinese.com")>=0) {

//                 //if(i<0.3){bpage=2}else if(i<0.5){bpage=3}
//                 if (v.length>=100) {bpage=3;}
//                 k=GetCookie("bp");
//                 if (k!==null&&k!==""&&k>=2){bpage=k;}
//                 barrierversion=paravalue(window.location.href,"barrierversion");
//                 if (barrierversion!==null && barrierversion!==""){bpage=parseInt(barrierversion,0);}
//                 //如果是IE6，则不弹出全屏模式，但是一定让他登录才能看文章
//                 ie6=!!window.ActiveXObject&&!window.XMLHttpRequest;
//                 isIE=!!window.ActiveXObject;
//                 if (ie6 && v.length>=100) {
//                     bpage=6;
//                     $.get("/m/marketing/reg.html", function(data){
//                         $("#bodytext p").slice(2).remove();
//                         $("#bodytext p").eq(1).after(data.replace(/5篇以上文章/g,"10篇以上文章")+"
友好提示：我们注意到您还在使用IE6浏览，这会带来安全隐患。建议您升级到更高的版本，或使用最新的FireFox或Chrome等浏览器。
");
//                     });
//                 } else if (isIE && v.length>=100) {
//                     $.get("/m/marketing/reg.html", function(data){
//                         $("#bodytext p").slice(2).remove();
//                         $("#bodytext p").eq(1).after(data.replace(/5篇以上文章/g,"10篇以上文章"));
//                     });
//                 } else if (bpage>=2 && v.length>=100 && $(window).width()>1024 && (window.Modernizr === undefined || !window.Modernizr.touch)) {
//                     $.get("/m/marketing/reg"+bpage+".html", function(data){
//                     if (data.indexOf("用户名或电子邮件")>0) {
//                         $("#bodytext").html(data);
//                         $("#rail-content").empty();
//                         $(".story_list,#top590x60,#commentheader,#logincomment,#nologincomment,.commentcontainer,#sharelinks,.announce").remove();
//                         SetCookie("bp",bpage,86400*100,"/");
//                         }
//                     });
//                 } else {
//                     $.get("/m/marketing/reg.html", function(data){
//                         $("#bodytext p").eq(1).after(data);
//                     });
//                 }
//             }
//         }
//     }
// }
/* jshint ignore:end */<|endoftext|>


<commit_before>#!/usr/bin/env node

const puppeteer = require('puppeteer-core');
const program = require('commander');

const imagesSelector = 'article img[srcset]'
const timeout = 10000
const instagramBaseUrl = 'https://www.instagram.com'

function instagramFeedUrl (user) {
  return `${instagramBaseUrl}/${user}/`;
}

function instagramPostUrl (shortCode) {
  return `${instagramBaseUrl}/p/${shortCode}/`;
}

async function fetchUser ({ name, executablePath }) {
  const browser = await puppeteer.launch({ executablePath });
  const page = await browser.newPage();

  await page.goto(instagramFeedUrl(name), {
    waitUntil: 'load'
  });

  // eslint-disable-next-line no-underscore-dangle
  const data = await page.evaluate(() => window._sharedData);
  process.stdout.write(`${JSON.stringify(data)}\n`);
  await browser.close();
}

async function fetchPost ({ shortCode, executablePath }) {
  const browser = await puppeteer.launch({ executablePath });
  const page = await browser.newPage();
  await page.goto(instagramPostUrl(shortCode));
  await page.waitForSelector(imagesSelector, { timeout });

  const data = await page.evaluate(() => (
    Array
      .from(document.querySelectorAll(imagesSelector))
      .map(item => item.src)
  ));

  process.stdout.write(`${JSON.stringify(data)}\n`);
  await browser.close();
}

program
  .version('0.0.1')
  .description('Instagram content downloader')
  .option(
    '--exec-path <path>',
    'Chrome executable path',
    '/usr/bin/google-chrome-stable'
  );

program
  .command('user <name>')
  .description('download Instagram feed for specified user')
  .action(name => fetchUser({
    name,
    executablePath: program.execPath
  }));

program
  .command('post <shortCode>')
  .description('fetch Instagram post contents')
  .action(shortCode => fetchPost({
    shortCode,
    executablePath: program.execPath
  }));

program.parse(process.argv);
<commit_msg>Bypass constant to the browser context<commit_after>#!/usr/bin/env node

const puppeteer = require('puppeteer-core');
const program = require('commander');

const imagesSelector = 'article img[srcset]'
const timeout = 10000
const instagramBaseUrl = 'https://www.instagram.com'

function instagramFeedUrl (user) {
  return `${instagramBaseUrl}/${user}/`;
}

function instagramPostUrl (shortCode) {
  return `${instagramBaseUrl}/p/${shortCode}/`;
}

async function fetchUser ({ name, executablePath }) {
  const browser = await puppeteer.launch({ executablePath });
  const page = await browser.newPage();

  await page.goto(instagramFeedUrl(name), {
    waitUntil: 'load'
  });

  // eslint-disable-next-line no-underscore-dangle
  const data = await page.evaluate(() => window._sharedData);
  process.stdout.write(`${JSON.stringify(data)}\n`);
  await browser.close();
}

async function fetchPost ({ shortCode, executablePath }) {
  const browser = await puppeteer.launch({ executablePath });
  const page = await browser.newPage();
  await page.goto(instagramPostUrl(shortCode));
  await page.waitForSelector(imagesSelector, { timeout });
  const data = await page.evaluate(selector => (
    Array
      .from(document.querySelectorAll(selector))
      .map(item => item.src)
  ), imagesSelector);
  process.stdout.write(`${JSON.stringify(data)}\n`);
  await browser.close();
}

program
  .version('0.0.1')
  .description('Instagram content downloader')
  .option(
    '--exec-path <path>',
    'Chrome executable path',
    '/usr/bin/google-chrome-stable'
  );

program
  .command('user <name>')
  .description('download Instagram feed for specified user')
  .action(name => fetchUser({
    name,
    executablePath: program.execPath
  }));

program
  .command('post <shortCode>')
  .description('fetch Instagram post contents')
  .action(shortCode => fetchPost({
    shortCode,
    executablePath: program.execPath
  }));

program.parse(process.argv);
<|endoftext|>


<commit_before>var passport = require('passport'),
    LocalStrategyPropertyManger = require('passport-local').Strategy,
    LocalStrategeTenant = require('passport-local').Strategy,
    Model = require('./model/models.js');

module.exports = function(app) {
  app.use(passport.initialize());
  app.use(passport.session());

  // property manager local strategy login check
  passport.use(new LocalStrategyPropertyManger(
    function(username, password, done) {
      Model.PropertyManager.findOne({
        where: {
          'username': username
        }
      }).then(function (propertyManager) {
        if (propertyManager === null) {
          return done(null, false, { message: 'Incorrect credentials.' });
        }

        if (propertyManager.password === password) {
          return done(null, propertyManager);
        }

        return done(null, false, { message: 'Incorrect credentials.' });
      });
    }
  ));

  // tenant local strategy login check
  passport.use(new LocalStrategyTenant(
    function(username, password, done) {
      Model.Tenant.findOne({
        where: {
          'username': username
        }
      }).then(function (tenant) {
        if (tenant === null) {
          return done(null, false, { message: 'Incorrect credentials.' });
        }

        if (tenant.password === password) {
          return done(null, tenant);
        }

        return done(null, false, { message: 'Incorrect credentials.' });
      });
    }
  ));

  // property manager serialize
  passport.serializeUser(function(propertyManager, done) {
    done(null, propertyManager.id);
  });
  // property manager deserialize
  passport.deserializeUser(function(id, done) {
    Model.PropertyManager.findOne({
      where: {
        'id': id
      }
    }).then(function (propertyManager) {
      if (propertyManager === null) {
        done(new Error('Wrong user id.'));
      }

      done(null, propertyManager);
    });
  });

  // tenant serialize
  passport.serializeUser(function(tenant, done) {
    done(null, tenant.id);
  });
  // tenant deserialize
  passport.deserializeUser(function(id, done) {
    Model.Tenant.findOne({
      where: {
        'id': id
      }
    }).then(function (tenant) {
      if (tenant === null) {
        done(new Error('Wrong user id.'));
      }

      done(null, tenant);
    });
  });

};<commit_msg>Update setupPassport.js<commit_after>var passport = require('passport'),
    LocalStrategyPropertyManger = require('passport-local').Strategy,
    LocalStrategyTenant = require('passport-local').Strategy,
    Model = require('./model/models.js');

module.exports = function(app) {
  app.use(passport.initialize());
  app.use(passport.session());

  // property manager local strategy login check
  passport.use(new LocalStrategyPropertyManger(
    function(username, password, done) {
      Model.PropertyManager.findOne({
        where: {
          'username': username
        }
      }).then(function (propertyManager) {
        if (propertyManager === null) {
          return done(null, false, { message: 'Incorrect credentials.' });
        }

        if (propertyManager.password === password) {
          return done(null, propertyManager);
        }

        return done(null, false, { message: 'Incorrect credentials.' });
      });
    }
  ));

  // tenant local strategy login check
  passport.use(new LocalStrategyTenant(
    function(username, password, done) {
      Model.Tenant.findOne({
        where: {
          'username': username
        }
      }).then(function (tenant) {
        if (tenant === null) {
          return done(null, false, { message: 'Incorrect credentials.' });
        }

        if (tenant.password === password) {
          return done(null, tenant);
        }

        return done(null, false, { message: 'Incorrect credentials.' });
      });
    }
  ));

  // property manager serialize
  passport.serializeUser(function(propertyManager, done) {
    done(null, propertyManager.id);
  });
  // property manager deserialize
  passport.deserializeUser(function(id, done) {
    Model.PropertyManager.findOne({
      where: {
        'id': id
      }
    }).then(function (propertyManager) {
      if (propertyManager === null) {
        done(new Error('Wrong user id.'));
      }

      done(null, propertyManager);
    });
  });

  // tenant serialize
  passport.serializeUser(function(tenant, done) {
    done(null, tenant.id);
  });
  // tenant deserialize
  passport.deserializeUser(function(id, done) {
    Model.Tenant.findOne({
      where: {
        'id': id
      }
    }).then(function (tenant) {
      if (tenant === null) {
        done(new Error('Wrong user id.'));
      }

      done(null, tenant);
    });
  });

};
<|endoftext|>


<commit_before>Joshfire.define(['joshfire/class', 'joshfire/tree.data', 'joshfire/vendor/underscore'], function(Class, DataTree, _) {

  return Class(DataTree, {

    buildTree: function() {

      var self = this;

      return [
        {
          id: 'datasourcelist',

          children: function(query, callback) {
            var datasources = Joshfire.config.datasources;
            console.log(datasources);

            if (!datasources) { callback(['ERROR'], null); }

            var datasourceArray = [];
            _.each(datasources, function(value, key) {
              if(_.isArray(value)) {
                _forEach(value, function(val, index) {
                  datasourceArray.push( _.extend(val, { id: key + index }) );
                })
              } else {
                datasourceArray.push( _.extend(value, { id: key }) );
              }
            });
            console.log(datasourceArray);

            // Loop trough all items to create data tree branches
            _.each(datasourceArray, function(datasource, index) {
              self.set('/datasource/' + datasource.id,
                {
                  'id': datasource.id,
                  children: function(query, callback) {
                    datasource.find({}, function (err, data) {
                      // Make sure every entry has an id
                      // Some datasource entries have an id (item.sourceID), others don't (id)
                      var items = _.map(data.entries, function(item, id) {
                        return _.extend(item, { id: item.sourceId || id });
                      });
                      console.warn("find", items);
                      callback(null, items);
                    });
                  }
                });
            });

            callback(null, datasourceArray);
          }
        },
        {
          id: 'datasource',
          children: []
        }

      ];

    }
  });

});<commit_msg>removed console log<commit_after>Joshfire.define(['joshfire/class', 'joshfire/tree.data', 'joshfire/vendor/underscore'], function(Class, DataTree, _) {

  return Class(DataTree, {

    buildTree: function() {

      var self = this;

      return [
        {
          id: 'datasourcelist',

          children: function(query, callback) {
            var datasources = Joshfire.config.datasources;

            if (!datasources) { callback(['ERROR'], null); }

            var datasourceArray = [];
            _.each(datasources, function(value, key) {
              if(_.isArray(value)) {
                _forEach(value, function(val, index) {
                  datasourceArray.push( _.extend(val, { id: key + index }) );
                })
              } else {
                datasourceArray.push( _.extend(value, { id: key }) );
              }
            });

            // Loop trough all items to create data tree branches
            _.each(datasourceArray, function(datasource, index) {
              self.set('/datasource/' + datasource.id,
                {
                  'id': datasource.id,
                  children: function(query, callback) {
                    datasource.find({}, function (err, data) {
                      // Make sure every entry has an id
                      // Some datasource entries have an id (item.sourceID), others don't (id)
                      var items = _.map(data.entries, function(item, id) {
                        return _.extend(item, { id: item.sourceId || id });
                      });
                      callback(null, items);
                    });
                  }
                });
            });

            callback(null, datasourceArray);
          }
        },
        {
          id: 'datasource',
          children: []
        }

      ];

    }
  });

});<|endoftext|>


<commit_before>var fs = require("fs");
var path = require("path");
var async = require("async");
var EventEmitter = require("events").EventEmitter;

var AssetScanner = module.exports = function (options) {
  this.directory = options.src;
  this.initialized = false;
};

AssetScanner.prototype = new EventEmitter();

AssetScanner.prototype.scan = function () {
  this.scanDirectory(this.directory, function (err) {
    if (err) throw err;

    this.initialized = true;
    this.emit("initialized");
  }.bind(this));
};

AssetScanner.prototype.scanDirectory = function (dir, callback) {
  fs.readdir(dir, function (err, paths) {
    if (err) {
      if (err.code == "ENOENT") return callback(null);
      else return callback(err);
    }

    var fns = {};

    for (var i = 0; i < paths.length; i++) {
      fns[paths[i]] = this.scanDirectoryItem.bind(this, dir + path.sep + paths[i]);
    };

    async.parallel(fns, callback);
  }.bind(this));
};

AssetScanner.prototype.scanDirectoryItem = function (item, callback) {
  fs.stat(item, function (err, stats) {
    if (err) return callback(err);
    if (stats.isFile()) return this.scanFile(item, callback);
    if (stats.isDirectory()) return this.scanDirectory(item, callback);
  }.bind(this));
};

AssetScanner.prototype.scanFile = function (item, callback) {
  return this.onFile(item, callback);
};<commit_msg>Added file watching when detectChanges: true<commit_after>var fs = require("fs");
var path = require("path");
var async = require("async");
var EventEmitter = require("events").EventEmitter;

var AssetScanner = module.exports = function (options) {
  this.directory = options.src;
  this.detectChanges = options.detectChanges;
  this.initialized = false;
};

AssetScanner.prototype = new EventEmitter();

AssetScanner.prototype.scan = function () {
  this.scanDirectory(this.directory, function (err) {
    if (err) throw err;

    this.initialized = true;
    this.emit("initialized");
  }.bind(this));
};

AssetScanner.prototype.scanDirectory = function (dir, callback) {
  fs.readdir(dir, function (err, paths) {
    if (err) {
      if (err.code == "ENOENT") return callback(null);
      else return callback(err);
    }

    var fns = {};

    for (var i = 0; i < paths.length; i++) {
      fns[paths[i]] = this.scanDirectoryItem.bind(this, dir + path.sep + paths[i]);
    };

    async.parallel(fns, callback);
  }.bind(this));
};

AssetScanner.prototype.scanDirectoryItem = function (item, callback) {
  fs.stat(item, function (err, stats) {
    if (err) return callback(err);
    if (stats.isFile()) return this.scanFile(item, callback);
    if (stats.isDirectory()) return this.scanDirectory(item, callback);
  }.bind(this));
};

AssetScanner.prototype.scanFile = function (item, callback) {
  if (this.detectChanges) {
    fs.watch(item, { persistent: false }, function (e, filename) {
      this.onFile(item, function (err) {
        if (err) throw err;
      });
    }.bind(this));
  }
  return this.onFile(item, callback);
};<|endoftext|>


<commit_before>/**
 * Copyright (C) 2012 Yusuke Suzuki (twitter: @Constellation) and other contributors.
 * Released under the BSD license.
 * https://github.com/Constellation/esmangle/blob/master/LICENSE.BSD
 */
'use strict';

var isArray = Array.isArray || function isArray (array) {
    return Object.prototype.toString.call(array) === '[object Array]';
};

function deepCopyInternal (obj, result) {
    var key, val;
    for (key in obj) {
        if (key.lastIndexOf('_', 0) === 0) {
            continue;
        }
        if (obj.hasOwnProperty(key)) {
            val = obj[key];
            if (typeof val === 'object' && val !== null) {
                if (val instanceof RegExp) {
                    val = new RegExp(val);
                } else {
                    val = deepCopyInternal(val, isArray(val) ? [] : {});
                }
            }
            result[key] = val;
        }
    }
    return result;
}

function deepCopy (obj) {
    return deepCopyInternal(obj, isArray(obj) ? [] : {});
}

module.exports = deepCopy;
<commit_msg>chore(espurify): delete previous deepcopy logic<commit_after><|endoftext|>


<commit_before>var widgetModule = angular.module('widget', ['ngCookies']);

widgetModule.controller('widgetCtrl', function ($scope, $timeout, widgetService, mixpanelService, paramsService, dbService) {

    var hpcloud = 'HP';
    var softlayer = 'SOFTLAYER';
    var play = 'RUNNING';
    var stop = 'STOPPED';

    $scope.widgetStatus = {};

    function _getAdvanced(){
        return $scope.advancedParams[$scope.cloudType];
    }

    $scope.advancedParams = {};
    $scope.advancedParams[hpcloud] = {'type':'hpcloud-compute','params':{'project':null, 'key':null, 'secretKey':null}};
    $scope.advancedParams[softlayer] = {'type':'softlayer', 'params' : {'username':null, 'apiKey':null} };

    $scope.poweredByUrl = {};
    $scope.poweredByUrl[hpcloud] = "http://hpcloud.com";
    $scope.poweredByUrl[softlayer] = "http://softlayer.com";

    function _hasAdvanced(){
        var aData = _getAdvanced();
        var params = aData.params;
        for ( var i in params ){
            if ( params.hasOwnProperty(i) && !params[i] ){
                return false;
            }
        }
        return true;
    }

    function resetWidgetStatus( msg ){
        $scope.widgetStatus = {
            'state' : stop,
            'reset':true
        };

        if ( !!msg ){
            $scope.widgetStatus.message = msg;
        }
        ellipsisIndex = 0;
    }

    var ellipsisIndex = 0;
    var ellipsis='......';

    function _scrollLog() {
        var log = $('#log')[0];
        log.scrollTop = log.scrollHeight;
    }

    function handleStatus( status, myTimeout ){

        console.log(['got status', status]);
        dbService.saveWidgetStatus( status );
        $scope.ellipsis = ellipsis.substring(ellipsis.length - ellipsisIndex % ellipsis.length);
        ellipsisIndex = ellipsisIndex +1;
        $scope.widgetStatus = status;
        $timeout(pollStatus, myTimeout || 3000) ;
        _scrollLog();

    }

    function pollStatus( myTimeout){

        if ( $scope.widgetStatus.state !== stop ){ // keep polling until widget stops ==> mainly for timeleft..
            widgetService.getStatus( $scope.widgetStatus.instanceId, $scope.params.apiKey ).then( function( result ){
                if ( !result ){
                    return ;
                }
                handleStatus( result.status, myTimeout );
            },function(result){
                    console.log(['status error',result]);
                });
        }else{
            console.log("removing widget status");
            dbService.remove();
        }
    }

    $scope.isCompleted = function(){
        return $scope.widgetStatus.state === stop && !$scope.widgetStatus.instanceId && !$scope.widgetStatus.message && $scope.widgetStatus.timeleftMillis === 0;
    };
    $scope.pendingOutput = function(){
        return $scope.widgetStatus.state == play && !$scope.widgetStatus.output;
    };

    $scope.play = function(){
        resetWidgetStatus();
        $scope.widgetStatus.state = play;
        widgetService.play(  $scope.params.apiKey,  _hasAdvanced() ? _getAdvanced() : null )
            .then(function( result ){
                console.log(['play result', result]);
                $scope.widgetStatus = result.status;

                pollStatus(1);
        }, function( result ){
                console.log(['play error', result]);
                resetWidgetStatus("unknown error");
            });
//        success: function (data, textStatus, jqXHR) {
//            var state = data.status.state.toLowerCase();
//            if (state == "error" || state == "stopped") {
//                widgetState.showPlayButton();
//                widgetLog.error(data.status.message);
//                return;
//            }
//            if (data.status.instanceId) {
//                widgetState.instanceId(data.status.instanceId);
//            }
//
//            if ( advancedDataAvailable( advancedData ) ){
//                if (advancedData.project == advancedCookie.project() &&
//                    advancedData.key == advancedCookie.key() &&
//                    advancedData.secretKey == advancedCookie.secretKey()) {
//
//                    advancedCookie.prolong();
//
//                } else {
//                    $(".remember_creds").show();
//                }
//            }
//
//            setTimeoutForUpdateStatus(1);
//        },
//        error: function (data) {
//            var displayMessage = data.getResponseHeader("display-message");
//            if (displayMessage) {
//                var displayMessageObj = JSON.parse(displayMessage);
//                widgetLog.error(displayMessageObj.msg);
//            }
//        }
    };

    $scope.stop = function(){
        $scope.widgetStatus.state = stop;
        resetWidgetStatus();
    };

    $scope.getTimeLeft = function(){
        if ( !$scope.widgetStatus || !$scope.widgetStatus.timeleftMillis ){
            return "";
        }
        var timeLeft = $scope.widgetStatus.timeleftMillis;
        if ( !!timeLeft ){
            timeLeft = timeLeft / 1000;
            return (parseInt(timeLeft /60 ) + 1 )+ " minutes";
        }
        return "";
    };

    $scope.showPlay = function(){
        return $scope.widgetStatus.state === stop;
    };

    $scope.showStop = function(){
        return $scope.widgetStatus.state === play;
    };

    $scope.submitAdvancedData = function(){
        console.log("submitting advanced");
        $scope.play();
    };

    var savedStatus = dbService.getWidgetStatus();

    if ( !!savedStatus ){
        handleStatus( savedStatus,1 );
    }else{
        resetWidgetStatus();
    }

    console.log(["saved status", savedStatus]);
    // place params on scope
    $scope.params = paramsService.params;
    $scope.cloudType = myConf.cloudProvider;

    $scope.isShowAdvanced = function () {
        console.log(["showadvanced param is ", $scope.params.showAdvanced, $scope.params.showAdvanced == "true"]);
        try {
            return $scope.params.showAdvanced == "true";
        } catch (e) {
            return true;
        }
    };

    var apiKey = $scope.params.apiKey;
    var shareUrl= encodeURI("http://bluforcloud.com/plans/play");

    var msg =  encodeURI("Launch on the cloud in a single click using the Cloudify widget");
    var twitterMsg = encodeURIComponent( "I just installed #bluforcloud with a single click");

    $("#facebook_share_link").attr("href", "http://www.facebook.com/sharer/sharer.php?u=" + shareUrl).click(function(){
        window.open('http://www.facebook.com/sharer/sharer.php?u=' + shareUrl, 'facebook_share', 'height=320, width=640, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, directories=no, status=no');
        return false;
    });
    $("#google_plus_share_link").attr("href", "https://plus.google.com/share?url=" + shareUrl).click(function(){
        window.open("https://plus.google.com/share?url=" + shareUrl, 'height=320, width=640, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, directories=no, status=no');
    });
    $("#twitter_share_link").attr("href", "https://twitter.com/share?url=" + encodeURIComponent($scope.params.origin_page_url) + "&text=" + twitterMsg).click(function(){
        window.open("https://twitter.com/share?url=" + encodeURIComponent($scope.params.origin_page_url) + "&text=" + twitterMsg, 'height=320, width=640, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, directories=no, status=no');
    });

});

// encrypt decrypt service
widgetModule.service('encryptDecrypt', function ($http) {
    this.encrypt = function (data) {
        return $http.post('/encrypt', {data: data });
    };

    this.decrypt = function (data) {
        return $http.post('/decrypt', {data: data})
    };
});

widgetModule.service('paramsService', function(){
    // read params from URL;
    function get_params() {
        var params = {};
        var hash;
        var hashes = window.location.search.substring(1).split('&');
        console.log(["using search tearm", hashes ]);
        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');
            if ($.trim(hash[1]) != ""){
                params[hash[0]] = decodeURIComponent(hash[1]);
            }
        }
        console.log(["params are",params]);
        return params;
    }

    this.params = get_params();
});

widgetModule.service('dbService', function( $cookieStore, paramsService ){

    var params = paramsService.params;

    function getCookieName(){
        return "widgetCookie" + params.origin_page_url + params.apiKey;
    }

    this.remove = function(){
        this.saveWidgetStatus(null);
    };

    this.saveWidgetStatus = function(status){
        if ( !status ){
           $cookieStore.remove( getCookieName() );
        }else{
            $cookieStore.put( getCookieName() , status);
        }
    };

    this.getWidgetStatus = function(){
        return $cookieStore.get( getCookieName() );
    }
});

widgetModule.service('advancedData', function (encryptDecrypt) {
    var cookieName = "ADVANCED_DATA";
    this.save = function (data) {
        encryptDecrypt.encrypt(data).then(function (result) {
            $.cookie(cookieName, JSON.stringify(data), {"path": "/", expires: 10000 });
        });
    };

    this.load = function () {

        encryptDecrypt.decrypt($.cookie(cookieName)).then(function (result) {
            return result.data
        });
    }
});

widgetModule.service('widgetService', function( $http, mixpanelService, paramsService ){
    var origin_page_url = paramsService.params.origin_page_url;
    this.getStatus = function( instanceId , apiKey ){
        return $http.get( "/widget/"+ instanceId + "/status?apiKey=" + apiKey).then( function( data ){
            $.postMessage( JSON.stringify({name:"widget_status", data:data.data}), origin_page_url , parent );
            return data.data;
        });
    };

    this.play = function( apiKey, advancedData ){

        mixpanelService.startWidget( !advancedData );
        $.postMessage( JSON.stringify({name:"play_widget"}), origin_page_url , parent );
        if ( !advancedData ){
            return $http.post( '/widget/start?apiKey=' + encodeURI(apiKey)).then(function(result){ return result.data; });
        }else{
            return $http.post( '/widget/start?apiKey=' + encodeURI(apiKey),advancedData).then(function(result){ return result.data});
        }

    };

    this.stop = function(){
        if (!confirm("Are you sure you want to stop the instance?")) {
            return;
        }
        mixpanelService.stopWidget();
        $.postMessage( JSON.stringify({name:"stop_widget"}), origin_page_url , parent );
        widgetState.showPlayButton();
        if ( widgetState.instanceId()) {
            $.post("/widget/"+ widgetState.instanceId() + "/stop?apiKey=" + params["apiKey"], {}, function (data) {
                if (data && data.status && data.status.state == "error") {
                    widgetState.showPlayButton();
                    widgetLog.error(data.status.message );
                    return;
                }
                stop_instance();
            });
        }
    }
});

widgetModule.service('mixpanelService', function( paramsService){
    var params = paramsService.params;

    if ( !window.mixpanel ){
        window.mixpanel = { track : function(){ console.log(["mixpanel mock: tracking",arguments])} };
    }

      this.stopWidget = function(){
            mixpanel.track("Stop Widget",{'page name' : params.title, 'url' : params.origin_page_url });
      };

    this.startWidget = function( isAnonymous ){
        mixpanel.track("Play Widget",{'page name' : params.title , 'url' : params.origin_page_url, "anonymous" : isAnonymous });
    };

    this.trackClick = function( linkTitle ){
        mixpanel.track("Click", {'page name':params.title, 'url' : params.origin_page_url, 'link' : linkTitle  })
    };

});

widgetModule.directive('track', function( mixpanelService ){
    return {
        restrict:'C',
        link:function(scope,element){
            element.click(function(){
                mixpanelService.trackClick( element.text() );
            })
        }
    }
});

<commit_msg>updating mixpanel events.<commit_after>var widgetModule = angular.module('widget', ['ngCookies']);

widgetModule.controller('widgetCtrl', function ($scope, $timeout, widgetService, mixpanelService, paramsService, dbService) {

    var hpcloud = 'HP';
    var softlayer = 'SOFTLAYER';
    var play = 'RUNNING';
    var stop = 'STOPPED';

    $scope.widgetStatus = {};

    function _getAdvanced(){
        return $scope.advancedParams[$scope.cloudType];
    }

    $scope.advancedParams = {};
    $scope.advancedParams[hpcloud] = {'type':'hpcloud-compute','params':{'project':null, 'key':null, 'secretKey':null}};
    $scope.advancedParams[softlayer] = {'type':'softlayer', 'params' : {'username':null, 'apiKey':null} };

    $scope.poweredByUrl = {};
    $scope.poweredByUrl[hpcloud] = "http://hpcloud.com";
    $scope.poweredByUrl[softlayer] = "http://softlayer.com";

    function _hasAdvanced(){
        var aData = _getAdvanced();
        var params = aData.params;
        for ( var i in params ){
            if ( params.hasOwnProperty(i) && !params[i] ){
                return false;
            }
        }
        return true;
    }

    function resetWidgetStatus( msg ){
        $scope.widgetStatus = {
            'state' : stop,
            'reset':true
        };

        if ( !!msg ){
            $scope.widgetStatus.message = msg;
        }
        ellipsisIndex = 0;
    }

    var ellipsisIndex = 0;
    var ellipsis='......';

    function _scrollLog() {
        var log = $('#log')[0];
        log.scrollTop = log.scrollHeight;
    }

    function handleStatus( status, myTimeout ){

        console.log(['got status', status]);
        dbService.saveWidgetStatus( status );
        $scope.ellipsis = ellipsis.substring(ellipsis.length - ellipsisIndex % ellipsis.length);
        ellipsisIndex = ellipsisIndex +1;
        $scope.widgetStatus = status;
        $timeout(pollStatus, myTimeout || 3000) ;
        _scrollLog();

    }

    function pollStatus( myTimeout){

        if ( $scope.widgetStatus.state !== stop ){ // keep polling until widget stops ==> mainly for timeleft..
            widgetService.getStatus( $scope.widgetStatus.instanceId, $scope.params.apiKey ).then( function( result ){
                if ( !result ){
                    return ;
                }
                handleStatus( result.status, myTimeout );
            },function(result){
                    console.log(['status error',result]);
                });
        }else{
            console.log("removing widget status");
            dbService.remove();
        }
    }

    $scope.isCompleted = function(){
        return $scope.widgetStatus.state === stop && !$scope.widgetStatus.instanceId && !$scope.widgetStatus.message && $scope.widgetStatus.timeleftMillis === 0;
    };
    $scope.pendingOutput = function(){
        return $scope.widgetStatus.state == play && !$scope.widgetStatus.output;
    };

    $scope.play = function(){
        resetWidgetStatus();
        $scope.widgetStatus.state = play;
        widgetService.play(  $scope.params.apiKey,  _hasAdvanced() ? _getAdvanced() : null )
            .then(function( result ){
                console.log(['play result', result]);
                $scope.widgetStatus = result.status;

                pollStatus(1);
        }, function( result ){
                console.log(['play error', result]);
                resetWidgetStatus("unknown error");
            });
//        success: function (data, textStatus, jqXHR) {
//            var state = data.status.state.toLowerCase();
//            if (state == "error" || state == "stopped") {
//                widgetState.showPlayButton();
//                widgetLog.error(data.status.message);
//                return;
//            }
//            if (data.status.instanceId) {
//                widgetState.instanceId(data.status.instanceId);
//            }
//
//            if ( advancedDataAvailable( advancedData ) ){
//                if (advancedData.project == advancedCookie.project() &&
//                    advancedData.key == advancedCookie.key() &&
//                    advancedData.secretKey == advancedCookie.secretKey()) {
//
//                    advancedCookie.prolong();
//
//                } else {
//                    $(".remember_creds").show();
//                }
//            }
//
//            setTimeoutForUpdateStatus(1);
//        },
//        error: function (data) {
//            var displayMessage = data.getResponseHeader("display-message");
//            if (displayMessage) {
//                var displayMessageObj = JSON.parse(displayMessage);
//                widgetLog.error(displayMessageObj.msg);
//            }
//        }
    };

    $scope.stop = function(){
        mixpanelService.stopWidget();
        $scope.widgetStatus.state = stop;
        resetWidgetStatus();
    };

    $scope.getTimeLeft = function(){
        if ( !$scope.widgetStatus || !$scope.widgetStatus.timeleftMillis ){
            return "";
        }
        var timeLeft = $scope.widgetStatus.timeleftMillis;
        if ( !!timeLeft ){
            timeLeft = timeLeft / 1000;
            return (parseInt(timeLeft /60 ) + 1 )+ " minutes";
        }
        return "";
    };

    $scope.showPlay = function(){
        return $scope.widgetStatus.state === stop;
    };

    $scope.showStop = function(){
        return $scope.widgetStatus.state === play;
    };

    $scope.submitAdvancedData = function(){
        console.log("submitting advanced");
        $scope.play();
    };

    var savedStatus = dbService.getWidgetStatus();

    if ( !!savedStatus ){
        handleStatus( savedStatus,1 );
    }else{
        resetWidgetStatus();
    }

    console.log(["saved status", savedStatus]);
    // place params on scope
    $scope.params = paramsService.params;
    $scope.cloudType = myConf.cloudProvider;

    $scope.isShowAdvanced = function () {
        console.log(["showadvanced param is ", $scope.params.showAdvanced, $scope.params.showAdvanced == "true"]);
        try {
            return $scope.params.showAdvanced == "true";
        } catch (e) {
            return true;
        }
    };

    var apiKey = $scope.params.apiKey;
    var shareUrl= encodeURI("http://bluforcloud.com/plans/play");

    var msg =  encodeURI("Launch on the cloud in a single click using the Cloudify widget");
    var twitterMsg = encodeURIComponent( "I just installed #bluforcloud with a single click");

    $("#facebook_share_link").attr("href", "http://www.facebook.com/sharer/sharer.php?u=" + shareUrl).click(function(){
        window.open('http://www.facebook.com/sharer/sharer.php?u=' + shareUrl, 'facebook_share', 'height=320, width=640, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, directories=no, status=no');
        return false;
    });
    $("#google_plus_share_link").attr("href", "https://plus.google.com/share?url=" + shareUrl).click(function(){
        window.open("https://plus.google.com/share?url=" + shareUrl, 'height=320, width=640, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, directories=no, status=no');
    });
    $("#twitter_share_link").attr("href", "https://twitter.com/share?url=" + encodeURIComponent($scope.params.origin_page_url) + "&text=" + twitterMsg).click(function(){
        window.open("https://twitter.com/share?url=" + encodeURIComponent($scope.params.origin_page_url) + "&text=" + twitterMsg, 'height=320, width=640, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, directories=no, status=no');
    });

});

// encrypt decrypt service
widgetModule.service('encryptDecrypt', function ($http) {
    this.encrypt = function (data) {
        return $http.post('/encrypt', {data: data });
    };

    this.decrypt = function (data) {
        return $http.post('/decrypt', {data: data})
    };
});

widgetModule.service('paramsService', function(){
    // read params from URL;
    function get_params() {
        var params = {};
        var hash;
        var hashes = window.location.search.substring(1).split('&');
        console.log(["using search tearm", hashes ]);
        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');
            if ($.trim(hash[1]) != ""){
                params[hash[0]] = decodeURIComponent(hash[1]);
            }
        }
        console.log(["params are",params]);
        return params;
    }

    this.params = get_params();
});

widgetModule.service('dbService', function( $cookieStore, paramsService ){

    var params = paramsService.params;

    function getCookieName(){
        return "widgetCookie" + params.origin_page_url + params.apiKey;
    }

    this.remove = function(){
        this.saveWidgetStatus(null);
    };

    this.saveWidgetStatus = function(status){
        if ( !status ){
           $cookieStore.remove( getCookieName() );
        }else{
            $cookieStore.put( getCookieName() , status);
        }
    };

    this.getWidgetStatus = function(){
        return $cookieStore.get( getCookieName() );
    }
});

widgetModule.service('advancedData', function (encryptDecrypt) {
    var cookieName = "ADVANCED_DATA";
    this.save = function (data) {
        encryptDecrypt.encrypt(data).then(function (result) {
            $.cookie(cookieName, JSON.stringify(data), {"path": "/", expires: 10000 });
        });
    };

    this.load = function () {

        encryptDecrypt.decrypt($.cookie(cookieName)).then(function (result) {
            return result.data
        });
    }
});

widgetModule.service('widgetService', function( $http, mixpanelService, paramsService ){
    var origin_page_url = paramsService.params.origin_page_url;
    this.getStatus = function( instanceId , apiKey ){
        return $http.get( "/widget/"+ instanceId + "/status?apiKey=" + apiKey).then( function( data ){
            $.postMessage( JSON.stringify({name:"widget_status", data:data.data}), origin_page_url , parent );
            return data.data;
        });
    };

    this.play = function( apiKey, advancedData ){

        mixpanelService.startWidget( !advancedData );
        $.postMessage( JSON.stringify({name:"play_widget"}), origin_page_url , parent );
        if ( !advancedData ){
            return $http.post( '/widget/start?apiKey=' + encodeURI(apiKey)).then(function(result){ return result.data; });
        }else{
            return $http.post( '/widget/start?apiKey=' + encodeURI(apiKey),advancedData).then(function(result){ return result.data});
        }

    };

    this.stop = function(){
        if (!confirm("Are you sure you want to stop the instance?")) {
            return;
        }

        $.postMessage( JSON.stringify({name:"stop_widget"}), origin_page_url , parent );
        widgetState.showPlayButton();
        if ( widgetState.instanceId()) {
            $.post("/widget/"+ widgetState.instanceId() + "/stop?apiKey=" + params["apiKey"], {}, function (data) {
                if (data && data.status && data.status.state == "error") {
                    widgetState.showPlayButton();
                    widgetLog.error(data.status.message );
                    return;
                }
                stop_instance();
            });
        }
    }
});

widgetModule.service('mixpanelService', function( paramsService){
    var params = paramsService.params;

    if ( !window.mixpanel ){
        window.mixpanel = { track : function(){ console.log(["mixpanel mock: tracking",arguments])} };
    }

      this.stopWidget = function(){
            mixpanel.track("Stop Widget",{'page name' : params.title, 'url' : params.origin_page_url });
      };

    this.startWidget = function( isAnonymous ){
        mixpanel.track("Play Widget",{'page name' : params.title , 'url' : params.origin_page_url, "anonymous" : isAnonymous });
    };

    this.trackClick = function( linkTitle ){
        mixpanel.track("Click", {'page name':params.title, 'url' : params.origin_page_url, 'link' : linkTitle  })
    };

});

widgetModule.directive('track', function( mixpanelService ){
    return {
        restrict:'C',
        link:function(scope,element){
            element.click(function(){
                mixpanelService.trackClick( element.text() );
            })
        }
    }
});

<|endoftext|>


<commit_before>var hijackResponse  = require('hijackresponse');
var autoprefixer = require('autoprefixer');
var postcss = require('postcss');

module.exports = function () {
    var args = Array.prototype.slice.call(arguments);

    return function (req, res, next) {
        var fileType = (req.originalUrl.match(/\.(le|c)ss$/) || []).shift();
        // Prevent If-None-Match revalidation with the downstream middleware with ETags that aren't suffixed with "-autoprefixer":
        var ifNoneMatch = req.headers['if-none-match'];
        if (ifNoneMatch) {
            var validIfNoneMatchTokens = ifNoneMatch.split(" ").filter(function (etag) {
                return (/-autoprefixer["-]$/).test(etag);
            });
            if (validIfNoneMatchTokens.length > 0) {
                // Give the upstream middleware a chance to reply 304:
                req.headers['if-none-match'] = validIfNoneMatchTokens.map(function (validIfNoneMatchToken) {
                    return validIfNoneMatchToken.replace(/-autoprefixer(["-])$/, '$1');
                }).join(" ");
            } else {
                delete req.headers['if-none-match'];
            }
        }
        delete req.headers['if-modified-since']; // Prevent false positive conditional GETs after enabling autoprefixer

        hijackResponse(res, function (err, res) {
            if (err) {
                res.unhijack();
                return next(err);
            }

            if (!(!!fileType || /text\/css/.test(res.getHeader('Content-Type')))) {
                return res.unhijack();
            }

            var upstreamETag;

            if (res.statusCode === 304) {
                upstreamETag = res.getHeader('ETag');
                if (upstreamETag && !(/-autoprefixer"$/.test(upstreamETag))) {
                    res.setHeader('ETag', upstreamETag.replace(/"$/, '-autoprefixer"'));
                }
                return res.unhijack();
            } else if (res.statusCode !== 200) {
                return res.unhijack();
            }

            var chunks = [];
            res.on('data', function (chunk) {
                chunks.push(chunk);
            }).on('end', function () {
                var body = Buffer.concat(chunks).toString()
                return postcss([autoprefixer.apply(null, args)])
                    .process(body)
                    .then(function (result) {
                        res.setHeader('Content-Type', 'text/css');
                        upstreamETag = res.getHeader('ETag');
                        if (upstreamETag) {
                            res.setHeader('ETag', upstreamETag.replace(/"$/, '-autoprefixer"'));
                        }
                        res.setHeader('Content-Length', Buffer.byteLength(result.css));
                        res.end(result.css);
                    })
                    .catch(function (err) {
                        res.unhijack();
                        return next(err);
                    });
            });
        });
        return next();
    };
};
<commit_msg>add missing semicolon<commit_after>var hijackResponse  = require('hijackresponse');
var autoprefixer = require('autoprefixer');
var postcss = require('postcss');

module.exports = function () {
    var args = Array.prototype.slice.call(arguments);

    return function (req, res, next) {
        var fileType = (req.originalUrl.match(/\.(le|c)ss$/) || []).shift();
        // Prevent If-None-Match revalidation with the downstream middleware with ETags that aren't suffixed with "-autoprefixer":
        var ifNoneMatch = req.headers['if-none-match'];
        if (ifNoneMatch) {
            var validIfNoneMatchTokens = ifNoneMatch.split(" ").filter(function (etag) {
                return (/-autoprefixer["-]$/).test(etag);
            });
            if (validIfNoneMatchTokens.length > 0) {
                // Give the upstream middleware a chance to reply 304:
                req.headers['if-none-match'] = validIfNoneMatchTokens.map(function (validIfNoneMatchToken) {
                    return validIfNoneMatchToken.replace(/-autoprefixer(["-])$/, '$1');
                }).join(" ");
            } else {
                delete req.headers['if-none-match'];
            }
        }
        delete req.headers['if-modified-since']; // Prevent false positive conditional GETs after enabling autoprefixer

        hijackResponse(res, function (err, res) {
            if (err) {
                res.unhijack();
                return next(err);
            }

            if (!(!!fileType || /text\/css/.test(res.getHeader('Content-Type')))) {
                return res.unhijack();
            }

            var upstreamETag;

            if (res.statusCode === 304) {
                upstreamETag = res.getHeader('ETag');
                if (upstreamETag && !(/-autoprefixer"$/.test(upstreamETag))) {
                    res.setHeader('ETag', upstreamETag.replace(/"$/, '-autoprefixer"'));
                }
                return res.unhijack();
            } else if (res.statusCode !== 200) {
                return res.unhijack();
            }

            var chunks = [];
            res.on('data', function (chunk) {
                chunks.push(chunk);
            }).on('end', function () {
                var body = Buffer.concat(chunks).toString();
                return postcss([autoprefixer.apply(null, args)])
                    .process(body)
                    .then(function (result) {
                        res.setHeader('Content-Type', 'text/css');
                        upstreamETag = res.getHeader('ETag');
                        if (upstreamETag) {
                            res.setHeader('ETag', upstreamETag.replace(/"$/, '-autoprefixer"'));
                        }
                        res.setHeader('Content-Length', Buffer.byteLength(result.css));
                        res.end(result.css);
                    })
                    .catch(function (err) {
                        res.unhijack();
                        return next(err);
                    });
            });
        });
        return next();
    };
};
<|endoftext|>


<commit_before>const addExports = require('babel-plugin-add-module-exports')
const babelEnv = require('@babel/preset-env')
const flow = require('@babel/preset-flow')
const react = require('@babel/preset-react')
const reactRequire = require('babel-plugin-react-require').default
const lodash = require('babel-plugin-lodash')
const reactDisplayName = require('@babel/plugin-transform-react-display-name')
const classProperties = require('@babel/plugin-proposal-class-properties')
const exportFrom = require('@babel/plugin-proposal-export-namespace-from')
const istanbul = require('babel-plugin-istanbul')

const browsers = require('./constants').BROWSER_SUPPORT

module.exports = function (env, instrument) {
  const plugins = [
    addExports,
    classProperties,
    exportFrom,
    lodash,
    reactDisplayName,
    reactRequire
  ]

  if (instrument) { plugins.push(istanbul) }

  return {
    plugins,
    presets: [
      [
        babelEnv,
        {
          loose: false, // Loose mode breaks spread operator on `Set`s
          targets: { browsers },
          useBuiltIns: 'usage'
        }
      ],
      flow,
      react
    ]
  }
}
<commit_msg>fix(babel): change useBuiltIns to entry for core-js polyfill<commit_after>const addExports = require('babel-plugin-add-module-exports')
const babelEnv = require('@babel/preset-env')
const flow = require('@babel/preset-flow')
const react = require('@babel/preset-react')
const reactRequire = require('babel-plugin-react-require').default
const lodash = require('babel-plugin-lodash')
const reactDisplayName = require('@babel/plugin-transform-react-display-name')
const classProperties = require('@babel/plugin-proposal-class-properties')
const exportFrom = require('@babel/plugin-proposal-export-namespace-from')
const istanbul = require('babel-plugin-istanbul')

const browsers = require('./constants').BROWSER_SUPPORT

module.exports = function (env, instrument) {
  const plugins = [
    addExports,
    classProperties,
    exportFrom,
    lodash,
    reactDisplayName,
    reactRequire
  ]

  if (instrument) { plugins.push(istanbul) }

  return {
    plugins,
    presets: [
      [
        babelEnv,
        {
          loose: false, // Loose mode breaks spread operator on `Set`s
          targets: { browsers },
          useBuiltIns: 'entry'
        }
      ],
      flow,
      react
    ]
  }
}
<|endoftext|>


<commit_before>import d3 from 'd3';
import d3tip from 'd3-tip';

module.exports = function(divId, data) {

//clear out any current graph/content in the target div
document.getElementById(divId).innerHTML = '';

var margin = {top: 20, right: 20, bottom: 30, left: 60},
    width = document.querySelector("#"+divId).clientWidth - margin.left - margin.right,
    height = 250 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
    .rangeRoundBands([0, width], .1);

var y = d3.scale.linear()
    .range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .ticks(5);

var svg = d3.select("#" + divId).append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var tip = d3tip(d3)
  .attr('class', 'd3-tip')
  .offset([-10, 0])
  .html(function(d) {
    return "Hits: " + Number(d.value).toLocaleString() + "";
  })

svg.call(tip);

  x.domain(data.map(function(d) { return d.date.toString().slice(6, 8); }));
  y.domain([0, d3.max(data, function(d) { return d.value; })]);

  svg.append("g")
      .attr("class", "x axisM")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

  svg.append("g")
      .attr("class", "y axisM")
      .call(yAxis)
    .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text("value");

  svg.selectAll(".appsbar")
      .data(data)
    .enter().append("rect")
      .attr("class", "appsbar")
      .attr("x", function(d) { return x(d.date.toString().slice(6, 8)); })
      .attr("width", x.rangeBand())
      .attr("y", function(d) { return y(d.value); })
      .attr("height", function(d) { return height - y(d.value); })
      .on('mouseover', tip.show)
      .on('mouseout', tip.hide);

function type(d) {
  d.value = +d.value;
  return d;
}
}
<commit_msg>fix conflict<commit_after>import d3 from 'd3';
import d3tip from 'd3-tip';

module.exports = function(divId, data) {

//clear out any current graph/content in the target div
var outerDiv = document.getElementById(divId);
if (outerDiv) { outerDiv.innerHTML = '';}

var margin = {top: 20, right: 20, bottom: 30, left: 60},
    width = document.querySelector("#"+divId).clientWidth - margin.left - margin.right,
    height = 250 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
    .rangeRoundBands([0, width], .1);

var y = d3.scale.linear()
    .range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .ticks(5);

var svg = d3.select("#" + divId).append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var tip = d3tip(d3)
  .attr('class', 'd3-tip')
  .offset([-10, 0])
  .html(function(d) {
    return "Hits: " + Number(d.value).toLocaleString() + "";
  })

svg.call(tip);

  x.domain(data.map(function(d) { return d.date.toString().slice(6, 8); }));
  y.domain([0, d3.max(data, function(d) { return d.value; })]);

  svg.append("g")
      .attr("class", "x axisM")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

  svg.append("g")
      .attr("class", "y axisM")
      .call(yAxis)
    .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text("value");

  svg.selectAll(".appsbar")
      .data(data)
    .enter().append("rect")
      .attr("class", "appsbar")
      .attr("x", function(d) { return x(d.date.toString().slice(6, 8)); })
      .attr("width", x.rangeBand())
      .attr("y", function(d) { return y(d.value); })
      .attr("height", function(d) { return height - y(d.value); })
      .on('mouseover', tip.show)
      .on('mouseout', tip.hide);

function type(d) {
  d.value = +d.value;
  return d;
}
}
<|endoftext|>


<commit_before>CKEDITOR.editorConfig = function( config ) {
    config.toolbar = [
        { name: 'styles', items: [ 'Format', 'Styles', 'Font', 'FontSize' ] },
        { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat' ] },
        { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'bidi' ], items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'BidiLtr', 'BidiRtl', 'Language' ] },
        { name: 'align', groups: [ 'align' ], items: [ 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock' ] },
        { name: 'links', items: [ 'Link', 'Unlink', 'Anchor' ] },
        { name: 'insert', items: [ 'Image', 'oembed', 'Table', 'HorizontalRule', 'PageBreak', 'Iframe' ] },
        { name: 'colors', items: [ 'TextColor', 'BGColor' ] },
        { name: 'tools', items: [ 'Maximize', 'ShowBlocks', 'Source' ] },
        { name: 'others', items: [ '-' ] },
    ];

    // Quicktable config
    config.qtRows = 20, // Count of rows
    config.qtColumns = 20, // Count of columns
    config.qtBorder = '0', // Border of inserted table
    config.qtWidth = '100%', // Width of inserted table
    config.qtCellPadding = '0', // Cell padding table
    config.qtCellSpacing = '0', // Cell spacing table

    // Remove some buttons provided by the standard plugins, which are
    // not needed in the Standard(s) toolbar.
    config.removeButtons = 'Underline';

    config.entities = false;

    // Set the most common block elements.
    config.format_tags = 'p;h1;h2;h3;h4;h5;h6;pre';

    config.extraPlugins = 'image2,codemirror,autocorrect,clipboard,panelbutton,oembed,justify,quicktable,showblocks';
    config.removePlugins = 'image';

    // Skin / UI
    config.skin = 'typicms';
    config.uiColor = '#eeeeee';
    config.height = 500;
    config.dialog_backgroundCoverColor = 'black';

    // config.forcePasteAsPlainText = true;
    config.contentsCss = ['/css/public.css', '/components/ckeditor/css/content.css'];
    config.allowedContent = true;

    // codemirror
    config.codemirror = {
        theme: 'twilight'
    }

    // Language
    config.language = $('html').attr('lang');

    // Simplify the dialog windows.
    config.removeDialogTabs = 'image:Link;link:advanced;link:send';

    // File browser
    config.filebrowserBrowseUrl = '/admin/files?view=filepicker';
    config.filebrowserImageBrowseUrl = '/admin/files?type=i&view=filepicker';
    config.filebrowserWindowWidth = 800;
    config.filebrowserWindowHeight = 500;

};
CKEDITOR.dtd.$removeEmpty.span = 0;
CKEDITOR.dtd.$removeEmpty.i = 0;
<commit_msg>ckeditor config<commit_after>CKEDITOR.dtd.$removeEmpty.span = 0;
CKEDITOR.dtd.$removeEmpty.i = 0;
CKEDITOR.stylesSet.add( 'typicms_styles', [
    { name: 'Default button', element: 'a', attributes: { 'class': 'btn btn-default' } },
    { name: 'Primary button', element: 'a', attributes: { 'class': 'btn btn-primary' } }
]);

CKEDITOR.editorConfig = function( config ) {
    config.toolbar = [
        { name: 'styles', items: [ 'Format', 'Styles', 'Font', 'FontSize' ] },
        { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat' ] },
        { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'bidi' ], items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'BidiLtr', 'BidiRtl', 'Language' ] },
        { name: 'align', groups: [ 'align' ], items: [ 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock' ] },
        { name: 'links', items: [ 'Link', 'Unlink', 'Anchor' ] },
        { name: 'insert', items: [ 'Image', 'oembed', 'Table', 'HorizontalRule', 'PageBreak', 'Iframe' ] },
        { name: 'colors', items: [ 'TextColor', 'BGColor' ] },
        { name: 'tools', items: [ 'Maximize', 'ShowBlocks', 'Source' ] },
        { name: 'others', items: [ '-' ] },
    ];

    // Quicktable config
    config.qtRows = 20, // Count of rows
    config.qtColumns = 20, // Count of columns
    config.qtBorder = '0', // Border of inserted table
    config.qtWidth = '100%', // Width of inserted table
    config.qtCellPadding = '0', // Cell padding table
    config.qtCellSpacing = '0', // Cell spacing table

    config.stylesSet = 'typicms_styles';

    // Remove some buttons provided by the standard plugins, which are
    // not needed in the Standard(s) toolbar.
    config.removeButtons = 'Underline';

    config.entities = false;

    // Set the most common block elements.
    config.format_tags = 'p;h1;h2;h3;h4;h5;h6;pre';

    config.extraPlugins = 'image2,codemirror,autocorrect,clipboard,panelbutton,oembed,justify,quicktable,showblocks';
    config.removePlugins = 'image';

    // Skin / UI
    config.skin = 'typicms';
    config.uiColor = '#eeeeee';
    config.height = 500;
    config.dialog_backgroundCoverColor = 'black';

    // config.forcePasteAsPlainText = true;
    config.contentsCss = ['/css/public.css', '/components/ckeditor/css/content.css'];
    config.allowedContent = true;

    // codemirror
    config.codemirror = {
        theme: 'twilight'
    }

    // Language
    config.language = $('html').attr('lang');

    // Simplify the dialog windows.
    config.removeDialogTabs = 'image:Link;link:advanced;link:send';

    // File browser
    config.filebrowserBrowseUrl = '/admin/files?view=filepicker';
    config.filebrowserImageBrowseUrl = '/admin/files?type=i&view=filepicker';
    config.filebrowserWindowWidth = 800;
    config.filebrowserWindowHeight = 500;

};
<|endoftext|>


<commit_before>'use strict'

var debug = require('debug')('owfs:convert')

exports.preparePayload = function (payload) {
  if (payload === true) {
    return '1'
  } else if (payload === false) {
    return '0'
  } else {
    return payload.toString()
  }
}

exports.extractValue = function (callback) {
  return function (error, messages) {
    if (!error) {
      var messageToUse
      if (messages.length > 1) {
        debug('Received multiple messages in simple read', messages)
        messageToUse = messages.filter(function (message) {
          debug('Checking Header payload > 0', message.header.payload)
          return message.header.payload > 0
        })
      } else {
        messageToUse = messages
      }
      debug('message to use', messageToUse)
      if (messageToUse.length > 0) {
        var payload = messageToUse[0].payload;
        var result = payload !== null ? payload.replace(new RegExp(' ', 'g'), '') : null;
        return callback(error, result)
      } else {
        var err = new Error('No usable messages received, but no error returned.')
        // FIXME: remove this in version 1.0.0
        err.msg = err.message
        return callback(err)
      }
    } else {
      return callback(error)
    }
  }
}

var extractDirectoriesFromMessage = function (message) {
  if (message.payload) {
    if (message.payload.substr(-1) === '\0') {
      // Remove trailing NULL character
      message.payload = message.payload.slice(0, -1)
    }
    return message.payload.split(',')
  } else {
    return []
  }
}

exports.extractDirectories = function (callback) {
  debug('extractDirectories')
  return function (err, messages) {
    debug(messages)
    if (!err) {
      var directories = messages.map(extractDirectoriesFromMessage)
      var _ref
      debug('extracted directories', directories)
      return callback(err, (_ref = []).concat.apply(_ref, directories))
    } else {
      return callback(err)
    }
  }
}

exports.extractPresence = function (callback) {
  return function (err, messages) {
    var presence = false
    // If device is not present ret < 0 will be returned.
    // Device is present if ret is 0.
    if (err && err.header && (err.header.ret < 0)) {
      presence = false
    } else if (messages && (messages[0].header.ret === 0)) {
      presence = true
    } else {
      debug('failed to extract presence')
      if (!err) {
        err = new Error('Unexpected response on presence request')
      }
      return callback(err)
    }

    debug('extracted presence: ', presence)
    return callback(null, presence)
  }
}
<commit_msg>remove semicolons to pass ci tests<commit_after>'use strict'

var debug = require('debug')('owfs:convert')

exports.preparePayload = function (payload) {
  if (payload === true) {
    return '1'
  } else if (payload === false) {
    return '0'
  } else {
    return payload.toString()
  }
}

exports.extractValue = function (callback) {
  return function (error, messages) {
    if (!error) {
      var messageToUse
      if (messages.length > 1) {
        debug('Received multiple messages in simple read', messages)
        messageToUse = messages.filter(function (message) {
          debug('Checking Header payload > 0', message.header.payload)
          return message.header.payload > 0
        })
      } else {
        messageToUse = messages
      }
      debug('message to use', messageToUse)
      if (messageToUse.length > 0) {
        var payload = messageToUse[0].payload
        var result = payload !== null ? payload.replace(new RegExp(' ', 'g'), '') : null
        return callback(error, result)
      } else {
        var err = new Error('No usable messages received, but no error returned.')
        // FIXME: remove this in version 1.0.0
        err.msg = err.message
        return callback(err)
      }
    } else {
      return callback(error)
    }
  }
}

var extractDirectoriesFromMessage = function (message) {
  if (message.payload) {
    if (message.payload.substr(-1) === '\0') {
      // Remove trailing NULL character
      message.payload = message.payload.slice(0, -1)
    }
    return message.payload.split(',')
  } else {
    return []
  }
}

exports.extractDirectories = function (callback) {
  debug('extractDirectories')
  return function (err, messages) {
    debug(messages)
    if (!err) {
      var directories = messages.map(extractDirectoriesFromMessage)
      var _ref
      debug('extracted directories', directories)
      return callback(err, (_ref = []).concat.apply(_ref, directories))
    } else {
      return callback(err)
    }
  }
}

exports.extractPresence = function (callback) {
  return function (err, messages) {
    var presence = false
    // If device is not present ret < 0 will be returned.
    // Device is present if ret is 0.
    if (err && err.header && (err.header.ret < 0)) {
      presence = false
    } else if (messages && (messages[0].header.ret === 0)) {
      presence = true
    } else {
      debug('failed to extract presence')
      if (!err) {
        err = new Error('Unexpected response on presence request')
      }
      return callback(err)
    }

    debug('extracted presence: ', presence)
    return callback(null, presence)
  }
}
<|endoftext|>