<commit_before>var SRC = 'src';
var ES5 = 'es5';
var CLIENT = __dirname + '/public';

var UI_SCRIPTS = [
    'common/ModelInterface',
    'common/UIControllerInterface',
    'logger/DefaultLogger',
    'logger/LoggerInterface',
    'ticTacToe/TicTacToeUIController',
    'ticTacToe/TicTacToeUIControllerInterface',
    'index'
];

var browserify = require('browserify');
var buffer = require('vinyl-buffer');
var bunyan = require('bunyan');
var concatCss = require('gulp-concat-css');
var del = require('del');
var gulp = require('gulp');
var gulpUtil = require('gulp-util');
var nodemon = require('gulp-nodemon');
var runSeq = require('run-sequence');
var source = require('vinyl-source-stream');
var sourceMaps = require('gulp-sourcemaps');
var spawn = require('child_process').spawn;
var typeScript = require('gulp-typescript');
var typeScriptify = require('tsify');
var typeScriptLint = require('gulp-tslint');
var uglify = require('gulp-uglify');

var environments = require('gulp-environments');
var development = environments.development;
var staging = environments.make('staging');
var production = environments.production;

var node;

function build(callback) {
    console.log('Building...');
    return runSeq(
            'clean-fast',
            ['transpile-ts', 'transcribe-html', 'transcribe-images', 'transcribe-css'],
            'transcribe-ui-js',
            callback
            );
}

function stop() {
    console.log('Stopping...');
    if (node){
        try {
            node && node.kill();
        } catch (error) {
            console.error('Failed to stop node: ' + error);
        }

    }
}

function transpile() {
    console.log('Transpiling...');
    var tsProject = typeScript.createProject('src/tsconfig.json');
    return tsProject
            .src()
            .pipe(typeScript(tsProject))
            .js.pipe(gulp.dest(ES5));
}

function transcribeCss() {
    console.log('Transcribing CSS...');
    return gulp.src([SRC + '/**/*.css'])
            .pipe(concatCss('index.css'))
            .pipe(gulp.dest(CLIENT));
}

function transcribeHtml() {
    console.log('Transcribing HTML...');
    return gulp.src([SRC + '/**/*.html'])
            .pipe(gulp.dest(CLIENT));
}

function transcribeImages () {
    console.log('Transcribing Images...');
    return gulp.src([SRC + '/**/*.png'])
            .pipe(gulp.dest(CLIENT));
}

function transcribeUiJs() {
    console.log('Transcribing UI JavaScript...');
    function pointTo(scripts) {
        return scripts.map(function (script) {
            return ES5 + '/' + script + '.js';
        });
    }

    return browserify({
        basedir: '.',
        debug: true,
        entries: pointTo(UI_SCRIPTS),
        cache: {},
        packageCache: {}
    })
            //.transform(production('babelify'))
            .bundle()
            .pipe(source('index.js'))
            .pipe(buffer())
            .pipe(sourceMaps.init({loadMaps: true}))
            //.pipe(production(uglify()))
            .pipe(sourceMaps.write('./'))
            .pipe(gulp.dest(CLIENT));
}

function tslint() {
    console.log('Linting...');
    return gulp.src('./src/**/*.ts')
            .pipe(typeScriptLint({
                configuration: 'tslint.json',
                formatter: 'verbose'
            }))
            .pipe(typeScriptLint.report({
                emitError: false,
                summarizeFailureOutput: true
            }));
}

// Cleaning tasks --------------------------------------

gulp.task('clean-all', function (callback) {
    return del([ES5, CLIENT], callback);
});

gulp.task('clean-fast', ['clean-api', 'clean-ui-fast']);

gulp.task('clean-api', function (callback) {
    return del([ES5], callback);
});

gulp.task('clean-ui-all', function (callback) {
    return del([CLIENT], callback);
});

gulp.task('clean-ui-fast', function (callback) {
    return del([
        CLIENT + '/**/*', CLIENT + '/**/*.*',
        '!' + CLIENT,
        '!' + CLIENT + '/bower_components',
        '!' + CLIENT + '/bower_components/**'
    ], callback);
});

// Transformation tasks --------------------------------------

gulp.task('default', ['start']);

gulp.task('build', build);
gulp.task('build-api', ['transpile']);
gulp.task('build-ui', ['build']);

gulp.task('transpile', ['transpile-ts']);
gulp.task('transpile-ts', transpile);
gulp.task('transcribe-css', transcribeCss);
gulp.task('transcribe-html', transcribeHtml);
gulp.task('transcribe-images', transcribeImages);
gulp.task('transcribe-ui-js', transcribeUiJs);

// Misc tasks --------------------------------------

gulp.task('stop', stop);

gulp.task('start', function () {
    runSeq('stop', 'tslint', 'build', function () {
        node = nodemon({
            ext: 'css html js json sh ts',
            ignore: [ES5, CLIENT],
            legacyWatch: true,
            readable: true,
            script: ES5 + '/app.js',
            stdout: true
        });
        node.on('restart', function () {
                    gulpUtil.log('---------- Restarted! ----------');
                    tslint();
                    transpile();
                    transcribeCss();
                    transcribeHtml();
                    transcribeImages();
                    transcribeUiJs();
                });
    });
});

gulp.task('tslint', tslint);

process.on('exit', stop);
<commit_msg>fixed bug in gulpfile so restart works more reliably<commit_after>var SRC = 'src';
var ES5 = 'es5';
var CLIENT = __dirname + '/public';

var UI_SCRIPTS = [
    'common/DifficultyLevel',
    'common/ModelInterface',
    'common/PlayerType',
    'common/UIControllerInterface',
    'logger/DefaultLogger',
    'logger/LoggerInterface',
    'ticTacToe/TicTacToeBadLocationError',
    'ticTacToe/TicTacToeBadPlayerError',
    'ticTacToe/TicTacToeBoard',
    'ticTacToe/TicTacToeComputerPlayer',
    'ticTacToe/TicTacToeGame',
    'ticTacToe/TicTacToeHumanPlayer',
    'ticTacToe/TicTacToeMarker',
    'ticTacToe/TicTacToePlayer',
    'ticTacToe/TicTacToeState',
    'ticTacToe/TicTacToeStatus',
    'ticTacToe/TicTacToeUIController',
    'ticTacToe/TicTacToeUIControllerInterface',
    'index'
];

var browserify = require('browserify');
var buffer = require('vinyl-buffer');
var bunyan = require('bunyan');
var concatCss = require('gulp-concat-css');
var del = require('del');
var gulp = require('gulp');
var gulpUtil = require('gulp-util');
var nodemon = require('gulp-nodemon');
var runSeq = require('run-sequence');
var source = require('vinyl-source-stream');
var sourceMaps = require('gulp-sourcemaps');
var spawn = require('child_process').spawn;
var typeScript = require('gulp-typescript');
var typeScriptify = require('tsify');
var typeScriptLint = require('gulp-tslint');
var uglify = require('gulp-uglify');

var environments = require('gulp-environments');
var development = environments.development;
var staging = environments.make('staging');
var production = environments.production;

var node;

function build(callback) {
    console.log('Building...');
    return runSeq(
            'clean-fast',
            ['transpile-ts', 'transcribe-html', 'transcribe-images', 'transcribe-css'],
            'transcribe-ui-js',
            callback
            );
}

function stop() {
    console.log('Stopping...');
    if (node){
        try {
            node && node.kill();
        } catch (error) {
            console.error('Failed to stop node: ' + error);
        }

    }
}

function transpile() {
    console.log('Transpiling...');
    var tsProject = typeScript.createProject('src/tsconfig.json');
    return tsProject
            .src()
            .pipe(typeScript(tsProject))
            .js.pipe(gulp.dest(ES5));
}

function transcribeCss() {
    console.log('Transcribing CSS...');
    return gulp.src([SRC + '/**/*.css'])
            .pipe(concatCss('index.css'))
            .pipe(gulp.dest(CLIENT));
}

function transcribeHtml() {
    console.log('Transcribing HTML...');
    return gulp.src([SRC + '/**/*.html'])
            .pipe(gulp.dest(CLIENT));
}

function transcribeImages () {
    console.log('Transcribing Images...');
    return gulp.src([SRC + '/**/*.png'])
            .pipe(gulp.dest(CLIENT));
}

function transcribeUiJs() {
    console.log('Transcribing UI JavaScript...');
    function pointTo(scripts) {
        return scripts.map(function (script) {
            return ES5 + '/' + script + '.js';
        });
    }

    return browserify({
        basedir: '.',
        debug: true,
        entries: pointTo(UI_SCRIPTS),
        cache: {},
        packageCache: {}
    })
            //.transform(production('babelify'))
            .bundle()
            .pipe(source('index.js'))
            .pipe(buffer())
            .pipe(sourceMaps.init({loadMaps: true}))
            //.pipe(production(uglify()))
            .pipe(sourceMaps.write('./'))
            .pipe(gulp.dest(CLIENT));
}

function tslint() {
    console.log('Linting...');
    return gulp.src('./src/**/*.ts')
            .pipe(typeScriptLint({
                configuration: 'tslint.json',
                formatter: 'verbose'
            }))
            .pipe(typeScriptLint.report({
                emitError: false,
                summarizeFailureOutput: true
            }));
}

// Cleaning tasks --------------------------------------

gulp.task('clean-all', function (callback) {
    return del([ES5, CLIENT], callback);
});

gulp.task('clean-fast', ['clean-api', 'clean-ui-fast']);

gulp.task('clean-api', function (callback) {
    return del([ES5], callback);
});

gulp.task('clean-ui-all', function (callback) {
    return del([CLIENT], callback);
});

gulp.task('clean-ui-fast', function (callback) {
    return del([
        CLIENT + '/**/*', CLIENT + '/**/*.*',
        '!' + CLIENT,
        '!' + CLIENT + '/bower_components',
        '!' + CLIENT + '/bower_components/**'
    ], callback);
});

// Transformation tasks --------------------------------------

gulp.task('default', ['start']);

gulp.task('build', build);
gulp.task('build-api', ['transpile']);
gulp.task('build-ui', ['build']);

gulp.task('transpile', ['transpile-ts']);
gulp.task('transpile-ts', transpile);
gulp.task('transcribe-css', transcribeCss);
gulp.task('transcribe-html', transcribeHtml);
gulp.task('transcribe-images', transcribeImages);
gulp.task('transcribe-ui-js', transcribeUiJs);

// Misc tasks --------------------------------------

gulp.task('stop', stop);

gulp.task('start', function () {
    runSeq('stop', 'tslint', 'build', function () {
        node = nodemon({
            ext: 'css html js json sh ts',
            ignore: [ES5, CLIENT],
            legacyWatch: true,
            readable: true,
            script: ES5 + '/app.js',
            stdout: true
        });
        node.on('restart', function () {
                    gulpUtil.log('---------- Restarted! ----------');
                    tslint();
                    transpile();
                    transcribeCss();
                    transcribeHtml();
                    transcribeImages();
                    transcribeUiJs();
                });
    });
});

gulp.task('tslint', tslint);

process.on('exit', stop);
<|endoftext|>


