<commit_before>"use strict";function Lightbox(){function t(){return window.innerHeight||document.documentElement.offsetHeight}function e(){return window.innerWidth||document.documentElement.offsetWidth}function n(t,e,n,o){t.addEventListener?t.addEventListener(e,n,o||!1):t.attachEvent&&t.attachEvent("on"+e,n)}function o(t,e){return t&&e?new RegExp("(^|\\s)"+e+"(\\s|$)").test(t.className):void 0}function i(t,e){return t&&e?(t.className=t.className.replace(new RegExp("(?:^|\\s)"+e+"(?!\\S)"),""),t):void 0}function a(t,e){return t&&e?(o(t,e)||(t.className+=" "+e),t):void 0}function r(t){return"undefined"!=typeof t}function s(t,e){if(!t||!r(t))return!1;var n;return t.getAttribute?n=t.getAttribute(e):t.getAttributeNode&&(n=t.getAttributeNode(e).value),r(n)&&""!==n?n:!1}function l(t,e){if(!t||!r(t))return!1;var n;return t.getAttribute?n=t.getAttribute(e):t.getAttributeNode&&(n=t.getAttributeNode(e).value),"string"==typeof n}function p(t){n(t,"click",function(e){W=s(t,"data-jslghtbx-group")||!1,M=t,v(t,!1,!1,!1)},!1)}function g(t){t.stopPropagation?t.stopPropagation():t.returnValue=!1}function c(t){for(var e=[],n=0;n<k.thumbnails.length;n++)s(k.thumbnails[n],"data-jslghtbx-group")===t&&e.push(k.thumbnails[n]);return e}function m(t,e){for(var n=c(e),o=0;o<n.length;o++)if(s(t,"src")===s(n[o],"src")&&s(t,"data-jslghtbx")===s(n[o],"data-jslghtbx"))return o}function d(){if(W){var t=new Image,e=new Image,n=m(M,W);n===L.length-1?(t.src=L[L.length-1].src,e.src=L[0].src):0===n?(t.src=L[L.length-1].src,e.src=L[1].src):(t.src=L[n-1].src,e.src=L[n+1].src)}}function u(){if(!H){f();var t=function(){if(a(k.box,"jslghtbx-loading"),!O&&"number"==typeof k.opt.loadingAnimation){var t=0;w=setInterval(function(){a(V[t],"jslghtbx-active"),setTimeout(function(){i(V[t],"jslghtbx-active")},k.opt.loadingAnimation),t=t>=V.length?0:t+=1},k.opt.loadingAnimation)}};A=setTimeout(t,500)}}function f(){if(!H&&(i(k.box,"jslghtbx-loading"),!O&&"string"!=typeof k.opt.loadingAnimation&&k.opt.loadingAnimation)){clearInterval(w);for(var t=0;t<V.length;t++)i(V[t],"jslghtbx-active")}}function h(){if(!P){if(P=document.createElement("span"),a(P,"jslghtbx-next"),k.opt.nextImg){var t=document.createElement("img");t.setAttribute("src",k.opt.nextImg),P.appendChild(t)}else a(P,"jslghtbx-no-img");n(P,"click",function(t){g(t),k.next()},!1),k.box.appendChild(P)}if(a(P,"jslghtbx-active"),!R){if(R=document.createElement("span"),a(R,"jslghtbx-prev"),k.opt.prevImg){var e=document.createElement("img");e.setAttribute("src",k.opt.prevImg),R.appendChild(e)}else a(R,"jslghtbx-no-img");n(R,"click",function(t){g(t),k.prev()},!1),k.box.appendChild(R)}a(R,"jslghtbx-active")}function b(){if(k.opt.responsive&&P&&R){var e=t()/2-P.offsetHeight/2;P.style.top=e+"px",R.style.top=e+"px"}}function x(t){function e(t){return"boolean"==typeof t?t:!0}if(t||(t={}),k.opt={boxId:t.boxId||!1,controls:e(t.controls),dimensions:e(t.dimensions),captions:e(t.captions),prevImg:"string"==typeof t.prevImg?t.prevImg:!1,nextImg:"string"==typeof t.nextImg?t.nextImg:!1,hideCloseBtn:t.hideCloseBtn||!1,closeOnClick:"boolean"==typeof t.closeOnClick?t.closeOnClick:!0,loadingAnimation:void 0===t.loadingAnimation?!0:t.loadingAnimation,animElCount:t.animElCount||4,preload:e(t.preload),carousel:e(t.carousel),animation:"number"==typeof t.animation||t.animation===!1?t.animation:400,nextOnClick:e(t.nextOnClick),responsive:e(t.responsive),maxImgSize:t.maxImgSize||.8,keyControls:e(t.keyControls),hideOverflow:t.hideOverflow||!0,onopen:t.onopen||!1,onclose:t.onclose||!1,onload:t.onload||!1,onresize:t.onresize||!1,onloaderror:t.onloaderror||!1},k.opt.boxId)k.box=document.getElementById(k.opt);else if(!k.box&&!document.getElementById("jslghtbx")){var o=document.createElement("div");o.setAttribute("id","jslghtbx"),o.setAttribute("class","jslghtbx"),k.box=o,T.appendChild(k.box)}if(k.box.innerHTML=z,H&&a(k.box,"jslghtbx-ie8"),k.wrapper=document.getElementById("jslghtbx-contentwrapper"),!k.opt.hideCloseBtn){var r=document.createElement("span");r.setAttribute("id","jslghtbx-close"),r.setAttribute("class","jslghtbx-close"),r.innerHTML="X",k.box.appendChild(r),n(r,"click",function(t){g(t),k.close()},!1)}if(!H&&k.opt.closeOnClick&&n(k.box,"click",function(t){k.close()},!1),"string"==typeof k.opt.loadingAnimation)j=document.createElement("img"),j.setAttribute("src",k.opt.loadingAnimation),a(j,"jslghtbx-loading-animation"),k.box.appendChild(j);else if(k.opt.loadingAnimation){k.opt.loadingAnimation="number"==typeof k.opt.loadingAnimation?k.opt.loadingAnimation:200,j=document.createElement("div"),a(j,"jslghtbx-loading-animation");for(var s=0;s<k.opt.animElCount;)V.push(j.appendChild(document.createElement("span"))),s++;k.box.appendChild(j)}k.opt.responsive?(n(window,"resize",function(t){k.resize()},!1),a(k.box,"jslghtbx-nooverflow")):i(k.box,"jslghtbx-nooverflow"),k.opt.keyControls&&n(document,"keydown",function(t){S&&(g(t),39===t.keyCode?k.next():37===t.keyCode?k.prev():27===t.keyCode&&k.close())},!1)}function v(t,e,i,l){if(!t&&!e)return!1;W=e||W||s(t,"data-jslghtbx-group"),W&&(L=c(W),"boolean"!=typeof t||t||(t=L[0])),B.img=new Image,M=t;var p;p="string"==typeof t?t:s(t,"data-jslghtbx")?s(t,"data-jslghtbx"):s(t,"src"),N=!1,S||("number"==typeof k.opt.animation&&a(B.img,"jslghtbx-animate-transition jslghtbx-animate-init"),S=!0,k.opt.onopen&&k.opt.onopen()),k.opt&&r(k.opt.hideOverflow)&&!k.opt.hideOverflow||T.setAttribute("style","overflow: hidden"),k.box.setAttribute("style","padding-top: 0"),k.wrapper.innerHTML="",k.wrapper.appendChild(B.img),k.opt.animation&&a(k.wrapper,"jslghtbx-animate");var m=s(t,"data-jslghtbx-caption");if(m&&k.opt.captions){var x=document.createElement("p");x.setAttribute("class","jslghtbx-caption"),x.innerHTML=m,k.wrapper.appendChild(x)}a(k.box,"jslghtbx-active"),H&&a(k.wrapper,"jslghtbx-active"),k.opt.controls&&L.length>1&&(h(),b()),B.img.onerror=function(){k.opt.onloaderror&&k.opt.onloaderror(l)},B.img.onload=function(){if(B.originalWidth=this.naturalWidth||this.width,B.originalHeight=this.naturalHeight||this.height,H||O){var t=new Image;t.setAttribute("src",p),B.originalWidth=t.width,B.originalHeight=t.height}var e=setInterval(function(){o(k.box,"jslghtbx-active")&&(a(k.wrapper,"jslghtbx-wrapper-active"),"number"==typeof k.opt.animation&&a(B.img,"jslghtbx-animate-transition"),i&&i(),f(),clearTimeout(A),k.opt.preload&&d(),k.opt.nextOnClick&&(a(B.img,"jslghtbx-next-on-click"),n(B.img,"click",function(t){g(t),k.next()},!1)),k.opt.onload&&k.opt.onload(l),clearInterval(e),k.resize())},10)},B.img.setAttribute("src",p),u()}var j,w,A,y,C,I,E,k=this,H=!1,O=!1,T=document.getElementsByTagName("body")[0],z='

',N=!1,W=!1,M=!1,B={},L=[],S=!1,V=[],P=!1,R=!1;k.opt={},k.box=!1,k.wrapper=!1,k.thumbnails=[],k.load=function(t){navigator.appVersion.indexOf("MSIE 8")>0&&(H=!0),navigator.appVersion.indexOf("MSIE 9")>0&&(O=!0),x(t);for(var e=document.getElementsByTagName("img"),n=0;n<e.length;n++)l(e[n],"data-jslghtbx")&&(k.thumbnails.push(e[n]),p(e[n]))},k.open=function(t,e){t&&e&&(e=!1),v(t,e,!1,!1)},k.resize=function(){if(B.img){y=e(),C=t();var n=k.box.offsetWidth,o=k.box.offsetHeight;!N&&B.img&&B.img.offsetWidth&&B.img.offsetHeight&&(N=B.img.offsetWidth/B.img.offsetHeight),Math.floor(n/N)>o?(I=o*N,E=o):(I=n,E=n/N),I=Math.floor(I*k.opt.maxImgSize),E=Math.floor(E*k.opt.maxImgSize),(k.opt.dimensions&&E>B.originalHeight||k.opt.dimensions&&I>B.originalWidth)&&(E=B.originalHeight,I=B.originalWidth),B.img.setAttribute("width",I),B.img.setAttribute("height",E),B.img.setAttribute("style","margin-top:"+(t()-E)/2+"px"),setTimeout(b,200),k.opt.onresize&&k.opt.onresize()}},k.next=function(){if(W){var t=m(M,W)+1;if(L[t])M=L[t];else{if(!k.opt.carousel)return;M=L[0]}"number"==typeof k.opt.animation?(i(B.img,"jslghtbx-animating-next"),setTimeout(function(){var t=function(){setTimeout(function(){a(B.img,"jslghtbx-animating-next")},k.opt.animation/2)};v(M,!1,t,"next")},k.opt.animation/2)):v(M,!1,!1,"next")}},k.prev=function(){if(W){var t=m(M,W)-1;if(L[t])M=L[t];else{if(!k.opt.carousel)return;M=L[L.length-1]}"number"==typeof k.opt.animation?(i(B.img,"jslghtbx-animating-prev"),setTimeout(function(){var t=function(){setTimeout(function(){a(B.img,"jslghtbx-animating-next")},k.opt.animation/2)};v(M,!1,t,"prev")},k.opt.animation/2)):v(M,!1,!1,"prev")}},k.close=function(){W=!1,M=!1,B={},L=[],S=!1,i(k.box,"jslghtbx-active"),i(k.wrapper,"jslghtbx-wrapper-active"),i(P,"jslghtbx-active"),i(R,"jslghtbx-active"),k.box.setAttribute("style","padding-top: 0px"),f(),H&&k.box.setAttribute("style","display: none"),k.opt&&r(k.opt.hideOverflow)&&!k.opt.hideOverflow||T.setAttribute("style","overflow: auto"),k.opt.onclose&&k.opt.onclose()}}<commit_msg>#21 -minified JS<commit_after>"use strict";function Lightbox(){function t(){return window.innerHeight||document.documentElement.offsetHeight}function e(){return window.innerWidth||document.documentElement.offsetWidth}function n(t,e,n,o){t.addEventListener?t.addEventListener(e,n,o||!1):t.attachEvent&&t.attachEvent("on"+e,n)}function o(t,e){return t&&e?new RegExp("(^|\\s)"+e+"(\\s|$)").test(t.className):void 0}function i(t,e){return t&&e?(t.className=t.className.replace(new RegExp("(?:^|\\s)"+e+"(?!\\S)"),""),t):void 0}function a(t,e){return t&&e?(o(t,e)||(t.className+=" "+e),t):void 0}function r(t){return"undefined"!=typeof t}function s(t,e){if(!t||!r(t))return!1;var n;return t.getAttribute?n=t.getAttribute(e):t.getAttributeNode&&(n=t.getAttributeNode(e).value),r(n)&&""!==n?n:!1}function l(t,e){if(!t||!r(t))return!1;var n;return t.getAttribute?n=t.getAttribute(e):t.getAttributeNode&&(n=t.getAttributeNode(e).value),"string"==typeof n}function p(t){n(t,"click",function(){W=s(t,"data-jslghtbx-group")||!1,M=t,v(t,!1,!1,!1)},!1)}function g(t){t.stopPropagation?t.stopPropagation():t.returnValue=!1}function c(t){for(var e=[],n=0;n<k.thumbnails.length;n++)s(k.thumbnails[n],"data-jslghtbx-group")===t&&e.push(k.thumbnails[n]);return e}function m(t,e){for(var n=c(e),o=0;o<n.length;o++)if(s(t,"src")===s(n[o],"src")&&s(t,"data-jslghtbx")===s(n[o],"data-jslghtbx"))return o}function d(){if(W){var t=new Image,e=new Image,n=m(M,W);n===L.length-1?(t.src=L[L.length-1].src,e.src=L[0].src):0===n?(t.src=L[L.length-1].src,e.src=L[1].src):(t.src=L[n-1].src,e.src=L[n+1].src)}}function u(){if(!H){f();var t=function(){if(a(k.box,"jslghtbx-loading"),!O&&"number"==typeof k.opt.loadingAnimation){var t=0;w=setInterval(function(){a(V[t],"jslghtbx-active"),setTimeout(function(){i(V[t],"jslghtbx-active")},k.opt.loadingAnimation),t=t>=V.length?0:t+=1},k.opt.loadingAnimation)}};A=setTimeout(t,500)}}function f(){if(!H&&(i(k.box,"jslghtbx-loading"),!O&&"string"!=typeof k.opt.loadingAnimation&&k.opt.loadingAnimation)){clearInterval(w);for(var t=0;t<V.length;t++)i(V[t],"jslghtbx-active")}}function h(){if(!P){if(P=document.createElement("span"),a(P,"jslghtbx-next"),k.opt.nextImg){var t=document.createElement("img");t.setAttribute("src",k.opt.nextImg),P.appendChild(t)}else a(P,"jslghtbx-no-img");n(P,"click",function(t){g(t),k.next()},!1),k.box.appendChild(P)}if(a(P,"jslghtbx-active"),!R){if(R=document.createElement("span"),a(R,"jslghtbx-prev"),k.opt.prevImg){var e=document.createElement("img");e.setAttribute("src",k.opt.prevImg),R.appendChild(e)}else a(R,"jslghtbx-no-img");n(R,"click",function(t){g(t),k.prev()},!1),k.box.appendChild(R)}a(R,"jslghtbx-active")}function b(){if(k.opt.responsive&&P&&R){var e=t()/2-P.offsetHeight/2;P.style.top=e+"px",R.style.top=e+"px"}}function x(t){function e(t){return"boolean"==typeof t?t:!0}if(t||(t={}),k.opt={boxId:t.boxId||!1,controls:e(t.controls),dimensions:e(t.dimensions),captions:e(t.captions),prevImg:"string"==typeof t.prevImg?t.prevImg:!1,nextImg:"string"==typeof t.nextImg?t.nextImg:!1,hideCloseBtn:t.hideCloseBtn||!1,closeOnClick:"boolean"==typeof t.closeOnClick?t.closeOnClick:!0,loadingAnimation:void 0===t.loadingAnimation?!0:t.loadingAnimation,animElCount:t.animElCount||4,preload:e(t.preload),carousel:e(t.carousel),animation:"number"==typeof t.animation||t.animation===!1?t.animation:400,nextOnClick:e(t.nextOnClick),responsive:e(t.responsive),maxImgSize:t.maxImgSize||.8,keyControls:e(t.keyControls),hideOverflow:t.hideOverflow||!0,onopen:t.onopen||!1,onclose:t.onclose||!1,onload:t.onload||!1,onresize:t.onresize||!1,onloaderror:t.onloaderror||!1},k.opt.boxId)k.box=document.getElementById(k.opt);else if(!k.box&&!document.getElementById("jslghtbx")){var o=document.createElement("div");o.setAttribute("id","jslghtbx"),o.setAttribute("class","jslghtbx"),k.box=o,T.appendChild(k.box)}if(k.box.innerHTML=z,H&&a(k.box,"jslghtbx-ie8"),k.wrapper=document.getElementById("jslghtbx-contentwrapper"),!k.opt.hideCloseBtn){var r=document.createElement("span");r.setAttribute("id","jslghtbx-close"),r.setAttribute("class","jslghtbx-close"),r.innerHTML="X",k.box.appendChild(r),n(r,"click",function(t){g(t),k.close()},!1)}if(!H&&k.opt.closeOnClick&&n(k.box,"click",function(){k.close()},!1),"string"==typeof k.opt.loadingAnimation)j=document.createElement("img"),j.setAttribute("src",k.opt.loadingAnimation),a(j,"jslghtbx-loading-animation"),k.box.appendChild(j);else if(k.opt.loadingAnimation){k.opt.loadingAnimation="number"==typeof k.opt.loadingAnimation?k.opt.loadingAnimation:200,j=document.createElement("div"),a(j,"jslghtbx-loading-animation");for(var s=0;s<k.opt.animElCount;)V.push(j.appendChild(document.createElement("span"))),s++;k.box.appendChild(j)}k.opt.responsive?(n(window,"resize",function(){k.resize()},!1),a(k.box,"jslghtbx-nooverflow")):i(k.box,"jslghtbx-nooverflow"),k.opt.keyControls&&n(document,"keydown",function(t){S&&(g(t),39===t.keyCode?k.next():37===t.keyCode?k.prev():27===t.keyCode&&k.close())},!1)}function v(t,e,i,l){if(!t&&!e)return!1;W=e||W||s(t,"data-jslghtbx-group"),W&&(L=c(W),"boolean"!=typeof t||t||(t=L[0])),B.img=new Image,M=t;var p;p="string"==typeof t?t:s(t,"data-jslghtbx")?s(t,"data-jslghtbx"):s(t,"src"),N=!1,S||("number"==typeof k.opt.animation&&a(B.img,"jslghtbx-animate-transition jslghtbx-animate-init"),S=!0,k.opt.onopen&&k.opt.onopen()),k.opt&&r(k.opt.hideOverflow)&&!k.opt.hideOverflow||T.setAttribute("style","overflow: hidden"),k.box.setAttribute("style","padding-top: 0"),k.wrapper.innerHTML="",k.wrapper.appendChild(B.img),k.opt.animation&&a(k.wrapper,"jslghtbx-animate");var m=s(t,"data-jslghtbx-caption");if(m&&k.opt.captions){var x=document.createElement("p");x.setAttribute("class","jslghtbx-caption"),x.innerHTML=m,k.wrapper.appendChild(x)}a(k.box,"jslghtbx-active"),H&&a(k.wrapper,"jslghtbx-active"),k.opt.controls&&L.length>1&&(h(),b()),B.img.onerror=function(){k.opt.onloaderror&&k.opt.onloaderror(l)},B.img.onload=function(){if(B.originalWidth=this.naturalWidth||this.width,B.originalHeight=this.naturalHeight||this.height,H||O){var t=new Image;t.setAttribute("src",p),B.originalWidth=t.width,B.originalHeight=t.height}var e=setInterval(function(){o(k.box,"jslghtbx-active")&&(a(k.wrapper,"jslghtbx-wrapper-active"),"number"==typeof k.opt.animation&&a(B.img,"jslghtbx-animate-transition"),i&&i(),f(),clearTimeout(A),k.opt.preload&&d(),k.opt.nextOnClick&&(a(B.img,"jslghtbx-next-on-click"),n(B.img,"click",function(t){g(t),k.next()},!1)),k.opt.onload&&k.opt.onload(l),clearInterval(e),k.resize())},10)},B.img.setAttribute("src",p),u()}var j,w,A,y,C,I,E,k=this,H=!1,O=!1,T=document.getElementsByTagName("body")[0],z='

',N=!1,W=!1,M=!1,B={},L=[],S=!1,V=[],P=!1,R=!1;k.opt={},k.box=!1,k.wrapper=!1,k.thumbnails=[],k.load=function(t){navigator.appVersion.indexOf("MSIE 8")>0&&(H=!0),navigator.appVersion.indexOf("MSIE 9")>0&&(O=!0),x(t);for(var e=document.getElementsByTagName("img"),n=0;n<e.length;n++)l(e[n],"data-jslghtbx")&&(k.thumbnails.push(e[n]),p(e[n]))},k.open=function(t,e){t&&e&&(e=!1),v(t,e,!1,!1)},k.resize=function(){if(B.img){y=e(),C=t();var n=k.box.offsetWidth,o=k.box.offsetHeight;!N&&B.img&&B.img.offsetWidth&&B.img.offsetHeight&&(N=B.img.offsetWidth/B.img.offsetHeight),Math.floor(n/N)>o?(I=o*N,E=o):(I=n,E=n/N),I=Math.floor(I*k.opt.maxImgSize),E=Math.floor(E*k.opt.maxImgSize),(k.opt.dimensions&&E>B.originalHeight||k.opt.dimensions&&I>B.originalWidth)&&(E=B.originalHeight,I=B.originalWidth),B.img.setAttribute("width",I),B.img.setAttribute("height",E),B.img.setAttribute("style","margin-top:"+(t()-E)/2+"px"),setTimeout(b,200),k.opt.onresize&&k.opt.onresize()}},k.next=function(){if(W){var t=m(M,W)+1;if(L[t])M=L[t];else{if(!k.opt.carousel)return;M=L[0]}"number"==typeof k.opt.animation?(i(B.img,"jslghtbx-animating-next"),setTimeout(function(){var t=function(){setTimeout(function(){a(B.img,"jslghtbx-animating-next")},k.opt.animation/2)};v(M,!1,t,"next")},k.opt.animation/2)):v(M,!1,!1,"next")}},k.prev=function(){if(W){var t=m(M,W)-1;if(L[t])M=L[t];else{if(!k.opt.carousel)return;M=L[L.length-1]}"number"==typeof k.opt.animation?(i(B.img,"jslghtbx-animating-prev"),setTimeout(function(){var t=function(){setTimeout(function(){a(B.img,"jslghtbx-animating-next")},k.opt.animation/2)};v(M,!1,t,"prev")},k.opt.animation/2)):v(M,!1,!1,"prev")}},k.close=function(){W=!1,M=!1,B={},L=[],S=!1,i(k.box,"jslghtbx-active"),i(k.wrapper,"jslghtbx-wrapper-active"),i(P,"jslghtbx-active"),i(R,"jslghtbx-active"),k.box.setAttribute("style","padding-top: 0px"),f(),H&&k.box.setAttribute("style","display: none"),k.opt&&r(k.opt.hideOverflow)&&!k.opt.hideOverflow||T.setAttribute("style","overflow: auto"),k.opt.onclose&&k.opt.onclose()}}<|endoftext|>


<commit_before>var url = require('url');
var path = require('path');
var config = require('../config');
var request = require('request');

module.exports = function (params, callback) {
  var logger = require('../logger')(path.join(config.root, 'log/' + params.owner + '/' + params.name + '.log'), 'version');
  logger.info('即将写入的数据: ' + JSON.stringify(params));

  var opt = {
    method: 'POST',
    url: url.resolve(config.vermgr.url, 'repos/' + params.name),
    form: {
      owner: params.owner,
      version: params.version,
      url: params.url
    },
    headers: {
      Authorization: config.vermgr.authorization
    }
  };

  logger.trace('请求地址: ' + opt.url);

  request(opt, function(err, res, body) {
    if (!err && res.statusCode == 200) {
      var data = JSON.parse(body);

      logger.info('写入版本到数据库成功');
      logger.info(JSON.stringify(data));
    } else {
      logger.fatal('写入版本到数据库失败');
      logger.info('status code: ' + res.statusCode);
      logger.info('response body: ' + body);
      logger.info('错误信息: ' + err.message);
    }

    callback();
  });
};
<commit_msg>fix bug<commit_after>var url = require('url');
var path = require('path');
var config = require('../config');
var request = require('request');

module.exports = function (params, callback) {
  var logger = require('../logger')(path.resolve(config.root, './log/' + params.owner + '/' + params.name + '.log'), 'version');
  logger.info('即将写入的数据: ' + JSON.stringify(params));

  var opt = {
    method: 'POST',
    url: url.resolve(config.vermgr.url, 'repos/' + params.name),
    form: {
      owner: params.owner,
      version: params.version,
      url: params.url
    },
    headers: {
      Authorization: config.vermgr.authorization
    }
  };

  logger.trace('请求地址: ' + opt.url);

  request(opt, function(err, res, body) {
    if (!err && res.statusCode == 200) {
      var data = JSON.parse(body);

      logger.info('写入版本到数据库成功');
      logger.info(JSON.stringify(data));
    } else {
      logger.fatal('写入版本到数据库失败');
      logger.info('status code: ' + res.statusCode);
      logger.info('response body: ' + body);
      logger.info('错误信息: ' + err.message);
    }

    callback();
  });
};
<|endoftext|>


<commit_before>'use strict'

var fs = require('fs')
var Path = require('path')

var Log = require(Path.join(__base, 'src/worker/log.js'))
var LogWorker = new Log({
  module: 'Torrent'
})
var Client = require(Path.join(__base, 'src/worker/client.js'))

/**
 * Torrent manager.
 * @constructor
*/
function Torrent () {
  var self = this
  this.client = {}

  this.dowloader = {}
  this.waitList = []

  setInterval(function () {
    self.startPointTorrent(self)
  }, 30000)
}

/**
 * Start downloadind torrent.
 * @param {string} url - Url / magnet of the torrent.
*/
Torrent.prototype.start = function (url) {
  var self = this
  // evite de lancer deux fois le meme torrent
  if (self.client[url] == null) {
    // Si trop de torrent en cours
    if (Object.keys(self.client).length < __config.torrent.max) {
      if (self.client[url] == null) {
        self.client[url] = {count: 1}
      } else {
        self.client[url].count++
      }

      if (self.client[url].count > __config.client.maxTry) {
        return -1
      }
      var c = new Client()
      c.download(url, function () {})

      c.on('start', function (hash) {
        if (self.client[url]) {
          self.client[url].hash = hash
        }
      })

      c.on('download', function (infos) {
        if (self.client[url]) {
          self.client[url].infos = infos
        }
      })

      c.on('done', function (err, hash, name) {
        if (self.client[url]) {
          if (err) {
            LogWorker.error('Fail downloading: ' + url)
            return
          }
          self.client[url].peer.stop()
          // Deplace les fichies
          LogWorker.info(Path.join(__config.torrent.downloads, name) + ' ' + Path.join(__config.directory.path, name))
          fs.renameSync(Path.join(__base, __config.torrent.downloads, name), Path.join(__base, __config.directory.path, name))
          // Defini l'owner
          if (self.dowloader[url]) {
            self.Directory.setOwner(name, self.dowloader[url])
          }
          delete self.client[url]
          // Relance un torrent si il y en a en attente
          if (self.waitList.length > 0) {
            LogWorker.info('Start torrent into waitList (left: ' + (self.waitList.length - 1) + ')')
            self.start(self.waitList.shift())
          }
        }
      })

      self.client[url].peer = c
    } else {
      LogWorker.warning('Too much client. Adding torrent to the waitlist.')
      // On push dans la liste d'attente
      if (self.waitList.indexOf(url) === -1) {
        self.waitList.push(url)
      }
    }
  } else {
    LogWorker.warning('Torrent is already downloading.')
  }
}

/**
 * Stop and remove a torrent.
 * @param {string} hash - Torrent to remove Hash.
*/
Torrent.prototype.remove = function (hash) {
  var url = this.getUrlFromHash(hash)
  if (url && this.client[url]) {
    this.client[url].peer.stop()
    delete this.client[url]
  }
}

/**
 * Get torrent url from hash.
 * @param {string} hash - Torrent Hash.
 * @return {string} - Torrent turl.
*/
Torrent.prototype.getUrlFromHash = function (hash) {
  for (var key in this.client) {
    if (this.client[key].hash === hash) {
      return key
    }
  }
  return null
}

/**
 * Start torrent into configured torrent file.
 * @param {object} self - Torrent instance.
*/
Torrent.prototype.startPointTorrent = function (self) {
  var data = fs.readFileSync(Path.join(__base, __config.torrent.scanTorrent), 'utf-8')
  var torrents = data.split('\n')
  fs.writeFileSync(Path.join(__base, __config.torrent.scanTorrent), '', 'utf-8')
  torrents.forEach(function (element) {
    if (element !== '') {
      self.start(element)
    }
  })
}

/**
 * Get infos about all current clients.
 * @return {object} - All torrent infos.
*/
Torrent.prototype.getInfo = function () {
  var torrents = {}
  for (var key in this.client) {
    var t = this.client[key].infos
    if (t) {
      torrents[t.hash] = t
    }
  }
  return torrents
}

/**
 * Define who download a torrent.
 * @param {string} user - User who download the torrent.
 * @param {string} url - Torrent url.
*/
Torrent.prototype.setDownloader = function (user, url) {
  this.dowloader[url] = user
}
module.exports = new Torrent()
<commit_msg>improve torrent async<commit_after>'use strict'

var fs = require('fs')
var Path = require('path')

var Log = require(Path.join(__base, 'src/worker/log.js'))
var LogWorker = new Log({
  module: 'Torrent'
})
var Client = require(Path.join(__base, 'src/worker/client.js'))

/**
 * Torrent manager.
 * @constructor
*/
function Torrent () {
  var self = this
  this.client = {}

  this.dowloader = {}
  this.waitList = []

  setInterval(function () {
    self.startPointTorrent(self)
  }, 30000)
}

/**
 * Start downloadind torrent.
 * @param {string} url - Url / magnet of the torrent.
*/
Torrent.prototype.start = function (url) {
  var self = this
  // evite de lancer deux fois le meme torrent
  if (self.client[url] == null) {
    // Si trop de torrent en cours
    if (Object.keys(self.client).length < __config.torrent.max) {
      if (self.client[url] == null) {
        self.client[url] = {count: 1}
      } else {
        self.client[url].count++
      }

      if (self.client[url].count > __config.client.maxTry) {
        return -1
      }
      var c = new Client()
      c.download(url, function () {})

      c.on('start', function (hash) {
        if (self.client[url]) {
          self.client[url].hash = hash
        }
      })

      c.on('download', function (infos) {
        if (self.client[url]) {
          self.client[url].infos = infos
        }
      })

      c.on('done', function (err, hash, name) {
        if (self.client[url]) {
          if (err) {
            LogWorker.error('Fail downloading: ' + url)
            return
          }
          self.client[url].peer.stop()
          // Deplace les fichies
          LogWorker.info(Path.join(__config.torrent.downloads, name) + ' ' + Path.join(__config.directory.path, name))
          fs.rename(Path.join(__base, __config.torrent.downloads, name), Path.join(__base, __config.directory.path, name), function(err){
            if(err){
              LogWorker.error(err)
              return
            }
            // Defini l'owner
            if (self.dowloader[url]) {
              self.Directory.setOwner(name, self.dowloader[url])
            }
            delete self.client[url]
            // Relance un torrent si il y en a en attente
            if (self.waitList.length > 0) {
              LogWorker.info('Start torrent into waitList (left: ' + (self.waitList.length - 1) + ')')
              self.start(self.waitList.shift())
            }
          })
        }
      })

      self.client[url].peer = c
    } else {
      LogWorker.warning('Too much client. Adding torrent to the waitlist.')
      // On push dans la liste d'attente
      if (self.waitList.indexOf(url) === -1) {
        self.waitList.push(url)
      }
    }
  } else {
    LogWorker.warning('Torrent is already downloading.')
  }
}

/**
 * Stop and remove a torrent.
 * @param {string} hash - Torrent to remove Hash.
*/
Torrent.prototype.remove = function (hash) {
  var url = this.getUrlFromHash(hash)
  if (url && this.client[url]) {
    this.client[url].peer.stop()
    delete this.client[url]
  }
}

/**
 * Get torrent url from hash.
 * @param {string} hash - Torrent Hash.
 * @return {string} - Torrent turl.
*/
Torrent.prototype.getUrlFromHash = function (hash) {
  for (var key in this.client) {
    if (this.client[key].hash === hash) {
      return key
    }
  }
  return null
}

/**
 * Start torrent into configured torrent file.
 * @param {object} self - Torrent instance.
*/
Torrent.prototype.startPointTorrent = function (self) {
  fs.readFile(Path.join(__base, __config.torrent.scanTorrent), 'utf-8', function(err, data){
    if(err){
      LogWorker.error(err)
      return
    }
    var torrents = data.split('\n')
    fs.writeFile(Path.join(__base, __config.torrent.scanTorrent), '', 'utf-8', function(err){
      if(err){
        LogWorker.error(err)
        return
      }
      torrents.forEach(function (element) {
        if (element !== '') {
          self.start(element)
        }
      })
    })
  })
}

/**
 * Get infos about all current clients.
 * @return {object} - All torrent infos.
*/
Torrent.prototype.getInfo = function () {
  var torrents = {}
  for (var key in this.client) {
    var t = this.client[key].infos
    if (t) {
      torrents[t.hash] = t
    }
  }
  return torrents
}

/**
 * Define who download a torrent.
 * @param {string} user - User who download the torrent.
 * @param {string} url - Torrent url.
*/
Torrent.prototype.setDownloader = function (user, url) {
  this.dowloader[url] = user
}
module.exports = new Torrent()
<|endoftext|>


<commit_before>
// Chromosome ideogram
//

var log = function(txt) {
	console.log("karyo: "+txt);
}
var igv = (function (igv) {

    igv.KaryoPanel = function (browser) {

        this.browser = browser;
        this.div = document.createElement('div');
        this.div.style.height = "200px";
        this.div.style.width = "100%";

        this.ideograms = null;
        igv.guichromosomes = [];

        var contentHeight = this.div.clientHeight;
        var contentWidth = this.div.clientWidth - browser.controlPanelWidth;
        var contentDiv = document.createElement("div");
        contentDiv.style.position = "absolute";
        contentDiv.style.height = "100%";
        contentDiv.style.left = browser.controlPanelWidth + "px";
        contentDiv.style.right = "0px";
        this.div.appendChild(contentDiv);

        var canvas = document.createElement('canvas');
        canvas.style.position = 'absolute';
        canvas.style.width = "100%";
        canvas.style.height = contentHeight;
        log("canvas height: "+ canvas.style.height);
        canvas.setAttribute('width', contentWidth);    //Must set the width & height of the canvas
        canvas.setAttribute('height', contentHeight);

        this.canvas = canvas;
        contentDiv.appendChild(canvas);

        this.ctx = canvas.getContext("2d");

        this.canvas.onclick = function (e) {
            var isFirefox = typeof InstallTrigger !== 'undefined';

            var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
            var isChrome = !!window.chrome && !isOpera;

            var mouseX;
            var mouseY;

            if (isFirefox) {
                // It's Firefox
                mouseX = e.layerX;
                mouseY = e.layerY;
            } else {
                // It's Chrome or Safari and works for both
                mouseX = e.offsetX;
                mouseY = e.offsetY;
            }

            this.getContext("2d").fillRect(mouseX, 0, 10, 10);
            igv.navigateKaryo(browser, mouseX, mouseY);
        }

    }

    // Move location of the reference panel by clicking on the genome ideogram
    igv.navigateKaryo = function (browser, mouseX, mouseY) {
    	// check each chromosome if the coordinates are within its bound
    	for (var i = 0; i < igv.guichromosomes.length; i++) {
    		var g = igv.guichromosomes[i];
    		if (g.x < mouseX && g.right > mouseX && g.y < mouseY && g.bottom > mouseY) {
    			var dy = mouseY - g.y;
    			var bp = Math.round(g.size * dy / g.h);
    			log("Going to position "+bp);
    			browser.search(g.name+":"+bp+"-"+(bp+10000));
    			break;
    		}
    	}

        browser.update();
    };

    igv.KaryoPanel.prototype.resize = function () {

        var contentHeight = this.div.clientHeight,
            contentWidth = this.div.clientWidth,
            canvas = this.canvas;
        canvas.style.width = "100%";
        canvas.style.height = contentHeight + "px";
        canvas.setAttribute('width', contentWidth);    //Must set the width & height of the canvas
        canvas.setAttribute('height', contentHeight);
        log("redraw: height is :"+contentHeight);

        this.repaint();
    }

    igv.KaryoPanel.prototype.repaint = function () {

        var genome = this.browser.genome,
            referenceFrame = this.browser.referenceFrame,
            stainColors = [],
            w = this.canvas.width,
            h = this.canvas.height;
        this.ctx.clearRect(0, 0, w, h);

        if (!(genome && genome.chromosomes)) return;

        var chromosomes = genome.getChromosomes();
        var image = this.ideograms;

        if (chromosomes.length < 1) {
        	log("No chromosomes yet, returning");
        	return;
        }
        var chrwidth = Math.min(30, w / 24);
        var chrheight = h-40;
        var longestChr = genome.getChromosome('chr1');
        var cytobands = longestChr.cytobands;
        var top = 30;
        var maxLen = cytobands[cytobands.length-1].end;
        if (!image || image == null) {
            image = document.createElement('canvas');
            image.width = w;

            image.height = 200;
            var bufferCtx = image.getContext('2d');
            var nr = 0;

            for (chr in chromosomes) {
            	if (nr > 23) break;
            	nr++;
            	var chromosome = genome.getChromosome(chr);
            	chromosome.x = nr*chrwidth;
            	var guichrom = new Object();
            	guichrom.name = chr;
            	igv.guichromosomes.push(guichrom);
            	drawIdeogram(guichrom, chromosome.x, top, chromosome, bufferCtx, chrwidth/2,chrheight, maxLen);

            }
            this.ideograms= image;
        }

        this.ctx.drawImage(image, 0, 0);

        // Draw red box
        this.ctx.save();
        var chromosome = this.browser.genome.getChromosome(this.browser.referenceFrame.chr);
        cytobands = chromosome.cytobands;
        var size = cytobands[cytobands.length-1].end;
        var ideoScale = h / maxLen;

        var boxPY1 = top+Math.round(this.browser.referenceFrame.start * ideoScale);
        //var boxPY2 = Math.round((this.browser.referenceFrame.start+100) * ideoScale);
        this.ctx.strokeStyle = "red";
        this.ctx.lineWidth = 2;
        this.ctx.strokeRect(chromosome.x-2, boxPY1, chrwidth/2+4, 3 );
        this.ctx.restore();

        function drawIdeogram(guichrom, ideogramLeft, top, chromosome, bufferCtx, ideogramWidth, ideogramHeight, longestChr) {

            if (!genome) return;
            if (!chromosome) return;

            var cytobands = chromosome.cytobands;

            var centerx = (ideogramLeft + ideogramWidth / 2);

            var xC = [];
            var yC = [];

            var len = cytobands.length;
            if (len == 0) return;
            var scale = ideogramHeight / longestChr;

            guichrom.x = ideogramLeft;
            guichrom.y = top;
            guichrom.w = ideogramWidth;
            guichrom.right = ideogramLeft + ideogramWidth;
            var last = cytobands[len-1].end;
            guichrom.h = scale * last;
            guichrom.size = last;
            guichrom.longest = longestChr;
            guichrom.bottom = top +guichrom.h;
            var lastPY = -1;
            for (var i = 0; i < cytobands.length; i++) {
                var cytoband = cytobands[i];

                var starty = scale * cytoband.start + top;
                var endy = scale * cytoband.end + top;
                if (endy > lastPY) {
                    if (cytoband.type == 'c') { // centermere: "acen"
                        if (cytoband.label.charAt(0) == 'p') {
                            yC[0] = starty;
                            xC[0] = ideogramWidth + ideogramLeft;
                            yC[1] = starty;
                            xC[1] = ideogramLeft;
                            yC[2] = endy;
                            xC[2] = centerx;
                        } else {
                            yC[0] = endy;
                            xC[0] = ideogramWidth + ideogramLeft;
                            yC[1] = endy;
                            xC[1] = ideogramLeft;
                            yC[2] = starty;
                            xC[2] = centerx;
                        }
                        bufferCtx.fillStyle = "rgb(150, 0, 0)"; //g2D.setColor(Color.RED.darker());
                        bufferCtx.strokeStyle = "rgb(150, 0, 0)"; //g2D.setColor(Color.RED.darker());
                        bufferCtx.polygon(xC, yC, 1, 0);
                       // g2D.fillPolygon(xC, yC, 3);
                    } else {
                    	var dy = endy - starty;

                        bufferCtx.fillStyle = getCytobandColor(cytoband); //g2D.setColor(getCytobandColor(cytoband));
                        bufferCtx.fillRect(ideogramLeft, starty,  ideogramWidth, dy);
                    }
                }

                lastPY = endy;

            }
            bufferCtx.fillStyle = null;
            bufferCtx.lineWidth = 1;
            bufferCtx.strokeStyle = "darkgray";
            var r = ideogramWidth / 2;
            bufferCtx.roundRect(ideogramLeft, top-r/2, ideogramWidth, lastPY-top+r, ideogramWidth / 2, 0, 1);

         // draw chromosome name

            bufferCtx.font = "bold 10px Arial";
            bufferCtx.fillStyle = "rgb(0, 0, 0)";
            bufferCtx.fillText(chromosome.name, ideogramLeft +ideogramWidth / 2-10, top-20);
        }

        function getCytobandColor(data) {
            if (data.type == 'c') { // centermere: "acen"
                return "rgb(150, 10, 10)"

            } else {
                var stain = data.stain; // + 4;

                var shade = 230;
                if (data.type == 'p') {
                    shade = Math.floor(230 - stain / 100.0 * 230);
                }
                var c = stainColors[shade];
                if (c == null) {
                    c = "rgb(" + shade + "," + shade + "," + shade + ")";
                    stainColors[shade] = c;
                }
                //log("Got color: "+c);
                return c;

            }
        }

    }

    return igv;
})
    (igv || {});<commit_msg>- ability to add tracks to karyo view (for testing uses first few chromosomes of gene track until we have a more reasonable track for a whole genome view) - tool tip on karyo view to see location of mouse pointer (which chromosome, what bp)<commit_after>
// Chromosome ideogram
//

var log = function(txt) {
	console.log("karyo: "+txt);
}
var igv = (function (igv) {

    igv.KaryoPanel = function (browser) {

        this.browser = browser;
        this.div = document.createElement('div');
        this.div.style.height = "200px";
        this.div.style.width = "100%";

        this.ideograms = null;
        igv.guichromosomes = [];

        var contentHeight = this.div.clientHeight;
        var contentWidth = this.div.clientWidth - browser.controlPanelWidth;
        var contentDiv = document.createElement("div");
        contentDiv.style.position = "absolute";
        contentDiv.style.height = "100%";
        contentDiv.style.left = browser.controlPanelWidth + "px";
        contentDiv.style.right = "0px";
        this.div.appendChild(contentDiv);

        var canvas = document.createElement('canvas');
        canvas.style.position = 'absolute';
        canvas.style.width = "100%";
        canvas.style.height = contentHeight;
        log("canvas height: "+ canvas.style.height);
        canvas.setAttribute('width', contentWidth);    //Must set the width & height of the canvas
        canvas.setAttribute('height', contentHeight);

        this.canvas = canvas;
        contentDiv.appendChild(canvas);

        this.ctx = canvas.getContext("2d");

        var tipCanvas = document.createElement('canvas');
        tipCanvas.style.position = 'absolute';
        tipCanvas.style.width = "100px";
        tipCanvas.style.height = "20px";
        tipCanvas.style.left = "-200px";
        tipCanvas.setAttribute('width', "100px");    //Must set the width & height of the canvas
        tipCanvas.setAttribute('height', "20px");
        var tipCtx = tipCanvas.getContext("2d");
        contentDiv.appendChild(tipCanvas);

        this.canvas.onmousemove = function (e) {
        	var isFirefox = typeof InstallTrigger !== 'undefined';

            var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
            var isChrome = !!window.chrome && !isOpera;

            var mouseX;
            var mouseY;

            if (isFirefox) {
                // It's Firefox
                mouseX = e.layerX;
                mouseY = e.layerY;
            } else {
                // It's Chrome or Safari and works for both
                mouseX = e.offsetX;
                mouseY = e.offsetY;
            }
            var hit = false;
            for (var i = 0; i < igv.guichromosomes.length; i++) {
        		var g = igv.guichromosomes[i];
        		if (g.x < mouseX && g.right > mouseX && g.y < mouseY && g.bottom > mouseY) {
        			var dy = mouseY - g.y;
        			var bp = Math.round(g.size * dy / g.h);
        			//log("Found chr "+g.name+", bp="+bp+", mousex="+mouseX+", mousey="+mouseY);
        			tipCanvas.style.left = Math.round(mouseX+20) + "px";
        			tipCanvas.style.top = Math.round(mouseY-5) + "px";

        			//log("width/height of tip canvas:"+tipCanvas.width+"/"+tipCanvas.height);
        			//log("tipCanvas.left="+tipCanvas.style.left);
        			tipCtx.clearRect(0, 0, tipCanvas.width, tipCanvas.height);
        			tipCtx.fillStyle = 'rgb(255,255,220)';
        			tipCtx.fillRect(0, 0, tipCanvas.width, tipCanvas.height);
        			tipCtx.fillStyle = 'rgb(0,0,0)';
        			var mb = Math.round(bp/1000000);
        			tipCtx.fillText(g.name+" @ "+mb+" MB", 3, 12);
                    hit = true;
        			break;
        		}
        	}
            if (!hit) { tipCanvas.style.left = "-200px"; }
        }
        this.canvas.onclick = function (e) {
            var isFirefox = typeof InstallTrigger !== 'undefined';

            var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
            var isChrome = !!window.chrome && !isOpera;

            var mouseX;
            var mouseY;

            if (isFirefox) {
                // It's Firefox
                mouseX = e.layerX;
                mouseY = e.layerY;
            } else {
                // It's Chrome or Safari and works for both
                mouseX = e.offsetX;
                mouseY = e.offsetY;
            }

            this.getContext("2d").fillRect(mouseX, 0, 10, 10);
            igv.navigateKaryo(browser, mouseX, mouseY);
        }

    }

    // Move location of the reference panel by clicking on the genome ideogram
    igv.navigateKaryo = function (browser, mouseX, mouseY) {
    	// check each chromosome if the coordinates are within its bound
    	for (var i = 0; i < igv.guichromosomes.length; i++) {
    		var g = igv.guichromosomes[i];
    		if (g.x < mouseX && g.right > mouseX && g.y < mouseY && g.bottom > mouseY) {
    			var dy = mouseY - g.y;
    			var bp = Math.round(g.size * dy / g.h);
    			log("Going to position "+bp);
    			browser.search(g.name+":"+bp+"-"+(bp+10000));
    			break;
    		}
    	}

        browser.update();
    };

    igv.KaryoPanel.prototype.resize = function () {

        var contentHeight = this.div.clientHeight,
            contentWidth = this.div.clientWidth,
            canvas = this.canvas;
        canvas.style.width = "100%";
        canvas.style.height = contentHeight + "px";
        canvas.setAttribute('width', contentWidth);    //Must set the width & height of the canvas
        canvas.setAttribute('height', contentHeight);
        log("redraw: height is :"+contentHeight);

        this.repaint();
    }

    igv.KaryoPanel.prototype.repaint = function () {

        var genome = this.browser.genome,
            referenceFrame = this.browser.referenceFrame,
            stainColors = [],
            w = this.canvas.width,
            h = this.canvas.height;
        this.ctx.clearRect(0, 0, w, h);

        if (!(genome && genome.chromosomes)) return;

        var chromosomes = genome.getChromosomes();
        var image = this.ideograms;

        if (chromosomes.length < 1) {
        	log("No chromosomes yet, returning");
        	return;
        }
        var totalchrwidth = Math.min(50, w / 25);
        var chrwidth = Math.min(20, totalchrwidth/2);
        var chrheight = h-40;
        var longestChr = genome.getChromosome('chr1');
        var cytobands = longestChr.cytobands;
        var top = 30;
        var me = this;
        var maxLen = cytobands[cytobands.length-1].end;
        if (!image || image == null) {
            image = document.createElement('canvas');
            image.width = w;

            image.height = 200;
            var bufferCtx = image.getContext('2d');
            var nr = 0;

            for (chr in chromosomes) {
            	if (nr > 23) break;
            	nr++;
            	var chromosome = genome.getChromosome(chr);
            	chromosome.x = nr*totalchrwidth;
            	var guichrom = new Object();
            	guichrom.name = chr;
            	igv.guichromosomes.push(guichrom);

            	drawIdeogram(guichrom, chromosome.x, top, chromosome, bufferCtx, chrwidth,chrheight, maxLen);

            }
            this.ideograms= image;

	        // now add some tracks?
	        log("============= PROCESSING "+igv.browser.trackPanels.length+" TRACKS");
	        for (var i = 0; i < igv.browser.trackPanels.length; i++) {
	        	var trackPanel = igv.browser.trackPanels[i];
	        	var track = trackPanel.track;
	        	log("-------Got track "+i+": ");
	        	for (var key in track) {
	        		if (key != "draw" && key != "drawLabel") log("   key "+key+":"+track[key]);
	        	}
	        	log("Got track: "+track.label);
	        	if (track.id == "genes") {
	        		log("adding gene tracks to karyo view: TODO");
	        		var source = track.featureSource;
	        		log("filename="+source.filename);
	        		nr = 0;
	                for (chr in chromosomes) {
	                	log("=========== processing chromosome "+chr);
	                	log("Currently just loading 1 chromosome, until we have some more reasonable tracks to actaully draw in a whole genome view :-)")
	                	if (nr > 1) break;
	                	var guichrom = igv.guichromosomes[nr];
	                	nr++;
	                	loadfeatures(source, chr, 0, guichrom.size, guichrom, bufferCtx);
	                }
	        	}
	        }

        }
        function loadfeatures(source, chr, start, end, guichrom, bufferCtx) {
        	log("=== loadfeatures of chr "+chr+", x="+guichrom.x);
        	source.getFeatures(chr, start, end, function (featureList) {
                if (featureList) {
                     len = featureList.length;
                     log(" -->- loaded: chrom "+chr+" as "+len+" features");
                     drawFeatures(featureList, guichrom, guichrom.x, top,  bufferCtx, chrwidth,chrheight, maxLen);
                     me.repaint();
                }
                else {
             	   log("Track has no features yet");
                }
     		});
        }
        this.ctx.drawImage(image, 0, 0);

        // Draw red box
        this.ctx.save();
        var chromosome = this.browser.genome.getChromosome(this.browser.referenceFrame.chr);
        cytobands = chromosome.cytobands;
        var size = cytobands[cytobands.length-1].end;
        var ideoScale = h / maxLen;

        var boxPY1 = top+Math.round(this.browser.referenceFrame.start * ideoScale);
        //var boxPY2 = Math.round((this.browser.referenceFrame.start+100) * ideoScale);
        this.ctx.strokeStyle = "rgb(150, 0, 0)";
        this.ctx.lineWidth = 2;
        this.ctx.strokeRect(chromosome.x-3, boxPY1, chrwidth+6, 3 );
        this.ctx.restore();

        function drawFeatures(featurelist, guichrom, ideogramLeft, top, bufferCtx, ideogramWidth, ideogramHeight, longestChr) {
        	 if (!genome) return;
             if (!chromosome) return;
             if (!featurelist) return;
             var len = featurelist.length;
             if (len == 0) return;
             var scale = ideogramHeight / longestChr;
             log("drawing "+len+" feaures of chrom "+guichrom.name);
             var dx = 3;
             for (var i = 0; i < featurelist.length; i++) {
                 var feature = featurelist[i];

                 var starty = scale * feature.start + top;
                 var endy = scale * feature.end + top;
                 var dy = Math.max(0.01, endy - starty);
                 if (i < 3) log("Drawing feature  "+feature.start+"-"+feature.end+" -> "+starty+", dy="+dy);
                 bufferCtx.fillStyle = 'rgb(0,0,150)'; //g2D.setColor(getCytobandColor(cytoband));
                 bufferCtx.fillRect(ideogramLeft+ideogramWidth+3, starty,  dx, dy);
             }
        }
        function drawIdeogram(guichrom, ideogramLeft, top, chromosome, bufferCtx, ideogramWidth, ideogramHeight, longestChr) {

            if (!genome) return;
            if (!chromosome) return;

            var cytobands = chromosome.cytobands;

            var centerx = (ideogramLeft + ideogramWidth / 2);

            var xC = [];
            var yC = [];

            var len = cytobands.length;
            if (len == 0) return;
            var scale = ideogramHeight / longestChr;

            guichrom.x = ideogramLeft;
            guichrom.y = top;
            guichrom.w = ideogramWidth;
            guichrom.right = ideogramLeft + ideogramWidth;
            var last = cytobands[len-1].end;
            guichrom.h = scale * last;
            guichrom.size = last;
            guichrom.longest = longestChr;
            guichrom.bottom = top +guichrom.h;
            var lastPY = -1;
            for (var i = 0; i < cytobands.length; i++) {
                var cytoband = cytobands[i];

                var starty = scale * cytoband.start + top;
                var endy = scale * cytoband.end + top;
                if (endy > lastPY) {
                    if (cytoband.type == 'c') { // centermere: "acen"
                        if (cytoband.label.charAt(0) == 'p') {
                            yC[0] = starty;
                            xC[0] = ideogramWidth + ideogramLeft;
                            yC[1] = starty;
                            xC[1] = ideogramLeft;
                            yC[2] = endy;
                            xC[2] = centerx;
                        } else {
                            yC[0] = endy;
                            xC[0] = ideogramWidth + ideogramLeft;
                            yC[1] = endy;
                            xC[1] = ideogramLeft;
                            yC[2] = starty;
                            xC[2] = centerx;
                        }
                        // centromer: carl wants another color
                        bufferCtx.fillStyle = "rgb(220, 150, 100)"; //g2D.setColor(Color.RED.darker());
                        bufferCtx.strokeStyle = "rgb(150, 0, 0)"; //g2D.setColor(Color.RED.darker());
                        bufferCtx.polygon(xC, yC, 1, 0);
                       // g2D.fillPolygon(xC, yC, 3);
                    } else {
                    	var dy = endy - starty;

                        bufferCtx.fillStyle = getCytobandColor(cytoband); //g2D.setColor(getCytobandColor(cytoband));
                        bufferCtx.fillRect(ideogramLeft, starty,  ideogramWidth, dy);
                    }
                }

                lastPY = endy;

            }
            bufferCtx.fillStyle = null;
            bufferCtx.lineWidth = 1;
            bufferCtx.strokeStyle = "darkgray";
            var r = ideogramWidth / 2;
            bufferCtx.roundRect(ideogramLeft, top-r/2, ideogramWidth, lastPY-top+r, ideogramWidth / 2, 0, 1);

         // draw chromosome name

            bufferCtx.font = "bold 10px Arial";
            bufferCtx.fillStyle = "rgb(0, 0, 0)";
            bufferCtx.fillText(chromosome.name, ideogramLeft +ideogramWidth / 2-10, top-20);
        }

        function getCytobandColor(data) {
            if (data.type == 'c') { // centermere: "acen"
                return "rgb(150, 10, 10)"

            } else {
                var stain = data.stain; // + 4;

                var shade = 230;
                if (data.type == 'p') {
                    shade = Math.floor(230 - stain / 100.0 * 230);
                }
                var c = stainColors[shade];
                if (c == null) {
                    c = "rgb(" + shade + "," + shade + "," + shade + ")";
                    stainColors[shade] = c;
                }
                //log("Got color: "+c);
                return c;

            }
        }

    }

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


<commit_before>Slingshot.S3Storage = {

  accessId: "AWSAccessKeyId",
  secretKey: "AWSSecretAccessKey",

  directiveMatch: {
    bucket: String,
    bucketUrl: Match.OneOf(String, Function),

    region: Match.Where(function (region) {
      check(region, String);

      return /^[a-z]{2}-\w+-\d+$/.test(region);
    }),

    AWSAccessKeyId: String,
    AWSSecretAccessKey: String,

    acl: Match.Optional(Match.Where(function (acl) {
      check(acl, String);

      return [
          "private",
          "public-read",
          "public-read-write",
          "authenticated-read",
          "bucket-owner-read",
          "bucket-owner-full-control",
          "log-delivery-write"
        ].indexOf(acl) >= 0;
    })),

    key: Match.OneOf(String, Function),

    expire: Match.Where(function (expire) {
      check(expire, Number);

      return expire > 0;
    }),

    cacheControl: Match.Optional(String),
    contentDisposition: Match.Optional(Match.OneOf(String, null))
  },

  directiveDefault: _.chain(Meteor.settings)
    .pick("AWSAccessKeyId", "AWSSecretAccessKey")
    .extend({
      bucket: Meteor.settings.S3Bucket,
      bucketUrl: function (bucket, region) {
        var bucketDomain = "s3-" + region + ".amazonaws.com";
        if (region === "us-east-1")
          bucketDomain = "s3.amazonaws.com";

        if (bucket.indexOf(".") !== -1)
          return "https://" + bucketDomain + "/" + bucket;

        return "https://" + bucket + "." + bucketDomain;
      },
      region: Meteor.settings.AWSRegion || "us-east-1",
      expire: 5 * 60 * 1000 //in 5 minutes
    })
    .value(),

  /**
   *
   * @param {{userId: String}} method
   * @param {Directive} directive
   * @param {FileInfo} file
   * @param {Object} [meta]
   *
   * @returns {UploadInstructions}
   */

  upload: function (method, directive, file, meta) {
    var url = Npm.require("url"),

        policy = new Slingshot.StoragePolicy()
          .expireIn(directive.expire)
          .contentLength(0, Math.min(file.size, directive.maxSize || Infinity)),

        payload = {
          key: _.isFunction(directive.key) ?
            directive.key.call(method, file, meta) : directive.key,

          bucket: directive.bucket,

          "Content-Type": file.type,
          "acl": directive.acl,

          "Cache-Control": directive.cacheControl,
          "Content-Disposition": directive.contentDisposition || file.name &&
            "inline; filename=" + quoteString(file.name, '"')
        },

        bucketUrl = _.isFunction(directive.bucketUrl) ?
          directive.bucketUrl(directive.bucket, directive.region) :
          directive.bucketUrl,

        downloadUrl = [
          (directive.cdn || bucketUrl),
          payload.key
        ].map(function (part) {
            return part.replace(/\/+$/, '');
          }).join("/");

    this.applySignature(payload, policy, directive);

    return {
      upload: bucketUrl,
      download: downloadUrl,
      postData: [{
        name: "key",
        value: payload.key
      }].concat(_.chain(payload).omit("key").map(function (value, name) {
          return !_.isUndefined(value) && {
              name: name,
              value: value
            };
        }).compact().value())
    };
  },

  /** Applies signature an upload payload
   *
   * @param {Object} payload - Data to be upload along with file
   * @param {Slingshot.StoragePolicy} policy
   * @param {Directive} directive
   */

  applySignature: function (payload, policy, directive) {
    var now =  new Date(),
        today = now.getUTCFullYear() + formatNumber(now.getUTCMonth() + 1, 2) +
          formatNumber(now.getUTCDate(), 2),
        service = "s3";

    _.extend(payload, {
      "x-amz-algorithm": "AWS4-HMAC-SHA256",
      "x-amz-credential": [
        directive[this.accessId],
        today,
        directive.region,
        service,
        "aws4_request"
      ].join("/"),
      "x-amz-date": today + "T000000Z"
    });

    payload.policy = policy.match(payload).stringify();
    payload["x-amz-signature"] = this.signAwsV4(payload.policy,
      directive[this.secretKey], today, directive.region, service);
  },

  /** Generate a AWS Signature Version 4
   *
   * @param {String} policy - Base64 encoded policy to sign.
   * @param {String} secretKey - AWSSecretAccessKey
   * @param {String} date - Signature date (yyyymmdd)
   * @param {String} region - AWS Data-Center region
   * @param {String} service - type of service to use
   * @returns {String} hex encoded HMAC-256 signature
   */

  signAwsV4: function (policy, secretKey, date, region, service) {
    var dateKey = hmac256("AWS4" + secretKey, date),
        dateRegionKey = hmac256(dateKey, region),
        dateRegionServiceKey= hmac256(dateRegionKey, service),
        signingKey = hmac256(dateRegionServiceKey, "aws4_request");

    return hmac256(signingKey, policy, "hex");
  }
};

function quoteString(string, quotes) {
  return quotes + string.replace(quotes, '\\' + quotes) + quotes;
}

function formatNumber(num, digits) {
  var string = String(num);

  return Array(digits - string.length + 1).join("0").concat(string);
}

var crypto = Npm.require("crypto");

function hmac256(key, data, encoding) {
  /* global Buffer: false */
  return crypto
    .createHmac("sha256", key)
    .update(new Buffer(data, "utf-8"))
    .digest(encoding);
}
<commit_msg>Support Content-Disposition non ASCII characters in file name, S3<commit_after>Slingshot.S3Storage = {

  accessId: "AWSAccessKeyId",
  secretKey: "AWSSecretAccessKey",

  directiveMatch: {
    bucket: String,
    bucketUrl: Match.OneOf(String, Function),

    region: Match.Where(function (region) {
      check(region, String);

      return /^[a-z]{2}-\w+-\d+$/.test(region);
    }),

    AWSAccessKeyId: String,
    AWSSecretAccessKey: String,

    acl: Match.Optional(Match.Where(function (acl) {
      check(acl, String);

      return [
          "private",
          "public-read",
          "public-read-write",
          "authenticated-read",
          "bucket-owner-read",
          "bucket-owner-full-control",
          "log-delivery-write"
        ].indexOf(acl) >= 0;
    })),

    key: Match.OneOf(String, Function),

    expire: Match.Where(function (expire) {
      check(expire, Number);

      return expire > 0;
    }),

    cacheControl: Match.Optional(String),
    contentDisposition: Match.Optional(Match.OneOf(String, null))
  },

  directiveDefault: _.chain(Meteor.settings)
    .pick("AWSAccessKeyId", "AWSSecretAccessKey")
    .extend({
      bucket: Meteor.settings.S3Bucket,
      bucketUrl: function (bucket, region) {
        var bucketDomain = "s3-" + region + ".amazonaws.com";
        if (region === "us-east-1")
          bucketDomain = "s3.amazonaws.com";

        if (bucket.indexOf(".") !== -1)
          return "https://" + bucketDomain + "/" + bucket;

        return "https://" + bucket + "." + bucketDomain;
      },
      region: Meteor.settings.AWSRegion || "us-east-1",
      expire: 5 * 60 * 1000 //in 5 minutes
    })
    .value(),

  /**
   *
   * @param {{userId: String}} method
   * @param {Directive} directive
   * @param {FileInfo} file
   * @param {Object} [meta]
   *
   * @returns {UploadInstructions}
   */

  upload: function (method, directive, file, meta) {
    var url = Npm.require("url"),

        policy = new Slingshot.StoragePolicy()
          .expireIn(directive.expire)
          .contentLength(0, Math.min(file.size, directive.maxSize || Infinity)),

        payload = {
          key: _.isFunction(directive.key) ?
            directive.key.call(method, file, meta) : directive.key,

          bucket: directive.bucket,

          "Content-Type": file.type,
          "acl": directive.acl,

          "Cache-Control": directive.cacheControl,
          "Content-Disposition": directive.contentDisposition || file.name &&
            "inline; filename=" + quoteString(file.name, '"') +
            "; filename*=utf-8''" + encodeURIComponent(file.name)
        },

        bucketUrl = _.isFunction(directive.bucketUrl) ?
          directive.bucketUrl(directive.bucket, directive.region) :
          directive.bucketUrl,

        downloadUrl = [
          (directive.cdn || bucketUrl),
          payload.key
        ].map(function (part) {
            return part.replace(/\/+$/, '');
          }).join("/");

    this.applySignature(payload, policy, directive);

    return {
      upload: bucketUrl,
      download: downloadUrl,
      postData: [{
        name: "key",
        value: payload.key
      }].concat(_.chain(payload).omit("key").map(function (value, name) {
          return !_.isUndefined(value) && {
              name: name,
              value: value
            };
        }).compact().value())
    };
  },

  /** Applies signature an upload payload
   *
   * @param {Object} payload - Data to be upload along with file
   * @param {Slingshot.StoragePolicy} policy
   * @param {Directive} directive
   */

  applySignature: function (payload, policy, directive) {
    var now =  new Date(),
        today = now.getUTCFullYear() + formatNumber(now.getUTCMonth() + 1, 2) +
          formatNumber(now.getUTCDate(), 2),
        service = "s3";

    _.extend(payload, {
      "x-amz-algorithm": "AWS4-HMAC-SHA256",
      "x-amz-credential": [
        directive[this.accessId],
        today,
        directive.region,
        service,
        "aws4_request"
      ].join("/"),
      "x-amz-date": today + "T000000Z"
    });

    payload.policy = policy.match(payload).stringify();
    payload["x-amz-signature"] = this.signAwsV4(payload.policy,
      directive[this.secretKey], today, directive.region, service);
  },

  /** Generate a AWS Signature Version 4
   *
   * @param {String} policy - Base64 encoded policy to sign.
   * @param {String} secretKey - AWSSecretAccessKey
   * @param {String} date - Signature date (yyyymmdd)
   * @param {String} region - AWS Data-Center region
   * @param {String} service - type of service to use
   * @returns {String} hex encoded HMAC-256 signature
   */

  signAwsV4: function (policy, secretKey, date, region, service) {
    var dateKey = hmac256("AWS4" + secretKey, date),
        dateRegionKey = hmac256(dateKey, region),
        dateRegionServiceKey= hmac256(dateRegionKey, service),
        signingKey = hmac256(dateRegionServiceKey, "aws4_request");

    return hmac256(signingKey, policy, "hex");
  }
};

function quoteString(string, quotes) {
  return quotes + string.replace(quotes, '\\' + quotes) + quotes;
}

function formatNumber(num, digits) {
  var string = String(num);

  return Array(digits - string.length + 1).join("0").concat(string);
}

var crypto = Npm.require("crypto");

function hmac256(key, data, encoding) {
  /* global Buffer: false */
  return crypto
    .createHmac("sha256", key)
    .update(new Buffer(data, "utf-8"))
    .digest(encoding);
}
<|endoftext|>


<commit_before>/* ---------------------------------------------------------------------- */
/*	doubleTapToGo
/* ---------------------------------------------------------------------- */

jQuery(document).ready(function($){
    var deviceAgent = navigator.userAgent.toLowerCase();
    var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
    if (agentID) {

    var width = $(window).width();
	if (width > 768) {
		if(jQuery( '#nav li:has(ul)' ).length)
		{
			jQuery( '#nav li:has(ul)' ).doubleTapToGo();
		}
	}

    }
else {
	jQuery( '#nav li:has(ul)' ).doubleTapToGo();
}
});

/* ---------------------------------------------------------------------- */
/*	Contact Form
/* ---------------------------------------------------------------------- */

$(function(){

$("#btnSend").click(function(){

$.ajax({type:'POST', url: './php/contact.php', data:$('#frmContact').serialize(), success: function(response) {
$("#spanMessage").html('Please Wait...');

	 if(parseInt(response)>0)
	   {
		 $("#spanMessage").html('
<button type="button" class="close" data-dismiss="alert">×</button>Well done! Your message has been sent.
');
	   }
	   else{
		 alert(response);
		 $("#spanMessage").html('
<button type="button" class="close" data-dismiss="alert">×</button>Error!  Somthing Wrong
');
	   }

}});

});

});

/* ---------------------------------------------------------------------- */
/*	Accordion
/* ---------------------------------------------------------------------- */

	(function() {

		var $container = $('.acc-container'),
			$trigger   = $('.acc-trigger');

		$container.hide();
		$trigger.first().addClass('active').next().show();

		var fullWidth = $container.outerWidth(true);
		$trigger.css('width', fullWidth);
		$container.css('width', fullWidth);

		$trigger.on('click', function(e) {
			if( $(this).next().is(':hidden') ) {
				$trigger.removeClass('active').next().slideUp(300);
				$(this).toggleClass('active').next().slideDown(300);
			}
			e.preventDefault();
		});

		// Resize
		$(window).on('resize', function() {
			fullWidth = $container.outerWidth(true)
			$trigger.css('width', $trigger.parent().width() );
			$container.css('width', $container.parent().width() );
		});

	})();

/* ---------------------------------------------------------------------- */
/*	Scroll to top
/* ---------------------------------------------------------------------- */

  jQuery(document).ready(function(){

        jQuery(window).scroll(function(){
            if (jQuery(this).scrollTop() > 100) {
                jQuery('.scrollup').fadeIn();
            } else {
                jQuery('.scrollup').fadeOut();
            }
        });

        jQuery('.scrollup').click(function(){
            jQuery("html, body").animate({ scrollTop: 0 }, 700);
            return false;
        });

    });

/* ---------------------------------------------------------------------- */
	/* Header search form
/* ---------------------------------------------------------------------- */
jQuery(document).ready(function(){

	jQuery('.search-text-box').click(function(){

		jQuery(this).animate({
		width:'140px',
		},240,function(){
			jQuery('.search-text-box').delay(100).queue(function(next){
				jQuery('.search-text-box').css('color','#444');
				next();
			});
		});

	});

	jQuery(document).click(function(ev){

		var myID = ev.target.id;

		if(myID != 'search-box'){
			jQuery('.search-text-box').animate({
			width:'1px',

			},200,function(){

				jQuery('.search-text-box').css('color','transparent');

			});
		}
	});

});

/*********************/
/*
/*		OurClient jCarousel Initialize
/*
/*********************/

jQuery(document).ready(function() {

	if(jQuery('#our-clients').length){
		jQuery('#our-clients').jcarousel();
	}

	if(jQuery('#latest-projects').length){
		jQuery('#latest-projects').jcarousel();
	}
});

/*********************/
/*
/*		Pie Initialize
/*
/*********************/

jQuery(document).ready(function(){

	if(jQuery('.pie').length)
	{
		jQuery('.pie').easyPieChart({
			barColor:'#ff9900',
			trackColor: '#f2f2f2',
			scaleColor: false,
			lineWidth:20,
			animate: 1000,
			onStep: function(value) {
				this.$el.find('span').text(~~value+1);
			}
		});
	}

});

/*********************/
/*
/*		Progress Bar
/*
/*********************/

initProgress('.progress');

function initProgress(el){
	jQuery(el).each(function(){
		var pData = jQuery(this).data('progress');
		progress(pData,jQuery(this));
	});
}

function progress(percent, $element) {
	var progressBarWidth = 0;

	(function myLoop (i,max) {
		progressBarWidth = i * $element.width() / 100;
		setTimeout(function () {
		$element.find('div').find('small').html(i+'%');
		$element.find('div').width(progressBarWidth);
		if (++i<=max) myLoop(i,max);
		}, 10)
	})(0,percent);
}

/*********************/
/*
/*		Sticky Menu
/*
/*********************/

jQuery(document).ready(function(){
	var width = $(window).width();
	if (width > 768) {
		if(jQuery("#sticker").length)
		{
			jQuery("#sticker").sticky({ topSpacing: 0, getWidthFrom: jQuery('#boxed-wrap')});
		}
	}
});

jQuery(window).scroll(function(){
	var width = $(window).width();
	if (width < 768) {
		if(jQuery("#sticker").length)
		{
			jQuery("#sticker").css("position","relative");
		}
	}
});

/*********************/
/*
/*		FlexSlider
/*
/*********************/

jQuery(document).ready(function() {

	  if(jQuery('.flexslider').length){
		  jQuery('.flexslider').flexslider({
			animation: "slide",
			start: function(slider){
			  jQuery('body').removeClass('loading');
			}
		  });
	  }
});

/*********************/
/*
/*		PrettyPhoto
/*
/*********************/

jQuery(document).ready(function($){

	    /* ------------------------------------------------------------------------ */
		/* Add PrettyPhoto */
		/* ------------------------------------------------------------------------ */

		var lightboxArgs = {
						animation_speed: 'fast',
						overlay_gallery: true,
			autoplay_slideshow: false,
						slideshow: 5000, /* light_rounded / dark_rounded / light_square / dark_square / facebook */
									theme: 'pp_default',
									opacity: 0.8,
						show_title: false,
			social_tools: "",			deeplinking: false,
			allow_resize: true, 			/* Resize the photos bigger than viewport. true/false */
			counter_separator_label: '/', 	/* The separator for the gallery counter 1 "of" 2 */
			default_width: 940,
			default_height: 529
		};

		if(jQuery('a[href$=jpg], a[href$=JPG], a[href$=jpeg], a[href$=JPEG], a[href$=png], a[href$=gif], a[href$=bmp]:has(img), a[class^="prettyPhoto"]').length){
			jQuery('a[href$=jpg], a[href$=JPG], a[href$=jpeg], a[href$=JPEG], a[href$=png], a[href$=gif], a[href$=bmp]:has(img), a[class^="prettyPhoto"]').prettyPhoto(lightboxArgs);
		}
		if(jQuery("a[rel^='prettyPhoto']").length){
			jQuery("a[rel^='prettyPhoto']").prettyPhoto({animation_speed:'normal',theme:'pp_default',slideshow:3000, autoplay_slideshow: false});
		}

});

/*********************/
/*
/*		Masonry
/*
/*********************/

jQuery(window).load(function() {

	// Initialize Masonry
	if(jQuery('#pin-content').length){
		jQuery('#pin-content').masonry({
			itemSelector: '.pin-box',
		}).imagesLoaded(function() {
			jQuery('#pin-content').data('masonry');
		});
	}

});

/*********************/
/*
/*		Twitter
/*
/*********************/

function tz_format_twitter(twitters) {
  var statusHTML = [];

    var status = twitters.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
      return ''+url+'';
    }).replace(/\B#([_a-z0-9]+)/ig, function(reply) {
      return  reply.charAt(0)+''+reply.substring(1)+'';
    });
    statusHTML.push(''+status+'');

  return statusHTML.join('');
}

jQuery(document).ready(function(){

 // jQuery.ajax({url:"twitter/twitter.php",success:function(result){

	// jQuery("#twitter").html(tz_format_twitter(result));
}});
});

