<commit_before>var Sequelize = require('sequelize');
var config = require('../config/environment');

var User, Event, Observation;

var init = function() {
  var orm;

  // Use different parameters for initializing the Sequelize instance depending on environment
  if (config.postgres.uri) {
    // The production environment should have a DATABASE_URL environment variable, which includes a URL
    // with username, password, host, port, and database. The URL will be set in config/environment/production.js.
    orm = new Sequelize(config.postgres.uri, config.postgres.options);
  } else {
    // The development environment will not use a URL, and each config parameter
    // will be set in config/environment/development.js
    orm = new Sequelize(config.postgres.database, config.postgres.user, config.postgres.password, config.postgres.options);
  }

  User = orm.define('User', {
    username: Sequelize.STRING,
    facebook_id: Sequelize.STRING
  });

  Event = orm.define('Event', {
    name: Sequelize.STRING,
    start: Sequelize.DATE,
    end: Sequelize.DATE,
    location: Sequelize.STRING,
    minParticipants: Sequelize.INTEGER,
    maxParticipants: Sequelize.INTEGER,
    action: Sequelize.STRING
  });

  Observation = orm.define('Observation', {
    content: Sequelize.STRING,
    completed: Sequelize.BOOLEAN,
    rawImage: Sequelize.TEXT
  });

  /**
   * MODEL RELATIONS
   * belongsToMany connects a source with multiple targets, and the targets can connect to multiple sources
   * Using a `through` option will create a new model with foreign keys for the source and target
   *
   * Example:
   * User.belongsToMany(Event, {as: 'ShepherdEvents', through: 'ShepherdEvent'});
   * Event.belongsToMany(User, {as: 'Shepherds', through: 'ShepherdEvent'});
   *
   * We create a many-to-many relationship between users and events, and the join table is called ShepherdEvent.
   * The ShepherdEvent table will have a foreign key for EventId and UserId.
   * The User and Event models will have get, set, and add methods. For example, user.getShepherdEvents()
   * will return all instances of a ShepherdEvent belonging to that user, and each instance would reference the
   * Event the user is a shepherd for.
   *
   * See http://sequelize.readthedocs.org/en/latest/docs/associations/#belongs-to-many-associations
   *
   * hasMany connects a source with multiple targets, but the targets can only connect to one source
   *
   * See http://sequelize.readthedocs.org/en/latest/docs/associations/#one-to-many-associations
   */

  User.belongsToMany(Event, {as: 'ShepherdEvents', through: 'ShepherdEvent'});
  Event.belongsToMany(User, {as: 'Shepherds', through: 'ShepherdEvent'});
  User.belongsToMany(Event, {as: 'SheepEvents', through: 'SheepEvent'});
  Event.belongsToMany(User, {as: 'Sheep', through: 'SheepEvent'});
  User.hasMany(Observation);
  Observation.belongsTo(User);
  Event.hasMany(Observation);
  Observation.belongsTo(Event);

  // EXAMPLE OF HOW TO CREATE A USER, THEN AN EVENT, AND FINALLY AN OBSERVATION TIED TO THE USER AND EVENT:
  // User.create({
  //   username: 'Kev'
  // }).then(function (user) {
  //   Event.create({
  //     name: 'Dance party',
  //     location: 'San Francisco'
  //   }).then(function (event) {
  //     Observation.create({
  //       content: 'It is poppin in herrr',
  //       completed: false
  //     }).then(function (observation) {
  //       // Associate the observation to the event
  //       return event.addObservation(observation);
  //     }).then(function (observation) {
  //       // Associate the observation to the user
  //       user.addObservation(observation);
  //     });
  //   });
  // });

  // EXAMPLE OF HOW TO CREATE A USER, A SHEEP, AND ADD THE USER TO AN EXISTING EVENT
  // User.create({
  //   username: 'Derek'
  // }).then(function (user) {
  //   var sheepId = user.id;
  //   Event.findOne({
  //     where: {
  //       name: 'Dance party'
  //     }
  //   }).then(function (event) {
  //     event.addSheep(sheepId);
  //   });
  // });

  // EXAMPLE OF HOW TO CREATE A USER, A SHEEP, ADD AND THEN REMOVE THE USER TO AND FROM AN EXISTING EVENT
  // var eventId, eventInstance, userInstance;
  // User.create({
  //   username: 'Eddie'
  // }).then(function (user) {
  //   userInstance = user;
  //   Event.findOne({
  //     where: {
  //       name: 'Dance party'
  //     }
  //   }).then(function (event) {
  //     eventInstance = event
  //     event.addSheep(user);
  //   }).then(function (user) {
  //     userInstance.removeSheepEvent(eventInstance);
  //   });
  // });

  // export all models
  exports.User = User;
  exports.Event = Event;
  exports.Observation = Observation;

  // sync all models
  return orm.sync();
};

exports.init = init;
<commit_msg>Added data for all tables<commit_after>var Sequelize = require('sequelize');
var config = require('../config/environment');

var User, Event, Observation;

var init = function() {
  var orm;

  // Use different parameters for initializing the Sequelize instance depending on environment
  if (config.postgres.uri) {
    // The production environment should have a DATABASE_URL environment variable, which includes a URL
    // with username, password, host, port, and database. The URL will be set in config/environment/production.js.
    orm = new Sequelize(config.postgres.uri, config.postgres.options);
  } else {
    // The development environment will not use a URL, and each config parameter
    // will be set in config/environment/development.js
    orm = new Sequelize(config.postgres.database, config.postgres.user, config.postgres.password, config.postgres.options);
  }

  User = orm.define('User', {
    username: Sequelize.STRING,
    facebook_id: Sequelize.STRING
  });

  Event = orm.define('Event', {
    name: Sequelize.STRING,
    start: Sequelize.DATE,
    end: Sequelize.DATE,
    location: Sequelize.STRING,
    minParticipants: Sequelize.INTEGER,
    maxParticipants: Sequelize.INTEGER,
    action: Sequelize.STRING
  });

  Observation = orm.define('Observation', {
    content: Sequelize.STRING,
    completed: Sequelize.BOOLEAN,
    rawImage: Sequelize.TEXT
  });

  /**
   * MODEL RELATIONS
   * belongsToMany connects a source with multiple targets, and the targets can connect to multiple sources
   * Using a `through` option will create a new model with foreign keys for the source and target
   *
   * Example:
   * User.belongsToMany(Event, {as: 'ShepherdEvents', through: 'ShepherdEvent'});
   * Event.belongsToMany(User, {as: 'Shepherds', through: 'ShepherdEvent'});
   *
   * We create a many-to-many relationship between users and events, and the join table is called ShepherdEvent.
   * The ShepherdEvent table will have a foreign key for EventId and UserId.
   * The User and Event models will have get, set, and add methods. For example, user.getShepherdEvents()
   * will return all instances of a ShepherdEvent belonging to that user, and each instance would reference the
   * Event the user is a shepherd for.
   *
   * See http://sequelize.readthedocs.org/en/latest/docs/associations/#belongs-to-many-associations
   *
   * hasMany connects a source with multiple targets, but the targets can only connect to one source
   *
   * See http://sequelize.readthedocs.org/en/latest/docs/associations/#one-to-many-associations
   */

  User.belongsToMany(Event, {as: 'ShepherdEvents', through: 'ShepherdEvent'});
  Event.belongsToMany(User, {as: 'Shepherds', through: 'ShepherdEvent'});
  User.belongsToMany(Event, {as: 'SheepEvents', through: 'SheepEvent'});
  Event.belongsToMany(User, {as: 'Sheep', through: 'SheepEvent'});
  User.hasMany(Observation);
  Observation.belongsTo(User);
  Event.hasMany(Observation);
  Observation.belongsTo(Event);

  // EXAMPLE OF HOW TO CREATE A USER, THEN AN EVENT, AND FINALLY AN OBSERVATION TIED TO THE USER AND EVENT:
  // User.create({
  //   username: 'Kev'
  // }).then(function (user) {
  //   Event.create({
  //     name: 'Dance party',
  //     location: 'San Francisco'
  //   }).then(function (event) {
  //     Observation.create({
  //       content: 'It is poppin in herrr',
  //       completed: false
  //     }).then(function (observation) {
  //       // Associate the observation to the event
  //       return event.addObservation(observation);
  //     }).then(function (observation) {
  //       // Associate the observation to the user
  //       user.addObservation(observation);
  //     });
  //   });
  // });

  // EXAMPLE OF HOW TO CREATE A USER, A SHEEP, AND ADD THE USER TO AN EXISTING EVENT
  // User.create({
  //   username: 'Derek'
  // }).then(function (user) {
  //   var sheepId = user.id;
  //   Event.findOne({
  //     where: {
  //       name: 'Dance party'
  //     }
  //   }).then(function (event) {
  //     event.addSheep(sheepId);
  //   });
  // });

  // EXAMPLE OF HOW TO CREATE A USER, A SHEEP, ADD AND THEN REMOVE THE USER TO AND FROM AN EXISTING EVENT
  // var eventId, eventInstance, userInstance;
  // User.create({
  //   username: 'Eddie'
  // }).then(function (user) {
  //   userInstance = user;
  //   Event.findOne({
  //     where: {
  //       name: 'Dance party'
  //     }
  //   }).then(function (event) {
  //     eventInstance = event
  //     event.addSheep(user);
  //   }).then(function (user) {
  //     userInstance.removeSheepEvent(eventInstance);
  //   });
  // });

  // export all models
  exports.User = User;
  exports.Event = Event;
  exports.Observation = Observation;

  // sync all models
  // return orm.sync();
  return orm.sync({force:true}).then(function(){

    User.bulkCreate([
      { username: 'steven', facebook_id: 123},
      { username: 'derek', facebook_id: 124},
      { username: 'kevin', facebook_id: 125},
      { username: 'eddie', facebook_id: 126}
    ]);

    Event.bulkCreate([
      { name: 'thing1', start: 'June 17, 2015 13:00:00', end: 'June 17, 2015 14:00:00', location: 'San Francisco', minParticipants: 0, maxParticipants: 4, action:''},
      { name: 'thing2', start: 'June 17, 2015 13:00:00', end: 'June 17, 2015 14:00:00', location: 'San Francisco', minParticipants: 0, maxParticipants: 4, action:'' },
      { name: 'thing3', start: 'June 17, 2015 13:00:00', end: 'June 17, 2015 14:00:00', location: 'San Francisco', minParticipants: 0, maxParticipants: 4, action:'' },
      { name: 'thing4', start: 'June 17, 2015 13:00:00', end: 'June 17, 2015 14:00:00', location: 'San Francisco', minParticipants: 0, maxParticipants: 4, action:'' },
      { name: 'thing5', start: 'June 17, 2015 13:00:00', end: 'June 17, 2015 14:00:00', location: 'San Francisco', minParticipants: 0, maxParticipants: 4, action:'' }
    ]);

    Observation.bulkCreate([
      {content: 'yes1', completed: false, rawImage: ''},
      {content: 'yes2', completed: false, rawImage: ''},
      {content: 'yes3', completed: false, rawImage: ''},
      {content: 'yes4', completed: false, rawImage: ''},
      {content: 'yes5', completed: false, rawImage: ''}
    ]);

  var user1;
  var event1;
  var observation1;

  User.findOne({
    where: {
    id: 1
  }
  }).then(function (user) {
    user1 = user;
    console.log(user1);
    Event.findOne({
      where: {
      id: 1
      }
    }).then(function (event) {
      event1 = event;
      console.log(event1);
      Observation.findOne({
        where: {
          id:1
        }
      }).then(function(observation){
        observation1 = observation;
      });
    });
  });

  var user2;
  var event2;
  var observation2;

  User.findOne({
    where: {
    id: 2
  }
  }).then(function (user) {
    user2 = user;
    Event.findOne({
      where: {
      id: 2
      }
    }).then(function (event) {
      event2 = event;
      Observation.findOne({
        where: {
          id: 2
        }
      }).then(function(observation){
        observation2 = observation;
      });
    });
  });

  var user3;
  var event3;
  var observation3;

  User.findOne({
    where: {
    id: 3
  }
  }).then(function (user) {
    user3 = user;
    Event.findOne({
      where: {
      id: 3
      }
    }).then(function (event) {
      event3 = event;
      Observation.findOne({
        where: {
          id:3
        }
      }).then(function(observation){
        observation3 = observation;
      });
    });
  });

  var user4;
  var event4;
  var observation4;

  User.findOne({
    where: {
    id: 4
  }
  }).then(function (user) {
    user4 = user;
    Event.findOne({
      where: {
      id: 4
      }
    }).then(function (event) {
      event4 = event;
      Observation.findOne({
        where: {
          id:4
        }
      }).then(function(observation){
        observation4 = observation;

        user1.addObservation(observation1);
        event1.addObservation(observation1);
        user2.addObservation(observation2);
        event1.addObservation(observation2);

        user1.addObservation(observation1);
        event2.addObservation(observation1);
        user1.addObservation(observation3);
        event2.addObservation(observation3);

        user2.addObservation(observation2);
        event2.addObservation(observation2);
        user3.addObservation(observation2);
        event2.addObservation(observation2);

        user1.addShepherdEvent(event1);
        user1.addShepherdEvent(event2);
        user1.addShepherdEvent(event3);
        user1.addShepherdEvent(event4);

        user1.addSheepEvent(event2);
        user3.addSheepEvent(event2);
        user4.addSheepEvent(event2);

        user2.addSheepEvent(event1);
        user3.addSheepEvent(event2);
        user4.addSheepEvent(event2);

      });
    });
  });

  console.log(user1);
  console.log(event1);
  console.log(observation1);

  // user1.addObservation(observation1);
  // event1.addObservation(observation1);
  // user2.addObservation(observation2);
  // event1.addObservation(observation2);

  // user1.addObservation(observation1);
  // event2.addObservation(observation1);
  // user2.addObservation(observation2);
  // event2.addObservation(observation2);

  // user1.addShepherdEvent(event2);
  // user1.addShepherdEvent(event3);
  // user1.addShepherdEvent(event4);

  // user1.addSheepEvent(event2);
  // user2.addSheepEvent(event1);
  // user3.addSheepEvent(event2);
  // user4.addSheepEvent(event2);

  //   ShepherdEvents.bulkCreate([
  //     {EventId: 1,
  //         UserId: 1}
  //     ]);

  //   // (User[1]).addShepherdEvent( Event[1]);

  });
};

