<commit_before>var dviz = (function() {

/*
 * Fast array min/max functions
 */
var array_min = function(array) {return Math.min.apply( Math, array );};
var array_max = function(array) {return Math.max.apply( Math, array );};

/*
 * Load javascript modules
 *
 * Params:
 *    jsids: array of predefined script ids
 *    callback: called right after the job done.
 */
var load_reqs = function(jsids, callback) {
    var loaded = 0;
    for(var i = 0; i < jsids.length; i++) {
        load_req(jsids[i], function() {
            loaded++;
            if(loaded == jsids.length) callback();
        });
    }
};

/*
 * Load single javascript module
 *
 * Params:
 *    jsid: predefined script id
 *    callback: called right after the job done.
 */
var load_req = function(jsid, callback) {
    var loader = load_req.loaders[jsid];
    var script = document.createElement("script");
    script.src = loader.url;
    script.type = "text/javascript";
    script.onload = function () {
        loader.callback(callback);
    };
    document.getElementsByTagName("head")[0].appendChild(script);
};
load_req.loaders = {
    'd3': {
        'url': 'http://d3js.org/d3.v2.min.js',
        'callback': function(cb) {cb();}
    },
    'google-viz': {
        'url': 'https://www.google.com/jsapi',
        'callback': function(cb) {
            google.load('visualization', '1.0', {
                'packages': ['corechart'],
                'callback': function() {cb();}
            });
        }
    }
};

/*
 * Parse raw string and return array(for single line string)
 * or array of array(for multi-line string).
 *
 * Params:
 *    raw: raw comma separated string
 *    hasColumnLabels: true if first row is header
 *    hasRowLabels: true if first column is header
 *
 * Returns:
 *    <raw> itself if <raw> is not a string
 *    one dimensional array if <raw> has single line
 *    two dimensional array if <raw> has multiple lines
 */
var parse_csv = function(raw, hasColumnLabels, hasRowLabels) {
    if(typeof(raw) != 'string') return raw;

    // tokenize
    var table = [];
    $(raw.trim().split('\n')).each(function() {
        table.push(this.split(','));
    });

    // convert data
    var rstart = hasColumnLabels ? 1 : 0;
    var cstart = hasRowLabels ? 1 : 0;
    for(var row = rstart; row < table.length; row++) {
        for(var col = cstart; col < table[row].length; col++) {
            table[row][col] = Number(table[row][col].trim());
        }
    }

    // done
    if(table.length == 1) {
        return table[0];
    } else {
        return table;
    }
};

/*
 * Extract texts from html TABLE element and return a single CSV string.
 *
 * Params:
 *    $table: jQuery TABLE element
 *
 * Returns:
 *    CSV string which can be parsed with parse_csv function
 */
var table_to_csv = function($table) {
    var table_buffer = [];
    $table.find('tr').each(function() {
        var row_buffer = [];
        $(this).find('td').each(function() {
            row_buffer.push($(this).text());
        });
        table_buffer.push(row_buffer.join(','));
    });
    return table_buffer.join('\n');
};

/* Return CSS color schemes for nominal data
 *
 * Params:
 *    nums: number of categories
 *
 * Returns:
 *    array of CSS color strings
 */
var get_nominal_colors = function(nums) {
    var colors;
    if(nums <= 1) {
        colors = ['#555'];
    } else if(nums <= 2) {
        colors = ['#555', '#999'];
    } else {
        colors = ['rgb(31,119,180)', 'rgb(255,127,14)', 'rgb(44,160,44)', 'rgb(214,39,40)', 'rgb(148,103,189)', 'rgb(140,86,75)'];
    }
    return colors;
};

/*
 * Set of declarative visualization functions
 */
var funcs = {
    /*
     * Create div elements for grid layout and append it into current element,
     * and than move existing elements into the layout just created.
     *
     * Params:
     *    $e: current element
     *    data: string with format "cols,rows,repeat"
     *       <cols> and <rows> specifies format of the grid
     *       <repeat> specifies # of elements each grid cell should contain
     */
    layout: function($e, data) {
        var tokens = data.split(',');
        var cols = Number(tokens[0].trim());
        var rows = Number(tokens[1].trim());
        var repeat = Number((tokens[2] || '1').trim());

        var $layout = $('<div />');
        for(var ri = 0; ri < rows; ri++) {
            var $row = $('<div />');
            $row.addClass('row-fluid');
            $layout.append($row);

            for(var ci = 0; ci < cols; ci++) {
                var $col = $('<div />');
                $col.addClass('span' + Math.floor(12 / cols));
                for(var x = 0; x < repeat; x++) {
                    $col.append($e.parent().next());
                }
                $row.append($col);
            }
        }
        $e.append($layout);
    },
    layout_requires: [],
    /*
     * Create scatter plot using Google Visualization API.
     *
     * Params:
     *    $e: current element
     *    data: raw comma separated string
     *    options: JSON string (see Google API docs for available options)
     */
    scatter: function($e, data, options) {
        // prepare data
        var table = google.visualization.arrayToDataTable(parse_csv(data, true, false));

        // merge default options
        var default_options = {
            colors: get_nominal_colors(table.getNumberOfColumns() - 1),
            pointSize: 3,
            hAxis: {title: table.getColumnLabel(0)}
        };
        actual_options = $.extend(default_options, options);

        // draw chart
        var $chart_div = $('<div />');
        $e.append($chart_div);
        var chart = new google.visualization.ScatterChart($chart_div[0]);
        chart.draw(table, actual_options);
    },
    scatter_requires: ['google-viz'],
    /*
     * Create scatter plot matrix using Google Visualization API.
     *
     * Params:
     *    $e: current element
     *    data: raw comma separated string
     *    options: JSON string (see Google API docs for available options)
     */
    scattermatrix: function($e, data, options) {
        // prepare data
        var table = google.visualization.arrayToDataTable(parse_csv(data, true, false));

        // merge default options
        var default_options = {
            colors: get_nominal_colors(1),
            pointSize: 3,
            chartArea: {
                'left': 0,
                'top': 0,
                'width': '100%',
                'height': '100%'
            },
            legend: 'none'
        };
        cell_options = $.extend(default_options, options);

        // render matrix and label
        var size = table.getNumberOfColumns();
        var $root = $('<div />');
        $e.append($root);

        // @TODO: remove twitter-bootstrap dependency
        for(var ri = 0; ri < size; ri++) {
            var $row = $('<div />');
            $row.addClass('row-fluid');
            $root.append($row);
            for(var ci = 0; ci < size; ci++) {
                var $col = $('<div />');
                var bootstrap_grid = 12;  // @TODO: remove magic number
                $col.addClass('span' + Math.floor(bootstrap_grid / size));
                $row.append($col);

                if(ri == ci) {
                    $col.css({'text-align': 'left', 'position': 'relative'});
                    if(ri != 0) $col.css('height', $col.width());
                    var $label = $('<span>' + table.getColumnLabel(ci) + '</span>');
                    $label.css({'position': 'absolute', 'bottom': 0, 'text-size': '12px'});
                    $col.html($label);
                }
            }
        }

        // render scatter plots
        for(var ri = 0; ri < size; ri++) {
            for(var ci = ri + 1; ci < size; ci++) {
                var $cell = $($($root.children()[ci]).children()[ri]);

                // extract values to be used in this cell
                var cell_values = [];
                cell_values.push([table.getColumnLabel(ri), table.getColumnLabel(ci)]);
                for(var i = 0; i < table.getNumberOfRows() - 1; i++) {
                    cell_values.push([table.getValue(i, ri), table.getValue(i, ci)]);
                }
                var cell_table = google.visualization.arrayToDataTable(cell_values);
                var chart = new google.visualization.ScatterChart($cell[0]);
                var actual_options = $.extend(cell_options, {
                    height: $cell.width()
                });
                chart.draw(cell_table, actual_options);
            }
        }
    },
    scattermatrix_requires: ['google-viz'],
    /*
     * Create horizontal bar chart using Google Visualization API.
     * See <dviz.funcs.common_chart> for more details.
     */
    bar: function($e, data, options) {
        dviz.funcs.common_chart('BarChart', $e, data, options);
    },
    bar_requires: ['google-viz'],
    /*
     * Create line chart using Google Visualization API.
     * See <dviz.funcs.common_chart> for more details.
     */
    line: function($e, data, options) {
        dviz.funcs.common_chart('LineChart', $e, data, options);
    },
    line_requires: ['google-viz'],
    /*
     * Create vertical bar chart using Google Visualization API.
     * See <dviz.funcs.common_chart> for more details.
     */
    column: function($e, data, options) {
        dviz.funcs.common_chart('ColumnChart', $e, data, options);
    },
    column_requires: ['google-viz'],
    /*
     * Create area chart using Google Visualization API.
     * See <dviz.funcs.common_chart> for more details.
     */
    area: function($e, data, options) {
        dviz.funcs.common_chart('AreaChart', $e, data, options);
    },
    area_requires: ['google-viz'],
    /*
     * Create table chart using Google Visualization API.
     * See <dviz.funcs.common_chart> for more details.
     */
    table: function($e, data, options) {
        dviz.funcs.common_chart('Table', $e, data, options);
    },
    table_requires: ['google-viz'],
    /*
     * Create stepped area chart using Google Visualization API.
     * See <dviz.funcs.common_chart> for more details.
     */
    steppedarea: function($e, data, options) {
        dviz.funcs.common_chart('SteppedAreaChart', $e, data, options);
    },
    steppedarea_requires: ['google-viz'],
    /*
     * Create specified corechart using Google Visualization API.
     *
     * Params:
     *    name: name of chart function
     *          (see Google API docs for available function name)
     *    $e: current element
     *    data: raw comma separated string
     *    options: JSON string (see Google API docs for available options)
     */
    common_chart: function(name, $e, data, options) {
        // prepare data
        table = google.visualization.arrayToDataTable(parse_csv(data, true, true));

        // merge default options
        var default_options = {
            colors: get_nominal_colors(table.getNumberOfColumns() - 1)
        };
        actual_options = $.extend(default_options, options);

        // render chart
        var $chart_div = $('<div />');
        $e.append($chart_div);
        var chart = new google.visualization[name]($chart_div[0]);
        chart.draw(table, actual_options);
    },
    /*
     * Create sparkline using D3
     *
     * Params:
     *    $e: current element
     *    data: raw comma separated string
     */
    sparkline: function($e, data) {
        // prepare data
        var parsed_data = parse_csv(data);
        var lines = [];
        for(var i = 0; i < parsed_data.length - 1; i++) {
            lines.push([parsed_data[i], parsed_data[i + 1]]);
        }

        // params
        var xstep = 10; // @TODO: remove magic number
        var height = 20; // @TODO: remove magic number
        var marginy = 4; // @TODO: remove magic number
        var width = xstep * lines.length;
        var scalex = d3.scale.linear().domain([0, lines.length]).range([0, width]);
        var scaley = d3.scale.linear().domain([array_min(parsed_data), array_max(parsed_data)]).range([height - marginy, 0 + marginy]);

        // render
        var e = $e[0];
        var svg = d3.select(e).append('svg')
            .attr('width', width + 'px')
            .attr('height', height + 'px')
            .attr('class', 'dviz sparkline');

        svg.selectAll('line')
            .data(lines)
            .enter()
            .append('line')
            .attr('x1', function(d, i) {return scalex(i);})
            .attr('x2', function(d, i) {return scalex(i + 1);})
            .attr('y1', function(d, i) {return scaley(d[0]);})
            .attr('y2', function(d, i) {return scaley(d[1]);});
    },
    sparkline_requires: ['d3']
};

/**
 * Scan and evaluate declarative commands.
 *
 * Params:
 *    content_selector: jQuery extended selector for content area (optional)
 *    code_selector: jQuery extended selector to select declarative commands (optional)
 */
var run = function(content_selector, code_selector) {
    content_selector = content_selector || '.dviz-content';
    code_selector = code_selector || '*:not(pre) > code';
    var p = /(.*)\(@(\w.+?)?\s?(\{.+\})?\)$/;

    // find declarations
    var $targets = $(content_selector + ' ' + code_selector).filter(function() {
        var $this = $(this);
        return !!$(this).text().match(p);
    });

    // find required libraries
    var reqs = [];
    $targets.each(function() {
        var $this = $(this);
        var m = $(this).text().match(p);
        var func_name = m[2];
        $(dviz.funcs[func_name + '_requires']).each(function(i, v) {
            if(reqs.indexOf(v) == -1) reqs.push(v);
        });
    });

    // load libraries
    load_reqs(reqs, function() {
        // evaluate declarations
        $targets.each(function() {
            var $this = $(this);
            var m = $this.text().match(p);
            var data = m[1];
            var func_name = m[2];
            var options = m[3];
            if(!(func_name in dviz.funcs)) return;

            if(!data) {
                var $data_node = $this.parent().prev();
                if($data_node.prop('nodeName').toUpperCase() == 'TABLE') {
                    data = table_to_csv($data_node);
                } else {
                    data = $data_node.text();
                }
                $data_node.remove();
            }

            if(options) {
                eval('options = ' + options);
            } else {
                options = {};
            }

            var wrapper = ($this.parent()[0].nodeName == 'pre') ? 'div' : 'span';
            var $e = $('<' + wrapper + ' />');
            $this.after($e);

            dviz.funcs[func_name]($e, data, options);

            var $parent = $this.parent();
            $this.remove();
            if($parent.children().length == 0) $parent.remove();
        });
    });
};

var dviz = {
    funcs: funcs,
    run: run
};

return dviz;

})();
<commit_msg>Don't load the same script twice<commit_after>var dviz = (function() {

