<commit_before>'use strict';

$(function() {
    var points = 0;
    var $pointContainer = $('.points');
    var keypressed = 'key-';
    var $container = $('.keys-container');
    var $square = $('.key-selector');
    // array of objects: {score, speed, message, points}
    var speeds = [
        {score: 0, speed: 800, message: '', points: 1, keys: 1},
        {score: 3, speed: 750, message: 'You\'ve got it!', points: 2, keys: 2},
        {score: 20, speed: 670, message: 'Keep going!', points: 5, keys: 3},
        {score: 70, speed: 620, message: 'You\'re doing great!', points: 7, keys: 3},
        {score: 150, speed: 560, message: 'You rock!', points: 10, keys: 3},
        {score: 300, speed: 510, message: 'Don\'t stop!', points: 12, keys: 4},
        {score: 500, speed: 490, message: 'Tricky!', points: 15, keys: 4},
        {score: 760, speed: 465, message: 'Great!', points: 17, keys: 4},
        {score: 1100, speed: 440, message: 'I like your style!', points: 20, keys: 4},
        {score: 1500, speed: 390, message: 'Awesome!', points: 22, keys: 4},
        {score: 2000, speed: 360, message: 'Yeah!!', points: 25, keys: 4},
        {score: 2700, speed: 330, message: 'How do you do that?', points: 27, keys: 4},
        {score: 3500, speed: 310, message: '...how?', points: 30, keys: 4},
        {score: 4300, speed: 290, message: 'Don\'t ever stop!!', points: 32, keys: 4},
        {score: 5500, speed: 280, message: 'I\'m really impressed.', points: 35, keys: 4},
        {score: 7000, speed: 270, message: 'Arrow hero!', points: 40, keys: 4},
        {score: 10000, speed: 260, message: 'You\'re really still here?', points: 40, keys: 4},
        {score: 10500, speed: 250, message: 'That\'s incredible!', points: 40, keys: 4}
    ];
    var current = speeds[0];
    var difficulty = 1;
    var started = false;
    var maxLife = 5000;
    var currentLife = maxLife;
    // array of objects: {delay, started, interval}
    var scheduledSpawns = [];
    var bestScore = localStorage.getItem('bestScore');
    var $mobileControls = $('.mobile-controls');
    var $body = $('body');

    // Migration from sessionStorage to localStorage
    var sessionStorageScore = sessionStorage.getItem('bestScore');
    if (sessionStorageScore) {
        localStorage.setItem('bestScore', sessionStorageScore);
        bestScore = sessionStorageScore;
    }

    function updatePoints(pts) {
        if (pts < 1) {
            pts = 1;
        }
        pts = Math.floor(pts);
        points += pts;
        $square.addClass('bump');
        $pointContainer
            .html(points)
            .addClass('bump')
            .on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function() {
                $pointContainer.removeClass('bump');
                $square.removeClass('bump');
            })
        ;
        var $ding = $('
+'+pts+'
');
        $ding.on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function() {
            $(this).remove();
        });
        $square.append($ding);
    }

    function updateSpeed() {
        var oldSpeed = current;
        for (var i in speeds) {
            var _speed = speeds[i];
            if (points >= _speed.score) {
                current = _speed;
            } else if (points < _speed.score) {
                break;
            }
        }
        if (current.speed !== oldSpeed.speed) {
            // Speed changed !
            $('.level-message')
                .text(current.message)
                .addClass('show')
                .on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function() {
                    $(this).removeClass('show');
                });
        }
    }

    function spawnRandomKey(obj) {
        if (started !== 'paused') { // running or ended
            removeScheduledSpawn(obj);
        }

        if (started === 'end' || started === 'paused' || started === 'restart') {
            return;
        }

        var arr = ['key-right', 'key-left', 'key-down', 'key-up'];
        var direction = arr[Math.floor(Math.random()*current.keys)];
        var $elem = $container.find('.idle').first();
        if ($elem.length <= 0) {
            $elem = $('

');
            $elem.on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function() {

                if (started === 'end' || started === 'restart' || $(this).hasClass('idle')) {
                    return;
                }

                if ($(this).hasClass(keypressed)) {
                    currentLife += 200;
                    if (currentLife > maxLife) {
                        currentLife = maxLife;
                    }
                    updatePoints(current.points);
                } else {
                    currentLife -= 1000;
                    $square
                        .addClass('bad')
                        .on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function() {
                            $square.removeClass('bad');
                        });
                }

                updateSpeed();

                var percent = currentLife*100/maxLife;
                var $elem = $('.percent');
                $elem.css('width', percent+'%');

                if (percent < 20) {
                    $elem.addClass('low');
                } else if (percent < 60) {
                    $elem.addClass('medium').removeClass('low');
                } else {
                    $elem.removeClass('low medium');
                }

                if (currentLife <= 0 && started === 'running') {
                    endGame();
                }

                $(this).removeClass('key-up key-down key-left key-right').addClass('idle');
            });
            $container.append($elem);
        } else {
            $elem.removeClass('idle').addClass(direction);
        }

        // Spawn next key
        scheduleSpawn(current.speed);
    }

    function scheduleSpawn(delay) {
        var now = new Date();
        var obj = {
            'delay': delay,
            'started': now.getTime()
        };
        obj.interval = setTimeout(spawnRandomKey, delay, obj);
        scheduledSpawns.push(obj);
    }

    function removeScheduledSpawn(obj) {
        var index = scheduledSpawns.indexOf(obj);
        if (index > -1) {
            scheduledSpawns.splice(index, 1);
        }
    }

    function pauseScheduledSpawns() {
        var now = new Date();
        for (var i in scheduledSpawns) {
            var obj = scheduledSpawns[i];
            obj.delay -= now.getTime() - obj.started;
            obj.started = null;
            clearInterval(obj.interval);
        }
    }

    function resumeScheduledSpawns() {
        var now = new Date();
        for (var i in scheduledSpawns) {
            var obj = scheduledSpawns[i];
            obj.started = now.getTime();
            obj.interval = setTimeout(spawnRandomKey, obj.delay, obj);
        }
    }

    function endGame () {
        started = 'end';
        $('.key').addClass('hide');
        $('.key-selector-container').addClass('hide').removeClass('show');
        $('.results').addClass('show').removeClass('hide');
        $('.points-container').addClass('hide').removeClass('show');
        $('.pause-btn').text('Restart');

        if (points > bestScore) {
            // update best score
            bestScore = points;
            sessionStorage.setItem('bestScore', bestScore);
            $('.best-points .value').text(bestScore);
            $('.best').fadeIn();
        }

        // Google Analytics tracking
        ga('send', { // jshint ignore:line
            'hitType': 'event',          // Required.
            'eventCategory': 'game',   // Required.
            'eventAction': 'score',      // Required.
            'eventValue': points
        });
    }

    function restartGame() {
        started = 'restart';
        points = 0;
        maxLife = 5000;
        currentLife = maxLife;
        current = speeds[0];
        difficulty = 1;

        if (keypressed !== '') {
            $square.removeClass('s-'+keypressed);
        }
        keypressed = '';

        $container.find('.key').removeClass('key-up key-down key-left key-right hide').addClass('idle');
        $('.key-selector-container').addClass('show').removeClass('hide');
        $('.results').addClass('hide').removeClass('show');
        $('.points-container').addClass('show').removeClass('hide');

        setTimeout(function() {
            for (var i in scheduledSpawns) {
                var obj = scheduledSpawns[i];
                clearInterval(obj.interval);
            }
            scheduledSpawns = [];
            $pointContainer.html(points);
            $('.percent').css('width', '100%').removeClass('low medium');
            setTimeout(function() {
                started = 'running';
                $('.key').addClass('remove');
                $('.pause-btn').text('Pause');
                scheduleSpawn(1);
            }, 950);
        }, 1000);
    }

    $(document).keydown(function(e) {

        if (e.keyCode === 32) {
            e.preventDefault();
            if (started === 'running' || started === 'paused') {
                // space bar pressed

                started = (started === 'running' ? 'paused' : 'running');
                $('.key').toggleClass('paused', started === 'paused');
                $('.pause').toggleClass('show', started === 'paused');

                if (started === 'paused') {
                    pauseScheduledSpawns();
                } else if (started === 'running') {
                    resumeScheduledSpawns();
                }
            } else if (started === 'end') {
                restartGame();
            }
        }

        if (((e.keyCode >= 37 && e.keyCode <= 40) || (e.keyCode >= 72 && e.keyCode <= 76))
            && started !== 'paused' && started !== 'restart') {
            // arrow keys pressed

            e.preventDefault();
            if (started === false) {
                startGame();
                return false;
            }

            if (keypressed !== '') {
                $square.removeClass('s-'+keypressed);
            }
            switch (e.keyCode) {
                case 37: // left
                case 72: // h
                    keypressed = 'key-left';
                    break;

                case 38: // up
                case 75: // j
                    keypressed = 'key-up';
                    break;

                case 39: // right
                case 76: // l
                    keypressed = 'key-right';
                    break;

                case 40: // down
                case 74: // j
                    keypressed = 'key-down';
                    break;
            }
            $square.addClass('s-'+keypressed);
        }

    });

    function startGame() {
        started = 'running';

        $('.points-container').addClass('show');
        $('.helper-container').addClass('hide');
        setTimeout(function() {
            $('.key-selector')
                .addClass('show fade')
                .on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function() {
                    $(this).removeClass('fade');
                });
        }, 500);
        scheduleSpawn(1000);

        $('.percent').css('width', '100%');
    }

    if (bestScore) {
        $('.best-points .value').text(bestScore);
        $('.best').fadeIn();
    }

    $mobileControls.find('.key-up, .key-down, .key-left, .key-right').on('touchstart click', function() {
        var _class = $(this).attr('class');
        var e = jQuery.Event('keydown');

        switch (_class) {
            case 'key-left':
                e.keyCode = 37;
                break;

            case 'key-up':
                e.keyCode = 38;
                break;

            case 'key-right':
                e.keyCode = 39;
                break;

            case 'key-down':
                e.keyCode = 40;
                break;
        }

        $(document).trigger(e);
    });
    $mobileControls.find('.pause-btn').on('touchstart', function() {
        var e = jQuery.Event('keydown');
        e.keyCode = 32;
        $(document).trigger(e);
    });

    $body.toggleClass('colorblind', (localStorage.getItem('colorblind') === 'yes'));
    $('.colorblind-btn').on('click touchstart', function() {
        $body.toggleClass('colorblind', !$body.hasClass('colorblind'));
        localStorage.setItem('colorblind', ($body.hasClass('colorblind') ? 'yes' : 'no'));
    })
});
<commit_msg>Lint fixes<commit_after>'use strict';