exports.init = init;
<|endoftext|>


<commit_before>var habitat = require('habitat');

habitat.load('.env');

var path = require('path'),
    fs = require('fs'),
    express = require('express'),
    helmet = require('helmet'),
    url = require('url'),
    React = require('react'),
    ReactRouter = require('react-router'),
    Router = ReactRouter.Router,
    match = ReactRouter.match,
    routington = require('routington'),
    PORT = process.env.PORT || 8008,
    PRODUCTION = (process.env.NODE_ENV === 'production'),
    DIST_DIR = path.join(__dirname, 'dist'),
    CODEMOJI_URL = process.env.CODEMOJI_URL || "https://codemoji.mofostaging.net",
    localize = require('mofo-localize'),
    urlToRoutePath = require('./server/url-to-route-path'),
    renderComponentPage = require('./server/render-component-page'),
    WpPageChecker = require('./lib/wp-page-checker'),
    config = require('./config/config'),
    SUPPORTED_LOCALES = config.SUPPORTED_LOCALES,
    locale = "";

// the static HTML generator
var serverBundle = require('./build/server.library');
var router = React.createElement(Router, {routes: serverBundle.routes});
var matcher;

if (process.env.NODE_ENV !== 'production') {
  var requireUncached = require('require-uncached'),
      chokidar = require('chokidar');

  // reload our index and router if there's a change to the static site generator code
  chokidar.watch('./build').on('all', function(_event, _path) {
    serverBundle = requireUncached('./build/server.library');
    router = React.createElement(Router, {routes: serverBundle.routes});
  });
}

var app = express();

/**
 * Several app security settings
 */
app.disable('x-powered-by');

var securityHeaders = require('./server/security-headers');

app.use(helmet.contentSecurityPolicy(securityHeaders));

app.use(helmet.xssFilter({
  setOnOldIE: true
}));

app.use(helmet.hsts({
  maxAge: 1000 * 60 * 60 * 24 * 90
}));

app.use(helmet.ieNoOpen());

app.use(helmet.noSniff());

if (process.env.HPKP) {
  app.use(helmet.hpkp({
    maxAge: 1000 * 60 * 60 * 24 * 90,
    sha256s: process.env.HPKP.split(' '),
    setIf: function (req, res) {
      return req.secure;
    }
  }));
}

/**
 * Wait for the router to come online.
 */
app.use(function(req, res, next) {
  if (router) {
    return next();
  }
  res.send('Please wait while the server-side bundle regenerates.');
});

/**
 * If we have a router, check if we're dealing with a redirect.
 */
app.use(function(req, res, next) {
  var routePath = urlToRoutePath(req.path);

  if (!serverBundle.REDIRECTS[routePath]) {
    return next();
  }
  res.redirect('/' + serverBundle.REDIRECTS[routePath] + '/');
});

/**
 * If it's not a redirect, is it a component page?
 */
app.use(function(req, res, next) {
  var routes = serverBundle.routes,
      location = urlToRoutePath(req.url),
      urls = serverBundle.URLS,
      lang;

  if (!matcher) {
    matcher = routington();
    urls.forEach(function(route) { matcher.define(route); });
  }

  match({ routes: routes, location: location}, function resolveRoute(err, redirect, props) {

    // React router based redirect? (routes.jsx)
    if(redirect) {
      return res.redirect(redirect.pathname);
    }

    // is this even a component?
    if ( !props ) {
      return next();
    }

    // if this belongs to one of the predefined urls, let's generate its associated page
    if ( matcher.match(location) ) {
      var search = url.parse(req.url).search || "";

      locale = localize.parseLocale(req.headers["accept-language"], location, SUPPORTED_LOCALES).locale;
      if (location === "/") {
        res.redirect(302, location + locale + search);
        return;
      }

      lang = location.split('/')[0];
      return renderComponentPage(serverBundle, location, res, lang);
    } else {
      // if neither of those, this is wordpress content...
      // check to see a page with this slug exists on the WordPress site
      WpPageChecker(location, function(error, wpContent) {
        if ( error ) {
          return next();
        }
        // WP page exists, let's load the WordPress content through a component page
        return renderComponentPage(serverBundle, location, res);
      });
    }
  });
});

/**
 * codemoji redirect - https://github.com/mozilla/codemoji
 */
app.use('/codemoji', function(req, res) {
  var location = url.parse(CODEMOJI_URL);

  location.pathname = req.path;
  location.query = req.query;
  res.redirect(307, url.format(location));
});

/**
 * Is this a static asset?
 */
app.use(express.static(DIST_DIR));

/**
* Maybe it is a route, but needs the localized path
*/
app.use(function(req, res, next) {
  var location = url.parse(req.url).pathname,
      search = url.parse(req.url).search || "",
      parsed = localize.parseLocale(req.headers["accept-language"], location, SUPPORTED_LOCALES),
      parsedLocale = parsed.locale,
      parsedRedirect = parsed.redirect;

  // See if we should redirect.
  if (parsedRedirect) {
    res.redirect(307, "/" + parsedLocale + parsedRedirect + search);
  } else {
    next();
  }
});

app.use(require('./server/404'));

app.READY_STRING = "Server listening on port";
app.PORT = PORT;

var startProdApp = function() {
  app.listen(PORT, function() {
    console.log('\n\n==================================================');
    console.log('=                                                =');
    console.log('=         ', app.READY_STRING, PORT, '        =');
    console.log('=                                                =');
    console.log('==================================================\n');
  });
};

app.startProdApp = startProdApp;

module.exports = app;

// Auto-start only if this was not a require() call for app.js
if (!module.parent) { startProdApp(); }
<commit_msg>Make locale negotiation work for events<commit_after>var habitat = require('habitat');

habitat.load('.env');

var path = require('path'),
    fs = require('fs'),
    express = require('express'),
    helmet = require('helmet'),
    url = require('url'),
    React = require('react'),
    ReactRouter = require('react-router'),
    Router = ReactRouter.Router,
    match = ReactRouter.match,
    routington = require('routington'),
    PORT = process.env.PORT || 8008,
    PRODUCTION = (process.env.NODE_ENV === 'production'),
    DIST_DIR = path.join(__dirname, 'dist'),
    CODEMOJI_URL = process.env.CODEMOJI_URL || "https://codemoji.mofostaging.net",
    localize = require('mofo-localize'),
    urlToRoutePath = require('./server/url-to-route-path'),
    renderComponentPage = require('./server/render-component-page'),
    WpPageChecker = require('./lib/wp-page-checker'),
    config = require('./config/config'),
    SUPPORTED_LOCALES = config.SUPPORTED_LOCALES,
    MAKER_PARTY_LOCALES = config.MAKER_PARTY_LOCALES,
    locale = "";

// the static HTML generator
var serverBundle = require('./build/server.library');
var router = React.createElement(Router, {routes: serverBundle.routes});
var matcher;

if (process.env.NODE_ENV !== 'production') {
  var requireUncached = require('require-uncached'),
      chokidar = require('chokidar');

  // reload our index and router if there's a change to the static site generator code
  chokidar.watch('./build').on('all', function(_event, _path) {
    serverBundle = requireUncached('./build/server.library');
    router = React.createElement(Router, {routes: serverBundle.routes});
  });
}

var app = express();

/**
 * Several app security settings
 */
app.disable('x-powered-by');

var securityHeaders = require('./server/security-headers');

app.use(helmet.contentSecurityPolicy(securityHeaders));

app.use(helmet.xssFilter({
  setOnOldIE: true
}));

app.use(helmet.hsts({
  maxAge: 1000 * 60 * 60 * 24 * 90
}));

app.use(helmet.ieNoOpen());

app.use(helmet.noSniff());

if (process.env.HPKP) {
  app.use(helmet.hpkp({
    maxAge: 1000 * 60 * 60 * 24 * 90,
    sha256s: process.env.HPKP.split(' '),
    setIf: function (req, res) {
      return req.secure;
    }
  }));
}

/**
 * Wait for the router to come online.
 */
app.use(function(req, res, next) {
  if (router) {
    return next();
  }
  res.send('Please wait while the server-side bundle regenerates.');
});

/**
 * If we have a router, check if we're dealing with a redirect.
 */
app.use(function(req, res, next) {
  var routePath = urlToRoutePath(req.path);

  if (!serverBundle.REDIRECTS[routePath]) {
    return next();
  }
  res.redirect('/' + serverBundle.REDIRECTS[routePath] + '/');
});

/**
 * If it's not a redirect, is it a component page?
 */
app.use(function(req, res, next) {
  var routes = serverBundle.routes,
      location = urlToRoutePath(req.url),
      urls = serverBundle.URLS,
      lang;

  if (!matcher) {
    matcher = routington();
    urls.forEach(function(route) { matcher.define(route); });
  }

  match({ routes: routes, location: location}, function resolveRoute(err, redirect, props) {

    // React router based redirect? (routes.jsx)
    if(redirect) {
      return res.redirect(redirect.pathname);
    }

    // is this even a component?
    if ( !props ) {
      return next();
    }

    // if this belongs to one of the predefined urls, let's generate its associated page
    if ( matcher.match(location) ) {
      var search = url.parse(req.url).search || "";

      locale = localize.parseLocale(req.headers["accept-language"], location, SUPPORTED_LOCALES).locale;
      if (location === "/") {
        res.redirect(302, location + locale + search);
        return;
      }

      lang = location.split('/')[0];
      return renderComponentPage(serverBundle, location, res, lang);
    } else {
      // if neither of those, this is wordpress content...
      // check to see a page with this slug exists on the WordPress site
      WpPageChecker(location, function(error, wpContent) {
        if ( error ) {
          return next();
        }
        // WP page exists, let's load the WordPress content through a component page
        return renderComponentPage(serverBundle, location, res);
      });
    }
  });
});