<commit_before>angular.module("omniControllers")
  .controller("ExchangeSaleController",["$scope", "Transaction", "ADDRESS_EXPLORER_URL", "SATOSHI_UNIT",
    function ExchangeSaleController($scope, Transaction, ADDRESS_EXPLORER_URL, SATOSHI_UNIT) {
                  $scope.editTransactionCost = function(){
                  $scope.modalManager.openTransactionCostModal($scope, $scope.confirm);
            }
      $scope.confirm = function(){
        //TODO: VALIDATIONS
        var fee = new Big($scope.minersFee);
        var exchangeSale = new Transaction(20,$scope.selectedAddress,fee,{
            transaction_version:0,
            amount_for_sale: +new Big($scope.saleAmount).times(SATOSHI_UNIT).valueOf(),
            amount_desired: $scope.salePrice,
            min_buyer_fee: new Big($scope.buyersFee).times(SATOSHI_UNIT).valueOf(),
            blocks: $scope.saleBlocks,
            currency_identifier: $scope.selectedAsset.symbol,
            donate: $scope.account.getSetting("donate")
          });

        $scope.modalManager.openConfirmationModal({
          dataTemplate: '/views/modals/partials/sale.html',
          scope:{
            title:"EXCHANGE.SALE.MODALTITLE",
            saleAmount: $scope.saleAmount,
            buyersFee: $scope.buyersFee,
            selectedCoin: $scope.selectedAsset,
            salePricePerCoin: $scope.salePrice / $scope.saleAmount,
            saleBlocks : $scope.saleBlocks,
            fees : $scope.minersFee,
            totalCost : exchangeSale.totalCost,
            confirmText:"EXCHANGE.SALE.CONFIRM",
            explorerUrl:ADDRESS_EXPLORER_URL,
            successRedirect:"/exchange/trade"
          },
          transaction:exchangeSale
        })
      }

      $scope.selectedAddress= $scope.hasCoins ? $scope.selectedAsset.tradableAddresses[0] : undefined;
      $scope.setAddress = function(address){
            $scope.selectedAddress = address;
      }

      // $scope.validateSaleForm = function() {
      //   var dustValue = 5757;
      //   var minerMinimum = 10000;
      //   var nonZeroValue = 1;
      //   var cancelFees = (5757*3);
      //   var divisible = $scope.selectedCoin.divisible;

      //   var convertToSatoshi = [
      //       $scope.minersFee,
      //       $scope.buyersFee,
      //       0, //$scope.salePricePerCoin,
      //       $scope.saleAmount,
      //       $scope.balanceData[0],
      //       $scope.balanceData[1]
      //     ];

      //   if (!divisible) {
      //     delete convertToSatoshi[ convertToSatoshi.indexOf( $scope.saleAmount ) ];
      //     delete convertToSatoshi[ convertToSatoshi.indexOf( $scope.balanceData[0] ) ];
      //   }

      //   var convertedValues = $scope.convertDisplayedValue( convertToSatoshi );

      //   var minersFee = +convertedValues[0];
      //   var buyersFee = +convertedValues[1];
      //   //var salePricePerCoin = +convertedValues[2];
      //   var saleAmount = divisible ? +convertedValues[3] : +$scope.saleAmount;

      //   var balance = divisible ? +convertedValues[4] : +$scope.balanceData[0];
      //   var btcbalance = +convertedValues[5];

      //   var coin = $scope.isCancel != true ? $scope.selectedCoin.symbol : $scope.selectedCoin_extra;
      //   var salePricePerCoin = $scope.salePricePerCoin;
      //   var address = $scope.selectedAddress;
      //   var saleBlocks = +$scope.saleBlocks;

      //   var totalFeeCost = parseFloat($scope.convertDisplayedValue($scope.totalCost));

      //   var required = [coin, address, saleAmount, saleBlocks, salePricePerCoin, minersFee, buyersFee, balance, btcbalance, $scope.saleForm.$valid];

      //   var error = 'Please ';
      //   if ($scope.saleForm.$valid == false) {
      //     error += 'make sure all fields are completely filled, ';
      //   }
      //   if ( $scope.isCancel != true && coin == 'BTC') {
      //     error += 'make sure your sale is for MSC or TMSC, ';
      //   }
      //   if( $scope.isCancel != true && ((coin == 'MSC') || (coin == 'TMSC')) ) {
      //     if (saleAmount < nonZeroValue)
      //       error += 'make sure your send amount is non-zero, ';
      //     if (buyersFee < minerMinimum)
      //       error += 'make sure your buyers fee entry is at least 0.0001 BTC, ';
      //     if (minersFee < minerMinimum)
      //       error += 'make sure your fee entry is at least 0.0001 BTC, ';
      //     if ((saleAmount <= balance) == false)
      //       error += 'make sure you aren\'t putting more coins up for sale than you own, ';
      //     if ((totalFeeCost <= btcbalance) == false)
      //       error += 'make sure you have enough Bitcoin to cover your fees, ';

      //     if (saleBlocks < 1)
      //       error += 'make sure your block timeframe is at least 1, ';
      //   }
      //   if ($scope.isCancel == true && (((cancelFees + minersFee) <= btcbalance) == false) )
      //     error += 'make sure you have enough Bitcoin to cover your transaction fees, ';
      //   if (error.length < 8) {
      //     $scope.$parent.showErrors = false;

      //     // open modal
      //     var modalInstance = $modal.open({
      //       templateUrl: $scope.isCancel == true ? '/partials/wallet_cancel_modal.html' : '/partials/wallet_sale_modal.html',
      //       controller: function($scope, $modalInstance, $rootScope, data, prepareSaleTransaction, getUnsignedSaleTransaction, convertSatoshiToDisplayedValue, getDisplayedAbbreviation) {
      //         $scope.sendSuccess = false, $scope.sendError = false, $scope.waiting = false, $scope.privKeyPass = {};
      //         $scope.convertSatoshiToDisplayedValue=convertSatoshiToDisplayedValue,
      //         $scope.getDisplayedAbbreviation=getDisplayedAbbreviation,
      //         $scope.saleAmount=data.amt,
      //         $scope.buyersFee=data.buyersfee,
      //         $scope.selectedCoin=data.selectedCoin,
      //         $scope.salePricePerCoin= data.price,
      //         $scope.saleBlocks = data.blocks;

      //         $scope.ok = function() {
      //           $scope.clicked = true;
      //           $scope.waiting = true;

      //           prepareSaleTransaction(data.seller, data.amt, data.price,
      //           data.buyersfee, data.fee, data.blocks, data.currency, $scope.privKeyPass, $scope);
      //         };
      //         $scope.cancel = function () {
      //           $modalInstance.dismiss('cancel');
      //         };
      //       },
      //       resolve: {
      //         data: function() {
      //           return {
      //             seller: address,
      //             amt: saleAmount,
      //             price: salePricePerCoin,
      //             buyersfee: buyersFee,
      //             fee: minersFee,
      //             blocks: saleBlocks,
      //             currency: coin,
      //             selectedCoin: $scope.selectedCoin,
      //             saleBlocks: saleBlocks
      //           };
      //         },
      //         prepareSaleTransaction: function() {
      //           return prepareSaleTransaction;
      //         },
      //         getUnsignedSaleTransaction: function() {
      //           return getUnsignedSaleTransaction;
      //         },
      //         pushSignedTransaction: function() {
      //           return walletTransactionService.pushSignedTransaction;
      //         },
      //         convertSatoshiToDisplayedValue: function() {
      //           return $scope.convertSatoshiToDisplayedValue;
      //         },
      //         getDisplayedAbbreviation: function() {
      //           return $scope.getDisplayedAbbreviation;
      //         }
      //       }
      //     });

      //     modalInstance.result.then(function() {
      //       if ($scope.isCancel)
      //         $scope.$parent.$parent.$parent.cancelTrig = null;
      //     }, function() {
      //       if ($scope.isCancel)
      //         $scope.$parent.$parent.$parent.cancelTrig = null;
      //     });

      //   } else {
      //     error += 'and try again.';
      //     $scope.error = error;
      //     $scope.$parent.showErrors = true;
      //   }
      // };
    }])

<commit_msg>Dex sell v1<commit_after>angular.module("omniControllers")
  .controller("ExchangeSaleController",["$scope", "Transaction", "ADDRESS_EXPLORER_URL", "SATOSHI_UNIT",
    function ExchangeSaleController($scope, Transaction, ADDRESS_EXPLORER_URL, SATOSHI_UNIT) {
                  $scope.editTransactionCost = function(){
                  $scope.modalManager.openTransactionCostModal($scope, $scope.confirm);
            }
      $scope.confirm = function(){
        //TODO: VALIDATIONS
        var fee = new Big($scope.minersFee);
        var exchangeSale = new Transaction(20,$scope.selectedAddress,fee,{
            transaction_version:1,
            amount_for_sale: +new Big($scope.saleAmount).times(SATOSHI_UNIT).valueOf(),
            amount_desired: $scope.salePrice,
            min_buyer_fee: new Big($scope.buyersFee).times(SATOSHI_UNIT).valueOf(),
            blocks: $scope.saleBlocks,
            currency_identifier: $scope.selectedAsset.symbol,
            action:1,
            donate: $scope.account.getSetting("donate")
          });

        $scope.modalManager.openConfirmationModal({
          dataTemplate: '/views/modals/partials/sale.html',
          scope:{
            title:"EXCHANGE.SALE.MODALTITLE",
            saleAmount: $scope.saleAmount,
            buyersFee: $scope.buyersFee,
            selectedCoin: $scope.selectedAsset,
            salePricePerCoin: $scope.salePrice / $scope.saleAmount,
            saleBlocks : $scope.saleBlocks,
            fees : $scope.minersFee,
            totalCost : exchangeSale.totalCost,
            confirmText:"EXCHANGE.SALE.CONFIRM",
            explorerUrl:ADDRESS_EXPLORER_URL,
            successRedirect:"/exchange/trade"
          },
          transaction:exchangeSale
        })
      }

      $scope.selectedAddress= $scope.hasCoins ? $scope.selectedAsset.tradableAddresses[0] : undefined;
      $scope.setAddress = function(address){
            $scope.selectedAddress = address;
      }

      // $scope.validateSaleForm = function() {
      //   var dustValue = 5757;
      //   var minerMinimum = 10000;
      //   var nonZeroValue = 1;
      //   var cancelFees = (5757*3);
      //   var divisible = $scope.selectedCoin.divisible;

      //   var convertToSatoshi = [
      //       $scope.minersFee,
      //       $scope.buyersFee,
      //       0, //$scope.salePricePerCoin,
      //       $scope.saleAmount,
      //       $scope.balanceData[0],
      //       $scope.balanceData[1]
      //     ];

      //   if (!divisible) {
      //     delete convertToSatoshi[ convertToSatoshi.indexOf( $scope.saleAmount ) ];
      //     delete convertToSatoshi[ convertToSatoshi.indexOf( $scope.balanceData[0] ) ];
      //   }

      //   var convertedValues = $scope.convertDisplayedValue( convertToSatoshi );

      //   var minersFee = +convertedValues[0];
      //   var buyersFee = +convertedValues[1];
      //   //var salePricePerCoin = +convertedValues[2];
      //   var saleAmount = divisible ? +convertedValues[3] : +$scope.saleAmount;

      //   var balance = divisible ? +convertedValues[4] : +$scope.balanceData[0];
      //   var btcbalance = +convertedValues[5];

      //   var coin = $scope.isCancel != true ? $scope.selectedCoin.symbol : $scope.selectedCoin_extra;
      //   var salePricePerCoin = $scope.salePricePerCoin;
      //   var address = $scope.selectedAddress;
      //   var saleBlocks = +$scope.saleBlocks;

      //   var totalFeeCost = parseFloat($scope.convertDisplayedValue($scope.totalCost));

      //   var required = [coin, address, saleAmount, saleBlocks, salePricePerCoin, minersFee, buyersFee, balance, btcbalance, $scope.saleForm.$valid];

      //   var error = 'Please ';
      //   if ($scope.saleForm.$valid == false) {
      //     error += 'make sure all fields are completely filled, ';
      //   }
      //   if ( $scope.isCancel != true && coin == 'BTC') {
      //     error += 'make sure your sale is for MSC or TMSC, ';
      //   }
      //   if( $scope.isCancel != true && ((coin == 'MSC') || (coin == 'TMSC')) ) {
      //     if (saleAmount < nonZeroValue)
      //       error += 'make sure your send amount is non-zero, ';
      //     if (buyersFee < minerMinimum)
      //       error += 'make sure your buyers fee entry is at least 0.0001 BTC, ';
      //     if (minersFee < minerMinimum)
      //       error += 'make sure your fee entry is at least 0.0001 BTC, ';
      //     if ((saleAmount <= balance) == false)
      //       error += 'make sure you aren\'t putting more coins up for sale than you own, ';
      //     if ((totalFeeCost <= btcbalance) == false)
      //       error += 'make sure you have enough Bitcoin to cover your fees, ';

      //     if (saleBlocks < 1)
      //       error += 'make sure your block timeframe is at least 1, ';
      //   }
      //   if ($scope.isCancel == true && (((cancelFees + minersFee) <= btcbalance) == false) )
      //     error += 'make sure you have enough Bitcoin to cover your transaction fees, ';
      //   if (error.length < 8) {
      //     $scope.$parent.showErrors = false;

      //     // open modal
      //     var modalInstance = $modal.open({
      //       templateUrl: $scope.isCancel == true ? '/partials/wallet_cancel_modal.html' : '/partials/wallet_sale_modal.html',
      //       controller: function($scope, $modalInstance, $rootScope, data, prepareSaleTransaction, getUnsignedSaleTransaction, convertSatoshiToDisplayedValue, getDisplayedAbbreviation) {
      //         $scope.sendSuccess = false, $scope.sendError = false, $scope.waiting = false, $scope.privKeyPass = {};
      //         $scope.convertSatoshiToDisplayedValue=convertSatoshiToDisplayedValue,
      //         $scope.getDisplayedAbbreviation=getDisplayedAbbreviation,
      //         $scope.saleAmount=data.amt,
      //         $scope.buyersFee=data.buyersfee,
      //         $scope.selectedCoin=data.selectedCoin,
      //         $scope.salePricePerCoin= data.price,
      //         $scope.saleBlocks = data.blocks;

      //         $scope.ok = function() {
      //           $scope.clicked = true;
      //           $scope.waiting = true;

      //           prepareSaleTransaction(data.seller, data.amt, data.price,
      //           data.buyersfee, data.fee, data.blocks, data.currency, $scope.privKeyPass, $scope);
      //         };
      //         $scope.cancel = function () {
      //           $modalInstance.dismiss('cancel');
      //         };
      //       },
      //       resolve: {
      //         data: function() {
      //           return {
      //             seller: address,
      //             amt: saleAmount,
      //             price: salePricePerCoin,
      //             buyersfee: buyersFee,
      //             fee: minersFee,
      //             blocks: saleBlocks,
      //             currency: coin,
      //             selectedCoin: $scope.selectedCoin,
      //             saleBlocks: saleBlocks
      //           };
      //         },
      //         prepareSaleTransaction: function() {
      //           return prepareSaleTransaction;
      //         },
      //         getUnsignedSaleTransaction: function() {
      //           return getUnsignedSaleTransaction;
      //         },
      //         pushSignedTransaction: function() {
      //           return walletTransactionService.pushSignedTransaction;
      //         },
      //         convertSatoshiToDisplayedValue: function() {
      //           return $scope.convertSatoshiToDisplayedValue;
      //         },
      //         getDisplayedAbbreviation: function() {
      //           return $scope.getDisplayedAbbreviation;
      //         }
      //       }
      //     });

      //     modalInstance.result.then(function() {
      //       if ($scope.isCancel)
      //         $scope.$parent.$parent.$parent.cancelTrig = null;
      //     }, function() {
      //       if ($scope.isCancel)
      //         $scope.$parent.$parent.$parent.cancelTrig = null;
      //     });

      //   } else {
      //     error += 'and try again.';
      //     $scope.error = error;
      //     $scope.$parent.showErrors = true;
      //   }
      // };
    }])

