<commit_before>import _ from 'lodash';
import pubsub from 'pubsub-js';
import rangeCheck from 'range_check';
import serialport from 'serialport';
import socketIO from 'socket.io';
import store from './store';
import log from './lib/log';
import settings from './config/settings';
import GrblController from './controllers/grbl';

const ALLOWED_IP_RANGES = [
    // IPv4 reserved space
    '10.0.0.0/8', // Used for local communications within a private network
    '127.0.0.0/8', // Used for loopback addresses to the local host
    '172.16.0.0/12', // Used for local communications within a private network
    '192.168.0.0/16', // Used for local communications within a private network

    // IPv4 mapped IPv6 address
    '::ffff:10.0.0.0/8',
    '::ffff:127.0.0.0/8',
    '::ffff:172.16.0.0/12',
    '::ffff:192.168.0.0/16',

    // IPv6 reserved space
    '::1/128', // loopback address to the local host
    'fc00::/7', // Unique local address
    'fe80::/10' // Link-local address
];

pubsub.subscribe('gcode:upload', (msg, data) => {
    let { port, meta, gcode } = data;
    let { name = '', size = 0 } = meta;
    let controller = store.get('controllers["' + port + '"]');

    if (!controller) {
        log.error('[cncserver] Controller not found:', { meta: meta });
        return;
    }

    // Load G-code
    let socket = null;
    controller.command(socket, 'load', name, gcode, (err) => {
        if (err) {
            log.error('[cncserver] Failed to load G-code: name="%s":', name, err);
        }
    });
});

class CNCServer {
    server = null;
    sockets = [];
    controllers = store.get('controllers');

    constructor(server) {
        this.server = server;

        store.on('change', (state) => {
            log.debug('[cncserver] store.on("change"):', state);
            this.controllers = _.get(state, 'controllers', {});
        });
    }
    start() {
        let io = socketIO(this.server, {
            serveClient: true,
            path: '/socket.io'
        });

        io.use((socket, next) => {
            let address = socket.handshake.address;
            let allowed = _.some(ALLOWED_IP_RANGES, (range) => {
                return rangeCheck.inRange(address, range);
            });

            if (!allowed) {
                log.warn('[cncserver] Reject connection from %s', address);
                next(new Error('You are not allowed on this server!'));
                return;
            }

            next();
        });

        io.on('connection', (socket) => {
            let address = socket.handshake.address;
            log.debug('[cncserver] New connection from %s', address);

            // Add to the socket pool
            this.sockets.push(socket);

            socket.on('disconnect', () => {
                log.debug('[cncserver] socket.on("%s"):', 'disconnect', { id: socket.id });

                _.each(this.controllers, (controller, port) => {
                    if (!controller) {
                        return;
                    }
                    controller.removeConnection(socket);
                });

                // Remove from the socket pool
                this.sockets.splice(this.sockets.indexOf(socket), 1);
            });

            // Show available serial ports
            socket.on('list', () => {
                log.debug('[cncserver] socket.on("%s"):', 'list', { id: socket.id });

                serialport.list((err, ports) => {
                    if (err) {
                        log.error(err);
                        return;
                    }

                    ports = ports.concat(_.get(settings, 'cnc.ports') || []);

                    let portsInUse = _(this.controllers)
                        .filter((controller) => {
                            return controller && controller.isOpen();
                        })
                        .map((controller) => {
                            return controller.port;
                        })
                        .value();

                    ports = _.map(ports, (port) => {
                        return {
                            port: port.comName,
                            manufacturer: port.manufacturer,
                            inuse: _.includes(portsInUse, port.comName) ? true : false
                        };
                    });

                    log.debug('[cncserver] serialport.list():', ports);
                    socket.emit('serialport:list', ports);
                });
            });

            // Open serial port
            socket.on('open', (port, baudrate) => {
                log.debug('[cncserver] socket.on("%s"):', 'open', { id: socket.id, port: port, baudrate: baudrate });

                let controller = this.controllers[port];
                if (!controller) {
                    controller = new GrblController(port, baudrate);
                }

                if (controller.isOpen()) {
                    controller.addConnection(socket);
                    socket.emit('serialport:open', {
                        port: port,
                        baudrate: baudrate,
                        inuse: true
                    });
                    return;
                }

                controller.open((err) => {
                    if (err) {
                        log.error('[cncserver] Error opening serial port "%s":', port, err);
                        socket.emit('serialport:error', { port: port });
                        return;
                    }

                    // It should default to an undefined value
                    console.assert(_.isUndefined(this.controllers[port]));
                    store.set('controllers["' + port + '"]', controller);

                    controller.addConnection(socket);
                    socket.emit('serialport:open', {
                        port: port,
                        baudrate: baudrate,
                        inuse: true
                    });
                });
            });

            // Close serial port
            socket.on('close', (port) => {
                log.debug('[cncserver] socket.on("%s"):', 'close', { id: socket.id, port: port });

                let controller = this.controllers[port];
                if (!controller) {
                    log.error('[cncserver] Serial port "%s" not accessible', port);
                    return;
                }

                controller.close((err) => {
                    if (err) {
                        log.error('[cncserver] Error closing serial port "%s":', port, err);
                    }
                    store.unset('controllers["' + port + '"]');
                });
            });

            socket.on('command', (port, cmd) => {
                log.debug('[cncserver] socket.on("%s"):', 'command', { id: socket.id, port: port, cmd: cmd });

                let controller = this.controllers[port];
                if (!controller || controller.isClose()) {
                    log.error('[cncserver] Serial port "%s" not accessible', port);
                    return;
                }

                controller.command(socket, cmd);
            });

            socket.on('write', (port, data) => {
                log.debug('[cncserver] socket.on("%s"):', 'write', { id: socket.id, port: port, data: data });

                let controller = this.controllers[port];
                if (!controller || controller.isClose()) {
                    log.error('[cncserver] Serial port "%s" not accessible', port);
                    return;
                }

                controller.write(socket, data);
            });
        });
    }
    stop() {
    }
}

const serverMain = (server) => {
    let cncServer = new CNCServer(server);
    cncServer.start();
};

module.exports = serverMain;
<commit_msg>Refine debug logs<commit_after>import _ from 'lodash';
import pubsub from 'pubsub-js';
import rangeCheck from 'range_check';
import serialport from 'serialport';
import socketIO from 'socket.io';
import store from './store';
import log from './lib/log';
import settings from './config/settings';
import GrblController from './controllers/grbl';

const ALLOWED_IP_RANGES = [
    // IPv4 reserved space
    '10.0.0.0/8', // Used for local communications within a private network
    '127.0.0.0/8', // Used for loopback addresses to the local host
    '172.16.0.0/12', // Used for local communications within a private network
    '192.168.0.0/16', // Used for local communications within a private network

    // IPv4 mapped IPv6 address
    '::ffff:10.0.0.0/8',
    '::ffff:127.0.0.0/8',
    '::ffff:172.16.0.0/12',
    '::ffff:192.168.0.0/16',

    // IPv6 reserved space
    '::1/128', // loopback address to the local host
    'fc00::/7', // Unique local address
    'fe80::/10' // Link-local address
];

pubsub.subscribe('gcode:upload', (msg, data) => {
    let { port, meta, gcode } = data;
    let { name = '', size = 0 } = meta;
    let controller = store.get('controllers["' + port + '"]');

    if (!controller) {
        log.error('[cncserver] Controller not found:', { meta: meta });
        return;
    }

    // Load G-code
    let socket = null;
    controller.command(socket, 'load', name, gcode, (err) => {
        if (err) {
            log.error('[cncserver] Failed to load G-code: name="%s":', name, err);
        }
    });
});

class CNCServer {
    server = null;
    sockets = [];
    controllers = store.get('controllers');

    constructor(server) {
        this.server = server;

        store.on('change', (state) => {
            log.debug('[cncserver] Update controllers:', state);
            this.controllers = _.get(state, 'controllers', {});
        });
    }
    start() {
        let io = socketIO(this.server, {
            serveClient: true,
            path: '/socket.io'
        });

        io.use((socket, next) => {
            let address = socket.handshake.address;
            let allowed = _.some(ALLOWED_IP_RANGES, (range) => {
                return rangeCheck.inRange(address, range);
            });

            if (!allowed) {
                log.warn('[cncserver] Reject connection from %s', address);
                next(new Error('You are not allowed on this server!'));
                return;
            }

            next();
        });

        io.on('connection', (socket) => {
            let address = socket.handshake.address;
            log.debug('[cncserver] New connection from %s:', address, { id: socket.id });

            // Add to the socket pool
            this.sockets.push(socket);

            socket.on('disconnect', () => {
                log.debug('[cncserver] socket.disconnect():', { id: socket.id });

                _.each(this.controllers, (controller, port) => {
                    if (!controller) {
                        return;
                    }
                    controller.removeConnection(socket);
                });

                // Remove from the socket pool
                this.sockets.splice(this.sockets.indexOf(socket), 1);
            });

            // Show available serial ports
            socket.on('list', () => {
                log.debug('[cncserver] socket.list():', { id: socket.id });

                serialport.list((err, ports) => {
                    if (err) {
                        log.error(err);
                        return;
                    }

                    ports = ports.concat(_.get(settings, 'cnc.ports') || []);

                    let portsInUse = _(this.controllers)
                        .filter((controller) => {
                            return controller && controller.isOpen();
                        })
                        .map((controller) => {
                            return controller.port;
                        })
                        .value();

                    ports = _.map(ports, (port) => {
                        return {
                            port: port.comName,
                            manufacturer: port.manufacturer,
                            inuse: _.includes(portsInUse, port.comName) ? true : false
                        };
                    });

                    socket.emit('serialport:list', ports);
                });
            });

            // Open serial port
            socket.on('open', (port, baudrate) => {
                log.debug('[cncserver] socket.open("%s", %d):', port, baudrate, { id: socket.id });

                let controller = this.controllers[port];
                if (!controller) {
                    controller = new GrblController(port, baudrate);
                }

                if (controller.isOpen()) {
                    controller.addConnection(socket);
                    socket.emit('serialport:open', {
                        port: port,
                        baudrate: baudrate,
                        inuse: true
                    });
                    return;
                }

                controller.open((err) => {
                    if (err) {
                        log.error('[cncserver] Error opening serial port "%s":', port, err);
                        socket.emit('serialport:error', { port: port });
                        return;
                    }

                    // It should default to an undefined value
                    console.assert(_.isUndefined(this.controllers[port]));
                    store.set('controllers["' + port + '"]', controller);

                    controller.addConnection(socket);
                    socket.emit('serialport:open', {
                        port: port,
                        baudrate: baudrate,
                        inuse: true
                    });
                });
            });

            // Close serial port
            socket.on('close', (port) => {
                log.debug('[cncserver] socket.close("%s"):', port, { id: socket.id });

                let controller = this.controllers[port];
                if (!controller) {
                    log.error('[cncserver] Serial port "%s" not accessible', port);
                    return;
                }

                controller.close((err) => {
                    if (err) {
                        log.error('[cncserver] Error closing serial port "%s":', port, err);
                    }
                    store.unset('controllers["' + port + '"]');
                });
            });

            socket.on('command', (port, cmd) => {
                log.debug('[cncserver] socket.command("%s", "%s"):', port, cmd, { id: socket.id });

                let controller = this.controllers[port];
                if (!controller || controller.isClose()) {
                    log.error('[cncserver] Serial port "%s" not accessible', port);
                    return;
                }

                controller.command(socket, cmd);
            });

            socket.on('write', (port, data) => {
                log.debug('[cncserver] socket.write("%s", "%s"):', port, data, { id: socket.id });

                let controller = this.controllers[port];
                if (!controller || controller.isClose()) {
                    log.error('[cncserver] Serial port "%s" not accessible', port);
                    return;
                }

                controller.write(socket, data);
            });
        });
    }
    stop() {
    }
}