$(function() {
    var points = 0;
    var $pointContainer = $('.points');
    var keypressed = 'key-';
    var $container = $('.keys-container');
    var $square = $('.key-selector');
    // array of objects: {score, speed, message, points}
    var speeds = [
        {score: 0, speed: 800, message: '', points: 1, keys: 1},
        {score: 3, speed: 750, message: 'You\'ve got it!', points: 2, keys: 2},
        {score: 20, speed: 670, message: 'Keep going!', points: 5, keys: 3},
        {score: 70, speed: 620, message: 'You\'re doing great!', points: 7, keys: 3},
        {score: 150, speed: 560, message: 'You rock!', points: 10, keys: 3},
        {score: 300, speed: 510, message: 'Don\'t stop!', points: 12, keys: 4},
        {score: 500, speed: 490, message: 'Tricky!', points: 15, keys: 4},
        {score: 760, speed: 465, message: 'Great!', points: 17, keys: 4},
        {score: 1100, speed: 440, message: 'I like your style!', points: 20, keys: 4},
        {score: 1500, speed: 390, message: 'Awesome!', points: 22, keys: 4},
        {score: 2000, speed: 360, message: 'Yeah!!', points: 25, keys: 4},
        {score: 2700, speed: 330, message: 'How do you do that?', points: 27, keys: 4},
        {score: 3500, speed: 310, message: '...how?', points: 30, keys: 4},
        {score: 4300, speed: 290, message: 'Don\'t ever stop!!', points: 32, keys: 4},
        {score: 5500, speed: 280, message: 'I\'m really impressed.', points: 35, keys: 4},
        {score: 7000, speed: 270, message: 'Arrow hero!', points: 40, keys: 4},
        {score: 10000, speed: 260, message: 'You\'re really still here?', points: 40, keys: 4},
        {score: 10500, speed: 250, message: 'That\'s incredible!', points: 40, keys: 4}
    ];
    var current = speeds[0];
    var difficulty = 1;
    var started = false;
    var maxLife = 5000;
    var currentLife = maxLife;
    // array of objects: {delay, started, interval}
    var scheduledSpawns = [];
    var bestScore = localStorage.getItem('bestScore');
    var $mobileControls = $('.mobile-controls');
    var $body = $('body');

    // Migration from sessionStorage to localStorage
    var sessionStorageScore = sessionStorage.getItem('bestScore');
    if (sessionStorageScore) {
        localStorage.setItem('bestScore', sessionStorageScore);
        bestScore = sessionStorageScore;
    }

    function updatePoints(pts) {
        if (pts < 1) {
            pts = 1;
        }
        pts = Math.floor(pts);
        points += pts;
        $square.addClass('bump');
        $pointContainer
            .html(points)
            .addClass('bump')
            .on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function() {
                $pointContainer.removeClass('bump');
                $square.removeClass('bump');
            })
        ;
        var $ding = $('
+'+pts+'
');
        $ding.on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function() {
            $(this).remove();
        });
        $square.append($ding);
    }

    function updateSpeed() {
        var oldSpeed = current;
        for (var i in speeds) {
            var _speed = speeds[i];
            if (points >= _speed.score) {
                current = _speed;
            } else if (points < _speed.score) {
                break;
            }
        }
        if (current.speed !== oldSpeed.speed) {
            // Speed changed !
            $('.level-message')
                .text(current.message)
                .addClass('show')
                .on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function() {
                    $(this).removeClass('show');
                });
        }
    }

    function spawnRandomKey(obj) {
        if (started !== 'paused') { // running or ended
            removeScheduledSpawn(obj);
        }

        if (started === 'end' || started === 'paused' || started === 'restart') {
            return;
        }

        var arr = ['key-right', 'key-left', 'key-down', 'key-up'];
        var direction = arr[Math.floor(Math.random()*current.keys)];
        var $elem = $container.find('.idle').first();
        if ($elem.length <= 0) {
            $elem = $('

');
            $elem.on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function() {

                if (started === 'end' || started === 'restart' || $(this).hasClass('idle')) {
                    return;
                }

                if ($(this).hasClass(keypressed)) {
                    currentLife += 200;
                    if (currentLife > maxLife) {
                        currentLife = maxLife;
                    }
                    updatePoints(current.points);
                } else {
                    currentLife -= 1000;
                    $square
                        .addClass('bad')
                        .on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function() {
                            $square.removeClass('bad');
                        });
                }

                updateSpeed();

                var percent = currentLife*100/maxLife;
                var $elem = $('.percent');
                $elem.css('width', percent+'%');

                if (percent < 20) {
                    $elem.addClass('low');
                } else if (percent < 60) {
                    $elem.addClass('medium').removeClass('low');
                } else {
                    $elem.removeClass('low medium');
                }

                if (currentLife <= 0 && started === 'running') {
                    endGame();
                }

                $(this).removeClass('key-up key-down key-left key-right').addClass('idle');
            });
            $container.append($elem);
        } else {
            $elem.removeClass('idle').addClass(direction);
        }

        // Spawn next key
        scheduleSpawn(current.speed);
    }

    function scheduleSpawn(delay) {
        var now = new Date();
        var obj = {
            'delay': delay,
            'started': now.getTime()
        };
        obj.interval = setTimeout(spawnRandomKey, delay, obj);
        scheduledSpawns.push(obj);
    }

    function removeScheduledSpawn(obj) {
        var index = scheduledSpawns.indexOf(obj);
        if (index > -1) {
            scheduledSpawns.splice(index, 1);
        }
    }

    function pauseScheduledSpawns() {
        var now = new Date();
        for (var i in scheduledSpawns) {
            var obj = scheduledSpawns[i];
            obj.delay -= now.getTime() - obj.started;
            obj.started = null;
            clearInterval(obj.interval);
        }
    }

    function resumeScheduledSpawns() {
        var now = new Date();
        for (var i in scheduledSpawns) {
            var obj = scheduledSpawns[i];
            obj.started = now.getTime();
            obj.interval = setTimeout(spawnRandomKey, obj.delay, obj);
        }
    }

    function endGame () {
        started = 'end';
        $('.key').addClass('hide');
        $('.key-selector-container').addClass('hide').removeClass('show');
        $('.results').addClass('show').removeClass('hide');
        $('.points-container').addClass('hide').removeClass('show');
        $('.pause-btn').text('Restart');

        if (points > bestScore) {
            // update best score
            bestScore = points;
            sessionStorage.setItem('bestScore', bestScore);
            $('.best-points .value').text(bestScore);
            $('.best').fadeIn();
        }

        // Google Analytics tracking
        ga('send', { // jshint ignore:line
            'hitType': 'event',          // Required.
            'eventCategory': 'game',   // Required.
            'eventAction': 'score',      // Required.
            'eventValue': points
        });
    }

    function restartGame() {
        started = 'restart';
        points = 0;
        maxLife = 5000;
        currentLife = maxLife;
        current = speeds[0];
        difficulty = 1;

        if (keypressed !== '') {
            $square.removeClass('s-'+keypressed);
        }
        keypressed = '';

        $container.find('.key').removeClass('key-up key-down key-left key-right hide').addClass('idle');
        $('.key-selector-container').addClass('show').removeClass('hide');
        $('.results').addClass('hide').removeClass('show');
        $('.points-container').addClass('show').removeClass('hide');

        setTimeout(function() {
            for (var i in scheduledSpawns) {
                var obj = scheduledSpawns[i];
                clearInterval(obj.interval);
            }
            scheduledSpawns = [];
            $pointContainer.html(points);
            $('.percent').css('width', '100%').removeClass('low medium');
            setTimeout(function() {
                started = 'running';
                $('.key').addClass('remove');
                $('.pause-btn').text('Pause');
                scheduleSpawn(1);
            }, 950);
        }, 1000);
    }

    $(document).keydown(function(e) {

        if (e.keyCode === 32) {
            e.preventDefault();
            if (started === 'running' || started === 'paused') {
                // space bar pressed

                started = (started === 'running' ? 'paused' : 'running');
                $('.key').toggleClass('paused', started === 'paused');
                $('.pause').toggleClass('show', started === 'paused');

                if (started === 'paused') {
                    pauseScheduledSpawns();
                } else if (started === 'running') {
                    resumeScheduledSpawns();
                }
            } else if (started === 'end') {
                restartGame();
            }
        }

        if (((e.keyCode >= 37 && e.keyCode <= 40) || (e.keyCode >= 72 && e.keyCode <= 76)) &&
            started !== 'paused' && started !== 'restart') {
            // arrow keys pressed

            e.preventDefault();
            if (started === false) {
                startGame();
                return false;
            }

            if (keypressed !== '') {
                $square.removeClass('s-'+keypressed);
            }
            switch (e.keyCode) {
                case 37: // left
                case 72: // h
                    keypressed = 'key-left';
                    break;

                case 38: // up
                case 75: // j
                    keypressed = 'key-up';
                    break;

                case 39: // right
                case 76: // l
                    keypressed = 'key-right';
                    break;

                case 40: // down
                case 74: // j
                    keypressed = 'key-down';
                    break;
            }
            $square.addClass('s-'+keypressed);
        }

    });

    function startGame() {
        started = 'running';

        $('.points-container').addClass('show');
        $('.helper-container').addClass('hide');
        setTimeout(function() {
            $('.key-selector')
                .addClass('show fade')
                .on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function() {
                    $(this).removeClass('fade');
                });
        }, 500);
        scheduleSpawn(1000);

        $('.percent').css('width', '100%');
    }

    if (bestScore) {
        $('.best-points .value').text(bestScore);
        $('.best').fadeIn();
    }

    $mobileControls.find('.key-up, .key-down, .key-left, .key-right').on('touchstart click', function() {
        var _class = $(this).attr('class');
        var e = jQuery.Event('keydown');

        switch (_class) {
            case 'key-left':
                e.keyCode = 37;
                break;

            case 'key-up':
                e.keyCode = 38;
                break;

            case 'key-right':
                e.keyCode = 39;
                break;

            case 'key-down':
                e.keyCode = 40;
                break;
        }

        $(document).trigger(e);
    });
    $mobileControls.find('.pause-btn').on('touchstart', function() {
        var e = jQuery.Event('keydown');
        e.keyCode = 32;
        $(document).trigger(e);
    });

    $body.toggleClass('colorblind', (localStorage.getItem('colorblind') === 'yes'));
    $('.colorblind-btn').on('click touchstart', function() {
        $body.toggleClass('colorblind', !$body.hasClass('colorblind'));
        localStorage.setItem('colorblind', ($body.hasClass('colorblind') ? 'yes' : 'no'));
    });
});
<|endoftext|>