/**
 * codemoji redirect - https://github.com/mozilla/codemoji
 */
app.use('/codemoji', function(req, res) {
  var location = url.parse(CODEMOJI_URL);

  location.pathname = req.path;
  location.query = req.query;
  res.redirect(307, url.format(location));
});

/**
 * Is this a static asset?
 */
app.use(express.static(DIST_DIR));

/**
* Maybe it is a route, but needs the localized path
*/
app.use(function(req, res, next) {
  var location = url.parse(req.url).pathname,
      // Useful locales changes if we're on maker party pages
      supportedLocales = location.match(/\/events(\/resources)?$/) ? SUPPORTED_LOCALES.concat(MAKER_PARTY_LOCALES) : SUPPORTED_LOCALES,
      search = url.parse(req.url).search || "",
      parsed = localize.parseLocale(req.headers["accept-language"], location, supportedLocales),
      parsedLocale = parsed.locale,
      parsedRedirect = parsed.redirect;

  // See if we should redirect.
  if (parsedRedirect) {
    res.redirect(307, "/" + parsedLocale + parsedRedirect + search);
  } else {
    next();
  }
});

app.use(require('./server/404'));

app.READY_STRING = "Server listening on port";
app.PORT = PORT;

var startProdApp = function() {
  app.listen(PORT, function() {
    console.log('\n\n==================================================');
    console.log('=                                                =');
    console.log('=         ', app.READY_STRING, PORT, '        =');
    console.log('=                                                =');
    console.log('==================================================\n');
  });
};

app.startProdApp = startProdApp;

module.exports = app;

// Auto-start only if this was not a require() call for app.js
if (!module.parent) { startProdApp(); }
<|endoftext|>


<commit_before><commit_msg>filtrado de datos de la base para borrar punto final y poner mayúscula al principio de cada campo<commit_after><|endoftext|>


<commit_before>(function () {
    console.log("I'm a git commit")
    var bodyParser = require('body-parser');
    var express = require('express');
    var app = express();
    var baltimore = require('./baltimore');
    var _ = require('lodash');
    app.all('*', function (req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header('Access-Control-Allow-Methods', 'OPTIONS,GET,POST,PUT,DELETE');
        res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
        if ('OPTIONS' == req.method) {
            return res.sendStatus(200);
        }
        next();
    });

    app.use(bodyParser.urlencoded({
        extended: true
    }));
    app.use(bodyParser.json());

    var router = require('express').Router();
    var port = process.env.PORT || 8080;

    router.use(function (req, res, next) {
        //do logging
        console.log('Something is happening.');
        next(); //ensure that the router doesn't halt here
    });

    router.route('/').get(function (req, res, next) {
        var jobTitleList = [];
        var annualSalaryList = [];
        var departmentList = [];
		  var aggregateList = [];
        baltimore.data.forEach(function (entry) {
            jobTitleList.push(entry[9])
        });
        baltimore.data.forEach(function (entry) {
            annualSalaryList.push(entry[13])
        });
        baltimore.data.forEach(function (entry) {
            departmentList.push(entry[11])
        });

		  var salaryList = baltimore.data.filter(function(person){
			  return parseInt(person[13]) >= 100000;
		  });

        var unique = _.uniq(departmentList);
		  console.log(unique);
        //console.log(jobTitleList.length + "job titles");
        //console.log(annualSalaryList.length + "annual salaries");
        //console.log(departmentList.length + "departments");
        //console.log(unique.length);
        //var thing = [];
        //for ( x in unique){
        //    if(baltimore.data.forEach(entry[11]) === x){
        //        thing.push({x: entry[13]})
        //    }
        //}
        //console.log(thing);
        //var comboObject = _.sortBy(annualSalaryList.map(Number));

		  res.send(salaryList);
        next();
    });

    //router.get('/', function(req, res){
    //    res.json({message: 'hooray, welcome to our api!'});
    //});
    app.use('/', router);
    app.listen(port);
    console.log('Magic happens on port ' + port);

}());<commit_msg>Showing git to the wife<commit_after>(function () {
    console.log("I'm a git commit");
    consolg.lof("I'm also a git commit");
    var bodyParser = require('body-parser');
    var express = require('express');
    var app = express();
    var baltimore = require('./baltimore');
    var _ = require('lodash');
    app.all('*', function (req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header('Access-Control-Allow-Methods', 'OPTIONS,GET,POST,PUT,DELETE');
        res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
        if ('OPTIONS' == req.method) {
            return res.sendStatus(200);
        }
        next();
    });

    app.use(bodyParser.urlencoded({
        extended: true
    }));
    app.use(bodyParser.json());

    var router = require('express').Router();
    var port = process.env.PORT || 8080;

    router.use(function (req, res, next) {
        //do logging
        console.log('Something is happening.');
        next(); //ensure that the router doesn't halt here
    });

    router.route('/').get(function (req, res, next) {
        var jobTitleList = [];
        var annualSalaryList = [];
        var departmentList = [];
		  var aggregateList = [];
        baltimore.data.forEach(function (entry) {
            jobTitleList.push(entry[9])
        });
        baltimore.data.forEach(function (entry) {
            annualSalaryList.push(entry[13])
        });
        baltimore.data.forEach(function (entry) {
            departmentList.push(entry[11])
        });

		  var salaryList = baltimore.data.filter(function(person){
			  return parseInt(person[13]) >= 100000;
		  });

        var unique = _.uniq(departmentList);
		  console.log(unique);
        //console.log(jobTitleList.length + "job titles");
        //console.log(annualSalaryList.length + "annual salaries");
        //console.log(departmentList.length + "departments");
        //console.log(unique.length);
        //var thing = [];
        //for ( x in unique){
        //    if(baltimore.data.forEach(entry[11]) === x){
        //        thing.push({x: entry[13]})
        //    }
        //}
        //console.log(thing);
        //var comboObject = _.sortBy(annualSalaryList.map(Number));

		  res.send(salaryList);
        next();
    });

    //router.get('/', function(req, res){
    //    res.json({message: 'hooray, welcome to our api!'});
    //});
    app.use('/', router);
    app.listen(port);
    console.log('Magic happens on port ' + port);

}());<|endoftext|>


<commit_before><commit_msg>remove weird file<commit_after><|endoftext|>


<commit_before>'use strict'

var st = require('st')
  , http = require('http')
  , path = require('path')
  , url = require('url')
  , fs = require('fs')
  , os = require('os')
  , js = require('atomify-js')
  , css = require('atomify-css')
  , prettyError = require('prettify-error')
  , AnsiToHTML = require('ansi-to-html')
  , ansiStyleFormat = require('style-format')
  , cssFiles = require('atomify-css/css')
  , lessFiles = require('atomify-css/less')
  , open = require('open')
  , browserSync = require('browser-sync').create()
  , defaultBundlePath = path.join(__dirname, '_bundle.js')
  , JS_REPLACE = '__ATOMIFY_JS__'
  , CSS_REPLACE = '__ATOMIFY_CSS__'
  , HTML_HEAD = '<!doctype html>'
    + '<meta charset="utf-8">'
    + '<meta http-equiv="X-UA-Compatible" content="IE=edge">'
    + '<meta name="viewport" content="initial-scale=1,width=device-width,user-scalable=0">'
  , cwd = process.cwd()
  , internals = {}
  , baseUrl
  , bs

internals.getDefaultHTML = function getDefaultHTML (args) {
  var src = HTML_HEAD
  src += '<title>generated by atomify</title>'
  if (args.css.entry) src += '<link rel="stylesheet" href="CSS">'
  src += ''
  src += ''
  src += ''

  src = src.replace('JS', args.js.alias)
  src = src.replace('CSS', args.css.alias)

  return src
}

internals.customDefaultHTML = ''

internals.setCustomDefaultHTML = function setCustomDefaultHTML (file, args) {
  var html = fs.readFileSync(file, {encoding: 'utf8'})
    , shouldReplaceJS = html.indexOf(JS_REPLACE) > -1
    , shouldReplaceCSS = html.indexOf(CSS_REPLACE) > -1

  if (shouldReplaceCSS) html.replace(CSS_REPLACE, args.css.alias)
  else html += '<link rel="stylesheet" href="' + args.css.alias + '">'

  if (shouldReplaceJS) html.replace(JS_REPLACE, args.js.alias)
  else html += ''

  internals.customDefaultHTML = html

  return internals.customDefaultHTML
}

internals.getCustomDefaultHTML = function getCustomDefaultHTML (req, args, callback) {
  var html = args.server.html
    , htmlIsFile = typeof html === 'string'

  // bail early if there is no html option
  if (!html) return void callback(null, null)

  // if the html arg is a string, assume it's a file name
  // if we've already cached this file, don't go read it again
  if (htmlIsFile && html !== internals.customDefaultHTML) {
    callback(null, internals.setCustomDefaultHTML(html, args))
  }
  else if (htmlIsFile){
    callback(null, internals.customDefaultHTML)
  }
  // if the html arg isn't a string, it should be a function that returns html
  else {
    html({js: args.js.alias, css: args.css.alias, request: req.url}, callback)
  }
}

internals.htmlifyBabelError = function htmlifyBabelError (err) {
  var stack = (new AnsiToHTML({
    escapeXML: true
    , fg: '#000'
    , bg: '#fff'
  })).toHtml(err.codeFrame)
    , html = '<!doctype html>'
      + '<meta charset="utf-8">'
      + '<meta http-equiv="X-UA-Compatible" content="IE=edge">'
      + '<meta name="viewport" content="initial-scale=1,width=device-width,user-scalable=0">'
      + '<title>' + err.toString() + '</title>'
      + ''
      + '
'
      + '
' + err.toString() + '
'
      + '
'
      + '
' + stack + '
'
      + ''

  return html
}

internals.htmlifyError = function htmlifyError (err) {
  var lines
    , html

  if (err._babel) return internals.htmlifyBabelError(err)

  lines = (new AnsiToHTML({escapeXML: true})).toHtml(err).split('\n')
  html = '<!doctype html>'
    + '<meta charset="utf-8">'
    + '<meta http-equiv="X-UA-Compatible" content="IE=edge">'
    + '<meta name="viewport" content="initial-scale=1,width=device-width,user-scalable=0">'
    + '<title>' + err.toString() + '</title>'
    + ''
    + '
'

  // first line is the error
  html += '
' + lines.shift() + '
'
    + '
'
    // second line is a location marker
    + lines.shift() + '\n'
    // third through fifth lines are code
    + lines.shift() + '\n'
    + lines.shift() + '\n'
    + lines.shift() + '\n'
    // sixth line is a location marker
    + lines.shift() + '\n'
    + '
'

    + '
'
      + lines.map(function eachLine (line) {
        return '
'
          + line.trim()
            .replace(/^at\s/, '')
            .replace(/\((.*)\)$/, '$1')
          + '
'
      }).join('')
    + '
'

  return html
    + '
'
    + ''
}

internals.logError = function logError (err) {
  var prettyifiedErr = prettyError(err)

  // if any of our custom error parsing fails, don't die
  try {
    // babel errors are really special, so give them custom error handling
    if (err._babel) {
      bs.logger.error(ansiStyleFormat('{red}' + err.toString() + '{reset}'))
      console.error(err.codeFrame)
    }
    else {
      bs.logger.error(prettyifiedErr || err)
    }
  }
  catch (e) {
    console.error(err)
  }
}

