<commit_before>'use strict';

angular.module('myApp.view1', ['ngRoute'])

    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/', {
            templateUrl: 'view1/view1.html',
            controller: 'View1Ctrl'
        });
    }])

    .controller('View1Ctrl', ['$scope', '$timeout', '$interval', function ($scope, $timeout, $interval) {
        function stackTrace(msg) {
            var err = new Error(msg);
            throw err.stack;
        }

        var simon = {
            setCallback: function (callback){
                if (callback === undefined) {
                    stackTrace('callback undefined!');
                }
                this.callback = callback;
            },
            toggleOnOff: function () {
                this.on = !this.on;
                this.counterOn = this.on;
                if (!this.on) {
                    this.strict = false;
                    this.count = '- -';
                    this._clearTimeOuts();
                    $interval.cancel(this.heartBeat);
                    this.heartBeat = undefined;
                    this.callback();
                } else {
                    // heart beat
                    var parent = this;
                    var lastTick = Date.now();
                    var updateTick = function () {
                        var tick = Date.now();
                        parent._onUpdate(tick - lastTick);
                        lastTick = tick;
                    };
                    this.heartBeat = $interval(updateTick, 33, 0, true);
                }
            },
            toggleStrict: function () {
                if (callback !== undefined) {
                    stackTrace('callback undefined!');
                }

                if (this.on) {
                    this.strict = !this.strict;
                }
            },
            _onUpdate: function (dt) {
                console.log('tick: ' + dt);

                // tell view to update
                this.callback();
            },

            start: function (callback) {
                if (callback === undefined) {
                    stackTrace('callback undefined!');
                }

                // callback = view update

                if (!this.on) {
                    return;
                }

                // make sure we are in a good state
                if (this.failTimer !== undefined) {
                    $timeout.cancel(this.failTimer);
                    this.failTimer = undefined;
                }
                this.promises = [];
                this._setState('starting', 0);
                this.count = '- -';
                this.seqCount = 0;
                this.seqNum = 0;
                this.timeDelay = 1500;
                this.btnGreen = false;
                this.btnRed = false;
                this.btnBlue = false;
                this.btnYellow = false;
                this.btnFlashTime = 1000;
                this.sndToPlay = undefined;

                // generate a sequence
                this._generateSequence();

                // run the game
                this._run(callback);

            },
            _setState: function (newState, timeDelay) {
                var parent = this;
                if (!timeDelay) {
                    timeDelay = 0;
                }
                return $timeout(function () {
                    parent.state = newState;
                }, timeDelay);
            },
            _failed: function (callback) {
                if (callback === undefined) {
                    stackTrace('callback undefined!');
                }
                console.log('_failed');
                // player failed for some reason, we dont care why
                // if strict that's it game over / restart
                if (this.strict) {
                    this.failTimer = undefined;

                    // restart
                    $timeout(function () {
                        parent.start(callback);
                    }, this.autoRestartTime);
                    return;
                }

                // if not strict then replay sequence
                this._playSequence(callback, 'waiting');
                this.seqNum = 0;
            },
            btnInput: function (color, callback) {
                if (callback === undefined) {
                    stackTrace('callback undefined!');
                }

                console.log('btnInput  color: ' + color + '  state: ' + this.state);

                // callback = view update
                if (this.state !== 'waiting') {
                    return;
                }
                var btn;
                var btnNum;
                if (color === 'green') {
                    btn = 'btnGreen';
                    btnNum = 1;
                } else if (color === 'red') {
                    btn = 'btnRed';
                    btnNum = 2;
                } else if (color === 'blue') {
                    btn = 'btnBlue';
                    btnNum = 3;
                } else if (color === 'yellow') {
                    btn = 'btnYellow';
                    btnNum = 4;
                }

                // play sound and light button
                this._btnOn(btn, 0, callback);
                this._btnOff(btn, 100, callback);

                // process input
                // good input
                if (this.sequence[this.seqNum] === btnNum) {
                    this.seqNum++;

                    if (this.seqNum > this.seqCount) {
                        this.seqNum = 0;
                        this.seqCount++;
                        $timeout.cancel(this.failTimer);
                        var promise = this._playSequence(callback, 'waiting');
                        var parent = this;

                        this.failTimer = promise.then(function () {
                            return $timeout(function () {
                                parent._failed(callback);
                            }, parent.inputTime);
                        });

                    }
                } else {
                    // bad input
                    this._error(callback);
                }

                console.log('btnInput  done' + '  state: ' + this.state);

            },
            _run: function (callback) {
                console.log('_run');
                // callback = view update
                if (callback === undefined) {
                    stackTrace('callback undefined!');
                }
                this._setState('updating', 0);

                var parent = this;

                // play the sequence up to sequence count + 1
                // time is how long it will take to complete the playing the sequence
                // set state to waiting after sequence is done playing
                var promise = this._playSequence(callback, 'waiting');

                // set timeout for failure i.e. player has this.inputTime to complete the sequence or this._failed is called
                // store the promise is this.failtimer so we can clear it
                this.failTimer = promise.then(function () {
                    return $timeout(function () {
                        parent._failed(callback);
                    }, parent.inputTime);
                });
                /*
                 this.failTimer = $timeout(function () {
                 parent._failed(callback);
                 }, this.inputTime + time);*/
            },
            _generateSequence: function () {
                this.sequence = [];
                for (var i = 0; i < 20; i++) {
                    var num = Math.floor(Math.random() * (5 - 1)) + 1;
                    this.sequence.push(num);
                }
            },
            _playSequence: function (callback, nextState) {
                // callback is the viewUpdate function
                if (callback === undefined) {
                    stackTrace('callback undefined!');
                }

                console.log('_playSequence');

                var delay = this.timeDelay;
                var parent = this;

                this.promises.push(this._setState('playing', 0));

                for (var i = 0; i < this.seqCount + 1; i++) {
                    // push timeouts onto an array so we can clear them all if needed
                    // set timeout to turn button on

                    // todo remove functions from loop
                    // turn buttons on off
                    this.promises.push(this._btnOn(
                        this._getBtn(this.sequence[i]),
                        delay,
                        callback
                    ));
                    // set timeout to turn button off
                    this.promises.push(this._btnOff(
                        this._getBtn(this.sequence[i]),
                        delay + this.btnFlashTime,
                        callback
                    ));
                    delay += this.timeDelay;
                }
                // set state to nextState after sequence is done playing
                this.promises.push(parent._setState(nextState, delay));
                console.log(this.promises);
                return this.promises[this.promises.length - 1];
            },
            _getBtn: function (nbr) {
                switch (nbr) {
                    case 1:
                        return 'btnGreen';
                    case 2:
                        return 'btnRed';
                    case 3:
                        return 'btnBlue';
                    case 4:
                        return 'btnYellow';
                }
            },
            _btnOn: function (btn, delay, callback) {
                // callback tells the view to update
                if (callback === undefined) {
                    stackTrace('callback undefined!');
                }
                var parent = this;
                $timeout(function () {
                        parent[btn] = true;
                        parent.sndToPlay = parent[btn + 'Snd'];
                        callback();
                    }, delay
                );
            },
            _btnOff: function (btn, delay, callback) {
                // callback tells the view to update
                if (callback === undefined) {
                    stackTrace('callback undefined!');
                }
                var parent = this;
                $timeout(function () {
                        parent[btn] = false;
                        parent.sndToPlay = undefined;
                        callback();
                    }, delay
                );
            },
            _error: function (callback) {
                if (callback === undefined) {
                    stackTrace('callback undefined!');
                }

                // tell view ctrler to flash ! ! on counter
                var parent = this;
                var time = this.flashTime;
                this.count = '! !';

                // tell view to update before we start flashing
                callback();

                var flashFunc = function () {
                    parent.counterOn = !parent.counterOn;
                    callback();
                };

                // tell view to flash ! !
                for (var i = 1; i < 6; i++) {
                    $timeout(flashFunc, time * i);
                }
                return time;
            },
            _clearTimeOuts: function () {
                this.promises.forEach(function (func) {
                    if (func !== undefined) {
                        $timeout.cancel(func);
                    }
                });
                this.promises = [];

                if (this.failTimer !== undefined) {
                    $timeout.cancel(this.failTimer);
                    this.failTimer = undefined;
                }
            },
            state: 'off',
            on: false,
            counterOn: false,
            strict: false,
            count: '- -',
            sequence: [],
            seqCount: 0,
            seqNum: 0,
            promises: [],
            btnGreen: false,
            btnGreenSnd: 'assets/sounds/simonSound1.mp3',
            btnRed: false,
            btnRedSnd: 'assets/sounds/simonSound2.mp3',
            btnBlue: false,
            btnBlueSnd: 'assets/sounds/simonSound3.mp3',
            btnYellow: false,
            btnYellowSnd: 'assets/sounds/simonSound4.mp3',
            timeDelay: 1500,            // millisecond time delay between buttons
            btnFlashTime: 1000,         // millisecond how long to leave a button on.
            inputTime: 8000,            // time player has to input the correct sequence
            autoRestartTime: 2000,       // millisecond how long to wait before restart
            flashTime: 300,
            sndToPlay: undefined,
            failTimer: undefined,
            heartBeat: undefined
        };

        var updateView = function () {
            $scope.onOff = simon.on;
            $scope.counterOn = simon.counterOn;
            $scope.strictLed = simon.strict;
            $scope.count = simon.count;
            $scope.greenBtnOn = simon.btnGreen;
            $scope.redBtnOn = simon.btnRed;
            $scope.blueBtnOn = simon.btnBlue;
            $scope.yellowBtnOn = simon.btnYellow;

            if (simon.sndToPlay !== undefined) {
                var audio = new Audio(simon.sndToPlay);
                audio.play();
            }
        };
        $scope.switchClick = function () {
            simon.toggleOnOff(updateView);
        };
        $scope.strictClick = function () {
            simon.toggleStrict(updateView);
        };
        $scope.btnPress = function (color) {
            simon.btnInput(color, updateView);
        };
        $scope.startBtn = function () {
            simon.start(updateView);
        };
        simon.setCallback(updateView);
        updateView();

    }])
;<commit_msg>add, remove, and process events, tested and working bug free (as far as I can tell) :D<commit_after>'use strict';

