<commit_before>// require ../support/jquery
// require esphinx_ui
// require esphinx/support/ajax
// require esphinx/support/function
// require esphinx/support/array
// require esphinx/observer

"use strict";

var
    jQuery,
    esPhinx,
    Singleton,
    Ajax,
    Constructor;

(function ($module) {

    $module.extend({

        windows: {
            modal: {
                // functions are objects in js
                new: function (contentSource, options) {

                    var
                        ModalConstructor = $module.windows.modal.new,
                        self = this,

                        $ = jQuery,
                        ajax = Ajax,
                        body = $("body"),

                        modal,
                        mask,
                        main,
                        container,
                        btnClose,
                        btnHide,
                        headers,
                        params,
                        asynchronousAnswer,
                        calledBack,
                        imgControl,

                        maskTransitionDuration = function (mask) {
                            return parseFloat(mask
                                .css("transition-duration")) * 1000;
                        },

                        restartTransition = function (mask) {
                            mask.css("transition", "opacity 0s");
                        },

                        resolveParams = function () {
                            options = options || {};

                            if (typeof options.windowController !== "boolean") {
                                options.windowController = true;
                            }

                            if (typeof options.remote !== "boolean") {
                                options.remote = true;
                            }
                        },

                        resolveHeaderActions = function (main, options) {
                            var
                                header,
                                actions;

                            if (options.windowController) {
                                header = $("");
                                actions = $("

").addClass("actions");
                                btnClose = $('')
                                    .addClass("btn-close");
                                btnHide = $('')
                                    .addClass("btn-hide");

                                header.append(actions);
                                actions.append(btnClose);
                                actions.append(btnHide);

                                main
                                    .prepend(header)
                                    .css({
                                        "max-height": $(window).height(),
                                        "max-width": $(document).width()
                                    });

                                bindHeaderEventListeners();
                            }
                        },

                        bindHeaderEventListeners = function () {
                            // $(document).off("keydown").on("keydown", function (e) {
                            //     if (e.keyCode === 27) {
                            //         self.hide();
                            //     }
                            // });

                            btnHide.click(function () {
                                self.hide();
                            });

                            btnClose.click(function () {
                                self.close();
                            });
                        },

                        observeContent = function () {
                            var
                                imgs,
                                length = 0;

                            esPhinx(main[0]).observe(function (observer) {
                                imgs = main.find("img");
                                if (imgs.length) {
                                    imgs.each(function (i, img) {
                                        esPhinx(img).on("load", function () {
                                            length += 1;
                                        });
                                    });

                                    FlowControl.new({
                                        condition: function (condition) {
                                            // when processing is synchronous
                                            if (!options.remote) {
                                                if (options.loading) {
                                                    options.loading(main);
                                                }
                                                if (!calledBack) {
                                                    calledBack = true;
                                                    self.show();
                                                }
                                            }

                                            condition(length === imgs.length);
                                        },
                                        ready: function () {
                                            if (!asynchronousAnswer) {
                                                container.html(contentSource);
                                                main.html(container);
                                            }

                                            length = 0;
                                            resolveHeaderActions(main, options);

                                            if (options.complete) {
                                                self.hide(false);
                                                options.complete(self);
                                            }
                                        }
                                    })

                                } else {
                                    resolveHeaderActions(main, options);

                                    if (options.complete) {
                                        options.complete(self);
                                    }
                                }

                                // talvez tenha que remanejar o disconnect
                                observer.disconnect();
                            });
                        },

                        create = function (remote) {
                            modal = $("

")
                                .addClass("esphinx ui modal");
                            main = $("")
                                .addClass("basicss hidden");
                            mask = $("

")
                                .addClass("basicss fixed transparent mask");
                            container = $("

").addClass("container");

                            modal
                                .append(mask)
                                .append(main);

                            body.append(modal);

                            observeContent();

                            if (options.remote) {
                                headers = options.header || options.headers || null;
                                params = options.param || options.params || null;
                                ajax.new(contentSource, {
                                    params: params,
                                    headers: headers,
                                    processing: function () {
                                        if (options.loading) {
                                            options.loading(main);
                                        }
                                        if (!calledBack) {
                                            calledBack = true;
                                            // because here the processing is asynchronous, it's not linear
                                            self.show();
                                        }
                                    },
                                    success: function (a) {
                                        if (options.success) {
                                            options.success(main);
                                        }
                                        asynchronousAnswer = a;
                                        container.html(asynchronousAnswer);
                                        // because here the processing is asynchronous, it's not linear
                                        self.hide(false);
                                        main.html(container);
                                    }
                                });
                            } else {
                                container.html(contentSource);
                                main.html(container);
                            }

                        };

                    // global scope (public)
                    this.close = function () {
                        main.hide();

                        restartTransition(mask);
                        if (options.fadeOut) {
                            mask.css("transition", "opacity " + options.fadeOut);
                        }
                        mask.addClass("transparent");

                        setTimeout(function () {
                            modal.remove();
                        }, maskTransitionDuration(mask));

                        self.deleteSingleton();
                    };

                    this.hide = function (animation = true) {
                        main.hide();

                        restartTransition(mask);

                        if (animation) {
                            if (options.fadeOut) {
                                mask.css("transition", "opacity " + options.fadeOut);
                                setTimeout(function () {
                                    modal.css("z-index", -1);
                                }, maskTransitionDuration(mask));
                            }
                        }

                        mask.addClass("transparent");
                    };

                    this.show = function () {
                        modal.css("z-index", 0);

                        restartTransition(mask);
                        if (options.fadeIn) {
                            mask.css("transition", "opacity " + options.fadeIn);
                        }
                        mask.removeClass("transparent");

                        main.centralizeAt($(document));
                        main.show();
                        debugger
                    };

                    if (!(this instanceof ModalConstructor)) {
                        self = Singleton.exists(ModalConstructor, arguments);
                        if (self) {
                            self.show();
                        } else {
                            return ModalConstructor.singleton(arguments);
                        }
                    // that "else" will should to exit for the "show" method can be used by who instanciates it
                    } else {
                        resolveParams();
                        create();
                    }

                    return self;
                }
            }
        }
    });

}(esPhinx.ui));
<commit_msg>it comment debugger statement<commit_after>// require ../support/jquery
// require esphinx_ui
// require esphinx/support/ajax
// require esphinx/support/function
// require esphinx/support/array
// require esphinx/observer

"use strict";

var
    jQuery,
    esPhinx,
    Singleton,
    Ajax,
    Constructor;

(function ($module) {

    $module.extend({

        windows: {
            modal: {
                // functions are objects in js
                new: function (contentSource, options) {

                    var
                        ModalConstructor = $module.windows.modal.new,
                        self = this,

                        $ = jQuery,
                        ajax = Ajax,
                        body = $("body"),

                        modal,
                        mask,
                        main,
                        container,
                        btnClose,
                        btnHide,
                        headers,
                        params,
                        asynchronousAnswer,
                        calledBack,
                        imgControl,

                        maskTransitionDuration = function (mask) {
                            return parseFloat(mask
                                .css("transition-duration")) * 1000;
                        },

                        restartTransition = function (mask) {
                            mask.css("transition", "opacity 0s");
                        },

                        resolveParams = function () {
                            options = options || {};

                            if (typeof options.windowController !== "boolean") {
                                options.windowController = true;
                            }

                            if (typeof options.remote !== "boolean") {
                                options.remote = true;
                            }
                        },

                        resolveHeaderActions = function (main, options) {
                            var
                                header,
                                actions;

                            if (options.windowController) {
                                header = $("");
                                actions = $("

").addClass("actions");
                                btnClose = $('')
                                    .addClass("btn-close");
                                btnHide = $('')
                                    .addClass("btn-hide");

                                header.append(actions);
                                actions.append(btnClose);
                                actions.append(btnHide);

                                main
                                    .prepend(header)
                                    .css({
                                        "max-height": $(window).height(),
                                        "max-width": $(document).width()
                                    });

                                bindHeaderEventListeners();
                            }
                        },

                        bindHeaderEventListeners = function () {
                            // $(document).off("keydown").on("keydown", function (e) {
                            //     if (e.keyCode === 27) {
                            //         self.hide();
                            //     }
                            // });

                            btnHide.click(function () {
                                self.hide();
                            });

                            btnClose.click(function () {
                                self.close();
                            });
                        },

                        observeContent = function () {
                            var
                                imgs,
                                length = 0;

                            esPhinx(main[0]).observe(function (observer) {
                                imgs = main.find("img");
                                if (imgs.length) {
                                    imgs.each(function (i, img) {
                                        esPhinx(img).on("load", function () {
                                            length += 1;
                                        });
                                    });

                                    FlowControl.new({
                                        condition: function (condition) {
                                            // when processing is synchronous
                                            if (!options.remote) {
                                                if (options.loading) {
                                                    options.loading(main);
                                                }
                                                if (!calledBack) {
                                                    calledBack = true;
                                                    self.show();
                                                }
                                            }

                                            condition(length === imgs.length);
                                        },
                                        ready: function () {
                                            if (!asynchronousAnswer) {
                                                container.html(contentSource);
                                                main.html(container);
                                            }

                                            length = 0;
                                            resolveHeaderActions(main, options);

                                            if (options.complete) {
                                                self.hide(false);
                                                options.complete(self);
                                            }
                                        }
                                    })

                                } else {
                                    resolveHeaderActions(main, options);

                                    if (options.complete) {
                                        options.complete(self);
                                    }
                                }

                                // talvez tenha que remanejar o disconnect
                                observer.disconnect();
                            });
                        },

                        create = function (remote) {
                            modal = $("

")
                                .addClass("esphinx ui modal");
                            main = $("")
                                .addClass("basicss hidden");
                            mask = $("

")
                                .addClass("basicss fixed transparent mask");
                            container = $("

").addClass("container");

                            modal
                                .append(mask)
                                .append(main);

                            body.append(modal);

                            observeContent();

                            if (options.remote) {
                                headers = options.header || options.headers || null;
                                params = options.param || options.params || null;
                                ajax.new(contentSource, {
                                    params: params,
                                    headers: headers,
                                    processing: function () {
                                        if (options.loading) {
                                            options.loading(main);
                                        }
                                        if (!calledBack) {
                                            calledBack = true;
                                            // because here the processing is asynchronous, it's not linear
                                            self.show();
                                        }
                                    },
                                    success: function (a) {
                                        if (options.success) {
                                            options.success(main);
                                        }
                                        asynchronousAnswer = a;
                                        container.html(asynchronousAnswer);
                                        // because here the processing is asynchronous, it's not linear
                                        self.hide(false);
                                        main.html(container);
                                    }
                                });
                            } else {
                                container.html(contentSource);
                                main.html(container);
                            }

                        };

                    // global scope (public)
                    this.close = function () {
                        main.hide();

                        restartTransition(mask);
                        if (options.fadeOut) {
                            mask.css("transition", "opacity " + options.fadeOut);
                        }
                        mask.addClass("transparent");

                        setTimeout(function () {
                            modal.remove();
                        }, maskTransitionDuration(mask));

                        self.deleteSingleton();
                    };

                    this.hide = function (animation = true) {
                        main.hide();

                        restartTransition(mask);

                        if (animation) {
                            if (options.fadeOut) {
                                mask.css("transition", "opacity " + options.fadeOut);
                                setTimeout(function () {
                                    modal.css("z-index", -1);
                                }, maskTransitionDuration(mask));
                            }
                        }

                        mask.addClass("transparent");
                    };

                    this.show = function () {
                        modal.css("z-index", 0);

                        restartTransition(mask);
                        if (options.fadeIn) {
                            mask.css("transition", "opacity " + options.fadeIn);
                        }
                        mask.removeClass("transparent");

                        main.centralizeAt($(document));
                        main.show();
                        // debugger'
                    };

                    if (!(this instanceof ModalConstructor)) {
                        self = Singleton.exists(ModalConstructor, arguments);
                        if (self) {
                            self.show();
                        } else {
                            return ModalConstructor.singleton(arguments);
                        }
                    // that "else" will should to exit for the "show" method can be used by who instanciates it
                    } else {
                        resolveParams();
                        create();
                    }

                    return self;
                }
            }
        }
    });

}(esPhinx.ui));
<|endoftext|>


<commit_before>const smash = require("../../../../smash.js");
const errorUtil = smash.errorUtil();

class Response {
	constructor(terminate, request) {
		if (typeof terminate !== 'object') {
			throw new errorUtil.TypeError("First parameter of new Response() must be a object, ", terminate);
		}
		if (typeof terminate.handleResponse !== 'function') {
			throw new errorUtil.TypeError("First parameter of new Response() must be a object with a function called handleResponse, ", terminate.handleResponse);
		}
		if (terminate.handleResponse.length !== 1) {
			throw new Error("First parameter of new Response() must be a function witch takes 1 parameter, " + terminate.handleResponse.length + " given");
		}
		if (typeof terminate !== 'object') {
			throw new errorUtil.TypeError("Second parameter of new Response() must be a object, ", terminate);
		}
		this._terminate = terminate;
		this.request = request;
		this.code = null;
		this.headers = {};
		this.body = null;
	}

	get _errorPointer() {
		return {
			400: this.badRequest,
			401: this.unauthorized,
			403: this.forbidden,
			404: this.notFound,
			409: this.conflict,
			500: this.internalServerError,
			501: this.notImplemented,
			503: this.serviceUnavailable,
		};
	}

	_cleanAndAssign(body) {
		return new Promise((resolve, reject) => {
			if (smash.filter.hasOutRule(this.request.route) === true) {
				body = smash.filter.cleanOut(this.request.route, body);
				resolve(body);
			} else {
				reject(this.internalServerError("No outRule found for " + JSON.stringify(this.request.route)));
			}
		});
	}

	cleanOk(body) {
		this._cleanAndAssign(body).then(body => {
			this.ok(body);
		}).catch(error => {
			this.handleError(error);
		});
	}

	ok(body) {
		return this._handleResponse(200, body);
	}

	created(body) {
		return this._handleResponse(201, body);
	}

	cleanCreated(body) {
		this._cleanAndAssign(body).then(body => {
			this.created(body);
		}).cacth(error => {
			this.handleError(error);
		});
	}

	accepted() {
		return this._handleResponse(202);
	}

	noContent() {
		return this._handleResponse(204);
	}

	_getRedirectHeaders(url) {
		return { Location: url };
	}

	movedPermanently(url) {
		return this._handleResponse(301, "", this._getRedirectHeaders(url));
	}

	found(url) {
		return this._handleResponse(302, "", this._getRedirectHeaders(url));
	}

	temporaryRedirect(url) {
		return this._handleResponse(307, "", this._getRedirectHeaders(url));
	}

	permanentRedirect(url) {
		return this._handleResponse(308, "", this._getRedirectHeaders(url));
	}

	badRequest(message, details) {
		return this.handleError(errorUtil.badRequestError(message, details));
	}

	unauthorized(message) {
		return this.handleError(errorUtil.unauthorizedError(message));
	}

	forbidden(message) {
		return this.handleError(errorUtil.forbiddenError(message));
	}

	notFound(message) {
		return this.handleError(errorUtil.notFoundError(message));
	}

	conflict(message) {
		return this.handleError(errorUtil.conflictError(message));
	}

	internalServerError(message) {
		return this.handleError(errorUtil.internalServerError(message));
	}

	notImplemented(message) {
		return this.handleError(errorUtil.notImplementedError(message));
	}

	serviceUnavailable(message) {
		return this.handleError(errorUtil.serviceUnavailableError(message));
	}

	forward(response) {
		this.addHeaders(response.headers);
		return this._handleResponse(response.statusCode, response.body);
	}

	_handleResponse(code, body = "", headers = null) {
		this.code = code;
		this.body = body;
		this.addHeaders(headers);
		this.terminate();
		return this;
	}

	handleError(error) {
		if (errorUtil.isSmashError(error) === false) {
			error = errorUtil.internalServerError("First argument of handleError(error) must ba a SmashError, " + errorUtil.typeOf(error), error);
		}
		error.requestId = this.request.requestId;
		error.printError();
		return this._handleResponse(error.code, error.body);
	}

	addHeader(key, value) {
		this.headers[key] = value;
		return this;
	}

	addHeaders(headers = {}) {
		for (const key in headers) {
			this.addHeader(key, headers[key]);
		}
		return this;
	}

	get stringifiedBody() {
		return typeof this.body === 'object' ? JSON.stringify(this.body) : this.body;
	}

	terminate() {
		Object.freeze(this);
		this._terminate.handleResponse(this);
	}
}

module.exports = Response;
<commit_msg>Improve error message<commit_after>const smash = require("../../../../smash.js");
const errorUtil = smash.errorUtil();

class Response {
	constructor(terminate, request) {
		if (typeof terminate !== 'object') {
			throw new errorUtil.TypeError("First parameter of new Response() must be a object, ", terminate);
		}
		if (typeof terminate.handleResponse !== 'function') {
			throw new errorUtil.TypeError("First parameter of new Response() must be a object with a function called handleResponse, ", terminate.handleResponse);
		}
		if (terminate.handleResponse.length !== 1) {
			throw new Error("First parameter of new Response() must be a function witch takes 1 parameter, " + terminate.handleResponse.length + " given");
		}
		if (typeof terminate !== 'object') {
			throw new errorUtil.TypeError("Second parameter of new Response() must be a object, ", terminate);
		}
		this._terminate = terminate;
		this.request = request;
		this.code = null;
		this.headers = {};
		this.body = null;
	}

	get _errorPointer() {
		return {
			400: this.badRequest,
			401: this.unauthorized,
			403: this.forbidden,
			404: this.notFound,
			409: this.conflict,
			500: this.internalServerError,
			501: this.notImplemented,
			503: this.serviceUnavailable,
		};
	}

	_cleanAndAssign(body) {
		return new Promise((resolve, reject) => {
			if (smash.filter.hasOutRule(this.request.route) === true) {
				body = smash.filter.cleanOut(this.request.route, body);
				resolve(body);
			} else {
				reject(this.internalServerError("No outRule found for " + JSON.stringify(this.request.route) + ", did you call cleanOk or cleanCreated without defining a outRule?"));
			}
		});
	}

	cleanOk(body) {
		this._cleanAndAssign(body).then(body => {
			this.ok(body);
		}).catch(error => {
			this.handleError(error);
		});
	}

	ok(body) {
		return this._handleResponse(200, body);
	}

	created(body) {
		return this._handleResponse(201, body);
	}

	cleanCreated(body) {
		this._cleanAndAssign(body).then(body => {
			this.created(body);
		}).cacth(error => {
			this.handleError(error);
		});
	}

	accepted() {
		return this._handleResponse(202);
	}

	noContent() {
		return this._handleResponse(204);
	}

	_getRedirectHeaders(url) {
		return { Location: url };
	}

	movedPermanently(url) {
		return this._handleResponse(301, "", this._getRedirectHeaders(url));
	}

	found(url) {
		return this._handleResponse(302, "", this._getRedirectHeaders(url));
	}

	temporaryRedirect(url) {
		return this._handleResponse(307, "", this._getRedirectHeaders(url));
	}

	permanentRedirect(url) {
		return this._handleResponse(308, "", this._getRedirectHeaders(url));
	}

	badRequest(message, details) {
		return this.handleError(errorUtil.badRequestError(message, details));
	}

	unauthorized(message) {
		return this.handleError(errorUtil.unauthorizedError(message));
	}

	forbidden(message) {
		return this.handleError(errorUtil.forbiddenError(message));
	}

	notFound(message) {
		return this.handleError(errorUtil.notFoundError(message));
	}

	conflict(message) {
		return this.handleError(errorUtil.conflictError(message));
	}

	internalServerError(message) {
		return this.handleError(errorUtil.internalServerError(message));
	}

	notImplemented(message) {
		return this.handleError(errorUtil.notImplementedError(message));
	}

	serviceUnavailable(message) {
		return this.handleError(errorUtil.serviceUnavailableError(message));
	}

	forward(response) {
		this.addHeaders(response.headers);
		return this._handleResponse(response.statusCode, response.body);
	}

	_handleResponse(code, body = "", headers = null) {
		this.code = code;
		this.body = body;
		this.addHeaders(headers);
		this.terminate();
		return this;
	}

	handleError(error) {
		if (errorUtil.isSmashError(error) === false) {
			error = errorUtil.internalServerError("First argument of handleError(error) must ba a SmashError, " + errorUtil.typeOf(error), error);
		}
		error.requestId = this.request.requestId;
		error.printError();
		return this._handleResponse(error.code, error.body);
	}

	addHeader(key, value) {
		this.headers[key] = value;
		return this;
	}

	addHeaders(headers = {}) {
		for (const key in headers) {
			this.addHeader(key, headers[key]);
		}
		return this;
	}

	get stringifiedBody() {
		return typeof this.body === 'object' ? JSON.stringify(this.body) : this.body;
	}

	terminate() {
		Object.freeze(this);
		this._terminate.handleResponse(this);
	}
}

module.exports = Response;
<|endoftext|>


<commit_before>var path = require("path");
var stealTools = require("steal-tools");

stealTools.optimize({
  config: path.join(__dirname, "package.json!npm")
}, {
	bundleAssets: false,
	minify: true
});
<commit_msg>Update build.js<commit_after>var path = require("path");
var stealTools = require("steal-tools");

stealTools.optimize({
  config: path.join(__dirname, "package.json!npm")
}, {
	bundleAssets: false,
	//minify: true
});
<|endoftext|>


<commit_before>var query = location.search.substring(1).split("&");
var params = {};
for(var i = 0; i < query.length; i++) {
  var item = query[i].split("=");
  params[item[0]] = item[1];
}

var packageName  = params.p || 'express'
    width        = (window.innerWidth / 2) - (window.innerWidth / 20),
    height       = width * 0.85,
    outerRadius  = height / 2,
    innerRadius  = outerRadius - 45,
    numResults   = params.t;

function codependencyGraph(codeps) {
  var pkg    = codeps.name,
      names  = codeps.names,
      matrix = codeps.matrix,
      values = codeps.values,
      totals;

  var fill = d3.scale.category20c();

  var fmt = {
    percent: d3.format('.2%'),
    decimal: d3.format(',.2f'),
    integer: d3.format('n')
  }

  var chord = d3.layout.chord()
    .padding(.08)
    .sortSubgroups(d3.descending)
    .sortChords(d3.descending);

  var arc = d3.svg.arc()
    .innerRadius(innerRadius)
    .outerRadius(innerRadius + 20);

  var container = d3.select('#codependencies')
    .append('article')
      .attr('id', codeps.type);

  var svg = container
    .append("svg")
      .attr("width", width)
      .attr("height", height)
    .append("svg:g")
      .attr("id", "circle")
      .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

  svg.append("circle")
    .attr("r", innerRadius + 20);

  var graph = svg.append("g")
    .attr("transform", "translate(" + outerRadius * 1.25 + "," + outerRadius + ")");

  document.getElementById("package-name").innerHTML = pkg;
  chord.matrix(matrix);

  //
  // Compute all the totals for
  // all packages
  //
  totals = values.map(function (arr) {
    return arr.reduce(function (sum, val) {
      return sum + val;
    }, 0);
  });

  //
  // ### function chordTip (d, i)
  // Returns the text for the chord tooltip
  //
  function chordTip (d, i) {
    var source = d.source.index,
        target = d.target.index;

    return [
      '
',
      '
',
      '
',
      '      	',
      '      Raw	',
      '      Weighted	',
      '      Total	',
      '
',
      '
',
      '
',
      '
',
      '      ' + names[source] + '	',
      '      ' + fmt.integer(values[source][target]) + '	',
      '      ' + fmt.decimal(matrix[source][target]) + '%	',
      '      ' + fmt.integer(totals[source]) + '	',
      '
',
      '
',
      '      ' + names[target] + '	',
      '      ' + fmt.integer(values[target][source]) + '	',
      '      ' + fmt.decimal(matrix[target][source]) + '%	',
      '      ' + fmt.integer(totals[target]) + '	',
      '
',
      '
',
      '
'
    ].join('\n');
  }

  //
  // ### function cMouseover (d, i)
  // Mouse enter handler for individual chords
  //
  function cMouseover(d, i) {
    d3.select("#tooltip")
      .style("visibility", "visible")
      .html(chordTip(d, i))
      .style("top", function () { return (d3.event.pageY - 100)+"px"})
      .style("left", function () { return (d3.event.pageX - 100)+"px";})
  };

  // //
  // // ### function groupTip (d, i)
  // // Returns the text for the group tooltip
  // //
  // function groupTip (d) {
  //   var name    = names[d.index],
  //       source  = d.index,
  //       headers = [],
  //       rows    = [];

  //   return [
  //     '
',
  //     '
',
  //     '
',
  //   ].concat(headers).concat([
  //     '
',
  //     '
',
  //     '
'
  //   ]).concat(rows).concat([
  //     '
',
  //     '
'
  //   ]).join('\n');
  // }

  //
  // ### function cMouseover (d, i)
  // Mouse enter handler for individual groups (i.e. packages)
  //
  function gMouseover(d, i) {
    // d3.select("#tooltip")
    //   .style("visibility", "visible")
    //   .html(groupTip(d))
    //   .style("top", function () { return (d3.event.pageY - 80)+"px"})
    //   .style("left", function () { return (d3.event.pageX - 130)+"px";});

    chordPaths.classed("fade", function(p) {
      return p.source.index != i
          && p.target.index != i;
    });
  }

  //
  // Hides the tooltip overlay
  //
  function hide() {
    d3.select("#tooltip").style("visibility", "hidden");
  }

  //
  // Create arcs representing the codependent
  // package relationships
  //
  var g = svg.selectAll("g.group")
      .data(chord.groups())
    .enter().append("svg:g")
      .attr("class", "group")
      .style("fill", function(d) { return fill(d.index); })
      .style("stroke", function(d) { d3.rgb(fill(d.index)).darker() })
      .on("mouseover", gMouseover);
      // .on("mouseout", hide);

  g.append("svg:path")
    .style("fill", function(d) { return fill(d.index); })
    .attr("d", arc);

  //
  // Set outer package labels
  //
  g.append("svg:text")
    .each(function(d) { d.angle = (d.startAngle + d.endAngle) / 2; })
      .attr("dy", ".35em")
      .attr("text-anchor", function(d) { return d.angle > Math.PI ? "end" : null; })
      .attr("transform", function(d) {
        return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")"
          + "translate(" + (innerRadius + 26) + ")"
          + (d.angle > Math.PI ? "rotate(180)" : "");
      })
      .text(function(d) { return names[d.index]; });

  //
  // Create chords
  //
  var chordPaths = svg.selectAll("path.chord")
      .data(chord.chords())
    .enter().append("svg:path")
      .attr("class", "chord")
      .style("stroke", function(d) { return d3.rgb(fill(d.source.index)).darker(); })
      .style("fill", function(d) { return fill(d.source.index); })
      .attr("d", d3.svg.chord().radius(innerRadius))
      .on("mouseover", cMouseover)
      .on("mouseout", hide);

  d3.select(window.frameElement).style("height", outerRadius * 2 + "px");

  container.append('h3')
    .style('margin-top', '30px')
    .style('margin-left', (width / 3) + 'px' )
    .text(codeps.type);
}

d3.json("samples/" + packageName + '.json', function(error, display) {
  ['dependencies', 'devDependencies'].forEach(function (type) {
    display[type].name = packageName;
    display[type].type = type;
    codependencyGraph(display[type]);
  });
});<commit_msg>[ux] More UX polish on codeps.<commit_after>
//
// ### function querystring()
// Returns a parsed querystring using a __very__
// naive parsing method.
//
function querystring() {
  return location.search.substring(1).split("&")
    .reduce(function (params, value) {
      parts = value.split('=');
      params[parts[0]] = parts[1];
      return params;
    }, {});
}

var params      = querystring(),
    packageName = params.p || 'express';

//
// ### function codependencyGraph (codeps)
// Draws the codependency graph based on the overall size
// of the relationship.
//
function codependencyGraph(codeps) {
  var width       = (window.innerWidth / 2) - (window.innerWidth / 20),
      height      = width * 0.85,
      outerRadius = height / 2,
      innerRadius = outerRadius - 45,
      matrix      = codeps.matrix,
      values      = codeps.values,
      names       = codeps.names,
      pkg         = codeps.name,
      totals;

  var fill = d3.scale.category20c();

  var fmt = {
    percent: d3.format('.2%'),
    decimal: d3.format(',.2f'),
    integer: d3.format('n')
  }

  var chord = d3.layout.chord()
    .padding(.08)
    .sortSubgroups(d3.descending)
    .sortChords(d3.descending);

  var arc = d3.svg.arc()
    .innerRadius(innerRadius)
    .outerRadius(innerRadius + 20);

  var container = d3.select('#codependencies')
    .append('article')
      .attr('id', codeps.type);

  var svg = container
    .append("svg")
      .attr("width", width)
      .attr("height", height)
    .append("svg:g")
      .attr("id", "circle")
      .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

  svg.append("circle")
    .attr("r", innerRadius + 20);

  var graph = svg.append("g")
    .attr("transform", "translate(" + outerRadius * 1.25 + "," + outerRadius + ")");

  document.getElementById("package-name").innerHTML = pkg;
  chord.matrix(matrix);

  //
  // Compute all the totals for
  // all packages
  //
  totals = values.map(function (arr) {
    return arr.reduce(function (sum, val) {
      return sum + val;
    }, 0);
  });

  //
  // ### function chordTip (d, i)
  // Returns the text for the chord tooltip
  //
  function chordTip (d, i) {
    var source = d.source.index,
        target = d.target.index;

    return [
      '
',
      '
',
      '
',
      '      	',
      '      Raw	',
      '      Weighted	',
      '      Total	',
      '
',
      '
',
      '
',
      '
',
      '      ' + names[source] + '	',
      '      ' + fmt.integer(values[source][target]) + '	',
      '      ' + fmt.decimal(matrix[source][target]) + '%	',
      '      ' + fmt.integer(totals[source]) + '	',
      '
',
      '
',
      '      ' + names[target] + '	',
      '      ' + fmt.integer(values[target][source]) + '	',
      '      ' + fmt.decimal(matrix[target][source]) + '%	',
      '      ' + fmt.integer(totals[target]) + '	',
      '
',
      '
',
      '
'
    ].join('\n');
  }

  //
  // ### function cMouseover (d, i)
  // Mouse enter handler for individual chords
  //
  function cMouseover(d, i) {
    d3.select("#tooltip")
      .style("visibility", "visible")
      .html(chordTip(d, i))
      .style("top", function () { return (d3.event.pageY - 100)+"px"})
      .style("left", function () { return (d3.event.pageX - 100)+"px";})
  };

  // //
  // // ### function groupTip (d, i)
  // // Returns the text for the group tooltip
  // //
  // function groupTip (d) {
  //   var name    = names[d.index],
  //       source  = d.index,
  //       headers = [],
  //       rows    = [];

  //   return [
  //     '
',
  //     '
',
  //     '
',
  //   ].concat(headers).concat([
  //     '
',
  //     '
',
  //     '
'
  //   ]).concat(rows).concat([
  //     '
',
  //     '
'
  //   ]).join('\n');
  // }

  //
  // ### function cMouseover (d, i)
  // Mouse enter handler for individual groups (i.e. packages)
  //
  function gMouseover(d, i) {
    // d3.select("#tooltip")
    //   .style("visibility", "visible")
    //   .html(groupTip(d))
    //   .style("top", function () { return (d3.event.pageY - 80)+"px"})
    //   .style("left", function () { return (d3.event.pageX - 130)+"px";});

    chordPaths.classed("fade", function(p) {
      return p.source.index != i
          && p.target.index != i;
    });
  }

  //
  // Hides the tooltip overlay
  //
  function hide() {
    d3.select("#tooltip").style("visibility", "hidden");
  }

  //
  // Create arcs representing the codependent
  // package relationships
  //
  var g = svg.selectAll("g.group")
      .data(chord.groups())
    .enter().append("svg:g")
      .attr("class", "group")
      .style("fill", function(d) { return fill(d.index); })
      .style("stroke", function(d) { d3.rgb(fill(d.index)).darker() })
      .on("mouseover", gMouseover);
      // .on("mouseout", hide);

  g.append("svg:path")
    .style("fill", function(d) { return fill(d.index); })
    .attr("d", arc);

  //
  // Set outer package labels
  //
  g.append("svg:text")
    .each(function(d) { d.angle = (d.startAngle + d.endAngle) / 2; })
      .attr("dy", ".35em")
      .attr("text-anchor", function(d) { return d.angle > Math.PI ? "end" : null; })
      .attr("transform", function(d) {
        return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")"
          + "translate(" + (innerRadius + 26) + ")"
          + (d.angle > Math.PI ? "rotate(180)" : "");
      })
      .text(function(d) { return names[d.index]; });

  //
  // Create chords
  //
  var chordPaths = svg.selectAll("path.chord")
      .data(chord.chords())
    .enter().append("svg:path")
      .attr("class", "chord")
      .style("stroke", function(d) { return d3.rgb(fill(d.source.index)).darker(); })
      .style("fill", function(d) { return fill(d.source.index); })
      .attr("d", d3.svg.chord().radius(innerRadius))
      .on("mouseover", cMouseover)
      .on("mouseout", hide);

  d3.select(window.frameElement).style("height", outerRadius * 2 + "px");

  //
  // Append the
 representing the subtitle of this diagram.
  //
  container.append('h3')
    .style('margin-top', '30px')
    .style('margin-left', (width / 3) + 'px' )
    .text(codeps.type);
}

//
// Download the JSON itself and calculate the relative widths
// based on the totals.
//
d3.json("samples/" + packageName + '.json', function(error, display) {
  ['dependencies', 'devDependencies'].forEach(function (type) {
    display[type].name = packageName;
    display[type].type = type;
    codependencyGraph(display[type]);
  });
});<|endoftext|>


<commit_before>"use strict";

// From https://www.abeautifulsite.net/parsing-urls-in-javascript
function parseURL(url) {
  var parser = document.createElement('a'),
      searchObject = {},
      queries, split, i;
  // Let the browser do the work
  parser.href = url;
  // Convert query string to object
  queries = parser.search.replace(/^\?/, '').split('&');
  for (i = 0; i < queries.length; i++) {
    split = queries[i].split('=');
    searchObject[split[0]] = split[1];
  }
  return {
    protocol: parser.protocol,
    host: parser.host,
    hostname: parser.hostname,
    port: parser.port,
    pathname: parser.pathname,
    search: parser.search,
    searchObject: searchObject,
    hash: parser.hash
  }
}

function postMessageHandler(event) {
  // Uncomment to debug
  // console.log("We've got a message!");
  // console.log("* Message:", event.data);
  // console.log("* Origin:", event.origin);
  // console.log("* Source:", event.source);

  // Set document title
  window.document.title = event.data.title;

  // Calculate new path based on the iframe src and the url provided in the message
  let newPath = containerPathName + event.data.href + event.data.hash;
  history.replaceState(event.data, event.data.title, newPath)
}

// The pathname of the page containing the iframe
let containerPathName = window.location.pathname
if (containerPathName[containerPathName.length - 1] === "/") {
  containerPathName = containerPathName.slice(0, -1);
}

window.addEventListener("message", postMessageHandler, false);

window.addEventListener('DOMContentLoaded', () => {
  let gobiertoEmbed = document.querySelector("[gobierto-embed]");
  if (gobiertoEmbed === null) {
    throw "Div gobierto-embed not found!";
  }
  let iframe = document.createElement('iframe');
  iframe.src = gobiertoEmbed.attributes['gobierto-embed'].nodeValue + "?embed";
  iframe.id = 'gobierto-embed';
  iframe.allowfullscreen = true;
  iframe.style="width:100%; height:1400px;border:0px;";

  gobiertoEmbed.appendChild(iframe)
});

<commit_msg>Remove unused function<commit_after>"use strict";

function postMessageHandler(event) {
  // Uncomment to debug
  // console.log("We've got a message!");
  // console.log("* Message:", event.data);
  // console.log("* Origin:", event.origin);
  // console.log("* Source:", event.source);

  // Set document title
  window.document.title = event.data.title;

  // Calculate new path based on the iframe src and the url provided in the message
  let newPath = containerPathName + event.data.href + event.data.hash;
  history.replaceState(event.data, event.data.title, newPath)
}

// The pathname of the page containing the iframe
let containerPathName = window.location.pathname
if (containerPathName[containerPathName.length - 1] === "/") {
  containerPathName = containerPathName.slice(0, -1);
}

window.addEventListener("message", postMessageHandler, false);

window.addEventListener('DOMContentLoaded', () => {
  let gobiertoEmbed = document.querySelector("[gobierto-embed]");
  if (gobiertoEmbed === null) {
    throw "Div gobierto-embed not found!";
  }
  let iframe = document.createElement('iframe');
  iframe.src = gobiertoEmbed.attributes['gobierto-embed'].nodeValue + "?embed";
  iframe.id = 'gobierto-embed';
  iframe.allowfullscreen = true;
  iframe.style="width:100%; height:1400px;border:0px;";

  gobiertoEmbed.appendChild(iframe)
});

<|endoftext|>


<commit_before>$('.toggleInformation').click(function () {
    $('.information').slideToggle()
})
$('.toggleMapInformation').click(function () {
    $('#map_wrapper').toggle()
    _.once(renderMap)()
})

$.getJSON('/courts', function (allData) {
    //var data = [].concat(_.map(allData, _.identity)
    var data = [].concat(allData.meilahti, allData.herttoniemi, allData.kulosaari)
    $('.schedule').html(groupBySortedAsList(data, 'date').map(toDateSection).join(''))
})

$('.schedule').on('click', '.locationLabel', function (e) {
    console.log('click')
    var $locationLabel = $(e.currentTarget)
    $locationLabel.toggle()
    $locationLabel.parent().find('.fieldLabel').toggle()
})
$.getJSON('/locations', function (locations) {
    window.locations = locations
    $('.information tbody').html(locations.map(function (obj) {
        var address = obj.address
        var url = obj.url
        var title = obj.title
        var tel = obj.tel
        return '
' + (url ? '' + title + '' : title) + '	' +
            '' + address + '	' +
            '' + tel + '
'
    }).join(''))
})
function renderMap() {
    var bounds = new google.maps.LatLngBounds()
    var map = new google.maps.Map(document.getElementById("map_canvas"), {mapTypeId: 'roadmap'})
    map.setTilt(45)
    var infoWindow = new google.maps.InfoWindow()
    locations.filter(function (loc) {
        return loc.lat !== null
    }).forEach(function (loc, i) {
        var position = new google.maps.LatLng(loc.lat, loc.lng)
        bounds.extend(position)
        var marker = new google.maps.Marker({
            position: position,
            map:      map,
            title:    loc.title
        })
        google.maps.event.addListener(marker, 'click', (function (marker, i) {
            return function () {
                infoWindow.setContent(locationTooltip(loc))
                infoWindow.open(map, marker)
            }
        })(marker, i))
        map.fitBounds(bounds)
    })
}

function locationTooltip(location) {
    return '
' + location.title + '

Varausjärjestelmä
' +
        '
' + location.address + '
' +
        '
' + location.tel + '
'
}

function toDateSection(dateObject) {
    var isoDate = dateObject.key
    var times = dateObject.val
    return '
' + new Date(isoDate).toDateString() + '
' +
        groupBySortedAsList(times, 'time').map(toTimeRow).join('')
}

function toTimeRow(timeObject) {
    var isoTime = timeObject.key
    var fields = timeObject.val
    return '
' + isoTime + '' +
        groupBySortedAsList(fields, 'location').map(toLocationButtonGroup).join('') + '
'
}

function toLocationButtonGroup(locationFields) {
    var location = locationFields.key
    var fields = locationFields.val
    return '<button type="button" class="locationLabel btn ' +
        location +
        ' btn-xs">' + location + ' (' + fields.length + ')</button>' +
        fields.map(toButtonMarkup).join('') + ''
}

function toButtonMarkup(field) {
    return '<button type="button" class="fieldLabel btn ' + field.location + ' btn-xs">' + field.field + '</button>'
}

function groupBySortedAsList(list, key) {
    return _.sortBy(_.map(_.groupBy(list, key), objectToArray), 'key')
}

function objectToArray(val, key) {
    return {key: key, val: val}
}
<commit_msg>Make joining object values generic<commit_after>$('.toggleInformation').click(function () {
    $('.information').slideToggle()
})
$('.toggleMapInformation').click(function () {
    $('#map_wrapper').toggle()
    _.once(renderMap)()
})

$.getJSON('/courts', function (allData) {
    var data = _.flatten((_.map(allData, _.identity)))
    $('.schedule').html(groupBySortedAsList(data, 'date').map(toDateSection).join(''))
})

$('.schedule').on('click', '.locationLabel', function (e) {
    console.log('click')
    var $locationLabel = $(e.currentTarget)
    $locationLabel.toggle()
    $locationLabel.parent().find('.fieldLabel').toggle()
})
$.getJSON('/locations', function (locations) {
    window.locations = locations
    $('.information tbody').html(locations.map(function (obj) {
        var address = obj.address
        var url = obj.url
        var title = obj.title
        var tel = obj.tel
        return '
' + (url ? '' + title + '' : title) + '	' +
            '' + address + '	' +
            '' + tel + '
'
    }).join(''))
})
function renderMap() {
    var bounds = new google.maps.LatLngBounds()
    var map = new google.maps.Map(document.getElementById("map_canvas"), {mapTypeId: 'roadmap'})
    map.setTilt(45)
    var infoWindow = new google.maps.InfoWindow()
    locations.filter(function (loc) {
        return loc.lat !== null
    }).forEach(function (loc, i) {
        var position = new google.maps.LatLng(loc.lat, loc.lng)
        bounds.extend(position)
        var marker = new google.maps.Marker({
            position: position,
            map:      map,
            title:    loc.title
        })
        google.maps.event.addListener(marker, 'click', (function (marker, i) {
            return function () {
                infoWindow.setContent(locationTooltip(loc))
                infoWindow.open(map, marker)
            }
        })(marker, i))
        map.fitBounds(bounds)
    })
}

function locationTooltip(location) {
    return '
' + location.title + '

Varausjärjestelmä
' +
        '
' + location.address + '
' +
        '
' + location.tel + '
'
}

function toDateSection(dateObject) {
    var isoDate = dateObject.key
    var times = dateObject.val
    return '
' + new Date(isoDate).toDateString() + '
' +
        groupBySortedAsList(times, 'time').map(toTimeRow).join('')
}

function toTimeRow(timeObject) {
    var isoTime = timeObject.key
    var fields = timeObject.val
    return '
' + isoTime + '' +
        groupBySortedAsList(fields, 'location').map(toLocationButtonGroup).join('') + '
'
}

function toLocationButtonGroup(locationFields) {
    var location = locationFields.key
    var fields = locationFields.val
    return '<button type="button" class="locationLabel btn ' +
        location +
        ' btn-xs">' + location + ' (' + fields.length + ')</button>' +
        fields.map(toButtonMarkup).join('') + ''
}

function toButtonMarkup(field) {
    return '<button type="button" class="fieldLabel btn ' + field.location + ' btn-xs">' + field.field + '</button>'
}

function groupBySortedAsList(list, key) {
    return _.sortBy(_.map(_.groupBy(list, key), objectToArray), 'key')
}

function objectToArray(val, key) {
    return {key: key, val: val}
}
<|endoftext|>


<commit_before>var s3_upload_file = function(url, formData) {
  $('.directUpload').find("input:file").each(function(i, elem) {

    var fileInput    = $(elem);
    var form         = $('.directUpload').find('form:first');
    var submitButton = form.find('input[type="submit"]');
    var progressBar  = $("

");
    var barContainer = $("

").append(progressBar);
    fileInput.after(barContainer);
    fileInput.fileupload({
      fileInput:       fileInput,
      url:             url,
      type:            'POST',
      formData:         formData,
      paramName:        'file', // S3 does not like nested name fields i.e. name="user[avatar_url]"
      dataType:         'XML',  // S3 returns XML if success_action_status is set to 201
      replaceFileInput: false,
      add: function (e,data){
        var uploadFile = data.files[0];
        if (!(/\.(params|mzXML)$/i).test(uploadFile.name)) {
            alert('Incorrect file type');
        }else {
            data.submit();
        }
      },
      progressall: function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        progressBar.css('width', progress + '%')
      },
      start: function (e) {
        e.preventDefault()
        submitButton.prop('disabled', true);

        progressBar.
          css('background', 'green').
          css('display', 'block').
          css('width', '0%').
          text("Loading...");
      },
      done: function(e, data) {
        submitButton.prop('disabled', false);
        progressBar.text("Uploading done");

        // extract key and generate URL from response
        var key   = $(data.jqXHR.responseXML).find("Key").text();

        // create hidden field
        var input = $("<input />", { type:'hidden', name: 's3_key', value: key })
        form.append(input);
      },
      fail: function(e, data) {
        submitButton.prop('disabled', false);

        progressBar.
          css("background", "red").
          text("Failed");
      }
    });
  });
};<commit_msg>added .txt file as valid file type<commit_after>var s3_upload_file = function(url, formData) {
  $('.directUpload').find("input:file").each(function(i, elem) {

    var fileInput    = $(elem);
    var form         = $('.directUpload').find('form:first');
    var submitButton = form.find('input[type="submit"]');
    var progressBar  = $("

");
    var barContainer = $("

").append(progressBar);
    fileInput.after(barContainer);
    fileInput.fileupload({
      fileInput:       fileInput,
      url:             url,
      type:            'POST',
      formData:         formData,
      paramName:        'file', // S3 does not like nested name fields i.e. name="user[avatar_url]"
      dataType:         'XML',  // S3 returns XML if success_action_status is set to 201
      replaceFileInput: false,
      add: function (e,data){
        var uploadFile = data.files[0];
        if (!(/\.(params|mzXML|txt)$/i).test(uploadFile.name)) {
            alert('Incorrect file type');
        }else {
            data.submit();
        }
      },
      progressall: function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        progressBar.css('width', progress + '%')
      },
      start: function (e) {
        e.preventDefault()
        submitButton.prop('disabled', true);

        progressBar.
          css('background', 'green').
          css('display', 'block').
          css('width', '0%').
          text("Loading...");
      },
      done: function(e, data) {
        submitButton.prop('disabled', false);
        progressBar.text("Uploading done");

        // extract key and generate URL from response
        var key   = $(data.jqXHR.responseXML).find("Key").text();

        // create hidden field
        var input = $("<input />", { type:'hidden', name: 's3_key', value: key })
        form.append(input);
      },
      fail: function(e, data) {
        submitButton.prop('disabled', false);

        progressBar.
          css("background", "red").
          text("Failed");
      }
    });
  });
};<|endoftext|>


<commit_before>define(function () {
	'use strict';

	var data = {};

	// Functions in alphabetical order
	// Functions are declared globally so that eval can access them.

	window.answer = function (expression) {
		data.lastAnswer = expression;

		return 'Answer received';
	};

	window.clear = function () {
		setTimeout(function () {
			$('.console li:not(.input-container)').remove();
		}, 10);
	};

	window.help = function () {
		return [
			'There are a number of useful commands to help you:',
			'clear() clears the previous commands from the console (or you can' +
				'press ctrl+l).',
			'help() displays this help message.',
			'info() displays information about Try Regex.',
			'reset() will clear all the previous commands and return you to' +
				'the beginning of the tutorial'
		].join('\n\n');
	};

	window.info = function () {
		return 'Try Regex is an interactive regular expressions tutorial ' +
			'written by Callum Macrae. Ask him for help!';
	};

	window.reset = function () {
		localStorage.removeItem('currentLesson');
		localStorage.removeItem('codeSoFar');

		setTimeout(location.reload.bind(location), 100);

		return 'Resetting…';
	};

	window.setName = function (name) {
		if (data.name) {
			return 'You have already set your name! ' +
				'Type reset() to start again, if you want.';
		}

		var firstName = name.split(' ')[0];

		if (firstName === 'code') {
			return 'Your name isn\'t code! Stop it.';
		}

		window.bio = 'A developer called ' + firstName + ' is learning regex';

		data.name = name;
		data.firstName = firstName;

		return 'Hello, ' + name + '!';
	};

	// Global vars in order of appearance

	window.num = '123456';

	window.shortStory = 'A regular expression (also regex or regexp) is a string.';

	window.bracketNumbers = '(123) (123456) (123456789)';
	window.shorterStory = window.bracketNumbers;

	window.username = 'BobbyTables';

	window.charTypeTest = 'Approximately 1920';

	window.possibleUrl = 'https://example.com/';

	window.rabbit = 'The rabbit ate';

	window.userData = 'user1=sad;\nuser2=angry;\n' +
		window.username + '=happy;\nuser4=crazy';

	window.boldText = '**bold text!**';

	window.partialSums = '1+1,2+2,3+3=,8+10,10+10+20,6+3=9,5+3';

	return data;
});<commit_msg>Shortened a line.<commit_after>define(function () {
	'use strict';

	var data = {};

	// Functions in alphabetical order
	// Functions are declared globally so that eval can access them.

	window.answer = function (expression) {
		data.lastAnswer = expression;

		return 'Answer received';
	};

	window.clear = function () {
		setTimeout(function () {
			$('.console li:not(.input-container)').remove();
		}, 10);
	};

	window.help = function () {
		return [
			'There are a number of useful commands to help you:',
			'clear() clears the previous commands from the console (or you ' +
				'can press ctrl+l).',
			'help() displays this help message.',
			'info() displays information about Try Regex.',
			'reset() will clear all the previous commands and return you to' +
				'the beginning of the tutorial'
		].join('\n\n');
	};

	window.info = function () {
		return 'Try Regex is an interactive regular expressions tutorial ' +
			'written by Callum Macrae. Ask him for help!';
	};

	window.reset = function () {
		localStorage.removeItem('currentLesson');
		localStorage.removeItem('codeSoFar');

		setTimeout(location.reload.bind(location), 100);

		return 'Resetting…';
	};

	window.setName = function (name) {
		if (data.name) {
			return 'You have already set your name! ' +
				'Type reset() to start again, if you want.';
		}

		var firstName = name.split(' ')[0];

		if (firstName === 'code') {
			return 'Your name isn\'t code! Stop it.';
		}

		window.bio = 'A developer called ' + firstName + ' is learning regex';

		data.name = name;
		data.firstName = firstName;

		return 'Hello, ' + name + '!';
	};

	// Global vars in order of appearance

	window.num = '123456';

	window.shortStory = 'A regular expression (also regex or regexp) is a string.';

	window.bracketNumbers = '(123) (123456) (123456789)';
	window.shorterStory = window.bracketNumbers;

	window.username = 'BobbyTables';

	window.charTypeTest = 'Approximately 1920';

	window.possibleUrl = 'https://example.com/';

	window.rabbit = 'The rabbit ate';

	window.userData = 'user1=sad;\nuser2=angry;\n' +
		window.username + '=happy;\nuser4=crazy';

	window.boldText = '**bold text!**';

	window.partialSums = '1+1,2+2,3+3=,8+10,10+10+20,6+3=9,5+3';

	return data;
});<|endoftext|>


<commit_before>$(function(){

  $('.show-coach').on('click', function(){
    startTimer();
    transitionToCoach();
  });

  appendTask(task1);
  appendTask(task2);

  appendMessage(message1);
  appendMessage(message2);
  theCoachSays();
  window.setInterval(function(){
    theCoachSays();
  }, 4500);

  $('.add-task').on('click', function(){
  	var hour=$("#hours").val();
  	var mins=$("#minutes").val();
  	var secs=$("#seconds").val();
  	if (!onlyNumbers(hour, mins, secs)) {
  		alert("Please insert only numbers");
  		return;
  	}
  	var tasks = $("#task").val();
  	var task = {
  	hours: hour,
  	minutes: mins,
  	seconds: secs,
  	name: tasks,
  	time: convertMS(hour,mins,secs),
  	};
  	appendTask(task);
  	$("#hours").val('');
  	$("#task").val('');
  	$("#minutes").val('');
  	$("#seconds").val('');
  })
});

function postMessage( message )
{
    $.get("post/?msg="+ message);
}

function getMessages()
{
  $.ajax({ url: "query/?id=" + maxId + "&time=" + full_time + "&date=" + full_date, success: function( data ) {
      data = JSON.parse(data);
      // sanitize the data into valid objects
      for(var i = 0; i < data.length; i++) {
          var message = {"id": "", "name": "", "message": "", "image_url": ""};
          message.id = data[i].pk;
          message.name = data[i].fields.name;
          message.text = data[i].fields.motivation_text;
          message.image_url = data[i].fields.image_url;
          appendMessage(message);
      }
  }, dataType: 'json'});
}

// call when user presses on lets go
function transitionToCoach()
{
  if (isSocial) {
      postMessage('Cheer me on at: http://localhost:8000/motivate ' + time_min);
  }
  $('.coach-page').fadeIn(1000);
  $('.task-number').html("Number of Tasks: " + tasklist.length);
  $('.initial-page').hide();
  getMessages();
  window.setInterval(function() {
      getMessages();
  }, 60000);
}

var finishedlist = [];
var count = 0;
function appendTask(item)
{
  finishedlist.push(0);
  tasklist.push(item);
  $('.task-list').append("

" +
    item.name + "
" +
    "Hour: " + item.hours + " " +
    "Min: " + item.minutes + " " +
    "Sec: " + item.seconds + " " +
    "

");
  count++;
  $('.front-list').prepend("

" +
     "" + item.name + "
" +
  	 "Hours: " + item.hours + " " +
  	 "Min: " + item.minutes + " " +
  	 "Sec: " + item.seconds + " " +
  	 "

");

  if (!readyToGo)
  {
    readyToGo = true;
    $('.lame-coach-message').hide();
    $('.ready-to-go').show();
  }
}

function appendMessage(item)
{
  if (item.id > maxId)
    maxId = item.id;

  // message from twitter
  if (item.image_url.length != 0)
  {
    $('.message-list').prepend($("

" + item.name +
      ": " + item.text + "</span
").fadeIn(1000));
  }
  else
  {
    var random = Math.floor(Math.random()*numberOfPersonOptions) + 1;
    $('.message-list').prepend($("

" + item.name +
      ": " + item.text + "</span
").fadeIn(1000));
  }
}

// accepts a message.  if no message, then random talks.
function theCoachSays(message)
{
  if (message)
  {
    window.clearInterval(coachTimer);
    $('.the-coach').addClass('talking');
    $('.the-coach-says').html(message);
    $('.the-coach-says').show();
    setTimeout(function(){
      $('.the-coach').removeClass('talking');
      $('.the-coach-says').hide();
      randomTalking();
    }, 2000 );
  }
  else {
    window.clearInterval(coachTimer);
    $('.the-coach').addClass('talking');
    $('.the-coach-says').html(coachMessages[Math.floor(Math.random()*coachMessages.length)]);
    $('.the-coach-says').show();
    setTimeout(function(){
      $('.the-coach').removeClass('talking');
      $('.the-coach-says').hide();
    }, 2000 );
    randomTalking();
  }
}
// Coach says random stuff
function randomTalking()
{
  coachTimer = setInterval(function(){
    $('.the-coach').addClass('talking');
    $('.the-coach-says').html(coachMessages[Math.floor(Math.random()*coachMessages.length)]);
    $('.the-coach-says').show();
    setTimeout(function(){
      $('.the-coach').removeClass('talking');
      $('.the-coach-says').hide();
    }, 2000 );
  }, 4500);
}

var date = new Date();
var date_year = date.getFullYear();
var date_day = date.getDate();
var date_month = date.getMonth() + 1;
var full_date = "" + date_year + "-" + date_month + "-" + date_day
var time_min = date.getMinutes();
var time_hours = date.getHours() - 1;
var full_time = "" + time_hours + ":" + time_min + ":00";
var messageList = [];
var maxId = -1;
var isSocial = true;
var numberOfPersonOptions = 2;
var coachMessages = [
  "Work on it harder soldier!",
  "What are you, a chicken?",
  "I really need a cheeseburger right now....",
  "You're doing well!  Just kidding, you're performing like crap.",
  "C'mon man, I've seen babies performing better.",
  "Hello World!",
  "Prove P = NP next!",
  "Man, this hackathon is kinda long, dontcha think?"
]

var tasklist = [];

var coachTimer;
var readyToGo = false; // has someone added a task yet?
var task1 = {
  name: "Study for ORF 309",
  time: 5000,
  hours: 0,
  minutes: 0,
  seconds: 8
};
var task2 = {
  name: "Finish drafting my Hackathon idea",
  time: 10000,
  hours: 0,
  minutes: 0,
  seconds: 10
};
var message1 = {
  id: 0,
  name: "Harold Wu",
  text: "Hey man, I hope you are doing well!  You got this!",
  image_url: ""
};
var message2 = {
  id: 0,
  name: "The Dude",
  text: "Dude, like thats just your opinion man.",
  image_url: 'https://pbs.twimg.com/profile_images/1448108270/image_normal.jpg'
};

/* Checks three imputs contains numbers */
function onlyNumbers(a,b,c)
{
	return !isNaN(a) && isFinite(parseFloat(a))
	&& !isNaN(b) && isFinite(parseFloat(b))
	&& !isNaN(c) && isFinite(parseFloat(c));
}

/* convert time to MS */
function convertMS(a,b,c)
{
	return parseInt(a)*3600000 + parseInt(b)*60000 + parseInt(c)*1000;
}

var taskNum = 0;

/* Used to start timers */
function startTimer()
{
  for (var i = taskNum; i < tasklist.length; i++) {
    if (finishedlist[i] == 0) {
      taskNum = i;
      var task = tasklist[i];
      $($('.task-time')[i]).countdown({until: task.hours + "h " + task.minutes + "m " + task.seconds + "s", format: "HMS", layout:'{d<}{dn} {dl} and {d>}'+
      '{hn} {hl}, {mn} {ml}, {sn} {sl}', onExpiry: expired});
      return;
    }
  }
}

/* Handling expiration of timers */
function expired() {
  if (isSocial) {
      var text = $($('.task-name')[taskNum]).text();
      postMessage("I didn't finish the time in task: "+ text +"! Come cheer me on so I don't fall behind!");
  }
  finishedlist[taskNum] = 1;
  taskNum++;
  startTimer();
}

var finished = 0;

function taskFinished(numTask) {
  theCoachSays("Good job!");
  if (isSocial) {
    var text = $($('.task-name')[numTask]).text();
    postMessage("I just finished my task: "+ text + "! Come and congratulate me!");
  }
  finished++;
  if (finished == tasklist.length) {
    theCoachSays("finished!");
    allDone();
  }
  if (numTask == (taskNum)) {
    expired();
  }
  $('.task-number').html("Number of Tasks: " + (tasklist.length - finished));
  $($('.task-item')[numTask]).fadeOut(1000);
  $($('.task-time')[numTask]).countdown('destroy');
  finishedlist[numTask] = 1;
}

function allDone() {

}
<commit_msg>updated<commit_after>$(function(){

  $('.show-coach').on('click', function(){
    startTimer();
    transitionToCoach();
  });

  appendTask(task1);
  appendTask(task2);

  appendMessage(message1);
  appendMessage(message2);
  theCoachSays();
  window.setInterval(function(){
    theCoachSays();
  }, 4500);

  $('.add-task').on('click', function(){
  	var hour=$("#hours").val();
  	var mins=$("#minutes").val();
  	var secs=$("#seconds").val();
  	if (!onlyNumbers(hour, mins, secs)) {
  		alert("Please insert only numbers");
  		return;
  	}
  	var tasks = $("#task").val();
  	var task = {
  	hours: hour,
  	minutes: mins,
  	seconds: secs,
  	name: tasks,
  	time: convertMS(hour,mins,secs),
  	};
  	appendTask(task);
  	$("#hours").val('');
  	$("#task").val('');
  	$("#minutes").val('');
  	$("#seconds").val('');
  })
});

function postMessage( message )
{
    $.get("post/?msg="+ message);
}

function getMessages()
{
  $.ajax({ url: "query/?id=" + maxId + "&time=" + full_time + "&date=" + full_date, success: function( data ) {
      data = JSON.parse(data);
      // sanitize the data into valid objects
      for(var i = 0; i < data.length; i++) {
          var message = {"id": "", "name": "", "message": "", "image_url": ""};
          message.id = data[i].pk;
          message.name = data[i].fields.name;
          message.text = data[i].fields.motivation_text;
          message.image_url = data[i].fields.image_url;
          appendMessage(message);
      }
  }, dataType: 'json'});
}

// call when user presses on lets go
function transitionToCoach()
{
  if (isSocial) {
      postMessage('Cheer me on at: http://localhost:8000/motivate ' + time_min);
  }
  $('.coach-page').fadeIn(1000);
  $('.task-number').html("Number of Tasks: " + tasklist.length);
  $('.initial-page').hide();
  getMessages();
  window.setInterval(function() {
      getMessages();
  }, 60000);
}

var finishedlist = [];
var count = 0;
function appendTask(item)
{
  finishedlist.push(0);
  tasklist.push(item);
  $('.task-list').append("

" +
    item.name + "
" +
    "Hour: " + item.hours + " " +
    "Min: " + item.minutes + " " +
    "Sec: " + item.seconds + " " +
    "

");
  count++;
  $('.front-list').prepend("

" +
     "" + item.name + "
" +
  	 "Hours: " + item.hours + " " +
  	 "Min: " + item.minutes + " " +
  	 "Sec: " + item.seconds + " " +
  	 "

");

  if (!readyToGo)
  {
    readyToGo = true;
    $('.lame-coach-message').hide();
    $('.ready-to-go').show();
  }
}

function appendMessage(item)
{
  if (item.id > maxId)
    maxId = item.id;

  // message from twitter
  if (item.image_url.length != 0)
  {
    $('.message-list').prepend($("

" + item.name +
      ": " + item.text + "</span
").fadeIn(1000));
  }
  else
  {
    var random = Math.floor(Math.random()*numberOfPersonOptions) + 1;
    $('.message-list').prepend($("

" + item.name +
      ": " + item.text + "</span
").fadeIn(1000));
  }
}

// accepts a message.  if no message, then random talks.
function theCoachSays(message)
{
  if (message)
  {
    window.clearInterval(coachTimer);
    $('.the-coach').addClass('talking');
    $('.the-coach-says').html(message);
    $('.the-coach-says').show();
    setTimeout(function(){
      $('.the-coach').removeClass('talking');
      $('.the-coach-says').hide();
      randomTalking();
    }, 2000 );
  }
  else {
    window.clearInterval(coachTimer);
    $('.the-coach').addClass('talking');
    $('.the-coach-says').html(coachMessages[Math.floor(Math.random()*coachMessages.length)]);
    $('.the-coach-says').show();
    setTimeout(function(){
      $('.the-coach').removeClass('talking');
      $('.the-coach-says').hide();
    }, 2000 );
    randomTalking();
  }
}
// Coach says random stuff
function randomTalking()
{
  coachTimer = setInterval(function(){
    $('.the-coach').addClass('talking');
    $('.the-coach-says').html(coachMessages[Math.floor(Math.random()*coachMessages.length)]);
    $('.the-coach-says').show();
    setTimeout(function(){
      $('.the-coach').removeClass('talking');
      $('.the-coach-says').hide();
    }, 2000 );
  }, 4500);
}

var date = new Date();
var date_year = date.getFullYear();
var date_day = date.getDate();
var date_month = date.getMonth() + 1;
var full_date = "" + date_year + "-" + date_month + "-" + date_day
var time_min = date.getMinutes();
var time_hours = date.getHours() - 1;
var full_time = "" + time_hours + ":" + time_min + ":00";
var messageList = [];
var maxId = -1;
var isSocial = true;
var numberOfPersonOptions = 2;
var coachMessages = [
  "Work on it harder soldier!",
  "What are you, a chicken?",
  "I really need a cheeseburger right now....",
  "You're doing well!  Just kidding, you're performing like crap.",
  "C'mon man, I've seen babies performing better.",
  "Hello World!",
  "Prove P = NP next!",
  "Man, this hackathon is kinda long, dontcha think?"
]

var tasklist = [];

var coachTimer;
var readyToGo = false; // has someone added a task yet?
var task1 = {
  name: "Study for ORF 309",
  time: 5000,
  hours: 0,
  minutes: 0,
  seconds: 8
};
var task2 = {
  name: "Finish drafting my Hackathon idea",
  time: 10000,
  hours: 0,
  minutes: 0,
  seconds: 10
};
var message1 = {
  id: 0,
  name: "Harold Wu",
  text: "Hey man, I hope you are doing well!  You got this!",
  image_url: ""
};
var message2 = {
  id: 0,
  name: "The Dude",
  text: "Dude, like thats just your opinion man.",
  image_url: 'https://pbs.twimg.com/profile_images/1448108270/image_normal.jpg'
};

/* Checks three imputs contains numbers */
function onlyNumbers(a,b,c)
{
	return !isNaN(a) && isFinite(parseFloat(a))
	&& !isNaN(b) && isFinite(parseFloat(b))
	&& !isNaN(c) && isFinite(parseFloat(c));
}

/* convert time to MS */
function convertMS(a,b,c)
{
	return parseInt(a)*3600000 + parseInt(b)*60000 + parseInt(c)*1000;
}

var taskNum = 0;

/* Used to start timers */
function startTimer()
{
  for (var i = taskNum; i < tasklist.length; i++) {
    if (finishedlist[i] == 0) {
      taskNum = i;
      var task = tasklist[i];
      $($('.task-time')[i]).countdown({until: task.hours + "h " + task.minutes + "m " + task.seconds + "s", format: "HMS", layout:'{d<}{dn} {dl} and {d>}'+
      '{hn} {hl}, {mn} {ml}, {sn} {sl}', onExpiry: expired});
      return;
    }
  }
}

/* Handling expiration of timers */
function expired() {
  if (isSocial) {
      var text = $($('.task-name')[taskNum]).text();
      postMessage("I didn't finish the task in time: "+ text +"! Come cheer me on so I don't fall behind!");
  }
  finishedlist[taskNum] = 1;
  taskNum++;
  startTimer();
}

var finished = 0;

function taskFinished(numTask) {
  theCoachSays("Good job!");
  if (isSocial) {
    var text = $($('.task-name')[numTask]).text();
    postMessage("I just finished my task: "+ text + "! Come and congratulate me!");
  }
  finished++;
  if (finished == tasklist.length) {
    theCoachSays("finished!");
    allDone();
  }
  if (numTask == (taskNum)) {
    expired();
  }
  $('.task-number').html("Number of Tasks: " + (tasklist.length - finished));
  $($('.task-item')[numTask]).fadeOut(1000);
  $($('.task-time')[numTask]).countdown('destroy');
  finishedlist[numTask] = 1;
}

function allDone() {

}
<|endoftext|>


<commit_before>exports.seed = function(knex, Promise) {
    // Deletes ALL existing entries
    return knex('users').del()
        .then(function() {
            // Inserts seed entries
            return knex('users').insert([{
                    id: 1,
                    first_name: 'Kevin',
                    last_name: 'Seagraves',
                    photo: 'https://media.licdn.com/mpr/mpr/shrinknp_400_400/AAEAAQAAAAAAAA2PAAAAJGQyNzU1YmI2LWE3NTgtNDg2Yi05YjRhLWQzY2Q2MTQ5ZmQyMA.jpg',
                    email: "me@me.com",
                    role_id: 1
                },
                {
                    id: 2,
                    first_name: 'Tim',
                    last_name: 'Cutter',
                    photo: 'https://media.licdn.com/mpr/mpr/shrinknp_400_400/AAEAAQAAAAAAAAspAAAAJDViMWUxODU0LTVjYWQtNGQ3Zi1iYTA1LThiZDg0MmU0OWUxOQ.jpg',
                    email: "you@you.com",
                    role_id: 2
                },
                {
                    id: 3,
                    first_name: 'Royal',
                    last_name: 'Robbins',
                    photo: 'https://static.royalrobbins.com/media/wysiwyg/Royalropes_sepia-padding2.jpg',
                    email: "him@him.com",
                    role_id: 3
                },
                {
                  id: 4,
                first_name: 'Adam',
                last_name: 'Rose',
                photo: 'https://static.royalrobbins.com/media/wysiwyg/Royalropes_sepia-padding2.jpg',
                email: "adamrose@mail.com",
                role_id: 1
              },
              {
                id: 5,
              first_name: 'Flavor',
              last_name: 'Lord',
              photo: './images/FlavorLord (1).png',
              email: "guyfieri@mail.com",
              role_id: 1
            },
            {
              id: 6,
            first_name: 'Sandra',
            last_name: 'Tooley',
            photo: 'https://static.royalrobbins.com/media/wysiwyg/Royalropes_sepia-padding2.jpg',
            email: "sandratooley@mail.com",
            role_id: 1
          },
            ]);
        })
        .then(() => {
            return knex.raw("SELECT setval('users_id_seq', (SELECT MAX(id) FROM users));")
        })
};
<commit_msg>adam rose<commit_after>exports.seed = function(knex, Promise) {
    // Deletes ALL existing entries
    return knex('users').del()
        .then(function() {
            // Inserts seed entries
            return knex('users').insert([{
                    id: 1,
                    first_name: 'Kevin',
                    last_name: 'Seagraves',
                    photo: 'https://media.licdn.com/mpr/mpr/shrinknp_400_400/AAEAAQAAAAAAAA2PAAAAJGQyNzU1YmI2LWE3NTgtNDg2Yi05YjRhLWQzY2Q2MTQ5ZmQyMA.jpg',
                    email: "me@me.com",
                    role_id: 1
                },
                {
                    id: 2,
                    first_name: 'Tim',
                    last_name: 'Cutter',
                    photo: 'https://media.licdn.com/mpr/mpr/shrinknp_400_400/AAEAAQAAAAAAAAspAAAAJDViMWUxODU0LTVjYWQtNGQ3Zi1iYTA1LThiZDg0MmU0OWUxOQ.jpg',
                    email: "you@you.com",
                    role_id: 2
                },
                {
                    id: 3,
                    first_name: 'Royal',
                    last_name: 'Robbins',
                    photo: 'https://static.royalrobbins.com/media/wysiwyg/Royalropes_sepia-padding2.jpg',
                    email: "him@him.com",
                    role_id: 3
                },
                {
                  id: 4,
                first_name: 'Adam',
                last_name: 'Rose',
                photo: 'https://static1.squarespace.com/static/54298190e4b0027ed7da9fa3/t/561ffd3ae4b0662b883e75f7/1444937020722/',
                email: "adamrose@mail.com",
                role_id: 1
              },
              {
                id: 5,
              first_name: 'Flavor',
              last_name: 'Lord',
              photo: './images/FlavorLord (1).png',
              email: "guyfieri@mail.com",
              role_id: 1
            },
            {
              id: 6,
            first_name: 'Sandra',
            last_name: 'Tooley',
            photo: 'https://static.royalrobbins.com/media/wysiwyg/Royalropes_sepia-padding2.jpg',
            email: "sandratooley@mail.com",
            role_id: 1
          },
            ]);
        })
        .then(() => {
            return knex.raw("SELECT setval('users_id_seq', (SELECT MAX(id) FROM users));")
        })
};
<|endoftext|>