<commit_before>var mouse = {};
var move;

var cskey = "";
var cskeycode = 0;

function getmover(mouse) {
    var mov = null;
    var adist = 1000000;
    var diff;
    for (var i = 0; i < csgeo.free.length; i++) {
        var el = csgeo.free[i];
        if (el.pinned)
            continue;

        var dx, dy, dist;
        var sc = csport.drawingstate.matrix.sdet;
        if (el.kind === "P") {
            var p = List.normalizeZ(el.homog);
            if (!List._helper.isAlmostReal(p))
                continue;
            dx = p.value[0].value.real - mouse.x;
            dy = p.value[1].value.real - mouse.y;
            dist = Math.sqrt(dx * dx + dy * dy);
            if (el.narrow & dist > 20 / sc) dist = 10000;
        } else if (el.kind === "C") { //Must be CircleMr
            var mid = csgeo.csnames[el.args[0]];
            var rad = el.radius;
            var xx = CSNumber.div(mid.homog.value[0], mid.homog.value[2]).value.real;
            var yy = CSNumber.div(mid.homog.value[1], mid.homog.value[2]).value.real;
            dx = xx - mouse.x;
            dy = yy - mouse.y;
            var ref = Math.sqrt(dx * dx + dy * dy);
            dist = ref - rad.value.real;
            dx = 0;
            dy = 0;
            if (dist < 0) {
                dist = -dist;
            }
            dist = dist + 30 / sc;

        } else if (el.kind === "L") { //Must be ThroughPoint(Horizontal/Vertical not treated yet)
            var l = el.homog;
            var N = CSNumber;
            var nn = N.add(N.mult(l.value[0], N.conjugate(l.value[0])),
                N.mult(l.value[1], N.conjugate(l.value[1])));
            var ln = List.scaldiv(N.sqrt(nn), l);
            dist = ln.value[0].value.real * mouse.x + ln.value[1].value.real * mouse.y + ln.value[2].value.real;
            dx = ln.value[0].value.real * dist;
            dy = ln.value[1].value.real * dist;

            if (dist < 0) {
                dist = -dist;
            }
            dist = dist + 1;
        }

        if (dist < adist + 0.2 / sc) { //A bit a dirty hack, prefers new points
            adist = dist;
            mov = el;
            diff = {
                x: dx,
                y: dy
            };
        }
    }
    console.log("Moving " + (mov ? mov.name : "nothing"));
    if (mov === null)
        return null;
    return {
        mover: mov,
        offset: diff,
        prev: {
            x: mouse.x,
            y: mouse.y
        }
    };
}

function addAutoCleaningEventListener(target, type, listener, useCapture) {
    if (useCapture === undefined)
        useCapture = false;
    shutdownHooks.push(function() {
        target.removeEventListener(type, listener, useCapture);
    });
    target.addEventListener(type, listener, useCapture);
}

function setuplisteners(canvas, data) {

    var MO = null;
    if (typeof MutationObserver !== "undefined")
        MO = MutationObserver;
    if (!MO && typeof WebKitMutationObserver !== "undefined")
        MO = WebKitMutationObserver; // jshint ignore: line
    if (MO) {
        MO = new MO(function(mutations) {
            // Browsers which support MutationObserver likely support contains
            if (!document.body.contains(canvas))
                shutdown();
        });
        MO.observe(document.documentElement, {
            "childList": true,
            "subtree": true
        });
        shutdownHooks.push(function() {
            MO.disconnect();
        });
    } else {
        addAutoCleaningEventListener(canvas, "DOMNodeRemovedFromDocument", shutdown);
        addAutoCleaningEventListener(canvas, "DOMNodeRemoved", shutdown);
    }

    function updatePostition(event) {
        var rect = canvas.getBoundingClientRect();
        var x = event.clientX - rect.left - canvas.clientLeft;
        var y = event.clientY - rect.top - canvas.clientTop;
        var pos = csport.to(x, y);
        mouse.prevx = mouse.x;
        mouse.prevy = mouse.y;
        mouse.x = pos[0];
        mouse.y = pos[1];
        csmouse[0] = mouse.x;
        csmouse[1] = mouse.y;
    }

    if (data.keylistener === true) {
        addAutoCleaningEventListener(document, "keydown", function(e) {
            cs_keypressed(e);
            return false;
        });
    } else if (cscompiled.keydown) {
        canvas.setAttribute("tabindex", "0");
        addAutoCleaningEventListener(canvas, "mousedown", function() {
            canvas.focus();
        });
        addAutoCleaningEventListener(canvas, "keydown", function(e) {
            // console.log("Got key " + e.charCode + " / " + e.keyCode);
            if (e.keyCode !== 9 /* tab */ ) {
                cs_keypressed(e);
                e.preventDefault();
            }
        });
    }

    addAutoCleaningEventListener(canvas, "mousedown", function(e) {
        mouse.button = e.which;
        updatePostition(e);
        cs_mousedown();
        move = getmover(mouse);
        startit(); //starts d3-timer

        mouse.down = true;
        e.preventDefault();
    });

    addAutoCleaningEventListener(canvas, "mouseup", function(e) {
        mouse.down = false;
        cindy_cancelmove();
        stateContinueFromHere();
        cs_mouseup();
        updateCindy();
        e.preventDefault();
    });

    addAutoCleaningEventListener(canvas, "mousemove", function(e) {
        updatePostition(e);
        if (mouse.down) {
            cs_mousedrag();
        } else {
            cs_mousemove();
        }
        e.preventDefault();
    });

    function touchMove(e) {
        updatePostition(e.targetTouches[0]);
        if (mouse.down) {
            cs_mousedrag();
        } else {
            cs_mousemove();
        }
        e.preventDefault();
    }

    function touchDown(e) {
        updatePostition(e.targetTouches[0]);
        cs_mousedown();
        mouse.down = true;
        move = getmover(mouse);
        startit();
        e.preventDefault();
    }

    function touchUp(e) {
        mouse.down = false;
        cindy_cancelmove();
        stateContinueFromHere();
        updateCindy();
        cs_mouseup();
        e.preventDefault();
    }

    addAutoCleaningEventListener(canvas, "touchstart", touchDown, false);
    addAutoCleaningEventListener(canvas, "touchmove", touchMove, true);
    addAutoCleaningEventListener(canvas, "touchend", touchUp, false);
    if (typeof document !== "undefined" && document.body) {
        addAutoCleaningEventListener(document.body, "touchcancel", touchUp, false);
        // addAutoCleaningEventListener(document.body, "mouseup", mouseUp, false);
    }

    updateCindy();
}

var requestAnimFrame;
if (instanceInvocationArguments.isNode) {
    requestAnimFrame = process.nextTick; // jshint ignore:line
} else {
    requestAnimFrame =
        window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
            //                window.setTimeout(callback, 1000 / 60);
            window.setTimeout(callback, 0);
        };
}

function doit() { //Callback for d3-timer
    if (isShutDown) return true;
    if (csanimating) {
        cs_tick();
    }
    updateCindy();
    csticking = csanimating || mouse.down;
    return !csticking;
}

function startit() {
    if (!csticking) {
        csticking = true;
        d3.timer(doit);
    }
}

function updateCindy() {
    csport.reset();
    csctx.save();
    csctx.clearRect(0, 0, csw, csh);
    if (csgridsize !== 0)
        evaluate(csgridscript);
    traceMouseAndScripts();
    //   console.log("NOW UPDATING");
    //  drawgrid();
    csport.greset();
    render();
    csctx.restore();
}

function update() {
    if (isShutDown) return;
    updateCindy();
    if (mouse.down)
        requestAnimFrame(update);
}

function cs_keypressed(e) {
    var evtobj = window.event ? event : e;
    var unicode = evtobj.charCode ? evtobj.charCode : evtobj.keyCode;
    var actualkey = String.fromCharCode(unicode);
    cskey = actualkey;
    cskeycode = unicode;

    evaluate(cscompiled.keydown);
    updateCindy();

}

function cs_mousedown(e) {
    evaluate(cscompiled.mousedown);

}

function cs_mouseup(e) {
    evaluate(cscompiled.mouseup);

}

function cs_mousedrag(e) {
    evaluate(cscompiled.mousedrag);

}

function cs_mousemove(e) {
    evaluate(cscompiled.mousemove);

}

function cs_tick(e) {
    if (csPhysicsInited) { //TODO: Check here if physics is required
        if (typeof(lab) !== 'undefined') {
            lab.tick();
        }
    }
    if (csanimating) {
        evaluate(cscompiled.tick);
    }

}

function cs_simulationstep(e) {
    evaluate(cscompiled.simulationstep);
}

function cs_simulationstart(e) {
    evaluate(cscompiled.simulationstart);
}

function cs_simulationstop(e) {
    evaluate(cscompiled.simulationstop);
}

function cindy_cancelmove() {
    move = undefined;
}
<commit_msg>Don't move invisible objects<commit_after>var mouse = {};
var move;

var cskey = "";
var cskeycode = 0;

function getmover(mouse) {
    var mov = null;
    var adist = 1000000;
    var diff;
    for (var i = 0; i < csgeo.free.length; i++) {
        var el = csgeo.free[i];
        if (el.pinned || el.visible === false)
            continue;

        var dx, dy, dist;
        var sc = csport.drawingstate.matrix.sdet;
        if (el.kind === "P") {
            var p = List.normalizeZ(el.homog);
            if (!List._helper.isAlmostReal(p))
                continue;
            dx = p.value[0].value.real - mouse.x;
            dy = p.value[1].value.real - mouse.y;
            dist = Math.sqrt(dx * dx + dy * dy);
            if (el.narrow & dist > 20 / sc) dist = 10000;
        } else if (el.kind === "C") { //Must be CircleMr
            var mid = csgeo.csnames[el.args[0]];
            var rad = el.radius;
            var xx = CSNumber.div(mid.homog.value[0], mid.homog.value[2]).value.real;
            var yy = CSNumber.div(mid.homog.value[1], mid.homog.value[2]).value.real;
            dx = xx - mouse.x;
            dy = yy - mouse.y;
            var ref = Math.sqrt(dx * dx + dy * dy);
            dist = ref - rad.value.real;
            dx = 0;
            dy = 0;
            if (dist < 0) {
                dist = -dist;
            }
            dist = dist + 30 / sc;

        } else if (el.kind === "L") { //Must be ThroughPoint(Horizontal/Vertical not treated yet)
            var l = el.homog;
            var N = CSNumber;
            var nn = N.add(N.mult(l.value[0], N.conjugate(l.value[0])),
                N.mult(l.value[1], N.conjugate(l.value[1])));
            var ln = List.scaldiv(N.sqrt(nn), l);
            dist = ln.value[0].value.real * mouse.x + ln.value[1].value.real * mouse.y + ln.value[2].value.real;
            dx = ln.value[0].value.real * dist;
            dy = ln.value[1].value.real * dist;

            if (dist < 0) {
                dist = -dist;
            }
            dist = dist + 1;
        }

        if (dist < adist + 0.2 / sc) { //A bit a dirty hack, prefers new points
            adist = dist;
            mov = el;
            diff = {
                x: dx,
                y: dy
            };
        }
    }
    console.log("Moving " + (mov ? mov.name : "nothing"));
    if (mov === null)
        return null;
    return {
        mover: mov,
        offset: diff,
        prev: {
            x: mouse.x,
            y: mouse.y
        }
    };
}