angular.module('myApp.view1', ['ngRoute'])

    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/', {
            templateUrl: 'view1/view1.html',
            controller: 'View1Ctrl'
        });
    }])

    .controller('View1Ctrl', ['$scope', '$timeout', '$interval', function ($scope, $timeout, $interval) {
        function stackTrace(msg) {
            var err = new Error(msg);
            throw err.stack;
        }

        var simon = {
            setCallback: function (callback) {
                if (callback === undefined) {
                    stackTrace('callback undefined!');
                }
                this.callback = callback;
            },
            toggleOnOff: function () {
                this.on = !this.on;
                this.counterOn = this.on;
                if (!this.on) {
                    this.strict = false;
                    this.count = '- -';
                    this._clearTimeOuts();
                    $interval.cancel(this.heartBeat);
                    this.heartBeat = undefined;
                    this.callback();
                } else {
                    // heart beat
                    var parent = this;
                    var lastTick = Date.now();
                    var updateTick = function () {
                        var tick = Date.now();
                        parent._onUpdate(tick - lastTick);
                        lastTick = tick;
                    };
                    this.heartBeat = $interval(updateTick, 33, 0, true);
                }
            },
            toggleStrict: function () {
                if (this.on) {
                    this.strict = !this.strict;
                }
            },
            _onUpdate: function (dt) {
                this._processEvents(dt);

                //console.log('tick: ' + dt);

                // tell view to update
                this.callback();
            },
            _addEvent: function (delay, func, prams) {
                var id = this.events.length;
                this.events.push({id: id, delay: delay, func: func, prams: prams});
                return id;
            },
            _removeEvent: function (id) {
                this.events.some(function (element, index) {
                    if (element.id === id) {
                        this.events[index] = undefined;
                        return true;
                    }
                }, this);
            },
            _processEvents: function (dt) {
                var marker = 'marker';
                this.events.push(marker);

                var shifted;
                do {
                    shifted = this.events.shift();
                    if (shifted !== marker) {
                        shifted.delay -= dt;
                        if (shifted.delay <= 0){
                            shifted.func(shifted.prams);
                        } else {
                            this.events.push(shifted);
                        }
                    }
                } while (shifted !== marker);
            },

            start: function () {
                // callback = view update

                if (!this.on) {
                    return;
                }

                // make sure we are in a good state
                if (this.failTimer !== undefined) {
                    $timeout.cancel(this.failTimer);
                    this.failTimer = undefined;
                }
                this.promises = [];
                this._setState('starting', 0);
                this.count = '- -';
                this.seqCount = 0;
                this.seqNum = 0;
                this.timeDelay = 1500;
                this.btnGreen = false;
                this.btnRed = false;
                this.btnBlue = false;
                this.btnYellow = false;
                this.btnFlashTime = 1000;
                this.sndToPlay = undefined;

                // generate a sequence
                this._generateSequence();

                // run the game
                this._run();
            },
            _setState: function (newState, timeDelay) {
                var parent = this;
                if (!timeDelay) {
                    timeDelay = 0;
                }
                return $timeout(function () {
                    parent.state = newState;
                }, timeDelay);
            },

            //todo rewrite
            _failed: function () {
                console.log('_failed');
                // player failed for some reason, we dont care why
                // if strict that's it game over / restart
                if (this.strict) {

                    // todo

                    return;
                }

                // if not strict then replay sequence
                this._playSequence('waiting');
                this.seqNum = 0;
            },
            btnInput: function (color) {
                if (callback === undefined) {
                    stackTrace('callback undefined!');
                }

                console.log('btnInput  color: ' + color + '  state: ' + this.state);

                // callback = view update
                if (this.state !== 'waiting') {
                    return;
                }
                var btn;
                var btnNum;
                if (color === 'green') {
                    btn = 'btnGreen';
                    btnNum = 1;
                } else if (color === 'red') {
                    btn = 'btnRed';
                    btnNum = 2;
                } else if (color === 'blue') {
                    btn = 'btnBlue';
                    btnNum = 3;
                } else if (color === 'yellow') {
                    btn = 'btnYellow';
                    btnNum = 4;
                }

                // play sound and light button
                this._btnOn(btn, 0);
                this._btnOff(btn, 100);

                // process input
                // good input
                if (this.sequence[this.seqNum] === btnNum) {
                    this.seqNum++;

                    if (this.seqNum > this.seqCount) {
                        this.seqNum = 0;
                        this.seqCount++;
                        $timeout.cancel(this.failTimer);
                        var promise = this._playSequence('waiting');
                        var parent = this;

                        // todo set fail timer

                    }
                } else {
                    // bad input
                    this._error();
                }

                console.log('btnInput  done' + '  state: ' + this.state);

            },
            _run: function () {
                console.log('_run');
                this._setState('updating', 0);

                var parent = this;

                // play the sequence up to sequence count + 1
                // time is how long it will take to complete the playing the sequence
                // set state to waiting after sequence is done playing
                var promise = this._playSequence('waiting');

                // set timeout for failure i.e. player has this.inputTime to complete the sequence or this._failed is called
                // store the promise is this.failtimer so we can clear it
                // todo set fail timer
            },
            _generateSequence: function () {
                this.sequence = [];
                for (var i = 0; i < 20; i++) {
                    var num = Math.floor(Math.random() * (5 - 1)) + 1;
                    this.sequence.push(num);
                }
            },
            _playSequence: function (nextState) {
                console.log('_playSequence');

                var delay = this.timeDelay;
                var parent = this;

                this.promises.push(this._setState('playing', 0));

                for (var i = 0; i < this.seqCount + 1; i++) {
                    // push timeouts onto an array so we can clear them all if needed
                    // set timeout to turn button on

                    // todo remove functions from loop
                    // turn buttons on off
                    this.promises.push(this._btnOn(
                        this._getBtn(this.sequence[i]),
                        delay
                    ));
                    // set timeout to turn button off
                    this.promises.push(this._btnOff(
                        this._getBtn(this.sequence[i]),
                        delay + this.btnFlashTime
                    ));
                    delay += this.timeDelay;
                }
                // set state to nextState after sequence is done playing
                this.promises.push(parent._setState(nextState, delay));
                return this.promises[this.promises.length - 1];
            },
            _getBtn: function (nbr) {
                switch (nbr) {
                    case 1:
                        return 'btnGreen';
                    case 2:
                        return 'btnRed';
                    case 3:
                        return 'btnBlue';
                    case 4:
                        return 'btnYellow';
                }
            },
            _btnOn: function (btn, delay) {
                // callback tells the view to update
                if (callback === undefined) {
                    stackTrace('callback undefined!');
                }
                var parent = this;
                $timeout(function () {
                        parent[btn] = true;
                        parent.sndToPlay = parent[btn + 'Snd'];
                    }, delay
                );
            },
            _btnOff: function (btn, delay) {
                // callback tells the view to update
                if (callback === undefined) {
                    stackTrace('callback undefined!');
                }
                var parent = this;
                $timeout(function () {
                        parent[btn] = false;
                        parent.sndToPlay = undefined;
                    }, delay
                );
            },
            _error: function () {
                // tell view ctrler to flash ! ! on counter
                var parent = this;
                var time = this.flashTime;
                this.count = '! !';

                // tell view to update before we start flashing
                callback();

                var flashFunc = function () {
                    parent.counterOn = !parent.counterOn;
                };

                // tell view to flash ! !
                for (var i = 1; i < 6; i++) {
                    $timeout(flashFunc, time * i);
                }
                return time;
            },
            _clearTimeOuts: function () {
                this.promises.forEach(function (func) {
                    if (func !== undefined) {
                        $timeout.cancel(func);
                    }
                });
                this.promises = [];

                if (this.failTimer !== undefined) {
                    $timeout.cancel(this.failTimer);
                    this.failTimer = undefined;
                }
            },
            events: [],
            state: 'off',
            on: false,
            counterOn: false,
            strict: false,
            count: '- -',
            sequence: [],
            seqCount: 0,
            seqNum: 0,
            promises: [],
            btnGreen: false,
            btnGreenSnd: 'assets/sounds/simonSound1.mp3',
            btnRed: false,
            btnRedSnd: 'assets/sounds/simonSound2.mp3',
            btnBlue: false,
            btnBlueSnd: 'assets/sounds/simonSound3.mp3',
            btnYellow: false,
            btnYellowSnd: 'assets/sounds/simonSound4.mp3',
            timeDelay: 1500,            // millisecond time delay between buttons
            btnFlashTime: 1000,         // millisecond how long to leave a button on.
            inputTime: 8000,            // time player has to input the correct sequence
            autoRestartTime: 2000,       // millisecond how long to wait before restart
            flashTime: 300,
            sndToPlay: undefined,
            failTimer: undefined,
            heartBeat: undefined
        };

        var updateView = function () {
            $scope.onOff = simon.on;
            $scope.counterOn = simon.counterOn;
            $scope.strictLed = simon.strict;
            $scope.count = simon.count;
            $scope.greenBtnOn = simon.btnGreen;
            $scope.redBtnOn = simon.btnRed;
            $scope.blueBtnOn = simon.btnBlue;
            $scope.yellowBtnOn = simon.btnYellow;

            if (simon.sndToPlay !== undefined) {
                var audio = new Audio(simon.sndToPlay);
                audio.play();
            }
        };
        $scope.switchClick = function () {
            simon.toggleOnOff(updateView);
        };
        $scope.strictClick = function () {
            simon.toggleStrict(updateView);
        };
        $scope.btnPress = function (color) {
            simon.btnInput(color, updateView);
        };
        $scope.startBtn = function () {
            simon.start(updateView);
        };
        simon.setCallback(updateView);
        updateView();

    }])
;<|endoftext|>


<commit_before>'use strict';

angular.module('myApp.view3', ['ngRoute', 'ngResource'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider
	.when('/view3', {
		redirectTo: '/plan/{D57CCB0C-9E31-44BD-9A3C-F729891B56DF}'
	})
	.when('/plan/:guid', {
		templateUrl: 'view3/view3.html',
		controller: 'View3Ctrl'
	});
}])

.factory('gabiObject', ['$resource', function($resource){
	return $resource( "data/:guid.json", { guid: '@uuid'} );
}])