<commit_before>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');

module.exports = yeoman.generators.Base.extend({
  constructor: function () {
    yeoman.Base.apply(this, arguments);
    this.argument('project_name', {type: String, required: false});
  },
  prompting: function () {
    var done = this.async();

    // Have Yeoman greet the user.
    this.log(yosay(
      'Mess with the best, ' + chalk.red('Django likes REST...') + ' Yeah...'
    ));

    var prompts = [];

    if (!this.project_name) {
      prompts.splice(0, 0, {
        type: 'input',
        name: 'project_name',
        message: 'What is the name of your project?',
        default: 'mysite'
        //store   : true // ? http://yeoman.io/authoring/user-interactions.html
      });
    }

    this.prompt(prompts, function (props) {
      this.props = props;
      // To access props later use this.props.someOption;
      if (!this.props.project_name) {
        this.props.project_name = this.project_name;
      }

      done();
    }.bind(this));
  },

  writing: {
    django: function() {
      // - first without the mysite module
      this.fs.copyTpl(
        // skip Gruntfile.js, since it uses <% templates, causing clashes
        this.templatePath('django/mysite/!(mysite){/**/*,*}'),
        //this.destinationPath('/whydoineedthis/'),
        this.destinationPath('./whydoineedthis/'),
        this.props
        //{interpolate: /{{([\s\S]+?)}}/g} // using the {{ }} template delim.
      );
      this.fs.copyTpl(
        this.templatePath('django/mysite/mysite/{/**/*,*}'),
        //this.destinationPath(this.props.project_name + '/whydoineedthis/'),
        this.destinationPath(this.props.project_name + '/whydoineedthis/'),
        this.props
        //{interpolate: /{{([\s\S]+?)}}/g} // using the {{ }} template delim.
      );
    },

    projectfiles: function () {
      this.fs.copyTpl(
        this.templatePath('*'),
        this.destinationPath('./whydoineedthis/'),
        this.props
        //{interpolate: /{{([\s\S]+?)}}/g} // using the {{ }} template delim.
      );
      // this.fs.copy(
      //   this.templatePath('editorconfig'),
      //   this.destinationPath('.editorconfig')
      // );
    }
  },

  install: function () {
    //this.installDependencies();
  }
});
<commit_msg>fix projectfiles dest path<commit_after>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');

module.exports = yeoman.generators.Base.extend({
  constructor: function () {
    yeoman.Base.apply(this, arguments);
    this.argument('project_name', {type: String, required: false});
  },
  prompting: function () {
    var done = this.async();

    // Have Yeoman greet the user.
    this.log(yosay(
      'Mess with the best, ' + chalk.red('Django likes REST...') + ' Yeah...'
    ));

    var prompts = [];

    if (!this.project_name) {
      prompts.splice(0, 0, {
        type: 'input',
        name: 'project_name',
        message: 'What is the name of your project?',
        default: 'mysite'
        //store   : true // ? http://yeoman.io/authoring/user-interactions.html
      });
    }

    this.prompt(prompts, function (props) {
      this.props = props;
      // To access props later use this.props.someOption;
      if (!this.props.project_name) {
        this.props.project_name = this.project_name;
      }

      done();
    }.bind(this));
  },

  writing: {
    django: function() {
      // - first without the mysite module
      this.fs.copyTpl(
        // skip Gruntfile.js, since it uses <% templates, causing clashes
        this.templatePath('django/mysite/!(mysite){/**/*,*}'),
        //this.destinationPath('/whydoineedthis/'),
        this.destinationPath('./whydoineedthis/'),
        this.props
        //{interpolate: /{{([\s\S]+?)}}/g} // using the {{ }} template delim.
      );
      this.fs.copyTpl(
        this.templatePath('django/mysite/mysite/{/**/*,*}'),
        //this.destinationPath(this.props.project_name + '/whydoineedthis/'),
        this.destinationPath(this.props.project_name + '/whydoineedthis/'),
        this.props
        //{interpolate: /{{([\s\S]+?)}}/g} // using the {{ }} template delim.
      );
    },

    projectfiles: function () {
      this.fs.copyTpl(
        this.templatePath('*'),
        this.destinationPath('./'),
        this.props

        //{interpolate: /{{([\s\S]+?)}}/g} // using the {{ }} template delim.
      );
      // this.fs.copy(
      //   this.templatePath('editorconfig'),
      //   this.destinationPath('.editorconfig')
      // );
    }
  },

  install: function () {
    //this.installDependencies();
  }
});
<|endoftext|>


<commit_before>'use strict';

angular.module('app', [
    'ngAnimate',
    'ngCookies',
    'ngResource',
    'ngSanitize',
    'ngTouch',
    'ngStorage',
    'ui.router',
    'ui.bootstrap',
    'ui.utils',
    'ui.load',
    'ui.jq',
    'smart-table',
    'oc.lazyLoad',
    'pascalprecht.translate',
    'satellizer'
]).constant("CONFIG", {
    "url": "https://tracklist.me/api",
    //"url": "http://localhost:3000",
    "imagePath": "image"
})<commit_msg>added dependency for sortable<commit_after>'use strict';

angular.module('app', [
    'ngAnimate',
    'ngCookies',
    'ngResource',
    'ngSanitize',
    'ngTouch',
    'ngStorage',
    'ui.router',
    'ui.bootstrap',
    'ui.utils',
    'ui.load',
    'ui.jq',
    'smart-table',
    'oc.lazyLoad',
    'pascalprecht.translate',
    'satellizer',
    'htmlSortable'
]).constant("CONFIG", {
    "url": "https://tracklist.me/api",
    //"url": "http://localhost:3000",
    "imagePath": "image"
})<|endoftext|>


<commit_before>'use strict';

var FrontEndGenerator = require('../front/index');
var BackEndGenerator = require('../back/index');
var Utils = require('../utils');
var lodash = require('lodash');
var yogen = require('yeoman-generator');
var yosay = require('yosay');
var chalk = require('chalk');
var Proto = require('Proto');
var path = require('path');

var FullStackGenerator = new Proto(yogen.Base, {
	constructor:function(args, options){
		this.super(args, options);
		this.option('debug', { type:Boolean, desc:'debug', defaults:false });
		this.argument('appname', { type:String, required:true });
		this.appname = lodash.camelCase(this.appname);
    this.pack = Utils.readJsonSync(path.join(__dirname, '../../package.json'));
    this.name = this.pack.name.replace(/^generator\-/, '');
    this.log(yosay(chalk.magenta('You\'re using the fantastic', chalk.yellow('Gulp\\RequireJS') + chalk.magenta(' fullstack generator.'))));
		this.composeWith(this.name +':front', { options:this.options, args:this.args });
    this.composeWith(this.name +':back', { options:this.options, args:this.args });
	}
});

module.exports = FullStackGenerator;
<commit_msg>Update: Optional appname 4 default generator<commit_after>'use strict';

var FrontEndGenerator = require('../front/index');
var BackEndGenerator = require('../back/index');
var Utils = require('../utils');
var lodash = require('lodash');
var yogen = require('yeoman-generator');
var yosay = require('yosay');
var chalk = require('chalk');
var Proto = require('Proto');
var path = require('path');

var FullStackGenerator = new Proto(yogen.Base, {
	constructor:function(args, options){
		this.super(args, options);
		this.option('debug', { type:Boolean, desc:'debug', defaults:false });
		this.argument('appname', { type:String, required:false, defaults:Utils.appname() });
		this.appname = lodash.camelCase(this.appname);
    this.pack = Utils.readJsonSync(path.join(__dirname, '../../package.json'));
    this.name = this.pack.name.replace(/^generator\-/, '');
    this.log(yosay(chalk.magenta('You\'re using the fantastic', chalk.yellow('Gulp\\RequireJS') + chalk.magenta(' fullstack generator.'))));
		this.composeWith(this.name +':front', { options:this.options, args:this.args });
    this.composeWith(this.name +':back', { options:this.options, args:this.args });
	}
});

