<commit_before>/**
 * @author: general
 * @website: note.generals.space
 * @email: generals.space@gmail.com
 * @github: https://github.com/generals-space/bootstrap-table-addrbar
 * @update: zhixin wen <wenzhixin2010@gmail.com>
 */

($ => {
  /*
     * function: 获取浏览器地址栏中的指定参数.
     * key: 参数名
     * url: 默认为当前地址栏
     */
  function _GET (key, url = window.location.search) {
    /*
     * 注意这里正则表达式的书写方法
     * (^|&)key匹配: 直接以key开始或以&key开始的字符串
     * 同理(&|$)表示以&结束或是直接结束的字符串
     * ...当然, 我并不知道这种用法.
     */
    const reg = new RegExp(`(^|&)${key}=([^&]*)(&|$)`)
    const result = url.substr(1).match(reg)

    if (result) {
      return decodeURIComponent(result[2])
    }
    return null
  }

  /*
    * function: 根据给定参数生成url地址
    * var dic = {name: 'genreal', age: 24}
    * var url = 'https://www.baidu.com?age=22';
    * _buildUrl(dic, url);
    * 将得到"https://www.baidu.com?age=24&name=genreal"
    * 哦, 忽略先后顺序吧...
    *
    * 补充: 可以参考浏览器URLSearchParams对象, 更加方便和强大.
    * 考虑到兼容性, 暂时不使用这个工具.
    */

  function _buildUrl (dict, url = window.location.search) {
    for (const [key, val] of Object.entries(dict)) {
      // 搜索name=general这种形式的字符串(&是分隔符)
      const pattern = `${key}=([^&]*)`
      const targetStr = `${key}=${val}`

      /*
       * 如果目标url中包含了key键, 我们需要将它替换成我们自己的val
       * 不然就直接添加好了.
       */
      if (url.match(pattern)) {
        const tmp = new RegExp(`(${key}=)([^&]*)`, 'gi')
        url = url.replace(tmp, targetStr)
      } else {
        const seperator = url.match('[?]') ? '&' : '?'
        url = url + seperator + targetStr
      }
    }
    return url
  }

  $.BootstrapTable = class extends $.BootstrapTable {
    init () {
      // 拥有addrbar选项并且其值为true的才会继续执行
      if (this.options.addrbar) {
        // 标志位, 初始加载后关闭
        this.addrbarInit = true
        const _prefix = this.options.addrPrefix || ''

        // 优先级排序: 用户指定值最优先, 未指定时从地址栏获取, 未获取到时采用默认值
        this.options.pageSize = this.options.pageSize || (
          _GET(`${_prefix}limit`) ? parseInt(_GET(`${_prefix}limit`)) : $.BootstrapTable.DEFAULTS.pageSize
        )
        this.options.pageNumber = this.options.pageNumber || (
          _GET(`${_prefix}page`) ? parseInt(_GET(`${_prefix}page`)) : $.BootstrapTable.DEFAULTS.pageNumber
        )
        this.options.sortOrder = this.options.sortOrder || (
          _GET(`${_prefix}order`) ? _GET(`${_prefix}order`) : $.BootstrapTable.DEFAULTS.sortOrder
        )
        this.options.sortName = this.options.sortName || (
          _GET(`${_prefix}sort`) ? _GET(`${_prefix}sort`) : 'id'
        )
        this.options.searchText = this.options.searchText || (
          _GET(`${_prefix}search`) ? _GET(`${_prefix}search`) : $.BootstrapTable.DEFAULTS.searchText
        )

        const _onLoadSuccess = this.options.onLoadSuccess

        this.options.onLoadSuccess = data => {
          if (this.addrbarInit) {
            this.addrbarInit = false
          } else {
            const params = {}
            params[`${_prefix}page`] = this.options.pageNumber,
            params[`${_prefix}limit`] = this.options.pageSize,
            params[`${_prefix}order`] = this.options.sortOrder,
            params[`${_prefix}sort`] = this.options.sortName,
            params[`${_prefix}search`] = this.options.searchText
            // h5提供的修改浏览器地址栏的方法
            window.history.pushState({}, '', _buildUrl(params))
          }

          if (_onLoadSuccess) {
            _onLoadSuccess.call(this, data)
          }
        }
      }
      super.init()
    }
  }
})(jQuery)
<commit_msg>fix #4199: Fixed addrbar remove hash from url bug.<commit_after>/**
 * @author: general
 * @website: note.generals.space
 * @email: generals.space@gmail.com
 * @github: https://github.com/generals-space/bootstrap-table-addrbar
 * @update: zhixin wen <wenzhixin2010@gmail.com>
 */

($ => {
  /*
     * function: 获取浏览器地址栏中的指定参数.
     * key: 参数名
     * url: 默认为当前地址栏
     */
  function _GET (key, url = window.location.search) {
    /*
     * 注意这里正则表达式的书写方法
     * (^|&)key匹配: 直接以key开始或以&key开始的字符串
     * 同理(&|$)表示以&结束或是直接结束的字符串
     * ...当然, 我并不知道这种用法.
     */
    const reg = new RegExp(`(^|&)${key}=([^&]*)(&|$)`)
    const result = url.substr(1).match(reg)

    if (result) {
      return decodeURIComponent(result[2])
    }
    return null
  }

  /*
    * function: 根据给定参数生成url地址
    * var dic = {name: 'genreal', age: 24}
    * var url = 'https://www.baidu.com?age=22';
    * _buildUrl(dic, url);
    * 将得到"https://www.baidu.com?age=24&name=genreal"
    * 哦, 忽略先后顺序吧...
    *
    * 补充: 可以参考浏览器URLSearchParams对象, 更加方便和强大.
    * 考虑到兼容性, 暂时不使用这个工具.
    */

  function _buildUrl (dict, url = window.location.search) {
    for (const [key, val] of Object.entries(dict)) {
      // 搜索name=general这种形式的字符串(&是分隔符)
      const pattern = `${key}=([^&]*)`
      const targetStr = `${key}=${val}`

      /*
       * 如果目标url中包含了key键, 我们需要将它替换成我们自己的val
       * 不然就直接添加好了.
       */
      if (url.match(pattern)) {
        const tmp = new RegExp(`(${key}=)([^&]*)`, 'gi')
        url = url.replace(tmp, targetStr)
      } else {
        const seperator = url.match('[?]') ? '&' : '?'
        url = url + seperator + targetStr
      }
    }
    if (location.hash) {
      url += location.hash
    }
    return url
  }

  $.BootstrapTable = class extends $.BootstrapTable {
    init () {
      // 拥有addrbar选项并且其值为true的才会继续执行
      if (this.options.addrbar) {
        // 标志位, 初始加载后关闭
        this.addrbarInit = true
        const _prefix = this.options.addrPrefix || ''

        // 优先级排序: 用户指定值最优先, 未指定时从地址栏获取, 未获取到时采用默认值
        this.options.pageSize = this.options.pageSize || (
          _GET(`${_prefix}limit`) ? parseInt(_GET(`${_prefix}limit`)) : $.BootstrapTable.DEFAULTS.pageSize
        )
        this.options.pageNumber = this.options.pageNumber || (
          _GET(`${_prefix}page`) ? parseInt(_GET(`${_prefix}page`)) : $.BootstrapTable.DEFAULTS.pageNumber
        )
        this.options.sortOrder = this.options.sortOrder || (
          _GET(`${_prefix}order`) ? _GET(`${_prefix}order`) : $.BootstrapTable.DEFAULTS.sortOrder
        )
        this.options.sortName = this.options.sortName || (
          _GET(`${_prefix}sort`) ? _GET(`${_prefix}sort`) : 'id'
        )
        this.options.searchText = this.options.searchText || (
          _GET(`${_prefix}search`) ? _GET(`${_prefix}search`) : $.BootstrapTable.DEFAULTS.searchText
        )

        const _onLoadSuccess = this.options.onLoadSuccess

        this.options.onLoadSuccess = data => {
          if (this.addrbarInit) {
            this.addrbarInit = false
          } else {
            const params = {}
            params[`${_prefix}page`] = this.options.pageNumber,
            params[`${_prefix}limit`] = this.options.pageSize,
            params[`${_prefix}order`] = this.options.sortOrder,
            params[`${_prefix}sort`] = this.options.sortName,
            params[`${_prefix}search`] = this.options.searchText
            // h5提供的修改浏览器地址栏的方法
            window.history.pushState({}, '', _buildUrl(params))
          }

          if (_onLoadSuccess) {
            _onLoadSuccess.call(this, data)
          }
        }
      }
      super.init()
    }
  }
})(jQuery)
<|endoftext|>