.controller('View3Ctrl', ['$scope', '$http', '$routeParams', 'gabiObject', function($scope, $http, $routeParams, gabiObject) {

  var first = function(){
    var s = Snap("#blackboard"); // This will use an existing svg element (not a div)

    var c = s.circle( 200,200,10 );
    var r = s.rect(200,100,100,100,20,20).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'red', 'opacity': 0.3 });

    var rclone = r.clone();
    var rclone2 = r.clone();
    var rclone3 = r.clone();
    var rclone4 = r.clone();
    var rclone5 = r.clone();

    //t=relative transform, T=absolute transform, s=relative scale, S=absolute Scale
    //r=relative rotate, R=relative rotate
    //relative means it takes into account previous transforms to accumulate
    //here it doesn't make much difference, until we combine later

    rclone.transform( 't100,100');
    rclone2.transform( 'r20,200,200' );
    rclone3.transform( 'r40,200,200' );

    s.text(350,150,"rotate around 200,200");

    rclone4.transform( 't100,100r20,200,200' );
    rclone5.transform( 't100,100r40,200,200' );

    s.text(450,250,"combined translate of 100,100 and rotate around 200,200");
  }
  first();

  var second = function(){
    var s = Snap("#svgout");
    var mapSvg = Snap.load("data/map.svg", function ( loadedFragment ) {
                                                s.append( loadedFragment );
                                        } );
  }
  second();

  var applyStandardFont = function(textelem){
		textelem.attr( { "font-size": "8pt" } );
  }

  var paintCommentInst = function(ciJson){
    var s = Snap("#owPlan");

    var ci = s.rect(
      ciJson["left"],
      ciJson["top"],
      ciJson["width"],
      ciJson["height"]).attr({
        stroke: "rgb(0,0,0)",
        "stroke-width": "0.5",
        fill: "rgb(255,255,128)"
      });
    var cmt = s.text( ciJson["left"]+5, ciJson["top"] + 15, ciJson["comment"] );
    applyStandardFont( cmt );
    var g = s.g(ci, cmt);
    g.drag();
  }

  var painterFnTemplate = function(x, y){
	  return function(name, guid){
      var s = Snap("#owPlan");
      var lnk = s.el("a").attr( { "xlink:href": "#/plan/" + guid } );
      var textelem = s.text(x+5, y+15, name);
      applyStandardFont(textelem);
      lnk.append(textelem);
	  }
  }

  var resolveAndPaintProcessInst = function(piJson, painterFn){
	var guid = { guid: piJson["process-ref"] };

	var myProcess = gabiObject.get( guid ).$promise.then(
		function(responseOK){
			painterFn( responseOK["name"], piJson["process-ref"]);
		},
		function(responseFail){
			painterFn("?");
		}
	);
  }

  var paintProcessInst = function(piJson){
    var s = Snap("#owPlan");

    var pi = s.rect(
      piJson["left"],
      piJson["top"],
      piJson["width"],
      piJson["height"]).attr({
        stroke: "#e1e1e1",
        "stroke-width": "0.75468",
        fill: "url(#linearGradient4156)"
      });

	var newFn = painterFnTemplate( piJson["left"], piJson["top"] );
	resolveAndPaintProcessInst( piJson, newFn );
  }

  var calcVector = function(ptStart, ptEnd){
    return {
      dirX: ptEnd.posX - ptStart.posX,
      dirY: ptEnd.posY - ptStart.posY,
      isLeftToRight: function(){ return (this.dirX>0   && this.dirY===0); },
      isRightToLeft: function(){ return (this.dirX<0   && this.dirY===0); },
      isTopToBottom: function(){ return (this.dirX===0 && this.dirY>0); },
      isBottomToTop: function(){ return (this.dirX===0 && this.dirY<0); }
    }
  }

  var paintArrowAt = function(x,y){
    var s = Snap("#owPlan");
    var arrowPath = "M" + x + " " + y + " l" + "-5 -5 l0 10 z";
    var arrow = s.path(arrowPath).attr({ fill: "rgb(0,0,255)", stroke: "rgb(0,0,255)" });
    return arrow;
  }

  var paintFlowInst = function(fiJson){
    var s = Snap("#owPlan");

    $scope.sorted = fiJson["points"].sort(function(left,right){
                                            var sortOrder = [0,2,1];
                                            return sortOrder[left.pointType] - sortOrder[right.pointType];
                                          });

    if ($scope.sorted.length > 0) {

      var pfad = [];

      for (var i = 0; i < $scope.sorted.length; i++) {
        var pt = $scope.sorted[i];
        pfad.push( pt.posX );
        pfad.push( pt.posY );
      }

      // paint flow instance line
      s.polyline(pfad).attr( { fill: "none", stroke: "rgb(0,0,255)", "stroke-width": "3" });

      var idx       = $scope.sorted.length;
      var lastPt    = $scope.sorted[idx-1];
      var butLastPt = $scope.sorted[idx-2];
      var arrowDirection = calcVector(butLastPt, lastPt);

      // paint arrow at end of line
      var arrow = paintArrowAt( lastPt.posX, lastPt.posY );

      var adon = ","+lastPt.posX+","+lastPt.posY;
      if (arrowDirection.isLeftToRight()){
      } else if (arrowDirection.isRightToLeft()) {
        arrow.transform("r180"+adon);
      } else if (arrowDirection.isTopToBottom()) {
        arrow.transform("r90"+adon);
      } else if (arrowDirection.isBottomToTop()) {
        arrow.transform("r270"+adon);
      };
    }
  }

  var fetchAndPaintVisibleQuantity = function(planJson, painterFn){
	  var guid = { guid: planJson["visibleQuantity-ref"] };
	  var visQnt = gabiObject.get( guid ).$promise.then(
		function(resonseOK){
			painterFn( resonseOK["name"] );
		},
		function(responseFail){
			painterFn( "?" );
		}
	  );
  }

  var michelangelo = function(planJson){
    var s = Snap("#owPlan");

    window.document.title = planJson["name"];
    var strPlanName = s.text( 15, 20, planJson["name"] ).attr({
        "font-size": "16pt",
        "font-style": "normal",
        "font-weight": "normal",
        "text-anchor": "start",
        "fill": "#000000",
        "font-family": "Segoe UI"
        });

    _.map( planJson["flowInstances"], paintFlowInst );
    _.map( planJson["processInstances"], paintProcessInst );
    _.map( planJson["commentInstances"], paintCommentInst );

    var paintVisibleQuantity = painterFnTemplate( 15, 20 );
    fetchAndPaintVisibleQuantity(planJson, paintVisibleQuantity);
  }

  var autsch = function(failData){
	var s = Snap("#owPlan");
	var txt = failData.status + " " + failData.statusText;
	s.text( 30, 52, txt ).attr( { "font-size": "48pt", "fill": "rgb(200,200,200)" } );
  }

  var fetch = function($scope){

	var rp = $routeParams;

	var guid = { guid: rp.guid };

	gabiObject.get( guid ).$promise.then(
		function(responseOK){
			$scope.aPlan = responseOK;
			michelangelo($scope.aPlan);
		},
		function(responseFail){
			$scope.failData = responseFail;
			autsch(responseFail);
		}
	);
  }
  fetch($scope);
}]);
<commit_msg>fine tuning: process instance box inside the true x,y,width,height box<commit_after>'use strict';

angular.module('myApp.view3', ['ngRoute', 'ngResource'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider
	.when('/view3', {
		redirectTo: '/plan/{D57CCB0C-9E31-44BD-9A3C-F729891B56DF}'
	})
	.when('/plan/:guid', {
		templateUrl: 'view3/view3.html',
		controller: 'View3Ctrl'
	});
}])

.factory('gabiObject', ['$resource', function($resource){
	return $resource( "data/:guid.json", { guid: '@uuid'} );
}])

.controller('View3Ctrl', ['$scope', '$http', '$routeParams', 'gabiObject', function($scope, $http, $routeParams, gabiObject) {

  var first = function(){
    var s = Snap("#blackboard"); // This will use an existing svg element (not a div)

    var c = s.circle( 200,200,10 );
    var r = s.rect(200,100,100,100,20,20).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'red', 'opacity': 0.3 });

    var rclone = r.clone();
    var rclone2 = r.clone();
    var rclone3 = r.clone();
    var rclone4 = r.clone();
    var rclone5 = r.clone();

    //t=relative transform, T=absolute transform, s=relative scale, S=absolute Scale
    //r=relative rotate, R=relative rotate
    //relative means it takes into account previous transforms to accumulate
    //here it doesn't make much difference, until we combine later

    rclone.transform( 't100,100');
    rclone2.transform( 'r20,200,200' );
    rclone3.transform( 'r40,200,200' );

    s.text(350,150,"rotate around 200,200");

    rclone4.transform( 't100,100r20,200,200' );
    rclone5.transform( 't100,100r40,200,200' );

    s.text(450,250,"combined translate of 100,100 and rotate around 200,200");
  }
  first();

  var second = function(){
    var s = Snap("#svgout");
    var mapSvg = Snap.load("data/map.svg", function ( loadedFragment ) {
                                                s.append( loadedFragment );
                                        } );
  }
  second();

  var applyStandardFont = function(textelem){
		textelem.attr( { "font-size": "8pt" } );
  }

  var paintCommentInst = function(ciJson){
    var s = Snap("#owPlan");

    var ci = s.rect(
      ciJson["left"],
      ciJson["top"],
      ciJson["width"],
      ciJson["height"]).attr({
        stroke: "rgb(0,0,0)",
        "stroke-width": "0.5",
        fill: "rgb(255,255,128)"
      });
    var cmt = s.text( ciJson["left"]+5, ciJson["top"] + 15, ciJson["comment"] );
    applyStandardFont( cmt );
    var g = s.g(ci, cmt);
    g.drag();
  }

  var painterFnTemplate = function(x, y){
	  return function(name, guid){
      var s = Snap("#owPlan");
      var lnk = s.el("a").attr( { "xlink:href": "#/plan/" + guid } );
      var textelem = s.text(x+5, y+15, name);
      applyStandardFont(textelem);
      lnk.append(textelem);
	  }
  }

  var resolveAndPaintProcessInst = function(piJson, painterFn){
	var guid = { guid: piJson["process-ref"] };

	var myProcess = gabiObject.get( guid ).$promise.then(
		function(responseOK){
			painterFn( responseOK["name"], piJson["process-ref"]);
		},
		function(responseFail){
			painterFn("?");
		}
	);
  }

  var paintProcessInst = function(piJson){
    var s = Snap("#owPlan");
    var strokeWidth = 0.75468
    var pi = s.rect(
          piJson["left"]   + strokeWidth,
          piJson["top"]    + strokeWidth,
          piJson["width"]  - strokeWidth,
          piJson["height"] - strokeWidth
      ).attr({
        stroke: "#e1e1e1",
        "stroke-width": strokeWidth,
        fill: "url(#linearGradient4156)"
      });

	var newFn = painterFnTemplate( piJson["left"], piJson["top"] );
	resolveAndPaintProcessInst( piJson, newFn );
  }

  var calcVector = function(ptStart, ptEnd){
    return {
      dirX: ptEnd.posX - ptStart.posX,
      dirY: ptEnd.posY - ptStart.posY,
      isLeftToRight: function(){ return (this.dirX>0   && this.dirY===0); },
      isRightToLeft: function(){ return (this.dirX<0   && this.dirY===0); },
      isTopToBottom: function(){ return (this.dirX===0 && this.dirY>0); },
      isBottomToTop: function(){ return (this.dirX===0 && this.dirY<0); }
    }
  }

  var paintArrowAt = function(x,y){
    var s = Snap("#owPlan");
    var arrowPath = "M" + x + " " + y + " l" + "-5 -5 l0 10 z";
    var arrow = s.path(arrowPath).attr({ fill: "rgb(0,0,255)", stroke: "rgb(0,0,255)" });
    return arrow;
  }

  var paintFlowInst = function(fiJson){
    var s = Snap("#owPlan");

    $scope.sorted = fiJson["points"].sort(function(left,right){
                                            var sortOrder = [0,2,1];
                                            return sortOrder[left.pointType] - sortOrder[right.pointType];
                                          });

    if ($scope.sorted.length > 0) {

      var pfad = [];

      for (var i = 0; i < $scope.sorted.length; i++) {
        var pt = $scope.sorted[i];
        pfad.push( pt.posX );
        pfad.push( pt.posY );
      }

      // paint flow instance line
      s.polyline(pfad).attr( { fill: "none", stroke: "rgb(0,0,255)", "stroke-width": "3" });

      var idx       = $scope.sorted.length;
      var lastPt    = $scope.sorted[idx-1];
      var butLastPt = $scope.sorted[idx-2];
      var arrowDirection = calcVector(butLastPt, lastPt);

      // paint arrow at end of line
      var arrow = paintArrowAt( lastPt.posX, lastPt.posY );

      var adon = ","+lastPt.posX+","+lastPt.posY;
      if (arrowDirection.isLeftToRight()){
      } else if (arrowDirection.isRightToLeft()) {
        arrow.transform("r180"+adon);
      } else if (arrowDirection.isTopToBottom()) {
        arrow.transform("r90"+adon);
      } else if (arrowDirection.isBottomToTop()) {
        arrow.transform("r270"+adon);
      };
    }
  }

  var fetchAndPaintVisibleQuantity = function(planJson, painterFn){
	  var guid = { guid: planJson["visibleQuantity-ref"] };
	  var visQnt = gabiObject.get( guid ).$promise.then(
		function(resonseOK){
			painterFn( resonseOK["name"] );
		},
		function(responseFail){
			painterFn( "?" );
		}
	  );
  }

  var michelangelo = function(planJson){
    var s = Snap("#owPlan");

    window.document.title = planJson["name"];
    var strPlanName = s.text( 15, 20, planJson["name"] ).attr({
        "font-size": "16pt",
        "font-style": "normal",
        "font-weight": "normal",
        "text-anchor": "start",
        "fill": "#000000",
        "font-family": "Segoe UI"
        });

    _.map( planJson["flowInstances"], paintFlowInst );
    _.map( planJson["processInstances"], paintProcessInst );
    _.map( planJson["commentInstances"], paintCommentInst );

    var paintVisibleQuantity = painterFnTemplate( 15, 20 );
    fetchAndPaintVisibleQuantity(planJson, paintVisibleQuantity);
  }

  var autsch = function(failData){
	var s = Snap("#owPlan");
	var txt = failData.status + " " + failData.statusText;
	s.text( 30, 52, txt ).attr( { "font-size": "48pt", "fill": "rgb(200,200,200)" } );
  }

  var fetch = function($scope){

	var rp = $routeParams;

	var guid = { guid: rp.guid };

	gabiObject.get( guid ).$promise.then(
		function(responseOK){
			$scope.aPlan = responseOK;
			michelangelo($scope.aPlan);
		},
		function(responseFail){
			$scope.failData = responseFail;
			autsch(responseFail);
		}
	);
  }
  fetch($scope);
}]);
<|endoftext|>