module.exports = FullStackGenerator;
<|endoftext|>


<commit_before>let isPushEnabled = false;

const sendSubscriptionToServer = (subscription) => {
  fetch('https://test-portal.absalon.is', {method: 'post', body: subscription.endpoint});
};

const subscribe = () => {
  // Disable the button so it can't be changed while
  // we process the permission request
  const pushButton = document.querySelector('.js-push-button');
  pushButton.disabled = true;

  navigator.serviceWorker.ready.then((serviceWorkerRegistration) => {
    serviceWorkerRegistration.pushManager.subscribe({userVisibleOnly: true})
      .then((subscription) => {
        // Subscription was successful
        isPushEnabled = true;
        pushButton.textContent = 'Disable Push Messages';
        pushButton.disabled = false;

        // TODO: Send the subscription.endpoint to your server
        // and save it to send a push messages at a later date
        return sendSubscriptionToServer(subscription);
      })
      .catch((e) => {
        if (Notification.permission === 'denied') {
          // The user denied
          console.warn('Permission for Notifications was denied');
          pushButton.disabled = true;
        } else {
          // A problem occured with the subscription
          console.error('Unable to subscribe to push.', e);
          pushButton.disabled = false;
          pushButton.textContent = 'Enable Push Messages';
        }
      });
  });
};

const unsubscribe = () => {
  const pushButton = document.querySelector('.js-push-button');
  pushButton.disabled = true;

  navigator.serviceWorker.ready.then((serviceWorkerRegistration) => {
    serviceWorkerRegistration.pushManager.getSubscription().then((pushSubscription) => {
      // Check we have a subcription to unsubscribe
      if (!pushSubscription) {
        // No subscription object, set state to allow to push
        isPushEnabled = false;
        pushButton.disabled = false;
        pushButton.textContent = 'Enable Push Messages';
        return;
      }

      // const subscriptionId = pushSubscription.subscriptionId;
      // TODO: Make a request to server to remove id

      // We have a subscription, so call unsubscribe on it
      pushSubscription.unsubscribe().then(() => {
        pushButton.disabled = false;
        pushButton.textContent = 'Enable Push Messages';
        isPushEnabled = false;
      })
      .catch((e) => {
        // Failed to unsubscribe.. remove user data from our data store
        // and let the user know we did so
        console.log('Unsubscription error: ', e);
        pushButton.disabled = false;
        pushButton.textContent = 'Enable Push Messages';
      });
    })
    .catch((e) => {
      console.error('Error thrown while unsubscribing from push messaging.', e);
    });
  });
};

const initialState = () => {
  // Are Notifications supported in the service worker?
  if (!('showNotification' in ServiceWorkerRegistration.prototype)) {
    console.warn('Notifications aren\'t supported.');
    return;
  }

  // Check current Notification permission.
  if (Notification.permission === 'denied') {
    console.warn('The user has blocked notifications.');
    return;
  }

  // Check is push messaging is supported
  if (!('PushManager' in window)) {
    console.warn('Push messaging isn\'t supported.');
    return;
  }

  // We need the service worker registration to check for a subscription
  navigator.serviceWorker.ready.then((serviceWorkerRegistration) => {
    // Do we already have a push message subscription?
    serviceWorkerRegistration.pushManager.getSubscription()
      .then((subscription) => {
        // Enable any UI which (un)subscribes from push messages
        const pushButton = document.querySelector('.js-push-button');
        pushButton.disabled = false;

        if (!subscription) {
          // We aren't subscribed to push, so set UI
          // to allow the user to enable push
          return;
        }

        // Keep your server in sync with the latest subscriptionID
        sendSubscriptionToServer(subscription);

        // Set your UI to show they have subscribed for push messages
        pushButton.textContent = 'Disable Push Messages';
        isPushEnabled = true;
      })
      .catch((err) => {
        console.warn('Error during getSubscription()', err);
      });
  });
};

window.addEventListener('load', () => {
  const pushButton = document.querySelector('.js-push-button');
  pushButton.addEventListener('click', () => {
    if (isPushEnabled) {
      unsubscribe();
    } else {
      subscribe();
    }
  });

  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/service-worker.js')
      .then(initialState);
  } else {
    console.warn('Service workers aren\'t supported in this browser.');
  }
});
<commit_msg>Rename `test-portal` to `test`<commit_after>let isPushEnabled = false;

const sendSubscriptionToServer = (subscription) => {
  fetch('https://test.absalon.is', {method: 'post', body: subscription.endpoint});
};

const subscribe = () => {
  // Disable the button so it can't be changed while
  // we process the permission request
  const pushButton = document.querySelector('.js-push-button');
  pushButton.disabled = true;

  navigator.serviceWorker.ready.then((serviceWorkerRegistration) => {
    serviceWorkerRegistration.pushManager.subscribe({userVisibleOnly: true})
      .then((subscription) => {
        // Subscription was successful
        isPushEnabled = true;
        pushButton.textContent = 'Disable Push Messages';
        pushButton.disabled = false;

        // TODO: Send the subscription.endpoint to your server
        // and save it to send a push messages at a later date
        return sendSubscriptionToServer(subscription);
      })
      .catch((e) => {
        if (Notification.permission === 'denied') {
          // The user denied
          console.warn('Permission for Notifications was denied');
          pushButton.disabled = true;
        } else {
          // A problem occured with the subscription
          console.error('Unable to subscribe to push.', e);
          pushButton.disabled = false;
          pushButton.textContent = 'Enable Push Messages';
        }
      });
  });
};

const unsubscribe = () => {
  const pushButton = document.querySelector('.js-push-button');
  pushButton.disabled = true;

  navigator.serviceWorker.ready.then((serviceWorkerRegistration) => {
    serviceWorkerRegistration.pushManager.getSubscription().then((pushSubscription) => {
      // Check we have a subcription to unsubscribe
      if (!pushSubscription) {
        // No subscription object, set state to allow to push
        isPushEnabled = false;
        pushButton.disabled = false;
        pushButton.textContent = 'Enable Push Messages';
        return;
      }

      // const subscriptionId = pushSubscription.subscriptionId;
      // TODO: Make a request to server to remove id

      // We have a subscription, so call unsubscribe on it
      pushSubscription.unsubscribe().then(() => {
        pushButton.disabled = false;
        pushButton.textContent = 'Enable Push Messages';
        isPushEnabled = false;
      })
      .catch((e) => {
        // Failed to unsubscribe.. remove user data from our data store
        // and let the user know we did so
        console.log('Unsubscription error: ', e);
        pushButton.disabled = false;
        pushButton.textContent = 'Enable Push Messages';
      });
    })
    .catch((e) => {
      console.error('Error thrown while unsubscribing from push messaging.', e);
    });
  });
};

const initialState = () => {
  // Are Notifications supported in the service worker?
  if (!('showNotification' in ServiceWorkerRegistration.prototype)) {
    console.warn('Notifications aren\'t supported.');
    return;
  }

  // Check current Notification permission.
  if (Notification.permission === 'denied') {
    console.warn('The user has blocked notifications.');
    return;
  }

  // Check is push messaging is supported
  if (!('PushManager' in window)) {
    console.warn('Push messaging isn\'t supported.');
    return;
  }

  // We need the service worker registration to check for a subscription
  navigator.serviceWorker.ready.then((serviceWorkerRegistration) => {
    // Do we already have a push message subscription?
    serviceWorkerRegistration.pushManager.getSubscription()
      .then((subscription) => {
        // Enable any UI which (un)subscribes from push messages
        const pushButton = document.querySelector('.js-push-button');
        pushButton.disabled = false;

        if (!subscription) {
          // We aren't subscribed to push, so set UI
          // to allow the user to enable push
          return;
        }

        // Keep your server in sync with the latest subscriptionID
        sendSubscriptionToServer(subscription);

        // Set your UI to show they have subscribed for push messages
        pushButton.textContent = 'Disable Push Messages';
        isPushEnabled = true;
      })
      .catch((err) => {
        console.warn('Error during getSubscription()', err);
      });
  });
};

window.addEventListener('load', () => {
  const pushButton = document.querySelector('.js-push-button');
  pushButton.addEventListener('click', () => {
    if (isPushEnabled) {
      unsubscribe();
    } else {
      subscribe();
    }
  });

  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/service-worker.js')
      .then(initialState);
  } else {
    console.warn('Service workers aren\'t supported in this browser.');
  }
});
<|endoftext|>


<commit_before>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var path = require('path');
var _ = require('lodash');
var extend = require('deep-extend');
var mkdirp = require('mkdirp');

