<commit_before>if ( typeof window === 'undefined' ) {
  require('../../app/arrays');
  var expect = require('chai').expect;
}

describe('arrays', function() {
  var a;

  beforeEach(function() {
    a = [ 1, 2, 3, 4 ];
  });

  it('you should be able to determine the location of an item in an array', function() {
    expect(arraysAnswers.indexOf(a, 3)).to.eql(2);
    expect(arraysAnswers.indexOf(a, 5)).to.eql(-1);
  });

  it('you should be able to add the values of an array', function() {
    expect(arraysAnswers.sum(a)).to.eql(10);
  });

  it('you should be able to remove all instances of a value from an array', function() {
    a.push(2); // Make sure the value appears more than one time
    var result = arraysAnswers.remove(a, 2);

    expect(result).to.have.length(3);
    expect(result.join(' ')).to.eql('1 3 4');
  });

  it('you should be able to remove all instances of a value from an array, returning the original array', function() {
    a.splice( 1, 0, 2 );
    a.push( 2 );
    a.push( 2 );

    var result = arraysAnswers.removeWithoutCopy(a, 2);

    expect(result).to.have.length(3);
    expect(result.join(' ')).to.eql('1 3 4');

    // make sure that you return the same array instance
    expect(result).equal(a);
  });

  it('you should be able to add an item to the end of an array', function() {
    var result = arraysAnswers.append(a, 10);

    expect(result).to.have.length(5);
    expect(result[result.length - 1]).to.eql(10);
  });

  it('you should be able to remove the last item of an array', function() {
    var result = arraysAnswers.truncate(a);

    expect(result).to.have.length(3);
    expect(result.join(' ')).to.eql('1 2 3');
  });

  it('you should be able to add an item to the beginning of an array', function () {
    var result = arraysAnswers.prepend(a, 10);

    expect(result).to.have.length(5);
    expect(result[0]).to.eql(10);
  });

  it('you should be able to remove the first item of an array', function () {
    var result = arraysAnswers.curtail(a);

    expect(result).to.have.length(3);
    expect(result.join(' ')).to.eql('2 3 4');
  });

  it('you should be able to join together two arrays', function() {
    var c = [ 'a', 'b', 'c', 1 ];
    var result = arraysAnswers.concat(a, c);

    expect(result).to.have.length(8);
    expect(result.join(' ')).to.eql('1 2 3 4 a b c 1');
  });

  it('you should be able to add an item anywhere in an array', function() {
    var result = arraysAnswers.insert(a, 'z', 2);

    expect(result).to.have.length(5);
    expect(result.join(' ')).to.eql('1 2 z 3 4');
  });

  it('you should be able to count the occurences of an item in an array', function() {
    var result = arraysAnswers.count([ 1, 2, 4, 4, 3, 4, 3 ], 4);

    expect(result).to.eql(3);
  });

  it('you should be able to find duplicates in an array', function() {
    var result = arraysAnswers.duplicates([ 1, 2, 4, 4, 3, 3, 1, 5, 3 ]);

    expect(result.sort()).to.eql([1, 3, 4]);
  });

  it('you should be able to square each number in an array', function() {
    var result = arraysAnswers.square(a);

    expect(result).to.have.length(4);
    expect(result.join(' ')).to.eql('1 4 9 16');
  });

  it('you should be able to find all occurrences of an item in an array', function() {
    var result = arraysAnswers.findAllOccurrences([ 1, 2, 3, 4, 5, 6, 1, 7], 1);

    expect(result.sort().join(' ')).to.eql('0 6');
  });

});
<commit_msg>Better arrayAnswers.remove test data<commit_after>if ( typeof window === 'undefined' ) {
  require('../../app/arrays');
  var expect = require('chai').expect;
}

describe('arrays', function() {
  var a;

  beforeEach(function() {
    a = [ 1, 2, 3, 4 ];
  });

  it('you should be able to determine the location of an item in an array', function() {
    expect(arraysAnswers.indexOf(a, 3)).to.eql(2);
    expect(arraysAnswers.indexOf(a, 5)).to.eql(-1);
  });

  it('you should be able to add the values of an array', function() {
    expect(arraysAnswers.sum(a)).to.eql(10);
  });

  it('you should be able to remove all instances of a value from an array', function() {
    a.push(2); // Make sure the value appears more than one time
    a.push(2); // Make sure the value appears more than one time in a row
    var result = arraysAnswers.remove(a, 2);

    expect(result).to.have.length(3);
    expect(result.join(' ')).to.eql('1 3 4');
  });

  it('you should be able to remove all instances of a value from an array, returning the original array', function() {
    a.splice( 1, 0, 2 );
    a.push( 2 );
    a.push( 2 );

    var result = arraysAnswers.removeWithoutCopy(a, 2);

    expect(result).to.have.length(3);
    expect(result.join(' ')).to.eql('1 3 4');

    // make sure that you return the same array instance
    expect(result).equal(a);
  });

  it('you should be able to add an item to the end of an array', function() {
    var result = arraysAnswers.append(a, 10);

    expect(result).to.have.length(5);
    expect(result[result.length - 1]).to.eql(10);
  });

  it('you should be able to remove the last item of an array', function() {
    var result = arraysAnswers.truncate(a);

    expect(result).to.have.length(3);
    expect(result.join(' ')).to.eql('1 2 3');
  });

  it('you should be able to add an item to the beginning of an array', function () {
    var result = arraysAnswers.prepend(a, 10);

    expect(result).to.have.length(5);
    expect(result[0]).to.eql(10);
  });

  it('you should be able to remove the first item of an array', function () {
    var result = arraysAnswers.curtail(a);

    expect(result).to.have.length(3);
    expect(result.join(' ')).to.eql('2 3 4');
  });

  it('you should be able to join together two arrays', function() {
    var c = [ 'a', 'b', 'c', 1 ];
    var result = arraysAnswers.concat(a, c);

    expect(result).to.have.length(8);
    expect(result.join(' ')).to.eql('1 2 3 4 a b c 1');
  });

  it('you should be able to add an item anywhere in an array', function() {
    var result = arraysAnswers.insert(a, 'z', 2);

    expect(result).to.have.length(5);
    expect(result.join(' ')).to.eql('1 2 z 3 4');
  });

  it('you should be able to count the occurences of an item in an array', function() {
    var result = arraysAnswers.count([ 1, 2, 4, 4, 3, 4, 3 ], 4);

    expect(result).to.eql(3);
  });

  it('you should be able to find duplicates in an array', function() {
    var result = arraysAnswers.duplicates([ 1, 2, 4, 4, 3, 3, 1, 5, 3 ]);

    expect(result.sort()).to.eql([1, 3, 4]);
  });

  it('you should be able to square each number in an array', function() {
    var result = arraysAnswers.square(a);

    expect(result).to.have.length(4);
    expect(result.join(' ')).to.eql('1 4 9 16');
  });

  it('you should be able to find all occurrences of an item in an array', function() {
    var result = arraysAnswers.findAllOccurrences([ 1, 2, 3, 4, 5, 6, 1, 7], 1);

    expect(result.sort().join(' ')).to.eql('0 6');
  });

});
<|endoftext|>


<commit_before>/*
*   Copyright 2012 Comcast
*
*   Licensed under the Apache License, Version 2.0 (the "License");
*   you may not use this file except in compliance with the License.
*   You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*   Unless required by applicable law or agreed to in writing, software
*   distributed under the License is distributed on an "AS IS" BASIS,
*   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*   See the License for the specific language governing permissions and
*   limitations under the License.
*/

var $X, Xooie;

$X = Xooie = (function(static_config) {
    var config = {
            modules: {},
            addons: {}
        },
        obj = function() {
            return false;
        };

    function copyObj(dst, src) {
        var name;

        for (name in src) {
            if (src.hasOwnProperty(name)) {
                dst[name] = src[name];
            }
        }
    }

    obj.config = function(cfg) {
        var name;

        for (name in cfg) {
            if (cfg.hasOwnProperty(name)) {
                if (name === 'modules' || name == 'addons') {
                    copyObj(config[name], cfg[name]);
                } else {
                    config[name] = cfg[name];
                }
            }
        }
    };

    obj.mapName = function(name, type, root) {
        if (typeof config[type][name] === 'undefined') {
            return root + name;
        } else {
            return config[type][name];
        }
    };

    if (static_config) {
        obj.config(static_config);
    }

    return obj;
}(Xooie));

define(['jquery'], function($){
    var config = Xooie.config,
        mapName = Xooie.mapName,

        instantiateWidget = function(Widget){
            new Widget(node);
        };

    $X = Xooie = function(element){
        element = $(element);

        var widgetElements = element.find('[data-widget-type]');

        if (element.is('[data-widget-type]')){
            widgetElements = widgetElements.add(element);
        }

        widgetElements.each(function(){
            var node = $(this),
                module_name,
                types = node.data('widgetType').split(/\s+/);

            for (var i = 0; i < types.length; i++) {
                module_name = $X.mapName(types[i], 'modules', 'xooie/');

                require([module_name], instantiateWidget);
            }
        });
    };

    Xooie.config = config;
    Xooie.mapName = mapName;

    $(document).ready(function() {
        $X($(this));
    });

    return Xooie;
});

<commit_msg>Fixed autoinstantiation<commit_after>/*
*   Copyright 2012 Comcast
*
*   Licensed under the Apache License, Version 2.0 (the "License");
*   you may not use this file except in compliance with the License.
*   You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*   Unless required by applicable law or agreed to in writing, software
*   distributed under the License is distributed on an "AS IS" BASIS,
*   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*   See the License for the specific language governing permissions and
*   limitations under the License.
*/

var $X, Xooie;

$X = Xooie = (function(static_config) {
    var config = {
            modules: {},
            addons: {}
        },
        obj = function() {
            return false;
        };

    function copyObj(dst, src) {
        var name;

        for (name in src) {
            if (src.hasOwnProperty(name)) {
                dst[name] = src[name];
            }
        }
    }

    obj.config = function(cfg) {
        var name;

        for (name in cfg) {
            if (cfg.hasOwnProperty(name)) {
                if (name === 'modules' || name == 'addons') {
                    copyObj(config[name], cfg[name]);
                } else {
                    config[name] = cfg[name];
                }
            }
        }
    };

    obj.mapName = function(name, type, root) {
        if (typeof config[type][name] === 'undefined') {
            return root + name;
        } else {
            return config[type][name];
        }
    };

    if (static_config) {
        obj.config(static_config);
    }

    return obj;
}(Xooie));

define(['jquery'], function($){
    var config = Xooie.config,
        mapName = Xooie.mapName,

        instantiateWidget = function(Widget){
            new Widget(node);
        };

    $X = Xooie = function(element){
        element = $(element);

        var widgetElements = element.find('[data-widget-type]');

        if (element.is('[data-widget-type]')){
            widgetElements = widgetElements.add(element);
        }

        widgetElements.each(function(){
            var node = $(this),
                module_name,
                types = node.data('widgetType').split(/\s+/);

            for (var i = 0; i < types.length; i++) {
                module_name = $X.mapName(types[i], 'modules', 'xooie/');

                require([module_name], instantiateWidget);
            }
        });
    };

    Xooie.config = config;
    Xooie.mapName = mapName;

    return Xooie;
});

require(['jquery', 'xooie'], function($, $X){
    $(document).ready(function() {
        $X($(this));
    });
});
<|endoftext|>