<commit_before>'use strict';

angular.module('myApp.view4', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/view4', {
    templateUrl: 'view4/view4.html',
    controller: 'View4Ctrl'
  });
}])

.controller('View4Ctrl', [function() {
	var image = new Image();
	image.onload = function() {
		var imageElement = angular.element(document.getElementById("noImage4"));
		imageElement.attr('src', image.src);
	}

	image.src = "https://raw.githubusercontent.com/oburakevych/progressive-image-loading/master/app/images/avatar-1260x1600xcopy4.jpg";
}]);<commit_msg>fix image name<commit_after>'use strict';

angular.module('myApp.view4', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/view4', {
    templateUrl: 'view4/view4.html',
    controller: 'View4Ctrl'
  });
}])

.controller('View4Ctrl', [function() {
	var image = new Image();
	image.onload = function() {
		var imageElement = angular.element(document.getElementById("noImage4"));
		imageElement.attr('src', image.src);
	}

	image.src = "https://raw.githubusercontent.com/oburakevych/progressive-image-loading/master/app/images/avatar-1260x1600-copy4.jpg";
}]);<|endoftext|>


<commit_before>const h = require('virtual-dom/h');
const logo = require('./logo');

module.exports = function (data) {
  const {lastTweet, games} = data;
  const gameIDs = Object.keys(games);
  return h('div', {className: 'index'}, [
    h('audio', {src: '/8bit-love-machine.mp3', autoplay: true, loop: true}),
    logo(),
    h('p', {id: 'tweet'}, lastTweet),
    gameIDs.length > 0 ?
      gameList(games) :
      h('p', {id: 'no-games'}, 'No Luaus found'),
      h('form', {action: '/', method: 'post'},
        h('button', 'Create Luau')
      )
  ]);
};

function gameList(games) {
  return h('div', {id: 'games-list'}, [
    h('h2', 'Games'),
    h('ul', Object.keys(games).map(gameID =>
      h('li', {className: Object.keys(games[gameID].playing) === true ? 'playing' : ''},
        h('a', {href: '/' + gameID}, [
          games[gameID].name,
          h('span', `${Object.keys(games[gameID].players).length} ${Object.keys(games[gameID].players).length === 1 ? 'player' : 'players'}`)
        ])
      )
    ))
  ]);
}
<commit_msg>Fix playing class on index<commit_after>const h = require('virtual-dom/h');
const logo = require('./logo');

module.exports = function (data) {
  const {lastTweet, games} = data;
  const gameIDs = Object.keys(games);
  return h('div', {className: 'index'}, [
    h('audio', {src: '/8bit-love-machine.mp3', autoplay: true, loop: true}),
    logo(),
    h('p', {id: 'tweet'}, lastTweet),
    gameIDs.length > 0 ?
      gameList(games) :
      h('p', {id: 'no-games'}, 'No Luaus found'),
      h('form', {action: '/', method: 'post'},
        h('button', 'Create Luau')
      )
  ]);
};

function gameList(games) {
  return h('div', {id: 'games-list'}, [
    h('h2', 'Games'),
    h('ul', Object.keys(games).map(gameID =>
      h('li', {className: games[gameID].playing ? 'playing' : ''},
        h('a', {href: '/' + gameID}, [
          games[gameID].name,
          h('span', `${Object.keys(games[gameID].players).length} ${Object.keys(games[gameID].players).length === 1 ? 'player' : 'players'}`)
        ])
      )
    ))
  ]);
}
<|endoftext|>


<commit_before>
var numCols = 4;
var pictureDimension = 256;
var animationDuration = 200;

SproutGram.PhotoView = SC.View.extend({

  itemIndexBinding: 'parentView.content.itemIndex',

  isZoomedIn: false,

  tapEnd: function() {
    console.log('tapEnd');
    if (this.get('isZoomedIn')) {
      this._resetTransforms();
    }
    else {
      this._centerPhoto();
    }
  },

  touchStart: function(evt) {
    console.log('touchStart');
    this.$().css('z-index',10);
    $('#curtain').css({
     zIndex: 2,
     opacity: (this.get('isZoomedIn'))? 0.8 : 0
    });
  },

  mouseDown: function() {
    this.touchStart();
  },

  mouseUp: function() {
    this.tapEnd();
  },

  pinchChange: function(recognizer) {
    var jq = this.$();
    var newScale = recognizer.get('scale');
    var curScale = jq.css('scale');

    var boundedScale = Math.max(1,Math.min(1.8, curScale * newScale));
    $('#curtain').css('opacity',boundedScale-1);

    this.$().css('scale',function(index, value) {
      return newScale * value
    });
  },

  pinchEnd: function(recognizer) {
    console.log('pinchEnd');
    var velocity = recognizer.get('velocity');

    if (velocity >= 0) {
      this._centerPhoto();
    }
    else {
      this._resetTransforms();
    }
  },

  panOptions: {
    numberOfRequiredTouches: 2
  },

  panChange: function(recognizer) {
    var val = recognizer.get('translation');

    this.$().css({
      translateX: '%@=%@'.fmt((val.x < 0)? '-' : '+',Math.abs(val.x)),
      translateY: '%@=%@'.fmt((val.y < 0)? '-' : '+',Math.abs(val.y))
    });
  },

  _resetTransforms: function(accepted) {
    var self = this;
    var position = this._resetPosition();
    this.set('isZoomedIn',false);

    $('#curtain').animate({
      opacity:0
    },animationDuration);

    this.$().animate({
      scale: 1,
      translateX: 0,
      translateY: 0,
      top: position.top,
      left: position.left,
      width: position.width,
      height: position.height,
    }, animationDuration, function() {
      $('#curtain').css('z-index',0);
      self.$().css('z-index',1);
    })
  },

  _centerPhoto: function() {
    var self = this;
    this.set('isZoomedIn',true);

    $('#curtain').animate({
      opacity:0.8
    },animationDuration);

    this.$().animate({
      scale: 1.5,
      translateX: 0,
      translateY: 0,

      top: 0,
      left: 0,
      width: window.innerWidth,
      height: window.innerHeight
    },animationDuration)
  },

  willInsertElement: function() {
    this.$().css(this._resetPosition());
  },

  _resetPosition: function() {
    var el = this.$();
    var idx = this.get('itemIndex');

    var row = Math.floor(idx / numCols);
    var col = idx % numCols;

    return {
      top: row * pictureDimension,
      left: col * pictureDimension,
      width: pictureDimension,
      height: pictureDimension
    };
  },

  didInsertElement: function() {
    var canvas = this.$('canvas.image_canvas')[0];
    if (!canvas) return;

    var image = new Image();
    image.src = this.getPath('parentView.content.standard_res');

    image.onload = function() {
      var ctx = canvas.getContext('2d');

      ctx.drawImage(image,50,50,500,500,0,0,pictureDimension,pictureDimension);
    }
  }
});
<commit_msg>Rearrange the file so it makes a bit more sense<commit_after>
//......................................................................
// Constants

var numCols = 4;
var pictureDimension = 256;
var animationDuration = 200;
var easing = "easeOutExpo";

//......................................................................
// Utilities

jQuery.extend( jQuery.easing,
{
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
});

//......................................................................
// Main Class

