<commit_before>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var GitHubApi = require('github');

var githubOptions = {
  version: '3.0.0'
};
var github = new GitHubApi(githubOptions);

var githubUserInfo = function (name, cb) {
  github.user.getFrom({
    user: name
  }, function (err, res) {
    if (err) {
      throw err;
    }
    cb(JSON.parse(JSON.stringify(res)));
  });
};

var ModuleGenerator = module.exports = function ModuleGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    this.installDependencies({
        npm: true,
        bower: false
    });
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(ModuleGenerator, yeoman.generators.Base);

ModuleGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  var prompts = [{
    type:'input',
    name:'githubUser',
    message:'What is your github username?'
  },{
    type:'input',
    name:'moduleName',
    message:'What is the name of the module?',
    default: 'toto'
  },
  {
    type:'input',
    name:'moduleDescription',
    message:'Can you give a description of your module?',
    default: ""
  },
  {
    type:'input',
    name:'dependencies',
    message:'Do you want to add dependencies? (sepatate modules with comma)',
    default: ""
  }];

  this.prompt(prompts, function (props) {
    this.githubUser = props.githubUser;
    this.moduleName = props.moduleName;
    this.moduleDescription = props.moduleDescription;
    this.dependencies = props.dependencies.split(',').filter(function (dep) {
        return dep.length > 0;
    });

    cb();
  }.bind(this));
};

ModuleGenerator.prototype.userInfo = function userInfo() {
  var done = this.async();

  githubUserInfo(this.githubUser, function (res) {
    this.realname = res.name;
    this.email = res.email;
    this.githubUrl = res.html_url;
    done();
  }.bind(this));
};

ModuleGenerator.prototype.lib = function app() {
  this.mkdir('lib');
  this.template('lib/_index.js', 'lib/index.js');
  this.template('_package.json', 'package.json');
  this.template('_README.md', 'README.md');
};
<commit_msg>add default module name<commit_after>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var GitHubApi = require('github');

var githubOptions = {
  version: '3.0.0'
};
var github = new GitHubApi(githubOptions);

var githubUserInfo = function (name, cb) {
  github.user.getFrom({
    user: name
  }, function (err, res) {
    if (err) {
      throw err;
    }
    cb(JSON.parse(JSON.stringify(res)));
  });
};

var ModuleGenerator = module.exports = function ModuleGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    this.installDependencies({
        npm: true,
        bower: false
    });
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(ModuleGenerator, yeoman.generators.Base);

ModuleGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  var prompts = [{
    type:'input',
    name:'githubUser',
    message:'What is your github username?'
  },{
    type:'input',
    name:'moduleName',
    message:'What is the name of the module?',
    default: path.basename(process.cwd())
  },
  {
    type:'input',
    name:'moduleDescription',
    message:'Can you give a description of your module?',
    default: ""
  },
  {
    type:'input',
    name:'dependencies',
    message:'Do you want to add dependencies? (sepatate modules with comma)',
    default: ""
  }];

  this.prompt(prompts, function (props) {
    this.githubUser = props.githubUser;
    this.moduleName = props.moduleName;
    this.moduleDescription = props.moduleDescription;
    this.dependencies = props.dependencies.split(',').filter(function (dep) {
        return dep.length > 0;
    });

    cb();
  }.bind(this));
};

ModuleGenerator.prototype.userInfo = function userInfo() {
  var done = this.async();

  githubUserInfo(this.githubUser, function (res) {
    this.realname = res.name;
    this.email = res.email;
    this.githubUrl = res.html_url;
    done();
  }.bind(this));
};

ModuleGenerator.prototype.lib = function app() {
  this.mkdir('lib');
  this.template('lib/_index.js', 'lib/index.js');
  this.template('_package.json', 'package.json');
  this.template('_README.md', 'README.md');
};
<|endoftext|>


<commit_before>/**
 * http://garbas.github.com/jquery.recurrenceinput.js
 *
 * Author: Rok Garbas <rok@garbas.si>
 * Since: Sep 2010
 * Date: XX-XX-XXXX
 */