<commit_before>define([
  'entity-component/position'
], function(Position) {
  'use strict';

  function Spwaner(entityFactory, position, options) {
    if (!(position instanceof Position)) { throw new TypeError('not a Position'); }
    options = options || {};
    this.entityFactory = entityFactory;
    this.position = position;
    this.areaRadius = options.areaRadius || 50;
    this.capacity = options.capacity || 5;
    this.spwaningTime = options.spwaningTime || 5000;
    this.entities = [];
    this.regen = 0;
    Object.seal(this);
  }

  Spwaner.prototype.update = function update(elapsedTime) {
    if (this.entities.length < this.capacity) {
      this.regen += elapsedTime;
      if (this.regen >= this.spwaningTime) {
        this.regen -= this.spwaningTime;
        const position = new Position(
          this.position.x - this.areaRadius + Math.round(Math.random() * this.areaRadius * 2),
          this.position.y - this.areaRadius + Math.round(Math.random() * this.areaRadius * 2)
        );
        this.entities.push(this.entityFactory.create(position));
      }
    }
  };

  Spwaner.prototype.cleanup = function cleanup() {
    this.entities = this.entities.filter(function filter(e) {
      return (e.health && (e.health.hp <= 0)) || !(e.health);
    });
  }

  return Spwaner;
});
<commit_msg>Fix Spwaner cleanup rules<commit_after>define([
  'entity-component/position'
], function(Position) {
  'use strict';

  function Spwaner(entityFactory, position, options) {
    if (!(position instanceof Position)) { throw new TypeError('not a Position'); }
    options = options || {};
    this.entityFactory = entityFactory;
    this.position = position;
    this.areaRadius = options.areaRadius || 50;
    this.capacity = options.capacity || 5;
    this.spwaningTime = options.spwaningTime || 5000;
    this.entities = [];
    this.regen = 0;
    Object.seal(this);
  }

  Spwaner.prototype.update = function update(elapsedTime) {
    if (this.entities.length < this.capacity) {
      this.regen += elapsedTime;
      if (this.regen >= this.spwaningTime) {
        this.regen -= this.spwaningTime;
        const position = new Position(
          this.position.x - this.areaRadius + Math.round(Math.random() * this.areaRadius * 2),
          this.position.y - this.areaRadius + Math.round(Math.random() * this.areaRadius * 2)
        );
        this.entities.push(this.entityFactory.create(position));
      }
    }
  };

  Spwaner.prototype.cleanup = function cleanup() {
    this.entities = this.entities.filter(function filter(e) {
      return (e.health && (e.health.hp > 0)) || !(e.health);
    });
  }

  return Spwaner;
});
<|endoftext|>