/*********************/
/*
/*  Parallax Sections
/*
/*********************/

jQuery(document).ready(function(){
	// Cache the Window object
	$window = jQuery(window);

   $('section[data-type="background"]').each(function(){
     var $bgobj = jQuery(this); // assigning the object

      jQuery(window).scroll(function() {

		// Scroll the background at var speed
		// the yPos is a negative value because we're scrolling it UP!
		var yPos = -($window.scrollTop() / $bgobj.data('speed'));

		// Put together our final background position
		var coords = '50% '+ yPos + 'px';

		// Move the background
		$bgobj.css({ backgroundPosition: coords });

}); // window scroll Ends

 });

});
/*
 * Create HTML5 elements for IE's sake
 */

document.createElement("article");
document.createElement("section");
<commit_msg>Fix JS error<commit_after>/* ---------------------------------------------------------------------- */
/*	doubleTapToGo
/* ---------------------------------------------------------------------- */

jQuery(document).ready(function($){
    var deviceAgent = navigator.userAgent.toLowerCase();
    var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
    if (agentID) {

    var width = $(window).width();
	if (width > 768) {
		if(jQuery( '#nav li:has(ul)' ).length)
		{
			jQuery( '#nav li:has(ul)' ).doubleTapToGo();
		}
	}

    }
else {
	jQuery( '#nav li:has(ul)' ).doubleTapToGo();
}
});

