<commit_before>'use strict';

/* Controllers */

angular.module('atpcms.controllers', [])
	/******************************************************************************
  	//////////////////////////////////////////// NavCtrl
  	******************************************************************************/
	.controller('NavCtrl', ['$scope', '$rootScope', '$location', 'AppstateSrv', function($scope, $rootScope, $location, AppstateSrv) {
	//
		//$scope.mylocation = $location.path();

		$scope.getscreen = function(screen) {
			$location.url('/' + screen);
		};

		$scope.chekLocation = function(loc) {
		  return $location.path() == loc;
		};

		$scope.checkLoggedin = function() {
		  return AppstateSrv.getParam("loggedin");
		};

		var authCheck = function (event) {
		    if(!AppstateSrv.getParam("loggedin")) {
		        //
		        $location.path('/login');
		    };
		};

		authCheck(null);

		$rootScope.$on("$routeChangeStart", authCheck);
	}])
	/******************************************************************************
  	//////////////////////////////////////////// HomeCtrl
  	******************************************************************************/
	.controller('HomeCtrl', ['$scope', 'AppstateSrv', 'AdvertisersSrv', 'MarketsSrv',function($scope, AppstateSrv, AdvertisersSrv, MarketsSrv) {
		//
		if(!AppstateSrv.getParam("loggedin")){
			return false;
		};

		if(AppstateSrv.getParam("advertisers") === null) {
			//
			AdvertisersSrv
			.getAdvertisers()
			.success(function(advData){

				var apiAdvertisers = [];

				angular.forEach(advData, function(advertiser){
					//
                    //
                    MarketsSrv.getMarkets(advertiser.advertiserID)
                    .success(function(mktData){
                        //
                        if(AppstateSrv.getParam('superadmin') || _.indexOf(AppstateSrv.getParam('advspermitted'), advertiser.advertiserID) !== -1){
                            //console.log("ADDIT")
                            apiAdvertisers.push({advertiser : advertiser, markets : mktData});
                            AppstateSrv.setParam("advertisers", apiAdvertisers);
                        } else {
                            //
                            //console.log("SKIpIT")
                        }
                    })
                    .error(function(){
                        // die silently
                    })

				});
			})
			.error(function(){
				//
				alert("error fetching advertisers");
			});
		}
	}])
	/******************************************************************************
  	//////////////////////////////////////////// HomeCtrl
  	******************************************************************************/
	.controller('LoginCtrl', [
		'$scope', '$location', 'LoginSrv', 'AppstateSrv', 'toaster',
		function($scope, $location, LoginSrv, AppstateSrv, toaster) {
		//
		$scope.login = {
			u : "",
			p : ""
		};

		$scope.dologin = function() {

            var user = $scope.login.u;
            //console.log(user)
            //alert(user.indexOf("SA"))
            if(user.indexOf("AD") !== -1){
                AppstateSrv.setParam('admin', true);
                user = user.replace("AD","");
            } else if(user.indexOf("SA") !== -1) {
                //alert("SUPER")
                AppstateSrv.setParam('superadmin', true);
                user = user.replace("SA","");
            };

            $scope.login.u = user;

			LoginSrv.getLogin($scope.login).success(onLoginSuccess).error(onLoginError);
		};

		var onLoginSuccess = function(data) {
			//
			toaster.pop('success', "success", '
Your login was successful
', 2000, 'trustedHtml');

            AppstateSrv.setParam('advspermitted', data.advertisers);
			AppstateSrv.setParam('loggedin', true);
			AppstateSrv.setParam('sid', data.sid);

            //console.log("SA " + AppstateSrv.getParam('superadmin'))
            //console.log("AD " + AppstateSrv.getParam('admin'))
			$location.path("home");
		};

		var onLoginError = function() {
			//
			toaster.pop('error', "error", '
Your login was unsuccessful
', 2000, 'trustedHtml');

		};
	}])
    /******************************************************************************
    //////////////////////////////////////////// HomeCtrl
    ******************************************************************************/
    .controller('LogoutCtrl', ['$location', 'AppstateSrv', function($location, AppstateSrv) {
        //
        AppstateSrv.setParam('loggedin', false);
        AppstateSrv.setParam('sid', null);
        AppstateSrv.setParam('advertisers', null);
        AppstateSrv.setParam('superadmin', false);
        AppstateSrv.setParam('admin', false);
        $location.path("login");
        //return false;
    }])
	/******************************************************************************
  	//////////////////////////////////////////// UsersCtrl
  	******************************************************************************/
	.controller('UsersCtrl', ['$scope', 'toaster', 'UsersSrv', 'AppstateSrv', function($scope, toaster, UsersSrv, AppstateSrv) {
		//
		if(!AppstateSrv.getParam("loggedin")){
			return false;
		};

		$scope.advertisers = AppstateSrv.getParam("advertisers");

		$scope.user = {
			email : "",
			user_admin : false,
			data : {}
		};

		$scope.useredit = {};

		$scope.users = [];

        $scope.addMode = true;

        var prepareEditusers = function() {

        	_.each($scope.users, function(user){

                var userdata = user.data;

        		$scope.useredit[user.id] = {
        			data : {},
        			email : user.email,
        			user_admin : user.user_admin
        		};

        		angular.forEach($scope.advertisers, function(advertiserObj){
        			$scope.useredit[user.id].data[advertiserObj.advertiser.advertiserID] = {};

        			_.each(advertiserObj.markets, function(market){

                        var marketId = market.marketID,
                            advertiserID = advertiserObj.advertiser.advertiserID;//$.parseJSON(user.data);

        				if($scope.userHasMarket(user, marketId, advertiserID)){
                            $scope.useredit[user.id].data[advertiserID][marketId] = true;
        				} else {
        					$scope.useredit[user.id].data[advertiserID][marketId] = false;
        				};

        			});
        		});
        	});
        };

        var prepareAdduser = function() {

    		angular.forEach($scope.advertisers, function(advertiserObj){

    			$scope.user.data[advertiserObj.advertiser.advertiserID] = {};

    			_.each(advertiserObj.markets, function(market){

    				var marketId = market.marketID;

    				$scope.user.data[advertiserObj.advertiser.advertiserID][marketId] = false;
    			});
    		});
    	};

    	var prepareUserexport = function(user, model){

        	var exportuser = {},
				permissionscopy = {};
            //console.log($scope.user.data)
            //return false;
			if(model) {
				//
				console.log(model)
				for (var userID in model) {
	        		if(userID == user.id) {
	        			exportuser = {
	        				id : userID,
	        				data : model[userID].data,
	        				email : model[userID].email,
	        				user_admin : model[userID].user_admin ? "1" : "0"
	        			};

	        			exportuser.id = user.id;

	        			permissionscopy[userID] = _.clone(model[userID].data);
	        		};
	        	};
			} else {
				exportuser = user;
				permissionscopy = _.clone(user.data);
                //

                //console.log(exportuser)
            //return false;
			};

        	for(var advID in exportuser.data){

        		var hasAllMarkets = true, apimarkets = [];

                for(var marketid in exportuser.data[advID]){
                    if(exportuser.data[advID][marketid] == true){
                        apimarkets.push(marketid);
                    }
                };

        		angular.forEach($scope.advertisers, function(advertiserObj){

        			if(advertiserObj.advertiser.advertiserID == advID) {
        				//
        				var allmarkets = advertiserObj.markets;

        				angular.forEach(allmarkets, function(market){

        					if(exportuser.data[advID][market.marketID] == false){
        						hasAllMarkets = false;
        					};
        				});
        			};
        		});

        		if(hasAllMarkets){
    				//
           			exportuser.data[advID] = true;

        			if(model){
        				$scope.useredit[exportuser.id].data = permissionscopy[exportuser.id];
        			} else {
        				//
        			};
        		} else if(apimarkets.length){
        			exportuser.data[advID] = apimarkets;

                    if(model){
                        $scope.useredit[exportuser.id].data = permissionscopy[exportuser.id];
                    } else {
                        //
                    };
        		};
        	};
            //console.log(exportuser)
        	return exportuser;
        };

        var validateEmail = function(email) {
		    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
		    return re.test(email);
		}

        var getUsersSuccessCallback = function (data, status) {
            $scope.users = data;

            prepareEditusers();
        };

        var successCallback = function (data, status, headers, config) {

            toaster.pop('success', "Success", "
The operation was successful
", 2000, 'trustedHtml');
            prepareAdduser();
            return UsersSrv.getUsers().success(getUsersSuccessCallback).error(errorCallback);
        };

        var successPostCallback = function (data, status, headers, config) {
        	//
            successCallback(data, status, headers, config).success(function () {
                $scope.toggleAddMode();
                $scope.user = {};
            });
        };

        var errorCallback = function (data, status, headers, config) {
            //notificationFactory.error(data.ExceptionMessage);
            //
            //toaster.pop('error', "Error", "
There was an error, please try again
", 5000, 'trustedHtml');
        };

        $scope.addUser = function () {
        	//
        	var apiUser;

        	if(!validateEmail($scope.user.email)){
        		toaster.pop('error', "Error", "
Please enter a valid email address
", 2000, 'trustedHtml');
        		return false;
        	};
            //console.log($scope.user)
            //return false;
        	apiUser = prepareUserexport($scope.user);

            //console.log(apiUser)

            UsersSrv.addUser(apiUser).success(successPostCallback).error(errorCallback);
           	//_.delay(function(){prepareAdduser()}, 1000);
        };

        $scope.deleteUser = function (user) {
        	//
            UsersSrv.deleteUser(user).success(successCallback).error(errorCallback);
        };

        $scope.updateUser = function (user) {
        	//
        	var apiUser;

        	if(!validateEmail($scope.useredit[user.id].email)){
        		toaster.pop('error', "Error", "
Please enter a valid email address
", 2000, 'trustedHtml');
        		return false;
        	};

        	apiUser = prepareUserexport(user, $scope.useredit);

            //console.log("PREPARED USER!!!")
            //console.log(apiUser)

            UsersSrv.updateUser(apiUser).success(successCallback).error(errorCallback);
        };

        $scope.userHasMarket = function(user, checkMarket, parentAdvertiser) {

        	var userPermission, hasMarket = false;

            if(user.data === true || user.data === "true") {
                hasMarket = true;
            } else {
                for(var advertiser in user.data){

                    if(advertiser == parentAdvertiser){
                        if(user.data[advertiser] === true || user.data[advertiser] === "true") {
                            hasMarket = true;
                        } else if(user.data[advertiser]) {
                            angular.forEach(user.data[advertiser], function(market){

                                if(market == checkMarket){
                                    hasMarket = true;
                                };
                            });
                        };
                    };
                };
            };

        	return hasMarket;
        };

        $scope.isSuperadmin = function() {
            //
            return AppstateSrv.getParam("superadmin");
        };

        $scope.isAdmin = function() {
            //
            return AppstateSrv.getParam("admin");
        };

        $scope.toggleAddMode = function () {
            $scope.addMode = !$scope.addMode;
        };

        $scope.toggleEditMode = function (user) {

            user.editMode = !user.editMode;
        };

        UsersSrv.getUsers().success(getUsersSuccessCallback).error(errorCallback);

        prepareAdduser();
	}]);<commit_msg>- reading user permissions from logon data<commit_after>'use strict';

/* Controllers */

angular.module('atpcms.controllers', [])
	/******************************************************************************
  	//////////////////////////////////////////// NavCtrl
  	******************************************************************************/
	.controller('NavCtrl', ['$scope', '$rootScope', '$location', 'AppstateSrv', function($scope, $rootScope, $location, AppstateSrv) {
	//
		//$scope.mylocation = $location.path();

		$scope.getscreen = function(screen) {
			$location.url('/' + screen);
		};

		$scope.chekLocation = function(loc) {
		  return $location.path() == loc;
		};

		$scope.checkLoggedin = function() {
		  return AppstateSrv.getParam("loggedin");
		};

		var authCheck = function (event) {
		    if(!AppstateSrv.getParam("loggedin")) {
		        //
		        $location.path('/login');
		    };
		};

		authCheck(null);

		$rootScope.$on("$routeChangeStart", authCheck);
	}])
	/******************************************************************************
  	//////////////////////////////////////////// HomeCtrl
  	******************************************************************************/
	.controller('HomeCtrl', ['$scope', 'AppstateSrv', 'AdvertisersSrv', 'MarketsSrv',function($scope, AppstateSrv, AdvertisersSrv, MarketsSrv) {
		//
		if(!AppstateSrv.getParam("loggedin")){
			return false;
		};

		if(AppstateSrv.getParam("advertisers") === null) {
			//
			AdvertisersSrv
			.getAdvertisers()
			.success(function(advData){

				var apiAdvertisers = [];

				angular.forEach(advData, function(advertiser){
					//
                    //
                    MarketsSrv.getMarkets(advertiser.advertiserID)
                    .success(function(mktData){
                        //
                        if(AppstateSrv.getParam('superadmin') || _.indexOf(AppstateSrv.getParam('advspermitted'), advertiser.advertiserID) !== -1){
                            //console.log("ADDIT")
                            apiAdvertisers.push({advertiser : advertiser, markets : mktData});
                            AppstateSrv.setParam("advertisers", apiAdvertisers);
                        } else {
                            //
                            //console.log("SKIpIT")
                        }
                    })
                    .error(function(){
                        // die silently
                    })

				});
			})
			.error(function(){
				//
				alert("error fetching advertisers");
			});
		}
	}])
	/******************************************************************************
  	//////////////////////////////////////////// HomeCtrl
  	******************************************************************************/
	.controller('LoginCtrl', [
		'$scope', '$location', 'LoginSrv', 'AppstateSrv', 'toaster',
		function($scope, $location, LoginSrv, AppstateSrv, toaster) {
		//
		$scope.login = {
			u : "",
			p : ""
		};

		$scope.dologin = function() {

            var user = $scope.login.u;

            $scope.login.u = user;

			LoginSrv.getLogin($scope.login).success(onLoginSuccess).error(onLoginError);
		};

		var onLoginSuccess = function(data) {
			//
			toaster.pop('success', "success", '
Your login was successful
', 2000, 'trustedHtml');

            AppstateSrv.setParam('advspermitted', data.advertisers);
			AppstateSrv.setParam('loggedin', true);
			AppstateSrv.setParam('sid', data.sid);
            AppstateSrv.setParam('admin',  data.admin === "1" ? true : false);
            AppstateSrv.setParam('superadmin', data.super_admin === "1" ? true : false);
            //console.log("SA " + AppstateSrv.getParam('superadmin'))
            //console.log("AD " + AppstateSrv.getParam('admin'))
			$location.path("home");
		};

		var onLoginError = function() {
			//
			toaster.pop('error', "error", '
Your login was unsuccessful
', 2000, 'trustedHtml');

		};
	}])
    /******************************************************************************
    //////////////////////////////////////////// HomeCtrl
    ******************************************************************************/
    .controller('LogoutCtrl', ['$location', 'AppstateSrv', function($location, AppstateSrv) {
        //
        AppstateSrv.setParam('loggedin', false);
        AppstateSrv.setParam('sid', null);
        AppstateSrv.setParam('advertisers', null);
        AppstateSrv.setParam('superadmin', false);
        AppstateSrv.setParam('admin', false);
        $location.path("login");
        //return false;
    }])
	/******************************************************************************
  	//////////////////////////////////////////// UsersCtrl
  	******************************************************************************/
	.controller('UsersCtrl', ['$scope', 'toaster', 'UsersSrv', 'AppstateSrv', function($scope, toaster, UsersSrv, AppstateSrv) {
		//
		if(!AppstateSrv.getParam("loggedin")){
			return false;
		};

		$scope.advertisers = AppstateSrv.getParam("advertisers");

		$scope.user = {
			email : "",
			user_admin : false,
			data : {}
		};

		$scope.useredit = {};

		$scope.users = [];

        $scope.addMode = true;

        var prepareEditusers = function() {

        	_.each($scope.users, function(user){

                var userdata = user.data;

        		$scope.useredit[user.id] = {
        			data : {},
        			email : user.email,
        			user_admin : user.user_admin
        		};

        		angular.forEach($scope.advertisers, function(advertiserObj){
        			$scope.useredit[user.id].data[advertiserObj.advertiser.advertiserID] = {};

        			_.each(advertiserObj.markets, function(market){

                        var marketId = market.marketID,
                            advertiserID = advertiserObj.advertiser.advertiserID;//$.parseJSON(user.data);

        				if($scope.userHasMarket(user, marketId, advertiserID)){
                            $scope.useredit[user.id].data[advertiserID][marketId] = true;
        				} else {
        					$scope.useredit[user.id].data[advertiserID][marketId] = false;
        				};

        			});
        		});
        	});
        };

        var prepareAdduser = function() {

    		angular.forEach($scope.advertisers, function(advertiserObj){

    			$scope.user.data[advertiserObj.advertiser.advertiserID] = {};

    			_.each(advertiserObj.markets, function(market){

    				var marketId = market.marketID;

    				$scope.user.data[advertiserObj.advertiser.advertiserID][marketId] = false;
    			});
    		});
    	};

    	var prepareUserexport = function(user, model){

        	var exportuser = {},
				permissionscopy = {};
            //console.log($scope.user.data)
            //return false;
			if(model) {
				//
				console.log(model)
				for (var userID in model) {
	        		if(userID == user.id) {
	        			exportuser = {
	        				id : userID,
	        				data : model[userID].data,
	        				email : model[userID].email,
	        				user_admin : model[userID].user_admin ? "1" : "0"
	        			};

	        			exportuser.id = user.id;

	        			permissionscopy[userID] = _.clone(model[userID].data);
	        		};
	        	};
			} else {
				exportuser = user;
				permissionscopy = _.clone(user.data);
                //

                //console.log(exportuser)
            //return false;
			};

        	for(var advID in exportuser.data){

        		var hasAllMarkets = true, apimarkets = [];

                for(var marketid in exportuser.data[advID]){
                    if(exportuser.data[advID][marketid] == true){
                        apimarkets.push(marketid);
                    }
                };

        		angular.forEach($scope.advertisers, function(advertiserObj){

        			if(advertiserObj.advertiser.advertiserID == advID) {
        				//
        				var allmarkets = advertiserObj.markets;

        				angular.forEach(allmarkets, function(market){

        					if(exportuser.data[advID][market.marketID] == false){
        						hasAllMarkets = false;
        					};
        				});
        			};
        		});

        		if(hasAllMarkets){
    				//
           			exportuser.data[advID] = true;

        			if(model){
        				$scope.useredit[exportuser.id].data = permissionscopy[exportuser.id];
        			} else {
        				//
        			};
        		} else if(apimarkets.length){
        			exportuser.data[advID] = apimarkets;

                    if(model){
                        $scope.useredit[exportuser.id].data = permissionscopy[exportuser.id];
                    } else {
                        //
                    };
        		};
        	};
            //console.log(exportuser)
        	return exportuser;
        };

        var validateEmail = function(email) {
		    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
		    return re.test(email);
		}

        var getUsersSuccessCallback = function (data, status) {
            $scope.users = data;

            prepareEditusers();
        };

        var successCallback = function (data, status, headers, config) {

            toaster.pop('success', "Success", "
The operation was successful
", 2000, 'trustedHtml');
            prepareAdduser();
            return UsersSrv.getUsers().success(getUsersSuccessCallback).error(errorCallback);
        };

        var successPostCallback = function (data, status, headers, config) {
        	//
            successCallback(data, status, headers, config).success(function () {
                $scope.toggleAddMode();
                $scope.user = {};
            });
        };

        var errorCallback = function (data, status, headers, config) {
            //notificationFactory.error(data.ExceptionMessage);
            //
            //toaster.pop('error', "Error", "
There was an error, please try again
", 5000, 'trustedHtml');
        };

        $scope.addUser = function () {
        	//
        	var apiUser;

        	if(!validateEmail($scope.user.email)){
        		toaster.pop('error', "Error", "
Please enter a valid email address
", 2000, 'trustedHtml');
        		return false;
        	};
            //console.log($scope.user)
            //return false;
        	apiUser = prepareUserexport($scope.user);

            //console.log(apiUser)

            UsersSrv.addUser(apiUser).success(successPostCallback).error(errorCallback);
           	//_.delay(function(){prepareAdduser()}, 1000);
        };

        $scope.deleteUser = function (user) {
        	//
            UsersSrv.deleteUser(user).success(successCallback).error(errorCallback);
        };

        $scope.updateUser = function (user) {
        	//
        	var apiUser;

        	if(!validateEmail($scope.useredit[user.id].email)){
        		toaster.pop('error', "Error", "
Please enter a valid email address
", 2000, 'trustedHtml');
        		return false;
        	};

        	apiUser = prepareUserexport(user, $scope.useredit);

            //console.log("PREPARED USER!!!")
            //console.log(apiUser)

            UsersSrv.updateUser(apiUser).success(successCallback).error(errorCallback);
        };

        $scope.userHasMarket = function(user, checkMarket, parentAdvertiser) {

        	var userPermission, hasMarket = false;

            if(user.data === true || user.data === "true") {
                hasMarket = true;
            } else {
                for(var advertiser in user.data){

                    if(advertiser == parentAdvertiser){
                        if(user.data[advertiser] === true || user.data[advertiser] === "true") {
                            hasMarket = true;
                        } else if(user.data[advertiser]) {
                            angular.forEach(user.data[advertiser], function(market){

                                if(market == checkMarket){
                                    hasMarket = true;
                                };
                            });
                        };
                    };
                };
            };

        	return hasMarket;
        };

        $scope.isSuperadmin = function() {
            //
            return AppstateSrv.getParam("superadmin");
        };

        $scope.isAdmin = function() {
            //
            return AppstateSrv.getParam("admin");
        };

        $scope.toggleAddMode = function () {
            $scope.addMode = !$scope.addMode;
        };

        $scope.toggleEditMode = function (user) {

            user.editMode = !user.editMode;
        };

        UsersSrv.getUsers().success(getUsersSuccessCallback).error(errorCallback);

        prepareAdduser();
	}]);<|endoftext|>


<commit_before>'use strict';

/* Controllers */

angular.module('myApp.controllers', [])
  .controller('MyCtrl1', ['$scope', function($scope) {

  }])
  .controller('MyCtrl2', ['$scope', function($scope) {

  }]);
<commit_msg>Added driversController<commit_after>'use strict';

/* Controllers */

// angular.module('myApp.controllers', [])
//   .controller('MyCtrl1', ['$scope', function($scope) {

//   }])
//   .controller('MyCtrl2', ['$scope', function($scope) {

//   }]);

angular.module('F1FeederApp.controllers', []).controller('driversController', function($scope) {
	$scope.driversList = [
		{
		Driver: {
			givenName: 'Sebastian',
			familyName: 'Vettel'
		},
		points: 322,
		nationality: "German",
		Constructors: [
			{name: "Red Bull"}
			]
		},
		{
			Driver: {
				givenName: 'Fernando',
				familyNameP 'Alonso'
			},
		points: 207,
		nationality: "Spanish",
		Constructors: [
			{name: "Ferrari"}
			]
		}
	];
});
<|endoftext|>


<commit_before>/*!
 * selectbox
 * Date: 2014-01-10
 * https://github.com/aui/popupjs
 * (c) 2009-2013 TangBin, http://www.planeArt.cn
 *
 * This is licensed under the GNU LGPL, version 2.1 or later.
 * For details, see: http://www.gnu.org/licenses/lgpl-2.1.html
 */

'use strict';

var $ = require('jquery'),
  Popup = require('./popup'),
  isIE6 = !('minWidth' in document.createElement('div').style);

/**
 * 下来框类
 * @param select
 * @param options
 * @constructor
 */
function Selectbox(select, options){
  var that = this,
    selectboxHtml;

  $.extend(this, options || {});

  select = this.select = $(select);

  if (select.is('[multiple]')) {
    return;
  }

  if (select.data('selectbox')) {
    // 删除上一次的 selectbox 以重新更新
    select.data('selectbox').remove();
  }

  selectboxHtml = this._tpl(this.selectboxHtml, $.extend({
    textContent: that._getOption().html() || ''
  }, select.data()));

  this._selectbox = $(selectboxHtml);
  this._value = this._selectbox.find('[data-value]');

  // selectbox 的事件绑定
  if (this.isShowDropdown && !select.attr('disabled')) {
    this._globalKeydown = $.proxy(this._globalKeydown, this);

    this._selectbox
      .on(this._clickType + ' focus blur', function (event){
        that[that._clickType === event.type ? 'click' : event.type]();
      });
  }

  this._selectbox
    .css({
      width: select.outerWidth() + 'px'
    });

  // 克隆原生 select 的基本 UI 事件
  select
    .on('focus blur', function (event){
      that[event.type]();
      event.preventDefault();
    })
    .on('change', function (){
      var text = that._getOption().html();
      that._value.html(text);
    });

  // 隐藏原生 select
  // 盲人仍然可以通过 tab 键访问到原生控件
  // iPad 与 iPhone 等设备点击仍然能够使用滚动操作 select
  select.css({
    opacity: 0,
    position: 'absolute',
    left: isIE6 ? '-9999px' : 'auto',
    right: 'auto',
    top: 'auto',
    bottom: 'auto',
    zIndex: this.isShowDropdown ? -1 : 1
  }).data('selectbox', this);

  // 代替原生 select
  select.after(this._selectbox);
}

// 继承 Popup 类
var popup = function (){};
popup.prototype = Popup.prototype;
Selectbox.prototype = new popup();

// 添加原型方法
$.extend(Selectbox.prototype, {
  selectboxHtml: ''
  + '
'
  + '
{{textContent}}
'
  + ''
  + '
',
  dropdownHtml: '
{{options}}
',
  optgroupHtml: '
{{label}}
',
  optionHtml: '
{{textContent}}
',
  selectedClass: 'ui-selectbox-selected',
  disabledClass: 'ui-selectbox-disabled',
  focusClass: 'ui-selectbox-focus',
  openClass: 'ui-selectbox-open',
  // 移动端不使用模拟下拉层
  isShowDropdown: !('createTouch' in document),
  selectedIndex: 0,
  value: '',
  /**
   * 关闭
   */
  close: function (){
    if (this._popup) {
      this._popup.close().remove();
      this.change();
    }
  },
  /**
   * 显示
   * @returns {boolean}
   */
  show: function (){
    var that = this,
      select = this.select,
      selectbox = that._selectbox;

    if (!select[0].length) {
      return false;
    }

    var MARGIN = 20,
      selectHeight = select.outerHeight(),
      topHeight = select.offset().top - $(document).scrollTop(),
      bottomHeight = $(window).height() - topHeight - selectHeight,
      maxHeight = Math.max(topHeight, bottomHeight) - MARGIN,
      popup = this._popup = new Popup();

    popup.node.innerHTML = this._dropdownHtml();
    this._dropdown = $(popup.node);

    $(popup.backdrop)
      .css('opacity', 0)
      .on(this._clickType, $.proxy(this.close, this));

    var children = that._dropdown.children();

    children.css({
      minWidth: selectbox.innerWidth(),
      maxHeight: maxHeight,
      overflowY: 'auto',
      overflowX: 'hidden'
    });

    this._dropdown
      .on(this._clickType, '[data-option]', function (event){
        var index = $(this).data('option');
        that.selected(index);
        that.close();

        event.preventDefault();
      });

    popup.onshow = function (){
      $(document).on('keydown', that._globalKeydown);
      selectbox.addClass(that.openClass);
      that.selectedIndex = select[0].selectedIndex;
      that.selected(that.selectedIndex);
    };

    popup.onremove = function (){
      $(document).off('keydown', that._globalKeydown);
      selectbox.removeClass(that.openClass);
    };

    // 记录展开前的 value
    this._oldValue = this.select.val();

    popup.showModal(selectbox[0]);

    if (isIE6) {
      children.css({
        width: Math.max(selectbox.innerWidth(), children.outerWidth()),
        height: Math.min(maxHeight, children.outerHeight())
      });

      popup.reset();
    }
  },
  /**
   * 设置激活项
   * @param index
   * @returns {boolean}
   */
  selected: function (index){
    // 检查当前项是否被禁用
    if (this._getOption(index).attr('disabled')) {
      return false;
    }

    var dropdown = this._dropdown,
      option = this._dropdown.find('[data-option=' + index + ']'),
      value = this.select[0].options[index].value,
      oldIndex = this.select[0].selectedIndex,
      selectedClass = this.selectedClass;

    // 更新选中状态样式
    dropdown.find('[data-option=' + oldIndex + ']').removeClass(selectedClass);
    option.addClass(selectedClass);
    option.focus();

    // 更新模拟控件的显示值
    this._value.html(this._getOption(index).html());
    // 更新 Selectbox 对象属性
    this.value = value;
    this.selectedIndex = index;

    // 同步数据到原生 select
    this.select[0].selectedIndex = this.selectedIndex;
    this.select[0].value = this.value;

    return true;
  },
  /**
   * 改变事件
   */
  change: function (){
    if (this._oldValue !== this.value) {
      this.select.triggerHandler('change');
    }
  },
  /**
   * 单击事件
   */
  click: function (){
    this.select.focus();

    if (this._popup && this._popup.open) {
      this.close();
    } else {
      this.show();
    }
  },
  /**
   * 获得焦点事件
   */
  focus: function (){
    this._selectbox.addClass(this.focusClass);
  },
  /**
   * 失去焦点事件
   */
  blur: function (){
    this._selectbox.removeClass(this.focusClass);
  },
  /**
   * 移除
   */
  remove: function (){
    this.close();
    this._selectbox.remove();
  },
  /**
   * 单击类型
   */
  _clickType: 'onmousedown' in document ? 'mousedown' : 'touchstart',
  /**
   * 获取原生 select 的 option jquery 对象
   * @param index
   * @returns {*}
   * @private
   */
  _getOption: function (index){
    index = index === undefined ? this.select[0].selectedIndex : index;
    return this.select.find('option').eq(index);
  },
  /**
   * 简单模板替换
   * @param tpl
   * @param data
   * @returns {XML|string|void}
   * @private
   */
  _tpl: function (tpl, data){
    return tpl.replace(/{{(.*?)}}/g, function ($1, $2){
      return data[$2];
    });
  },
  /**
   * 获取下拉框的 HTML
   * @returns {XML|string|void}
   * @private
   */
  _dropdownHtml: function (){
    var options = '',
      that = this,
      select = this.select,
      selectData = select.data(),
      index = 0,
      getOptionsData = function ($options){
        $options.each(function (){
          var $this = $(this),
            className = '';

          if (this.selected) {
            className = that.selectedClass;
          } else {
            className = this.disabled ? that.disabledClass : '';
          }

          options += that._tpl(that.optionHtml, $.extend({
            value: $this.val(),
            // 如果内容类似： "<s>选项</s>" 使用 .text() 会导致 XSS
            // 另外，原生 option 不支持 html 文本
            textContent: $this.html(),
            index: index,
            className: className
          }, $this.data(), selectData));

          index++;
        });
      };

    if (select.find('optgroup').length) {
      select.find('optgroup').each(function (index){
        options += that._tpl(that.optgroupHtml, $.extend({
          index: index,
          label: this.label
        }, $(this).data(), selectData));

        getOptionsData($(this).find('option'));
      });
    } else {
      getOptionsData(select.find('option'));
    }

    return this._tpl(this.dropdownHtml, {
      options: options
    });
  },
  /**
   * 上下移动
   * @param n
   * @private
   */
  _move: function (n){
    var min = 0;
    var max = this.select[0].length - 1;
    var index = this.select[0].selectedIndex + n;

    if (index >= min && index <= max) {
      // 跳过带有 disabled 属性的选项
      if (!this.selected(index)) {
        this._move(n + n);
      }
    }
  },
  /**
   * 全局键盘监听
   * @param event
   * @private
   */
  _globalKeydown: function (event){
    var p;

    switch (event.keyCode) {
      // backspace
      case 8:
        p = true;
        break;
      // tab
      case 9:
      // esc
      case 27:
      // enter
      case 13:
        this.close();
        p = true;
        break;
      // up
      case 38:
        this._move(-1);
        p = true;
        break;
      // down
      case 40:
        this._move(1);
        p = true;
        break;
    }

    if (p) {
      event.preventDefault();
    }
  }
});

module.exports = function (elem, options){
  // 注意：不要返回 Selectbox 更多接口给外部，只保持装饰用途
  // 保证模拟的下拉是原生控件的子集，这样可以随时在项目中撤销装饰
  if (elem.type === 'select') {
    new Selectbox(elem, options);
  } else {
    $(elem).each(function (){
      new Selectbox(this, options);
    });
  }
};
<commit_msg>add lib file<commit_after>/*!
 * selectbox
 * Date: 2014-01-10
 * https://github.com/aui/popupjs
 * (c) 2009-2013 TangBin, http://www.planeArt.cn
 *
 * This is licensed under the GNU LGPL, version 2.1 or later.
 * For details, see: http://www.gnu.org/licenses/lgpl-2.1.html
 */

'use strict';

var $ = require('jquery'),
  Popup = require('./popup'),
  isIE6 = !('minWidth' in document.createElement('div').style);

/**
 * 下来框类
 * @param select
 * @param options
 * @constructor
 */
function Selectbox(select, options){
  var that = this,
    selectboxHtml;

  $.extend(this, options || {});

  select = this.select = $(select);

  if (select.is('[multiple]')) {
    return;
  }

  if (select.data('selectbox')) {
    // 删除上一次的 selectbox 以重新更新
    select.data('selectbox').remove();
  }

  selectboxHtml = this._tpl(this.selectboxHtml, $.extend({
    textContent: that._getOption().html() || ''
  }, select.data()));

  this._selectbox = $(selectboxHtml);
  this._value = this._selectbox.find('[data-value]');

  // selectbox 的事件绑定
  if (this.isShowDropdown && !select.attr('disabled')) {
    this._globalKeydown = $.proxy(this._globalKeydown, this);

    this._selectbox
      .on(this._clickType + ' focus blur', function (event){
        that[that._clickType === event.type ? 'click' : event.type]();
      });
  }

  this._selectbox
    .css({
      width: select.outerWidth()
    });

  // 克隆原生 select 的基本 UI 事件
  select
    .on('focus blur', function (event){
      that[event.type]();
      event.preventDefault();
    })
    .on('change', function (){
      var text = that._getOption().html();
      that._value.html(text);
    });

  // 隐藏原生 select
  // 盲人仍然可以通过 tab 键访问到原生控件
  // iPad 与 iPhone 等设备点击仍然能够使用滚动操作 select
  select.css({
    opacity: 0,
    position: 'absolute',
    left: isIE6 ? '-9999px' : 'auto',
    right: 'auto',
    top: 'auto',
    bottom: 'auto',
    zIndex: this.isShowDropdown ? -1 : 1
  }).data('selectbox', this);

  // 代替原生 select
  select.after(this._selectbox);
}

// 继承 Popup 类
var popup = function (){};
popup.prototype = Popup.prototype;
Selectbox.prototype = new popup();

// 添加原型方法
$.extend(Selectbox.prototype, {
  selectboxHtml: ''
  + '
'
  + '
{{textContent}}
'
  + ''
  + '
',
  dropdownHtml: '
{{options}}
',
  optgroupHtml: '
{{label}}
',
  optionHtml: '
{{textContent}}
',
  selectedClass: 'ui-selectbox-selected',
  disabledClass: 'ui-selectbox-disabled',
  focusClass: 'ui-selectbox-focus',
  openClass: 'ui-selectbox-open',
  // 移动端不使用模拟下拉层
  isShowDropdown: !('createTouch' in document),
  selectedIndex: 0,
  value: '',
  /**
   * 关闭
   */
  close: function (){
    if (this._popup) {
      this._popup.close().remove();
      this.change();
    }
  },
  /**
   * 显示
   * @returns {boolean}
   */
  show: function (){
    var that = this,
      select = this.select,
      selectbox = that._selectbox;

    if (!select[0].length) {
      return false;
    }

    var MARGIN = 20,
      selectHeight = select.outerHeight(),
      topHeight = select.offset().top - $(document).scrollTop(),
      bottomHeight = $(window).height() - topHeight - selectHeight,
      maxHeight = Math.max(topHeight, bottomHeight) - MARGIN,
      popup = this._popup = new Popup();

    popup.node.innerHTML = this._dropdownHtml();
    this._dropdown = $(popup.node);

    $(popup.backdrop)
      .css('opacity', 0)
      .on(this._clickType, $.proxy(this.close, this));

    var children = that._dropdown.children();

    children.css({
      minWidth: selectbox.innerWidth(),
      maxHeight: maxHeight,
      overflowY: 'auto',
      overflowX: 'hidden'
    });

    this._dropdown
      .on(this._clickType, '[data-option]', function (event){
        var index = $(this).data('option');
        that.selected(index);
        that.close();

        event.preventDefault();
      });

    popup.onshow = function (){
      $(document).on('keydown', that._globalKeydown);
      selectbox.addClass(that.openClass);
      that.selectedIndex = select[0].selectedIndex;
      that.selected(that.selectedIndex);
    };

    popup.onremove = function (){
      $(document).off('keydown', that._globalKeydown);
      selectbox.removeClass(that.openClass);
    };

    // 记录展开前的 value
    this._oldValue = this.select.val();

    popup.showModal(selectbox[0]);

    if (isIE6) {
      children.css({
        width: Math.max(selectbox.innerWidth(), children.outerWidth()),
        height: Math.min(maxHeight, children.outerHeight())
      });

      popup.reset();
    }
  },
  /**
   * 设置激活项
   * @param index
   * @returns {boolean}
   */
  selected: function (index){
    // 检查当前项是否被禁用
    if (this._getOption(index).attr('disabled')) {
      return false;
    }

    var dropdown = this._dropdown,
      option = this._dropdown.find('[data-option=' + index + ']'),
      value = this.select[0].options[index].value,
      oldIndex = this.select[0].selectedIndex,
      selectedClass = this.selectedClass;

    // 更新选中状态样式
    dropdown.find('[data-option=' + oldIndex + ']').removeClass(selectedClass);
    option.addClass(selectedClass);
    option.focus();

    // 更新模拟控件的显示值
    this._value.html(this._getOption(index).html());
    // 更新 Selectbox 对象属性
    this.value = value;
    this.selectedIndex = index;

    // 同步数据到原生 select
    this.select[0].selectedIndex = this.selectedIndex;
    this.select[0].value = this.value;

    return true;
  },
  /**
   * 改变事件
   */
  change: function (){
    if (this._oldValue !== this.value) {
      this.select.triggerHandler('change');
    }
  },
  /**
   * 单击事件
   */
  click: function (){
    this.select.focus();

    if (this._popup && this._popup.open) {
      this.close();
    } else {
      this.show();
    }
  },
  /**
   * 获得焦点事件
   */
  focus: function (){
    this._selectbox.addClass(this.focusClass);
  },
  /**
   * 失去焦点事件
   */
  blur: function (){
    this._selectbox.removeClass(this.focusClass);
  },
  /**
   * 移除
   */
  remove: function (){
    this.close();
    this._selectbox.remove();
  },
  /**
   * 单击类型
   */
  _clickType: 'onmousedown' in document ? 'mousedown' : 'touchstart',
  /**
   * 获取原生 select 的 option jquery 对象
   * @param index
   * @returns {*}
   * @private
   */
  _getOption: function (index){
    index = index === undefined ? this.select[0].selectedIndex : index;
    return this.select.find('option').eq(index);
  },
  /**
   * 简单模板替换
   * @param tpl
   * @param data
   * @returns {XML|string|void}
   * @private
   */
  _tpl: function (tpl, data){
    return tpl.replace(/{{(.*?)}}/g, function ($1, $2){
      return data[$2];
    });
  },
  /**
   * 获取下拉框的 HTML
   * @returns {XML|string|void}
   * @private
   */
  _dropdownHtml: function (){
    var options = '',
      that = this,
      select = this.select,
      selectData = select.data(),
      index = 0,
      getOptionsData = function ($options){
        $options.each(function (){
          var $this = $(this),
            className = '';

          if (this.selected) {
            className = that.selectedClass;
          } else {
            className = this.disabled ? that.disabledClass : '';
          }

          options += that._tpl(that.optionHtml, $.extend({
            value: $this.val(),
            // 如果内容类似： "<s>选项</s>" 使用 .text() 会导致 XSS
            // 另外，原生 option 不支持 html 文本
            textContent: $this.html(),
            index: index,
            className: className
          }, $this.data(), selectData));

          index++;
        });
      };

    if (select.find('optgroup').length) {
      select.find('optgroup').each(function (index){
        options += that._tpl(that.optgroupHtml, $.extend({
          index: index,
          label: this.label
        }, $(this).data(), selectData));

        getOptionsData($(this).find('option'));
      });
    } else {
      getOptionsData(select.find('option'));
    }

    return this._tpl(this.dropdownHtml, {
      options: options
    });
  },
  /**
   * 上下移动
   * @param n
   * @private
   */
  _move: function (n){
    var min = 0;
    var max = this.select[0].length - 1;
    var index = this.select[0].selectedIndex + n;

    if (index >= min && index <= max) {
      // 跳过带有 disabled 属性的选项
      if (!this.selected(index)) {
        this._move(n + n);
      }
    }
  },
  /**
   * 全局键盘监听
   * @param event
   * @private
   */
  _globalKeydown: function (event){
    var p;

    switch (event.keyCode) {
      // backspace
      case 8:
        p = true;
        break;
      // tab
      case 9:
      // esc
      case 27:
      // enter
      case 13:
        this.close();
        p = true;
        break;
      // up
      case 38:
        this._move(-1);
        p = true;
        break;
      // down
      case 40:
        this._move(1);
        p = true;
        break;
    }

    if (p) {
      event.preventDefault();
    }
  }
});

module.exports = function (elem, options){
  // 注意：不要返回 Selectbox 更多接口给外部，只保持装饰用途
  // 保证模拟的下拉是原生控件的子集，这样可以随时在项目中撤销装饰
  if (elem.type === 'select') {
    new Selectbox(elem, options);
  } else {
    $(elem).each(function (){
      new Selectbox(this, options);
    });
  }
};
<|endoftext|>


<commit_before>/*global
    angular
*/

(function(angular) {
    "use strict";

    // TaskListController
    function TaskListController($scope) {
        var self = this,
            tasks = $scope.tasks = [];

        $scope.addTask = function(task) {
            var title, duration;

            if (!task) { return; }

            title = self.getTitle(self.matchPattern, task.toString());
            duration = self.getDuration(self.matchPattern, task.toString());

            $scope.newTask = null;

            tasks.push({
                title: title,
                description: "Beschreibung des tasks....",
                duration: duration,
                done: false
            });
        };

        $scope.removeTask = function(task) {
            tasks.splice(tasks.indexOf(task), 1);
        };

        $scope.toggleTaskStatus = function(task) {
            task.done = !task.done;
        };
    }

    // inject needed services
    TaskListController.$inject = ["$scope"];

    // prototype functions
    TaskListController.prototype.matchPattern = function (str) {
        return str.match(/(\s*[0-9]+h)?(\s*[0-9]+m)?$/);
    };

    TaskListController.prototype.getTitle = function(matcher, str) {
        var matchedInput, title;

        matchedInput = matcher(str);

        title = (matchedInput[0])
            ? matchedInput.input.replace(matchedInput[0], "")
            : matchedInput.input;

        return title;
    };

    TaskListController.prototype.getDuration = function(matcher, str) {
        var matchedInput, duration, h, m;

        matchedInput = matcher(str);

        duration = 0;

        if (matchedInput[1]) {
            h = parseInt(matchedInput[1].replace(/\s|h/, ""), 10);
            duration = h * 60;
        }

        if (matchedInput[2]) {
            m = parseInt(matchedInput[2].replace(/\s|m/, ""), 10);
            duration += m;
        }

        return duration;
    };

    // add controller to controllers module
    angular.module("Controllers", []).
        controller("TaskListController", TaskListController);

}(angular));
<commit_msg>Changed default task description<commit_after>/*global
    angular
*/

(function(angular) {
    "use strict";

    // TaskListController
    function TaskListController($scope) {
        var self = this,
            tasks = $scope.tasks = [];

        $scope.addTask = function(task) {
            var title, duration;

            if (!task) { return; }

            title = self.getTitle(self.matchPattern, task.toString());
            duration = self.getDuration(self.matchPattern, task.toString());

            $scope.newTask = null;

            tasks.push({
                title: title,
                description: "...",
                duration: duration,
                done: false
            });
        };

        $scope.removeTask = function(task) {
            tasks.splice(tasks.indexOf(task), 1);
        };

        $scope.toggleTaskStatus = function(task) {
            task.done = !task.done;
        };
    }

    // inject needed services
    TaskListController.$inject = ["$scope"];

    // prototype functions
    TaskListController.prototype.matchPattern = function (str) {
        return str.match(/(\s*[0-9]+h)?(\s*[0-9]+m)?$/);
    };

    TaskListController.prototype.getTitle = function(matcher, str) {
        var matchedInput, title;

        matchedInput = matcher(str);

        title = (matchedInput[0])
            ? matchedInput.input.replace(matchedInput[0], "")
            : matchedInput.input;

        return title;
    };

    TaskListController.prototype.getDuration = function(matcher, str) {
        var matchedInput, duration, h, m;

        matchedInput = matcher(str);

        duration = 0;

        if (matchedInput[1]) {
            h = parseInt(matchedInput[1].replace(/\s|h/, ""), 10);
            duration = h * 60;
        }

        if (matchedInput[2]) {
            m = parseInt(matchedInput[2].replace(/\s|m/, ""), 10);
            duration += m;
        }

        return duration;
    };

    // add controller to controllers module
    angular.module("Controllers", []).
        controller("TaskListController", TaskListController);

}(angular));
<|endoftext|>


<commit_before>//-------------------------------------------------------------------
// Invoke Chaincode
//-------------------------------------------------------------------
var path = require('path');

module.exports = function (g_options, logger) {
	var common = require(path.join(__dirname, './common.js'))(logger);
	var invoke_cc = {};

	if (!g_options) g_options = {};
	if (!g_options.block_delay) g_options.block_delay = 10000;

	//-------------------------------------------------------------------
	// Invoke Chaincode - aka write to the ledger
	//-------------------------------------------------------------------
	/*
		options: {
					chaincode_id: "chaincode id",
					event_url: "peers event url",			<optional>
					endorsed_hook: function(error, res){},	<optional>
					ordered_hook: function(error, res){},	<optional>
					cc_function: "function_name",
					cc_args: ["argument 1"],
					peer_tls_opts: {
						pem: 'complete tls certificate',					<required if using ssl>
						common_name: 'common name used in pem certificate' 	<required if using ssl>
					}
		}
	*/
	invoke_cc.invoke_chaincode = function (obj, options, cb) {
		logger.debug('[fcw] Invoking Chaincode: ' + options.cc_function + '()');
		var eventHub;
		var channel = obj.channel;
		var client = obj.client;
		var cbCalled = false;
		var startTime = Date.now();

		// send proposal to endorser
		var request = {
			chaincodeId: options.chaincode_id,
			fcn: options.cc_function,
			args: options.cc_args,
			txId: client.newTransactionID(),
		};
		logger.debug('[fcw] Sending invoke req', request);

		// Setup EventHub
		if (options.event_url) {
			console.log('------------------ test');
			logger.debug('[fcw] listening to event url', options.event_url);
			eventHub = client.newEventHub();
			eventHub.setPeerAddr(options.event_url, {
				pem: options.peer_tls_opts.pem,
				'ssl-target-name-override': options.peer_tls_opts.common_name,		//can be null if cert matches hostname
				'grpc.http2.keepalive_time': 15
			});
			eventHub.connect();
		} else {
			logger.debug('[fcw] will not use tx event');
		}

		// Send Proposal
		channel.sendTransactionProposal(request).then(function (results) {

			// Check Response
			var request = common.check_proposal_res(results, options.endorsed_hook);
			return channel.sendTransaction(request);
		}).then(function (response) {

			// All good
			if (response.status === 'SUCCESS') {
				logger.debug('[fcw] Successfully ordered endorsement transaction.');

				// Call optional order hook
				if (options.ordered_hook) options.ordered_hook(null, request.txId.toString());

				// ------- [A] Use Event for Tx Confirmation ------- // option A
				if (options.event_url) {
					try {
						// Watchdog for no block event
						var watchdog = setTimeout(() => {
							logger.error('[fcw] Failed to receive block event within the timeout period');
							eventHub.disconnect();

							if (cb && !cbCalled) {
								cbCalled = true;
								return cb(null);						//timeout pass it back
							}
							else return;
						}, g_options.block_delay + 2000);

						// Wait for tx committed event
						eventHub.registerTxEvent(request.txId.getTransactionID(), (tx, code) => {
							var elapsed = Date.now() - startTime + 'ms';
							logger.info('[fcw] The chaincode transaction event has happened! success?:', code, elapsed);
							clearTimeout(watchdog);
							eventHub.disconnect();

							if (code !== 'VALID') {
								if (cb && !cbCalled) {
									cbCalled = true;
									return cb(common.format_error_msg('Commit code: ' + code));//pass error back
								}
								else return;
							} else {
								if (cb && !cbCalled) {
									cbCalled = true;
									return cb(null);					//all good, pass it back
								}
								else return;
							}
						});
					} catch (e) {
						logger.error('[fcw] Illusive event error: ', e);//not sure why this happens, seems rare 3/27/2017
						try {
							eventHub.disconnect();
						} catch (e) { }
						if (cb && !cbCalled) {
							cbCalled = true;
							return cb(e);								//all terrible, pass it back
						}
						else return;
					}

					// ------- [B] Wait xxxx ms for Block  ------- // option B
				} else {
					setTimeout(function () {
						if (cb) return cb(null);
						else return;
					}, g_options.block_delay + 2000);
				}
			}

			// ordering failed, No good
			else {
				if (options.ordered_hook) options.ordered_hook('failed');
				logger.error('[fcw] Failed to order the transaction. Error code: ', response);
				throw response;
			}
		}).catch(function (err) {
			logger.error('[fcw] Error in invoke catch block', typeof err, err);

			var formatted = common.format_error_msg(err);
			if (options.ordered_hook) options.ordered_hook('failed', formatted);

			if (cb) return cb(formatted, null);
			else return;
		});
	};
	return invoke_cc;
};
<commit_msg>disconnect eventhub after error<commit_after>//-------------------------------------------------------------------
// Invoke Chaincode
//-------------------------------------------------------------------
var path = require('path');

module.exports = function (g_options, logger) {
	var common = require(path.join(__dirname, './common.js'))(logger);
	var invoke_cc = {};

	if (!g_options) g_options = {};
	if (!g_options.block_delay) g_options.block_delay = 10000;

	//-------------------------------------------------------------------
	// Invoke Chaincode - aka write to the ledger
	//-------------------------------------------------------------------
	/*
		options: {
					chaincode_id: "chaincode id",
					event_url: "peers event url",			<optional>
					endorsed_hook: function(error, res){},	<optional>
					ordered_hook: function(error, res){},	<optional>
					cc_function: "function_name",
					cc_args: ["argument 1"],
					peer_tls_opts: {
						pem: 'complete tls certificate',					<required if using ssl>
						common_name: 'common name used in pem certificate' 	<required if using ssl>
					}
		}
	*/
	invoke_cc.invoke_chaincode = function (obj, options, cb) {
		logger.debug('[fcw] Invoking Chaincode: ' + options.cc_function + '()');
		var eventHub;
		var channel = obj.channel;
		var client = obj.client;
		var cbCalled = false;
		var startTime = Date.now();

		// send proposal to endorser
		var request = {
			chaincodeId: options.chaincode_id,
			fcn: options.cc_function,
			args: options.cc_args,
			txId: client.newTransactionID(),
		};
		logger.debug('[fcw] Sending invoke req', request);

		// Setup EventHub
		if (options.event_url) {
			logger.debug('[fcw] listening to event url', options.event_url);
			eventHub = client.newEventHub();
			eventHub.setPeerAddr(options.event_url, {
				pem: options.peer_tls_opts.pem,
				'ssl-target-name-override': options.peer_tls_opts.common_name,		//can be null if cert matches hostname
				'grpc.http2.keepalive_time': 15
			});
			eventHub.connect();
		} else {
			logger.debug('[fcw] will not use tx event');
		}

		// Send Proposal
		channel.sendTransactionProposal(request).then(function (results) {

			// Check Response
			var request = common.check_proposal_res(results, options.endorsed_hook);
			return channel.sendTransaction(request);
		}).then(function (response) {

			// All good
			if (response.status === 'SUCCESS') {
				logger.debug('[fcw] Successfully ordered endorsement transaction.');

				// Call optional order hook
				if (options.ordered_hook) options.ordered_hook(null, request.txId.toString());

				// ------- [A] Use Event for Tx Confirmation ------- // option A
				if (options.event_url) {
					try {
						// Watchdog for no block event
						var watchdog = setTimeout(() => {
							logger.error('[fcw] Failed to receive block event within the timeout period');
							eventHub.disconnect();

							if (cb && !cbCalled) {
								cbCalled = true;
								return cb(null);						//timeout pass it back
							}
							else return;
						}, g_options.block_delay + 2000);

						// Wait for tx committed event
						eventHub.registerTxEvent(request.txId.getTransactionID(), (tx, code) => {
							var elapsed = Date.now() - startTime + 'ms';
							logger.info('[fcw] The chaincode transaction event has happened! success?:', code, elapsed);
							clearTimeout(watchdog);
							eventHub.disconnect();

							if (code !== 'VALID') {
								if (cb && !cbCalled) {
									cbCalled = true;
									return cb(common.format_error_msg('Commit code: ' + code));//pass error back
								}
								else return;
							} else {
								if (cb && !cbCalled) {
									cbCalled = true;
									return cb(null);					//all good, pass it back
								}
								else return;
							}
						});
					} catch (e) {
						logger.error('[fcw] Illusive event error: ', e);//not sure why this happens, seems rare 3/27/2017
						try {
							eventHub.disconnect();
						} catch (e) { }
						if (cb && !cbCalled) {
							cbCalled = true;
							return cb(e);								//all terrible, pass it back
						}
						else return;
					}

					// ------- [B] Wait xxxx ms for Block  ------- // option B
				} else {
					setTimeout(function () {
						if (cb) return cb(null);
						else return;
					}, g_options.block_delay + 2000);
				}
			}

			// ordering failed, No good
			else {
				if (options.ordered_hook) options.ordered_hook('failed');
				logger.error('[fcw] Failed to order the transaction. Error code: ', response);
				throw response;
			}
		}).catch(function (err) {
			logger.error('[fcw] Error in invoke catch block', typeof err, err);
			if (options.event_url) {
				eventHub.disconnect();
			}

			var formatted = common.format_error_msg(err);
			if (options.ordered_hook) options.ordered_hook('failed', formatted);

			if (cb) return cb(formatted, null);
			else return;
		});
	};
	return invoke_cc;
};
<|endoftext|>


<commit_before>/*global module:true*/
/*
 * Basic table support with re-entrant parsing, where cell content
 * can also specify markdown.
 *
 * Tables
 * ======
 *
 * | Col 1   | Col 2                                              |
 * |======== |====================================================|
 * |**bold** | ![Valid XHTML] (http://w3.org/Icons/valid-xhtml10) |
 * | Plain   | Value                                              |
 *
 */

(function(){
  var table = function(converter) {
    var tables = {}, style = 'text-align:left;', filter;
    tables.th = function(header){
      if (header.trim() === "") { return "";}
      var id = header.trim().replace(/ /g, '_').toLowerCase();
      return '' + header + '	';
    };
    tables.td = function(cell) {
      return '' + converter.makeHtml(cell) + '	';
    };
    tables.ths = function(){
      var out = "", i = 0, hs = [].slice.apply(arguments);
      for (i;i<hs.length;i+=1) {
        out += tables.th(hs[i]) + '\n';
      }
      return out;
    };
    tables.tds = function(){
      var out = "", i = 0, ds = [].slice.apply(arguments);
      for (i;i<ds.length;i+=1) {
        out += tables.td(ds[i]) + '\n';
      }
      return out;
    };
    tables.thead = function() {
      var out, i = 0, hs = [].slice.apply(arguments);
      out = "
\n";
      out += "
\n";
      out += tables.ths.apply(this, hs);
      out += "
\n";
      out += "
\n";
      return out;
    };
    tables.tr = function() {
      var out, i = 0, cs = [].slice.apply(arguments);
      out = "
\n";
      out += tables.tds.apply(this, cs);
      out += "
\n";
      return out;
    };
    filter = function(text) {
      var i=0, lines = text.split('\n'), tbl = [], line, hs, rows, out = [];
      for (i; i<lines.length;i+=1) {
        line = lines[i];
        // looks like a table heading
        if (line.trim().match(/^[|]{1}.*[|]{1}$/)) {
          line = line.trim();
          tbl.push('
');
          hs = line.substring(1, line.length -1).split('|');
          tbl.push(tables.thead.apply(this, hs));
          line = lines[++i];
          if (!line.trim().match(/^[|]{1}[-=| ]+[|]{1}$/)) {
            // not a table rolling back
            line = lines[--i];
          }
          else {
            line = lines[++i];
            tbl.push('
');
            while (line.trim().match(/^[|]{1}.*[|]{1}$/)) {
              line = line.trim();
              tbl.push(tables.tr.apply(this, line.substring(1, line.length -1).split('|')));
              line = lines[++i];
            }
            tbl.push('
');
            tbl.push('
');
            // we are done with this table and we move along
            out.push(tbl.join('\n'));
            continue;
          }
        }
        out.push(line);
      }
      return out.join('\n');
    };
    return [
    {
      type: 'lang',
      filter: filter
    }
    ];
  };

  // Client-side export
  if (typeof window !== 'undefined' && window.Showdown && window.Showdown.extensions) { window.Showdown.extensions.table = table; }
  // Server-side export
  if (typeof module !== 'undefined') {
    module.exports = table;
  }
}());
<commit_msg>Display multiple tables correctly.<commit_after>/*global module:true*/
/*
 * Basic table support with re-entrant parsing, where cell content
 * can also specify markdown.
 *
 * Tables
 * ======
 *
 * | Col 1   | Col 2                                              |
 * |======== |====================================================|
 * |**bold** | ![Valid XHTML] (http://w3.org/Icons/valid-xhtml10) |
 * | Plain   | Value                                              |
 *
 */

(function(){
  var table = function(converter) {
    var tables = {}, style = 'text-align:left;', filter;
    tables.th = function(header){
      if (header.trim() === "") { return "";}
      var id = header.trim().replace(/ /g, '_').toLowerCase();
      return '' + header + '	';
    };
    tables.td = function(cell) {
      return '' + converter.makeHtml(cell) + '	';
    };
    tables.ths = function(){
      var out = "", i = 0, hs = [].slice.apply(arguments);
      for (i;i<hs.length;i+=1) {
        out += tables.th(hs[i]) + '\n';
      }
      return out;
    };
    tables.tds = function(){
      var out = "", i = 0, ds = [].slice.apply(arguments);
      for (i;i<ds.length;i+=1) {
        out += tables.td(ds[i]) + '\n';
      }
      return out;
    };
    tables.thead = function() {
      var out, i = 0, hs = [].slice.apply(arguments);
      out = "
\n";
      out += "
\n";
      out += tables.ths.apply(this, hs);
      out += "
\n";
      out += "
\n";
      return out;
    };
    tables.tr = function() {
      var out, i = 0, cs = [].slice.apply(arguments);
      out = "
\n";
      out += tables.tds.apply(this, cs);
      out += "
\n";
      return out;
    };
    filter = function(text) {
      var i=0, lines = text.split('\n'), tbl = [], line, hs, rows, out = [];
      for (i; i<lines.length;i+=1) {
        line = lines[i];
        // looks like a table heading
        if (line.trim().match(/^[|]{1}.*[|]{1}$/)) {
          line = line.trim();
          tbl.push('
');
          hs = line.substring(1, line.length -1).split('|');
          tbl.push(tables.thead.apply(this, hs));
          line = lines[++i];
          if (!line.trim().match(/^[|]{1}[-=| ]+[|]{1}$/)) {
            // not a table rolling back
            line = lines[--i];
          }
          else {
            line = lines[++i];
            tbl.push('
');
            while (line.trim().match(/^[|]{1}.*[|]{1}$/)) {
              line = line.trim();
              tbl.push(tables.tr.apply(this, line.substring(1, line.length -1).split('|')));
              line = lines[++i];
            }
            tbl.push('
');
            tbl.push('
');
            // we are done with this table and we move along
            out.push(tbl.join('\n'));
            tbl = [];
            continue;
          }
        }
        out.push(line);
      }
      return out.join('\n');
    };
    return [
    {
      type: 'lang',
      filter: filter
    }
    ];
  };

  // Client-side export
  if (typeof window !== 'undefined' && window.Showdown && window.Showdown.extensions) { window.Showdown.extensions.table = table; }
  // Server-side export
  if (typeof module !== 'undefined') {
    module.exports = table;
  }
}());
<|endoftext|>


<commit_before>'use strict';

/* Controllers */

myApp.controller('StartGameCtrl', [ '$scope', '$http', '$timeout', '$window', 'mainSettings',
        function( $scope, $http, $timeout, $window, mainSettings ){
            $scope.userScore = 0;
            $scope.bestScore = localStorage.getItem("bestScore") || 0;
            $scope.attempts = 3;
            $scope.canClickOnCar = true;
            $scope.gameEnd = false;
            $scope.timeIsUp = false;

            $scope.progressbar = {
                'status' : '',
                'width' : 0
            };

            var progressbarTimer;

            $http.get('cars/cars.json').success( function( data ) {
                //receive all cars from json and then shuffling
                $scope.carsData = shuffle( data );

                //first start only after preloading all images
                preloadImages( $scope.carsData );

                //set delay to fix showing images in first drawing
                $timeout( function(){
                    $scope.updateGame();
                }, 300);
            });

            $scope.progressbarLength = function( timeForChoose ){
                var timeForChoose = timeForChoose || 10000,
                    value = $scope.progressbar.width,
                    type;

                $scope.progressbar.width += 5000 / timeForChoose;

                if ( value < 45 ) {
                    type = 'success';
                } else if ( value < 70 ) {
                    type = 'info';
                } else if ( value < 90 ) {
                    type = 'warning';
                } else {
                    type = 'danger';
                }

                $scope.progressbar.status = type;

                if ( $scope.progressbar.width >= 100 ) {
                    $timeout.cancel( progressbarTimer );

                    //user don't make a choice
                    $scope.attempts--;
                    $scope.canClickOnCar = false;

                    if ( $scope.attempts > 0 && !$scope.gameEnd) {

                        //show warning box
                        $scope.timeIsUp = true;

                        $timeout( function(){
                            $scope.updateGame();
                        }, 2000);

                    } else if ( $scope.attempts == 0 ) {
                        $scope.endGame();
                    }
                } else {

                    if ( !$scope.gameEnd ) {
                        //need to fix time for progressbar
                        //call itself for change length of progressbar
                  	    progressbarTimer = $timeout( $scope.progressbarLength, 50);
                    } else {
                        $timeout.cancel( progressbarTimer );
                    }
                }
            };

            $scope.checkChoice = function( carName ) {
            	//defence from double choice or clicking when time is up
                if ( !$scope.canClickOnCar ) return;

                $timeout.cancel( progressbarTimer );
            	$scope.canClickOnCar = false;

                if ( carName.name == $scope.randomCarName ) {
                    carName.flag = "choice-success";

                    //add points depending on the speed of an answer
                    var score = Math.floor( 100 - $scope.progressbar.width );

                    $timeout(function() {
                    	$scope.updateGame(score);
                    	}, 1500);

                } else {
                	carName.flag = "choice-fail";
                    $scope.attempts--;

                    $timeout(function() {
                    	$scope.updateGame();
                    	}, 1500);
                }
            };

            $scope.updateGame = function( /* optional */ score, /* optional */ numberOfCars ) {
                var tempArray = [],
                    score = score || 0,
                    numberOfCars = numberOfCars || 4,
                    randomNumber = Math.floor( Math.random() * numberOfCars );

                //add score
                $scope.userScore += score;

                $scope.timeIsUp = false;
                $scope.progressbar.width = 0;

                //we can make a one choice
                $scope.canClickOnCar = true;

                if ( $scope.gameEnd || !$scope.attempts || !$scope.carsData.length ) {
                    $scope.endGame();
                    return;
                } else {
                    $scope.progressbarLength(10000);
                }

                //playing until we have a cars
                if ( $scope.carsData.length <= numberOfCars ) {
                    //show only the remaining cars
                    numberOfCars = $scope.carsData.length;
                    randomNumber = Math.floor( Math.random() * $scope.carsData.length );
                }

                for ( var i = 0; i < numberOfCars; i++ ) {
                    tempArray.push( $scope.carsData.pop() );
                }

                $scope.randomCarName = tempArray[ randomNumber ].name;
                $scope.cars = tempArray;
            };

            $scope.endGame = function(){
                //check for new bestScore and save to localStorage
                $scope.bestScore = ( $scope.userScore > $scope.bestScore ) ? $scope.userScore : $scope.bestScore;
                localStorage.setItem( 'bestScore', $scope.bestScore );

                //clear blocks with cars
                $scope.cars = [];

                // show/hide blocks when game over
                $scope.gameEnd = true;
            };

            $scope.submitScore = function(){

                //check name input
                if ( !$scope.userName ) {
                    $scope.inputHasError = 'has-error';
                    return;
                } else {
                    $scope.inputHasError = 'has-success';
                }

            	var userResult = {
            		name: $scope.userName,
            		score: $scope.userScore
            	};

            	$http.post( mainSettings.dbUrl , userResult).success( function() {
            		//hide submit form
            		$scope.successSubmit = true;
            	});

            };

            $scope.restart = function(){
                $window.location.reload();
            };
        }
    ])
	.controller('RecordsCtrl', [ '$scope', '$http', 'mainSettings', function( $scope, $http, mainSettings) {
		$http.get( mainSettings.dbUrl ).success( function( data ) {
                var tempArray = [];
                for ( var x in data ) {
					tempArray.push( data[x]);
				}

				$scope.scoreList = tempArray;
        });
	}])
	.controller('MainCtrl', [ '$scope', function( $scope ) {

	}]);

function shuffle( array ) {
    var i = array.length,
        j,
        temp;

    while ( --i ) {
        j = Math.floor( Math.random() * (i + 1) );
        temp = array[ i ];
        array[ i ] = array[ j ];
        array[ j ] = temp;
    }

    return array;
}

function preloadImages( images, callback ) {

    var imageObj = new Image();

    for ( var i = 0, len = images.length; i < len; i++ ) {
        imageObj.src = images[i].imageUrl;
    }
}<commit_msg>Added JSDoc and some refactoring<commit_after>'use strict';

/* Controllers */

myApp.controller('StartGameCtrl', [ '$scope', '$http', '$timeout', '$window', 'mainSettings',
        function( $scope, $http, $timeout, $window, mainSettings ){
            $scope.userScore = 0;
            $scope.bestScore = localStorage.getItem("bestScore") || 0;
            $scope.attempts = 3;
            $scope.canClickOnCar = true;
            $scope.gameEnd = false;
            $scope.timeIsUp = false;

            $scope.progressbar = {
                'status' : '',
                'width' : 0
            };

            var progressbarTimer;

            $http.get('cars/cars.json').success( function( data ) {
                //receive all cars from json and then shuffling
                $scope.carsData = shuffle( data );

                //first start only after preloading all images
                preloadImages( $scope.carsData );

                //set delay to fix showing images in first drawing
                $timeout( function(){
                    $scope.updateGame();
                }, 300);
            });

            /**
             * Change width of progressbar
             *
             * @param {number} [timeForChoose=10000] - Time to make a choice (ms)
             */
            $scope.progressbarLength = function( timeForChoose ){
                var timeForChoose = timeForChoose || 10000,
                    value = $scope.progressbar.width,
                    type;

                $scope.progressbar.width += 5000 / timeForChoose;

                if ( value < 45 ) {
                    type = 'success';
                } else if ( value < 70 ) {
                    type = 'info';
                } else if ( value < 90 ) {
                    type = 'warning';
                } else {
                    type = 'danger';
                }

                $scope.progressbar.status = type;

                if ( $scope.progressbar.width >= 100 ) {
                    $timeout.cancel( progressbarTimer );

                    //user don't make a choice
                    $scope.attempts--;
                    $scope.canClickOnCar = false;

                    if ( $scope.attempts > 0 && !$scope.gameEnd) {

                        //show warning box
                        $scope.timeIsUp = true;

                        $timeout( function(){
                            $scope.updateGame();
                        }, 2000);

                    } else if ( $scope.attempts == 0 ) {
                        $scope.endGame();
                    }
                } else {

                    if ( !$scope.gameEnd ) {
                        // @TODO: Need to fix time for progressbar
                        //call itself for change length of progressbar
                  	    progressbarTimer = $timeout( $scope.progressbarLength, 50);
                    } else {
                        $timeout.cancel( progressbarTimer );
                    }
                }
            };

            $scope.checkChoice = function( carName ) {
            	//defence from double choice or clicking when time is up
                if ( !$scope.canClickOnCar ) return;

                $timeout.cancel( progressbarTimer );
            	$scope.canClickOnCar = false;

                if ( carName.name == $scope.randomCarName ) {
                    carName.flag = "choice-success";

                    //add points depending on the speed of an answer
                    var score = Math.floor( 100 - $scope.progressbar.width );

                    $timeout(function() {
                    	$scope.updateGame(score);
                    	}, 1500);

                } else {
                	carName.flag = "choice-fail";
                    $scope.attempts--;

                    $timeout(function() {
                    	$scope.updateGame();
                    	}, 1500);
                }
            };

            /** Updating all game blocks
             *
             * @param {number} [points=0] - Points to be added to the total bill
             * @param {number} [numberOfCars=4] - The number of cars participating in one round
             */
            $scope.updateGame = function( points, numberOfCars ) {
                var tempArray = [],
                    points = points || 0,
                    numberOfCars = numberOfCars || 4,
                    randomNumber = Math.floor( Math.random() * numberOfCars );

                //add score
                $scope.userScore += points;

                //reset values
                $scope.timeIsUp = false;
                $scope.progressbar.width = 0;

                //we can make a one choice
                $scope.canClickOnCar = true;

                if ( $scope.gameEnd || !$scope.attempts || !$scope.carsData.length ) {
                    $scope.endGame();
                    return;
                } else {
                    $scope.progressbarLength(10000);
                }

                //playing until we have a cars
                if ( $scope.carsData.length <= numberOfCars ) {
                    //show only the remaining cars
                    numberOfCars = $scope.carsData.length;
                    randomNumber = Math.floor( Math.random() * $scope.carsData.length );
                }

                for ( var i = 0; i < numberOfCars; i++ ) {
                    tempArray.push( $scope.carsData.pop() );
                }

                $scope.randomCarName = tempArray[ randomNumber ].name;
                $scope.cars = tempArray;
            };

            $scope.endGame = function(){
                //check for new bestScore and save to localStorage
                $scope.bestScore = ( $scope.userScore > $scope.bestScore ) ? $scope.userScore : $scope.bestScore;
                localStorage.setItem( 'bestScore', $scope.bestScore );

                //clear blocks with cars
                $scope.cars = [];

                // show/hide blocks when game over
                $scope.gameEnd = true;
            };

            $scope.submitScore = function(){

                //check name input
                if ( !$scope.userName ) {
                    $scope.inputHasError = 'has-error';
                    return;
                } else {
                    $scope.inputHasError = 'has-success';
                }

            	var userResult = {
            		name: $scope.userName,
            		score: $scope.userScore
            	};

            	$http.post( mainSettings.dbUrl , userResult).success( function() {
            		//hide submit form
            		$scope.successSubmit = true;
            	});

            };

            $scope.restart = function(){
                $window.location.reload();
            };
        }
    ])
	.controller('RecordsCtrl', [ '$scope', '$http', 'mainSettings', function( $scope, $http, mainSettings) {
		$http.get( mainSettings.dbUrl ).success( function( data ) {
                var tempArray = [];
                for ( var x in data ) {
					tempArray.push( data[x]);
				}

				$scope.scoreList = tempArray;
        });
	}])
	.controller('MainCtrl', [ '$scope', function( $scope ) {

	}]);

/**
 * Mix passed array
 *
 * @param {array} arr
 * @returns {array} mixed array
 */
function shuffle( arr ) {
    var i = arr.length,
        j,
        temp;

    while ( --i ) {
        j = Math.floor( Math.random() * (i + 1) );
        temp = arr[ i ];
        arr[ i ] = arr[ j ];
        arr[ j ] = temp;
    }

    return arr;
}

/**
 * Preload images of cars
 *
 * @param {array} arrWithImages - Array of objects, with image properties
 */
function preloadImages( arrWithImages ) {

    var imageObj = new Image();

    for ( var i = 0, len = arrWithImages.length; i < len; i++ ) {
        imageObj.src = arrWithImages[i].imageUrl;
    }
}<|endoftext|>


<commit_before>'use strict';

/* Controllers */

angular.module('poNG.controllers', [])
  .controller('poNG', ['$scope', 'Players', function($scope, Players) {
    $scope.players = Players;
    $scope.dropped = function(dragEl, dropEl) {
      var drop = angular.element(dropEl),
          drag = angular.element(dragEl);
      var name = drag.attr('data-name'),
          rank = drag.attr('data-rank'),
          newLi = document.createElement("li"),
          nameDiv = document.createElement("div"),
          rankDiv = document.createElement("div");
      nameDiv.innerHTML = name;
      rankDiv.innerHTML = rank;
      newLi.appendChild(nameDiv);
      newLi.appendChild(rankDiv);

      document.getElementsByTagName("ul")[1].appendChild(newLi);

    };

  }]);<commit_msg>Rewrite controller using angular.element<commit_after>'use strict';

/* Controllers */

angular.module('poNG.controllers', [])
  .controller('poNG', ['$scope', 'Players', function($scope, Players) {
    $scope.players = Players;
    $scope.dropped = function(dragEl, dropEl) {
      var drop = angular.element(dropEl),
          drag = angular.element(dragEl).clone();

      drop.append(drag);
      dragEl.remove();
    };

  }]);
<|endoftext|>


<commit_before>
import VCDonationModel from './VCDonationModel'
import addVc from '../users/addVc'
import addVcDonatedAllTime from '../users/addVcDonatedAllTime'

/**
 * Donate the user's virtal currency to the specified charity.
 * Deduct the VC from the user's balance and create a VCDonation log.
 * @param {object} userContext - The user authorizer object.
 * @param {string} id - The user id.
 * @param {string} charityId - The charity id.
 * @param {integer} vc - The amount of virtual currency to add to the
 *   user's balance.
 * @return {Promise<User>}  A promise that resolves into a User instance.
 */
export default async (userContext, userId, charityId, vc) => {
  try {
    // Subtract VC from the user.
    const user = await addVc(userContext, userId, -vc)

    // Create the VC donation.
    await VCDonationModel.create(userContext, {
      userId: userId,
      charityId: charityId,
      vcDonated: vc
    })

    // Add VC donated to the user's all time count.
    await addVcDonatedAllTime(userContext, userId, vc)

    return user
  } catch (e) {
    throw e
  }
}
<commit_msg>Return latest user from donateVc mutation.<commit_after>
import VCDonationModel from './VCDonationModel'
import addVc from '../users/addVc'
import addVcDonatedAllTime from '../users/addVcDonatedAllTime'

/**
 * Donate the user's virtal currency to the specified charity.
 * Deduct the VC from the user's balance and create a VCDonation log.
 * @param {object} userContext - The user authorizer object.
 * @param {string} id - The user id.
 * @param {string} charityId - The charity id.
 * @param {integer} vc - The amount of virtual currency to add to the
 *   user's balance.
 * @return {Promise<User>}  A promise that resolves into a User instance.
 */
export default async (userContext, userId, charityId, vc) => {
  try {
    // Subtract VC from the user.
    await addVc(userContext, userId, -vc)

    // Create the VC donation.
    await VCDonationModel.create(userContext, {
      userId: userId,
      charityId: charityId,
      vcDonated: vc
    })

    // Add VC donated to the user's all time count.
    const user = await addVcDonatedAllTime(userContext, userId, vc)

    return user
  } catch (e) {
    throw e
  }
}
<|endoftext|>


<commit_before>const ACCELERATION_REPORT_MIN = 12;

app.controller('PhoneController', function($scope) {
  $scope.greeting = 'Hello World Of Physics!';
  const socket = io();

  // socket.on('news', function (data) {
  //   console.log(data);
  //   $scope.newsFromSocket = data;
  //   socket.emit('my other event', { my: 'data' });
  //   $scope.$apply();
  // });

  $scope.xShakes = 0; // used to "count shakes" in game logic later
  $scope.yShakes = 0;
  $scope.zShakes = 0;
  $scope.emitShake = function(data) {
    return socket.emit('shake', data);
  };

  $scope.handleDeviceAccelChange = function(event) {
    event.preventDefault();
    if (event.acceleration.x > ACCELERATION_REPORT_MIN) {
      $scope.xAcceleration = event.acceleration.x;
      $scope.xShakes++;
      $scope.emitShake({
        xShakes: $scope.xShakes,
        yShakes: $scope.yShakes,
        zShakes: $scope.zShakes
      });
    }
    if (event.acceleration.y > ACCELERATION_REPORT_MIN) {
      $scope.yAcceleration = event.acceleration.y;
      $scope.yShakes++;
      $scope.emitShake({
        xShakes: $scope.xShakes,
        yShakes: $scope.yShakes,
        zShakes: $scope.zShakes
      });
    }
    if (event.acceleration.z > ACCELERATION_REPORT_MIN) {
      $scope.zAcceleration = event.acceleration.z;
      $scope.zShakes++;
      $scope.emitShake({
        xShakes: $scope.xShakes,
        yShakes: $scope.yShakes,
        zShakes: $scope.zShakes
      });
    }
    // $scope.accelEventData = event.acceleration;
    $scope.$apply();
  };
  window.addEventListener('devicemotion', $scope.handleDeviceAccelChange, true);
}).controller('PlayGridController', function($scope) {
  // players are hardcoded for now, eventually this will be aggregated from somewhere else
  // so it's sort of a stub that will be adjusted later
  $scope.title = "SHAKE RACE!!!";
  $scope.players = [{name: 'Bob', score: 5}, {name: 'Fred', score: 7}, {name: 'Jenny', score: 4}]
});

<commit_msg>whitespace<commit_after>const ACCELERATION_REPORT_MIN = 12;

app.controller('PhoneController', function($scope) {
  $scope.greeting = 'Hello World Of Physics!';
  const socket = io();

  // socket.on('news', function (data) {
  //   console.log(data);
  //   $scope.newsFromSocket = data;
  //   socket.emit('my other event', { my: 'data' });
  //   $scope.$apply();
  // });

  $scope.xShakes = 0; // used to "count shakes" in game logic later
  $scope.yShakes = 0;
  $scope.zShakes = 0;
  $scope.emitShake = function(data) {
    return socket.emit('shake', data);
  };

  $scope.handleDeviceAccelChange = function(event) {
    event.preventDefault();
    if (event.acceleration.x > ACCELERATION_REPORT_MIN) {
      $scope.xAcceleration = event.acceleration.x;
      $scope.xShakes++;
      $scope.emitShake({
        xShakes: $scope.xShakes,
        yShakes: $scope.yShakes,
        zShakes: $scope.zShakes
      });
    }
    if (event.acceleration.y > ACCELERATION_REPORT_MIN) {
      $scope.yAcceleration = event.acceleration.y;
      $scope.yShakes++;
      $scope.emitShake({
        xShakes: $scope.xShakes,
        yShakes: $scope.yShakes,
        zShakes: $scope.zShakes
      });
    }
    if (event.acceleration.z > ACCELERATION_REPORT_MIN) {
      $scope.zAcceleration = event.acceleration.z;
      $scope.zShakes++;
      $scope.emitShake({
        xShakes: $scope.xShakes,
        yShakes: $scope.yShakes,
        zShakes: $scope.zShakes
      });
    }
    // $scope.accelEventData = event.acceleration;
    $scope.$apply();
  };
  window.addEventListener('devicemotion', $scope.handleDeviceAccelChange, true);
}).controller('PlayGridController', function($scope) {
  // players are hardcoded for now, eventually this will be aggregated from somewhere else
  // so it's sort of a stub that will be adjusted later
  $scope.title = "SHAKE RACE!!!";
  $scope.players = [{name: 'Bob', score: 5}, {name: 'Fred', score: 7}, {name: 'Jenny', score: 4}]
});

<|endoftext|>


<commit_before>define(['jquery', 'backbone', 'knockout', 'underscore', 'plugins/knockout-select2'], function ($, Backbone, ko, _) {
    return Backbone.View.extend({

        events: function(){
            return {
                'click #saveedits': 'submit'
            }
        },

        constructor: function (options) {
            var self = this;

            Backbone.View.apply(this, arguments);

            _.each(this.branchLists, function(branchList) {
                self.listenTo(branchList, 'change', function(eventtype, item){
                    self.trigger('change', eventtype, item);
                }));
            });

            ko.applyBindings(this.viewModel, this.el);
            return this;
        },

        initialize: function() {
            var self = this;
            this.form = this.$el;
            // parse then restringify JSON data to ensure whitespace is identical
            this._rawdata = ko.toJSON(JSON.parse(this.form.find('#formdata').val()));
            this.viewModel = JSON.parse(this._rawdata);
            this.viewModel.editing = {};
            this.viewModel.formatDomainValue = function (item) {
                return item.value;
            };

            this.viewModel.selectDomainValue = function (item) {
                if (this.labelValue) {
                    this.labelValue(item.value);
                }
                return self.viewModel.formatDomainValue(item);
            };

            $('input,select').change(function() {
                var isDirty = self.isDirty();
                self.trigger('change', isDirty);
            });

            this.on('change', function(eventtype, item){
                console.log(eventtype);
                console.log(item);
                $('#saveedits').removeClass('disabled');
                $('#canceledits').removeClass('disabled');
            });

            this.branchLists = [];
        },

        isDirty: function () {
            // var viewModel = JSON.parse(ko.toJSON(this.viewModel));
            // for(branch in ko.toJS(this.viewModel)){
            //     if(branch !== 'domains' && branch !== 'defaults' && branch !== 'editing'){
            //         for(index in viewModel[branch]){
            //             for(item in viewModel[branch][index]){
            //                 if(item.indexOf('entityid') > 0){
            //                     if(viewModel[branch][index][item] === ''){
            //                         return true;
            //                         break;
            //                     }
            //                 }
            //             }
            //         }
            //     }
            // }
            return this.getData(true) !== this._rawdata;
        },

        getData: function(includeDomains){
            var data = ko.toJS(this.viewModel)
            if (!includeDomains) {
                delete data.domains;
            }
            delete data.editing;
            return ko.toJSON(data);
        },

        validate: function(){
            return true;
        },

        submit: function(){
            if (this.validate()){
                this.form.find('#formdata').val(this.getData());
                this.form.submit();
            }
        }
    });
});<commit_msg>fixing error in base.js<commit_after>define(['jquery', 'backbone', 'knockout', 'underscore', 'plugins/knockout-select2'], function ($, Backbone, ko, _) {
    return Backbone.View.extend({

        events: function(){
            return {
                'click #saveedits': 'submit'
            }
        },

        constructor: function (options) {
            var self = this;

            Backbone.View.apply(this, arguments);

            _.each(this.branchLists, function(branchList) {
                self.listenTo(branchList, 'change', function(eventtype, item){
                    self.trigger('change', eventtype, item);
                });
            });

            ko.applyBindings(this.viewModel, this.el);
            return this;
        },

        initialize: function() {
            var self = this;
            this.form = this.$el;
            // parse then restringify JSON data to ensure whitespace is identical
            this._rawdata = ko.toJSON(JSON.parse(this.form.find('#formdata').val()));
            this.viewModel = JSON.parse(this._rawdata);
            this.viewModel.editing = {};
            this.viewModel.formatDomainValue = function (item) {
                return item.value;
            };

            this.viewModel.selectDomainValue = function (item) {
                if (this.labelValue) {
                    this.labelValue(item.value);
                }
                return self.viewModel.formatDomainValue(item);
            };

            $('input,select').change(function() {
                var isDirty = self.isDirty();
                self.trigger('change', isDirty);
            });

            this.on('change', function(eventtype, item){
                console.log(eventtype);
                console.log(item);
                $('#saveedits').removeClass('disabled');
                $('#canceledits').removeClass('disabled');
            });

            this.branchLists = [];
        },

        isDirty: function () {
            // var viewModel = JSON.parse(ko.toJSON(this.viewModel));
            // for(branch in ko.toJS(this.viewModel)){
            //     if(branch !== 'domains' && branch !== 'defaults' && branch !== 'editing'){
            //         for(index in viewModel[branch]){
            //             for(item in viewModel[branch][index]){
            //                 if(item.indexOf('entityid') > 0){
            //                     if(viewModel[branch][index][item] === ''){
            //                         return true;
            //                         break;
            //                     }
            //                 }
            //             }
            //         }
            //     }
            // }
            return this.getData(true) !== this._rawdata;
        },

        getData: function(includeDomains){
            var data = ko.toJS(this.viewModel)
            if (!includeDomains) {
                delete data.domains;
            }
            delete data.editing;
            return ko.toJSON(data);
        },

        validate: function(){
            return true;
        },

        submit: function(){
            if (this.validate()){
                this.form.find('#formdata').val(this.getData());
                this.form.submit();
            }
        }
    });
});<|endoftext|>