<commit_before>(function() {
  uR.mountElement = function mountElement(names,options) {
    options = options || {};
    if (options.ur_modal) {
      options.mount_to = options.mount_to || uR.config.mount_alerts_to;
    }
    var mount_to = options.mount_to || uR.config.mount_to
    var target = document.querySelector(mount_to);
    var children = target.childNodes;
    var i = target.childNodes.length;
    while (i--) { target.removeChild(children[i]); }

    if (typeof names == "string") { names = [names]; }
    var _t = [];
    uR.forEach(names,function(name) {
      name = name.replace(/\//g,''); // Some tags pass in tag name for path like /hello-world/
      var element = document.createElement(name);
      if (options.innerHTML) { element.innerHTML = options.innerHTML; }
      target.appendChild(element);
      _t.push(mount_to + " " + name);
    });
    riot.mount(_t.join(","),options);
  }

  uR.alertElement = function alertElement(name,options) {
    options = options || {};
    if (!options.hasOwnProperty("ur_modal")) { options.ur_modal = true; }
    uR.mountElement(name,options);
  }

  uR.newElement = function newElement(tagName,attrs,options) {
    var element = document.createElement(tagName);
    if (attrs.parent) {
      attrs.parent.appendChild(element);
      delete attrs.parent;
    }

    element.innerHTML = attrs.innerHTML || "";
    delete attrs.innerHTML;

    for (var attr in attrs) { element[attr] = attrs[attr]; }
    if (options) { riot.mount(element,options); }
    return element;
  }

  uR.loadTemplate = function loadTemplate(template_name,data) {
    template_name = template_name.match(/[^\/].+[^\/]/)[0].replace(/\//g,"-");
    riot.compile(
      uR.static("templates/"+template_name+".html"),
      function() { uR.router.routeElement(template_name)(template_name,data); }
    );
  }

  function pushState(path,data) {
    if (window.location.pathname == path) { return; }
    // #! TODO the empty string here is the page title. Need some sort of lookup table
    history.replaceState({path:path},"" || document.title,path);
  }

  uR.pushState = uR.debounce(pushState,100);

  uR.route = function route(href,data) {
    var new_url = new URL(href,href.match("://")?undefined:window.location.origin);
    var old_url = new URL(window.location.href);
    var pathname = (new_url.pathname || href).replace(window.location.origin,"");

    uR.forEach(uR._on_routes,function(f) {f(pathname,data)});
    var path_match = uR.router.resolve(pathname);
    var hash_match = new_url && uR.router.resolve(new_url.hash);
    if (path_match) {
      var data = { matches: path_match };
      document.body.dataset.ur_path = pathname;
      uR._routes[path_match.key](pathname,data);
    } else if (hash_match) {
      var data = {
        matches: hash_match,
        ur_modal: new_url.hash.match(uR.config.MODAL_PREFIX),
        cancel: function() {
          window.location.hash = "";
          this.unmount && this.unmount();
        }
      }
      uR._routes[hash_match.key](new_url.hash,data);
    }
    if (path_match || hash_match) {
      uR.pushState(href);
      uR.STALE_STATE = true;
      return;
    } else if (uR.router.default_route) { uR.router.default_route(pathname,{matches: []}); }
    // uR.config.do404();

    // #! TODO The following is used for django pages + back button
    // We're not in the single page app, reload if necessary
    if (uR.STALE_STATE) {
      window.location = href;
    }
    uR.STALE_STATE = true;
  }

  function onClick(e) {
    // Borrowed heavily from riot
    // this will stop links from changing the page so I can use href instead of onclick
    if (
      e.which != 1 // not left click
        || e.metaKey || e.ctrlKey || e.shiftKey // or meta keys
        || e.defaultPrevented // or default prevented
    ) return

    var el = e.target, loc = (window.history.location || window.location);
    if (el && el.nodeName) {
      var selector = el.nodeName;
      if (el.id) { "#"+el.id; }
      if (el.className) { selector += "." + el.className; }
      if (el.name) { selector += "[name="+el.name+"]" }
      window.airbrake && window.airbrake.log("clicked: " + selector);
    }
    while (el && el.nodeName != 'A') el = el.parentNode;

    if (
      !el || el.nodeName != 'A' // not A tag
        || el.hasAttribute('download') // has download attr
        || !el.hasAttribute('href') // has no href attr
        || el.target && el.target != '_self' // another window or frame
        || el.href.indexOf(loc.href.match(/^.+?\/\/+[^\/]+/)[0]) == -1 // cross origin
    ) return

    /*if (el.href != loc.href && (
      el.href.split('#')[0] == loc.href.split('#')[0] // internal jump
        || el.href.startsWith("#") // hash only
        || base[0] != '#' && getPathFromRoot(el.href).indexOf(base) !== 0 // outside of base
        || base[0] == '#' && el.href.split(base)[0] != loc.href.split(base)[0] // outside of #base
        || !go(getPathFromBase(el.href), el.title || document.title) // route not found
    )) return*/
    e.preventDefault();
    uR.route(el.href);
  }

  var RouterMixin = {
    init: function() {
      if (uR.router._current_tagname == this.__.tagName.toUpperCase()) {
        // this tag can be updated, so store it in uR.router
        uR.router._current_tag = this;
        this.on("unmount",function () {
          // all done, remove this if still assigned to the router
          if (uR.router._current_tagname == this.root.tagName) { uR.router._current_tagname = undefined }
          if (uR.router._current_tag == this) { uR.router._current_tag = undefined }
        });
      }
    }
  }
  window.riot && window.riot.mixin(RouterMixin);

  uR.config.do404 = function() { uR.mountElement("four-oh-four"); }
  uR.config.MODAL_PREFIX = /^#!/;
  uR._routes = uR._routes || {};
  uR._on_routes = [];
  uR.onRoute = function(f) { uR._on_routes.push(f) }
  uR.router = {
    start: function() {
      document.addEventListener('click', onClick);
      // window.popstate = function(event) { uR.route(window.location.href,event.state,false); };
    },
    add: function(routes) { uR.extend(uR._routes,routes); },
    routeElement: function(element_name) {
      return function(pathname,data) {
        var tagName = element_name.toUpperCase();
        if (uR.router._current_tag &&
            uR.router._current_tag.root.tagName == tagName &&
            typeof uR.router._current_tag.route == "function") {
          uR.router._current_tag.route(pathname,data);
        } else {
          uR.router._current_tagname = tagName;
          uR.mountElement(element_name,data);
        }
      }
    },
    resolve: function(path) {
      for (var key in uR._routes) {
        var regexp = new RegExp(key);
        var match = path.match(regexp)
        if (match) {
          match.key = key
          return match;
        }
      }
    },
  };
  uR.startRouter = uR.depracated(uR.router.start,'uR.startRouter','uR.router.start()');
  uR.addRoutes = uR.depracated(uR.router.add,'uR.addRoutes','uR.router.add()');
  if (!document.querySelector("#alert-div")) { // #! TODO this is hardcoded, but am unsure what else to do CCC
    var e = document.createElement("div");
    e.id = "alert-div";
    document.body.appendChild(e);
  }
})();
<commit_msg>hash match has priority and path_match erases the hash<commit_after>(function() {
  uR.mountElement = function mountElement(names,options) {
    options = options || {};
    if (options.ur_modal) {
      options.mount_to = options.mount_to || uR.config.mount_alerts_to;
    }
    var mount_to = options.mount_to || uR.config.mount_to
    var target = document.querySelector(mount_to);
    var children = target.childNodes;
    var i = target.childNodes.length;
    while (i--) { target.removeChild(children[i]); }

    if (typeof names == "string") { names = [names]; }
    var _t = [];
    uR.forEach(names,function(name) {
      name = name.replace(/\//g,''); // Some tags pass in tag name for path like /hello-world/
      var element = document.createElement(name);
      if (options.innerHTML) { element.innerHTML = options.innerHTML; }
      target.appendChild(element);
      _t.push(mount_to + " " + name);
    });
    riot.mount(_t.join(","),options);
    if (names.join(",").toUpperCase().indexOf(uR.router._current_tagname) == -1) {
      uR.router._current_tag = uR.router._current_tagname = undefined
    }
  }

  uR.alertElement = function alertElement(name,options) {
    options = options || {};
    if (!options.hasOwnProperty("ur_modal")) { options.ur_modal = true; }
    uR.mountElement(name,options);
  }

  uR.newElement = function newElement(tagName,attrs,options) {
    var element = document.createElement(tagName);
    if (attrs.parent) {
      attrs.parent.appendChild(element);
      delete attrs.parent;
    }

    element.innerHTML = attrs.innerHTML || "";
    delete attrs.innerHTML;

    for (var attr in attrs) { element[attr] = attrs[attr]; }
    if (options) { riot.mount(element,options); }
    return element;
  }

  uR.loadTemplate = function loadTemplate(template_name,data) {
    template_name = template_name.match(/[^\/].+[^\/]/)[0].replace(/\//g,"-");
    riot.compile(
      uR.static("templates/"+template_name+".html"),
      function() { uR.router.routeElement(template_name)(template_name,data); }
    );
  }

  function pushState(path,data) {
    if (window.location.pathname == path) { return; }
    // #! TODO the empty string here is the page title. Need some sort of lookup table
    history.replaceState({path:path},"" || document.title,path);
  }

  uR.pushState = uR.debounce(pushState,100);

  uR.route = function route(href,data) {
    var new_url = new URL(href,href.match("://")?undefined:window.location.origin);
    var old_url = new URL(window.location.href);
    var pathname = (new_url.pathname || href).replace(window.location.origin,"");

    uR.forEach(uR._on_routes,function(f) {f(pathname,data)});
    var path_match = uR.router.resolve(pathname);
    var hash_match = new_url && uR.router.resolve(new_url.hash);

    if (hash_match) {
      var data = {
        matches: hash_match,
        ur_modal: new_url.hash.match(uR.config.MODAL_PREFIX),
        cancel: function() {
          window.location.hash = "";
          this.unmount && this.unmount();
        }
      }
      uR._routes[hash_match.key](new_url.hash,data);
    } else if (path_match) {
      var data = { matches: path_match };
      document.body.dataset.ur_path = pathname;
      uR._routes[path_match.key](pathname,data);
      if (uR.STALE_STATE) { window.location.hash = ""; }
    }
    if (path_match || hash_match) {
      uR.pushState(href);
      uR.STALE_STATE = true;
      return;
    } else if (uR.router.default_route) { uR.router.default_route(pathname,{matches: []}); }
    // uR.config.do404();

    // #! TODO The following is used for django pages + back button
    // We're not in the single page app, reload if necessary
    if (uR.STALE_STATE) {
      window.location = href;
    }
    uR.STALE_STATE = true;
  }

  function onClick(e) {
    // Borrowed heavily from riot
    // this will stop links from changing the page so I can use href instead of onclick
    if (
      e.which != 1 // not left click
        || e.metaKey || e.ctrlKey || e.shiftKey // or meta keys
        || e.defaultPrevented // or default prevented
    ) return

    var el = e.target, loc = (window.history.location || window.location);
    if (el && el.nodeName) {
      var selector = el.nodeName;
      if (el.id) { "#"+el.id; }
      if (el.className) { selector += "." + el.className; }
      if (el.name) { selector += "[name="+el.name+"]" }
      window.airbrake && window.airbrake.log("clicked: " + selector);
    }
    while (el && el.nodeName != 'A') el = el.parentNode;

    if (
      !el || el.nodeName != 'A' // not A tag
        || el.hasAttribute('download') // has download attr
        || !el.hasAttribute('href') // has no href attr
        || el.target && el.target != '_self' // another window or frame
        || el.href.indexOf(loc.href.match(/^.+?\/\/+[^\/]+/)[0]) == -1 // cross origin
    ) return

    /*if (el.href != loc.href && (
      el.href.split('#')[0] == loc.href.split('#')[0] // internal jump
        || el.href.startsWith("#") // hash only
        || base[0] != '#' && getPathFromRoot(el.href).indexOf(base) !== 0 // outside of base
        || base[0] == '#' && el.href.split(base)[0] != loc.href.split(base)[0] // outside of #base
        || !go(getPathFromBase(el.href), el.title || document.title) // route not found
    )) return*/
    e.preventDefault();
    uR.route(el.href);
  }

  var RouterMixin = {
    init: function() {
      if (uR.router._current_tagname == this.__.tagName.toUpperCase()) {
        // this tag can be updated, so store it in uR.router
        uR.router._current_tag = this;
        this.on("unmount",function () {
          // all done, remove this if still assigned to the router
          if (uR.router._current_tagname == this.root.tagName) { uR.router._current_tagname = undefined }
          if (uR.router._current_tag == this) { uR.router._current_tag = undefined }
        });
      }
    }
  }
  window.riot && window.riot.mixin(RouterMixin);

  uR.config.do404 = function() { uR.mountElement("four-oh-four"); }
  uR.config.MODAL_PREFIX = /^#!/;
  uR._routes = uR._routes || {};
  uR._on_routes = [];
  uR.onRoute = function(f) { uR._on_routes.push(f) }
  uR.router = {
    start: function() {
      document.addEventListener('click', onClick);
      // window.popstate = function(event) { uR.route(window.location.href,event.state,false); };
    },
    add: function(routes) { uR.extend(uR._routes,routes); },
    routeElement: function(element_name) {
      return function(pathname,data) {
        var tagName = element_name.toUpperCase();
        if (uR.router._current_tag &&
            uR.router._current_tag.root.tagName == tagName &&
            typeof uR.router._current_tag.route == "function") {
          uR.router._current_tag.route(pathname,data);
        } else {
          uR.router._current_tagname = tagName;
          uR.mountElement(element_name,data);
        }
      }
    },
    resolve: function(path) {
      for (var key in uR._routes) {
        var regexp = new RegExp(key);
        var match = path.match(regexp)
        if (match) {
          match.key = key
          return match;
        }
      }
    },
  };
  uR.startRouter = uR.depracated(uR.router.start,'uR.startRouter','uR.router.start()');
  uR.addRoutes = uR.depracated(uR.router.add,'uR.addRoutes','uR.router.add()');
  if (!document.querySelector("#alert-div")) { // #! TODO this is hardcoded, but am unsure what else to do CCC
    var e = document.createElement("div");
    e.id = "alert-div";
    document.body.appendChild(e);
  }
})();
<|endoftext|>


<commit_before>Version = { id: '7913879' };
<commit_msg>Bump up version<commit_after>Version = { id: '53c875c' };
<|endoftext|>


<commit_before>/**
 * Created by Stein-Otto Svorstøl on 26.08.15.
 */
'use strict';

var bookController = require('./controllers/bookController'),
    crowdController = require('./controllers/crowdController'),
    userController = require('./controllers/userController');

var express = require('express');

function setup(app){
    var bodyParser = require('body-parser'); // Some setup for encoding of requests
    app.use(bodyParser.json());       // to support JSON-encoded bodies
    app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
        extended: true
    }));

    app.use(function(req, res, next) { // Headers to allow CORS and different requests
        res.header("Access-Control-Allow-Origin", "*");
        res.header('Access-Control-Allow-Methods', 'OPTIONS, GET, PUT');
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        res.header('X-API-VERSION', 2);
        next();
    });

    app.use('/api', express.static('public'));

    // Book API v2: /books
    app.route('/api/books')
        .post(bookController.create)
        .put(bookController.update) // @TOOD
        .get(bookController.getBooks);
    app.route('/api/books/:bookId')
        .get(bookController.getWithID)
        .delete(bookController.remove);
    app.route('/api/books/:bookId/renter/:username')
        .put(bookController.addRenter)
        .delete(bookController.removeRenter);

    // User API v2: /users
    app.route('/api/users/:userId')
        .get(userController.getUser)
        .delete(userController.remove);
    app.post('/api/users', userController.create);

    app.route('/api/crowds')
        .post( crowdController.create)
        .get(crowdController.getCrowds);

    app.route('/api/crowds/:crowdId')
        .get(crowdController.getWithID)
        .put(crowdController.update)
        .delete(crowdController.remove);

    app.route('/api/crowds/:crowdId/members/:username')
        .put(crowdController.addMember)
        .delete(crowdController.removeMember);
}

exports.setup = setup;<commit_msg>Log incoming requests<commit_after>/**
 * Created by Stein-Otto Svorstøl on 26.08.15.
 */
'use strict';

var bookController = require('./controllers/bookController'),
    crowdController = require('./controllers/crowdController'),
    userController = require('./controllers/userController');

var express = require('express'),
    bodyParser = require('body-parser');

function setup(app){
    // Some setup for encoding of requests
    app.use(bodyParser.json());       // to support JSON-encoded bodies
    app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
        extended: true
    }));

    app.use(function(req, res, next) { // Headers to allow CORS and different requests
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, DELETE, PUT');
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        res.header('X-API-VERSION', 2);
        console.log(req.method+ '-request to: ' + req.url);
        next();
    });

    app.use('/api', express.static('public'));

    // Book API v2: /books
    app.route('/api/books')
        .post(bookController.create)
        .put(bookController.update) // @TOOD
        .get(bookController.getBooks);
    app.route('/api/books/:bookId')
        .get(bookController.getWithID)
        .delete(bookController.remove);
    app.route('/api/books/:bookId/renter/:username')
        .put(bookController.addRenter)
        .delete(bookController.removeRenter);

    // User API v2: /users
    app.route('/api/users/:userId')
        .get(userController.getUser)
        .delete(userController.remove);
    app.post('/api/users', userController.create);

    app.route('/api/crowds')
        .post( crowdController.create)
        .get(crowdController.getCrowds);

    app.route('/api/crowds/:crowdId')
        .get(crowdController.getWithID)
        .put(crowdController.update)
        .delete(crowdController.remove);

    app.route('/api/crowds/:crowdId/members/:username')
        .put(crowdController.addMember)
        .delete(crowdController.removeMember);
}

exports.setup = setup;<|endoftext|>


<commit_before>var Profile = require("./profile.js");
var renderer = require("./renderer.js");

// Handle HTTP route GET / and POST / i.e. Home
function home(request, response) {
    // if url == "/" && GET
    if (request.url === "/") {
       // show search
       response.writeHead(200, {'Content-Type': 'text/plain'});
       renderer.view("header", {}, response);
       renderer.view("search", {}, response);
       renderer.view("footer", {}, response);
       response.end();
     }

}

// Handle HTTP route GET /:username i.e. /chalkers
function user(request, response) {
    // if url == "/...."
    var username = request.url.replace("/", "");
    if (username.length > 0) {
       response.writeHead(200, {'Content-Type': 'text/plain'});
       renderer.view("header", {}, response);

       // Get json from Treehouse
       var studentProfile = new Profile(username);
       // on "end"
       studentProfile.on("end", function(profileJSON){
           // show profile

           // Store the values which we need
           var values = {
               avatarUrl: profileJSON.gravatar_url,
               username: profileJSON.profile_name,
               badges: profileJSON.badges.length,
               javascriptPoints: profileJSON.points.JavaScript
           }
           // Simple repsonse
           renderer.view("profile", values, response);
           renderer.view("footer", {}, response);
           response.end();
       });
       // on "error"
       studentProfile.on("error", function(error){
           // show error
           renderer.view("error", {errorMessage: error.message}, response);
           renderer.view("search", {}, response);
           renderer.view("footer", {}, response);
           response.end();
       });

    }
}

module.exports.home = home;
module.exports.user = user;<commit_msg>User profiles are finally displayed in HTML format<commit_after>var Profile = require("./profile.js");
var renderer = require("./renderer.js");
var commonHeaders = {'Content-Type': 'text/html'};

// Handle HTTP route GET / and POST / i.e. Home
function home(request, response) {
    // if url == "/" && GET
    if (request.url === "/") {
       // show search
       response.writeHead(200, commonHeaders);
       renderer.view("header", {}, response);
       renderer.view("search", {}, response);
       renderer.view("footer", {}, response);
       response.end();
     }

}