SproutGram.PhotoView = SC.View.extend({

  itemIndexBinding: 'parentView.content.itemIndex',
  usernameBinding: 'parentView.content.username',

  isZoomedIn: false,

  willInsertElement: function() {
    this.$().css(this._resetPosition());
    this.$('.username').css({
      rotateY: Math.PI
    });
  },

  didInsertElement: function() {
    var canvas = this.$('canvas.image_canvas')[0];
    if (!canvas) return;

    var image = new Image();
    image.src = this.getPath('parentView.content.standard_res');

    image.onload = function() {
      var ctx = canvas.getContext('2d');

      ctx.drawImage(image,50,50,500,500,0,0,pictureDimension,pictureDimension);
    }
  },

  //.................................................................
  // Event Handlers

  touchStart: function(evt) {
    this.$().css('z-index',10);
    $('#curtain').css({
     zIndex: 2,
     opacity: (this.get('isZoomedIn'))? 0.8 : 0
    });
  },

  tapEnd: function() {
    if (this.get('isZoomedIn')) {
      this._resetTransforms();
    }
    else {
      this._centerPhoto();
    }
  },

  mouseDown: function() {
    this.touchStart();
  },

  mouseUp: function() {
    this.tapEnd();
  },

  pinchChange: function(recognizer) {
    var jq = this.$();
    var newScale = recognizer.get('scale');
    var curScale = jq.css('scale');

    var boundedScale = Math.max(1,Math.min(1.8, curScale * newScale));
    $('#curtain').css('opacity',boundedScale-1);

    this.$().css('scale',function(index, value) {
      return newScale * value
    });
  },

  pinchEnd: function(recognizer) {
    var velocity = recognizer.get('velocity');

    if (velocity >= 0) {
      this._centerPhoto();
    }
    else {
      this._resetTransforms();
    }
  },

  panOptions: {
    numberOfRequiredTouches: 2
  },

  panChange: function(recognizer) {
    var val = recognizer.get('translation');

    this.$().css({
      translateX: '%@=%@'.fmt((val.x < 0)? '-' : '+',Math.abs(val.x)),
      translateY: '%@=%@'.fmt((val.y < 0)? '-' : '+',Math.abs(val.y))
    });
  },

  //.................................................................
  // Transforms

  _centerPhoto: function() {
    var self = this;

    this.set('isZoomedIn',true);

    $('#curtain').animate({
      opacity:0.8
    }, animationDuration, easing);

    this.$().animate({
      scale: 1,
      translateX: 0,
      translateY: 0,

      top: document.body.scrollTop,
      left: 0,
      width: window.innerWidth,
      height: window.innerHeight
    }, {

      duration: animationDuration * 3,
      easing: easing,
      complete: function() {
        setTimeout(function() {
          self._showDetails()
        }, 300);
      }

    })

    // this.$('.username').animate({
    //   rotateY: 0
    // }, 400);
  },

  _showDetails: function() {

    this.$('.username').css({
      'WebkitTransformOrigin': '0 50%'
    });

    this.$('.username').animate({
      rotateY: Math.PI
    }, 500, "easeOutElastic");
  },

  _resetTransforms: function(accepted) {
    var self = this;
    var position = this._resetPosition();
    this.set('isZoomedIn',false);

    $('#curtain').animate({
      opacity:0
    },animationDuration,easing);

    this.$().animate({
      scale: 1,
      translateX: 0,
      translateY: 0,
      top: position.top,
      left: position.left,
      width: position.width,
      height: position.height,
    }, animationDuration, easing, function() {
      $('#curtain').css('z-index',0);
      self.$().css('z-index',1);
    });
    this.$('.username').css({
      rotateY: Math.PI
    });
  },

  _resetPosition: function() {
    var el = this.$();
    var idx = this.get('itemIndex');

    var row = Math.floor(idx / numCols);
    var col = idx % numCols;

    return {
      top: row * pictureDimension,
      left: col * pictureDimension,
      width: pictureDimension,
      height: pictureDimension
    };
  }

});
<|endoftext|>


<commit_before>var cexio = require('cexio'),
   moment = require('moment'),
     nedb = require('nedb'),
    async = require('async'),
       db = new nedb({filename: 'cexio.db', autoload: true}),
        _ = require('lodash'),
     util = require('../util'),
      log = require('../log');

var Trader = function(config) {
  this.user = config.username;
  this.key = config.key;
  this.secret = config.secret;
  this.pair = 'ghs_' + config.currency.toLowerCase();
  this.name = 'cex.io';
  this.next_tid = 0;

  _.bindAll(this);

  this.cexio = new cexio(this.pair, this.user,
                        this.key, this.secret);
}

Trader.prototype.getTrades = function(since, callback, descending) {
  var self = this;
  var last_tid = next_tid = 0;

  if(since && !_.isNumber(since))
    since = util.toMicro(since);

  var args = _.toArray(arguments);

  // FIXME:  fetching and updating our db shall be done in an seperate
  // thread (timeout-callback) rather than here.  This method shall
  // only fetch and return from local db.

  async.waterfall([
    function(callback) {
      db.find({}, function(err, docs) {
        if(!docs || docs.length === 0)
          tid = 263000;
        else
          tid = 1 + _.max(docs, 'tid').tid;

        //log.info(self.name, 'Updating cex.io historical data store');
        log.debug(self.name, 'fetching from tid ' + tid);

        self.cexio.trades({since: tid},
          function(err, trades) {
            if(err || !trades || trades.length === 0)
              return self.retry(self.getTrades, args);
            else if('error' in trades)
              throw 'Error from cexio: ' + trades.error
            else {
              trades = trades.reverse();
              _.forEach(trades, function(trade) {
                // convert to int
                trade.amount = Number(trade.amount);
                trade.price = Number(trade.price);
                trade.tid = Number(trade.tid);
                trade.date = Number(trade.date);
                db.insert(trade);
              });
            }
            callback();
        });
      });
    },
    function(callback) {
      if(!since) {
        since = new Date().getTime() * 1000;
        since -= (10 * 1000 * 1000);
      }
      since = Math.floor(since / 1000 / 1000);
      log.debug('fetching since ' + since);

      db.find({'date': {$gte: since}}, function(err, docs) {
        docs = _.sortBy(docs, 'tid');
        // log.debug(self.name, docs);
        if(!docs || docs.length === 0)
          return self.retry(self.getTrades, args);
        callback(null, docs);
      });
    }
  ], function(err, result) {
    if(err) return log.error(self.name, 'error: ' + err);
    callback(result);
  });
}

Trader.prototype.buy = function(amount, price, callback) {
  // Prevent "You incorrectly entered one of fields."
  // because of more than 8 decimals.
  amount *= 100000000;
  amount = Math.floor(amount);
  amount /= 100000000;

  // test placing orders which will not be filled
  //price /=10; price = price.toFixed(8);

  log.debug('BUY', amount, 'GHS @', price, 'BTC');

  var set = function(err, data) {
    if(err)
      return log.error('unable to buy:', err);
    if(data.error)
      return log.error('unable to buy:', data.error);

    log.debug('BUY order placed.  Order ID', data.id);
    callback(data.id);
  };

  this.cexio.place_order('buy', amount, price, _.bind(set, this));
}

Trader.prototype.sell = function(amount, price, callback) {
  // Prevent "You incorrectly entered one of fields."
  // because of more than 8 decimals.
  amount *= 100000000;
  amount = Math.ceil(amount);
  amount /= 100000000;

  // test placing orders which will not be filled
  //price *= 10; price = price.toFixed(8);

  log.debug('SELL', amount, 'GHS @', price, 'BTC');

  var set = function(err, data) {
    if(err)
      return log.error('unable to sell:', err);
    if(data.error)
      return log.error('unable to sell:', data.error);

    log.debug('SELL order placed.  Order ID', data.id);
    callback(data.id);
  };

  this.cexio.place_order('sell', amount, price, _.bind(set, this));
}

Trader.prototype.retry = function(method, args) {
  var wait = +moment.duration(10, 'seconds');
  log.debug(this.name, 'returned an error, retrying..');

  var self = this;

  // make sure the callback (and any other fn)
  // is bound to Trader
  _.each(args, function(arg, i) {
    if(_.isFunction(arg))
      args[i] = _.bind(arg, self);
  });

  // run the failed method again with the same
  // arguments after wait
  setTimeout(
    function() { method.apply(self, args) },
    wait
  );
}

Trader.prototype.getPortfolio = function(callback) {
  var calculate = function(err, data) {
    if(err)
      return this.retry(this.cexio.getInfo, calculate);

    currency = parseFloat(data.BTC.available) - parseFloat(data.BTC.orders);
    assets = parseFloat(data.GHS.available) - parseFloat(data.GHS.orders);

    var portfolio = [];
    portfolio.push({name: 'BTC', amount: currency});
    portfolio.push({name: 'GHS', amount: assets});
    callback(err, portfolio);
  }
  this.cexio.balance(_.bind(calculate, this));
}

Trader.prototype.getTicker = function(callback) {
  var set = function(err, data) {
    var ticker = {
      ask: data.ask,
      bid: data.bid
    };
    callback(err, ticker);
  }
  this.cexio.ticker(_.bind(set, this));
}

Trader.prototype.getFee = function(callback) {
  // cexio does currently don't take a fee on trades
  callback(false, 0.0);
}

Trader.prototype.checkOrder = function(order, callback) {
  var check = function(err, result) {

    if(err)
      callback(false, true);
    if(result.error)
      callback(false, true);

    var exists = false;
    _.forEach(result, function(entry) {
      if(entry.id === order) {
        exists = true; return;
      }
    });
    callback(err, !exists);
  };

  this.cexio.open_orders(_.bind(check, this));
}

Trader.prototype.cancelOrder = function(order) {
  var check= function(err, result) {
    if(err)
      log.error('cancel order failed:', err);
    if(result.error)
      log.error('cancel order failed:', result.error);
  }
  this.cexio.cancel_order(order, check);
}

module.exports = Trader;
<commit_msg>Gekko can't pull GHS balance from cex.io<commit_after>var cexio = require('cexio'),
   moment = require('moment'),
     nedb = require('nedb'),
    async = require('async'),
       db = new nedb({filename: 'cexio.db', autoload: true}),
        _ = require('lodash'),
     util = require('../util'),
      log = require('../log');

var Trader = function(config) {
  this.user = config.username;
  this.key = config.key;
  this.secret = config.secret;
  this.pair = 'ghs_' + config.currency.toLowerCase();
  this.name = 'cex.io';
  this.next_tid = 0;

  _.bindAll(this);

  this.cexio = new cexio(this.pair, this.user,
                        this.key, this.secret);
}