function addAutoCleaningEventListener(target, type, listener, useCapture) {
    if (useCapture === undefined)
        useCapture = false;
    shutdownHooks.push(function() {
        target.removeEventListener(type, listener, useCapture);
    });
    target.addEventListener(type, listener, useCapture);
}

function setuplisteners(canvas, data) {

    var MO = null;
    if (typeof MutationObserver !== "undefined")
        MO = MutationObserver;
    if (!MO && typeof WebKitMutationObserver !== "undefined")
        MO = WebKitMutationObserver; // jshint ignore: line
    if (MO) {
        MO = new MO(function(mutations) {
            // Browsers which support MutationObserver likely support contains
            if (!document.body.contains(canvas))
                shutdown();
        });
        MO.observe(document.documentElement, {
            "childList": true,
            "subtree": true
        });
        shutdownHooks.push(function() {
            MO.disconnect();
        });
    } else {
        addAutoCleaningEventListener(canvas, "DOMNodeRemovedFromDocument", shutdown);
        addAutoCleaningEventListener(canvas, "DOMNodeRemoved", shutdown);
    }

    function updatePostition(event) {
        var rect = canvas.getBoundingClientRect();
        var x = event.clientX - rect.left - canvas.clientLeft;
        var y = event.clientY - rect.top - canvas.clientTop;
        var pos = csport.to(x, y);
        mouse.prevx = mouse.x;
        mouse.prevy = mouse.y;
        mouse.x = pos[0];
        mouse.y = pos[1];
        csmouse[0] = mouse.x;
        csmouse[1] = mouse.y;
    }

    if (data.keylistener === true) {
        addAutoCleaningEventListener(document, "keydown", function(e) {
            cs_keypressed(e);
            return false;
        });
    } else if (cscompiled.keydown) {
        canvas.setAttribute("tabindex", "0");
        addAutoCleaningEventListener(canvas, "mousedown", function() {
            canvas.focus();
        });
        addAutoCleaningEventListener(canvas, "keydown", function(e) {
            // console.log("Got key " + e.charCode + " / " + e.keyCode);
            if (e.keyCode !== 9 /* tab */ ) {
                cs_keypressed(e);
                e.preventDefault();
            }
        });
    }

    addAutoCleaningEventListener(canvas, "mousedown", function(e) {
        mouse.button = e.which;
        updatePostition(e);
        cs_mousedown();
        move = getmover(mouse);
        startit(); //starts d3-timer

        mouse.down = true;
        e.preventDefault();
    });

    addAutoCleaningEventListener(canvas, "mouseup", function(e) {
        mouse.down = false;
        cindy_cancelmove();
        stateContinueFromHere();
        cs_mouseup();
        updateCindy();
        e.preventDefault();
    });

    addAutoCleaningEventListener(canvas, "mousemove", function(e) {
        updatePostition(e);
        if (mouse.down) {
            cs_mousedrag();
        } else {
            cs_mousemove();
        }
        e.preventDefault();
    });

    function touchMove(e) {
        updatePostition(e.targetTouches[0]);
        if (mouse.down) {
            cs_mousedrag();
        } else {
            cs_mousemove();
        }
        e.preventDefault();
    }

    function touchDown(e) {
        updatePostition(e.targetTouches[0]);
        cs_mousedown();
        mouse.down = true;
        move = getmover(mouse);
        startit();
        e.preventDefault();
    }

    function touchUp(e) {
        mouse.down = false;
        cindy_cancelmove();
        stateContinueFromHere();
        updateCindy();
        cs_mouseup();
        e.preventDefault();
    }

    addAutoCleaningEventListener(canvas, "touchstart", touchDown, false);
    addAutoCleaningEventListener(canvas, "touchmove", touchMove, true);
    addAutoCleaningEventListener(canvas, "touchend", touchUp, false);
    if (typeof document !== "undefined" && document.body) {
        addAutoCleaningEventListener(document.body, "touchcancel", touchUp, false);
        // addAutoCleaningEventListener(document.body, "mouseup", mouseUp, false);
    }

    updateCindy();
}

var requestAnimFrame;
if (instanceInvocationArguments.isNode) {
    requestAnimFrame = process.nextTick; // jshint ignore:line
} else {
    requestAnimFrame =
        window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
            //                window.setTimeout(callback, 1000 / 60);
            window.setTimeout(callback, 0);
        };
}

function doit() { //Callback for d3-timer
    if (isShutDown) return true;
    if (csanimating) {
        cs_tick();
    }
    updateCindy();
    csticking = csanimating || mouse.down;
    return !csticking;
}

function startit() {
    if (!csticking) {
        csticking = true;
        d3.timer(doit);
    }
}

function updateCindy() {
    csport.reset();
    csctx.save();
    csctx.clearRect(0, 0, csw, csh);
    if (csgridsize !== 0)
        evaluate(csgridscript);
    traceMouseAndScripts();
    //   console.log("NOW UPDATING");
    //  drawgrid();
    csport.greset();
    render();
    csctx.restore();
}

function update() {
    if (isShutDown) return;
    updateCindy();
    if (mouse.down)
        requestAnimFrame(update);
}

function cs_keypressed(e) {
    var evtobj = window.event ? event : e;
    var unicode = evtobj.charCode ? evtobj.charCode : evtobj.keyCode;
    var actualkey = String.fromCharCode(unicode);
    cskey = actualkey;
    cskeycode = unicode;

    evaluate(cscompiled.keydown);
    updateCindy();

}

function cs_mousedown(e) {
    evaluate(cscompiled.mousedown);

}

function cs_mouseup(e) {
    evaluate(cscompiled.mouseup);

}

function cs_mousedrag(e) {
    evaluate(cscompiled.mousedrag);

}

function cs_mousemove(e) {
    evaluate(cscompiled.mousemove);

}

function cs_tick(e) {
    if (csPhysicsInited) { //TODO: Check here if physics is required
        if (typeof(lab) !== 'undefined') {
            lab.tick();
        }
    }
    if (csanimating) {
        evaluate(cscompiled.tick);
    }

}

function cs_simulationstep(e) {
    evaluate(cscompiled.simulationstep);
}

function cs_simulationstart(e) {
    evaluate(cscompiled.simulationstart);
}

function cs_simulationstop(e) {
    evaluate(cscompiled.simulationstop);
}

function cindy_cancelmove() {
    move = undefined;
}
<|endoftext|>


<commit_before>var extend = require('xtend');
var Route = require('./Route');
var Request = require('./Request');
var Response = require('./Response');
var Unhandled = require('./errors/Unhandled');
var delayed = require('./utils/delayed');
var getDefaultHistory = require('./history/getHistory');
var invokeHandlers = require('./utils/invokeHandlers');
var noop = require('./utils/noop');
var inherits = require('inherits');
var EventEmitter = require('wolfy87-eventemitter');
var attach = require('./attach');
var urllite = require('urllite');
require('urllite/lib/extensions/resolve');
require('urllite/lib/extensions/toString');

function Router(opts) {
  this.state = {};
  this.defaultVars = opts && opts.defaultVars;
}

inherits(Router, EventEmitter);

/**
 * Expose the `Unhandled` error so it can be used in handlers more easily.
 */
Router.Unhandled = Unhandled;

function throwNoEngine() {
  throw new Error('You are attempting to render but your router has no rendering engine.');
}

Router.engine = {
  renderInto: throwNoEngine,
  renderToString: throwNoEngine
};

/**
 * Add a route to the router class. This API can be used in a manner similar
 * to many server-side JS routing libraries—by chainging calls to `route`—
 * however, it's more likely that you'll want to pass your routes to the
 * router class constructor using JSX.
 *
 * This function accepts either `(path, handlers...)`, or
 * `(name, path, handlers...)`.
 */
Router.route = function() {
  var RouterClass = this;
  var args = Array.prototype.slice.call(arguments, 0);
  var name, path, handlers;

  if (typeof args[1] !== 'function') name = args.shift();
  path = args.shift();
  handlers = args;

  var route = new Route(path);

  if (name) {
    if (RouterClass.namedRoutes[name])
      throw new Error('Route with name "' + name + '" already exists.');
    RouterClass.namedRoutes[name] = route;
  }

  // Create and register a middleware to represent this route.
  RouterClass.use(function(req, next) {
    // If this route doesn't match, skip it.
    var match = route.match(req.path);
    if (!match) return next();

    req.params = match;

    invokeHandlers(handlers, req, this, next);
  });

  // For chaining!
  return this;
};

Router.prototype.setState = function(state) {
  this.state = extend(this.state, state);
  this.emit('stateChange');
};

Router.prototype.getVars = function() {
  return extend(this.defaultVars, this.state);
};

Router.prototype.setView = function(view) {
  this.view = view;
  this.emit('viewChange');
};

Router.prototype.render = function() {
  if (!this.view) {
    throw new Error('You must set a view before rendering');
  }
  return this.view(this.getVars());
};

Router.prototype.finalMiddleware = [
  // If we've exhausted the middleware without handling the request, call the
  // `unhandled()` method. Going through `unhandled` instead of just creating an
  // error in the dispatch callback means we're always going through the same
  // process, getting the same events, etc.
  function(req, next) {
    if (!this.error && !this.ended) this.unhandled();
  }
];

/**
 *
 * @param {string} url
 * @param {function?} callback
 */
Router.prototype.dispatch = function(url, opts, callback) {
  var RouterClass = this.constructor;

  if (typeof arguments[1] === 'function') {
    callback = arguments[1];
    opts = null;
  }

  // Wrap the callback, imposing a delay to force asynchronousness in
  // case the user calls it synchronously.
  var cb = function(err) {
    // Clean up listeners
    res.off('error', cb).off('end', cb);

    this._currentResponse = null;
    if (callback) callback(err, err ? null : res);
  }.bind(this);

  // Resolve the URL to our root.
  var outsideRoot;
  try {
    url = urllite(url).relativize(RouterClass.rootURL).toString();
  } catch (err) {
    // FIXME: We shouldn't really assume that this error is the "URL not within root" error.
    // Oops. This URL isn't underneath the router's rootURL.
    outsideRoot = true;
  }

  var req = new Request(url, opts);
  var res = new Response(req, this)
    .on('error', cb)
    .on('end', cb);

  if (outsideRoot) {
    delayed(function() {
      res.unhandled('URL not within router root: ' + url);
    })();
    return res;
  }

  if (this._currentResponse) {
    this._currentResponse.request.cancel();
  }
  this._currentResponse = res;

  // Force async behavior so you have a chance to add listeners to the
  // request object.
  var middleware = RouterClass.middleware.concat(this.finalMiddleware);
  delayed(function() {
    invokeHandlers(middleware, req, res, function(err) {
      if (err) res['throw'](err);
    });
  })();

  return res;
};

Router.use = function(middleware) {
  var RouterClass = this;
  RouterClass.middleware.push(middleware);
  return this;
};

Router.extend = function(opts) {
  var SuperClass = this;
  var NewRouter = function() {
    if (!(this instanceof NewRouter)) {
      return new NewRouter();
    }
    SuperClass.call(this);
  };
  inherits(NewRouter, SuperClass);

  // Add "static" props to the new router.
  for (var k in SuperClass) {
    if (SuperClass.hasOwnProperty(k)) {
      NewRouter[k] = SuperClass[k];
    }
  }

  NewRouter.engine = opts && opts.engine;
  NewRouter.rootURL = opts && opts.rootURL || '/';
  NewRouter.middleware = [];
  NewRouter.namedRoutes = {};

  return NewRouter;
};

Router.attach = function(element, opts) {
  return attach(this, element, opts);
};