const serverMain = (server) => {
    let cncServer = new CNCServer(server);
    cncServer.start();
};

module.exports = serverMain;
<|endoftext|>


<commit_before>$(document).ready(function() {
    //turn the select options into select2
    $(".data-store-select").each(function() {
        $(this).select2();
    });
    $(".geoserver-select").each(function() {
        $(this).select2();
    });
    //manage on change event
    $(".geoserver-select").change(function() {
        var geoserver_id = $(this).val();
        if(geoserver_id == 1) {
            $(this).parent().parent().find('.drainage-line-kml')
                    .removeAttr('contenteditable')
                    .html('
' +
                            '<input class="drainage-line-kml-upload-input" name="drainage-line-kml-upload-input" type="file" accept="*.kml">' +
                            '
Must select file to submit!
' +
                         '
');
            $(this).parent().parent().find('.catchment-kml')
                    .removeAttr('contenteditable')
                    .html('
' +
                            '<input class="catchment-kml-upload-input" name="catchment-kml-upload-input" type="file" accept="*.kml">' +
                            '
Must select file to submit!
' +
                         '
');
        } else {
            var drainage_line_element = $(this).parent().parent().find('.drainage-line-kml');
            drainage_line_element.attr('contenteditable','true')
                                .text(drainage_line_element.attr('geoserver-kml-file'));
            var catchment_element = $(this).parent().parent().find('.catchment-kml');
            catchment_element.attr('contenteditable','true')
                                .text(catchment_element.attr('geoserver-kml-file'));

        }
    });
});

//handle the submit event
$('.submit-update-watershed').click(function(){
    var safe_to_submit = {val: true};
    var parent_row = $(this).parent().parent().parent();
    //check data store input
    var watershed_id = parent_row.find('.watershed-id').text();
    var watershed_name = checkTableCellInputWithError(parent_row.find('.watershed-name'),safe_to_submit);
    var subbasin_name = checkTableCellInputWithError(parent_row.find('.subbasin-name'),safe_to_submit);
    var data_store_id = checkInputWithError(parent_row.find('.data-store-select'),safe_to_submit, true, true);
    var geoserver_id = checkInputWithError(parent_row.find('.geoserver-select'),safe_to_submit, true, true);
    //check if files are uploaded or not
    if(geoserver_id==1){
        //local upload
        //upload new kml files if selected or if old does not exist

        //drainage line
        var old_drainage_line_kml = parent_row.find('.drainage-line-kml').attr('local-kml-file');
        var new_drainage_line_kml = parent_row.find('.drainage-line-kml-upload-input');
        if(new_drainage_line_kml.val() || !old_drainage_line_kml) {
            var geoserver_drainage_line_layer = checkInputWithError(new_drainage_line_kml,safe_to_submit, true);
        } else {
            var geoserver_drainage_line_layer = old_drainage_line_kml;
        }

        //catchment
        var old_catchment_kml = parent_row.find('.catchment-kml').attr('local-kml-file');
        var new_catchment_kml = parent_row.find('.catchment-kml-upload-input');
        if(new_catchment_kml.val() || !old_catchment_kml) {
            var geoserver_catchment_layer = checkInputWithError(new_catchment_kml,safe_to_submit, true);
        } else {
            var geoserver_catchment_layer = old_catchment_kml;
        }
    } else {
        //file located on geoserver
        var geoserver_drainage_line_layer = checkTableCellInputWithError(parent_row.find('.drainage-line-kml'),safe_to_submit);
        var geoserver_catchment_layer = checkTableCellInputWithError(parent_row.find('.catchment-kml'),safe_to_submit);
    }

    //submit if it form is ok
    if(safe_to_submit.val) {
        //give user information
        addInfoMessage("Submitting Data. Please Wait.");
        submit_button.text('Submitting ...');
        //update database
        if(geoserver_id==1 && (geoserver_drainage_line_layer != old_drainage_line_kml || geoserver_catchment_layer != old_catchment_kml)){
            //local upload
            var data = new FormData();
            data.append("watershed_id",watershed_id);
            data.append("watershed_name",watershed_name);
            data.append("subbasin_name",subbasin_name);
            data.append("data_store_id",data_store_id);
            data.append("geoserver_id",geoserver_id);
            data.append("geoserver_drainage_line_layer",geoserver_drainage_line_layer);
            data.append("geoserver_catchment_layer",geoserver_catchment_layer);
            //append the file if it exists
            if(geoserver_drainage_line_layer != old_drainage_line_kml) {
                data.append("drainage_line_kml_file",parent_row.find('.drainage-line-kml-upload-input')[0].files[0]);
            }
            if(geoserver_catchment_layer != old_catchment_kml) {
                data.append("catchment_kml_file",parent_row.find('.catchment-kml-upload-input')[0].files[0]);
            }
            var xhr = ajax_update_database_with_file("submit",data);
        } else {
            var data = {
                    watershed_id: watershed_id,
                    watershed_name: watershed_name,
                    subbasin_name: subbasin_name,
                    data_store_id: data_store_id,
                    geoserver_id: geoserver_id,
                    geoserver_drainage_line_layer: geoserver_drainage_line_layer,
                    geoserver_catchment_layer: geoserver_catchment_layer,
                    };

            var xhr = ajax_update_database("submit",data);
        }
        xhr.done(function(data) {
            if ('success' in data) {
                if(geoserver_id!=1) {
                    //clean up data
                    parent_row.find('.drainage-line-kml').removeAttr('local-kml-file');
                    parent_row.find('.catchment-kml').removeAttr('local-kml-file');
                }
            }
        }).always(function(){
            submit_button.html(' Update');
        });
    } else {
        addErrorMessage("Not submitted. Please fix form errors to proceed.");
    }

});

//handle the submit update event
$('.submit-delete-watershed').click(function(){
    data = {
            watershed_id: $(this).parent().parent().parent()
                            .find('.watershed-id').text(),
            };
    //update database
    deleteRowData($(this),data);
});<commit_msg>Fixed bug in file.<commit_after>$(document).ready(function() {
    //turn the select options into select2
    $(".data-store-select").each(function() {
        $(this).select2();
    });
    $(".geoserver-select").each(function() {
        $(this).select2();
    });
    //manage on change event
    $(".geoserver-select").change(function() {
        var geoserver_id = $(this).val();
        if(geoserver_id == 1) {
            $(this).parent().parent().find('.drainage-line-kml')
                    .removeAttr('contenteditable')
                    .html('
' +
                            '<input class="drainage-line-kml-upload-input" name="drainage-line-kml-upload-input" type="file" accept="*.kml">' +
                            '
Must select file to submit!
' +
                         '
');
            $(this).parent().parent().find('.catchment-kml')
                    .removeAttr('contenteditable')
                    .html('
' +
                            '<input class="catchment-kml-upload-input" name="catchment-kml-upload-input" type="file" accept="*.kml">' +
                            '
Must select file to submit!
' +
                         '
');
        } else {
            var drainage_line_element = $(this).parent().parent().find('.drainage-line-kml');
            drainage_line_element.attr('contenteditable','true')
                                .text(drainage_line_element.attr('geoserver-kml-file'));
            var catchment_element = $(this).parent().parent().find('.catchment-kml');
            catchment_element.attr('contenteditable','true')
                                .text(catchment_element.attr('geoserver-kml-file'));

        }
    });
});

//handle the submit event
$('.submit-update-watershed').click(function(){
    var safe_to_submit = {val: true};
    var parent_row = $(this).parent().parent().parent();
    //check data store input
    var watershed_id = parent_row.find('.watershed-id').text();
    var watershed_name = checkTableCellInputWithError(parent_row.find('.watershed-name'),safe_to_submit);
    var subbasin_name = checkTableCellInputWithError(parent_row.find('.subbasin-name'),safe_to_submit);
    var data_store_id = checkInputWithError(parent_row.find('.data-store-select'),safe_to_submit, true, true);
    var geoserver_id = checkInputWithError(parent_row.find('.geoserver-select'),safe_to_submit, true, true);
    //check if files are uploaded or not
    if(geoserver_id==1){
        //local upload
        //upload new kml files if selected or if old does not exist

        //drainage line
        var old_drainage_line_kml = parent_row.find('.drainage-line-kml').attr('local-kml-file');
        var new_drainage_line_kml = parent_row.find('.drainage-line-kml-upload-input');
        if(new_drainage_line_kml.val() || !old_drainage_line_kml) {
            var geoserver_drainage_line_layer = checkInputWithError(new_drainage_line_kml,safe_to_submit, true);
        } else {
            var geoserver_drainage_line_layer = old_drainage_line_kml;
        }

        //catchment
        var old_catchment_kml = parent_row.find('.catchment-kml').attr('local-kml-file');
        var new_catchment_kml = parent_row.find('.catchment-kml-upload-input');
        if(new_catchment_kml.val() || !old_catchment_kml) {
            var geoserver_catchment_layer = checkInputWithError(new_catchment_kml,safe_to_submit, true);
        } else {
            var geoserver_catchment_layer = old_catchment_kml;
        }
    } else {
        //file located on geoserver
        var geoserver_drainage_line_layer = checkTableCellInputWithError(parent_row.find('.drainage-line-kml'),safe_to_submit);
        var geoserver_catchment_layer = checkTableCellInputWithError(parent_row.find('.catchment-kml'),safe_to_submit);
    }

    //submit if it form is ok
    if(safe_to_submit.val) {
        var submit_button = $(this);
        //give user information
        addInfoMessage("Submitting Data. Please Wait.");
        submit_button.text('Submitting ...');
        //update database
        if(geoserver_id==1 && (geoserver_drainage_line_layer != old_drainage_line_kml || geoserver_catchment_layer != old_catchment_kml)){
            //local upload
            var data = new FormData();
            data.append("watershed_id",watershed_id);
            data.append("watershed_name",watershed_name);
            data.append("subbasin_name",subbasin_name);
            data.append("data_store_id",data_store_id);
            data.append("geoserver_id",geoserver_id);
            data.append("geoserver_drainage_line_layer",geoserver_drainage_line_layer);
            data.append("geoserver_catchment_layer",geoserver_catchment_layer);
            //append the file if it exists
            if(geoserver_drainage_line_layer != old_drainage_line_kml) {
                data.append("drainage_line_kml_file",parent_row.find('.drainage-line-kml-upload-input')[0].files[0]);
            }
            if(geoserver_catchment_layer != old_catchment_kml) {
                data.append("catchment_kml_file",parent_row.find('.catchment-kml-upload-input')[0].files[0]);
            }
            var xhr = ajax_update_database_with_file("submit",data);
        } else {
            var data = {
                    watershed_id: watershed_id,
                    watershed_name: watershed_name,
                    subbasin_name: subbasin_name,
                    data_store_id: data_store_id,
                    geoserver_id: geoserver_id,
                    geoserver_drainage_line_layer: geoserver_drainage_line_layer,
                    geoserver_catchment_layer: geoserver_catchment_layer,
                    };

            var xhr = ajax_update_database("submit",data);
        }
        xhr.done(function(data) {
            if ('success' in data) {
                if(geoserver_id!=1) {
                    //clean up data
                    parent_row.find('.drainage-line-kml').removeAttr('local-kml-file');
                    parent_row.find('.catchment-kml').removeAttr('local-kml-file');
                }
            }
        }).always(function(){
            submit_button.html(' Update');
        });
    } else {
        addErrorMessage("Not submitted. Please fix form errors to proceed.");
    }

});

//handle the submit update event
$('.submit-delete-watershed').click(function(){
    data = {
            watershed_id: $(this).parent().parent().parent()
                            .find('.watershed-id').text(),
            };
    //update database
    deleteRowData($(this),data);
});<|endoftext|>


<commit_before>"use strict";

function HttpRequestError(message) {
  this.message = 'HttpRequest Error: ' + (message || '');
}
HttpRequestError.prototype = new Error();
HttpRequestError.prototype.name = "HttpRequest Error";

function HttpRequest(createXhr) {
  if (!isFunction(createXhr)) {
    throw new HttpRequestError('Missing XMLHttpRequest factory method');
  }

  this.createXhr = createXhr;
}

HttpRequest.prototype.run = function (method, url, callback, options) {
  sanityCheck(url, callback, options);
  var timeout, timeoutId;
  var xhr = this.createXhr();
  options = options || {};
  timeout = isNumber(options.timeout) ? options.timeout : 0;

  xhr.open(method, urlParts(url).href, true);

  if (options.headers) {
    setHeaders(xhr, options.headers);
  }

  if (options.withCredentials) {
    xhr.withCredentials = true;
  }

  xhr.onload = function () {
    var statusText, response, status;

    /**
     * The only way to do a secure request on IE8 and IE9 is with the XDomainRequest object. Unfortunately, microsoft is
     * so nice that decided that the status property and the 'getAllResponseHeaders' method where not needed so we have to
     * fake them. If the request gets done with an XDomainRequest instance, we will assume that there are no headers and
     * the status will always be 200. If you don't like it, DO NOT USE ANCIENT BROWSERS!!!
     *
     * For mor info go to: https://msdn.microsoft.com/en-us/library/cc288060(v=vs.85).aspx
     */
    if (!xhr.getAllResponseHeaders) {
      xhr.getAllResponseHeaders = function () {
        return null;
      }
    }

    if (!xhr.status) {
      xhr.status = 200;
    }

    if (isDefined(timeoutId)) {
      clearTimeout(timeoutId);
      timeoutId = undefined;
    }

    statusText = xhr.statusText || '';

    // responseText is the old-school way of retrieving response (supported by IE8 & 9)
    // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
    response = ('response' in xhr) ? xhr.response : xhr.responseText;

    // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
    status = xhr.status === 1223 ? 204 : xhr.status;

    callback(
      status,
      response,
      xhr.getAllResponseHeaders(),
      statusText);
  };

  xhr.onerror = requestError;
  xhr.onabort = requestError;

  xhr.send();

  if (timeout > 0) {
    timeoutId = setTimeout(function () {
      xhr && xhr.abort();
    }, timeout);
  }

  function sanityCheck(url, callback, options) {
    if (!isString(url) || isEmptyString(url)) {
      throw new HttpRequestError("Invalid url '" + url + "'");
    }

    if (!isFunction(callback)) {
      throw new HttpRequestError("Invalid handler '" + callback + "' for the http request");
    }

    if (isDefined(options) && !isObject(options)) {
      throw new HttpRequestError("Invalid options map '" + options + "'");
    }
  }

  function setHeaders(xhr, headers) {
    forEach(headers, function (value, key) {
      if (isDefined(value)) {
        xhr.setRequestHeader(key, value);
      }
    });
  }

  function requestError() {
    callback(-1, null, null, '');
  }
};

HttpRequest.prototype.get = function (url, callback, options) {
  this.run('GET', url, processResponse, options);

  function processResponse(status, response, headersString, statusText) {
    if (isSuccess(status)) {
      callback(null, response, status, headersString, statusText);
    } else {
      callback(new HttpRequestError(statusText), response, status, headersString, statusText);
    }
  }

  function isSuccess(status) {
    return 200 <= status && status < 300;
  }
};

function createXhr() {
  var xhr = new XMLHttpRequest();
  if (!("withCredentials" in xhr)) {
    // XDomainRequest for IE.
    xhr = new XDomainRequest();
  }
  return xhr;
}

var http = new HttpRequest(createXhr);
<commit_msg>[Luis] fix comma<commit_after>"use strict";

function HttpRequestError(message) {
  this.message = 'HttpRequest Error: ' + (message || '');
}
HttpRequestError.prototype = new Error();
HttpRequestError.prototype.name = "HttpRequest Error";

function HttpRequest(createXhr) {
  if (!isFunction(createXhr)) {
    throw new HttpRequestError('Missing XMLHttpRequest factory method');
  }

  this.createXhr = createXhr;
}

HttpRequest.prototype.run = function (method, url, callback, options) {
  sanityCheck(url, callback, options);
  var timeout, timeoutId;
  var xhr = this.createXhr();
  options = options || {};
  timeout = isNumber(options.timeout) ? options.timeout : 0;

  xhr.open(method, urlParts(url).href, true);

  if (options.headers) {
    setHeaders(xhr, options.headers);
  }

  if (options.withCredentials) {
    xhr.withCredentials = true;
  }

  xhr.onload = function () {
    var statusText, response, status;

    /**
     * The only way to do a secure request on IE8 and IE9 is with the XDomainRequest object. Unfortunately, microsoft is
     * so nice that decided that the status property and the 'getAllResponseHeaders' method where not needed so we have to
     * fake them. If the request gets done with an XDomainRequest instance, we will assume that there are no headers and
     * the status will always be 200. If you don't like it, DO NOT USE ANCIENT BROWSERS!!!
     *
     * For mor info go to: https://msdn.microsoft.com/en-us/library/cc288060(v=vs.85).aspx
     */
    if (!xhr.getAllResponseHeaders) {
      xhr.getAllResponseHeaders = function () {
        return null;
      };
    }

    if (!xhr.status) {
      xhr.status = 200;
    }

    if (isDefined(timeoutId)) {
      clearTimeout(timeoutId);
      timeoutId = undefined;
    }

    statusText = xhr.statusText || '';

    // responseText is the old-school way of retrieving response (supported by IE8 & 9)
    // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
    response = ('response' in xhr) ? xhr.response : xhr.responseText;

    // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
    status = xhr.status === 1223 ? 204 : xhr.status;

    callback(
      status,
      response,
      xhr.getAllResponseHeaders(),
      statusText);
  };

  xhr.onerror = requestError;
  xhr.onabort = requestError;

  xhr.send();

  if (timeout > 0) {
    timeoutId = setTimeout(function () {
      xhr && xhr.abort();
    }, timeout);
  }

  function sanityCheck(url, callback, options) {
    if (!isString(url) || isEmptyString(url)) {
      throw new HttpRequestError("Invalid url '" + url + "'");
    }

    if (!isFunction(callback)) {
      throw new HttpRequestError("Invalid handler '" + callback + "' for the http request");
    }

    if (isDefined(options) && !isObject(options)) {
      throw new HttpRequestError("Invalid options map '" + options + "'");
    }
  }

  function setHeaders(xhr, headers) {
    forEach(headers, function (value, key) {
      if (isDefined(value)) {
        xhr.setRequestHeader(key, value);
      }
    });
  }

  function requestError() {
    callback(-1, null, null, '');
  }
};

HttpRequest.prototype.get = function (url, callback, options) {
  this.run('GET', url, processResponse, options);

  function processResponse(status, response, headersString, statusText) {
    if (isSuccess(status)) {
      callback(null, response, status, headersString, statusText);
    } else {
      callback(new HttpRequestError(statusText), response, status, headersString, statusText);
    }
  }

  function isSuccess(status) {
    return 200 <= status && status < 300;
  }
};

function createXhr() {
  var xhr = new XMLHttpRequest();
  if (!("withCredentials" in xhr)) {
    // XDomainRequest for IE.
    xhr = new XDomainRequest();
  }
  return xhr;
}

var http = new HttpRequest(createXhr);
<|endoftext|>


<commit_before>
var app=angular.module('myApp',[]);
app.controller('myCtrl',function($scope,$http,$q) {
  var svg;
  //6ad0a82c922020a5d1750918d4e2f1120ad9f9bb
  function f1(){
    var margin = {top: 100, right: 100, bottom: 100, left: 100},
    width = 960 - margin.left - margin.right,
    height = 300 - margin.top - margin.bottom;

    var x = d3.scale.linear()
    .domain([0, 5.9])
    .range([0, width]);

    var y = d3.scale.linear()
    .domain([-1, 1])
    .range([height, 0]);

    var z = d3.scale.linear()
    .domain([0, 5.9])
    .range([0, 360]);

    var points = d3.range(0, 6, .1).map(function(t) {
      return {value: t, 0: x(t), 1: y(Math.sin(t))};
    });

    svg = d3.select("#waver").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var path = svg.selectAll("path")
    .data(quad(points))
    .enter().append("path")
    .style("fill", function(d) { return d3.hsl(z(d[1].value), 1, .5); })
    .style("stroke", "#000");

    var t0 = Date.now();
    d3.timer(function() {
      var dt = (Date.now() - t0) * .001;
      points.forEach(function(d) { d[1] = y(d.scale = Math.sin(d.value + dt)); });
      path.attr("d", function(d) { return lineJoin(d[0], d[1], d[2], d[3], 80 * d[1].scale * d[1].scale + 10); });
    });

// Compute quads of adjacent points [p0, p1, p2, p3].
function quad(points) {
  return d3.range(points.length - 1).map(function(i) {
    return [points[i - 1], points[i], points[i + 1], points[i + 2]];
  });
}

// Compute stroke outline for segment p12.
function lineJoin(p0, p1, p2, p3, width) {
  var u12 = perp(p1, p2),
  r = width / 2,
  a = [p1[0] + u12[0] * r, p1[1] + u12[1] * r],
  b = [p2[0] + u12[0] * r, p2[1] + u12[1] * r],
  c = [p2[0] - u12[0] * r, p2[1] - u12[1] * r],
  d = [p1[0] - u12[0] * r, p1[1] - u12[1] * r];

  if (p0) { // clip ad and dc using average of u01 and u12
    var u01 = perp(p0, p1), e = [p1[0] + u01[0] + u12[0], p1[1] + u01[1] + u12[1]];
    a = lineIntersect(p1, e, a, b);
    d = lineIntersect(p1, e, d, c);
  }

  if (p3) { // clip ab and dc using average of u12 and u23
    var u23 = perp(p2, p3), e = [p2[0] + u23[0] + u12[0], p2[1] + u23[1] + u12[1]];
    b = lineIntersect(p2, e, a, b);
    c = lineIntersect(p2, e, d, c);
  }

  return "M" + a + "L" + b + " " + c + " " + d + "Z";
}

// Compute intersection of two infinite lines ab and cd.
function lineIntersect(a, b, c, d) {
  var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3,
  y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3,
  ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21);
  return [x1 + ua * x21, y1 + ua * y21];
}

// Compute unit vector perpendicular to p01.
function perp(p0, p1) {
  var u01x = p0[1] - p1[1], u01y = p1[0] - p0[0],
  u01d = Math.sqrt(u01x * u01x + u01y * u01y);
  return [u01x / u01d, u01y / u01d];
}

}
f1();

function f2(){
  var width = 960,
  height = 500,
  radius = 80,
  x = Math.sin(2 * Math.PI / 3),
  y = Math.cos(2 * Math.PI / 3);

  var offset = 0,
  speed = 4,
  start = Date.now();

  var svg = d3.select("#loader").append("svg")
  .attr("width", width)
  .attr("height", height)
  .append("g")
  .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(.55)")
  .append("g");

  var frame = svg.append("g")
  .datum({radius: Infinity});

  frame.append("g")
  .attr("class", "annulus")
  .datum({teeth: 80, radius: -radius * 5, annulus: true})
  .append("path")
  .attr("d", gear);

  frame.append("g")
  .attr("class", "sun")
  .datum({teeth: 16, radius: radius})
  .append("path")
  .attr("d", gear);

  frame.append("g")
  .attr("class", "planet")
  .attr("transform", "translate(0,-" + radius * 3 + ")")
  .datum({teeth: 32, radius: -radius * 2})
  .append("path")
  .attr("d", gear);

  frame.append("g")
  .attr("class", "planet")
  .attr("transform", "translate(" + -radius * 3 * x + "," + -radius * 3 * y + ")")
  .datum({teeth: 32, radius: -radius * 2})
  .append("path")
  .attr("d", gear);

  frame.append("g")
  .attr("class", "planet")
  .attr("transform", "translate(" + radius * 3 * x + "," + -radius * 3 * y + ")")
  .datum({teeth: 32, radius: -radius * 2})
  .append("path")
  .attr("d", gear);

  d3.selectAll("input[name=reference]")
  .data([radius * 5, Infinity, -radius])
  .on("change", function(radius1) {
    var radius0 = frame.datum().radius, angle = (Date.now() - start) * speed;
    frame.datum({radius: radius1});
    svg.attr("transform", "rotate(" + (offset += angle / radius0 - angle / radius1) + ")");
  });

  d3.selectAll("input[name=speed]")
  .on("change", function() { speed = +this.value; });

  function gear(d) {
    var n = d.teeth,
    r2 = Math.abs(d.radius),
    r0 = r2 - 8,
    r1 = r2 + 8,
    r3 = d.annulus ? (r3 = r0, r0 = r1, r1 = r3, r2 + 20) : 20,
    da = Math.PI / n,
    a0 = -Math.PI / 2 + (d.annulus ? Math.PI / n : 0),
    i = -1,
    path = ["M", r0 * Math.cos(a0), ",", r0 * Math.sin(a0)];
    while (++i < n) path.push(
      "A", r0, ",", r0, " 0 0,1 ", r0 * Math.cos(a0 += da), ",", r0 * Math.sin(a0),
      "L", r2 * Math.cos(a0), ",", r2 * Math.sin(a0),
      "L", r1 * Math.cos(a0 += da / 3), ",", r1 * Math.sin(a0),
      "A", r1, ",", r1, " 0 0,1 ", r1 * Math.cos(a0 += da / 3), ",", r1 * Math.sin(a0),
      "L", r2 * Math.cos(a0 += da / 3), ",", r2 * Math.sin(a0),
      "L", r0 * Math.cos(a0), ",", r0 * Math.sin(a0));
      path.push("M0,", -r3, "A", r3, ",", r3, " 0 0,0 0,", r3, "A", r3, ",", r3, " 0 0,0 0,", -r3, "Z");
    return path.join("");
  }

  d3.timer(function() {
    var angle = (Date.now() - start) * speed,
    transform = function(d) { return "rotate(" + angle / d.radius + ")"; };
    frame.selectAll("path").attr("transform", transform);
  frame.attr("transform", transform); // frame of reference
});

}
f2();

$http.get('https://api.github.com/users/darshanhs90/repos')
.success(function(data, status, headers, config) {
  console.log(data);
  var languages={};
  languages['Java']=0;
  languages['HTML']=0;
  languages['CSS']=0;
  languages['JavaScript']=0;
  languages['Arduino']=0;
  languages['C']=0;

  $scope.myXhr = function(i1){

    var deferred = $q.defer();
    $http({
      url: data[i1].languages_url
    })
        //if request is successful
        .success(function(data,status,headers,config){
            if(data.message!=undefined && data.message.indexof('API rate limit exceeded')!=-1)
            {
              alert('exceeded Maximum Requests,Try Again Later');
              throw new Error("Something went badly wrong!");
            }
            //resolve the promise
            if(data.Java!=undefined)
              languages['Java']+=1;
            if(data.HTML!=undefined)
              languages['HTML']+=1;
            if(data.CSS!=undefined)
              languages['CSS']+=1;
            if(data.JavaScript!=undefined)
              languages['JavaScript']+=1;
            if(data.Arduino!=undefined)
              languages['Arduino']+=1;
            if(data.C!=undefined)
              languages['C']+=1;

            deferred.resolve('request successful');

          })
        //if request is not successful
        .error(function(data,status,headers,config){
            //reject the promise
            deferred.reject('ERROR');
          });

    //return the promise
    return deferred.promise;
  }

  $scope.callXhrAsynchronous = function(i1){

    var myPromise = $scope.myXhr(i1);

    // wait until the promise return resolve or eject
    //"then" has 2 functions (resolveFunction, rejectFunction)
    myPromise.then(function(resolve){
      if(i1==data.length-1)
      {
       Morris.Donut({
        element: 'donut-example',
        data: [
        {label: "Java", value: languages['Java']},
        {label: "HTML", value: languages['HTML']},
        {label: "JavaScript", value: languages['JavaScript']},
        {label: "CSS", value: languages['CSS']},
        {label: "C", value: languages['C']},
        {label: "Arduino", value: languages['Arduino']}
        ]
      });
       $('#loader').css('visibility','hidden');
       $('#loader').css('height','0px');

       $('#areas').css('visibility','visible');
       $('#areas').css('height','250px');
     }

   }, function(reject){
    alert(reject)
  });

  }

  for (var i = 0; i <data.length; i++) {
   $scope.callXhrAsynchronous(i);
 };
$scope.arryear=[];
$scope.arrcommit=[];

 $scope.myXhr1 = function(i1){

  var deferred = $q.defer();
  str=data[i1].commits_url
  $http({
    url: str.substring(0,str.length-6)
  })
        //if request is successful
        .success(function(data1,status,headers,config){

            //resolve the promise
            console.log(data1);
            date1=data[i1].created_at;
            $scope.arryear[i1]=date1.substring(0,10);
            $scope.arrcommit[i1]=data1.length;
            console.log(data[i1].created_at);
            console.log(data1.length);

            deferred.resolve('request successful');

          })
        //if request is not successful
        .error(function(data,status,headers,config){
            //reject the promise
            deferred.reject('ERROR');
          });

    //return the promise
    return deferred.promise;
  }

  $scope.callXhrAsynchronous1 = function(i1){

    var myPromise = $scope.myXhr1(i1);

    // wait until the promise return resolve or eject
    //"then" has 2 functions (resolveFunction, rejectFunction)
    myPromise.then(function(resolve){
      if(i1==data.length-2)
      {

        var myData = [];
for (var index = 0; index <data.length-1; index++) {
  var obj = {
        year:$scope.arryear[index],
      commits:$scope.arrcommit[index],

    };
    myData.push(obj);
}

        new Morris.Line({
  // ID of the element in which to draw the chart.
  element: 'myfirstchart',
  // Chart data records -- each entry in this array corresponds to a point on
  // the chart.
  data: myData,
  // The name of the data record attribute that contains x-values.
  xkey: 'year',
  // A list of names of data record attributes that contain y-values.
  ykeys: ['commits'],
  // Labels for the ykeys -- will be displayed when you hover over the
  // chart.
  labels: ['Commits']
});
        $('#waver').css('visibility','hidden');
        $('#waver').css('height','0px');

        $('#contributions').css('visibility','visible');
        $('#contributions').css('height','250px');
      }

    }, function(reject){
      //alert(reject)
    });

  }

  for (var i = 0; i <data.length-1; i++) {
   $scope.callXhrAsynchronous1(i);

 };

});

// });

});<commit_msg>error tracking added<commit_after>
var app=angular.module('myApp',[]);
app.controller('myCtrl',function($scope,$http,$q) {
  var svg;
  //6ad0a82c922020a5d1750918d4e2f1120ad9f9bb
  function f1(){
    var margin = {top: 100, right: 100, bottom: 100, left: 100},
    width = 960 - margin.left - margin.right,
    height = 300 - margin.top - margin.bottom;

    var x = d3.scale.linear()
    .domain([0, 5.9])
    .range([0, width]);

    var y = d3.scale.linear()
    .domain([-1, 1])
    .range([height, 0]);

    var z = d3.scale.linear()
    .domain([0, 5.9])
    .range([0, 360]);

    var points = d3.range(0, 6, .1).map(function(t) {
      return {value: t, 0: x(t), 1: y(Math.sin(t))};
    });

    svg = d3.select("#waver").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var path = svg.selectAll("path")
    .data(quad(points))
    .enter().append("path")
    .style("fill", function(d) { return d3.hsl(z(d[1].value), 1, .5); })
    .style("stroke", "#000");

    var t0 = Date.now();
    d3.timer(function() {
      var dt = (Date.now() - t0) * .001;
      points.forEach(function(d) { d[1] = y(d.scale = Math.sin(d.value + dt)); });
      path.attr("d", function(d) { return lineJoin(d[0], d[1], d[2], d[3], 80 * d[1].scale * d[1].scale + 10); });
    });

// Compute quads of adjacent points [p0, p1, p2, p3].
function quad(points) {
  return d3.range(points.length - 1).map(function(i) {
    return [points[i - 1], points[i], points[i + 1], points[i + 2]];
  });
}

// Compute stroke outline for segment p12.
function lineJoin(p0, p1, p2, p3, width) {
  var u12 = perp(p1, p2),
  r = width / 2,
  a = [p1[0] + u12[0] * r, p1[1] + u12[1] * r],
  b = [p2[0] + u12[0] * r, p2[1] + u12[1] * r],
  c = [p2[0] - u12[0] * r, p2[1] - u12[1] * r],
  d = [p1[0] - u12[0] * r, p1[1] - u12[1] * r];

  if (p0) { // clip ad and dc using average of u01 and u12
    var u01 = perp(p0, p1), e = [p1[0] + u01[0] + u12[0], p1[1] + u01[1] + u12[1]];
    a = lineIntersect(p1, e, a, b);
    d = lineIntersect(p1, e, d, c);
  }

  if (p3) { // clip ab and dc using average of u12 and u23
    var u23 = perp(p2, p3), e = [p2[0] + u23[0] + u12[0], p2[1] + u23[1] + u12[1]];
    b = lineIntersect(p2, e, a, b);
    c = lineIntersect(p2, e, d, c);
  }

  return "M" + a + "L" + b + " " + c + " " + d + "Z";
}

// Compute intersection of two infinite lines ab and cd.
function lineIntersect(a, b, c, d) {
  var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3,
  y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3,
  ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21);
  return [x1 + ua * x21, y1 + ua * y21];
}

// Compute unit vector perpendicular to p01.
function perp(p0, p1) {
  var u01x = p0[1] - p1[1], u01y = p1[0] - p0[0],
  u01d = Math.sqrt(u01x * u01x + u01y * u01y);
  return [u01x / u01d, u01y / u01d];
}

}
f1();

function f2(){
  var width = 960,
  height = 500,
  radius = 80,
  x = Math.sin(2 * Math.PI / 3),
  y = Math.cos(2 * Math.PI / 3);

  var offset = 0,
  speed = 4,
  start = Date.now();

  var svg = d3.select("#loader").append("svg")
  .attr("width", width)
  .attr("height", height)
  .append("g")
  .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(.55)")
  .append("g");

  var frame = svg.append("g")
  .datum({radius: Infinity});

  frame.append("g")
  .attr("class", "annulus")
  .datum({teeth: 80, radius: -radius * 5, annulus: true})
  .append("path")
  .attr("d", gear);

  frame.append("g")
  .attr("class", "sun")
  .datum({teeth: 16, radius: radius})
  .append("path")
  .attr("d", gear);

  frame.append("g")
  .attr("class", "planet")
  .attr("transform", "translate(0,-" + radius * 3 + ")")
  .datum({teeth: 32, radius: -radius * 2})
  .append("path")
  .attr("d", gear);

  frame.append("g")
  .attr("class", "planet")
  .attr("transform", "translate(" + -radius * 3 * x + "," + -radius * 3 * y + ")")
  .datum({teeth: 32, radius: -radius * 2})
  .append("path")
  .attr("d", gear);

  frame.append("g")
  .attr("class", "planet")
  .attr("transform", "translate(" + radius * 3 * x + "," + -radius * 3 * y + ")")
  .datum({teeth: 32, radius: -radius * 2})
  .append("path")
  .attr("d", gear);

  d3.selectAll("input[name=reference]")
  .data([radius * 5, Infinity, -radius])
  .on("change", function(radius1) {
    var radius0 = frame.datum().radius, angle = (Date.now() - start) * speed;
    frame.datum({radius: radius1});
    svg.attr("transform", "rotate(" + (offset += angle / radius0 - angle / radius1) + ")");
  });

  d3.selectAll("input[name=speed]")
  .on("change", function() { speed = +this.value; });

  function gear(d) {
    var n = d.teeth,
    r2 = Math.abs(d.radius),
    r0 = r2 - 8,
    r1 = r2 + 8,
    r3 = d.annulus ? (r3 = r0, r0 = r1, r1 = r3, r2 + 20) : 20,
    da = Math.PI / n,
    a0 = -Math.PI / 2 + (d.annulus ? Math.PI / n : 0),
    i = -1,
    path = ["M", r0 * Math.cos(a0), ",", r0 * Math.sin(a0)];
    while (++i < n) path.push(
      "A", r0, ",", r0, " 0 0,1 ", r0 * Math.cos(a0 += da), ",", r0 * Math.sin(a0),
      "L", r2 * Math.cos(a0), ",", r2 * Math.sin(a0),
      "L", r1 * Math.cos(a0 += da / 3), ",", r1 * Math.sin(a0),
      "A", r1, ",", r1, " 0 0,1 ", r1 * Math.cos(a0 += da / 3), ",", r1 * Math.sin(a0),
      "L", r2 * Math.cos(a0 += da / 3), ",", r2 * Math.sin(a0),
      "L", r0 * Math.cos(a0), ",", r0 * Math.sin(a0));
      path.push("M0,", -r3, "A", r3, ",", r3, " 0 0,0 0,", r3, "A", r3, ",", r3, " 0 0,0 0,", -r3, "Z");
    return path.join("");
  }

  d3.timer(function() {
    var angle = (Date.now() - start) * speed,
    transform = function(d) { return "rotate(" + angle / d.radius + ")"; };
    frame.selectAll("path").attr("transform", transform);
  frame.attr("transform", transform); // frame of reference
});

}
f2();

$http.get('https://api.github.com/users/darshanhs90/repos')
.success(function(data, status, headers, config) {
  console.log(data);
  var languages={};
  languages['Java']=0;
  languages['HTML']=0;
  languages['CSS']=0;
  languages['JavaScript']=0;
  languages['Arduino']=0;
  languages['C']=0;

  $scope.myXhr = function(i1){

    var deferred = $q.defer();
    $http({
      url: data[i1].languages_url
    })
        //if request is successful
        .success(function(data,status,headers,config){
          if(data.message!=undefined && data.message.indexof('API rate limit exceeded')!=-1)
          {
            alert('exceeded Maximum Requests,Try Again Later');
            throw new Error("Something went badly wrong!");
          }
            //resolve the promise
            if(data.Java!=undefined)
              languages['Java']+=1;
            if(data.HTML!=undefined)
              languages['HTML']+=1;
            if(data.CSS!=undefined)
              languages['CSS']+=1;
            if(data.JavaScript!=undefined)
              languages['JavaScript']+=1;
            if(data.Arduino!=undefined)
              languages['Arduino']+=1;
            if(data.C!=undefined)
              languages['C']+=1;

            deferred.resolve('request successful');

          })
        //if request is not successful
        .error(function(data,status,headers,config){
            //reject the promise
            deferred.reject('ERROR');
          });

    //return the promise
    return deferred.promise;
  }

  $scope.callXhrAsynchronous = function(i1){

    var myPromise = $scope.myXhr(i1);

    // wait until the promise return resolve or eject
    //"then" has 2 functions (resolveFunction, rejectFunction)
    myPromise.then(function(resolve){
      if(i1==data.length-1)
      {
       Morris.Donut({
        element: 'donut-example',
        data: [
        {label: "Java", value: languages['Java']},
        {label: "HTML", value: languages['HTML']},
        {label: "JavaScript", value: languages['JavaScript']},
        {label: "CSS", value: languages['CSS']},
        {label: "C", value: languages['C']},
        {label: "Arduino", value: languages['Arduino']}
        ]
      });
       $('#loader').css('visibility','hidden');
       $('#loader').css('height','0px');

       $('#areas').css('visibility','visible');
       $('#areas').css('height','250px');
     }

   }, function(reject){
    alert(reject)
  });

  }

  for (var i = 0; i <data.length; i++) {
   $scope.callXhrAsynchronous(i);
 };
 $scope.arryear=[];
 $scope.arrcommit=[];

 $scope.myXhr1 = function(i1){

  var deferred = $q.defer();
  str=data[i1].commits_url
  $http({
    url: str.substring(0,str.length-6)
  })
        //if request is successful
        .success(function(data1,status,headers,config){
          if(data.message!=undefined && data.message.indexof('API rate limit exceeded')!=-1)
          {
            alert('exceeded Maximum Requests,Try Again Later');
            throw new Error("Something went badly wrong!");
          }
            //resolve the promise
            console.log(data1);
            date1=data[i1].created_at;
            $scope.arryear[i1]=date1.substring(0,10);
            $scope.arrcommit[i1]=data1.length;
            console.log(data[i1].created_at);
            console.log(data1.length);

            deferred.resolve('request successful');

          })
        //if request is not successful
        .error(function(data,status,headers,config){
            //reject the promise
            deferred.reject('ERROR');
          });

    //return the promise
    return deferred.promise;
  }

  $scope.callXhrAsynchronous1 = function(i1){

    var myPromise = $scope.myXhr1(i1);

    // wait until the promise return resolve or eject
    //"then" has 2 functions (resolveFunction, rejectFunction)
    myPromise.then(function(resolve){
      if(i1==data.length-2)
      {

        var myData = [];
        for (var index = 0; index <data.length-1; index++) {
          var obj = {
            year:$scope.arryear[index],
            commits:$scope.arrcommit[index],

          };
          myData.push(obj);
        }

        new Morris.Line({
  // ID of the element in which to draw the chart.
  element: 'myfirstchart',
  // Chart data records -- each entry in this array corresponds to a point on
  // the chart.
  data: myData,
  // The name of the data record attribute that contains x-values.
  xkey: 'year',
  // A list of names of data record attributes that contain y-values.
  ykeys: ['commits'],
  // Labels for the ykeys -- will be displayed when you hover over the
  // chart.
  labels: ['Commits']
});
        $('#waver').css('visibility','hidden');
        $('#waver').css('height','0px');

        $('#contributions').css('visibility','visible');
        $('#contributions').css('height','250px');
      }

    }, function(reject){
      //alert(reject)
    });

}

for (var i = 0; i <data.length-1; i++) {
 $scope.callXhrAsynchronous1(i);

};

});

// });

});<|endoftext|>


<commit_before>/**
 * Created by MewX on 4/22/2017.
 */

import * as React from "react";
import {ListView, StatusBar, Text, TextInput, TouchableNativeFeedback, View} from "react-native";
import {Toolbar, BottomNavigation, ThemeProvider} from 'react-native-material-ui';
import * as COLOR from "react-native-material-ui/src/styles/colors";

const uiTheme = {
    palette: {
        primaryColor: COLOR.green500,
        accentColor: COLOR.pink500,
    },
    toolbar: {
        container: {
            height: 56,
        },
    },
};

class MainActivity extends React.Component {
    static ACTIVE_ALL = 'ALL';
    static ACTIVE_PENDING = 'PENDING';
    static ACTIVE_DONE = 'DONE';

    constructor() {
        super();
        this.state = {
            ds: new ListView.DataSource({rowHasChanged: (ori, n) => ori !== n}),
            active: MainActivity.ACTIVE_ALL,
            edit: '',
            items: [
                {text: 'Done sample', done: true},
                {text: 'Pending sample', done: false}
            ]
        };

        // bindings
        // this.addNewItem = this.addNewItem.bind(this);
    }

    componentWillMount() {
    }

    render() {
        return (
            <ThemeProvider uiTheme={uiTheme}>
                <View style={{flex: 1}}>
                    {/*Interesting ways to make translucent*/}
                    <StatusBar backgroundColor="rgba(0, 0, 0, 0.2)" translucent />
                    <View style={{ backgroundColor: COLOR.green500, height: 24 }} />
                    <Toolbar
                        leftElement="menu"
                        centerElement="RN Material Todo List"
                    />

                    <TextInput
                        style={{paddingLeft: 12, paddingRight: 12, fontSize: 16, borderColor: 'grey', borderWidth: 0}}
                        onChangeText={(text) => this.setState({edit: text})}
                        placeholder="What to do?"
                        value={this.state.edit}
                        onSubmitEditing={(event) => this.addNewItem(event.nativeEvent.text)}
                    />

                    <ListView
                        style={{ flex: 1 }}
                        dataSource={this.state.ds.cloneWithRows(
                            this.state.items
                                .map(this.itemMapping.bind(this))
                                .filter(this.itemFilter.bind(this)))
                        }
                        renderRow={(rowData) => {
                            let textBgColor = rowData.done ? COLOR.grey300 : '#ffffff00';
                            let textDeco = rowData.done ? 'line-through' : 'none';
                            console.log(rowData);

                            return (<TouchableNativeFeedback
                                background={TouchableNativeFeedback.SelectableBackground()}>
                                <View style={{alignSelf: "stretch", backgroundColor: textBgColor}}>
                                    <Text
                                        style={{padding: 12, textAlign: 'left', justifyContent: 'center',
                                            fontSize: 16, textDecorationLine: textDeco}}
                                        onPress={() => this.changeItemState(rowData.id)}
                                    >{rowData.text}</Text>
                                </View>
                            </TouchableNativeFeedback>);
                        }}
                    />

                    <BottomNavigation active={this.state.active} hidden={false}>
                        <BottomNavigation.Action
                            key={MainActivity.ACTIVE_ALL}
                            icon="home"
                            label="All"
                            onPress={() => this.setState({active: MainActivity.ACTIVE_ALL})}/>
                        <BottomNavigation.Action
                            key={MainActivity.ACTIVE_PENDING}
                            icon="compare-arrows"
                            label="Pending"
                            onPress={() => this.setState({active: MainActivity.ACTIVE_PENDING})}/>
                        <BottomNavigation.Action
                            key={MainActivity.ACTIVE_DONE}
                            icon="archive"
                            label="Done"
                            onPress={() => this.setState({active: MainActivity.ACTIVE_DONE})}/>
                    </BottomNavigation>
                </View>
            </ThemeProvider>
        )
    }

    /**
     * map each item with its index
     * @param it the item
     * @param index its index
     * @returns {{text, done, id: *}}
     */
    itemMapping(it, index) {
        return {text: it.text, done: it.done, id: index};
    }

    /**
     * filter items by current active label
     * @param it the item
     * @returns {boolean}
     */
    itemFilter(it) {
        switch (this.state.active) {
            case MainActivity.ACTIVE_DONE:
                return it.done;
            case MainActivity.ACTIVE_PENDING:
                return !it.done;
            default:
                return true;
        }
    }

    addNewItem(str) {
        // pre process, and ignore empty string
        str = str.trim();
        this.setState({edit: ''});
        if (!str || !str.length) return;

        let i = this.state.items;
        i.unshift({text: str, done: false});
        this.setState({items: i});
    }

    changeItemState(id) {
        if (id === undefined) return;
        console.log("clicked: " + id);

        let i = this.state.items;
        i[id].done = !i[id].done;
        this.setState({items: i});
    }
}

module.exports = MainActivity;
<commit_msg>Fixed empty list error<commit_after>/**
 * Created by MewX on 4/22/2017.
 */

import * as React from "react";
import {ListView, StatusBar, Text, TextInput, TouchableNativeFeedback, View} from "react-native";
import {Toolbar, BottomNavigation, ThemeProvider} from 'react-native-material-ui';
import * as COLOR from "react-native-material-ui/src/styles/colors";

const uiTheme = {
    palette: {
        primaryColor: COLOR.green500,
        accentColor: COLOR.pink500,
    },
    toolbar: {
        container: {
            height: 56,
        },
    },
};

class MainActivity extends React.Component {
    static ACTIVE_ALL = 'ALL';
    static ACTIVE_PENDING = 'PENDING';
    static ACTIVE_DONE = 'DONE';

    constructor() {
        super();
        this.state = {
            ds: new ListView.DataSource({rowHasChanged: (ori, n) => ori !== n}),
            active: MainActivity.ACTIVE_ALL,
            edit: '',
            items: [
                {text: 'Done sample', done: true},
                {text: 'Pending sample', done: false}
            ]
        };

        // bindings
        // this.addNewItem = this.addNewItem.bind(this);
    }

    componentWillMount() {
    }

    render() {
        return (
            <ThemeProvider uiTheme={uiTheme}>
                <View style={{flex: 1}}>
                    {/*Interesting ways to make translucent*/}
                    <StatusBar backgroundColor="rgba(0, 0, 0, 0.2)" translucent />
                    <View style={{ backgroundColor: COLOR.green500, height: 24 }} />
                    <Toolbar
                        leftElement="menu"
                        centerElement="RN Material Todo List"
                    />

                    <TextInput
                        style={{paddingLeft: 12, paddingRight: 12, fontSize: 16, borderColor: 'grey', borderWidth: 0}}
                        onChangeText={(text) => this.setState({edit: text})}
                        placeholder="What to do?"
                        value={this.state.edit}
                        onSubmitEditing={(event) => this.addNewItem(event.nativeEvent.text)}
                    />

                    <ListView
                        enableEmptySections={true}
                        style={{flex: 1}}
                        dataSource={this.state.ds.cloneWithRows(
                            this.state.items
                                .map(this.itemMapping.bind(this))
                                .filter(this.itemFilter.bind(this)))
                        }
                        renderRow={(rowData) => {
                            let textBgColor = rowData.done ? COLOR.grey300 : '#ffffff00';
                            let textDeco = rowData.done ? 'line-through' : 'none';
                            console.log(rowData);

                            return (<TouchableNativeFeedback
                                background={TouchableNativeFeedback.SelectableBackground()}>
                                <View style={{alignSelf: "stretch", backgroundColor: textBgColor}}>
                                    <Text
                                        style={{
                                            padding: 12, textAlign: 'left', justifyContent: 'center',
                                            fontSize: 16, textDecorationLine: textDeco
                                        }}
                                        onPress={() => this.changeItemState(rowData.id)}
                                    >{rowData.text}</Text>
                                </View>
                            </TouchableNativeFeedback>);
                        }}
                    />

                    <BottomNavigation active={this.state.active} hidden={false}>
                        <BottomNavigation.Action
                            key={MainActivity.ACTIVE_ALL}
                            icon="home"
                            label="All"
                            onPress={() => this.setState({active: MainActivity.ACTIVE_ALL})}/>
                        <BottomNavigation.Action
                            key={MainActivity.ACTIVE_PENDING}
                            icon="compare-arrows"
                            label="Pending"
                            onPress={() => this.setState({active: MainActivity.ACTIVE_PENDING})}/>
                        <BottomNavigation.Action
                            key={MainActivity.ACTIVE_DONE}
                            icon="archive"
                            label="Done"
                            onPress={() => this.setState({active: MainActivity.ACTIVE_DONE})}/>
                    </BottomNavigation>
                </View>
            </ThemeProvider>
        )
    }

    /**
     * map each item with its index
     * @param it the item
     * @param index its index
     * @returns {{text, done, id: *}}
     */
    itemMapping(it, index) {
        return {text: it.text, done: it.done, id: index};
    }

    /**
     * filter items by current active label
     * @param it the item
     * @returns {boolean}
     */
    itemFilter(it) {
        switch (this.state.active) {
            case MainActivity.ACTIVE_DONE:
                return it.done;
            case MainActivity.ACTIVE_PENDING:
                return !it.done;
            default:
                return true;
        }
    }

    addNewItem(str) {
        // pre process, and ignore empty string
        str = str.trim();
        this.setState({edit: ''});
        if (!str || !str.length) return;

        let i = this.state.items;
        i.unshift({text: str, done: false});
        this.setState({items: i});
    }

    changeItemState(id) {
        if (id === undefined) return;
        console.log("clicked: " + id);

        let i = this.state.items;
        i[id].done = !i[id].done;
        this.setState({items: i});
    }
}

module.exports = MainActivity;
<|endoftext|>


<commit_before>const express = require('express');
const graphqlHTTP = require('express-graphql');

const {
    FieldValidationDefinitions,
    wrapResolvers,
    graphQLValidityMiddleware
} = require('../lib');

const schema = require('./schema');

const app = express();

function validateSomeTestThing(...args) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve([new Error('Wrong stuff here!')]);
        }, 130)
    });
}