// Handle HTTP route GET /:username i.e. /chalkers
function user(request, response) {
    // if url == "/...."
    var username = request.url.replace("/", "");
    if (username.length > 0) {
       response.writeHead(200, commonHeaders);
       renderer.view("header", {}, response);

       // Get json from Treehouse
       var studentProfile = new Profile(username);
       // on "end"
       studentProfile.on("end", function(profileJSON){
           // show profile

           // Store the values which we need
           var values = {
               avatarUrl: profileJSON.gravatar_url,
               username: profileJSON.profile_name,
               badges: profileJSON.badges.length,
               javascriptPoints: profileJSON.points.JavaScript
           }
           // Simple repsonse
           renderer.view("profile", values, response);
           renderer.view("footer", {}, response);
           response.end();
       });
       // on "error"
       studentProfile.on("error", function(error){
           // show error
           renderer.view("error", {errorMessage: error.message}, response);
           renderer.view("search", {}, response);
           renderer.view("footer", {}, response);
           response.end();
       });

    }
}

module.exports.home = home;
module.exports.user = user;<|endoftext|>


<commit_before>/**
 * yayax (c) Mikhail Bogdanov 2015
 * based on https://github.com/radiosilence/xr
 * URL: https://github.com/gm0t/yajax
 * License: MIT
 */

var Events = {
  READY_STATE_CHANGE: "readystatechange",
  LOAD_START: "loadstart",
  PROGRESS: "progress",
  ABORT: "abort",
  ERROR: "error",
  LOAD: "load",
  TIMEOUT: "timeout",
  LOAD_END: "loadend"
};

var defaults = {
  method: "GET",
  data: undefined,
  headers: {
    "Accept": "application/json",
    "Content-Type": "application/json"
  },
  dataEncoder: JSON.stringify,
  responseDecoder: JSON.parse,
  xmlHttpRequest: function () {
    return new XMLHttpRequest();
  },
  promise: function (fn) {
    return new Promise(fn);
  }
};

var interceptors = {
  send: [],
  complete: [],
  error: []
}

function onError(xhr, opts, reject) {
  // onComplete interceptors
  (interceptors.error || []).forEach(function onErrorInterceptor(fn) {
    fn(xhr);
  });

  reject({
    status: xhr.status,
    response: xhr.response,
    xhr: xhr
  });
}

function stringify(params) {
  params = params || {};

  var k, result = "", sep = "";
  for (k in params) {
    if (params.hasOwnProperty(k)) {
      result += sep + encodeURIComponent(k) + "=" + encodeURIComponent(params[k]);
      sep = "&";
    }
  }

  return result;
}

var config = {};

function configure(opts) {
  config = Object.assign({}, config, opts);
}

function createPromise(args, fn) {
  return ((args && args.promise)
      ? args.promise
      : (config.promise || defaults.promise)
  )(fn);
}

function yajax(args) {
  var xhr;
  var promise = createPromise(args, function(resolve, reject) {
    var opts = Object.assign({}, defaults, config, args);

    xhr = opts.xmlHttpRequest();
    var failed = onError.bind(null, xhr, opts, reject)

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

    var url = opts.url;
    if (opts.params) {
      url = url.split("?")[0] + "?" + stringify(opts.params);
    }
    xhr.open(opts.method, url, true);

    xhr.addEventListener(Events.LOAD, function () {
      if (xhr.status < 200 || xhr.status >= 300) {
        return failed();
      }

      // onComplete interceptors
      (interceptors.complete || []).forEach(function onCompleteInterceptor(fn) {
        fn(xhr, opts);
      });

      var data;
      if (!xhr.responseType || xhr.responseType === "text") {
        data = xhr.responseText;
      } else {
        data = xhr.response;
      }

      if (data && !opts.raw) {
        data = opts.responseDecoder(data);
      }
      resolve(data, xhr);
    });

    xhr.addEventListener(Events.ABORT, failed);
    xhr.addEventListener(Events.ERROR, failed);
    xhr.addEventListener(Events.TIMEOUT, failed);

    var k, headers = opts.headers;
    for (k in headers) {
      if (headers.hasOwnProperty(k)) {
        xhr.setRequestHeader(k, headers[k]);
      }
    }

    var events = opts.events;
    for (k in events) {
      if (events.hasOwnProperty(k)) {
        xhr.addEventListener(k, events[k].bind(null, xhr), false);
      }
    }

    // onSend interceptors
    (interceptors.send || []).forEach(function onSendInterceptor(fn) {
      fn(xhr, opts);
    });

    var data = opts.data;
    if (typeof opts.data === "object" && !opts.raw) {
      data = opts.dataEncoder(data, xhr);
    }

    if (xhr.readyState !== 1) {
      //one of the intercepters has called abort
      return failed();
    }

    if (opts.responseType) {
        xhr.responseType = opts.responseType;
    }

    xhr.send(data);
  });

  promise.abort = function () {
    return xhr.abort();
  }

  return promise;
}

yajax.configure = configure;
yajax.Events = Events;
yajax.defaults = defaults;

yajax.get = function (url, params, args) {
  return yajax(Object.assign({url: url, method: "GET", params: params}, args));
};
yajax.put = function (url, data, args) {
  return yajax(Object.assign({url: url, method: "PUT", data: data}, args));
};
yajax.post = function (url, data, args) {
  return yajax(Object.assign({url: url, method: "POST", data: data}, args));
};
yajax.patch = function (url, data, args) {
  return yajax(Object.assign({url: url, method: "PATCH", data: data}, args));
};
yajax.del = function (url, args) {
  return yajax(Object.assign({url: url, method: "DELETE"}, args));
};
yajax.options = function (url, args) {
  return yajax(Object.assign({url: url, method: "OPTIONS"}, args));
};

yajax.addInterceptor = function addInterceptor(type, fn, asFirst) {
  var list = interceptors[type];
  if (!list) {
    throw new Error("Unknown interceptor type: " + type + " available: send, complete");
  }

  if (asFirst) {
    list.unshift(fn);
  }  else {
    list.push(fn);
  }
};

yajax.removeInterceptor = function removeInterceptor(type, fn) {
  var list = interceptors[type];
  if (!list) {
    throw new Error("Unknown interceptor type: " + type + " available: send, complete");
  }

  var idx = list.indexOf(fn);
  if (idx !== -1) {
    list.splice(idx, 1);
    return true;
  }

  return false;
}

module.exports = yajax;
<commit_msg>Added support for XMLHttpRequest.timeout<commit_after>/**
 * yayax (c) Mikhail Bogdanov 2015
 * based on https://github.com/radiosilence/xr
 * URL: https://github.com/gm0t/yajax
 * License: MIT
 */

var Events = {
  READY_STATE_CHANGE: "readystatechange",
  LOAD_START: "loadstart",
  PROGRESS: "progress",
  ABORT: "abort",
  ERROR: "error",
  LOAD: "load",
  TIMEOUT: "timeout",
  LOAD_END: "loadend"
};

var defaults = {
  method: "GET",
  data: undefined,
  headers: {
    "Accept": "application/json",
    "Content-Type": "application/json"
  },
  dataEncoder: JSON.stringify,
  responseDecoder: JSON.parse,
  xmlHttpRequest: function () {
    return new XMLHttpRequest();
  },
  promise: function (fn) {
    return new Promise(fn);
  }
};

var interceptors = {
  send: [],
  complete: [],
  error: []
}

function onError(xhr, opts, reject) {
  // onComplete interceptors
  (interceptors.error || []).forEach(function onErrorInterceptor(fn) {
    fn(xhr);
  });

  reject({
    status: xhr.status,
    response: xhr.response,
    xhr: xhr
  });
}

function stringify(params) {
  params = params || {};

  var k, result = "", sep = "";
  for (k in params) {
    if (params.hasOwnProperty(k)) {
      result += sep + encodeURIComponent(k) + "=" + encodeURIComponent(params[k]);
      sep = "&";
    }
  }

  return result;
}

var config = {};

function configure(opts) {
  config = Object.assign({}, config, opts);
}

function createPromise(args, fn) {
  return ((args && args.promise)
      ? args.promise
      : (config.promise || defaults.promise)
  )(fn);
}

function yajax(args) {
  var xhr;
  var promise = createPromise(args, function(resolve, reject) {
    var opts = Object.assign({}, defaults, config, args);

    xhr = opts.xmlHttpRequest();
    var failed = onError.bind(null, xhr, opts, reject)

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

    var url = opts.url;
    if (opts.params) {
      url = url.split("?")[0] + "?" + stringify(opts.params);
    }
    xhr.open(opts.method, url, true);

    xhr.addEventListener(Events.LOAD, function () {
      if (xhr.status < 200 || xhr.status >= 300) {
        return failed();
      }

      // onComplete interceptors
      (interceptors.complete || []).forEach(function onCompleteInterceptor(fn) {
        fn(xhr, opts);
      });

      var data;
      if (!xhr.responseType || xhr.responseType === "text") {
        data = xhr.responseText;
      } else {
        data = xhr.response;
      }

      if (data && !opts.raw) {
        data = opts.responseDecoder(data);
      }
      resolve(data, xhr);
    });

    xhr.addEventListener(Events.ABORT, failed);
    xhr.addEventListener(Events.ERROR, failed);
    xhr.addEventListener(Events.TIMEOUT, failed);

    var k, headers = opts.headers;
    for (k in headers) {
      if (headers.hasOwnProperty(k)) {
        xhr.setRequestHeader(k, headers[k]);
      }
    }

    var events = opts.events;
    for (k in events) {
      if (events.hasOwnProperty(k)) {
        xhr.addEventListener(k, events[k].bind(null, xhr), false);
      }
    }

    if (opts.timeout !== void 0) {
        xhr.timeout = opts.timeout;
    }

    // onSend interceptors
    (interceptors.send || []).forEach(function onSendInterceptor(fn) {
      fn(xhr, opts);
    });

    var data = opts.data;
    if (typeof opts.data === "object" && !opts.raw) {
      data = opts.dataEncoder(data, xhr);
    }

    if (xhr.readyState !== 1) {
      //one of the intercepters has called abort
      return failed();
    }

    if (opts.responseType) {
        xhr.responseType = opts.responseType;
    }

    xhr.send(data);
  });

  promise.abort = function () {
    return xhr.abort();
  }

  return promise;
}

yajax.configure = configure;
yajax.Events = Events;
yajax.defaults = defaults;

yajax.get = function (url, params, args) {
  return yajax(Object.assign({url: url, method: "GET", params: params}, args));
};
yajax.put = function (url, data, args) {
  return yajax(Object.assign({url: url, method: "PUT", data: data}, args));
};
yajax.post = function (url, data, args) {
  return yajax(Object.assign({url: url, method: "POST", data: data}, args));
};
yajax.patch = function (url, data, args) {
  return yajax(Object.assign({url: url, method: "PATCH", data: data}, args));
};
yajax.del = function (url, args) {
  return yajax(Object.assign({url: url, method: "DELETE"}, args));
};
yajax.options = function (url, args) {
  return yajax(Object.assign({url: url, method: "OPTIONS"}, args));
};

yajax.addInterceptor = function addInterceptor(type, fn, asFirst) {
  var list = interceptors[type];
  if (!list) {
    throw new Error("Unknown interceptor type: " + type + " available: send, complete");
  }

  if (asFirst) {
    list.unshift(fn);
  }  else {
    list.push(fn);
  }
};