module.exports = Router;
<commit_msg>Call next() if no error<commit_after>var extend = require('xtend');
var Route = require('./Route');
var Request = require('./Request');
var Response = require('./Response');
var Unhandled = require('./errors/Unhandled');
var delayed = require('./utils/delayed');
var getDefaultHistory = require('./history/getHistory');
var invokeHandlers = require('./utils/invokeHandlers');
var noop = require('./utils/noop');
var inherits = require('inherits');
var EventEmitter = require('wolfy87-eventemitter');
var attach = require('./attach');
var urllite = require('urllite');
require('urllite/lib/extensions/resolve');
require('urllite/lib/extensions/toString');

function Router(opts) {
  this.state = {};
  this.defaultVars = opts && opts.defaultVars;
}

inherits(Router, EventEmitter);

/**
 * Expose the `Unhandled` error so it can be used in handlers more easily.
 */
Router.Unhandled = Unhandled;

function throwNoEngine() {
  throw new Error('You are attempting to render but your router has no rendering engine.');
}

Router.engine = {
  renderInto: throwNoEngine,
  renderToString: throwNoEngine
};

/**
 * Add a route to the router class. This API can be used in a manner similar
 * to many server-side JS routing libraries—by chainging calls to `route`—
 * however, it's more likely that you'll want to pass your routes to the
 * router class constructor using JSX.
 *
 * This function accepts either `(path, handlers...)`, or
 * `(name, path, handlers...)`.
 */
Router.route = function() {
  var RouterClass = this;
  var args = Array.prototype.slice.call(arguments, 0);
  var name, path, handlers;

  if (typeof args[1] !== 'function') name = args.shift();
  path = args.shift();
  handlers = args;

  var route = new Route(path);

  if (name) {
    if (RouterClass.namedRoutes[name])
      throw new Error('Route with name "' + name + '" already exists.');
    RouterClass.namedRoutes[name] = route;
  }

  // Create and register a middleware to represent this route.
  RouterClass.use(function(req, next) {
    // If this route doesn't match, skip it.
    var match = route.match(req.path);
    if (!match) return next();

    req.params = match;

    invokeHandlers(handlers, req, this, next);
  });

  // For chaining!
  return this;
};

Router.prototype.setState = function(state) {
  this.state = extend(this.state, state);
  this.emit('stateChange');
};

Router.prototype.getVars = function() {
  return extend(this.defaultVars, this.state);
};

Router.prototype.setView = function(view) {
  this.view = view;
  this.emit('viewChange');
};

Router.prototype.render = function() {
  if (!this.view) {
    throw new Error('You must set a view before rendering');
  }
  return this.view(this.getVars());
};

Router.prototype.finalMiddleware = [
  // If we've exhausted the middleware without handling the request, call the
  // `unhandled()` method. Going through `unhandled` instead of just creating an
  // error in the dispatch callback means we're always going through the same
  // process, getting the same events, etc.
  function(req, next) {
    if (!this.error && !this.ended) return this.unhandled();
    next();
  }
];

/**
 *
 * @param {string} url
 * @param {function?} callback
 */
Router.prototype.dispatch = function(url, opts, callback) {
  var RouterClass = this.constructor;

  if (typeof arguments[1] === 'function') {
    callback = arguments[1];
    opts = null;
  }

  // Wrap the callback, imposing a delay to force asynchronousness in
  // case the user calls it synchronously.
  var cb = function(err) {
    // Clean up listeners
    res.off('error', cb).off('end', cb);

    this._currentResponse = null;
    if (callback) callback(err, err ? null : res);
  }.bind(this);

  // Resolve the URL to our root.
  var outsideRoot;
  try {
    url = urllite(url).relativize(RouterClass.rootURL).toString();
  } catch (err) {
    // FIXME: We shouldn't really assume that this error is the "URL not within root" error.
    // Oops. This URL isn't underneath the router's rootURL.
    outsideRoot = true;
  }

  var req = new Request(url, opts);
  var res = new Response(req, this)
    .on('error', cb)
    .on('end', cb);

  if (outsideRoot) {
    delayed(function() {
      res.unhandled('URL not within router root: ' + url);
    })();
    return res;
  }

  if (this._currentResponse) {
    this._currentResponse.request.cancel();
  }
  this._currentResponse = res;

  // Force async behavior so you have a chance to add listeners to the
  // request object.
  var middleware = RouterClass.middleware.concat(this.finalMiddleware);
  delayed(function() {
    invokeHandlers(middleware, req, res, function(err) {
      if (err) res['throw'](err);
    });
  })();

  return res;
};

Router.use = function(middleware) {
  var RouterClass = this;
  RouterClass.middleware.push(middleware);
  return this;
};

Router.extend = function(opts) {
  var SuperClass = this;
  var NewRouter = function() {
    if (!(this instanceof NewRouter)) {
      return new NewRouter();
    }
    SuperClass.call(this);
  };
  inherits(NewRouter, SuperClass);

  // Add "static" props to the new router.
  for (var k in SuperClass) {
    if (SuperClass.hasOwnProperty(k)) {
      NewRouter[k] = SuperClass[k];
    }
  }

  NewRouter.engine = opts && opts.engine;
  NewRouter.rootURL = opts && opts.rootURL || '/';
  NewRouter.middleware = [];
  NewRouter.namedRoutes = {};

  return NewRouter;
};

Router.attach = function(element, opts) {
  return attach(this, element, opts);
};

module.exports = Router;
<|endoftext|>


<commit_before>/*
	ColorBox v1.1.4 - a full featured, light-weight, customizable lightbox based on jQuery 1.3
	(c) 2009 Jack Moore - www.colorpowered.com - jack@colorpowered.com
	Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
*/