function applyToAll(...args) {
    return [new Error('All failed!')];
}

function applyGlobally(...args) {
    return [new Error('Global failure!')];
}

function validateSomeTestMutation(...args) {
    return [new Error('testMutation failed!')];
}

function specialThird(...args) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve([new Error('Special third failed!')]);
        }, 250)
    });
}

FieldValidationDefinitions['$'] = [applyGlobally];
// FieldValidationDefinitions['*'] = [applyToAll];
FieldValidationDefinitions['Mutation:testMutation'] = [validateSomeTestMutation];
FieldValidationDefinitions['TestType'] = [validateSomeTestThing];
FieldValidationDefinitions['TestType:fourth'] = [validateSomeTestThing];
FieldValidationDefinitions['TestType:fifth'] = [validateSomeTestThing];
FieldValidationDefinitions['TestType2:first'] = [validateSomeTestThing];
FieldValidationDefinitions['TestType2:second'] = [validateSomeTestThing];
FieldValidationDefinitions['TestType2:third'] = [specialThird];

wrapResolvers(schema, {
    wrapErrors: true,
    enableProfiling: true,
    profilingResultHandler: (profilingResult) => {
        // console.log(JSON.stringify(Array.from(Object.keys(profilingResult)).map(o=>profilingResult[o].profile), null, 2));
        console.log(JSON.stringify(profilingResult, null, 2));
    }
});