<|endoftext|>


<commit_before>/* global describe, it, expect, before */
/* jshint camelcase: false */

var chai = require('chai')
  , token = require('../../lib/middleware/token')
  , Server = require('../../lib/server');

describe('token', function() {

  var server = new Server();
  server.exchange('authorization_code', function(req, res, next) {
    if (req.body.code !== 'abc123') { return done(new Error('incorrect req.body argument')); }
    var json = JSON.stringify({ token_type: 'bearer', access_token: 'aaa-111-ccc' });
    return res.end(json);
  });
  server.exchange('error', function(req, res, next) {
    next(new Error('something went wrong'));
  });

  it('should be named token', function() {
    expect(token(server).name).to.equal('token');
  });

  it('should throw if constructed without a server argument', function() {
    expect(function() {
      token();
    }).to.throw(TypeError, 'oauth2orize.token middleware requires a server argument');
  });

  describe('handling a request for an access token', function() {
    var response;

    before(function(done) {
      chai.connect.use(token(server))
        .req(function(req) {
          req.body = { grant_type: 'authorization_code', code: 'abc123' };
        })
        .end(function(res) {
          response = res;
          done();
        })
        .dispatch();
    });

    it('should respond', function() {
      expect(response.body).to.equal('{"token_type":"bearer","access_token":"aaa-111-ccc"}');
    });
  });

  describe('handling a request for an access token with unsupported grant type', function() {
    var err;

    before(function(done) {
      chai.connect.use(token(server))
        .req(function(req) {
          req.body = { grant_type: 'foo', code: 'abc123' };
        })
        .next(function(e) {
          err = e;
          done();
        })
        .dispatch();
    });

    it('should error', function() {
      expect(err).to.be.an.instanceOf(Error);
      expect(err.constructor.name).to.equal('TokenError');
      expect(err.message).to.equal('Unsupported grant type: foo');
      expect(err.code).to.equal('unsupported_grant_type');
    });
  });

  describe('encountering an error while exchanging grant', function() {
    var err;

    before(function(done) {
      chai.connect.use(token(server))
        .req(function(req) {
          req.body = { grant_type: 'error', code: 'abc123' };
        })
        .next(function(e) {
          err = e;
          done();
        })
        .dispatch();
    });

    it('should error', function() {
      expect(err).to.be.an.instanceOf(Error);
      expect(err.message).to.equal('something went wrong');
    });
  });

});
<commit_msg>Clarify test cases.<commit_after>/* global describe, it, expect, before */
/* jshint camelcase: false */

var chai = require('chai')
  , token = require('../../lib/middleware/token')
  , Server = require('../../lib/server');

describe('token', function() {

  it('should be named token', function() {
    var server = new Server();
    expect(token(server).name).to.equal('token');
  });

  it('should throw if constructed without a server argument', function() {
    expect(function() {
      token();
    }).to.throw(TypeError, 'oauth2orize.token middleware requires a server argument');
  });

  describe('exchanging a grant for an access token', function() {
    var server = new Server();

    server.exchange('authorization_code', function(req, res, next) {
      if (req.body.code !== 'abc123') { return done(new Error('incorrect req.body argument')); }
      var json = JSON.stringify({ token_type: 'bearer', access_token: 'aaa-111-ccc' });
      return res.end(json);
    });

    server.exchange('fubar', function(req, res, next) {
      next(new Error('something went wrong'));
    });

    describe('handling a request with supported grant', function() {
      var response;

      before(function(done) {
        chai.connect.use(token(server))
          .req(function(req) {
            req.body = { grant_type: 'authorization_code', code: 'abc123' };
          })
          .end(function(res) {
            response = res;
            done();
          })
          .dispatch();
      });

      it('should respond', function() {
        expect(response.body).to.equal('{"token_type":"bearer","access_token":"aaa-111-ccc"}');
      });
    });

    describe('handling a request with unsupported grant type', function() {
      var err;

      before(function(done) {
        chai.connect.use(token(server))
          .req(function(req) {
            req.body = { grant_type: 'foo', code: 'abc123' };
          })
          .next(function(e) {
            err = e;
            done();
          })
          .dispatch();
      });

      it('should error', function() {
        expect(err).to.be.an.instanceOf(Error);
        expect(err.constructor.name).to.equal('TokenError');
        expect(err.message).to.equal('Unsupported grant type: foo');
        expect(err.code).to.equal('unsupported_grant_type');
      });
    });

    describe('encountering an error while exchanging grant', function() {
      var err;

      before(function(done) {
        chai.connect.use(token(server))
          .req(function(req) {
            req.body = { grant_type: 'fubar', code: 'abc123' };
          })
          .next(function(e) {
            err = e;
            done();
          })
          .dispatch();
      });

      it('should error', function() {
        expect(err).to.be.an.instanceOf(Error);
        expect(err.message).to.equal('something went wrong');
      });
    });

  });

});
<|endoftext|>


<commit_before>var gulp = require('gulp');
var bump = require('gulp-bump');
var concat = require('gulp-concat');
var less = require('gulp-less');
var cssmin = require('gulp-cssmin');
var rename = require('gulp-rename');
var header = require('gulp-header');
var handlebars = require('gulp-handlebars');
var wrap = require('gulp-wrap');
var declare = require('gulp-declare');
var jsValidate = require('gulp-jsvalidate');
var uglify = require('gulp-uglify');
var del = require('del');
var runSequence = require('run-sequence');

var pkg = require('./package.json');
var banner = ['/*!',
  ' * PJAX Table v<%= pkg.version %> (<%= pkg.homepage %>)',
  ' * Copyright ' + (new Date()).getFullYear(),
  ' * <%= pkg.author %>',
  ' */\n'
].join('\n');

var output_names = {
  standalone_vendor_js: 'standalone_vendor.js',
  less: 'pjax_table.css',
  lessmin: 'pjax_table.min.css',
  js: 'pjax_table.js'
};

var paths = {
  json: [
    './bower.json',
    './package.json'
  ],
  js: [
    './src/js/table.js',
    './src/js/search.js'
  ],
  standalone_vendor_css: [
    './bower_components/fontawesome/css/font-awesome.css'
  ],
  standalone_vendor_fonts: [
    './bower_components/fontawesome/fonts/*'
  ],
  standalone_vendor_js: [
    './bower_components/jquery/dist/jquery.js',
    './bower_components/jquery-pjax/jquery.pjax.js',
    './bower_components/spin.js/spin.js',
    './bower_components/spin.js/jquery.spin.js',
    './bower_components/chance/chance.js',
    './bower_components/handlebars/handlebars.runtime.js'
  ],
  all_less: ['./src/less/**/*.less'],
  less: ['./src/less/table.less'],
  templates: ['./src/templates/*.hbs'],
};

gulp.task('clean', function(cb) {
  del(['dist/**/*', 'standalone/js/vendor/*', 'standalone/js/templates.js'], cb);
});

gulp.task('bump-patch', function(){ return gulp.src(paths.json).pipe(bump()).pipe(gulp.dest('./')); });
gulp.task('bump-minor', function(){ return gulp.src(paths.json).pipe(bump({ type: 'minor' })).pipe(gulp.dest('./')); });
gulp.task('bump-major', function(){ return gulp.src(paths.json).pipe(bump({ type: 'major' })).pipe(gulp.dest('./')); });

gulp.task('templates', function(){
  gulp.src(paths.templates)
    .pipe(handlebars())
    .pipe(wrap('Handlebars.template(<%= contents %>)'))
    .pipe(declare({
      namespace: 'UI.templates',
      noRedeclare: true, // Avoid duplicate declarations
    }))
    .pipe(concat('templates.js'))
    .pipe(gulp.dest('./standalone/js'));
});

gulp.task('standalone_vendor_js', function() {
  return gulp.src(paths.standalone_vendor_js)
    .pipe(concat(output_names.standalone_vendor_js))
    .pipe(gulp.dest('./standalone/js/vendor'));
});

gulp.task('standalone_vendor_css', function() {
  return gulp.src(paths.standalone_vendor_css)
    .pipe(gulp.dest('./standalone/css'));
});

gulp.task('standalone_vendor_fonts', function() {
  return gulp.src(paths.standalone_vendor_fonts)
    .pipe(gulp.dest('./standalone/fonts'));
});

