<commit_before>import Ember from 'ember';

export default Ember.Component.extend({
    classNames: 'graph-data',

    didInsertElement() {
        this._super(...arguments);

        Ember.$(window).on('resize.chart', () => this.rerender());
        Ember.$(document).on('googleChartsLoaded', () => this.rerender());
    },

    willDestroyElement() {
        Ember.$(window).off('resize.chart');
        Ember.$(document).off('googleChartsLoaded');
    },

    didRender() {
        this._super(...arguments);

        let data = this.get('data');

        let subarray_length = (data[1] || []).length;

        // Start at 1 to skip the date element in the 0th
        // location in the array.
        for (let k = 1; k < subarray_length; k++) {
            let on = false;

            // Start at 1 because the 0th entry in the array
            // is an array of version numbers.
            //
            // End before the last element is reached because we never
            // want to change the last element.
            for (let i = 1; i < data.length - 1; i++) {
                // k + 1 because the first entry in the array is the date
                let value = data[i][k];

                // If we are "off" and are looking at a zero
                // replace the data at this point with `null`.
                //
                // Null tells google.visualization to stop drawing
                // the line altogether.
                if (!on && value === 0) {
                    data[i][k] = null;
                }

                // If we are off and the value is not zero, we
                // need to turn back on.  (keep the value the same though)
                else if (!on && value !== 0) {
                    on = true;

                    // We previously wrote a null into data[i - 1][k + 1],
                    // so to make the graph look pretty, we'll switch it back
                    // to the zero that it was before.
                    if (i >= 2) {
                        data[i - 1][k] = 0;
                    }
                }
                // If we are on and the value is zero, turn off
                // but keep the zero in the array
                else if (on && value === 0) {
                    on = false;
                }
            }
        }

        if (!data || !window.google || !window.googleChartsLoaded) {
            this.$().hide();
            return;
        } else {
            this.$().show();
        }

        var myData = window.google.visualization.arrayToDataTable(data);

        var fmt = new window.google.visualization.DateFormat({
            pattern: 'LLL d, yyyy',
        });
        fmt.format(myData, 0);

        // use a DataView to calculate an x-day moving average
        var days = 7;
        var view = new window.google.visualization.DataView(myData);
        var moving_avg_func_for_col = function(col) {
            return function(dt, row) {
                // For the last rows (the *first* days, remember, the dataset is
                // backwards), we cannot calculate the avg. of previous days.
                if (row >= dt.getNumberOfRows() - days) {
                    return null;
                }

                var total = 0;
                for (var i = days; i > 0; i--) {
                    total += dt.getValue(row + i, col);
                }
                var avg = total / days;
                return {
                    v: avg,
                    f: avg.toFixed(2)
                };
            };
        };

        var columns = [0]; // 0 = datetime
        var seriesOption = {};
        // Colors by http://colorbrewer2.org/#type=diverging&scheme=RdBu&n=10
        var colors = ['#67001f', '#b2182b', '#d6604d', '#f4a582', '#92c5de',
                      '#4393c3', '#2166ac', '#053061'];
        var [headers, ] = data;
        // Walk over the headers/colums in reverse order, as the newest version
        // is at the end, but in the UI we want it at the top of the chart legend.

        window._.range(headers.length - 1, 0, -1).forEach((dataCol, i) => {
            columns.push(dataCol); // add the column itself
            columns.push({ // add a 'calculated' column, the moving average
                type: 'number',
                label: `${headers[dataCol]} ${days}-day avg.`,
                calc: moving_avg_func_for_col(dataCol)
            });
            // Note: while the columns start with index 1 (because 0 is the time
            // axis), the series configuration starts with index 0.
            seriesOption[i * 2] = {
                type: 'scatter',
                color: colors[i % colors.length],
                pointSize: 3,
                pointShape: 'square'
            };
            seriesOption[i * 2 + 1] = {
                type: 'line',
                color: colors[i % colors.length],
                lineWidth: 2,
                curveType: 'function',
                visibleInLegend: false
            };
        });
        view.setColumns(columns);

        var chart = new window.google.visualization.ComboChart(this.get('element'));
        chart.draw(view, {
            chartArea: { 'left': 85, 'width': '77%', 'height': '80%' },
            hAxis: {
                minorGridlines: { count: 8 },
            },
            vAxis: {
                minorGridlines: { count: 5 },
                viewWindow: { min: 0, },
            },
            isStacked: false,
            focusTarget: 'category',
            seriesType: 'scatter',
            series: seriesOption
        });
    },
});
<commit_msg>Import from lodash; window._ seems gone since the ember upgrade?<commit_after>import Ember from 'ember';
import _ from 'lodash';

export default Ember.Component.extend({
    classNames: 'graph-data',

    didInsertElement() {
        this._super(...arguments);

        Ember.$(window).on('resize.chart', () => this.rerender());
        Ember.$(document).on('googleChartsLoaded', () => this.rerender());
    },

    willDestroyElement() {
        Ember.$(window).off('resize.chart');
        Ember.$(document).off('googleChartsLoaded');
    },

    didRender() {
        this._super(...arguments);

        let data = this.get('data');

        let subarray_length = (data[1] || []).length;

        // Start at 1 to skip the date element in the 0th
        // location in the array.
        for (let k = 1; k < subarray_length; k++) {
            let on = false;

            // Start at 1 because the 0th entry in the array
            // is an array of version numbers.
            //
            // End before the last element is reached because we never
            // want to change the last element.
            for (let i = 1; i < data.length - 1; i++) {
                // k + 1 because the first entry in the array is the date
                let value = data[i][k];

                // If we are "off" and are looking at a zero
                // replace the data at this point with `null`.
                //
                // Null tells google.visualization to stop drawing
                // the line altogether.
                if (!on && value === 0) {
                    data[i][k] = null;
                }

                // If we are off and the value is not zero, we
                // need to turn back on.  (keep the value the same though)
                else if (!on && value !== 0) {
                    on = true;

                    // We previously wrote a null into data[i - 1][k + 1],
                    // so to make the graph look pretty, we'll switch it back
                    // to the zero that it was before.
                    if (i >= 2) {
                        data[i - 1][k] = 0;
                    }
                }
                // If we are on and the value is zero, turn off
                // but keep the zero in the array
                else if (on && value === 0) {
                    on = false;
                }
            }
        }

        if (!data || !window.google || !window.googleChartsLoaded) {
            this.$().hide();
            return;
        } else {
            this.$().show();
        }

        var myData = window.google.visualization.arrayToDataTable(data);

        var fmt = new window.google.visualization.DateFormat({
            pattern: 'LLL d, yyyy',
        });
        fmt.format(myData, 0);

        // use a DataView to calculate an x-day moving average
        var days = 7;
        var view = new window.google.visualization.DataView(myData);
        var moving_avg_func_for_col = function(col) {
            return function(dt, row) {
                // For the last rows (the *first* days, remember, the dataset is
                // backwards), we cannot calculate the avg. of previous days.
                if (row >= dt.getNumberOfRows() - days) {
                    return null;
                }

                var total = 0;
                for (var i = days; i > 0; i--) {
                    total += dt.getValue(row + i, col);
                }
                var avg = total / days;
                return {
                    v: avg,
                    f: avg.toFixed(2)
                };
            };
        };

        var columns = [0]; // 0 = datetime
        var seriesOption = {};
        // Colors by http://colorbrewer2.org/#type=diverging&scheme=RdBu&n=10
        var colors = ['#67001f', '#b2182b', '#d6604d', '#f4a582', '#92c5de',
                      '#4393c3', '#2166ac', '#053061'];
        var [headers, ] = data;
        // Walk over the headers/colums in reverse order, as the newest version
        // is at the end, but in the UI we want it at the top of the chart legend.

        _.range(headers.length - 1, 0, -1).forEach((dataCol, i) => {
            columns.push(dataCol); // add the column itself
            columns.push({ // add a 'calculated' column, the moving average
                type: 'number',
                label: `${headers[dataCol]} ${days}-day avg.`,
                calc: moving_avg_func_for_col(dataCol)
            });
            // Note: while the columns start with index 1 (because 0 is the time
            // axis), the series configuration starts with index 0.
            seriesOption[i * 2] = {
                type: 'scatter',
                color: colors[i % colors.length],
                pointSize: 3,
                pointShape: 'square'
            };
            seriesOption[i * 2 + 1] = {
                type: 'line',
                color: colors[i % colors.length],
                lineWidth: 2,
                curveType: 'function',
                visibleInLegend: false
            };
        });
        view.setColumns(columns);

        var chart = new window.google.visualization.ComboChart(this.get('element'));
        chart.draw(view, {
            chartArea: { 'left': 85, 'width': '77%', 'height': '80%' },
            hAxis: {
                minorGridlines: { count: 8 },
            },
            vAxis: {
                minorGridlines: { count: 5 },
                viewWindow: { min: 0, },
            },
            isStacked: false,
            focusTarget: 'category',
            seriesType: 'scatter',
            series: seriesOption
        });
    },
});
<|endoftext|>


<commit_before>
"use strict";

var React = require('react');
var Grid = require('react-bootstrap').Grid;
var Col = require('react-bootstrap').Col;
var Row = require('react-bootstrap').Row;
var Modal = require('react-bootstrap').Modal;
var Input = require('react-bootstrap').Input;
var Button = require('react-bootstrap').Button;
//var FormControls = require('react-bootstrap').FormControls;
// var ButtonGroup = require('react-bootstrap').ButtonGroup;
// var FormControls = require('react-bootstrap').FormControls;
var LinkedStateMixin = require('react-addons-linked-state-mixin');

var Switch = require('react-bootstrap-switch');

var dialog = require('electron').remote.dialog;

var Blink1SerialOption = require('./blink1SerialOption');
var Blink1Service = require('../../server/blink1Service'); // FIXME: shouldn't need this dep