(function($){
var clone, loadedWidth, loadedHeight, interfaceHeight, interfaceWidth, index, related, closeModal, loadingElement, modal, modalWrap, modalOverlay, modalLoadingOverlay, modalContent, loaded, modalClose, btc, bml, bmr, bbc;
function setModalOverlay(){
	$([modalOverlay]).css({"position":"absolute", width:$(window).width(), height:$(window).height(), top:$(window).scrollTop(), left:$(window).scrollLeft()});
}
function keypressEvents(e){
	if(e.keyCode == 37){
		$(document).unbind('keydown.colorKeys');
		$("a#contentPrevious").click();
	} else if(e.keyCode == 39){
		$(document).unbind('keydown.colorKeys');
		$("a#contentNext").click();
	}
}
function clearLoading(){
	if($("#colorboxInlineTemp").length > 0){
		$(loaded).children().insertAfter("#colorboxInlineTemp");
	}
	if(loadingElement){$(loadingElement).remove();}
}

closeModal = function(){
	clearLoading();
	$(modalOverlay).css({cursor:"auto"}).fadeOut("fast");
	$(modal).removeData("open").fadeOut("fast", function(){
		$(loaded).remove();
	});
	$(document).unbind('keydown.colorKeys');
	$(window).unbind('resize scroll', setModalOverlay);
};

// Convert % values to pixels
function setSize(size, dimension){
	return (typeof size == 'string') ? (size.match(/%/) ? (dimension/100)*parseInt(size, 10) : parseInt(size, 10)) : size;
}

//Initialize the modal: store common calculations, preload the interface graphics, append the html.
$(function(){
	$("body").append(
		$([
			modalOverlay = $('
')[0],
			modal = $('
')[0]
		]).hide()
	);
	$(modal).append(
		$([
			modalWrap = $('
')[0]
		])
	).css("opacity", 0).show();
	$(modalWrap).append(
		$([
			$('

')[0],
			bml = $('
')[0],
			modalContent = $('
')[0],
			bmr = $('
')[0],
			$('

')[0]
		])
	);
	$(modalContent).append(
		$([
			loaded = $('

')[0],
			modalLoadingOverlay = $('
')[0],
			modalClose = $('')[0]
		])
	);

	$(document).bind("keydown.colorClose", function(e){
		if (e.keyCode == 27) { closeModal(); }
	});

	$(modalClose).click(function(){
		closeModal();
		return false;
	});

	btc = $("#borderTopCenter")[0];
	bbc = $("#borderBottomCenter")[0];

	interfaceHeight = $(btc).height()+$(bbc).height()+$(modalContent).outerHeight(true) - $(modalContent).height();//Subtraction needed for IE6
	interfaceWidth = $(bml).width()+$(bmr).width()+$(modalContent).outerWidth(true) - $(modalContent).width();

	loadedHeight = $(loaded).outerHeight(true);
	loadedWidth = $(loaded).outerWidth(true);

	$(loaded).empty();
	$(modal).css({"padding-bottom":interfaceHeight,"padding-right":interfaceWidth}).hide();//the padding removes the need to do size conversions during the animation step.

	//Archaic rollover code because IE8 is a piece of shit.  Hopefully they'll fix their css-rollover bug and so that this can be removed.
	$("#contentPrevious, #contentNext, #modalClose").live('mouseover', function(){$(this).addClass("hover");});
	$("#contentPrevious, #contentNext, #modalClose").live('mouseout', function(){$(this).removeClass("hover");});
});

$.fn.colorbox = function(settings, callback) {

	function modalPosition(mWidth, mHeight, speed, loadedCallback){

		var winHeight = document.documentElement.clientHeight;
		var posTop = winHeight/2 - mHeight/2 + $(window).scrollTop();
		var posLeft = document.documentElement.clientWidth/2 - mWidth/2 + $(window).scrollLeft();
		//keeps the box from expanding to an inaccessible area offscreen.
		if(mHeight > winHeight){posTop -=(mHeight - winHeight);}
		if(posTop < 0){posTop = 0;}
		if(posLeft < 0){posLeft = 0;}

		mWidth = mWidth - interfaceWidth;
		mHeight = mHeight - interfaceHeight;

		function modalDimensions(that){
			modalContent.style.width = btc.style.width = bbc.style.width = that.style.width;
			modalContent.style.height = bml.style.height = bmr.style.height = that.style.height;
		}

		$(modal).animate({height:mHeight, width:mWidth, top:posTop, left:posLeft}, {duration: speed,
			complete: function(){
				if (loadedCallback) {loadedCallback();}
				modalDimensions(this);
				if ($.browser.msie && $.browser.version < 7) {setModalOverlay();}
			},
			step: function(){
				modalDimensions(this);
			}
		});
	}
	var preloads = [];
	function preload(){
		if(settings.preloading !== false && related.length>1){
			var previous, next;
			previous = index > 0 ? related[index-1].href : related[related.length-1].href;
			next = index < related.length-1 ? related[index+1].href : related[0].href;
			return [$("").attr("src", next), $("").attr("src", previous)];
		}
		return false;
	}

	function contentNav(){
		$(modalLoadingOverlay).show();
		if($(this).attr("id") == "contentPrevious"){
			index = index > 0 ? index-1 : related.length-1;
		} else {
			index = index < related.length-1 ? index+1 : 0;
		}
		loadModal(related[index].href, related[index].title);
		return false;
	}

	function centerModal (object, contentInfo){

		var speed = settings.transition=="none" ? 0 : settings.transitionSpeed;
		$(loaded).remove();
		loaded = $(object)[0];

		$(loaded).hide()
		.appendTo('body')
		.css({width:(settings.fixedWidth)?settings.fixedWidth - loadedWidth - interfaceWidth:$(loaded).width()}).css({height:(settings.fixedHeight)?settings.fixedHeight - loadedHeight - interfaceHeight:$(loaded).height()})
		.attr({id:"modalLoadedContent"})
		.append(contentInfo)
		.prependTo($(modalContent));

		if($("#modalPhoto").length > 0 && settings.fixedHeight){
			var topMargin = (parseInt($(loaded)[0].style.height, 10) - parseInt($("#modalPhoto")[0].style.height, 10))/2;
			$("#modalPhoto").css({marginTop:(topMargin > 0?topMargin:0)});
		}

		function setPosition(s){
			modalPosition(parseInt(loaded.style.width, 10)+loadedWidth+interfaceWidth, parseInt(loaded.style.height, 10)+loadedHeight+interfaceHeight, s, function(){
				$(loaded).show();
				$(modalLoadingOverlay).hide();
				if (callback) {callback();}
				if ($(modal).data("open")!==true){
					closeModal();
				}
				else if (settings.transition === "fade"){
					$(modal).animate({"opacity":1}, speed);
				}
				$(document).bind('keydown.colorKeys', keypressEvents);
			});
		}
		if (settings.transition == "fade") {
			$(modal).animate({"opacity":0}, speed, function(){setPosition(0);});
		} else {
			setPosition(speed);
		}
		var preloads = preload();
	}

	function loadModal(href, title){
		clearLoading();
		var contentInfo = "
"+title+"
";
		if(related.length>1){
			contentInfo += " " + settings.contentCurrent + "";
			contentInfo = contentInfo.replace(/\{current\}/, index+1).replace(/\{total\}/, related.length);
			contentInfo += ""+settings.contentPrevious+""+settings.contentNext+" ";
		}

		if (settings.inline) {
			loadingElement = $('
').hide().insertBefore($(href)[0]);
			clone = $(href).clone(true);
			centerModal($(href).wrapAll("
").parent(), contentInfo);
		} else if (settings.iframe) {
			centerModal($("

"), contentInfo);//timestamp to prevent caching.
		} else if (href.match(/\.(gif|png|jpg|jpeg|bmp)(?:\?([^#]*))?(?:#(.*))?$/i)){
			var modalPhoto = new Image();
			modalPhoto.onload = function(){
				modalPhoto.onload = null;
				centerModal($("
").css({width:this.width, height:this.height}).append($(this).css({width:this.width, height:this.height, display:"block", margin:"auto"}).attr('id', 'modalPhoto')), contentInfo);
				if(related.length > 1){
					$(this).css({cursor:'pointer'}).click(contentNav);
				}
			};
			modalPhoto.src = href;
		}else {
			loadingElement = $('
').load(href, function(data, textStatus){
				if(textStatus == "success"){
					centerModal($(this), contentInfo);
				} else {
					centerModal($("
Request unsuccessful.
"));
				}
			});
		}
	}

	settings = $.extend({}, $.fn.colorbox.settings, settings);

	$(this).bind("click.colorbox", function () {
		if(settings.fixedWidth){ settings.fixedWidth = setSize(settings.fixedWidth, document.documentElement.clientWidth);}
		if(settings.fixedHeight){ settings.fixedHeight = setSize(settings.fixedHeight, document.documentElement.clientHeight);}
		if (this.rel && 'nofollow' != this.rel) {
			related = $("a[rel='" + this.rel + "']");
			index = $(related).index(this);
		}
		else {
			related = $(this);
			index = 0;
		}

		if ($(modal).data("open") !== true) {
			$(modal).data("open", true);
			$(modalClose).html(settings.modalClose);
			$(modalOverlay).css({"opacity": settings.bgOpacity});
			$([modal, modalLoadingOverlay, modalOverlay]).show();
			modalPosition(setSize(settings.initialWidth, document.documentElement.clientWidth), setSize(settings.initialHeight, document.documentElement.clientHeight), 0);

			$(modal).css({"opacity":1});

			$(document).bind('keydown.colorKeys', keypressEvents);
			if ($.browser.msie && $.browser.version < 7) {
				$(window).bind("resize scroll", setModalOverlay);
			}
		}

		loadModal(settings.href ? settings.href : related[index].href, settings.title ? settings.title : related[index].title);
		$("a#contentPrevious, a#contentNext").die().live("click", contentNav);

		if(settings.overlayClose!==false){
			$(modalOverlay).css({"cursor":"pointer"}).click(function(){closeModal();});
		}
		return false;
	});

	if(settings.open!==false && $(modal).data("open")!==true){
		$(this).triggerHandler('click.colorbox');
	}

	return this.each(function() {
	});
};

/*
	ColorBox Default Settings.

	The colorbox() function takes one argument, an object of key/value pairs, that are used to initialize the modal.

	Please do not change these settings here, instead overwrite these settings when attaching the colorbox() event to your anchors.
	Example (Global)	: $.fn.colorbox.settings.transition = "fade"; //changes the transition to fade for all colorBox() events proceeding it's declaration.
	Example (Specific)	: $("a[href='http://www.google.com']").colorbox({fixedWidth:"90%", fixedHeight:"450px", iframe:true});
*/
$.fn.colorbox.settings = {
	transition : "elastic", // Transition types: "elastic", "fade", or "none".
	transitionSpeed : 350, // Sets the speed of the fade and elastic transitions, in milliseconds.
	initialWidth : "400", // Set the initial width of the modal, prior to any content being loaded.
	initialHeight : "400", // Set the initial height of the modal, prior to any content being loaded.
	fixedWidth : false, // Set a fixed width for div#loaded.  Example: "500px"
	fixedHeight : false, // Set a fixed height for div#modalLoadedContent.  Example: "500px"
	inline : false, // Set this to the selector of inline content to be displayed.  Example "#myHiddenDiv" or "body p".
	iframe : false, // If 'true' specifies that content should be displayed in an iFrame.
	href : false, // This can be used as an alternate anchor URL for ColorBox to use, or can be used to assign a URL for non-anchor elments such as images or form buttons.
	title : false, // This can be used as an alternate anchor title.
	bgOpacity : 0.85, // The modalBackgroundOverlay opacity level. Range: 0 to 1.
	preloading : true, // Allows for preloading of 'Next' and 'Previous' content in a shared relation group (same values for the 'rel' attribute), after the current content has finished loading.  Set to 'false' to disable.
	contentCurrent : "image {current} of {total}", // the format of the contentCurrent information
	contentPrevious : "previous", // the anchor text for the previous link in a shared relation group (same values for 'rel').
	contentNext : "next", // the anchor text for the next link in a shared relation group (same 'rel' attribute').
	modalClose : "close", // the anchor text for the close link.  Esc will also close the modal.
	open : false, //Automatically opens ColorBox. (fires the click.colorbox event without waiting for user input).
	overlayClose : true  //If true, enables closing ColorBox by clicking on the background overlay.
};

})(jQuery);

<commit_msg>Signed-off-by: Jack Moore <jack@colorpowered.com><commit_after>/*
	ColorBox v1.1.5 - a full featured, light-weight, customizable lightbox based on jQuery 1.3
	(c) 2009 Jack Moore - www.colorpowered.com - jack@colorpowered.com
	Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
*/

(function($){
var clone, loadedWidth, loadedHeight, interfaceHeight, interfaceWidth, index, related, closeModal, loadingElement, modal, modalWrap, modalOverlay, modalLoadingOverlay, modalContent, loaded, modalClose, btc, bml, bmr, bbc;
function setModalOverlay(){
	$([modalOverlay]).css({"position":"absolute", width:$(window).width(), height:$(window).height(), top:$(window).scrollTop(), left:$(window).scrollLeft()});
}
function keypressEvents(e){
	if(e.keyCode == 37){
		$(document).unbind('keydown.colorKeys');
		$("a#contentPrevious").click();
	} else if(e.keyCode == 39){
		$(document).unbind('keydown.colorKeys');
		$("a#contentNext").click();
	}
}
function clearLoading(){
	if($("#colorboxInlineTemp").length > 0){
		$(loaded).children().insertAfter("#colorboxInlineTemp");
	}
	if(loadingElement){$(loadingElement).remove();}
}

closeModal = function(){
	clearLoading();
	$(modalOverlay).css({cursor:"auto"}).fadeOut("fast");
	$(modal).stop(true, false).removeData("open").fadeOut("fast", function(){
		$(loaded).remove();
	});
	$(document).unbind('keydown.colorKeys');
	$(window).unbind('resize scroll', setModalOverlay);
};

// Convert % values to pixels
function setSize(size, dimension){
	return (typeof size == 'string') ? (size.match(/%/) ? (dimension/100)*parseInt(size, 10) : parseInt(size, 10)) : size;
}

//Initialize the modal: store common calculations, preload the interface graphics, append the html.
$(function(){
	$("body").append(
		$([
			modalOverlay = $('
')[0],
			modal = $('
')[0]
		]).hide()
	);
	$(modal).append(
		$([
			modalWrap = $('
')[0]
		])
	).css("opacity", 0).show();
	$(modalWrap).append(
		$([
			$('

')[0],
			bml = $('
')[0],
			modalContent = $('
')[0],
			bmr = $('
')[0],
			$('

')[0]
		])
	);
	$(modalContent).append(
		$([
			loaded = $('

')[0],
			modalLoadingOverlay = $('
')[0],
			modalClose = $('')[0]
		])
	);

	$(document).bind("keydown.colorClose", function(e){
		if (e.keyCode == 27) { closeModal(); }
	});

	$(modalClose).click(function(){
		closeModal();
		return false;
	});

	btc = $("#borderTopCenter")[0];
	bbc = $("#borderBottomCenter")[0];

	interfaceHeight = $(btc).height()+$(bbc).height()+$(modalContent).outerHeight(true) - $(modalContent).height();//Subtraction needed for IE6
	interfaceWidth = $(bml).width()+$(bmr).width()+$(modalContent).outerWidth(true) - $(modalContent).width();

	loadedHeight = $(loaded).outerHeight(true);
	loadedWidth = $(loaded).outerWidth(true);

	$(loaded).empty();
	$(modal).css({"padding-bottom":interfaceHeight,"padding-right":interfaceWidth}).hide();//the padding removes the need to do size conversions during the animation step.

	//Archaic rollover code because IE8 is a piece of shit.  Hopefully they'll fix their css-rollover bug so the following code can be removed.
	$("#contentPrevious, #contentNext, #modalClose").live('mouseover', function(){$(this).addClass("hover");});
	$("#contentPrevious, #contentNext, #modalClose").live('mouseout', function(){$(this).removeClass("hover");});
});

$.fn.colorbox = function(settings, callback) {

	function modalPosition(mWidth, mHeight, speed, loadedCallback){

		var winHeight = document.documentElement.clientHeight;
		var posTop = winHeight/2 - mHeight/2 + $(window).scrollTop();
		var posLeft = document.documentElement.clientWidth/2 - mWidth/2 + $(window).scrollLeft();
		//keeps the box from expanding to an inaccessible area offscreen.
		if(mHeight > winHeight){posTop -=(mHeight - winHeight);}
		if(posTop < 0){posTop = 0;}
		if(posLeft < 0){posLeft = 0;}

		mWidth = mWidth - interfaceWidth;
		mHeight = mHeight - interfaceHeight;

		function modalDimensions(that){
			modalContent.style.width = btc.style.width = bbc.style.width = that.style.width;
			modalContent.style.height = bml.style.height = bmr.style.height = that.style.height;
		}

		$(modal).animate({height:mHeight, width:mWidth, top:posTop, left:posLeft}, {duration: speed,
			complete: function(){
				if (loadedCallback) {loadedCallback();}
				modalDimensions(this);
				if ($.browser.msie && $.browser.version < 7) {setModalOverlay();}
			},
			step: function(){
				modalDimensions(this);
			}
		});
	}
	var preloads = [];
	function preload(){
		if(settings.preloading !== false && related.length>1){
			var previous, next;
			previous = index > 0 ? related[index-1].href : related[related.length-1].href;
			next = index < related.length-1 ? related[index+1].href : related[0].href;
			return [$("").attr("src", next), $("").attr("src", previous)];
		}
		return false;
	}

	function contentNav(){
		$(modalLoadingOverlay).show();
		if($(this).attr("id") == "contentPrevious"){
			index = index > 0 ? index-1 : related.length-1;
		} else {
			index = index < related.length-1 ? index+1 : 0;
		}
		loadModal(related[index].href, related[index].title);
		return false;
	}

	function centerModal (object, contentInfo){

		var speed = settings.transition=="none" ? 0 : settings.transitionSpeed;
		$(loaded).remove();
		loaded = $(object)[0];

		$(loaded).hide()
		.appendTo('body')
		.css({width:(settings.fixedWidth)?settings.fixedWidth - loadedWidth - interfaceWidth:$(loaded).width()}).css({height:(settings.fixedHeight)?settings.fixedHeight - loadedHeight - interfaceHeight:$(loaded).height()})
		.attr({id:"modalLoadedContent"})
		.append(contentInfo)
		.prependTo($(modalContent));

		if($("#modalPhoto").length > 0 && settings.fixedHeight){
			var topMargin = (parseInt($(loaded)[0].style.height, 10) - parseInt($("#modalPhoto")[0].style.height, 10))/2;
			$("#modalPhoto").css({marginTop:(topMargin > 0?topMargin:0)});
		}

		function setPosition(s){
			modalPosition(parseInt(loaded.style.width, 10)+loadedWidth+interfaceWidth, parseInt(loaded.style.height, 10)+loadedHeight+interfaceHeight, s, function(){
				$(loaded).show();
				$(modalLoadingOverlay).hide();
				$(document).bind('keydown.colorKeys', keypressEvents);
				if (callback) {
					callback();
				}
				if($(modal).data("open")!==true){
					closeModal();
				} else if (settings.transition === "fade"){
					$(modal).animate({"opacity":1}, speed);
				}
			});
		}
		if (settings.transition == "fade") {
			$(modal).animate({"opacity":0}, speed, function(){setPosition(0);});
		} else {
			setPosition(speed);
		}
		var preloads = preload();
	}

	function loadModal(href, title){
		clearLoading();
		var contentInfo = "
"+title+"
";
		if(related.length>1){
			contentInfo += " " + settings.contentCurrent + "";
			contentInfo = contentInfo.replace(/\{current\}/, index+1).replace(/\{total\}/, related.length);
			contentInfo += ""+settings.contentPrevious+""+settings.contentNext+" ";
		}
		if (settings.inline) {
			loadingElement = $('
').hide().insertBefore($(href)[0]);
			clone = $(href).clone(true);
			centerModal($(href).wrapAll("
").parent(), contentInfo);
		} else if (settings.iframe) {
			centerModal($("

"), contentInfo);//timestamp to prevent caching.
		} else if (href.match(/\.(gif|png|jpg|jpeg|bmp)(?:\?([^#]*))?(?:#(.*))?$/i)){
			loadingElement = new Image();
			loadingElement.onload = function(){
				loadingElement.onload = null;
				centerModal($("
").css({width:this.width, height:this.height}).append($(this).css({width:this.width, height:this.height, display:"block", margin:"auto"}).attr('id', 'modalPhoto')), contentInfo);
				if(related.length > 1){
					$(this).css({cursor:'pointer'}).click(contentNav);
				}
			};
			loadingElement.src = href;
		}else {
			loadingElement = $('
').load(href, function(data, textStatus){
				if(textStatus == "success"){
					centerModal($(this), contentInfo);
				} else {
					centerModal($("
Request unsuccessful.
"));
				}
			});
		}
	}

	settings = $.extend({}, $.fn.colorbox.settings, settings);

	$(this).unbind("click.colorbox").bind("click.colorbox", function () {
		if(settings.fixedWidth){ settings.fixedWidth = setSize(settings.fixedWidth, document.documentElement.clientWidth);}
		if(settings.fixedHeight){ settings.fixedHeight = setSize(settings.fixedHeight, document.documentElement.clientHeight);}
		if (this.rel && 'nofollow' != this.rel) {
			related = $("a[rel='" + this.rel + "']");
			index = $(related).index(this);
		}
		else {
			related = $(this);
			index = 0;
		}

		if ($(modal).data("open") !== true) {
			$(modal).data("open", true);
			$(modalClose).html(settings.modalClose);
			$(modalOverlay).css({"opacity": settings.bgOpacity});
			$([modal, modalLoadingOverlay, modalOverlay]).show();
			modalPosition(setSize(settings.initialWidth, document.documentElement.clientWidth), setSize(settings.initialHeight, document.documentElement.clientHeight), 0);

			$(modal).css({"opacity":1});

			$(document).bind('keydown.colorKeys', keypressEvents);
			if ($.browser.msie && $.browser.version < 7) {
				$(window).bind("resize scroll", setModalOverlay);
			}
		}

		loadModal(settings.href ? settings.href : related[index].href, settings.title ? settings.title : related[index].title);
		$("a#contentPrevious, a#contentNext").die().live("click", contentNav);

		if(settings.overlayClose!==false){
			$(modalOverlay).css({"cursor":"pointer"}).click(function(){closeModal();});
		}
		return false;
	});

	if(settings.open!==false && $(modal).data("open")!==true){
		$(this).triggerHandler('click.colorbox');
	}

	return this.each(function() {
	});
};

/*
	ColorBox Default Settings.

	The colorbox() function takes one argument, an object of key/value pairs, that are used to initialize the modal.

	Please do not change these settings here, instead overwrite these settings when attaching the colorbox() event to your anchors.
	Example (Global)	: $.fn.colorbox.settings.transition = "fade"; //changes the transition to fade for all colorBox() events proceeding it's declaration.
	Example (Specific)	: $("a[href='http://www.google.com']").colorbox({fixedWidth:"90%", fixedHeight:"450px", iframe:true});
*/
$.fn.colorbox.settings = {
	transition : "elastic", // Transition types: "elastic", "fade", or "none".
	transitionSpeed : 350, // Sets the speed of the fade and elastic transitions, in milliseconds.
	initialWidth : "400", // Set the initial width of the modal, prior to any content being loaded.
	initialHeight : "400", // Set the initial height of the modal, prior to any content being loaded.
	fixedWidth : false, // Set a fixed width for div#loaded.  Example: "500px"
	fixedHeight : false, // Set a fixed height for div#modalLoadedContent.  Example: "500px"
	inline : false, // Set this to the selector of inline content to be displayed.  Example "#myHiddenDiv" or "body p".
	iframe : false, // If 'true' specifies that content should be displayed in an iFrame.
	href : false, // This can be used as an alternate anchor URL for ColorBox to use, or can be used to assign a URL for non-anchor elments such as images or form buttons.
	title : false, // This can be used as an alternate anchor title.
	bgOpacity : 0.85, // The modalBackgroundOverlay opacity level. Range: 0 to 1.
	preloading : true, // Allows for preloading of 'Next' and 'Previous' content in a shared relation group (same values for the 'rel' attribute), after the current content has finished loading.  Set to 'false' to disable.
	contentCurrent : "image {current} of {total}", // the format of the contentCurrent information
	contentPrevious : "previous", // the anchor text for the previous link in a shared relation group (same values for 'rel').
	contentNext : "next", // the anchor text for the next link in a shared relation group (same 'rel' attribute').
	modalClose : "close", // the anchor text for the close link.  Esc will also close the modal.
	open : false, //Automatically opens ColorBox. (fires the click.colorbox event without waiting for user input).
	overlayClose : true  //If true, enables closing ColorBox by clicking on the background overlay.
};

})(jQuery);

<|endoftext|>


<commit_before>#! /usr/bin/env node

const cli = require("../dist/lib/module-structure-cli");

try {
    new cli.Application().run();
}
catch (e) {
    // already logged
    process.exit(e === null ? 0 : -1);
}
<commit_msg>Line endings<commit_after>#! /usr/bin/env node

const cli = require("../dist/lib/module-structure-cli");

try {
    new cli.Application().run();
}
catch (e) {
    // already logged
    process.exit(e === null ? 0 : -1);
}

<|endoftext|>


<commit_before>var KanaList = require('./kana');

module.exports = Game;

function Game(){
    this.game = loadGame();
    this.unlockNextRow();
}

Game.prototype.getQuestion = function(){
    var available = getAvailable(this.game);

    var fields = Math.random() > 0.5 ? ['sound', 'kana'] : ['kana', 'sound'],
        questionField = fields[0], answerField = fields[1];

    var questionKana = _.sample(available);

    question = {
        kana: questionKana,
        question:questionKana[questionField],
        answer: questionKana[answerField]
    };

    var choices = _.chain(available)
                   .filter(function(kana){
                       return kana[answerField] !== question.answer &&
                              kana[questionField] !== question.question;
                    })
                   .sample(3)
                   .pluck(answerField)
                   .value();

    choices.push(question.answer);

    question.choices = _.shuffle(choices);

    return question;
};

Game.prototype.updateScore = function(kana, correct){
    kana.score[correct ? 'correct' : 'incorrect'] += 1;
};

Game.prototype.unlockNextRow = function(){
    var nextToUnlock = _.find(this.game, function(row){
        return !row[0].score;
    });

    var allLearned = _.every(getAvailable(this.game), function(kana){
            var attempts = kana.score.correct + kana.score.incorrect,
                errorRatio = attempts > 0 ? kana.score.incorrect / attempts : 1;
            return errorRatio < 0.5;
        });

    if (nextToUnlock && allLearned){
        initRow(nextToUnlock);
    }

    saveGame(this.game);
};

function loadGame(){
    return (localStorage && JSON.parse(localStorage.getItem("game"))) ||
           KanaList.hiragana.concat(KanaList.katakana);
}

function initRow(row){
    _.forEach(row, function(q){
        q.score = {correct: 0, incorrect: 0};
    });
}

function getAvailable(rows){
    return _.filter(_.flatten(rows), function(kana){
        return kana.score;
    });
}

function saveGame(game){
    return localStorage && localStorage.setItem("game", JSON.stringify(game));
}
<commit_msg>Improves question picking algorithm<commit_after>var KanaList = require('./kana');

module.exports = Game;

function Game(){
    this.game = loadGame();
    this.unlockNextRow();
}

Game.prototype.getQuestion = function(){
    var available = getAvailable(this.game);

    var fields = Math.random() > 0.5 ? ['sound', 'kana'] : ['kana', 'sound'],
        questionField = fields[0], answerField = fields[1];

    var questionKana = pickQuestion(available);

    question = {
        kana: questionKana,
        question:questionKana[questionField],
        answer: questionKana[answerField]
    };

    var choices = _.chain(available)
                   .filter(function(kana){
                       return kana[answerField] !== question.answer &&
                              kana[questionField] !== question.question;
                    })
                   .sample(3)
                   .pluck(answerField)
                   .value();

    choices.push(question.answer);

    question.choices = _.shuffle(choices);

    return question;
};

Game.prototype.updateScore = function(kana, correct){
    kana.score[correct ? 'correct' : 'incorrect'] += 1;
};

Game.prototype.unlockNextRow = function(){
    var nextToUnlock = _.find(this.game, function(row){
        return !row[0].score;
    });

    var allLearned = _.every(getAvailable(this.game), function(kana){
            return kana.score.correct >= 3;
        });

    if (nextToUnlock && allLearned){
        initRow(nextToUnlock);
    }

    saveGame(this.game);
};

function loadGame(){
    return (localStorage && JSON.parse(localStorage.getItem("game"))) ||
           KanaList.hiragana.concat(KanaList.katakana);
}

function initRow(row){
    _.forEach(row, function(q){
        q.score = {correct: 0, incorrect: 0};
    });
}

function pickQuestion(options){
    var byAttempts = _.sortBy(options, function(kana){
        return kana.score.correct + kana.score.incorrect;
    }),
        pivot = Math.ceil(byAttempts.length * 0.2),
        recent = _.initial(byAttempts, pivot),
        old = _.last(byAttempts, byAttempts.length - pivot),
        picked = undefined;

    if(Math.random() > 0.2){
        picked = _.sample(recent);
    }
    else{
        picked = _.sample(old);
    }

    return picked;
}

function getAvailable(rows){
    return _.filter(_.flatten(rows), function(kana){
        return kana.score;
    });
}

function saveGame(game){
    return localStorage && localStorage.setItem("game", JSON.stringify(game));
}
<|endoftext|>


<commit_before>/**
 * Entrypoint for the react app
 * Provides a basic app wrapper for react
 * @author Fabian Beuke <mail@beuke.org>
 * @license AGPL-3.0
 */

import React from 'react'
import ReactDOM from 'react-dom'
import { HashRouter } from 'react-router-dom'
import Layout from './components/Layout'
import styles from '../style.styl' // eslint-disable-line no-unused-vars
import { getMaxDataDate } from './utils.js'

const production = window.location.href.includes('madnight.github.io')

if (!production) {
    const { registerObserver } = require('react-perf-devtool')
    registerObserver({ shouldLog: true })
}

getMaxDataDate().then(maxDate => {
    const defaultPath = '#/pull_requests/' + maxDate.year + '/' + maxDate.quarter
    if (!(window.location.href).includes('#')) {
        if (production) { window.location.href = '/githut/' + defaultPath } else { window.location.href = '/' + defaultPath }
    }

    const app = document.createElement('div')
    app.id = 'app'
    document.body.appendChild(app)
    ReactDOM.render(<HashRouter><Layout/></HashRouter>, app)
}
)

<commit_msg>fix empty url<commit_after>/**
 * Entrypoint for the react app
 * Provides a basic app wrapper for react
 * @author Fabian Beuke <mail@beuke.org>
 * @license AGPL-3.0
 */

import React from 'react'
import ReactDOM from 'react-dom'
import { HashRouter } from 'react-router-dom'
import Layout from './components/Layout'
import styles from '../style.styl' // eslint-disable-line no-unused-vars
import { getMaxDataDate } from './utils.js'

const production = window.location.href.includes('madnight.github.io')

if (!production) {
    const { registerObserver } = require('react-perf-devtool')
    registerObserver({ shouldLog: true })
}

getMaxDataDate().then(maxDate => {
    const defaultPath = '#/pull_requests/' + maxDate.year + '/' + maxDate.quarter
    if (!(window.location.href).includes('pull_requests') &&
        !(window.location.href).includes('pushes') &&
        !(window.location.href).includes('stars') &&
        !(window.location.href).includes('issues')) {
        if (production) {
            window.location.href = '/githut/' + defaultPath
        } else {
            window.location.href = '/' + defaultPath
        }
    }

    const app = document.createElement('div')
    app.id = 'app'
    document.body.appendChild(app)
    ReactDOM.render(<HashRouter><Layout/></HashRouter>, app)
}
)

<|endoftext|>


<commit_before>/*!
 * ws: a node.js websocket client
 * Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com>
 * MIT Licensed
 */

var events = require('events')
  , util = require('util')
  , EventEmitter = events.EventEmitter
  , ErrorCodes = require('./ErrorCodes')
  , bufferUtil = require('./BufferUtil').BufferUtil;

/**
 * HyBi Sender implementation
 */

function Sender(socket) {
  this._socket = socket;
  this.firstFragment = true;
}

/**
 * Inherits from EventEmitter.
 */

util.inherits(Sender, events.EventEmitter);

/**
 * Sends a close instruction to the remote party.
 *
 * @api public
 */

Sender.prototype.close = function(code, data, mask) {
  if (typeof code !== 'undefined') {
    if (typeof code !== 'number' ||
      !ErrorCodes.isValidErrorCode(code)) throw new Error('first argument must be a valid error code number');
  }
  code = code || 1000;
  var dataBuffer = new Buffer(2 + (data ? Buffer.byteLength(data) : 0));
  writeUInt16BE.call(dataBuffer, code, 0);
  if (dataBuffer.length > 2) dataBuffer.write(data, 2);
  this.frameAndSend(0x8, dataBuffer, true, mask);
}

/**
 * Sends a ping message to the remote party.
 *
 * @api public
 */

Sender.prototype.ping = function(data, options) {
  var mask = options && options.mask;
  this.frameAndSend(0x9, data || '', true, mask);
}

/**
 * Sends a pong message to the remote party.
 *
 * @api public
 */

Sender.prototype.pong = function(data, options) {
  var mask = options && options.mask;
  this.frameAndSend(0xa, data || '', true, mask);
}

/**
 * Sends text or binary data to the remote party.
 *
 * @api public
 */

Sender.prototype.send = function(data, options, cb) {
  var finalFragment = options && options.fin === false ? false : true;
  var mask = options && options.mask;
  var opcode = options && options.binary ? 2 : 1;
  if (this.firstFragment === false) opcode = 0;
  else this.firstFragment = false;
  if (finalFragment) this.firstFragment = true
  this.frameAndSend(opcode, data, finalFragment, mask, cb);
}

/**
 * Frames and sends a piece of data according to the HyBi WebSocket protocol.
 *
 * @api private
 */

Sender.prototype.frameAndSend = function(opcode, data, finalFragment, maskData, cb) {
  var canModifyData = false;

  if (!data) {
    try {
      this._socket.write(new Buffer([opcode | (finalFragment ? 0x80 : 0), 0 | (maskData ? 0x80 : 0)].concat(maskData ? [0, 0, 0, 0] : [])), 'binary', cb);
    }
    catch (e) {
      if (typeof cb == 'function') cb(e);
      else this.emit('error', e);
    }
    return;
  }

  if (!Buffer.isBuffer(data)) {
    canModifyData = true;
    data = (data && typeof data.buffer !== 'undefined') ? getArrayBuffer(data.buffer) : new Buffer(data);
  }

  var dataLength = data.length
    , dataOffset = maskData ? 6 : 2
    , secondByte = dataLength;

  if (dataLength >= 65536) {
    dataOffset += 8;
    secondByte = 127;
  }
  else if (dataLength > 125) {
    dataOffset += 2;
    secondByte = 126;
  }

  var mergeBuffers = dataLength < 32768 || (maskData && !canModifyData);
  var totalLength = mergeBuffers ? dataLength + dataOffset : dataOffset;
  var outputBuffer = new Buffer(totalLength);
  outputBuffer[0] = finalFragment ? opcode | 0x80 : opcode;

  switch (secondByte) {
    case 126:
      writeUInt16BE.call(outputBuffer, dataLength, 2);
      break;
    case 127:
      writeUInt32BE.call(outputBuffer, 0, 2);
      writeUInt32BE.call(outputBuffer, dataLength, 6);
  }

  if (maskData) {
    outputBuffer[1] = secondByte | 0x80;
    var mask = this._randomMask || (this._randomMask = getRandomMask());
    outputBuffer[dataOffset - 4] = mask[0];
    outputBuffer[dataOffset - 3] = mask[1];
    outputBuffer[dataOffset - 2] = mask[2];
    outputBuffer[dataOffset - 1] = mask[3];
    if (mergeBuffers) {
      bufferUtil.mask(data, mask, outputBuffer, dataOffset, dataLength);
      try {
        this._socket.write(outputBuffer, 'binary', cb);
      }
      catch (e) {
        if (typeof cb == 'function') cb(e);
        else this.emit('error', e);
      }
    }
    else {
      bufferUtil.mask(data, mask, data, 0, dataLength);
      try {
        this._socket.write(outputBuffer, 'binary');
        this._socket.write(data, 'binary', cb);
      }
      catch (e) {
        if (typeof cb == 'function') cb(e);
        else this.emit('error', e);
      }
    }
  }
  else {
    outputBuffer[1] = secondByte;
    if (mergeBuffers) {
      data.copy(outputBuffer, dataOffset);
      try {
        this._socket.write(outputBuffer, 'binary', cb);
      }
      catch (e) {
        if (typeof cb == 'function') cb(e);
        else this.emit('error', e);
      }
    }
    else {
      try {
        this._socket.write(outputBuffer, 'binary');
        this._socket.write(data, 'binary', cb);
      }
      catch (e) {
        if (typeof cb == 'function') cb(e);
        else this.emit('error', e);
      }
    }
  }
}

module.exports = Sender;

function writeUInt16BE(value, offset) {
  this[offset] = (value & 0xff00)>>8;
  this[offset+1] = value & 0xff;
}

function writeUInt32BE(value, offset) {
  this[offset] = (value & 0xff000000)>>24;
  this[offset+1] = (value & 0xff0000)>>16;
  this[offset+2] = (value & 0xff00)>>8;
  this[offset+3] = value & 0xff;
}

function getArrayBuffer(array) {
  var l = array.byteLength
    , buffer = new Buffer(l);
  for (var i = 0; i < l; ++i) {
    buffer[i] = array[i];
  }
  return buffer;
}

function getRandomMask() {
  return new Buffer([
    ~~(Math.random() * 255),
    ~~(Math.random() * 255),
    ~~(Math.random() * 255),
    ~~(Math.random() * 255)
  ]);
}
<commit_msg>Don't use byteLength when being passed an ArrayBufferView<commit_after>/*!
 * ws: a node.js websocket client
 * Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com>
 * MIT Licensed
 */

var events = require('events')
  , util = require('util')
  , EventEmitter = events.EventEmitter
  , ErrorCodes = require('./ErrorCodes')
  , bufferUtil = require('./BufferUtil').BufferUtil;

/**
 * HyBi Sender implementation
 */

function Sender(socket) {
  this._socket = socket;
  this.firstFragment = true;
}

/**
 * Inherits from EventEmitter.
 */

util.inherits(Sender, events.EventEmitter);

/**
 * Sends a close instruction to the remote party.
 *
 * @api public
 */

Sender.prototype.close = function(code, data, mask) {
  if (typeof code !== 'undefined') {
    if (typeof code !== 'number' ||
      !ErrorCodes.isValidErrorCode(code)) throw new Error('first argument must be a valid error code number');
  }
  code = code || 1000;
  var dataBuffer = new Buffer(2 + (data ? Buffer.byteLength(data) : 0));
  writeUInt16BE.call(dataBuffer, code, 0);
  if (dataBuffer.length > 2) dataBuffer.write(data, 2);
  this.frameAndSend(0x8, dataBuffer, true, mask);
}

/**
 * Sends a ping message to the remote party.
 *
 * @api public
 */

Sender.prototype.ping = function(data, options) {
  var mask = options && options.mask;
  this.frameAndSend(0x9, data || '', true, mask);
}

/**
 * Sends a pong message to the remote party.
 *
 * @api public
 */

Sender.prototype.pong = function(data, options) {
  var mask = options && options.mask;
  this.frameAndSend(0xa, data || '', true, mask);
}

/**
 * Sends text or binary data to the remote party.
 *
 * @api public
 */

Sender.prototype.send = function(data, options, cb) {
  var finalFragment = options && options.fin === false ? false : true;
  var mask = options && options.mask;
  var opcode = options && options.binary ? 2 : 1;
  if (this.firstFragment === false) opcode = 0;
  else this.firstFragment = false;
  if (finalFragment) this.firstFragment = true
  this.frameAndSend(opcode, data, finalFragment, mask, cb);
}

/**
 * Frames and sends a piece of data according to the HyBi WebSocket protocol.
 *
 * @api private
 */

Sender.prototype.frameAndSend = function(opcode, data, finalFragment, maskData, cb) {
  var canModifyData = false;

  if (!data) {
    try {
      this._socket.write(new Buffer([opcode | (finalFragment ? 0x80 : 0), 0 | (maskData ? 0x80 : 0)].concat(maskData ? [0, 0, 0, 0] : [])), 'binary', cb);
    }
    catch (e) {
      if (typeof cb == 'function') cb(e);
      else this.emit('error', e);
    }
    return;
  }

  if (!Buffer.isBuffer(data)) {
    canModifyData = true;
    if (data && (typeof data.byteLength !== 'undefined' || typeof data.buffer !== 'undefined')) {
      data = getArrayBuffer(data);
    } else {
      data = new Buffer(data);
    }
  }

  var dataLength = data.length
    , dataOffset = maskData ? 6 : 2
    , secondByte = dataLength;

  if (dataLength >= 65536) {
    dataOffset += 8;
    secondByte = 127;
  }
  else if (dataLength > 125) {
    dataOffset += 2;
    secondByte = 126;
  }

  var mergeBuffers = dataLength < 32768 || (maskData && !canModifyData);
  var totalLength = mergeBuffers ? dataLength + dataOffset : dataOffset;
  var outputBuffer = new Buffer(totalLength);
  outputBuffer[0] = finalFragment ? opcode | 0x80 : opcode;

  switch (secondByte) {
    case 126:
      writeUInt16BE.call(outputBuffer, dataLength, 2);
      break;
    case 127:
      writeUInt32BE.call(outputBuffer, 0, 2);
      writeUInt32BE.call(outputBuffer, dataLength, 6);
  }

  if (maskData) {
    outputBuffer[1] = secondByte | 0x80;
    var mask = this._randomMask || (this._randomMask = getRandomMask());
    outputBuffer[dataOffset - 4] = mask[0];
    outputBuffer[dataOffset - 3] = mask[1];
    outputBuffer[dataOffset - 2] = mask[2];
    outputBuffer[dataOffset - 1] = mask[3];
    if (mergeBuffers) {
      bufferUtil.mask(data, mask, outputBuffer, dataOffset, dataLength);
      try {
        this._socket.write(outputBuffer, 'binary', cb);
      }
      catch (e) {
        if (typeof cb == 'function') cb(e);
        else this.emit('error', e);
      }
    }
    else {
      bufferUtil.mask(data, mask, data, 0, dataLength);
      try {
        this._socket.write(outputBuffer, 'binary');
        this._socket.write(data, 'binary', cb);
      }
      catch (e) {
        if (typeof cb == 'function') cb(e);
        else this.emit('error', e);
      }
    }
  }
  else {
    outputBuffer[1] = secondByte;
    if (mergeBuffers) {
      data.copy(outputBuffer, dataOffset);
      try {
        this._socket.write(outputBuffer, 'binary', cb);
      }
      catch (e) {
        if (typeof cb == 'function') cb(e);
        else this.emit('error', e);
      }
    }
    else {
      try {
        this._socket.write(outputBuffer, 'binary');
        this._socket.write(data, 'binary', cb);
      }
      catch (e) {
        if (typeof cb == 'function') cb(e);
        else this.emit('error', e);
      }
    }
  }
}

module.exports = Sender;

function writeUInt16BE(value, offset) {
  this[offset] = (value & 0xff00)>>8;
  this[offset+1] = value & 0xff;
}

function writeUInt32BE(value, offset) {
  this[offset] = (value & 0xff000000)>>24;
  this[offset+1] = (value & 0xff0000)>>16;
  this[offset+2] = (value & 0xff00)>>8;
  this[offset+3] = value & 0xff;
}

function getArrayBuffer(data) {
  // data is either an ArrayBuffer or ArrayBufferView.
  var array = data.buffer || data
    , l = data.byteLength || data.length
    , buffer = new Buffer(l);
  for (var i = 0; i < l; ++i) {
    buffer[i] = array[i];
  }
  return buffer;
}

function getRandomMask() {
  return new Buffer([
    ~~(Math.random() * 255),
    ~~(Math.random() * 255),
    ~~(Math.random() * 255),
    ~~(Math.random() * 255)
  ]);
}
<|endoftext|>


<commit_before>"use strict";

var git = require("nodegit");
var path = require("path");
var fs = require("q-io/fs"); // https://github.com/kriskowal/q-io

/**
 * Get a copy of the project using Git.
 *
 * @return a PROMISE for the HEAD commit hash of the repo.
 */
module.exports = function getProject(repoUrl, repoName, localName) {
  var repository;
  var branchName;

  function generateRepoMetaData(sha) {
    return {
      repoName: repoName,
      repoUrl: repoUrl,
      localName: localName,
      commit: sha,
      shortCommit: sha.substring(0, 7)
    };
  }

  return fs.exists(localName)
    .then(function(pathExists) {

      // Mac OSX certificate issue http://www.nodegit.org/guides/cloning/
      var copingWithMacCertBug = {
        certificateCheck: function() { return 1; }
      };

      // If there is no matching directory then **CLONE** the repo.
      if (!pathExists) {
        var cloneOptions = {};
        cloneOptions.remoteCallbacks = copingWithMacCertBug;
        return git.Clone(repoUrl, localName, cloneOptions)
          .then(function(repo) {
            return repo.getHeadCommit();
          })
          .then(function(commit) {
            return generateRepoMetaData(commit.sha());
          });

      // Else the repo probably exists, perform a **PULL** on it.
      // https://github.com/nodegit/nodegit/issues/341
      // https://github.com/nodegit/nodegit/commit/dc814a45268305e56c99db64efd5d0fe8bbbb8c2
      } else {
        return git.Repository.open(localName)
          .then(function(repo) {
            repository = repo;
            return repository.getCurrentBranch();
          })
          .then(function(branch) {
            branchName = branch.shorthand();
            return repository.fetchAll(copingWithMacCertBug, true);
          })
          .then(function() {
            // Should be a fast-forward merge.
            // Will return the commit hash of merge, hopefully matching remote HEAD.
            return repository
              .mergeBranches(branchName, "origin/" + branchName)
              .then(function(commitHash) {
                return generateRepoMetaData(commitHash);
              });
          });
      }
    });
};
<commit_msg>Docs.<commit_after>/**
 * Interact with local and remote project repos using Git.
 *
 * TODO: Separate out the Clone and Pull logic so Pull can be called independently.
 * TODO: Changing branch.
 */

"use strict";

var git = require("nodegit");
var path = require("path");
var fs = require("q-io/fs"); // https://github.com/kriskowal/q-io

/**
 * Get a copy of the project using Git.
 *
 * @return a PROMISE for the HEAD commit hash of the repo.
 */
module.exports = function getProject(repoUrl, repoName, localName) {
  var repository;
  var branchName;

  function generateRepoMetaData(sha) {
    return {
      repoName: repoName,
      repoUrl: repoUrl,
      localName: localName,
      commit: sha,
      shortCommit: sha.substring(0, 7)
    };
  }

  return fs.exists(localName)
    .then(function(pathExists) {

      // Mac OSX certificate issue http://www.nodegit.org/guides/cloning/
      var copingWithMacCertBug = {
        certificateCheck: function() { return 1; }
      };

      // If there is no matching directory then **CLONE** the repo.
      if (!pathExists) {
        var cloneOptions = {};
        cloneOptions.remoteCallbacks = copingWithMacCertBug;
        return git.Clone(repoUrl, localName, cloneOptions)
          .then(function(repo) {
            return repo.getHeadCommit();
          })
          .then(function(commit) {
            return generateRepoMetaData(commit.sha());
          });

      // Else the repo probably exists, perform a **PULL** on it.
      // https://github.com/nodegit/nodegit/issues/341
      // https://github.com/nodegit/nodegit/commit/dc814a45268305e56c99db64efd5d0fe8bbbb8c2
      } else {
        return git.Repository.open(localName)
          .then(function(repo) {
            repository = repo;
            return repository.getCurrentBranch();
          })
          .then(function(branch) {
            branchName = branch.shorthand();
            return repository.fetchAll(copingWithMacCertBug, true);
          })
          .then(function() {
            // Should be a fast-forward merge.
            // Will return the commit hash of merge, hopefully matching remote HEAD.
            return repository
              .mergeBranches(branchName, "origin/" + branchName)
              .then(function(commitHash) {
                return generateRepoMetaData(commitHash);
              });
          });
      }
    });
};
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Component.extend({
    tagName: 'button',
    buttonText: '',
    submitting: false,
    showSpinner: false,
    showSpinnerTimeout: null,
    autoWidth: true,

    // Disable Button when isLoading equals true
    attributeBindings: ['disabled', 'type', 'tabindex'],

    // Must be set on the controller
    disabled: Ember.computed.equal('showSpinner', true),

    click: function () {
        if (this.get('action')) {
            this.sendAction('action');
            return false;
        }
        return true;
    },

    toggleSpinner: Ember.observer('submitting', function () {
        var submitting = this.get('submitting'),
            timeout = this.get('showSpinnerTimeout');

        if (submitting) {
            this.set('showSpinner', true);
            this.set('showSpinnerTimeout', Ember.run.later(this, function () {
                if (!this.get('submitting')) {
                    this.set('showSpinner', false);
                    this.set('showSpinnerTimeout', null);
                }
            }, 1000));
        } else if (!submitting && timeout === null) {
            this.set('showSpinner', false);
        }
    }),

    setSize: Ember.observer('showSpinner', function () {
        if (this.get('showSpinner') && this.get('autoWidth')) {
            this.$().width(this.$().width());
            this.$().height(this.$().height());
        } else {
            this.$().width('');
            this.$().height('');
        }
    }),

    willDestroy: function () {
        Ember.run.cancel(this.get('showSpinnerTimeout'));
    }
});
<commit_msg>Prevent gh-spin-button from infinite spin<commit_after>import Ember from 'ember';

export default Ember.Component.extend({
    tagName: 'button',
    buttonText: '',
    submitting: false,
    showSpinner: false,
    showSpinnerTimeout: null,
    autoWidth: true,

    // Disable Button when isLoading equals true
    attributeBindings: ['disabled', 'type', 'tabindex'],

    // Must be set on the controller
    disabled: Ember.computed.equal('showSpinner', true),

    click: function () {
        if (this.get('action')) {
            this.sendAction('action');
            return false;
        }
        return true;
    },

    toggleSpinner: Ember.observer('submitting', function () {
        var submitting = this.get('submitting'),
            timeout = this.get('showSpinnerTimeout');

        if (submitting) {
            this.set('showSpinner', true);
            this.set('showSpinnerTimeout', Ember.run.later(this, function () {
                if (!this.get('submitting')) {
                    this.set('showSpinner', false);
                }
                this.set('showSpinnerTimeout', null);
            }, 1000));
        } else if (!submitting && timeout === null) {
            this.set('showSpinner', false);
        }
    }),

    setSize: Ember.observer('showSpinner', function () {
        if (this.get('showSpinner') && this.get('autoWidth')) {
            this.$().width(this.$().width());
            this.$().height(this.$().height());
        } else {
            this.$().width('');
            this.$().height('');
        }
    }),

    willDestroy: function () {
        Ember.run.cancel(this.get('showSpinnerTimeout'));
    }
});
<|endoftext|>


<commit_before>/**
 * @file createRole command
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license GPL-3.0
 */

exports.exec = async (Bastion, message, args) => {
  if (!args.name) {
    return Bastion.emit('commandUsage', message, this.help);
  }

  if (!Bastion.resolver.resolveColor(args.color)) {
    args.color = 0;
  }

  let maxLength = 100;
  args.name = args.name.join(' ');

  if (args.name.length.inRange(0, maxLength)) {
    return Bastion.emit('error', '', Bastion.i18n.error(message.guild.language, 'roleNameLength', maxLength), message.channel);
  }

  let data = roleData(args.name, args.color);
  let role = await message.guild.createRole(data);

  await message.channel.send({
    embed: {
      color: Bastion.colors.GREEN,
      description: Bastion.i18n.info(message.guild.language, 'createRole', message.author.tag, role.name),
      footer: {
        text: `ID: ${role.id}`
      }
    }
  }).catch(e => {
    Bastion.log.error(e);
  });
};

exports.config = {
  aliases: [ 'creater' ],
  enabled: true,
  argsDefinitions: [
    { name: 'name', type: String, alias: 'n', multiple: true, defaultOption: true, defaultValue: [ 'new role' ] },
    { name: 'color', type: String, alias: 'c', defaultValue: '0' }
  ]
};

exports.help = {
  name: 'createRole',
  description: 'Creates a new role on your Discord server.',
  botPermission: 'MANAGE_ROLES',
  userTextPermission: 'MANAGE_ROLES',
  userVoicePermission: '',
  usage: 'createrole [[-n] Role Name] [-c hex-color-code]',
  example: [ 'createrole -n Role Name -c #dc143', 'createrole -c #dc143c', 'createrole Role Name', 'createrole' ]
};

/**
 * Takes Discord role info and returns the role data object for use.
 * @function roleData
 * @param {string} [name=new role] role The array that contains the character pool.
 * @param {string} [color=0] The array of the string to match with the character pool.
 * @returns {object} The Discord role data object.
*/
function roleData(name = 'new role', color = '#000000') {
  let data = {
    name: name,
    color: color
  };
  return data;
}
<commit_msg>commands: fix wrong input length check in createRolecommand<commit_after>/**
 * @file createRole command
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license GPL-3.0
 */

exports.exec = async (Bastion, message, args) => {
  if (!args.name) {
    return Bastion.emit('commandUsage', message, this.help);
  }

  if (!Bastion.resolver.resolveColor(args.color)) {
    args.color = 0;
  }

  let maxLength = 100;
  args.name = args.name.join(' ');

  if (!args.name.length.inRange(0, maxLength)) {
    return Bastion.emit('error', '', Bastion.i18n.error(message.guild.language, 'roleNameLength', maxLength), message.channel);
  }

  let data = roleData(args.name, args.color);
  let role = await message.guild.createRole(data);

  await message.channel.send({
    embed: {
      color: Bastion.colors.GREEN,
      description: Bastion.i18n.info(message.guild.language, 'createRole', message.author.tag, role.name),
      footer: {
        text: `ID: ${role.id}`
      }
    }
  }).catch(e => {
    Bastion.log.error(e);
  });
};

exports.config = {
  aliases: [ 'creater' ],
  enabled: true,
  argsDefinitions: [
    { name: 'name', type: String, alias: 'n', multiple: true, defaultOption: true, defaultValue: [ 'new role' ] },
    { name: 'color', type: String, alias: 'c', defaultValue: '0' }
  ]
};

exports.help = {
  name: 'createRole',
  description: 'Creates a new role on your Discord server.',
  botPermission: 'MANAGE_ROLES',
  userTextPermission: 'MANAGE_ROLES',
  userVoicePermission: '',
  usage: 'createrole [[-n] Role Name] [-c hex-color-code]',
  example: [ 'createrole -n Role Name -c #dc143', 'createrole -c #dc143c', 'createrole Role Name', 'createrole' ]
};

/**
 * Takes Discord role info and returns the role data object for use.
 * @function roleData
 * @param {string} [name=new role] role The array that contains the character pool.
 * @param {string} [color=0] The array of the string to match with the character pool.
 * @returns {object} The Discord role data object.
*/
function roleData(name = 'new role', color = '#000000') {
  let data = {
    name: name,
    color: color
  };
  return data;
}
<|endoftext|>


<commit_before>/**!
 * AngularJS dropzone directive
 * @author Uday Hiwarale <uhiwarale@gmail.com>
 * https://www.github.com/thatisuday/ngDropzone
 */

(function(root){
    'use strict';
  function factory(angular, Dropzone){

    angular.module('thatisuday.dropzone', []).provider('dropzoneOps', function(){
      /*
       *  Add default options here
      **/
      var defOps = {
        //Add your options here
      };

      return {
        setOptions : function(newOps){
          angular.extend(defOps, newOps);
        },
        $get : function(){
          return defOps;
        }
      }
    }).directive('ngDropzone', ['$timeout', 'dropzoneOps', function($timeout, dropzoneOps){
      return {
        restrict : 'AE',
        template : '

',
        replace : true,
        scope : {
          options : '=?', //http://www.dropzonejs.com/#configuration-options
          callbacks : '=?', //http://www.dropzonejs.com/#events
          methods : '=?' //http://www.dropzonejs.com/#dropzone-methods
        },
        link : function(scope, iElem, iAttr){
          //Set options for dropzone {override from dropzone options provider}
          scope.options = scope.options || {};
          var initOps = angular.extend({}, dropzoneOps, scope.options);

          //Instantiate dropzone with initOps
          var dropzone = new Dropzone(iElem[0], initOps);

          /*********************************************/

          //Instantiate Dropzone methods (Control actions)
          scope.methods = scope.methods || {};

          scope.methods.getDropzone = function(){
            return dropzone; //Return dropzone instance
          };

          scope.methods.getAllFiles = function(){
            return dropzone.files; //Return all files
          };

          var controlMethods = [
            'removeFile', 'removeAllFiles', 'processQueue',
            'getAcceptedFiles', 'getRejectedFiles', 'getQueuedFiles', 'getUploadingFiles',
            'disable', 'enable', 'confirm', 'createThumbnailFromUrl'
          ];

          angular.forEach(controlMethods, function(methodName){
            scope.methods[methodName] = function(){
              dropzone[methodName].apply(dropzone, arguments);
              if(!scope.$$phase && !scope.$root.$$phase) scope.$apply();
            }
          });

          /*********************************************/

          //Set invents (callbacks)
          if(scope.callbacks){
            var callbackMethods = [
              'drop', 'dragstart', 'dragend',
              'dragenter', 'dragover', 'dragleave', 'addedfile', 'removedfile',
              'thumbnail', 'error', 'processing', 'uploadprogress',
              'sending', 'success', 'complete', 'canceled', 'maxfilesreached',
              'maxfilesexceeded', 'processingmultiple', 'sendingmultiple', 'successmultiple',
              'completemultiple', 'canceledmultiple', 'totaluploadprogress', 'reset', 'queuecomplete'
            ];
            angular.forEach(callbackMethods, function(method){
              var callback = (scope.callbacks[method] || angular.noop);
              dropzone.on(method, function(){
                callback.apply(null, arguments);
                if(!scope.$$phase && !scope.$root.$$phase) scope.$apply();
              });
            });
          }
        }
      }
    }]);
  }

  if ((typeof module === 'object') && module.exports) {
    /* CommonJS module */
    module.exports = factory(require('angular'), require('dropzone'));
  } else if (typeof define === 'function' && define.amd) {
    /* AMD module */
    define(['angular', 'dropzone'], factory);
  } else {
    /* Browser global */
    factory(root.angular, root.Dropzone);
  }
})(this);
<commit_msg>Allow users to include a custom drop area message<commit_after>/**!
 * AngularJS dropzone directive
 * @author Uday Hiwarale <uhiwarale@gmail.com>
 * https://www.github.com/thatisuday/ngDropzone
 */

(function(root){
    'use strict';
  function factory(angular, Dropzone){

    angular.module('thatisuday.dropzone', []).provider('dropzoneOps', function(){
      /*
       *  Add default options here
      **/
      var defOps = {
        //Add your options here
      };

      return {
        setOptions : function(newOps){
          angular.extend(defOps, newOps);
        },
        $get : function(){
          return defOps;
        }
      }
    }).directive('ngDropzone', ['$timeout', 'dropzoneOps', function($timeout, dropzoneOps){
      return {
        restrict : 'AE',
        template : '

',
        replace : true,
        transclude: true,
        scope : {
          options : '=?', //http://www.dropzonejs.com/#configuration-options
          callbacks : '=?', //http://www.dropzonejs.com/#events
          methods : '=?' //http://www.dropzonejs.com/#dropzone-methods
        },
        link : function(scope, iElem, iAttr){
          //Set options for dropzone {override from dropzone options provider}
          scope.options = scope.options || {};
          var initOps = angular.extend({}, dropzoneOps, scope.options);

          //Instantiate dropzone with initOps
          var dropzone = new Dropzone(iElem[0], initOps);

          /*********************************************/

          //Instantiate Dropzone methods (Control actions)
          scope.methods = scope.methods || {};

          scope.methods.getDropzone = function(){
            return dropzone; //Return dropzone instance
          };

          scope.methods.getAllFiles = function(){
            return dropzone.files; //Return all files
          };

          var controlMethods = [
            'removeFile', 'removeAllFiles', 'processQueue',
            'getAcceptedFiles', 'getRejectedFiles', 'getQueuedFiles', 'getUploadingFiles',
            'disable', 'enable', 'confirm', 'createThumbnailFromUrl'
          ];

          angular.forEach(controlMethods, function(methodName){
            scope.methods[methodName] = function(){
              dropzone[methodName].apply(dropzone, arguments);
              if(!scope.$$phase && !scope.$root.$$phase) scope.$apply();
            }
          });

          /*********************************************/

          //Set invents (callbacks)
          if(scope.callbacks){
            var callbackMethods = [
              'drop', 'dragstart', 'dragend',
              'dragenter', 'dragover', 'dragleave', 'addedfile', 'removedfile',
              'thumbnail', 'error', 'processing', 'uploadprogress',
              'sending', 'success', 'complete', 'canceled', 'maxfilesreached',
              'maxfilesexceeded', 'processingmultiple', 'sendingmultiple', 'successmultiple',
              'completemultiple', 'canceledmultiple', 'totaluploadprogress', 'reset', 'queuecomplete'
            ];
            angular.forEach(callbackMethods, function(method){
              var callback = (scope.callbacks[method] || angular.noop);
              dropzone.on(method, function(){
                callback.apply(null, arguments);
                if(!scope.$$phase && !scope.$root.$$phase) scope.$apply();
              });
            });
          }
        }
      }
    }]);
  }

  if ((typeof module === 'object') && module.exports) {
    /* CommonJS module */
    module.exports = factory(require('angular'), require('dropzone'));
  } else if (typeof define === 'function' && define.amd) {
    /* AMD module */
    define(['angular', 'dropzone'], factory);
  } else {
    /* Browser global */
    factory(root.angular, root.Dropzone);
  }
})(this);
<|endoftext|>