(function($) {

    /**
     * TODO:
     *  - start date, end date and number of recurrences for each rule
     *  - reuse start date from other fields
     *
     */
    var default_conf = {
        'widget-tmpl': '#jquery-recurrenceinput-widget-tmpl',
        'rule-tmpl': '#jquery-recurrenceinput-rule-tmpl',
        'date-tmpl': '#jquery-recurrenceinput-date-tmpl',
        'months': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                   'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    };

    // private

    function Recurrenceinput (textarea, conf) {

        var self = this;
        var widget = $(conf['widget-tmpl']).tmpl();

        var today = new Date();
        var dateDay = today.getDate();
        var dateMonth = today.getMonth();
        var dateYear = today.getFullYear();

        /*
         * Initial steps to activate widget
         */

        // add actions to widget buttons
        widget.find('p.button > a')
            .unbind('click')
            .click(function (e) {
                e.preventDefault();

                var class_name = $(this).attr('class');
                if (class_name == 'button-add-rrule') { add_rule('rrule') }
                else if (class_name == 'button-add-exrule') { add_rule('exrule') }
                else if (class_name == 'button-add-rdate') { add_date('rdate') }
                else if (class_name == 'button-add-exdate') { add_date('exdate') }
            });

        function init_data(class, tmpl_id) {

            var rule = $(conf[tmpl_id]).tmpl({
                months: conf.months, dateDay: dateDay,
                dateMonth: dateMonth, dateYear: dateYear });
            rule.addClass(class);

            // remove rule action
            $('a.remove', rule).unbind("click").click(function () {
                $(this).closest("li.rule").slideUp("fast", function() { $(this).remove() });
            });

            // activate dateinput calendar
            rule.find('input[class=recurrence_calendar]')
                    .dateinput({
                        value: new Date(dateYear, dateMonth, dateDay),
                        change: function() {
                            var value = this.getValue("yyyy-m-d").split("-");
                            this.getInput().parent().find('input=[name$=_year]').val(value[0]);
                            this.getInput().parent().find('select=[name$=_month]').val(value[1]);
                            this.getInput().parent().find('input=[name$=_day]').val(value[2]); },
                        selectors: true,
                        trigger: true,
                        yearRange: [-10, 10] })
                    .unbind('change')
                    .bind('onShow', function (event) {
                        var trigger_offset = $(this).next().offset();
                        $(this).data('dateinput').getCalendar().offset(
                            {top: trigger_offset.top+33, left: trigger_offset.left}
                        );
                    });

            // append rule to ruleset
            rule.hide();
            $('.recurrenceinput-' + class + " ul.ruleset", widget).append(rule);
            rule.slideDown("fast");

            return rule;
        }

        function add_date(date_class, initial_data) {

            if (initial_data) {
                dateYear = initial_data.substring(0,4);
                dateMonth = initial_data.substring(4,6);
                dateDay = initial_data.substring(6,8);
            }

            init_data(date_class, 'date-tmpl');
        }

        function add_rule(rule_class, initial_data) {

            var rule = init_data(rule_class, 'rule-tmpl');

            // hide options for frequencies
            $('.freq-options > div', rule).hide();

            // make label of freq option active for selection
            rule.find('.freq label').unbind("click").click(function () {
                var input = $(this).parent().find('input[name=freq]');
                input.click();
                input.change();
            });

            // select
            rule.find('.freq input[name=freq]').removeClass("active");
            rule.find('.freq input[name=freq]').unbind("change").change(function() {
                var el = $(this);

                rule.find('.freq input[name=freq]').removeClass("active");
                rule.find('.freq-options > div').hide();

                el.addClass('active');

                parent_list = el.closest("ul");
                font_size = parent_list.css('font-size').replace('px', '').replace('em','');

                rule.find('.freq-options div.' + el.val().toLowerCase())
                        .css('margin-left', + (parent_list.width() + 2*font_size))
                        .show();
            });

            // parse the initial data if it exists
            if (initial_data) {
                widget_load_from_rfc2445(rule, initial_data);
            }
        }

        function widget_load_from_rfc2445(el, initial_data) {
            /* At this point, el is a fully constructed rule div */
            // what's the frequency?
            matches = initial_data.match("^FREQ=(DAILY|WEEKLY|MONTHLY|YEARLY)");
            frequency = matches[1];

            interval = null;
            matches = initial_data.match("INTERVAL=([0-9]+);?");
            if (matches) {
                interval = matches[1];
            }

            byday = null;
            matches = initial_data.match("BYDAY=([^;]+);?");
            if (matches) {
                byday = matches[1].split(",");
            }

            bymonthday = null;
            matches = initial_data.match("BYMONTHDAY=([^;]+);?");
            if (matches) {
                bymonthday = matches[1].split(",");
            }

            bymonth = null;
            matches = initial_data.match("BYMONTH=([^;]+);?");
            if (matches) {
                bymonth = matches[1].split(",");
            }

            bysetpos = null;
            matches = initial_data.match("BYSETPOS=([^;]+);?");
            if (matches) {
                bysetpos = matches[1].split(",");
            }

            switch (frequency) {
            case "DAILY":
            case "WEEKLY":
            case "MONTHLY":
            case "YEARLY":
                $("ul.freq input", el).val([frequency]);
                $("ul.freq input[value="+frequency+"]", el).change();
                break;
            }

            switch (frequency) {
            case "DAILY":
                if (interval) {
                    $("input[name=recurrence_daily_interval]", el).val(interval);
                }
                else {
                    alert("Cannot parse! " + initial_data);
                }
                break;
            case "WEEKLY":
                if (interval) {
                    $("input[name=recurrence_weekly_interval_number]", el).val(interval);
                }
                if (byday) {
                    // TODO: if this is weekdays and interval=null, select DAILY#weekdays?
                    $('input[name^=recurrence_weekly_days_]', el).val(byday);
                }
                if (!interval) {
                    $("input[name=recurrence_weekly_interval_number]", el).val("1");
                }
                if (!byday) {
                    alert("Cannot parse! " + initial_data);
                }
                break;
            case "MONTHLY":
                break;
            case "YEARLY":
                $("ul.freq input", el).val([frequency]);
                $("ul.freq input[value="+frequency+"]", el).change();
                break;
            }
        }

        /*
         * Parsing RFC2554 from widget
         */

        // method for parsing rules (rrule and exrule)
        function parse_rule(el) {
            var str_ = '';
            frequency = el.find('input.freq.active').val();
            var result = "NO RULE FOUND"
            switch (frequency) {
            case "DAILY":
                result = parse_daily(el);
                break;
            case "WEEKLY":
                result = parse_weekly(el);
                break;
            case "MONTHLY":
                result = parse_monthly(el);
                break;
            case "YEARLY":
                result = parse_yearly(el);
                break;
            }

            return result
        }

        function parse_daily(el) {
            result = 'FREQ=DAILY'

            daily_type = $('input[name=recurrence_daily_type]:checked', el).val();

            switch (daily_type) {
            case "DAILY":
                interval = $('input[name=recurrence_daily_interval]', el).val();
                result += ";INTERVAL=" + interval;
                break;
            case "WEEKDAYS":
                result = "FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR"
                break;
            }

            return result
        }

        function parse_weekly(el) {
            result = "FREQ=WEEKLY"

            interval = $('input[name=recurrence_weekly_interval_number]', el).val();
            result += ";INTERVAL=" + interval

            days = []
            $('input[name^=recurrence_weekly_days_]:checked', el).each(function() {
                    days[days.length] = $(this).val();
                });

            if (days.length) {
                result += ";BYDAY=" + days
            }

            return result;
        }

        function parse_monthly(el) {
            result = "FREQ=MONTHLY";

            monthly_type = $('input[name=recurrence_monthly_type]:checked', el).val();

            switch (monthly_type) {
            case "dayofmonth":
                day = $("select[name=recurrence_monthly_dayofmonth_day]", el).val();
                interval = $("input[name=recurrence_monthly_dayofmonth_interval]", el).val();

                result += ";BYMONTHDAY=" + day;
                result += ";INTERVAL=" + interval;
                break;
            case "dayofweek":
                var index = $("select[name=recurrence_monthly_dayofweek_index]", el).val();
                var day = $("select[name=recurrence_monthly_dayofweek_day]", el).val();
                var interval = $("input[name=recurrence_monthly_dayofweek_interval]", el).val();

                if ($.inArray(day, ['MO','TU','WE','TH','FR','SA','SU']) > -1) {
                    result += ";BYDAY=" + index + day;
                }
                else if (day == "DAY") {
                    result += ";BYDAY=" + index;
                }
                else if (day == "WEEKDAY") {
                    result += ";BYDAY=MO,TU,WE,TH,FR;BYSETPOS=" + index;
                }
                else if (day == "WEEKEND_DAY") {
                    result += ";BYDAY=SA,SU;BYSETPOS=" + index;
                }

                result += ";INTERVAL=" + interval;
                break;
            }

            return result;
        }

        function parse_yearly(el) {
            result = "FREQ=YEARLY"

            yearly_type = $("input[name=recurrence_yearly_type]:checked", el).val();

            switch (yearly_type) {
            case "dayofmonth":
                var month = $("select[name=recurrence_yearly_dayofmonth_month]", el).val();
                var day = $("select[name=recurrence_yearly_dayofmonth_day]", el).val();

                result += ";BYMONTH=" + month;
                result += ";BYMONTHDAY=" + day;
                break;
            case "dayofweek":
                var index = $("select[name=recurrence_yearly_dayofweek_index]", el).val();
                var day = $("select[name=recurrence_yearly_dayofweek_day]", el).val();
                var month = $("select[name=recurrence_yearly_dayofweek_month]", el).val();

                result += ";BYMONTH=" + month;

                if ($.inArray(day, ['MO','TU','WE','TH','FR','SA','SU']) > -1) {
                    result += ";BYDAY=" + index + day;
                }
                else if (day == "DAY") {
                    result += ";BYDAY=" + index;
                }
                else if (day == "WEEKDAY") {
                    result += ";BYDAY=MO,TU,WE,TH,FR;BYSETPOS=" + index;
                }
                else if (day == "WEEKEND_DAY") {
                    result += ";BYDAY=SA,SU;BYSETPOS=" + index;
                }
                break;
            }

            return result;
        }

        // function for parsing dates (rdate and exdate)
        function parse_date(el) {
            var day = $("input[name=recurrence_date_day]", el).val();
            var month = $("select[name=recurrence_date_month]", el).val();
            var year = $("input[name=recurrence_date_year]", el).val();

            f_day = parseInt(day) < 10 ? "0" + day : day;
            f_month = parseInt(month) < 10 ? "0" + month : month;

            var formatted = year + f_month + f_day;

            return formatted;
        }

        /*
         * Public API of Recurrenceinput
         */

        $.extend(self, {
            widget: widget,
            initial_structure: function () { add_rule('rrule') },
            parse_rrule: function (el) { return 'RRULE:'+parse_rule(el) },
            parse_exrule: function (el) { return 'EXRULE:'+parse_rule(el) },
            parse_rdate: function (el) { return 'RDATE:'+parse_date(el) },
            parse_exdate: function (el) { return 'EXDATE:'+parse_date(el) },
            add_rule: function(rule_class, rule) { return add_rule(rule_class, rule) },
            add_date: function(date_class, rule) { return add_date(date_class, rule) },
        });

    }

    /*
     * jQuery plugin implementation
     */

    $.fn.recurrenceinput = function(conf) {

        // already installed
        if (this.data("recurrenceinput")) { return this; }

        // apply this for every textarea we can match
        this.each(function() {
            if (this.tagName == 'TEXTAREA') {

                var textarea = $(this);
                var form = textarea.closest("form");
                var recurrenceinput = new Recurrenceinput(
                    textarea,
                    $.extend(true, {}, default_conf, conf));

                //textarea.hide();

                // initialize widget
                if (textarea.val() == '') {
                    recurrenceinput.initial_structure();
                } else {
                    // Populate data from existing relations
                    rules = textarea.val().split('\n');
                    for (i = 0; i < rules.length; i++) {
                        rule = rules[i];
                        if (rule.search("^RRULE") >= 0) {
                            recurrenceinput.add_rule('rrule', rule.substring(6));
                        }
                        else if (rule.search("^RDATE") >= 0) {
                            recurrenceinput.add_date('rdate', rule.substring(6));
                        }
                        else if (rule.search("^EXRULE") >= 0) {
                            recurrenceinput.add_rule('exrule', rule.substring(7));
                        }
                        else if (rule.search("^EXDATE") >= 0) {
                            recurrenceinput.add_date('exdate', rule.substring(7));
                        }
                    }
                }

                // on form submit we write to textarea
                form.submit(function(e) {
                    e.preventDefault();

                    // create string for rule widget
                    var ruleset_str = '';
                    var f = function(pf, el) {
                        ruleset_str += pf($(el)) + "\n";
                    }
                    var widgets = recurrenceinput.widget;
                    $('div.recurrenceinput-rrule li.rule', widgets).each( function() {
                            f(recurrenceinput.parse_rrule, this)
                        });
                    $('div.recurrenceinput-exrule li.rule', widgets).each(function() {
                            f(recurrenceinput.parse_exrule, this)
                        });
                    $('div.recurrenceinput-rdate li.rule', widgets).each( function() {
                            f(recurrenceinput.parse_rdate, this)
                        });
                    $('div.recurrenceinput-exdate li.rule', widgets).each(function() {
                            f(recurrenceinput.parse_exdate, this)
                        })

                    // insert string generated form above to textarea
                    textarea.val(ruleset_str);

                    // remove widget
                    //recurrenceinput.widget.remove();
                });

                // insert recurrance widget right after textarea
                textarea.after(recurrenceinput.widget)
            };
        });
    };

})(jQuery);
<commit_msg>Prevent event bubbling in remove link code to prevent page scrolling to top when removing item<commit_after>/**
 * http://garbas.github.com/jquery.recurrenceinput.js
 *
 * Author: Rok Garbas <rok@garbas.si>
 * Since: Sep 2010
 * Date: XX-XX-XXXX
 */
(function($) {

    /**
     * TODO:
     *  - start date, end date and number of recurrences for each rule
     *  - reuse start date from other fields
     *
     */
    var default_conf = {
        'widget-tmpl': '#jquery-recurrenceinput-widget-tmpl',
        'rule-tmpl': '#jquery-recurrenceinput-rule-tmpl',
        'date-tmpl': '#jquery-recurrenceinput-date-tmpl',
        'months': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                   'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    };

    // private

    function Recurrenceinput (textarea, conf) {

        var self = this;
        var widget = $(conf['widget-tmpl']).tmpl();

        var today = new Date();
        var dateDay = today.getDate();
        var dateMonth = today.getMonth();
        var dateYear = today.getFullYear();

        /*
         * Initial steps to activate widget
         */

        // add actions to widget buttons
        widget.find('p.button > a')
            .unbind('click')
            .click(function (e) {
                e.preventDefault();

                var class_name = $(this).attr('class');
                if (class_name == 'button-add-rrule') { add_rule('rrule') }
                else if (class_name == 'button-add-exrule') { add_rule('exrule') }
                else if (class_name == 'button-add-rdate') { add_date('rdate') }
                else if (class_name == 'button-add-exdate') { add_date('exdate') }
            });

        function init_data(class, tmpl_id) {

            var rule = $(conf[tmpl_id]).tmpl({
                months: conf.months, dateDay: dateDay,
                dateMonth: dateMonth, dateYear: dateYear });
            rule.addClass(class);

            // remove rule action
            $('a.remove', rule).unbind("click").click(function (e) {
                e.preventDefault();
                $(this).closest("li.rule").slideUp("fast", function() { $(this).remove() });
            });

            // activate dateinput calendar
            rule.find('input[class=recurrence_calendar]')
                    .dateinput({
                        value: new Date(dateYear, dateMonth, dateDay),
                        change: function() {
                            var value = this.getValue("yyyy-m-d").split("-");
                            this.getInput().parent().find('input=[name$=_year]').val(value[0]);
                            this.getInput().parent().find('select=[name$=_month]').val(value[1]);
                            this.getInput().parent().find('input=[name$=_day]').val(value[2]); },
                        selectors: true,
                        trigger: true,
                        yearRange: [-10, 10] })
                    .unbind('change')
                    .bind('onShow', function (event) {
                        var trigger_offset = $(this).next().offset();
                        $(this).data('dateinput').getCalendar().offset(
                            {top: trigger_offset.top+33, left: trigger_offset.left}
                        );
                    });

            // append rule to ruleset
            rule.hide();
            $('.recurrenceinput-' + class + " ul.ruleset", widget).append(rule);
            rule.slideDown("fast");

            return rule;
        }

        function add_date(date_class, initial_data) {

            if (initial_data) {
                dateYear = initial_data.substring(0,4);
                dateMonth = initial_data.substring(4,6);
                dateDay = initial_data.substring(6,8);
            }

            init_data(date_class, 'date-tmpl');
        }

        function add_rule(rule_class, initial_data) {

            var rule = init_data(rule_class, 'rule-tmpl');

            // hide options for frequencies
            $('.freq-options > div', rule).hide();

            // make label of freq option active for selection
            rule.find('.freq label').unbind("click").click(function () {
                var input = $(this).parent().find('input[name=freq]');
                input.click();
                input.change();
            });

            // select
            rule.find('.freq input[name=freq]').removeClass("active");
            rule.find('.freq input[name=freq]').unbind("change").change(function() {
                var el = $(this);

                rule.find('.freq input[name=freq]').removeClass("active");
                rule.find('.freq-options > div').hide();

                el.addClass('active');

                parent_list = el.closest("ul");
                font_size = parent_list.css('font-size').replace('px', '').replace('em','');

                rule.find('.freq-options div.' + el.val().toLowerCase())
                        .css('margin-left', + (parent_list.width() + 2*font_size))
                        .show();
            });

            // parse the initial data if it exists
            if (initial_data) {
                widget_load_from_rfc2445(rule, initial_data);
            }
        }

        function widget_load_from_rfc2445(el, initial_data) {
            /* At this point, el is a fully constructed rule div */
            // what's the frequency?
            matches = initial_data.match("^FREQ=(DAILY|WEEKLY|MONTHLY|YEARLY)");
            frequency = matches[1];

            interval = null;
            matches = initial_data.match("INTERVAL=([0-9]+);?");
            if (matches) {
                interval = matches[1];
            }

            byday = null;
            matches = initial_data.match("BYDAY=([^;]+);?");
            if (matches) {
                byday = matches[1].split(",");
            }

            bymonthday = null;
            matches = initial_data.match("BYMONTHDAY=([^;]+);?");
            if (matches) {
                bymonthday = matches[1].split(",");
            }

            bymonth = null;
            matches = initial_data.match("BYMONTH=([^;]+);?");
            if (matches) {
                bymonth = matches[1].split(",");
            }

            bysetpos = null;
            matches = initial_data.match("BYSETPOS=([^;]+);?");
            if (matches) {
                bysetpos = matches[1].split(",");
            }

            switch (frequency) {
            case "DAILY":
            case "WEEKLY":
            case "MONTHLY":
            case "YEARLY":
                $("ul.freq input", el).val([frequency]);
                $("ul.freq input[value="+frequency+"]", el).change();
                break;
            }

            switch (frequency) {
            case "DAILY":
                if (interval) {
                    $("input[name=recurrence_daily_interval]", el).val(interval);
                }
                else {
                    alert("Cannot parse! " + initial_data);
                }
                break;
            case "WEEKLY":
                if (interval) {
                    $("input[name=recurrence_weekly_interval_number]", el).val(interval);
                }
                if (byday) {
                    // TODO: if this is weekdays and interval=null, select DAILY#weekdays?
                    $('input[name^=recurrence_weekly_days_]', el).val(byday);
                }
                if (!interval) {
                    $("input[name=recurrence_weekly_interval_number]", el).val("1");
                }
                if (!byday) {
                    alert("Cannot parse! " + initial_data);
                }
                break;
            case "MONTHLY":
                break;
            case "YEARLY":
                break;
            }
        }

        /*
         * Parsing RFC2554 from widget
         */

        // method for parsing rules (rrule and exrule)
        function parse_rule(el) {
            var str_ = '';
            frequency = el.find('input.freq.active').val();
            var result = "NO RULE FOUND"
            switch (frequency) {
            case "DAILY":
                result = parse_daily(el);
                break;
            case "WEEKLY":
                result = parse_weekly(el);
                break;
            case "MONTHLY":
                result = parse_monthly(el);
                break;
            case "YEARLY":
                result = parse_yearly(el);
                break;
            }

            return result
        }

        function parse_daily(el) {
            result = 'FREQ=DAILY'

            daily_type = $('input[name=recurrence_daily_type]:checked', el).val();

            switch (daily_type) {
            case "DAILY":
                interval = $('input[name=recurrence_daily_interval]', el).val();
                result += ";INTERVAL=" + interval;
                break;
            case "WEEKDAYS":
                result = "FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR"
                break;
            }

            return result
        }

        function parse_weekly(el) {
            result = "FREQ=WEEKLY"

            interval = $('input[name=recurrence_weekly_interval_number]', el).val();
            result += ";INTERVAL=" + interval

            days = []
            $('input[name^=recurrence_weekly_days_]:checked', el).each(function() {
                    days[days.length] = $(this).val();
                });

            if (days.length) {
                result += ";BYDAY=" + days
            }

            return result;
        }

        function parse_monthly(el) {
            result = "FREQ=MONTHLY";

            monthly_type = $('input[name=recurrence_monthly_type]:checked', el).val();

            switch (monthly_type) {
            case "dayofmonth":
                day = $("select[name=recurrence_monthly_dayofmonth_day]", el).val();
                interval = $("input[name=recurrence_monthly_dayofmonth_interval]", el).val();

                result += ";BYMONTHDAY=" + day;
                result += ";INTERVAL=" + interval;
                break;
            case "dayofweek":
                var index = $("select[name=recurrence_monthly_dayofweek_index]", el).val();
                var day = $("select[name=recurrence_monthly_dayofweek_day]", el).val();
                var interval = $("input[name=recurrence_monthly_dayofweek_interval]", el).val();

                if ($.inArray(day, ['MO','TU','WE','TH','FR','SA','SU']) > -1) {
                    result += ";BYDAY=" + index + day;
                }
                else if (day == "DAY") {
                    result += ";BYDAY=" + index;
                }
                else if (day == "WEEKDAY") {
                    result += ";BYDAY=MO,TU,WE,TH,FR;BYSETPOS=" + index;
                }
                else if (day == "WEEKEND_DAY") {
                    result += ";BYDAY=SA,SU;BYSETPOS=" + index;
                }

                result += ";INTERVAL=" + interval;
                break;
            }

            return result;
        }

        function parse_yearly(el) {
            result = "FREQ=YEARLY"

            yearly_type = $("input[name=recurrence_yearly_type]:checked", el).val();

            switch (yearly_type) {
            case "dayofmonth":
                var month = $("select[name=recurrence_yearly_dayofmonth_month]", el).val();
                var day = $("select[name=recurrence_yearly_dayofmonth_day]", el).val();

                result += ";BYMONTH=" + month;
                result += ";BYMONTHDAY=" + day;
                break;
            case "dayofweek":
                var index = $("select[name=recurrence_yearly_dayofweek_index]", el).val();
                var day = $("select[name=recurrence_yearly_dayofweek_day]", el).val();
                var month = $("select[name=recurrence_yearly_dayofweek_month]", el).val();

                result += ";BYMONTH=" + month;

                if ($.inArray(day, ['MO','TU','WE','TH','FR','SA','SU']) > -1) {
                    result += ";BYDAY=" + index + day;
                }
                else if (day == "DAY") {
                    result += ";BYDAY=" + index;
                }
                else if (day == "WEEKDAY") {
                    result += ";BYDAY=MO,TU,WE,TH,FR;BYSETPOS=" + index;
                }
                else if (day == "WEEKEND_DAY") {
                    result += ";BYDAY=SA,SU;BYSETPOS=" + index;
                }
                break;
            }

            return result;
        }

        // function for parsing dates (rdate and exdate)
        function parse_date(el) {
            var day = $("input[name=recurrence_date_day]", el).val();
            var month = $("select[name=recurrence_date_month]", el).val();
            var year = $("input[name=recurrence_date_year]", el).val();

            f_day = parseInt(day) < 10 ? "0" + day : day;
            f_month = parseInt(month) < 10 ? "0" + month : month;

            var formatted = year + f_month + f_day;

            return formatted;
        }

        /*
         * Public API of Recurrenceinput
         */

        $.extend(self, {
            widget: widget,
            initial_structure: function () { add_rule('rrule') },
            parse_rrule: function (el) { return 'RRULE:'+parse_rule(el) },
            parse_exrule: function (el) { return 'EXRULE:'+parse_rule(el) },
            parse_rdate: function (el) { return 'RDATE:'+parse_date(el) },
            parse_exdate: function (el) { return 'EXDATE:'+parse_date(el) },
            add_rule: function(rule_class, rule) { return add_rule(rule_class, rule) },
            add_date: function(date_class, rule) { return add_date(date_class, rule) },
        });

    }

    /*
     * jQuery plugin implementation
     */

    $.fn.recurrenceinput = function(conf) {

        // already installed
        if (this.data("recurrenceinput")) { return this; }

        // apply this for every textarea we can match
        this.each(function() {
            if (this.tagName == 'TEXTAREA') {

                var textarea = $(this);
                var form = textarea.closest("form");
                var recurrenceinput = new Recurrenceinput(
                    textarea,
                    $.extend(true, {}, default_conf, conf));

                //textarea.hide();

                // initialize widget
                if (textarea.val() == '') {
                    recurrenceinput.initial_structure();
                } else {
                    // Populate data from existing relations
                    rules = textarea.val().split('\n');
                    for (i = 0; i < rules.length; i++) {
                        rule = rules[i];
                        if (rule.search("^RRULE") >= 0) {
                            recurrenceinput.add_rule('rrule', rule.substring(6));
                        }
                        else if (rule.search("^RDATE") >= 0) {
                            recurrenceinput.add_date('rdate', rule.substring(6));
                        }
                        else if (rule.search("^EXRULE") >= 0) {
                            recurrenceinput.add_rule('exrule', rule.substring(7));
                        }
                        else if (rule.search("^EXDATE") >= 0) {
                            recurrenceinput.add_date('exdate', rule.substring(7));
                        }
                    }
                }

                // on form submit we write to textarea
                form.submit(function(e) {
                    e.preventDefault();

                    // create string for rule widget
                    var ruleset_str = '';
                    var f = function(pf, el) {
                        ruleset_str += pf($(el)) + "\n";
                    }
                    var widgets = recurrenceinput.widget;
                    $('div.recurrenceinput-rrule li.rule', widgets).each( function() {
                            f(recurrenceinput.parse_rrule, this)
                        });
                    $('div.recurrenceinput-exrule li.rule', widgets).each(function() {
                            f(recurrenceinput.parse_exrule, this)
                        });
                    $('div.recurrenceinput-rdate li.rule', widgets).each( function() {
                            f(recurrenceinput.parse_rdate, this)
                        });
                    $('div.recurrenceinput-exdate li.rule', widgets).each(function() {
                            f(recurrenceinput.parse_exdate, this)
                        })

                    // insert string generated form above to textarea
                    textarea.val(ruleset_str);

                    // remove widget
                    //recurrenceinput.widget.remove();
                });

                // insert recurrance widget right after textarea
                textarea.after(recurrenceinput.widget)
            };
        });
    };

})(jQuery);
<|endoftext|>


<commit_before>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var moment = require('moment');
var markdown = require('markdown-it')({
                                      html:         false,
                                      xhtmlOut:     true,
                                      breaks:       true,
                                      langPrefix:   'language-',
                                      linkify:      true,
                                      typographer:  true,
                                      quotes: '“”‘’',
                                      highlight: function() {return '';}
                                      });
app.get('/', function(req, res){
        res.sendFile(__dirname + '/index.html');
        });
io.on('connection', function(socket){
      if(socketConnections().length <= 1024){
      socket.on('auth_details', function(details){
                socket.username = details.username;
                socket.toString = function(){return this.name};
                });
      socket.on('postName', function(username){
                socket.username = username;
                });
      var socketsConnected = socketConnections();
      io.emit('connections', socketsConnected.length);
      socket.on('chat message', function(msg){
                var markedMessage =  markdown.renderInline(msg.message);
                var messageDate = moment(msg.date).format("LT, D/M");
                var messageToBeSent = '
' + escapeHTML(msg.username) + ': ' + markedMessage + '

' + messageDate + '
';
                if(messageToBeSent.length <= 8192){
                if(!verifyEmptyness(msg.message)){
                io.emit('chat message', messageToBeSent);
                }else{
                socket.emit('chat message', 'PM: Sorry, you cannot send empty messages.');
                }
                }else{
                socket.emit('chat message', 'PM: Oops! You cannot send messages longer than 8192 characters. Sorry!');
                }
                });
      socket.on('users', function(){
                var socketsConnected = socketConnections();
                io.emit('connections', socketsConnected.length);
                });
      socket.on('disconnect', function(){
                var socketsConnected = socketConnections();
                io.emit('connections', socketsConnected.length);
                });
      }else{
      socket.emit('chat message', 'PM: Sorry, we cannot allow more than 1024 connections in the server');
      socket.emit('chat message', 'PM: Disconnecting! Try again later.');
      socket.emit('connections', 'You are not connected.');
      socket.disconnect();
      }
      });
http.listen(3030, function(){
            console.log('listening on *:3030');
            });
var verifyEmptyness = function(str) {
    return (str.length === 0 || !str.trim());
};
function socketConnections(roomId, namespace) {
    var res = []
    , ns = io.of(namespace ||"/");    // the default namespace is "/"

    if (ns) {
        for (var id in ns.connected) {
            if(roomId) {
                var index = ns.connected[id].rooms.indexOf(roomId) ;
                if(index !== -1) {
                    res.push(ns.connected[id]);
                }
            } else {
                res.push(ns.connected[id]);
            }
        }
    }
    return res;
}
function escapeHTML(text) {
    var map = {
        '&': '&',
        '<': '<',
        '>': '>',
        '"': '"',
        "'": '''
    };

    return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}
<commit_msg>Added support to commands.<commit_after>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var moment = require('moment');
var markdown = require('markdown-it')({
                                      html:         false,
                                      xhtmlOut:     true,
                                      breaks:       true,
                                      langPrefix:   'language-',
                                      linkify:      true,
                                      typographer:  true,
                                      quotes: '“”‘’',
                                      highlight: function() {return '';}
                                      });
app.get('/', function(req, res){
        res.sendFile(__dirname + '/index.html');
        });
io.on('connection', function(socket){
      if(socketConnections().length <= 1024){
        socket.username = socket.handshake.query.username;
        socket.toString = function(){return this.name};
        socket.on('postName', function(username){
                socket.username = username;
                });
        var socketsConnected = socketConnections();
        io.emit('connections', socketsConnected.length);
        socket.on('chat message', function(msg){
            var markedMessage =  markdown.renderInline(msg.message);
            var messageDate = moment(msg.date).format("LT, D/M");
            var firstWord = markedMessage.substr(0, markedMessage.indexOf(" "));
            if(msg.message !== "/help"){
            if(firstWord === "/broadcast"){
            var finalMessage = markedMessage.substr(markedMessage.indexOf(" ") + 1);
             var messageToBeSent = '
 BROADCAST: ' + finalMessage + '

' + messageDate + '
';
            }else if(firstWord === "/bot-say"){
                var finalMessage = markedMessage.substr(markedMessage.indexOf(" ") + 1);
                var messageToBeSent = '
 Chat bot: ' + finalMessage + '

' + messageDate + '
';
            }else{
            var messageToBeSent = '
' + escapeHTML(msg.username) + ': ' + markedMessage + '

' + messageDate + '
';
            }
            if(messageToBeSent.length <= 8192){
                  if(!verifyEmptyness(msg.message)){
                    io.emit('chat message', messageToBeSent);
                  }else{
                  socket.emit('chat message', 'PM: Sorry, you cannot send empty messages.');
                  }
                }else{
                  socket.emit('chat message', 'PM: Oops! You cannot send messages longer than 8192 characters. Sorry!');
                }
            }else{
                socket.emit('chat message', 'Montreus Chat - v1.3.2
Available commands:
/help - Display help commands
/bot-say <message> - Give something for the bot to say!
/broadcast <message> - Broadcast a message');
            }
        });
      socket.on('users', function(){
                var socketsConnected = socketConnections();
                io.emit('connections', socketsConnected.length);
                });
      socket.on('disconnect', function(){
                var socketsConnected = socketConnections();
                io.emit('connections', socketsConnected.length);
                });
      }else{
      socket.emit('chat message', 'PM: Sorry, we cannot allow more than 1024 connections in the server');
      socket.emit('chat message', 'PM: Disconnecting! Try again later.');
      socket.emit('connections', 'You are not connected.');
      socket.disconnect();
      }
      });
http.listen(3030, function(){
            console.log('listening on *:3030');
            });
var verifyEmptyness = function(str) {
    return (str.length === 0 || !str.trim());
};
function socketConnections(roomId, namespace) {
    var res = []
    , ns = io.of(namespace ||"/");    // the default namespace is "/"

    if (ns) {
        for (var id in ns.connected) {
            if(roomId) {
                var index = ns.connected[id].rooms.indexOf(roomId) ;
                if(index !== -1) {
                    res.push(ns.connected[id]);
                }
            } else {
                res.push(ns.connected[id]);
            }
        }
    }
    return res;
}
function escapeHTML(text) {
    var map = {
        '&': '&',
        '<': '<',
        '>': '>',
        '"': '"',
        "'": '''
    };

    return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}
<|endoftext|>


<commit_before>/* globals magazineBuilder */

(function(window, $, app) {
    function NewElement() {
        this.newText = function() {
            console.log("CREATING NEW TEXT OBJECT");
            $('
TEXT ELEMENT
').prependTo(app.Page.getContent());
        };

        this.newImage = function() {
            console.log("CREATING NEW IMAGE OBJECT");
            $('

', {
                class: "draggable push-down-18 push-right-18"
            }).prependTo(app.Page.getContent());
        };

        this.newCTA = function() {
            console.log("CREATING NEW CTA OBJECT");
            $('
 DÉCOUVRIR LA SÉLECTION
', {
                class: "draggable resizable editable textAlignCenter span-11 btnShopThe pull-up-1-a push-right-37-c"
            }).prependTo(app.Page.getContent());
        };
    }

    app.modules.NewElement = NewElement;
})(window, jQuery, MagTool);
<commit_msg>Update to NewElement.js<commit_after>/* globals magazineBuilder */

(function(window, $, app) {
    function NewElement() {

        // If a slug exists, add the new element after the slug, else add it to the top of the page
        var addToDom = function($element) {
            console.log("ADDING " + $element + " TO DOM");
            var $slug = app.Slug.findSlug();

            if ($slug.length) {
                console.log("Placing after slug");
                $slug.after($element);
            } else {
                console.log("placing at top of page");
                $element.prependTo(app.Page.getContent());
            }
        };

        // Create New Text Element
        this.newText = function() {
            console.log("Creating text element");
            addToDom('
TEXT ELEMENT
');
        };

        // Create New Image Element
        this.newImage = function() {
            console.log("Creating image element");
            var $imageElement = '

';
            addToDom($imageElement);
        };

        // Create New CTA Element
        this.newCTA = function() {
            console.log("Creating CTA element");
            var $ctaElement = '
SHOP THE SELECTION
';
            addToDom($ctaElement);
        };
    }

    app.modules.NewElement = NewElement;
})(window, jQuery, MagTool);
<|endoftext|>


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

var EnyoGenerator = module.exports = function EnyoGenerator(args, options) {
	yeoman.generators.Base.apply(this, arguments);
	this.argument("appdir", { type: String, required: false });
	this.appdir = this.appdir || ".";
	this.option("bootplate", {
		desc: "Use a specific version of Enyo and libraries for the bootplate",
		type: String,
		required: "false",
		default:"*"
	});
	this.bootplate = options["bootplate"] || options["b"] || "*";
	if(this.bootplate===true) {
		this.bootplate = "*";
	}
	/*this.hookFor('enyo:webOS', {
		args: args
	});*/
	this.on("end", function () {
		this.installDependencies({
			skipInstall: this.options["skip-install"],
			npm: false
		});
	});
};

util.inherits(EnyoGenerator, yeoman.generators.Base);

EnyoGenerator.prototype.welcome = function() {
	var msg = "Generating " + chalk.cyan("Enyo Bootplate");
	if(this.bootplate!=="*") {
		msg += " v" + chalk.cyan(this.bootplate)
	}
	msg += "...";
	this.log.writeln(msg);
}

EnyoGenerator.prototype.bootplateFiles = function() {
	var files = this.expandFiles('**/*', {cwd: this.sourceRoot(), dot: true});
	var filter = [
		"_bower.json",
		"_bowerrc"
	];
	files.forEach(function(file) {
		if(filter.indexOf(file)<0) {
			this.copy(file, this.appdir + "/" + file);
		}
	}, this);
};

EnyoGenerator.prototype.bowerFiles = function() {
	this.template("_bower.json", this.appdir + "/" + "bower.json");
	this.copy("_bowerrc", this.appdir + "/" + ".bowerrc");
};
<commit_msg>Symlinks /lib/enyo to /enyo so library samples function currently<commit_after>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var fs = require('fs');

var EnyoGenerator = module.exports = function EnyoGenerator(args, options) {
	yeoman.generators.Base.apply(this, arguments);
	this.argument("appdir", { type: String, required: false });
	this.appdir = this.appdir || ".";
	this.option("bootplate", {
		desc: "Use a specific version of Enyo and libraries for the bootplate",
		type: String,
		required: "false",
		default:"*"
	});
	this.bootplate = options["bootplate"] || options["b"] || "*";
	if(this.bootplate===true) {
		this.bootplate = "*";
	}
	/*this.hookFor('enyo:webOS', {
		args: args
	});*/
	this.on("end", function () {
		this.installDependencies({
			skipInstall: this.options["skip-install"],
			npm: false,
			callback: function() {
				try {
					if(fs.existsSync("lib/enyo") && !fs.existsSync("enyo")) {
						fs.symlinkSync("lib/enyo", "enyo");
					}
				} catch(e) {
					// samples may not function, but the bootplate should still
					this.log.writeln("Warning: unable to symlink enyo directory");
				}

			}
		});
	});
};

util.inherits(EnyoGenerator, yeoman.generators.Base);

EnyoGenerator.prototype.welcome = function() {
	var msg = "Generating " + chalk.cyan("Enyo Bootplate");
	if(this.bootplate!=="*") {
		msg += " v" + chalk.cyan(this.bootplate)
	}
	msg += "...";
	this.log.writeln(msg);
}

EnyoGenerator.prototype.bootplateFiles = function() {
	var files = this.expandFiles('**/*', {cwd: this.sourceRoot(), dot: true});
	var filter = [
		"_bower.json",
		"_bowerrc"
	];
	files.forEach(function(file) {
		if(filter.indexOf(file)<0) {
			this.copy(file, this.appdir + "/" + file);
		}
	}, this);
};

EnyoGenerator.prototype.bowerFiles = function() {
	this.template("_bower.json", this.appdir + "/" + "bower.json");
	this.copy("_bowerrc", this.appdir + "/" + ".bowerrc");
};
<|endoftext|>


<commit_before>/**
 * Mapzen API Key Check
 */

/**
 * The URL_PATTERN handles the old vector.mapzen.com origin (until it is fully
 * deprecated) as well as the new v1 tile.mapzen.com endpoint.
 *
 * Extensions include both vector and raster tile services.
 */
var URL_PATTERN = /((https?:)?\/\/(vector|tile).mapzen.com([a-z]|[A-Z]|[0-9]|\/|\{|\}|\.|\||:)+(topojson|geojson|mvt|png|tif|gz))/;

/**
 * A basic check to see if an API key string looks like a valid key.
 * Not *is* a valid key, just *looks like* one.
 *
 * @param {string} apiKey Mapzen API key string
 */
var isValidMapzenApiKey = function (apiKey) {
  return (typeof apiKey === 'string' && apiKey.match(/^[-a-z]+-[0-9a-zA-Z_-]{5,7}$/));
};

var warningCounter = 0;

var getKeyAndOptions = function (_key, _options) {
  var key;
  var options = {};

  if (typeof _key !== 'string' && typeof _key !== 'object') {
    // When nothing is passed
    key = L.Mapzen.apiKey;
  } else if (typeof _key === 'object') {
    // When the key is omitted and options is passed
    key = L.Mapzen.apiKey;
    options = _key;
  } else {
    key = _key;
    options = _options || options;
  }
  return {
    key: key,
    options: options
  };
};

/**
 * Throw console warning about missing API key
 *
 * @param {string} component Name of component with missing API key (optional)
 */
var throwApiKeyWarning = function (component) {
  component = component || 'all Mapzen Services';

  console.warn('A valid API key is required for access to ' + component);

  // Show expanded warning the first time
  if (warningCounter === 0) {
    console.warn('****************************** \n' +
                 'Generate your free API key at  \n' +
                 'https://mapzen.com/developers  \n' +
                 '******************************');
  }
  warningCounter++;
};

module.exports = {
  URL_PATTERN: URL_PATTERN,
  isValidMapzenApiKey: isValidMapzenApiKey,
  throwApiKeyWarning: throwApiKeyWarning,
  getKeyAndOptions: getKeyAndOptions
};

<commit_msg>Fix missing require in apiKeyCheck<commit_after>/**
 * Mapzen API Key Check
 */

var L = require('leaflet');

/**
 * The URL_PATTERN handles the old vector.mapzen.com origin (until it is fully
 * deprecated) as well as the new v1 tile.mapzen.com endpoint.
 *
 * Extensions include both vector and raster tile services.
 */
var URL_PATTERN = /((https?:)?\/\/(vector|tile).mapzen.com([a-z]|[A-Z]|[0-9]|\/|\{|\}|\.|\||:)+(topojson|geojson|mvt|png|tif|gz))/;

/**
 * A basic check to see if an API key string looks like a valid key.
 * Not *is* a valid key, just *looks like* one.
 *
 * @param {string} apiKey Mapzen API key string
 */
var isValidMapzenApiKey = function (apiKey) {
  return (typeof apiKey === 'string' && apiKey.match(/^[-a-z]+-[0-9a-zA-Z_-]{5,7}$/));
};

var warningCounter = 0;

var getKeyAndOptions = function (_key, _options) {
  var key;
  var options = {};

  if (typeof _key !== 'string' && typeof _key !== 'object') {
    // When nothing is passed
    key = L.Mapzen.apiKey;
  } else if (typeof _key === 'object') {
    // When the key is omitted and options is passed
    key = L.Mapzen.apiKey;
    options = _key;
  } else {
    key = _key;
    options = _options || options;
  }
  return {
    key: key,
    options: options
  };
};

/**
 * Throw console warning about missing API key
 *
 * @param {string} component Name of component with missing API key (optional)
 */
var throwApiKeyWarning = function (component) {
  component = component || 'all Mapzen Services';

  console.warn('A valid API key is required for access to ' + component);

  // Show expanded warning the first time
  if (warningCounter === 0) {
    console.warn('****************************** \n' +
                 'Generate your free API key at  \n' +
                 'https://mapzen.com/developers  \n' +
                 '******************************');
  }
  warningCounter++;
};

module.exports = {
  URL_PATTERN: URL_PATTERN,
  isValidMapzenApiKey: isValidMapzenApiKey,
  throwApiKeyWarning: throwApiKeyWarning,
  getKeyAndOptions: getKeyAndOptions
};
<|endoftext|>


<commit_before>'use strict';
var path = require('path');
var Base = require('yeoman-generator').Base;
var yosay = require('yosay');
var chalk = require('chalk');
var isWin = process.platform === 'win32';
var homedir = (isWin) ? process.env.HOMEPATH : process.env.HOME;
var fs = require('fs');
var mkdirp = require('mkdirp');

function getDirectories(srcpath) {
  return fs.readdirSync(srcpath).filter(function(file) {
    return fs.statSync(path.join(srcpath, file)).isDirectory();
  });
}

module.exports = Base.extend({
  initializing: function() {
    // check for existence of package.json
    try {
      fs.accessSync('./package.json', fs.F_OK);
      this.hasPackageJson = true;
    } catch (e) {
      this.hasPackageJson = false;
    }
  },

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

    // Have Yeoman greet the user.
    this.log(yosay('Welcome to the ArcGIS Web AppBuilder generator!'));
    this.log(chalk.yellow('These generators should be run in the root folder of your project.'));

    var prompts = [{
      name: 'abort',
      type: 'confirm',
      default: true,
      message: 'No package.json found. Would you like to abort and run npm init first?',
      when: function() {
        return !self.hasPackageJson;
      }
    }, {
      type: 'list',
      choices: [
        {
        value: 'is2d',
        name: '2D'
        },
        {
        value: 'is3d',
        name: '3D'
        }
      ],
      name: 'widgetsType',
      message: 'Type of widget(s) to be generated:',
      when: function(currentAnswers) {
        return !currentAnswers.abort;
      }
    }, {
      when: function(currentAnswers) {
        return !currentAnswers.abort;
      },
      name: 'wabRoot',
      message: 'Web AppBuilder install root:',
      'default': function(currentAnswers) {
        var wabDir;
        if (currentAnswers.widgetsType === 'is3d') {
          wabDir = path.join(homedir, 'WebAppBuilderForArcGIS');
        } else {
          wabDir = path.join(homedir, 'arcgis-web-appbuilder-1.3');
        }
        return wabDir;
      },
      validate: function(wabPath) {
        // make sure input directory and apps directory is valid and exists.
        var paths = [wabPath, path.join(wabPath, 'server/apps')];
        try {
          paths.forEach(function(path) {
            fs.accessSync(path, fs.F_OK);
          });
          return true;
        } catch (e) {
          // It isn't accessible
          return 'Invalid path. Please ensure this is a valid path to your WAB root.';
        }
      }
    }, {
      when: function(currentAnswers) {
        if (currentAnswers.abort) {
          return false;
        }
        var appsPath = path.join(currentAnswers.wabRoot, 'server', 'apps');
        var appsDirectories = getDirectories(appsPath);
        if (appsDirectories.length > 0) {
          return true;
        } else {
          this.log(chalk.red('You do not have any WAB apps setup yet. After you create an app, please see the Gruntfile for a todo, or run this generator again.'));
        }
      }.bind(this),
      name: 'appDirId',
      type: 'list',
      message: 'Web AppBuilder application:',
      choices: function(currentAnswers) {
        // Always include option for "None"
        var retArray = [{
          name: 'None',
          value: 'None',
          short: 'N'
        }];
        var appsPath = path.join(currentAnswers.wabRoot, 'server', 'apps');
        var appsDirectories = getDirectories(appsPath);
        appsDirectories.forEach(function(appDirectory) {
          try {
            // get the config file, convert to JSON, and read the title property
            var configPath = path.join(currentAnswers.wabRoot, 'server', 'apps', appDirectory, 'config.json');
            var configJson = JSON.parse(fs.readFileSync(configPath, 'utf8'));
            if (configJson.hasOwnProperty('title') && configJson.title !== '') {
              retArray.push({
                name: configJson.title,
                value: appDirectory,
                short: appDirectory
              });
            } else {
              // does not have title property or is empty. Use the app folder name (number) as the name.
              retArray.push({
                name: appDirectory,
                value: appDirectory,
                short: appDirectory
              });
            }
          } catch (e) {
            // Cannot open the config file. Just use the app folder name (number) as the name
            retArray.push({
              name: appDirectory,
              value: appDirectory,
              short: appDirectory
            });
          }
        });
        return retArray;
      }
    }];

    this.prompt(prompts, function(props) {
      this.abort = props.abort;
      this.wabRoot = props.wabRoot;
      this.widgetsType = props.widgetsType;
      if (props.appDirId && props.appDirId !== 'None') {
        this.appDirId = props.appDirId;
      } else {
        this.appDirId = false;
      }
      done();
    }.bind(this));
  },

  writing: {
    app: function() {
      if (this.abort) {
        return;
      }
      mkdirp('widgets');
      this.config.set('widgetsType', this.widgetsType);
    },

    gruntConfig: function() {
      if (this.abort) {
        return;
      }

      // Setting up the stemappDir and appDir Gruntfile variables:
      var stemappDir;
      if (this.widgetsType === 'is3d') {
        stemappDir = path.join(this.wabRoot, 'client', 'stemapp3d');
      } else {
        stemappDir = path.join(this.wabRoot, 'client', 'stemapp');
      }
      var appDir = false;
      if (this.appDirId) {
        appDir = path.join(this.wabRoot, 'server', 'apps', this.appDirId);
      }
      if (isWin) {
        // this hack is needed to ensure paths are not escaped when injected into Gruntfile
        stemappDir = stemappDir.replace(/\\/g, '/');
        if (appDir) {
          appDir = appDir.replace(/\\/g, '/');
        }
      }
      this.gruntfile.insertVariable('stemappDir', '"' + stemappDir + '"');
      if (appDir) {
        this.gruntfile.insertVariable('appDir', '"' + appDir + '"');
      } else {
        this.gruntfile.insertVariable('appDir', '"TODO - AFTER CREATING AN APP, PLEASE PUT PATH HERE AND INSERT ENTRY IN SYNC.MAIN.FILES BELOW."');
      }

      // SYNC CONFIG
      var syncConfig = '{ main: { verbose: true, files: [';
      var filesPrefix = '{cwd: \'dist/\', src: \'**\', dest: ';
      syncConfig = syncConfig + filesPrefix + 'stemappDir }';
      if (appDir) {
        syncConfig = syncConfig + ',' + filesPrefix + 'appDir }';
      }
      syncConfig = syncConfig + ']';
      syncConfig = syncConfig + '} }';

      this.gruntfile.insertConfig('sync', syncConfig);

      // BABEL CONFIG
      var babelConfig = {
        main: {
          files: [{
            expand: true,
            cwd: 'widgets/',
            src: [
              '*.js', '**/*.js', '**/**/*.js',
              '!**/**/nls/*.js',
            ],
            dest: 'dist/widgets/'
          }]
        }
      };
      this.gruntfile.insertConfig('babel', JSON.stringify(babelConfig));

      // WATCH CONFIG
      this.gruntfile.insertConfig('watch', JSON.stringify({
        main: {
          files: ['widgets/**'],
          tasks: ['clean', 'babel', 'copy', 'sync'],
          options: {
            spawn: false,
            atBegin: true
          }
        }
      }));

      // COPY CONFIG
      this.gruntfile.insertConfig('copy', JSON.stringify({
        main: {
          cwd: 'widgets/',
          src: [
            '**/**.html',
            '**/**.json',
            '**/**.css',
            '**/images/**',
            '**/nls/**'
          ],
          dest: 'dist/widgets/',
          expand: true
        }
      }));

      // CLEAN CONFIG
      this.gruntfile.insertConfig('clean', JSON.stringify({
        dist: {
          src: 'dist/**'
        }
      }));

      // load tasks
      this.gruntfile.loadNpmTasks('grunt-babel');
      this.gruntfile.loadNpmTasks('grunt-contrib-clean');
      this.gruntfile.loadNpmTasks('grunt-contrib-copy');
      this.gruntfile.loadNpmTasks('grunt-contrib-watch');
      this.gruntfile.loadNpmTasks('grunt-sync');

      // register tasks
      this.gruntfile.registerTask('default', ['watch']);
    },

    projectfiles: function() {
      if (this.abort) {
        return;
      }
      this.copy('editorconfig', '.editorconfig');
      this.copy('jshintrc', '.jshintrc');
      this.copy('babelrc', '.babelrc');
    }
  },

  install: function() {
    if (this.abort || this.options['skip-install']) {
      return;
    }
    this.npmInstall([
      'babel-plugin-transform-es2015-modules-simple-amd',
      'babel-preset-es2015-without-strict',
      'babel-preset-stage-0',
      'grunt',
      'grunt-contrib-watch',
      'grunt-sync',
      'grunt-babel',
      'grunt-contrib-clean',
      'grunt-contrib-copy'
    ], {
      'saveDev': true
    });
  }
});
<commit_msg>Added support for custom themes<commit_after>'use strict';
var path = require('path');
var Base = require('yeoman-generator').Base;
var yosay = require('yosay');
var chalk = require('chalk');
var isWin = process.platform === 'win32';
var homedir = (isWin) ? process.env.HOMEPATH : process.env.HOME;
var fs = require('fs');
var mkdirp = require('mkdirp');

function getDirectories(srcpath) {
  return fs.readdirSync(srcpath).filter(function(file) {
    return fs.statSync(path.join(srcpath, file)).isDirectory();
  });
}

module.exports = Base.extend({
  initializing: function() {
    // check for existence of package.json
    try {
      fs.accessSync('./package.json', fs.F_OK);
      this.hasPackageJson = true;
    } catch (e) {
      this.hasPackageJson = false;
    }
  },

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

    // Have Yeoman greet the user.
    this.log(yosay('Welcome to the ArcGIS Web AppBuilder generator!'));
    this.log(chalk.yellow('These generators should be run in the root folder of your project.'));

    var prompts = [{
      name: 'abort',
      type: 'confirm',
      default: true,
      message: 'No package.json found. Would you like to abort and run npm init first?',
      when: function() {
        return !self.hasPackageJson;
      }
    }, {
      type: 'list',
      choices: [
        {
        value: 'is2d',
        name: '2D'
        },
        {
        value: 'is3d',
        name: '3D'
        }
      ],
      name: 'widgetsType',
      message: 'Type of widget(s) to be generated:',
      when: function(currentAnswers) {
        return !currentAnswers.abort;
      }
    }, {
      when: function(currentAnswers) {
        return !currentAnswers.abort;
      },
      name: 'wabRoot',
      message: 'Web AppBuilder install root:',
      'default': function(currentAnswers) {
        var wabDir;
        if (currentAnswers.widgetsType === 'is3d') {
          wabDir = path.join(homedir, 'WebAppBuilderForArcGIS');
        } else {
          wabDir = path.join(homedir, 'arcgis-web-appbuilder-1.3');
        }
        return wabDir;
      },
      validate: function(wabPath) {
        // make sure input directory and apps directory is valid and exists.
        var paths = [wabPath, path.join(wabPath, 'server/apps')];
        try {
          paths.forEach(function(path) {
            fs.accessSync(path, fs.F_OK);
          });
          return true;
        } catch (e) {
          // It isn't accessible
          return 'Invalid path. Please ensure this is a valid path to your WAB root.';
        }
      }
    }, {
      when: function(currentAnswers) {
        if (currentAnswers.abort) {
          return false;
        }
        var appsPath = path.join(currentAnswers.wabRoot, 'server', 'apps');
        var appsDirectories = getDirectories(appsPath);
        if (appsDirectories.length > 0) {
          return true;
        } else {
          this.log(chalk.red('You do not have any WAB apps setup yet. After you create an app, please see the Gruntfile for a todo, or run this generator again.'));
        }
      }.bind(this),
      name: 'appDirId',
      type: 'list',
      message: 'Web AppBuilder application:',
      choices: function(currentAnswers) {
        // Always include option for "None"
        var retArray = [{
          name: 'None',
          value: 'None',
          short: 'N'
        }];
        var appsPath = path.join(currentAnswers.wabRoot, 'server', 'apps');
        var appsDirectories = getDirectories(appsPath);
        appsDirectories.forEach(function(appDirectory) {
          try {
            // get the config file, convert to JSON, and read the title property
            var configPath = path.join(currentAnswers.wabRoot, 'server', 'apps', appDirectory, 'config.json');
            var configJson = JSON.parse(fs.readFileSync(configPath, 'utf8'));
            if (configJson.hasOwnProperty('title') && configJson.title !== '') {
              retArray.push({
                name: configJson.title,
                value: appDirectory,
                short: appDirectory
              });
            } else {
              // does not have title property or is empty. Use the app folder name (number) as the name.
              retArray.push({
                name: appDirectory,
                value: appDirectory,
                short: appDirectory
              });
            }
          } catch (e) {
            // Cannot open the config file. Just use the app folder name (number) as the name
            retArray.push({
              name: appDirectory,
              value: appDirectory,
              short: appDirectory
            });
          }
        });
        return retArray;
      }
    }];

    this.prompt(prompts, function(props) {
      this.abort = props.abort;
      this.wabRoot = props.wabRoot;
      this.widgetsType = props.widgetsType;
      if (props.appDirId && props.appDirId !== 'None') {
        this.appDirId = props.appDirId;
      } else {
        this.appDirId = false;
      }
      done();
    }.bind(this));
  },

  writing: {
    app: function() {
      if (this.abort) {
        return;
      }
      mkdirp('widgets');
      this.config.set('widgetsType', this.widgetsType);
    },

    gruntConfig: function() {
      if (this.abort) {
        return;
      }

      // Setting up the stemappDir and appDir Gruntfile variables:
      var stemappDir;
      if (this.widgetsType === 'is3d') {
        stemappDir = path.join(this.wabRoot, 'client', 'stemapp3d');
      } else {
        stemappDir = path.join(this.wabRoot, 'client', 'stemapp');
      }
      var appDir = false;
      if (this.appDirId) {
        appDir = path.join(this.wabRoot, 'server', 'apps', this.appDirId);
      }
      if (isWin) {
        // this hack is needed to ensure paths are not escaped when injected into Gruntfile
        stemappDir = stemappDir.replace(/\\/g, '/');
        if (appDir) {
          appDir = appDir.replace(/\\/g, '/');
        }
      }
      this.gruntfile.insertVariable('stemappDir', '"' + stemappDir + '"');
      if (appDir) {
        this.gruntfile.insertVariable('appDir', '"' + appDir + '"');
      } else {
        this.gruntfile.insertVariable('appDir', '"TODO - AFTER CREATING AN APP, PLEASE PUT PATH HERE AND INSERT ENTRY IN SYNC.MAIN.FILES BELOW."');
      }

      // SYNC CONFIG
      var syncConfig = '{ main: { verbose: true, files: [';
      var filesPrefix = '{cwd: \'dist/\', src: \'**\', dest: ';
      syncConfig = syncConfig + filesPrefix + 'stemappDir }';
      if (appDir) {
        syncConfig = syncConfig + ',' + filesPrefix + 'appDir }';
      }
      syncConfig = syncConfig + ']';
      syncConfig = syncConfig + '} }';

      this.gruntfile.insertConfig('sync', syncConfig);

      // BABEL CONFIG
      var babelConfig = {
        main: {
          files: [{
            expand: true,
            src: [
                'widgets/*.js',
				'widgets/**/*.js',
				'widgets/**/**/*.js',
				'widgets/!**/**/nls/*.js',
				'themes/*.js',
				'themes/**/*.js',
				'themes/**/**/*.js',
				'themes/!**/**/nls/*.js'
            ],
            dest: 'dist/'
          }]
        }
      };
      this.gruntfile.insertConfig('babel', JSON.stringify(babelConfig));

      // WATCH CONFIG
      this.gruntfile.insertConfig('watch', JSON.stringify({
        main: {
          files: ['widgets/**', 'themes/**'],
          tasks: ['clean', 'babel', 'copy', 'sync'],
          options: {
            spawn: false,
            atBegin: true
          }
        }
      }));

      // COPY CONFIG
      this.gruntfile.insertConfig('copy', JSON.stringify({
        main: {
          cwd: 'widgets/',
          src: [
            'widgets/**/**.html',
            'widgets/**/**.json',
            'widgets/**/**.css',
            'widgets/**/images/**',
            'widgets/**/nls/**',
			'themes**/**.html',
			'themes**/**.json',
			'themes**/**.css',
			'themes**/images/**',
			'themes**/nls/**'
          ],
          dest: 'dist/',
          expand: true
        }
      }));

      // CLEAN CONFIG
      this.gruntfile.insertConfig('clean', JSON.stringify({
        dist: {
          src: 'dist/**'
        }
      }));

      // load tasks
      this.gruntfile.loadNpmTasks('grunt-babel');
      this.gruntfile.loadNpmTasks('grunt-contrib-clean');
      this.gruntfile.loadNpmTasks('grunt-contrib-copy');
      this.gruntfile.loadNpmTasks('grunt-contrib-watch');
      this.gruntfile.loadNpmTasks('grunt-sync');

      // register tasks
      this.gruntfile.registerTask('default', ['watch']);
    },

    projectfiles: function() {
      if (this.abort) {
        return;
      }
      this.copy('editorconfig', '.editorconfig');
      this.copy('jshintrc', '.jshintrc');
      this.copy('babelrc', '.babelrc');
    }
  },

  install: function() {
    if (this.abort || this.options['skip-install']) {
      return;
    }
    this.npmInstall([
      'babel-plugin-transform-es2015-modules-simple-amd',
      'babel-preset-es2015-without-strict',
      'babel-preset-stage-0',
      'grunt',
      'grunt-contrib-watch',
      'grunt-sync',
      'grunt-babel',
      'grunt-contrib-clean',
      'grunt-contrib-copy'
    ], {
      'saveDev': true
    });
  }
});
<|endoftext|>