<commit_before>/*! wpt - v3.0.1 - 2013-07-30\n* Copyright (c) 2013 Billy Vong <billy@woopra.com>; Licensed  */(function(t,i){"use strict";var e,n,o,a={},s=[],r=!0,c=!0;a.CONSTANTS={VERSION:11,ENDPOINT:"//www.woopra.com/track/"},a.extend=function(t,i){for(var e in i)t[e]=i[e]},a.readCookie=function(e){var n,o,a;return""===e?"":(n=""+i.cookie,o=n.indexOf(e),-1===o?"":(a=n.indexOf(";",o),-1===a&&(a=n.length),t.unescape(n.substring(o+e.length+1,a))))},a.setCookie=function(t,e,n,o,a){var s=[];s.push(t+"="+e),s.push("expires="+n),s.push("path="+a),s.push("domain=."+o),i.cookie=s.join("; ")},a.getCampaignData=function(){for(var t,i,e=a.getUrlParams(),n={},o=["source","medium","content","campaign","term"],s=0;o.length>s;s++)t=o[s],i=e["utm_"+t]||e["woo_"+t],i!==void 0&&(n["campaign_"+("campaign"===t?"name":t)]=i);return n},a.getUrlParams=function(){var i={};return t.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(t,e,n){i[e]=decodeURIComponent(n.split("+").join(" "))}),i},a.buildUrlParams=function(t,i){var e,n=i||"",o=[];if(t===void 0)return t;for(e in t)o.push(n+encodeURIComponent(e)+"="+encodeURIComponent(t[e]));return o.join("&")},a.randomString=function(){var t,i,e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",n="";for(t=0;12>t;t++)i=Math.floor(Math.random()*e.length),n+=e.substring(i,i+1);return n},a.loadScript=function(t,e){var n,o,s=i.createElement("script");s.type="text/javascript",s.src=t,s.async=!0,e&&"function"==typeof e&&(o=e),s.onreadystatechange!==void 0?s.onreadystatechange=function(){(4===this.readyState||"complete"===this.readyState||"loaded"===this.readyState)&&(o&&o(),a.removeScript(s))}:s.onload=function(){o&&o(),a.removeScript(s)},n=i.getElementsByTagName("script")[0],n.parentNode.insertBefore(s,n)},a.removeScript=function(t){t.parentNode.removeChild(t)},a.getHost=function(){return t.location.host.replace("www.","")},a.endsWith=function(t,i){return-1!==t.indexOf(i,t.length-i.length)},a.sleep=function(t){for(var i=new Date,e=new Date;t>e-i;)e=new Date},e=a._on=function(t,i){s[t]||(s[t]=[]),s[t].push(i)},a._fire=function(t){var i;if(s[t])for(i=0;s[t].length>i;i++)s[t][i].apply(this,Array.prototype.slice.call(arguments,1))},a.attachEvent=function(i,e,n){var o,a,s;t.document.attachEvent!==void 0?(o="attachEvent",a="on"+e):(o="addEventListener",a=e,s=!1),i[o](a,n,s)},a.attachEvent(i,"mousedown",function(i){var e,s,h,p;for(a._fire("mousemove",i,new Date),e=i.srcElement||i.target;e!==void 0&&null!==e&&(!e.tagName||"a"!==e.tagName.toLowerCase());)e=e.parentNode;e!==void 0&&null!==e&&(s=e,h=s.pathname.match(/(?:doc|dmg|eps|jpg|jpeg|png|svg|xls|ppt|pdf|xls|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3|mp4|m4v)($|\&)/),p=!1,r&&h&&0>(""+s.href).indexOf("woopra-ns.com")&&(a._fire("download",s.href),a.sleep(n)),c&&!h&&s.hostname!==t.location.host&&-1===s.hostname.indexOf("javascript")&&""!==s.hostname&&(a._fire("outgoing",s.href),a.sleep(o)))}),a.attachEvent(i,"mousemove",function(t){a._fire("mousemove",t,new Date)}),a.attachEvent(i,"keydown",function(){a._fire("keydown")});var h=function(i){this.visitorData={},this.sessionData={},this.options={},this.instanceName=i,this.idle=0,this.cookie="",this.last_activity=new Date,this._loaded=!1,this.version=a.CONSTANTS.VERSION,i&&""!==i&&(t[i]=this)};if(h.prototype={init:function(){this._setOptions(),this._processQueue("config"),this._setupCookie(),this._bindEvents(),this._loaded=!0,this._processQueue()},_setOptions:function(){var t=new Date;t.setDate(t.getDate()+365),this.config({domain:a.getHost(),cookie_name:"wooTracker",cookie_domain:null,cookie_path:"/",cookie_expire:t,ping:!0,ping_interval:12e3,idle_timeout:3e5,idle_threshold:1e4,download_pause:200,outgoing_pause:400,download_tracking:!0,outgoing_tracking:!0,ignore_query_url:!0})},_processQueue:function(i){var e,n,o,a=t._w[this.instanceName];if(a&&a._e)for(o=a._e,e=0;o.length>e;e++)n=o[e],void 0===n||!this[n[0]]||void 0!==i&&i!==n[0]||this[n[0]].apply(this,Array.prototype.slice.call(n,1))},_setupCookie:function(){this.cookie=a.readCookie(this.config("cookie_name")),this.cookie&&this.cookie.length>0||(this.cookie=a.randomString()),null===this.config("cookie_domain")&&(a.endsWith(t.location.host,"."+this.config("domain"))?this.config("cookie_domain",this.config("domain")):this.config("cookie_domain",a.getHost())),a.setCookie(this.config("cookie_name"),this.cookie,this.config("cookie_exp"),this.config("cookie_domain"),this.config("cookie_path"))},_bindEvents:function(){var t=this;e("mousemove",function(){t.moved.apply(t,arguments)}),e("keydown",function(){t.typed.apply(t,arguments)}),e("download",function(){t.downloaded.apply(t,arguments)}),e("outgoing",function(){t.outgoing.apply(t,arguments)})},_dataSetter:function(t,i,e){var n;if(i===void 0)return t;if(e===void 0){if("string"==typeof i)return t[i];if("object"==typeof i)for(n in i)t[n]=i[n]}else t[i]=e;return this},_push:function(t){var i,e,n,o,s,r=t||{},c=this.config("protocol"),h=c&&""!==c?c+":":"",p=h+a.CONSTANTS.ENDPOINT+r.endpoint+"/",u="ra="+a.randomString(),l=[["visitorData","cv_"],["eventData","ce_"],["sessionData","cs_"]],g=[];g.push(u),g.push(a.buildUrlParams(this.getOptionParams()));for(s in l)o=l[s],r[o[0]]&&(e=a.buildUrlParams(r[o[0]],o[1]),e&&g.push(e));i="?"+g.join("&"),n=p+i,a.loadScript(n,r.callback)},config:function(t,i){var e=this._dataSetter(this.options,t,i);return e===this&&(6e3>this.options.ping_interval?this.options.ping_interval=6e3:this.options.ping_interval>6e4&&(this.options.ping_interval=6e4),c=c&&this.options.outgoing_tracking,o=o||this.options.outgoing_pause,r=r&&this.options.download_tracking,n=n||this.options.download_pause),e},visit:function(t,i){return this._dataSetter(this.sessionData,t,i)},identify:function(t,i){return this._dataSetter(this.visitorData,t,i)},call:function(t){this[t]&&"function"==typeof this[t]&&this[t].apply(this,Array.prototype.slice.call(arguments,1))},track:function(t,i){var e,n={},o=arguments[arguments.length-1];a.extend(n,a.getCampaignData()),"function"==typeof o&&(e=o),t===void 0||t===e?(n.name="pv",n.url=this.getPageUrl(),n.title=this.getPageTitle()):i===void 0||i===e?("string"==typeof t&&(n.name=t),"object"==typeof t&&this._dataSetter(n,t)):(n.name=t,this._dataSetter(n,i)),this._push({endpoint:"ce",visitorData:this.visitorData,sessionData:this.sessionData,eventData:n,callback:e}),this.startPing()},startPing:function(){var i=this;this.pingInterval===void 0&&(this.pingInterval=t.setInterval(function(){i.ping()},this.config("ping_interval")))},stopPing:function(){this.pingInterval!==void 0&&(t.clearInterval(this.pingInterval),delete this.pingInterval)},ping:function(){var t;return this.config("ping")&&this.idle<this.config("idle_timeout")?this._push({endpoint:"ping"}):this.stopPing(),t=new Date,t-this.last_activity>this.config("idle_threshold")&&(this.idle=t-this.last_activity),this},push:function(t){return this._push({endpoint:"identify",visitorData:this.visitorData,sessionData:this.sessionData,callback:t}),this},sleep:function(t){a.sleep(t)},moved:function(t,i){this.last_activity=i,this.idle=0},typed:function(){this.vs=2},downloaded:function(t){this.track("download",{url:t})},outgoing:function(t){this.track("outgoing",{url:t})},getPageUrl:function(){return this.options.ignore_query_url?t.location.pathname:t.location.pathname+t.location.search},getPageTitle:function(){return 0===i.getElementsByTagName("title").length?"":i.getElementsByTagName("title")[0].innerHTML},getOptionParams:function(){var e={alias:this.config("domain"),instance:this.instanceName,cookie:a.readCookie(this.config("cookie_name")),ka:this.config("keep_alive")||2*this.config("ping_interval"),meta:a.readCookie("wooMeta")||"",screen:t.screen.width+"x"+t.screen.height,language:t.navigator.browserLanguage||t.navigator.language||"",referer:i.referrer,idle:""+parseInt(this.idle/1e3,10),vs:"i"};return 2===this.vs?(e.vs="w",this.vs=0):0===this.idle&&(e.vs="r"),e},dispose:function(){this.stopPing(),t[this.instanceName]!==void 0&&delete t[this.instanceName]}},t._w!==void 0)for(var p in t._w){var u=new h(p);u.init(),void 0===typeof t.woopraTracker&&(t.woopraTracker=u)}t.WoopraTracker=h,t.WoopraLoadScript=a.loadScript,t.exports!==void 0&&(a.Tracker=h,t.exports.Woopra=a)})(window,document);<commit_msg>Update build<commit_after>/*! wpt - v3.0.1 - 2013-07-31\n* Copyright (c) 2013 Billy Vong <billy@woopra.com>; Licensed  */(function(t,i){"use strict";var e,n,o,a={},s=[],r=!0,c=!0;a.CONSTANTS={VERSION:11,ENDPOINT:"//www.woopra.com/track/"},a.extend=function(t,i){for(var e in i)t[e]=i[e]},a.readCookie=function(e){var n,o,a;return""===e?"":(n=""+i.cookie,o=n.indexOf(e),-1===o?"":(a=n.indexOf(";",o),-1===a&&(a=n.length),t.unescape(n.substring(o+e.length+1,a))))},a.setCookie=function(t,e,n,o,a){var s=[];s.push(t+"="+e),s.push("expires="+n),s.push("path="+a),s.push("domain=."+o),i.cookie=s.join("; ")},a.getCampaignData=function(){for(var t,i,e=a.getUrlParams(),n={},o=["source","medium","content","campaign","term"],s=0;o.length>s;s++)t=o[s],i=e["utm_"+t]||e["woo_"+t],i!==void 0&&(n["campaign_"+("campaign"===t?"name":t)]=i);return n},a.getUrlParams=function(){var i={};return t.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(t,e,n){i[e]=decodeURIComponent(n.split("+").join(" "))}),i},a.buildUrlParams=function(t,i){var e,n=i||"",o=[];if(t===void 0)return t;for(e in t)o.push(n+encodeURIComponent(e)+"="+encodeURIComponent(t[e]));return o.join("&")},a.randomString=function(){var t,i,e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",n="";for(t=0;12>t;t++)i=Math.floor(Math.random()*e.length),n+=e.substring(i,i+1);return n},a.loadScript=function(t,e){var n,o,s=i.createElement("script");s.type="text/javascript",s.src=t,s.async=!0,e&&"function"==typeof e&&(o=e),s.onreadystatechange!==void 0?s.onreadystatechange=function(){(4===this.readyState||"complete"===this.readyState||"loaded"===this.readyState)&&o&&o(),a.removeScript(s)}:(s.onload=function(){o&&o(),a.removeScript(s)},s.onerror=function(){a.removeScript(s)}),n=i.getElementsByTagName("script")[0],n.parentNode.insertBefore(s,n)},a.removeScript=function(t){t.parentNode.removeChild(t)},a.getHost=function(){return t.location.host.replace("www.","")},a.endsWith=function(t,i){return-1!==t.indexOf(i,t.length-i.length)},a.sleep=function(t){for(var i=new Date,e=new Date;t>e-i;)e=new Date},e=a._on=function(t,i){s[t]||(s[t]=[]),s[t].push(i)},a._fire=function(t){var i;if(s[t])for(i=0;s[t].length>i;i++)s[t][i].apply(this,Array.prototype.slice.call(arguments,1))},a.attachEvent=function(i,e,n){var o,a,s;t.document.attachEvent!==void 0?(o="attachEvent",a="on"+e):(o="addEventListener",a=e,s=!1),i[o](a,n,s)},a.attachEvent(i,"mousedown",function(i){var e,s,h,p;for(a._fire("mousemove",i,new Date),e=i.srcElement||i.target;e!==void 0&&null!==e&&(!e.tagName||"a"!==e.tagName.toLowerCase());)e=e.parentNode;e!==void 0&&null!==e&&(s=e,h=s.pathname.match(/(?:doc|dmg|eps|jpg|jpeg|png|svg|xls|ppt|pdf|xls|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3|mp4|m4v)($|\&)/),p=!1,r&&h&&0>(""+s.href).indexOf("woopra-ns.com")&&(a._fire("download",s.href),a.sleep(n)),c&&!h&&s.hostname!==t.location.host&&-1===s.hostname.indexOf("javascript")&&""!==s.hostname&&(a._fire("outgoing",s.href),a.sleep(o)))}),a.attachEvent(i,"mousemove",function(t){a._fire("mousemove",t,new Date)}),a.attachEvent(i,"keydown",function(){a._fire("keydown")});var h=function(i){this.visitorData={},this.sessionData={},this.options={},this.instanceName=i,this.idle=0,this.cookie="",this.last_activity=new Date,this._loaded=!1,this.version=a.CONSTANTS.VERSION,i&&""!==i&&(t[i]=this)};if(h.prototype={init:function(){this._setOptions(),this._processQueue("config"),this._setupCookie(),this._bindEvents(),this._loaded=!0,this._processQueue()},_setOptions:function(){var t=new Date;t.setDate(t.getDate()+365),this.config({domain:a.getHost(),cookie_name:"wooTracker",cookie_domain:null,cookie_path:"/",cookie_expire:t,ping:!0,ping_interval:12e3,idle_timeout:3e5,idle_threshold:1e4,download_pause:200,outgoing_pause:400,download_tracking:!0,outgoing_tracking:!0,ignore_query_url:!0})},_processQueue:function(i){var e,n,o,a=t._w[this.instanceName];if(a&&a._e)for(o=a._e,e=0;o.length>e;e++)n=o[e],void 0===n||!this[n[0]]||void 0!==i&&i!==n[0]||this[n[0]].apply(this,Array.prototype.slice.call(n,1))},_setupCookie:function(){this.cookie=a.readCookie(this.config("cookie_name")),this.cookie&&this.cookie.length>0||(this.cookie=a.randomString()),null===this.config("cookie_domain")&&(a.endsWith(t.location.host,"."+this.config("domain"))?this.config("cookie_domain",this.config("domain")):this.config("cookie_domain",a.getHost())),a.setCookie(this.config("cookie_name"),this.cookie,this.config("cookie_exp"),this.config("cookie_domain"),this.config("cookie_path"))},_bindEvents:function(){var t=this;e("mousemove",function(){t.moved.apply(t,arguments)}),e("keydown",function(){t.typed.apply(t,arguments)}),e("download",function(){t.downloaded.apply(t,arguments)}),e("outgoing",function(){t.outgoing.apply(t,arguments)})},_dataSetter:function(t,i,e){var n;if(i===void 0)return t;if(e===void 0){if("string"==typeof i)return t[i];if("object"==typeof i)for(n in i)t[n]=i[n]}else t[i]=e;return this},_push:function(t){var i,e,n,o,s,r=t||{},c=this.config("protocol"),h=c&&""!==c?c+":":"",p=h+a.CONSTANTS.ENDPOINT+r.endpoint+"/",u="ra="+a.randomString(),l=[["visitorData","cv_"],["eventData","ce_"],["sessionData","cs_"]],g=[];g.push(u),g.push(a.buildUrlParams(this.getOptionParams()));for(s in l)o=l[s],r[o[0]]&&(e=a.buildUrlParams(r[o[0]],o[1]),e&&g.push(e));i="?"+g.join("&"),n=p+i,a.loadScript(n,r.callback)},config:function(t,i){var e=this._dataSetter(this.options,t,i);return e===this&&(6e3>this.options.ping_interval?this.options.ping_interval=6e3:this.options.ping_interval>6e4&&(this.options.ping_interval=6e4),c=c&&this.options.outgoing_tracking,o=o||this.options.outgoing_pause,r=r&&this.options.download_tracking,n=n||this.options.download_pause),e},visit:function(t,i){return this._dataSetter(this.sessionData,t,i)},identify:function(t,i){return this._dataSetter(this.visitorData,t,i)},call:function(t){this[t]&&"function"==typeof this[t]&&this[t].apply(this,Array.prototype.slice.call(arguments,1))},track:function(t,i){var e,n={},o=arguments[arguments.length-1];a.extend(n,a.getCampaignData()),"function"==typeof o&&(e=o),t===void 0||t===e?(n.name="pv",n.url=this.getPageUrl(),n.title=this.getPageTitle()):i===void 0||i===e?("string"==typeof t&&(n.name=t),"object"==typeof t&&this._dataSetter(n,t)):(n.name=t,this._dataSetter(n,i)),this._push({endpoint:"ce",visitorData:this.visitorData,sessionData:this.sessionData,eventData:n,callback:e}),this.startPing()},startPing:function(){var i=this;this.pingInterval===void 0&&(this.pingInterval=t.setInterval(function(){i.ping()},this.config("ping_interval")))},stopPing:function(){this.pingInterval!==void 0&&(t.clearInterval(this.pingInterval),delete this.pingInterval)},ping:function(){var t;return this.config("ping")&&this.idle<this.config("idle_timeout")?this._push({endpoint:"ping"}):this.stopPing(),t=new Date,t-this.last_activity>this.config("idle_threshold")&&(this.idle=t-this.last_activity),this},push:function(t){return this._push({endpoint:"identify",visitorData:this.visitorData,sessionData:this.sessionData,callback:t}),this},sleep:function(t){a.sleep(t)},moved:function(t,i){this.last_activity=i,this.idle=0},typed:function(){this.vs=2},downloaded:function(t){this.track("download",{url:t})},outgoing:function(t){this.track("outgoing",{url:t})},getPageUrl:function(){return this.options.ignore_query_url?t.location.pathname:t.location.pathname+t.location.search},getPageTitle:function(){return 0===i.getElementsByTagName("title").length?"":i.getElementsByTagName("title")[0].innerHTML},getOptionParams:function(){var e={alias:this.config("domain"),instance:this.instanceName,cookie:a.readCookie(this.config("cookie_name")),ka:this.config("keep_alive")||2*this.config("ping_interval"),meta:a.readCookie("wooMeta")||"",screen:t.screen.width+"x"+t.screen.height,language:t.navigator.browserLanguage||t.navigator.language||"",referer:i.referrer,idle:""+parseInt(this.idle/1e3,10),vs:"i"};return 2===this.vs?(e.vs="w",this.vs=0):0===this.idle&&(e.vs="r"),e},dispose:function(){this.stopPing(),t[this.instanceName]!==void 0&&delete t[this.instanceName]}},t._w!==void 0)for(var p in t._w){var u=new h(p);u.init(),void 0===typeof t.woopraTracker&&(t.woopraTracker=u)}t.WoopraTracker=h,t.WoopraLoadScript=a.loadScript,t.exports!==void 0&&(a.Tracker=h,t.exports.Woopra=a)})(window,document);<|endoftext|>


<commit_before>/**
 * @name model.js<spec>
 * @author Kei Funagayama <funagayama_kei@cyberagent.co.jp>
 * copyright (c) Cyberagent Inc.
 * @overview TestCase: s/beez-mvcr/model
 */

define(['model', 'backbone.localStorage'], function(model, LocalStorage){

    var Collection = model.Collection;
    var Model = model.Model;
    var ModelManager = model.ModelManager;

    //var manager = model.manager;
    var manager = new ModelManager('midx');

    var TestRootModel = Model.extend('TestRootModel', {
        midx: '@', defaults: {title: '', completed: false}, localStorage: new LocalStorage('beez-spec'), flag: false, urlRoot: 'http://0.0.0.0:1109/p',
        dispose: function() { this.flag = true; TestRootModel.__super__.dispose.apply(this); }
    });
    var TestModel = Model.extend('TestModel', {
        midx:'test', defaults:{title:'',completed:false}, localStorage:new LocalStorage('beez-spec'), flag:false, urlRoot:'http://0.0.0.0:1109/p',
        dispose:function () { this.flag=true; TestModel.__super__.dispose.apply(this);}
    });
    var TestModel1 = Model.extend('TestModel1', {
        midx:'test1', defaults:{title:'',completed:false}, localStorage:new LocalStorage('beez-spec'), flag:false, urlRoot:'http://0.0.0.0:1109/p',
        dispose: function () { this.flag=true; TestModel1.__super__.dispose.apply(this); }
    });
    var TestModel2 = Model.extend('TestModel2', {
        midx:'test2', defaults:{title:'',completed:false}, localStorage:new LocalStorage('beez-spec'), flag:false, urlRoot:'http://0.0.0.0:1109/p',
        dispose:function(){ this.flag=true; TestModel2.__super__.dispose.apply(this); }
    });
    var TestModel3 = Model.extend('TestModel3', {
        midx:'test3', defaults:{title:'',completed:false}, localStorage:new LocalStorage('beez-spec'), flag:false, urlRoot:'http://0.0.0.0:1109/p',
        dispose:function () { this.flag=true; TestModel3.__super__.dispose.apply(this);}
    });
    var TestCollection = Collection.extend('TestCollection', {
        midx:'tests', model:TestModel, localStorage:new LocalStorage('beez-spec-Collection'), flag:false,
        dispose:function(){ this.flag=true; TestCollection.__super__.dispose.apply(this); }
    });
    var TestCModel = Model.extend('TestCModel', {
        midx:'ctest', defaults:{title:'',completed:false}, localStorage:new LocalStorage('beez-spec-Collection'), flag:false,
        dispose:function(){ this.flag=true; }
    });

    var model1, collection1, testModel1;

    return function () {

        before(function () {
            console.log('localStorage is cleared');
            window.localStorage.removeItem('beez-spec');
            window.localStorage.removeItem('beez-spec-Collection');
            localStorage.clear(); // prepared for failing test.
        });
        describe('Model', function () {
            it('set/fetch/save/destroy sync', function () {
                for (var i = 0; i < 10; i++) {
                    var t = new TestModel();
                    t.set('title', 'aaaaa' + i);
                    t.fetch();
                    t.save();
                    t.destroy();
                    t.fetch();
                }
                expect(localStorage.getItem("beez-spec")).not.be.ok; // browser api

            });
            it('fetch #1', function (done) {
                testModel1 = new TestModel();
                testModel1.set('title', 'taro');
                testModel1
                    .async()
                    .fetch()
                    .then(function(res, next) {
                        expect(res.model.constructor.name).eq('TestModel');
                        done();
                    })
                    .error(function(err, next) {
                        throw new Error("fetch error. #1");
                        done();
                    })
                    .end()
                ;
            });

            it('save', function (done) {
                testModel1.save({title: 'I am TestModel!!'});

                testModel1
                    .async()
                    .save()
                    .then(function(res) {
                        expect(res.model.get('title')).eq('I am TestModel!!').be.ok
                        expect(res.model.attributes.title).eq('I am TestModel!!');
                        //expect(res.model._manager._idxProp).eq('midx');
                        expect(res.model.urlRoot).eq('http://0.0.0.0:1109/p');
                        done();
                    })
                    .end()
                ;
            });
            it('destroy', function (done) {
                testModel1
                    .async()
                    .destroy()
                    .then(function(res, next) {
                        expect(res.model.constructor.name).eq('TestModel');
                        done();

                    }).error(function(err, next) {
                        throw new Error("destroy error.");
                        done();
                    }).end()
                ;
            });
            it('fetch #2', function (done) {
                testModel1
                    .async()
                    .fetch()
                    .then(function(res, next) {
                        throw new Error("fetch error. #2");
                        done();

                    }).error(function(err, next) {
                        done();
                    })
                    .end()
                ;
            });
        });

        describe('Collection', function () {
            var c;
            it('new/create/destroy/fetch sync', function () {
                c = new TestCollection();
                var testcmodel1 = new TestCModel();
                testcmodel1.set('title', 'bbbbb');
                c.create(testcmodel1);
                expect(c.length).eq(1);

                testcmodel1.destroy();
                ///c.fetch();

                expect(c.length).eq(0);
            });

            it('midx', function () {
                expect(c.midx).eq('tests');
            });

            it('create async', function (done) {
                var cmodel1 = new TestCModel();
                cmodel1.set('title', "1");
                var cmodel2 = new TestCModel();
                cmodel2.set('title', "2");

                c.async().create(cmodel1).create(cmodel2).then(function() {
                    expect(c.models.length).eq(2);
                    expect(localStorage.getItem('beez-spec-Collection').split(",").length).eq(2);
                    cmodel1.destroy();
                    cmodel2.destroy();

                    //c.fetch();
                    expect(c.models.length).eq(0);
                    expect(localStorage.getItem('beez-spec-Collection').split(",").length).eq(1); // empty
                    done();
                }).error(function(err, next) {
                    throw new Error("create error. async");
                    done();
                }).end()
                ;
            });
        });

        describe('manager', function () {

            it('_idxProp: "midx"', function () {
                expect(manager._idxProp).eq('midx');
            });
            it('objs: Object', function () {
                expect(manager.objs.midx).eq('$');
            });

            it('root', function () {
                var model = manager.root(TestRootModel);
                expect(manager.get('/@')).be.ok;
            });

            it('create async', function (done) {
                //
                manager.async().create('/@', TestModel).then(function() {
                    expect(manager.get('/@/test')).be.ok;
                    done();
                }).error(function(err, next) {
                    console.log(err);
                    console.log(next);
                    throw new Error('manager.create error.');
                    done();
                }).end();;
            });
            it('create', function () {
                expect(manager.create('/@', TestModel1)).be.ok;
                expect(manager.get('/@/test1')).be.ok;
                expect(manager.create('/@', TestModel2)).be.ok;
                expect(manager.get('/@/test2')).be.ok;
            });
            it('createCollection', function () {
                var model = new TestModel3({'title': 'Collection in TestModel!!'});
                manager.createCollection('/@', TestCollection, [model]);
                var col = manager.get('/@/tests');
                expect(col.length).eq(1);
                expect(col.prefix).eq('/@');
                expect(col.midx).eq('tests');
                expect(col.models[0].get('title')).eq('Collection in TestModel!!');

                // remove
                col.each(function (model) {
                    col.remove(model);
                }, this);
                expect(col.length).eq(0);
            });
            it('dispose: function dispose(path) {', function () {
                manager.dispose('/@/test2');
                if (manager.get('/@/test2')) {
                    throw new Error('/@/test2 dispose error');
                }
            });
        });
        describe('ModelManager', function () {
            it('TODO', function () {
                // TOOD
            })
        });
    };
});
<commit_msg>Add: testecase for `isBinded`<commit_after>/**
 * @name model.js<spec>
 * @author Kei Funagayama <funagayama_kei@cyberagent.co.jp>
 * copyright (c) Cyberagent Inc.
 * @overview TestCase: s/beez-mvcr/model
 */

define(['model', 'backbone.localStorage'], function(model, LocalStorage){

    var Collection = model.Collection;
    var Model = model.Model;
    var ModelManager = model.ModelManager;

    //var manager = model.manager;
    var manager = new ModelManager('midx');

    var TestRootModel = Model.extend('TestRootModel', {
        midx: '@', defaults: {title: '', completed: false}, localStorage: new LocalStorage('beez-spec'), flag: false, urlRoot: 'http://0.0.0.0:1109/p',
        dispose: function() { this.flag = true; TestRootModel.__super__.dispose.apply(this); }
    });
    var TestModel = Model.extend('TestModel', {
        midx:'test', defaults:{title:'',completed:false}, localStorage:new LocalStorage('beez-spec'), flag:false, urlRoot:'http://0.0.0.0:1109/p',
        dispose:function () { this.flag=true; TestModel.__super__.dispose.apply(this);}
    });
    var TestModel1 = Model.extend('TestModel1', {
        midx:'test1', defaults:{title:'',completed:false}, localStorage:new LocalStorage('beez-spec'), flag:false, urlRoot:'http://0.0.0.0:1109/p',
        dispose: function () { this.flag=true; TestModel1.__super__.dispose.apply(this); }
    });
    var TestModel2 = Model.extend('TestModel2', {
        midx:'test2', defaults:{title:'',completed:false}, localStorage:new LocalStorage('beez-spec'), flag:false, urlRoot:'http://0.0.0.0:1109/p',
        dispose:function(){ this.flag=true; TestModel2.__super__.dispose.apply(this); }
    });
    var TestModel3 = Model.extend('TestModel3', {
        midx:'test3', defaults:{title:'',completed:false}, localStorage:new LocalStorage('beez-spec'), flag:false, urlRoot:'http://0.0.0.0:1109/p',
        dispose:function () { this.flag=true; TestModel3.__super__.dispose.apply(this);}
    });
    var TestCollection = Collection.extend('TestCollection', {
        midx:'tests', model:TestModel, localStorage:new LocalStorage('beez-spec-Collection'), flag:false,
        dispose:function(){ this.flag=true; TestCollection.__super__.dispose.apply(this); }
    });
    var TestCModel = Model.extend('TestCModel', {
        midx:'ctest', defaults:{title:'',completed:false}, localStorage:new LocalStorage('beez-spec-Collection'), flag:false,
        dispose:function(){ this.flag=true; }
    });

    var model1, collection1, testModel1;

    return function () {

        before(function () {
            console.log('localStorage is cleared');
            window.localStorage.removeItem('beez-spec');
            window.localStorage.removeItem('beez-spec-Collection');
            localStorage.clear(); // prepared for failing test.
        });
        describe('Model', function () {
            it('set/fetch/save/destroy sync', function () {
                for (var i = 0; i < 10; i++) {
                    var t = new TestModel();
                    t.set('title', 'aaaaa' + i);
                    t.fetch();
                    t.save();
                    t.destroy();
                    t.fetch();
                }
                expect(localStorage.getItem("beez-spec")).not.be.ok; // browser api

            });
            it('fetch #1', function (done) {
                testModel1 = new TestModel();
                testModel1.set('title', 'taro');
                testModel1
                    .async()
                    .fetch()
                    .then(function(res, next) {
                        expect(res.model.constructor.name).eq('TestModel');
                        done();
                    })
                    .error(function(err, next) {
                        throw new Error("fetch error. #1");
                        done();
                    })
                    .end()
                ;
            });

            it('save', function (done) {
                testModel1.save({title: 'I am TestModel!!'});

                testModel1
                    .async()
                    .save()
                    .then(function(res) {
                        expect(res.model.get('title')).eq('I am TestModel!!').be.ok
                        expect(res.model.attributes.title).eq('I am TestModel!!');
                        //expect(res.model._manager._idxProp).eq('midx');
                        expect(res.model.urlRoot).eq('http://0.0.0.0:1109/p');
                        done();
                    })
                    .end()
                ;
            });
            it('destroy', function (done) {
                testModel1
                    .async()
                    .destroy()
                    .then(function(res, next) {
                        expect(res.model.constructor.name).eq('TestModel');
                        done();

                    }).error(function(err, next) {
                        throw new Error("destroy error.");
                        done();
                    }).end()
                ;
            });
            it('fetch #2', function (done) {
                testModel1
                    .async()
                    .fetch()
                    .then(function(res, next) {
                        throw new Error("fetch error. #2");
                        done();

                    }).error(function(err, next) {
                        done();
                    })
                    .end()
                ;
            });
            it('isBinded', function () {
                var model1 = new TestModel();
                var model2 = new TestModel();
                var model3 = new TestModel();

                model1.listenTo(model2, 'sync', beez.none);
                model3.listenTo(model3, 'sync', beez.none);
                expect(model1.isBinded()).be.not.ok;
                expect(model2.isBinded()).be.ok;
                expect(model3.isBinded()).be.not.ok;
            });
        });

        describe('Collection', function () {
            var c;
            it('new/create/destroy/fetch sync', function () {
                c = new TestCollection();
                var testcmodel1 = new TestCModel();
                testcmodel1.set('title', 'bbbbb');
                c.create(testcmodel1);
                expect(c.length).eq(1);

                testcmodel1.destroy();
                ///c.fetch();

                expect(c.length).eq(0);
            });

            it('midx', function () {
                expect(c.midx).eq('tests');
            });

            it('create async', function (done) {
                var cmodel1 = new TestCModel();
                cmodel1.set('title', "1");
                var cmodel2 = new TestCModel();
                cmodel2.set('title', "2");

                c.async().create(cmodel1).create(cmodel2).then(function() {
                    expect(c.models.length).eq(2);
                    expect(localStorage.getItem('beez-spec-Collection').split(",").length).eq(2);
                    cmodel1.destroy();
                    cmodel2.destroy();

                    //c.fetch();
                    expect(c.models.length).eq(0);
                    expect(localStorage.getItem('beez-spec-Collection').split(",").length).eq(1); // empty
                    done();
                }).error(function(err, next) {
                    throw new Error("create error. async");
                    done();
                }).end()
                ;
            });
            it('isBinded', function () {
                var cmodel1 = new TestCModel();
                var cmodel2 = new TestCModel();
                var cmodel3 = new TestCModel();

                cmodel1.listenTo(cmodel2, 'sync', beez.none);
                cmodel3.listenTo(cmodel3, 'sync', beez.none);
                expect(cmodel1.isBinded()).be.not.ok;
                expect(cmodel2.isBinded()).be.ok;
                expect(cmodel3.isBinded()).be.not.ok;
            });
        });

        describe('manager', function () {

            it('_idxProp: "midx"', function () {
                expect(manager._idxProp).eq('midx');
            });
            it('objs: Object', function () {
                expect(manager.objs.midx).eq('$');
            });

            it('root', function () {
                var model = manager.root(TestRootModel);
                expect(manager.get('/@')).be.ok;
            });

            it('create async', function (done) {
                //
                manager.async().create('/@', TestModel).then(function() {
                    expect(manager.get('/@/test')).be.ok;
                    done();
                }).error(function(err, next) {
                    console.log(err);
                    console.log(next);
                    throw new Error('manager.create error.');
                    done();
                }).end();;
            });
            it('create', function () {
                expect(manager.create('/@', TestModel1)).be.ok;
                expect(manager.get('/@/test1')).be.ok;
                expect(manager.create('/@', TestModel2)).be.ok;
                expect(manager.get('/@/test2')).be.ok;
            });
            it('createCollection', function () {
                var model = new TestModel3({'title': 'Collection in TestModel!!'});
                manager.createCollection('/@', TestCollection, [model]);
                var col = manager.get('/@/tests');
                expect(col.length).eq(1);
                expect(col.prefix).eq('/@');
                expect(col.midx).eq('tests');
                expect(col.models[0].get('title')).eq('Collection in TestModel!!');

                // remove
                col.each(function (model) {
                    col.remove(model);
                }, this);
                expect(col.length).eq(0);
            });
            it('dispose: function dispose(path) {', function () {
                manager.dispose('/@/test2');
                if (manager.get('/@/test2')) {
                    throw new Error('/@/test2 dispose error');
                }
            });
        });
        describe('ModelManager', function () {
            it('TODO', function () {
                // TOOD
            })
        });
    };
});
<|endoftext|>


<commit_before>module.exports = {

	/*
		WEARABLE
	*/

	// Flag for if feathers should be started in verbose mode
	START_FEATHER_IN_VERBOSE_MODE: false,

	// Flag for if feathers should request rssi updates
	REQUEST_RSSI_UPDATES: true,

	// Override rate at which RSSI should be updated
	OVERRIDE_REQUEST_RSSI_UPDATE_RATE: 500
};<commit_msg>update<commit_after>module.exports = {

	/*
		WEARABLE
	*/

	// Flag for if feathers should be started in verbose mode
	START_FEATHER_IN_VERBOSE_MODE: false,

	// Flag for if feathers should request rssi updates
	REQUEST_RSSI_UPDATES: true,

	// Override rate at which RSSI should be updated
	OVERRIDE_REQUEST_RSSI_UPDATE_RATE: 1000
};<|endoftext|>


<commit_before>'use strict';

var doiuse = require('doiuse');
var path = require('path');
var postcss = require('postcss');
var request = require('request');
var diff = require('./diffParse');
var parseSource = require('./sourceParse');

var token = 'token ' + process.env.OAUTH_TOKEN;
var productName = 'Discord';

var comment = function(httpRequest, response) {
    var eventType = httpRequest.headers['x-github-event'];
    var payload = httpRequest.body;
    var configMetadataURL = payload.repository.contents_url.replace('{+path}', '.doiuse');
    var commitsURL, commentURL;

    // TODO: Only acknowledge pushes to the "Master" branch.
    console.log('Repo: ' + payload.repository.full_name);
    console.log('Payload:');
    console.log(payload);

    response.status(200).send('ok');

    request({
        url: configMetadataURL,
        headers: {
            'User-Agent': productName
        }
    }, function(error, response, body) {
        var configMetadata = JSON.parse(body);
        var config = ['last 2 versions'];
        var configMetadataContent;

        if (configMetadata.content) {
            configMetadataContent = new Buffer(configMetadata.content, 'base64').toString();

            // Consider text separated by commas and linebreaks to be individual
            // options
            config = configMetadataContent.replace(/\r?\n|\r/g, ', ').split(/,\s*/);
        }

        if(eventType === 'pull_request') {
            commitsURL = payload.pull_request.commits_url;
            commentURL = payload.pull_request.review_comments_url;
            request({
                url: commitsURL,
                headers: {
                    'User-Agent': productName
                }
            }, function(error, response, body) {
                var commits = JSON.parse(body);

                commits.forEach(function(element, index) {
                    request({
                        url: element.url,
                        headers: {
                            'User-Agent': productName
                        }
                    }, function(error, response, body) {
                        var commitMeta = JSON.parse(body);
                        var commitFiles = commitMeta.files;
                        var commitSHA = commitMeta.sha;
                        parseCSS(commitFiles, config, commentURL, token, function(usageInfo) {}, commitSHA);
                    });
                });
            });
        }
    });
};

var parseCSS = function(files, config, commentURL, token, cb, sha) {
    files.forEach(function(file, index) {
        var addFeature = function(feature) {
            var diffIndex = parseDiff(feature, file);
            var comment = feature.featureData.title + ' not supported by: ' + feature.featureData.missing;
            renderComment(commentURL, file.filename, comment, diffIndex, token, sha);
        };
        if (path.extname(file.filename) === '.styl') {
            parseSource.stylus(file, config, addFeature);
        }
        if (path.extname(file.filename) === '.css') {
            var rawURL = file.raw_url;
            request({
                url: rawURL,
                headers: {
                    'User-Agent': productName
                }
            }, function(error, response, body) {
                var contents = body;
                postcss(doiuse({
                    browsers: config,
                    onFeatureUsage: addFeature
                })).process(contents, {
                    from: '/' + file.filename
                }).then(function(response) {
                });
            });
        }
    });
};

var renderComment = function(url, file, comment, position, token, sha) {
    request({
        url: url,
        method: 'POST',
        headers: {
            'User-Agent': productName,
            'Authorization': token
        },
        body: JSON.stringify({
            body: comment,
            path: file,
            commit_id: sha,
            position: position
        })
    }, function(error, response, body) {
        console.error(error);
    });
};

var parseDiff = function(feature, file) {
    return diff.lineToIndex(file.patch, feature.usage.source.start.line);
};

exports.comment = comment;
<commit_msg>Rename request module to sendRequest for clarity<commit_after>'use strict';

var doiuse = require('doiuse');
var path = require('path');
var postcss = require('postcss');
var sendRequest = require('request');
var diff = require('./diffParse');
var parseSource = require('./sourceParse');

var token = 'token ' + process.env.OAUTH_TOKEN;
var productName = 'Discord';

var comment = function(request, response) {
    var eventType = request.headers['x-github-event'];
    var payload = request.body;
    var configMetadataURL = payload.repository.contents_url.replace('{+path}', '.doiuse');
    var commitsURL, commentURL;

    // TODO: Only acknowledge pushes to the "Master" branch.
    console.log('Repo: ' + payload.repository.full_name);
    console.log('Payload:');
    console.log(payload);

    response.status(200).send('ok');

    sendRequest({
        url: configMetadataURL,
        headers: {
            'User-Agent': productName
        }
    }, function(error, response, body) {
        var configMetadata = JSON.parse(body);
        var config = ['last 2 versions'];
        var configMetadataContent;

        if (configMetadata.content) {
            configMetadataContent = new Buffer(configMetadata.content, 'base64').toString();

            // Consider text separated by commas and linebreaks to be individual
            // options
            config = configMetadataContent.replace(/\r?\n|\r/g, ', ').split(/,\s*/);
        }

        if(eventType === 'pull_request') {
            commitsURL = payload.pull_request.commits_url;
            commentURL = payload.pull_request.review_comments_url;
            sendRequest({
                url: commitsURL,
                headers: {
                    'User-Agent': productName
                }
            }, function(error, response, body) {
                var commits = JSON.parse(body);

                commits.forEach(function(element, index) {
                    sendRequest({
                        url: element.url,
                        headers: {
                            'User-Agent': productName
                        }
                    }, function(error, response, body) {
                        var commitMeta = JSON.parse(body);
                        var commitFiles = commitMeta.files;
                        var commitSHA = commitMeta.sha;
                        parseCSS(commitFiles, config, commentURL, token, function(usageInfo) {}, commitSHA);
                    });
                });
            });
        }
    });
};

var parseCSS = function(files, config, commentURL, token, cb, sha) {
    files.forEach(function(file, index) {
        var addFeature = function(feature) {
            var diffIndex = parseDiff(feature, file);
            var comment = feature.featureData.title + ' not supported by: ' + feature.featureData.missing;
            renderComment(commentURL, file.filename, comment, diffIndex, token, sha);
        };
        if (path.extname(file.filename) === '.styl') {
            parseSource.stylus(file, config, addFeature);
        }
        if (path.extname(file.filename) === '.css') {
            var rawURL = file.raw_url;
            sendRequest({
                url: rawURL,
                headers: {
                    'User-Agent': productName
                }
            }, function(error, response, body) {
                var contents = body;
                postcss(doiuse({
                    browsers: config,
                    onFeatureUsage: addFeature
                })).process(contents, {
                    from: '/' + file.filename
                }).then(function(response) {
                });
            });
        }
    });
};

var renderComment = function(url, file, comment, position, token, sha) {
    sendRequest({
        url: url,
        method: 'POST',
        headers: {
            'User-Agent': productName,
            'Authorization': token
        },
        body: JSON.stringify({
            body: comment,
            path: file,
            commit_id: sha,
            position: position
        })
    }, function(error, response, body) {
        console.error(error);
    });
};

var parseDiff = function(feature, file) {
    return diff.lineToIndex(file.patch, feature.usage.source.start.line);
};

exports.comment = comment;
<|endoftext|>


<commit_before>/*
Gradebook from Names and Scores
I worked on this challenge [by myself, with:]
This challenge took me [#] hours.
You will work with the following two variables.  The first, students, holds the names of four students.
The second, scores, holds groups of test scores.  The relative positions of elements within the two
variables match (i.e., 'Joseph' is the first element in students; his scores are the first value in scores.).
Do not alter the students and scores code.
*/

var students = ["Joseph", "Susan", "William", "Elizabeth"]

var scores = [ [80, 70, 70, 100],
               [85, 80, 90, 90],
               [75, 70, 80, 75],
               [100, 90, 95, 85] ]

// __________________________________________
// Write your code below.

// __________________________________________
// Refactored Solution

// __________________________________________
// Reflect

// __________________________________________
// Test Code:  Do not alter code below this line.

function assert(test, message, test_number) {
  if (!test) {
    console.log(test_number + "false");
    throw "ERROR: " + message;
  }
  console.log(test_number + "true");
  return true;
}

assert(
  (gradebook instanceof Object),
  "The value of gradebook should be an Object.\n",
  "1. "
)

assert(
  (gradebook["Elizabeth"] instanceof Object),
  "gradebook's Elizabeth property should be an object.",
  "2. "
)

assert(
  (gradebook.William.testScores === scores[2]),
  "William's testScores should equal the third element in scores.",
  "3. "
)

assert(
  (gradebook.addScore instanceof Function),
  "The value of gradebook's addScore property should be a Function.",
  "4. "
)

gradebook.addScore("Susan", 80)

assert(
  (gradebook.Susan.testScores.length === 5
   && gradebook.Susan.testScores[4] === 80),
  "Susan's testScores should have a new score of 80 added to the end.",
  "5. "
)

assert(
  (gradebook.getAverage instanceof Function),
  "The value of gradebook's getAverage property should be a Function.",
  "6. "
)

assert(
  (average instanceof Function),
  "The value of average should be a Function.\n",
  "7. "
)
assert(
  average([1, 2, 3]) === 2,
  "average should return the average of the elements in the array argument.\n",
  "8. "
)

assert(
  (gradebook.getAverage("Joseph") === 80),
  "gradebook's getAverage should return 80 if passed 'Joseph'.",
  "9. "
)<commit_msg>Add solution and reflection<commit_after>/*
Gradebook from Names and Scores
I worked on this challenge with: Alicia Briceland & Robin Soubry
This challenge took me [#] hours.
You will work with the following two variables.  The first, students, holds the names of four students.
The second, scores, holds groups of test scores.  The relative positions of elements within the two
variables match (i.e., 'Joseph' is the first element in students; his scores are the first value in scores.).
Do not alter the students and scores code.
*/

var students = ["Joseph", "Susan", "William", "Elizabeth"]

var scores = [ [80, 70, 70, 100],
               [85, 80, 90, 90],
               [75, 70, 80, 75],
               [100, 90, 95, 85] ]

// __________________________________________
// Write your code below.

// var gradebook = {};

// gradebook["Joseph"] = {};
// gradebook["Susan"] = {};
// gradebook["William"] = {};
// gradebook["Elizabeth"] = {};

// gradebook["Joseph"]["testScores"] = scores[0];
// gradebook["Susan"]["testScores"] = scores[1];
// gradebook["William"]["testScores"] = scores[2];
// gradebook["Elizabeth"]["testScores"] = scores[3];

// console.log(gradebook);
// // var testScores = gradebook[name]

// gradebook.addScore = function(name, score) {
//   gradebook[name]["testScores"].push(score);
// }

// var average = function (array){
//   var sum = array.reduce (function(a,b) {return a + b;});
//   var avg = sum / array.length;
//   return avg;
// }

// gradebook.getAverage = function(name){
//   return average(gradebook[name]["testScores"]);
// }

// __________________________________________
// Refactored Solution
var gradebook = {};

for (var i = 0; i < students.length; i++){
  gradebook[students[i]] = {}
}

for (var i = 0; i < students.length; i++){
  gradebook[students[i]]["testScores"] = scores[i];
}

gradebook.addScore = function(name, score) {
  gradebook[name]["testScores"].push(score);
}

var average = function (array){
  var sum = array.reduce (function(a,b) {return a + b;});
  return sum / array.length;
}

gradebook.getAverage = function(name){
  return average(gradebook[name]["testScores"]);
}

// __________________________________________
// Reflect
/*
What did you learn about adding functions to objects?
	Adding a function to an object is relatively straightforward.
	Instead of declaring a variable to equal a function, you can declare a parameter to equal that function.

How did you iterate over nested arrays in JavaScript?
	In the refactored solution, we used a for loop to iterate over the scores array and push each element to the respective student (parameter in the object).
	To access, set or push the array elements, we used the bracket notation. This notation allows to use the 'i' counter of the iteration as the index of the array at each iteration.

Were there any new methods you were able to incorporate? If so, what were they and how did they work?
	Yes, we used the reduce method. This method, just like in Ruby allows sum up all the elements in an array.
	The code however is much harder to read and interpret, but I found the Mozilla docs very useful to get a better understanding.
		https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
*/

// __________________________________________
// Test Code:  Do not alter code below this line.

function assert(test, message, test_number) {
  if (!test) {
    console.log(test_number + "false");
    throw "ERROR: " + message;
  }
  console.log(test_number + "true");
  return true;
}

assert(
  (gradebook instanceof Object),
  "The value of gradebook should be an Object.\n",
  "1. "
)

assert(
  (gradebook["Elizabeth"] instanceof Object),
  "gradebook's Elizabeth property should be an object.",
  "2. "
)

assert(
  (gradebook.William.testScores === scores[2]),
  "William's testScores should equal the third element in scores.",
  "3. "
)

assert(
  (gradebook.addScore instanceof Function),
  "The value of gradebook's addScore property should be a Function.",
  "4. "
)

gradebook.addScore("Susan", 80)

assert(
  (gradebook.Susan.testScores.length === 5
   && gradebook.Susan.testScores[4] === 80),
  "Susan's testScores should have a new score of 80 added to the end.",
  "5. "
)

assert(
  (gradebook.getAverage instanceof Function),
  "The value of gradebook's getAverage property should be a Function.",
  "6. "
)

assert(
  (average instanceof Function),
  "The value of average should be a Function.\n",
  "7. "
)
assert(
  average([1, 2, 3]) === 2,
  "average should return the average of the elements in the array argument.\n",
  "8. "
)

assert(
  (gradebook.getAverage("Joseph") === 80),
  "gradebook's getAverage should return 80 if passed 'Joseph'.",
  "9. "
)<|endoftext|>


<commit_before>/**
 * @author sunag / http://www.sunag.com.br/
 */

import {
	LinearFilter,
	Mesh,
	OrthographicCamera,
	PlaneBufferGeometry,
	RGBAFormat,
	Scene,
	Vector2,
	WebGLRenderTarget
} from '../../../../build/three.module.js';

import { NodeMaterial } from '../materials/NodeMaterial.js';
import { ScreenNode } from '../inputs/ScreenNode.js';

function NodePostProcessing( renderer, renderTarget ) {

	if ( renderTarget === undefined ) {

		var parameters = {
			minFilter: LinearFilter,
			magFilter: LinearFilter,
			format: RGBAFormat,
			stencilBuffer: false
		};

		var size = renderer.getDrawingBufferSize( new Vector2() );
		renderTarget = new WebGLRenderTarget( size.width, size.height, parameters );

	}

	this.renderer = renderer;
	this.renderTarget = renderTarget;

	this.output = new ScreenNode();
	this.material = new NodeMaterial();

	this.camera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
	this.scene = new Scene();

	this.quad = new Mesh( new PlaneBufferGeometry( 2, 2 ), this.material );
	this.quad.frustumCulled = false; // Avoid getting clipped
	this.scene.add( this.quad );

	this.needsUpdate = true;

}

NodePostProcessing.prototype = {

	constructor: NodePostProcessing,

	render: function ( scene, camera, frame ) {

		if ( this.needsUpdate ) {

			this.material.dispose();

			this.material.fragment.value = this.output;
			this.material.build();

			if ( this.material.uniforms.renderTexture ) {

				this.material.uniforms.renderTexture.value = this.renderTarget.texture;

			}

			this.needsUpdate = false;

		}

		frame.setRenderer( this.renderer )
			.setRenderTexture( this.renderTarget.texture );

		this.renderer.setRenderTarget( this.renderTarget );
		this.renderer.render( scene, camera );

		frame.updateNode( this.material );

		this.renderer.setRenderTarget( null );
		this.renderer.render( this.scene, this.camera );

	},

	setSize: function ( width, height ) {

		this.renderTarget.setSize( width, height );

		this.renderer.setSize( width, height );

	},

	copy: function ( source ) {

		this.output = source.output;

		return this;

	},

	toJSON: function ( meta ) {

		var isRootObject = ( meta === undefined || typeof meta === 'string' );

		if ( isRootObject ) {

			meta = {
				nodes: {}
			};

		}

		if ( meta && ! meta.post ) meta.post = {};

		if ( ! meta.post[ this.uuid ] ) {

			var data = {};

			data.uuid = this.uuid;
			data.type = "NodePostProcessing";

			meta.post[ this.uuid ] = data;

			if ( this.name !== "" ) data.name = this.name;

			if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;

			data.output = this.output.toJSON( meta ).uuid;

		}

		meta.post = this.uuid;

		return meta;

	}

};

export { NodePostProcessing };
<commit_msg>fix postprocessing ratio<commit_after>/**
 * @author sunag / http://www.sunag.com.br/
 */

import {
	LinearFilter,
	Mesh,
	OrthographicCamera,
	PlaneBufferGeometry,
	RGBAFormat,
	Scene,
	Vector2,
	WebGLRenderTarget
} from '../../../../build/three.module.js';

import { NodeMaterial } from '../materials/NodeMaterial.js';
import { ScreenNode } from '../inputs/ScreenNode.js';

function NodePostProcessing( renderer, renderTarget ) {

	if ( renderTarget === undefined ) {

		var parameters = {
			minFilter: LinearFilter,
			magFilter: LinearFilter,
			format: RGBAFormat,
			stencilBuffer: false
		};

		var size = renderer.getDrawingBufferSize( new Vector2() );
		renderTarget = new WebGLRenderTarget( size.width, size.height, parameters );

	}

	this.renderer = renderer;
	this.renderTarget = renderTarget;

	this.output = new ScreenNode();
	this.material = new NodeMaterial();

	this.camera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
	this.scene = new Scene();

	this.quad = new Mesh( new PlaneBufferGeometry( 2, 2 ), this.material );
	this.quad.frustumCulled = false; // Avoid getting clipped
	this.scene.add( this.quad );

	this.needsUpdate = true;

}

NodePostProcessing.prototype = {

	constructor: NodePostProcessing,

	render: function ( scene, camera, frame ) {

		if ( this.needsUpdate ) {

			this.material.dispose();

			this.material.fragment.value = this.output;
			this.material.build();

			if ( this.material.uniforms.renderTexture ) {

				this.material.uniforms.renderTexture.value = this.renderTarget.texture;

			}

			this.needsUpdate = false;

		}

		frame.setRenderer( this.renderer )
			.setRenderTexture( this.renderTarget.texture );

		this.renderer.setRenderTarget( this.renderTarget );
		this.renderer.render( scene, camera );

		frame.updateNode( this.material );

		this.renderer.setRenderTarget( null );
		this.renderer.render( this.scene, this.camera );

	},

	setPixelRatio: function ( value ) {

		this.renderer.setPixelRatio( value );

		var size = this.renderer.getSize( new Vector2() );

		this.setSize( size.width, size.height );

	},

	setSize: function ( width, height ) {

		var pixelRatio = this.renderer.getPixelRatio();

		this.renderTarget.setSize( width * pixelRatio, height * pixelRatio );

		this.renderer.setSize( width, height );

	},

	copy: function ( source ) {

		this.output = source.output;

		return this;

	},

	toJSON: function ( meta ) {

		var isRootObject = ( meta === undefined || typeof meta === 'string' );

		if ( isRootObject ) {

			meta = {
				nodes: {}
			};

		}

		if ( meta && ! meta.post ) meta.post = {};

		if ( ! meta.post[ this.uuid ] ) {

			var data = {};

			data.uuid = this.uuid;
			data.type = "NodePostProcessing";

			meta.post[ this.uuid ] = data;

			if ( this.name !== "" ) data.name = this.name;

			if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;

			data.output = this.output.toJSON( meta ).uuid;

		}

		meta.post = this.uuid;

		return meta;

	}

};

export { NodePostProcessing };
<|endoftext|>


<commit_before>var Menus = require('./menus');

var Connection = function(app, frontEndpoint) {
  this._app = app;

  // Current state
  this.frontEndpoint = frontEndpoint;
  this.backEndpoint = null;
  this.menu = null;
}

Connection.prototype.doAction = function(action) {
  // If there is a current menu, let it go/deinit
  if(this.menu !== null) {
    // De-init the menu
  }

  // If the action is a menu, init the new menu
  if(action.menu !== undefined) {
    // Init menu
    this.menu = new Menus.Basic(this._app, this.frontEndpoint, this._app.config.menus[action.menu]);
    this.menu.init(); // This will display the menu to the user and wait for an option to be selected
    return;
  }

  // More actions down here
}

Connection.prototype.init = function() {

}

Connection.prototype.deinit = function() {
  if(this.menu !== null) this.menu.deinit(); // Deinit the menu if it exists
  this.frontEndpoint.deinit(); // Deinit the front endpoint
}

module.exports = Connection;
<commit_msg>cleanup an if statement<commit_after>var Menus = require('./menus');

var Connection = function(app, frontEndpoint) {
  this._app = app;

  // Current state
  this.frontEndpoint = frontEndpoint;
  this.backEndpoint = null;
  this.menu = null;
}

Connection.prototype.doAction = function(action) {
  // If there is a current menu, let it go/deinit
  if(this.menu !== null) this.menu.deinit();

  // If the action is a menu, init the new menu
  if(action.menu !== undefined) {
    // Init menu
    this.menu = new Menus.Basic(this._app, this.frontEndpoint, this._app.config.menus[action.menu]);
    this.menu.init(); // This will display the menu to the user and wait for an option to be selected
    return;
  }

  // More actions down here
}

Connection.prototype.init = function() {

}

Connection.prototype.deinit = function() {
  if(this.menu !== null) this.menu.deinit(); // Deinit the menu if it exists
  this.frontEndpoint.deinit(); // Deinit the front endpoint
}

module.exports = Connection;
<|endoftext|>


<commit_before>'use strict';
module.exports = function() {

  const dotenv = require('dotenv').load();
  const Sequelize = require('sequelize');
  const mysql = require('mysql');

  const _sequelize = new Sequelize(process.env.DB_NAME, process.env.DB_USER, process.env.DB_PASS, {
    host: process.env.DB_HOST,
    dialect: 'mysql',
    port: process.env.DB_PORT,
    pool: {
      max: 5,
      min: 0,
      idle: 10000
    }
  });

  const _users = _sequelize.define('users', {
    userId: {
      type: Sequelize.STRING,
      primaryKey: true
    },
    email: {
      type: Sequelize.STRING
    },
    token: {
      type: Sequelize.STRING
    }
  });

  const _meals = _sequelize.define('meals', {
    mealId: {
      type: Sequelize.INTEGER,
      primaryKey: true,
      autoIncrement: false
    },
    name: {
      type: Sequelize.STRING
    },
    image: {
      type: Sequelize.STRING
    }
  });

  const _userMeals = _sequelize.define('userMeals', {
    date: {
      type: Sequelize.STRING
    },
    mealType: {
      type: Sequelize.STRING
    }
  });

  const _groceryLists = _sequelize.define('groceryLists', {
    listId: {
      type: Sequelize.UUID,
    },
  });

  const _userGroceryLists = _sequelize.define('userGroceryLists', {

  });

  const _ingredients = _sequelize.define('ingredients', {
    ingredientId: {
      type: Sequelize.UUID
    },
    name: {
      type: Sequelize.STRING
    },
    completed: {
      type: Sequelize.BOOLEAN
    }
  });

  const _intolerances = _sequelize.define('intolerances', {
    intoleranceId: {
      type: Sequelize.UUID
    },
    name: {
      type: Sequelize.STRING
    }
  });

  const _userIntolerances = _sequelize.define('userIntolerances', {
    status: {
      type: Sequelize.BOOLEAN
    }
  });

  //Relationships
  _users.belongsToMany(_meals, {
    through: {
      model: _userMeals,
      unique: false
    },
    foreignKey: 'userId',
    constraints: false
  });

  _users.belongsToMany(_groceryLists, {
    through: {
      model: _userGroceryLists,
      unique: false
    },
    foreignKey: 'userId',
    constraints: false
  });

  _users.belongsToMany(_intolerances, {
    through: {
      model: _userIntolerances,
      unique: false
    },
      foreignKey: 'userId',
      constraints: false
  });

  _meals.belongsToMany(_users, {
    through: {
      model: _userMeals,
      unique: false
    },
    foreignKey: 'mealId',
    constraints: false
  });

  _groceryLists.belongsToMany(_users, {
    through: {
      model: _userGroceryLists,
      unique: false
    },
    foreignKey: 'listId',
    constraints: false
  });

  _groceryLists.hasMany(_ingredients, {
    foreignKey: 'listId',
    constraints: false
  });

  _intolerances.belongsToMany(_users, {
    through: {
      model: _userIntolerances,
      unique: false
    },
    foreignKey: 'intoleranceId',
    constraints: false
  });

  //Syncs newly created tables and datatypes inside.
  _sequelize.sync({ force: true });

  return {
    connection: _sequelize,
    groceryLists: _groceryLists,
    userGroceryLists: _userGroceryLists,
    ingredients: _ingredients,
    meals: _meals,
    userMeals: _userMeals,
    intolerances: _intolerances,
    userIntolerances: _userIntolerances,
    users: _users,
  };

}();
<commit_msg>removed auto increment from meals<commit_after>'use strict';
module.exports = function() {

  const dotenv = require('dotenv').load();
  const Sequelize = require('sequelize');
  const mysql = require('mysql');

  const _sequelize = new Sequelize(process.env.DB_NAME, process.env.DB_USER, process.env.DB_PASS, {
    host: process.env.DB_HOST,
    dialect: 'mysql',
    port: process.env.DB_PORT,
    pool: {
      max: 5,
      min: 0,
      idle: 10000
    }
  });

  const _users = _sequelize.define('users', {
    userId: {
      type: Sequelize.STRING,
      primaryKey: true
    },
    email: {
      type: Sequelize.STRING
    },
    token: {
      type: Sequelize.STRING
    }
  });

  const _meals = _sequelize.define('meals', {
    mealId: {
      type: Sequelize.INTEGER,
      primaryKey: true
    },
    name: {
      type: Sequelize.STRING
    },
    image: {
      type: Sequelize.STRING
    }
  });

  const _userMeals = _sequelize.define('userMeals', {
    date: {
      type: Sequelize.STRING
    },
    mealType: {
      type: Sequelize.STRING
    }
  });

  const _groceryLists = _sequelize.define('groceryLists', {
    listId: {
      type: Sequelize.UUID,
    },
  });

  const _userGroceryLists = _sequelize.define('userGroceryLists', {

  });

  const _ingredients = _sequelize.define('ingredients', {
    ingredientId: {
      type: Sequelize.UUID
    },
    name: {
      type: Sequelize.STRING
    },
    completed: {
      type: Sequelize.BOOLEAN
    }
  });

  const _intolerances = _sequelize.define('intolerances', {
    intoleranceId: {
      type: Sequelize.UUID
    },
    name: {
      type: Sequelize.STRING
    }
  });

  const _userIntolerances = _sequelize.define('userIntolerances', {
    status: {
      type: Sequelize.BOOLEAN
    }
  });

  //Relationships
  _users.belongsToMany(_meals, {
    through: {
      model: _userMeals,
      unique: false
    },
    foreignKey: 'userId',
    constraints: false
  });

  _users.belongsToMany(_groceryLists, {
    through: {
      model: _userGroceryLists,
      unique: false
    },
    foreignKey: 'userId',
    constraints: false
  });

  _users.belongsToMany(_intolerances, {
    through: {
      model: _userIntolerances,
      unique: false
    },
      foreignKey: 'userId',
      constraints: false
  });

  _meals.belongsToMany(_users, {
    through: {
      model: _userMeals,
      unique: false
    },
    foreignKey: 'mealId',
    constraints: false
  });

  _groceryLists.belongsToMany(_users, {
    through: {
      model: _userGroceryLists,
      unique: false
    },
    foreignKey: 'listId',
    constraints: false
  });

  _groceryLists.hasMany(_ingredients, {
    foreignKey: 'listId',
    constraints: false
  });

  _intolerances.belongsToMany(_users, {
    through: {
      model: _userIntolerances,
      unique: false
    },
    foreignKey: 'intoleranceId',
    constraints: false
  });

  //Syncs newly created tables and datatypes inside.
  _sequelize.sync({ force: true });

  return {
    connection: _sequelize,
    groceryLists: _groceryLists,
    userGroceryLists: _userGroceryLists,
    ingredients: _ingredients,
    meals: _meals,
    userMeals: _userMeals,
    intolerances: _intolerances,
    userIntolerances: _userIntolerances,
    users: _users,
  };

}();
<|endoftext|>


<commit_before>/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import React, { Component, PropTypes } from 'react';
import emptyFunction from 'fbjs/lib/emptyFunction';
import s from './App.scss';
import Header from '../Header';
import Footer from '../Footer';

import {
  cyan500, cyan700,
  pinkA200,
  grey100, grey300, grey400, grey500,
  white, darkBlack, fullBlack,
} from 'material-ui/styles/colors';

import {fade} from 'material-ui/utils/colorManipulator';
import spacing from 'material-ui/styles/spacing';

import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import RaisedButton from 'material-ui/RaisedButton';

const muiTheme = getMuiTheme({
  palette: {
    primary1Color: '#74C2CE',
    primary2Color: cyan700,
    primary3Color: grey400,
    accent1Color: '#F2DF83',
    accent2Color: grey100,
    accent3Color: grey500,
    textColor: darkBlack,
    alternateTextColor: white,
    canvasColor: white,
    borderColor: grey300,
    disabledColor: fade(darkBlack, 0.3),
    pickerHeaderColor: cyan500,
    clockCircleColor: fade(darkBlack, 0.07),
    shadowColor: fullBlack,
  },
  appBar: {
    color: '#F2DF83',
  },
  raisedButton: {
    fontWeight: '500',
  }
});

class App extends Component {

  static propTypes = {
    context: PropTypes.shape({
      insertCss: PropTypes.func,
      onSetTitle: PropTypes.func,
      onSetMeta: PropTypes.func,
      onPageNotFound: PropTypes.func,
    }),
    children: PropTypes.element.isRequired,
    error: PropTypes.object,
  };

  static childContextTypes = {
    insertCss: PropTypes.func.isRequired,
    onSetTitle: PropTypes.func.isRequired,
    onSetMeta: PropTypes.func.isRequired,
    onPageNotFound: PropTypes.func.isRequired,
  };

  getChildContext() {
    const context = this.props.context;
    return {
      insertCss: context.insertCss || emptyFunction,
      onSetTitle: context.onSetTitle || emptyFunction,
      onSetMeta: context.onSetMeta || emptyFunction,
      onPageNotFound: context.onPageNotFound || emptyFunction,
    };
  }

  componentWillMount() {
    const { insertCss } = this.props.context;
    this.removeCss = insertCss(s);
  }

  componentWillUnmount() {
    this.removeCss();
  }

  render() {
    return !this.props.error ? (
      <MuiThemeProvider muiTheme={muiTheme}>

        {this.props.children}

      </MuiThemeProvider>
    ) : this.props.children;
  }

}

export default App;
<commit_msg>Update global style<commit_after>/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import React, { Component, PropTypes } from 'react';
import emptyFunction from 'fbjs/lib/emptyFunction';
import s from './App.scss';
import Header from '../Header';
import Footer from '../Footer';

import {
  cyan500, cyan700,
  pinkA200,
  grey100, grey300, grey400, grey500,
  white, darkBlack, fullBlack,
} from 'material-ui/styles/colors';

import {fade} from 'material-ui/utils/colorManipulator';
import spacing from 'material-ui/styles/spacing';

import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import RaisedButton from 'material-ui/RaisedButton';

const muiTheme = getMuiTheme({
  fontFamily: 'Segoe UI, \'HelveticaNeue-Light\', sans-serif',
  palette: {
    primary1Color: '#74C2CE',
    primary2Color: cyan700,
    primary3Color: grey400,
    accent1Color: '#F2DF83',
    accent2Color: grey100,
    accent3Color: grey500,
    textColor: darkBlack,
    alternateTextColor: white,
    canvasColor: white,
    borderColor: grey300,
    disabledColor: fade(darkBlack, 0.3),
    pickerHeaderColor: cyan500,
    clockCircleColor: fade(darkBlack, 0.07),
    shadowColor: fullBlack,
  },
  appBar: {
    color: '#F2DF83',
  },
  raisedButton: {
    fontWeight: '500',
  }
});

class App extends Component {

  static propTypes = {
    context: PropTypes.shape({
      insertCss: PropTypes.func,
      onSetTitle: PropTypes.func,
      onSetMeta: PropTypes.func,
      onPageNotFound: PropTypes.func,
    }),
    children: PropTypes.element.isRequired,
    error: PropTypes.object,
  };

  static childContextTypes = {
    insertCss: PropTypes.func.isRequired,
    onSetTitle: PropTypes.func.isRequired,
    onSetMeta: PropTypes.func.isRequired,
    onPageNotFound: PropTypes.func.isRequired,
  };

  getChildContext() {
    const context = this.props.context;
    return {
      insertCss: context.insertCss || emptyFunction,
      onSetTitle: context.onSetTitle || emptyFunction,
      onSetMeta: context.onSetMeta || emptyFunction,
      onPageNotFound: context.onPageNotFound || emptyFunction,
    };
  }

  componentWillMount() {
    const { insertCss } = this.props.context;
    this.removeCss = insertCss(s);
  }

  componentWillUnmount() {
    this.removeCss();
  }

  render() {
    return !this.props.error ? (
      <MuiThemeProvider muiTheme={muiTheme}>

        {this.props.children}

      </MuiThemeProvider>
    ) : this.props.children;
  }

}

export default App;
<|endoftext|>


<commit_before>import React, {PropTypes} from 'react'
import OverlayTechnologies from 'shared/components/OverlayTechnologies'

const style = {
  padding: '8px',
  borderRadius: '4px',
  backgroundColor: '#202028',
  margin: '0 15%',
  top: '16px',
  position: 'relative',
  display: 'flex',
  flexDirection: 'column',
  alignItems: 'center',
  height: 'calc(100% - 76px)',
}

const TICKscriptOverlay = ({tickscript, onClose}) => (
  <OverlayTechnologies>

Generated TICKscript

        {tickscript}

  </OverlayTechnologies>
)

const {string, func} = PropTypes

TICKscriptOverlay.propTypes = {
  tickscript: string,
  onClose: func.isRequired,
}

export default TICKscriptOverlay
<commit_msg>Tweak styles a bit<commit_after>import React, {PropTypes} from 'react'
import OverlayTechnologies from 'shared/components/OverlayTechnologies'

const style = {
  padding: '8px',
  borderRadius: '4px',
  backgroundColor: '#202028',
  margin: '0 15%',
  top: '16px',
  position: 'relative',
  display: 'flex',
  flexDirection: 'column',
  alignItems: 'center',
  height: 'calc(100% - 76px)',
}

const TICKscriptOverlay = ({tickscript, onClose}) => (
  <OverlayTechnologies>

Generated TICKscript

        {tickscript}

  </OverlayTechnologies>
)

const {string, func} = PropTypes

TICKscriptOverlay.propTypes = {
  tickscript: string,
  onClose: func.isRequired,
}

export default TICKscriptOverlay
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require jquery-ui/accordion
//= require jquery-ui/datepicker
//= require chosen-jquery
//= require magnific-popup
//= require jquery.timepicker.js
//= require ckeditor/init

var ready = function(){
  // datepicker
  $( ".datepicker" ).datepicker({dateFormat: 'yy-mm-dd'});
  // timepicker
  $( ".timepicker" ).timepicker({timeFormat: "H:i:s", scrollDefault: '00:00:00', step: 0.25});
  $( ".monthpicker" ).datepicker( {
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    dateFormat: 'yy-mm-dd',
    minDate: new Date(2014, 10, 1),
    maxDate: new Date,
    onClose: function(dateText, inst) {
        var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
        var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
        $(this).datepicker('setDate', new Date(year, month, 1));
    }
  });
  // enable chosen js
  $('.chosen-select').chosen({
    search_contains: true,
    allow_single_deselect: true,
    no_results_text: 'No results matched',
    width: '200px',
  });
  $(".chosen-select").trigger('chosen:updated');
  $(".recent-search-form-select").change(function() {
    var selected_value = this.value;
    $.each(this.children, function(){
      var form_class = '.' + this.value + '-search';
      if (selected_value == this.value){
        $(form_class).show();
      }else{
        $(form_class).hide();
      }
    });
  });

  $(".video_type").change(function(){
    if (this.value == 'ivod'){
      $('.others_field').hide();
      $('.news_field').hide();
      $('.ivod_field').show();
    } else if (this.value == 'news'){
      $('.others_field').hide();
      $('.ivod_field').hide();
      $('.news_field').show();
    } else if (this.value == 'others'){
      $('.news_field').hide();
      $('.ivod_field').hide();
      $('.others_field').show();
    }
  });
  $(".video_type").change();

  $("#accordion").accordion({
    heightStyle: "content"
  });

  $('.all_party_button').click(function(){
    $('.kmt').show();
    $('.dpp').show();
    $('.pfp').show();
    $('.nsu').show();
    $('.tsu').show();
    $('.null').show();
    $('.all_party_button').addClass('current');
    $('.kmt_party_button').removeClass('current');
    $('.dpp_party_button').removeClass('current');
    $('.pfp_party_button').removeClass('current');
    $('.nsu_party_button').removeClass('current');
    $('.tsu_party_button').removeClass('current');
    $('.null_party_button').removeClass('current');
  });
  $('.kmt_party_button').click(function(){
    $('.kmt').show();
    $('.dpp').hide();
    $('.pfp').hide();
    $('.nsu').hide();
    $('.tsu').hide();
    $('.null').hide();
    $('.all_party_button').removeClass('current');
    $('.kmt_party_button').addClass('current');
    $('.dpp_party_button').removeClass('current');
    $('.pfp_party_button').removeClass('current');
    $('.nsu_party_button').removeClass('current');
    $('.tsu_party_button').removeClass('current');
    $('.null_party_button').removeClass('current');
  });
  $('.dpp_party_button').click(function(){
    $('.kmt').hide();
    $('.dpp').show();
    $('.pfp').hide();
    $('.nsu').hide();
    $('.tsu').hide();
    $('.null').hide();
    $('.all_party_button').removeClass('current');
    $('.kmt_party_button').removeClass('current');
    $('.dpp_party_button').addClass('current');
    $('.pfp_party_button').removeClass('current');
    $('.nsu_party_button').removeClass('current');
    $('.tsu_party_button').removeClass('current');
    $('.null_party_button').removeClass('current');
  });
  $('.pfp_party_button').click(function(){
    $('.kmt').hide();
    $('.dpp').hide();
    $('.pfp').show();
    $('.nsu').hide();
    $('.tsu').hide();
    $('.null').hide();
    $('.all_party_button').removeClass('current');
    $('.kmt_party_button').removeClass('current');
    $('.dpp_party_button').removeClass('current');
    $('.pfp_party_button').addClass('current');
    $('.nsu_party_button').removeClass('current');
    $('.tsu_party_button').removeClass('current');
    $('.null_party_button').removeClass('current');
  });
  $('.nsu_party_button').click(function(){
    $('.kmt').hide();
    $('.dpp').hide();
    $('.pfp').hide();
    $('.nsu').show();
    $('.tsu').hide();
    $('.null').hide();
    $('.all_party_button').removeClass('current');
    $('.kmt_party_button').removeClass('current');
    $('.dpp_party_button').removeClass('current');
    $('.pfp_party_button').removeClass('current');
    $('.nsu_party_button').addClass('current');
    $('.tsu_party_button').removeClass('current');
    $('.null_party_button').removeClass('current');
  });
  $('.tsu_party_button').click(function(){
    $('.kmt').hide();
    $('.dpp').hide();
    $('.pfp').hide();
    $('.nsu').hide();
    $('.tsu').show();
    $('.null').hide();
    $('.all_party_button').removeClass('current');
    $('.kmt_party_button').removeClass('current');
    $('.dpp_party_button').removeClass('current');
    $('.pfp_party_button').removeClass('current');
    $('.nsu_party_button').removeClass('current');
    $('.tsu_party_button').addClass('current');
    $('.null_party_button').removeClass('current');
  });
  $('.null_party_button').click(function(){
    $('.kmt').hide();
    $('.dpp').hide();
    $('.pfp').hide();
    $('.nsu').hide();
    $('.tsu').hide();
    $('.null').show();
    $('.all_party_button').removeClass('current');
    $('.kmt_party_button').removeClass('current');
    $('.dpp_party_button').removeClass('current');
    $('.pfp_party_button').removeClass('current');
    $('.nsu_party_button').removeClass('current');
    $('.tsu_party_button').removeClass('current');
    $('.null_party_button').addClass('current');
  });

  $('.check_all_box').change(function(){
    $.each($('.published_box'), function(){
      this.checked = $('.check_all_box')[0].checked;
    });
  });
  if ($('.alert').length > 0) {
    $.magnificPopup.open({
      items: {
        src: $('.alert'), // can be a HTML string, jQuery object, or CSS selector
        type: 'inline',
        removalDelay: 500
      }
    });
  }

  $("div.text").hide();
  $(".box h3").click(function(){
    $(this).next(".text").slideToggle("slow");
  });

  $('.show-more-snippet').css({height:'100%'});
  var show_more_snippet_height = $('.show-more-snippet').height();
  if(show_more_snippet_height < 34){
    $('.show-more').hide();
  } else {
    $('.show-more-snippet').css({height:'34px'});
    $('.show-more').click(function() {
      if($('.show-more-snippet').css('height') != '34px'){
        $('.show-more-snippet').stop().animate({height: '34px'}, 200);
        $(this).text('更多...');
      }else{
        $('.show-more-snippet').stop().animate({height: show_more_snippet_height}, 400);
        $(this).text('收合...');
      }
    });
  }

  CKEDITOR.on( 'dialogDefinition', function( ev ){
    // Take the dialog name and its definition from the event
    // data.
    var dialogName = ev.data.name;
    var dialogDefinition = ev.data.definition;

    // Check if the definition is from the dialog we're
    // interested on (the Link and Image dialog).
    if ( dialogName == 'link' || dialogName == 'image'  || dialogName == 'flash' )
    {
      // remove Upload tab
      dialogDefinition.removeContents('Upload');
      dialogDefinition.removeContents('upload');
    }
  });

};

$(document).ready(ready);
$(document).on('page:load', ready);<commit_msg>add recalculate function<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require jquery-ui/accordion
//= require jquery-ui/datepicker
//= require chosen-jquery
//= require magnific-popup
//= require jquery.timepicker.js
//= require ckeditor/init

var ready = function(){
  // datepicker
  $( ".datepicker" ).datepicker({dateFormat: 'yy-mm-dd'});
  // timepicker
  $( ".timepicker" ).timepicker({timeFormat: "H:i:s", scrollDefault: '00:00:00', step: 0.25});
  $( ".monthpicker" ).datepicker( {
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    dateFormat: 'yy-mm-dd',
    minDate: new Date(2014, 10, 1),
    maxDate: new Date,
    onClose: function(dateText, inst) {
        var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
        var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
        $(this).datepicker('setDate', new Date(year, month, 1));
    }
  });
  // enable chosen js
  $('.chosen-select').chosen({
    search_contains: true,
    allow_single_deselect: true,
    no_results_text: 'No results matched',
    width: '200px',
  });
  $(".chosen-select").trigger('chosen:updated');
  $(".recent-search-form-select").change(function() {
    var selected_value = this.value;
    $.each(this.children, function(){
      var form_class = '.' + this.value + '-search';
      if (selected_value == this.value){
        $(form_class).show();
      }else{
        $(form_class).hide();
      }
    });
  });

  $(".video_type").change(function(){
    if (this.value == 'ivod'){
      $('.others_field').hide();
      $('.news_field').hide();
      $('.ivod_field').show();
    } else if (this.value == 'news'){
      $('.others_field').hide();
      $('.ivod_field').hide();
      $('.news_field').show();
    } else if (this.value == 'others'){
      $('.news_field').hide();
      $('.ivod_field').hide();
      $('.others_field').show();
    }
  });
  $(".video_type").change();

  $("#accordion").accordion({
    heightStyle: "content"
  });

  $('.all_party_button').click(function(){
    $('.kmt').show();
    $('.dpp').show();
    $('.pfp').show();
    $('.nsu').show();
    $('.tsu').show();
    $('.null').show();
    $('.all_party_button').addClass('current');
    $('.kmt_party_button').removeClass('current');
    $('.dpp_party_button').removeClass('current');
    $('.pfp_party_button').removeClass('current');
    $('.nsu_party_button').removeClass('current');
    $('.tsu_party_button').removeClass('current');
    $('.null_party_button').removeClass('current');
  });
  $('.kmt_party_button').click(function(){
    $('.kmt').show();
    $('.dpp').hide();
    $('.pfp').hide();
    $('.nsu').hide();
    $('.tsu').hide();
    $('.null').hide();
    $('.all_party_button').removeClass('current');
    $('.kmt_party_button').addClass('current');
    $('.dpp_party_button').removeClass('current');
    $('.pfp_party_button').removeClass('current');
    $('.nsu_party_button').removeClass('current');
    $('.tsu_party_button').removeClass('current');
    $('.null_party_button').removeClass('current');
  });
  $('.dpp_party_button').click(function(){
    $('.kmt').hide();
    $('.dpp').show();
    $('.pfp').hide();
    $('.nsu').hide();
    $('.tsu').hide();
    $('.null').hide();
    $('.all_party_button').removeClass('current');
    $('.kmt_party_button').removeClass('current');
    $('.dpp_party_button').addClass('current');
    $('.pfp_party_button').removeClass('current');
    $('.nsu_party_button').removeClass('current');
    $('.tsu_party_button').removeClass('current');
    $('.null_party_button').removeClass('current');
  });
  $('.pfp_party_button').click(function(){
    $('.kmt').hide();
    $('.dpp').hide();
    $('.pfp').show();
    $('.nsu').hide();
    $('.tsu').hide();
    $('.null').hide();
    $('.all_party_button').removeClass('current');
    $('.kmt_party_button').removeClass('current');
    $('.dpp_party_button').removeClass('current');
    $('.pfp_party_button').addClass('current');
    $('.nsu_party_button').removeClass('current');
    $('.tsu_party_button').removeClass('current');
    $('.null_party_button').removeClass('current');
  });
  $('.nsu_party_button').click(function(){
    $('.kmt').hide();
    $('.dpp').hide();
    $('.pfp').hide();
    $('.nsu').show();
    $('.tsu').hide();
    $('.null').hide();
    $('.all_party_button').removeClass('current');
    $('.kmt_party_button').removeClass('current');
    $('.dpp_party_button').removeClass('current');
    $('.pfp_party_button').removeClass('current');
    $('.nsu_party_button').addClass('current');
    $('.tsu_party_button').removeClass('current');
    $('.null_party_button').removeClass('current');
  });
  $('.tsu_party_button').click(function(){
    $('.kmt').hide();
    $('.dpp').hide();
    $('.pfp').hide();
    $('.nsu').hide();
    $('.tsu').show();
    $('.null').hide();
    $('.all_party_button').removeClass('current');
    $('.kmt_party_button').removeClass('current');
    $('.dpp_party_button').removeClass('current');
    $('.pfp_party_button').removeClass('current');
    $('.nsu_party_button').removeClass('current');
    $('.tsu_party_button').addClass('current');
    $('.null_party_button').removeClass('current');
  });
  $('.null_party_button').click(function(){
    $('.kmt').hide();
    $('.dpp').hide();
    $('.pfp').hide();
    $('.nsu').hide();
    $('.tsu').hide();
    $('.null').show();
    $('.all_party_button').removeClass('current');
    $('.kmt_party_button').removeClass('current');
    $('.dpp_party_button').removeClass('current');
    $('.pfp_party_button').removeClass('current');
    $('.nsu_party_button').removeClass('current');
    $('.tsu_party_button').removeClass('current');
    $('.null_party_button').addClass('current');
  });

  $('.check_all_box').change(function(){
    $.each($('.published_box'), function(){
      this.checked = $('.check_all_box')[0].checked;
    });
  });
  if ($('.alert').length > 0) {
    $.magnificPopup.open({
      items: {
        src: $('.alert'), // can be a HTML string, jQuery object, or CSS selector
        type: 'inline',
        removalDelay: 500
      }
    });
  }

  $("div.text").hide();
  $(".box h3").click(function(){
    $(this).next(".text").slideToggle("slow");
  });

  $('.show-more-snippet').css({height:'100%'});
  var show_more_snippet_height = $('.show-more-snippet').height();
  if(show_more_snippet_height < 34){
    $('.show-more').hide();
  } else {
    $('.show-more-snippet').css({height:'34px'});
    $('.show-more').click(function() {
      if($('.show-more-snippet').css('height') != '34px'){
        $('.show-more-snippet').stop().animate({height: '34px'}, 200);
        $(this).text('更多...');
      }else{
        // re-calculate it
        $('.show-more-snippet').css({height:'100%'});
        var show_more_snippet_height = $('.show-more-snippet').height();
        $('.show-more-snippet').css({height:'34px'});
        $('.show-more-snippet').stop().animate({height: show_more_snippet_height}, 400);
        $(this).text('收合...');
      }
    });
  }

  CKEDITOR.on( 'dialogDefinition', function( ev ){
    // Take the dialog name and its definition from the event
    // data.
    var dialogName = ev.data.name;
    var dialogDefinition = ev.data.definition;

    // Check if the definition is from the dialog we're
    // interested on (the Link and Image dialog).
    if ( dialogName == 'link' || dialogName == 'image'  || dialogName == 'flash' )
    {
      // remove Upload tab
      dialogDefinition.removeContents('Upload');
      dialogDefinition.removeContents('upload');
    }
  });

};

$(document).ready(ready);
$(document).on('page:load', ready);<|endoftext|>


<commit_before>const Boom = require('boom');
const bookshelf = require('../../bookshelf');

module.exports = (server, ValidationError) => async (value, options) => {
  const tokenQuery = bookshelf.model('email_token').where({token: value});
  const token = await tokenQuery.fetch();
  const userQuery = bookshelf.model('user').where({id: token.get('user_id')})
  const user = await userQuery.fetch();
  if (!user.get('pending_email_lower')) {
    // Email change has been canceled
    const badEmailToken = new ValidationError('That email token is no longer good');
    throw badEmailToken;
  }
  return value
}

module.exports['@singleton'] = true;
module.exports['@require'] = ['server', 'validator/validation-error'];
<commit_msg>Change where badEmailToken error is declared<commit_after>const Boom = require('boom');
const bookshelf = require('../../bookshelf');

module.exports = (server, ValidationError) => async (value, options) => {
  const tokenQuery = bookshelf.model('email_token').where({token: value});
  const token = await tokenQuery.fetch();
  const userQuery = bookshelf.model('user').where({id: token.get('user_id')})
  const user = await userQuery.fetch();
  const badEmailToken = new ValidationError('That email token is no longer good');
  if (!user.get('pending_email_lower') || !user.get('pending_email')) {
    // Email change has been canceled
    throw badEmailToken;
  }
  return value
}

module.exports['@singleton'] = true;
module.exports['@require'] = ['server', 'validator/validation-error'];
<|endoftext|>