app.use(graphQLValidityMiddleware);

app.use('/graphql', graphqlHTTP((request) => {
    return {
        schema,
        graphiql: true,
        rootValue: request
    }
}));

app.listen(4000);<commit_msg>- test data updated<commit_after>const express = require('express');
const graphqlHTTP = require('express-graphql');

const {
    FieldValidationDefinitions,
    wrapResolvers,
    graphQLValidityMiddleware
} = require('../lib');

const schema = require('./schema');

const app = express();

function validateSomeTestThing(...args) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve([new Error('Wrong stuff here!')]);
        }, 130)
    });
}

function applyToAll(...args) {
    return [new Error('All failed!')];
}

function applyGlobally(...args) {
    return [new Error('Global failure!')];
}

function validateSomeTestMutation(...args) {
    return [new Error('testMutation failed!')];
}

function specialThird(...args) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve([new Error('Special third failed!')]);
        }, 250)
    });
}

FieldValidationDefinitions['$'] = [applyGlobally];
FieldValidationDefinitions['Mutation:testMutation'] = [validateSomeTestMutation];
FieldValidationDefinitions['TestType'] = [validateSomeTestThing];
FieldValidationDefinitions['TestType:fourth'] = [validateSomeTestThing];
FieldValidationDefinitions['TestType:fifth'] = [validateSomeTestThing];
FieldValidationDefinitions['TestType2:first'] = [validateSomeTestThing];
FieldValidationDefinitions['TestType2:second'] = [validateSomeTestThing];
FieldValidationDefinitions['TestType2:third'] = [specialThird];

