<commit_before>/*
 *  LoadingScene.js
 *  2014/12/09
 *  @auther minimo
 *  This Program is MIT license.
 *
 */

tm.define("pb3.LoadingScene", {
    superClass: "tm.app.Scene",

    init: function(param) {
        this.superInit();

        this.fromJSON({
            children: {
                stage: {
                    type: "tm.display.CanvasElement",
                },
            }
        });

        this.stage.fromJSON({
            children: {
                bg: {
                    type: "tm.display.Shape",
                    init: [{width: param.width, height: param.height}],
                    originX: 0,
                    originY: 0,
                },
                label: {
                    type: "tm.display.Label",
                    text: "Asset read error!!",
                    x: param.width/2,
                    y: param.height/2-20,
                    align: "center",
                    baseline: "middle",
                    fontSize: 46,
                    shadowBlur: 4,
                    shadowColor: "hsl(190, 100%, 50%)",
                    alpha: 0,
                },
                bar: {
                    type: "tm.ui.Gauge",
                    init: [{
                        width: SC_W*0.4,
                        height: 20,
                        color: "blue",
                        bgColor: "rgba(20, 20, 20, 1)",
                        borderColor: "transparent",
                        borderWidth: 0,
                    }],
                    x: SC_W*0.3,
                    y: SC_H*0.5+20,
                },
            }
        });

        // bg
        var bg = this.stage.bg;
        bg.canvas.clearColor(param.bgColor);

        var text = "LOADING";
        var text_space = [0,31,31,30,20,20,30];
                        //L O  A  D  I  N  G
        var spc = 0;
        for (var i = 0; i < text.length; i++) {
            spc += text_space[i];
            var x = param.width/2-84+spc;
            var y = param.height/2-20;

            var base = tm.app.Object2D()
                .addChildTo(this.stage)
                .setPosition(x, y);
            base.tweener
                .wait(500+150*i)
                .moveBy(0, -30, 300, "easeOutSine")
                .moveBy(0, 30, 600, "easeOutBounce")
                .wait(1000)
                .moveBy(0, -30, 300, "easeOutSine")
                .moveBy(0, 30, 600, "easeOutBounce")
                .wait(1000)
                .moveBy(0, -30, 300, "easeOutSine")
                .moveBy(0, 30, 600, "easeOutBounce")
                .wait(1000)
                .moveBy(0, -30, 300, "easeOutSine")
                .moveBy(0, 30, 600, "easeOutBounce")
                .wait(1000)
                .moveBy(0, -30, 300, "easeOutSine")
                .moveBy(0, 30, 600, "easeOutBounce")

            var chr = tm.display.Label(text.charAt(i), 46)
                .addChildTo(base)
                .setAlign("center")
                .setBaseline("middle")
                .setShadowBlur(4)
                .setShadowColor("hsl(190, 100%, 50%)");
            chr.tweener
                .to({alpha:0.3}, 1000, "easeInOutSine")
                .to({alpha:1}, 1000, "easeInOutSine")
                .to({alpha:0.3}, 1000, "easeInOutSine")
                .to({alpha:1}, 1000, "easeInOutSine")
                .to({alpha:0.3}, 1000, "easeInOutSine")
                .to({alpha:1}, 1000, "easeInOutSine")
                .to({alpha:0.3}, 1000, "easeInOutSine")
                .to({alpha:1}, 1000, "easeInOutSine")
                .to({alpha:0.3}, 1000, "easeInOutSine")
                .to({alpha:1}, 1000, "easeInOutSine")
                .to({alpha:0.0}, 1000, "easeInOutSine");
//                .setLoop(true);
        }

        this.stage.label.tweener.wait(11000).fadeIn(10);

        // bar
        var bar = this.stage.bar;
        bar.animationFlag = false;
        bar.value = 0;
        bar.animationFlag = true;
        bar.animationTime = 100;

        var stage = this.stage;
        stage.alpha = 0.0;
        stage.tweener.clear().fadeIn(100).call(function() {
            if (param.assets) {
                var loader = tm.asset.Loader();
                loader.onload = function() {
                    stage.tweener.clear().wait(200).fadeOut(200).call(function() {
                        if (param.nextScene) {
                                this.app.replaceScene(param.nextScene());
                        }
                        var e = tm.event.Event("load");
                        this.fire(e);
                    }.bind(this));
                }.bind(this);

                loader.onprogress = function(e) {
                    // update bar
                    bar.value = e.progress*100;

                    // dispatch event
                    var event = tm.event.Event("progress");
                    event.progress = e.progress;
                    this.fire(event);
                }.bind(this);

                loader.load(param.assets);
            }
        }.bind(this));
    },
});
<commit_msg>LoadingScene変更<commit_after>/*
 *  LoadingScene.js
 *  2014/12/09
 *  @auther minimo
 *  This Program is MIT license.
 *
 */

tm.define("pb3.LoadingScene", {
    superClass: "tm.app.Scene",

    init: function(param) {
        this.superInit();

        this.fromJSON({
            children: {
                stage: {
                    type: "tm.display.CanvasElement",
                },
            }
        });

        this.stage.fromJSON({
            children: {
                bg: {
                    type: "tm.display.Shape",
                    init: [{width: param.width, height: param.height}],
                    originX: 0,
                    originY: 0,
                },
                label: {
                    type: "tm.display.Label",
                    text: "Asset read error!!",
                    x: param.width/2,
                    y: param.height/2-20,
                    align: "center",
                    baseline: "middle",
                    fontSize: 46,
                    shadowBlur: 4,
                    shadowColor: "hsl(190, 100%, 50%)",
                    alpha: 0,
                },
                bar: {
                    type: "tm.ui.Gauge",
                    init: [{
                        width: SC_W*0.4,
                        height: 10,
                        color: "blue",
                        bgColor: "rgba(20, 20, 20, 1)",
                        borderColor: "transparent",
                        borderWidth: 0,
                    }],
                    x: SC_W*0.3,
                    y: SC_H*0.5+20,
                },
            }
        });

        // bg
        var bg = this.stage.bg;
        bg.canvas.clearColor(param.bgColor);

        var text = "LOADING";
        var text_space = [0,31,31,30,20,20,30];
                        //L O  A  D  I  N  G
        var spc = 0;
        for (var i = 0; i < text.length; i++) {
            spc += text_space[i];
            var x = param.width/2-84+spc;
            var y = param.height/2-20;

            var base = tm.app.Object2D()
                .addChildTo(this.stage)
                .setPosition(x, y);
            base.tweener
                .wait(500+150*i)
                .moveBy(0, -30, 300, "easeOutSine")
                .moveBy(0, 30, 600, "easeOutBounce")
                .wait(1000)
                .moveBy(0, -30, 300, "easeOutSine")
                .moveBy(0, 30, 600, "easeOutBounce")
                .wait(1000)
                .moveBy(0, -30, 300, "easeOutSine")
                .moveBy(0, 30, 600, "easeOutBounce")
                .wait(1000)
                .moveBy(0, -30, 300, "easeOutSine")
                .moveBy(0, 30, 600, "easeOutBounce")
                .wait(1000)
                .moveBy(0, -30, 300, "easeOutSine")
                .moveBy(0, 30, 600, "easeOutBounce")

            var chr = tm.display.Label(text.charAt(i), 30)
                .addChildTo(base)
                .setAlign("center")
                .setBaseline("middle")
                .setShadowBlur(4)
                .setShadowColor("hsl(190, 100%, 50%)");
            chr.tweener
                .to({alpha:0.3}, 1000, "easeInOutSine")
                .to({alpha:1}, 1000, "easeInOutSine")
                .to({alpha:0.3}, 1000, "easeInOutSine")
                .to({alpha:1}, 1000, "easeInOutSine")
                .to({alpha:0.3}, 1000, "easeInOutSine")
                .to({alpha:1}, 1000, "easeInOutSine")
                .to({alpha:0.3}, 1000, "easeInOutSine")
                .to({alpha:1}, 1000, "easeInOutSine")
                .to({alpha:0.3}, 1000, "easeInOutSine")
                .to({alpha:1}, 1000, "easeInOutSine")
                .to({alpha:0.0}, 1000, "easeInOutSine");
//                .setLoop(true);
        }

        this.stage.label.tweener.wait(11000).fadeIn(10);

        // bar
        var bar = this.stage.bar;
        bar.animationFlag = false;
        bar.value = 0;
        bar.animationFlag = true;
        bar.animationTime = 100;

        var stage = this.stage;
        stage.alpha = 0.0;
        stage.tweener.clear().fadeIn(100).call(function() {
            if (param.assets) {
                var loader = tm.asset.Loader();
                loader.onload = function() {
                    stage.tweener.clear().wait(200).fadeOut(200).call(function() {
                        if (param.nextScene) {
                                this.app.replaceScene(param.nextScene());
                        }
                        var e = tm.event.Event("load");
                        this.fire(e);
                    }.bind(this));
                }.bind(this);

                loader.onprogress = function(e) {
                    // update bar
                    bar.value = e.progress*100;

                    // dispatch event
                    var event = tm.event.Event("progress");
                    event.progress = e.progress;
                    this.fire(event);
                }.bind(this);

                loader.load(param.assets);
            }
        }.bind(this));
    },
});
<|endoftext|>


<commit_before>const addPaintOptions = (options, layer) => {
  if (layer.isPoint) {
    options['type'] = 'circle'
    options['paint'] = {
      'circle-radius': [
        'interpolate',
        ['exponential', 1],
        ['zoom'],
        0, 1.5,
        6, 4
      ],
      'circle-color': layer.color,
      'circle-opacity': 0.7
    }
  } else {
    options['type'] = 'fill'
    options['paint'] = {
      'fill-color': layer.color,
      'fill-opacity': 0.8,
    }
  }
}

export default {
  methods: {
    addRasterTileLayer (layer) {
      this.map.addLayer({
        id: layer.id,
        type: 'raster',
        minzoom: 0,
        maxzoom: 22,
        source: {
          type: 'raster',
          tiles: [layer.url],
          tileSize: 256,
        },
        layout: {
          visibility: 'visible'
        }
      }, this.firstForegroundLayerId)
    },

    addRasterDataLayer(layer) {
      const options = {
        id: layer.id,
        source: {
          type: 'geojson',
          data: layer.url
        },
        layout: {
          visibility: 'visible'
        }
      }

      addPaintOptions(options, layer)
      console.log('Adding data layer:', layer, options, this.firstForegroundLayerId)
      this.map.addLayer(options, this.firstForegroundLayerId)
    },
  },
}
<commit_msg>Check whether a layer existing on the map before trying to add it<commit_after>const addPaintOptions = (options, layer) => {
  if (layer.isPoint) {
    options['type'] = 'circle'
    options['paint'] = {
      'circle-radius': [
        'interpolate',
        ['exponential', 1],
        ['zoom'],
        0, 1.5,
        6, 4
      ],
      'circle-color': layer.color,
      'circle-opacity': 0.7
    }
  } else {
    options['type'] = 'fill'
    options['paint'] = {
      'fill-color': layer.color,
      'fill-opacity': 0.8,
    }
  }
}

export default {

  methods: {
    addRasterTileLayer (layer) {
      if(!this.hasExistingMapLayer(layer.id)) {
        this.map.addLayer({
          id: layer.id,
          type: 'raster',
          minzoom: 0,
          maxzoom: 22,
          source: {
            type: 'raster',
            tiles: [layer.url],
            tileSize: 256,
          },
          layout: {
            visibility: 'visible'
          }
        }, this.firstForegroundLayerId)
      }
    },

    addRasterDataLayer(layer) {
      if(!this.hasExistingMapLayer(layer.id)) {
        const options = {
          id: layer.id,
          source: {
            type: 'geojson',
            data: layer.url
          },
          layout: {
            visibility: 'visible'
          }
        }

        addPaintOptions(options, layer)

        this.map.addLayer(options, this.firstForegroundLayerId)
      }
    },

    hasExistingMapLayer (id) {
      const existingMapLayer = this.map.getLayer(id)

      return typeof existingMapLayer !== 'undefined'
    }
  },
}
<|endoftext|>