var ScriptForm = React.createClass({
    mixins: [LinkedStateMixin],
    propTypes: {
		rule: React.PropTypes.object.isRequired,
        allowMultiBlink1: React.PropTypes.bool,
        patterns: React.PropTypes.array,
        onSave: React.PropTypes.func,
        onCancel: React.PropTypes.func,
        onDelete: React.PropTypes.func,
        onCopy: React.PropTypes.func
	},
    getInitialState: function() {
        return {};
    },
    // FIXME: why am I doing this instead of getInitialState?
    componentWillReceiveProps: function(nextProps) {
        var rule = nextProps.rule;
		this.setState({
            type: rule.type || 'script',
            enabled: rule.enabled,
            name: rule.name,
            initialName: rule.name,
            actionType: rule.actionType || 'parse-color',
            actOnNew: rule.actOnNew,
            // patternId: rule.patternId,
            blink1Id: rule.blink1Id || 0,
            path: rule.path,
            intervalSecs: rule.intervalSecs || 10
         });
	},
    handleClose: function() {
        if( !this.state.path ) {
            this.setState({errormsg: 'Must choose a path'});
            return;
        }
        this.props.onSave(this.state);
    },
    openFileDialog: function() {
        var self = this;
        dialog.showOpenDialog(function (filenames) {
            if (filenames === undefined) { return; }
            var filename = filenames[0];
            self.setState({path: filename});
        });
    },
    handleActionType: function(e) {
        var actionType = e.target.value;
        this.setState({actionType:actionType});
    },
    handleBlink1SerialChange: function(blink1Id) {
        // console.log("handleBlink1SerialChange: ",e);//,blink1Id);
        this.setState({blink1Id: blink1Id});
    },
    render: function() {
        var self = this;
        var type = this.state.type;

        var title = "Script";
        var pathlabel = "Script Path";
        var pathplaceholder = "Click to choose script";
        if( type === 'file' ) {
            title = "File";
            pathlabel = "File Path";
            pathplaceholder = "Click to choose file path";
        }
        else if( type === 'url' ) {
            title = "URL";
            pathlabel = "URL";
            pathplaceholder = "Enter URL";
        }

        return (

                <Modal show={this.props.show} onHide={this.handleClose} >
                    <Modal.Header>
                        <Modal.Title>{title} Settings</Modal.Title>
                    </Modal.Header>
                    <Modal.Body>

{this.state.errormsg}

                        <form className="form-horizontal" >
                            <Input labelClassName="col-xs-3" wrapperClassName="col-xs-8"
                                type="text" label="Rule Name" placeholder="Descriptive name"
                                valueLink={this.linkState('name')} />
                            <Input labelClassName="col-xs-3" wrapperClassName="col-xs-8"
                                type="text" label={pathlabel} placeholder={pathplaceholder}
                                valueLink={this.linkState('path')}
                                onClick={type!=='url' ? this.openFileDialog : null}/>
                            <Input labelClassName="col-xs-3" wrapperClassName="col-xs-5"
                                type="select" label="Check interval" placeholder="15 seconds"
                                valueLink={this.linkState('intervalSecs')} >
                                <option value="2">2 seconds</option>
                                <option value="5">5 seconds</option>
                                <option value="10">10 seconds</option>
                                <option value="15">15 seconds</option>
                                <option value="30">30 seconds</option>
                                <option value="60">1 minute</option>
                                <option value="360">5 minutes</option>
                            </Input>
                            <Grid >
                                <Row><Col xs={2}>
                                     Parse output as
                                </Col><Col xs={4} style={{border:'0px solid green'}}>
                                    <Input title="here is an title tag as a tool-tip, does it work? I wonder. How long can it be? Not so long as to be useful I bet"
                                        type="radio" label="Parse output as JSON" value="parse-json"
                                        checked={this.state.actionType==='parse-json'}
                                        onChange={this.handleActionType} />
                                    <Input
                                        type="radio" label="Parse output as pattern name" value="parse-pattern"
                                        checked={this.state.actionType==='parse-pattern'}
                                        onChange={this.handleActionType} />
                                    <Input
                                        type="radio" label="Parse output as color" value="parse-color"
                                        checked={this.state.actionType==='parse-color'}
                                        onChange={this.handleActionType} />
                                </Col></Row>
                                <Row><Col xs={4} xsOffset={2}>
                                    <Input bsSize="small" type="checkbox" label="Trigger on new values only"
                                        checkedLink={this.linkState('actOnNew')} />
                                </Col></Row>
                            </Grid>

                            {!this.props.allowMultiBlink1 ? null :
                                <Blink1SerialOption label="blink(1) to use" defaultText="-use default-"
                                    labelClassName="col-xs-3" wrapperClassName="col-xs-3"
                                    serial={this.state.blink1Id} onChange={this.handleBlink1SerialChange}/>}

                        </form>
                    </Modal.Body>
                    <Modal.Footer>
                        <Row>
                            <Col xs={5}>
                                <Button bsSize="small" bsStyle="danger" onClick={this.props.onDelete} style={{float:'left'}}>Delete</Button>
                                <Button bsSize="small" onClick={this.props.onCopy} style={{float:'left'}}>Copy</Button>
                            </Col>
                            <Col xs={3}>
                                    <Switch size="small" labelText="Enable"
                                        state={this.state.enabled} onChange={function(s){self.setState({enabled:s});}} />
                            </Col>
                            <Col xs={4}>
                                <Button bsSize="small" onClick={this.props.onCancel}>Cancel</Button>
                                <Button bsSize="small" onClick={this.handleClose}>OK</Button>
                            </Col>
                        </Row>
                    </Modal.Footer>
              </Modal>

        );
    }
});

module.exports = ScriptForm;
<commit_msg>fix warning in Blink1SerialOption when passing 0 blink1Id<commit_after>
"use strict";

var React = require('react');
var Grid = require('react-bootstrap').Grid;
var Col = require('react-bootstrap').Col;
var Row = require('react-bootstrap').Row;
var Modal = require('react-bootstrap').Modal;
var Input = require('react-bootstrap').Input;
var Button = require('react-bootstrap').Button;
//var FormControls = require('react-bootstrap').FormControls;
// var ButtonGroup = require('react-bootstrap').ButtonGroup;
// var FormControls = require('react-bootstrap').FormControls;
var LinkedStateMixin = require('react-addons-linked-state-mixin');

var Switch = require('react-bootstrap-switch');

var dialog = require('electron').remote.dialog;

var Blink1SerialOption = require('./blink1SerialOption');
var Blink1Service = require('../../server/blink1Service'); // FIXME: shouldn't need this dep

var ScriptForm = React.createClass({
    mixins: [LinkedStateMixin],
    propTypes: {
		rule: React.PropTypes.object.isRequired,
        allowMultiBlink1: React.PropTypes.bool,
        patterns: React.PropTypes.array,
        onSave: React.PropTypes.func,
        onCancel: React.PropTypes.func,
        onDelete: React.PropTypes.func,
        onCopy: React.PropTypes.func
	},
    getInitialState: function() {
        return {};
    },
    // FIXME: why am I doing this instead of getInitialState?
    componentWillReceiveProps: function(nextProps) {
        var rule = nextProps.rule;
		this.setState({
            type: rule.type || 'script',
            enabled: rule.enabled,
            name: rule.name,
            initialName: rule.name,
            actionType: rule.actionType || 'parse-color',
            actOnNew: rule.actOnNew,
            // patternId: rule.patternId,
            blink1Id: rule.blink1Id || "0",
            path: rule.path,
            intervalSecs: rule.intervalSecs || 10
         });
	},
    handleClose: function() {
        if( !this.state.path ) {
            this.setState({errormsg: 'Must choose a path'});
            return;
        }
        this.props.onSave(this.state);
    },
    openFileDialog: function() {
        var self = this;
        dialog.showOpenDialog(function (filenames) {
            if (filenames === undefined) { return; }
            var filename = filenames[0];
            self.setState({path: filename});
        });
    },
    handleActionType: function(e) {
        var actionType = e.target.value;
        this.setState({actionType:actionType});
    },
    handleBlink1SerialChange: function(blink1Id) {
        // console.log("handleBlink1SerialChange: ",e);//,blink1Id);
        this.setState({blink1Id: blink1Id});
    },
    render: function() {
        var self = this;
        var type = this.state.type;

        var title = "Script";
        var pathlabel = "Script Path";
        var pathplaceholder = "Click to choose script";
        if( type === 'file' ) {
            title = "File";
            pathlabel = "File Path";
            pathplaceholder = "Click to choose file path";
        }
        else if( type === 'url' ) {
            title = "URL";
            pathlabel = "URL";
            pathplaceholder = "Enter URL";
        }

        return (

                <Modal show={this.props.show} onHide={this.handleClose} >
                    <Modal.Header>
                        <Modal.Title>{title} Settings</Modal.Title>
                    </Modal.Header>
                    <Modal.Body>

{this.state.errormsg}

                        <form className="form-horizontal" >
                            <Input labelClassName="col-xs-3" wrapperClassName="col-xs-8"
                                type="text" label="Rule Name" placeholder="Descriptive name"
                                valueLink={this.linkState('name')} />
                            <Input labelClassName="col-xs-3" wrapperClassName="col-xs-8"
                                type="text" label={pathlabel} placeholder={pathplaceholder}
                                valueLink={this.linkState('path')}
                                onClick={type!=='url' ? this.openFileDialog : null}/>
                            <Input labelClassName="col-xs-3" wrapperClassName="col-xs-5"
                                type="select" label="Check interval" placeholder="15 seconds"
                                valueLink={this.linkState('intervalSecs')} >
                                <option value="2">2 seconds</option>
                                <option value="5">5 seconds</option>
                                <option value="10">10 seconds</option>
                                <option value="15">15 seconds</option>
                                <option value="30">30 seconds</option>
                                <option value="60">1 minute</option>
                                <option value="360">5 minutes</option>
                            </Input>
                            <Grid >
                                <Row><Col xs={2}>
                                     Parse output as
                                </Col><Col xs={4} style={{border:'0px solid green'}}>
                                    <Input title="here is an title tag as a tool-tip, does it work? I wonder. How long can it be? Not so long as to be useful I bet"
                                        type="radio" label="Parse output as JSON" value="parse-json"
                                        checked={this.state.actionType==='parse-json'}
                                        onChange={this.handleActionType} />
                                    <Input
                                        type="radio" label="Parse output as pattern name" value="parse-pattern"
                                        checked={this.state.actionType==='parse-pattern'}
                                        onChange={this.handleActionType} />
                                    <Input
                                        type="radio" label="Parse output as color" value="parse-color"
                                        checked={this.state.actionType==='parse-color'}
                                        onChange={this.handleActionType} />
                                </Col></Row>
                                <Row><Col xs={4} xsOffset={2}>
                                    <Input bsSize="small" type="checkbox" label="Trigger on new values only"
                                        checkedLink={this.linkState('actOnNew')} />
                                </Col></Row>
                            </Grid>

                            {!this.props.allowMultiBlink1 ? null :
                                <Blink1SerialOption label="blink(1) to use" defaultText="-use default-"
                                    labelClassName="col-xs-3" wrapperClassName="col-xs-3"
                                    serial={this.state.blink1Id} onChange={this.handleBlink1SerialChange}/>}

                        </form>
                    </Modal.Body>
                    <Modal.Footer>
                        <Row>
                            <Col xs={5}>
                                <Button bsSize="small" bsStyle="danger" onClick={this.props.onDelete} style={{float:'left'}}>Delete</Button>
                                <Button bsSize="small" onClick={this.props.onCopy} style={{float:'left'}}>Copy</Button>
                            </Col>
                            <Col xs={3}>
                                    <Switch size="small" labelText="Enable"
                                        state={this.state.enabled} onChange={function(s){self.setState({enabled:s});}} />
                            </Col>
                            <Col xs={4}>
                                <Button bsSize="small" onClick={this.props.onCancel}>Cancel</Button>
                                <Button bsSize="small" onClick={this.handleClose}>OK</Button>
                            </Col>
                        </Row>
                    </Modal.Footer>
              </Modal>

        );
    }
});