/* ---------------------------------------------------------------------- */
/*	Contact Form
/* ---------------------------------------------------------------------- */

$(function(){

$("#btnSend").click(function(){

$.ajax({type:'POST', url: './php/contact.php', data:$('#frmContact').serialize(), success: function(response) {
$("#spanMessage").html('Please Wait...');

	 if(parseInt(response)>0)
	   {
		 $("#spanMessage").html('
<button type="button" class="close" data-dismiss="alert">×</button>Well done! Your message has been sent.
');
	   }
	   else{
		 alert(response);
		 $("#spanMessage").html('
<button type="button" class="close" data-dismiss="alert">×</button>Error!  Somthing Wrong
');
	   }

}});

});

});

/* ---------------------------------------------------------------------- */
/*	Accordion
/* ---------------------------------------------------------------------- */

	(function() {

		var $container = $('.acc-container'),
			$trigger   = $('.acc-trigger');

		$container.hide();
		$trigger.first().addClass('active').next().show();

		var fullWidth = $container.outerWidth(true);
		$trigger.css('width', fullWidth);
		$container.css('width', fullWidth);

		$trigger.on('click', function(e) {
			if( $(this).next().is(':hidden') ) {
				$trigger.removeClass('active').next().slideUp(300);
				$(this).toggleClass('active').next().slideDown(300);
			}
			e.preventDefault();
		});

		// Resize
		$(window).on('resize', function() {
			fullWidth = $container.outerWidth(true)
			$trigger.css('width', $trigger.parent().width() );
			$container.css('width', $container.parent().width() );
		});

	})();

/* ---------------------------------------------------------------------- */
/*	Scroll to top
/* ---------------------------------------------------------------------- */

  jQuery(document).ready(function(){

        jQuery(window).scroll(function(){
            if (jQuery(this).scrollTop() > 100) {
                jQuery('.scrollup').fadeIn();
            } else {
                jQuery('.scrollup').fadeOut();
            }
        });

        jQuery('.scrollup').click(function(){
            jQuery("html, body").animate({ scrollTop: 0 }, 700);
            return false;
        });

    });

/* ---------------------------------------------------------------------- */
	/* Header search form
/* ---------------------------------------------------------------------- */
jQuery(document).ready(function(){

	jQuery('.search-text-box').click(function(){

		jQuery(this).animate({
		width:'140px',
		},240,function(){
			jQuery('.search-text-box').delay(100).queue(function(next){
				jQuery('.search-text-box').css('color','#444');
				next();
			});
		});

	});

	jQuery(document).click(function(ev){

		var myID = ev.target.id;

		if(myID != 'search-box'){
			jQuery('.search-text-box').animate({
			width:'1px',

			},200,function(){

				jQuery('.search-text-box').css('color','transparent');

			});
		}
	});

});

/*********************/
/*
/*		OurClient jCarousel Initialize
/*
/*********************/

jQuery(document).ready(function() {

	if(jQuery('#our-clients').length){
		jQuery('#our-clients').jcarousel();
	}

	if(jQuery('#latest-projects').length){
		jQuery('#latest-projects').jcarousel();
	}
});

/*********************/
/*
/*		Pie Initialize
/*
/*********************/

jQuery(document).ready(function(){

	if(jQuery('.pie').length)
	{
		jQuery('.pie').easyPieChart({
			barColor:'#ff9900',
			trackColor: '#f2f2f2',
			scaleColor: false,
			lineWidth:20,
			animate: 1000,
			onStep: function(value) {
				this.$el.find('span').text(~~value+1);
			}
		});
	}

});

/*********************/
/*
/*		Progress Bar
/*
/*********************/

initProgress('.progress');

function initProgress(el){
	jQuery(el).each(function(){
		var pData = jQuery(this).data('progress');
		progress(pData,jQuery(this));
	});
}

function progress(percent, $element) {
	var progressBarWidth = 0;

	(function myLoop (i,max) {
		progressBarWidth = i * $element.width() / 100;
		setTimeout(function () {
		$element.find('div').find('small').html(i+'%');
		$element.find('div').width(progressBarWidth);
		if (++i<=max) myLoop(i,max);
		}, 10)
	})(0,percent);
}

/*********************/
/*
/*		Sticky Menu
/*
/*********************/

jQuery(document).ready(function(){
	var width = $(window).width();
	if (width > 768) {
		if(jQuery("#sticker").length)
		{
			jQuery("#sticker").sticky({ topSpacing: 0, getWidthFrom: jQuery('#boxed-wrap')});
		}
	}
});

jQuery(window).scroll(function(){
	var width = $(window).width();
	if (width < 768) {
		if(jQuery("#sticker").length)
		{
			jQuery("#sticker").css("position","relative");
		}
	}
});

/*********************/
/*
/*		FlexSlider
/*
/*********************/

jQuery(document).ready(function() {

	  if(jQuery('.flexslider').length){
		  jQuery('.flexslider').flexslider({
			animation: "slide",
			start: function(slider){
			  jQuery('body').removeClass('loading');
			}
		  });
	  }
});

/*********************/
/*
/*		PrettyPhoto
/*
/*********************/

jQuery(document).ready(function($){

	    /* ------------------------------------------------------------------------ */
		/* Add PrettyPhoto */
		/* ------------------------------------------------------------------------ */

		var lightboxArgs = {
						animation_speed: 'fast',
						overlay_gallery: true,
			autoplay_slideshow: false,
						slideshow: 5000, /* light_rounded / dark_rounded / light_square / dark_square / facebook */
									theme: 'pp_default',
									opacity: 0.8,
						show_title: false,
			social_tools: "",			deeplinking: false,
			allow_resize: true, 			/* Resize the photos bigger than viewport. true/false */
			counter_separator_label: '/', 	/* The separator for the gallery counter 1 "of" 2 */
			default_width: 940,
			default_height: 529
		};

		if(jQuery('a[href$=jpg], a[href$=JPG], a[href$=jpeg], a[href$=JPEG], a[href$=png], a[href$=gif], a[href$=bmp]:has(img), a[class^="prettyPhoto"]').length){
			jQuery('a[href$=jpg], a[href$=JPG], a[href$=jpeg], a[href$=JPEG], a[href$=png], a[href$=gif], a[href$=bmp]:has(img), a[class^="prettyPhoto"]').prettyPhoto(lightboxArgs);
		}
		if(jQuery("a[rel^='prettyPhoto']").length){
			jQuery("a[rel^='prettyPhoto']").prettyPhoto({animation_speed:'normal',theme:'pp_default',slideshow:3000, autoplay_slideshow: false});
		}

});

/*********************/
/*
/*		Masonry
/*
/*********************/

jQuery(window).load(function() {

	// Initialize Masonry
	if(jQuery('#pin-content').length){
		jQuery('#pin-content').masonry({
			itemSelector: '.pin-box',
		}).imagesLoaded(function() {
			jQuery('#pin-content').data('masonry');
		});
	}

});

/*********************/
/*
/*		Twitter
/*
/*********************/

function tz_format_twitter(twitters) {
  var statusHTML = [];

    var status = twitters.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
      return ''+url+'';
    }).replace(/\B#([_a-z0-9]+)/ig, function(reply) {
      return  reply.charAt(0)+''+reply.substring(1)+'';
    });
    statusHTML.push(''+status+'');

  return statusHTML.join('');
}