Trader.prototype.getTrades = function(since, callback, descending) {
  var self = this;
  var last_tid = next_tid = 0;

  if(since && !_.isNumber(since))
    since = util.toMicro(since);

  var args = _.toArray(arguments);

  // FIXME:  fetching and updating our db shall be done in an seperate
  // thread (timeout-callback) rather than here.  This method shall
  // only fetch and return from local db.

  async.waterfall([
    function(callback) {
      db.find({}, function(err, docs) {
        if(!docs || docs.length === 0)
          tid = 263000;
        else
          tid = 1 + _.max(docs, 'tid').tid;

        //log.info(self.name, 'Updating cex.io historical data store');
        log.debug(self.name, 'fetching from tid ' + tid);

        self.cexio.trades({since: tid},
          function(err, trades) {
            if(err || !trades || trades.length === 0)
              return self.retry(self.getTrades, args);
            else if('error' in trades)
              throw 'Error from cexio: ' + trades.error
            else {
              trades = trades.reverse();
              _.forEach(trades, function(trade) {
                // convert to int
                trade.amount = Number(trade.amount);
                trade.price = Number(trade.price);
                trade.tid = Number(trade.tid);
                trade.date = Number(trade.date);
                db.insert(trade);
              });
            }
            callback();
        });
      });
    },
    function(callback) {
      if(!since) {
        since = new Date().getTime() * 1000;
        since -= (10 * 1000 * 1000);
      }
      since = Math.floor(since / 1000 / 1000);
      log.debug('fetching since ' + since);

      db.find({'date': {$gte: since}}, function(err, docs) {
        docs = _.sortBy(docs, 'tid');
        // log.debug(self.name, docs);
        if(!docs || docs.length === 0)
          return self.retry(self.getTrades, args);
        callback(null, docs);
      });
    }
  ], function(err, result) {
    if(err) return log.error(self.name, 'error: ' + err);
    callback(result);
  });
}

Trader.prototype.buy = function(amount, price, callback) {
  // Prevent "You incorrectly entered one of fields."
  // because of more than 8 decimals.
  amount *= 100000000;
  amount = Math.floor(amount);
  amount /= 100000000;

  // test placing orders which will not be filled
  //price /=10; price = price.toFixed(8);

  log.debug('BUY', amount, 'GHS @', price, 'BTC');

  var set = function(err, data) {
    if(err)
      return log.error('unable to buy:', err);
    if(data.error)
      return log.error('unable to buy:', data.error);

    log.debug('BUY order placed.  Order ID', data.id);
    callback(data.id);
  };

  this.cexio.place_order('buy', amount, price, _.bind(set, this));
}

Trader.prototype.sell = function(amount, price, callback) {
  // Prevent "You incorrectly entered one of fields."
  // because of more than 8 decimals.
  amount *= 100000000;
  amount = Math.ceil(amount);
  amount /= 100000000;

  // test placing orders which will not be filled
  //price *= 10; price = price.toFixed(8);

  log.debug('SELL', amount, 'GHS @', price, 'BTC');

  var set = function(err, data) {
    if(err)
      return log.error('unable to sell:', err);
    if(data.error)
      return log.error('unable to sell:', data.error);

    log.debug('SELL order placed.  Order ID', data.id);
    callback(data.id);
  };

  this.cexio.place_order('sell', amount, price, _.bind(set, this));
}

Trader.prototype.retry = function(method, args) {
  var wait = +moment.duration(10, 'seconds');
  log.debug(this.name, 'returned an error, retrying..');

  var self = this;

  // make sure the callback (and any other fn)
  // is bound to Trader
  _.each(args, function(arg, i) {
    if(_.isFunction(arg))
      args[i] = _.bind(arg, self);
  });

  // run the failed method again with the same
  // arguments after wait
  setTimeout(
    function() { method.apply(self, args) },
    wait
  );
}

Trader.prototype.getPortfolio = function(callback) {
  var calculate = function(err, data) {
    if(err)
      return this.retry(this.cexio.getInfo, calculate);

    currency = parseFloat(data.BTC.available)
    if(parseFloat(data.BTC.orders)){
      currency -= parseFloat(data.BTC.orders)
    }
    assets = parseFloat(data.GHS.available);
    if( parseFloat(data.GHS.orders)){
	  assets -= parseFloat(data.GHS.orders);
    }

    var portfolio = [];
    portfolio.push({name: 'BTC', amount: currency});
    portfolio.push({name: 'GHS', amount: assets});
    callback(err, portfolio);
  }
  this.cexio.balance(_.bind(calculate, this));
}

Trader.prototype.getTicker = function(callback) {
  var set = function(err, data) {
    var ticker = {
      ask: data.ask,
      bid: data.bid
    };
    callback(err, ticker);
  }
  this.cexio.ticker(_.bind(set, this));
}

Trader.prototype.getFee = function(callback) {
  // cexio does currently don't take a fee on trades
  callback(false, 0.0);
}

Trader.prototype.checkOrder = function(order, callback) {
  var check = function(err, result) {

    if(err)
      callback(false, true);
    if(result.error)
      callback(false, true);

    var exists = false;
    _.forEach(result, function(entry) {
      if(entry.id === order) {
        exists = true; return;
      }
    });
    callback(err, !exists);
  };

  this.cexio.open_orders(_.bind(check, this));
}

Trader.prototype.cancelOrder = function(order) {
  var check= function(err, result) {
    if(err)
      log.error('cancel order failed:', err);
    if(result.error)
      log.error('cancel order failed:', result.error);
  }
  this.cexio.cancel_order(order, check);
}

module.exports = Trader;
<|endoftext|>


<commit_before>var fs = require( 'fs' );
var git = require( 'nodegit' );
var mongo = require( 'mongodb' );
var monk = require( 'monk' );
var db = monk( 'localhost:27017/pelias' );

function addTests( testsJson, cb ){
  var peliasCollection = db.get( 'pelias' );

  peliasCollection.find({}, function (err, docs){
    if( err ){
      console.error( err );
      process.exit( 1 );
    }

    docs.forEach( function ( doc ){
      var expectedOutput = null;
      if( doc.foundInPelias ){
        var testCaseProps = doc.selected[ 0 ].properties;
        delete testCaseProps.id;
        expectedOutput = testCaseProps;
      }
      else if( 'selected' in doc ){
        expectedOutput = doc.selected[ 0 ].display_name;
      }

      testsJson.tests.push({
        id: 1,
        user: 'feedback-app',
        in: {
          input: doc.query
        },
        out: expectedOutput
      });
    });

    cb( testsJson );
    db.close();
  });
}

function updateTestFile( testFilePath ){
  var testsJson = JSON.parse(fs.readFileSync( testFilePath ));
  addTests( testsJson, function writeNewFile( newTestJson ){
    fs.writeFile( testFilePath, JSON.stringify( newTestJson, undefined, 2 ) );
  });
}

if( process.argv.length !== 3 ){
  console.error(
    'Incorrect number of arguments. Usage:\n\n' +
    '\tnode generate_tests.js PATH/TO/acceptance-tests/test_cases/search.json'
  );
  process.exit( 1 );
}
else {
  updateTestFile( process.argv[ 2 ] );
}
<commit_msg>Add documentation comments to generate_tests.js.<commit_after>/**
 * Given a path to a `pelias/acceptance-tests` tests JSON file, add the tests
 * in the local Mongo server's Pelias collection (as stored by the feedback
 * app) to it.
 */

var fs = require( 'fs' );
var git = require( 'nodegit' );
var mongo = require( 'mongodb' );
var monk = require( 'monk' );
var db = monk( 'localhost:27017/pelias' );

/**
 * Extract tests-cases from Mongo, conform them to the
 * `pelias/acceptance-tests` format, inject them into the `testsJson` object,
 * and pass it to `cb()`.
 */
function addTests( testsJson, cb ){
  var peliasCollection = db.get( 'pelias' );

  peliasCollection.find({}, function (err, docs){
    if( err ){
      console.error( err );
      process.exit( 1 );
    }

    docs.forEach( function ( doc ){
      var expectedOutput = null;
      if( doc.foundInPelias ){
        var testCaseProps = doc.selected[ 0 ].properties;
        delete testCaseProps.id;
        expectedOutput = testCaseProps;
      }
      else if( 'selected' in doc ){
        expectedOutput = doc.selected[ 0 ].display_name;
      }

      testsJson.tests.push({
        id: 1,
        user: 'feedback-app',
        in: {
          input: doc.query
        },
        out: expectedOutput
      });
    });

    cb( testsJson );
    db.close();
  });
}

/**
 * Modify the JSON tests file specified by `testFilePath`, adding test cases to
 * its `tests` property.
 */
function updateTestFile( testFilePath ){
  var testsJson = JSON.parse(fs.readFileSync( testFilePath ));
  addTests( testsJson, function writeNewFile( newTestJson ){
    fs.writeFile( testFilePath, JSON.stringify( newTestJson, undefined, 2 ) );
  });
}

if( process.argv.length !== 3 ){
  console.error(
    'Incorrect number of arguments. Usage:\n\n' +
    '\tnode generate_tests.js PATH/TO/acceptance-tests/test_cases/search.json'
  );
  process.exit( 1 );
}
else {
  updateTestFile( process.argv[ 2 ] );
}
<|endoftext|>


<commit_before>loadTemplate(
  prompt('Which template do you want to load?', 'lively-toolbox'),
  prompt('Where does your server run?', 'http://localhost:8081/lively4-core/'));

function loadTemplate (partName, url) {
  lively4Url = url;
  loadJQuery();
  loadSystem();
  setTimeout(function () {
    loadBabel();
    loadLively4();
    loadAce();
    loadPartViaLinkTag(partName);
    mountPart(partName);
  }, 1000)
}

function loadPartViaLinkTag (partName) {
  var linkTag = document.createElement('link');
  linkTag.setAttribute('rel', 'import');
  linkTag.setAttribute('href', lively4Url + 'templates/' + partName + '.html');
  document.head.appendChild(linkTag);
}

function mountPart(partIdentifierString) {
  var aToolbox = document.createElement(partIdentifierString);
  document.body.insertBefore(aToolbox, document.body.firstChild);
  aToolbox.style.setProperty('position', 'fixed');
  aToolbox.style.setProperty('z-index', 10000);
}

function loadAce() {
  var aceNode = document.createElement('script');
  aceNode.setAttribute('type', 'text/javascript');
  aceNode.setAttribute('src', lively4Url + 'src/external/ace.js');
  document.head.appendChild(aceNode);
}

function loadJQuery () {
  var jQueryNode = document.createElement('script');
  jQueryNode.setAttribute('type', 'text/javascript');
  jQueryNode.setAttribute('src', 'https://code.jquery.com/jquery-2.1.4.js');
  document.head.appendChild(jQueryNode);
}

function loadSystem () {
  $.get(lively4Url + 'src/external/system.src.js', function(data) {
    data = data.replace(
      'var baseURIObj = new URL(baseURI);',
      'var baseURIObj = new URL("' + lively4Url + '");' );
    var systemScriptNode = document.createElement('script');
    systemScriptNode.setAttribute('type', 'text/javascript');
    systemScriptNode.innerHTML = data;
    document.head.appendChild(systemScriptNode);
  })
}

function loadBabel () {
  var babelLoaderNode = document.createElement('script');
  babelLoaderNode.setAttribute('type', 'text/javascript');
  babelLoaderNode.innerHTML = '' + '\n' +
    "System.paths['babel'] = '" + lively4Url + "src/external/babel-browser.js'" + '\n' +
    "System.config({" + '\n' +
      "transpiler: 'babel'," + '\n' +
      "babelOptions: { }," + '\n' +
      "map: {" + '\n' +
          "babel: '" + lively4Url + "src/external/babel-browser.js'" + '\n' +
      "}" + '\n' +
    "});"
  document.head.appendChild(babelLoaderNode);
  System.config({
    baseURL: lively4Url + 'draft/'
  });
}