module.exports = ScriptForm;
<|endoftext|>


<commit_before>var modelLength = 9;
var model = new Array(9);
function initBoard() {
    var i = 0;
    var j = 0;
    for (i = 0; i < modelLength; i++) {
        model[i] = new Array(9);
        for (j = 0; j < modelLength; j++) {
            model[i][j] = 0;
        }
    }
    // Create the initial board
    model[0][0] = 9;
    model[0][3] = 2;
    model[0][6] = 7;
    model[0][7] = 5;
    model[1][0] = 6;
    model[1][4] = 5;
    model[1][7] = 4;
    model[2][1] = 2;
    model[2][3] = 4;
    //model[2][7] = 1 ;
    model[2][6] = 3;
    //model[3][0] = 2 ;
    model[3][2] = 8;
    //model[4][1] = 7 ;
    model[4][3] = 5;
    model[4][5] = 9;
    model[4][7] = 6;
    model[5][6] = 4;
    model[5][8] = 1;
    model[6][1] = 1;
    model[6][5] = 5;
    model[6][7] = 8;
    model[7][1] = 9;
    model[7][4] = 7;
    model[7][8] = 4;
    model[8][1] = 8;
    model[8][2] = 2;
    model[8][4] = 4;
    //model[8][8] = 6 ;
}
function main() {
    solve(0, 0);
}
function solve(row, col) {
    if (row > 8) {
        // finished computing the board
    }
    if (model[row][col] != 0)
        nextElem(row, col);
    else {
        for (var i = 1; i <= 9; i++) {
            if (checkRow(row, i) && checkCol(col, i) && checkBox(row, col, i)) {
                model[row][col] = i;
                nextElem(row, col);
            }
        }
        model[row][col] = 0;
    }
}
function nextElem(row, col) {
    if (col < 8) {
        // can go to next element in column
        solve(row, col + 1);
    }
    else {
        // reached the end of the row. Move on to the next row
        solve(row + 1, 0);
    }
}
// return int instead of boolean to work with AssemblyScript
// checks if the element is present in the row
function checkRow(row, value) {
    for (var i = 0; i < modelLength; i++) {
        if (value == model[row][i])
            return 0;
    }
    return 1;
}
// checks if the element is present in the column
function checkCol(col, value) {
    for (var i = 0; i < modelLength; i++) {
        if (value == model[i][col])
            return 0;
    }
    return 1;
}
// checks if the element is present in the box
function checkBox(row, col, value) {
    // Need to floor to get integer value
    row = ((row / 3) | 0) * 3;
    col = ((row / 3) | 0) * 3;
    for (var i = 0; i < 3; i++) {
        for (var j = 0; j < 3; j++) {
            if (model[row + i][col + j] == value)
                return 0;
        }
    }
    return 1;
}
<commit_msg>small correction to Daniel's solution<commit_after>var modelLength = 9;
var model = new Array(9);
function initBoard() {
    var i = 0;
    var j = 0;
    for (i = 0; i < modelLength; i++) {
        model[i] = new Array(9);
        for (j = 0; j < modelLength; j++) {
            model[i][j] = 0;
        }
    }
    // Create the initial board
    model[0][0] = 9;
    model[0][3] = 2;
    model[0][6] = 7;
    model[0][7] = 5;
    model[1][0] = 6;
    model[1][4] = 5;
    model[1][7] = 4;
    model[2][1] = 2;
    model[2][3] = 4;
    //model[2][7] = 1 ;
    model[2][6] = 3;
    //model[3][0] = 2 ;
    model[3][2] = 8;
    //model[4][1] = 7 ;
    model[4][3] = 5;
    model[4][5] = 9;
    model[4][7] = 6;
    model[5][6] = 4;
    model[5][8] = 1;
    model[6][1] = 1;
    model[6][5] = 5;
    model[6][7] = 8;
    model[7][1] = 9;
    model[7][4] = 7;
    model[7][8] = 4;
    model[8][1] = 8;
    model[8][2] = 2;
    model[8][4] = 4;
    //model[8][8] = 6 ;
}
function main() {
    solve(0, 0);
}
function solve(row, col) {
    if (row > 8) {
        // finished computing the board
    }
    if (model[row][col] != 0)
        nextElem(row, col);
    else {
        for (var i = 1; i <= 9; i++) {
            if (checkRow(row, i) && checkCol(col, i) && checkBox(row, col, i)) {
                model[row][col] = i;
                nextElem(row, col);
            }
        }
        model[row][col] = 0;
    }
}
function nextElem(row, col) {
    if (col < 8) {
        // can go to next element in column
        solve(row, col + 1);
    }
    else {
        // reached the end of the row. Move on to the next row
        solve(row + 1, 0);
    }
}
// return int instead of boolean to work with AssemblyScript
// checks if the element is present in the row
function checkRow(row, value) {
    for (var i = 0; i < modelLength; i++) {
        if (value == model[row][i])
            return 0;
    }
    return 1;
}
// checks if the element is present in the column
function checkCol(col, value) {
    for (var i = 0; i < modelLength; i++) {
        if (value == model[i][col])
            return 0;
    }
    return 1;
}
// checks if the element is present in the box
function checkBox(row, col, value) {
    // Need to floor to get integer value
    row = ((row / 3) | 0) * 3;
    col = ((col / 3) | 0) * 3;
    for (var i = 0; i < 3; i++) {
        for (var j = 0; j < 3; j++) {
            if (model[row + i][col + j] == value)
                return 0;
        }
    }
    return 1;
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';

import { ipcRenderer } from 'electron';
import { Link, browserHistory } from 'react-router';
import bytes from 'bytes'

import config from '../../config'

import section from '../cssModules/section.scss'
import content from '../cssModules/content.scss'

// hax for the moment
let folder = require('path').resolve(require('os').tmpdir(), 'aergia')
try {
  require('fs').mkdirSync(folder)
} catch (e) {}

let selectSD = React.createClass({
  getInitialState() {
    return {
      drives: []
    }
  },
  componentDidMount() {
    ipcRenderer.on('driveListReply', (event, drives) => {
      drives = JSON.parse(drives)
      drives = drives.filter(function (drive) {
        return drive.system === false && drive.protected === false && drive.mountpoints.length
      }).map(function (drive) {
        return {
          description: drive.description,
          mountPoint: drive.mountpoints.length ? drive.mountpoints[0].path : 'Not mounted',
          size: bytes(drive.size)
        }
      })
      this.setState({
        drives
      })
    })
    this.processDrives()
  },
  processDrives () {
    ipcRenderer.send('driveList')
  },
  getDrives () {
    return this.state.drives.map(drive => {
      return
{drive.description} @ {drive.mountPoint} ({drive.size})

    })
  },
  setDrive (drive) {
    return () => {
      config.drive = drive
      this.props.router.push(this.props.location.query.returnTo)
    }
  },
  render() {
    return (

          {this.getDrives().length > 0 ? (

Select which SD card you wish to use:

              {this.getDrives()}

          ) : (

              Oops, can't detect any valid drives.

          )}

Refresh

use {folder}

Back

    )
  }
})

export default selectSD
<commit_msg>refactor drive select<commit_after>import React, { Component } from 'react';

import { ipcRenderer } from 'electron';
import { Link, browserHistory } from 'react-router';
import { ScaleLoader } from 'halogen'

import bytes from 'bytes'

import config from '../../config'

import section from '../cssModules/section.scss'
import content from '../cssModules/content.scss'

// hax for the moment
let folder = require('path').resolve(require('os').tmpdir(), 'aergia')
try {
  require('fs').mkdirSync(folder)
} catch (e) {}

let selectSD = React.createClass({
  getInitialState() {
    return {
      drives: [],
      loaded: false
    }
  },
  componentDidMount() {
    ipcRenderer.on('driveListReply', (event, drives) => {
      drives = JSON.parse(drives)
      drives = drives.filter(function (drive) {
        return drive.system === false && drive.protected === false && drive.mountpoints.length
      }).map(function (drive) {
        return {
          description: drive.description,
          mountPoint: drive.mountpoints.length ? drive.mountpoints[0].path : 'Not mounted',
          size: bytes(drive.size)
        }
      })
      this.setState({
        ...this.state,
        loaded: true,
        drives
      })
    })
    this.processDrives()
  },
  processDrives () {
    ipcRenderer.send('driveList')
  },
  getDrives () {
    return this.state.drives.map(drive => {
      return
{drive.description} @ {drive.mountPoint} ({drive.size})

    })
  },
  setDrive (drive) {
    return () => {
      config.drive = drive
      this.props.router.push(this.props.location.query.returnTo)
    }
  },
  getContent () {
    let drives = this.getDrives()

    if (drives.length) {
      return

Select which SD card you wish to use:

          {drives}

Refresh

    } else {
      if (this.state.loaded) {
        return

          Oops, can't detect any valid drives.

Refresh

      } else {
        return

          <ScaleLoader color="#000000" width="20px" height="120px" />
          Loading drives...

      }
    }
  },
  render() {
    return (

          {this.getContent()}

hacks: use {folder}

Back

    )
  }
})

export default selectSD
<|endoftext|>


<commit_before>var datatables_checkbox_columns_initialized = false;

$(function() {
    function header_has_been_clicked() {
        if (($('input[name="' +  $(this).attr('name')+ '_hidden"]').val() == 'None') || ($('input[name="' +  $(this).attr('name')+ '_hidden"]').val() == 'Some')) {
            $('input[name="' +  $(this).attr('name')+ '_hidden"]').val('All');
            $(this).addClass('all_selected').removeClass('none_selected').removeClass('some_selected');
            var checked = 'checked';
        } else if ($('input[name="' +  $(this).attr('name')+ '_hidden"]').val() == 'All') {
            $('input[name="' +  $(this).attr('name')+ '_hidden"]').val('None');
            $(this).addClass('none_selected').removeClass('all_selected').removeClass('some_selected');
            var checked = false;
        }
        checkboxes = $('div.dataTables_wrapper').find('input.datatables_checkbox_column[name="location"]');
        checkboxes.each(function(index) {
            if (checked == 'checked') {
                $(this).siblings('a').addClass('checked');
            } else {
                $(this).siblings('a').removeClass('checked');
            }
            if ($(this).prop('checked') != checked) {
                $(this).prop('checked', checked);
            }
        });
        $('input.datatables_checkbox_column')[0].click();
        $('input.datatables_checkbox_column')[0].click();
    }

    function checkbox_has_been_clicked() {
        var checked = $(this).siblings('input').prop('checked');
        if (checked == false) {
            $(this).addClass('checked');
            checked = 'checked';
        } else {
            $(this).removeClass('checked');
            checked = false;
        }
        $(this).siblings('input:first').prop('checked', checked);
        $(this).siblings('input').click();
        $(this).siblings('input:first').prop('checked', checked);
        if (checked == 'checked') {
            checked = true;
        }
        var unanimous = true;
        checkboxes = $('div.dataTables_wrapper').find('input.datatables_checkbox_column[name="location"]');
        checkboxes.each(function(index) {
            if ($(this).prop('checked') != checked) {
                unanimous = false;
            }
        });
        if (unanimous == true) {
            if (checked == true) {
                $('a[name="' + $(this).siblings('input:first').attr('name') + '"]').addClass('all_selected').removeClass('none_selected').removeClass('some_selected');
                $('input[name="' +  $(this).siblings('input:first').attr('name')+ '_hidden"]').val('All');
            } else {
                $('a[name="' + $(this).siblings('input:first').attr('name') + '"]').addClass('none_selected').removeClass('all_selected').removeClass('some_selected');
                $('input[name="' +  $(this).siblings('input:first').attr('name')+ '_hidden"]').val('None');
            }
        } else {
            $('a[name="' + $(this).siblings('input:first').attr('name') + '"]').addClass('some_selected').removeClass('none_selected').removeClass('all_selected');
            $('input[name="' +  $(this).siblings('input:first').attr('name')+ '_hidden"]').val('Some');
        }
    }

    if (!datatables_checkbox_columns_initialized) {
        $('a.django_datatables_tristate_checkbox').live('click', header_has_been_clicked);
        $('a.django_datatables_bistate_checkbox').live('click', checkbox_has_been_clicked);
        datatables_checkbox_columns_initialized = true;
      }
});<commit_msg>Updated checkbox column to be agnostic to the field name<commit_after>var datatables_checkbox_columns_initialized = false;

$(function() {
    function header_has_been_clicked() {
        if (($('input[name="' +  $(this).attr('name')+ '_hidden"]').val() == 'None') || ($('input[name="' +  $(this).attr('name')+ '_hidden"]').val() == 'Some')) {
            $('input[name="' +  $(this).attr('name')+ '_hidden"]').val('All');
            $(this).addClass('all_selected').removeClass('none_selected').removeClass('some_selected');
            var checked = 'checked';
        } else if ($('input[name="' +  $(this).attr('name')+ '_hidden"]').val() == 'All') {
            $('input[name="' +  $(this).attr('name')+ '_hidden"]').val('None');
            $(this).addClass('none_selected').removeClass('all_selected').removeClass('some_selected');
            var checked = false;
        }
        checkboxes = $('div.dataTables_wrapper').find('input.datatables_checkbox_column[name="' +  $(this).attr('name') + '"]');
        checkboxes.each(function(index) {
            if (checked == 'checked') {
                $(this).siblings('a').addClass('checked');
            } else {
                $(this).siblings('a').removeClass('checked');
            }
            if ($(this).prop('checked') != checked) {
                $(this).prop('checked', checked);
            }
        });
        $('input.datatables_checkbox_column')[0].click();
        $('input.datatables_checkbox_column')[0].click();
    }

    function checkbox_has_been_clicked() {
        var checked = $(this).siblings('input').prop('checked');
        if (checked == false) {
            $(this).addClass('checked');
            checked = 'checked';
        } else {
            $(this).removeClass('checked');
            checked = false;
        }
        $(this).siblings('input:first').prop('checked', checked);
        $(this).siblings('input').click();
        $(this).siblings('input:first').prop('checked', checked);
        if (checked == 'checked') {
            checked = true;
        }
        var unanimous = true;
        checkboxes = $('div.dataTables_wrapper').find('input.datatables_checkbox_column[name="' +  $(this).siblings('input:first').attr('name') + '"]');
        checkboxes.each(function(index) {
            if ($(this).prop('checked') != checked) {
                unanimous = false;
            }
        });
        if (unanimous == true) {
            if (checked == true) {
                $('a[name="' + $(this).siblings('input:first').attr('name') + '"]').addClass('all_selected').removeClass('none_selected').removeClass('some_selected');
                $('input[name="' +  $(this).siblings('input:first').attr('name')+ '_hidden"]').val('All');
            } else {
                $('a[name="' + $(this).siblings('input:first').attr('name') + '"]').addClass('none_selected').removeClass('all_selected').removeClass('some_selected');
                $('input[name="' +  $(this).siblings('input:first').attr('name')+ '_hidden"]').val('None');
            }
        } else {
            $('a[name="' + $(this).siblings('input:first').attr('name') + '"]').addClass('some_selected').removeClass('none_selected').removeClass('all_selected');
            $('input[name="' +  $(this).siblings('input:first').attr('name')+ '_hidden"]').val('Some');
        }
    }

    if (!datatables_checkbox_columns_initialized) {
        $('a.django_datatables_tristate_checkbox').live('click', header_has_been_clicked);
        $('a.django_datatables_bistate_checkbox').live('click', checkbox_has_been_clicked);
        datatables_checkbox_columns_initialized = true;
      }
});<|endoftext|>


<commit_before>/**
Version modificada de rainbow.js para poner otros colores, creditos a el/los creadores de rainbow.js
 */

 exports.commands = {

	pinkhelp: 'raincolors',
        pinkiehelp: 'raincolors',
        rainhelp: 'raincolors',
        rainbowhelp: 'raincolors',
        colors: 'raincolors',
        	raincolors: function () {
		if (!this.canBroadcast()) return false;
		this.sendReplyBox(
			"<big>Rain Colors</big>

" +
			"/pinkie, /pink o /p (mensaje) para cambiar el color de tu usuario a rosa en un mensaje
" +
			"/rainbow, /rain o /r (mensaje) para cambiar el color de tu usuario a arcoiris en un mensaje
" +
			"Creditos a CelestiaPrincess por reinventar el plugin
"
		);
	},

  r: 'rainbow',
  rain: 'rainbow',
  rainbow: function(target, room, user){
          if (user.can('broadcast', null, room)) {
                var colors = ['#ED1C24', '#F26522', '#F7941D', '#F0D200', '#8DC73F', '#39B54A', '#00A651', '#00A99D', '#00AEEF', '#0072BC', '#0054A6', '#2E3192', '#662D91', '#92278F', '#EC008C', '#ED145B'];
                if(!target) return this.sendReply('/rainbow message');
                       var userColor = '',
                        currentDate = new Date(),
                        randomNumber = '';
                        for(var x = 0; x < user.name.length; x++){
                                randomNumber = Math.floor(Math.random() * colors.length);
                                if(user.name.substring(x, x + 1) !== undefined){
                                        userColor += '' + user.name.substring(x, x + 1) + '';
                                } else {
                                        userColor += ':';
                                }
                        }
                        if(target.indexOf('/me') > -1) {
                                room.add('|raw|' + user.group + '' + userColor + '' + Tools.escapeHTML(target.substring(3, target.length)) + '');
                        } else {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + target);
                        }
          }
          else return this.errorReply('Necesitas ser minimo voiced para usar este comando.');
  },
  p: 'pinkie',
  pink: 'pinkie',
  pinkie: function(target, room, user){
          if (user.can('broadcast', null, room)) {
                var colors = ['#EDACEC', '#DEAAEC', '#DAAEEA', '#eebaea'];
                if(!target) return this.sendReply('/pinkie mensaje');
                       var userColor = '',
                        currentDate = new Date(),
                        randomNumber = '';
                        for(var x = 0; x < user.name.length; x++){
                                randomNumber = Math.floor(Math.random() * colors.length);
                                if(user.name.substring(x, x + 1) !== undefined){
                                        userColor += '' + user.name.substring(x, x + 1) + '';
                                } else {
                                        userColor += ':';
                                }
                        }
                        if(target.indexOf('/me') > -1) {
                                room.add('|raw|' + user.group + '' + userColor + '' + Tools.escapeHTML(target.substring(3, target.length)) + '');
                        } else {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + target);
                        }
          }
          else return this.errorReply('Necesitas ser minimo voiced para usar este comando.');
  },
        };