yajax.removeInterceptor = function removeInterceptor(type, fn) {
  var list = interceptors[type];
  if (!list) {
    throw new Error("Unknown interceptor type: " + type + " available: send, complete");
  }

  var idx = list.indexOf(fn);
  if (idx !== -1) {
    list.splice(idx, 1);
    return true;
  }

  return false;
}

module.exports = yajax;
<|endoftext|>


<commit_before>/*The MIT License (MIT)

Copyright (c) 2014 Shine Xavier

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/

Array.prototype.getIterator = function () {
    "use strict";
    var that = {},
    getFunctionContext = function (fnIndex, input) {
        var fnContext = that.fnContexts[fnIndex];
        if (fnContext === undefined) {
            fnContext = {
				"index" : 0,
                "current" : input,
                "outList" : []
            };
            that.fnContexts[fnIndex] = fnContext;
        } else {
            fnContext.current = input;
			fnContext.index += 1;
        }
        return fnContext;
    },
    isYieldEmpty = function () {
        return ((that.yieldIndex + 1) === that.inList.length);
    },
	current = null,
    moveNext = function () {
        var args = arguments,
        yieldedResult = null,
        core = function () {
            var i,
            result = null,
            fn = null,
            fnCtxt = null;
            that.yieldIndex += 1;
            result = that.inList[that.yieldIndex];
            if (args.length > 0) {
                for (i = 0; i < args.length; i += 1) {
                    fn = args[i];
                    fnCtxt = getFunctionContext(i, result);
                    result = fn.call(fnCtxt);
                    if (result === null) {
                        break;
                    } else {
                        fnCtxt.outList.push(result);
                    }
                }
				if (result !== null) {
					that.outList.push(result);
					that.current = result;
				}
				return result;
            } else {
                that.current = that.inList[that.yieldIndex];
				that.outList.push(that.current);
				return that.current;
            }
        };
        while ((yieldedResult === null) && (!isYieldEmpty())) {
            yieldedResult = core();
        }
        return (yieldedResult !== null) ? true : false;
    };
    that.fnContexts = [];
    that.inList = this;
    that.length = that.inList.length;
    that.outList = [];
    that.yieldIndex = -1;
    that.current = null;
    that.moveNext = moveNext;
    return that;
};

//Test Harness
function unique() {
    "use strict";
    if (this.outList.indexOf(this.current) < 0) {
        return this.current;
    } else {
        return null;
    }
}

function square() {
    "use strict";
    return (this.current * this.current);
}

function filter(condition) {
	"use strict";
	return function () {
		return condition(this.current) ? this.current : null;
	};
}

function even(val) {
	"use strict";
	return (val % 2 === 0);
}

function skip(count) {
	"use strict";
	return function () {
		//console.log(this.index.toString() + " : " + this.current.toString());
		return ((this.index % (count+1)) === 0) ? this.current : null;
	};
}

var x = [1,2,3,200,1,2,3,200],
	continuation = x.getIterator();

while (continuation.moveNext(filter(even))) {
    //console.log(continuation.current);
	continuation.current;
}
console.log(continuation.outList);
<commit_msg>Release v 1.0<commit_after>/*The MIT License (MIT)

Copyright (c) 2014 Shine Xavier

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/

Array.prototype.getIterator = function () {
    "use strict";
    var inList = this,
		it = {},
		fnContexts = [],
		yieldIndex = -1,
		getFunctionContext = function (fnIndex, input) {
			var fnContext = fnContexts[fnIndex];
			if (fnContext === undefined) {
				fnContext = {
					"index" : 0,
					"current" : input,
					"outList" : []
				};
				fnContexts[fnIndex] = fnContext;
			} else {
				fnContext.current = input;
				fnContext.index += 1;
			}
			return fnContext;
		},
		isYieldEmpty = function () {
			return ((yieldIndex + 1) === inList.length);
		},
		moveNext = function () {
			var args = arguments,
				yieldedResult = null,
				core = function () {
					var i,
						result = null,
						fn = null,
						fnCtxt = null,
						returnVal = null;
					yieldIndex += 1;
					result = inList[yieldIndex];
					if (args.length > 0) {
						for (i = 0; i < args.length; i += 1) {
							fn = args[i];
							fnCtxt = getFunctionContext(i, result);
							result = fn.call(null, fnCtxt);
							if (result === null) {
								break;
							} else {
								fnCtxt.outList.push(result);
							}
						}
						if (result !== null) {
							it.outList.push(result);
							it.current = result;
						}
						returnVal = result;
					} else {
						it.current = inList[yieldIndex];
						it.outList.push(it.current);
						returnVal = it.current;
					}
					return returnVal;
				};
			while ((yieldedResult === null) && (!isYieldEmpty())) {
				//Recursive call to find the next non-null value
				yieldedResult = core();
			}
			return (yieldedResult !== null) ? true : false;
		};
    it.length = inList.length;
    it.outList = [];
    it.current = null;
    it.moveNext = moveNext;
    return it;
};
<|endoftext|>


<commit_before>/**
 * Created by 3er on 1/5/15.
 */

// Since Node 0.8, .existsSync() moved from path to fs:
var path = require('path');
var fs = require('fs');
var walk = require('walk');
var config = require('./config/oped');
var PRIVATE = require('./config/private');
var async = require('async');
var _existsSync = fs.existsSync || path.existsSync;

var _ = require('underscore');
var moment = require('moment');
var formidable = require('formidable');

var chokidar = require('chokidar');

// qiniu
var qiniu = require('qiniu')
qiniu.conf.ACCESS_KEY = PRIVATE.qiniu.access_key
qiniu.conf.SECRET_KEY = PRIVATE.qiniu.secret_key

var compress = require('./compress')

var generateURL = function (ver, key) {
    var deadline = Math.floor(Date.now() / 1000) + ver.expiration;
    var link = encodeURI('http://' + ver.domain + '/' + key + '?e=' + deadline);
    var token = qiniu.conf.ACCESS_KEY + ':' +
        qiniu.util.base64ToUrlSafe(qiniu.util.hmacSha1(link, qiniu.conf.SECRET_KEY));
    return link +
        '&token=' + token;
}

var generateInfoURL = function (ver, key) {
    var deadline = Math.floor(Date.now() / 1000) + ver.expiration;
    var link = encodeURI('http://' + ver.domain + '/' + key + '?avinfo&e=' + deadline);
    var token = qiniu.conf.ACCESS_KEY + ':' +
        qiniu.util.base64ToUrlSafe(qiniu.util.hmacSha1(link, qiniu.conf.SECRET_KEY));
    return link +
        '&token=' + token;
}

var generateCompressScripts = function (path, oped) {
    var cmd = compress.generate(path, oped);
    // console.log(cmd);
    return cmd;
}
var deleteAsync = function (key, cb) {
    var rmQiniu = function (reso, key, next) {
        var client = new qiniu.rs.Client();
        client.remove(PRIVATE.qiniu[reso].bucket, key, function (err) {
            if (err) {
                next(err)
            }
            else {
                //console.log('a')
                next()
            }
        });
    };

    var rmLocal = function (reso, key, next) {
        var filePath = config.dir.rsync + reso + '/' + key;
        fs.unlink(filePath, function (err) {
            if (err) {
                next(err);
            }
            else {
                // console.log('b')
                next();
            }
        });
    };
    async.parallel([
            function (next) {
                rmQiniu('originNew', key, next)
            }, function (next) {
                rmQiniu('highNew', key, next)
            }, function (next) {
                rmQiniu('mediumNew', key, next)
            }, function (next) {
                rmQiniu('lowNew', key, next)
            }, function (next) {
                rmQiniu('mobileNew',key,next)
            },
            function (next) {
                rmLocal('originNew', key, next)
            }, function (next) {
                rmLocal('highNew', key, next)
            }, function (next) {
                rmLocal('mediumNew', key, next)
            }, function (next) {
                rmLocal('lowNew', key, next)
            },function(next){
                rmLocal('mobileNew',key,next)
            }
        ], cb
    );

}

var deleteList = [];

module.exports = function (app) {
    var testAdd = config.dir.rsync + 'lowNew/';

    var watcher = chokidar.watch(testAdd, {ignored: /\.DS_Store/, persistent: true});

    //watcher.add(['/1.txt', '2.txt', '3.txt']);
    watcher.on('add', function (path) {
        var testArr = _.map(deleteList, function (item) {
            return testAdd + item;
        });
        var judger = _.find(testArr, function (asis) {
            return asis === path;
        });

        if (judger !== undefined) {
            var delKey = path.replace(/^.*[\/]/, '');
            deleteAsync(delKey, function (err, result) {
                if (err) {
                    console.log(err);
                }
                //reserved console log which indicates the delete process
                console.log('delete success: ' + path);
                var index = deleteList.indexOf(delKey);

                if (index > -1) {
                    deleteList.splice(index, 1);
                }
            });
        }
    });

    // http api
    app.get('/video/opeds', function (req, res) {
        res.status(200).json(config.opeds);
    });

    app.post('/video/upload', function (req, res) {
        var dir = config.dir;
        // headers
        res.setHeader('Pragma', 'no-cache');
        res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate');
        res.setHeader('Content-Disposition', 'inline; filename="files.json"');

        // init
        var ret = {files: []};
        var form = new formidable.IncomingForm();
        form.encoding = 'utf-8';
        // 把mov转为mp4
        form.keepExtensions = false;

        var command = new compress.oped();

        // make upload directory
        form.uploadDir = dir.upload + moment().format('YYYYMMDDhhmmss/');

        // TODO: Exception判断
        fs.mkdirSync(form.uploadDir);

        // handle uplaod
        form.on('fileBegin', function (name, file) {
            file.name = file.name.replace(/-/g, "_").replace(/\.[^/.]+$/, "") + '.mp4'
            //console.log(file.name)
            file.path = form.uploadDir + file.name;

            ret.files.push({name: file.name, path: file.path});
            if (_existsSync(file.path) || _existsSync(config.dir.rsync + 'origin/' + file.name)) {
                ret.files[0].error = '文件已存在，不能覆盖';
                //console.log(ret.files[0].error);
            }
        }).on('field', function (name, value) {
            // 生成片头片尾命令
            command[name] = value;
        }).on('file', function (name, file) {
//                console.log(file.path);
            ret.files[0].size = file.size;
        }).on('aborted', function () {
            ret.files.forEach(function (file) {
                fs.unlinkSync(file.path);
            });
            // TODO: Exception判断
            fs.rmdirSync(path.dirname(ret.files[0].path));
            //console.log('删除文件夹')
        }).on('error', function (e) {
            ret.files[0].error = e;
            fs.rmdirSync(path.dirname(ret.files[0].path));
            // console.log(e);
        }).on('progress', function (bytesReceived) {
        }).on('end', function () {
            var error = ret.files[0].error;
            res.status(error ? 500 : 201).json(ret);
            if (!error) {
                //console.log(ret.files[0].path)
                // console.log(command);
                if (_existsSync(form.uploadDir)) {
                    generateCompressScripts(ret.files[0].path, command)
                }
            }
        }).parse(req);
    });

    app.get('/qiniu/link/origin/:key', function (req, res) {
//        console.log(req.param('ver'));
//        console.log(req.param('key'));
        var l = generateURL(PRIVATE.qiniu['origin'], req.param('key'), qiniu);
        res.redirect(l);
    });

    app.get('/qiniu/info/origin/:key', function (req, res) {
//        console.log(req.param('ver'));
//        console.log(req.param('key'));
        var l = generateInfoURL(PRIVATE.qiniu['origin'], req.param('key'), qiniu);
        res.redirect(l);
    });

    app.post('/qiniu/list', function (req, res) {
        var marker = null;
        qiniu.rsf.listPrefix(PRIVATE.qiniu.origin.bucket, '', marker, 999999, function (err, ret) {
            if (err) {
                res.status(500).send(err);
                console.log(err);
            } else {
                // process ret.marker & ret.items
//            console.log(ret.marker);
//            console.log(ret.items);

                var retr = _.chain(ret.items)
                    .sortBy(function (item) {
                        return -item.putTime
                    })
//                    .each(function (item) {
//                        item.link = generateURL(item, qiniu, PRIVATE.origin)
//                    })
                    .value();
                res.status(200).send({
                    current: 1,
                    rowCount: -1,
                    rows: retr,
                    total: retr.length
                });
            }
        });
    });
    app.delete('/qiniu/list/:key', function (req, res) {
        var key = req.params.key;
        deleteAsync(key, function (err) {

            if (err) console.log(err);
            res.status(200);
            res.end('delete success')

        });

    });

    app.post('/video/compressing/:key', function (req, res) {
        deleteList.push(req.params.key);
        _.uniq(deleteList);
        res.status(201);
        res.end('cancel success');
    });

    app.post('/video/compressing', function (req, res) {
        // mock
        var arr = [];
        var filters = [
            '.DS_Store', 'command'
        ]

        var options = {
            listeners: {
                names: function (root, nodeNamesArray) {
                    _.chain(nodeNamesArray)
                        .flatten()
                        .difference(filters)
                        .reject(function (item) {
                            return (item.length == 14) && (item.indexOf('201') == 0);
                        })
                        .each(function (item) {
                            arr.push({key: item, progress: "compress"})
                        });
                }, directories: function (root, dirStatsArray, next) {
                    next();
                }, files: function (root, fileStats, next) {
                    next();
                }, errors: function (root, nodeStatsArray, next) {
                    next();
                }
            }
        };

        walker = walk.walkSync(config.dir.upload, options);

//        console.log("all done");

        var retr = arr;
        var tempKeys = _.object(deleteList, ['']);
        var temp = _.filter(retr, function (item) {
            return !(item.key in tempKeys);
        });
//            _.chain(arr)
//            .sortBy(function (item) {
//                return item.progress;
//            })
//            .value();

        res.status(200).send({
            current: 1,
            rowCount: -1,
            rows: temp,
            total: 2
        });
    });
}<commit_msg>change some route config<commit_after>/**
 * Created by 3er on 1/5/15.
 */