jQuery(document).ready(function(){

 // jQuery.ajax({url:"twitter/twitter.php",success:function(result){

	// jQuery("#twitter").html(tz_format_twitter(result));
// }});
});

/*********************/
/*
/*  Parallax Sections
/*
/*********************/

jQuery(document).ready(function(){
	// Cache the Window object
	$window = jQuery(window);

   $('section[data-type="background"]').each(function(){
     var $bgobj = jQuery(this); // assigning the object

      jQuery(window).scroll(function() {

		// Scroll the background at var speed
		// the yPos is a negative value because we're scrolling it UP!
		var yPos = -($window.scrollTop() / $bgobj.data('speed'));

		// Put together our final background position
		var coords = '50% '+ yPos + 'px';

		// Move the background
		$bgobj.css({ backgroundPosition: coords });

}); // window scroll Ends

 });

});
/*
 * Create HTML5 elements for IE's sake
 */

document.createElement("article");
document.createElement("section");
<|endoftext|>


<commit_before>import 'skatejs-named-slots';
import { emit } from '../src/index';
import { number } from '../src/properties';
import * as IncrementalDOM from 'incremental-dom';
import kickflip from '../src/kickflip';
import state from '../src/state';
import vdom, { IncrementalDOM as VdomIncrementalDOM } from '../src/vdom';
import version from '../src/version';