<commit_msg>Update raincolors.js<commit_after>/**
Version modificada de rainbow.js para poner otros colores, creditos a el/los creadores de rainbow.js
 */

 exports.commands = {

	pinkhelp: 'raincolors',
        pinkiehelp: 'raincolors',
        rainhelp: 'raincolors',
        rainbowhelp: 'raincolors',
        colors: 'raincolors',
        	raincolors: function () {
		if (!this.canBroadcast()) return false;
		this.sendReplyBox(
			"<big>Rain Colors</big>

" +
			"/pinkie, /pink o /p (mensaje) para cambiar el color de tu usuario a rosa en un mensaje
" +
			"/rainbow, /rain o /r (mensaje) para cambiar el color de tu usuario a arcoiris en un mensaje
" +
			"Creditos a Yomika por reinventar el plugin
"
		);
	},

  r: 'rainbow',
  rain: 'rainbow',
  rainbow: function(target, room, user){
          if (user.can('broadcast', null, room)) {
                var colors = ['#ED1C24', '#F26522', '#F7941D', '#F0D200', '#8DC73F', '#39B54A', '#00A651', '#00A99D', '#00AEEF', '#0072BC', '#0054A6', '#2E3192', '#662D91', '#92278F', '#EC008C', '#ED145B'];
                if(!target) return this.sendReply('/rainbow message');
                       var userColor = '',
                        currentDate = new Date(),
                        randomNumber = '';
                        for(var x = 0; x < user.name.length; x++){
                                randomNumber = Math.floor(Math.random() * colors.length);
                                if(user.name.substring(x, x + 1) !== undefined){
                                        userColor += '' + user.name.substring(x, x + 1) + '';
                                } else {
                                        userColor += ':';
                                }
                        }
                        if(target.indexOf('/me') > -1) {
                                room.add('|raw|' + user.group + '' + userColor + '' + Tools.escapeHTML(target.substring(3, target.length)) + '');
                        } else {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + target);
                        }
          }
          else return this.errorReply('Necesitas ser minimo voiced para usar este comando.');
  },
  p: 'pinkie',
  pink: 'pinkie',
  pinkie: function(target, room, user){
          if (user.can('broadcast', null, room)) {
                var colors = ['#EDACEC', '#DEAAEC', '#DAAEEA', '#eebaea'];
                if(!target) return this.sendReply('/pinkie mensaje');
                       var userColor = '',
                        currentDate = new Date(),
                        randomNumber = '';
                        for(var x = 0; x < user.name.length; x++){
                                randomNumber = Math.floor(Math.random() * colors.length);
                                if(user.name.substring(x, x + 1) !== undefined){
                                        userColor += '' + user.name.substring(x, x + 1) + '';
                                } else {
                                        userColor += ':';
                                }
                        }
                        if(target.indexOf('/me') > -1) {
                                room.add('|raw|' + user.group + '' + userColor + '' + Tools.escapeHTML(target.substring(3, target.length)) + '');
                        } else {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + target);
                        }
          }
          else return this.errorReply('Necesitas ser minimo voiced para usar este comando.');
  },
        };
