<commit_before>

'use strict';

/*
angular.module('mean.socket').controller('ModalDemoCtrl', function ($scope, $uibModal, $log, $rootScope) {

/!*    $scope.items = ['item1', 'item2', 'item3'];*!/

    $scope.animationsEnabled = true;

    $scope.open = function (size) {

        var modalInstance = $uibModal.open({
            animation: $scope.animationsEnabled,
            templateUrl: 'myModalContent.html',
            controller: 'ModalInstanceCtrl',
            size: size,
            resolve: {
                modalHeader: function () {
                    return $rootScope.modalHeader;
                }
            }
        });

        modalInstance.result.then(function (selectedItem) {
            //$scope.selected = selectedItem;
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };

    $scope.toggleAnimation = function () {
        $scope.animationsEnabled = !$scope.animationsEnabled;
    };

});*/

angular.module('mean.socket').controller('ModalInstanceCtrl', function ($scope, $uibModalInstance, modalHeader, modalBody) {

    $scope.modalHeader = modalHeader;
    $scope.modalBody = modalBody;
    //$scope.selected = {
    //    item: $scope.items[0]
    //};
    //
    //$scope.ok = function () {
    //    $uibModalInstance.close($scope.selected.item);
    //};
    //
    //$scope.cancel = function () {
    //    $uibModalInstance.dismiss('cancel');
    //};
});

angular.module('mean.socket').controller('MeanSocketController', ['$scope', '$state', '$stateParams', 'Global', 'MeanSocket', 'MeanUser', '$interval', '$rootScope', '$uibModal',
    function ($scope, $state, $stateParams, Global, MeanSocket, MeanUser, $interval, $rootScope, $uibModal) {
        $scope.global = Global;
        $scope.package = {
            name: 'socket'
        };
        //config region
        var timeConfig = 120;
        //

        $scope.channel = $stateParams.category;
        $scope.myturn = false;
        $scope.activeUser = '';
        $scope.myword = '';
        $scope.timeleft = timeConfig;
        /*var timerObj=$('#timer');*/
        $scope.drawingTimer = null;
        $scope.gameStatus = 'readyToDraw';
        $scope.statusText = 'לחץ על כפתור התחל משחק והתחל לצייר';
        /*$scope.messages = [];
         $scope.message = '';*/
        $scope.users = [];
        $scope.modalHeader = 'modalHeader';
        $scope.modalBody = 'modalBody';

        $scope.animationsEnabled = true;

        $scope.open = function (size) {

            var modalInstance = $uibModal.open({
                animation: $scope.animationsEnabled,
                templateUrl: 'myModalContent.html',
                controller: 'ModalInstanceCtrl',
                size: size,
                resolve: {
                    modalHeader: function () {
                        return $scope.modalHeader;
                    },
                    modalBody: function () {
                        return $scope.modalBody;
                    }
                }
            });

            modalInstance.result.then(function (selectedItem) {
                //$scope.selected = selectedItem;
            }, function () {
                $log.info('Modal dismissed at: ' + new Date());
            });
        };

        $scope.toggleAnimation = function () {
            $scope.animationsEnabled = !$scope.animationsEnabled;
        };

        MeanSocket.on('user:channel:joined:' + $scope.channel, function (channelInfo) {
            console.log('user:joined ');
        });
        MeanSocket.on('user:disconnect:' + $scope.channel, function (user) {
            console.log('user:disconnect ');
        });

        MeanSocket.on("activeUser:disconnect:" + $scope.channel, function (user) {
            console.log('activeUser:disconnect ');
            if(!$scope.myturn){
                $scope.modalHeader = "הסיבוב נגמר";
                $scope.modalBody = "המשתמש עזב את המשחק";
                $scope.open();
            }
        });

        //todo
        MeanSocket.on('wait:' + $scope.channel, function (word) {
            $scope.gameStatus = "wait";
            console.log('wait');
        });

        MeanSocket.on('youDraw:' + $scope.channel, function (word) {
            $scope.myturn = true;
            $scope.myword = word;
            $scope.gameStatus = "youDraw";

            $scope.statusText = 'מילתך היא: '+$scope.myword;

            // turn on drawing timer

            MeanSocket.emit("youDrawSuccess:" + $scope.channel, {
                channel: $scope.channel,
                user: MeanUser.user
            });
        });

        /*        function timerTickActiveUser() {
         if ($scope.timeleft > 0) {
         $scope.timeleft--;
         } else {
         $scope.timeleft = 120;
         clearInterval($scope.drawingTimer);
         $scope.drawingTimer = null;
         $scope.gameStatus = "readyToDraw";
         }
         }*/

        function timerTick() {
            if ($scope.timeleft > 0) {
                var x = $scope.timeleft - 1;
                $scope.timeleft = x;
                /*timerObj.text($scope.timeleft);*/
            } else {
                stopTimer();
                //only active user emit this
                if ($scope.myturn) {
                    MeanSocket.emit('turnFinished:' + $scope.channel, {
                        channel: $scope.channel,
                        user: MeanUser.user._id
                    });
                }
            }
        }

        function stopTimer() {
            if (angular.isDefined($scope.drawingTimer)) {
                $interval.cancel($scope.drawingTimer);
                $scope.drawingTimer = undefined;
                $scope.timeleft = timeConfig;
            }
        }

        function startTimer() {
            $scope.drawingTimer = $interval(timerTick, 1000);
        }

        MeanSocket.on('friendDraw:' + $scope.channel, function (data) {
            startTimer();
            $scope.activeUser = data.activeUser;
            if (!$scope.myturn) {
                console.log("friend draw");
                $scope.gameStatus = "friendDraw";
                $scope.statusText = data.activeUser.username +' '+ ':מצייר כעת';
                //$scope.timeleft = data.remainingTime / 1000;
                // turn on drawing timer
                //$scope.drawingTimer = setInterval(timerTick, 1000);
            }
        });

        MeanSocket.on('readyToDraw:' + $scope.channel, function (data) {
            //if ($scope.myturn) {
            $scope.activeUser = '';
            $scope.gameStatus = "readyToDraw";
            $scope.statusText = 'לחץ על כפתור התחל משחק והתחל לצייר';
            $scope.myturn = false;
            //}
        });

        MeanSocket.on('wordGuessed:' + $scope.channel, function (data) {
            stopTimer();
            console.log("wordGuessed");
            if ($scope.gameStatus !== 'wait') {
                //if user is the one who guessed
                if (MeanUser.user._id == data.user._id) {
                    $scope.modalHeader = "כל הכבוד!";
                    $scope.modalBody = "ניחשת נכון המילה היא: " + data.word;
                    $scope.open();
                }
                else{
                    $scope.modalHeader = "המילה נוחשה נכון!";
                    $scope.modalBody =data.user.username + " ניחש את המילה: "+ data.word;
                    $scope.open();
                }
            }
        });

        MeanSocket.on('wordNotGuessed:' + $scope.channel, function (data) {
            if ($scope.gameStatus !== 'wait') {
            $scope.modalHeader = "נגמר הזמן...";
            $scope.modalBody = "המילה היתה: " + data.word;
            $scope.open();
            /*alert("The turn is over! The word was " + data.word);*/
            }
        });

        /*        MeanSocket.on('timer:' + $scope.channel, function (data) {
         $scope.timeleft = data.countdown;

         });*/

        $scope.init=function(){
            $scope.channel = $stateParams.category;
            //join channel
            //$scope.statusText = 'status: online';
            console.log("logged user: " + MeanUser.user.name);
            MeanSocket.emit('channel:join', {
                channel: $scope.channel,
                user: MeanUser.user
            });
        }

        $scope.$on('$destroy', function () {
            // Make sure that the interval is destroyed too
            stopTimer();
        });

        /*        //disconnect
         //todo: emit disconnect on return page etc
         $(window).on("beforeunload", function () {
         MeanSocket.emit('disconnect');
         })*/
        /*

         $scope.socketAfterSend = function (message) {
         $scope.message = {};
         };

         $scope.socketAfterJoin = function (channel, messages) {
         $scope.channel = channel;
         $scope.messages = messages;
         };

         $scope.socketAfterGet = function (message) {
         $scope.messages.push(message);
         };

         $scope.socketAfterGetChannels = function (channels) {
         $scope.channels = channels;
         };
         */

        /*$scope.createNewChannel = function(channel) {
         $scope.activeChannel = channel;
         $scope.newChannel = '';
         };*/

        // $scope.channel = {
        // 	name: ''
        // };

        // // 			// //App info
        // // // $scope.channels = [];
        // $scope.listeningChannels = [];
        // // // $scope.activeChannel = null;
        // // // $scope.userName = $scope.global.user._id;
        // // // $scope.messages = [];

        // // // ///////////////////////////////////////////////////////////////////////
        // // // ///////////////////////////////////////////////////////////////////////
        // // // //Socket.io listeners
        // // // ///////////////////////////////////////////////////////////////////////
        // // // ///////////////////////////////////////////////////////////////////////

        // // // MeanSocket.on('channels', function channels(channels) {
        // // // 	console.log('channels', channels);

        // // // 	console.log(channels);
        // // // 	$scope.channels = channels;
        // // // 	$scope.channels = channels;
        // // // });

        // // // MeanSocket.on('message:received', function messageReceived(message) {
        // // // 	$scope.messages.push(message);
        // // // });

        // // // MeanSocket.emit('user:joined', {
        // // // 	name: $scope.global.user._id
        // // // });

        // // // MeanSocket.on('user:joined', function(user) {
        // // // 	console.log('user:joined');
        // // // 	$scope.messages.push(user);
        // // // });

        // $scope.listenChannel = function listenChannel(channel) {
        // 	MeanSocket.on('messages:channel:' + channel, function messages(messages) {
        // 		alert(channel)
        // 		MeanSocket.activeChannel = channel;
        // 		$scope.afterJoin({
        // 			messages: messages,
        // 			channel: channel
        // 		});
        // 	});

        // 	MeanSocket.on('message:channel:' + channel, function message(message) {
        // 		console.log('got message: ', message);
        // 		console.log(channel, MeanSocket.activeChannel)
        // 		if (channel === MeanSocket.activeChannel) {
        // 			$scope.meanSocketAfterGet({
        // 				message: message
        // 			});
        // 		}
        // 	});

        // 	MeanSocket.on('message:remove:channel:' + channel, function(removalInfo) {

        // 	});

        // 	if ($scope.listeningChannels.indexOf(channel) === -1)
        // 		$scope.listeningChannels.push(channel);

        // };

        // // Join

        // $scope.joinChannel = function joinChannel(channel) {
        // 	alert(channel);
        // 	//Listen to channel if we dont have it already.
        // 	if ($scope.listeningChannels.indexOf(channel) === -1) {
        // 		$scope.listenChannel(channel);
        // 	}

        // 	MeanSocket.emit('channel:join', {
        // 		channel: channel,
        // 		name: $scope.global.user._id
        // 	});
        // };

        // //Auto join the defaultChannel
        // console.log(typeof MeanSocket.activeChannel)
        // if (typeof MeanSocket.activeChannel === 'undefined')
        // 	$scope.joinChannel('mean');

        // // $scope.$watch('joinToChannel', function() {
        // // 	if ($scope.joinToChannel)
        // // 		$scope.joinChannel($scope.joinToChannel);
        // // });
    }
]);
<commit_msg>Update meanSocket.js<commit_after>'use strict';

/*
 angular.module('mean.socket').controller('ModalDemoCtrl', function ($scope, $uibModal, $log, $rootScope) {

 /!*    $scope.items = ['item1', 'item2', 'item3'];*!/

 $scope.animationsEnabled = true;

 $scope.open = function (size) {

 var modalInstance = $uibModal.open({
 animation: $scope.animationsEnabled,
 templateUrl: 'myModalContent.html',
 controller: 'ModalInstanceCtrl',
 size: size,
 resolve: {
 modalHeader: function () {
 return $rootScope.modalHeader;
 }
 }
 });

 modalInstance.result.then(function (selectedItem) {
 //$scope.selected = selectedItem;
 }, function () {
 $log.info('Modal dismissed at: ' + new Date());
 });
 };

 $scope.toggleAnimation = function () {
 $scope.animationsEnabled = !$scope.animationsEnabled;
 };

 });*/