module.exports = yeoman.generators.Base.extend({

  initializing: function () {
    this.props = {};
  },

  prompting: function () {
    var done = this.async();

    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the luminous ' + chalk.red('generator-koa-sudiyi') + ' generator!'
    ));

    var prompts = [
      {
        type: 'input',
        name: 'projectName',
        message: 'Please input project name (sudiyi_app):',
        default: 'sudiyi_app'
      },
      {
        type: 'input',
        name: 'projectDesc',
        message: 'Please input project description:'
      },
      {
        type: 'input',
        name: 'projectMain',
        message: 'Main file (app.js):',
        default: 'app.js'
      },
      {
        type: 'input',
        name: 'projectAuthor',
        message: 'Author (sudiyi):',
        default: 'sudiyi'
      },
      {
        type: 'list',
        name: 'projectLicense',
        message: 'Please choose license:',
        choices: ['MIT', 'ISC', 'Apache-2.0', 'AGPL-3.0']
      }
    ];

    this.prompt(prompts, function (props) {
      this.props = props;
      // To access props later use this.props.someOption;
      done();
    }.bind(this));

  },

  defaults: function () {

    console.log(this.props);

    if (path.basename(this.destinationPath()) !== this.props.projectName) {
      this.log(
        'Your generator must be inside a folder named ' + this.props.projectName + '\n' +
        'I\'ll automatically create this folder.'
      );
      mkdirp(this.props.projectName);
      this.destinationRoot(this.destinationPath(this.props.projectName));
    }

  },

  writing: function () {

    var readmeTpl = _.template(this.fs.read(this.templatePath('README.md')));
    this.fs.write(this.destinationPath, readmeTpl({
      generatorName: 'generator-koa-sudiyi'
      yoName: 'koa-sudiyi'
    }));

    var pkg = this.fs.readJSON(this.templatePath('package_tmpl.json'), {});
    extend(pkg, {
      dependencies: {
        "aliyun-sdk": "^1.6.3",
        "bluebird": "^3.0.6",
        "co": "^4.6.0",
        "co-body": "^4.0.0",
        "co-busboy": "^1.3.1",
        "co-foreach": "^1.1.1",
        "co-redis": "^2.0.0",
        "co-request": "^1.0.0",
        "co-views": "^0.2.0",
        "cron": "^1.1.0",
        "kcors": "^1.0.1",
        "koa": "^1.1.2",
        "koa-bodyparser": "^2.0.1",
        "koa-compress": "^1.0.8",
        "koa-jwt": "^1.1.1",
        "koa-logger": "^1.3.0",
        "koa-route": "^2.4.2",
        "koa-router": "^5.3.0",
        "koa-static": "^1.5.2",
        "lodash": "^3.10.1",
        "log4js": "^0.6.29",
        "moment": "^2.10.6",
        "node-uuid": "^1.4.7",
        "nodemailer": "^1.10.0",
        "redis": "^2.4.2",
        "sequelize": "^3.14.2",
        "sequelize-cli": "^2.2.1",
        "socket.io": "^1.3.7",
        "swig": "^1.4.2",
        "thunkify-wrap": "^1.0.4",
        "async": "^1.5.0",
        "koa-body-parser": "^1.1.2",
        "koa-generic-session": "^1.10.0",
        "koa-redis": "^1.0.1",
        "mysql": "^2.9.0",
        "request": "^2.67.0"
      },
      devDependencies: {
        "mocha": "^2.3.3",
        "chai": "^3.4.1",
        "gulp": "^3.9.0",
        "faker": "^3.0.1",
        "minimist": "^1.2.0",
        "co-mocha": "^1.1.2"
      }
    });
    pkg.keywords = pkg.keywords || [];
    pkg.keywords.push('generator-koa-sudiyi');

    pkg.name = this.props.projectName;
    pkg.description = this.props.projectDesc;
    pkg.main = this.props.projectMain;
    pkg.author = this.props.projectAuthor;
    pkg.license = this.props.projectLicense;

    this.fs.writeJSON(this.destinationPath('package.json'), pkg);

    this.mkdir('lib/controllers');
    this.mkdir('lib/middlewares');
    this.mkdir('lib/middlewares/common');
    this.mkdir('lib/models');
    this.mkdir('lib/db');
    this.mkdir('lib/logger');
    this.mkdir('lib/routes');
    this.mkdir('lib/utils');
    this.mkdir('public');

    this.fs.copy(
      this.templatePath('dummyfile.txt'),
      this.destinationPath('dummyfile.txt')
    );
    this.fs.copy(
      this.templatePath('gitignore_tmpl'),
      this.destinationPath('.gitignore')
    );
    this.fs.copy(
      this.templatePath('jshintrc_tmpl'),
      this.destinationPath('.jshintrc')
    );
    this.fs.copy(
      this.templatePath('app_tmpl.js'),
      this.destinationPath('app.js')
    );

    this.fs.copy(
      this.templatePath('index_tmpl.js'),
      'lib/index.js'
    );
    this.fs.copy(
      this.templatePath('request_id_tmpl.js'),
      'lib/middlewares/common/request_id.js'
    );

  },

  install: function () {
    this.installDependencies();
  }
})
;
<commit_msg>miss comma update<commit_after>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var path = require('path');
var _ = require('lodash');
var extend = require('deep-extend');
var mkdirp = require('mkdirp');

module.exports = yeoman.generators.Base.extend({

  initializing: function () {
    this.props = {};
  },

  prompting: function () {
    var done = this.async();

    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the luminous ' + chalk.red('generator-koa-sudiyi') + ' generator!'
    ));

    var prompts = [
      {
        type: 'input',
        name: 'projectName',
        message: 'Please input project name (sudiyi_app):',
        default: 'sudiyi_app'
      },
      {
        type: 'input',
        name: 'projectDesc',
        message: 'Please input project description:'
      },
      {
        type: 'input',
        name: 'projectMain',
        message: 'Main file (app.js):',
        default: 'app.js'
      },
      {
        type: 'input',
        name: 'projectAuthor',
        message: 'Author (sudiyi):',
        default: 'sudiyi'
      },
      {
        type: 'list',
        name: 'projectLicense',
        message: 'Please choose license:',
        choices: ['MIT', 'ISC', 'Apache-2.0', 'AGPL-3.0']
      }
    ];

    this.prompt(prompts, function (props) {
      this.props = props;
      // To access props later use this.props.someOption;
      done();
    }.bind(this));

  },

  defaults: function () {

    console.log(this.props);

    if (path.basename(this.destinationPath()) !== this.props.projectName) {
      this.log(
        'Your generator must be inside a folder named ' + this.props.projectName + '\n' +
        'I\'ll automatically create this folder.'
      );
      mkdirp(this.props.projectName);
      this.destinationRoot(this.destinationPath(this.props.projectName));
    }

  },

  writing: function () {

    var readmeTpl = _.template(this.fs.read(this.templatePath('README.md')));
    this.fs.write(this.destinationPath, readmeTpl({
      generatorName: 'generator-koa-sudiyi',
      yoName: 'koa-sudiyi'
    }));

    var pkg = this.fs.readJSON(this.templatePath('package_tmpl.json'), {});
    extend(pkg, {
      dependencies: {
        "aliyun-sdk": "^1.6.3",
        "bluebird": "^3.0.6",
        "co": "^4.6.0",
        "co-body": "^4.0.0",
        "co-busboy": "^1.3.1",
        "co-foreach": "^1.1.1",
        "co-redis": "^2.0.0",
        "co-request": "^1.0.0",
        "co-views": "^0.2.0",
        "cron": "^1.1.0",
        "kcors": "^1.0.1",
        "koa": "^1.1.2",
        "koa-bodyparser": "^2.0.1",
        "koa-compress": "^1.0.8",
        "koa-jwt": "^1.1.1",
        "koa-logger": "^1.3.0",
        "koa-route": "^2.4.2",
        "koa-router": "^5.3.0",
        "koa-static": "^1.5.2",
        "lodash": "^3.10.1",
        "log4js": "^0.6.29",
        "moment": "^2.10.6",
        "node-uuid": "^1.4.7",
        "nodemailer": "^1.10.0",
        "redis": "^2.4.2",
        "sequelize": "^3.14.2",
        "sequelize-cli": "^2.2.1",
        "socket.io": "^1.3.7",
        "swig": "^1.4.2",
        "thunkify-wrap": "^1.0.4",
        "async": "^1.5.0",
        "koa-body-parser": "^1.1.2",
        "koa-generic-session": "^1.10.0",
        "koa-redis": "^1.0.1",
        "mysql": "^2.9.0",
        "request": "^2.67.0"
      },
      devDependencies: {
        "mocha": "^2.3.3",
        "chai": "^3.4.1",
        "gulp": "^3.9.0",
        "faker": "^3.0.1",
        "minimist": "^1.2.0",
        "co-mocha": "^1.1.2"
      }
    });
    pkg.keywords = pkg.keywords || [];
    pkg.keywords.push('generator-koa-sudiyi');

    pkg.name = this.props.projectName;
    pkg.description = this.props.projectDesc;
    pkg.main = this.props.projectMain;
    pkg.author = this.props.projectAuthor;
    pkg.license = this.props.projectLicense;

    this.fs.writeJSON(this.destinationPath('package.json'), pkg);

    this.mkdir('lib/controllers');
    this.mkdir('lib/middlewares');
    this.mkdir('lib/middlewares/common');
    this.mkdir('lib/models');
    this.mkdir('lib/db');
    this.mkdir('lib/logger');
    this.mkdir('lib/routes');
    this.mkdir('lib/utils');
    this.mkdir('public');

    this.fs.copy(
      this.templatePath('dummyfile.txt'),
      this.destinationPath('dummyfile.txt')
    );
    this.fs.copy(
      this.templatePath('gitignore_tmpl'),
      this.destinationPath('.gitignore')
    );
    this.fs.copy(
      this.templatePath('jshintrc_tmpl'),
      this.destinationPath('.jshintrc')
    );
    this.fs.copy(
      this.templatePath('app_tmpl.js'),
      this.destinationPath('app.js')
    );

    this.fs.copy(
      this.templatePath('index_tmpl.js'),
      'lib/index.js'
    );
    this.fs.copy(
      this.templatePath('request_id_tmpl.js'),
      'lib/middlewares/common/request_id.js'
    );

  },

  install: function () {
    this.installDependencies();
  }
})
;
<|endoftext|>