<|endoftext|>


<commit_before>var inherits = require('util').inherits,
    Task = require('./Task'),
    gulp = require('gulp'),
    mocha = require('gulp-mocha'),
    concat = require('gulp-concat'),
    fs = require('fs');

var DocTask = function (buildHelper) {
    Task.call(this, buildHelper);
};

inherits(DocTask, Task);

DocTask.prototype.command = "doc";
DocTask.prototype.action = function () {
    //Dirty trick to capture Mocha output into a file
    //since gulp-mocha does not pipe the test output
    fs.writeFileSync('./doc.html', '');
    var ogWrite = process.stdout.write;
    process.stdout.write = function (chunk) {
        var textChunk = chunk.toString('utf8');
        if (!textChunk.match(/finished.+after/gmi)) {
            fs.appendFile('./doc.html', chunk);
        }
        ogWrite.apply(this, arguments);
    };

    return gulp.src(this._buildHelper.options.test, {read: false})
        .pipe(mocha({reporter: 'doc'}));
};

module.exports = DocTask;<commit_msg>Cleaner code<commit_after>var inherits = require('util').inherits,
    Task = require('./Task'),
    gulp = require('gulp'),
    mocha = require('gulp-mocha'),
    concat = require('gulp-concat'),
    fs = require('fs');

var DocTask = function (buildHelper) {
    Task.call(this, buildHelper);
};

inherits(DocTask, Task);

DocTask.prototype.command = "doc";
DocTask.prototype.action = function () {
    //Dirty trick to capture Mocha output into a file
    //since gulp-mocha does not pipe the test output
    fs.writeFileSync('./doc.html', '');
    var originalWrite = process.stdout.write;
    process.stdout.write = function (chunk) {
        var textChunk = chunk.toString('utf8');
        if (!textChunk.match(/finished.+after/gmi)) {
            fs.appendFile('./doc.html', chunk);
        }
        originalWrite.apply(this, arguments);
    };

    return gulp.src(this._buildHelper.options.test, {read: false})
        .pipe(mocha({reporter: 'doc'}));
};

module.exports = DocTask;<|endoftext|>


<commit_before>//remove:
var next = require('../build/sob.node.js');
//:remove

wru.test([
  {
    name: "it's an obejct",
    test: function () {
      wru.assert(typeof sob == 'object');
    }
  }, {
    name: 'requestAnimationFrame',
    test: function () {
      sob.frame(wru.async(function () {
        wru.assert('requestAnimationFrame happened', true);
      }));
    }
  }, {
    name: 'requestIdleCallback',
    test: function () {
      sob.frame(wru.async(function () {
        wru.assert('requestIdleCallback happened', true);
      }));
    }
  }, {
    name: 'clear',
    test: function () {
      var
        animHappened = false,
        idleHappened = false,
        animId = sob.frame(function () {
          animHappened = true;
        }),
        idleId = sob.idle(function () {
          idleHappened = true;
        })
      ;
      sob.clear(animId);
      sob.clear(idleId);
      setTimeout(wru.async(function () {
        wru.assert(!animHappened && !idleHappened);
      }), 300);
    }
  }, {
    name: 'clear inverted',
    test: function () {
      var
        animHappened = false,
        idleHappened = false,
        animId = sob.frame(function () {
          animHappened = true;
        }),
        idleId = sob.idle(function () {
          idleHappened = true;
        })
      ;
      sob.clear(idleId);
      sob.clear(animId);
      setTimeout(wru.async(function () {
        wru.assert(!animHappened && !idleHappened);
      }), 300);
    }
  }, {
    name: 'no duplicated rAF',
    test: function () {
      var
        executed = [],
        first = function () {
          executed.push(first);
        },
        second = function () {
          executed.push(second);
        }
      ;
      sob.frame(first);
      sob.frame(first);
      sob.frame(second);
      sob.frame(first);
      sob.frame(second);
      sob.frame(second);
      sob.frame(first);
      setTimeout(wru.async(function () {
        wru.assert(
          executed.length === 2 &&
          executed[0] === first &&
          executed[1] === second
        );
      }), 300);
    }
  }, {
    name: 'no duplicated rIC',
    test: function () {
      var
        executed = [],
        first = function () {
          executed.push(first);
        },
        second = function () {
          executed.push(second);
        }
      ;
      sob.idle(first);
      sob.idle(first);
      sob.idle(second);
      sob.idle(first);
      sob.idle(second);
      sob.idle(second);
      sob.idle(first);
      setTimeout(wru.async(function () {
        wru.assert(
          executed.length === 2 &&
          executed[0] === first &&
          executed[1] === second
        );
      }), 300);
    }
  }, {
    name: 'passed arguments rAF',
    test: function () {
      var
        executed = [],
        first = function () {
          executed.push(arguments);
        },
        second = function () {
          executed.push(arguments);
        }
      ;
      sob.frame(first, 1, 2, 3);
      sob.frame(second, 4, 5, 6);
      setTimeout(wru.async(function () {
        wru.assert(
          [].join.call(executed[0]) === '1,2,3' &&
          [].join.call(executed[1]) === '4,5,6'
        );
      }), 300);
    }
  }, {
    name: 'passed arguments rIC',
    test: function () {
      var
        executed = [],
        first = function () {
          executed.push(arguments);
        },
        second = function () {
          executed.push(arguments);
        }
      ;
      sob.idle(first, 1, 2, 3);
      sob.idle(second, 4, 5);
      setTimeout(wru.async(function () {
        wru.assert(
          [].join.call(executed[0]) === '1,2,3' &&
          [].join.call(executed[1]) === '4,5'
        );
      }), 300);
    }
  }, {
    name: 'no duplicated rAF + args',
    test: function () {
      var
        executed = [],
        first = function first() {
          executed.push({
            fn: first,
            ar: [].slice.call(arguments)
          });
        },
        second = function second() {
          executed.push({
            fn: second,
            ar: [].slice.call(arguments)
          });
        }
      ;
      sob.frame(first, 1, 2, 3);
      sob.frame(first, 1, 2, 3);
      sob.frame(second, 4, 5);
      sob.frame(first, 1, 2, 3);
      sob.frame(second, 4, 5);
      sob.frame(second, 4, 5);
      sob.frame(first, 1, 2, 3);
      setTimeout(wru.async(function () {
        wru.assert(
          executed.length === 2 &&
          executed[0].fn === first &&
          executed[1].fn === second &&
          executed[0].ar.join(',') === '1,2,3' &&
          executed[1].ar.join(',') === '4,5'
        );
      }), 300);
    }
  }, {
    name: 'no duplicated rIC + args',
    test: function () {
      var
        executed = [],
        first = function first() {
          executed.push({
            fn: first,
            ar: [].slice.call(arguments)
          });
        },
        second = function second() {
          executed.push({
            fn: second,
            ar: [].slice.call(arguments)
          });
        }
      ;
      sob.idle(first, 1, 2, 3);
      sob.idle(first, 1, 2, 3);
      sob.idle(second, 4, 5);
      sob.idle(first, 1, 2, 3);
      sob.idle(second, 4, 5);
      sob.idle(second, 4, 5);
      sob.idle(first, 1, 2, 3);
      setTimeout(wru.async(function () {
        wru.assert(
          executed.length === 2 &&
          executed[0].fn === first &&
          executed[1].fn === second &&
          executed[0].ar.join(',') === '1,2,3' &&
          executed[1].ar.join(',') === '4,5'
        );
      }), 300);
    }
  }, {
    name: 'same callback, different rAF args',
    test: function () {
      var
        executed = [],
        first = function () {
          executed.push({
            fn: first,
            ar: [].slice.call(arguments)
          });
        },
        second = function () {
          executed.push({
            fn: second,
            ar: [].slice.call(arguments)
          });
        },
        ids = [
          sob.frame(first),
          sob.frame(first, 1),
          sob.frame(first, 1, 2),
          sob.frame(second),
          sob.frame(second, 1),
          sob.frame(first),
          sob.frame(first, 1),
          sob.frame(first, 1, 2),
          sob.frame(second),
          sob.frame(second, 1)
        ]
      ;
      sob.clear(ids[1]);
      sob.clear(ids[3]);
      setTimeout(wru.async(function () {
        wru.assert(
          executed.length === 3 &&
          executed[0].fn === first &&
          executed[1].fn === first &&
          executed[2].fn === second &&
          executed[0].ar.join(',') === '' &&
          executed[1].ar.join(',') === '1,2' &&
          executed[2].ar.join(',') === '1'
        );
      }), 300);
    }
  }, {
    name: 'same callback, different rIC args',
    test: function () {
      var
        executed = [],
        first = function () {
          executed.push({
            fn: first,
            ar: [].slice.call(arguments)
          });
        },
        second = function () {
          executed.push({
            fn: second,
            ar: [].slice.call(arguments)
          });
        },
        ids = [
          sob.idle(first),
          sob.idle(first, 1),
          sob.idle(first, 1, 2),
          sob.idle(second),
          sob.idle(second, 1),
          sob.idle(first),
          sob.idle(first, 1),
          sob.idle(first, 1, 2),
          sob.idle(second),
          sob.idle(second, 1)
        ]
      ;
      sob.clear(ids[1]);
      sob.clear(ids[3]);
      setTimeout(wru.async(function () {
        wru.assert(
          executed.length === 3 &&
          executed[0].fn === first &&
          executed[1].fn === first &&
          executed[2].fn === second &&
          executed[0].ar.join(',') === '' &&
          executed[1].ar.join(',') === '1,2' &&
          executed[2].ar.join(',') === '1'
        );
      }), 300);
    }
  }, {
    name: 'overload',
    test: function () {
      sob.frame(function () {
        var t = (new Date).getTime();
        while ((new Date).getTime() - t < (1000 / (sob.minFPS / 2)));
      });
      sob.frame(wru.async(function () {
        wru.assert(sob.isOverloaded);
      }));
    }
  }, {
    name: 'multiple calls',
    test: function () {
      var
        frame = 0,
        idle = 0,
        done = wru.async(function () {
          wru.assert(true);
        })
      ;
      (function f() {
        if (++frame >= 10 && idle === 10) done();
        else sob.frame(f);
      }());
      (function i() {
        if (++idle < 10) sob.idle(i);
      }());
    }
  }, {
    name: 'fail safe frame',
    test: function () {
      var calls = [];
      sob.frame(function a() { calls.push('a'); });
      sob.frame(function b() { throw new Error('b'); });
      sob.frame(function c() { calls.push('c'); });
      sob.frame(function d() { calls.push('d'); });
      sob.frame(wru.async(function () {
        wru.assert(calls.join(',') === 'a,c,d');
      }));
    }
  }, {
    name: 'fail safe idle',
    test: function () {
      var calls = [];
      sob.idle(function a() { calls.push('a'); });
      sob.idle(function b() { throw new Error('b'); });
      sob.idle(function c() { calls.push('c'); });
      sob.idle(function d() { calls.push('d'); });
      sob.idle(wru.async(function () {
        wru.assert(calls.join(',') === 'a,c,d');
      }));
    }
  }, {
    name: 'performance',
    test: function () {
      var
        counter = 0,
        id
      ;
      setTimeout(wru.async(function () {
        sob.clear(id);
        wru.assert('frames ' + counter, 60 <= counter);
      }), 1000);
      (function run() {
        counter++;
        id = sob.frame(run);
      }());
    }
  }
]);
<commit_msg>used better comparison for FPS<commit_after>//remove:
var next = require('../build/sob.node.js');
//:remove