angular.module('mean.socket').controller('ModalInstanceCtrl', function ($scope, $uibModalInstance, modalHeader, modalBody) {

    $scope.modalHeader = modalHeader;
    $scope.modalBody = modalBody;
    //$scope.selected = {
    //    item: $scope.items[0]
    //};
    //
    //$scope.ok = function () {
    //    $uibModalInstance.close($scope.selected.item);
    //};
    //
    //$scope.cancel = function () {
    //    $uibModalInstance.dismiss('cancel');
    //};
});

angular.module('mean.socket').controller('MeanSocketController', ['$scope', '$state', '$stateParams', 'Global', 'MeanSocket', 'MeanUser', '$interval', '$rootScope', '$uibModal',
    function ($scope, $state, $stateParams, Global, MeanSocket, MeanUser, $interval, $rootScope, $uibModal) {
        $scope.global = Global;
        $scope.package = {
            name: 'socket'
        };
        //config region
        var timeConfig = 120;
        //

        $scope.channel = $stateParams.category;
        $scope.myturn = false;
        $scope.activeUser = '';
        $scope.myword = '';
        $scope.timeleft = timeConfig;
        /*var timerObj=$('#timer');*/
        $scope.drawingTimer = null;
        $scope.gameStatus = 'readyToDraw';
        $scope.statusText = 'לחץ על כפתור התחל משחק והתחל לצייר';
        /*$scope.messages = [];
         $scope.message = '';*/
        $scope.users = [];
        $scope.modalHeader = 'modalHeader';
        $scope.modalBody = 'modalBody';

        $scope.animationsEnabled = true;

        $scope.open = function (size) {

            var modalInstance = $uibModal.open({
                animation: $scope.animationsEnabled,
                templateUrl: 'myModalContent.html',
                controller: 'ModalInstanceCtrl',
                size: size,
                resolve: {
                    modalHeader: function () {
                        return $scope.modalHeader;
                    },
                    modalBody: function () {
                        return $scope.modalBody;
                    }
                }
            });

            modalInstance.result.then(function (selectedItem) {
                //$scope.selected = selectedItem;
            }, function () {
                $log.info('Modal dismissed at: ' + new Date());
            });
        };

        $scope.toggleAnimation = function () {
            $scope.animationsEnabled = !$scope.animationsEnabled;
        };

        MeanSocket.on('user:channel:joined:' + $scope.channel, function (channelInfo) {
            console.log('user:joined ');
        });
        MeanSocket.on('user:disconnect:' + $scope.channel, function (user) {
            console.log('user:disconnect ');
        });

        MeanSocket.on("activeUser:disconnect:" + $scope.channel, function (user) {
            if ($state.current.name === 'Pictionary game') {
                console.log('activeUser:disconnect ');
                if (!$scope.myturn) {
                    $scope.modalHeader = "הסיבוב נגמר";
                    $scope.modalBody = "המשתמש עזב את המשחק";
                    $scope.open();
                    stopTimer();
                }
            }
        });

        //todo
        MeanSocket.on('wait:' + $scope.channel, function (word) {
            if ($state.current.name === 'Pictionary game') {
                $scope.gameStatus = "wait";
                console.log('wait');
            }
        });

        MeanSocket.on('youDraw:' + $scope.channel, function (word) {
            if ($state.current.name === 'Pictionary game') {
                $scope.myturn = true;
                $scope.myword = word;
                $scope.gameStatus = "youDraw";

                $scope.statusText = 'מילתך היא: ' + $scope.myword;

                // turn on drawing timer

                MeanSocket.emit("youDrawSuccess:" + $scope.channel, {
                    channel: $scope.channel,
                    user: MeanUser.user
                });
            }
        });

        /*        function timerTickActiveUser() {
         if ($scope.timeleft > 0) {
         $scope.timeleft--;
         } else {
         $scope.timeleft = 120;
         clearInterval($scope.drawingTimer);
         $scope.drawingTimer = null;
         $scope.gameStatus = "readyToDraw";
         }
         }*/

        function timerTick() {
            if ($state.current.name === 'Pictionary game') {
                if ($scope.timeleft > 0) {
                    var x = $scope.timeleft - 1;
                    $scope.timeleft = x;
                    /*timerObj.text($scope.timeleft);*/
                } else {
                    stopTimer();
                    //only active user emit this
                    if ($scope.myturn) {
                        MeanSocket.emit('turnFinished:' + $scope.channel, {
                            channel: $scope.channel,
                            user: MeanUser.user._id
                        });
                    }
                }
            }
        }

        function stopTimer() {
            if ($state.current.name === 'Pictionary game') {
                if (angular.isDefined($scope.drawingTimer)) {
                    $interval.cancel($scope.drawingTimer);
                    $scope.drawingTimer = undefined;
                    $scope.timeleft = timeConfig;
                }
            }
        }

        function startTimer() {
            if ($state.current.name === 'Pictionary game') {
                $scope.drawingTimer = $interval(timerTick, 1000);
            }
        }

        MeanSocket.on('friendDraw:' + $scope.channel, function (data) {
            if ($state.current.name === 'Pictionary game') {
                startTimer();
                $scope.activeUser = data.activeUser;
                if (!$scope.myturn) {
                    console.log("friend draw");
                    $scope.gameStatus = "friendDraw";
                    $scope.statusText = data.activeUser.username + ' ' + ':מצייר כעת';
                    //$scope.timeleft = data.remainingTime / 1000;
                    // turn on drawing timer
                    //$scope.drawingTimer = setInterval(timerTick, 1000);
                }
            }
        });

        MeanSocket.on('readyToDraw:' + $scope.channel, function (data) {
            if ($state.current.name === 'Pictionary game') {
                //if ($scope.myturn) {
                $scope.activeUser = '';
                $scope.gameStatus = "readyToDraw";
                $scope.statusText = 'לחץ על כפתור התחל משחק והתחל לצייר';
                $scope.myturn = false;
                //}
            }
        });

        MeanSocket.on('wordGuessed:' + $scope.channel, function (data) {
            if ($state.current.name === 'Pictionary game') {
                stopTimer();
                console.log("wordGuessed");
                if ($scope.gameStatus !== 'wait') {
                    //if user is the one who guessed
                    if (MeanUser.user._id == data.user._id) {
                        $scope.modalHeader = "כל הכבוד!";
                        $scope.modalBody = "ניחשת נכון המילה היא: " + data.word;
                        $scope.open();
                    }
                    else {
                        $scope.modalHeader = "המילה נוחשה נכון!";
                        $scope.modalBody = data.user.username + " ניחש את המילה: " + data.word;
                        $scope.open();
                    }
                }
            }
        });

        MeanSocket.on('wordNotGuessed:' + $scope.channel, function (data) {
            if ($state.current.name === 'Pictionary game') {
                if ($scope.gameStatus !== 'wait') {
                    $scope.modalHeader = "נגמר הזמן...";
                    $scope.modalBody = "המילה היתה: " + data.word;
                    $scope.open();
                    /*alert("The turn is over! The word was " + data.word);*/
                }
            }
        });

        /*        MeanSocket.on('timer:' + $scope.channel, function (data) {
         $scope.timeleft = data.countdown;

         });*/

        $scope.init = function () {
            if ($state.current.name === 'Pictionary game') {
                $scope.channel = $stateParams.category;
                //join channel
                //$scope.statusText = 'status: online';
                console.log("logged user: " + MeanUser.user.name);
                MeanSocket.emit('channel:join', {
                    channel: $scope.channel,
                    user: MeanUser.user
                });
            }
        }

        $scope.$on('$destroy', function () {
            if ($state.current.name === 'Pictionary game') {
                // Make sure that the interval is destroyed too
                stopTimer();
            }
        });

        /*        //disconnect
         //todo: emit disconnect on return page etc
         $(window).on("beforeunload", function () {
         MeanSocket.emit('disconnect');
         })*/
        /*

         $scope.socketAfterSend = function (message) {
         $scope.message = {};
         };

         $scope.socketAfterJoin = function (channel, messages) {
         $scope.channel = channel;
         $scope.messages = messages;
         };

         $scope.socketAfterGet = function (message) {
         $scope.messages.push(message);
         };

         $scope.socketAfterGetChannels = function (channels) {
         $scope.channels = channels;
         };
         */

        /*$scope.createNewChannel = function(channel) {
         $scope.activeChannel = channel;
         $scope.newChannel = '';
         };*/

        // $scope.channel = {
        // 	name: ''
        // };

        // // 			// //App info
        // // // $scope.channels = [];
        // $scope.listeningChannels = [];
        // // // $scope.activeChannel = null;
        // // // $scope.userName = $scope.global.user._id;
        // // // $scope.messages = [];

        // // // ///////////////////////////////////////////////////////////////////////
        // // // ///////////////////////////////////////////////////////////////////////
        // // // //Socket.io listeners
        // // // ///////////////////////////////////////////////////////////////////////
        // // // ///////////////////////////////////////////////////////////////////////

        // // // MeanSocket.on('channels', function channels(channels) {
        // // // 	console.log('channels', channels);

        // // // 	console.log(channels);
        // // // 	$scope.channels = channels;
        // // // 	$scope.channels = channels;
        // // // });

        // // // MeanSocket.on('message:received', function messageReceived(message) {
        // // // 	$scope.messages.push(message);
        // // // });

        // // // MeanSocket.emit('user:joined', {
        // // // 	name: $scope.global.user._id
        // // // });

        // // // MeanSocket.on('user:joined', function(user) {
        // // // 	console.log('user:joined');
        // // // 	$scope.messages.push(user);
        // // // });

        // $scope.listenChannel = function listenChannel(channel) {
        // 	MeanSocket.on('messages:channel:' + channel, function messages(messages) {
        // 		alert(channel)
        // 		MeanSocket.activeChannel = channel;
        // 		$scope.afterJoin({
        // 			messages: messages,
        // 			channel: channel
        // 		});
        // 	});

        // 	MeanSocket.on('message:channel:' + channel, function message(message) {
        // 		console.log('got message: ', message);
        // 		console.log(channel, MeanSocket.activeChannel)
        // 		if (channel === MeanSocket.activeChannel) {
        // 			$scope.meanSocketAfterGet({
        // 				message: message
        // 			});
        // 		}
        // 	});

        // 	MeanSocket.on('message:remove:channel:' + channel, function(removalInfo) {

        // 	});

        // 	if ($scope.listeningChannels.indexOf(channel) === -1)
        // 		$scope.listeningChannels.push(channel);

        // };

        // // Join

        // $scope.joinChannel = function joinChannel(channel) {
        // 	alert(channel);
        // 	//Listen to channel if we dont have it already.
        // 	if ($scope.listeningChannels.indexOf(channel) === -1) {
        // 		$scope.listenChannel(channel);
        // 	}

        // 	MeanSocket.emit('channel:join', {
        // 		channel: channel,
        // 		name: $scope.global.user._id
        // 	});
        // };

        // //Auto join the defaultChannel
        // console.log(typeof MeanSocket.activeChannel)
        // if (typeof MeanSocket.activeChannel === 'undefined')
        // 	$scope.joinChannel('mean');

        // // $scope.$watch('joinToChannel', function() {
        // // 	if ($scope.joinToChannel)
        // // 		$scope.joinChannel($scope.joinToChannel);
        // // });
    }
]);
<|endoftext|>