wrapResolvers(schema, {
    wrapErrors: true,
    enableProfiling: true,
    profilingResultHandler: (profilingData) => {
        console.log(JSON.stringify(profilingData, null, 2));
    }
});

app.use(graphQLValidityMiddleware);

app.use('/graphql', graphqlHTTP((request) => {
    return {
        schema,
        graphiql: true,
        rootValue: request
    }
}));

app.listen(4000);<|endoftext|>


<commit_before>// account.js

var org = {

	// added on script load
	config: {
						endpoint: { hzws: 'http://api.spokanelibrary.org/v2/hzws/' }
					 }

	// added on authentication
	,user: {}

	// called on script load
	,init: function() {
		_self = this;

		// init ui
		this.initDonate();

	} // init()

, initDonate: function() {

		$('body').on('submit', '#donate-form', function() {

			//$('input', this).prop('disabled', true);
			//$('button', this).prop('disabled', true);

			var $specify = $('#specify');
			var specify = parseInt($specify.val());
			if ( specify > 0 ) {
				$('#amount').val(specify).prop('checked',true);
			}

			return false;

		});

  } // initDonate()

, toggleCheckboxGroup: function(all, item, scope) {
		var $selectAll;
		var $selectItem;
		if ( scope ) {
			$selectAll = $(all, scope);
			$selectItem = $(item, scope);
		} else {
			$selectAll = $(all);
			$selectItem = $(item);
		}

		$selectAll.on('change', function(e) {
			if ( $(this).is(':checked') ) {
				$selectAll.prop('checked', true);
				$selectItem.prop('checked', true);
			} else {
				$selectAll.prop('checked', false);
				$selectItem.prop('checked', false);
			}
		});
	}

};
<commit_msg>donate<commit_after>// account.js