let componentCount = 0;

function component (opts) {
  return kickflip(`my-el-${++componentCount}`, opts);
}

function element (opts) {
  return component(opts)();
}

describe('kickflip', function () {
  it('kickflip', function () {
    expect(kickflip).to.be.a('function');
  });

  it('state', function () {
    expect(state).to.be.a('function');
  });

  it('vdom', function () {
    expect(vdom).to.be.a('function');
  });

  it('version', function () {
    expect(version).to.be.a('string');
  });
});

describe('events (on*)', function () {
  it('built-in events', function () {
    let count = 0;
    const el = element({
      render () {
        vdom('div', { onclick: () => ++count });
      }
    }).shadowRoot.firstChild;
    expect(count).to.equal(0);
    expect(el.onclick).to.be.a('function');
    el.onclick();
    expect(count).to.equal(1);
    emit(el, 'click');
    expect(count).to.equal(2);
  });

  it('custom events', function () {
    let count = 0;
    const el = element({
      render () {
        vdom('div', { ontest: () => ++count });
      }
    }).shadowRoot.firstChild;
    expect(count).to.equal(0);
    expect(el.test).to.equal(undefined)
    emit(el, 'test');
    expect(count).to.equal(1);
  });

  it('should not duplicate listeners', function (done) {
    const myel = component({
      properties: {
        test: number({ default: 0 })
      },
      created (elem) {
        elem._test = 0;
      },
      render (elem) {
        vdom('div', {
          onevent () {
            elem._test++;
          }
        }, elem.test);
      }
    });

    const el = myel();
    const shadowDiv = el.shadowRoot.children[0];

    // Ensures that it rendered.
    expect(shadowDiv.textContent).to.equal('0');
    expect(el._test).to.equal(0);

    // Trigger the handler.
    emit(shadowDiv, 'event');

    // Ensure the event fired.
    expect(el._test).to.equal(1);

    // Re-render.
    el.test++;

    setTimeout(function () {
      expect(shadowDiv.textContent).to.equal('1');
      emit(shadowDiv, 'event');
      expect(el._test).to.equal(2);

      el.test++;
      setTimeout(function () {
        expect(shadowDiv.textContent).to.equal('2');
        emit(shadowDiv, 'event');
        expect(el._test).to.equal(3);
        done();
      }, 100);
    }, 100);
  });

  it('should not trigger events bubbled from descendants', function () {
    let called = false;
    const test = () => called = true;
    const myel = component({
      render () {
        vdom('div', { ontest: test }, vdom.bind(null, 'span'));
      }
    })();

    emit(myel.querySelector('span'), 'test');
    expect(called).to.equal(false);
  });

  it('should not fail for listeners that are not functions', function () {
    const myel = component({
      render () {
        vdom('div', { ontest: null });
      }
    })();
    emit(myel.shadowRoot.firstChild, 'test');
  });
});