/*
 * Fast array min/max functions
 */
var array_min = function(array) {return Math.min.apply( Math, array );};
var array_max = function(array) {return Math.max.apply( Math, array );};

/*
 * Load javascript modules
 *
 * Params:
 *    jsids: array of predefined script ids
 *    callback: called right after the job done.
 */
var load_reqs = function(jsids, callback) {
    var loaded = 0;
    for(var i = 0; i < jsids.length; i++) {
        load_req(jsids[i], function() {
            loaded++;
            if(loaded == jsids.length) callback();
        });
    }
};

/*
 * Load single javascript module
 *
 * Params:
 *    jsid: predefined script id
 *    callback: called right after the job done.
 */
var load_req = function(jsid, callback) {
    var loader = load_req.loaders[jsid];
    if(loader.check()) {
        loader.callback(callback);
        return;
    }

    var script = document.createElement("script");
    script.src = loader.url;
    script.type = "text/javascript";
    script.onload = function () {
        loader.callback(callback);
    };
    document.getElementsByTagName("head")[0].appendChild(script);
};
load_req.loaders = {
    'd3': {
        'url': 'http://d3js.org/d3.v2.min.js',
        'check': function() {return !!window['d3'];},
        'callback': function(cb) {cb();}
    },
    'google-viz': {
        'url': 'https://www.google.com/jsapi',
        'check': function() {return !!window['google'];},
        'callback': function(cb) {
            google.load('visualization', '1.0', {
                'packages': ['corechart', 'table'],
                'callback': function() {cb();}
            });
        }
    }
};

/*
 * Parse raw string and return array(for single line string)
 * or array of array(for multi-line string).
 *
 * Params:
 *    raw: raw comma separated string
 *    hasColumnLabels: true if first row is header
 *    hasRowLabels: true if first column is header
 *
 * Returns:
 *    <raw> itself if <raw> is not a string
 *    one dimensional array if <raw> has single line
 *    two dimensional array if <raw> has multiple lines
 */
var parse_csv = function(raw, hasColumnLabels, hasRowLabels) {
    if(typeof(raw) != 'string') return raw;

    // tokenize
    var table = [];
    $(raw.trim().split('\n')).each(function() {
        table.push(this.split(','));
    });

    // convert data
    var rstart = hasColumnLabels ? 1 : 0;
    var cstart = hasRowLabels ? 1 : 0;
    for(var row = rstart; row < table.length; row++) {
        for(var col = cstart; col < table[row].length; col++) {
            table[row][col] = Number(table[row][col].trim());
        }
    }

    // done
    if(table.length == 1) {
        return table[0];
    } else {
        return table;
    }
};

/*
 * Extract texts from html TABLE element and return a single CSV string.
 *
 * Params:
 *    $table: jQuery TABLE element
 *
 * Returns:
 *    CSV string which can be parsed with parse_csv function
 */
var table_to_csv = function($table) {
    var table_buffer = [];
    $table.find('tr').each(function() {
        var row_buffer = [];
        $(this).find('td').each(function() {
            row_buffer.push($(this).text());
        });
        table_buffer.push(row_buffer.join(','));
    });
    return table_buffer.join('\n');
};

/* Return CSS color schemes for nominal data
 *
 * Params:
 *    nums: number of categories
 *
 * Returns:
 *    array of CSS color strings
 */
var get_nominal_colors = function(nums) {
    var colors;
    if(nums <= 1) {
        colors = ['#555'];
    } else if(nums <= 2) {
        colors = ['#555', '#999'];
    } else {
        colors = ['rgb(31,119,180)', 'rgb(255,127,14)', 'rgb(44,160,44)', 'rgb(214,39,40)', 'rgb(148,103,189)', 'rgb(140,86,75)'];
    }
    return colors;
};

/*
 * Set of declarative visualization functions
 */
var funcs = {
    /*
     * Create div elements for grid layout and append it into current element,
     * and than move existing elements into the layout just created.
     *
     * Params:
     *    $e: current element
     *    data: string with format "cols,rows,repeat"
     *       <cols> and <rows> specifies format of the grid
     *       <repeat> specifies # of elements each grid cell should contain
     */
    layout: function($e, data) {
        var tokens = data.split(',');
        var cols = Number(tokens[0].trim());
        var rows = Number(tokens[1].trim());
        var repeat = Number((tokens[2] || '1').trim());

        var $layout = $('<div />');
        for(var ri = 0; ri < rows; ri++) {
            var $row = $('<div />');
            $row.addClass('row-fluid');
            $layout.append($row);

            for(var ci = 0; ci < cols; ci++) {
                var $col = $('<div />');
                $col.addClass('span' + Math.floor(12 / cols));
                for(var x = 0; x < repeat; x++) {
                    $col.append($e.parent().next());
                }
                $row.append($col);
            }
        }
        $e.append($layout);
    },
    layout_requires: [],
    /*
     * Create scatter plot using Google Visualization API.
     *
     * Params:
     *    $e: current element
     *    data: raw comma separated string
     *    options: JSON string (see Google API docs for available options)
     */
    scatter: function($e, data, options) {
        // prepare data
        var table = google.visualization.arrayToDataTable(parse_csv(data, true, false));

        // merge default options
        var default_options = {
            colors: get_nominal_colors(table.getNumberOfColumns() - 1),
            pointSize: 3,
            hAxis: {title: table.getColumnLabel(0)}
        };
        actual_options = $.extend(default_options, options);

        // draw chart
        var $chart_div = $('<div />');
        $e.append($chart_div);
        var chart = new google.visualization.ScatterChart($chart_div[0]);
        chart.draw(table, actual_options);
    },
    scatter_requires: ['google-viz'],
    /*
     * Create scatter plot matrix using Google Visualization API.
     *
     * Params:
     *    $e: current element
     *    data: raw comma separated string
     *    options: JSON string (see Google API docs for available options)
     */
    scattermatrix: function($e, data, options) {
        // prepare data
        var table = google.visualization.arrayToDataTable(parse_csv(data, true, false));

        // merge default options
        var default_options = {
            colors: get_nominal_colors(1),
            pointSize: 3,
            chartArea: {
                'left': 0,
                'top': 0,
                'width': '100%',
                'height': '100%'
            },
            legend: 'none'
        };
        cell_options = $.extend(default_options, options);

        // render matrix and label
        var size = table.getNumberOfColumns();
        var $root = $('<div />');
        $e.append($root);

        // @TODO: remove twitter-bootstrap dependency
        for(var ri = 0; ri < size; ri++) {
            var $row = $('<div />');
            $row.addClass('row-fluid');
            $root.append($row);
            for(var ci = 0; ci < size; ci++) {
                var $col = $('<div />');
                var bootstrap_grid = 12;  // @TODO: remove magic number
                $col.addClass('span' + Math.floor(bootstrap_grid / size));
                $row.append($col);

                if(ri == ci) {
                    $col.css({'text-align': 'left', 'position': 'relative'});
                    if(ri != 0) $col.css('height', $col.width());
                    var $label = $('<span>' + table.getColumnLabel(ci) + '</span>');
                    $label.css({'position': 'absolute', 'bottom': 0, 'text-size': '12px'});
                    $col.html($label);
                }
            }
        }

        // render scatter plots
        for(var ri = 0; ri < size; ri++) {
            for(var ci = ri + 1; ci < size; ci++) {
                var $cell = $($($root.children()[ci]).children()[ri]);

                // extract values to be used in this cell
                var cell_values = [];
                cell_values.push([table.getColumnLabel(ri), table.getColumnLabel(ci)]);
                for(var i = 0; i < table.getNumberOfRows() - 1; i++) {
                    cell_values.push([table.getValue(i, ri), table.getValue(i, ci)]);
                }
                var cell_table = google.visualization.arrayToDataTable(cell_values);
                var chart = new google.visualization.ScatterChart($cell[0]);
                var actual_options = $.extend(cell_options, {
                    height: $cell.width()
                });
                chart.draw(cell_table, actual_options);
            }
        }
    },
    scattermatrix_requires: ['google-viz'],
    /*
     * Create horizontal bar chart using Google Visualization API.
     * See <dviz.funcs.common_chart> for more details.
     */
    bar: function($e, data, options) {
        dviz.funcs.common_chart('BarChart', $e, data, options);
    },
    bar_requires: ['google-viz'],
    /*
     * Create line chart using Google Visualization API.
     * See <dviz.funcs.common_chart> for more details.
     */
    line: function($e, data, options) {
        dviz.funcs.common_chart('LineChart', $e, data, options);
    },
    line_requires: ['google-viz'],
    /*
     * Create vertical bar chart using Google Visualization API.
     * See <dviz.funcs.common_chart> for more details.
     */
    column: function($e, data, options) {
        dviz.funcs.common_chart('ColumnChart', $e, data, options);
    },
    column_requires: ['google-viz'],
    /*
     * Create area chart using Google Visualization API.
     * See <dviz.funcs.common_chart> for more details.
     */
    area: function($e, data, options) {
        dviz.funcs.common_chart('AreaChart', $e, data, options);
    },
    area_requires: ['google-viz'],
    /*
     * Create table chart using Google Visualization API.
     * See <dviz.funcs.common_chart> for more details.
     */
    table: function($e, data, options) {
        dviz.funcs.common_chart('Table', $e, data, options);
    },
    table_requires: ['google-viz'],
    /*
     * Create stepped area chart using Google Visualization API.
     * See <dviz.funcs.common_chart> for more details.
     */
    steppedarea: function($e, data, options) {
        dviz.funcs.common_chart('SteppedAreaChart', $e, data, options);
    },
    steppedarea_requires: ['google-viz'],
    /*
     * Create specified corechart using Google Visualization API.
     *
     * Params:
     *    name: name of chart function
     *          (see Google API docs for available function name)
     *    $e: current element
     *    data: raw comma separated string
     *    options: JSON string (see Google API docs for available options)
     */
    common_chart: function(name, $e, data, options) {
        // prepare data
        table = google.visualization.arrayToDataTable(parse_csv(data, true, true));

        // merge default options
        var default_options = {
            colors: get_nominal_colors(table.getNumberOfColumns() - 1)
        };
        actual_options = $.extend(default_options, options);

        // render chart
        var $chart_div = $('<div />');
        $e.append($chart_div);
        var chart = new google.visualization[name]($chart_div[0]);
        chart.draw(table, actual_options);
    },
    /*
     * Create sparkline using D3
     *
     * Params:
     *    $e: current element
     *    data: raw comma separated string
     */
    sparkline: function($e, data) {
        // prepare data
        var parsed_data = parse_csv(data);
        var lines = [];
        for(var i = 0; i < parsed_data.length - 1; i++) {
            lines.push([parsed_data[i], parsed_data[i + 1]]);
        }

        // params
        var xstep = 10; // @TODO: remove magic number
        var height = 20; // @TODO: remove magic number
        var marginy = 4; // @TODO: remove magic number
        var width = xstep * lines.length;
        var scalex = d3.scale.linear().domain([0, lines.length]).range([0, width]);
        var scaley = d3.scale.linear().domain([array_min(parsed_data), array_max(parsed_data)]).range([height - marginy, 0 + marginy]);

        // render
        var e = $e[0];
        var svg = d3.select(e).append('svg')
            .attr('width', width + 'px')
            .attr('height', height + 'px')
            .attr('class', 'dviz sparkline');

        svg.selectAll('line')
            .data(lines)
            .enter()
            .append('line')
            .attr('x1', function(d, i) {return scalex(i);})
            .attr('x2', function(d, i) {return scalex(i + 1);})
            .attr('y1', function(d, i) {return scaley(d[0]);})
            .attr('y2', function(d, i) {return scaley(d[1]);});
    },
    sparkline_requires: ['d3']
};