var org = {

	// added on script load
	config: {
						endpoint: { hzws: 'http://api.spokanelibrary.org/v2/hzws/' }
					 }

	// added on authentication
	,user: {}

	// called on script load
	,init: function() {
		_self = this;

		// init ui
		this.initDonate();

	} // init()

, initDonate: function() {

		$('body').on('submit', '#donate-form', function() {

			//$('input', this).prop('disabled', true);
			//$('button', this).prop('disabled', true);

			var $specify = $('#specify');
			var specify = parseInt($specify.val());
			if ( specify > 0 ) {
				$('#amount').val(specify).prop('checked',true);
			}

			console.log(specify);

			return false;

		});

  } // initDonate()

, toggleCheckboxGroup: function(all, item, scope) {
		var $selectAll;
		var $selectItem;
		if ( scope ) {
			$selectAll = $(all, scope);
			$selectItem = $(item, scope);
		} else {
			$selectAll = $(all);
			$selectItem = $(item);
		}

		$selectAll.on('change', function(e) {
			if ( $(this).is(':checked') ) {
				$selectAll.prop('checked', true);
				$selectItem.prop('checked', true);
			} else {
				$selectAll.prop('checked', false);
				$selectItem.prop('checked', false);
			}
		});
	}

};
<|endoftext|>