// Since Node 0.8, .existsSync() moved from path to fs:
var path = require('path');
var fs = require('fs');
var walk = require('walk');
var config = require('./config/oped');
var PRIVATE = require('./config/private');
var async = require('async');
var _existsSync = fs.existsSync || path.existsSync;

var _ = require('underscore');
var moment = require('moment');
var formidable = require('formidable');

var chokidar = require('chokidar');

// qiniu
var qiniu = require('qiniu')
qiniu.conf.ACCESS_KEY = PRIVATE.qiniu.access_key
qiniu.conf.SECRET_KEY = PRIVATE.qiniu.secret_key

var compress = require('./compress')

var generateURL = function (ver, key) {
    var deadline = Math.floor(Date.now() / 1000) + ver.expiration;
    var link = encodeURI('http://' + ver.domain + '/' + key + '?e=' + deadline);
    var token = qiniu.conf.ACCESS_KEY + ':' +
        qiniu.util.base64ToUrlSafe(qiniu.util.hmacSha1(link, qiniu.conf.SECRET_KEY));
    return link +
        '&token=' + token;
}

var generateInfoURL = function (ver, key) {
    var deadline = Math.floor(Date.now() / 1000) + ver.expiration;
    var link = encodeURI('http://' + ver.domain + '/' + key + '?avinfo&e=' + deadline);
    var token = qiniu.conf.ACCESS_KEY + ':' +
        qiniu.util.base64ToUrlSafe(qiniu.util.hmacSha1(link, qiniu.conf.SECRET_KEY));
    return link +
        '&token=' + token;
}

var generateCompressScripts = function (path, oped) {
    var cmd = compress.generate(path, oped);
    // console.log(cmd);
    return cmd;
}
var deleteAsync = function (key, cb) {
    var rmQiniu = function (reso, key, next) {
        var client = new qiniu.rs.Client();
        client.remove(PRIVATE.qiniu[reso].bucket, key, function (err) {
            if (err) {
                next(err)
            }
            else {
                //console.log('a')
                next()
            }
        });
    };

    var rmLocal = function (reso, key, next) {
        var filePath = config.dir.rsync + reso + '/' + key;
        fs.unlink(filePath, function (err) {
            if (err) {
                next(err);
            }
            else {
                // console.log('b')
                next();
            }
        });
    };
    async.parallel([
            function (next) {
                rmQiniu('originNew', key, next)
            }, function (next) {
                rmQiniu('highNew', key, next)
            }, function (next) {
                rmQiniu('mediumNew', key, next)
            }, function (next) {
                rmQiniu('lowNew', key, next)
            }, function (next) {
                rmQiniu('mobileNew',key,next)
            },
            function (next) {
                rmLocal('originNew', key, next)
            }, function (next) {
                rmLocal('highNew', key, next)
            }, function (next) {
                rmLocal('mediumNew', key, next)
            }, function (next) {
                rmLocal('lowNew', key, next)
            },function(next){
                rmLocal('mobileNew',key,next)
            }
        ], cb
    );

}

var deleteList = [];

module.exports = function (app) {
    var testAdd = config.dir.rsync + 'mobileNew/';

    var watcher = chokidar.watch(testAdd, {ignored: /\.DS_Store/, persistent: true});

    //watcher.add(['/1.txt', '2.txt', '3.txt']);
    watcher.on('add', function (path) {
        var testArr = _.map(deleteList, function (item) {
            return testAdd + item;
        });
        var judger = _.find(testArr, function (asis) {
            return asis === path;
        });

        if (judger !== undefined) {
            var delKey = path.replace(/^.*[\/]/, '');
            deleteAsync(delKey, function (err, result) {
                if (err) {
                    console.log(err);
                }
                //reserved console log which indicates the delete process
                console.log('delete success: ' + path);
                var index = deleteList.indexOf(delKey);

                if (index > -1) {
                    deleteList.splice(index, 1);
                }
            });
        }
    });

    // http api
    app.get('/video/opeds', function (req, res) {
        res.status(200).json(config.opeds);
    });

    app.post('/video/upload', function (req, res) {
        var dir = config.dir;
        // headers
        res.setHeader('Pragma', 'no-cache');
        res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate');
        res.setHeader('Content-Disposition', 'inline; filename="files.json"');

        // init
        var ret = {files: []};
        var form = new formidable.IncomingForm();
        form.encoding = 'utf-8';
        // 把mov转为mp4
        form.keepExtensions = false;

        var command = new compress.oped();

        // make upload directory
        form.uploadDir = dir.upload + moment().format('YYYYMMDDhhmmss/');

        // TODO: Exception判断
        fs.mkdirSync(form.uploadDir);

        // handle uplaod
        form.on('fileBegin', function (name, file) {
            file.name = file.name.replace(/-/g, "_").replace(/\.[^/.]+$/, "") + '.mp4'
            //console.log(file.name)
            file.path = form.uploadDir + file.name;

            ret.files.push({name: file.name, path: file.path});
            if (_existsSync(file.path) || _existsSync(config.dir.rsync + 'origin/' + file.name)) {
                ret.files[0].error = '文件已存在，不能覆盖';
                //console.log(ret.files[0].error);
            }
        }).on('field', function (name, value) {
            // 生成片头片尾命令
            command[name] = value;
        }).on('file', function (name, file) {
//                console.log(file.path);
            ret.files[0].size = file.size;
        }).on('aborted', function () {
            ret.files.forEach(function (file) {
                fs.unlinkSync(file.path);
            });
            // TODO: Exception判断
            fs.rmdirSync(path.dirname(ret.files[0].path));
            //console.log('删除文件夹')
        }).on('error', function (e) {
            ret.files[0].error = e;
            fs.rmdirSync(path.dirname(ret.files[0].path));
            // console.log(e);
        }).on('progress', function (bytesReceived) {
        }).on('end', function () {
            var error = ret.files[0].error;
            res.status(error ? 500 : 201).json(ret);
            if (!error) {
                //console.log(ret.files[0].path)
                // console.log(command);
                if (_existsSync(form.uploadDir)) {
                    generateCompressScripts(ret.files[0].path, command)
                }
            }
        }).parse(req);
    });

    app.get('/qiniu/link/origin/:key', function (req, res) {
//        console.log(req.param('ver'));
//        console.log(req.param('key'));
        var l = generateURL(PRIVATE.qiniu['origin'], req.param('key'), qiniu);
        res.redirect(l);
    });

    app.get('/qiniu/info/origin/:key', function (req, res) {
//        console.log(req.param('ver'));
//        console.log(req.param('key'));
        var l = generateInfoURL(PRIVATE.qiniu['origin'], req.param('key'), qiniu);
        res.redirect(l);
    });

    app.post('/qiniu/list', function (req, res) {
        var marker = null;
        qiniu.rsf.listPrefix(PRIVATE.qiniu.origin.bucket, '', marker, 999999, function (err, ret) {
            if (err) {
                res.status(500).send(err);
                console.log(err);
            } else {
                // process ret.marker & ret.items
//            console.log(ret.marker);
//            console.log(ret.items);

                var retr = _.chain(ret.items)
                    .sortBy(function (item) {
                        return -item.putTime
                    })
//                    .each(function (item) {
//                        item.link = generateURL(item, qiniu, PRIVATE.origin)
//                    })
                    .value();
                res.status(200).send({
                    current: 1,
                    rowCount: -1,
                    rows: retr,
                    total: retr.length
                });
            }
        });
    });
    app.delete('/qiniu/list/:key', function (req, res) {
        var key = req.params.key;
        deleteAsync(key, function (err) {

            if (err) console.log(err);
            res.status(200);
            res.end('delete success')

        });

    });

    app.post('/video/compressing/:key', function (req, res) {
        deleteList.push(req.params.key);
        _.uniq(deleteList);
        res.status(201);
        res.end('cancel success');
    });

    app.post('/video/compressing', function (req, res) {
        // mock
        var arr = [];
        var filters = [
            '.DS_Store', 'command'
        ]

        var options = {
            listeners: {
                names: function (root, nodeNamesArray) {
                    _.chain(nodeNamesArray)
                        .flatten()
                        .difference(filters)
                        .reject(function (item) {
                            return (item.length == 14) && (item.indexOf('201') == 0);
                        })
                        .each(function (item) {
                            arr.push({key: item, progress: "compress"})
                        });
                }, directories: function (root, dirStatsArray, next) {
                    next();
                }, files: function (root, fileStats, next) {
                    next();
                }, errors: function (root, nodeStatsArray, next) {
                    next();
                }
            }
        };

        walker = walk.walkSync(config.dir.upload, options);

//        console.log("all done");

        var retr = arr;
        var tempKeys = _.object(deleteList, ['']);
        var temp = _.filter(retr, function (item) {
            return !(item.key in tempKeys);
        });
//            _.chain(arr)
//            .sortBy(function (item) {
//                return item.progress;
//            })
//            .value();

        res.status(200).send({
            current: 1,
            rowCount: -1,
            rows: temp,
            total: 2
        });
    });
}<|endoftext|>