/**
 * Scan and evaluate declarative commands.
 *
 * Params:
 *    content_selector: jQuery extended selector for content area (optional)
 *    code_selector: jQuery extended selector to select declarative commands (optional)
 */
var run = function(content_selector, code_selector) {
    content_selector = content_selector || '.dviz-content';
    code_selector = code_selector || '*:not(pre) > code';
    var p = /(.*)\(@(\w.+?)?\s?(\{.+\})?\)$/;

    // find declarations
    var $targets = $(content_selector + ' ' + code_selector).filter(function() {
        var $this = $(this);
        return !!$(this).text().match(p);
    });

    // find required libraries
    var reqs = [];
    $targets.each(function() {
        var $this = $(this);
        var m = $(this).text().match(p);
        var func_name = m[2];
        $(dviz.funcs[func_name + '_requires']).each(function(i, v) {
            if(reqs.indexOf(v) == -1) reqs.push(v);
        });
    });

    // load libraries
    load_reqs(reqs, function() {
        // evaluate declarations
        $targets.each(function() {
            var $this = $(this);
            var m = $this.text().match(p);
            var data = m[1];
            var func_name = m[2];
            var options = m[3];
            if(!(func_name in dviz.funcs)) return;

            if(!data) {
                var $data_node = $this.parent().prev();
                if($data_node.prop('nodeName').toUpperCase() == 'TABLE') {
                    data = table_to_csv($data_node);
                } else {
                    data = $data_node.text();
                }
                $data_node.remove();
            }

            if(options) {
                eval('options = ' + options);
            } else {
                options = {};
            }

            var wrapper = ($this.parent()[0].nodeName == 'pre') ? 'div' : 'span';
            var $e = $('<' + wrapper + ' />');
            $this.after($e);

            dviz.funcs[func_name]($e, data, options);

            var $parent = $this.parent();
            $this.remove();
            if($parent.children().length == 0) $parent.remove();
        });
    });
};

var dviz = {
    funcs: funcs,
    run: run
};

return dviz;

})();
<|endoftext|>


<commit_before>/* globals ajax app dom listenCanvas canvas getState setState */

(function(global){
    'use strict';

    var defaultStyle = '<style>path{stroke-linecap: round; stroke-linejoin: round; pointer-events: none; fill: none;}</style>';
    var defaultCanvas = '<svg id="canvas"><g class="frame selected"></g></svg>';

    function saveLocal(){
        localStorage._currentWork = saveFormat();
    }

    function updateSavedState(){
      let state = getState();
      console.log('saving state: \n%s', JSON.stringify(state, null, 2));
      for (let key in state){
        canvas.dataset[key] = state[key];
      }
    }

  function restoreSavedState(){
    let state = {};
    for (let key in canvas.dataset){
      state[key] = canvas.dataset[key];
    }
    console.log('restoring state: \n%s', JSON.stringify(state, null, 2));
    setState(state);
  }

    function saveFormat(){
      if (canvas){
        updateSavedState();
        return canvas.outerHTML;
      }else{
        return '';
      }
    }

    window.canvas = null;

    function restoreFormat(savetext){
      canvas = document.querySelector('#canvas');
      if (!canvas){
        canvas = dom.svg('svg');
        document.body.prepend(canvas);
      }
      if (!savetext){
        savetext = defaultCanvas;
      }
      canvas.outerHTML = savetext;
      canvas = document.querySelector('#canvas');
      app.updateFrameCount();
      canvas.setAttribute('width', document.body.clientWidth + 'px');
      canvas.setAttribute('height', document.body.clientHeight + 'px');
      // let style = canvas.querySelector('style');
      // if (!style){
      //   canvas.prepend(defaultStyle);
      // }
      listenCanvas();
      restoreSavedState();
    }

    function restore(){
        var path = location.href.split('?');
        var query = location.search;
        if (query){
            var queryparts = query.slice(1).split('=');
            if (queryparts[0] === 'gist'){
                loadScriptsFromGistId(queryparts[1]);
                return;
            }
        }
        restoreLocal();
    }

    function restoreLocal(){
      restoreFormat(localStorage._currentWork || defaultCanvas);
    }

    function clear(){
        restoreFormat(defaultCanvas);
    }

    function saveFile(evt){
        if (evt){
          evt.preventDefault();
        }
        var title = prompt("Save file as: ");
        if (!title){ return; }
        var file = new Blob([saveFormat()], {type: 'image/svg+xml'}); // change for non-svg
        var reader = new FileReader();
        reader.onloadend = function(){
            var a = dom.html('a', {'href': reader.result, 'download': title + '.svg', target: '_blank'}); // change for non-svg
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        };
        reader.readAsDataURL(file);
    }

    function readFile(file){
        var fileName = file.name;
        if (fileName.indexOf('.svg', fileName.length - 5) === -1) {
            return alert('Not an SVG file');
        }
        var reader = new FileReader();
        reader.readAsText( file );
        reader.onload = function (evt){ restoreFormat(evt.target.result); };
    }

    function loadFile(){
        var input = dom.html('input', {'type': 'file', 'accept': 'image/svg+xml'});
        if (!input){ return; }
        input.addEventListener('change', function(evt){ readFile(input.files[0]); });
        input.click();
    }

    // Save script to gist;
    function saveCurrentScriptsToGist(event){
        event.preventDefault();
        // console.log("Saving to Gist");
        ajax.post("https://api.github.com/gists", function(data){
            //var raw_url = JSON.parse(data).files["script.json"].raw_url;
            gistID = JSON.parse(data).url.split("/").pop();
            var path = location.href.split('?')[0];
            path += "?gist=" + gistID;
            window.location = path;
        }, JSON.stringify({
            "description": "saved drawingboard file",
            "public": true,
            "files": {
                "animation.svg": {
                    "content": saveFormat()
                },
            }
        }), function(statusCode, x){
            alert("Can't save to Gist:\n" + statusCode + " (" + x.statusText + ") ");
        });
    }

    var gistID = null;

    function loadScriptsFromGistId(id){
        //we may get an event passed to this function so make sure we have a valid id or ask for one
        gistID = isNaN(parseInt(id)) ? prompt("What Gist would you like to load? Please enter the ID of the Gist: ")  : id;
        // console.log("Loading gist " + id);
        if( !gistID ) return;
        ajax.get("https://api.github.com/gists/"+gistID, function(gist){
            restoreFormat(JSON.parse(gist).files['animation.svg'].content);
        }, function(statusCode, x){
            alert("Can't load from Gist:\n" + statusCode + " (" + x.statusText + ") ");
        });
    }

    function newFile(){
        clear();
        onChange();
    }

    function onChange(){
        if (gistID){
            gistID = null;
            var path = location.href.split('?')[0];
            history.replaceState(null,null,path);
        }
    }

    window.file = {
        onChange: onChange,
        'new': newFile,
        clear: clear,
        loadFile,
        saveFile
    };

    // document.querySelector('#new').addEventListener('click', newFile, false);
    // document.querySelector('#upload').addEventListener('click', saveCurrentScriptsToGist, false);
    // document.querySelector('#download').addEventListener('click', loadScriptsFromGistId, false);
    // document.querySelector('#clear').addEventListener('click', clear, false);
    // document.querySelector('#save').addEventListener('click', saveFile, false);
    // document.querySelector('#open').addEventListener('click', loadFile, false);
    window.addEventListener('unload', saveLocal, false);
    window.addEventListener('load', restore, false);

})(window);<commit_msg>🚙🚥 Checkpoint ./js/file.js:739936/27<commit_after>/* globals ajax app dom listenCanvas canvas getState setState */