<commit_before>(function(window, undefined){
  "use strict";
  var routes = [];

  /**
  * @method hrouter
  * @param path url pattern
  * @param fn callback
  */
  function hrouter(path, fn) {
    var
        length = arguments.length
      , route  = {}
      , keys = []
      , regexp ;

    //if there are no arguments then we dispatch the current route
    if (arguments.length === 0) {
      trigger();
      return;
    } else if (arguments.length === 1 && typeof path != "function") {
      trigger(String(path));
      return;
    }

    // No path specified we assume is the root path
    if (typeof path == 'function') {
      // fn to function
      fn = path;
      // path to root
      path = '';
    }
    // For multiple callbacks
    fn = [];
    for (var i = 0 ; i < length; i++) {
      if (typeof arguments[i] == 'function') {
        fn.push(arguments[i]);
      }
    }

    regexp = pathtoregexp(path, keys);
    //console.log("REGEXP ", regexp);
    route.keys = keys;
    route.regexp = regexp;
    route.callback = fn;
    routes.push(route);
  }

  /**
  * @method pathtoregexp
  * @param path url route pattern
  * @param keys reference to the url paceholders
  * @retun RegExp
  */
  function pathtoregexp(path, keys) {
    path = path
      .replace(/(\/)?$/,"")
      .replace(/\*/g, "(.*)")
      .replace(/(\/)?(\w+)?:(\w+)(\?)?/g, function (match, slash, fragment, key, optional) {
        // console.log("option", optional);
        // console.log("replace arguments ", arguments);
        var pattern;
        slash = slash || '';
        if (fragment) {
          pattern = slash + fragment + '([^\/]*)';
        } else {
          pattern = slash + '([^\/]+)';
        }
        if (optional) {
          pattern = "(?:\/([^\/]+))?";
        }
        return pattern;
    });
    return new RegExp("^" + path + "\/?$");
  };

  /**
  * @method dispatch
  * @params url
  * @return void
  */
  function dispatch(url) {
    var
        length = routes.length
      , matches;
    for (var i = 0 ; i < length; i++) {
      matches = routes[i].regexp.exec(url);
      if (matches) {
        routes[i].callback;
        routes[i].callback.some(function(fn) {
          fn.apply(routes[i], matches.slice(1, matches.length));
        });
      }
    }
  };

  /**
  * @method addEvent
  * @param elem DOMElement
  */
  function addEvent(elem, event, fn) {
    if (elem.addEventListener) {
      elem.addEventListener(event, fn, false);
    } else {
      elem.attachEvent("on" + event, function() {
        return(fn.call(elem, window.event));
      });
    }
  }

  /**
  * @method trigger
  * @return void
  */
  function trigger(hash) {
    var hash = hash || location.hash.replace(/#/,"");
    dispatch(hash);
  }

  addEvent(window,'hashchange',trigger);
  window.hrouter = hrouter;
}(this));<commit_msg>adding few comments<commit_after>(function(window, undefined){
  "use strict";
  var routes = [];

  /**
  * Defines the routes
  * Routes if the given parameter is just an url
  * @method hrouter
  * @param path url pattern
  * @param fn callback
  */
  function hrouter(path, fn) {
    var
        length = arguments.length
      , route  = {}
      , keys = []
      , regexp ;

    //if there are no arguments then we dispatch the current route
    if (arguments.length === 0) {
      trigger();
      return;
    } else if (arguments.length === 1 && typeof path != "function") {
      trigger(String(path));
      return;
    }

    // No path specified we assume is the root path
    if (typeof path == 'function') {
      // fn to function
      fn = path;
      // path to root
      path = '';
    }
    // For multiple callbacks
    fn = [];
    for (var i = 0 ; i < length; i++) {
      if (typeof arguments[i] == 'function') {
        fn.push(arguments[i]);
      }
    }

    regexp = pathtoregexp(path, keys);
    //console.log("REGEXP ", regexp);
    route.keys = keys;
    route.regexp = regexp;
    route.callback = fn;
    routes.push(route);
  }

  /**
  * Converts the route pattern to a Regular Expression
  * @method pathtoregexp
  * @param path url route pattern
  * @param keys reference to the url paceholders
  * @retun {RegExp}
  */
  function pathtoregexp(path, keys) {
    path = path
      .replace(/(\/)?$/,"")
      .replace(/\*/g, "(.*)")
      .replace(/(\/)?(\w+)?:(\w+)(\?)?/g, function (match, slash, fragment, key, optional) {
        // console.log("option", optional);
        // console.log("replace arguments ", arguments);
        var pattern;
        slash = slash || '';
        if (fragment) {
          pattern = slash + fragment + '([^\/]*)';
        } else {
          pattern = slash + '([^\/]+)';
        }
        if (optional) {
          pattern = "(?:\/([^\/]+))?";
        }
        return pattern;
    });
    return new RegExp("^" + path + "\/?$");
  };

  /**
  * Matches the url with the stored patterns
  * @method dispatch
  * @params url
  * @return void
  */
  function dispatch(url) {
    var
        length = routes.length
      , matches;
    for (var i = 0 ; i < length; i++) {
      matches = routes[i].regexp.exec(url);
      if (matches) {
        routes[i].callback;
        routes[i].callback.some(function(fn) {
          fn.apply(routes[i], matches.slice(1, matches.length));
        });
      }
    }
  };

  /**
  * Cross Browser Eventlistener
  * @method addEvent
  * @param elem DOMElement
  */
  function addEvent(elem, event, fn) {
    if (elem.addEventListener) {
      elem.addEventListener(event, fn, false);
    } else {
      elem.attachEvent("on" + event, function() {
        return(fn.call(elem, window.event));
      });
    }
  }

  /**
  * Event handler
  * @method trigger
  */
  function trigger(hash) {
    var hash = hash || location.hash.replace(/#/,"");
    dispatch(hash);
  }

  addEvent(window,'hashchange',trigger);
  window.hrouter = hrouter;
}(this));<|endoftext|>


<commit_before>const { execSync } = require('child_process');

const { getAllUsers } = require('../../storage/users');

const MS_PER_DAY = 1000 * 60 * 60 * 24;
const daysAgo = date => Math.floor((Date.now() - new Date(date).getTime()) / MS_PER_DAY);

const getDistribution = list => list.reduce((obj, stat) => {
  obj[stat] = (obj[stat] || 0) + 1;
  return obj;
}, {});

const getGitHash = () => execSync('git rev-parse HEAD').toString().trim();

const makeAppAnalysis = (models, info) => {
  const getResources = Promise.all([
    getAllUsers(),
    models.Session.findAll({ state: { $not: 'deleted' } })
  ]);
  getResources.then(([users, sessions]) => {
    const userSessions = users.map(user => ({ user, sessions: sessions.filter(session => session.owner === user.user_id) }));
    const viewStats = sessions.map(session => (session.analytics ? (session.analytics.views || 0) : 0));
    const totalViews = viewStats.reduce((a, b) => a + b);
    const publishedSessions = userSessions.filter(data => data.sessions.some(session => session.state === 'published'));
    const analysis = {
      timestamp: new Date(),
      version: process.env.npm_package_version,
      gitHead: getGitHash(),
      info,
      stats: {
        user: {
          total: users.length,
          active: {
            total: users.filter(user => daysAgo(user.last_login) > 28).length,
            distribution: getDistribution(users.map(user => daysAgo(user.last_login)))
          },
          published: {
            total: publishedSessions.length,
            live: publishedSessions.filter(data => data.sessions.some(session => session.sortedSchedule.some(slot => !slot.hasOccurred))).length
          }
        },
        session: {
          total: sessions.length,
          published: sessions.filter(session => session.state === 'published').length,
          publishedYesterday: sessions.filter(session => session.state === 'published' && daysAgo(session.updatedAt) === 1).length,
          views: {
            total: totalViews,
            distribution: getDistribution(viewStats)
          }
        }
      }
    };
    models.Analysis.create({ analysis });
  }).catch(console.error);
};

module.exports = { makeAppAnalysis };
<commit_msg>heroku get version / git hash<commit_after>const { execSync } = require('child_process');

const { getAllUsers } = require('../../storage/users');

const MS_PER_DAY = 1000 * 60 * 60 * 24;
const daysAgo = date => Math.floor((Date.now() - new Date(date).getTime()) / MS_PER_DAY);

const getDistribution = list => list.reduce((obj, stat) => {
  obj[stat] = (obj[stat] || 0) + 1;
  return obj;
}, {});

const getGitHash = () => execSync('git rev-parse HEAD').toString().trim();

const makeAppAnalysis = (models, info) => {
  const getResources = Promise.all([
    getAllUsers(),
    models.Session.findAll({ state: { $not: 'deleted' } })
  ]);
  getResources.then(([users, sessions]) => {
    const userSessions = users.map(user => ({ user, sessions: sessions.filter(session => session.owner === user.user_id) }));
    const viewStats = sessions.map(session => (session.analytics ? (session.analytics.views || 0) : 0));
    const totalViews = viewStats.reduce((a, b) => a + b);
    const publishedSessions = userSessions.filter(data => data.sessions.some(session => session.state === 'published'));
    const analysis = {
      timestamp: new Date(),
      version: process.env.HEROKU_RELEASE_VERSION || process.env.npm_package_version || false,
      gitHead: process.env.HEROKU_SLUG_COMMIT || getGitHash(),
      info,
      stats: {
        user: {
          total: users.length,
          active: {
            total: users.filter(user => daysAgo(user.last_login) > 28).length,
            distribution: getDistribution(users.map(user => daysAgo(user.last_login)))
          },
          published: {
            total: publishedSessions.length,
            live: publishedSessions.filter(data => data.sessions.some(session => session.sortedSchedule.some(slot => !slot.hasOccurred))).length
          }
        },
        session: {
          total: sessions.length,
          published: sessions.filter(session => session.state === 'published').length,
          publishedYesterday: sessions.filter(session => session.state === 'published' && daysAgo(session.updatedAt) === 1).length,
          views: {
            total: totalViews,
            distribution: getDistribution(viewStats)
          }
        }
      }
    };
    models.Analysis.create({ analysis });
  }).catch(console.error);
};

module.exports = { makeAppAnalysis };
<|endoftext|>


<commit_before>import { prettyNumber } from '../../utils/pretty-number';
import { escapeHtml } from '../../utils/escape-html';
import copyToClipboard from '../../utils/copy-to-clipboard';

export default {
  render: function(){
    let color = this.config.colors[0];
    const theme = this.config.theme;
    const title = this.config.title;
    const opts = this.config;
    let value = '-';
    let prevValue= '';
    let html = '';
    let prefix = '';
    let suffix = '';
    let formattedNum;
    let flexDifferenceStyle = '';
    let resultDifference = '';
    let differenceStyle = '';
    let smallerValue = '';
    const { results, previousResults, isExtraction, comparedProp } = this.config;
    if(results && previousResults){
      flexDifferenceStyle = previousResults ? ' metric-comparison' : '';
      smallerValue = previousResults && title ? '-smaller' : '';
      resultDifference = results.result - previousResults.result;
      differenceStyle = (resultDifference > 0) ? '-green' : '-red';
      resultDifference = Math.abs(resultDifference);
      color = '';
    }

    if (this.data() && this.data()[1] && this.data()[1][1] && typeof this.data()[1][1] === 'number') {
      value = this.data()[1][1];
    }

    if (isExtraction && comparedProp) {
      value = this.data()[1];
      prevValue = this.data()[2];

      flexDifferenceStyle = prevValue ? ' metric-comparison' : '';
      smallerValue = prevValue && title ? '-smaller' : '';
      resultDifference = value - prevValue;
      differenceStyle = (resultDifference > 0) ? '-green' : '-red';
      resultDifference = Math.abs(resultDifference);
      color = '';
    }

    formattedNum = value;
    if ( (typeof opts['prettyNumber'] === 'undefined' || opts['prettyNumber'] === true)
      && !isNaN(parseInt(value)) ) {
        formattedNum = prettyNumber(value);
        if(results && previousResults){
          resultDifference = prettyNumber(resultDifference);
        }
    }

    if (opts['prefix']) {
      prefix = '' + opts['prefix'] + '';
    }
    if (opts['suffix']) {
      suffix = '' + opts['suffix'] + '';
    }
    html += '
';
    html +=   '
';
    if (results && previousResults) {
      html +=   '

' + escapeHtml(resultDifference) + '
';
    }
    if (isExtraction && comparedProp) {
      if (value && prevValue) {
        html +=   '

' + escapeHtml(resultDifference) + '
';
        html += '' + prevValue + '';
      } else {
        html += '
No data to display
';
      }
    }
    html +=     '
' + prefix + escapeHtml(formattedNum) + suffix + '
';
    if (title) {
      html +=   '
' + escapeHtml(title) + '
';
    }
    html +=   '
';
    html += '
';

    this.el().innerHTML = html;

    if (this.config.onrendered) {
      this.config.onrendered();
    }

    if (this.config.utils && this.config.utils.clickToCopyToClipboard) {
      const resultClassName = `.${theme}-metric-value${smallerValue}`;
      document.querySelector(resultClassName).addEventListener('click', e => copyToClipboard(e.target.innerText, e));

      if (results && previousResults) {
        const previousResultsClassName = `.${theme}-metric${differenceStyle}`;
        document.querySelector(previousResultsClassName).addEventListener('click', e => copyToClipboard(e.target.innerText, e));
      }
    }
  },
  update: function(){
    // no special update handling
    this.render();
  },
  destroy: function(){
    // no special clean-up
  }
};
<commit_msg>format extraction data<commit_after>import { prettyNumber } from '../../utils/pretty-number';
import { escapeHtml } from '../../utils/escape-html';
import copyToClipboard from '../../utils/copy-to-clipboard';

function formatExtractionData(res, prop) {
  const { query, result } = res;
  const formattedResult = [];
  if (query.analysis_type !== 'extraction') throw new Error('Analysis type is not an extraction!');
  if (Array.isArray(result)) {
    result.forEach((item) => {
      const obj = {
        query,
        result: item[prop],
      };
      formattedResult.push(obj);
    });
  }
  return formattedResult;
}

export default {
  render: function(){
    let color = this.config.colors[0];
    const theme = this.config.theme;
    const title = this.config.title;
    const opts = this.config;
    let value = '-';
    let prevValue= '';
    let html = '';
    let prefix = '';
    let suffix = '';
    let formattedNum;
    let flexDifferenceStyle = '';
    let resultDifference = '';
    let differenceStyle = '';
    let smallerValue = '';
    const { results, previousResults, isExtraction, comparedProp } = this.config;
    if(results && previousResults){
      flexDifferenceStyle = previousResults ? ' metric-comparison' : '';
      smallerValue = previousResults && title ? '-smaller' : '';
      resultDifference = results.result - previousResults.result;
      differenceStyle = (resultDifference > 0) ? '-green' : '-red';
      resultDifference = Math.abs(resultDifference);
      color = '';
    }

    if (this.data() && this.data()[1] && this.data()[1][1] && typeof this.data()[1][1] === 'number') {
      value = this.data()[1][1];
    }

    if (isExtraction && comparedProp) {
      const formattedResult = formatExtractionData(results, comparedProp);

      value = formattedResult[0].result;
      prevValue = formattedResult[1].result;

      flexDifferenceStyle = prevValue ? ' metric-comparison' : '';
      smallerValue = prevValue && title ? '-smaller' : '';
      resultDifference = value - prevValue;
      differenceStyle = (resultDifference > 0) ? '-green' : '-red';
      resultDifference = Math.abs(resultDifference);
      color = '';
    }

    formattedNum = value;
    if ( (typeof opts['prettyNumber'] === 'undefined' || opts['prettyNumber'] === true)
      && !isNaN(parseInt(value)) ) {
        formattedNum = prettyNumber(value);
        if(results && previousResults){
          resultDifference = prettyNumber(resultDifference);
        }
    }

    if (opts['prefix']) {
      prefix = '' + opts['prefix'] + '';
    }
    if (opts['suffix']) {
      suffix = '' + opts['suffix'] + '';
    }
    html += '
';
    html +=   '
';
    if (results && previousResults) {
      html +=   '

' + escapeHtml(resultDifference) + '
';
    }
    if (isExtraction && comparedProp) {
      if (value && prevValue) {
        html +=   '

' + escapeHtml(resultDifference) + '
';
        html += '' + prevValue + '';
      } else {
        html += '
No data to display
';
      }
    }
    html +=     '
' + prefix + escapeHtml(formattedNum) + suffix + '
';
    if (title) {
      html +=   '
' + escapeHtml(title) + '
';
    }
    html +=   '
';
    html += '
';

    this.el().innerHTML = html;

    if (this.config.onrendered) {
      this.config.onrendered();
    }

    if (this.config.utils && this.config.utils.clickToCopyToClipboard) {
      const resultClassName = `.${theme}-metric-value${smallerValue}`;
      document.querySelector(resultClassName).addEventListener('click', e => copyToClipboard(e.target.innerText, e));

      if (results && previousResults) {
        const previousResultsClassName = `.${theme}-metric${differenceStyle}`;
        document.querySelector(previousResultsClassName).addEventListener('click', e => copyToClipboard(e.target.innerText, e));
      }
    }
  },
  update: function(){
    // no special update handling
    this.render();
  },
  destroy: function(){
    // no special clean-up
  }
};
<|endoftext|>


<commit_before>var Promise = require('bluebird');
var request = Promise.promisifyAll(require('request'), {multiArgs: true});

var config = require('../config/config');
var ImageCache = require('../models/ImageCache')

var imageSearch = module.exports;

imageSearch.image = function (query) {
	return googleImageSearch(query)
		// .catch(() => bingImageSearch(query, true))
		.catch(() => ({provider: 'none', images:[]}));
};

imageSearch.gif = function (query) {
	return googleImageSearch(query, true)
		// .catch(() => bingImageSearch(query, true))
		.catch(() => ({provider: 'none', images:[]}));
};

function googleImageSearch(query, animated) {
	var key = `imageSearch/google-${animated ? 'gif' : 'image'}|${query}`;
	return ImageCache.findOne({key:key})
		.then(dbCache => {
			if(dbCache) {
				log.info(`cache hit: ${key}`)
				return dbCache.results
			}
			return lookup()
		})

	function lookup() {
		if(!query) return Promise.reject('no query');

		var qs = {
			q: query,
			searchType: 'image',
			safe: 'high',
			fields: 'items(link)',
			cx: config.google.cse_id,
			key: config.google.cse_key
		};

		if (animated) {
			//qs.q += ' ".gif"';
			qs.fileType = 'gif';
			//qs.hq = 'animated';
			qs.tbs = 'itp:animated';
		}

		return request.getAsync({
			json: true,
			url: 'https://www.googleapis.com/customsearch/v1',
			qs: qs
		})
			.spread((res, body) => {
				if (res.statusCode === 403) {
					console.log('sad face');
					return Promise.reject(new Error('over capacity'));
				}

				return {
					provider: 'google',
					images: _(body.items).map('link').map(ensureResult).value()
				}
			})
			.then(results => {
				if(results) log.info(`no cache: ${key}`)
				return ImageCache.create({key, results})
			})
			.then(dbCache =>{
				return dbCache.results
			})
	}
}

var encodedBingKey = new Buffer(config.bingApiKey + ":" + config.bingApiKey).toString("base64");

function bingImageSearch(query, animated) {
	var key = `imageSearch/bing-${animated ? 'gif' : 'image'}|${query}`;
	return cacheService.fourMonths.getAsync(key)
		.then(result => result || lookup())
		.then(JSON.parse);

	function lookup() {
		if(!query) return Promise.reject('no query');

		var qs = {
			$format: 'json',
			Query: `'${query}'`,
			Adult: "'Strict'"
		};

		if (animated) {
			// arg why?! no good api unfortunately
			qs.Query = `'${query} ".gif"'`;
		}

		return request.getAsync({
			json: true,
			url: "https://api.datamarket.azure.com/Bing/Search/Image",
			headers: {
				"Authorization": `Basic ${encodedBingKey}`
			},
			qs: qs
		})
			.spread((res, body) => {
				if (res.statusCode === 403) {
					console.log('sad face');
					return Promise.reject(new Error('over capacity'));
				}

				if (res.statusCode == 400) {
					console.error('bing error', body)
					return Promise.reject(body);
				}

				// we don't need 50 results
				body.d.results.length = 12;

				return {
					provider: 'bing',
					images: _(body.d.results).map('MediaUrl').map(ensureResult).value()
				}
			})
			.then(JSON.stringify)
			.then(results => cacheService.fourMonths.setAsync(key, results));
	}
}

function ensureResult(url, animated) {
	if (animated === true) {
		return ensureImageExtension(url.replace(/(giphy\.com\/.*)\/.+_s.gif$/, '$1/giphy.gif'));
	} else {
		return ensureImageExtension(url);
	}
}

function ensureImageExtension(url) {
	if (/(png|jpe?g|gif)$/i.test(url)) {
		return url;
	} else {
		return url + "#.png";
	}
}
<commit_msg>rejiggered results to not make everything a png<commit_after>var Promise = require('bluebird');
var request = Promise.promisifyAll(require('request'), {multiArgs: true});

var config = require('../config/config');
var ImageCache = require('../models/ImageCache')

var imageSearch = module.exports;

imageSearch.image = function (query) {
	return googleImageSearch(query)
		.catch(() => ({provider: 'none', images: []}));
};

imageSearch.gif = function (query) {
	return googleImageSearch(query, true)
		.catch(() => ({provider: 'none', images: []}));
};

function googleImageSearch(query, animated) {
	var key = `imageSearch/google-${animated ? 'gif' : 'image'}|${query}`;
	return ImageCache.findOne({key: key})
		.then(dbCache => {
			if (dbCache) {
				log.info(`cache hit: ${key}`)
				return dbCache.results
			}
			return lookup()
		})

	function lookup() {
		if (!query) return Promise.reject('no query');

		var qs = {
			q: query,
			searchType: 'image',
			safe: 'high',
			fields: 'items(link)',
			cx: config.google.cse_id,
			key: config.google.cse_key
		};

		if (animated) {
			//qs.q += ' ".gif"';
			qs.fileType = 'gif';
			//qs.hq = 'animated';
			qs.tbs = 'itp:animated';
		}

		return request.getAsync({
			json: true,
			url: 'https://www.googleapis.com/customsearch/v1',
			qs: qs
		})
			.spread((res, body) => {
				if (res.statusCode === 403) {
					console.log('sad face');
					return Promise.reject(new Error('over capacity'));
				}

				return {
					provider: 'google',
					images: _(body.items).map('link').map(ensureResult).value()
				}
			})
			.then(results => {
				if (results) log.info(`no cache: ${key}`)
				return ImageCache.create({key, results})
			})
			.then(dbCache => {
				return dbCache.results
			})
	}
}

function ensureResult(url) {
	url = url.replace(/(giphy\.com\/.*)\/.+_s.gif$/, '$1/giphy.gif')
	return ensureImageExtension(url);
}

function ensureImageExtension(url) {
	// check if it doesn't end in file extension
	const match = /(png|jpe?g|gif).+$/i.exec(url)
	if (match && match[1]) {
		return url + `#.${match[1]}`
	} else {
		return url;
	}
}
<|endoftext|>


<commit_before>import {__} from 'embark-i18n';
import {AddressUtils, dappPath} from 'embark-utils';
const async = require('async');
import Web3 from 'web3';
const embarkJsUtils = require('embarkjs').Utils;
import checkContractSize from "./checkContractSize";
const {ZERO_ADDRESS} = AddressUtils;
import EthereumAPI from "./api";
import constants from "embark-core/constants";

class EthereumBlockchainClient {

  constructor(embark) {
    this.embark = embark;
    this.events = embark.events;
    this.logger = embark.logger;
    this.fs = embark.fs;

    this.logFile = dappPath(".embark", "contractEvents.json");

    this.embark.registerActionForEvent("deployment:contract:undeployed", this.addContractJSONToPipeline.bind(this));
    this.embark.registerActionForEvent("deployment:contract:deployed", this.addContractJSONToPipeline.bind(this));
    this.embark.registerActionForEvent('deployment:contract:beforeDeploy', this.determineArguments.bind(this));
    this.embark.registerActionForEvent('deployment:contract:beforeDeploy', this.doLinking.bind(this));
    this.embark.registerActionForEvent('deployment:contract:beforeDeploy', checkContractSize.bind(this));
    this.embark.registerActionForEvent('deployment:contract:beforeDeploy', this.determineAccounts.bind(this));
    this.events.request("blockchain:client:register", "ethereum", this.getEthereumClient.bind(this));
    this.events.request("deployment:deployer:register", "ethereum", this.deployer.bind(this));

    this.events.on("blockchain:started", () => {
      this._web3 = null;
    });

    this.registerAPIRequests();
  }

  get web3() {
    return (async () => {
      if (!this._web3) {
        const provider = await this.events.request2("blockchain:client:provider", "ethereum");
        this._web3 = new Web3(provider);
      }
      return this._web3;
    })();
  }

  async registerAPIRequests() {
    const ethereumApi = new EthereumAPI(this.embark, await this.web3, "ethereum");
    ethereumApi.registerRequests();
    ethereumApi.registerAPIs();
  }

  getEthereumClient(endpoint) {
    if (endpoint.startsWith('ws')) {
      return new Web3.providers.WebsocketProvider(endpoint, {
        headers: { Origin: constants.embarkResourceOrigin }
      });
    }
    const web3 = new Web3(endpoint);
    return web3.currentProvider;
  }

  async deployer(contract, additionalDeployParams, done) {
    try {
      const web3 = await this.web3;
      const [account] = await web3.eth.getAccounts();
      const contractObj = new web3.eth.Contract(contract.abiDefinition, contract.address);
      contractObj._jsonInterface.find(obj => {
        if (obj.type === 'constructor') {
          if (!obj.name) {
            // Add constructor as the name of the method, because if there is an error, it prints `undefined` otherwise
            obj.name = 'constructor';
          }
          return true;
        }
        return false;
      });
      const code = contract.code.substring(0, 2) === '0x' ? contract.code : "0x" + contract.code;
      const contractObject = contractObj.deploy({arguments: (contract.args || []), data: code});
      if (contract.gas === 'auto' || !contract.gas) {
        const gasValue = await contractObject.estimateGas({value: 0, from: account});
        const increase_per = 1 + (Math.random() / 10.0);
        contract.gas = Math.floor(gasValue * increase_per);
      }

      if (!contract.gasPrice) {
        contract.gasPrice = await web3.eth.getGasPrice();
      }

      embarkJsUtils.secureSend(web3, contractObject, {
        from: account, gas: contract.gas, ...additionalDeployParams
      }, true, (err, receipt) => {
        if (err) {
          return done(err);
        }
        contract.deployedAddress = receipt.contractAddress;
        contract.transactionHash = receipt.transactionHash;
        contract.log(`${contract.className.bold.cyan} ${__('deployed at').green} ${receipt.contractAddress.bold.cyan} ${__("using").green} ${receipt.gasUsed} ${__("gas").green} (txHash: ${receipt.transactionHash.bold.cyan})`);
        done(err, receipt);
      }, (hash) => {
        const estimatedCost = contract.gas * contract.gasPrice;
        contract.log(`${__("Deploying")} ${contract.className.bold.cyan} ${__("with").green} ${contract.gas} ${__("gas at the price of").green} ${contract.gasPrice} ${__("Wei. Estimated cost:").green} ${estimatedCost} ${"Wei".green}  (txHash: ${hash.bold.cyan})`);
      });
    } catch (e) {
      this.logger.error(__('Error deploying contract %s', contract.className.underline));
      done(e);
    }
  }

  async doLinking(params, callback) {
    let contract = params.contract;

    if (!contract.linkReferences || !Object.keys(contract.linkReferences).length) {
      return callback(null, params);
    }
    let contractCode = contract.code;
    let offset = 0;

    let contractsList = await this.events.request2("contracts:list");

    async.eachLimit(contract.linkReferences, 1, (fileReference, eachCb1) => {
      async.eachOfLimit(fileReference, 1, (references, libName, eachCb2) => {
        const libContract = contractsList.find(c => c.className === libName);

        if (!libContract) {
          return eachCb2(new Error(__('{{contractName}} has a link to the library {{libraryName}}, but it was not found. Is it in your contract folder?'), {
            contractName: contract.className,
            libraryName: libName
          }));
        }

        let libAddress = libContract.deployedAddress;

        if (!libAddress) {
          return eachCb2(new Error(__("{{contractName}} needs {{libraryName}} but an address was not found, did you deploy it or configured an address?", {
            contractName: contract.className,
            libraryName: libName
          })));
        }

        libAddress = libAddress.substr(2).toLowerCase();

        async.eachLimit(references, 1, (reference, eachCb3) => {
          // Multiplying by two because the original pos and length are in bytes, but we have an hex string
          contractCode = contractCode.substring(0, (reference.start * 2) + offset) + libAddress + contractCode.substring((reference.start * 2) + offset + (reference.length * 2));
          // Calculating an offset in case the length is at some point different than the address length
          offset += libAddress.length - (reference.length * 2);

          eachCb3();
        }, eachCb2);
      }, eachCb1);
    }, (err) => {
      contract.code = contractCode;
      callback(err, params);
    });
  }
  // TODO we can separate this into 3 separate methods, which will make it easier to test
  // determineArguments(suppliedArgs, contract, accounts, callback) {
  async determineArguments(params, callback) {
    const suppliedArgs = params.contract.args;
    const contract = params.contract;
    const web3 = await this.web3;
    const accounts = await web3.eth.getAccounts();

    const self = this;

    let args = suppliedArgs;
    if (!Array.isArray(args)) {
      args = [];
      let abi = contract.abiDefinition.find((abi) => abi.type === 'constructor');

      for (let input of abi.inputs) {
        let inputValue = suppliedArgs[input.name];
        if (!inputValue) {
          this.logger.error(__("{{inputName}} has not been defined for {{className}} constructor", {inputName: input.name, className: contract.className}));
        }
        args.push(inputValue || "");
      }
    }

    function parseArg(arg, cb) {
      const match = arg.match(/\$accounts\[([0-9]+)]/);
      if (match) {
        if (!accounts[match[1]]) {
          return cb(__('No corresponding account at index %d', match[1]));
        }
        return cb(null, accounts[match[1]]);
      }
      let contractName = arg.substr(1);
      self.events.request('contracts:contract', contractName, (err, referedContract) => {
        // Because we're referring to a contract that is not being deployed (ie. an interface),
        // we still need to provide a valid address so that the ABI checker won't fail.
        cb(err, (referedContract.deployedAddress || ZERO_ADDRESS));
      });
    }

    function checkArgs(argus, cb) {
      async.map(argus, (arg, nextEachCb) => {
        if (Array.isArray(arg)) {
          return checkArgs(arg, nextEachCb);
        }
        if (arg && arg[0] === "$") {
          return parseArg(arg, nextEachCb);
        }
        nextEachCb(null, arg);
      }, cb);
    }

    checkArgs(args, (err, realArgs) => {
      if (err) {
        return callback(err);
      }
      params.contract.args = realArgs;
      callback(null, params);
    });
  }

  async determineAccounts(params, callback) {
    const web3 = await this.web3;
    let accounts = await web3.eth.getAccounts();
    let deploymentAccount = accounts[0];
    let contract = params.contract;

    // applying deployer account configuration, if any
    if (typeof contract.fromIndex === 'number') {
      deploymentAccount = accounts[contract.fromIndex];
      if (deploymentAccount === undefined) {
        return callback(__("error deploying") + " " + contract.className + ": " + __("no account found at index") + " " + contract.fromIndex + __(" check the config"));
      }
    }
    if (typeof contract.from === 'string' && typeof contract.fromIndex !== 'undefined') {
      self.logger.warn(__('Both "from" and "fromIndex" are defined for contract') + ' "' + contract.className + '". ' + __('Using "from" as deployer account.'));
    }
    if (typeof contract.from === 'string') {
      deploymentAccount = contract.from;
    }

    contract.deploymentAccount = deploymentAccount;
    callback(null, params);
  }

  addContractJSONToPipeline(params, cb) {
    // TODO: check if this is correct json object to generate
    const contract = params.contract;

    this.events.request("pipeline:register", {
      path: [this.embark.config.embarkConfig.buildDir, 'contracts'],
      file: contract.className + '.json',
      format: 'json',
      content: contract
    }, cb);
  }

}

module.exports = EthereumBlockchainClient;
<commit_msg>chore(dashboard): change currency unit to Gwei and Ether in deployment output<commit_after>import {__} from 'embark-i18n';
import {AddressUtils, dappPath} from 'embark-utils';
const async = require('async');
import Web3 from 'web3';
const embarkJsUtils = require('embarkjs').Utils;
import checkContractSize from "./checkContractSize";
const {ZERO_ADDRESS} = AddressUtils;
import EthereumAPI from "./api";
import constants from "embark-core/constants";

class EthereumBlockchainClient {

  constructor(embark) {
    this.embark = embark;
    this.events = embark.events;
    this.logger = embark.logger;
    this.fs = embark.fs;

    this.logFile = dappPath(".embark", "contractEvents.json");

    this.embark.registerActionForEvent("deployment:contract:undeployed", this.addContractJSONToPipeline.bind(this));
    this.embark.registerActionForEvent("deployment:contract:deployed", this.addContractJSONToPipeline.bind(this));
    this.embark.registerActionForEvent('deployment:contract:beforeDeploy', this.determineArguments.bind(this));
    this.embark.registerActionForEvent('deployment:contract:beforeDeploy', this.doLinking.bind(this));
    this.embark.registerActionForEvent('deployment:contract:beforeDeploy', checkContractSize.bind(this));
    this.embark.registerActionForEvent('deployment:contract:beforeDeploy', this.determineAccounts.bind(this));
    this.events.request("blockchain:client:register", "ethereum", this.getEthereumClient.bind(this));
    this.events.request("deployment:deployer:register", "ethereum", this.deployer.bind(this));

    this.events.on("blockchain:started", () => {
      this._web3 = null;
    });

    this.registerAPIRequests();
  }

  get web3() {
    return (async () => {
      if (!this._web3) {
        const provider = await this.events.request2("blockchain:client:provider", "ethereum");
        this._web3 = new Web3(provider);
      }
      return this._web3;
    })();
  }

  async registerAPIRequests() {
    const ethereumApi = new EthereumAPI(this.embark, await this.web3, "ethereum");
    ethereumApi.registerRequests();
    ethereumApi.registerAPIs();
  }

  getEthereumClient(endpoint) {
    if (endpoint.startsWith('ws')) {
      return new Web3.providers.WebsocketProvider(endpoint, {
        headers: { Origin: constants.embarkResourceOrigin }
      });
    }
    const web3 = new Web3(endpoint);
    return web3.currentProvider;
  }

  async deployer(contract, additionalDeployParams, done) {
    try {
      const web3 = await this.web3;
      const [account] = await web3.eth.getAccounts();
      const contractObj = new web3.eth.Contract(contract.abiDefinition, contract.address);
      contractObj._jsonInterface.find(obj => {
        if (obj.type === 'constructor') {
          if (!obj.name) {
            // Add constructor as the name of the method, because if there is an error, it prints `undefined` otherwise
            obj.name = 'constructor';
          }
          return true;
        }
        return false;
      });
      const code = contract.code.substring(0, 2) === '0x' ? contract.code : "0x" + contract.code;
      const contractObject = contractObj.deploy({arguments: (contract.args || []), data: code});
      if (contract.gas === 'auto' || !contract.gas) {
        const gasValue = await contractObject.estimateGas({value: 0, from: account});
        const increase_per = 1 + (Math.random() / 10.0);
        contract.gas = Math.floor(gasValue * increase_per);
      }

      if (!contract.gasPrice) {
        contract.gasPrice = await web3.eth.getGasPrice();
      }

      embarkJsUtils.secureSend(web3, contractObject, {
        from: account, gas: contract.gas, ...additionalDeployParams
      }, true, (err, receipt) => {
        if (err) {
          return done(err);
        }
        contract.deployedAddress = receipt.contractAddress;
        contract.transactionHash = receipt.transactionHash;
        contract.log(`${contract.className.bold.cyan} ${__('deployed at').green} ${receipt.contractAddress.bold.cyan} ${__("using").green} ${receipt.gasUsed} ${__("gas").green} (txHash: ${receipt.transactionHash.bold.cyan})`);
        done(err, receipt);
      }, (hash) => {
        const estimatedCost = contract.gas * contract.gasPrice;
        contract.log(`${__("Deploying")} ${contract.className.bold.cyan} ${__("with").green} ${contract.gas} ${__("gas at the price of").green} ${Web3.utils.fromWei(contract.gasPrice, 'gwei')} ${__("Gwei. Estimated cost:").green} ${Web3.utils.fromWei(estimatedCost.toString())} ${"ether".green}  (txHash: ${hash.bold.cyan})`);
      });
    } catch (e) {
      this.logger.error(__('Error deploying contract %s', contract.className.underline));
      done(e);
    }
  }

  async doLinking(params, callback) {
    let contract = params.contract;

    if (!contract.linkReferences || !Object.keys(contract.linkReferences).length) {
      return callback(null, params);
    }
    let contractCode = contract.code;
    let offset = 0;

    let contractsList = await this.events.request2("contracts:list");

    async.eachLimit(contract.linkReferences, 1, (fileReference, eachCb1) => {
      async.eachOfLimit(fileReference, 1, (references, libName, eachCb2) => {
        const libContract = contractsList.find(c => c.className === libName);

        if (!libContract) {
          return eachCb2(new Error(__('{{contractName}} has a link to the library {{libraryName}}, but it was not found. Is it in your contract folder?'), {
            contractName: contract.className,
            libraryName: libName
          }));
        }

        let libAddress = libContract.deployedAddress;

        if (!libAddress) {
          return eachCb2(new Error(__("{{contractName}} needs {{libraryName}} but an address was not found, did you deploy it or configured an address?", {
            contractName: contract.className,
            libraryName: libName
          })));
        }

        libAddress = libAddress.substr(2).toLowerCase();

        async.eachLimit(references, 1, (reference, eachCb3) => {
          // Multiplying by two because the original pos and length are in bytes, but we have an hex string
          contractCode = contractCode.substring(0, (reference.start * 2) + offset) + libAddress + contractCode.substring((reference.start * 2) + offset + (reference.length * 2));
          // Calculating an offset in case the length is at some point different than the address length
          offset += libAddress.length - (reference.length * 2);

          eachCb3();
        }, eachCb2);
      }, eachCb1);
    }, (err) => {
      contract.code = contractCode;
      callback(err, params);
    });
  }
  // TODO we can separate this into 3 separate methods, which will make it easier to test
  // determineArguments(suppliedArgs, contract, accounts, callback) {
  async determineArguments(params, callback) {
    const suppliedArgs = params.contract.args;
    const contract = params.contract;
    const web3 = await this.web3;
    const accounts = await web3.eth.getAccounts();

    const self = this;

    let args = suppliedArgs;
    if (!Array.isArray(args)) {
      args = [];
      let abi = contract.abiDefinition.find((abi) => abi.type === 'constructor');

      for (let input of abi.inputs) {
        let inputValue = suppliedArgs[input.name];
        if (!inputValue) {
          this.logger.error(__("{{inputName}} has not been defined for {{className}} constructor", {inputName: input.name, className: contract.className}));
        }
        args.push(inputValue || "");
      }
    }

    function parseArg(arg, cb) {
      const match = arg.match(/\$accounts\[([0-9]+)]/);
      if (match) {
        if (!accounts[match[1]]) {
          return cb(__('No corresponding account at index %d', match[1]));
        }
        return cb(null, accounts[match[1]]);
      }
      let contractName = arg.substr(1);
      self.events.request('contracts:contract', contractName, (err, referedContract) => {
        // Because we're referring to a contract that is not being deployed (ie. an interface),
        // we still need to provide a valid address so that the ABI checker won't fail.
        cb(err, (referedContract.deployedAddress || ZERO_ADDRESS));
      });
    }

    function checkArgs(argus, cb) {
      async.map(argus, (arg, nextEachCb) => {
        if (Array.isArray(arg)) {
          return checkArgs(arg, nextEachCb);
        }
        if (arg && arg[0] === "$") {
          return parseArg(arg, nextEachCb);
        }
        nextEachCb(null, arg);
      }, cb);
    }

    checkArgs(args, (err, realArgs) => {
      if (err) {
        return callback(err);
      }
      params.contract.args = realArgs;
      callback(null, params);
    });
  }

  async determineAccounts(params, callback) {
    const web3 = await this.web3;
    let accounts = await web3.eth.getAccounts();
    let deploymentAccount = accounts[0];
    let contract = params.contract;

    // applying deployer account configuration, if any
    if (typeof contract.fromIndex === 'number') {
      deploymentAccount = accounts[contract.fromIndex];
      if (deploymentAccount === undefined) {
        return callback(__("error deploying") + " " + contract.className + ": " + __("no account found at index") + " " + contract.fromIndex + __(" check the config"));
      }
    }
    if (typeof contract.from === 'string' && typeof contract.fromIndex !== 'undefined') {
      self.logger.warn(__('Both "from" and "fromIndex" are defined for contract') + ' "' + contract.className + '". ' + __('Using "from" as deployer account.'));
    }
    if (typeof contract.from === 'string') {
      deploymentAccount = contract.from;
    }

    contract.deploymentAccount = deploymentAccount;
    callback(null, params);
  }

  addContractJSONToPipeline(params, cb) {
    // TODO: check if this is correct json object to generate
    const contract = params.contract;

    this.events.request("pipeline:register", {
      path: [this.embark.config.embarkConfig.buildDir, 'contracts'],
      file: contract.className + '.json',
      format: 'json',
      content: contract
    }, cb);
  }

}

module.exports = EthereumBlockchainClient;
<|endoftext|>


<commit_before>var img2 = new Image();
img2.src = "../static/assets/particle.png";

var background = document.getElementById("cv1"),
foreground1 = document.getElementById("cv2"),
foreground2 = document.getElementById("cv3"),
canvas_bg = document.querySelector("#bg").children,
config = {
	circle: {
		amount: 21,
		layer: 3,
		color: [0, 0, 0],
		alpha: 0.3
	},
	line: {
		amount: 15,
		layer: 3,
		color: [0, 255, 255],
		alpha: 0.3
	},
	speed: 0.5,
	angle: 20
};

console.log(canvas_bg);

if (background.getContext){
	var bctx = background.getContext('2d'),
	fctx1 = foreground1.getContext('2d'),
	fctx2 = foreground2.getContext('2d'),
	M = window.Math, // Cached Math
	degree = config.angle/360*M.PI*2,
	circles = [],
	lines = [],
	wWidth, wHeight, timer;

	requestAnimationFrame = window.requestAnimationFrame ||
	window.mozRequestAnimationFrame ||
	window.webkitRequestAnimationFrame ||
	window.msRequestAnimationFrame ||
	window.oRequestAnimationFrame ||
	function(callback, element) { setTimeout(callback, 1000 / 60); };

	cancelAnimationFrame = window.cancelAnimationFrame ||
	window.mozCancelAnimationFrame ||
	window.webkitCancelAnimationFrame ||
	window.msCancelAnimationFrame ||
	window.oCancelAnimationFrame ||
	clearTimeout;

	var setCanvasHeight = function(){

		wndsize = wndsize()
		for(var i = 0; canvas_bg.length > i ; i++){
			canvas_bg[i].width = wWidth;
			canvas_bg[i].height = wHeight;
		}
	};

	var drawCircle = function(x, y, radius, color, alpha){
		var gradient = fctx1.createRadialGradient(x, y, radius, x, y, 0);
		gradient.addColorStop(0, 'rgba('+color[0]+','+color[1]+','+color[2]+','+alpha+')');
		gradient.addColorStop(1, 'rgba('+color[0]+','+color[1]+','+color[2]+','+(alpha-0.1)+')');

		fctx1.beginPath();
		fctx1.arc(x, y, radius, 0, M.PI*2, true);
		fctx1.fillStyle = gradient;
		fctx1.fill();
	};

	var drawLine = function(x, y, width, color, alpha){
		var endX = x+M.sin(degree)*width,
		endY = y-M.cos(degree)*width,
		gradient = fctx2.createLinearGradient(x, y, endX, endY);
		gradient.addColorStop(0, 'rgba('+color[0]+','+color[1]+','+color[2]+','+alpha+')');
		gradient.addColorStop(1, 'rgba('+color[0]+','+color[1]+','+color[2]+','+(alpha-0.1)+')');

		fctx2.beginPath();
		fctx2.drawImage(img2,x,y,30,20);
		fctx2.moveTo(x, y);

		// fctx2.lineTo(endX, endY);
		// fctx2.lineWidth = 3;
		// fctx2.lineCap = 'round';
		// fctx2.strokeStyle = gradient;
		// fctx2.stroke();
	};

	var drawBack = function(){
		bctx.clearRect(0, 0, wWidth, wHeight);

		var gradient = [];

		gradient[0] = bctx.createRadialGradient(wWidth*0.3, wHeight*0.1, 0, wWidth*0.3, wHeight*0.1, wWidth*0.9);
		gradient[0].addColorStop(0, 'rgb(243, 72, 45)');
		gradient[0].addColorStop(1, 'transparent');

		bctx.translate(wWidth, 0);
		bctx.scale(-1,1);
		bctx.beginPath();
		bctx.fillStyle = gradient[0];
		bctx.fillRect(0, 0, wWidth, wHeight);

		gradient[1] = bctx.createRadialGradient(wWidth*0.1, wHeight*0.1, 0, wWidth*0.3, wHeight*0.1, wWidth);
		gradient[1].addColorStop(0, 'rgb(243, 72, 45)');
		gradient[1].addColorStop(0.8, 'transparent');

		bctx.translate(wWidth, 0);
		bctx.scale(-1,1);
		bctx.beginPath();
		bctx.fillStyle = gradient[1];
		bctx.fillRect(0, 0, wWidth, wHeight);

		gradient[2] = bctx.createRadialGradient(wWidth*0.1, wHeight*0.5, 0, wWidth*0.1, wHeight*0.5, wWidth*0.5);
		gradient[2].addColorStop(0, 'rgb(243, 72, 45)');
		gradient[2].addColorStop(1, 'transparent');

		bctx.beginPath();
		bctx.fillStyle = gradient[2];
		bctx.fillRect(0, 0, wWidth, wHeight);
	};

	var animate = function(){
		var sin = M.sin(degree),
		cos = M.cos(degree);

		if (config.circle.amount > 0 && config.circle.layer > 0){
			fctx1.clearRect(0, 0, wWidth, wHeight);
			for (var i=0, len = circles.length; i<len; i++){
				var item = circles[i],
				x = item.x,
				y = item.y,
				radius = item.radius,
				speed = item.speed;

				if (x > wWidth + radius){
					x = -radius;
				} else if (x < -radius){
					x = wWidth + radius
				} else {
					x += sin*speed;
				}

				if (y > wHeight + radius){
					y = -radius;
				} else if (y < -radius){
					y = wHeight + radius;
				} else {
					y -= cos*speed;
				}

				item.x = x;
				item.y = y;
				drawCircle(x, y, radius, item.color, item.alpha);
			}
		}

		if (config.line.amount > 0 && config.line.layer > 0){
			fctx2.clearRect(0, 0, wWidth, wHeight);
			for (var j=0, len = lines.length; j<len; j++){
				var item = lines[j],
				x = item.x,
				y = item.y,
				width = item.width,
				speed = item.speed;

				if (x > wWidth + width * sin){
					x = -width * sin;
				} else if (x < -width * sin){
					x = wWidth + width * sin;
				} else {
					x += sin*speed;
				}

				if (y > wHeight + width * cos){
					y = -width * cos;
				} else if (y < -width * cos){
					y = wHeight + width * cos;
				} else {
					y -= cos*speed;
				}

				item.x = x;
				item.y = y;
				drawLine(x, y, width, item.color, item.alpha);
			}
		}

		timer = requestAnimationFrame(animate);
	};

	var createItem = function(){
		circles = [];
		lines = [];

		if (config.circle.amount > 0 && config.circle.layer > 0){
			for (var i=0; i<config.circle.amount/config.circle.layer; i++){
				for (var j=0; j<config.circle.layer; j++){
					circles.push({
						x: M.random() * wWidth,
						y: M.random() * wHeight,
						radius: M.random()*(20+j*5)+(20+j*5),
						color: config.circle.color,
						alpha: M.random()*0.2+(config.circle.alpha-j*0.1),
						speed: config.speed*(1+j*0.5)
					});
				}
			}
		}

		if (config.line.amount > 0 && config.line.layer > 0){
			for (var m=0; m<config.line.amount/config.line.layer; m++){
				for (var n=0; n<config.line.layer; n++){
					lines.push({
						x: M.random() * wWidth,
						y: M.random() * wHeight,
						width: M.random()*(20+n*5)+(20+n*5),
						color: config.line.color,
						alpha: M.random()*0.2+(config.line.alpha-n*0.1),
						speed: config.speed*(1+n*0.5)
					});
				}
			}
		}

		cancelAnimationFrame(timer);
		timer = requestAnimationFrame(animate);
		drawBack();
	};

	window.onload = function(){
		setCanvasHeight();
		createItem();
	}
};

function wndsize(){
	var w = 0;var h = 0;
	if(!window.innerWidth){
		if(!(document.documentElement.clientWidth == 0)){
			w = document.documentElement.clientWidth;h = document.documentElement.clientHeight;
		} else{
			w = document.body.clientWidth;h = document.body.clientHeight;
		}
	} else {
		w = window.innerWidth;h = window.innerHeight;
	}
	return {width:w,height:h};
}
<commit_msg>removed console log and unbroke vwidth<commit_after>var img2 = new Image();
img2.src = "../static/assets/particle.png";

var background = document.getElementById("cv1"),
foreground1 = document.getElementById("cv2"),
foreground2 = document.getElementById("cv3"),
canvas_bg = document.querySelector("#bg").children,
config = {
	circle: {
		amount: 21,
		layer: 3,
		color: [0, 0, 0],
		alpha: 0.3
	},
	line: {
		amount: 15,
		layer: 3,
		color: [0, 255, 255],
		alpha: 0.3
	},
	speed: 0.5,
	angle: 20
};

if (background.getContext){
	var bctx = background.getContext('2d'),
	fctx1 = foreground1.getContext('2d'),
	fctx2 = foreground2.getContext('2d'),
	M = window.Math, // Cached Math
	degree = config.angle/360*M.PI*2,
	circles = [],
	lines = [],
	wWidth, wHeight, timer;

	requestAnimationFrame = window.requestAnimationFrame ||
	window.mozRequestAnimationFrame ||
	window.webkitRequestAnimationFrame ||
	window.msRequestAnimationFrame ||
	window.oRequestAnimationFrame ||
	function(callback, element) { setTimeout(callback, 1000 / 60); };

	cancelAnimationFrame = window.cancelAnimationFrame ||
	window.mozCancelAnimationFrame ||
	window.webkitCancelAnimationFrame ||
	window.msCancelAnimationFrame ||
	window.oCancelAnimationFrame ||
	clearTimeout;

	var setCanvasHeight = function(){

		wndsize = wndsize()
		wWidth = wndsize.width;
		wHeight = wndsize.height;
		for(var i = 0; canvas_bg.length > i ; i++){
			canvas_bg[i].width = wWidth;
			canvas_bg[i].height = wHeight;
		}
	};

	var drawCircle = function(x, y, radius, color, alpha){
		var gradient = fctx1.createRadialGradient(x, y, radius, x, y, 0);
		gradient.addColorStop(0, 'rgba('+color[0]+','+color[1]+','+color[2]+','+alpha+')');
		gradient.addColorStop(1, 'rgba('+color[0]+','+color[1]+','+color[2]+','+(alpha-0.1)+')');

		fctx1.beginPath();
		fctx1.arc(x, y, radius, 0, M.PI*2, true);
		fctx1.fillStyle = gradient;
		fctx1.fill();
	};

	var drawLine = function(x, y, width, color, alpha){
		var endX = x+M.sin(degree)*width,
		endY = y-M.cos(degree)*width,
		gradient = fctx2.createLinearGradient(x, y, endX, endY);
		gradient.addColorStop(0, 'rgba('+color[0]+','+color[1]+','+color[2]+','+alpha+')');
		gradient.addColorStop(1, 'rgba('+color[0]+','+color[1]+','+color[2]+','+(alpha-0.1)+')');

		fctx2.beginPath();
		fctx2.drawImage(img2,x,y,30,20);
		fctx2.moveTo(x, y);

		// fctx2.lineTo(endX, endY);
		// fctx2.lineWidth = 3;
		// fctx2.lineCap = 'round';
		// fctx2.strokeStyle = gradient;
		// fctx2.stroke();
	};

	var drawBack = function(){
		bctx.clearRect(0, 0, wWidth, wHeight);

		var gradient = [];
		console.log(wWidth);
		gradient[0] = bctx.createRadialGradient(wWidth*0.3, wHeight*0.1, 0, wWidth*0.3, wHeight*0.1, wWidth*0.9);
		gradient[0].addColorStop(0, 'rgb(243, 72, 45)');
		gradient[0].addColorStop(1, 'transparent');

		bctx.translate(wWidth, 0);
		bctx.scale(-1,1);
		bctx.beginPath();
		bctx.fillStyle = gradient[0];
		bctx.fillRect(0, 0, wWidth, wHeight);

		gradient[1] = bctx.createRadialGradient(wWidth*0.1, wHeight*0.1, 0, wWidth*0.3, wHeight*0.1, wWidth);
		gradient[1].addColorStop(0, 'rgb(243, 72, 45)');
		gradient[1].addColorStop(0.8, 'transparent');

		bctx.translate(wWidth, 0);
		bctx.scale(-1,1);
		bctx.beginPath();
		bctx.fillStyle = gradient[1];
		bctx.fillRect(0, 0, wWidth, wHeight);

		gradient[2] = bctx.createRadialGradient(wWidth*0.1, wHeight*0.5, 0, wWidth*0.1, wHeight*0.5, wWidth*0.5);
		gradient[2].addColorStop(0, 'rgb(243, 72, 45)');
		gradient[2].addColorStop(1, 'transparent');

		bctx.beginPath();
		bctx.fillStyle = gradient[2];
		bctx.fillRect(0, 0, wWidth, wHeight);
	};

	var animate = function(){
		var sin = M.sin(degree),
		cos = M.cos(degree);

		if (config.circle.amount > 0 && config.circle.layer > 0){
			fctx1.clearRect(0, 0, wWidth, wHeight);
			for (var i=0, len = circles.length; i<len; i++){
				var item = circles[i],
				x = item.x,
				y = item.y,
				radius = item.radius,
				speed = item.speed;

				if (x > wWidth + radius){
					x = -radius;
				} else if (x < -radius){
					x = wWidth + radius
				} else {
					x += sin*speed;
				}

				if (y > wHeight + radius){
					y = -radius;
				} else if (y < -radius){
					y = wHeight + radius;
				} else {
					y -= cos*speed;
				}

				item.x = x;
				item.y = y;
				drawCircle(x, y, radius, item.color, item.alpha);
			}
		}

		if (config.line.amount > 0 && config.line.layer > 0){
			fctx2.clearRect(0, 0, wWidth, wHeight);
			for (var j=0, len = lines.length; j<len; j++){
				var item = lines[j],
				x = item.x,
				y = item.y,
				width = item.width,
				speed = item.speed;

				if (x > wWidth + width * sin){
					x = -width * sin;
				} else if (x < -width * sin){
					x = wWidth + width * sin;
				} else {
					x += sin*speed;
				}

				if (y > wHeight + width * cos){
					y = -width * cos;
				} else if (y < -width * cos){
					y = wHeight + width * cos;
				} else {
					y -= cos*speed;
				}

				item.x = x;
				item.y = y;
				drawLine(x, y, width, item.color, item.alpha);
			}
		}

		timer = requestAnimationFrame(animate);
	};

	var createItem = function(){
		circles = [];
		lines = [];

		if (config.circle.amount > 0 && config.circle.layer > 0){
			for (var i=0; i<config.circle.amount/config.circle.layer; i++){
				for (var j=0; j<config.circle.layer; j++){
					circles.push({
						x: M.random() * wWidth,
						y: M.random() * wHeight,
						radius: M.random()*(20+j*5)+(20+j*5),
						color: config.circle.color,
						alpha: M.random()*0.2+(config.circle.alpha-j*0.1),
						speed: config.speed*(1+j*0.5)
					});
				}
			}
		}

		if (config.line.amount > 0 && config.line.layer > 0){
			for (var m=0; m<config.line.amount/config.line.layer; m++){
				for (var n=0; n<config.line.layer; n++){
					lines.push({
						x: M.random() * wWidth,
						y: M.random() * wHeight,
						width: M.random()*(20+n*5)+(20+n*5),
						color: config.line.color,
						alpha: M.random()*0.2+(config.line.alpha-n*0.1),
						speed: config.speed*(1+n*0.5)
					});
				}
			}
		}

		cancelAnimationFrame(timer);
		timer = requestAnimationFrame(animate);
		drawBack();
	};

	setCanvasHeight();
	createItem();
};

function wndsize(){
	var w = 0;var h = 0;
	if(!window.innerWidth){
		if(!(document.documentElement.clientWidth == 0)){
			w = document.documentElement.clientWidth;h = document.documentElement.clientHeight;
		} else{
			w = document.body.clientWidth;h = document.body.clientHeight;
		}
	} else {
		w = window.innerWidth;h = window.innerHeight;
	}
	return {width:w,height:h};
}
<|endoftext|>


<commit_before>import test from 'ava';
import postcss from 'postcss';
import plugin from '..';
import {name} from '../../package.json';

const suites = [{
    message: 'should merge identical border values',
    fixture: 'h1{border-top:1px solid black;border-bottom:1px solid black;border-left:1px solid black;border-right:1px solid black}',
    expected: 'h1{border:1px solid black}'
}, {
    message: 'should merge identical border values with !important',
    fixture: 'h1{border-top:1px solid black!important;border-bottom:1px solid black!important;border-left:1px solid black!important;border-right:1px solid black!important}',
    expected: 'h1{border:1px solid black!important}'
}, {
    message: 'should not merge identical border values with mixed !important',
    fixture: 'h1{border-top:1px solid black;border-bottom:1px solid black;border-left:1px solid black!important;border-right:1px solid black!important}',
    expected: 'h1{border-top:1px solid black;border-bottom:1px solid black;border-left:1px solid black!important;border-right:1px solid black!important}',
}, {
    message: 'should merge border values',
    fixture: 'h1{border-color:red;border-width:1px;border-style:dashed}',
    expected: 'h1{border:1px dashed red}'
}, {
    message: 'should merge border values with !important',
    fixture: 'h1{border-color:red!important;border-width:1px!important;border-style:dashed!important}',
    expected: 'h1{border:1px dashed red!important}'
}, {
    message: 'should merge border values with identical values for all sides',
    fixture: 'h1{border-color:red red red red;border-width:1px 1px 1px 1px;border-style:solid solid solid solid}',
    expected: 'h1{border:1px solid red}'
}, {
    message: 'should merge border value shorthands',
    fixture: 'h1{border-color:red blue red blue;border-style:solid;border-width:10px 20px 10px 20px}',
    expected: 'h1{border-color:red blue;border-style:solid;border-width:10px 20px}'
}, {
    message: 'should not merge border values with mixed !important',
    fixture: 'h1{border-color:red;border-width:1px!important;border-style:dashed!important}',
    expected: 'h1{border-color:red;border-width:1px!important;border-style:dashed!important}'
}, {
    message: 'should not merge border values with more than 3 values',
    fixture: 'h1{border-color:red;border-style:dashed;border-width:1px 5px}',
    expected: 'h1{border-color:red;border-style:dashed;border-width:1px 5px}',
}, {
    message: 'should not merge rules with the inherit keyword',
    fixture: 'h1{border-width:3px;border-style:solid;border-color:inherit}',
    expected: 'h1{border:3px solid;border-color:inherit}',
}, {
    message: 'should not crash on comments',
    fixture: 'h1{\n  border-width:3px;/* 1 */\n  border-style:solid;/* 2 */\n  border-color:red;/* 3 */}',
    expected: 'h1{/* 1 *//* 2 */\n  border:3px solid red;/* 3 */}'
}, {
    message: 'should merge border-top-width',
    fixture: 'h1{border-top-width:5px;border-top-style:solid;border-top-color:red}',
    expected: 'h1{border-top:5px solid red}'
}, {
    message: 'should merge border-right-width',
    fixture: 'h1{border-right-width:5px;border-right-style:solid;border-right-color:red}',
    expected: 'h1{border-right:5px solid red}'
}, {
    message: 'should merge border-bottom-width',
    fixture: 'h1{border-bottom-width:5px;border-bottom-style:solid;border-bottom-color:red}',
    expected: 'h1{border-bottom:5px solid red}'
}, {
    message: 'should merge border-left-width',
    fixture: 'h1{border-left-width:5px;border-left-style:solid;border-left-color:red}',
    expected: 'h1{border-left:5px solid red}'
}, {
    message: 'should not convert border: 0 to border-width: 0',
    fixture: 'h1{border:0}',
    expected: 'h1{border:0}'
}, {
    message: 'should not merge border-left values with mixed !important',
    fixture: 'h1{border-left-color:red;border-left-width:1px!important;border-left-style:dashed!important}',
    expected: 'h1{border-left-color:red;border-left-width:1px!important;border-left-style:dashed!important}'
}, {
    message: 'should minimize default border values',
    fixture: 'h1{border:medium none currentColor}',
    expected: 'h1{border:medium}'
}, {
    message: 'should optimize border merging for length',
    fixture: 'h1{border:1px solid #ddd;border-bottom:1px solid #fff}',
    expected: 'h1{border:1px solid;border-color:#ddd #ddd #fff}'
}, {
    message: 'should not mangle borders',
    fixture: 'hr{display:block;height:1px;border:0;border-top:1px solid #ddd}',
    expected: 'hr{display:block;height:1px;border:0;border-top:1px solid #ddd}'
}, {
    message: 'should use shorter equivalent rules',
    fixture: 'h1{border:5px solid;border-color:#222 transparent transparent}',
    expected: 'h1{border:5px solid transparent;border-top:5px solid #222}'
}, {
    message: 'should merge redundant values',
    fixture: 'h1{border-width:5px 5px 0;border-bottom-width:0}',
    expected: 'h1{border-width:5px 5px 0}'
}, {
    message: 'should merge redundant values (2)',
    fixture: 'h1{border-width:5px 5px 0;border-bottom-width:10px}',
    expected: 'h1{border-width:5px 5px 10px}'
}, {
    message: 'should merge redundant values (3)',
    fixture: 'h1{border:1px solid #ddd;border-bottom-color:transparent}',
    expected: 'h1{border:1px solid;border-color:#ddd #ddd transparent}'
}, {
    message: 'should produce the minimum css necessary',
    fixture: 'h1{border-width:0;border-top:1px solid #e1e1e1}',
    expected: 'h1{border-width:0;border-top:1px solid #e1e1e1}'
}, {
    message: 'should produce the minimum css necessary (2)',
    fixture: 'h1{border-color:rgba(0,0,0,.2);border-right-style:solid;border-right-width:1px}',
    expected: 'h1{border-right:1px solid;border-color:rgba(0,0,0,.2)}'
}];

suites.forEach(suite => {
    test(suite.message, t => {
        return postcss(plugin).process(suite.fixture).then(({css}) => {
            t.deepEqual(css, suite.expected);
        });
    });
});

test('should use the postcss plugin api', t => {
    t.truthy(plugin().postcssVersion, 'should be able to access version');
    t.deepEqual(plugin().postcssPlugin, name, 'should be able to access name');
});
<commit_msg>Add more tests.<commit_after>import test from 'ava';
import postcss from 'postcss';
import plugin from '..';
import {name} from '../../package.json';
import trbl from '../lib/trbl';

let suites = [];

const wsc = [{
    property: 'width',
    fixture: '1px'
}, {
    property: 'style',
    fixture: 'solid'
}, {
    property: 'color',
    fixture: 'red'
}];

wsc.forEach(({property, fixture}) => {
    suites.push({
        message: `should merge to form a border-trbl-${property} definition`,
        fixture: [
            `h1{`,
            `border-${trbl[0]}-${property}:${fixture};`,
            `border-${trbl[1]}-${property}:${fixture};`,
            `border-${trbl[2]}-${property}:${fixture};`,
            `border-${trbl[3]}-${property}:${fixture}`,
            `}`,
        ].join(''),
        expected: `h1{border-${property}:${fixture}}`
    });
});

trbl.forEach(direction => {
    const value = wsc.reduce((list, {fixture}) => [...list, fixture], []);
    suites.push({
        message: `should merge to form a border-${direction} definition`,
        fixture: [
            `h1{`,
            `border-${direction}-width:${value[0]};`,
            `border-${direction}-style:${value[1]};`,
            `border-${direction}-color:${value[2]}`,
            `}`,
        ].join(''),
        expected: `h1{border-${direction}:${value[0]} ${value[1]} ${value[2]}}`
    });
});

suites.push({
    message: 'should merge identical border values',
    fixture: 'h1{border-top:1px solid black;border-bottom:1px solid black;border-left:1px solid black;border-right:1px solid black}',
    expected: 'h1{border:1px solid black}'
}, {
    message: 'should merge identical border values with !important',
    fixture: 'h1{border-top:1px solid black!important;border-bottom:1px solid black!important;border-left:1px solid black!important;border-right:1px solid black!important}',
    expected: 'h1{border:1px solid black!important}'
}, {
    message: 'should not merge identical border values with mixed !important',
    fixture: 'h1{border-top:1px solid black;border-bottom:1px solid black;border-left:1px solid black!important;border-right:1px solid black!important}',
    expected: 'h1{border-top:1px solid black;border-bottom:1px solid black;border-left:1px solid black!important;border-right:1px solid black!important}',
}, {
    message: 'should merge border values',
    fixture: 'h1{border-color:red;border-width:1px;border-style:dashed}',
    expected: 'h1{border:1px dashed red}'
}, {
    message: 'should merge border values with !important',
    fixture: 'h1{border-color:red!important;border-width:1px!important;border-style:dashed!important}',
    expected: 'h1{border:1px dashed red!important}'
}, {
    message: 'should merge border values with identical values for all sides',
    fixture: 'h1{border-color:red red red red;border-width:1px 1px 1px 1px;border-style:solid solid solid solid}',
    expected: 'h1{border:1px solid red}'
}, {
    message: 'should merge border value shorthands',
    fixture: 'h1{border-color:red blue red blue;border-style:solid;border-width:10px 20px 10px 20px}',
    expected: 'h1{border-color:red blue;border-style:solid;border-width:10px 20px}'
}, {
    message: 'should not merge border values with mixed !important',
    fixture: 'h1{border-color:red;border-width:1px!important;border-style:dashed!important}',
    expected: 'h1{border-color:red;border-width:1px!important;border-style:dashed!important}'
}, {
    message: 'should not merge border values with more than 3 values',
    fixture: 'h1{border-color:red;border-style:dashed;border-width:1px 5px}',
    expected: 'h1{border-color:red;border-style:dashed;border-width:1px 5px}',
}, {
    message: 'should not merge rules with the inherit keyword',
    fixture: 'h1{border-width:3px;border-style:solid;border-color:inherit}',
    expected: 'h1{border:3px solid;border-color:inherit}',
}, {
    message: 'should not crash on comments',
    fixture: 'h1{\n  border-width:3px;/* 1 */\n  border-style:solid;/* 2 */\n  border-color:red;/* 3 */}',
    expected: 'h1{/* 1 *//* 2 */\n  border:3px solid red;/* 3 */}'
}, {
    message: 'should not convert border: 0 to border-width: 0',
    fixture: 'h1{border:0}',
    expected: 'h1{border:0}'
}, {
    message: 'should not merge border-left values with mixed !important',
    fixture: 'h1{border-left-color:red;border-left-width:1px!important;border-left-style:dashed!important}',
    expected: 'h1{border-left-color:red;border-left-width:1px!important;border-left-style:dashed!important}'
}, {
    message: 'should minimize default border values',
    fixture: 'h1{border:medium none currentColor}',
    expected: 'h1{border:medium}'
}, {
    message: 'should optimize border merging for length',
    fixture: 'h1{border:1px solid #ddd;border-bottom:1px solid #fff}',
    expected: 'h1{border:1px solid;border-color:#ddd #ddd #fff}'
}, {
    message: 'should not mangle borders',
    fixture: 'hr{display:block;height:1px;border:0;border-top:1px solid #ddd}',
    expected: 'hr{display:block;height:1px;border:0;border-top:1px solid #ddd}'
}, {
    message: 'should use shorter equivalent rules',
    fixture: 'h1{border:5px solid;border-color:#222 transparent transparent}',
    expected: 'h1{border:5px solid transparent;border-top:5px solid #222}'
}, {
    message: 'should merge redundant values',
    fixture: 'h1{border-width:5px 5px 0;border-bottom-width:0}',
    expected: 'h1{border-width:5px 5px 0}'
}, {
    message: 'should merge redundant values (2)',
    fixture: 'h1{border-width:5px 5px 0;border-bottom-width:10px}',
    expected: 'h1{border-width:5px 5px 10px}'
}, {
    message: 'should merge redundant values (3)',
    fixture: 'h1{border:1px solid #ddd;border-bottom-color:transparent}',
    expected: 'h1{border:1px solid;border-color:#ddd #ddd transparent}'
}, {
    message: 'should produce the minimum css necessary',
    fixture: 'h1{border-width:0;border-top:1px solid #e1e1e1}',
    expected: 'h1{border-width:0;border-top:1px solid #e1e1e1}'
}, {
    message: 'should produce the minimum css necessary (2)',
    fixture: 'h1{border-color:rgba(0,0,0,.2);border-right-style:solid;border-right-width:1px}',
    expected: 'h1{border-right:1px solid;border-color:rgba(0,0,0,.2)}'
});

suites.forEach(suite => {
    test(suite.message, t => {
        return postcss(plugin).process(suite.fixture).then(({css}) => {
            t.deepEqual(css, suite.expected);
        });
    });
});

test('should use the postcss plugin api', t => {
    t.truthy(plugin().postcssVersion, 'should be able to access version');
    t.deepEqual(plugin().postcssPlugin, name, 'should be able to access name');
});
<|endoftext|>