function loadLively4 () {
  System.import(lively4Url + "src/client/load.js").then(function(){

  }).catch(function(err) { alert("load Lively4 failed")});
  System.import(lively4Url + "src/client/script-manager.js").then(function(module) {
      window.scriptManager = module;
      log("scriptManager loaded");
  });
  System.import(lively4Url + "src/client/persistence.js").then(function(module) {
      window.persistence = module;
      log("persistence loaded");
  });
}
<commit_msg>setting correct baseURI to /draft/, since we can only load pages that are in subfolder of lively4-core (this should be changed sometime!!!)<commit_after>loadTemplate(
  prompt('Which template(s) do you want to load?', 'lively-halos'),
  prompt('Where does your server run?', 'http://localhost:8081/lively4-core/'));

function loadTemplate (partName, url) {
  lively4Url = url;
  loadJQuery();
  loadSystem();
  setTimeout(function () {
    loadBabel();
    loadLively4();
    loadAce();
    loadPartViaLinkTag(partName);
    mountPart(partName);
  }, 1000)
}

function loadPartViaLinkTag (partName) {
  var linkTag = document.createElement('link');
  linkTag.setAttribute('rel', 'import');
  linkTag.setAttribute('href', lively4Url + 'templates/' + partName + '.html');
  document.head.appendChild(linkTag);
}

function mountPart(partIdentifierString) {
  var aToolbox = document.createElement(partIdentifierString);
  document.body.insertBefore(aToolbox, document.body.firstChild);
  aToolbox.style.setProperty('position', 'fixed');
  aToolbox.style.setProperty('z-index', 10000);
}

function loadAce() {
  var aceNode = document.createElement('script');
  aceNode.setAttribute('type', 'text/javascript');
  aceNode.setAttribute('src', lively4Url + 'src/external/ace.js');
  document.head.appendChild(aceNode);
}

function loadJQuery () {
  var jQueryNode = document.createElement('script');
  jQueryNode.setAttribute('type', 'text/javascript');
  jQueryNode.setAttribute('src', 'https://code.jquery.com/jquery-2.1.4.js');
  document.head.appendChild(jQueryNode);
}

function loadSystem () {
  $.get(lively4Url + 'src/external/system.src.js', function(data) {
    data = data.replace(
      'var baseURIObj = new URL(baseURI);',
      'var baseURIObj = new URL("' + lively4Url + 'draft/");' );
    var systemScriptNode = document.createElement('script');
    systemScriptNode.setAttribute('type', 'text/javascript');
    systemScriptNode.innerHTML = data;
    document.head.appendChild(systemScriptNode);
  })
}

function loadBabel () {
  var babelLoaderNode = document.createElement('script');
  babelLoaderNode.setAttribute('type', 'text/javascript');
  babelLoaderNode.innerHTML = '' + '\n' +
    "System.paths['babel'] = '" + lively4Url + "src/external/babel-browser.js'" + '\n' +
    "System.config({" + '\n' +
      "transpiler: 'babel'," + '\n' +
      "babelOptions: { }," + '\n' +
      "map: {" + '\n' +
          "babel: '" + lively4Url + "src/external/babel-browser.js'" + '\n' +
      "}" + '\n' +
    "});"
  document.head.appendChild(babelLoaderNode);
  System.config({
    baseURL: lively4Url + 'draft/'
  });
}

function loadLively4 () {
  System.import(lively4Url + "src/client/load.js").then(function(){

  }).catch(function(err) { alert("load Lively4 failed")});
  System.import(lively4Url + "src/client/script-manager.js").then(function(module) {
      window.scriptManager = module;
      log("scriptManager loaded");
  });
  System.import(lively4Url + "src/client/persistence.js").then(function(module) {
      window.persistence = module;
      log("persistence loaded");
  });
}
<|endoftext|>