<commit_before>'use strict';var _createClass=function(){function a(b,c){for(var e,d=0;d<c.length;d++)e=c[d],e.enumerable=e.enumerable||!1,e.configurable=!0,'value'in e&&(e.writable=!0),Object.defineProperty(b,e.key,e)}return function(b,c,d){return c&&a(b.prototype,c),d&&a(b,d),b}}();function _classCallCheck(a,b){if(!(a instanceof b))throw new TypeError('Cannot call a class as a function')}var Sandbox=function(){function Sandbox(){var a=0<arguments.length&&void 0!==arguments[0]?arguments[0]:null,b=1<arguments.length&&void 0!==arguments[1]?arguments[1]:null;_classCallCheck(this,Sandbox),this.globalContext=b||{},this.dom=a||document,this.globalContextProxy=new Proxy(this.globalContext,{get:function(c,d){var e=d in c?c[d]:window[d];return!(d in c)&&e instanceof Function&&(e=function(g){for(var h=[],j=0;j+1<arguments.length;j++)h[j]=arguments[j+1];return g.apply(this,h)}.bind(window,e)),e}.bind(window)}),this.domProxy=new Proxy(this.dom,{get:function(c,d){if('body'==d)return c;var e=d in c?c[d]:document[d];if(!(d in c)&&e instanceof Function)e=function(h){for(var j=[],k=0;k+1<arguments.length;k++)j[k]=arguments[k+1];return h.apply(this,j)}.bind(document,e);else if(e instanceof Function)var g=function(h){for(var j=[],k=0;k+1<arguments.length;k++)j[k]=arguments[k+1];return h.apply(this,j)}.bind(c,e);return e='getElementsByTagName'==d?function(h,j){return'body'==j?[this]:h.apply(this,arguments)}.bind(c,g):g,e}.bind(document),set:function set(c,d,e){var g=function(){this[d]=e}.bind(c);return g(),!0}})}return _createClass(Sandbox,[{key:'execCode',value:function execCode(code){var newcontext=1<arguments.length&&void 0!==arguments[1]?arguments[1]:this.globalContext;(function(window,document,code){var globalScopeInit='';for(var x in window)globalScopeInit+='var '+x+' = window["'+x+'"];';eval(globalScopeInit+code)}).bind(newcontext)(this.globalContextProxy,this.domProxy,code)}},{key:'execFunction',value:function execFunction(func,args){var newcontext=2<arguments.length&&void 0!==arguments[2]?arguments[2]:this.globalContext;if(!(func instanceof Function))throw new Exception('Object passed is not a function');return function(window,document,func){var globalScopeInit='';for(var x in window)globalScopeInit+='var '+x+' = window["'+x+'"];';var func_str=func.toString();return func_str.startsWith('function')||(func_str='function '+func_str),eval(globalScopeInit+'('+func_str+'.bind(this)).apply(this,args)')}.bind(newcontext)(this.globalContextProxy,this.domProxy,func,args)}}]),Sandbox}();<commit_msg>updated js-sandbox.min.js<commit_after>'use strict';var _createClass=function(){function a(b,c){for(var e,d=0;d<c.length;d++)e=c[d],e.enumerable=e.enumerable||!1,e.configurable=!0,'value'in e&&(e.writable=!0),Object.defineProperty(b,e.key,e)}return function(b,c,d){return c&&a(b.prototype,c),d&&a(b,d),b}}();function _classCallCheck(a,b){if(!(a instanceof b))throw new TypeError('Cannot call a class as a function')}var Sandbox=function(){function Sandbox(){var a=0<arguments.length&&void 0!==arguments[0]?arguments[0]:null,b=1<arguments.length&&void 0!==arguments[1]?arguments[1]:null;_classCallCheck(this,Sandbox),this.globalContext=b||{},this.dom=a||document,this.domProxy=new Proxy(this.dom,{get:function(c,d){if('body'==d)return c;if('rootNode'==d)return c;var e;if(e='nodeName'==d||'nodeType'==d||'ownerDocument'==d||'parentElement'==d?document[d]:d in c?c[d]:document[d],!(d in c)&&e instanceof Function)e=function(h){for(var j=[],k=0;k+1<arguments.length;k++)j[k]=arguments[k+1];return h.apply(this,j)}.bind(document,e);else if(e instanceof Function){var g=function(h){for(var j=[],k=0;k+1<arguments.length;k++)j[k]=arguments[k+1];return h.apply(this,j)}.bind(c,e);e='getElementsByTagName'==d?function(h,j){return'body'==j?[this]:h.apply(this,arguments)}.bind(c,g):g}return e}.bind(document),set:function set(c,d,e){var g=function(){this[d]=e}.bind(c);return g(),!0}}),this.globalContextProxy=new Proxy(this.globalContext,{get:function(c,d,e){if('document'==e)return c.domProxy;var g=e in d?d[e]:window[e];return!(e in d)&&g instanceof Function&&(g=function(h){for(var j=[],k=0;k+1<arguments.length;k++)j[k]=arguments[k+1];return h.apply(this,j)}.bind(window,g)),g}.bind(window,this)})}return _createClass(Sandbox,[{key:'execCode',value:function execCode(code){var newcontext=1<arguments.length&&void 0!==arguments[1]?arguments[1]:this.globalContext;(function(window,document,code){var globalScopeInit='';for(var x in window)globalScopeInit+='var '+x+' = window["'+x+'"];';eval(globalScopeInit+code)}).bind(newcontext)(this.globalContextProxy,this.domProxy,code)}},{key:'execFunction',value:function execFunction(func,args){var newcontext=2<arguments.length&&void 0!==arguments[2]?arguments[2]:this.globalContext;if(!(func instanceof Function))throw new Exception('Object passed is not a function');return function(window,document,func){var globalScopeInit='';for(var x in window)globalScopeInit+='var '+x+' = window["'+x+'"];';var func_str=func.toString();return func_str.startsWith('function')||(func_str='function '+func_str),eval(globalScopeInit+'('+func_str+'.bind(this)).apply(this,args)')}.bind(newcontext)(this.globalContextProxy,this.domProxy,func,args)}}]),Sandbox}();<|endoftext|>


<commit_before>Math.randomRange = function(max, min){
  min = min || 0;

  return Math.round(Math.random() * (max - min)) + min;
};

var parent;
var camera = new THREE.PerspectiveCamera(40, 1.5, 1, 10000);
camera.position.y = 0;
camera.position.z = 3000;
//name$append : 템플릿 'name'을 사용하며, 이름 뒤에 'append'를 붙임
//name#replace: 템플릿 'name'을 사용하며, 이름이 'replace'로 출력됨

var cards = {
	1: {
		1: { // 1-1
	  		1: 'korean$b',
	  		2: 'career',
	  		3: 'physics',
	  		4: 'english',
	  		5: 'mathematics_i',
	  		6: 'korean$a',
	  		7: 'club#학급',
	  		8: 'club#학급'
		}
  },
  2: {
	  1: { // 2-1
		  	1: 'korean$b',
		  	2: 'career',
		  	3: 'physics',
		  	4: 'english',
		  	5: 'mathematics_i',
		  	6: 'korean$a',
		  	7: 'club#학급',
		  	8: 'club#학급'
		}
	},
	3: {
  	  1: { // 3-1
  		  	1: 'korean$b',
  		  	2: 'career',
  		  	3: 'physics',
  		  	4: 'english',
  		  	5: 'mathematics_i',
  		  	6: 'korean$a',
  		  	7: 'club#학급',
  		  	8: 'club#학급'
  		}
  	}
};

var scene = {};

var renderer = {};

_.forEach(cards, function(v, grade){
	renderer[grade] = new THREE.CSS3DRenderer();
	scene[grade] = new THREE.Scene();
});

var cardObjects = {};
var moveTarget = {};
var animateDuration = 2000;

var width = undefined;
var height = undefined;

var cardWidth = 350; // default : 300
var cardHeight = 650; // default : 600
var cardsPerRow = undefined;
var cardsRow = undefined;
var cardZ = 1000;

function animate(){
  requestAnimationFrame(animate);
  TWEEN.update();
}

function startAnimation(grade){
  TWEEN.removeAll();
  _.forEach(cardObjects[grade], function(object, kClass){
    var target = moveTarget[grade][kClass];

    new TWEEN.Tween(object.position)
      .to(target.position, animateDuration)
      .easing(TWEEN.Easing.Quintic.In)
      .start();

    new TWEEN.Tween(object.rotation)
      .to(target.rotation, animateDuration)
      .easing(TWEEN.Easing.Quintic.In)
      .start();
  });

  new TWEEN.Tween(this)
    .to({}, animateDuration)
    .onUpdate(function(){
      renderer[grade].render(scene[grade], camera);
    })
    .start();
}