<commit_before>(function (window, angular) {
    'use strict';

    /**
     * Adds a leading zero to any number with only one digit
     * @param {Number} n Number
     * @return {String} Padded number
     */
    var pad = (n) => n > 9 ? n : '0' + n;

    /**
     * Returns the given date formated as DD/MM/YYYY HH:mm
     * @param {Date} d Date
     * @return {String}
     */
    var strDate = (d) => [d.getDate(), d.getMonth() + 1, d.getFullYear()].map(pad).join('/')
        + ' ' + [d.getHours(), d.getMinutes()].map(pad).join(':');

    var app = angular.module('app', []);

    app.service('storage', function () {
        return {
            /**
             * Stores the given value at the given key on localStorage
             * @method store
             * @param {String} k Key
             * @param {*}      v Value
             */
            store: (k, v) => localStorage.setItem(k, angular.toJson(v)),

            /**
             * Retrieves the value at the given key
             * @method get
             * @param {String} k Key
             * @return {*}
             */
            get: (k) => angular.fromJson(localStorage.getItem(k))
        };
    });

    app.controller('TodoCtrl', ['$scope', 'storage', function ($scope, storage) {
        $scope.tasks = storage.get('tasks') || [];

        /**
         * Saves the tasks array to localStorage
         */
        var save = () => storage.store('tasks', $scope.tasks);

        /**
         * Adds a new task
         * @param {String} task Title of the task
         */
        $scope.addTask = function (task) {
            if (task.trim().length > 0) {
                $scope.tasks.push({
                    title: task,
                    added: strDate(new Date())
                });
                $scope.$digest();
                save();
            }
        };

        /**
         * Removes the task at the given index
         * @param {Number} i Index where the task is in the tasks array
         */
        $scope.removeTask = function (i) {
            $scope.tasks.splice(i, 1);
            $scope.$digest();
            save();
        };

        /**
         * Update the title of a task element
         * @param {Number} i     Index where the task is in the tasks array
         * @param {String} title New title for the task
         */
        $scope.updateTitle = function (i, title) {
            $scope.tasks[i].title = title;
            $scope.$digest();
            save();
        };
    }]);

    app.directive('todoList', function () {
        return {
            restrict: 'E',
            replace: true,
            scope: {
                tasks: '='
            },
            link: function (scope, elem) {
                scope.$watchCollection('tasks', function (val) {
                    React.renderComponent(
                        TodoList({tasks: val, scope: scope.$parent}),
                        elem[0]
                    );
                });
            }
        }
    });

    app.directive('todoForm', function () {
        return {
            restrict: 'E',
            replace: true,
            link: function (scope, elem) {
                React.renderComponent(
                    TodoForm({scope: scope}), elem[0]
                );
            }
        };
    });

}(window, angular));<commit_msg>Update app.js<commit_after>(function (window, angular, React) {
    'use strict';

    /**
     * Adds a leading zero to any number with only one digit
     * @param {Number} n Number
     * @return {String} Padded number
     */
    var pad = (n) => n > 9 ? n : '0' + n;

    /**
     * Returns the given date formated as DD/MM/YYYY HH:mm
     * @param {Date} d Date
     * @return {String}
     */
    var strDate = (d) => [d.getDate(), d.getMonth() + 1, d.getFullYear()].map(pad).join('/')
        + ' ' + [d.getHours(), d.getMinutes()].map(pad).join(':');

    var app = angular.module('app', []);

    app.service('storage', function () {
        return {
            /**
             * Stores the given value at the given key on localStorage
             * @method store
             * @param {String} k Key
             * @param {*}      v Value
             */
            store: (k, v) => localStorage.setItem(k, angular.toJson(v)),

            /**
             * Retrieves the value at the given key
             * @method get
             * @param {String} k Key
             * @return {*}
             */
            get: (k) => angular.fromJson(localStorage.getItem(k))
        };
    });

    app.controller('TodoCtrl', ['$scope', 'storage', function ($scope, storage) {
        $scope.tasks = storage.get('tasks') || [];

        /**
         * Saves the tasks array to localStorage
         */
        var save = () => storage.store('tasks', $scope.tasks);

        /**
         * Adds a new task
         * @param {String} task Title of the task
         */
        $scope.addTask = function (task) {
            if (task.trim().length > 0) {
                $scope.tasks.push({
                    title: task,
                    added: strDate(new Date())
                });
                $scope.$digest();
                save();
            }
        };

        /**
         * Removes the task at the given index
         * @param {Number} i Index where the task is in the tasks array
         */
        $scope.removeTask = function (i) {
            $scope.tasks.splice(i, 1);
            $scope.$digest();
            save();
        };

        /**
         * Update the title of a task element
         * @param {Number} i     Index where the task is in the tasks array
         * @param {String} title New title for the task
         */
        $scope.updateTitle = function (i, title) {
            $scope.tasks[i].title = title;
            $scope.$digest();
            save();
        };
    }]);

    app.directive('todoList', function () {
        return {
            restrict: 'E',
            replace: true,
            scope: {
                tasks: '='
            },
            link: function (scope, elem) {
                scope.$watchCollection('tasks', function (val) {
                    React.renderComponent(
                        TodoList({tasks: val, scope: scope.$parent}),
                        elem[0]
                    );
                });
            }
        }
    });

    app.directive('todoForm', function () {
        return {
            restrict: 'E',
            replace: true,
            link: function (scope, elem) {
                React.renderComponent(
                    TodoForm({scope: scope}), elem[0]
                );
            }
        };
    });

}(window, angular, React));
<|endoftext|>


<commit_before>'use strict';
var util = require('util'),
    generators = require('yeoman-generator'),
    chalk = require('chalk'),
    scriptBase = require('../generator-base'),
    cleanup = require('../cleanup'),
    prompts = require('./prompts'),
    packagejs = require('../../package.json'),
    exec = require('child_process').exec;

var JhipsterGenerator = generators.Base.extend({});

util.inherits(JhipsterGenerator, scriptBase);

/* Constants use throughout */
const constants = require('../generator-constants');