<commit_before>// account.js

var org = {

	// added on script load
	config: {
						amount: 20
					, endpoint: { hzws: 'http://api.spokanelibrary.org/v2/hzws/' }
					 }

	// added on authentication
	,user: {}

	// called on script load
	,init: function() {
		_self = this;

		// init ui
		this.initDonate();

	} // init()

, initDonate: function() {

		this.normalizeValues();

  } // initValues()

, normalizeValues: function() {

		$('body').on('submit', '#donate-form', function() {

			// amount
			var $specify = $('#donate-specify');
			var $amount = $('#donate-amount');
			$amount.val('');

			var specify = parseInt($specify.val());
			if ( typeof(specify) != 'NaN' && specify > 0 ) {
				$amount.val(specify).prop('checked',true);
			} else {
				$amount.val('');
			}

			var amount = parseInt($('input[name="amount"]:checked').val());
			if ( (typeof(specify) == 'NaN') || !(amount > 0) ) {
				$amount.val(_self.config.amount).prop('checked',true);
				$specify.val(_self.config.amount);
			}
			console.log( parseInt($('input[name="amount"]:checked').val()) );

			// name
			var $name = $('#donate-number'); // we're hijacking the item_number field
			var $behalf = $('#donate-behalf');
			var $memory = $('#donate-memory');

			if ( $behalf.val().length > 0 ) {
				$name.val($behalf.val());
			}

			if ( $memory.val().length > 0 ) {
				$name.val($memory.val());
			}

			// anon

			var $reason = $('input[name="item_name"]:checked');
			console.log( $reason.val() );

			var $anon = $('#donate-anon');
			if ( $anon.prop('checked') ) {
				console.log( 'anon' );
			}

			// sustain

			//$('input', this).prop('disabled', true);
			//$('button', this).prop('disabled', true);

			return false;

		});

	}

, toggleCheckboxGroup: function(all, item, scope) {
		var $selectAll;
		var $selectItem;
		if ( scope ) {
			$selectAll = $(all, scope);
			$selectItem = $(item, scope);
		} else {
			$selectAll = $(all);
			$selectItem = $(item);
		}

		$selectAll.on('change', function(e) {
			if ( $(this).is(':checked') ) {
				$selectAll.prop('checked', true);
				$selectItem.prop('checked', true);
			} else {
				$selectAll.prop('checked', false);
				$selectItem.prop('checked', false);
			}
		});
	}

};
<commit_msg>donate<commit_after>// account.js

var org = {

	// added on script load
	config: {
						amount: 20
					, endpoint: { hzws: 'http://api.spokanelibrary.org/v2/hzws/' }
					 }

	// added on authentication
	,user: {}

	// called on script load
	,init: function() {
		_self = this;

		// init ui
		this.initDonate();

	} // init()

, initDonate: function() {

		this.normalizeValues();

  } // initValues()

, normalizeValues: function() {

		$('body').on('submit', '#donate-form', function() {

			// amount
			var $specify = $('#donate-specify');
			var $amount = $('#donate-amount');
			$amount.val('');

			var specify = parseInt($specify.val());
			if ( typeof(specify) != 'NaN' && specify > 0 ) {
				$amount.val(specify).prop('checked',true);
			} else {
				$amount.val('');
			}

			var amount = parseInt($('input[name="amount"]:checked').val());
			if ( (typeof(specify) == 'NaN') || !(amount > 0) ) {
				$amount.val(_self.config.amount).prop('checked',true);
				$specify.val(_self.config.amount);
			}
			console.log( parseInt($('input[name="amount"]:checked').val()) );

			// name
			var $name = $('#donate-number'); // we're hijacking the item_number field
			var $behalf = $('#donate-behalf');
			var $memory = $('#donate-memory');

			if ( $behalf.val().length > 0 ) {
				$name.val($behalf.val());
			}

			if ( $memory.val().length > 0 ) {
				$name.val($memory.val());
			}

			// anon

			var $reason = $('input[name="item_name"]:checked');
			console.log( $reason.val() );

			var $anon = $('#donate-anon');
			if ( $anon.prop('checked') ) {
				console.log( 'anon' );
				$reason.val( $reason.val() + ' (Anonymous)' );
			}

			// sustain

			//$('input', this).prop('disabled', true);
			//$('button', this).prop('disabled', true);

			return true;

		});

	}

, toggleCheckboxGroup: function(all, item, scope) {
		var $selectAll;
		var $selectItem;
		if ( scope ) {
			$selectAll = $(all, scope);
			$selectItem = $(item, scope);
		} else {
			$selectAll = $(all);
			$selectItem = $(item);
		}

		$selectAll.on('change', function(e) {
			if ( $(this).is(':checked') ) {
				$selectAll.prop('checked', true);
				$selectItem.prop('checked', true);
			} else {
				$selectAll.prop('checked', false);
				$selectItem.prop('checked', false);
			}
		});
	}

};
<|endoftext|>


<commit_before>// Copyright 2015, University of Colorado Boulder

/**
 * Tandem is a general instance registry that can be used to track creation/disposal of instances in PhET Simulations.
 * It is used for together.js instrumentation for PhET-iO support.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var tandemNamespace = require( 'TANDEM/tandemNamespace' );

  /**
   * @param {string} id - id as a string (or '' for a root id)
   * @constructor
   */
  function Tandem( id ) {

    // @public {read-only}
    this.id = (id !== undefined) ? id : '';

    // @private for generating indices from a pool
    this.poolElementIndex = 0;
  }

  tandemNamespace.register( 'Tandem', Tandem );

  // Listeners that will be notified when items are registered/deregistered
  var instanceListeners = [];

  inherit( Object, Tandem, {

    /**
     * Adds an instance of any type.  For example, it could be an axon Property, scenery Node or Sun button.  Each
     * item should only be added to the registry once, but that is not enforced here in Tandem.
     *
     * This is used to register instances with together.
     * @param {Object} instance - the instance to add
     * @public
     */
    addInstance: function( instance ) {
      for ( var i = 0; i < instanceListeners.length; i++ ) {
        instanceListeners[ i ].addInstance( this.id, instance );
      }
    },

    /**
     * Removes an instance from the
     * @param {Object} instance - the instance to remove
     * @public
     */
    removeInstance: function( instance ) {
      for ( var i = 0; i < instanceListeners.length; i++ ) {
        instanceListeners[ i ].removeInstance( this.id, instance );
      }
    },

    /**
     * Create a new Tandem by appending the given id
     * @param {string} id
     * @returns {Tandem}
     * @public
     */
    createTandem: function( id ) {
      var string = (this.id.length > 0) ? (this.id + '.' + id) : id;
      return new Tandem( string );
    },

    /**
     * Creates a new tandem by appending the given id then underscore and a new index.  For instance:
     * sim.screen.model.electron_0
     * Used for arrays, observable arrays, or when many elements of the same type are created and they do not otherwise
     * have unique identifiers.
     * @param id
     * @returns {Tandem}
     */
    createPoolElementTandem: function( id ) {
      assert && assert( this.id.length > 0, 'indexed tandems must have an id' );
      return new Tandem( this.id + '.' + id + '_' + (this.poolElementIndex++) );
    }
  }, {

    /**
     * Adds a listener that will be notified when items are registered/deregistered
     * Listeners have the form
     * {
     *   addInstance(id,instance),
     *   removeInstance(id,instance)
     * }
     * where id is of type {string} and instance is of type {Object}
     *
     * @param {Object} instanceListener - described above
     * @public
     * @static
     */
    addInstanceListener: function( instanceListener ) {
      instanceListeners.push( instanceListener );
    }
  } );

  // Tandem checks for listeners added before the Tandem module was loaded.  This is necessary so that together.js can
  // receive notifications about items created during static initialization such as Solute.js
  // which is created before Sim.js runs.
  if ( window.tandemPreloadInstanceListeners ) {
    for ( var i = 0; i < window.tandemPreloadInstanceListeners.length; i++ ) {
      Tandem.addInstanceListener( window.tandemPreloadInstanceListeners[ i ] );
    }
  }

  return Tandem;
} );<commit_msg>Pass tandem to screen instances, and updated docs, see https://github.com/phetsims/together/issues/114<commit_after>// Copyright 2015, University of Colorado Boulder

/**
 * Tandem is a general instance registry that can be used to track creation/disposal of instances in PhET Simulations.
 * It is used for together.js instrumentation for PhET-iO support.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var tandemNamespace = require( 'TANDEM/tandemNamespace' );

  /**
   * @param {string} id - id as a string (or '' for a root id)
   * @constructor
   */
  function Tandem( id ) {

    // @public {read-only}
    this.id = (id !== undefined) ? id : '';

    // @private for generating indices from a pool
    this.poolElementIndex = 0;
  }

  tandemNamespace.register( 'Tandem', Tandem );

  // Listeners that will be notified when items are registered/deregistered
  var instanceListeners = [];

  inherit( Object, Tandem, {

    /**
     * Adds an instance of any type.  For example, it could be an axon Property, scenery Node or Sun button.  Each
     * item should only be added to the registry once, but that is not enforced here in Tandem.
     *
     * This is used to register instances with together.
     * @param {Object} instance - the instance to add
     * @public
     */
    addInstance: function( instance ) {
      for ( var i = 0; i < instanceListeners.length; i++ ) {
        instanceListeners[ i ].addInstance( this.id, instance );
      }
    },

    /**
     * Removes an instance from the
     * @param {Object} instance - the instance to remove
     * @public
     */
    removeInstance: function( instance ) {
      for ( var i = 0; i < instanceListeners.length; i++ ) {
        instanceListeners[ i ].removeInstance( this.id, instance );
      }
    },

    /**
     * Create a new Tandem by appending the given id
     * @param {string} id
     * @returns {Tandem}
     * @public
     */
    createTandem: function( id ) {
      var string = (this.id.length > 0) ? (this.id + '.' + id) : id;
      return new Tandem( string );
    },

    /**
     * Creates a new tandem by appending the given id then underscore and a new index.  For instance:
     * sim.screen.model.electron_0
     * Used for arrays, observable arrays, or when many elements of the same type are created and they do not otherwise
     * have unique identifiers.
     * @param id
     * @returns {Tandem}
     */
    createPoolElementTandem: function( id ) {
      assert && assert( this.id.length > 0, 'indexed tandems must have an id' );
      return new Tandem( this.id + '.' + id + '_' + (this.poolElementIndex++) );
    },

    /**
     * Get the last part of the tandem (after the last .), used in Joist for creating button names dynamically based
     * on screen names
     * @return {string} the tail of the tandem
     */
    get tail() {
      assert && assert( this.id.indexOf( '.' ) >= 0, 'tandem ID does not have a tail' );

      var lastIndexOfDot = this.id.lastIndexOf( '.' );
      var tail = this.id.substring( lastIndexOfDot + 1 );
      assert && assert( tail.length > 0, 'tandem ID did not have a tail' );
      return tail;
    }
  }, {

    /**
     * Adds a listener that will be notified when items are registered/deregistered
     * Listeners have the form
     * {
     *   addInstance(id,instance),
     *   removeInstance(id,instance)
     * }
     * where id is of type {string} and instance is of type {Object}
     *
     * @param {Object} instanceListener - described above
     * @public
     * @static
     */
    addInstanceListener: function( instanceListener ) {
      instanceListeners.push( instanceListener );
    }
  } );

  // Tandem checks for listeners added before the Tandem module was loaded.  This is necessary so that together.js can
  // receive notifications about items created during static initialization such as Solute.js
  // which is created before Sim.js runs.
  if ( window.tandemPreloadInstanceListeners ) {
    for ( var i = 0; i < window.tandemPreloadInstanceListeners.length; i++ ) {
      Tandem.addInstanceListener( window.tandemPreloadInstanceListeners[ i ] );
    }
  }

  return Tandem;
} );<|endoftext|>