function addCards(){
	_.forEach(cards, function(v1, grade){
		cardObjects[grade] = {};
		_.forEach(cards[grade], function(v2, kClass){
			var elem = $(document.createElement('div')).addClass('gg card')
			  .append(
				$(document.createElement('h2')).html(grade + ' - ' + kClass)
			  );

			var object = new THREE.CSS3DObject(elem.get(0));

			object.position.x = Math.randomRange(-300, 300);
			object.position.y = Math.randomRange(300, -300);
			object.position.z = Math.randomRange(-300, 300);

			object.rotateX(Math.randomRange(0, 360));
			object.rotateY(Math.randomRange(0, 360));
			object.rotateZ(Math.randomRange(0, 360));
			cardObject[grade].gradeCard = object;

			cardObject[grade][kClass] = {};
			_.forEach(cards[grade][kClass], function(v, period){
				var match = v.match(/^([^\s$#]+)(?:(\$|#)([^]+))?$/);
			    if(match){
			      v = match[1];
			    }

			    var text = assigned[v].text;

			    if(match && match[2] && match[3]){
			      text = (match[2] === '$') ? text + match[3] : match[3];
			    }

			    var elem = $(document.createElement('div')).addClass('gg card')
			      .append(
			        $(document.createElement('h2'))
			          .append($(document.createElement('i')).addClass(assigned[v].icon))
			      )
			      .append(
			        $(document.createElement('h3')).text(period + '교시 ' + text)
			      );

			    var object = new THREE.CSS3DObject(elem.get(0));

			    //Randomize Object position
			    /*
				  object.position.x = Math.randomRange(-300, 300);
			    object.position.y = Math.randomRange(300, -300);
			    object.position.z = Math.randomRange(-300, 300);

			    object.rotateX(Math.randomRange(0, 360));
			    object.rotateY(Math.randomRange(0, 360));
			    object.rotateZ(Math.randomRange(0, 360));
				*/ //TODO update period code

			    cardObjects[grade][kClass][period] = object;
			});
		});
	});
}

function writeMoveTarget(){
	_.forEach(cards, function(v1, grade){
		moveTarget[grade] = {};
		_.forEach(cards[grade], function(v2, kClass){
			var cardX = (kClass - 1) % Math.floor(cardsPerRow);
		    var cardY = Math.floor((kClass - 1) / Math.floor(cardsPerRow));
		    var parentWidth = parseInt(window.getComputedStyle(parent).width.replace(/[^0-9\.]/g, ''));
		    moveTarget[grade][kClass] = {
		      position: {
		        x: ((cardX) * cardWidth) - ((cardsPerRow + 1) * cardWidth / 2)  - (parentWidth - 640) / 4,
		        y: (((cardsRow - 1) / 2) - cardY) * (cardHeight / 2),
		        z: cardZ
		      },

		      rotation: {
		        x: 0,
		        y: 0,
		        z: 0
		      }
			};
		});
	});
}

function update(){
  width = parseInt(window.getComputedStyle(parent).width.replace(/[^0-9\.]/g, ''));
  height = 600;

  camera.aspect = width / height;
  camera.updateProjectionMatrix();
  _.forEach(cards, function(v1, grade){
	  renderer[grade].setSize(width, height);
  });

  cardsPerRow = width / (cardWidth / 2.24);
  if(cardsPerRow < 1) cardsPerRow = 1;

  cardsRow = Math.ceil(Object.keys(cards).length / cardsPerRow);
  writeMoveTarget();
}

function resize(){
  update();
  startAnimationAll();
}

animate();

$(document).ready(function(){
  parent = $('#top').get(0);
  update();
  addCards();

  _.forEach(cards, function(v, grade){
	  var renderView = $(renderer[grade].domElement);
	  $('#timetable-' + grade + 'grade').append(renderView);
  });
  startAnimationAll();
});

function startAnimationAll(){
	_.forEach(cards, function(v, grade){
		startAnimation(grade);
	});
}

$(window).resize(resize);
<commit_msg>Fixed layout not showing<commit_after>Math.randomRange = function(max, min){
  min = min || 0;

  return Math.round(Math.random() * (max - min)) + min;
};

var parent;
var camera = new THREE.PerspectiveCamera(40, 1.5, 1, 10000);
camera.position.y = 0;
camera.position.z = 3000;
//name$append : 템플릿 'name'을 사용하며, 이름 뒤에 'append'를 붙임
//name#replace: 템플릿 'name'을 사용하며, 이름이 'replace'로 출력됨

var cards = {
	1: {
		1: { // 1-1
	  		1: 'korean$b',
	  		2: 'career',
	  		3: 'physics',
	  		4: 'english',
	  		5: 'mathematics_i',
	  		6: 'korean$a',
	  		7: 'club#학급',
	  		8: 'club#학급'
		}
  },
  2: {
	  1: { // 2-1
		  	1: 'korean$b',
		  	2: 'career',
		  	3: 'physics',
		  	4: 'english',
		  	5: 'mathematics_i',
		  	6: 'korean$a',
		  	7: 'club#학급',
		  	8: 'club#학급'
		}
	},
	3: {
  	  1: { // 3-1
  		  	1: 'korean$b',
  		  	2: 'career',
  		  	3: 'physics',
  		  	4: 'english',
  		  	5: 'mathematics_i',
  		  	6: 'korean$a',
  		  	7: 'club#학급',
  		  	8: 'club#학급'
  		}
  	}
};

var scene = {};

var renderer = {};

_.forEach(cards, function(v, grade){
	renderer[grade] = new THREE.CSS3DRenderer();
	scene[grade] = new THREE.Scene();
});

var cardObjects = {};
var moveTarget = {};
var animateDuration = 2000;

var width = undefined;
var height = undefined;

var cardWidth = 350; // default : 300
var cardHeight = 650; // default : 600
var cardsPerRow = undefined;
var cardsRow = undefined;
var cardZ = 1000;

function animate(){
  requestAnimationFrame(animate);
  TWEEN.update();
}

function startAnimation(grade){
  _.forEach(cardObjects[grade], function(object, kClass){
    var target = moveTarget[grade][kClass];
	var object = object.classCard;

    new TWEEN.Tween(object.position)
      .to(target.position, animateDuration)
      .easing(TWEEN.Easing.Quintic.In)
      .start();

    new TWEEN.Tween(object.rotation)
      .to(target.rotation, animateDuration)
      .easing(TWEEN.Easing.Quintic.In)
      .start();
  });

  new TWEEN.Tween(this)
    .to({}, animateDuration)
    .onUpdate(function(){
      renderer[grade].render(scene[grade], camera);
    })
    .start();
}

function addCards(){
	_.forEach(cards, function(v1, grade){
		cardObjects[grade] = {};
		_.forEach(cards[grade], function(v2, kClass){
			var elem = $(document.createElement('div')).addClass('gg card')
			  .append(
				$(document.createElement('a')).append(
					$(document.createElement('h1')).html(grade + ' - ' + kClass)
				).on('click', function(){
					updateClass(grade, kClass);
				})
			  );

			var object = new THREE.CSS3DObject(elem.get(0));

			object.position.x = Math.randomRange(-300, 300);
			object.position.y = Math.randomRange(300, -300);
			object.position.z = Math.randomRange(-300, 300);

			object.rotateX(Math.randomRange(0, 360));
			object.rotateY(Math.randomRange(0, 360));
			object.rotateZ(Math.randomRange(0, 360));

			cardObjects[grade][kClass] = {};
			cardObjects[grade][kClass].classCard = object;
			scene[grade].add(object);

			_.forEach(cards[grade][kClass], function(v, period){
				var match = v.match(/^([^\s$#]+)(?:(\$|#)([^]+))?$/);
			    if(match){
			      v = match[1];
			    }

			    var text = assigned[v].text;

			    if(match && match[2] && match[3]){
			      text = (match[2] === '$') ? text + match[3] : match[3];
			    }

			    var elem = $(document.createElement('div')).addClass('gg card')
			      .append(
			        $(document.createElement('h2'))
			          .append($(document.createElement('i')).addClass(assigned[v].icon))
			      )
			      .append(
			        $(document.createElement('h3')).text(period + '교시 ' + text)
			      );

			    var object = new THREE.CSS3DObject(elem.get(0));

			    //Randomize Object position
			    /*
				  object.position.x = Math.randomRange(-300, 300);
			    object.position.y = Math.randomRange(300, -300);
			    object.position.z = Math.randomRange(-300, 300);

			    object.rotateX(Math.randomRange(0, 360));
			    object.rotateY(Math.randomRange(0, 360));
			    object.rotateZ(Math.randomRange(0, 360));
				*/ //TODO update period code

			    cardObjects[grade][kClass][period] = object;
			});
		});
	});
}

function updateClass(){
	//TODO show periods
}

function writeMoveTarget(){
	_.forEach(cards, function(v1, grade){
		moveTarget[grade] = {};
		_.forEach(cards[grade], function(v2, kClass){
			var cardX = (kClass - 1) % Math.floor(cardsPerRow);
		    var cardY = Math.floor((kClass - 1) / Math.floor(cardsPerRow));
		    var parentWidth = parseInt(window.getComputedStyle(parent).width.replace(/[^0-9\.]/g, ''));
		    moveTarget[grade][kClass] = {
		      position: {
		        x: ((cardX) * cardWidth) - ((cardsPerRow + 1) * cardWidth / 2)  - (parentWidth - 640) / 4,
		        y: (((cardsRow - 1) / 2) - cardY) * (cardHeight / 2),
		        z: cardZ
		      },

		      rotation: {
		        x: 0,
		        y: 0,
		        z: 0
		      }
			};
		});
	});
}

function update(){
  width = parseInt(window.getComputedStyle(parent).width.replace(/[^0-9\.]/g, ''));
  height = 600;

  camera.aspect = width / height;
  camera.updateProjectionMatrix();
  _.forEach(cards, function(v1, grade){
	  renderer[grade].setSize(width, height);
  });

  cardsPerRow = width / (cardWidth / 2.24);
  if(cardsPerRow < 1) cardsPerRow = 1;

  cardsRow = Math.ceil(Object.keys(cards).length / cardsPerRow);
  writeMoveTarget();
}

function resize(){
  update();
  startAnimationAll();
}

animate();

$(document).ready(function(){
  parent = $('#top').get(0);
  update();
  addCards();

  _.forEach(cards, function(v, grade){
	  var renderView = $(renderer[grade].domElement);
	  $('#timetable-' + grade + 'grade').append(renderView);
  });
  startAnimationAll();
});

function startAnimationAll(){
	TWEEN.removeAll();
	_.forEach(cards, function(v, grade){
		startAnimation(grade);
	});
}

$(window).resize(resize);
<|endoftext|>


<commit_before>
ngCubes.directive('cubesTable', ['$rootScope', function($rootScope) {
  return {
    restrict: 'EA',
    require: '^cubes',
    scope: {
      drilldown: '='
    },
    templateUrl: 'angular-cubes-templates/table.html',
    link: function(scope, element, attrs, cubesCtrl) {
      var model = null, query = {};
      scope.columns = [];
      scope.rows = [];
      scope.table = [];

      cubesCtrl.registerQueryProcessor(function(q, state) {
        return q;
      });

      $rootScope.$on(cubesCtrl.modelUpdate, function(event, m) {
        model = m;
      });

      $rootScope.$on(cubesCtrl.dataUpdate, function(event, data) {
        console.log('data recv', data);
      });

      cubesCtrl.init({
        rows: {label: 'Rows', multiple: true},
        columns: {label: 'Columns', multiple: true},
      });
    }
  };
}]);

<commit_msg>multiply number of entries for crosstab<commit_after>
ngCubes.directive('cubesTable', ['$rootScope', function($rootScope) {
  return {
    restrict: 'EA',
    require: '^cubes',
    scope: {
      drilldown: '='
    },
    templateUrl: 'angular-cubes-templates/table.html',
    link: function(scope, element, attrs, cubesCtrl) {
      var model = null, query = {};
      scope.columns = [];
      scope.rows = [];
      scope.table = [];

      cubesCtrl.registerQueryProcessor(function(q, state) {
        state.rows = asArray(state.rows);
        state.columns = asArray(state.columns);

        var multiplier = Math.max((state.rows.length + 1) * (state.columns.length + 1), 1);
        q.pagesize = q.pagesize * multiplier;
        return q;
      });

      $rootScope.$on(cubesCtrl.modelUpdate, function(event, m) {
        model = m;
      });

      $rootScope.$on(cubesCtrl.dataUpdate, function(event, data) {
        console.log('data recv', data);
      });

      cubesCtrl.init({
        rows: {label: 'Rows', multiple: true},
        columns: {label: 'Columns', multiple: true},
      });
    }
  };
}]);

<|endoftext|>


<commit_before>(function () {

	window.repwho = {};

	repwho.go = function (mode) {
		var url = "https://reps.mozilla.org/api/v1/rep/?offset=0&limit=0&callback=?&group=" + mode;
		$.getJSON( url,
			function (data) {
				repwho.data = data;
				repwho.pick();
				repwho.pushDOM();
				$("#rep_names button").shuffle();
			},
			function (error) {
				console.log(error);
			}
		)
	};

	repwho.pick = function () {
		repwho.id = Math.floor(Math.random() * repwho.data.objects.length);
		repwho.rep = repwho.data.objects[repwho.id];
	};

	repwho.random = function () {
		repwho.tmp = Math.floor(Math.random() * repwho.data.objects.length);
		if (repwho.tmp == repwho.id) repwho.random();
		return repwho.tmp;
	};

	repwho.pushDOM = function () {
		$("#rep_image").attr("data-id", repwho.id).attr("src", repwho.rep.profile.avatar_url + "&size=256");
		$("#rep_names").html(
			"<button id='richtig'>"+ repwho.rep.fullname +"</button>" +
			"<button class='falsch'>"+ repwho.data.objects[repwho.random()].fullname +"</button>" +
			"<button class='falsch'>"+ repwho.data.objects[repwho.random()].fullname +"</button>" +
			"<button class='falsch'>"+ repwho.data.objects[repwho.random()].fullname +"</button>"
		);
	};

	repwho.reset = function () {
		$("#mode_selector").show();
		$("#rep_quiz").hide();
		$("#quiz_result").hide();
		$("#rep_image").removeAttr("src");
		$("#rep_names").html("");
		$("#baDumTss").html("");
	};

	$("#mode_selector").on("click", "button", function () {
		window.mode = $(this).data("mode");
		repwho.go(mode);
		$("#mode_selector").hide();
		$("#rep_quiz").show();
	});

	$("#rep_names").on("click", "#richtig", function () {
		$("#rep_quiz").hide();
		$("#baDumTss").html("Yeehaw! xD");
		$("#quiz_result").show();
		window.setTimeout(repwho.reset, 2000);
	}).on("click", ".falsch", function () {
		$("#rep_quiz").hide();
		$("#baDumTss").html("Booooooo! :P");
		$("#quiz_result").show();
		window.setTimeout(repwho.reset, 2000);
	});
})();

(function($){

	$.fn.shuffle = function() {

		var allElems = this.get(),
			getRandom = function(max) {
				return Math.floor(Math.random() * max);
			},
			shuffled = $.map(allElems, function(){
				var random = getRandom(allElems.length),
					randEl = $(allElems[random]).clone(true)[0];
				allElems.splice(random, 1);
				return randEl;
			});

		this.each(function(i){
			$(this).replaceWith($(shuffled[i]));
		});

		return $(shuffled);
	};

})(jQuery);
<commit_msg>Caching responses [not on localStorage yet]<commit_after>(function () {

	window.repwho = {};

	repwho.go = function (mode) {
		repwho.mode = mode;
		if (!repwho[mode]) {
			var url = "https://reps.mozilla.org/api/v1/rep/?offset=0&limit=0&callback=?&group=" + mode;
			$.getJSON( url,
				function (data) {
					repwho[mode] = data;
					repwho.repeat();
				},
				function (error) {
					console.log(error);
				}
			)
		} else repwho.repeat();
	};

	repwho.pick = function () {
		repwho.id = Math.floor(Math.random() * repwho[repwho.mode].objects.length);
		repwho.rep = repwho[repwho.mode].objects[repwho.id];
	};

	repwho.random = function () {
		repwho.tmp = Math.floor(Math.random() * repwho[repwho.mode].objects.length);
		if (repwho.tmp == repwho.id) repwho.random();
		return repwho.tmp;
	};

	repwho.pushDOM = function () {
		$("#rep_image").attr("data-id", repwho.id).attr("src", repwho.rep.profile.avatar_url + "&size=256");
		$("#rep_names").html(
			"<button id='richtig'>"+ repwho.rep.fullname +"</button>" +
			"<button class='falsch'>"+ repwho[repwho.mode].objects[repwho.random()].fullname +"</button>" +
			"<button class='falsch'>"+ repwho[repwho.mode].objects[repwho.random()].fullname +"</button>" +
			"<button class='falsch'>"+ repwho[repwho.mode].objects[repwho.random()].fullname +"</button>"
		);
	};

	repwho.reset = function () {
		repwho.repeat();
		$("#rep_quiz").show();
		$("#baDumTss").html("");
		$("#quiz_result").hide();
		$("#rep_image").attr("src", "");
	};

	repwho.repeat = function () {
		repwho.pick();
		repwho.pushDOM();
		$("#rep_names button").shuffle();
	}

	$("#mode_selector").on("click", "button", function () {
		window.mode = $(this).data("mode");
		repwho.go(mode);
		$("#mode_selector").hide();
		$("#rep_quiz").show();
	});

	$("#rep_names").on("click", "#richtig", function () {
		$("#rep_quiz").hide();
		$("#baDumTss").html("Yeehaw! xD");
		$("#quiz_result").show();
		window.setTimeout(repwho.reset, 2000);
	}).on("click", ".falsch", function () {
		$("#rep_quiz").hide();
		$("#baDumTss").html("Booooooo! :P");
		$("#quiz_result").show();
		window.setTimeout(repwho.reset, 2000);
	});
})();

(function($){

	$.fn.shuffle = function() {

		var allElems = this.get(),
			getRandom = function(max) {
				return Math.floor(Math.random() * max);
			},
			shuffled = $.map(allElems, function(){
				var random = getRandom(allElems.length),
					randEl = $(allElems[random]).clone(true)[0];
				allElems.splice(random, 1);
				return randEl;
			});

		this.each(function(i){
			$(this).replaceWith($(shuffled[i]));
		});

		return $(shuffled);
	};

})(jQuery);
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2012 Intel Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/*****************************************************************************/

var cloudeebus = window.cloudeebus = {};

cloudeebus.reset = function() {
	cloudeebus.sessionBus = null;
	cloudeebus.systemBus = null;
	cloudeebus.wampSession = null;
	cloudeebus.uri = null;
};

cloudeebus.log = function(msg) {
};

cloudeebus.connect = function(uri, successCB, errorCB) {
	cloudeebus.reset();
	cloudeebus.uri = uri;

	function onWAMPSessionConnectedCB(session) {
		cloudeebus.wampSession = session;
		cloudeebus.sessionBus = new cloudeebus.BusConnection("session", cloudeebus.wampSession);
		cloudeebus.systemBus = new cloudeebus.BusConnection("system", cloudeebus.wampSession);
		cloudeebus.log("Connected to " + cloudeebus.uri);
		if (successCB)
			successCB();
	}

	function onWAMPSessionErrorCB(code, reason) {
		if (code == ab.CONNECTION_UNSUPPORTED) {
			cloudeebus.log("Browser is not supported");
		}
		else {
			cloudeebus.log("Failed to open session, code = " + code + ", reason = " + reason);
		}
		if (errorCB)
			errorCB(reason);
	}

	return ab.connect(cloudeebus.uri, onWAMPSessionConnectedCB, onWAMPSessionErrorCB);
};

cloudeebus.SessionBus = function() {
	return cloudeebus.sessionBus;
};

cloudeebus.SystemBus = function() {
	return cloudeebus.systemBus;
};

/*****************************************************************************/

cloudeebus.BusConnection = function(name, session) {
	this.name = name;
	this.wampSession = session;
	return this;
};

cloudeebus.BusConnection.prototype.getObject = function(busName, objectPath, introspectCB, errorCB) {
	var proxy = new cloudeebus.ProxyObject(this.wampSession, this, busName, objectPath);
	if (introspectCB)
		proxy._introspect(introspectCB, errorCB);
	return proxy;
};

/*****************************************************************************/

cloudeebus.ProxyObject = function(session, busConnection, busName, objectPath) {
	this.wampSession = session;
	this.busConnection = busConnection;
	this.busName = busName;
	this.objectPath = objectPath;
	return this;
};

cloudeebus.ProxyObject.prototype._introspect = function(successCB, errorCB) {

	var self = this;

	function getAllPropertiesSuccessCB(props) {
		for (var prop in props)
			self[prop] = props[prop];
		if (self.propInterfaces.length > 0)
		    self.callMethod("org.freedesktop.DBus.Properties",
				"GetAll",
				[self.propInterfaces.pop()],
				getAllPropertiesSuccessCB,
				errorCB);
		else {
			self.propInterfaces = null;
			if (successCB)
				successCB(self);
		}
	}

	function introspectSuccessCB(str) {
		var parser = new DOMParser();
		var xmlDoc = parser.parseFromString(str, "text/xml");
		var interfaces = xmlDoc.getElementsByTagName("interface");
		self.propInterfaces = [];
		var supportDBusProperties = false;
		for (var i=0; i < interfaces.length; i++) {
			var ifName = interfaces[i].attributes.getNamedItem("name").value;
			if (ifName == "org.freedesktop.DBus.Properties")
				supportDBusProperties = true;
			var hasProperties = false;
			var ifChild = interfaces[i].firstChild;
			while (ifChild) {
				if (ifChild.nodeName == "method") {
					var nArgs = 0;
					var metChild = ifChild.firstChild;
					while (metChild) {
						if (metChild.nodeName == "arg" &&
							metChild.attributes.getNamedItem("direction").value == "in")
								nArgs++;
						metChild = metChild.nextSibling;
					}
					self._addMethod(ifName,
							ifChild.attributes.getNamedItem("name").value,
							nArgs);
				}
				else if (ifChild.nodeName == "property") {
					if (!hasProperties)
						self.propInterfaces.push(ifName);
					hasProperties = true;
				}
				ifChild = ifChild.nextSibling;
			}
		}
		if (supportDBusProperties && self.propInterfaces.length > 0) {
		    self.callMethod("org.freedesktop.DBus.Properties",
				"GetAll",
				[self.propInterfaces.pop()],
				getAllPropertiesSuccessCB,
				errorCB);
		}
		else {
			self.propInterfaces = null;
			if (successCB)
				successCB(self);
		}
	}

    // call Introspect on self
    self.callMethod("org.freedesktop.DBus.Introspectable", "Introspect", [], introspectSuccessCB, errorCB);
};

cloudeebus.ProxyObject.prototype._addMethod = function(ifName, method, nArgs) {

	var self = this;

	self[method] = function() {
		if (arguments.length < nArgs || arguments.length > nArgs + 2)
			throw "Error: method " + method + " takes " + nArgs + " parameters, got " + arguments.length + ".";
		var args = [];
		var successCB = null;
		var errorCB = null;
		for (var i=0; i < nArgs; i++ )
			args.push(arguments[i]);
		if (arguments.length > nArgs)
			successCB = arguments[nArgs];
		if (arguments.length > nArgs + 1)
			errorCB = arguments[nArgs + 1];
		self.callMethod(ifName, method, args, successCB, errorCB);
	};

};

cloudeebus.ProxyObject.prototype.callMethod = function(ifName, method, args, successCB, errorCB) {

	var self = this;

	function callMethodSuccessCB(str) {
		if (successCB)
			successCB.apply(self, JSON.parse(str));
	}

	function callMethodErrorCB(error) {
		cloudeebus.log("Error calling method: " + method + " on object: " + self.objectPath + " : " + error.desc);
		if (errorCB)
			errorCB(error.desc);
	}

    var arglist = [
		self.busConnection.name,
		self.busName,
		self.objectPath,
		ifName,
		method,
		JSON.stringify(args)
	];

    // call dbusSend with bus type, destination, object, message and arguments
    self.wampSession.call("dbusSend", arglist).then(callMethodSuccessCB, callMethodErrorCB);
};

cloudeebus.ProxyObject.prototype.connectToSignal = function(ifName, signal, successCB, errorCB) {

	var self = this;

	function signalHandler(id, data) {
		if (successCB)
			successCB.apply(self, JSON.parse(data));
	}

	function connectToSignalSuccessCB(str) {
		try {
			self.wampSession.subscribe(str, signalHandler);
		}
		catch (e) {
			cloudeebus.log("Subscribe error: " + e);
		}
	}

	function connectToSignalErrorCB(error) {
		cloudeebus.log("Error connecting to signal: " + signal + " on object: " + self.objectPath + " : " + error.desc);
		if (errorCB)
			errorCB(error.desc);
	}

    var arglist = [
		self.busConnection.name,
		self.busName,
		self.objectPath,
		ifName,
		signal
	];

    // call dbusSend with bus type, destination, object, message and arguments
    self.wampSession.call("dbusRegister", arglist).then(connectToSignalSuccessCB, connectToSignalErrorCB);
};

cloudeebus.ProxyObject.prototype.disconnectSignal = function(ifName, signal) {
	try {
		this.wampSession.unsubscribe(this.busName + "#" + this.objectPath + "#" + ifName + "#" + signal);
	}
	catch (e) {
		cloudeebus.log("Unsubscribe error: " + e);
	}
};
<commit_msg>update cloudeebus js lib<commit_after>/******************************************************************************
 * Copyright 2012 Intel Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/*****************************************************************************/

var cloudeebus = window.cloudeebus = {};

cloudeebus.reset = function() {
	cloudeebus.sessionBus = null;
	cloudeebus.systemBus = null;
	cloudeebus.wampSession = null;
	cloudeebus.uri = null;
};

cloudeebus.log = function(msg) {
};

cloudeebus.connect = function(uri, successCB, errorCB) {
	cloudeebus.reset();
	cloudeebus.uri = uri;

	function onWAMPSessionConnectedCB(session) {
		cloudeebus.wampSession = session;
		cloudeebus.sessionBus = new cloudeebus.BusConnection("session", cloudeebus.wampSession);
		cloudeebus.systemBus = new cloudeebus.BusConnection("system", cloudeebus.wampSession);
		cloudeebus.log("Connected to " + cloudeebus.uri);
		if (successCB)
			successCB();
	}

	function onWAMPSessionErrorCB(code, reason) {
		if (code == ab.CONNECTION_UNSUPPORTED) {
			cloudeebus.log("Browser is not supported");
		}
		else {
			cloudeebus.log("Failed to open session, code = " + code + ", reason = " + reason);
		}
		if (errorCB)
			errorCB(reason);
	}

	return ab.connect(cloudeebus.uri, onWAMPSessionConnectedCB, onWAMPSessionErrorCB);
};

cloudeebus.SessionBus = function() {
	return cloudeebus.sessionBus;
};

cloudeebus.SystemBus = function() {
	return cloudeebus.systemBus;
};

/*****************************************************************************/

cloudeebus.BusConnection = function(name, session) {
	this.name = name;
	this.wampSession = session;
	return this;
};

cloudeebus.BusConnection.prototype.getObject = function(busName, objectPath, introspectCB, errorCB) {
	var proxy = new cloudeebus.ProxyObject(this.wampSession, this, busName, objectPath);
	if (introspectCB)
		proxy._introspect(introspectCB, errorCB);
	return proxy;
};

/*****************************************************************************/

cloudeebus.ProxyObject = function(session, busConnection, busName, objectPath) {
	this.wampSession = session;
	this.busConnection = busConnection;
	this.busName = busName;
	this.objectPath = objectPath;
	return this;
};

cloudeebus.ProxyObject.prototype._introspect = function(successCB, errorCB) {

	var self = this;

	function getAllPropertiesSuccessCB(props) {
		for (var prop in props)
			self[prop] = props[prop];
		if (self.propInterfaces.length > 0)
			self.callMethod("org.freedesktop.DBus.Properties",
				"GetAll",
				[self.propInterfaces.pop()],
				getAllPropertiesSuccessCB,
				errorCB);
		else {
			self.propInterfaces = null;
			if (successCB)
				successCB(self);
		}
	}

	function introspectSuccessCB(str) {
		var parser = new DOMParser();
		var xmlDoc = parser.parseFromString(str, "text/xml");
		var interfaces = xmlDoc.getElementsByTagName("interface");
		self.propInterfaces = [];
		var supportDBusProperties = false;
		for (var i=0; i < interfaces.length; i++) {
			var ifName = interfaces[i].attributes.getNamedItem("name").value;
			if (ifName == "org.freedesktop.DBus.Properties")
				supportDBusProperties = true;
			var hasProperties = false;
			var ifChild = interfaces[i].firstChild;
			while (ifChild) {
				if (ifChild.nodeName == "method") {
					var nArgs = 0;
					var metChild = ifChild.firstChild;
					while (metChild) {
						if (metChild.nodeName == "arg" &&
							metChild.attributes.getNamedItem("direction").value == "in")
								nArgs++;
						metChild = metChild.nextSibling;
					}
					self._addMethod(ifName,
							ifChild.attributes.getNamedItem("name").value,
							nArgs);
				}
				else if (ifChild.nodeName == "property") {
					if (!hasProperties)
						self.propInterfaces.push(ifName);
					hasProperties = true;
				}
				ifChild = ifChild.nextSibling;
			}
		}
		if (supportDBusProperties && self.propInterfaces.length > 0) {
			self.callMethod("org.freedesktop.DBus.Properties",
				"GetAll",
				[self.propInterfaces.pop()],
				getAllPropertiesSuccessCB,
				errorCB);
		}
		else {
			self.propInterfaces = null;
			if (successCB)
				successCB(self);
		}
	}

	// call Introspect on self
	self.callMethod("org.freedesktop.DBus.Introspectable", "Introspect", [], introspectSuccessCB, errorCB);
};

cloudeebus.ProxyObject.prototype._addMethod = function(ifName, method, nArgs) {

	var self = this;

	self[method] = function() {
		if (arguments.length < nArgs || arguments.length > nArgs + 2)
			throw "Error: method " + method + " takes " + nArgs + " parameters, got " + arguments.length + ".";
		var args = [];
		var successCB = null;
		var errorCB = null;
		for (var i=0; i < nArgs; i++ )
			args.push(arguments[i]);
		if (arguments.length > nArgs)
			successCB = arguments[nArgs];
		if (arguments.length > nArgs + 1)
			errorCB = arguments[nArgs + 1];
		self.callMethod(ifName, method, args, successCB, errorCB);
	};

};

cloudeebus.ProxyObject.prototype.callMethod = function(ifName, method, args, successCB, errorCB) {

	var self = this;

	function callMethodSuccessCB(str) {
		if (successCB)
			successCB.apply(self, JSON.parse(str));
	}

	function callMethodErrorCB(error) {
		cloudeebus.log("Error calling method: " + method + " on object: " + self.objectPath + " : " + error.desc);
		if (errorCB)
			errorCB(error.desc);
	}

	var arglist = [
		self.busConnection.name,
		self.busName,
		self.objectPath,
		ifName,
		method,
		JSON.stringify(args)
	];

	// call dbusSend with bus type, destination, object, message and arguments
	self.wampSession.call("dbusSend", arglist).then(callMethodSuccessCB, callMethodErrorCB);
};

cloudeebus.ProxyObject.prototype.connectToSignal = function(ifName, signal, successCB, errorCB) {

	var self = this;

	function signalHandler(id, data) {
		if (successCB)
			successCB.apply(self, JSON.parse(data));
	}

	function connectToSignalSuccessCB(str) {
		try {
			self.wampSession.subscribe(str, signalHandler);
		}
		catch (e) {
			cloudeebus.log("Subscribe error: " + e);
		}
	}

	function connectToSignalErrorCB(error) {
		cloudeebus.log("Error connecting to signal: " + signal + " on object: " + self.objectPath + " : " + error.desc);
		if (errorCB)
			errorCB(error.desc);
	}

	var arglist = [
		self.busConnection.name,
		self.busName,
		self.objectPath,
		ifName,
		signal
	];

	// call dbusSend with bus type, destination, object, message and arguments
	self.wampSession.call("dbusRegister", arglist).then(connectToSignalSuccessCB, connectToSignalErrorCB);
};

cloudeebus.ProxyObject.prototype.disconnectSignal = function(ifName, signal) {
	try {
		this.wampSession.unsubscribe(this.busName + "#" + this.objectPath + "#" + ifName + "#" + signal);
	}
	catch (e) {
		cloudeebus.log("Unsubscribe error: " + e);
	}
};
<|endoftext|>


<commit_before>//Resize event
jviz.modules.karyoviewer.prototype.resize = function()
{
  //Set the canvas width
  //this._canvas.el.width(this._width);

  //Set the canvas height
  this._canvas.el.height(this._height);

  //Resize the canvas
  this._canvas.el.resize();

  //Save the full width
  this._width = this._canvas.el.width();

  //Save the full height
  //this._height = this._canvas.el.height();

  //Set to resize the chromosomes data
  this._chromosomes.resized = false;

  //Set to resize the features data
  this._features.resized = false;

  //Exit
  return this;
};
<commit_msg>js/resize.js: minor changes<commit_after>//Resize event
jviz.modules.karyoviewer.prototype.resize = function()
{
  //Set the canvas width
  //this._canvas.el.width(this._width);

  //Resize the canvas
  this._canvas.el.resize();

  //Save the full width
  this._width = this._canvas.el.width();

  //Save the full height
  //this._height = this._canvas.el.height();

  //Set to resize the block object
  this._block.resized = false;

  //Set to resize the chromosomes data
  this._chromosomes.resized = false;

  //Set to resize the features data
  this._features.resized = false;

  //Exit
  return this;
};
<|endoftext|>


<commit_before>describe('product controller', function() {

	var productCtrl;
  var scope;
	var data = [{title:"Mixer", price: "199.99 USD", Images:[{PrimaryImage:[{image:"img.jpg"}]}],CustomerReview: [{consolidatedOverallRating:5,Pro:[{overallRating:5,datePosted:"11/25/2016"}],Con:[{overallRating:5,datePosted:"11/25/2016"}]}]}];

  beforeEach(module('tgtApp'));
  beforeEach(module('tgtApp.prdt_detl'));
  beforeEach(inject(function ($controller, $rootScope,_dataService_,_$q_) {
		$q = _$q_;
		deferred = _$q_.defer();
    scope = $rootScope.$new();
    mockDataSvc=_dataService_;
  	spyOn(mockDataSvc,'getItems').and.returnValue(deferred.promise);
    productCtrl = $controller('prdt_detl_ctrl', {
            $scope: scope,
            dataService: mockDataSvc
        });
    }));

  it('should be defined', function(){
  	deferred.resolve(data);
    scope.$apply();
    expect(productCtrl).toBeDefined();
  });

  it('methods should be defined', function(){
    expect(scope.changePrimaryImage).toBeDefined();
    expect(scope.plus).toBeDefined();
    expect(scope.minus).toBeDefined();
  });

  it('scope variables should be initialized', function(){
    deferred.resolve(data);
    scope.$apply();
    expect(scope.product).toEqual(data[0]);
    //rating widget variables
    expect(scope.max).toEqual(5);
    expect(scope.isReadonly).toBeTruthy();
    //quantity control variables
    expect(scope.qty).toEqual(1);
    expect(scope.minQty).toEqual(1);
    expect(scope.maxQty).toEqual(10);
    expect(scope.plusActive).toBeFalsy();
    expect(scope.minusActive).toBeTruthy();
    scope.plus();
    expect(scope.qty).toEqual(2);
    scope.minus();
    expect(scope.qty).toEqual(1);
    var i=1;
    while(i<=9)
    {
      scope.plus();
      i=i+1;
    }
    expect(scope.qty).toEqual(10);
    scope.$apply(); //scope.$digest()
    expect(scope.plusActive).toBeTruthy();
    /*
    expect(scope.primaryImage).toEqual(data[0].Images[0].PrimaryImage[0].image);
    expect(scope.overallRating).toEqual(data[0].CustomerReview[0].consolidatedOverallRating);
    expect(scope.proRating).toEqual(data[0].CustomerReview[0].Pro[0].overallRating);
    expect(scope.conRating).toEqual(data[0].CustomerReview[0].Con[0].overallRating);
    */
  });

});
<commit_msg>Update prdt_detl_controller.spec.js<commit_after>describe('product controller', function() {

	var productCtrl;
  	var scope;
	var data = [{title:"Mixer", price: "199.99 USD", Images:[{PrimaryImage:[{image:"img.jpg"}]}],CustomerReview: [{consolidatedOverallRating:5,Pro:[{overallRating:5,datePosted:"11/25/2016"}],Con:[{overallRating:5,datePosted:"11/25/2016"}]}]}];

  beforeEach(module('tgtApp'));
  beforeEach(module('tgtApp.prdt_detl'));
  beforeEach(inject(function ($controller, $rootScope,_dataService_,_$q_) {
		$q = _$q_;
		deferred = _$q_.defer();
    scope = $rootScope.$new();
    mockDataSvc=_dataService_;
  	spyOn(mockDataSvc,'getItems').and.returnValue(deferred.promise);
    productCtrl = $controller('prdt_detl_ctrl', {
            $scope: scope,
            dataService: mockDataSvc
        });
    }));

  it('should be defined', function(){
  	deferred.resolve(data);
    scope.$apply();
    expect(productCtrl).toBeDefined();
  });

  it('methods should be defined', function(){
    expect(scope.changePrimaryImage).toBeDefined();
    expect(scope.plus).toBeDefined();
    expect(scope.minus).toBeDefined();
  });

  it('scope variables should be initialized', function(){
    deferred.resolve(data);
    scope.$apply();
    expect(scope.product).toEqual(data[0]);
    //rating widget variables
    expect(scope.max).toEqual(5);
    expect(scope.isReadonly).toBeTruthy();
    //quantity control variables
    expect(scope.qty).toEqual(1);
    expect(scope.minQty).toEqual(1);
    expect(scope.maxQty).toEqual(10);
    expect(scope.plusActive).toBeFalsy();
    expect(scope.minusActive).toBeTruthy();
    scope.plus();
    expect(scope.qty).toEqual(2);
    scope.minus();
    expect(scope.qty).toEqual(1);
    var i=1;
    while(i<=9)
    {
      scope.plus();
      i=i+1;
    }
    expect(scope.qty).toEqual(10);
    scope.$apply(); //scope.$digest()
    expect(scope.plusActive).toBeTruthy();
    /*
    expect(scope.primaryImage).toEqual(data[0].Images[0].PrimaryImage[0].image);
    expect(scope.overallRating).toEqual(data[0].CustomerReview[0].consolidatedOverallRating);
    expect(scope.proRating).toEqual(data[0].CustomerReview[0].Pro[0].overallRating);
    expect(scope.conRating).toEqual(data[0].CustomerReview[0].Con[0].overallRating);
    */
  });

});
<|endoftext|>


<commit_before>function placeBsBtn() {
	var importBtn = "<button id='import' class='bs-btn bs-btn-default'>Import</button>";
	$("#import-1_wrapper").append(importBtn);

	$("#import.bs-btn").click(function () {
		var pokes = document.getElementsByClassName("import-team-text")[0].value;
    // var pokes = document.getElementsByClassName("import-team-text").value;
    // var Leder = $.csv.toArrays(pokes);
    console.log(pokes);
		addSets(pokes);
	});

}

function serialize(array, separator) {
	var text = "";
	for (var i = 0; i < array.length; i++) {
		if (i < array.length - 1) {
			text += array[i] + separator;
		} else {
			text += array[i];
		}
	}
	return text;
}

function addSets(pokes) {
	//var rows = pokes.split("\n");
	var currentRow;
	var currentPoke;
	var addedpokes = 0;

  //var pokes;
  var i;
  var j;
  var FPlacement = 0;
  var UPlacement = 0;
  var APlacement = 0;
  var Leder = $.csv.toArrays(pokes);
//var pokes = document.getElementsByClassName("import-team-text")[0].value;
  console.log(pokes);
  console.log(Leder);

  var Ffullout = [];
  var Ufullout = [];
  var Afullout = [];
  //loop the outer array
  for (var i = 0; i < Leder.length; i++) {
     var innerArrayLength = Leder[i].length;
     var userName = Leder[i][0];
     var userId = Leder[i][1];
     var streakLen = Leder[i][2];
     var url1 = Leder[i][3];
     var pokeAmount = Leder[i][4];

     var teamPokes = [];

     teamPokes[0] = Leder[i][5];
     teamPokes[1] = Leder[i][6];
     teamPokes[2] = Leder[i][7];
     teamPokes[3] = Leder[i][8];
     teamPokes[4] = Leder[i][9];
     teamPokes[5] = Leder[i][10];
    console.log(parseInt(pokeAmount))
     switch (parseInt(pokeAmount)) {
       case 1:
         var url1Text = teamPokes[0];
         break;
       case 2:
         var url1Text = teamPokes[0] + " / " + teamPokes[1];
         break;
       case 3:
         var url1Text = teamPokes[0] + " / " + teamPokes[1] + " / " + teamPokes[2];
         break;
       case 4:
         var url1Text = teamPokes[0] + " / " + teamPokes[1] + " / " + teamPokes[2] + " / " + teamPokes[3];
         break;
       case 5:
         var url1Text = teamPokes[0] + " / " + teamPokes[1] + " / " + teamPokes[2] + " / " + teamPokes[3] + " / " +teamPokes[4];
         break;
       case 6:
         var url1Text = teamPokes[0] + " / " + teamPokes[1] + " / " + teamPokes[2] + " / " + teamPokes[3] + " / " +teamPokes[4] + " / " + teamPokes[5];
         break;
     }

     var streakFlags = Leder[i][11];
     var finish = streakFlags.charAt(0);
     var url2 = Leder[i][12];
     var url2Text = Leder[i][13];
     var url3 = Leder[i][14];
     var url3Text = Leder[i][15];

     switch (finish) {
       case "F":
         var FPlacement = FPlacement + 1;
         var Fout_bbcode = "#" + FPlacement + ". " + "[b][user=" + userId + "]" + userName + "[/user][/b], ([b]" + streakLen + "[/b] - [url=" + url1 + "]" + url1Text + "[/url]"
         Ffullout[FPlacement] = Fout_bbcode;
         break;

       case "U":
         var UPlacement = UPlacement + 1;
         var Uout_bbcode = "#" + UPlacement + ". " + "[b][user=" + userId + "]" + userName + "[/user][/b], ([b]" + streakLen + "[/b] - [url=" + url1 + "]" + url1Text + "[/url]"
         Ufullout[UPlacement] = Uout_bbcode;
         break;
     }

     var APlacement = APlacement + 1;
     var Aout_bbcode = "#" + APlacement + ". " + "[b][user=" + userId + "]" + userName + "[/user][/b], ([b]" + streakLen + "[/b] - [url=" + url1 + "]" + url1Text + "[/url]"
     Afullout[APlacement] = Aout_bbcode;

     //var url1Text = teamPoke1 + " / " + teamPoke2 + " / " + teamPoke3 + " / " + teamPoke4;
    //console.log(userName, userId, streakLen, url1, teamPoke1, teamPoke2, teamPoke3, teamPoke4, streakFlags, url2, url2Text, url3, url3Text, url1Text);
    //var TestingTesting = userName + userId + streakLen + url1 + teamPoke1 + teamPoke2 + teamPoke3 + teamPoke4 + streakFlags + url2 + url2Text + url3 + url3Text + url1Text;
    //console.log(TestingTesting);

     //document.getElementsByClassName("leder-result-text")[0].value= TestingTesting;
     // loop the inner array
     //for (var j = 0; j < innerArrayLength; j++) {
     //console.log('[' + i + ',' + j + '] = ' + Leder[i][j]);

   }
 // output the list generated into the fullout array to output field
     document.getElementsByClassName("leder-result-text-F")[0].value= Ffullout.join("\n");
     document.getElementsByClassName("leder-result-text-U")[0].value= Ufullout.join("\n");
     document.getElementsByClassName("leder-result-text-A")[0].value= Afullout.join("\n");
  }

$(document).ready(function () {
	var customSets;
  var Leder;
	placeBsBtn();
	//if (localStorage.customsets) {
	//	customSets = JSON.parse(localStorage.customsets);
	//	updateDex(customSets);
	//	$(bothPokemon("#importedSetsOptions")).css("display", "inline");
	//}// else {
	//	loadDefaultLists();
	//}
});
<commit_msg>More bordizer war crimes, spaghetti inside<commit_after>function placeBsBtn() {
	var importBtn = "<button id='import' class='bs-btn bs-btn-default'>Import</button>";
	$("#import-1_wrapper").append(importBtn);

	$("#import.bs-btn").click(function () {
		var pokes = document.getElementsByClassName("import-team-text")[0].value;
    // var pokes = document.getElementsByClassName("import-team-text").value;
    // var Leder = $.csv.toArrays(pokes);
    //console.log(pokes);
		addSets(pokes);
	});

}

function serialize(array, separator) {
	var text = "";
	for (var i = 0; i < array.length; i++) {
		if (i < array.length - 1) {
			text += array[i] + separator;
		} else {
			text += array[i];
		}
	}
	return text;
}

function addSets(pokes) {
	//var rows = pokes.split("\n");
	var currentRow;
	var currentPoke;
	var addedpokes = 0;

  var userIdPrev
  //var pokes;
  var i;
  var j;
  var FPlacement = 0;
  var UPlacement = 0;
  var APlacement = 0;

  var FPlacementVisual = 0;
  var UPlacementVisual = 0;
  var APlacementVisual = 0;

  var FPlacementVisual = 0;
  var UPlacementVisual = 0;
  var Leder = $.csv.toArrays(pokes);
//var pokes = document.getElementsByClassName("import-team-text")[0].value;
  //console.log(pokes);
  //console.log(Leder);

  var Ffullout = [];
  var Ufullout = [];
  var Afullout = [];
  //loop the outer array
  for (var i = 0; i < Leder.length; i++) {
     var innerArrayLength = Leder[i].length;
     var userName = Leder[i][0];
     var userId = Leder[i][1];
     var streakLen = Leder[i][2];
     var url1 = Leder[i][3];
     var pokeAmount = Leder[i][4];

     var teamPokes = [];

     teamPokes[0] = Leder[i][5];
     teamPokes[1] = Leder[i][6];
     teamPokes[2] = Leder[i][7];
     teamPokes[3] = Leder[i][8];
     teamPokes[4] = Leder[i][9];
     teamPokes[5] = Leder[i][10];

    if ( i > 0 ) {
      userIdPrev = Leder[i-1][1]
    }

    //console.log(parseInt(pokeAmount))
     switch (parseInt(pokeAmount)) {
       case 1:
         var url1Text = teamPokes[0];
         break;
       case 2:
         var url1Text = teamPokes[0] + " / " + teamPokes[1];
         break;
       case 3:
         var url1Text = teamPokes[0] + " / " + teamPokes[1] + " / " + teamPokes[2];
         break;
       case 4:
         var url1Text = teamPokes[0] + " / " + teamPokes[1] + " / " + teamPokes[2] + " / " + teamPokes[3];
         break;
       case 5:
         var url1Text = teamPokes[0] + " / " + teamPokes[1] + " / " + teamPokes[2] + " / " + teamPokes[3] + " / " +teamPokes[4];
         break;
       case 6:
         var url1Text = teamPokes[0] + " / " + teamPokes[1] + " / " + teamPokes[2] + " / " + teamPokes[3] + " / " +teamPokes[4] + " / " + teamPokes[5];
         break;
     }

     var streakFlags = Leder[i][11];
     var finish = streakFlags.charAt(0);
     var url2 = Leder[i][12];
     var url2Text = Leder[i][13];
     var url3 = Leder[i][14];
     var url3Text = Leder[i][15];

     switch (finish) {
       case "F":
         if ( userIdPrev === userId ) {
           var FPlacementVisual = FPlacementVisual + 0;
           var FPlacementCur = "   ";
         } else {
         var FPlacementVisual = FPlacementVisual + 1;
         var FPlacementCur = "#" + String(FPlacementVisual) + ". ";
         }
         var FPlacement = FPlacement + 1;
         var Fout_bbcode = FPlacementCur + "[b][user=" + userId + "]" + userName + "[/user][/b], ([b]" + streakLen + "[/b] - [url=" + url1 + "]" + url1Text + "[/url]"
         Ffullout[FPlacement] = Fout_bbcode;
         break;

       case "U":
         if ( userIdPrev === userId ) {
           var UPlacementVisual = UPlacementVisual + 0;
           var UPlacementCur = "   ";
         } else {
         var UPlacementVisual = UPlacementVisual + 1;
         var UPlacementCur = "#" + String(UPlacementVisual) + ". ";
         }
         var UPlacement = UPlacement + 1;
         var Uout_bbcode = UPlacementCur + "[b][user=" + userId + "]" + userName + "[/user][/b], ([b]" + streakLen + "[/b] - [url=" + url1 + "]" + url1Text + "[/url]"
         Ufullout[UPlacement] = Uout_bbcode;
         break;
     }

     if ( userIdPrev === userId ) {
       var APlacementVisual = APlacementVisual + 0;
       var APlacementCur = "   ";
     } else {
     var APlacementVisual = APlacementVisual + 1;
     var APlacementCur = "#" + String(APlacementVisual) + ". ";
     }

     var APlacement = APlacement + 1;
     var Aout_bbcode = APlacementCur + "[b][user=" + userId + "]" + userName + "[/user][/b], ([b]" + streakLen + "[/b] - [url=" + url1 + "]" + url1Text + "[/url]"
     Afullout[APlacement] = Aout_bbcode;

     //var url1Text = teamPoke1 + " / " + teamPoke2 + " / " + teamPoke3 + " / " + teamPoke4;
    //console.log(userName, userId, streakLen, url1, teamPoke1, teamPoke2, teamPoke3, teamPoke4, streakFlags, url2, url2Text, url3, url3Text, url1Text);
    //var TestingTesting = userName + userId + streakLen + url1 + teamPoke1 + teamPoke2 + teamPoke3 + teamPoke4 + streakFlags + url2 + url2Text + url3 + url3Text + url1Text;
    //console.log(TestingTesting);

     //document.getElementsByClassName("leder-result-text")[0].value= TestingTesting;
     // loop the inner array
     //for (var j = 0; j < innerArrayLength; j++) {
     //console.log('[' + i + ',' + j + '] = ' + Leder[i][j]);

   }
 // output the list generated into the fullout array to output field
     document.getElementsByClassName("leder-result-text-F")[0].value= Ffullout.join("\n");
     document.getElementsByClassName("leder-result-text-U")[0].value= Ufullout.join("\n");
     document.getElementsByClassName("leder-result-text-A")[0].value= Afullout.join("\n");
  }

$(document).ready(function () {
	var customSets;
  var Leder;
	placeBsBtn();
	//if (localStorage.customsets) {
	//	customSets = JSON.parse(localStorage.customsets);
	//	updateDex(customSets);
	//	$(bothPokemon("#importedSetsOptions")).css("display", "inline");
	//}// else {
	//	loadDefaultLists();
	//}
});
<|endoftext|>


<commit_before>export default [
    '(business|client|community|culture|customer|data|goal|intelligence|market' +
        '|process|quality|results|role|sales|subject|service|user)' +
        '.(centric(ity)?|facing|oriented|driven|focused|assessment|service|process|align(ed|ment|ing))',
    '10x',
    '24/7',
    'ai',
    'agile',
    'ambassador',
    'artificial intelligence',
    'at (your|their) fingertips?',
    'autonomous',
    'a[-/]b testing',
    'acquisition',
    'action items?',
    'act in time',
    'advanc(es?|ing)',
    'advantages?',
    'agendas?',
    'agents?',
    'aggregat(e|ion)',
    'accelerate',
    'all.in.one',
    'all.new',
    'amazing',
    'analytics?',
    'application service providers?',
    'as a service',
    'assets?',
    'astonishing',
    'authoritative',
    'automated',
    'augmented',
    'extended reality',
    'award.winning',
    'b2(b|c)',
    'back to the drawing board',
    'ball.?park',
    'band.aid',
    'bandwidth',
    '(benefit|gap) analysis',
    'bespoke',
    'best.in.class',
    'best.of.breed',
    'best.practice',
    'big.data',
    'big picture',
    'big thinkers?',
    'block.?chain',
    'blazing(ly)? fast',
    'boil the ocean',
    'bottom.line',
    'bottom.up',
    'boost(s|ing)?',
    'boundless',
    'brain.?storm(ing)?',
    'brain.?dump',
    'brand(s?|ing|ed)',
    'bright',
    'building.trust',
    'bulletproof',
    'burn.rates?',
    'business( cases| plans)',
    'buzz',
    'call to action',
    'capacity',
    'capabilit(y|ies)',
    'capitali(s|z)e',
    'centers? of excellence',
    'challenges?',
    'change agents?',
    'circle the wagons',
    'client-centered',
    'client-centric',
    'client-focused',
    'cloud',
    'cloud native',
    'cloudif(y|ication)',
    'collaborat(e|ion|ive)s?',
    'combat(ing|s)?',
    'comfort( zone)?',
    'commit(ments?|tee)?',
    'communicat(e|ion)s?',
    'company-employee.fit',
    'compelling',
    'competitive( advantage)?',
    'connected systems?',
    'complex(ity)?',
    'comprehensive',
    'connect the dots',
    'container orchestration',
    'containerizat(e|ion|ing)',
    'content management',
    'contextual(ly)?',
    'contingency plans?',
    'control groups?',
    'control plane',
    'convergence',
    'convergent',
    'conversions?',
    'core business',
    'core competenc(y|ies)',
    'core.to.edge',
    'cosmic',
    'cost-effective',
    'cost/benefit',
    'cost control',
    'counter(s|ing)?',
    'craftsmanship',
    'critical path',
    'crypto.currency',
    'crypto(?!graphy).\\w+',
    'crm',
    'cross.sell',
    'crowd.?(fund(s?|ed|ing)|sourc(ed|e|ing))',
    'customer obsession',
    'cutting.edge',
    'cyber',
    'dashboards?',
    'dashboarding',
    'data mining',
    'decentrali(s|z)ed',
    'de-?dupe',
    'deep dive',
    'deep learning',
    'delight',
    'deliver(able)?s?',
    'demographic',
    'demystify',
    'demystifying',
    'deploy(less|s)?',
    'devops?',
    'dialog(ue?)s?',
    'digital transformation',
    'differentiation',
    'discover(y|ed)?',
    'distributed ledgers?',
    'disrupt(ive|tor|ion|er)?',
    'dollar.productive',
    'downsi(s|z)e',
    'drill down',
    'drink the kool-aid',
    'drive( out|s)?',
    'drop.?in',
    'drop the ball',
    'due dilligence',
    'dynamic(s|ally)?',
    'e-?(business|commerce|tailers)',
    'early.stage',
    'eas(y|ily)',
    'ecosystem(s)?',
    'edge.comput?(ed|ing)',
    'efficien(t|cy)',
    'effortless(ly)?',
    'elastic',
    'elaboration',
    'elephant in the room',
    'elevator pitch(ing)?',
    'enabl(e|ing)',
    'emerging markets?',
    'empower(ing|ment|s)?',
    'enablement',
    'end of the day',
    'end.to.end',
    'engulf',
    'engag(e(d)|ing|ment)',
    'enhanced?',
    'enterprise',
    'erp',
    'estimate',
    'eta',
    'etched in stone',
    'evangelist',
    'evolution',
    'exceed expectations',
    'excellent',
    'exceptional',
    'exclusive(ly)?',
    'exhaustive',
    'expedite',
    'experiences',
    'experts?',
    'expertise',
    'exposure',
    'extraordinary',
    'facilitat(e|or)',
    'fast track',
    'fault.tolerant',
    'feeling excited',
    'first.rate',
    'first.to.market',
    'flexibility',
    'flux',
    'focus(es|ing)?',
    'foot view',
    'forward-thinking',
    'fosters?',
    'four pillars',
    'frictionless',
    'front lines',
    'frustration[- ]free',
    'functional',
    'futurist',
    'full benefit',
    'future.proof',
    'game changer',
    'game plan',
    'behavioral',
    'global(ly)?',
    'go public',
    'go.to.market',
    'goals?',
    'god-speed',
    'going forward',
    'granular',
    'ground.?breaking',
    'growth',
    'grow',
    'guidance',
    'guru',
    'guarantee(d)?',
    'hackathon',
    'hacker( mindset)?',
    'happiness manage(ment|rs?)',
    'hardball',
    'heavy.lifting',
    'herding cats',
    'hidden.gem',
    'hidden.meaning',
    'high.level',
    '(high|mass).impact',
    'high quality',
    'highly.scalable',
    'hive ?mind',
    'hybrid environments?',
    'hyperautomation',
    'hyper.personalization',
    'hyperconverged',
    'hyperscal(e|ed|er|ing)',
    'holistic',
    'ideathon',
    'ideation',
    'impact(ful|s)?',
    'impeccable',
    'in( |-)a( |-)nutshell',
    'incent',
    '(dis)?incentivi(s|z)e',
    'increase the odds',
    'incredibl(e|y)',
    '(inflat|redeem)able value',
    'influencers?',
    'influx',
    'initiat(es?|ing|ives?)',
    'innovat(e|ed|ion|ive|ing|or)s?',
    'inspir(e|ing|ation)',
    'insights?',
    'integrat(e|ed|ion)s?',
    'internet[- ]of[- ]things',
    'intellectual property',
    'intuitive',
    'iot',
    'key( result)?s?',
    'kickstart(er|ed|ing)?s?',
    'killjoy',
    'knowledge.(base|transfer|sharing)',
    'kpis?',
    'land(ing page)?s?',
    'lead the field',
    'leading',
    'leaders?',
    'leadership',
    'learnings',
    'legacy',
    'lessons learned',
    'level (the )? playing field',
    'level set',
    'leverag(e|ing)s?',
    'liais(es?|ings?)',
    'lifecycle',
    'low.hanging fruit',
    'look.(&|and).feel',
    'm2m',
    'machine learning',
    'made simple',
    'magical',
    'market (chang(er|ing)|leader|window|simplified|fit)',
    'market.ready',
    'marketing automation',
    'marketing collateral',
    'maximi(s|z)e',
    'meaningful( client | )interactions?',
    'measurements?',
    'methodolog(y|ies)',
    'metrics',
    'middleware',
    'milestone',
    'military.grade encryption',
    'mind ?share',
    'mind ?shower',
    'mind-boggling',
    'mindset',
    '(mission|time).critical',
    'miracle',
    'ml',
    'moneti(s|z)e',
    'mov(e|ing) (fast|forward)',
    'multitask(ing?)',
    'multifaceted',
    'multi-?tenant(ed)?',
    'mvp',
    'negotiated',
    'networking',
    'new.economy',
    'new.breed',
    '(new|next|second).(level|gen|generation)',
    'nexus',
    'niches?',
    'ninja',
    'no-brainer',
    'non-traditional management',
    'objectives',
    'occupy the field',
    'off.site',
    'off.the.(radar|shelf)',
    'on board',
    'on.premises?',
    'on the (back end|radar screen|same page|house)',
    'one.stop.shop',
    'one to one',
    'open the kimono',
    'opportunit(y|ies)',
    'outperform',
    'overarch(es?|ing)?',
    'optimal',
    'orthogonal',
    'outcome(s)',
    'outstanding',
    'out(side)?.(of)?.the.(box|loop)',
    'outsourc(e|ed|ing)',
    '(total cost of )?ownership',
    'paradigms?( shift)?',
    'partner(ships?)?',
    'patents?',
    'people.focus(ed|sed)',
    'performance indicators',
    'perfect(ly)?',
    'personaliz(e|ed|ation)',
    'perspective',
    'phases?',
    'phased approach',
    'pipeline',
    'pioneers',
    'pivot',
    'planning horizon',
    'platforms?',
    'pledg(es?|ing)',
    'plethora',
    'plug.?in',
    'potentials?',
    'powerful',
    'prioriti(s|z)ed?',
    'proactive',
    'problem space',
    'processes',
    'profit(ability)?',
    'progress(es)?',
    'promot(e|ion)?s?',
    'promotional collateral',
    'prominent',
    'promise',
    'proprietary',
    'proof.of.concept',
    'prove(n|d)?',
    'purpose.built',
    'push the envelope',
    'push.back',
    'production.ready',
    'productivity',
    'pushing on open doors',
    'quick wins?',
    'rais(e|ing) the bar',
    'ramp.up',
    'ravishing',
    '(reaping )(tangible )rewards',
    'relationship management',
    'responsive',
    'engage(ments?)?',
    'reach out',
    'reactivation',
    'real.time',
    'real.world',
    'reconfigure',
    'redefin(e|ed|ing)',
    'red flags?',
    'reengineering',
    'reimagin(e|ed|ing)',
    'reinvent(ing)? the(.square)? wheel',
    'reinvigorate',
    'relevance',
    'repurpose',
    'resilien(ce|cy|t)',
    'resource allocation',
    'restructuring',
    'retention',
    'return on investment',
    'results',
    'reus(e|ability)',
    'revenue',
    'reverse.engineer',
    'revisit',
    'revolution',
    'revolutionary',
    'reward(ing)?(.experience)?',
    'rich',
    'ring fencing',
    'road ?map',
    'robust',
    'rock.?star',
    'roi',
    'run the numbers',
    '(s|p)aas',
    'sacrific(e|es|ing)',
    'scal(e|es|ing|ability)',
    'high availability',
    'scenarios?',
    'scope',
    'scrum( master)?',
    'seamless',
    'secret sauce',
    'search engine optimization',
    'segments?',
    'self.?guid(ed|ing|ance)',
    'self-managed team',
    'seo',
    '(serial )?entrepreneurs?',
    'serverless',
    'service mesh',
    'shareholder value',
    'significant(ly)?',
    'single-source responsibility',
    'skill ?sets?',
    'slim(ming)? down',
    'smart(er)?',
    'smoke (&|and) mirrors',
    'social(.media|.gaming|.networks?)',
    'solidality',
    'solutions?',
    'sophisticated',
    'soup to nuts',
    'sow',
    'spatial.computing',
    'stakeholders?',
    'start.up?',
    'statement of work',
    'state.of.the.art',
    'step.changes?',
    'sticky-?ness',
    'strateg(y|ic|ize|ise)',
    'streamlin(ed|e|ing)',
    'strength(en(ing)?|s)?',
    'story points?',
    'success(ful)?',
    'super(critical|star|nova)',
    'sustainab(le|ility)',
    'synerg(y|ies|ized|i)',
    'systems?',
    'tackl(es?|ing)',
    'tailwinds?',
    'talented',
    'take offline',
    'talking points',
    'target (audience|group)',
    'targeted',
    'tasked',
    'tco',
    'team.building',
    'team.player',
    'teamwork',
    'technolog(y|ies)',
    'that being said',
    'thought.leader',
    'throughput',
    'time.to.awesome',
    'time.to.market',
    'timelines?',
    'top.down',
    'top.of.the.game',
    'total quality',
    'touch.base',
    'touchpoints?',
    'traction',
    'transform(ing|ative|ation(al)?|s?)',
    'trends?',
    'true',
    'truths?',
    'turnkey',
    'ultimate',
    'up.to.speed',
    'up-?sell',
    'upside',
    'user.friendly',
    'user funnels?',
    'user.experience',
    'utili(s|z)(e|ation)',
    'uncover',
    'unicorn',
    'unique approach',
    'unlimited.holidays',
    'values?',
    'valueable',
    'value.add(ed)?',
    'venture',
    'venturing',
    'vertical market',
    'viral',
    'virtual(ization|isation)?',
    'visibility',
    'visio(n|nary)',
    'walk the talk',
    'wearable',
    'web.enabled',
    'win-win',
    'wisdom of crowds',
    'with due respect',
    'with ease',
    'wizards?',
    'workflows?',
    'workloads?',
    'workplaceless',
    'workspace',
    'world.?class',
    'world a better place',
    'wow.factor',
    'you\'ve never seen (a|an) \\w+',
    'zeitgeist',
    'zenith',
    'quantum'
];
<commit_msg>Added term future-facing (#175)<commit_after>export default [
    '(business|client|community|culture|customer|data|goal|intelligence|market' +
        '|process|quality|results|role|sales|subject|service|user)' +
        '.(centric(ity)?|facing|oriented|driven|focused|assessment|service|process|align(ed|ment|ing))',
    '10x',
    '24/7',
    'ai',
    'agile',
    'ambassador',
    'artificial intelligence',
    'at (your|their) fingertips?',
    'autonomous',
    'a[-/]b testing',
    'acquisition',
    'action items?',
    'act in time',
    'advanc(es?|ing)',
    'advantages?',
    'agendas?',
    'agents?',
    'aggregat(e|ion)',
    'accelerate',
    'all.in.one',
    'all.new',
    'amazing',
    'analytics?',
    'application service providers?',
    'as a service',
    'assets?',
    'astonishing',
    'authoritative',
    'automated',
    'augmented',
    'extended reality',
    'award.winning',
    'b2(b|c)',
    'back to the drawing board',
    'ball.?park',
    'band.aid',
    'bandwidth',
    '(benefit|gap) analysis',
    'bespoke',
    'best.in.class',
    'best.of.breed',
    'best.practice',
    'big.data',
    'big picture',
    'big thinkers?',
    'block.?chain',
    'blazing(ly)? fast',
    'boil the ocean',
    'bottom.line',
    'bottom.up',
    'boost(s|ing)?',
    'boundless',
    'brain.?storm(ing)?',
    'brain.?dump',
    'brand(s?|ing|ed)',
    'bright',
    'building.trust',
    'bulletproof',
    'burn.rates?',
    'business( cases| plans)',
    'buzz',
    'call to action',
    'capacity',
    'capabilit(y|ies)',
    'capitali(s|z)e',
    'centers? of excellence',
    'challenges?',
    'change agents?',
    'circle the wagons',
    'client-centered',
    'client-centric',
    'client-focused',
    'cloud',
    'cloud native',
    'cloudif(y|ication)',
    'collaborat(e|ion|ive)s?',
    'combat(ing|s)?',
    'comfort( zone)?',
    'commit(ments?|tee)?',
    'communicat(e|ion)s?',
    'company-employee.fit',
    'compelling',
    'competitive( advantage)?',
    'connected systems?',
    'complex(ity)?',
    'comprehensive',
    'connect the dots',
    'container orchestration',
    'containerizat(e|ion|ing)',
    'content management',
    'contextual(ly)?',
    'contingency plans?',
    'control groups?',
    'control plane',
    'convergence',
    'convergent',
    'conversions?',
    'core business',
    'core competenc(y|ies)',
    'core.to.edge',
    'cosmic',
    'cost-effective',
    'cost/benefit',
    'cost control',
    'counter(s|ing)?',
    'craftsmanship',
    'critical path',
    'crypto.currency',
    'crypto(?!graphy).\\w+',
    'crm',
    'cross.sell',
    'crowd.?(fund(s?|ed|ing)|sourc(ed|e|ing))',
    'customer obsession',
    'cutting.edge',
    'cyber',
    'dashboards?',
    'dashboarding',
    'data mining',
    'decentrali(s|z)ed',
    'de-?dupe',
    'deep dive',
    'deep learning',
    'delight',
    'deliver(able)?s?',
    'demographic',
    'demystify',
    'demystifying',
    'deploy(less|s)?',
    'devops?',
    'dialog(ue?)s?',
    'digital transformation',
    'differentiation',
    'discover(y|ed)?',
    'distributed ledgers?',
    'disrupt(ive|tor|ion|er)?',
    'dollar.productive',
    'downsi(s|z)e',
    'drill down',
    'drink the kool-aid',
    'drive( out|s)?',
    'drop.?in',
    'drop the ball',
    'due dilligence',
    'dynamic(s|ally)?',
    'e-?(business|commerce|tailers)',
    'early.stage',
    'eas(y|ily)',
    'ecosystem(s)?',
    'edge.comput?(ed|ing)',
    'efficien(t|cy)',
    'effortless(ly)?',
    'elastic',
    'elaboration',
    'elephant in the room',
    'elevator pitch(ing)?',
    'enabl(e|ing)',
    'emerging markets?',
    'empower(ing|ment|s)?',
    'enablement',
    'end of the day',
    'end.to.end',
    'engulf',
    'engag(e(d)|ing|ment)',
    'enhanced?',
    'enterprise',
    'erp',
    'estimate',
    'eta',
    'etched in stone',
    'evangelist',
    'evolution',
    'exceed expectations',
    'excellent',
    'exceptional',
    'exclusive(ly)?',
    'exhaustive',
    'expedite',
    'experiences',
    'experts?',
    'expertise',
    'exposure',
    'extraordinary',
    'facilitat(e|or)',
    'fast track',
    'fault.tolerant',
    'feeling excited',
    'first.rate',
    'first.to.market',
    'flexibility',
    'flux',
    'focus(es|ing)?',
    'foot view',
    'forward-thinking',
    'fosters?',
    'four pillars',
    'frictionless',
    'front lines',
    'frustration[- ]free',
    'functional',
    'futurist',
    'full benefit',
    'future[- ]facing',
    'future.proof',
    'game changer',
    'game plan',
    'behavioral',
    'global(ly)?',
    'go public',
    'go.to.market',
    'goals?',
    'god-speed',
    'going forward',
    'granular',
    'ground.?breaking',
    'growth',
    'grow',
    'guidance',
    'guru',
    'guarantee(d)?',
    'hackathon',
    'hacker( mindset)?',
    'happiness manage(ment|rs?)',
    'hardball',
    'heavy.lifting',
    'herding cats',
    'hidden.gem',
    'hidden.meaning',
    'high.level',
    '(high|mass).impact',
    'high quality',
    'highly.scalable',
    'hive ?mind',
    'hybrid environments?',
    'hyperautomation',
    'hyper.personalization',
    'hyperconverged',
    'hyperscal(e|ed|er|ing)',
    'holistic',
    'ideathon',
    'ideation',
    'impact(ful|s)?',
    'impeccable',
    'in( |-)a( |-)nutshell',
    'incent',
    '(dis)?incentivi(s|z)e',
    'increase the odds',
    'incredibl(e|y)',
    '(inflat|redeem)able value',
    'influencers?',
    'influx',
    'initiat(es?|ing|ives?)',
    'innovat(e|ed|ion|ive|ing|or)s?',
    'inspir(e|ing|ation)',
    'insights?',
    'integrat(e|ed|ion)s?',
    'internet[- ]of[- ]things',
    'intellectual property',
    'intuitive',
    'iot',
    'key( result)?s?',
    'kickstart(er|ed|ing)?s?',
    'killjoy',
    'knowledge.(base|transfer|sharing)',
    'kpis?',
    'land(ing page)?s?',
    'lead the field',
    'leading',
    'leaders?',
    'leadership',
    'learnings',
    'legacy',
    'lessons learned',
    'level (the )? playing field',
    'level set',
    'leverag(e|ing)s?',
    'liais(es?|ings?)',
    'lifecycle',
    'low.hanging fruit',
    'look.(&|and).feel',
    'm2m',
    'machine learning',
    'made simple',
    'magical',
    'market (chang(er|ing)|leader|window|simplified|fit)',
    'market.ready',
    'marketing automation',
    'marketing collateral',
    'maximi(s|z)e',
    'meaningful( client | )interactions?',
    'measurements?',
    'methodolog(y|ies)',
    'metrics',
    'middleware',
    'milestone',
    'military.grade encryption',
    'mind ?share',
    'mind ?shower',
    'mind-boggling',
    'mindset',
    '(mission|time).critical',
    'miracle',
    'ml',
    'moneti(s|z)e',
    'mov(e|ing) (fast|forward)',
    'multitask(ing?)',
    'multifaceted',
    'multi-?tenant(ed)?',
    'mvp',
    'negotiated',
    'networking',
    'new.economy',
    'new.breed',
    '(new|next|second).(level|gen|generation)',
    'nexus',
    'niches?',
    'ninja',
    'no-brainer',
    'non-traditional management',
    'objectives',
    'occupy the field',
    'off.site',
    'off.the.(radar|shelf)',
    'on board',
    'on.premises?',
    'on the (back end|radar screen|same page|house)',
    'one.stop.shop',
    'one to one',
    'open the kimono',
    'opportunit(y|ies)',
    'outperform',
    'overarch(es?|ing)?',
    'optimal',
    'orthogonal',
    'outcome(s)',
    'outstanding',
    'out(side)?.(of)?.the.(box|loop)',
    'outsourc(e|ed|ing)',
    '(total cost of )?ownership',
    'paradigms?( shift)?',
    'partner(ships?)?',
    'patents?',
    'people.focus(ed|sed)',
    'performance indicators',
    'perfect(ly)?',
    'personaliz(e|ed|ation)',
    'perspective',
    'phases?',
    'phased approach',
    'pipeline',
    'pioneers',
    'pivot',
    'planning horizon',
    'platforms?',
    'pledg(es?|ing)',
    'plethora',
    'plug.?in',
    'potentials?',
    'powerful',
    'prioriti(s|z)ed?',
    'proactive',
    'problem space',
    'processes',
    'profit(ability)?',
    'progress(es)?',
    'promot(e|ion)?s?',
    'promotional collateral',
    'prominent',
    'promise',
    'proprietary',
    'proof.of.concept',
    'prove(n|d)?',
    'purpose.built',
    'push the envelope',
    'push.back',
    'production.ready',
    'productivity',
    'pushing on open doors',
    'quick wins?',
    'rais(e|ing) the bar',
    'ramp.up',
    'ravishing',
    '(reaping )(tangible )rewards',
    'relationship management',
    'responsive',
    'engage(ments?)?',
    'reach out',
    'reactivation',
    'real.time',
    'real.world',
    'reconfigure',
    'redefin(e|ed|ing)',
    'red flags?',
    'reengineering',
    'reimagin(e|ed|ing)',
    'reinvent(ing)? the(.square)? wheel',
    'reinvigorate',
    'relevance',
    'repurpose',
    'resilien(ce|cy|t)',
    'resource allocation',
    'restructuring',
    'retention',
    'return on investment',
    'results',
    'reus(e|ability)',
    'revenue',
    'reverse.engineer',
    'revisit',
    'revolution',
    'revolutionary',
    'reward(ing)?(.experience)?',
    'rich',
    'ring fencing',
    'road ?map',
    'robust',
    'rock.?star',
    'roi',
    'run the numbers',
    '(s|p)aas',
    'sacrific(e|es|ing)',
    'scal(e|es|ing|ability)',
    'high availability',
    'scenarios?',
    'scope',
    'scrum( master)?',
    'seamless',
    'secret sauce',
    'search engine optimization',
    'segments?',
    'self.?guid(ed|ing|ance)',
    'self-managed team',
    'seo',
    '(serial )?entrepreneurs?',
    'serverless',
    'service mesh',
    'shareholder value',
    'significant(ly)?',
    'single-source responsibility',
    'skill ?sets?',
    'slim(ming)? down',
    'smart(er)?',
    'smoke (&|and) mirrors',
    'social(.media|.gaming|.networks?)',
    'solidality',
    'solutions?',
    'sophisticated',
    'soup to nuts',
    'sow',
    'spatial.computing',
    'stakeholders?',
    'start.up?',
    'statement of work',
    'state.of.the.art',
    'step.changes?',
    'sticky-?ness',
    'strateg(y|ic|ize|ise)',
    'streamlin(ed|e|ing)',
    'strength(en(ing)?|s)?',
    'story points?',
    'success(ful)?',
    'super(critical|star|nova)',
    'sustainab(le|ility)',
    'synerg(y|ies|ized|i)',
    'systems?',
    'tackl(es?|ing)',
    'tailwinds?',
    'talented',
    'take offline',
    'talking points',
    'target (audience|group)',
    'targeted',
    'tasked',
    'tco',
    'team.building',
    'team.player',
    'teamwork',
    'technolog(y|ies)',
    'that being said',
    'thought.leader',
    'throughput',
    'time.to.awesome',
    'time.to.market',
    'timelines?',
    'top.down',
    'top.of.the.game',
    'total quality',
    'touch.base',
    'touchpoints?',
    'traction',
    'transform(ing|ative|ation(al)?|s?)',
    'trends?',
    'true',
    'truths?',
    'turnkey',
    'ultimate',
    'up.to.speed',
    'up-?sell',
    'upside',
    'user.friendly',
    'user funnels?',
    'user.experience',
    'utili(s|z)(e|ation)',
    'uncover',
    'unicorn',
    'unique approach',
    'unlimited.holidays',
    'values?',
    'valueable',
    'value.add(ed)?',
    'venture',
    'venturing',
    'vertical market',
    'viral',
    'virtual(ization|isation)?',
    'visibility',
    'visio(n|nary)',
    'walk the talk',
    'wearable',
    'web.enabled',
    'win-win',
    'wisdom of crowds',
    'with due respect',
    'with ease',
    'wizards?',
    'workflows?',
    'workloads?',
    'workplaceless',
    'workspace',
    'world.?class',
    'world a better place',
    'wow.factor',
    'you\'ve never seen (a|an) \\w+',
    'zeitgeist',
    'zenith',
    'quantum'
];
<|endoftext|>


<commit_before>/**
 * Created with JetBrains WebStorm.
 * User: shem
 * Date: 8/27/13
 * Time: 9:47 PM
 * To change this template use File | Settings | File Templates.
 */
var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
var BSON = require('mongodb').BSON;
var ObjectID = require('mongodb').ObjectID;
var moment = require('moment');
var _DATEFORMAT = "dddd, MMMM Do YYYY, h:mm:ss a";

ArticleProvider = function(host, port) {
    this.db= new Db('blogdb', new Server(host, port, {safe: false}, {auto_reconnect: true}, {}));
    this.db.open(function(err, db) {

    });
};

ArticleProvider.prototype.getCollection= function(callback) {
    this.db.collection('articles', function(error, article_collection) {
        if( error ) callback(error);
        else callback(null, article_collection);
    });
};

ArticleProvider.prototype.findAll = function(callback) {
    this.getCollection(function(error, article_collection) {
        if( error ) callback(error)
        else {
            article_collection.find().toArray(function(error, results) {
                if( error ) callback(error)
                else callback(null, results)
            });
        }
    });
};

ArticleProvider.prototype.findById = function(id, callback) {
    this.getCollection(function(error, article_collection) {
        if( error ) callback(error)
        else {
            article_collection.findOne({_id: article_collection.db.bson_serializer.ObjectID.createFromHexString(id)}, function(error, result) {
                if( error ) callback(error)
                else callback(null, result)
            });
        }
    });
};

ArticleProvider.prototype.save = function(articles, callback) {
    this.getCollection(function(error, article_collection) {
        if( error ) callback(error)
        else {
            if( typeof(articles.length)=="undefined")
                articles = [articles];

            for( var i = 0, article;i< articles.length;i++ ) {
                article = articles[i];
                article.created_at = moment().format(_DATEFORMAT);
                if( article.comments === undefined ) article.comments = [];
                for(var j =0;j< article.comments.length; j++) {
                    article.comments[j].created_at = moment().format(_DATEFORMAT);
                }
            }

            article_collection.insert(articles, function() {
                callback(null, articles);
            });
        }
    });
};

ArticleProvider.prototype.saveComment = function(articleId, comment, callback) {
    this.getCollection(function(error, article_collection) {
        if( error ) callback(error)
        else {
            comment.created_at = moment().format(_DATEFORMAT);
            article_collection.update({
                _id: article_collection.db.bson_serializer.ObjectID.createFromHexString(articleId)}, {
                $push: { comments: comment }
            }, function(error, article){
                if( error ) callback(error);
                else callback(null, articleId)
            });
        }
    });
};

exports.ArticleProvider = ArticleProvider;<commit_msg>added mongolab port<commit_after>/**
 * Created with JetBrains WebStorm.
 * User: shem
 * Date: 8/27/13
 * Time: 9:47 PM
 * To change this template use File | Settings | File Templates.
 */
var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
var BSON = require('mongodb').BSON;
var ObjectID = require('mongodb').ObjectID;
var moment = require('moment');
var _DATEFORMAT = "dddd, MMMM Do YYYY, h:mm:ss a";

var mongoUri = process.env.MONGOLAB_URI ||
    process.env.MONGOHQ_URL ||
    'blogdb';

ArticleProvider = function(host, port) {
    this.db= new Db(mongoUri, new Server(host, port, {safe: false}, {auto_reconnect: true}, {}));
    this.db.open(function(err, db) {

    });
};

ArticleProvider.prototype.getCollection= function(callback) {
    this.db.collection('articles', function(error, article_collection) {
        if( error ) callback(error);
        else callback(null, article_collection);
    });
};

ArticleProvider.prototype.findAll = function(callback) {
    this.getCollection(function(error, article_collection) {
        if( error ) callback(error)
        else {
            article_collection.find().toArray(function(error, results) {
                if( error ) callback(error)
                else callback(null, results)
            });
        }
    });
};

ArticleProvider.prototype.findById = function(id, callback) {
    this.getCollection(function(error, article_collection) {
        if( error ) callback(error)
        else {
            article_collection.findOne({_id: article_collection.db.bson_serializer.ObjectID.createFromHexString(id)}, function(error, result) {
                if( error ) callback(error)
                else callback(null, result)
            });
        }
    });
};

ArticleProvider.prototype.save = function(articles, callback) {
    this.getCollection(function(error, article_collection) {
        if( error ) callback(error)
        else {
            if( typeof(articles.length)=="undefined")
                articles = [articles];

            for( var i = 0, article;i< articles.length;i++ ) {
                article = articles[i];
                article.created_at = moment().format(_DATEFORMAT);
                if( article.comments === undefined ) article.comments = [];
                for(var j =0;j< article.comments.length; j++) {
                    article.comments[j].created_at = moment().format(_DATEFORMAT);
                }
            }

            article_collection.insert(articles, function() {
                callback(null, articles);
            });
        }
    });
};

ArticleProvider.prototype.saveComment = function(articleId, comment, callback) {
    this.getCollection(function(error, article_collection) {
        if( error ) callback(error)
        else {
            comment.created_at = moment().format(_DATEFORMAT);
            article_collection.update({
                _id: article_collection.db.bson_serializer.ObjectID.createFromHexString(articleId)}, {
                $push: { comments: comment }
            }, function(error, article){
                if( error ) callback(error);
                else callback(null, articleId)
            });
        }
    });
};

exports.ArticleProvider = ArticleProvider;<|endoftext|>