describe('IncrementalDOM', function () {
  it('should export all the same members as the incremental-dom we consume', function () {
    expect(VdomIncrementalDOM).to.contain(IncrementalDOM);
  });
});

describe('properties', function () {
  it('class -> className', function () {
    const elem = element({
      render () {
        vdom('div', { class: 'test' });
      }
    });
    expect(elem.shadowRoot.firstChild.className).to.equal('test');
  });

  it('false should remove the attribute', function () {
    const elem = element({
      render () {
        vdom('div', { test: false });
      }
    });
    expect(elem.shadowRoot.firstChild.hasAttribute('test')).to.equal(false);
  });
});
<commit_msg>Add tests for testing specifically how built-in and custom events behave at each part in their lifecycle: binding, triggering and unbinding.<commit_after>import 'skatejs-named-slots';
import { emit } from '../src/index';
import { boolean, number } from '../src/properties';
import * as IncrementalDOM from 'incremental-dom';
import kickflip, { render } from '../src/index';
import state from '../src/state';
import vdom, { IncrementalDOM as VdomIncrementalDOM } from '../src/vdom';
import version from '../src/version';

let componentCount = 0;

function component (opts) {
  return kickflip(`my-el-${++componentCount}`, opts);
}

function element (opts) {
  return component(opts)();
}