internals.sendError = function sendError (err, res) {
  var prettyifiedErr = prettyError(err)

  if (!res.headersSent) {
    res.setHeader('Content-Type', 'text/html')
    res.statusCode = 500
  }

  internals.logError(err)

  try {
    res.end(internals.htmlifyError(prettyifiedErr || err))
  }
  catch (e){
    res.end('
' + err.toString() + err.stack + '
')
  }

  return true
}

internals.serveDefaultPage = function serveDefaultPage (req, res, args) {
  internals.getCustomDefaultHTML(req, args, function gotCustomDefaultHTML (err, html) {
    var src = html || internals.getDefaultHTML(args)

    res.setHeader('Content-Type', 'text/html')

    if (err) internals.sendError(err, res)
    else res.end(src)
  })
}

internals.parseSyncOptions = function parseSyncOptions (opts) {
  if (!opts) return false
  if (typeof opts === 'object') return opts

  return {
    clicks: true
    , location: true
    , forms: true
    , scroll: true
  }
}

internals.getNormalizedPath = function getNormalizedPath (pathStr) {
  if (!pathStr || pathStr.charAt(0) === '/') return pathStr

  return '/' + pathStr
}

internals.responder = function responder (type, res) {
  return function response (err, src) {
    if (err) return void internals.sendError(err, res)

    if (!res.headersSent) res.setHeader('Content-Type', 'text/' + type)
    res.end(src || err)
  }
}

internals.startFileWatch = function startFileWatch (lr, args) {
  var watchedFiles = []
    , addFile = function addFile (file) {
      if (watchedFiles.indexOf(file) < 0){
        watchedFiles.push(file)
        browserSync.watch(file).on('change', function onCSSChanged () {
          browserSync.reload(args.css.alias)
        })
      }
    }

  if (!lr.quiet) {
    js.emitter.on('changed', function onJsChanged (filepath) {
      bs.logger.info('{cyan:File changed: {magenta:%s', path.relative(cwd, filepath))
      browserSync.notify('Compiling, please wait!')
    })
  }

  js.emitter.on('bundle', function onJSBundled (time) {
    if (!lr.quiet) {
      bs.logger.info('{grey:Bundle updated in {magenta:%s', time + 'ms')
    }
    // for JS, just reload the whole page
    browserSync.reload()
  })

  cssFiles.emitter.on('file', addFile)
  lessFiles.emitter.on('file', addFile)
  addFile(args.css.entry)
}

module.exports = function server (args) {
  // sometimes the hostname has a '.local' on it, sometimes it doesn't
  var hostname = args.server.hostname || args.server.h ? os.hostname().replace(/\.local$/, '') + '.local' : 'localhost'

  args.server.url = args.server.url || 'http://' + hostname + ':1337/default'

  var stOptions = args.server.st || {path: cwd, cache: false}
    , mount = st(stOptions)
    , parsedUrl = url.parse(args.server.url)
    , port = args.server.port || parsedUrl.port
    , serverPath = internals.getNormalizedPath(args.server.path || parsedUrl.path)
    , lr = args.server.lr || args.server.l
    , launch = args.server.open || args.server.o
    , handler = args.server.handler || Function()
    , spaMode = args.server.spaMode

  if (args.server.sync || args.server.s) lr = {sync: true}

  args.servePath = stOptions.path

  // the router checks these, so they have to exist
  args.js = args.js || {}
  args.js.alias = internals.getNormalizedPath(args.js.alias || args.js.entry)
  args.css = args.css || {}
  args.css.alias = internals.getNormalizedPath(args.css.alias || args.css.entry)

  baseUrl = parsedUrl.protocol + '//' + parsedUrl.hostname

  // cache the browserify and watchify instances
  js.emitter.on('browserify', function storeBrowserifyInstace (b) {
    internals.browserify = b
  })
  js.emitter.on('watchify', function storeWatchifyInstance (w) {
    internals.watchify = w
  })

  if (lr) {
    // if live reloading, use watchify
    args.js.watch = true
    args.js.output = args.js.output || defaultBundlePath

    lr = typeof lr === 'boolean' ? {} : lr
    lr.patterns = lr.patterns
      ? lr.patterns
      : [path.join(args.servePath, '**/*.html')]

    if (args.css.output) lr.patterns.push(args.css.output)

    lr.port = lr.port || 3000
    lr.sync = internals.parseSyncOptions(lr.sync || lr.s)

    if (port >= lr.port && port <= lr.port + 2) {
      throw new Error('Ports ' + lr.port + ' through ' + (lr.port + 2) + 'in use for Live Reload')
    }

    bs = browserSync.init({
      proxy: {
        target: parsedUrl.hostname + ':' + port
      }
      , port: lr.port
      , injectChanges: true
      , ghostMode: lr.sync
      , notify: !!lr.quiet
      , logSnippet: false
      , open: false
      , logLevel: lr.verbose ? 'debug' : 'info'
      , logFileChanges: !!lr.quiet
      , logConnections: !!lr.quiet
      // don't minify for speed!
      , minify: false
      , startPath: '/default'
      , logPrefix: 'atomify'
      , files: lr.patterns.map(function doNotWatchNodeModules (match) {
        return {
          match: match
          , options: {
            ignored: /node_modules/
          }
        }
      })
    })

    internals.startFileWatch(lr, args)

    // listen for initial bundle completion before opening
    js(args.js).on('end', function onJSBundled () {
      if (launch && bs.options && bs.options.port){
        open(baseUrl + ':' + bs.options.port + serverPath)
      }
    })
  }

  http.createServer(function createServer (req, res) {
    switch (req.url.split('?')[0]) {
      case args.js.alias || args.js.entry:
        if (lr) {
          res.setHeader('Content-Type', 'text/javascript')
          res.end(fs.readFileSync(args.js.output, {encoding: 'utf8'}))
        }
        else {
          js(args.js, internals.responder('javascript', res))
        }
      break

      case args.css.alias || args.css.entry:
        css(args.css, internals.responder('css', res))
      break

      case '/default':
        internals.serveDefaultPage(req, res, args)
      break

      default:
        if (spaMode) internals.serveDefaultPage(req, res, args)
        else if (handler(req, res, args)) return null
        else mount(req, res)
      break
    }
  }).listen(port)

  // if live reload is enabled we open after initial bundling
  if (launch && !lr) open(baseUrl + ':' + port + serverPath)
}

<commit_msg>fix: server: js compilation can now error<commit_after>'use strict'

var st = require('st')
  , http = require('http')
  , path = require('path')
  , url = require('url')
  , fs = require('fs')
  , os = require('os')
  , js = require('atomify-js')
  , css = require('atomify-css')
  , prettyError = require('prettify-error')
  , AnsiToHTML = require('ansi-to-html')
  , ansiStyleFormat = require('style-format')
  , cssFiles = require('atomify-css/css')
  , lessFiles = require('atomify-css/less')
  , open = require('open')
  , browserSync = require('browser-sync').create()
  , defaultBundlePath = path.join(__dirname, '_bundle.js')
  , JS_REPLACE = '__ATOMIFY_JS__'
  , CSS_REPLACE = '__ATOMIFY_CSS__'
  , HTML_HEAD = '<!doctype html>'
    + '<meta charset="utf-8">'
    + '<meta http-equiv="X-UA-Compatible" content="IE=edge">'
    + '<meta name="viewport" content="initial-scale=1,width=device-width,user-scalable=0">'
  , cwd = process.cwd()
  , internals = {}
  , baseUrl
  , bs

internals.getDefaultHTML = function getDefaultHTML (args) {
  var src = HTML_HEAD
  src += '<title>generated by atomify</title>'
  if (args.css.entry) src += '<link rel="stylesheet" href="CSS">'
  src += ''
  src += ''
  src += ''

  src = src.replace('JS', args.js.alias)
  src = src.replace('CSS', args.css.alias)

  return src
}

internals.customDefaultHTML = ''

internals.setCustomDefaultHTML = function setCustomDefaultHTML (file, args) {
  var html = fs.readFileSync(file, {encoding: 'utf8'})
    , shouldReplaceJS = html.indexOf(JS_REPLACE) > -1
    , shouldReplaceCSS = html.indexOf(CSS_REPLACE) > -1

  if (shouldReplaceCSS) html.replace(CSS_REPLACE, args.css.alias)
  else html += '<link rel="stylesheet" href="' + args.css.alias + '">'

  if (shouldReplaceJS) html.replace(JS_REPLACE, args.js.alias)
  else html += ''

  internals.customDefaultHTML = html

  return internals.customDefaultHTML
}

internals.getCustomDefaultHTML = function getCustomDefaultHTML (req, args, callback) {
  var html = args.server.html
    , htmlIsFile = typeof html === 'string'

  // bail early if there is no html option
  if (!html) return void callback(null, null)

  // if the html arg is a string, assume it's a file name
  // if we've already cached this file, don't go read it again
  if (htmlIsFile && html !== internals.customDefaultHTML) {
    callback(null, internals.setCustomDefaultHTML(html, args))
  }
  else if (htmlIsFile){
    callback(null, internals.customDefaultHTML)
  }
  // if the html arg isn't a string, it should be a function that returns html
  else {
    html({js: args.js.alias, css: args.css.alias, request: req.url}, callback)
  }
}

internals.htmlifyBabelError = function htmlifyBabelError (err) {
  var stack = (new AnsiToHTML({
    escapeXML: true
    , fg: '#000'
    , bg: '#fff'
  })).toHtml(err.codeFrame)
    , html = '<!doctype html>'
      + '<meta charset="utf-8">'
      + '<meta http-equiv="X-UA-Compatible" content="IE=edge">'
      + '<meta name="viewport" content="initial-scale=1,width=device-width,user-scalable=0">'
      + '<title>' + err.toString() + '</title>'
      + ''
      + '
'
      + '
' + err.toString() + '
'
      + '
'
      + '
' + stack + '
'
      + ''

  return html
}

internals.htmlifyError = function htmlifyError (err) {
  var lines
    , html

  if (err._babel) return internals.htmlifyBabelError(err)

  lines = (new AnsiToHTML({escapeXML: true})).toHtml(err).split('\n')
  html = '<!doctype html>'
    + '<meta charset="utf-8">'
    + '<meta http-equiv="X-UA-Compatible" content="IE=edge">'
    + '<meta name="viewport" content="initial-scale=1,width=device-width,user-scalable=0">'
    + '<title>' + err.toString() + '</title>'
    + ''
    + '
'

  // first line is the error
  html += '
' + lines.shift() + '
'
    + '
'
    // second line is a location marker
    + lines.shift() + '\n'
    // third through fifth lines are code
    + lines.shift() + '\n'
    + lines.shift() + '\n'
    + lines.shift() + '\n'
    // sixth line is a location marker
    + lines.shift() + '\n'
    + '
'

    + '
'
      + lines.map(function eachLine (line) {
        return '
'
          + line.trim()
            .replace(/^at\s/, '')
            .replace(/\((.*)\)$/, '$1')
          + '
'
      }).join('')
    + '
'

  return html
    + '
'
    + ''
}

internals.logError = function logError (err) {
  var prettyifiedErr = prettyError(err)

  // if any of our custom error parsing fails, don't die
  try {
    // babel errors are really special, so give them custom error handling
    if (err._babel) {
      bs.logger.error(ansiStyleFormat('{red}' + err.toString() + '{reset}'))
      console.error(err.codeFrame)
    }
    else {
      bs.logger.error(prettyifiedErr || err)
    }
  }
  catch (e) {
    console.error(err)
  }
}

internals.sendError = function sendError (err, res) {
  var prettyifiedErr = prettyError(err)

  if (!res.headersSent) {
    res.setHeader('Content-Type', 'text/html')
    res.statusCode = 500
  }

  internals.logError(err)

  try {
    res.end(internals.htmlifyError(prettyifiedErr || err))
  }
  catch (e){
    res.end('
' + err.toString() + err.stack + '
')
  }

  return true
}

internals.serveDefaultPage = function serveDefaultPage (req, res, args) {
  internals.getCustomDefaultHTML(req, args, function gotCustomDefaultHTML (err, html) {
    var src = html || internals.getDefaultHTML(args)

    res.setHeader('Content-Type', 'text/html')

    if (err) internals.sendError(err, res)
    else res.end(src)
  })
}

internals.parseSyncOptions = function parseSyncOptions (opts) {
  if (!opts) return false
  if (typeof opts === 'object') return opts

  return {
    clicks: true
    , location: true
    , forms: true
    , scroll: true
  }
}

internals.getNormalizedPath = function getNormalizedPath (pathStr) {
  if (!pathStr || pathStr.charAt(0) === '/') return pathStr

  return '/' + pathStr
}

internals.responder = function responder (type, res) {
  return function response (err, src) {
    if (err) return void internals.sendError(err, res)

    if (!res.headersSent) res.setHeader('Content-Type', 'text/' + type)
    res.end(src || err)
  }
}

internals.startFileWatch = function startFileWatch (lr, args) {
  var watchedFiles = []
    , addFile = function addFile (file) {
      if (watchedFiles.indexOf(file) < 0){
        watchedFiles.push(file)
        browserSync.watch(file).on('change', function onCSSChanged () {
          browserSync.reload(args.css.alias)
        })
      }
    }

  if (!lr.quiet) {
    js.emitter.on('changed', function onJsChanged (filepath) {
      bs.logger.info('{cyan:File changed: {magenta:%s', path.relative(cwd, filepath))
      browserSync.notify('Compiling, please wait!')
    })
  }

  js.emitter.on('bundle', function onJSBundled (time) {
    if (!lr.quiet) {
      bs.logger.info('{grey:Bundle updated in {magenta:%s', time + 'ms')
    }
    // for JS, just reload the whole page
    browserSync.reload()
  })

  cssFiles.emitter.on('file', addFile)
  lessFiles.emitter.on('file', addFile)
  addFile(args.css.entry)
}

module.exports = function server (args) {
  // sometimes the hostname has a '.local' on it, sometimes it doesn't
  var hostname = args.server.hostname || args.server.h ? os.hostname().replace(/\.local$/, '') + '.local' : 'localhost'

  args.server.url = args.server.url || 'http://' + hostname + ':1337/default'

  var stOptions = args.server.st || {path: cwd, cache: false}
    , mount = st(stOptions)
    , parsedUrl = url.parse(args.server.url)
    , port = args.server.port || parsedUrl.port
    , serverPath = internals.getNormalizedPath(args.server.path || parsedUrl.path)
    , lr = args.server.lr || args.server.l
    , launch = args.server.open || args.server.o
    , handler = args.server.handler || Function()
    , spaMode = args.server.spaMode

  if (args.server.sync || args.server.s) lr = {sync: true}

  args.servePath = stOptions.path

  // the router checks these, so they have to exist
  args.js = args.js || {}
  args.js.alias = internals.getNormalizedPath(args.js.alias || args.js.entry)
  args.css = args.css || {}
  args.css.alias = internals.getNormalizedPath(args.css.alias || args.css.entry)

  baseUrl = parsedUrl.protocol + '//' + parsedUrl.hostname

  // cache the browserify and watchify instances
  js.emitter.on('browserify', function storeBrowserifyInstace (b) {
    internals.browserify = b
  })
  js.emitter.on('watchify', function storeWatchifyInstance (w) {
    internals.watchify = w
  })

  if (lr) {
    // if live reloading, use watchify
    args.js.watch = true
    args.js.output = args.js.output || defaultBundlePath

    lr = typeof lr === 'boolean' ? {} : lr
    lr.patterns = lr.patterns
      ? lr.patterns
      : [path.join(args.servePath, '**/*.html')]

    if (args.css.output) lr.patterns.push(args.css.output)

    lr.port = lr.port || 3000
    lr.sync = internals.parseSyncOptions(lr.sync || lr.s)

    if (port >= lr.port && port <= lr.port + 2) {
      throw new Error('Ports ' + lr.port + ' through ' + (lr.port + 2) + 'in use for Live Reload')
    }

    bs = browserSync.init({
      proxy: {
        target: parsedUrl.hostname + ':' + port
      }
      , port: lr.port
      , injectChanges: true
      , ghostMode: lr.sync
      , notify: !!lr.quiet
      , logSnippet: false
      , open: false
      , logLevel: lr.verbose ? 'debug' : 'info'
      , logFileChanges: !!lr.quiet
      , logConnections: !!lr.quiet
      // don't minify for speed!
      , minify: false
      , startPath: '/default'
      , logPrefix: 'atomify'
      , files: lr.patterns.map(function doNotWatchNodeModules (match) {
        return {
          match: match
          , options: {
            ignored: /node_modules/
          }
        }
      })
    })

    internals.startFileWatch(lr, args)

    // listen for initial bundle completion before opening
    js(args.js, function onJSError (err) {
      if (err) internals.logError(err)
    }).on('end', function onJSBundled () {
      if (launch && bs.options && bs.options.port){
        open(baseUrl + ':' + bs.options.port + serverPath)
      }
    })
  }

  http.createServer(function createServer (req, res) {
    switch (req.url.split('?')[0]) {
      case args.js.alias || args.js.entry:
        if (lr) {
          res.setHeader('Content-Type', 'text/javascript')
          res.end(fs.readFileSync(args.js.output, {encoding: 'utf8'}))
        }
        else {
          js(args.js, internals.responder('javascript', res))
        }
      break

      case args.css.alias || args.css.entry:
        css(args.css, internals.responder('css', res))
      break

      case '/default':
        internals.serveDefaultPage(req, res, args)
      break

      default:
        if (spaMode) internals.serveDefaultPage(req, res, args)
        else if (handler(req, res, args)) return null
        else mount(req, res)
      break
    }
  }).listen(port)

  // if live reload is enabled we open after initial bundling
  if (launch && !lr) open(baseUrl + ':' + port + serverPath)
}

<|endoftext|>


<commit_before>
var StringUtilities = {
	getFirstInternVowel: function(word){
		vowels = word.substring(1).match(new RegExp('[AEIOU]'));
		return vowels ? vowels[0] : 'X';
	},
	getFirstInternConsonant: function(word){
		vowels = word.substring(1).match(new RegExp('[BCDFGHJKLMNPQRSTUVWXYZ]'));
		return vowels ? vowels[0] : 'X';
	},
	clearString: function(word) {

		cleanWord = word.trim();
		cleanword.replace(/\s/g,' ');
		return cleanWord.toUpperCase();
	}
}

var mxk = {

	getCURP: 		function(name, surnameFather, surnameMother, bornDay, bornMonth, bornYear, bornState, gender) {

							name 	= StringUtilities.clearString(name);
							surnameFather = StringUtilities.clearString(surnameFather);
							surnameMother = StringUtilities.clearString(surnameMother);
							bornDay =		StringUtilities.clearString(bornDay);
							bornMonth =		StringUtilities.clearString(bornMonth);
							bornYear =		StringUtilities.clearString(bornYear);

							curp = this.getCommonPart(name, surnameFather, surnameMother, bornDay, bornMonth, bornYear);
							curp += this.getGenderLetter(gender);
							curp += this.getBornStateCode(bornState);
							curp += StringUtilities.getFirstInternConsonant(surnameFather);
							curp += StringUtilities.getFirstInternConsonant(surnameMother);
							curp += StringUtilities.getFirstInternConsonant(name);

							curp += this.getSpecialChar(bornYear);

							return curp;

					},

	getCommonPart: 	function(name, surnameFather, surnameMother, bornDay, bornMonth, bornYear) {

							commonPart = surnameFather[0];
							commonPart += StringUtilities.getFirstInternVowel(surnameFather);
							commonPart += surnameMother[0];
							commonPart += name[0];

							commonPart += bornYear.substring(2);
							commonPart += bornMonth;
							commonPart += bornDay;
							 return commonPart;
					},
	getBornStateCode: function(idState){
						return this.states[idState].code;
					},
	getGenderLetter: function(idGender){
						return idGender == 1 ? 'H' : 'M';
					},
	getSpecialChar: function(bornYear){
						if(bornYear[0] == '1') {
							return '0';
						} else {
							return 'A';
						}
					},
	removeCommonNames: function(name) {

						if(name.indexOf(' ')){
							separatedNames 	= name.split(' ');
							firstName 		= separatedNames[0];
							if(firstName in notAcceptedNames) {
								return separatedNames[1];
							}
						}

					},
	states: new Array(
				{name: "AGUASCALIENTES" , code: "AS"}, //1
				{name: "BAJA CALIFORNIA" , code: "BC"},
				{name: "BAJA CALIFORNIA SUR" , code: "BS"},
				{name: "CAMPECHE" , code: "CC"},
				{name: "COAHUILA" , code: "CL"},
				{name: "COLIMA" , code: "CM"},
				{name: "CHIAPAS" , code: "CS"},
				{name: "CHIHUAHUA" , code: "CH"},
				{name: "DISTRITO FEDERAL" , code: "DF"},
				{name: "DURANGO" , code: "DG"},
				{name: "GUANAJUATO" , code: "GT"},
				{name: "GUERRERO" , code: "GR"},
				{name: "HIDALGO" , code: "HG"},
				{name: "JALISCO" , code: "JC"},
				{name: "MÉXICO" , code: "MC"},
				{name: "MICHOACÁN" , code: "MN"},
				{name: "MORELOS" , code: "MS"},
				{name: "NAYARIT" , code: "NT"},
				{name: "NUEVO LEÓN", code: "NL"},
				{name: "OAXACA" , code: "OC"},
				{name: "PUEBLA" , code: "PL"},
				{name: "QUERÉTARO" , code: "QT"},
				{name: "QUINTANA ROO" , code: "QR"},
				{name: "SAN LUIS POTOSÍ" , code: "SP"},
				{name: "SINALOA" , code: "SL"},
				{name: "SONORA" , code: "SR"},
				{name: "TABASCO" , code: "TC"},
				{name: "TAMAULIPAS" , code: "TS"},
				{name: "TLAXCALA" , code: "TL"},
				{name: "VERACRUZ" , code: "VZ"},
				{name: "YUCATÁN" , code: "YN"},
				{name: "ZACATECAS" , code: "ZS"} //32
				)

}<commit_msg>common names finished, not tested<commit_after>
var StringUtilities = {
	getFirstInternVowel: function(word){
		vowels = word.substring(1).match(new RegExp('[AEIOU]'));
		return vowels ? vowels[0] : 'X';
	},
	getFirstInternConsonant: function(word){
		vowels = word.substring(1).match(new RegExp('[BCDFGHJKLMNPQRSTUVWXYZ]'));
		return vowels ? vowels[0] : 'X';
	},
	clearString: function(word) {

		cleanWord = word.trim();
		cleanword.replace(/\s/g,' ');
		return cleanWord.toUpperCase();
	},
	removeAccents: function(word)
	{
		accents = //todo
	}

}

var mxk = {

	getCURP: 		function(name, surnameFather, surnameMother, bornDay, bornMonth, bornYear, bornState, gender) {

							name 	= StringUtilities.clearString(name);
							surnameFather = StringUtilities.clearString(surnameFather);
							surnameMother = StringUtilities.clearString(surnameMother);
							bornDay =		StringUtilities.clearString(bornDay);
							bornMonth =		StringUtilities.clearString(bornMonth);
							bornYear =		StringUtilities.clearString(bornYear);

							curp = this.getCommonPart(name, surnameFather, surnameMother, bornDay, bornMonth, bornYear);
							curp += this.getGenderLetter(gender);
							curp += this.getBornStateCode(bornState);
							curp += StringUtilities.getFirstInternConsonant(surnameFather);
							curp += StringUtilities.getFirstInternConsonant(surnameMother);
							curp += StringUtilities.getFirstInternConsonant(name);

							curp += this.getSpecialChar(bornYear);

							return curp;

					},

	getCommonPart: 	function(name, surnameFather, surnameMother, bornDay, bornMonth, bornYear) {

							commonPart = surnameFather[0];
							commonPart += StringUtilities.getFirstInternVowel(surnameFather);
							commonPart += surnameMother[0];
							commonPart += name[0];

							commonPart += bornYear.substring(2);
							commonPart += bornMonth;
							commonPart += bornDay;
							 return commonPart;
					},
	getBornStateCode: function(idState){
						return this.states[idState].code;
					},
	getGenderLetter: function(idGender){
						return idGender == 1 ? 'H' : 'M';
					},
	getSpecialChar: function(bornYear){
						if(bornYear[0] == '1') {
							return '0';
						} else {
							return 'A';
						}
					},
	removeCommonNames: function(name) {
						this.notAcceptedNames.forEach(
							function(notAccepted){
								name = name.replace(new RegExp('^' + notAccepted,g),'');
							}
							);

						return name;
					},
	states: new Array(
				{name: "AGUASCALIENTES" , code: "AS"}, //1
				{name: "BAJA CALIFORNIA" , code: "BC"},
				{name: "BAJA CALIFORNIA SUR" , code: "BS"},
				{name: "CAMPECHE" , code: "CC"},
				{name: "COAHUILA" , code: "CL"},
				{name: "COLIMA" , code: "CM"},
				{name: "CHIAPAS" , code: "CS"},
				{name: "CHIHUAHUA" , code: "CH"},
				{name: "DISTRITO FEDERAL" , code: "DF"},
				{name: "DURANGO" , code: "DG"},
				{name: "GUANAJUATO" , code: "GT"},
				{name: "GUERRERO" , code: "GR"},
				{name: "HIDALGO" , code: "HG"},
				{name: "JALISCO" , code: "JC"},
				{name: "MÉXICO" , code: "MC"},
				{name: "MICHOACÁN" , code: "MN"},
				{name: "MORELOS" , code: "MS"},
				{name: "NAYARIT" , code: "NT"},
				{name: "NUEVO LEÓN", code: "NL"},
				{name: "OAXACA" , code: "OC"},
				{name: "PUEBLA" , code: "PL"},
				{name: "QUERÉTARO" , code: "QT"},
				{name: "QUINTANA ROO" , code: "QR"},
				{name: "SAN LUIS POTOSÍ" , code: "SP"},
				{name: "SINALOA" , code: "SL"},
				{name: "SONORA" , code: "SR"},
				{name: "TABASCO" , code: "TC"},
				{name: "TAMAULIPAS" , code: "TS"},
				{name: "TLAXCALA" , code: "TL"},
				{name: "VERACRUZ" , code: "VZ"},
				{name: "YUCATÁN" , code: "YN"},
				{name: "ZACATECAS" , code: "ZS"} //32
				),
	notAcceptedNames: new Array(
		'MARIA ',
		'MARIA DE LOS '
		'JOSE ',
		'JOSÉ DE ',
		'MA. ',
		'MA ',
		'J ',
		'J. '
		)

}<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var express = require('express');
var http = require('http');
var path = require('path');
var handlebars = require('express3-handlebars')
var mongoose = require('mongoose');

var addACourse = require('./routes/addACourse');
var index = require('./routes/index');
var add = require ('./routes/add');
var viewAssignments = require('./routes/viewAssignments');
var info = require('./routes/info');
var viewCourses = require('./routes/viewCourses');
var addCourse = require ('./routes/addCourse');
var editCourse = require ('./routes/editCourse');
var login = require ('./routes/login');
var signup = require('./routes/signup');
var course = require('./routes/course');
var assignment = require('./routes/assignment');

// Example route
// var user = require('./routes/user');

// Connect to the Mongo database, whether locally or on Heroku
// MAKE SURE TO CHANGE THE NAME FROM 'lab7' TO ... IN OTHER PROJECTS
var local_database_name = 'project';
var local_database_uri  = 'mongodb://localhost/' + local_database_name
var database_uri = process.env.MONGOLAB_URI || local_database_uri
mongoose.connect(database_uri);

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', handlebars());
app.set('view engine', 'handlebars');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('Intro HCI secret key'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

// ADD ROUTES HERE
    //Routes we definitely use
app.get('/',login.view);

    //Do we use these?
app.get('/add',add.addAssignment);
app.get('/viewAssignments',viewAssignments.view);
app.get('/info',info.view);
app.get('/viewCourses',viewCourses.view);
app.post('/addCourse',addCourse.add);
app.get('/addACourse',addACourse.view);
app.get('/editCourse',editCourse.view);
app.get('/index',index.view)
app.post('/login',login.checkUsername);
app.get('/signup',function(req, res) {
	res.render('signup');
});
app.get('/courses/:id/syllabus', course.viewCourseInfo);
app.get('/course/:courseName', viewCourses.viewCoursePage);

app.post('/signup',signup.signIn);
app.post('/editCourse',editCourse.addSyllabusFields)
app.post('/addACourse/new',course.add);

app.post('/signup/check/username', function(req, res) {
  var username = req.body.username;
  // check if username contains non-url-safe characters
  if (username !== encodeURIComponent(username)) {
    res.json(403, {
      invalidChars: true
    });
    return;
  }
  // check if username is already taken - query your db here
  var usernameTaken = false;
  for (var i = 0; i < dummyDb.length; i++) {
    if (dummyDb[i].username === username) {
      usernameTaken = true;
      break;
    }
  }
  if (usernameTaken) {
    res.json(403, {
      isTaken: true
    });
    return
  }
  // looks like everything is fine
  res.send(200);
});
// Example route
// app.get('/users', user.list);

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
<commit_msg>functionality notes<commit_after>
/**
 * Module dependencies.
 */

var express = require('express');
var http = require('http');
var path = require('path');
var handlebars = require('express3-handlebars')
var mongoose = require('mongoose');

var addACourse = require('./routes/addACourse');
var index = require('./routes/index');
var add = require ('./routes/add');
var viewAssignments = require('./routes/viewAssignments');
var info = require('./routes/info');
var viewCourses = require('./routes/viewCourses');
var addCourse = require ('./routes/addCourse');
var editCourse = require ('./routes/editCourse');
var login = require ('./routes/login');
var signup = require('./routes/signup');
var course = require('./routes/course');
var assignment = require('./routes/assignment');

// Example route
// var user = require('./routes/user');

// Connect to the Mongo database, whether locally or on Heroku
// MAKE SURE TO CHANGE THE NAME FROM 'lab7' TO ... IN OTHER PROJECTS
var local_database_name = 'project';
var local_database_uri  = 'mongodb://localhost/' + local_database_name
var database_uri = process.env.MONGOLAB_URI || local_database_uri
mongoose.connect(database_uri);

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', handlebars());
app.set('view engine', 'handlebars');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('Intro HCI secret key'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

// ADD ROUTES HERE
    //Routes we definitely use
app.get('/',login.view);
app.get('/signup',function(req, res) {
  res.render('signup');
});
app.post('/signup',signup.signIn);

// i think we should change the name of these and/or consolidate them
app.get('/add',add.addAssignment);
app.post('/editCourse',editCourse.addSyllabusFields);
app.get('/viewAssignments',viewAssignments.view);

    //Do we use these?

app.get('/info',info.view);
app.get('/viewCourses',viewCourses.view);
app.post('/addCourse',addCourse.add);
app.get('/addACourse',addACourse.view);
app.get('/editCourse',editCourse.view);
app.get('/index',index.view)
app.post('/login',login.checkUsername);

app.get('/courses/:id/syllabus', course.viewCourseInfo);
app.get('/course/:courseName', viewCourses.viewCoursePage);

app.post('/addACourse/new',course.add);

app.post('/signup/check/username', function(req, res) {
  var username = req.body.username;
  // check if username contains non-url-safe characters
  if (username !== encodeURIComponent(username)) {
    res.json(403, {
      invalidChars: true
    });
    return;
  }
  // check if username is already taken - query your db here
  var usernameTaken = false;
  for (var i = 0; i < dummyDb.length; i++) {
    if (dummyDb[i].username === username) {
      usernameTaken = true;
      break;
    }
  }
  if (usernameTaken) {
    res.json(403, {
      isTaken: true
    });
    return
  }
  // looks like everything is fine
  res.send(200);
});
// Example route
// app.get('/users', user.list);

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
<|endoftext|>


<commit_before>var colors = require('colors');
var github = require('./github.js');
var http = require('http');
var http_proxy = require('http-proxy');
var mimelib = require("mimelib-noiconv");
var semver = require('semver');

var exposed, versionData;

var handle200 = function(res, data) {
  res.writeHead(200);
  res.write(data);
  res.end();
};

var handle404 = function(res, data) {
  res.writeHead(404);
  res.write(data);
  res.end();
};

var handleRequest = function(req, res, proxy) {
  var urlMatch = req.url.match(/\/([^\/]*)\/?([^\/]*)?/);
  var project = urlMatch[1];
  var version = urlMatch[2];
  if ((req.method == 'GET' && project) && (Object.keys(versionData).indexOf(project) > -1 || version == 'latest') ) {
    if (version) {
      if (versionData[project].versions && Object.keys(versionData[project].versions).indexOf(version) > -1) {
        exposed._handle200(res, JSON.stringify(
          versionData[project].versions[version]
        ));
      } else if (version == 'latest') {
        exposed._handle200(res, JSON.stringify(
          getInfoLatestVersion(versionData[project])
        ));
      } else {
        exposed._handle404(res, 'depository: Package not found.');
      }
    } else {
      exposed._handle200(res, JSON.stringify(
        versionData[project]
      ));
    }
  } else {
    // just proxy to npmjs
    req.headers.host = 'registry.npmjs.org'
    proxy.proxyRequest(req, res, {
      host: 'registry.npmjs.org',
      port: 80
    });
  }
};

var server = http_proxy.createServer(handleRequest);
server.proxy.on('end', function(req, res) {
  console.log('Served package from: '.green + req.url.magenta);
});

var init = function(config, callback) {

  var getInfo = function(repos, callback) {
    if(repos.length == 0) {
      versionData = {};
      callback(null, versionData, server);
    } else {
      github.getInfo(repos, function(err, data) {
        versionData = prepareVersionsForNpm(data);
        callback(err, versionData, server);
      });
    }
  };

  // grab version information from github
  github.init(config.username, config.password);
  if (! config.repos) {
    if (config.queryAll) {
      github.getAllRepos(function(err, repos) {
        if (err) {
          callback(err);
        } else {
          getInfo(repos, callback);
        }
      });
    } else {
      github.getWatchedRepos(function(err, repos) {
        if (err) {
          callback(err);
        } else {
          getInfo(repos, callback);
        }
      });
    }
  } else {
    getInfo(config.repos, callback);
  }

};

var setupServer = function(config, callback) {
  init(config, callback);
};

var prepareVersionsForNpm = function(versionData) {
  var latestVersion, latestVersionData, projectName, projectVersions;
  var retData = {};
  for (projectName in versionData) {
    projectVersions = versionData[projectName];
    projectVersions = Object.keys(projectVersions).sort(function(a, b) {
      return semver.lt(a, b) ? 1 : -1;
    });
    latestVersion = projectVersions[0];
    latestVersionData = versionData[projectName][latestVersion] || {};
    latestVersionData.maintainers = latestVersionData.maintainers || [];
    var latestMaintainers = latestVersionData.maintainers.map(function(address) {
      var parsedAddress = mimelib.parseAddresses(address);
      return {
        email: parsedAddress[0].address,
        name: parsedAddress[0].name
      }
    });
    retData[projectName] = {
      _id: latestVersionData.name,
      name: latestVersionData.name,
      'dist-tags': {
        latest: latestVersion
      },
      versions: versionData[projectName],
      maintainers: latestMaintainers
    };
  }
  return retData;
};

var getInfoLatestVersion = function(projectData) {
  projectData = projectData ||{};
  var latestVersion = projectData['dist-tags'] ? projectData['dist-tags'].latest : null;
  return projectData.versions ? projectData.versions[latestVersion] : {};
};

exposed = module.exports = {
  _handle200: handle200,
  _handle404: handle404,
  _handleRequest: handleRequest,
  _versionData: versionData,
  getInfoLatestVersion: getInfoLatestVersion,
  init: init,
  prepareVersionsForNpm: prepareVersionsForNpm,
  setup: setupServer
};
<commit_msg>Add more logging details<commit_after>var colors = require('colors');
var github = require('./github.js');
var http = require('http');
var http_proxy = require('http-proxy');
var mimelib = require("mimelib-noiconv");
var semver = require('semver');

var exposed, versionData;

var handle200 = function(res, data) {
  res.writeHead(200);
  res.write(data);
  res.end();
};

var handle404 = function(res, data) {
  res.writeHead(404);
  res.write(data);
  res.end();
};

var handleRequest = function(req, res, proxy) {
  var urlMatch = req.url.match(/\/([^\/]*)\/?([^\/]*)?/);
  var project = urlMatch[1];
  var version = urlMatch[2];
  if ((req.method == 'GET' && project) && (Object.keys(versionData).indexOf(project) > -1 || version == 'latest') ) {
    console.log(
      'Serving package from GitHub ('.green +
      versionData[project]._github.green + ') as: '.green +
      req.url.magenta
    );
    if (version) {
      if (versionData[project].versions && Object.keys(versionData[project].versions).indexOf(version) > -1) {
        exposed._handle200(res, JSON.stringify(
          versionData[project].versions[version]
        ));
      } else if (version == 'latest') {
        exposed._handle200(res, JSON.stringify(
          getInfoLatestVersion(versionData[project])
        ));
      } else {
        exposed._handle404(res, 'depository: Package not found.');
      }
    } else {
      exposed._handle200(res, JSON.stringify(
        versionData[project]
      ));
    }
  } else {
    // just proxy to npmjs
    req.headers.host = 'registry.npmjs.org'
    proxy.proxyRequest(req, res, {
      host: 'registry.npmjs.org',
      port: 80
    });
  }
};

var server = http_proxy.createServer(handleRequest);
server.proxy.on('end', function(req, res) {
  console.log('Serving package from "registry.npmjs.org": '.green + req.url.magenta);
});

var init = function(config, callback) {

  var getInfo = function(repos, callback) {
    if(repos.length == 0) {
      versionData = {};
      callback(null, versionData, server);
    } else {
      github.getInfo(repos, function(err, data) {
        versionData = prepareVersionsForNpm(data);
        callback(err, versionData, server);
      });
    }
  };

  // grab version information from github
  github.init(config.username, config.password);
  if (! config.repos) {
    if (config.queryAll) {
      github.getAllRepos(function(err, repos) {
        if (err) {
          callback(err);
        } else {
          getInfo(repos, callback);
        }
      });
    } else {
      github.getWatchedRepos(function(err, repos) {
        if (err) {
          callback(err);
        } else {
          getInfo(repos, callback);
        }
      });
    }
  } else {
    getInfo(config.repos, callback);
  }

};

var setupServer = function(config, callback) {
  init(config, callback);
};

var prepareVersionsForNpm = function(versionData) {
  var latestVersion, latestVersionData, projectName, projectVersions;
  var retData = {};
  for (projectName in versionData) {
    projectVersions = versionData[projectName];
    projectVersions = Object.keys(projectVersions).sort(function(a, b) {
      return semver.lt(a, b) ? 1 : -1;
    });
    latestVersion = projectVersions[0];
    latestVersionData = versionData[projectName][latestVersion] || {};
    latestVersionData.maintainers = latestVersionData.maintainers || [];
    var latestMaintainers = latestVersionData.maintainers.map(function(address) {
      var parsedAddress = mimelib.parseAddresses(address);
      return {
        email: parsedAddress[0].address,
        name: parsedAddress[0].name
      }
    });
    retData[projectName] = {
      _id: latestVersionData.name,
      _github: latestVersionData.__github,
      name: latestVersionData.name,
      'dist-tags': {
        latest: latestVersion
      },
      versions: versionData[projectName],
      maintainers: latestMaintainers
    };
  }
  return retData;
};

var getInfoLatestVersion = function(projectData) {
  projectData = projectData ||{};
  var latestVersion = projectData['dist-tags'] ? projectData['dist-tags'].latest : null;
  return projectData.versions ? projectData.versions[latestVersion] : {};
};

exposed = module.exports = {
  _handle200: handle200,
  _handle404: handle404,
  _handleRequest: handleRequest,
  _versionData: versionData,
  getInfoLatestVersion: getInfoLatestVersion,
  init: init,
  prepareVersionsForNpm: prepareVersionsForNpm,
  setup: setupServer
};
<|endoftext|>


<commit_before>/*
** Copyright 2013 Google Inc.
**
** 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.
*/

define(
['config', 'bigl', 'validate', 'stapes', 'googlemaps', 'sv_svc'],
function(config, L, validate, Stapes, GMaps, sv_svc) {
  var StreetViewModule = Stapes.subclass({

    // street view horizontal field of view per zoom level
    // varies per render mode
    SV_HFOV_TABLES: {
      "webgl": [
        127,
        90,
        53.5,
        28.125,
        14.25
      ],
      "html4": [
        180,
        90,
        45,
        22.5,
        11.25
      ],
      "html5": [
        127,
        90,
        53.5,
        28.125,
        14.25
      ],
      "flash": [
        180,
        90,
        45,
        22.5,
        11.25
      ]
    },

    constructor: function($canvas, master) {
      this.$canvas = $canvas;
      this.master = master;
      this.map = null;
      this.streetview = null;
      this.meta = null;
      this.pov = null;
      this.mode = config.display.mode;
      this.zoom = config.display.zoom;
      this.fov_table = this.SV_HFOV_TABLES[this.mode];
      this.hfov = this.fov_table[this.zoom];
      this.vfov = null;
    },

    // PUBLIC

    // *** init()
    // should be called once when ready to set Maps API into motion
    init: function() {
      console.debug('StreetView: init');

      var self = this;

      // *** ensure success of Maps API load
      if (typeof GMaps === 'undefined') L.error('Maps API not loaded!');

      // *** initial field-of-view
      this._resize();

      // *** create a local streetview query object
      this.sv_svc = new GMaps.StreetViewService();

      // *** options for the map object
      // the map will never be seen, but we can still manipulate the experience
      // with these options.
      var mapOptions = {
        disableDefaultUI: true,
        center: new GMaps.LatLng(45,45),
        backgroundColor: "black",
        zoom: 8
      };

      // *** options for the streetview object
      var svOptions = {
        visible: true,
        disableDefaultUI: true,
        scrollwheel: false
      };

      // *** only show links on the master display
      if (this.master && config.display.show_links) {
        svOptions.linksControl = true;
      }

      // *** init map object
      this.map = new GMaps.Map(
        this.$canvas,
        mapOptions
      );

      // *** init streetview object
      this.streetview = new GMaps.StreetViewPanorama(
        this.$canvas,
        svOptions
      );

      // *** init streetview pov
      this.streetview.setPov({
        heading: 0,
        pitch: 0,
        zoom: this.zoom
      });

      // *** set the display mode as specified in global configuration
      this.streetview.setOptions({ mode: this.mode });

      // *** apply the custom streetview object to the map
      this.map.setStreetView( this.streetview );

      // *** events for master only
      if (this.master) {
        // *** handle view change events from the streetview object
        GMaps.event.addListener(this.streetview, 'pov_changed', function() {
          var pov = self.streetview.getPov();

          self._broadcastPov(pov);
          self.pov = pov;
        });

        // *** handle pano change events from the streetview object
        GMaps.event.addListener(this.streetview, 'pano_changed', function() {
          var panoid = self.streetview.getPano();

          if (panoid != self.pano) {
            self._broadcastPano(panoid);
            self.pano = panoid;
          }
        });
      }

      // *** disable <a> tags at the bottom of the canvas
      GMaps.event.addListenerOnce(this.map, 'idle', function() {
        var links = self.$canvas.getElementsByTagName("a");
        var len = links.length;
        for (var i = 0; i < len; i++) {
          links[i].style.display = 'none';
          links[i].onclick = function() {return(false);};
        }
      });

      // *** request the last known state from the server
      this.on('ready', function() {
        self.emit('refresh');
      });

      // *** wait for an idle event before reporting module readiness
      GMaps.event.addListenerOnce(this.map, 'idle', function() {
        console.debug('StreetView: ready');
        self.emit('ready');
      });

      // *** handle window resizing
      window.addEventListener('resize',  function() {
        self._resize();
      });
    },

    // *** setPano(panoid)
    // switch to the provided pano, immediately
    setPano: function(panoid) {
      if (!validate.panoid(panoid)) {
        L.error('StreetView: bad panoid to setPano!');
        return;
      }

      if (panoid != this.streetview.getPano()) {
        var pov = this.streetview.getPov();
        pov.pitch = 0;
        pov.zoom = this.zoom;
        this.pano = panoid;
        this.streetview.setPano(panoid);
        this.setPov(pov);
      } else {
        console.warn('StreetView: ignoring redundant setPano');
      }
    },

    // *** setPov(GMaps.StreetViewPov)
    // set the view to the provided pov, immediately
    setPov: function(pov) {
      if (!validate.number(pov.heading) || !validate.number(pov.pitch)) {
        L.error('StreetView: bad pov to setPov!');
        return;
      }

      this.streetview.setPov(pov);
    },

    // *** setHdg(heading)
    // set just the heading of the POV, zero the pitch
    setHdg: function(heading) {
      if (!validate.number(heading)) {
        L.error('StreetView: bad heading to setHdg!');
        return;
      }

      this.setPov({ heading: heading, pitch: 0 });
    },

    // *** translatePov({yaw, pitch})
    // translate the view by a relative pov
    translatePov: function(abs) {
      if (!validate.number(abs.yaw) || !validate.number(abs.pitch)) {
        L.error('StreetView: bad abs to translatePov!');
        return;
      }

      var pov = this.streetview.getPov();

      pov.heading += abs.yaw;
      pov.pitch   += abs.pitch;

      this.streetview.setPov(pov);
    },

    // *** moveForward()
    // move to the pano nearest the current heading
    moveForward: function() {
      console.log('moving forward');
      var forward = this._getForwardLink();
      if(forward) {
        this.setPano(forward.pano);
        this._broadcastPano(forward.pano);
      } else {
        console.log("can't move forward, no links!");
      }
    },

    // PRIVATE

    // *** _resize()
    // called when the canvas size has changed
    _resize: function() {
      var screenratio = window.innerHeight / window.innerWidth;
      this.vfov = this.hfov * screenratio;
      this.emit('size_changed', {hfov: this.hfov, vfov: this.vfov});
      console.debug('StreetView: resize', this.hfov, this.vfov);
    },

    // *** _broadcastPov(GMaps.StreetViewPov)
    // report a pov change to listeners
    _broadcastPov: function(pov) {
      this.emit('pov_changed', pov);
    },

    // *** _broadcastPano(panoid)
    // report a pano change to listeners
    _broadcastPano: function(panoid) {
      this.emit('pano_changed', panoid);

      var self = this;
      sv_svc.getPanoramaById(
        panoid,
        function (data, stat) {
          if (stat == GMaps.StreetViewStatus.OK) {
            sv_svc.serializePanoData(data);
            self.emit('meta', data);
          }
        }
      );
    },

    // *** _getLinkDifference(
    //                         GMaps.StreetViewPov,
    //                         GMaps.StreetViewLink
    //                       )
    // return the difference between the current heading and the provided link
    _getLinkDifference: function(pov, link) {
      var pov_heading = pov.heading;
      var link_heading = link.heading;

      var diff = Math.abs(link_heading - pov_heading) % 360;

      return diff >= 180 ? diff - (diff - 180) * 2 : diff;
    },

    // *** _getForwardLink()
    // return the link nearest the current heading
    _getForwardLink: function() {
      var pov = this.streetview.getPov();
      var links = this.streetview.getLinks();
      var len = links.length;
      var nearest = null;
      var nearest_difference = 360;

      for(var i=0; i<len; i++) {
        var link = links[i];
        var difference = this._getLinkDifference(pov, link);
        console.log(difference, link);
        if (difference < nearest_difference) {
          nearest = link;
          nearest_difference = difference;
        }
      }

      return nearest;
    }
  });

  return StreetViewModule;
});
<commit_msg>disable pitch enforcement due to presence of multi-row systems<commit_after>/*
** Copyright 2013 Google Inc.
**
** 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.
*/

define(
['config', 'bigl', 'validate', 'stapes', 'googlemaps', 'sv_svc'],
function(config, L, validate, Stapes, GMaps, sv_svc) {
  var StreetViewModule = Stapes.subclass({

    // street view horizontal field of view per zoom level
    // varies per render mode
    SV_HFOV_TABLES: {
      "webgl": [
        127,
        90,
        53.5,
        28.125,
        14.25
      ],
      "html4": [
        180,
        90,
        45,
        22.5,
        11.25
      ],
      "html5": [
        127,
        90,
        53.5,
        28.125,
        14.25
      ],
      "flash": [
        180,
        90,
        45,
        22.5,
        11.25
      ]
    },

    constructor: function($canvas, master) {
      this.$canvas = $canvas;
      this.master = master;
      this.map = null;
      this.streetview = null;
      this.meta = null;
      this.pov = null;
      this.mode = config.display.mode;
      this.zoom = config.display.zoom;
      this.fov_table = this.SV_HFOV_TABLES[this.mode];
      this.hfov = this.fov_table[this.zoom];
      this.vfov = null;
    },

    // PUBLIC

    // *** init()
    // should be called once when ready to set Maps API into motion
    init: function() {
      console.debug('StreetView: init');

      var self = this;

      // *** ensure success of Maps API load
      if (typeof GMaps === 'undefined') L.error('Maps API not loaded!');

      // *** initial field-of-view
      this._resize();

      // *** create a local streetview query object
      this.sv_svc = new GMaps.StreetViewService();

      // *** options for the map object
      // the map will never be seen, but we can still manipulate the experience
      // with these options.
      var mapOptions = {
        disableDefaultUI: true,
        center: new GMaps.LatLng(45,45),
        backgroundColor: "black",
        zoom: 8
      };

      // *** options for the streetview object
      var svOptions = {
        visible: true,
        disableDefaultUI: true,
        scrollwheel: false
      };

      // *** only show links on the master display
      if (this.master && config.display.show_links) {
        svOptions.linksControl = true;
      }

      // *** init map object
      this.map = new GMaps.Map(
        this.$canvas,
        mapOptions
      );

      // *** init streetview object
      this.streetview = new GMaps.StreetViewPanorama(
        this.$canvas,
        svOptions
      );

      // *** init streetview pov
      this.streetview.setPov({
        heading: 0,
        pitch: 0,
        zoom: this.zoom
      });

      // *** set the display mode as specified in global configuration
      this.streetview.setOptions({ mode: this.mode });

      // *** apply the custom streetview object to the map
      this.map.setStreetView( this.streetview );

      // *** events for master only
      if (this.master) {
        // *** handle view change events from the streetview object
        GMaps.event.addListener(this.streetview, 'pov_changed', function() {
          var pov = self.streetview.getPov();

          self._broadcastPov(pov);
          self.pov = pov;
        });

        // *** handle pano change events from the streetview object
        GMaps.event.addListener(this.streetview, 'pano_changed', function() {
          var panoid = self.streetview.getPano();

          if (panoid != self.pano) {
            self._broadcastPano(panoid);
            self.pano = panoid;
          }
        });
      }

      // *** disable <a> tags at the bottom of the canvas
      GMaps.event.addListenerOnce(this.map, 'idle', function() {
        var links = self.$canvas.getElementsByTagName("a");
        var len = links.length;
        for (var i = 0; i < len; i++) {
          links[i].style.display = 'none';
          links[i].onclick = function() {return(false);};
        }
      });

      // *** request the last known state from the server
      this.on('ready', function() {
        self.emit('refresh');
      });

      // *** wait for an idle event before reporting module readiness
      GMaps.event.addListenerOnce(this.map, 'idle', function() {
        console.debug('StreetView: ready');
        self.emit('ready');
      });

      // *** handle window resizing
      window.addEventListener('resize',  function() {
        self._resize();
      });
    },

    // *** setPano(panoid)
    // switch to the provided pano, immediately
    setPano: function(panoid) {
      if (!validate.panoid(panoid)) {
        L.error('StreetView: bad panoid to setPano!');
        return;
      }

      if (panoid != this.streetview.getPano()) {
        var pov = this.streetview.getPov();
        pov.zoom = this.zoom;
        this.pano = panoid;
        this.streetview.setPano(panoid);
        this.setPov(pov);
      } else {
        console.warn('StreetView: ignoring redundant setPano');
      }
    },

    // *** setPov(GMaps.StreetViewPov)
    // set the view to the provided pov, immediately
    setPov: function(pov) {
      if (!validate.number(pov.heading) || !validate.number(pov.pitch)) {
        L.error('StreetView: bad pov to setPov!');
        return;
      }

      this.streetview.setPov(pov);
    },

    // *** setHdg(heading)
    // set just the heading of the POV, zero the pitch
    setHdg: function(heading) {
      if (!validate.number(heading)) {
        L.error('StreetView: bad heading to setHdg!');
        return;
      }

      this.setPov({ heading: heading, pitch: 0 });
    },

    // *** translatePov({yaw, pitch})
    // translate the view by a relative pov
    translatePov: function(abs) {
      if (!validate.number(abs.yaw) || !validate.number(abs.pitch)) {
        L.error('StreetView: bad abs to translatePov!');
        return;
      }

      var pov = this.streetview.getPov();

      pov.heading += abs.yaw;
      pov.pitch   += abs.pitch;

      this.streetview.setPov(pov);
    },

    // *** moveForward()
    // move to the pano nearest the current heading
    moveForward: function() {
      console.log('moving forward');
      var forward = this._getForwardLink();
      if(forward) {
        this.setPano(forward.pano);
        this._broadcastPano(forward.pano);
      } else {
        console.log("can't move forward, no links!");
      }
    },

    // PRIVATE

    // *** _resize()
    // called when the canvas size has changed
    _resize: function() {
      var screenratio = window.innerHeight / window.innerWidth;
      this.vfov = this.hfov * screenratio;
      this.emit('size_changed', {hfov: this.hfov, vfov: this.vfov});
      console.debug('StreetView: resize', this.hfov, this.vfov);
    },

    // *** _broadcastPov(GMaps.StreetViewPov)
    // report a pov change to listeners
    _broadcastPov: function(pov) {
      this.emit('pov_changed', pov);
    },

    // *** _broadcastPano(panoid)
    // report a pano change to listeners
    _broadcastPano: function(panoid) {
      this.emit('pano_changed', panoid);

      var self = this;
      sv_svc.getPanoramaById(
        panoid,
        function (data, stat) {
          if (stat == GMaps.StreetViewStatus.OK) {
            sv_svc.serializePanoData(data);
            self.emit('meta', data);
          }
        }
      );
    },

    // *** _getLinkDifference(
    //                         GMaps.StreetViewPov,
    //                         GMaps.StreetViewLink
    //                       )
    // return the difference between the current heading and the provided link
    _getLinkDifference: function(pov, link) {
      var pov_heading = pov.heading;
      var link_heading = link.heading;

      var diff = Math.abs(link_heading - pov_heading) % 360;

      return diff >= 180 ? diff - (diff - 180) * 2 : diff;
    },

    // *** _getForwardLink()
    // return the link nearest the current heading
    _getForwardLink: function() {
      var pov = this.streetview.getPov();
      var links = this.streetview.getLinks();
      var len = links.length;
      var nearest = null;
      var nearest_difference = 360;

      for(var i=0; i<len; i++) {
        var link = links[i];
        var difference = this._getLinkDifference(pov, link);
        console.log(difference, link);
        if (difference < nearest_difference) {
          nearest = link;
          nearest_difference = difference;
        }
      }

      return nearest;
    }
  });

  return StreetViewModule;
});
<|endoftext|>


<commit_before>'use strict';

var express = require('express')
  , app = express()
  , url = require('url')
  , fs = require('fs')
  , path = require('path')
  , uploadDir = __dirname + '/files';

/* 로컬 개발 환경 설정 */
if (app.get('env') === 'development') {
  app.set('config', require('./config/development.json'));
}

/* 테스트 서버 환경 설정 */
if (app.get('env') === 'test') {
  // app.set('config', require('./config/test.json'));
}

/* 실 서버 환경 설정 */
if (app.get('env') === 'production') {
  // app.set('config', require('./config/production.json'));
}

/* 공통 환경 설정 */
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');

app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'files'));
app.use(express.limit('5mb'));
app.use(express.bodyParser({uploadDir: uploadDir}));
app.use(express.methodOverride());
app.use(express.logger({ buffer: 5000}));
app.use(app.router);
app.use(express.errorHandler());

fs.exists(uploadDir, function (exist) {
  if (!exist) {
    fs.mkdir(uploadDir);
  }
});

/* 데이터 모델 설정 */
require('./models').init(app);

/* 라우터 설정 */
require('./routes').init(app);

/* 서버 실행 */
app.listen(app.get('port'), function() {
  console.log('Hello, world!');
});

process.on('uncaughtException', function(err) {
  console.error(err.stack);
});<commit_msg>files도 public 폴더로 만듬에러수정 :cry:<commit_after>'use strict';

var express = require('express')
  , app = express()
  , url = require('url')
  , fs = require('fs')
  , path = require('path')
  , uploadDir = __dirname + '/files';

/* 로컬 개발 환경 설정 */
if (app.get('env') === 'development') {
  app.set('config', require('./config/development.json'));
}

/* 테스트 서버 환경 설정 */
if (app.get('env') === 'test') {
  // app.set('config', require('./config/test.json'));
}

/* 실 서버 환경 설정 */
if (app.get('env') === 'production') {
  // app.set('config', require('./config/production.json'));
}

/* 공통 환경 설정 */
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');

app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'files')));
app.use(express.limit('5mb'));
app.use(express.bodyParser({uploadDir: uploadDir}));
app.use(express.methodOverride());
app.use(express.logger({ buffer: 5000}));
app.use(app.router);
app.use(express.errorHandler());

fs.exists(uploadDir, function (exist) {
  if (!exist) {
    fs.mkdir(uploadDir);
  }
});

/* 데이터 모델 설정 */
require('./models').init(app);

/* 라우터 설정 */
require('./routes').init(app);

/* 서버 실행 */
app.listen(app.get('port'), function() {
  console.log('Hello, world!');
});

process.on('uncaughtException', function(err) {
  console.error(err.stack);
});<|endoftext|>