<commit_before>require(['jquery'], function ($) {
    var firstLoading  = true,
        jsonBase      = wity_base_url + 'm/crs',
        refreshTimer  = 1, // In seconds
        $crs_app      = $('.wity-app-crs.wity-app-crs-overlay'),
        $heroes_list  = $crs_app.find('ul.heroes-list'),
        $players_list = $crs_app.find('ul.players-list'),
        $safari_timer = $crs_app.find('div.safari-timer');

    function refreshContent() {
        $.getJSON(jsonBase, function (json) {
            if (!('result' in json)) {
                return;
            }

            var result = json.result;

            // Display the target on the correct hero
            loadTarget(result);

            // Refresh target kill count
            if (firstLoading) {
                $players_list.children().fadeOut(500, function () {
                    $players_list.empty();
                    loadPlayers(result);
                    loadOptions(result);
                });
            } else {
                $players_list.empty();
                loadPlayers(result);
                loadOptions(result);
            }

            firstLoading = false;
        });
    }

    function loadTarget(result) {
        $heroes_list
            .find('li')
            .removeClass('target transition');

        if ('target' in result) {
            $heroes_list
                .find('li:nth-child(' + result.target + ')')
                .addClass(function () {
                    return 'target' + (firstLoading ? ' transition' : '');
                });
        }
    }

    function loadPlayers(result) {
        if ('players' in result) {
            var players = result.players;

            $.each(players, function (index, player) {
                var $player = $('<li>').addClass('player-' + (index + 1));

                if ('hero' in player && player.hero !== false) {
                    $player.append($('<i>').addClass('miniheroes-sprite miniheroes-sprite-'+player.hero.icon));
                }

                $player.append($('<span>').text(player.name + ' : ' + player.kills));

                $players_list.append($player);
            });
        }
    }

    function loadOptions(result) {
        // Refresh safari timer
        if ('options' in result) {
            var options = result.options;

            if ('timer' in options) {
                var timer = options.timer;

                $safari_timer
                    .css('top', (parseInt($players_list.css('top'), 10) + parseInt($players_list.css('height'), 10) + 10) + 'px')
                    .text('Safari : ' + timer);
            }
        }
    }

    var current_link = 0;
    function animateLinks() {
        var $links        = $crs_app.find('ul.links'),
            numberOfLinks = $links.find('li').length;

        $links.find('li:eq(' + current_link + ')')
              .animate({'opacity': '1'}, 1000)
              .animate({'opacity': '1'}, 10000)
              .animate({'opacity': '0'}, 1000, function() {
                    current_link = (current_link == numberOfLinks - 1) ? 0 : current_link + 1;
                    animateLinks();
              });
    }

    function displayHostName() {
        $crs_app.find('div.host')
            .animate({'left': '-10px'}, 1000)
            .animate({'opacity': '1'}, 5000)
            .animate({'left': '-200px'}, 1000);
    }

    // When the DOM is ready
    $(function () {
        setInterval(refreshContent, refreshTimer * 1000);
        setTimeout(displayHostName, 10 * 1000);

        animateLinks();
    });
});
<commit_msg>Order player list by kills count<commit_after>require(['jquery'], function ($) {
    var firstLoading  = true,
        jsonBase      = wity_base_url + 'm/crs',
        refreshTimer  = 1, // In seconds
        $crs_app      = $('.wity-app-crs.wity-app-crs-overlay'),
        $heroes_list  = $crs_app.find('ul.heroes-list'),
        $players_list = $crs_app.find('ul.players-list'),
        $safari_timer = $crs_app.find('div.safari-timer');

    function refreshContent() {
        $.getJSON(jsonBase, function (json) {
            if (!('result' in json)) {
                return;
            }

            var result = json.result;

            // Display the target on the correct hero
            loadTarget(result);

            // Refresh target kill count
            if (firstLoading) {
                $players_list.children().fadeOut(500, function () {
                    $players_list.empty();
                    loadPlayers(result);
                    loadOptions(result);
                });
            } else {
                $players_list.empty();
                loadPlayers(result);
                loadOptions(result);
            }

            firstLoading = false;
        });
    }

    function loadTarget(result) {
        $heroes_list
            .find('li')
            .removeClass('target transition');

        if ('target' in result) {
            $heroes_list
                .find('li:nth-child(' + result.target + ')')
                .addClass(function () {
                    return 'target' + (firstLoading ? ' transition' : '');
                });
        }
    }

    function loadPlayers(result) {
        if ('players' in result) {
            var players = result.players;

            players.sort(function (a, b) {
                return a.kills < b.kills;
            });

            $.each(players, function (index, player) {
                var $player = $('<li>').addClass('player-' + (index + 1));

                if ('hero' in player && player.hero !== false) {
                    $player.append($('<i>').addClass('miniheroes-sprite miniheroes-sprite-'+player.hero.icon));
                }

                $player.append($('<span>').text(player.name + ' : ' + player.kills));

                $players_list.append($player);
            });
        }
    }

    function loadOptions(result) {
        // Refresh safari timer
        if ('options' in result) {
            var options = result.options;

            if ('timer' in options) {
                var timer = options.timer;

                $safari_timer
                    .css('top', (parseInt($players_list.css('top'), 10) + parseInt($players_list.css('height'), 10) + 10) + 'px')
                    .text('Safari : ' + timer);
            }
        }
    }

    var current_link = 0;
    function animateLinks() {
        var $links        = $crs_app.find('ul.links'),
            numberOfLinks = $links.find('li').length;

        $links.find('li:eq(' + current_link + ')')
              .animate({'opacity': '1'}, 1000)
              .animate({'opacity': '1'}, 10000)
              .animate({'opacity': '0'}, 1000, function() {
                    current_link = (current_link == numberOfLinks - 1) ? 0 : current_link + 1;
                    animateLinks();
              });
    }

    function displayHostName() {
        $crs_app.find('div.host')
            .animate({'left': '-10px'}, 1000)
            .animate({'opacity': '1'}, 5000)
            .animate({'left': '-200px'}, 1000);
    }

    // When the DOM is ready
    $(function () {
        setInterval(refreshContent, refreshTimer * 1000);
        setTimeout(displayHostName, 10 * 1000);

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


<commit_before>/*
 * Copyright (C) 2011  JTalks.org Team
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
var Utils = {};

function quote(postId, postNumber) {
	var callback = function (text) {
        $('#post').focus();
        console.log(text);
        var answer = $('#postBody');
        answer.focus();
        if (answer) {
            answer.val(answer.val() + text);
        }

    }

    $.ajax({
        url: baseUrl + '/posts/' + postId + '/quote',
        type: 'POST',
        data: {
            selection: getSelectedPostText(postNumber)
        },
        success: function (data) {
            callback(data.result);
        },
        error: function () {
            callback('');
        }
    });
}

function getSelectedPostText(postNumber) {
    var txt = '';
    console.log(postNumber);
    if (window.getSelection && isRangeInPost(window.getSelection().getRangeAt(0)) && isSelectedPostQuoted(postNumber)) {
        txt = window.getSelection().toString();
    }
    else if (document.selection && isRangeInPost(document.selection.createRange()) && isSelectedPostQuoted(postNumber)) {
        txt = document.selection.createRange().text;
    }
    return txt;
}

/**
 * Checks if selected document fragment is a part of the post content.
 * @param {Range} range Range object which represent current selection.
 * @return {boolean} true if if selected document fragment is a part of the post content
 *                   false otherwise.
 */
function isRangeInPost(range) {
    return range.startContainer.parentNode.classList.contains("post-content-body");
}

/**
 * Checks if "quote" button pressed on the post which was selected.
 * @param {Number} postNumber number of the post on the page which "quote" button was pressed.
 * @return {boolean} true</> if selected text is a part of the post which will be quoted
 *                   false otherwise.
 */
function isSelectedPostQuoted(postNumber) {
    console.log("btn" + $(window.getSelection().getRangeAt(0).startContainer).closest('.post').length);
    return $(window.getSelection().getRangeAt(0).startContainer).closest('.post').prevAll().length == postNumber;
}

/**
 * Encodes given string by escaping special HTML characters
 *
 * @param s string to be encoded
 */
Utils.htmlEncode = function (s) {
    return $('
').text(s).html();
};

/**
 * Do focus to element
 *
 * @param target selector of element to focus
 */
Utils.focusFirstEl = function (target) {
    $(target).focus();
}

/**
 * Replaces all \n characters by
 tags. Used for review comments.
 *
 * @param s string where perform replacing
 */
Utils.lf2br = function (s) {
    return s.replace(/\n/g, "
");
}

/**
 * Replaces all \
 tags by \n characters. Used for review comments.
 *
 * @param s string where perform replacing
 */
Utils.br2lf = function (s) {
    return s.replace(/
/gi, "\n");
}

/**
 * Create form field with given label(placeholder), id, type
 */
Utils.createFormElement = function (label, id, type, cls) {
    var elementHtml = ' \

 \

 \
                <input type="' + type + '" id="' + id + '" name="' + id + '" placeholder="' + label + '" class="input-xlarge ' + cls + '" /> \

 \

 \
    ';

    return elementHtml;
}
<commit_msg>#JC-1853: Move focus to Create topic dialog on quoting: *Debug output replaced<commit_after>/*
 * Copyright (C) 2011  JTalks.org Team
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
var Utils = {};

function quote(postId, postNumber) {
	var callback = function (text) {
        $('#post').focus();
        console.log(text);
        var answer = $('#postBody');
        answer.focus();
        if (answer) {
            answer.val(answer.val() + text);
        }

    }

    $.ajax({
        url: baseUrl + '/posts/' + postId + '/quote',
        type: 'POST',
        data: {
            selection: getSelectedPostText(postNumber)
        },
        success: function (data) {
            callback(data.result);
        },
        error: function () {
            callback('');
        }
    });
}

function getSelectedPostText(postNumber) {
    var txt = '';
    if (window.getSelection && isRangeInPost(window.getSelection().getRangeAt(0)) && isSelectedPostQuoted(postNumber)) {
        txt = window.getSelection().toString();
    }
    else if (document.selection && isRangeInPost(document.selection.createRange()) && isSelectedPostQuoted(postNumber)) {
        txt = document.selection.createRange().text;
    }
    return txt;
}

/**
 * Checks if selected document fragment is a part of the post content.
 * @param {Range} range Range object which represent current selection.
 * @return {boolean} true if if selected document fragment is a part of the post content
 *                   false otherwise.
 */
function isRangeInPost(range) {
    return range.startContainer.parentNode.classList.contains("post-content-body");
}

/**
 * Checks if "quote" button pressed on the post which was selected.
 * @param {Number} postNumber number of the post on the page which "quote" button was pressed.
 * @return {boolean} true</> if selected text is a part of the post which will be quoted
 *                   false otherwise.
 */
function isSelectedPostQuoted(postNumber) {
    return $(window.getSelection().getRangeAt(0).startContainer).closest('.post').prevAll().length == postNumber;
}

/**
 * Encodes given string by escaping special HTML characters
 *
 * @param s string to be encoded
 */
Utils.htmlEncode = function (s) {
    return $('
').text(s).html();
};

/**
 * Do focus to element
 *
 * @param target selector of element to focus
 */
Utils.focusFirstEl = function (target) {
    $(target).focus();
}

/**
 * Replaces all \n characters by
 tags. Used for review comments.
 *
 * @param s string where perform replacing
 */
Utils.lf2br = function (s) {
    return s.replace(/\n/g, "
");
}

/**
 * Replaces all \
 tags by \n characters. Used for review comments.
 *
 * @param s string where perform replacing
 */
Utils.br2lf = function (s) {
    return s.replace(/
/gi, "\n");
}

/**
 * Create form field with given label(placeholder), id, type
 */
Utils.createFormElement = function (label, id, type, cls) {
    var elementHtml = ' \

 \

 \
                <input type="' + type + '" id="' + id + '" name="' + id + '" placeholder="' + label + '" class="input-xlarge ' + cls + '" /> \

 \

 \
    ';

    return elementHtml;
}
<|endoftext|>


<commit_before>var Class = require('../../utils/Class');
var CONST = require('../const');
var File = require('../File');
var GetFastValue = require('../../utils/object/GetFastValue');

//  Phaser.Loader.FileTypes.HTMLFile

var HTMLFile = new Class({

    Extends: File,

    initialize:

    function HTMLFile (key, url, width, height, path, xhrSettings)
    {
        if (width === undefined) { width = 512; }
        if (height === undefined) { height = 512; }

        var fileKey = (typeof key === 'string') ? key : GetFastValue(key, 'key', '');

        var fileConfig = {
            type: 'html',
            extension: GetFastValue(key, 'extension', 'html'),
            responseType: 'text',
            key: fileKey,
            url: GetFastValue(key, 'file', url),
            path: path,
            xhrSettings: GetFastValue(key, 'xhr', xhrSettings),
            config: {
                width: width,
                height: height
            }
        };

        File.call(this, fileConfig);
    },

    onProcess: function (callback)
    {
        this.state = CONST.FILE_PROCESSING;

        var w = this.config.width;
        var h = this.config.height;

        var data = [];

        data.push('<svg width="' + w + 'px" height="' + h + 'px" viewBox="0 0 ' + w + ' ' + h + '" xmlns="http://www.w3.org/2000/svg">');
        data.push('<foreignObject width="100%" height="100%">');
        data.push('');
        data.push(this.xhrLoader.responseText);
        data.push('');
        data.push('</foreignObject>');
        data.push('</svg>');

        var svg = [ data.join('\n') ];
        var _this = this;

        try
        {
            var blob = new window.Blob(svg, { type: 'image/svg+xml;charset=utf-8' });
        }
        catch (e)
        {
            _this.state = CONST.FILE_ERRORED;

            callback(_this);

            return;
        }

        this.data = new Image();

        this.data.crossOrigin = this.crossOrigin;

        this.data.onload = function ()
        {
            URL.revokeObjectURL(_this.data.src);

            _this.onComplete();

            callback(_this);
        };

        this.data.onerror = function ()
        {
            URL.revokeObjectURL(_this.data.src);

            _this.state = CONST.FILE_ERRORED;

            callback(_this);
        };

        this.data.src = URL.createObjectURL(blob);
    }

});

HTMLFile.create = function (loader, key, url, width, height, xhrSettings)
{
    if (Array.isArray(key))
    {
        for (var i = 0; i < key.length; i++)
        {
            //  If it's an array it has to be an array of Objects, so we get everything out of the 'key' object
            loader.addFile(new HTMLFile(key[i], url, width, height, loader.path, xhrSettings));
        }
    }
    else
    {
        loader.addFile(new HTMLFile(key, url, width, height, loader.path, xhrSettings));
    }

    //  For method chaining
    return loader;
};

module.exports = HTMLFile;
<commit_msg>using new static methods for generating object url when loading html files as well<commit_after>var Class = require('../../utils/Class');
var CONST = require('../const');
var File = require('../File');
var GetFastValue = require('../../utils/object/GetFastValue');

//  Phaser.Loader.FileTypes.HTMLFile

var HTMLFile = new Class({

    Extends: File,

    initialize:

    function HTMLFile (key, url, width, height, path, xhrSettings)
    {
        if (width === undefined) { width = 512; }
        if (height === undefined) { height = 512; }

        var fileKey = (typeof key === 'string') ? key : GetFastValue(key, 'key', '');

        var fileConfig = {
            type: 'html',
            extension: GetFastValue(key, 'extension', 'html'),
            responseType: 'text',
            key: fileKey,
            url: GetFastValue(key, 'file', url),
            path: path,
            xhrSettings: GetFastValue(key, 'xhr', xhrSettings),
            config: {
                width: width,
                height: height
            }
        };

        File.call(this, fileConfig);
    },

    onProcess: function (callback)
    {
        this.state = CONST.FILE_PROCESSING;

        var w = this.config.width;
        var h = this.config.height;

        var data = [];

        data.push('<svg width="' + w + 'px" height="' + h + 'px" viewBox="0 0 ' + w + ' ' + h + '" xmlns="http://www.w3.org/2000/svg">');
        data.push('<foreignObject width="100%" height="100%">');
        data.push('');
        data.push(this.xhrLoader.responseText);
        data.push('');
        data.push('</foreignObject>');
        data.push('</svg>');

        var svg = [ data.join('\n') ];
        var _this = this;

        try
        {
            var blob = new window.Blob(svg, { type: 'image/svg+xml;charset=utf-8' });
        }
        catch (e)
        {
            _this.state = CONST.FILE_ERRORED;

            callback(_this);

            return;
        }

        this.data = new Image();

        this.data.crossOrigin = this.crossOrigin;

        this.data.onload = function ()
        {
            File.revokeObjectURL(_this.data);

            _this.onComplete();

            callback(_this);
        };

        this.data.onerror = function ()
        {
            File.revokeObjectURL(_this.data);

            _this.state = CONST.FILE_ERRORED;

            callback(_this);
        };

        File.createObjectURL(this.data, blob, 'image/svg+xml');
    }

});

HTMLFile.create = function (loader, key, url, width, height, xhrSettings)
{
    if (Array.isArray(key))
    {
        for (var i = 0; i < key.length; i++)
        {
            //  If it's an array it has to be an array of Objects, so we get everything out of the 'key' object
            loader.addFile(new HTMLFile(key[i], url, width, height, loader.path, xhrSettings));
        }
    }
    else
    {
        loader.addFile(new HTMLFile(key, url, width, height, loader.path, xhrSettings));
    }

    //  For method chaining
    return loader;
};

module.exports = HTMLFile;
<|endoftext|>