wru.test([
  {
    name: "it's an obejct",
    test: function () {
      wru.assert(typeof sob == 'object');
    }
  }, {
    name: 'requestAnimationFrame',
    test: function () {
      sob.frame(wru.async(function () {
        wru.assert('requestAnimationFrame happened', true);
      }));
    }
  }, {
    name: 'requestIdleCallback',
    test: function () {
      sob.frame(wru.async(function () {
        wru.assert('requestIdleCallback happened', true);
      }));
    }
  }, {
    name: 'clear',
    test: function () {
      var
        animHappened = false,
        idleHappened = false,
        animId = sob.frame(function () {
          animHappened = true;
        }),
        idleId = sob.idle(function () {
          idleHappened = true;
        })
      ;
      sob.clear(animId);
      sob.clear(idleId);
      setTimeout(wru.async(function () {
        wru.assert(!animHappened && !idleHappened);
      }), 300);
    }
  }, {
    name: 'clear inverted',
    test: function () {
      var
        animHappened = false,
        idleHappened = false,
        animId = sob.frame(function () {
          animHappened = true;
        }),
        idleId = sob.idle(function () {
          idleHappened = true;
        })
      ;
      sob.clear(idleId);
      sob.clear(animId);
      setTimeout(wru.async(function () {
        wru.assert(!animHappened && !idleHappened);
      }), 300);
    }
  }, {
    name: 'no duplicated rAF',
    test: function () {
      var
        executed = [],
        first = function () {
          executed.push(first);
        },
        second = function () {
          executed.push(second);
        }
      ;
      sob.frame(first);
      sob.frame(first);
      sob.frame(second);
      sob.frame(first);
      sob.frame(second);
      sob.frame(second);
      sob.frame(first);
      setTimeout(wru.async(function () {
        wru.assert(
          executed.length === 2 &&
          executed[0] === first &&
          executed[1] === second
        );
      }), 300);
    }
  }, {
    name: 'no duplicated rIC',
    test: function () {
      var
        executed = [],
        first = function () {
          executed.push(first);
        },
        second = function () {
          executed.push(second);
        }
      ;
      sob.idle(first);
      sob.idle(first);
      sob.idle(second);
      sob.idle(first);
      sob.idle(second);
      sob.idle(second);
      sob.idle(first);
      setTimeout(wru.async(function () {
        wru.assert(
          executed.length === 2 &&
          executed[0] === first &&
          executed[1] === second
        );
      }), 300);
    }
  }, {
    name: 'passed arguments rAF',
    test: function () {
      var
        executed = [],
        first = function () {
          executed.push(arguments);
        },
        second = function () {
          executed.push(arguments);
        }
      ;
      sob.frame(first, 1, 2, 3);
      sob.frame(second, 4, 5, 6);
      setTimeout(wru.async(function () {
        wru.assert(
          [].join.call(executed[0]) === '1,2,3' &&
          [].join.call(executed[1]) === '4,5,6'
        );
      }), 300);
    }
  }, {
    name: 'passed arguments rIC',
    test: function () {
      var
        executed = [],
        first = function () {
          executed.push(arguments);
        },
        second = function () {
          executed.push(arguments);
        }
      ;
      sob.idle(first, 1, 2, 3);
      sob.idle(second, 4, 5);
      setTimeout(wru.async(function () {
        wru.assert(
          [].join.call(executed[0]) === '1,2,3' &&
          [].join.call(executed[1]) === '4,5'
        );
      }), 300);
    }
  }, {
    name: 'no duplicated rAF + args',
    test: function () {
      var
        executed = [],
        first = function first() {
          executed.push({
            fn: first,
            ar: [].slice.call(arguments)
          });
        },
        second = function second() {
          executed.push({
            fn: second,
            ar: [].slice.call(arguments)
          });
        }
      ;
      sob.frame(first, 1, 2, 3);
      sob.frame(first, 1, 2, 3);
      sob.frame(second, 4, 5);
      sob.frame(first, 1, 2, 3);
      sob.frame(second, 4, 5);
      sob.frame(second, 4, 5);
      sob.frame(first, 1, 2, 3);
      setTimeout(wru.async(function () {
        wru.assert(
          executed.length === 2 &&
          executed[0].fn === first &&
          executed[1].fn === second &&
          executed[0].ar.join(',') === '1,2,3' &&
          executed[1].ar.join(',') === '4,5'
        );
      }), 300);
    }
  }, {
    name: 'no duplicated rIC + args',
    test: function () {
      var
        executed = [],
        first = function first() {
          executed.push({
            fn: first,
            ar: [].slice.call(arguments)
          });
        },
        second = function second() {
          executed.push({
            fn: second,
            ar: [].slice.call(arguments)
          });
        }
      ;
      sob.idle(first, 1, 2, 3);
      sob.idle(first, 1, 2, 3);
      sob.idle(second, 4, 5);
      sob.idle(first, 1, 2, 3);
      sob.idle(second, 4, 5);
      sob.idle(second, 4, 5);
      sob.idle(first, 1, 2, 3);
      setTimeout(wru.async(function () {
        wru.assert(
          executed.length === 2 &&
          executed[0].fn === first &&
          executed[1].fn === second &&
          executed[0].ar.join(',') === '1,2,3' &&
          executed[1].ar.join(',') === '4,5'
        );
      }), 300);
    }
  }, {
    name: 'same callback, different rAF args',
    test: function () {
      var
        executed = [],
        first = function () {
          executed.push({
            fn: first,
            ar: [].slice.call(arguments)
          });
        },
        second = function () {
          executed.push({
            fn: second,
            ar: [].slice.call(arguments)
          });
        },
        ids = [
          sob.frame(first),
          sob.frame(first, 1),
          sob.frame(first, 1, 2),
          sob.frame(second),
          sob.frame(second, 1),
          sob.frame(first),
          sob.frame(first, 1),
          sob.frame(first, 1, 2),
          sob.frame(second),
          sob.frame(second, 1)
        ]
      ;
      sob.clear(ids[1]);
      sob.clear(ids[3]);
      setTimeout(wru.async(function () {
        wru.assert(
          executed.length === 3 &&
          executed[0].fn === first &&
          executed[1].fn === first &&
          executed[2].fn === second &&
          executed[0].ar.join(',') === '' &&
          executed[1].ar.join(',') === '1,2' &&
          executed[2].ar.join(',') === '1'
        );
      }), 300);
    }
  }, {
    name: 'same callback, different rIC args',
    test: function () {
      var
        executed = [],
        first = function () {
          executed.push({
            fn: first,
            ar: [].slice.call(arguments)
          });
        },
        second = function () {
          executed.push({
            fn: second,
            ar: [].slice.call(arguments)
          });
        },
        ids = [
          sob.idle(first),
          sob.idle(first, 1),
          sob.idle(first, 1, 2),
          sob.idle(second),
          sob.idle(second, 1),
          sob.idle(first),
          sob.idle(first, 1),
          sob.idle(first, 1, 2),
          sob.idle(second),
          sob.idle(second, 1)
        ]
      ;
      sob.clear(ids[1]);
      sob.clear(ids[3]);
      setTimeout(wru.async(function () {
        wru.assert(
          executed.length === 3 &&
          executed[0].fn === first &&
          executed[1].fn === first &&
          executed[2].fn === second &&
          executed[0].ar.join(',') === '' &&
          executed[1].ar.join(',') === '1,2' &&
          executed[2].ar.join(',') === '1'
        );
      }), 300);
    }
  }, {
    name: 'overload',
    test: function () {
      sob.frame(function () {
        var t = (new Date).getTime();
        while ((new Date).getTime() - t < (1000 / (sob.minFPS / 2)));
      });
      sob.frame(wru.async(function () {
        wru.assert(sob.isOverloaded);
      }));
    }
  }, {
    name: 'multiple calls',
    test: function () {
      var
        frame = 0,
        idle = 0,
        done = wru.async(function () {
          wru.assert(true);
        })
      ;
      (function f() {
        if (++frame >= 10 && idle === 10) done();
        else sob.frame(f);
      }());
      (function i() {
        if (++idle < 10) sob.idle(i);
      }());
    }
  }, {
    name: 'fail safe frame',
    test: function () {
      var calls = [];
      sob.frame(function a() { calls.push('a'); });
      sob.frame(function b() { throw new Error('b'); });
      sob.frame(function c() { calls.push('c'); });
      sob.frame(function d() { calls.push('d'); });
      sob.frame(wru.async(function () {
        wru.assert(calls.join(',') === 'a,c,d');
      }));
    }
  }, {
    name: 'fail safe idle',
    test: function () {
      var calls = [];
      sob.idle(function a() { calls.push('a'); });
      sob.idle(function b() { throw new Error('b'); });
      sob.idle(function c() { calls.push('c'); });
      sob.idle(function d() { calls.push('d'); });
      sob.idle(wru.async(function () {
        wru.assert(calls.join(',') === 'a,c,d');
      }));
    }
  }, {
    name: 'performance',
    test: function () {
      var
        counter = 0,
        id
      ;
      setTimeout(wru.async(function () {
        sob.clear(id);
        wru.assert('frames ' + counter, sob.minFPS <= counter);
      }), 1000);
      (function run() {
        counter++;
        id = sob.frame(run);
      }());
    }
  }
]);
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree.
 */

/* More information about these options at jshint.com/docs/options */

/* exported setUpFullScreen, fullScreenElement, isFullScreen,
   requestTurnServers, sendAsyncUrlRequest, sendSyncUrlRequest, randomString, $,
   queryStringToDictionary */