gulp.task('js', function() {
  return gulp.src(paths.js)
    .pipe(jsValidate())
    .pipe(concat(output_names.js))
    .pipe(gulp.dest('./dist/js'));
});

gulp.task('js_min', function() {
  return gulp.src(paths.js)
    .pipe(jsValidate())
    .pipe(concat(output_names.js))
    .pipe(uglify({ preserveComments: 'some' }))
    .pipe(header(banner, { pkg: pkg }))
    .pipe(rename({ suffix: '.min' }))
    .pipe(gulp.dest('./dist/js'));
});

gulp.task('less', function() {
  return gulp.src(paths.less)
    .pipe(less({ strictMath: true }))
    .pipe(header(banner, { pkg: pkg }))
    .pipe(rename(output_names.less))
    .pipe(gulp.dest('./dist/css'));
});

gulp.task('lessmin', function() {
  return gulp.src(paths.less)
    .pipe(less({ strictMath: true }))
    .pipe(cssmin({ keepSpecialComments: 1 }))
    .pipe(header(banner, { pkg: pkg }))
    .pipe(rename(output_names.lessmin))
    .pipe(gulp.dest('./dist/css'));
});

gulp.task('less_copy', function() {
  return gulp.src(paths.all_less)
    .pipe(gulp.dest('./dist/less'));
});

gulp.task('default', function(callback){
  runSequence('clean', [
    'js',
    'js_min',
    'less',
    'lessmin',
    'less_copy',
    'templates',
    'standalone_vendor_js',
    'standalone_vendor_css',
    'standalone_vendor_fonts'
  ], callback);
});<commit_msg>update gulp build with browserify<commit_after>var gulp = require('gulp');

// CSS Build
var less = require('gulp-less');
var cssmin = require('gulp-cssmin');

// JS Build
var watchify = require('watchify');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
var jshint = require('gulp-jshint');

// Utils
var gutil = require('gulp-util');
var del = require('del');
var runSequence = require('run-sequence');
var assign = require('lodash.assign');

// Output
var rename = require('gulp-rename');
var header = require('gulp-header');

// Standalone Templates
var handlebars = require('gulp-handlebars');
var wrap = require('gulp-wrap');
var declare = require('gulp-declare');
var concat = require('gulp-concat');

// Versioning
var bump = require('gulp-bump');

// Configuration
var pkg = require('./package.json');
var banner = ['/*!',
  ' * PJAX Table v<%= pkg.version %> (<%= pkg.homepage %>)',
  ' * Copyright ' + (new Date()).getFullYear(),
  ' * <%= pkg.author %>',
  ' */\n'
].join('\n');

var output_names = {
  standalone_vendor_js: 'standalone_vendor.js',
  less: 'pjax_table.css',
  lessmin: 'pjax_table.min.css',
  js: 'pjax_table.js'
};

var paths = {
  json: [
    './bower.json',
    './package.json'
  ],
  js: [
    './src/js/pjax_table.js',
    './src/js/external_plugins/search_plugin.js',
    './src/js/cell_plugins/cell_plugin_mixin.js',
    './src/js/cell_plugins/ajax_mixin.js'
  ],
  standalone_vendor_css: [
    './bower_components/fontawesome/css/font-awesome.css'
  ],
  standalone_vendor_fonts: [
    './bower_components/fontawesome/fonts/*'
  ],
  standalone_vendor_js: [
    './bower_components/jquery/dist/jquery.js',
    './bower_components/jquery-pjax/jquery.pjax.js',
    './bower_components/spin.js/spin.js',
    './bower_components/spin.js/jquery.spin.js',
    './bower_components/chance/chance.js',
    './bower_components/handlebars/handlebars.runtime.js'
  ],
  all_less: ['./src/less/**/*.less'],
  less: ['./src/less/table.less'],
  templates: ['./src/templates/*.hbs'],
};

// add custom browserify options here
var customOpts = {
  entries: paths.js,
  standalone: 'PjaxTable'
};
var dev_opts = assign({ debug: true }, watchify.args, customOpts);
var dev_b = watchify(browserify(dev_opts));

var dist_opts = assign({}, watchify.args, customOpts);
var dist_b = watchify(browserify(dist_opts));

gulp.task('clean', function(cb) {
  del(['dist/**/*', 'standalone/js/vendor/*', 'standalone/js/templates.js'], cb);
});

gulp.task('bump-patch', function(){ return gulp.src(paths.json).pipe(bump()).pipe(gulp.dest('./')); });
gulp.task('bump-minor', function(){ return gulp.src(paths.json).pipe(bump({ type: 'minor' })).pipe(gulp.dest('./')); });
gulp.task('bump-major', function(){ return gulp.src(paths.json).pipe(bump({ type: 'major' })).pipe(gulp.dest('./')); });

gulp.task('templates', function(){
  gulp.src(paths.templates)
    .pipe(handlebars())
    .pipe(wrap('Handlebars.template(<%= contents %>)'))
    .pipe(declare({
      namespace: 'UI.templates',
      noRedeclare: true, // Avoid duplicate declarations
    }))
    .pipe(concat('templates.js'))
    .pipe(gulp.dest('./standalone/js'));
});

gulp.task('standalone_vendor_js', function() {
  return gulp.src(paths.standalone_vendor_js)
    .pipe(concat(output_names.standalone_vendor_js))
    .pipe(gulp.dest('./standalone/js/vendor'));
});

gulp.task('standalone_vendor_css', function() {
  return gulp.src(paths.standalone_vendor_css)
    .pipe(gulp.dest('./standalone/css'));
});

gulp.task('standalone_vendor_fonts', function() {
  return gulp.src(paths.standalone_vendor_fonts)
    .pipe(gulp.dest('./standalone/fonts'));
});

gulp.task('js', function() {
  return dev_b.bundle()
    .on('error', gutil.log.bind(gutil, 'Browserify Error'))
    .pipe(source('pjax_table.js'))
    .pipe(buffer())
    .pipe(gulp.dest('./dist/js'));
});

gulp.task('js_min', function() {
    return dist_b.bundle()
      .on('error', gutil.log.bind(gutil, 'Browserify Error'))
      .pipe(source('pjax_table.js'))
      .pipe(buffer()) // for uglify
      .pipe(uglify({ preserveComments: 'some' }))
      .pipe(header(banner, { pkg: pkg }))
      .pipe(rename({ suffix: '.min' }))
      .pipe(gulp.dest('./dist/js'));
});

gulp.task('less', function() {
  return gulp.src(paths.less)
    .pipe(less({ strictMath: true }))
    .pipe(header(banner, { pkg: pkg }))
    .pipe(rename(output_names.less))
    .pipe(gulp.dest('./dist/css'));
});

gulp.task('lessmin', function() {
  return gulp.src(paths.less)
    .pipe(less({ strictMath: true }))
    .pipe(cssmin({ keepSpecialComments: 1 }))
    .pipe(header(banner, { pkg: pkg }))
    .pipe(rename(output_names.lessmin))
    .pipe(gulp.dest('./dist/css'));
});

gulp.task('less_copy', function() {
  return gulp.src(paths.all_less)
    .pipe(gulp.dest('./dist/less'));
});

gulp.task('default', function(callback){
  runSequence('clean', 'js', 'js_min', 'less', 'lessmin', [
    'less_copy',
    'templates',
    'standalone_vendor_js',
    'standalone_vendor_css',
    'standalone_vendor_fonts'
  ], callback);
});
<|endoftext|>


<commit_before>var pkg     = require('./package.json');
var fs      = require('fs');

var gulp    = require('gulp');
var jshint  = require('gulp-jshint');
var uglify  = require('gulp-uglify');
var concat  = require('gulp-concat');
var replace = require('gulp-replace');

gulp.task('lint', function() {

  return gulp.src([
      './gulpfile.js',
      './src/*.js'
     ])
    .pipe(jshint())
    .pipe(jshint.reporter('default'));

});