<commit_before>/*
 * Copyright (C) 2015 The Gravitee team (http://gravitee.io)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* global setInterval:false, clearInterval:false */
function runBlock ($rootScope, $window, $http, $cookieStore) {
  'ngInject';
  var graviteeAuthenticationKey = 'GraviteeAuthentication';

  function setAuthorization() {
    var graviteeAuthentication = $cookieStore.get(graviteeAuthenticationKey);
    if (graviteeAuthentication) {
      $http.defaults.headers.common.Authorization = 'Basic ' + graviteeAuthentication;
      $rootScope.authenticated = true;
    } else {
      delete $http.defaults.headers.common.Authorization;
      $rootScope.authenticated = false;
    }
  }

  setAuthorization();

  $rootScope.$on('graviteeLogout', function() {
    $cookieStore.remove(graviteeAuthenticationKey);
		$cookieStore.remove('authenticatedUser');
		$rootScope.authenticated = false;
    setAuthorization();
    $window.location.href = '/';
  });

	$rootScope.$on('$stateChangeStart', function(event, toState){
    $rootScope.contentIsActive = (toState.name.indexOf("application.") === 0
																	|| toState.name.indexOf("apis.admin") === 0
																	|| toState.name.indexOf("apis.portal") === 0);
	});

  // Progress Bar
  var interval, intervalTimeInMs = 500;
  $rootScope.$watch(function () {
    return $http.pendingRequests.length > 0;
  }, function (hasPendingRequests) {
    if (hasPendingRequests) {
			$rootScope.isLoading = true;
      $rootScope.progressValue = 0;
      interval = setInterval(function () {
        $rootScope.$apply(function () {
          if ($rootScope.progressValue === 100) {
            $rootScope.progressValue = 0;
          } else {
            $rootScope.progressValue += 10;
          }
        });
      }, intervalTimeInMs);
    } else {
      clearInterval(interval);
      $rootScope.progressValue = 100;
			$rootScope.isLoading = false;
    }
  });
}

export default runBlock;
<commit_msg>refactor: remove authentication on request header<commit_after>/*
 * Copyright (C) 2015 The Gravitee team (http://gravitee.io)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* global setInterval:false, clearInterval:false */
function runBlock ($rootScope, $window, $http, $cookieStore) {
  'ngInject';
  var graviteeAuthenticationKey = 'GraviteeAuthentication';

  function setAuthorization() {
    var graviteeAuthentication = $cookieStore.get(graviteeAuthenticationKey);
    if (graviteeAuthentication) {
      $http.defaults.headers.common.Authorization = 'Basic ' + graviteeAuthentication;
      $rootScope.authenticated = true;
    } else {
      $http.defaults.headers.common.Authorization = '';
      $rootScope.authenticated = false;
    }
  }

  setAuthorization();

  $rootScope.$on('graviteeLogout', function() {
    $cookieStore.remove(graviteeAuthenticationKey);
		$cookieStore.remove('authenticatedUser');
		$rootScope.authenticated = false;
    setAuthorization();
    $window.location.href = '/';
  });

	$rootScope.$on('$stateChangeStart', function(event, toState){
    $rootScope.contentIsActive = (toState.name.indexOf("application.") === 0
																	|| toState.name.indexOf("apis.admin") === 0
																	|| toState.name.indexOf("apis.portal") === 0);
	});

  // Progress Bar
  var interval, intervalTimeInMs = 500;
  $rootScope.$watch(function () {
    return $http.pendingRequests.length > 0;
  }, function (hasPendingRequests) {
    if (hasPendingRequests) {
			$rootScope.isLoading = true;
      $rootScope.progressValue = 0;
      interval = setInterval(function () {
        $rootScope.$apply(function () {
          if ($rootScope.progressValue === 100) {
            $rootScope.progressValue = 0;
          } else {
            $rootScope.progressValue += 10;
          }
        });
      }, intervalTimeInMs);
    } else {
      clearInterval(interval);
      $rootScope.progressValue = 100;
			$rootScope.isLoading = false;
    }
  });
}

export default runBlock;
<|endoftext|>


<commit_before>hljs.registerLanguage("powershell", function(e) {
    var t= {
        b: "`[\\s\\S]", r: 0
    }
    , r= {
        cN:"variable", b: /\$[\w\d][\w\d_: ]*/
    }
    , a= {
        cN:"string", b:/"/,e:/"/, c:[t, r, {
            cN: "variable", b: /\$[\w\d][\w\d_: ]*/
        }
        ]
    }
    , i= {
        cN: "string", b: /'/,e:/'/
    }
    , f= {
        cN: "function", b: /([\d\w]+-[\d\w]+)/
    }
    , p= {
        cN: "params", b: /-[\d\w]+/
    }
    , t= {
        cN: "type", b: /\[/, e:/\]/, c:[r, {
            cN: "variable", b: /\$[\w\d][\w\d_: ]*/
        }
        ]
    }
    ;
    return {
        aliases:["ps"], l:/-?[A-z\.\-]+/, cI:!0, k: {
            keyword: "if else foreach return function do while until elseif begin for trap data dynamicparam end break throw param continue finally in switch exit filter try process catch", built_in: "Add-Content Add-History Add-Member Add-PSSnapin Clear-Content Clear-Item Clear-Item Property Clear-Variable Compare-Object ConvertFrom-SecureString Convert-Path ConvertTo-Html ConvertTo-SecureString Copy-Item Copy-ItemProperty Export-Alias Export-Clixml Export-Console Export-Csv ForEach-Object Format-Custom Format-List Format-Table Format-Wide Get-Acl Get-Alias Get-AuthenticodeSignature Get-ChildItem Get-Command Get-Content Get-Credential Get-Culture Get-Date Get-EventLog Get-ExecutionPolicy Get-Help Get-History Get-Host Get-Item Get-ItemProperty Get-Location Get-Member Get-PfxCertificate Get-Process Get-PSDrive Get-PSProvider Get-PSSnapin Get-Service Get-TraceSource Get-UICulture Get-Unique Get-Variable Get-WmiObject Group-Object Import-Alias Import-Clixml Import-Csv Invoke-Expression Invoke-History Invoke-Item Join-Path Measure-Command Measure-Object Move-Item Move-ItemProperty New-Alias New-Item New-ItemProperty New-Object New-PSDrive New-Service New-TimeSpan New-Variable Out-Default Out-File Out-Host Out-Null Out-Printer Out-String Pop-Location Push-Location Read-Host Remove-Item Remove-ItemProperty Remove-PSDrive Remove-PSSnapin Remove-Variable Rename-Item Rename-ItemProperty Resolve-Path Restart-Service Resume-Service Select-Object Select-String Set-Acl Set-Alias Set-AuthenticodeSignature Set-Content Set-Date Set-ExecutionPolicy Set-Item Set-ItemProperty Set-Location Set-PSDebug Set-Service Set-TraceSource Set-Variable Sort-Object Split-Path Start-Service Start-Sleep Start-Transcript Stop-Process Stop-Service Stop-Transcript Suspend-Service Tee-Object Test-Path Trace-Command Update-FormatData Update-TypeData Where-Object Write-Debug Write-Error Write-Host Write-Output Write-Progress Write-Verbose Write-Warning", nomarkup: "-ne -eq -lt -gt -ge -le -not -like -notlike -match -notmatch -contains -notcontains -in -notin -replace"
        }
        , c:[e.HCM, e.NM, a, i, r, f, p, t]
    }
}

);<commit_msg>More type fixes<commit_after>hljs.registerLanguage("powershell", function(e) {
    var t= {
        b: "`[\\s\\S]", r: 0
    }
    , r= {
        cN:"variable", b: /\$[\w\d][\w\d_: ]*/
    }
    , a= {
        cN:"string", b:/"/,e:/"/, c:[t, r, {
            cN: "variable", b: /\$[\w\d][\w\d_: ]*/
        }
        ]
    }
    , i= {
        cN: "string", b: /'/,e:/'/
    }
    , f= {
        cN: "function", b: /([\d\w]+-[\d\w]+)/
    }
    , p= {
        cN: "params", b: /-[\d\w]+/
    }
    , t= {
        cN: "type", b: /\[/, e:/\]/, c:[t, r, {
            cN: "variable", b: /\$[\w\d][\w\d_: ]*/
        }
        ]
    }
    ;
    return {
        aliases:["ps"], l:/-?[A-z\.\-]+/, cI:!0, k: {
            keyword: "if else foreach return function do while until elseif begin for trap data dynamicparam end break throw param continue finally in switch exit filter try process catch", built_in: "Add-Content Add-History Add-Member Add-PSSnapin Clear-Content Clear-Item Clear-Item Property Clear-Variable Compare-Object ConvertFrom-SecureString Convert-Path ConvertTo-Html ConvertTo-SecureString Copy-Item Copy-ItemProperty Export-Alias Export-Clixml Export-Console Export-Csv ForEach-Object Format-Custom Format-List Format-Table Format-Wide Get-Acl Get-Alias Get-AuthenticodeSignature Get-ChildItem Get-Command Get-Content Get-Credential Get-Culture Get-Date Get-EventLog Get-ExecutionPolicy Get-Help Get-History Get-Host Get-Item Get-ItemProperty Get-Location Get-Member Get-PfxCertificate Get-Process Get-PSDrive Get-PSProvider Get-PSSnapin Get-Service Get-TraceSource Get-UICulture Get-Unique Get-Variable Get-WmiObject Group-Object Import-Alias Import-Clixml Import-Csv Invoke-Expression Invoke-History Invoke-Item Join-Path Measure-Command Measure-Object Move-Item Move-ItemProperty New-Alias New-Item New-ItemProperty New-Object New-PSDrive New-Service New-TimeSpan New-Variable Out-Default Out-File Out-Host Out-Null Out-Printer Out-String Pop-Location Push-Location Read-Host Remove-Item Remove-ItemProperty Remove-PSDrive Remove-PSSnapin Remove-Variable Rename-Item Rename-ItemProperty Resolve-Path Restart-Service Resume-Service Select-Object Select-String Set-Acl Set-Alias Set-AuthenticodeSignature Set-Content Set-Date Set-ExecutionPolicy Set-Item Set-ItemProperty Set-Location Set-PSDebug Set-Service Set-TraceSource Set-Variable Sort-Object Split-Path Start-Service Start-Sleep Start-Transcript Stop-Process Stop-Service Stop-Transcript Suspend-Service Tee-Object Test-Path Trace-Command Update-FormatData Update-TypeData Where-Object Write-Debug Write-Error Write-Host Write-Output Write-Progress Write-Verbose Write-Warning", nomarkup: "-ne -eq -lt -gt -ge -le -not -like -notlike -match -notmatch -contains -notcontains -in -notin -replace"
        }
        , c:[e.HCM, e.NM, a, i, r, f, p, t]
    }
}

);<|endoftext|>