/* globals chrome */

'use strict';

function $(selector) {
  return document.querySelector(selector);
}

// Returns the URL query key-value pairs as a dictionary object.
function queryStringToDictionary(queryString) {
  var pairs = queryString.slice(1).split('&');

  var result = {};
  pairs.forEach(function(pair) {
    if (pair) {
      pair = pair.split('=');
      if (pair[0]) {
        result[pair[0]] = decodeURIComponent(pair[1] || '');
      }
    }
  });
  return result;
}

// Sends the URL request and returns a Promise as the result.
function sendAsyncUrlRequest(method, url, body) {
  return sendUrlRequest(method, url, true, body);
}

// If async is true, returns a Promise and executes the xhr request
// async. If async is false, the xhr will be executed sync and a
// resolved promise is returned.
function sendUrlRequest(method, url, async, body) {
  return new Promise(function(resolve, reject) {
    var xhr;
    var reportResults = function() {
      if (xhr.status !== 200) {
        reject(
            Error('Status=' + xhr.status + ', response=' +
                  xhr.responseText));
        return;
      }
      resolve(xhr.responseText);
    };

    xhr = new XMLHttpRequest();
    if (async) {
      xhr.onreadystatechange = function() {
        if (xhr.readyState !== 4) {
          return;
        }
        reportResults();
      };
    }
    xhr.open(method, url, async);
    xhr.send(body);

    if (!async) {
      reportResults();
    }
  });
}

// Returns a list of turn servers after requesting it from the TURN server.
function requestTurnServers(turnRequestUrl, turnTransports) {
  return new Promise(function(resolve, reject) {
    sendAsyncUrlRequest('POST', turnRequestUrl).then(function(response) {
      var turnServerResponse = parseJSON(response);
      if (!turnServerResponse) {
        reject(Error('Error parsing response JSON: ' + response));
        return;
      }
      turnTransports = 'tcp';
      if (turnTransports.length > 0) {
        filterTurnUrls(turnServerResponse, turnTransports);
      }
      trace('Retrieved TURN server information.');
      resolve(turnServerResponse.iceServers);
    }).catch(function(error) {
      reject(Error('TURN server request error: ' + error.message));
      return;
    });
  });
}

// Parse the supplied JSON, or return null if parsing fails.
function parseJSON(json) {
  try {
    return JSON.parse(json);
  } catch (e) {
    trace('Error parsing json: ' + json);
  }
  return null;
}

// Filter a list of TURN urls to only contain those with transport=|protocol|.
function filterTurnUrls(config, protocol) {
  var transport = 'transport=' + protocol;
  var newIceServers = [];
  for (var i = 0; i < config.iceServers.length; ++i) {
    var iceServer = config.iceServers[i];
    var newUrls = [];
    for (var j = 0; j < iceServer.urls.length; ++j) {
      var uri = iceServer.urls[j];
      if (uri.indexOf(transport) !== -1) {
        newUrls.push(uri);
      } else if (
        uri.indexOf('?transport=') === -1 && uri.startsWith('turn')) {
          newUrls.push(uri + '?' + transport);
      }
    }
    if (newUrls.length !== 0) {
      iceServer.urls = newUrls;
      newIceServers.push(iceServer);
    }
  }
  config.iceServers = newIceServers;
}

// Start shims for fullscreen
function setUpFullScreen() {
  if (isChromeApp()) {
    document.cancelFullScreen = function() {
      chrome.app.window.current().restore();
    };
  } else {
    document.cancelFullScreen = document.webkitCancelFullScreen ||
        document.mozCancelFullScreen || document.cancelFullScreen;
  }

  if (isChromeApp()) {
    document.body.requestFullScreen = function() {
      chrome.app.window.current().fullscreen();
    };
  } else {
    document.body.requestFullScreen = document.body.webkitRequestFullScreen ||
        document.body.mozRequestFullScreen || document.body.requestFullScreen;
  }

  document.onfullscreenchange = document.onfullscreenchange ||
        document.onwebkitfullscreenchange || document.onmozfullscreenchange;
}

function isFullScreen() {
  if (isChromeApp()) {
    return chrome.app.window.current().isFullscreen();
  }

  return !!(document.webkitIsFullScreen || document.mozFullScreen ||
    document.isFullScreen); // if any defined and true
}

function fullScreenElement() {
  return document.webkitFullScreenElement ||
      document.webkitCurrentFullScreenElement ||
      document.mozFullScreenElement ||
      document.fullScreenElement;
}

// End shims for fullscreen

// Return a random numerical string.
function randomString(strLength) {
  var result = [];
  strLength = strLength || 5;
  var charSet = '0123456789';
  while (strLength--) {
    result.push(charSet.charAt(Math.floor(Math.random() * charSet.length)));
  }
  return result.join('');
}

// Returns true if the code is running in a packaged Chrome App.
function isChromeApp() {
  return (typeof chrome !== 'undefined' &&
          typeof chrome.storage !== 'undefined' &&
          typeof chrome.storage.local !== 'undefined');
}
<commit_msg>fix grunt issue<commit_after>/*
 *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree.
 */

/* More information about these options at jshint.com/docs/options */

/* exported setUpFullScreen, fullScreenElement, isFullScreen,
   requestTurnServers, sendAsyncUrlRequest, sendSyncUrlRequest, randomString, $,
   queryStringToDictionary */
/* globals chrome */

'use strict';

function $(selector) {
  return document.querySelector(selector);
}

// Returns the URL query key-value pairs as a dictionary object.
function queryStringToDictionary(queryString) {
  var pairs = queryString.slice(1).split('&');

  var result = {};
  pairs.forEach(function(pair) {
    if (pair) {
      pair = pair.split('=');
      if (pair[0]) {
        result[pair[0]] = decodeURIComponent(pair[1] || '');
      }
    }
  });
  return result;
}

// Sends the URL request and returns a Promise as the result.
function sendAsyncUrlRequest(method, url, body) {
  return sendUrlRequest(method, url, true, body);
}

// If async is true, returns a Promise and executes the xhr request
// async. If async is false, the xhr will be executed sync and a
// resolved promise is returned.
function sendUrlRequest(method, url, async, body) {
  return new Promise(function(resolve, reject) {
    var xhr;
    var reportResults = function() {
      if (xhr.status !== 200) {
        reject(
            Error('Status=' + xhr.status + ', response=' +
                  xhr.responseText));
        return;
      }
      resolve(xhr.responseText);
    };

    xhr = new XMLHttpRequest();
    if (async) {
      xhr.onreadystatechange = function() {
        if (xhr.readyState !== 4) {
          return;
        }
        reportResults();
      };
    }
    xhr.open(method, url, async);
    xhr.send(body);

    if (!async) {
      reportResults();
    }
  });
}

// Returns a list of turn servers after requesting it from the TURN server.
function requestTurnServers(turnRequestUrl, turnTransports) {
  return new Promise(function(resolve, reject) {
    sendAsyncUrlRequest('POST', turnRequestUrl).then(function(response) {
      var turnServerResponse = parseJSON(response);
      if (!turnServerResponse) {
        reject(Error('Error parsing response JSON: ' + response));
        return;
      }
      turnTransports = 'tcp';
      if (turnTransports.length > 0) {
        filterTurnUrls(turnServerResponse, turnTransports);
      }
      trace('Retrieved TURN server information.');
      resolve(turnServerResponse.iceServers);
    }).catch(function(error) {
      reject(Error('TURN server request error: ' + error.message));
      return;
    });
  });
}

// Parse the supplied JSON, or return null if parsing fails.
function parseJSON(json) {
  try {
    return JSON.parse(json);
  } catch (e) {
    trace('Error parsing json: ' + json);
  }
  return null;
}

// Filter a list of TURN urls to only contain those with transport=|protocol|.
function filterTurnUrls(config, protocol) {
  var transport = 'transport=' + protocol;
  var newIceServers = [];
  for (var i = 0; i < config.iceServers.length; ++i) {
    var iceServer = config.iceServers[i];
    var newUrls = [];
    for (var j = 0; j < iceServer.urls.length; ++j) {
      var uri = iceServer.urls[j];
      if (uri.indexOf(transport) !== -1) {
        newUrls.push(uri);
      } else if (
        uri.indexOf('?transport=') === -1 && uri.startsWith('turn')) {
        newUrls.push(uri + '?' + transport);
      }
    }
    if (newUrls.length !== 0) {
      iceServer.urls = newUrls;
      newIceServers.push(iceServer);
    }
  }
  config.iceServers = newIceServers;
}

// Start shims for fullscreen
function setUpFullScreen() {
  if (isChromeApp()) {
    document.cancelFullScreen = function() {
      chrome.app.window.current().restore();
    };
  } else {
    document.cancelFullScreen = document.webkitCancelFullScreen ||
        document.mozCancelFullScreen || document.cancelFullScreen;
  }

  if (isChromeApp()) {
    document.body.requestFullScreen = function() {
      chrome.app.window.current().fullscreen();
    };
  } else {
    document.body.requestFullScreen = document.body.webkitRequestFullScreen ||
        document.body.mozRequestFullScreen || document.body.requestFullScreen;
  }

  document.onfullscreenchange = document.onfullscreenchange ||
        document.onwebkitfullscreenchange || document.onmozfullscreenchange;
}

function isFullScreen() {
  if (isChromeApp()) {
    return chrome.app.window.current().isFullscreen();
  }

  return !!(document.webkitIsFullScreen || document.mozFullScreen ||
    document.isFullScreen); // if any defined and true
}

function fullScreenElement() {
  return document.webkitFullScreenElement ||
      document.webkitCurrentFullScreenElement ||
      document.mozFullScreenElement ||
      document.fullScreenElement;
}

// End shims for fullscreen

// Return a random numerical string.
function randomString(strLength) {
  var result = [];
  strLength = strLength || 5;
  var charSet = '0123456789';
  while (strLength--) {
    result.push(charSet.charAt(Math.floor(Math.random() * charSet.length)));
  }
  return result.join('');
}

// Returns true if the code is running in a packaged Chrome App.
function isChromeApp() {
  return (typeof chrome !== 'undefined' &&
          typeof chrome.storage !== 'undefined' &&
          typeof chrome.storage.local !== 'undefined');
}
<|endoftext|>


<commit_before>"use strict";

var rework = require('rework');
var pureGrids = require('rework-pure-grids');
var mkdirp = require('mkdirp');
var fs = require('fs');

module.exports = function(config) {
    return function (cb) {
        createGrid(config.files.dest + 'custom-grid.css', config.breakpoints, function() {
            createCustomMediaVariables(config.files.dest + 'custom-media-variables.pcss', config.breakpoints, function() {
                cb();
            });
        });
    };
};