(function(global){
    'use strict';

    var defaultStyle = '<style>path{stroke-linecap: round; stroke-linejoin: round; pointer-events: none; fill: none;}</style>';
    var defaultCanvas = '<svg id="canvas"><g class="frame selected"></g></svg>';

    function saveLocal(){
        localStorage._currentWork = saveFormat();
    }

    function updateSavedState(){
      let state = getState();
      console.log('saving state: \n%s', JSON.stringify(state, null, 2));
      for (let key in state){
        canvas.dataset[key] = state[key];
      }
    }

  function restoreSavedState(){
    let state = {};
    for (let key in canvas.dataset){
      state[key] = canvas.dataset[key];
    }
    console.log('restoring state: \n%s', JSON.stringify(state, null, 2));
    setState(state);
  }

    function saveFormat(){
      if (canvas){
        updateSavedState();
        return canvas.outerHTML;
      }else{
        return '';
      }
    }

    window.canvas = null;

    function restoreFormat(savetext){
      canvas = document.querySelector('#canvas');
      if (!canvas){
        canvas = dom.svg('svg');
        document.body.prepend(canvas);
      }
      if (!savetext){
        savetext = defaultCanvas;
      }
      canvas.outerHTML = savetext;
      canvas = document.querySelector('#canvas');
      app.updateFrameCount();
      canvas.setAttribute('width', document.body.clientWidth + 'px');
      canvas.setAttribute('height', document.body.clientHeight + 'px');
      // let style = canvas.querySelector('style');
      // if (!style){
      //   canvas.prepend(defaultStyle);
      // }
      listenCanvas();
      restoreSavedState();
    }

    function restore(){
        var path = location.href.split('?');
        var query = location.search;
        if (query){
            var queryparts = query.slice(1).split('=');
            if (queryparts[0] === 'gist'){
                loadScriptsFromGistId(queryparts[1]);
                return;
            }
        }
        restoreLocal();
    }

    function restoreLocal(){
      restoreFormat(localStorage._currentWork || defaultCanvas);
    }

    function clear(){
        restoreFormat(defaultCanvas);
    }

    function saveFile(evt){
        if (evt){
          evt.preventDefault();
        }
        var title = prompt("Save file as: ");
        if (!title){ return; }
        var file = new Blob([saveFormat()], {type: 'image/svg+xml'}); // change for non-svg
        var reader = new FileReader();
        reader.onloadend = function(){
            var a = dom.html('a', {'href': reader.result, 'download': title + '.svg', target: '_blank'}); // change for non-svg
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        };
        reader.readAsDataURL(file);
    }

    function saveAs()

    function readFile(file){
        var fileName = file.name;
        if (fileName.indexOf('.svg', fileName.length - 5) === -1) {
            return alert('Not an SVG file');
        }
        var reader = new FileReader();
        reader.readAsText( file );
        reader.onload = function (evt){ restoreFormat(evt.target.result); };
    }

    function loadFile(){
        var input = dom.html('input', {'type': 'file', 'accept': 'image/svg+xml'});
        if (!input){ return; }
        input.addEventListener('change', function(evt){ readFile(input.files[0]); });
        input.click();
    }

    // Save script to gist;
    function saveCurrentScriptsToGist(event){
        event.preventDefault();
        // console.log("Saving to Gist");
        ajax.post("https://api.github.com/gists", function(data){
            //var raw_url = JSON.parse(data).files["script.json"].raw_url;
            gistID = JSON.parse(data).url.split("/").pop();
            var path = location.href.split('?')[0];
            path += "?gist=" + gistID;
            window.location = path;
        }, JSON.stringify({
            "description": "saved drawingboard file",
            "public": true,
            "files": {
                "animation.svg": {
                    "content": saveFormat()
                },
            }
        }), function(statusCode, x){
            alert("Can't save to Gist:\n" + statusCode + " (" + x.statusText + ") ");
        });
    }

    var gistID = null;

    function loadScriptsFromGistId(id){
        //we may get an event passed to this function so make sure we have a valid id or ask for one
        gistID = isNaN(parseInt(id)) ? prompt("What Gist would you like to load? Please enter the ID of the Gist: ")  : id;
        // console.log("Loading gist " + id);
        if( !gistID ) return;
        ajax.get("https://api.github.com/gists/"+gistID, function(gist){
            restoreFormat(JSON.parse(gist).files['animation.svg'].content);
        }, function(statusCode, x){
            alert("Can't load from Gist:\n" + statusCode + " (" + x.statusText + ") ");
        });
    }

    function newFile(){
        clear();
        onChange();
    }

    function onChange(){
        if (gistID){
            gistID = null;
            var path = location.href.split('?')[0];
            history.replaceState(null,null,path);
        }
    }

    window.file = {
        onChange: onChange,
        'new': newFile,
        clear: clear,
        loadFile,
        saveFile
    };

    // document.querySelector('#new').addEventListener('click', newFile, false);
    // document.querySelector('#upload').addEventListener('click', saveCurrentScriptsToGist, false);
    // document.querySelector('#download').addEventListener('click', loadScriptsFromGistId, false);
    // document.querySelector('#clear').addEventListener('click', clear, false);
    // document.querySelector('#save').addEventListener('click', saveFile, false);
    // document.querySelector('#open').addEventListener('click', loadFile, false);
    window.addEventListener('unload', saveLocal, false);
    window.addEventListener('load', restore, false);

})(window);<|endoftext|>


<commit_before>var generators = require('yeoman-generator');