<commit_before>'use strict';

var cors = require('cors');

function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  }
  res.set('X-Auth-Required', 'true');
  req.session.returnUrl = req.originalUrl;
  res.redirect('/login/');
}

function ensureAdmin(req, res, next) {
  if (req.user.canPlayRoleOf('admin')) {
    return next();
  }
  res.redirect('/');
}

function ensureAccount(req, res, next) {
  if (req.user.canPlayRoleOf('account')) {
    if (req.app.config.requireAccountVerification) {
      if (req.user.roles.account.isVerified !== 'yes' && !/^\/account\/verification\//.test(req.url)) {
        return res.redirect('/account/verification/');
      }
    }
    return next();
  }
  res.redirect('/');
}

exports = module.exports = function(app, passport) {
  //front end
  app.get('/', require('./views/index').init);
  app.get('/about/', require('./views/about/index').init);
  app.get('/contact/', require('./views/contact/index').init);
  app.post('/contact/', require('./views/contact/index').sendMessage);

  //sign up
  app.get('/signup/', require('./views/signup/index').init);
  app.post('/signup/', require('./views/signup/index').signup);

  //social sign up
  app.post('/signup/social/', require('./views/signup/index').signupSocial);
  app.get('/signup/twitter/', passport.authenticate('twitter', { callbackURL: '/signup/twitter/callback/' }));
  app.get('/signup/twitter/callback/', require('./views/signup/index').signupTwitter);
  app.get('/signup/github/', passport.authenticate('github', { callbackURL: '/signup/github/callback/', scope: ['user:email'] }));
  app.get('/signup/github/callback/', require('./views/signup/index').signupGitHub);
  app.get('/signup/facebook/', passport.authenticate('facebook', { callbackURL: '/signup/facebook/callback/', scope: ['email'] }));
  app.get('/signup/facebook/callback/', require('./views/signup/index').signupFacebook);
  app.get('/signup/google/', passport.authenticate('google', { callbackURL: '/signup/google/callback/', scope: ['profile email'] }));
  app.get('/signup/google/callback/', require('./views/signup/index').signupGoogle);
  app.get('/signup/tumblr/', passport.authenticate('tumblr', { callbackURL: '/signup/tumblr/callback/' }));
  app.get('/signup/tumblr/callback/', require('./views/signup/index').signupTumblr);

  //login/out
  app.get('/login/', require('./views/login/index').init);
  app.post('/login/', require('./views/login/index').login);
  app.get('/login/forgot/', require('./views/login/forgot/index').init);
  app.post('/login/forgot/', require('./views/login/forgot/index').send);
  app.get('/login/reset/', require('./views/login/reset/index').init);
  app.get('/login/reset/:email/:token/', require('./views/login/reset/index').init);
  app.put('/login/reset/:email/:token/', require('./views/login/reset/index').set);
  app.get('/logout/', require('./views/logout/index').init);

  //social login
  app.get('/login/twitter/', passport.authenticate('twitter', { callbackURL: '/login/twitter/callback/' }));
  app.get('/login/twitter/callback/', require('./views/login/index').loginTwitter);
  app.get('/login/github/', passport.authenticate('github', { callbackURL: '/login/github/callback/' }));
  app.get('/login/github/callback/', require('./views/login/index').loginGitHub);
  app.get('/login/facebook/', passport.authenticate('facebook', { callbackURL: '/login/facebook/callback/' }));
  app.get('/login/facebook/callback/', require('./views/login/index').loginFacebook);
  app.get('/login/google/', passport.authenticate('google', { callbackURL: '/login/google/callback/', scope: ['profile email'] }));
  app.get('/login/google/callback/', require('./views/login/index').loginGoogle);
  app.get('/login/tumblr/', passport.authenticate('tumblr', { callbackURL: '/login/tumblr/callback/', scope: ['profile email'] }));
  app.get('/login/tumblr/callback/', require('./views/login/index').loginTumblr);

  //admin
  app.all('/admin*', ensureAuthenticated);
  app.all('/admin*', ensureAdmin);
  app.get('/admin/', require('./views/admin/index').init);

  //admin > users
  app.get('/admin/users/', require('./views/admin/users/index').find);
  app.post('/admin/users/', require('./views/admin/users/index').create);
  app.get('/admin/users/:id/', require('./views/admin/users/index').read);
  app.put('/admin/users/:id/', require('./views/admin/users/index').update);
  app.put('/admin/users/:id/password/', require('./views/admin/users/index').password);
  app.put('/admin/users/:id/role-admin/', require('./views/admin/users/index').linkAdmin);
  app.delete('/admin/users/:id/role-admin/', require('./views/admin/users/index').unlinkAdmin);
  app.put('/admin/users/:id/role-account/', require('./views/admin/users/index').linkAccount);
  app.delete('/admin/users/:id/role-account/', require('./views/admin/users/index').unlinkAccount);
  app.delete('/admin/users/:id/', require('./views/admin/users/index').delete);

  //admin > administrators
  app.get('/admin/administrators/', require('./views/admin/administrators/index').find);
  app.post('/admin/administrators/', require('./views/admin/administrators/index').create);
  app.get('/admin/administrators/:id/', require('./views/admin/administrators/index').read);
  app.put('/admin/administrators/:id/', require('./views/admin/administrators/index').update);
  app.put('/admin/administrators/:id/permissions/', require('./views/admin/administrators/index').permissions);
  app.put('/admin/administrators/:id/groups/', require('./views/admin/administrators/index').groups);
  app.put('/admin/administrators/:id/user/', require('./views/admin/administrators/index').linkUser);
  app.delete('/admin/administrators/:id/user/', require('./views/admin/administrators/index').unlinkUser);
  app.delete('/admin/administrators/:id/', require('./views/admin/administrators/index').delete);

  //admin > admin groups
  app.get('/admin/admin-groups/', require('./views/admin/admin-groups/index').find);
  app.post('/admin/admin-groups/', require('./views/admin/admin-groups/index').create);
  app.get('/admin/admin-groups/:id/', require('./views/admin/admin-groups/index').read);
  app.put('/admin/admin-groups/:id/', require('./views/admin/admin-groups/index').update);
  app.put('/admin/admin-groups/:id/permissions/', require('./views/admin/admin-groups/index').permissions);
  app.delete('/admin/admin-groups/:id/', require('./views/admin/admin-groups/index').delete);

  //admin > accounts
  app.get('/admin/accounts/', require('./views/admin/accounts/index').find);
  app.post('/admin/accounts/', require('./views/admin/accounts/index').create);
  app.get('/admin/accounts/:id/', require('./views/admin/accounts/index').read);
  app.put('/admin/accounts/:id/', require('./views/admin/accounts/index').update);
  app.put('/admin/accounts/:id/user/', require('./views/admin/accounts/index').linkUser);
  app.delete('/admin/accounts/:id/user/', require('./views/admin/accounts/index').unlinkUser);
  app.post('/admin/accounts/:id/notes/', require('./views/admin/accounts/index').newNote);
  app.post('/admin/accounts/:id/status/', require('./views/admin/accounts/index').newStatus);
  app.delete('/admin/accounts/:id/', require('./views/admin/accounts/index').delete);

  //admin > statuses
  app.get('/admin/statuses/', require('./views/admin/statuses/index').find);
  app.post('/admin/statuses/', require('./views/admin/statuses/index').create);
  app.get('/admin/statuses/:id/', require('./views/admin/statuses/index').read);
  app.put('/admin/statuses/:id/', require('./views/admin/statuses/index').update);
  app.delete('/admin/statuses/:id/', require('./views/admin/statuses/index').delete);

  //admin > categories
  app.get('/admin/categories/', require('./views/admin/categories/index').find);
  app.post('/admin/categories/', require('./views/admin/categories/index').create);
  app.get('/admin/categories/:id/', require('./views/admin/categories/index').read);
  app.put('/admin/categories/:id/', require('./views/admin/categories/index').update);
  app.delete('/admin/categories/:id/', require('./views/admin/categories/index').delete);

  //admin > search
  app.get('/admin/search/', require('./views/admin/search/index').find);

  //account
  app.all('/account*', ensureAuthenticated);
  app.all('/account*', ensureAccount);
  app.get('/account/', require('./views/account/index').init);

  //account > verification
  app.get('/account/verification/', require('./views/account/verification/index').init);
  app.post('/account/verification/', require('./views/account/verification/index').resendVerification);
  app.get('/account/verification/:token/', require('./views/account/verification/index').verify);

  //account > settings
  app.get('/account/settings/', require('./views/account/settings/index').init);
  app.put('/account/settings/', require('./views/account/settings/index').update);
  app.put('/account/settings/identity/', require('./views/account/settings/index').identity);
  app.put('/account/settings/password/', require('./views/account/settings/index').password);

  //account > settings > social
  app.get('/account/settings/twitter/', passport.authenticate('twitter', { callbackURL: '/account/settings/twitter/callback/' }));
  app.get('/account/settings/twitter/callback/', require('./views/account/settings/index').connectTwitter);
  app.get('/account/settings/twitter/disconnect/', require('./views/account/settings/index').disconnectTwitter);
  app.get('/account/settings/github/', passport.authenticate('github', { callbackURL: '/account/settings/github/callback/' }));
  app.get('/account/settings/github/callback/', require('./views/account/settings/index').connectGitHub);
  app.get('/account/settings/github/disconnect/', require('./views/account/settings/index').disconnectGitHub);
  app.get('/account/settings/facebook/', passport.authenticate('facebook', { callbackURL: '/account/settings/facebook/callback/' }));
  app.get('/account/settings/facebook/callback/', require('./views/account/settings/index').connectFacebook);
  app.get('/account/settings/facebook/disconnect/', require('./views/account/settings/index').disconnectFacebook);
  app.get('/account/settings/google/', passport.authenticate('google', { callbackURL: '/account/settings/google/callback/', scope: ['profile email'] }));
  app.get('/account/settings/google/callback/', require('./views/account/settings/index').connectGoogle);
  app.get('/account/settings/google/disconnect/', require('./views/account/settings/index').disconnectGoogle);
  app.get('/account/settings/tumblr/', passport.authenticate('tumblr', { callbackURL: '/account/settings/tumblr/callback/' }));
  app.get('/account/settings/tumblr/callback/', require('./views/account/settings/index').connectTumblr);
  app.get('/account/settings/tumblr/disconnect/', require('./views/account/settings/index').disconnectTumblr);

  /* REST APIs */
  app.get('/1/post', cors(), require('./views/api/post').readPost);
  app.get('/1/post/:id', cors(), require('./views/api/post').readPostById);
  app.get('/1/post/subject/:subject', cors(), require('./views/api/post').readPostBySubject);
  app.post('/1/post', cors(), require('./views/api/post').createPost);
  app.put('/1/post', cors(), require('./views/api/post').updatePost);
  app.put('/1/post/:subject/publish', cors(), require('./views/api/post').publish);
  app.put('/1/post/:subject/unpublish', cors(), require('./views/api/post').unpublish);

  //route not found
  app.all('*', require('./views/http/index').http404);
};
<commit_msg>fix CORS OPTIONS<commit_after>'use strict';