function createGrid(dest, map, cb) {
    var css = rework('').use(pureGrids.units(12, {
        decimals: 4,
        includeOldIEWidths: false,
        includeReducedFractions: false,
        includeWholeNumbers: false,
        selectorPrefix: '.col-',
        mediaQueries: map
    })).toString();
    writeFile(dest, css, cb);
}

function createCustomMediaVariables(dest, map, cb) {
    var vars = '';
    for(var key in map) {
        if (map.hasOwnProperty(key)) {
            vars += '@custom-media --screen-' + key + ' ' + map[key] + ';\n';
        }
    }
    writeFile(dest, vars, cb);
}

var getDirName = require("upath").dirname;
function writeFile(path, content, cb) {
    mkdirp(getDirName(path), function (err) {
        if (err) {
            return cb(err);
        }
        fs.writeFile(path, content, cb);
    });
}
<commit_msg>purecss - reconfiguration<commit_after>"use strict";

var rework = require('rework');
var pureGrids = require('rework-pure-grids');
var mkdirp = require('mkdirp');
var fs = require('fs');

module.exports = function(config) {
    return function (cb) {
        createGrid(config.files.dest + 'custom-grid.css', config.breakpoints, function() {
            createCustomMediaVariables(config.files.dest + 'custom-media-variables.pcss', config.columns, config.breakpoints, function() {
                cb();
            });
        });
    };
};

function createGrid(dest, columns, map, cb) {
    var css = rework('').use(pureGrids.units(columns || 12, {
        decimals: 4,
        includeOldIEWidths: false,
        includeReducedFractions: false,
        includeWholeNumbers: false,
        mediaQueries: map
    })).toString();
    writeFile(dest, css, cb);
}

function createCustomMediaVariables(dest, map, cb) {
    var vars = '';
    for(var key in map) {
        if (map.hasOwnProperty(key)) {
            vars += '@custom-media --screen-' + key + ' ' + map[key] + ';\n';
        }
    }
    writeFile(dest, vars, cb);
}

var getDirName = require("upath").dirname;
function writeFile(path, content, cb) {
    mkdirp(getDirName(path), function (err) {
        if (err) {
            return cb(err);
        }
        fs.writeFile(path, content, cb);
    });
}
<|endoftext|>


<commit_before>import Ember from 'ember';

const {
    $,
    Controller,
    inject: {service},
    isArray
} = Ember;

export default Controller.extend({
    uploadButtonText: 'Import',
    importErrors: '',
    submitting: false,
    showDeleteAllModal: false,

    ghostPaths: service(),
    notifications: service(),
    session: service(),

    actions: {
        onUpload(file) {
            let formData = new FormData();
            let notifications = this.get('notifications');
            let currentUserId = this.get('session.user.id');
            let dbUrl = this.get('ghostPaths.url').api('db');

            this.set('uploadButtonText', 'Importing');
            this.set('importErrors', '');

            formData.append('importfile', file);

            this.get('ajax').post(dbUrl, {
                data: formData,
                dataType: 'json',
                cache: false,
                contentType: false,
                processData: false
            }).then(() => {
                // Clear the store, so that all the new data gets fetched correctly.
                this.store.unloadAll();
                // Reload currentUser and set session
                this.set('session.user', this.store.findRecord('user', currentUserId));
                // TODO: keep as notification, add link to view content
                notifications.showNotification('Import successful.', {key: 'import.upload.success'});
            }).catch((response) => {
                if (response && response.errors && isArray(response.errors)) {
                    this.set('importErrors', response.errors);
                }

                notifications.showAlert('Import Failed', {type: 'error', key: 'import.upload.failed'});
            }).finally(() => {
                this.set('uploadButtonText', 'Import');
            });
        },

        exportData() {
            let dbUrl = this.get('ghostPaths.url').api('db');
            let accessToken = this.get('session.data.authenticated.access_token');
            let downloadURL = `${dbUrl}?access_token=${accessToken}`;
            let iframe = $('#iframeDownload');

            if (iframe.length === 0) {
                iframe = $('<iframe>', {id: 'iframeDownload'}).hide().appendTo('body');
            }

            iframe.attr('src', downloadURL);
        },

        sendTestEmail() {
            let notifications = this.get('notifications');
            let emailUrl = this.get('ghostPaths.url').api('mail', 'test');

            this.toggleProperty('submitting');

            this.get('ajax').post(emailUrl).then(() => {
                notifications.showAlert('Check your email for the test message.', {type: 'info', key: 'test-email.send.success'});
                this.toggleProperty('submitting');
            }).catch((error) => {
                notifications.showAPIError(error, {key: 'test-email:send'});
                this.toggleProperty('submitting');
            });
        },

        toggleDeleteAllModal() {
            this.toggleProperty('showDeleteAllModal');
        }
    }
});
<commit_msg>inject ajax service in settings/labs<commit_after>import Ember from 'ember';

const {
    $,
    Controller,
    inject: {service},
    isArray
} = Ember;

export default Controller.extend({
    uploadButtonText: 'Import',
    importErrors: '',
    submitting: false,
    showDeleteAllModal: false,

    ghostPaths: service(),
    notifications: service(),
    session: service(),
    ajax: service(),

    actions: {
        onUpload(file) {
            let formData = new FormData();
            let notifications = this.get('notifications');
            let currentUserId = this.get('session.user.id');
            let dbUrl = this.get('ghostPaths.url').api('db');

            this.set('uploadButtonText', 'Importing');
            this.set('importErrors', '');

            formData.append('importfile', file);

            this.get('ajax').post(dbUrl, {
                data: formData,
                dataType: 'json',
                cache: false,
                contentType: false,
                processData: false
            }).then(() => {
                // Clear the store, so that all the new data gets fetched correctly.
                this.store.unloadAll();
                // Reload currentUser and set session
                this.set('session.user', this.store.findRecord('user', currentUserId));
                // TODO: keep as notification, add link to view content
                notifications.showNotification('Import successful.', {key: 'import.upload.success'});
            }).catch((response) => {
                if (response && response.errors && isArray(response.errors)) {
                    this.set('importErrors', response.errors);
                }

                notifications.showAlert('Import Failed', {type: 'error', key: 'import.upload.failed'});
            }).finally(() => {
                this.set('uploadButtonText', 'Import');
            });
        },

        exportData() {
            let dbUrl = this.get('ghostPaths.url').api('db');
            let accessToken = this.get('session.data.authenticated.access_token');
            let downloadURL = `${dbUrl}?access_token=${accessToken}`;
            let iframe = $('#iframeDownload');

            if (iframe.length === 0) {
                iframe = $('<iframe>', {id: 'iframeDownload'}).hide().appendTo('body');
            }

            iframe.attr('src', downloadURL);
        },

        sendTestEmail() {
            let notifications = this.get('notifications');
            let emailUrl = this.get('ghostPaths.url').api('mail', 'test');

            this.toggleProperty('submitting');

            this.get('ajax').post(emailUrl).then(() => {
                notifications.showAlert('Check your email for the test message.', {type: 'info', key: 'test-email.send.success'});
                this.toggleProperty('submitting');
            }).catch((error) => {
                notifications.showAPIError(error, {key: 'test-email:send'});
                this.toggleProperty('submitting');
            });
        },

        toggleDeleteAllModal() {
            this.toggleProperty('showDeleteAllModal');
        }
    }
});
<|endoftext|>


<commit_before>"use strict";

var gulp = require('gulp');
var webpackStream = require('webpack-stream');
var webpack = require('webpack');
var upath = require('upath');
var taskGenerator = require('../taskGenerator');

module.exports = function(name, config, serverConfig) {
    return taskGenerator(name, config, serverConfig, function(taskName, task) {
        gulp.task(taskName, function() {
            return gulp.src(task.files.src)
                .pipe(webpackStream({
                    entry: task.entry,
                    plugins: function() {
                        return task.plugins.map(function(plugin) {
                            return require(plugin.script)(webpack, plugin.config);
                        });
                    }(),
                    module: {
                        preLoaders: (task.module.preLoaders || []).map(convertLoader),
                        loaders: (task.module.loaders || []).map(convertLoader),
                        postLoaders: (task.module.postLoaders || []).map(convertLoader)
                    },
                    resolve: task.resolve,
                    output: {
                        filename: upath.basename(task.files.dest),
                        library:task.files.library
                    }
                }, null))
                .pipe(gulp.dest(upath.dirname(task.files.dest)));
        });
    });
};

function convertLoader(loader) {
    loader.test = new RegExp(loader.test);
    if(loader.exclude) {
        loader.exclude = new RegExp(loader.exclude);
    }
    return loader;
}
<commit_msg>added loader agency require for custom loader scripts<commit_after>"use strict";

var gulp = require('gulp');
var webpackStream = require('webpack-stream');
var webpack = require('webpack');
var upath = require('upath');
var taskGenerator = require('../taskGenerator');

module.exports = function(name, config, serverConfig) {
    return taskGenerator(name, config, serverConfig, function(taskName, task) {
        gulp.task(taskName, function() {
            return gulp.src(task.files.src)
                .pipe(webpackStream({
                    entry: task.entry,
                    plugins: function() {
                        return task.plugins.map(function(plugin) {
                            return require(plugin.script)(webpack, plugin.config);
                        });
                    }(),
                    module: {
                        preLoaders: (task.module.preLoaders || []).map(convertLoader),
                        loaders: (task.module.loaders || []).map(convertLoader),
                        postLoaders: (task.module.postLoaders || []).map(convertLoader)
                    },
                    resolve: task.resolve,
                    output: {
                        filename: upath.basename(task.files.dest),
                        library:task.files.library
                    }
                }, null))
                .pipe(gulp.dest(upath.dirname(task.files.dest)));
        });
    });
};

function convertLoader(loader) {
    loader.test = new RegExp(loader.test);
    if(loader.exclude) {
        loader.exclude = new RegExp(loader.exclude);
    }
    if (loader.agency) {
        if (loader.agency.customs) {
            loader.agency.customs.forEach(function(custom) {
                require(custom);
            });
        }
    }
    return loader;
}
<|endoftext|>


<commit_before>function start() {
	console.log("Request handler 'start' was called.");
}

function upload() {
	console.log("Request handler 'upload' was called.");
}

exports.start = start;
exports.upload = upload;
<commit_msg>Deal with `response` in `requestHandlers`<commit_after>var exec = require("child_process").exec;

function start(response) {
	console.log("Request handler 'start' was called.");

	exec(
		"ls -lah",
		function (error, stdout, stderr) {
			response.writeHead(200, {"Content-Type": "text/plain"});
			response.write(stdout);
			response.end();
		}
	);
}

function upload(response) {
	console.log("Request handler 'upload' was called.");
	response.writeHead(200, {"Content-Type": "text/plain"});
	response.write("Hello Upload");
	response.end();
}

exports.start = start;
exports.upload = upload;
<|endoftext|>