module.exports = generators.Base.extend({
  // The name `constructor` is important here
  constructor: function () {
    // Calling the super constructor is important so our generator is correctly set up
    generators.Base.apply(this, arguments);

    // Next, add your custom code
    this.option('coffee'); // This method adds support for a `--coffee` flag
  },

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

	var prompts = [{
		name: 'projectionName',
		message: 'What is your Projection\'s name?'
	},{
		name: 'namespace',
		message: 'What is your Projection\'s namespace?'
	}];

	var addPropertyConfirmPrompt = [{
		name: 'addProperty',
		message: 'Would you like to add a property?',
		type: 'confirm'
	}];

	var addPropertyPrompts = [{
		name: 'propertyName',
		message: 'What is your property\'s name?',
	},
	{
		type: 'list',
		name: 'propertyType',
		message: 'What type is your property?',
		choices: ['Int32', 'String', 'Boolean']
	},
	{
		type: 'list',
		name: 'propertyAccessModifier',
		message: 'What is the access modifier of this property?',
		choices: ['public', 'private']
	}];

    this.prompt(prompts, function (props) {
		this.projectionName = props.projectionName;
		this.namespace = props.namespace;

		var askForProperty = function() {
			this.prompt(addPropertyConfirmPrompt, function(response) {
				if (response.addProperty) {
					this.prompt(addPropertyPrompts, function(addPropertyResponse) {
						var property = { name: addPropertyResponse.propertyName, type: addPropertyResponse.propertyType, accessModifier: addPropertyResponse.propertyAccessModifier }
						this.properties.push(property);
						askForProperty();
					}.bind(this));
				}
				else {
					done();
				}
			}.bind(this));
		}.bind(this);

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

  writing: function () {
	var propertiesString = '';

	this.properties.forEach(function(element, index, array) {
		if (index > 0)
			propertiesString += '\r\n        ';

		propertiesString += element.accessModifier + ' ' + element.type + ' ' + element.name + ' { get; set; }';
	});

    this.fs.copyTpl(
      this.templatePath('Projection.cs'),
      this.destinationPath('public/' + this.projectionName + 'Projection.cs'),
      { classTitle: this.projectionName, namespace: this.namespace, propertiesString: propertiesString }
    );
  }
});<commit_msg>Formatting fixes.<commit_after>var generators = require('yeoman-generator');

module.exports = generators.Base.extend({
  constructor: function () {
    generators.Base.apply(this, arguments);
    this.option('coffee'); // This method adds support for a `--coffee` flag
  },

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

	var prompts = [
    {
		name: 'projectionName',
		message: 'What is your Projection\'s name?'
	},
    {
		name: 'namespace',
		message: 'What is your Projection\'s namespace?'
	}];

	var addPropertyConfirmPrompt = [
    {
		name: 'addProperty',
		message: 'Would you like to add a property?',
		type: 'confirm'
	}];

	var addPropertyPrompts = [
    {
		name: 'propertyName',
		message: 'What is your property\'s name?',
	},
	{
		type: 'list',
		name: 'propertyType',
		message: 'What type is your property?',
		choices: ['Int32', 'String', 'Boolean']
	},
	{
		type: 'list',
		name: 'propertyAccessModifier',
		message: 'What is the access modifier of this property?',
		choices: ['public', 'private']
	}];

    this.prompt(prompts, function (props) {
        this.projectionName = props.projectionName;
        this.namespace = props.namespace;

        var askForProperty = function() {
            this.prompt(addPropertyConfirmPrompt, function(response) {
                if (response.addProperty) {
                    this.prompt(addPropertyPrompts, function(addPropertyResponse) {
                        var property =
                        {
                            name: addPropertyResponse.propertyName,
                            type: addPropertyResponse.propertyType,
                            accessModifier: addPropertyResponse.propertyAccessModifier
                        }

                        this.properties.push(property);
                        askForProperty();
                    }.bind(this));
                }
                else {
                    done();
                }
            }.bind(this));
        }.bind(this);

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

  writing: function () {
    var propertiesString = '';

    this.properties.forEach(function(element, index, array) {
        if (index > 0)
            propertiesString += '\r\n        ';

        propertiesString += element.accessModifier + ' ' + element.type + ' ' + element.name + ' { get; set; }';
    });

    this.fs.copyTpl(
        this.templatePath('Projection.cs'),
        this.destinationPath('public/' + this.projectionName + 'Projection.cs'),
        {
            classTitle: this.projectionName,
            namespace: this.namespace,
            propertiesString: propertiesString
        }
    );
  }
});<|endoftext|>


<commit_before>$(document).ready(function() {
  // This is called after the document has loaded in its entirety
  // This guarantees that any elements we bind to will exist on the page
  // when we try to bind to them

  // See: http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
});

// TWITTER SHARE
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');

// FB SHARE
(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.5";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
<commit_msg>add instagram AJAX requests<commit_after>$(document).ready(function() {

var getInstagramId = $.ajax({
  url: "https://api.instagram.com/v1/users/search?q=msg0927&client_id=a963ba34ecb443bcbaeafa815a9154a9",
  method: "get"
});

var instagramId = getInstagramId.done(function(response){
  return response;
});

console.log(instagramId);

//   $.ajax({
//     url: "https://api.instagram.com/v1/users/" + instagramId + "/media/recent/",
//     method: "get"
//   })
//
});

// TWITTER SHARE
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');

// FB SHARE
(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.5";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
<|endoftext|>


<commit_before>'use strict';
var util    = require('util');
var path    = require('path');
var yeoman  = require('yeoman-generator');
var fs      = require('fs-extra');
var chalk   = require('chalk');
var glob    = require('glob');
var latest  = require('github-latest');
var request = require('request');

var EvolvedGenerator = yeoman.generators.Base.extend({
  init: function() {
    this.prompts  = [];
    this.pkg      = require('../package.json');

    this.on('end', function() {
      this.config.save();
      this.log.info('Running ' + chalk.yellow('bower install') + ' & ' + chalk.yellow('npm install') + ' for you to install the required dependencies. If this fails, try running the command yourself.');
      if (!this.options['skip-install']) {
        this.installDependencies({
          bower:        true,
          npm:          true,
          skipMessage:  true,
          callback:     function() {
            this.log.ok('All done! Run ' + chalk.yellow('grunt build:dev') + ' and ' + chalk.yellow('grunt watch') + ' to get started!');
          }.bind(this)
        });
      }
    });
  },
  setBranch: function() {
    if (this.args.length) {
      var i = 0;
      var l = this.args.length;

      for(i; i < l; i++) {
        if (this.args[i].indexOf('@') === 0) {
          this.branch = this.args[i].slice(1);
        }
      }
    }
  },
  verifyBranch: function() {
    if (this.branch) {
      var done  = this.async();
      var url   = 'http://github.com/wp-evolved/evolved-theme/archive/' + this.branch + '.tar.gz';

      request(url, function(err, resp, body) {
        if (err || resp.statusCode !== 200) {
          var err = chalk.yellow(this.branch) + chalk.red(' is not an existing remote endpoint') + '\n';

          throw err;
        } else {
          done();
        }
      }.bind(this));
    }
  },
  promptForName: function() {
    var existing = function() {
      try {
        var bower = require(path.join(this.env.cwd, 'bower.json'));

        return bower.name;
      } catch(e) {};
    }.bind(this);

    this.prompts.push({
      required: true,
      type:     'text',
      name:     'projName',
      message:  'Project Name (e.g. MySite)',
      default:  function() {
        return existing() || path.basename(this.env.cwd);
      }.bind(this)
    });
  },
  promptForShortName: function() {
    var existing = function() {
      try {
        var bower = require(path.join(this.env.cwd, 'bower.json'));

        return bower.shortName;
      } catch(e) {};
    }.bind(this);

    this.prompts.push({
      required: true,
      type:     'text',
      name:     'projShortName',
      message:  'Project short name (e.g. mscom)',
      default:  function() {
        var ext       = path.extname(this.env.cwd);
        var extname   = ext.replace('.','');
        var base      = path.basename(this.env.cwd).replace(ext, '');
        var basename  = (/[A-Z]/.test(base)) ? base.replace(/[^A-Z]/g, '') : base.charAt(0);

        return existing() || (basename + extname).toLowerCase();
      }.bind(this)
    });
  },
  promptForAuthorName: function() {
    var existing = function() {
      try {
        var bower = require(path.join(this.env.cwd, 'bower.json'));

        return bower.author.name;
      } catch(e) {};
    }.bind(this);

    this.prompts.push({
      type:     'text',
      name:     'authorName',
      message:  'Author Name (e.g. John Smith)',
      default:  function() {
        return existing() || '';
      }.bind(this)
    });
  },
  promptForAuthorURI: function() {
    var existing = function() {
      try {
        var bower = require(path.join(this.env.cwd, 'bower.json'));

        return bower.author.url
      } catch(e) {};
    }.bind(this);

    this.prompts.push({
      type:     'text',
      name:     'authorURI',
      message:  'Author URI (e.g. www.johnsmith.com)',
      default:  function() {
        return existing() || '';
      }.bind(this)
    });
  },
  promptForDescription: function() {
    var existing = function() {
      try {
        var bower = require(path.join(this.env.cwd, 'bower.json'));

        return bower.description;
      } catch(e) {};
    }.bind(this);

    this.prompts.push({
      type:     'text',
      name:     'projDescription',
      message:  'Project Description',
      default:  function() {
        return existing() || '';
      }.bind(this)
    });
  },
  promptForVersion: function() {
    var existing = function() {
      try {
        var bower = require(path.join(this.env.cwd, 'bower.json'));

        return bower.version;
      } catch(e) {};
    }.bind(this);

    this.prompts.push({
      type:     'text',
      name:     'projVersion',
      message:  'Project version',
      default:  function() {
        return existing() || '0.1.0';
      }.bind(this)
    });
  },
  searchForThemesDir: function() {
    var props = this.props = [];

    glob.sync('**/wp-content/themes', function(err, matches) {
      if (err) throw err;

      if (matches.length) {
        props.themesDir = matches[0];
      }
    });
  },
  promptForThemesDir: function() {
    this.prompts.push({
      type:     'text',
      name:     'themesDir',
      message:  'Themes directory',
      default:  function() {
        return this.props.themesDir || 'web/wp-content/themes';
      }.bind(this)
    });
  },
  promptForChild: function() {
    var existing = function(response) {
      var childLoc = path.join(response.themesDir, response.projShortName + '-theme');

      try {
        var style = this.readFileAsString(path.join(childLoc, 'style.css'));

        if (style.length) {
          return true;
        }
      } catch(e) {}
    }.bind(this);

    this.prompts.push({
      when:     function(response) {
        return existing(response);
      },
      type:     'confirm',
      name:     'writeChild',
      message:  'Overwrite existing child theme?',
      default:  'no'
    });
  },
  ask: function() {
    var done = this.async();

    // have Yeoman greet the user.
    console.log(this.yeoman);

    this.prompt(this.prompts, function(props) {
      this.props = props;

      done();
    }.bind(this));
  },
  ready: function() {
    this.log.write('\n');
    this.log.info(chalk.green('Here we go!'));
  },
  getBranch: function() {
    if (this.branch) {
      return false;
    }

    var done = this.async();

    latest('wp-evolved', 'evolved-theme', function(err, tag) {
      this.branch = tag || 'master';
      done();
    }.bind(this));
  },
  cloneThemeFiles: function() {
    this.log.info('Copying theme files from ' + chalk.cyan('evolved-theme ') + chalk.yellow('@' + this.branch));

    var done = this.async();
    var existing = function(location) {
      try {
        var style = this.readFileAsString(path.join(location, 'style.css'));

        if (style.length) {
          return true;
        } else {
          return false;
        }
      } catch(e) {}
    }.bind(this);

    var themesDir   = this.props.themesDir;
    var childName   = this.props.projShortName + '-theme';
    var parentDir   = path.join(themesDir, '/evolved-parent-theme')
    var childDir    = path.join(themesDir, childName);
    var writeChild  = !existing(childDir) || this.props.writeChild;

    this.remote('wp-evolved', 'evolved-theme', this.branch, function(err, remote) {
      remote.directory('./themes/evolved-parent-theme', parentDir);

      if (writeChild) {
        remote.directory('./themes/evolved-child-theme', childDir);
      }

      done();
    });
  },
  writeProjectFiles: function() {
    this.log.info('Writing project files...');

    this.copy('_gitignore', '.gitignore');
    this.copy('_editorconfig', '.editorconfig');
    this.copy('_jshintrc', '.jshintrc');

    this.template('_Gruntfile.js', 'Gruntfile.js');
    this.template('_bower.json', 'bower.json');
    this.template('_package.json', 'package.json');
  }
});

module.exports = EvolvedGenerator;
<commit_msg>Updated user name and theme repo to variables for re-use<commit_after>'use strict';
var util    = require('util');
var path    = require('path');
var yeoman  = require('yeoman-generator');
var fs      = require('fs-extra');
var chalk   = require('chalk');
var glob    = require('glob');
var latest  = require('github-latest');
var request = require('request');

var user_name   = 'wp-evolved';
var theme_repo  = 'evolved-theme';

var EvolvedGenerator = yeoman.generators.Base.extend({
  init: function() {
    this.prompts  = [];
    this.pkg      = require('../package.json');

    this.on('end', function() {
      this.config.save();
      this.log.info('Running ' + chalk.yellow('bower install') + ' & ' + chalk.yellow('npm install') + ' for you to install the required dependencies. If this fails, try running the command yourself.');
      if (!this.options['skip-install']) {
        this.installDependencies({
          bower:        true,
          npm:          true,
          skipMessage:  true,
          callback:     function() {
            this.log.ok('All done! Run ' + chalk.yellow('grunt build:dev') + ' and ' + chalk.yellow('grunt watch') + ' to get started!');
          }.bind(this)
        });
      }
    });
  },
  setBranch: function() {
    if (this.args.length) {
      var i = 0;
      var l = this.args.length;

      for(i; i < l; i++) {
        if (this.args[i].indexOf('@') === 0) {
          this.branch = this.args[i].slice(1);
        }
      }
    }
  },
  verifyBranch: function() {
    if (this.branch) {
      var done  = this.async();
      var url   = 'http://github.com/' + [user_name, theme_repo, 'archive', this.branch].join('/') + '.tar.gz';

      request(url, function(err, resp, body) {
        if (err || resp.statusCode !== 200) {
          var err = chalk.yellow(this.branch) + chalk.red(' is not an existing remote endpoint') + '\n';

          throw err;
        } else {
          done();
        }
      }.bind(this));
    }
  },
  promptForName: function() {
    var existing = function() {
      try {
        var bower = require(path.join(this.env.cwd, 'bower.json'));

        return bower.name;
      } catch(e) {};
    }.bind(this);

    this.prompts.push({
      required: true,
      type:     'text',
      name:     'projName',
      message:  'Project Name (e.g. MySite)',
      default:  function() {
        return existing() || path.basename(this.env.cwd);
      }.bind(this)
    });
  },
  promptForShortName: function() {
    var existing = function() {
      try {
        var bower = require(path.join(this.env.cwd, 'bower.json'));

        return bower.shortName;
      } catch(e) {};
    }.bind(this);

    this.prompts.push({
      required: true,
      type:     'text',
      name:     'projShortName',
      message:  'Project short name (e.g. mscom)',
      default:  function() {
        var ext       = path.extname(this.env.cwd);
        var extname   = ext.replace('.','');
        var base      = path.basename(this.env.cwd).replace(ext, '');
        var basename  = (/[A-Z]/.test(base)) ? base.replace(/[^A-Z]/g, '') : base.charAt(0);

        return existing() || (basename + extname).toLowerCase();
      }.bind(this)
    });
  },
  promptForAuthorName: function() {
    var existing = function() {
      try {
        var bower = require(path.join(this.env.cwd, 'bower.json'));

        return bower.author.name;
      } catch(e) {};
    }.bind(this);

    this.prompts.push({
      type:     'text',
      name:     'authorName',
      message:  'Author Name (e.g. John Smith)',
      default:  function() {
        return existing() || '';
      }.bind(this)
    });
  },
  promptForAuthorURI: function() {
    var existing = function() {
      try {
        var bower = require(path.join(this.env.cwd, 'bower.json'));

        return bower.author.url
      } catch(e) {};
    }.bind(this);

    this.prompts.push({
      type:     'text',
      name:     'authorURI',
      message:  'Author URI (e.g. www.johnsmith.com)',
      default:  function() {
        return existing() || '';
      }.bind(this)
    });
  },
  promptForDescription: function() {
    var existing = function() {
      try {
        var bower = require(path.join(this.env.cwd, 'bower.json'));

        return bower.description;
      } catch(e) {};
    }.bind(this);

    this.prompts.push({
      type:     'text',
      name:     'projDescription',
      message:  'Project Description',
      default:  function() {
        return existing() || '';
      }.bind(this)
    });
  },
  promptForVersion: function() {
    var existing = function() {
      try {
        var bower = require(path.join(this.env.cwd, 'bower.json'));

        return bower.version;
      } catch(e) {};
    }.bind(this);

    this.prompts.push({
      type:     'text',
      name:     'projVersion',
      message:  'Project version',
      default:  function() {
        return existing() || '0.1.0';
      }.bind(this)
    });
  },
  searchForThemesDir: function() {
    var props = this.props = [];

    glob.sync('**/wp-content/themes', function(err, matches) {
      if (err) throw err;

      if (matches.length) {
        props.themesDir = matches[0];
      }
    });
  },
  promptForThemesDir: function() {
    this.prompts.push({
      type:     'text',
      name:     'themesDir',
      message:  'Themes directory',
      default:  function() {
        return this.props.themesDir || 'web/wp-content/themes';
      }.bind(this)
    });
  },
  promptForChild: function() {
    var existing = function(response) {
      var childLoc = path.join(response.themesDir, response.projShortName + '-theme');

      try {
        var style = this.readFileAsString(path.join(childLoc, 'style.css'));

        if (style.length) {
          return true;
        }
      } catch(e) {}
    }.bind(this);

    this.prompts.push({
      when:     function(response) {
        return existing(response);
      },
      type:     'confirm',
      name:     'writeChild',
      message:  'Overwrite existing child theme?',
      default:  'no'
    });
  },
  ask: function() {
    var done = this.async();

    // have Yeoman greet the user.
    console.log(this.yeoman);

    this.prompt(this.prompts, function(props) {
      this.props = props;

      done();
    }.bind(this));
  },
  ready: function() {
    this.log.write('\n');
    this.log.info(chalk.green('Here we go!'));
  },
  getBranch: function() {
    if (this.branch) {
      return false;
    }

    var done = this.async();

    latest(user_name, theme_repo, function(err, tag) {
      this.branch = tag || 'master';
      done();
    }.bind(this));
  },
  cloneThemeFiles: function() {
    this.log.info('Copying theme files from ' + chalk.cyan(theme_repo) + ' ' + chalk.yellow('@' + this.branch));

    var done = this.async();
    var existing = function(location) {
      try {
        var style = this.readFileAsString(path.join(location, 'style.css'));

        if (style.length) {
          return true;
        } else {
          return false;
        }
      } catch(e) {}
    }.bind(this);

    var themesDir   = this.props.themesDir;
    var childName   = this.props.projShortName + '-theme';
    var parentDir   = path.join(themesDir, '/evolved-parent-theme')
    var childDir    = path.join(themesDir, childName);
    var writeChild  = !existing(childDir) || this.props.writeChild;

    this.remote(user_name, theme_repo, this.branch, function(err, remote) {
      remote.directory('./themes/evolved-parent-theme', parentDir);

      if (writeChild) {
        remote.directory('./themes/evolved-child-theme', childDir);
      }

      done();
    });
  },
  writeProjectFiles: function() {
    this.log.info('Writing project files...');

    this.copy('_gitignore', '.gitignore');
    this.copy('_editorconfig', '.editorconfig');
    this.copy('_jshintrc', '.jshintrc');

    this.template('_Gruntfile.js', 'Gruntfile.js');
    this.template('_bower.json', 'bower.json');
    this.template('_package.json', 'package.json');
  }
});

module.exports = EvolvedGenerator;
<|endoftext|>


<commit_before>$(document).ready(function() {
	$(".delete").click(deleteHabit);

	$("#create-habit").submit(createHabit);

	_.templateSettings = {
	interpolate: /\<\@\=(.+?)\@\>/gim,
	evaluate: /\<\@(.+?)\@\>/gim,
	escape: /\<\@\-(.+?)\@\>/gim
	};
});

var deleteHabit = function(e){
	e.preventDefault();
	url = $(e.target).attr('href');
	$target = $(e.target);

	$.ajax({
		url: url,
		type: 'delete'
	}).done(function(response){
		$target.closest('.habit-each').remove();
	})
}

var createHabit = function(e){
	e.preventDefault();
	$target = $(e.target);

	//
Habit Name

	//

	//
consecutive counter :

	//
total counter :

	//

	// done!
	// edit
	// delete

	$.ajax({
		url: $target.attr('action'),
		type: 'post',
		data: $target.serialize()
	}).done(function(response){
		var habitTemplate = document.getElementById("habit-template");
		var content = habitTemplate.innerHTML;
		var habit = document.createElement('div');
		habit.className = "habit-each"
		habit.id = response.id
		// $('#habit-container').prepend('
' + response.habit_name + '

consecutive counter : '+ response.consecutive_counter + '

total counter : ' + response.total_counter + '

done! edit delete');

    var templateFunction = _.template(content);

		$('#habit-container').prepend(templateFunction( {habit_name: response.habit_name,
										  							consecutive_counter: response.consecutive_counter,
									  								total_counter: response.total_counter,
																		id: response.id
																	} )
		);
		// debugger;
		// console.log(templateFunction( {habit_name: response.habit_name,
		// 								  							consecutive_counter: response.consecutive_counter,
		// 							  								total_counter: response.total_counter,
		// 																id: response.id
		// 															} )
  //   );

    // var orangeTreeTemplate = document.getElementById("orange-tree-template")
    // var content = orangeTreeTemplate.innerHTML
    // var orangeTree = document.createElement('div');
    // orangeTree.className = "tree-container"
    // orangeTree.id = generateTreeId();
    // orangeTree.innerHTML = content;
    // var grove = document.querySelector(".grove");
    // grove.appendChild(orangeTree);
	});
}<commit_msg>delete comments<commit_after>$(document).ready(function() {
	$(".delete").click(deleteHabit);

	$("#create-habit").submit(createHabit);

	_.templateSettings = {
	interpolate: /\<\@\=(.+?)\@\>/gim,
	evaluate: /\<\@(.+?)\@\>/gim,
	escape: /\<\@\-(.+?)\@\>/gim
	};
});

var deleteHabit = function(e){
	e.preventDefault();
	url = $(e.target).attr('href');
	$target = $(e.target);

	$.ajax({
		url: url,
		type: 'delete'
	}).done(function(response){
		$target.closest('.habit-each').remove();
	})
}

var createHabit = function(e){
	e.preventDefault();
	$target = $(e.target);

	$.ajax({
		url: $target.attr('action'),
		type: 'post',
		data: $target.serialize()
	}).done(function(response){
		var habitTemplate = document.getElementById("habit-template");
		var content = habitTemplate.innerHTML;
		var habit = document.createElement('div');
		habit.className = "habit-each"
		habit.id = response.id

    var templateFunction = _.template(content);

		$('#habit-container').prepend(templateFunction( { habit_name: response.habit_name,
										  						  consecutive_counter: response.consecutive_counter,
									  							  total_counter: response.total_counter,
																	  id: response.id
																	} )
		);
	});
}<|endoftext|>


<commit_before>(function(module) {

  formHandler = {};
  formHandler.userName = '';
  formHandler.el = {};
  formHandler.el.$nameAlert = $('#nameAlert');
  formHandler.el.$output = $('#output');
  formHandler.el.$outputText = $('#outputText');
  formHandler.el.$nameForm = $('#nameForm');
  formHandler.el.$locationForm = $('#locationForm');
  formHandler.el.$submitName = $('#submitName');
  formHandler.el.$submitLocation = $('#submitLocation');

  formHandler.init = function(){
    if (localStorage.currentUser) {
      console.log('Name was already there.');
      userName = localStorage.currentUser;
      formHandler.el.$nameForm.hide();
      formHandler.el.$locationForm.show();
    } else {

      $('button').click(function(e){
        e.preventDefault();
        userName = $('input:text').val();
        localStorage.currentUser = userName;
      });
    }

  };

  formHandler.recommendation= function(temp){
    console.log(temp + 'hi there');
    var response = '';
    if (temp < 50){
      response = 'cold';
    } else if ((temp >= 50) && (temp < 75)) {
      response = 'good';
    } else {
      resonse = 'hot';
    }

    return response;
  };

  formHandler.showRec = function (){
    formHandler.el.$output.text(formHandler.recommendation(userLocation.all[0].temperature));
  };

  // function useName(currentUser, goodDayOrBadDay) { //params of currentUser and what kind of day it is
  //   var makeGoodorBad = function(goodOrBad) {  //makeGoodorBad - to display correct kind of day later
  //     formHandler.el.$output.append('
' + formHandler.el.$outputText.text() + '
'); // adds a
 to the output section
  //     formHandler.el.$outputText.text('Hey ' + currentUser + ', ' + goodOrBad); // adds the message text to the output

  //   };
  //   return makeGoodorBad;
  // }
  //
  // //here cometh the Closure 😱
  // function message (currentUser){
  //   var goodDay = useName(currentUser, 'itsgood');
  //   goodDay('what a great day for biking!');
  //   var badDay = useName(currentUser, 'itsbad');
  //   badDay('maybe leave the bike at home today....');
  //   var soSoDay = useName(currentUser, 'itssoso');
  //   soSoDay('Conditions are not ideal. Depends on you, dude...');
  // };

  //Event Listeners for Submit Button
  formHandler.el.$submitName.click(validateUserName);

  function validateUserName(e) {
    e.preventDefault();
    // $nfValidator.element('#fname');
    var userName = document.forms['nameInput']['fname'].value;
    if (!userName) { // if userName is falsy
      formHandler.el.$nameAlert.show();
      // $output.hide();
    }else {

      formHandler.el.$nameAlert.hide();
      formHandler.el.$nameForm.hide();
      // $output.show();
      formHandler.el.$locationForm.show();
    }
  };

  //Event Listener for Submit Button2
  formHandler.el.$submitLocation.click(validateLocation);

  //Validating the input for the Location Form

  function validateLocation(e){
    e.preventDefault();

    var locationDataForm = document.forms['locationData'];
    var inputLocation = {};
    var locationName = locationDataForm['flocationname'].value;

    if (!locationName){ // if location name falsy
      $('#locationNameAlert').show();
    } else {
      inputLocation.locationName = locationName;
    };

    var streetAddress = locationDataForm['fstreetaddress'].value;
    if (!streetAddress) { // if location address falsy
      $('#locationAddressAlert').show();
    } else {
      inputLocation.streetAddress = streetAddress;
    };

    var city = locationDataForm['fcity'].value;
    if (!city) { // if location city falsy
      $('#locationCityAlert').show();
    } else {
      inputLocation.city = city;
    };

    var state = locationDataForm['fstate'].value;
    if (!state) { // if location state falsy
      $('#locationStateAlert').show();
    } else {
      inputLocation.state = state;
    };

    var zipcode = locationDataForm['fzip'].value;
    if (!zipcode) { // if location zipcode falsy
      $('#locationZipAlert').show();
    } else {
      inputLocation.zipcode = zipcode;
    };
    var obj = new userLocation(inputLocation);
    obj.insertRecord(userLocation.merge);
  };

//tooltips

  // var $nfValidator = $('#nameForm').validate({
  //   debug: true,
  //   showErrors: function(errorMap, errorList) {
  //     console.log('got to showErrors.');
  //     $.each(this.validElements(), function (index, element) {
  //       var $element = $(element);
  //       $element.data('title', '')
  //       .removeClass('error')
  //       .tooltip('destroy');
  //     });
  //
  //     $.each(errorList, function (index, error) {
  //       var $element = $(error.element);
  //       $element.parent().addClass('has-error');
  //       $element.tooltip('destroy')
  //       .data('title', error.message)
  //       // .addClass('error')
  //       .tooltip();
  //     });
  //   },
  //   submitHandler: function(form) {
  //     alert('This is a valid form!');
  //   }
  // });

  formHandler.init();

  module.formHandler = formHandler;
})(window);
<commit_msg>Refactored form handler.  Added per-item validation.  Reset thej form after submit.  Only submit after complete form is valid.  Resolves #80.  Resolves #79.<commit_after>(function(module) {

  formHandler = {};
  formHandler.userName = '';
  formHandler.el = {};
  formHandler.el.$nameAlert = $('#nameAlert');
  formHandler.el.$output = $('#output');
  formHandler.el.$outputText = $('#outputText');
  formHandler.el.$nameForm = $('#nameForm');
  formHandler.el.$locationForm = $('#locationForm');
  formHandler.el.$submitName = $('#submitName');
  formHandler.el.$submitLocation = $('#submitLocation');

  formHandler.init = function(){
    if (localStorage.currentUser) {
      console.log('Name was already there.');
      userName = localStorage.currentUser;
      formHandler.el.$nameForm.hide();
      formHandler.el.$locationForm.show();
    } else {

      $('button').click(function(e){
        e.preventDefault();
        userName = $('input:text').val();
        localStorage.currentUser = userName;
      });
    }

  };

  formHandler.recommendation= function(temp){
    console.log(temp + 'hi there');
    var response = '';
    if (temp < 50){
      response = 'cold';
    } else if ((temp >= 50) && (temp < 75)) {
      response = 'good';
    } else {
      resonse = 'hot';
    }

    return response;
  };

  formHandler.showRec = function (){
    formHandler.el.$output.text(formHandler.recommendation(userLocation.all[0].temperature));
  };

  //Event Listeners for Submit Button
  formHandler.el.$submitName.click(validateUserName);

  function validateUserName(e) {
    e.preventDefault();
    // $nfValidator.element('#fname');
    var userName = document.forms['nameInput']['fname'].value;
    if (!userName) { // if userName is falsy
      formHandler.el.$nameAlert.show();
      // $output.hide();
    }else {

      formHandler.el.$nameAlert.hide();
      formHandler.el.$nameForm.hide();
      // $output.show();
      formHandler.el.$locationForm.show();
    }
  };

  //Event Listener for Submit Button2
  formHandler.el.$submitLocation.click(validateLocation);

  //Validating the input for the Location Form

  function validateLocation(e){
    e.preventDefault();
    var error = false;
    var ldf = document.getElementById('locationForm');
    var inputLocation = {};
    $('fieldset > p').hide();
    inputLocation.locationName = ldf.elements.flocationname.value;
    inputLocation.streetAddress = ldf.elements.fstreetaddress.value;
    inputLocation.city = ldf.elements.fcity.value;
    inputLocation.state = ldf.elements.fstate.value;
    inputLocation.zipcode = ldf.elements.fzip.value;

    if (!inputLocation.locationName){ // if location name falsy
      $('#locationNameAlert').show();
      error = true;
    }
    if (!inputLocation.streetAddress) { // if location address falsy
      $('#locationAddressAlert').show();
      error = true;
    }
    if (!inputLocation.city) { // if location city falsy
      $('#locationCityAlert').show();
      error = true;
    }
    if (!inputLocation.state) { // if location state falsy
      $('#locationStateAlert').show();
      error = true;
    }
    if (!inputLocation.zipcode) { // if location zipcode falsy
      $('#locationZipAlert').show();
      error = true;
    }
    if (!error) {
      var obj = new userLocation(inputLocation);
      obj.insertRecord(userLocation.merge);
      ldf.reset();
    }
  };

//tooltips

  // var $nfValidator = $('#nameForm').validate({
  //   debug: true,
  //   showErrors: function(errorMap, errorList) {
  //     console.log('got to showErrors.');
  //     $.each(this.validElements(), function (index, element) {
  //       var $element = $(element);
  //       $element.data('title', '')
  //       .removeClass('error')
  //       .tooltip('destroy');
  //     });
  //
  //     $.each(errorList, function (index, error) {
  //       var $element = $(error.element);
  //       $element.parent().addClass('has-error');
  //       $element.tooltip('destroy')
  //       .data('title', error.message)
  //       // .addClass('error')
  //       .tooltip();
  //     });
  //   },
  //   submitHandler: function(form) {
  //     alert('This is a valid form!');
  //   }
  // });

  formHandler.init();

  module.formHandler = formHandler;
})(window);
<|endoftext|>


<commit_before>// Copyright 2002-2014, University of Colorado Boulder

/**
 * Basic model for a push button, intended to be added as an input listener to
 * any Scenery node in order to allow it to behave as a button.
 *
 * IMPORTANT USAGE NOTES:
 * - The node to which this is added should not be made non-pickable when
 *   the disabled state is entered, or subsequent states may not be correct.
 * - Generally speaking, only one of these should be added to a given node.
 *
 * @author John Blanco
 */
define( function( require ) {
  'use strict';

  var inherit = require( 'PHET_CORE/inherit' );
  var PropertySet = require( 'AXON/PropertySet' );

  /**
   * @param {Object} options
   * @constructor
   */
  function ToggleButtonModel3( options ) {
    options = _.extend(
      {
        toggleOnDown: false
      }, options );

    PropertySet.call( this, {
      overPointer: null,
      downPointer: null,
      up: true,
      enabled: true
    } );

    //Example of how to map to the ButtonModelStates
    this.addDerivedProperty( 'interactionState', ['overPointer', 'downPointer', 'up', 'enabled'], function( overPointer, downPointer, up, enabled ) {
      if ( !enabled ) {
        return 'disabled';
      }
      else {
        if ( !overPointer && !downPointer ) {
          return 'idle';
        }
        else if ( overPointer && downPointer && overPointer === downPointer ) {
          return 'down';
        }

        //... etc.
      }
    } );

    //But what about just using these boolean states directly for rendering:  enabled, up, over
  }

  return inherit( PropertySet, ToggleButtonModel3, {
  } );
} );<commit_msg>Removed ToggleButtonModel3, an unused prototype for discussion<commit_after><|endoftext|>


<commit_before>if(void 0===OGX)var OGX=function(){};OGX.FormTools=function(){"use strict";var l=this,o={container:!1,allowed:!1,forbidden:!1,change_cb:!1,submit_cb:!1,validate:!1,elem_types:["input","textarea"],wait:1e3,fields:{}},t={container:!1,allowed:/^[a-z0-9\\!\\.\\?\\#\\@\\$\\-\\:\\(\\)\\/_,;%'"’ ]$/gi,forbidden:!1,mask:!1,mask_char:"%",paste:!0,autocomplete:null,multiline:!1,input_cb:!1,change_cb:!1,val:null,changing:!1,wait:1e3,intv:null,max:2500,type:"string",params:null},u={},a={};function c(e,t){if(u[t].change_cb){var n=p(t);for(var a in n)u[t].hasOwnProperty("fields")&&u[t].fields.hasOwnProperty(a)&&u[t].fields[a].hasOwnProperty("type")?n[a]=s(u[t].fields[a].type,n[a]):u[t].hasOwnProperty("type")&&(n[a]=s(u[t].type,n[a]));u[t].change_cb(n)}}function s(e,t){switch(e){case"string":return String(t);case"number":return Number(t);case"int":return parseInt(t);case"bool":return"true"===t||1===t}}function p(e){return $(e).serializeArray().map(function(e){return this[e.name]=e.value,this}.bind({}))[0]}function f(e){return Object.assign({},e)}function m(e,t){for(var n in t)e.hasOwnProperty(n)&&(e[n]=t[n]);return e}this.bindForm=function(e){return!u.hasOwnProperty(e.container)&&(function(e){var r,i,a=m(f(o),e);$(a.container).on("submit",function(e){e.preventDefault(),e.stopImmediatePropagation();var t={obj:p(a.container),form:a.container};if(u[a.container].validate){var n=l.validateForm(a.container);!0===n?t.valid=!0:(t.valid=!1,t.error=n)}u[a.container].change_cb?u[a.container].change_cb(t):u[a.container].submit_cb?u[a.container].submit_cb(t):$(a.container).trigger("change",t)});for(var t=0;t<a.elem_types.length;t++)$(a.container).find(a.elem_types[t]).each(function(e,t){n(a,e,t)});function n(e,t,n){if(n.hasAttribute("name")){if(r=$(n).attr("name"),delete(i=f(e)).fields,delete i.container,e.hasOwnProperty("fields")&&e.fields.hasOwnProperty(r))for(var a in e.fields[r])i[a]=e.fields[r][a];i.container=e.container+" "+n.tagName.toLowerCase()+'[name="'+r+'"]',i.change_cb=c,i.params=e.container,l.bindField(i)}}u[a.container]=a}(e),!0)},this.unbindForm=function(e){u.hasOwnProperty(e)&&(!function(n){var a;$(document).off("submit",n);for(var r=0;r<u[n].elem_types.length;r++)$(n).find(u[n].elem_types[r]).each(function(e,t){t.hasAttribute("name")&&(a=$(t).attr("name"),l.unbindField(n+" "+u[n].elem_types[r]+'[name="'+a+'"]'))});delete u[n]}(e),delete u[e])},this.bindField=function(e){if(u.hasOwnProperty(e.container))return!1;!function(e){var i=m(f(t),e),o=$(i.container),c=o.attr("name");o.on("input change",function(){var e=$(this).val();if(i.input_cb){var t={value:null,obj:{},el:null};e=s(i.type,e),t.el=o[0],t.value=e,t.property=c,t.obj[c]=e,options.input_cb(t,i.params)}u[i.container].intv||(u[i.container].intv=setInterval(function(){!function(e,t){var n=$(e).val(),a=u[e];if(a.val!==n&&(a.val=n,a.changing=(new Date).getTime()),a.changing&&(new Date).getTime()>a.wait+a.changing&&(clearInterval(a.intv),a.intv=!1,u[e].change_cb)){var r={value:null,obj:{},el:null};n=s(u[e].type,n),r.el=$(e)[0],r.property=$(e).attr("name"),r.value=n,r.obj[r.property]=n,u[e].change_cb(r,t)}}(i.container,i.params)},50))}),i.multiline||o.on("keypress",function(e){var t=$(this).val();if(13!==e.which&&i.mask){if(t.length>i.mask.length)return e.preventDefault(),e.stopImmediatePropagation(),!1;for(var n=i.mask,a=0;a<t.length;a++)i.mask.substr(a,1)===i.mask_char&&(n=n.replace(i.mask_char,t.substr(a,1)));-1!==(t=n).indexOf(i.mask_char)&&(t=t.substr(0,t.indexOf(i.mask_char))),o.val(t)}if(13===e.which){e.preventDefault(),e.stopImmediatePropagation();var t=$(this).val();if(u[i.container].intv&&(clearInterval(u[i.container].intv),u[i.container].intv=null),i.change_cb){var r={value:null,obj:{},el:null};t=s(i.type,t),r.el=o[0],r.property=c,r.value=t,r.obj[c]=t,i.change_cb(r,i.params)}else o.trigger("change",t)}});((u[i.container]=i).allowed||i.forbidden)&&l.restrictField(i)}(e)},this.unbindField=function(e){if(u.hasOwnProperty(e)){var t=$(e);t.off("input change"),u[e].multiline||t.off("keypress"),u[e].intv&&clearInterval(u[e].intv),a.hasOwnProperty(e)&&l.unrestrictField(e),delete u[e]}},this.restrictField=function(e){return!a.hasOwnProperty(e.container)&&(function(n){var e=$(n.container);a[n.container]=n,a[n.container].keys=[],null===n.autocomplete&&e[0].hasAttribute("autocomplete")&&"on"===e.attr("autocomplete")?n.autocomplete=!0:n.autocomplete=!1;n.autocomplete?n.hasOwnProperty("allowed")&&n.allowed&&(n.allowed=new RegExp(n.allowed.toString().replace("$/gi","+$").replace("/^","^"),"gi")):a[n.container].keys.push(229);-1!==["input","texarea"].indexOf(e.get(0).tagName.toLowerCase())?a[n.container].content="val":a[n.container].content="html";a[n.container].multiline||a[n.container].keys.push(13);e.on("textInput keydown",function(e){if("textInput"===e.type){var t=e.originalEvent.data;if(a[n.container].allowed){if(!t.match(a[n.container].allowed))return e.preventDefault(),e.stopImmediatePropagation(),!1}else if(a[n.container].forbidden&&t.match(a[n.container].forbidden))return e.preventDefault(),e.stopImmediatePropagation(),!1}if("keydown"===e.type){if(-1!==a[n.container].keys.indexOf(e.which))return e.preventDefault(),e.stopImmediatePropagation(),!1;if($(this)[a[n.container].content]().length>=a[n.container].max&&8!==e.which)return e.preventDefault(),e.stopImmediatePropagation(),!1}}),a[n.container].paste||e.on("paste",function(e){e.preventDefault(),e.stopImmediatePropagation()})}(e),!0)},this.unrestrictField=function(e){if(a.hasOwnProperty(e)){var t=$(e);return t.off("textInput keydown"),a[e].paste||t.off("paste"),delete a[e],!0}return!1},this.formToObj=function(e){return p(e)},this.populateForm=function(e,n){var a,t=$(e);function r(e,t){a=$(t).attr("name"),e.hasOwnProperty(a)&&$(t).val(e[a])}t.find("input").each(function(e,t){r(n,t)}),t.find("texarea").each(function(e,t){r(n,t)})},this.validateForm=function(e){var n,a,r,t=$(e),i={},o=!0;return t.find("input").each(function(e,t){n=$(t),t.hasAttribute("required")&&t.hasAttribute("pattern")&&"submit"!==n.attr("type")&&(a=n.attr("pattern"),r=n.val(),a&&((a=new RegExp(a,"g")).test(r)||(i[n.attr("name")]=!1,o=!1)))}),!!o||i}},OGX.FormTools=new OGX.FormTools;<commit_msg><commit_after>if(void 0===OGX)var OGX=function(){};OGX.FormTools=function(){"use strict";var l=this,o={container:!1,allowed:!1,forbidden:!1,change_cb:!1,submit_cb:!1,validate:!1,elem_types:["input","textarea"],wait:1e3,fields:{}},t={container:!1,allowed:/^[a-z0-9\\!\\.\\?\\#\\@\\$\\-\\:\\(\\)\\/_,;%'"’ ]$/gi,forbidden:!1,mask:!1,mask_char:"%",paste:!0,autocomplete:null,multiline:!1,input_cb:!1,change_cb:!1,val:null,changing:!1,wait:1e3,intv:null,max:2500,type:"string",params:null},u={},a={};function c(e,t){if(u[t].change_cb){var n=p(t);for(var a in n)u[t].hasOwnProperty("fields")&&u[t].fields.hasOwnProperty(a)&&u[t].fields[a].hasOwnProperty("type")?n[a]=s(u[t].fields[a].type,n[a]):u[t].hasOwnProperty("type")&&(n[a]=s(u[t].type,n[a]));u[t].change_cb(n)}}function s(e,t){switch(e){case"string":return String(t);case"number":return Number(t);case"int":return parseInt(t);case"bool":return"true"===t||1===t}}function p(e){return $(e).serializeArray().map(function(e){return this[e.name]=e.value,this}.bind({}))[0]}function f(e){return Object.assign({},e)}function m(e,t){for(var n in t)e.hasOwnProperty(n)&&(e[n]=t[n]);return e}this.bindForm=function(e){return!u.hasOwnProperty(e.container)&&(function(e){var r,i,a=m(f(o),e);$(a.container).on("submit",function(e){e.preventDefault(),e.stopImmediatePropagation();var t={obj:p(a.container),form:a.container};if(u[a.container].validate){var n=l.validateForm(a.container);!0===n?t.valid=!0:(t.valid=!1,t.error=n)}u[a.container].change_cb?u[a.container].change_cb(t):u[a.container].submit_cb?u[a.container].submit_cb(t):$(a.container).trigger("change",t)});for(var t=0;t<a.elem_types.length;t++)$(a.container).find(a.elem_types[t]).each(function(e,t){n(a,e,t)});function n(e,t,n){if(n.hasAttribute("name")){if(r=$(n).attr("name"),delete(i=f(e)).fields,delete i.container,e.hasOwnProperty("fields")&&e.fields.hasOwnProperty(r))for(var a in e.fields[r])i[a]=e.fields[r][a];i.container=e.container+" "+n.tagName.toLowerCase()+'[name="'+r+'"]',i.change_cb=c,i.params=e.container,l.bindField(i)}}u[a.container]=a}(e),!0)},this.unbindForm=function(e){u.hasOwnProperty(e)&&(!function(n){var a;$(document).off("submit",n);for(var r=0;r<u[n].elem_types.length;r++)$(n).find(u[n].elem_types[r]).each(function(e,t){t.hasAttribute("name")&&(a=$(t).attr("name"),l.unbindField(n+" "+u[n].elem_types[r]+'[name="'+a+'"]'))});delete u[n]}(e),delete u[e])},this.bindField=function(e){if(u.hasOwnProperty(e.container))return!1;!function(e){var i=m(f(t),e),o=$(i.container),c=o.attr("name"),n=o.val();o.on("input change",function(){var e=$(this).val();if(e!==n){if(n=e,i.input_cb){var t={value:null,obj:{},el:null};e=s(i.type,e),t.el=o[0],t.value=e,t.property=c,t.obj[c]=e,options.input_cb(t,i.params)}u[i.container].intv||(u[i.container].intv=setInterval(function(){!function(e,t){var n=$(e).val(),a=u[e];if(a.val!==n&&(a.val=n,a.changing=(new Date).getTime()),a.changing&&(new Date).getTime()>a.wait+a.changing&&(clearInterval(a.intv),a.intv=!1,u[e].change_cb)){var r={value:null,obj:{},el:null};n=s(u[e].type,n),r.el=$(e)[0],r.property=$(e).attr("name"),r.value=n,r.obj[r.property]=n,u[e].change_cb(r,t)}}(i.container,i.params)},50))}}),i.multiline||o.on("keypress",function(e){var t=$(this).val();if(13!==e.which&&i.mask){if(t.length>i.mask.length)return e.preventDefault(),e.stopImmediatePropagation(),!1;for(var n=i.mask,a=0;a<t.length;a++)i.mask.substr(a,1)===i.mask_char&&(n=n.replace(i.mask_char,t.substr(a,1)));-1!==(t=n).indexOf(i.mask_char)&&(t=t.substr(0,t.indexOf(i.mask_char))),o.val(t)}if(13===e.which){e.preventDefault(),e.stopImmediatePropagation();var t=$(this).val();if(u[i.container].intv&&(clearInterval(u[i.container].intv),u[i.container].intv=null),i.change_cb){var r={value:null,obj:{},el:null};t=s(i.type,t),r.el=o[0],r.property=c,r.value=t,r.obj[c]=t,i.change_cb(r,i.params)}else o.trigger("change",t)}});((u[i.container]=i).allowed||i.forbidden)&&l.restrictField(i)}(e)},this.unbindField=function(e){if(u.hasOwnProperty(e)){var t=$(e);t.off("input change"),u[e].multiline||t.off("keypress"),u[e].intv&&clearInterval(u[e].intv),a.hasOwnProperty(e)&&l.unrestrictField(e),delete u[e]}},this.restrictField=function(e){return!a.hasOwnProperty(e.container)&&(function(n){var e=$(n.container);a[n.container]=n,a[n.container].keys=[],null===n.autocomplete&&e[0].hasAttribute("autocomplete")&&"on"===e.attr("autocomplete")?n.autocomplete=!0:n.autocomplete=!1;n.autocomplete?n.hasOwnProperty("allowed")&&n.allowed&&(n.allowed=new RegExp(n.allowed.toString().replace("$/gi","+$").replace("/^","^"),"gi")):a[n.container].keys.push(229);-1!==["input","texarea"].indexOf(e.get(0).tagName.toLowerCase())?a[n.container].content="val":a[n.container].content="html";a[n.container].multiline||a[n.container].keys.push(13);e.on("textInput keydown",function(e){if("textInput"===e.type){var t=e.originalEvent.data;if(a[n.container].allowed){if(!t.match(a[n.container].allowed))return e.preventDefault(),e.stopImmediatePropagation(),!1}else if(a[n.container].forbidden&&t.match(a[n.container].forbidden))return e.preventDefault(),e.stopImmediatePropagation(),!1}if("keydown"===e.type){if(-1!==a[n.container].keys.indexOf(e.which))return e.preventDefault(),e.stopImmediatePropagation(),!1;if($(this)[a[n.container].content]().length>=a[n.container].max&&8!==e.which)return e.preventDefault(),e.stopImmediatePropagation(),!1}}),a[n.container].paste||e.on("paste",function(e){e.preventDefault(),e.stopImmediatePropagation()})}(e),!0)},this.unrestrictField=function(e){if(a.hasOwnProperty(e)){var t=$(e);return t.off("textInput keydown"),a[e].paste||t.off("paste"),delete a[e],!0}return!1},this.formToObj=function(e){return p(e)},this.populateForm=function(e,n){var a,t=$(e);function r(e,t){a=$(t).attr("name"),e.hasOwnProperty(a)&&$(t).val(e[a])}t.find("input").each(function(e,t){r(n,t)}),t.find("texarea").each(function(e,t){r(n,t)})},this.validateForm=function(e){var n,a,r,t=$(e),i={},o=!0;return t.find("input").each(function(e,t){n=$(t),t.hasAttribute("required")&&t.hasAttribute("pattern")&&"submit"!==n.attr("type")&&(a=n.attr("pattern"),r=n.val(),a&&((a=new RegExp(a,"g")).test(r)||(i[n.attr("name")]=!1,o=!1)))}),!!o||i}},OGX.FormTools=new OGX.FormTools;<|endoftext|>


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

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

  this.on('end', function() {
    this.installDependencies({
      skipInstall: options['skip-install']
    });
  });

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

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

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

  // have Yeoman greet the user.
  console.log(this.yeoman);

  var prompts = [{
    type: 'input',
    name: 'moduleName',
    message: 'Name of your module?',
    default: 'ngMod'
  }, {
    type: 'input',
    name: 'moduleDescription',
    message: 'Module short description...'
  }, {
    type: 'input',
    name: 'version',
    message: 'Module initial version'
  }, {
    type: 'input',
    name: 'author',
    message: '... And you are?'
  }, {
    type: 'input',
    name: 'email',
    message: '... your email address?'
  }, {
    type: 'input',
    name: 'registry',
    message: '... a private bower registry for your module ...',
    default: 'http://localhost:8888'
  }];

  this.prompt(prompts, function(props) {
    this.moduleName = props.moduleName;
    this.author = props.author;
    this.email = props.email;
    this.moduleDescription = props.moduleDescription;
    this.version = props.version;
    this.registry = props.registry;

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

AngularModuleGenerator.prototype.app = function app() {
  this.mkdir('app');
  this.copy('appjshintrc', '.jshintrc');
  this.mkdir('app/js');
  this.mkdir('app/js/angular');
  this.mkdir('app/js/vendor');
  this.template('_app.js', 'app/js/angular/app.js');

  this.mkdir('test');
  this.copy('testjshintrc', '.jshintrc');
  this.mkdir('test/spec');
  this.mkdir('test/spec/angular');
  this.mkdir('test/spec/angular/services');
  this.mkdir('test/spec/angular/factories');
  this.mkdir('test/spec/angular/filters');
  this.mkdir('test/vendor');
};

AngularModuleGenerator.prototype.projectfiles = function projectfiles() {
  this.copy('mainjshintrc', '.jshintrc');
  this.template('_Gruntfile.js', 'Gruntfile.js');

  this.mkdir('conf');
  this.copy('karma.conf.js', 'conf/karma.conf.js');
  this.copy('karma.e2e.conf.js', 'conf/karma.e2e.conf.js');

  this.copy('gitignore', '.gitignore');
  this.template('_README.md', 'README.md');

  this.template('_package.json', 'package.json');
  this.template('_bower.json', 'bower.json');
  this.template('_bowerrc', '.bowerrc');
};
<commit_msg>fix bug<commit_after>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

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

  this.on('end', function() {
    this.installDependencies({
      skipInstall: options['skip-install']
    });
  });

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

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

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

  // have Yeoman greet the user.
  console.log(this.yeoman);

  var prompts = [{
    type: 'input',
    name: 'moduleName',
    message: 'Name of your module?',
    default: 'ngMod'
  }, {
    type: 'input',
    name: 'moduleDescription',
    message: 'Module short description...'
  }, {
    type: 'input',
    name: 'version',
    message: 'Module initial version'
  }, {
    type: 'input',
    name: 'author',
    message: '... And you are?'
  }, {
    type: 'input',
    name: 'email',
    message: '... your email address?'
  },
  {
    type: 'input',
    name: 'repository',
    message: 'git repo address?'
  },
  {
    type: 'input',
    name: 'registry',
    message: '... a private bower registry for your module ...',
    default: 'http://localhost:8888'
  }];

  this.prompt(prompts, function(props) {
    this.moduleName = props.moduleName;
    this.author = props.author;
    this.email = props.email;
    this.moduleDescription = props.moduleDescription;
    this.version = props.version;
    this.registry = props.registry;
    this.repository = props.repository;
    cb();
  }.bind(this));
};

AngularModuleGenerator.prototype.app = function app() {
  this.mkdir('app');
  this.copy('appjshintrc', '.jshintrc');
  this.mkdir('app/js');
  this.mkdir('app/js/angular');
  this.mkdir('app/js/vendor');
  this.template('_app.js', 'app/js/angular/app.js');

  this.mkdir('test');
  this.copy('testjshintrc', '.jshintrc');
  this.mkdir('test/spec');
  this.mkdir('test/spec/angular');
  this.mkdir('test/spec/angular/services');
  this.mkdir('test/spec/angular/factories');
  this.mkdir('test/spec/angular/filters');
  this.mkdir('test/vendor');
};

AngularModuleGenerator.prototype.projectfiles = function projectfiles() {
  this.copy('mainjshintrc', '.jshintrc');
  this.template('_Gruntfile.js', 'Gruntfile.js');

  this.mkdir('conf');
  this.copy('karma.conf.js', 'conf/karma.conf.js');
  this.copy('karma.e2e.conf.js', 'conf/karma.e2e.conf.js');

  this.copy('gitignore', '.gitignore');
  this.template('_README.md', 'README.md');

  this.template('_package.json', 'package.json');
  this.template('_bower.json', 'bower.json');
  this.template('_bowerrc', '.bowerrc');
};
<|endoftext|>