module.exports = JhipsterGenerator.extend({
    constructor: function () {
        generators.Base.apply(this, arguments);

        this.configOptions = {};
        // This adds support for a `--skip-client` flag
        this.option('skip-client', {
            desc: 'Skip the client-side application generation',
            type: Boolean,
            defaults: false
        });

        // This adds support for a `--skip-server` flag
        this.option('skip-server', {
            desc: 'Skip the server-side application generation',
            type: Boolean,
            defaults: false
        });

        // This adds support for a `--skip-user-management` flag
        this.option('skip-user-management', {
            desc: 'Skip the user management module during app generation',
            type: Boolean,
            defaults: false
        });

        // This adds support for a `--[no-]i18n` flag
        this.option('i18n', {
            desc: 'Disable or enable i18n when skipping client side generation, has no effect otherwise',
            type: Boolean,
            defaults: true
        });

        // This adds support for a `--with-entities` flag
        this.option('with-entities', {
            desc: 'Regenerate the existing entities if any',
            type: Boolean,
            defaults: false
        });

        // This adds support for a `--skip-checks` flag
        this.option('skip-checks', {
            desc: 'Check the status of the required tools',
            type: Boolean,
            defaults: false
        });

        // This adds support for a `--jhi-prefix` flag
        this.option('jhi-prefix', {
            desc: 'Add prefix before services, controllers and states name',
            type: String,
            defaults: 'jhi'
        });

        // This adds support for a `--npm` flag
        this.option('npm', {
            desc: 'Use npm instead of yarn',
            type: Boolean,
            defaults: false
        });

        this.currentQuestion = 0;
        this.totalQuestions = constants.QUESTIONS;
        this.skipClient = this.configOptions.skipClient = this.options['skip-client'] || this.config.get('skipClient');
        this.skipServer = this.configOptions.skipServer = this.options['skip-server'] || this.config.get('skipServer');
        this.skipUserManagement = this.configOptions.skipUserManagement = this.options['skip-user-management'] || this.config.get('skipUserManagement');
        this.jhiPrefix = this.configOptions.jhiPrefix || this.config.get('jhiPrefix') || this.options['jhi-prefix'];
        this.withEntities = this.options['with-entities'];
        this.skipChecks = this.options['skip-checks'];
        this.yarnInstall = this.configOptions.yarnInstall = !this.options['npm'];
    },

    initializing: {
        displayLogo: function () {
            this.printJHipsterLogo();
        },

        checkJava: function () {
            if (this.skipChecks || this.skipServer) return;
            var done = this.async();
            exec('java -version', function (err, stdout, stderr) {
                if (err) {
                    this.warning('Java 8 is not found on your computer.');
                } else {
                    var javaVersion = stderr.match(/(?:java|openjdk) version "(.*)"/)[1];
                    if (!javaVersion.match(/1\.8/)) {
                        this.warning('Java 8 is not found on your computer. Your Java version is: ' + chalk.yellow(javaVersion));
                    }
                }
                done();
            }.bind(this));
        },

        checkGit: function () {
            if (this.skipChecks || this.skipClient) return;
            var done = this.async();
            this.isGitInstalled(function (code) {
                this.gitInstalled = code === 0;
                done();
            }.bind(this));
        },

        checkGitConnection: function () {
            if (!this.gitInstalled) return;
            var done = this.async();
            exec('git ls-remote git://github.com/jhipster/generator-jhipster.git HEAD', {timeout: 15000}, function (error) {
                if (error) {
                    this.warning('Failed to connect to "git://github.com"\n',
                        ' 1. Check your Internet connection.\n',
                        ' 2. If you are using an HTTP proxy, try this command: ' + chalk.yellow('git config --global url."https://".insteadOf git://')
                    );
                }
                done();
            }.bind(this));
        },

        checkYarn: function () {
            if (this.skipChecks || !this.yarnInstall) return;
            var done = this.async();
            exec('yarn --version', function (err) {
                if (err) {
                    this.warning('yarn is not found on your computer.\n',
                        ' Using npm instead');
                    this.yarnInstall = false;
                } else {
                    this.yarnInstall = true;
                }
                done();
            }.bind(this));
        },

        validate: function () {
            if (this.skipServer && this.skipClient) {
                this.error(chalk.red('You can not pass both ' + chalk.yellow('--skip-client') + ' and ' + chalk.yellow('--skip-server') + ' together'));
            }
        },

        setupVars: function () {
            this.applicationType = this.config.get('applicationType');
            if (!this.applicationType) {
                this.applicationType = 'monolith';
            }
            this.baseName = this.config.get('baseName');
            this.jhipsterVersion = this.config.get('jhipsterVersion');
            this.clientFramework = this.config.get('clientFramework');
            if (!this.clientFramework) {
                /* for backward compatibility */
                this.clientFramework = 'angular1';
            }
            this.otherModules = this.config.get('otherModules');
            this.testFrameworks = this.config.get('testFrameworks');
            this.enableTranslation = this.config.get('enableTranslation');
            this.nativeLanguage = this.config.get('nativeLanguage');
            this.languages = this.config.get('languages');
            var configFound = this.baseName !== undefined && this.applicationType !== undefined;
            if (configFound) {
                this.existingProject = true;
                // If translation is not defined, it is enabled by default
                if (this.enableTranslation === undefined) {
                    this.enableTranslation = true;
                }
            }
            this.clientPackageManager = this.config.get('clientPackageManager');
            if (!this.clientPackageManager) {
                if (this.yarnInstall) {
                    this.clientPackageManager = 'yarn';
                } else {
                    this.clientPackageManager = 'npm';
                }
            }
        }
    },

    prompting: {
        askForInsightOptIn: prompts.askForInsightOptIn,

        askForApplicationType: prompts.askForApplicationType,

        askForClient: prompts.askForClient,

        askForModuleName: prompts.askForModuleName,

        askForMoreModules: prompts.askForMoreModules,
    },

    configuring: {
        setup: function () {
            this.configOptions.skipI18nQuestion = true;
            this.configOptions.baseName = this.baseName;
            this.configOptions.logo = false;
            this.configOptions.clientFramework = this.clientFramework;
            this.configOptions.otherModules = this.otherModules;
            this.configOptions.lastQuestion = this.currentQuestion;
            this.generatorType = 'app';
            if (this.applicationType === 'microservice') {
                this.skipClient = true;
                this.generatorType = 'server';
                this.skipUserManagement = this.configOptions.skipUserManagement = true;
            }
            if (this.applicationType === 'uaa') {
                this.skipClient = true;
                this.generatorType = 'server';
                this.skipUserManagement = this.configOptions.skipUserManagement = false;
                this.authenticationType = this.configOptions.authenticationType = 'uaa';
            }
            if (this.skipClient) {
                // defaults to use when skipping client
                this.generatorType = 'server';
                this.configOptions.enableTranslation = this.options['i18n'];
            }
            if (this.skipServer) {
                this.generatorType = 'client';
                // defaults to use when skipping server
            }
            this.configOptions.clientPackageManager = this.clientPackageManager;
        },

        composeServer: function () {
            if (this.skipServer) return;

            this.composeWith('jhipster:server', {
                options: {
                    'client-hook': !this.skipClient,
                    configOptions: this.configOptions,
                    force: this.options['force']
                }
            }, {
                local: require.resolve('../server')
            });
        },

        composeClient: function () {
            if (this.skipClient) return;

            this.composeWith('jhipster:client', {
                options: {
                    'skip-install': this.options['skip-install'],
                    configOptions: this.configOptions,
                    force: this.options['force']
                }
            }, {
                local: require.resolve('../client')
            });
        },

        askFori18n: prompts.askFori18n
    },

    default: {

        askForTestOpts: prompts.askForTestOpts,

        setSharedConfigOptions: function () {
            this.configOptions.lastQuestion = this.currentQuestion;
            this.configOptions.totalQuestions = this.totalQuestions;
            this.configOptions.testFrameworks = this.testFrameworks;
            this.configOptions.enableTranslation = this.enableTranslation;
            this.configOptions.nativeLanguage = this.nativeLanguage;
            this.configOptions.languages = this.languages;
            this.configOptions.clientFramework = this.clientFramework;
            this.configOptions.clientPackageManager = this.clientPackageManager;
        },

        insight: function () {
            var insight = this.insight();
            insight.trackWithEvent('generator', 'app');
            insight.track('app/applicationType', this.applicationType);
            insight.track('app/clientFramework', this.clientFramework);
            insight.track('app/testFrameworks', this.testFrameworks);
            insight.track('app/otherModules', this.otherModules);
        },

        composeLanguages: function () {
            if (this.skipI18n) return;
            this.composeLanguagesSub(this, this.configOptions, this.generatorType);
        },

        saveConfig: function () {
            this.config.set('jhipsterVersion', packagejs.version);
            this.config.set('applicationType', this.applicationType);
            this.config.set('clientFramework', this.clientFramework);
            this.config.set('baseName', this.baseName);
            this.config.set('testFrameworks', this.testFrameworks);
            this.config.set('jhiPrefix', this.jhiPrefix);
            this.config.set('otherModules', this.otherModules);
            this.skipClient && this.config.set('skipClient', true);
            this.skipServer && this.config.set('skipServer', true);
            this.skipUserManagement && this.config.set('skipUserManagement', true);
            this.config.set('enableTranslation', this.enableTranslation);
            if (this.enableTranslation) {
                this.config.set('nativeLanguage', this.nativeLanguage);
                this.config.set('languages', this.languages);
            }
            this.config.set('clientPackageManager', this.clientPackageManager);
        }
    },

    writing: {
        cleanup: function () {
            cleanup.cleanupOldFiles(this, this.javaDir, this.testDir);
        },

        regenerateEntities: function () {
            if (this.withEntities) {
                this.getExistingEntities().forEach(function (entity) {
                    this.composeWith('jhipster:entity', {
                        options: {
                            regenerate: true,
                            'skip-install': true,
                            force: this.options['force']
                        },
                        args: [entity.name]
                    }, {
                        local: require.resolve('../entity')
                    });
                }, this);
            }
        }
    },

    end: {
        localInstall: function() {
            if (this.skipClient === true) {
                if (this.otherModules === undefined) {
                    this.otherModules = [];
                }
                // Generate a package.json file containing the current version of the generator as dependency
                this.template('_skipClientApp.package.json', 'package.json', this, {});

                if (this.yarnInstall) {
                    this.log(chalk.bold(`\nInstalling generator-jhipster@${this.jhipsterVersion} locally using yarn`));
                    this.spawnCommand('yarn', ['install']);
                }
                else {
                    this.log(chalk.bold(`\nInstalling generator-jhipster@${this.jhipsterVersion} locally using npm`));
                    this.npmInstall();
                }
            }
        },

        afterRunHook: function () {
            try {
                var modules = this.getModuleHooks();
                if (modules.length > 0) {
                    this.log('\n' + chalk.bold.green('Running post run module hooks\n'));
                    // run through all post app creation module hooks
                    this.callHooks('app', 'post', {
                        appConfig: this.configOptions,
                        force: this.options['force']
                    });
                }
            } catch (err) {
                this.log('\n' + chalk.bold.red('Running post run module hooks failed. No modification done to the generated app.'));
            }
        }
    }
});
<commit_msg>respect skip-install flag<commit_after>'use strict';
var util = require('util'),
    generators = require('yeoman-generator'),
    chalk = require('chalk'),
    scriptBase = require('../generator-base'),
    cleanup = require('../cleanup'),
    prompts = require('./prompts'),
    packagejs = require('../../package.json'),
    exec = require('child_process').exec;

var JhipsterGenerator = generators.Base.extend({});

util.inherits(JhipsterGenerator, scriptBase);

/* Constants use throughout */
const constants = require('../generator-constants');