describe('kickflip', function () {
  it('kickflip', function () {
    expect(kickflip).to.be.a('function');
  });

  it('state', function () {
    expect(state).to.be.a('function');
  });

  it('vdom', function () {
    expect(vdom).to.be.a('function');
  });

  it('version', function () {
    expect(version).to.be.a('string');
  });
});

describe('events (on*)', function () {
  it('should not duplicate listeners', function (done) {
    const myel = component({
      properties: {
        test: number({ default: 0 })
      },
      created (elem) {
        elem._test = 0;
      },
      render (elem) {
        vdom('div', {
          onevent () {
            elem._test++;
          }
        }, elem.test);
      }
    });

    const el = myel();
    const shadowDiv = el.shadowRoot.children[0];

    // Ensures that it rendered.
    expect(shadowDiv.textContent).to.equal('0');
    expect(el._test).to.equal(0);

    // Trigger the handler.
    emit(shadowDiv, 'event');

    // Ensure the event fired.
    expect(el._test).to.equal(1);

    // Re-render.
    el.test++;

    setTimeout(function () {
      expect(shadowDiv.textContent).to.equal('1');
      emit(shadowDiv, 'event');
      expect(el._test).to.equal(2);

      el.test++;
      setTimeout(function () {
        expect(shadowDiv.textContent).to.equal('2');
        emit(shadowDiv, 'event');
        expect(el._test).to.equal(3);
        done();
      }, 100);
    }, 100);
  });

  it('should not trigger events bubbled from descendants', function () {
    let called = false;
    const test = () => called = true;
    const myel = component({
      render () {
        vdom('div', { ontest: test }, vdom.bind(null, 'span'));
      }
    })();

    emit(myel.querySelector('span'), 'test');
    expect(called).to.equal(false);
  });

  it('should not fail for listeners that are not functions', function () {
    const myel = element({
      render () {
        vdom('div', { ontest: null });
      }
    });
    emit(myel.shadowRoot.firstChild, 'test');
  });

  describe('built-in / custom', function () {
    let count, div, el;

    function inc () {
      ++count;
    }

    beforeEach(function () {
      count = 0;
      el = element({
        properties: {
          unbind: boolean()
        },
        render (elem) {
          if (elem.unbind) {
            vdom('div');
          } else {
            vdom('div', { onclick: inc, ontest: inc });
          }
        }
      });
      div = el.shadowRoot.firstChild;
    });

    describe('built-in', function () {
      it('binding', function () {
        expect(div.onclick).to.be.a('function');
      });

      it('triggering via function', function () {
        div.onclick();
        expect(count).to.equal(1);
      });

      it('triggering via dispatchEvent()', function () {
        emit(div, 'click');
        expect(count).to.equal(1);
      });

      it('unbinding', function (done) {
        el.unbind = true;
        requestAnimationFrame(function () {
          expect(div.onclick).to.equal(null);
          done();
        });
      });
    });

    describe('custom', function () {
      it('binding', function () {
        expect(div.ontest).to.equal(undefined);
      });

      it('triggering via dispatchEvent()', function () {
        emit(div, 'test');
        expect(count).to.equal(1);
      });

      it('unbinding', function (done) {
        el.unbind = true;
        requestAnimationFrame(function () {
          emit(div, 'test');
          expect(count).to.equal(0);
          done();
        });
      });
    });
  });
});

describe('IncrementalDOM', function () {
  it('should export all the same members as the incremental-dom we consume', function () {
    expect(VdomIncrementalDOM).to.contain(IncrementalDOM);
  });
});

describe('properties', function () {
  it('class -> className', function () {
    const elem = element({
      render () {
        vdom('div', { class: 'test' });
      }
    });
    expect(elem.shadowRoot.firstChild.className).to.equal('test');
  });

  it('false should remove the attribute', function () {
    const elem = element({
      render () {
        vdom('div', { test: false });
      }
    });
    expect(elem.shadowRoot.firstChild.hasAttribute('test')).to.equal(false);
  });
});
<|endoftext|>