var cors = require('cors');

function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  }
  res.set('X-Auth-Required', 'true');
  req.session.returnUrl = req.originalUrl;
  res.redirect('/login/');
}

function ensureAdmin(req, res, next) {
  if (req.user.canPlayRoleOf('admin')) {
    return next();
  }
  res.redirect('/');
}

function ensureAccount(req, res, next) {
  if (req.user.canPlayRoleOf('account')) {
    if (req.app.config.requireAccountVerification) {
      if (req.user.roles.account.isVerified !== 'yes' && !/^\/account\/verification\//.test(req.url)) {
        return res.redirect('/account/verification/');
      }
    }
    return next();
  }
  res.redirect('/');
}

exports = module.exports = function(app, passport) {
  //front end
  app.get('/', cors(), require('./views/index').init);
  app.get('/about/', require('./views/about/index').init);
  app.get('/contact/', require('./views/contact/index').init);
  app.post('/contact/', require('./views/contact/index').sendMessage);

  //sign up
  app.get('/signup/', require('./views/signup/index').init);
  app.post('/signup/', require('./views/signup/index').signup);

  //social sign up
  app.post('/signup/social/', require('./views/signup/index').signupSocial);
  app.get('/signup/twitter/', passport.authenticate('twitter', { callbackURL: '/signup/twitter/callback/' }));
  app.get('/signup/twitter/callback/', require('./views/signup/index').signupTwitter);
  app.get('/signup/github/', passport.authenticate('github', { callbackURL: '/signup/github/callback/', scope: ['user:email'] }));
  app.get('/signup/github/callback/', require('./views/signup/index').signupGitHub);
  app.get('/signup/facebook/', passport.authenticate('facebook', { callbackURL: '/signup/facebook/callback/', scope: ['email'] }));
  app.get('/signup/facebook/callback/', require('./views/signup/index').signupFacebook);
  app.get('/signup/google/', passport.authenticate('google', { callbackURL: '/signup/google/callback/', scope: ['profile email'] }));
  app.get('/signup/google/callback/', require('./views/signup/index').signupGoogle);
  app.get('/signup/tumblr/', passport.authenticate('tumblr', { callbackURL: '/signup/tumblr/callback/' }));
  app.get('/signup/tumblr/callback/', require('./views/signup/index').signupTumblr);

  //login/out
  app.get('/login/', require('./views/login/index').init);
  app.post('/login/', require('./views/login/index').login);
  app.get('/login/forgot/', require('./views/login/forgot/index').init);
  app.post('/login/forgot/', require('./views/login/forgot/index').send);
  app.get('/login/reset/', require('./views/login/reset/index').init);
  app.get('/login/reset/:email/:token/', require('./views/login/reset/index').init);
  app.put('/login/reset/:email/:token/', require('./views/login/reset/index').set);
  app.get('/logout/', require('./views/logout/index').init);

  //social login
  app.get('/login/twitter/', passport.authenticate('twitter', { callbackURL: '/login/twitter/callback/' }));
  app.get('/login/twitter/callback/', require('./views/login/index').loginTwitter);
  app.get('/login/github/', passport.authenticate('github', { callbackURL: '/login/github/callback/' }));
  app.get('/login/github/callback/', require('./views/login/index').loginGitHub);
  app.get('/login/facebook/', passport.authenticate('facebook', { callbackURL: '/login/facebook/callback/' }));
  app.get('/login/facebook/callback/', require('./views/login/index').loginFacebook);
  app.get('/login/google/', passport.authenticate('google', { callbackURL: '/login/google/callback/', scope: ['profile email'] }));
  app.get('/login/google/callback/', require('./views/login/index').loginGoogle);
  app.get('/login/tumblr/', passport.authenticate('tumblr', { callbackURL: '/login/tumblr/callback/', scope: ['profile email'] }));
  app.get('/login/tumblr/callback/', require('./views/login/index').loginTumblr);

  //admin
  app.all('/admin*', ensureAuthenticated);
  app.all('/admin*', ensureAdmin);
  app.get('/admin/', require('./views/admin/index').init);

  //admin > users
  app.get('/admin/users/', require('./views/admin/users/index').find);
  app.post('/admin/users/', require('./views/admin/users/index').create);
  app.get('/admin/users/:id/', require('./views/admin/users/index').read);
  app.put('/admin/users/:id/', require('./views/admin/users/index').update);
  app.put('/admin/users/:id/password/', require('./views/admin/users/index').password);
  app.put('/admin/users/:id/role-admin/', require('./views/admin/users/index').linkAdmin);
  app.delete('/admin/users/:id/role-admin/', require('./views/admin/users/index').unlinkAdmin);
  app.put('/admin/users/:id/role-account/', require('./views/admin/users/index').linkAccount);
  app.delete('/admin/users/:id/role-account/', require('./views/admin/users/index').unlinkAccount);
  app.delete('/admin/users/:id/', require('./views/admin/users/index').delete);

  //admin > administrators
  app.get('/admin/administrators/', require('./views/admin/administrators/index').find);
  app.post('/admin/administrators/', require('./views/admin/administrators/index').create);
  app.get('/admin/administrators/:id/', require('./views/admin/administrators/index').read);
  app.put('/admin/administrators/:id/', require('./views/admin/administrators/index').update);
  app.put('/admin/administrators/:id/permissions/', require('./views/admin/administrators/index').permissions);
  app.put('/admin/administrators/:id/groups/', require('./views/admin/administrators/index').groups);
  app.put('/admin/administrators/:id/user/', require('./views/admin/administrators/index').linkUser);
  app.delete('/admin/administrators/:id/user/', require('./views/admin/administrators/index').unlinkUser);
  app.delete('/admin/administrators/:id/', require('./views/admin/administrators/index').delete);

  //admin > admin groups
  app.get('/admin/admin-groups/', require('./views/admin/admin-groups/index').find);
  app.post('/admin/admin-groups/', require('./views/admin/admin-groups/index').create);
  app.get('/admin/admin-groups/:id/', require('./views/admin/admin-groups/index').read);
  app.put('/admin/admin-groups/:id/', require('./views/admin/admin-groups/index').update);
  app.put('/admin/admin-groups/:id/permissions/', require('./views/admin/admin-groups/index').permissions);
  app.delete('/admin/admin-groups/:id/', require('./views/admin/admin-groups/index').delete);

  //admin > accounts
  app.get('/admin/accounts/', require('./views/admin/accounts/index').find);
  app.post('/admin/accounts/', require('./views/admin/accounts/index').create);
  app.get('/admin/accounts/:id/', require('./views/admin/accounts/index').read);
  app.put('/admin/accounts/:id/', require('./views/admin/accounts/index').update);
  app.put('/admin/accounts/:id/user/', require('./views/admin/accounts/index').linkUser);
  app.delete('/admin/accounts/:id/user/', require('./views/admin/accounts/index').unlinkUser);
  app.post('/admin/accounts/:id/notes/', require('./views/admin/accounts/index').newNote);
  app.post('/admin/accounts/:id/status/', require('./views/admin/accounts/index').newStatus);
  app.delete('/admin/accounts/:id/', require('./views/admin/accounts/index').delete);

  //admin > statuses
  app.get('/admin/statuses/', require('./views/admin/statuses/index').find);
  app.post('/admin/statuses/', require('./views/admin/statuses/index').create);
  app.get('/admin/statuses/:id/', require('./views/admin/statuses/index').read);
  app.put('/admin/statuses/:id/', require('./views/admin/statuses/index').update);
  app.delete('/admin/statuses/:id/', require('./views/admin/statuses/index').delete);

  //admin > categories
  app.get('/admin/categories/', require('./views/admin/categories/index').find);
  app.post('/admin/categories/', require('./views/admin/categories/index').create);
  app.get('/admin/categories/:id/', require('./views/admin/categories/index').read);
  app.put('/admin/categories/:id/', require('./views/admin/categories/index').update);
  app.delete('/admin/categories/:id/', require('./views/admin/categories/index').delete);

  //admin > search
  app.get('/admin/search/', require('./views/admin/search/index').find);

  //account
  app.all('/account*', ensureAuthenticated);
  app.all('/account*', ensureAccount);
  app.get('/account/', require('./views/account/index').init);

  //account > verification
  app.get('/account/verification/', require('./views/account/verification/index').init);
  app.post('/account/verification/', require('./views/account/verification/index').resendVerification);
  app.get('/account/verification/:token/', require('./views/account/verification/index').verify);

  //account > settings
  app.get('/account/settings/', require('./views/account/settings/index').init);
  app.put('/account/settings/', require('./views/account/settings/index').update);
  app.put('/account/settings/identity/', require('./views/account/settings/index').identity);
  app.put('/account/settings/password/', require('./views/account/settings/index').password);

  //account > settings > social
  app.get('/account/settings/twitter/', passport.authenticate('twitter', { callbackURL: '/account/settings/twitter/callback/' }));
  app.get('/account/settings/twitter/callback/', require('./views/account/settings/index').connectTwitter);
  app.get('/account/settings/twitter/disconnect/', require('./views/account/settings/index').disconnectTwitter);
  app.get('/account/settings/github/', passport.authenticate('github', { callbackURL: '/account/settings/github/callback/' }));
  app.get('/account/settings/github/callback/', require('./views/account/settings/index').connectGitHub);
  app.get('/account/settings/github/disconnect/', require('./views/account/settings/index').disconnectGitHub);
  app.get('/account/settings/facebook/', passport.authenticate('facebook', { callbackURL: '/account/settings/facebook/callback/' }));
  app.get('/account/settings/facebook/callback/', require('./views/account/settings/index').connectFacebook);
  app.get('/account/settings/facebook/disconnect/', require('./views/account/settings/index').disconnectFacebook);
  app.get('/account/settings/google/', passport.authenticate('google', { callbackURL: '/account/settings/google/callback/', scope: ['profile email'] }));
  app.get('/account/settings/google/callback/', require('./views/account/settings/index').connectGoogle);
  app.get('/account/settings/google/disconnect/', require('./views/account/settings/index').disconnectGoogle);
  app.get('/account/settings/tumblr/', passport.authenticate('tumblr', { callbackURL: '/account/settings/tumblr/callback/' }));
  app.get('/account/settings/tumblr/callback/', require('./views/account/settings/index').connectTumblr);
  app.get('/account/settings/tumblr/disconnect/', require('./views/account/settings/index').disconnectTumblr);

  /* REST APIs */
  app.get('/1/post', cors(), require('./views/api/post').readPost);
  app.get('/1/post/:id', cors(), require('./views/api/post').readPostById);
  app.get('/1/post/subject/:subject', cors(), require('./views/api/post').readPostBySubject);
  app.post('/1/post', cors(), require('./views/api/post').createPost);
  app.put('/1/post', cors(), require('./views/api/post').updatePost);
  app.all('/1/post', cors(), require('./views/api/post').createPost);
  app.put('/1/post/:subject/publish', cors(), require('./views/api/post').publish);
  app.put('/1/post/:subject/unpublish', cors(), require('./views/api/post').unpublish);

  //route not found
  app.all('*', require('./views/http/index').http404);
};
<|endoftext|>