module.exports = JhipsterGenerator.extend({
    constructor: function () {
        generators.Base.apply(this, arguments);

        this.configOptions = {};
        // This adds support for a `--skip-client` flag
        this.option('skip-client', {
            desc: 'Skip the client-side application generation',
            type: Boolean,
            defaults: false
        });

        // This adds support for a `--skip-server` flag
        this.option('skip-server', {
            desc: 'Skip the server-side application generation',
            type: Boolean,
            defaults: false
        });

        // This adds support for a `--skip-user-management` flag
        this.option('skip-user-management', {
            desc: 'Skip the user management module during app generation',
            type: Boolean,
            defaults: false
        });

        // This adds support for a `--[no-]i18n` flag
        this.option('i18n', {
            desc: 'Disable or enable i18n when skipping client side generation, has no effect otherwise',
            type: Boolean,
            defaults: true
        });

        // This adds support for a `--with-entities` flag
        this.option('with-entities', {
            desc: 'Regenerate the existing entities if any',
            type: Boolean,
            defaults: false
        });

        // This adds support for a `--skip-checks` flag
        this.option('skip-checks', {
            desc: 'Check the status of the required tools',
            type: Boolean,
            defaults: false
        });

        // This adds support for a `--jhi-prefix` flag
        this.option('jhi-prefix', {
            desc: 'Add prefix before services, controllers and states name',
            type: String,
            defaults: 'jhi'
        });

        // This adds support for a `--npm` flag
        this.option('npm', {
            desc: 'Use npm instead of yarn',
            type: Boolean,
            defaults: false
        });

        this.currentQuestion = 0;
        this.totalQuestions = constants.QUESTIONS;
        this.skipClient = this.configOptions.skipClient = this.options['skip-client'] || this.config.get('skipClient');
        this.skipServer = this.configOptions.skipServer = this.options['skip-server'] || this.config.get('skipServer');
        this.skipUserManagement = this.configOptions.skipUserManagement = this.options['skip-user-management'] || this.config.get('skipUserManagement');
        this.jhiPrefix = this.configOptions.jhiPrefix || this.config.get('jhiPrefix') || this.options['jhi-prefix'];
        this.withEntities = this.options['with-entities'];
        this.skipChecks = this.options['skip-checks'];
        this.yarnInstall = this.configOptions.yarnInstall = !this.options['npm'];
    },

    initializing: {
        displayLogo: function () {
            this.printJHipsterLogo();
        },

        checkJava: function () {
            if (this.skipChecks || this.skipServer) return;
            var done = this.async();
            exec('java -version', function (err, stdout, stderr) {
                if (err) {
                    this.warning('Java 8 is not found on your computer.');
                } else {
                    var javaVersion = stderr.match(/(?:java|openjdk) version "(.*)"/)[1];
                    if (!javaVersion.match(/1\.8/)) {
                        this.warning('Java 8 is not found on your computer. Your Java version is: ' + chalk.yellow(javaVersion));
                    }
                }
                done();
            }.bind(this));
        },

        checkGit: function () {
            if (this.skipChecks || this.skipClient) return;
            var done = this.async();
            this.isGitInstalled(function (code) {
                this.gitInstalled = code === 0;
                done();
            }.bind(this));
        },

        checkGitConnection: function () {
            if (!this.gitInstalled) return;
            var done = this.async();
            exec('git ls-remote git://github.com/jhipster/generator-jhipster.git HEAD', {timeout: 15000}, function (error) {
                if (error) {
                    this.warning('Failed to connect to "git://github.com"\n',
                        ' 1. Check your Internet connection.\n',
                        ' 2. If you are using an HTTP proxy, try this command: ' + chalk.yellow('git config --global url."https://".insteadOf git://')
                    );
                }
                done();
            }.bind(this));
        },

        checkYarn: function () {
            if (this.skipChecks || !this.yarnInstall) return;
            var done = this.async();
            exec('yarn --version', function (err) {
                if (err) {
                    this.warning('yarn is not found on your computer.\n',
                        ' Using npm instead');
                    this.yarnInstall = false;
                } else {
                    this.yarnInstall = true;
                }
                done();
            }.bind(this));
        },

        validate: function () {
            if (this.skipServer && this.skipClient) {
                this.error(chalk.red('You can not pass both ' + chalk.yellow('--skip-client') + ' and ' + chalk.yellow('--skip-server') + ' together'));
            }
        },

        setupVars: function () {
            this.applicationType = this.config.get('applicationType');
            if (!this.applicationType) {
                this.applicationType = 'monolith';
            }
            this.baseName = this.config.get('baseName');
            this.jhipsterVersion = this.config.get('jhipsterVersion');
            this.clientFramework = this.config.get('clientFramework');
            if (!this.clientFramework) {
                /* for backward compatibility */
                this.clientFramework = 'angular1';
            }
            this.otherModules = this.config.get('otherModules');
            this.testFrameworks = this.config.get('testFrameworks');
            this.enableTranslation = this.config.get('enableTranslation');
            this.nativeLanguage = this.config.get('nativeLanguage');
            this.languages = this.config.get('languages');
            var configFound = this.baseName !== undefined && this.applicationType !== undefined;
            if (configFound) {
                this.existingProject = true;
                // If translation is not defined, it is enabled by default
                if (this.enableTranslation === undefined) {
                    this.enableTranslation = true;
                }
            }
            this.clientPackageManager = this.config.get('clientPackageManager');
            if (!this.clientPackageManager) {
                if (this.yarnInstall) {
                    this.clientPackageManager = 'yarn';
                } else {
                    this.clientPackageManager = 'npm';
                }
            }
        }
    },

    prompting: {
        askForInsightOptIn: prompts.askForInsightOptIn,

        askForApplicationType: prompts.askForApplicationType,

        askForClient: prompts.askForClient,

        askForModuleName: prompts.askForModuleName,

        askForMoreModules: prompts.askForMoreModules,
    },

    configuring: {
        setup: function () {
            this.configOptions.skipI18nQuestion = true;
            this.configOptions.baseName = this.baseName;
            this.configOptions.logo = false;
            this.configOptions.clientFramework = this.clientFramework;
            this.configOptions.otherModules = this.otherModules;
            this.configOptions.lastQuestion = this.currentQuestion;
            this.generatorType = 'app';
            if (this.applicationType === 'microservice') {
                this.skipClient = true;
                this.generatorType = 'server';
                this.skipUserManagement = this.configOptions.skipUserManagement = true;
            }
            if (this.applicationType === 'uaa') {
                this.skipClient = true;
                this.generatorType = 'server';
                this.skipUserManagement = this.configOptions.skipUserManagement = false;
                this.authenticationType = this.configOptions.authenticationType = 'uaa';
            }
            if (this.skipClient) {
                // defaults to use when skipping client
                this.generatorType = 'server';
                this.configOptions.enableTranslation = this.options['i18n'];
            }
            if (this.skipServer) {
                this.generatorType = 'client';
                // defaults to use when skipping server
            }
            this.configOptions.clientPackageManager = this.clientPackageManager;
        },

        composeServer: function () {
            if (this.skipServer) return;

            this.composeWith('jhipster:server', {
                options: {
                    'client-hook': !this.skipClient,
                    configOptions: this.configOptions,
                    force: this.options['force']
                }
            }, {
                local: require.resolve('../server')
            });
        },

        composeClient: function () {
            if (this.skipClient) return;

            this.composeWith('jhipster:client', {
                options: {
                    'skip-install': this.options['skip-install'],
                    configOptions: this.configOptions,
                    force: this.options['force']
                }
            }, {
                local: require.resolve('../client')
            });
        },

        askFori18n: prompts.askFori18n
    },

    default: {

        askForTestOpts: prompts.askForTestOpts,

        setSharedConfigOptions: function () {
            this.configOptions.lastQuestion = this.currentQuestion;
            this.configOptions.totalQuestions = this.totalQuestions;
            this.configOptions.testFrameworks = this.testFrameworks;
            this.configOptions.enableTranslation = this.enableTranslation;
            this.configOptions.nativeLanguage = this.nativeLanguage;
            this.configOptions.languages = this.languages;
            this.configOptions.clientFramework = this.clientFramework;
            this.configOptions.clientPackageManager = this.clientPackageManager;
        },

        insight: function () {
            var insight = this.insight();
            insight.trackWithEvent('generator', 'app');
            insight.track('app/applicationType', this.applicationType);
            insight.track('app/clientFramework', this.clientFramework);
            insight.track('app/testFrameworks', this.testFrameworks);
            insight.track('app/otherModules', this.otherModules);
        },

        composeLanguages: function () {
            if (this.skipI18n) return;
            this.composeLanguagesSub(this, this.configOptions, this.generatorType);
        },

        saveConfig: function () {
            this.config.set('jhipsterVersion', packagejs.version);
            this.config.set('applicationType', this.applicationType);
            this.config.set('clientFramework', this.clientFramework);
            this.config.set('baseName', this.baseName);
            this.config.set('testFrameworks', this.testFrameworks);
            this.config.set('jhiPrefix', this.jhiPrefix);
            this.config.set('otherModules', this.otherModules);
            this.skipClient && this.config.set('skipClient', true);
            this.skipServer && this.config.set('skipServer', true);
            this.skipUserManagement && this.config.set('skipUserManagement', true);
            this.config.set('enableTranslation', this.enableTranslation);
            if (this.enableTranslation) {
                this.config.set('nativeLanguage', this.nativeLanguage);
                this.config.set('languages', this.languages);
            }
            this.config.set('clientPackageManager', this.clientPackageManager);
        }
    },

    writing: {
        cleanup: function () {
            cleanup.cleanupOldFiles(this, this.javaDir, this.testDir);
        },

        regenerateEntities: function () {
            if (this.withEntities) {
                this.getExistingEntities().forEach(function (entity) {
                    this.composeWith('jhipster:entity', {
                        options: {
                            regenerate: true,
                            'skip-install': true,
                            force: this.options['force']
                        },
                        args: [entity.name]
                    }, {
                        local: require.resolve('../entity')
                    });
                }, this);
            }
        }
    },

    end: {
        localInstall: function() {
            if (this.skipClient && !this.options['skip-install']) {
                if (this.otherModules === undefined) {
                    this.otherModules = [];
                }
                // Generate a package.json file containing the current version of the generator as dependency
                this.template('_skipClientApp.package.json', 'package.json', this, {});

                if (this.yarnInstall) {
                    this.log(chalk.bold(`\nInstalling generator-jhipster@${this.jhipsterVersion} locally using yarn`));
                    this.spawnCommand('yarn', ['install']);
                }
                else {
                    this.log(chalk.bold(`\nInstalling generator-jhipster@${this.jhipsterVersion} locally using npm`));
                    this.npmInstall();
                }
            }
        },

        afterRunHook: function () {
            try {
                var modules = this.getModuleHooks();
                if (modules.length > 0) {
                    this.log('\n' + chalk.bold.green('Running post run module hooks\n'));
                    // run through all post app creation module hooks
                    this.callHooks('app', 'post', {
                        appConfig: this.configOptions,
                        force: this.options['force']
                    });
                }
            } catch (err) {
                this.log('\n' + chalk.bold.red('Running post run module hooks failed. No modification done to the generated app.'));
            }
        }
    }
});
<|endoftext|>