gulp.task('build', function() {

  return fs.readFile('./src/devizr.tests.js', 'utf8', function(err, tests) {

    if (err) {
      throw err;
    }

    // Adding indent to all lines in test file
		var lines_indent = [];
    var lines = tests.split('\n');
    lines.forEach(function(line){
      lines_indent.push('  ' + line);
    });
    tests = lines_indent.join('\n');

    return gulp.src('./src/devizr.app.js')
      .pipe(replace(/\/\/{{TESTS}}/i, tests))
      .pipe(concat('devizr.js'))
      .pipe(gulp.dest('dest'))
      .pipe(uglify({ preserveComments: 'some' }))
      .pipe(replace(/##VERSION##/i, pkg.version))
      .pipe(replace(/##YEAR##/i, new Date().getFullYear()))
      .pipe(concat('devizr.min.js'))
      .pipe(gulp.dest('dest'));

  });

});

gulp.task('default', [ 'lint', 'build']);
<commit_msg>some cleanup<commit_after>var pkg     = require('./package.json');
var fs      = require('fs');

var gulp    = require('gulp');
var jshint  = require('gulp-jshint');
var uglify  = require('gulp-uglify');
var concat  = require('gulp-concat');
var replace = require('gulp-replace');

gulp.task('lint', function() {

  return gulp.src([
      './gulpfile.js',
      './src/*.js'
     ])
    .pipe(jshint())
    .pipe(jshint.reporter('default'));

});

gulp.task('build', function() {

  return fs.readFile('./src/devizr.tests.js', 'utf8', function(err, tests) {

    if (err) {
      throw err;
    }

    // Adding indent to all lines in test file
    var lines_indent = [];
    var lines = tests.split('\n');
    lines.forEach(function(line){
      lines_indent.push('  ' + line);
    });
    tests = lines_indent.join('\n');

    return gulp.src('./src/devizr.app.js')
      .pipe(replace(/\/\/{{TESTS}}/i, tests))
      .pipe(concat('devizr.js'))
      .pipe(gulp.dest('dest'))
      .pipe(uglify({ preserveComments: 'some' }))
      .pipe(replace(/##VERSION##/i, pkg.version))
      .pipe(replace(/##YEAR##/i, new Date().getFullYear()))
      .pipe(concat('devizr.min.js'))
      .pipe(gulp.dest('dest'));

  });

});

gulp.task('default', [ 'lint', 'build']);
<|endoftext|>


<commit_before>/**
 * Js-coding-standards
 *
 * @author      Robert Rossmann <rr.rossmann@me.com>
 * @copyright   2016 STRV
 * @license     http://choosealicense.com/licenses/bsd-3-clause  BSD-3-Clause License
 */

'use strict'

module.exports = {
  rules: {
    // enforce line breaks after opening and before closing array brackets
    // Unused, does not enforce newlines after each array element, resulting in weird-looking code
    'array-bracket-newline': 0,

    // Treat var as Block Scoped
    // Unused in favour of `no-var` rule. Front-end could have some interest in this rule.
    'block-scoped-var': 0,

    // Enforce or disallow capitalization of the first letter of a comment
    // Unused, too restrictive.
    'capitalized-comments': 0,

    // Limit Cyclomatic Complexity
    // Let the developer decide if what they write expresses their intent well enough, while
    // maintaining readability.
    complexity: 0,

    // Blacklist certain identifiers
    // Unused, too restrictive.
    'id-blacklist': 0,

    // Enforce a maximum file length
    // Unused, no one cares.
    'max-lines': 0,

    // Disallow Bitwise Operators
    // Unused, too restrictive.
    'no-bitwise': 0,

    // Disallow arrow functions where they could be confused with comparisons
    'no-confusing-arrow': 0,

    // Disallow Regexs That Look Like Division
    // Unused, `return /=foo/` does not really look like a division to me.
    'no-div-regex': 0,

    // Disallow Null Comparisons
    // Unused in favour of eqeqeq rule requiring all comparisons to be strict.
    'no-eq-null': 0,

    // Disallow var and Named Functions in Global Scope
    // This rule disallows var and named function declarations at the top-level script scope. This
    // does not apply to ES and CommonJS modules since they have a module scope.
    // Unused, front-end specific.
    'no-implicit-globals': 0,

    // Disallow this keywords outside of classes or class-like objects
    // Unused, too restrictive.
    'no-invalid-this': 0,

    // Disallow Use of Chained Assignment Expressions
    // Unused, seems handy.
    'no-multi-assign': 0,

    // Disallow Multiline Strings
    // Unused, seems handy. This rule should be enabled when pre-ES5 compatibility is required.
    'no-multi-str': 0,

    // Disallow Reassignment of Function Parameters
    // Unused, too restrictive. This is used frequently to "normalise" a function input and define
    // default values (if ES6's function parameter defaults are not available).
    'no-param-reassign': 0,

    // Disallow ++ and --
    // Unused, these operators are quite useful as long as whitespace is used responsibly around
    // them.
    'no-plusplus': 0,

    // Disallow use of the void operator
    // void is quite useful with IIFEs and for discarding return values when using return for
    // short-circuiting.
    'no-void': 0,

    // Require IDs to match a pattern
    // Unused, too restrictive.
    'id-match': 0,

    // Enforce empty lines around comments
    // Unused, too restrictive.
    'lines-around-comment': 0,

    // Enforce position of line comments
    // Unused, too restrictive.
    'line-comment-position': 0,

    // Enforce newlines between operands of ternary expressions
    // Unused, ternaries are usually simple enough that they are OK to be written on a single line.
    'multiline-ternary': 0,

    // Disallow continue
    // Unused, continue seems to be quite useful.
    'no-continue': 0,

    // Disallow specific imports
    // Unused, no use case.
    'no-restricted-imports': 0,

    // Disallow specific modules
    // Unused, no use case.
    'no-restricted-modules': 0,

    // Disallow Ternary Operators
    // You kidding me? Ternaries are great!
    'no-ternary': 0,

    // Enforce placing object properties on separate lines
    // Unused, too restrictive.
    'object-property-newline': 0,

    // Prefer destructuring from arrays and objects
    // Unused, too restrictive.
    'prefer-destructuring': 0,

    // Suggest using Reflect methods where applicable
    // Deprecated, will be removed from ESLint soon
    'prefer-reflect': 0,

    // Require JSDoc comment
    // Unused, not as useful. It's the developers' responsibility to write JSDoc comments when they
    // are relevant/needed. Many times they are not.
    'require-jsdoc': 0,

    // eslint-plugin-react

    // Forbid certain elements
    'react/forbid-elements': 0,

    // Forbid certain propTypes
    // This rule checks all JSX components and verifies that no forbidden propsTypes are used.
    'react/forbid-prop-types': 0,

    // Prevent usage of setState
    'react/no-set-state': 0,

    // Prevent usage of unwrapped JSX strings
    'react/jsx-no-literals': 0,

    // Enforce props alphabetical sorting
    'react/jsx-sort-props': 0,

    // Limit maximum of props on a single line in JSX
    'react/jsx-max-props-per-line': 0,

    // Enforce event handler naming conventions in JSX
    'react/jsx-handler-names': 0,

    // Prevent missing displayName in a React component definition
    'react/display-name': 0,

    // Forbid certain props on Components
    'react/forbid-component-props': 0,

    // Enforce React components to have a shouldComponentUpdate method
    'react/require-optimization': 0,
  },
}
<commit_msg>Update unused rules<commit_after>/**
 * Js-coding-standards
 *
 * @author      Robert Rossmann <rr.rossmann@me.com>
 * @copyright   2016 STRV
 * @license     http://choosealicense.com/licenses/bsd-3-clause  BSD-3-Clause License
 */

'use strict'

module.exports = {
  rules: {
    // Enforce line breaks between array elements
    // Unused, too restrictive
    'array-element-newline': 0,

    // enforce line breaks after opening and before closing array brackets
    // Unused, does not enforce newlines after each array element, resulting in weird-looking code
    'array-bracket-newline': 0,

    // Treat var as Block Scoped
    // Unused in favour of `no-var` rule. Front-end could have some interest in this rule.
    'block-scoped-var': 0,

    // Enforce or disallow capitalization of the first letter of a comment
    // Unused, too restrictive.
    'capitalized-comments': 0,

    // Limit Cyclomatic Complexity
    // Let the developer decide if what they write expresses their intent well enough, while
    // maintaining readability.
    complexity: 0,

    // Blacklist certain identifiers
    // Unused, too restrictive.
    'id-blacklist': 0,

    // Enforce a maximum file length
    // Unused, no one cares.
    'max-lines': 0,

    // Disallow Bitwise Operators
    // Unused, too restrictive.
    'no-bitwise': 0,

    // Disallow arrow functions where they could be confused with comparisons
    // Unused, not really confusing enough.
    'no-confusing-arrow': 0,

    // Disallow Regexs That Look Like Division
    // Unused, `return /=foo/` does not really look like a division to me.
    'no-div-regex': 0,

    // Disallow Null Comparisons
    // Unused in favour of eqeqeq rule requiring all comparisons to be strict.
    'no-eq-null': 0,

    // Disallow var and Named Functions in Global Scope
    // This rule disallows var and named function declarations at the top-level script scope. This
    // does not apply to ES and CommonJS modules since they have a module scope.
    // Unused, front-end specific.
    'no-implicit-globals': 0,

    // Disallow this keywords outside of classes or class-like objects
    // Unused, too restrictive.
    'no-invalid-this': 0,

    // Disallow Use of Chained Assignment Expressions
    // Unused, seems handy.
    'no-multi-assign': 0,

    // Disallow Multiline Strings
    // Unused, seems handy. This rule should be enabled when pre-ES5 compatibility is required.
    'no-multi-str': 0,

    // Disallow Reassignment of Function Parameters
    // Unused, too restrictive. This is used frequently to "normalise" a function input and define
    // default values (if ES6's function parameter defaults are not available).
    'no-param-reassign': 0,

    // Disallow ++ and --
    // Unused, these operators are quite useful as long as whitespace is used responsibly around
    // them.
    'no-plusplus': 0,

    // Disallow use of the void operator
    // void is quite useful with IIFEs and for discarding return values when using return for
    // short-circuiting.
    'no-void': 0,

    // Require IDs to match a pattern
    // Unused, too restrictive.
    'id-match': 0,

    // Enforce empty lines around comments
    // Unused, too restrictive.
    'lines-around-comment': 0,

    // Enforce position of line comments
    // Unused, too restrictive.
    'line-comment-position': 0,

    // Enforce newlines between operands of ternary expressions
    // Unused, ternaries are usually simple enough that they are OK to be written on a single line.
    'multiline-ternary': 0,

    // Disallow continue
    // Unused, continue seems to be quite useful.
    'no-continue': 0,

    // Disallow specific imports
    // Unused, no use case.
    'no-restricted-imports': 0,

    // Disallow specific modules
    // Unused, no use case.
    'no-restricted-modules': 0,

    // Disallow Ternary Operators
    // You kidding me? Ternaries are great!
    'no-ternary': 0,

    // Enforce placing object properties on separate lines
    // Unused, too restrictive.
    'object-property-newline': 0,

    // Prefer destructuring from arrays and objects
    // Unused, too restrictive.
    'prefer-destructuring': 0,

    // Suggest using Reflect methods where applicable
    // Deprecated, will be removed from ESLint soon
    'prefer-reflect': 0,

    // Require JSDoc comment
    // Unused, not as useful. It's the developers' responsibility to write JSDoc comments when they
    // are relevant/needed. Many times they are not.
    'require-jsdoc': 0,

    // eslint-plugin-react

    // Forbid certain elements
    'react/forbid-elements': 0,

    // Forbid certain propTypes
    // This rule checks all JSX components and verifies that no forbidden propsTypes are used.
    'react/forbid-prop-types': 0,

    // Prevent usage of setState
    'react/no-set-state': 0,

    // Prevent usage of unwrapped JSX strings
    'react/jsx-no-literals': 0,

    // Enforce props alphabetical sorting
    'react/jsx-sort-props': 0,

    // Limit maximum of props on a single line in JSX
    'react/jsx-max-props-per-line': 0,

    // Enforce event handler naming conventions in JSX
    'react/jsx-handler-names': 0,

    // Prevent missing displayName in a React component definition
    'react/display-name': 0,

    // Forbid certain props on Components
    'react/forbid-component-props': 0,

    // Enforce React components to have a shouldComponentUpdate method
    'react/require-optimization': 0,
  },
}
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var path = require('path');
var gulp = require('gulp');
var sass = require('gulp-sass');
var cached = require('gulp-cached');
var remember = require('gulp-remember');
var jas = require('gulp-jasmine');
var jshint = require('gulp-jshint');
var to5 = require('gulp-6to5');
var react = require('gulp-react');
var browserify = require('browserify');
var notify = require('gulp-notify');
var plumber = require('gulp-plumber');
var source = require('vinyl-source-stream');
var nodemon = require('gulp-nodemon');

// var refresh = require('gulp-livereload');
// var livereload = require('tiny-lr');
// var server = livereload();

function pathItem(name) {
	return function(children) {
		var items = [ name ];
		if (this instanceof Function) { items.unshift(this()); }
		if (children) { items.push(children); }
		return path.join.apply(path, items);
	};
}

var PATHS = pathItem('.');
PATHS.bin = pathItem('bin');
PATHS.client = pathItem('client');
PATHS.server = pathItem('server');
PATHS.build = pathItem('build');
PATHS.build.server = pathItem('server');
PATHS.build.client = pathItem('client');
PATHS.client.scssLib = pathItem('scss_lib');
PATHS.client.components = pathItem('components');

PATHS.client.js = pathItem('js');
PATHS.server = pathItem('server');
PATHS.specs = pathItem('specs');
PATHS.docs = pathItem('docs');
PATHS.docs.libs = pathItem('libs');
PATHS.specs = pathItem('specs');
PATHS.specs.matchers = pathItem('matchers');

/* -- Actions -- */

/** BUild all js transpiling from ES6 to ES5 */
function buildJs() {
  return gulp.src([PATHS.server('**/*.js')], { base: PATHS.server() })
    .pipe(cached('js'))
    .pipe(remember('js'))
    .pipe(to5({ sourceRoot: PATHS.server() }))
    .pipe(gulp.dest(PATHS.build.server()));
}

/** Performs all unit tests */
function testUnit() {

  return gulp.src([
      // './node_modules/gulp-6to5/node_modules/6to5/register.js',
      PATHS.specs('env.js'),
      PATHS.specs.matchers('**/*.js'),
      PATHS.build.server('**/*.spec.js'),
      PATHS.client('**/*.spec.js')
    ]).pipe(jas({includeStackTrace: true, verbose: true}));

}

function cleanCache() {
  // Clear all caches to perform a full actions
  cached.caches = {};
}

/* --  Build tasks -- */

gulp.task('build:js', buildJs);

// Special task to order properly tasks
gulp.task('watch:js:test', ['build:js'], testUnit);

gulp.task('watch:js', function() {
  gulp.watch([
      PATHS.server('**/*.js'),
      PATHS.specs('**/*.js')
    ], ['build:js', 'watch:js:test']);
});

gulp.task('build:sass', function () {
  return gulp.src([
        PATHS.client.components('*.scss'),
        PATHS.client.scssLib('**/*.scss')
      ])
  		.pipe(sass({
  			includePaths: [ PATHS.client.scssLib() ]
  		}))
      .pipe(gulp.dest(PATHS.build.client('css')));
});

gulp.task('build:jsx', function() {
  return gulp.src(PATHS.client.js('components/**/*.jsx'))
      .pipe(plumber({errorHandler: notify.onError("Build:jsx : <%= error.message %>")}))
      .pipe(react({harmony: true}))
      .pipe(plumber.stop())
      .pipe(gulp.dest(PATHS.client.js('compiled')));
});

gulp.task('build:browserify', ['test:lint', 'build:jsx'], function(){
  var b = browserify('./' + PATHS.client.js('compiled/main.js'))
  var stream = b.bundle()
    .pipe(source('main.js')) // the output filename
    .pipe(gulp.dest(PATHS.build.client('js'))); // the output directory
  return stream;
});

gulp.task('build', ['build:js', 'build:sass', 'build:browserify']);

/* -- Watcher -- */
gulp.task('watch:jsx', function() {
  gulp.watch(PATHS.client.js('components/**/*.jsx'), ['build:browserify']);
});

gulp.task('watch:sass', function() {
  gulp.watch(PATHS.client.components('*.scss'), ['build:sass']);
});

gulp.task('watch', ['watch:js', 'watch:jsx', 'watch:sass']);

//watch + server

gulp.task('develop', ['watch', 'server']);

/* -- Test task -- */

gulp.task('test:unit', ['server'], testUnit);

gulp.task('test:lint', ['build:jsx'], function() {
  return gulp.src([
  		PATHS.bin('*.js'),
  		PATHS.client('**/*.js'),
  		PATHS.server('**/*.js')
  	]).pipe(plumber({errorHandler: notify.onError("test:lint : <%= error.message %>")}))
    .pipe(jshint())
    .pipe(jshint.reporter('default'))
    .pipe(jshint.reporter('fail'))
    .pipe(plumber.stop());
});

gulp.task('test', ['test:unit', 'test:lint']);

/* -- Live reload && watchs-- */

// gulp.task('css', function () {
//   gulp.src('app/**/*.css').pipe(refresh(server));
// });

// gulp.task('js', function () {
//   gulp.src('app/**/*.js').pipe(refresh(server));
// });

// gulp.task('livereload-server', function () {
//   server.listen(35729, function (err) {
//     if (err) { return console.log(err); }
//   });
// });

// gulp.task('serve', function () {
//   gulp.run('livereload-server');

//   gulp.watch('app/**/*.css', function (event) {
//     gulp.run('css');
//   });

//   gulp.watch('app/**/*.js', function (event) {
//     gulp.run('js');
//   });
// });

/* -- Documentation -- */

gulp.task('docs:install', function() {
	var request = require('request');

	// Fetch the master version of mermaid for documentation
	return request('https://raw.githubusercontent.com/knsv/mermaid/master/dist/mermaid.full.min.js')
		.pipe(fs.createWriteStream(PATHS.docs.libs('mermaid.js')));
});

gulp.task('docs:serve', function() {
	// Somehow provide a way to navigate through documentation
});

gulp.task('docs', ['docs:install', 'docs:serve']);

//default gulp
gulp.task('default', [ 'build', 'test', 'docs' ]);

/* -- Launch server -- */
gulp.task('server', function(done) {
  var isDone = false;

  nodemon({ script: 'bin/catane', ignore: [PATHS.docs('libs/*')], stderr: false, stdout: false})
    .on('start', function() {
      if(!isDone) {
        isDone = true;
        done();
      }
    })
    .on('crash', function() {
      console.log('Server already launched, just failing');
    });

});

gulp.task('clean:cache', cleanCache);

gulp.task('clean', [ 'clean:cache' ]);

/**
 * Master task to rebuild all the project
 * Named in hommage to 'Legend of Korra'
 * This will perform all actions to build and test the application.
 */
gulp.task('do_the_thing', function() {
  var runSequence = require('run-sequence');
  runSequence('clean', 'build', 'test', 'docs:install', function() {
    console.log('All things are done Sir :)');
  });
});
<commit_msg>Exclude docs from watch.<commit_after>'use strict';

var fs = require('fs');
var path = require('path');
var gulp = require('gulp');
var sass = require('gulp-sass');
var cached = require('gulp-cached');
var remember = require('gulp-remember');
var jas = require('gulp-jasmine');
var jshint = require('gulp-jshint');
var to5 = require('gulp-6to5');
var react = require('gulp-react');
var browserify = require('browserify');
var notify = require('gulp-notify');
var plumber = require('gulp-plumber');
var source = require('vinyl-source-stream');
var nodemon = require('gulp-nodemon');

// var refresh = require('gulp-livereload');
// var livereload = require('tiny-lr');
// var server = livereload();

function pathItem(name) {
	return function(children) {
		var items = [ name ];
		if (this instanceof Function) { items.unshift(this()); }
		if (children) { items.push(children); }
		return path.join.apply(path, items);
	};
}

var PATHS = pathItem('.');
PATHS.bin = pathItem('bin');
PATHS.client = pathItem('client');
PATHS.server = pathItem('server');
PATHS.build = pathItem('build');
PATHS.build.server = pathItem('server');
PATHS.build.client = pathItem('client');
PATHS.client.scssLib = pathItem('scss_lib');
PATHS.client.components = pathItem('components');

PATHS.client.js = pathItem('js');
PATHS.server = pathItem('server');
PATHS.specs = pathItem('specs');
PATHS.docs = pathItem('docs');
PATHS.docs.libs = pathItem('libs');
PATHS.specs = pathItem('specs');
PATHS.specs.matchers = pathItem('matchers');

/* -- Actions -- */

/** BUild all js transpiling from ES6 to ES5 */
function buildJs() {
  return gulp.src([PATHS.server('**/*.js')], { base: PATHS.server() })
    .pipe(cached('js'))
    .pipe(remember('js'))
    .pipe(to5({ sourceRoot: PATHS.server() }))
    .pipe(gulp.dest(PATHS.build.server()));
}

/** Performs all unit tests */
function testUnit() {

  return gulp.src([
      // './node_modules/gulp-6to5/node_modules/6to5/register.js',
      PATHS.specs('env.js'),
      PATHS.specs.matchers('**/*.js'),
      PATHS.build.server('**/*.spec.js'),
      PATHS.client('**/*.spec.js')
    ]).pipe(jas({includeStackTrace: true, verbose: true}));

}

function cleanCache() {
  // Clear all caches to perform a full actions
  cached.caches = {};
}

/* --  Build tasks -- */

gulp.task('build:js', buildJs);

// Special task to order properly tasks
gulp.task('watch:js:test', ['build:js'], testUnit);

gulp.task('watch:js', function() {
  gulp.watch([
      PATHS.server('**/*.js'),
      PATHS.specs('**/*.js')
    ], ['build:js', 'watch:js:test']);
});

gulp.task('build:sass', function () {
  return gulp.src([
        PATHS.client.components('*.scss'),
        PATHS.client.scssLib('**/*.scss')
      ])
  		.pipe(sass({
  			includePaths: [ PATHS.client.scssLib() ]
  		}))
      .pipe(gulp.dest(PATHS.build.client('css')));
});

gulp.task('build:jsx', function() {
  return gulp.src(PATHS.client.js('components/**/*.jsx'))
      .pipe(plumber({errorHandler: notify.onError("Build:jsx : <%= error.message %>")}))
      .pipe(react({harmony: true}))
      .pipe(plumber.stop())
      .pipe(gulp.dest(PATHS.client.js('compiled')));
});

gulp.task('build:browserify', ['test:lint', 'build:jsx'], function(){
  var b = browserify('./' + PATHS.client.js('compiled/main.js'))
  var stream = b.bundle()
    .pipe(source('main.js')) // the output filename
    .pipe(gulp.dest(PATHS.build.client('js'))); // the output directory
  return stream;
});

gulp.task('build', ['build:js', 'build:sass', 'build:browserify']);

/* -- Watcher -- */
gulp.task('watch:jsx', function() {
  gulp.watch(PATHS.client.js('components/**/*.jsx'), ['build:browserify']);
});

gulp.task('watch:sass', function() {
  gulp.watch(PATHS.client.components('*.scss'), ['build:sass']);
});

gulp.task('watch', ['watch:js', 'watch:jsx', 'watch:sass']);

//watch + server

gulp.task('develop', ['watch', 'server']);

/* -- Test task -- */

gulp.task('test:unit', ['server'], testUnit);

gulp.task('test:lint', ['build:jsx'], function() {
  return gulp.src([
  		PATHS.bin('*.js'),
  		PATHS.client('**/*.js'),
  		PATHS.server('**/*.js')
  	]).pipe(plumber({errorHandler: notify.onError("test:lint : <%= error.message %>")}))
    .pipe(jshint())
    .pipe(jshint.reporter('default'))
    .pipe(jshint.reporter('fail'))
    .pipe(plumber.stop());
});

gulp.task('test', ['test:unit', 'test:lint']);

/* -- Live reload && watchs-- */

// gulp.task('css', function () {
//   gulp.src('app/**/*.css').pipe(refresh(server));
// });

// gulp.task('js', function () {
//   gulp.src('app/**/*.js').pipe(refresh(server));
// });

// gulp.task('livereload-server', function () {
//   server.listen(35729, function (err) {
//     if (err) { return console.log(err); }
//   });
// });

// gulp.task('serve', function () {
//   gulp.run('livereload-server');

//   gulp.watch('app/**/*.css', function (event) {
//     gulp.run('css');
//   });

//   gulp.watch('app/**/*.js', function (event) {
//     gulp.run('js');
//   });
// });

/* -- Documentation -- */

gulp.task('docs:install', function() {
	var request = require('request');

	// Fetch the master version of mermaid for documentation
	return request('https://raw.githubusercontent.com/knsv/mermaid/master/dist/mermaid.full.min.js')
		.pipe(fs.createWriteStream(PATHS.docs.libs('mermaid.js')));
});

gulp.task('docs:serve', function() {
	// Somehow provide a way to navigate through documentation
});

gulp.task('docs', ['docs:install', 'docs:serve']);

//default gulp
gulp.task('default', [ 'build', 'test', 'docs' ]);

/* -- Launch server -- */
gulp.task('server', function(done) {
  var isDone = false;

  nodemon({
    script: 'bin/catane',
    ignore: [
      PATHS.docs('libs/*'),
      PATHS.specs('**/*'),
      PATHS('**/*.spec.js')
    ],
    stderr: false,
    stdout: false
  }).on('start', function() {
      if(!isDone) {
        isDone = true;
        done();
      }
    })
    .on('crash', function() {
      console.log('Server already launched, just failing');
    });

});

gulp.task('clean:cache', cleanCache);

gulp.task('clean', [ 'clean:cache' ]);

/**
 * Master task to rebuild all the project
 * Named in hommage to 'Legend of Korra'
 * This will perform all actions to build and test the application.
 */
gulp.task('do_the_thing', function() {
  var runSequence = require('run-sequence');
  runSequence('clean', 'build', 'test', 'docs:install', function() {
    console.log('All things are done Sir :)');
  });
});
<|endoftext|>


<commit_before>var test = require('../test-tools/test')('“autohide” plugin');
var mockPlugin = require('../test-tools/mockPlugin');
var noop = require('1-liners/noop');

var autohide = require('../../plugins/autohide');

test(
  'Hides the dropdown',
  function(is) {
    is.plan(1);

    // Prepare an unfolded select.
    var mock = mockPlugin(autohide);
    mock.model.state.emit('unfolded', {attributes: {unfolded: ''}});

    // Blur the select.
    mock.model.patch.on('patch', function(patch) {is.equal(
      patch.unfolded,
      undefined,
      'when the select loses focus'
    );});

    mock.view.switchElement.emit('blur');
    mock.model.patch.off('patch');

    // Finnito.
    is.end();
  }
);

test(
  'Prevents the select from losing focus unintentionally',
  function(is) {
    is.plan(1);

    // Prepare an unfolded select.
    var mock = mockPlugin(autohide);

    // Trigger a `change`.
    mock.view.switchElement.focus = function() {is.pass(
      'when the selection is changed'
    );};

    mock.view.dropdownElement.emit('change');
    mock.view.switchElement.focus = noop;

    // Finnito.
    is.end();
  }
);

test.skip(  // TODO
  'Fails gracefully',
  function(is) {
    is.plan(0);
    is.end();
  }
);
<commit_msg>Update tests [#6797]<commit_after>var test = require('../test-tools/test')('“autohide” plugin');
var mockPlugin = require('../test-tools/mockPlugin');
var noop = require('1-liners/noop');

var autohide = require('../../plugins/autohide');

test(
  'Hides the dropdown',
  function(is) {
    is.plan(1);

    // Prepare a mock select.
    var mock = mockPlugin(autohide);

    mock.model.patch.on('patch', function(patch) {is.equal(
      patch.unfolded,
      undefined,
      'when the select loses focus'
    );});

    // Blur the select.
    mock.view.switchElement.emit('blur');

    // Prepare another mock select.
    var anotherMock = mockPlugin(autohide);

    anotherMock.model.patch.on('patch', function() {is.fail(
      'not when the blur was triggered by a click within the dropdown'
    );});

    // Blur the select by clicking in the dropdown.
    anotherMock.view.switchElement.emit('blur');
    anotherMock.view.dropdownElement.emit('mousedown');

    is.timeoutAfter(200);
  }
);

test(
  'Prevents the select from losing focus unintentionally',
  function(is) {
    is.plan(1);

    // Prepare an unfolded select.
    var mock = mockPlugin(autohide);

    mock.view.update.on('focused', function(focused) {is.equal(
      focused.newValue,
      true,
      'when the blur was caused by a click inside the dropdown'
    );});

    // Trigger a `click` within the dropdown.
    mock.view.dropdownElement.emit('click');

    is.timeoutAfter(200);
  }
);

test.skip(  // TODO
  'Fails gracefully',
  function(is) {
    is.plan(0);
    is.end();
  }
);
<|endoftext|>


<commit_before>var gulp = require('gulp');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var watchify = require('watchify');
var gutil = require('gulp-util');
var debug = require('gulp-debug');
var less = require('gulp-less');
var rename = require('gulp-rename');
var sourcemaps = require('gulp-sourcemaps');
var cleanCSS = require('gulp-clean-css');
var babelify = require('babelify');
var uglify = require('gulp-uglify');
var buffer = require('vinyl-buffer');
var gulpif = require('gulp-if');

var args = require('yargs').argv;

var config = {
  gameday: {
    js: {
      src: ['./react/gameday2/gameday2.js'],
      outputDir: './static/compiled/javascript',
      outputFile: 'gameday2.min.js'
    },
    less: {
      src: ['./react/gameday2/gameday2.less'],
      outputDir: './static/compiled/css/',
      outputFile: 'gameday2.min.css',
      watch: ['./react/gameday2/**/*.less']
    }
  },
  apidocs: {
    js: {
      src: ['./react/apidocs/apidocs.js'],
      outputDir: './static/compiled/javascript',
      outputFile: 'apidocs.min.js'
    },
    less: {
      src: ['./react/apidocs/apidocs.less'],
      outputDir: './static/compiled/css/',
      outputFile: 'apidocs.min.css',
      watch: ['./react/apidocs/**/*.less']
    }
  },
  eventwizard: {
    js: {
      src: ['./react/eventwizard/eventwizard.js'],
      outputDir: './static/compiled/javascript',
      outputFile: 'eventwizard.min.js'
    },
    less: {
      src: ['./react/eventwizard/eventwizard.less'],
      outputDir: './static/compiled/css/',
      outputFile: 'eventwizard.min.css',
      watch: ['./react/eventwizard/**/*.less']
    }
  },
  liveevent: {
    js: {
      src: ['./react/liveevent/liveevent.js'],
      outputDir: './static/compiled/javascript',
      outputFile: 'liveevent.min.js'
    }
  }
};

var errorHandler = function(err) {
  gutil.log(err);
  this.emit('end');

  //TODO this should actually bail
  //process.exit(1);
};

function compile(watch, config) {
  if (args.production) {
    process.env.NODE_ENV = 'production';
  }
  var bundler = browserify({
    entries: config.js.src,
    debug: true, // Gives us sourcemapping
    cache: {},
    packageCache: {},
  }).transform('babelify', {
    presets: ['es2015', 'react', 'stage-2']
  });

  function rebundle() {
    bundler.bundle()
      .on('error', errorHandler)
      .pipe(source(config.js.outputFile))
      .pipe(buffer())
      .pipe(sourcemaps.init({loadMaps: true}))
      .pipe(gulpif(args.production, uglify()))
      .on('error', errorHandler)
      .pipe(sourcemaps.write('./'))
      .pipe(debug())
      .pipe(gulp.dest(config.js.outputDir));
  }

  if (watch) {
    var watcher = watchify(bundler);
    watcher.on('update', function() {
      rebundle();
    });
  }

  rebundle();
}

function compileLess(config) {
  gulp.src(config.less.src)
    .pipe(sourcemaps.init())
    .pipe(less())
    .pipe(cleanCSS())
    .pipe(sourcemaps.write())
    .pipe(debug())
    .on('error', errorHandler)
    .pipe(rename(config.less.outputFile))
    .pipe(gulp.dest(config.less.outputDir));
}

gulp.task('apidocs-js', function() {
  return compile(false, config.apidocs);
});

gulp.task('apidocs-js-watch', function() {
  return compile(true, config.apidocs);
});

gulp.task('eventwizard-js', function() {
  return compile(false, config.eventwizard);
});

gulp.task('eventwizard-js-watch', function() {
  return compile(true, config.eventwizard);
});

gulp.task('gameday-js', function() {
  return compile(false, config.gameday);
});

gulp.task('gameday-js-watch', function() {
  return compile(true, config.gameday);
});

gulp.task('liveevent-js', function() {
  return compile(false, config.liveevent);
});

gulp.task('liveevent-js-watch', function() {
  return compile(true, config.liveevent);
});

gulp.task('apidocs-less', function() {
  return compileLess(config.apidocs)
});

gulp.task('gameday-less', function() {
  return compileLess(config.gameday)
});

gulp.task('eventwizard-less', function() {
  return compileLess(config.eventwizard)
});

gulp.task('gameday-less-watch', function() {
  gulp.watch(config.gameday.less.watch, ['gameday-less']);
});

gulp.task('build', ['gameday-js', 'gameday-less',
                    'apidocs-js', 'apidocs-less',
                    'eventwizard-js', 'eventwizard-less',
                    'liveevent-js']);

gulp.task('watch', ['gameday-js-watch', 'gameday-less-watch',
                    'apidocs-js-watch',
                    'eventwizard-js-watch',
                    'liveevent-js-watch']);

gulp.task('default', ['build', 'watch']);
<commit_msg>gulp throws on fail again<commit_after>var gulp = require('gulp');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var watchify = require('watchify');
var gutil = require('gulp-util');
var debug = require('gulp-debug');
var less = require('gulp-less');
var rename = require('gulp-rename');
var sourcemaps = require('gulp-sourcemaps');
var cleanCSS = require('gulp-clean-css');
var babelify = require('babelify');
var uglify = require('gulp-uglify');
var buffer = require('vinyl-buffer');
var gulpif = require('gulp-if');

var args = require('yargs').argv;

var config = {
  gameday: {
    js: {
      src: ['./react/gameday2/gameday2.js'],
      outputDir: './static/compiled/javascript',
      outputFile: 'gameday2.min.js'
    },
    less: {
      src: ['./react/gameday2/gameday2.less'],
      outputDir: './static/compiled/css/',
      outputFile: 'gameday2.min.css',
      watch: ['./react/gameday2/**/*.less']
    }
  },
  apidocs: {
    js: {
      src: ['./react/apidocs/apidocs.js'],
      outputDir: './static/compiled/javascript',
      outputFile: 'apidocs.min.js'
    },
    less: {
      src: ['./react/apidocs/apidocs.less'],
      outputDir: './static/compiled/css/',
      outputFile: 'apidocs.min.css',
      watch: ['./react/apidocs/**/*.less']
    }
  },
  eventwizard: {
    js: {
      src: ['./react/eventwizard/eventwizard.js'],
      outputDir: './static/compiled/javascript',
      outputFile: 'eventwizard.min.js'
    },
    less: {
      src: ['./react/eventwizard/eventwizard.less'],
      outputDir: './static/compiled/css/',
      outputFile: 'eventwizard.min.css',
      watch: ['./react/eventwizard/**/*.less']
    }
  },
  liveevent: {
    js: {
      src: ['./react/liveevent/liveevent.js'],
      outputDir: './static/compiled/javascript',
      outputFile: 'liveevent.min.js'
    }
  }
};

var errorHandler = function(err) {
  gutil.log(err);
  this.emit('end');

  process.exit(1);
};

function compile(watch, config) {
  if (args.production) {
    process.env.NODE_ENV = 'production';
  }
  var bundler = browserify({
    entries: config.js.src,
    debug: true, // Gives us sourcemapping
    cache: {},
    packageCache: {},
  }).transform('babelify', {
    presets: ['es2015', 'react', 'stage-2']
  });

  function rebundle() {
    bundler.bundle()
      .on('error', errorHandler)
      .pipe(source(config.js.outputFile))
      .pipe(buffer())
      .pipe(sourcemaps.init({loadMaps: true}))
      .pipe(gulpif(args.production, uglify()))
      .on('error', errorHandler)
      .pipe(sourcemaps.write('./'))
      .pipe(debug())
      .pipe(gulp.dest(config.js.outputDir));
  }

  if (watch) {
    var watcher = watchify(bundler);
    watcher.on('update', function() {
      rebundle();
    });
  }

  rebundle();
}

function compileLess(config) {
  gulp.src(config.less.src)
    .pipe(sourcemaps.init())
    .pipe(less())
    .pipe(cleanCSS())
    .pipe(sourcemaps.write())
    .pipe(debug())
    .on('error', errorHandler)
    .pipe(rename(config.less.outputFile))
    .pipe(gulp.dest(config.less.outputDir));
}

gulp.task('apidocs-js', function() {
  return compile(false, config.apidocs);
});

gulp.task('apidocs-js-watch', function() {
  return compile(true, config.apidocs);
});

gulp.task('eventwizard-js', function() {
  return compile(false, config.eventwizard);
});

gulp.task('eventwizard-js-watch', function() {
  return compile(true, config.eventwizard);
});

gulp.task('gameday-js', function() {
  return compile(false, config.gameday);
});

gulp.task('gameday-js-watch', function() {
  return compile(true, config.gameday);
});

gulp.task('liveevent-js', function() {
  return compile(false, config.liveevent);
});

gulp.task('liveevent-js-watch', function() {
  return compile(true, config.liveevent);
});

gulp.task('apidocs-less', function() {
  return compileLess(config.apidocs)
});

gulp.task('gameday-less', function() {
  return compileLess(config.gameday)
});

gulp.task('eventwizard-less', function() {
  return compileLess(config.eventwizard)
});

gulp.task('gameday-less-watch', function() {
  gulp.watch(config.gameday.less.watch, ['gameday-less']);
});

gulp.task('build', ['gameday-js', 'gameday-less',
                    'apidocs-js', 'apidocs-less',
                    'eventwizard-js', 'eventwizard-less',
                    'liveevent-js']);

gulp.task('watch', ['gameday-js-watch', 'gameday-less-watch',
                    'apidocs-js-watch',
                    'eventwizard-js-watch',
                    'liveevent-js-watch']);

gulp.task('default', ['build', 'watch']);
<|endoftext|>


<commit_before>'use strict';

const gulp = require('gulp');
const eslint = require('gulp-eslint');
const mocha = require('gulp-mocha');
const webpack = require('webpack-stream');
const KarmaServer = require('karma').Server;
const sass = require('gulp-sass');

const scripts = ['index.js', 'gulpfile.js', 'lib/*.js',
'test/*-test.js', 'models/*.js', 'app/**/*.js'];

gulp.task('lint', () => {
  return gulp.src(scripts)
  .pipe(eslint())
  .pipe(eslint.format());
});

gulp.task('server:test', () => {
  return gulp.src('test/server_test.js')
  .pipe(mocha());
});

gulp.task('watch', () => {
  return gulp.watch(scripts, ['lint', 'test']);
});

gulp.task('webpack:dev', ['html:dev', 'scss:dev'], () => {
  return gulp.src('app/js/entry.js')
    .pipe(webpack({
      output: {
        devtool: 'source-map',
        filename: 'bundle.js'
      }
    }))
    .pipe(gulp.dest('./build'));
});

gulp.task('webpack:unitTest', () => {
  return gulp.src('test/unit/test_entry.js')
    .pipe(webpack({
      devtool: 'source-map',
      output: {
        filename: 'bundle.js'
      },
      module: {
        loaders: [
          {
            test: /\.html$/,
            loader: 'html'
          }
        ]
      }
    }))
    .pipe(gulp.dest('./test/unit'));
});

gulp.task('karmaTest', (done) => {
  return new KarmaServer({
    configfile: __dirname + './karma.conf.js'
  }, done).start();
});

gulp.task('html:dev', () => {
  return gulp.src('app/**/*.html')
  .pipe(gulp.dest('./build'));
});

gulp.task('scss:dev', () => {
  return gulp.src('app/styles/main.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('./build/styles'));
});

gulp.task('client:test', ['webpack:unitTest']);
gulp.task('build', ['webpack:dev']);
gulp.task('test', ['lint', 'server:test', 'client:test']);
<commit_msg>added sourcemap to build directory via gulp<commit_after>'use strict';

const gulp = require('gulp');
const eslint = require('gulp-eslint');
const mocha = require('gulp-mocha');
const webpack = require('webpack-stream');
const KarmaServer = require('karma').Server;
const sass = require('gulp-sass');

const scripts = ['index.js', 'gulpfile.js', 'lib/*.js',
'test/*-test.js', 'models/*.js', 'app/**/*.js'];

gulp.task('lint', () => {
  return gulp.src(scripts)
  .pipe(eslint())
  .pipe(eslint.format());
});

gulp.task('server:test', () => {
  return gulp.src('test/server_test.js')
  .pipe(mocha());
});

gulp.task('watch', () => {
  return gulp.watch(scripts, ['lint', 'test']);
});

gulp.task('webpack:dev', ['html:dev', 'scss:dev'], () => {
  return gulp.src('app/js/entry.js')
    .pipe(webpack({
      devtool: 'source-map',
      output: {
        filename: 'bundle.js'
      }
    }))
    .pipe(gulp.dest('./build'));
});

gulp.task('webpack:unitTest', () => {
  return gulp.src('test/unit/test_entry.js')
    .pipe(webpack({
      devtool: 'source-map',
      output: {
        filename: 'bundle.js'
      },
      module: {
        loaders: [
          {
            test: /\.html$/,
            loader: 'html'
          }
        ]
      }
    }))
    .pipe(gulp.dest('./test/unit'));
});

gulp.task('karmaTest', (done) => {
  return new KarmaServer({
    configfile: __dirname + './karma.conf.js'
  }, done).start();
});

gulp.task('html:dev', () => {
  return gulp.src('app/**/*.html')
  .pipe(gulp.dest('./build'));
});

gulp.task('scss:dev', () => {
  return gulp.src('app/styles/main.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('./build/styles'));
});

gulp.task('client:test', ['webpack:unitTest']);
gulp.task('build', ['webpack:dev']);
gulp.task('test', ['lint', 'server:test', 'client:test']);
<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var allocCluster = require('./lib/alloc-cluster.js');

allocCluster.test('request() without hasNoParent', {
    numPeers: 2
}, function t(cluster, assert) {
    var one = remoteService(cluster.channels[0]);
    var two = cluster.channels[1];

    var subTwo = two.makeSubChannel({
        serviceName: 'server',
        peers: [one.hostPort]
    });

    subTwo.waitForIdentified({
        host: one.hostPort
    }, function onIdentified(err) {
        assert.ifError(err);

        assert.throws(function throwIt() {
            subTwo.request({
                serviceName: 'server'
            }).send('echo', 'a', 'b');
        }, /For the call to server/);

        assert.end();
    });
});

allocCluster.test('request() without as header', {
    numPeers: 2
}, function t(cluster, assert) {
    var one = remoteService(cluster.channels[0]);
    var two = cluster.channels[1];

    var subTwo = two.makeSubChannel({
        serviceName: 'server',
        peers: [one.hostPort]
    });

    subTwo.waitForIdentified({
        host: one.hostPort
    }, function onIdentified(err) {
        assert.ifError(err);

        assert.throws(function throwIt() {
            subTwo.request({
                serviceName: 'server',
                hasNoParent: true
            }).send('echo', 'a', 'b', noop);
        }, /Got request for server echo without as header/);

        // purge orphaned out req.
        subTwo.peers.get(one.hostPort).connections[0].ops.clear();

        assert.end();
    });
});

allocCluster.test('request() without cn header', {
    numPeers: 2
}, function t(cluster, assert) {
    var one = remoteService(cluster.channels[0]);
    var two = cluster.channels[1];

    var subTwo = two.makeSubChannel({
        serviceName: 'server',
        peers: [one.hostPort]
    });

    subTwo.waitForIdentified({
        host: one.hostPort
    }, function onIdentified(err) {
        assert.ifError(err);

        assert.throws(function throwIt() {
            subTwo.request({
                serviceName: 'server',
                hasNoParent: true,
                headers: {
                    as: 'raw'
                }
            }).send('echo', 'a', 'b', noop);
        }, /Got request for server echo without cn header/);

        // purge orphaned out req.
        subTwo.peers.get(one.hostPort).connections[0].ops.clear();

        assert.end();
    });
});

function noop() {}

function remoteService(chan) {
    chan.makeSubChannel({
        serviceName: 'server'
    }).register('echo', function echo(req, res, arg2, arg3) {
        res.headers.as = 'raw';
        res.sendOk(arg2, arg3);
    });

    return chan;
}
<commit_msg>test/request-error-context: drop orphan purge... now that we fixed the orphaning<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var allocCluster = require('./lib/alloc-cluster.js');

allocCluster.test('request() without hasNoParent', {
    numPeers: 2
}, function t(cluster, assert) {
    var one = remoteService(cluster.channels[0]);
    var two = cluster.channels[1];

    var subTwo = two.makeSubChannel({
        serviceName: 'server',
        peers: [one.hostPort]
    });

    subTwo.waitForIdentified({
        host: one.hostPort
    }, function onIdentified(err) {
        assert.ifError(err);

        assert.throws(function throwIt() {
            subTwo.request({
                serviceName: 'server'
            }).send('echo', 'a', 'b');
        }, /For the call to server/);

        assert.end();
    });
});

allocCluster.test('request() without as header', {
    numPeers: 2
}, function t(cluster, assert) {
    var one = remoteService(cluster.channels[0]);
    var two = cluster.channels[1];

    var subTwo = two.makeSubChannel({
        serviceName: 'server',
        peers: [one.hostPort]
    });

    subTwo.waitForIdentified({
        host: one.hostPort
    }, function onIdentified(err) {
        assert.ifError(err);

        assert.throws(function throwIt() {
            subTwo.request({
                serviceName: 'server',
                hasNoParent: true
            }).send('echo', 'a', 'b', noop);
        }, /Got request for server echo without as header/);

        assert.end();
    });
});

allocCluster.test('request() without cn header', {
    numPeers: 2
}, function t(cluster, assert) {
    var one = remoteService(cluster.channels[0]);
    var two = cluster.channels[1];

    var subTwo = two.makeSubChannel({
        serviceName: 'server',
        peers: [one.hostPort]
    });

    subTwo.waitForIdentified({
        host: one.hostPort
    }, function onIdentified(err) {
        assert.ifError(err);

        assert.throws(function throwIt() {
            subTwo.request({
                serviceName: 'server',
                hasNoParent: true,
                headers: {
                    as: 'raw'
                }
            }).send('echo', 'a', 'b', noop);
        }, /Got request for server echo without cn header/);

        assert.end();
    });
});

function noop() {}

function remoteService(chan) {
    chan.makeSubChannel({
        serviceName: 'server'
    }).register('echo', function echo(req, res, arg2, arg3) {
        res.headers.as = 'raw';
        res.sendOk(arg2, arg3);
    });

    return chan;
}
<|endoftext|>


<commit_before>'use strict'

const chai = require('chai')
const assert = require('assert')

const Name = require('./../../lib/data/name')
const Location = require('./../../lib/data/location')
const Province = require('./../../lib/data/province')
const SystemHelper = require('./../../lib/rule/rule-helper')
const Order = require('./../../lib/variant/standard/order')

chai.should()

describe('RuleHelper', () => {
  it('defines helper functions.', () => {
    const fleet = new Name('Fleet', 'F')
    const army = new Name('Army', 'A')

    const spain = new Province(new Name('Spa'), null, true)
    const spa = new Location(spain, [army])
    const spaSc = new Location(spain, [fleet])
    spaSc.toString = () => 'Spa/SC'

    const naples = new Province(new Name('Nap'))
    const nap = new Location(naples, [army, fleet])

    const western = new Province(new Name('Wes'))
    const wes = new Location(western, [fleet])

    const orders = []
    for (const name in Order) {
      orders.push([name.toLowerCase(), Order[name]])
    }

    const h = new SystemHelper([], [fleet, army], orders)
    h.$m.F(nap).militaryBranch.should.deep.equal(fleet)
    h.$m.F(nap).location.should.deep.equal(nap)

    const c = h.F(wes).convoy(h.A(nap).move(spa).viaConvoy())

    c.unit.militaryBranch.should.deep.equal(fleet)
    c.unit.location.should.deep.equal(wes)
    c.target.unit.militaryBranch.should.deep.equal(army)
    c.target.unit.location.should.deep.equal(nap)
    c.target.destination.should.deep.equal(spa)
    c.target.isViaConvoy.should.equal(true)
  })
})
<commit_msg>Fix class-name in test case<commit_after>'use strict'

const chai = require('chai')
const assert = require('assert')

const Name = require('./../../lib/data/name')
const Location = require('./../../lib/data/location')
const Province = require('./../../lib/data/province')
const RuleHelper = require('./../../lib/rule/rule-helper')
const Order = require('./../../lib/variant/standard/order')

chai.should()

describe('RuleHelper', () => {
  it('defines helper functions.', () => {
    const fleet = new Name('Fleet', 'F')
    const army = new Name('Army', 'A')

    const spain = new Province(new Name('Spa'), null, true)
    const spa = new Location(spain, [army])
    const spaSc = new Location(spain, [fleet])
    spaSc.toString = () => 'Spa/SC'

    const naples = new Province(new Name('Nap'))
    const nap = new Location(naples, [army, fleet])

    const western = new Province(new Name('Wes'))
    const wes = new Location(western, [fleet])

    const orders = []
    for (const name in Order) {
      orders.push([name.toLowerCase(), Order[name]])
    }

    const h = new RuleHelper([], [fleet, army], orders)
    h.$m.F(nap).militaryBranch.should.deep.equal(fleet)
    h.$m.F(nap).location.should.deep.equal(nap)

    const c = h.F(wes).convoy(h.A(nap).move(spa).viaConvoy())

    c.unit.militaryBranch.should.deep.equal(fleet)
    c.unit.location.should.deep.equal(wes)
    c.target.unit.militaryBranch.should.deep.equal(army)
    c.target.unit.location.should.deep.equal(nap)
    c.target.destination.should.deep.equal(spa)
    c.target.isViaConvoy.should.equal(true)
  })
})
<|endoftext|>