<commit_before>$(document).ready(function() {

//smooth scroll

  $(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

//change navbar color
  // var scroll_start = 0;
  // var startchange = $('.navbar');
  // var offset = startchange.offset();
  // $(document).scroll(function() {
  //     scroll_start = $(this).scrollTop();
  //     if(scroll_start > offset.top) {
  //         $('.navbar').css({"background":"white"});
  //      } else {
  //         $('.navbar').css({"background": "rgba(255,255,255,.3"});
  //      }
  // });

//Technical courses
  var $p = $("#hidden");
  $(document).ready(function () {
    $("#hide, #show").click(function () {
        $("p").toggle(this.id == "show");
    });
  });

});
<commit_msg>Delete script.js<commit_after><|endoftext|>


<commit_before>/*
 * TODO:
 *  - breakpint mixin (http://codepen.io/chriscoyier/blog/codepens-css)
 *  - better generator file system
 *  - GULP
 *  - https://github.com/yeoman/grunt-usemin#blockreplacements for
 *  - picturefill + http://vimeo.com/92794354 (img/original -> img/scaled)
 *  - make imagemin work
 *  - Modernizr CDN
 *  - visuallyhidden -> vh? (+ remove unneccessary/unused classes)
 *  - humans.txt + rel attr
 *  - uncss, class names minification
 *  - GA (https://github.com/dciccale/grunt-processhtml, https://github.com/changer/grunt-targethtml) + ask for key
 *    - new task ("dploy"/"production"), because of build is sometimes being used for testing final product (don't wanna analyze this :))
 *  - modernizr custom build/CDN
 *  - do I need to include normalize, h5bp, foundation & compass resets?
 *  - support IE desktops https://github.com/jtangelder/grunt-stripmq, http://robin.medvedi.eu/mobile-first-and-ie8-solution-introducing-grunt-legacssy/
 *  - separate print styles and add media element for IE8-
 *  - print.scss, ie.scss (if supported)
 *  - git initialization
 *  - README - file system (to both READMEs)
 *  - open sublime when ready
 *  - check svgmin options
 *
 */

'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var file = yeoman.file;

var WebProjectGenerator = module.exports = function WebProjectGenerator(args, options, config) {
	yeoman.generators.Base.apply(this, arguments);

	this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(WebProjectGenerator, yeoman.generators.Base);

WebProjectGenerator.prototype.askFor = function askFor() {
	var cb = this.async();

	// welcome message
	console.log(this.yeoman);
	console.log('Foundation5 with Compass and HTML5 Boilerplate are prepared!');

	var prompts = [{
		name: 'language',
		message: 'Which language would you like to use? (ISO abbreviation)',
		default: 'en'
	}, {
		type: 'confirm',
		name: 'createSublimeTextProjectFile',
		message: 'Create Sublime Text project file?',
		default: true
	}, {
		name: 'htmlTitle',
		message: 'Your HTML <title>?',
		default: this.appname
	}];

	this.prompt(prompts, function (answers) {
		// // manually deal with the response, get back and store the results.
		// // we change a bit this way of doing to automatically do this in the self.prompt() method.
		this.language = answers.language;
		this.createSublimeTextProjectFile = answers.createSublimeTextProjectFile;
		this.htmlTitle = answers.htmlTitle;

		cb();
	}.bind(this));
};

WebProjectGenerator.prototype.gruntfile = function gruntfile() {
	this.template('Gruntfile.js');
};

WebProjectGenerator.prototype.packageJSON = function packageJSON() {
	this.template('_package.json', 'package.json');
};

WebProjectGenerator.prototype.SassConfig = function SassConfig() {
	this.copy('config.rb', 'config.rb');
};

WebProjectGenerator.prototype.git = function git() {
	this.copy('gitignore', '.gitignore');
	this.copy('gitattributes', '.gitattributes');
};

WebProjectGenerator.prototype.bower = function bower() {
	this.copy('bowerrc', '.bowerrc');
	this.template('_bower.json', 'bower.json');
};

WebProjectGenerator.prototype.editor = function editor() {
	this.copy('editorconfig', '.editorconfig');
	if (this.createSublimeTextProjectFile) {
		this.template('project.sublime-project', this._.slugify(this.appname) + '.sublime-project');
	}
};

WebProjectGenerator.prototype.assets = function assets() {
	this.mkdir('assets');
	this.mkdir('assets/font');
	this.mkdir('assets/img');
	this.mkdir('assets/js');
	this.mkdir('assets/scss');

	this.mkdir('assets/scss/components');
	this.mkdir('assets/scss/helpers');
	this.mkdir('assets/scss/layout');
	this.mkdir('assets/scss/settings');
	this.mkdir('assets/scss/vendor');
};

WebProjectGenerator.prototype.files = function files() {
	this.template('_README.md', 'README.md');

	if (file.exists(this.src._base + '/404_' + this.language + '.html')) {
		this.copy('404_' + this.language + '.html', '404.html');
	}
	else {
		console.log('There is not 404.html error page in your choosen language, I\'m including english version.');
		this.copy('404_en.html', '404.html');
	}

	this.copy('favicon.ico', 'favicon.ico');
	this.copy('apple-touch-icon-precomposed.png', 'apple-touch-icon-precomposed.png');

	this.copy('htaccess', '.htaccess');
	this.copy('robots.txt', 'robots.txt');
	this.copy('crossdomain.xml', 'crossdomain.xml');

	this.copy('main.scss', 'assets/scss/main.scss');
	this.copy('ie8.scss', 'assets/scss/ie8.scss');
	this.copy('settings.scss', 'assets/scss/settings/_foundation.scss');
	this.copy('h5bp.scss', 'assets/scss/vendor/_h5bp.scss');
	this.copy('foundation.scss', 'assets/scss/vendor/_foundation.scss');
	this.copy('mixins.scss', 'assets/scss/helpers/_mixins.scss');

	this.copy('z-index-settings.scss', 'assets/scss/settings/_z-index.scss');
	this.copy('z-index-helper.scss', 'assets/scss/helpers/_z-index.scss');

	this.copy('main.js', 'assets/js/main.js');
	this.copy('plugins.js', 'assets/js/plugins.js');
	this.copy('jquery-2.1.0.js', 'assets/js/jquery.js'); // for dev CDN fallback, for production compiled by grunt from bower_components
	this.copy('jquery-1.8.0.js', 'assets/js/jquery-1.8.0.js');
	this.copy('selectivizr-1.0.3b.js', 'assets/js/selectivizr-1.0.3b.js');
};

WebProjectGenerator.prototype.index = function index() {

	this.copy('index.html', 'index.html');
};

WebProjectGenerator.prototype.install = function () {
	var done = this.async();
	this.installDependencies({
		callback: done
	});
};<commit_msg>Update todos<commit_after>/*
 * TODO:
 *  - TODO.md
 *  - update to new h5bp structure
 *  - 404 in one with ifs
 *  - breakpint mixin (http://codepen.io/chriscoyier/blog/codepens-css)
 *  - better generator file system
 *  - drop compass ?
 *  - drop Foundation ?
 *  - https://github.com/filamentgroup/grunt-criticalcss?utm_source=Responsive+Design+Weekly&utm_campaign=6ead7a5573-Responsive_Design_Weekly_120&utm_medium=email&utm_term=0_df65b6d7c8-6ead7a5573-58722333&goal=0_df65b6d7c8-6ead7a5573-58722333
 *  - GULP
 *  - https://github.com/yeoman/grunt-usemin#blockreplacements for
 *  - picturefill + http://vimeo.com/92794354 (img/original -> img/scaled)
 *  - make imagemin work
 *  - Modernizr CDN
 *  - visuallyhidden -> vh? (+ remove unneccessary/unused classes)
 *  - humans.txt + rel attr
 *  - uncss, class names minification
 *  - GA (https://github.com/dciccale/grunt-processhtml, https://github.com/changer/grunt-targethtml) + ask for key
 *    - new task ("dploy"/"production"), because of build is sometimes being used for testing final product (don't wanna analyze this :))
 *  - modernizr custom build/CDN
 *  - do I need to include normalize, h5bp, foundation & compass resets?
 *  - support IE desktops https://github.com/jtangelder/grunt-stripmq, http://robin.medvedi.eu/mobile-first-and-ie8-solution-introducing-grunt-legacssy/
 *  - separate print styles and add media element for IE8-
 *  - print.scss, ie.scss (if supported)
 *  - git initialization
 *  - README - file system (to both READMEs)
 *  - open sublime when ready
 *  - check svgmin options
 *
 */

'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var file = yeoman.file;

var WebProjectGenerator = module.exports = function WebProjectGenerator(args, options, config) {
	yeoman.generators.Base.apply(this, arguments);

	this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(WebProjectGenerator, yeoman.generators.Base);

WebProjectGenerator.prototype.askFor = function askFor() {
	var cb = this.async();

	// welcome message
	console.log(this.yeoman);
	console.log('Foundation5 with Compass and HTML5 Boilerplate are prepared!');

	var prompts = [{
		name: 'language',
		message: 'Which language would you like to use? (ISO abbreviation)',
		default: 'en'
	}, {
		type: 'confirm',
		name: 'createSublimeTextProjectFile',
		message: 'Create Sublime Text project file?',
		default: true
	}, {
		name: 'htmlTitle',
		message: 'Your HTML <title>?',
		default: this.appname
	}];

	this.prompt(prompts, function (answers) {
		// // manually deal with the response, get back and store the results.
		// // we change a bit this way of doing to automatically do this in the self.prompt() method.
		this.language = answers.language;
		this.createSublimeTextProjectFile = answers.createSublimeTextProjectFile;
		this.htmlTitle = answers.htmlTitle;

		cb();
	}.bind(this));
};

WebProjectGenerator.prototype.gruntfile = function gruntfile() {
	this.template('Gruntfile.js');
};

WebProjectGenerator.prototype.packageJSON = function packageJSON() {
	this.template('_package.json', 'package.json');
};

WebProjectGenerator.prototype.SassConfig = function SassConfig() {
	this.copy('config.rb', 'config.rb');
};

WebProjectGenerator.prototype.git = function git() {
	this.copy('gitignore', '.gitignore');
	this.copy('gitattributes', '.gitattributes');
};

WebProjectGenerator.prototype.bower = function bower() {
	this.copy('bowerrc', '.bowerrc');
	this.template('_bower.json', 'bower.json');
};

WebProjectGenerator.prototype.editor = function editor() {
	this.copy('editorconfig', '.editorconfig');
	if (this.createSublimeTextProjectFile) {
		this.template('project.sublime-project', this._.slugify(this.appname) + '.sublime-project');
	}
};

WebProjectGenerator.prototype.assets = function assets() {
	this.mkdir('assets');
	this.mkdir('assets/font');
	this.mkdir('assets/img');
	this.mkdir('assets/js');
	this.mkdir('assets/scss');

	this.mkdir('assets/scss/components');
	this.mkdir('assets/scss/helpers');
	this.mkdir('assets/scss/layout');
	this.mkdir('assets/scss/settings');
	this.mkdir('assets/scss/vendor');
};

WebProjectGenerator.prototype.files = function files() {
	this.template('_README.md', 'README.md');

	if (file.exists(this.src._base + '/404_' + this.language + '.html')) {
		this.copy('404_' + this.language + '.html', '404.html');
	}
	else {
		console.log('There is not 404.html error page in your choosen language, I\'m including english version.');
		this.copy('404_en.html', '404.html');
	}

	this.copy('favicon.ico', 'favicon.ico');
	this.copy('apple-touch-icon-precomposed.png', 'apple-touch-icon-precomposed.png');

	this.copy('htaccess', '.htaccess');
	this.copy('robots.txt', 'robots.txt');
	this.copy('crossdomain.xml', 'crossdomain.xml');

	this.copy('main.scss', 'assets/scss/main.scss');
	this.copy('ie8.scss', 'assets/scss/ie8.scss');
	this.copy('settings.scss', 'assets/scss/settings/_foundation.scss');
	this.copy('h5bp.scss', 'assets/scss/vendor/_h5bp.scss');
	this.copy('foundation.scss', 'assets/scss/vendor/_foundation.scss');
	this.copy('mixins.scss', 'assets/scss/helpers/_mixins.scss');

	this.copy('z-index-settings.scss', 'assets/scss/settings/_z-index.scss');
	this.copy('z-index-helper.scss', 'assets/scss/helpers/_z-index.scss');

	this.copy('main.js', 'assets/js/main.js');
	this.copy('plugins.js', 'assets/js/plugins.js');
	this.copy('jquery-2.1.0.js', 'assets/js/jquery.js'); // for dev CDN fallback, for production compiled by grunt from bower_components
	this.copy('jquery-1.8.0.js', 'assets/js/jquery-1.8.0.js');
	this.copy('selectivizr-1.0.3b.js', 'assets/js/selectivizr-1.0.3b.js');
};

WebProjectGenerator.prototype.index = function index() {

	this.copy('index.html', 'index.html');
};

WebProjectGenerator.prototype.install = function () {
	var done = this.async();
	this.installDependencies({
		callback: done
	});
};<|endoftext|>


<commit_before>const bodyParser = require('body-parser');
const jsonAPI = require('json-server');
const compression = require('compression');
const { __PRODUCTION__ } = require('environs');
const { join, resolve } = require('path');
const cors = require('cors');
const express = require('express');
const helmet = require('helmet');
const hpp = require('hpp');
const logger = require('morgan');
const responseTime = require('response-time');

// Le App
const app = express();

app.use(logger('dev'));
app.use(helmet.xssFilter({ setOnOldIE: true }));
app.use(responseTime());
app.use(helmet.frameguard());
app.use(helmet.ieNoOpen());
app.use(helmet.noSniff());
app.use(helmet.hidePoweredBy({ setTo: 'react' }));
app.use(bodyParser.json());

// Forms and compression!
app.use(compression());
app.use(hpp());
app.use(cors());

app.options(__PRODUCTION__ ? 'http://social.learnreactjs.io' : '*', cors());

// ==== Serve the app ====
app.use('/api', jsonAPI.router(join(__dirname, '..', '..', 'db', 'seed', 'db.json')));
app.use('/', express.static(resolve(__dirname, '..')));

app.use('*', (req, res) => res.sendFile(resolve(__dirname, '..', 'index.html')));

// ====ERROR-HANDLING===
app.use((req, res, next) => {
  const err = new Error('Not Found');
  err.status = 404;
  next(err);
});

app.use((err, req, res) => {
  console.error(err);
  return res.status(err.status || 500).json({
    message: err.message,
  });
});

export default app;
<commit_msg>fix server<commit_after>const bodyParser = require('body-parser');
const jsonAPI = require('json-server');
const compression = require('compression');
const { __PRODUCTION__ } = require('environs');
const { join, resolve } = require('path');
const cors = require('cors');
const express = require('express');
const helmet = require('helmet');
const hpp = require('hpp');
const logger = require('morgan');
const responseTime = require('response-time');

// Le App
const app = express();

app.use(logger('dev'));
app.use(helmet.xssFilter({ setOnOldIE: true }));
app.use(responseTime());
app.use(helmet.frameguard());
app.use(helmet.ieNoOpen());
app.use(helmet.noSniff());
app.use(helmet.hidePoweredBy({ setTo: 'react' }));
app.use(bodyParser.json());

// Forms and compression!
app.use(compression());
app.use(hpp());
app.use(cors());

app.options(__PRODUCTION__ ? 'http://social.learnreactjs.io' : '*', cors());

// ==== Serve the app ====
app.use('/api', jsonAPI.router(join(__dirname, '..', '..', 'db', 'seed', 'db.json')));
app.use('/', express.static(resolve(__dirname, '..')));

app.use('*', (req, res) => res.sendFile(resolve(__dirname, '..', 'index.html')));

// ====ERROR-HANDLING===
app.use((req, res, next) => {
  const err = new Error('Not Found');
  err.status = 404;
  next(err);
});

app.use((err, req, res) => {
  console.error(err);
  return res.status(err.status || 500).json({
    message: err.message,
  });
});

module.exports = app;
<|endoftext|>