<commit_before>var express = require('express');
var router = express.Router();

const mongo = require('mongoskin');
const db = mongo.db('mongodb://localhost:27017/fuse');
const groupsdb = db.collection('groups');
const methodOverride = require('method-override');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local');
const TwitterStrategy = require('passport-twitter');
const GoogleStrategy = require('passport-google');
const FacebookStrategy = require('passport-facebook');
//used to collect username
var myModule = require("C:\\Users\\Robbie\\Desktop\\project\\fuse\\functions.js");

//We will be creating these two files shortly
// var config = require('./config.js'), //config file contains all tokens and other private info
//    funct = require('./functions.js'); //funct file contains our helper functions for our Passport and database work

//===============ROUTES=================
//displays our signup page
router.get('/signin', function(req, res){
  res.render('signin');
});

//sends the request through our local signup strategy, and if successful takes user to homepage, otherwise returns then to signin page
router.post('/local-reg', passport.authenticate('local-signup', {
  successRedirect: '/',
  failureRedirect: '/signin'
  })
);

//sends the request through our local login/signin strategy, and if successful takes user to homepage, otherwise returns then to signin page
router.post('/login', passport.authenticate('local-signin', {
  successRedirect: '/',
  failureRedirect: '/signin'
  })
);

//logs user out of site, deleting them from the session, and returns to homepage
router.get('/logout', function(req, res){
  var name = req.user.username;
  console.log("LOGGIN OUT " + req.user.username)
  req.logout();
  res.redirect('/');
  req.session.notice = "You have successfully been logged out " + name + "!";
});

// TODO: cleanup
/* GET home page. */
router.get('/', function(req, res, next) {
    groupsdb.find().toArray(function(err, items) {
        if (err) {
            throw err;
        }
        //the username of logfed in user
        var name1 = myModule.name;

        // set the first one to be the selected one
        //items[0].selected = true;
        res.render('index', { title: 'Fuse Chat', groups: items, selectedGroup: items[0], username: name1});
    });
});

module.exports = router;
<commit_msg>Fixing a couple issues in index.js. This reintroduces the bug that a database with no groups crashes the server (as it cannot set selected to true on a null component.<commit_after>var express = require('express');
var router = express.Router();

const app_root_path = require('app-root-path').path;
const mongo = require('mongoskin');
const db = mongo.db('mongodb://localhost:27017/fuse');
const groupsdb = db.collection('groups');
const methodOverride = require('method-override');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local');
const TwitterStrategy = require('passport-twitter');
const GoogleStrategy = require('passport-google');
const FacebookStrategy = require('passport-facebook');
//used to collect username
var myModule = require(app_root_path + '/functions.js');

//We will be creating these two files shortly
// var config = require('./config.js'), //config file contains all tokens and other private info
//    funct = require('./functions.js'); //funct file contains our helper functions for our Passport and database work

//===============ROUTES=================
//displays our signup page
router.get('/signin', function(req, res){
  res.render('signin');
});

//sends the request through our local signup strategy, and if successful takes user to homepage, otherwise returns then to signin page
router.post('/local-reg', passport.authenticate('local-signup', {
  successRedirect: '/',
  failureRedirect: '/signin'
  })
);

//sends the request through our local login/signin strategy, and if successful takes user to homepage, otherwise returns then to signin page
router.post('/login', passport.authenticate('local-signin', {
  successRedirect: '/',
  failureRedirect: '/signin'
  })
);

//logs user out of site, deleting them from the session, and returns to homepage
router.get('/logout', function(req, res){
  var name = req.user.username;
  console.log("LOGGIN OUT " + req.user.username)
  req.logout();
  res.redirect('/');
  req.session.notice = "You have successfully been logged out " + name + "!";
});

// TODO: cleanup
/* GET home page. */
router.get('/', function(req, res, next) {
    groupsdb.find().toArray(function(err, items) {
        if (err) {
            throw err;
        }
        //the username of logfed in user
        var name1 = myModule.name;

        // set the first one to be the selected one
        items[0].selected = true;
        res.render('index', { title: 'Fuse Chat', groups: items, selectedGroup: items[0], username: name1});
    });
});

module.exports = router;
<|endoftext|>


<commit_before>/**
 * Unit test waterfall
 */
describe('Unit test plot module', function() {
    var $compile;
    var $rootScope;
    var data = [
        {name: "A", value: .08167},
        {name: "B", value: .01492},
        {name: "C", value: .02782},
        {name: "D", value: .04253},
        {name: "E", value: .12702},
        {name: "F", value: .02288}
    ];
    var plotService, d3Service;

// Load the module
    beforeEach(module('lcaApp.plot'));

// Store references to $rootScope and $compile
// so they are available to all tests in this describe block
    beforeEach(inject(function(_$rootScope_, _$compile_,
                               _PlotService_, _d3Service_ ) {
        // The injector unwraps the underscores (_) from around the parameter names when matching
        $compile = _$compile_;
        $rootScope = _$rootScope_;
        plotService = _PlotService_;
        d3Service = _d3Service_;
    }));

    function getValue(d) {
        return d.value;
    }

    function getNumLabel(d) {
        return d3Service.format("^.2g").call(d.value);
    }

    function getColor(d) {
        return d["color"];
    }

    // Test bar
    it('should be able to create a bar definition object', function() {
        var bar = plotService.createBar();

        expect(bar.shape()).toBeTruthy();  // Has a default shape
        expect(bar.color()).toBeTruthy();  // Has default color
        expect(bar.orientation()).toBeTruthy();  // Has default color
        // defaults, other than shape, can be overridden
        expect(bar.width(12).width()).toBe(12);
        expect(bar.color(getColor).color()).toBe(getColor);
        expect(bar.orientation("vertical").orientation()).toBe("vertical");
    });

    // Test axis
    it('should be able to create an axis object', function() {
        var axis = plotService.createAxis();

        expect(axis.orientation()).toBeTruthy();  // Has a default orientation
        // defaults can be overridden
        expect(axis.orientation("left").orientation()).toBe("left");
    });

    // Test dimension
    it('should create a dimension object', function() {
        var di = plotService.createDimension(),
            ai = plotService.createAxis(),
            s = "linear",
            dom = [0,1];

        expect(di.axis(ai).axis()).toBe(ai);
        expect(di.scale(s).scale()).toBe(s);
        expect(di.domain(dom).domain()).toBe(dom);
        expect(di.unit("kg").unit()).toBe("kg");
        expect(di.valueFn(getValue).valueFn()).toBe(getValue);
        expect(di.labelFn(getNumLabel).labelFn()).toBe(getNumLabel);
    });

    // Test margin
    it('should create margin object', function() {
        var margin = plotService.createMargin();

        expect(margin.top).toBe(0);
        expect(margin.bottom).toBe(0);
        expect(margin.left).toBe(0);
        expect(margin.right).toBe(0);

        margin = plotService.createMargin(1, 2, 3, 4);
        expect(margin.top).toBe(1);
        expect(margin.right).toBe(2);
        expect(margin.bottom).toBe(3);
        expect(margin.left).toBe(4);

        margin = plotService.createMargin(5);
        expect(margin.top).toBe(5);
        expect(margin.right).toBe(5);
        expect(margin.bottom).toBe(5);
        expect(margin.left).toBe(5);
    });

    // Test complete definition
    it('should create complete definition object', function() {
        var instance = plotService.createConfig(),
            x = plotService.createDimension(),
            y = plotService.createDimension(),
            m = plotService.createMargin(),
            bar = plotService.createBar();

        expect(instance).toBeTruthy();
        expect(instance.x(x).x()).toBe(x);
        expect(instance.y(y).y()).toBe(y);
        expect(instance.margin(m).margin()).toBe(m);
        expect(instance.content(bar).content()).toBe(bar);
    });

    it('should be able to compile and digest the directive', function() {
        var plot = plotService.createConfig(),
            data = [];

        // Compile a piece of HTML containing the directive
        var element = $compile("<plot config=\"plot\" data=\"data\"></plot>")($rootScope);
        // fire all the watches, so the scope will be evaluated
        element.scope().$digest();
    });

});<commit_msg>Test: Plot directive<commit_after>/**
 * Unit test plot
 */
describe('Unit test plot module', function() {
    var $compile;
    var $rootScope;
    var data = [
        {name: "A", value: .08167},
        {name: "B", value: .01492},
        {name: "C", value: .02782},
        {name: "D", value: .04253},
        {name: "E", value: .12702},
        {name: "F", value: .02288}
    ];
    var template = "<svg><plot config=\"config\" data=\"data\"></plot></svg>";
    var plotService, d3Service;

// Load the module
    beforeEach(module('lcaApp.plot'));

// Store references to $rootScope and $compile
// so they are available to all tests in this describe block
    beforeEach(inject(function(_$rootScope_, _$compile_,
                               _PlotService_, _d3Service_ ) {
        // The injector unwraps the underscores (_) from around the parameter names when matching
        $compile = _$compile_;
        $rootScope = _$rootScope_;
        plotService = _PlotService_;
        d3Service = _d3Service_;
    }));

    function getValue(d) {
        return d.value;
    }

    function getName(d) {
        return d.name;
    }

    function getNumLabel(d) {
        return d3Service.format("^.2g").call(d.value);
    }

    function getColor(d) {
        return d["color"];
    }

    // Test bar
    it('should be able to create a bar definition object', function() {
        var bar = plotService.createBar();

        expect(bar.shape()).toBeTruthy();  // Has a default shape
        expect(bar.color()).toBeTruthy();  // Has default color
        expect(bar.orientation()).toBeTruthy();  // Has default color
        // defaults, other than shape, can be overridden
        expect(bar.width(12).width()).toBe(12);
        expect(bar.color(getColor).color()).toBe(getColor);
        expect(bar.orientation("vertical").orientation()).toBe("vertical");
    });

    // Test axis
    it('should be able to create an axis object', function() {
        var axis = plotService.createAxis();

        expect(axis.orientation()).toBeTruthy();  // Has a default orientation
        // defaults can be overridden
        expect(axis.orientation("left").orientation()).toBe("left");
    });

    // Test dimension
    it('should create a dimension object', function() {
        var di = plotService.createDimension(),
            ai = plotService.createAxis(),
            s = "linear",
            dom = [0,1];

        expect(di.axis(ai).axis()).toBe(ai);
        expect(di.scale(s).scale()).toBe(s);
        expect(di.domain(dom).domain()).toBe(dom);
        expect(di.unit("kg").unit()).toBe("kg");
        expect(di.valueFn(getValue).valueFn()).toBe(getValue);
        expect(di.labelFn(getNumLabel).labelFn()).toBe(getNumLabel);
    });

    // Test margin
    it('should create margin object', function() {
        var margin = plotService.createMargin();

        expect(margin.top).toBe(0);
        expect(margin.bottom).toBe(0);
        expect(margin.left).toBe(0);
        expect(margin.right).toBe(0);

        margin = plotService.createMargin(1, 2, 3, 4);
        expect(margin.top).toBe(1);
        expect(margin.right).toBe(2);
        expect(margin.bottom).toBe(3);
        expect(margin.left).toBe(4);

        margin = plotService.createMargin(5);
        expect(margin.top).toBe(5);
        expect(margin.right).toBe(5);
        expect(margin.bottom).toBe(5);
        expect(margin.left).toBe(5);
    });

    // Test complete definition
    it('should create complete definition object', function() {
        var instance = plotService.createConfig(),
            x = plotService.createDimension(),
            y = plotService.createDimension(),
            m = plotService.createMargin(),
            bar = plotService.createBar();

        expect(instance).toBeTruthy();
        expect(instance.x(x).x()).toBe(x);
        expect(instance.y(y).y()).toBe(y);
        expect(instance.margin(m).margin()).toBe(m);
        expect(instance.content(bar).content()).toBe(bar);
    });

    it('should be able to compile and digest the directive', function() {
        var config = plotService.createConfig();

        config.x(plotService.createDimension().scale("ordinal").valueFn(getName))
              .y(plotService.createDimension().scale("linear").valueFn(getValue))
            .margin(plotService.createMargin())
            .content(plotService.createBar());

        $rootScope.config = config;
        $rootScope.data = data;

        // Compile a piece of HTML containing the directive
        var element = $compile(template)($rootScope);
        // fire all the watches, so the scope will be evaluated
        element.scope().$digest();
        var replaceElt = element.find("g").eq(0);
        expect(replaceElt).toBeDefined();
        //expect(angular.element(replaceElt).hasClass("lcia-bar-container")).toBe(true);
    });

});<|endoftext|>


<commit_before>const schema = {
    name: '',
    active: false,
    proxy: {
        preserve_host: false,
        listen_path: '',
        upstream_url: '',
        strip_path: false,
        append_path: false,
        methods: ['ALL'],
        hosts: ['hellofresh.*'],
    },
    health_check: {
        url: '',
        timeout: 3,
    },
    plugins: [
        {
            name: 'cors',
            enabled: false,
            config: {
                domains: ['*'],
                methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
                request_headers: ['Origin', 'Authorization', 'Content-Type'],
                exposed_headers: ['X-Debug-Token', 'X-Debug-Token-Link'],
            },
        },
        {
            name: 'rate_limit',
            enabled: false,
            config: {
                // limit: '10-S',
                limit: {
                    value: 0,
                    // units: ['ns', 'us', 'ms', 's', 'm', 'h'],
                    units: ['S', 'M', 'H'],
                },
                policy: [
                    {
                        label: 'local',
                        value: 'local',
                    },
                    {
                        label: 'destributed',
                        value: 'redis',
                    }
                ],
            },
        },
        {
            name: 'oauth2',
            enabled: false,
            config: {
                server_name: 'local',
            },
        },
        {
            name: 'compression',
            enabled: false,
        },
        {
            name: 'request_transformer',

            enabled: false,
            config: {
                add: {
                    headers: [],
                    querystring: [],
                },
                append: {
                    headers: [],
                    querystring: [],
                },
                replace: {
                    headers: [],
                    querystring: [],
                },
                remove: {
                    headers: []   ,
                    querystring: [],
                },
            },
        },
    ],
};

export default schema;
<commit_msg>remove redundant stuff from api schema<commit_after>const schema = {
    name: '',
    active: false,
    proxy: {
        preserve_host: false,
        listen_path: '',
        upstream_url: '',
        strip_path: false,
        append_path: false,
        methods: ['ALL'],
        hosts: ['hellofresh.*'],
    },
    health_check: {
        url: '',
        timeout: 3,
    },
    plugins: [
        {
            name: 'cors',
            enabled: false,
            config: {
                domains: ['*'],
                methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
                request_headers: ['Origin', 'Authorization', 'Content-Type'],
                exposed_headers: ['X-Debug-Token', 'X-Debug-Token-Link'],
            },
        },
        {
            name: 'rate_limit',
            enabled: false,
            config: {
                limit: {
                    value: 0,
                    units: ['S', 'M', 'H'],
                },
                policy: [
                    {
                        label: 'local',
                        value: 'local',
                    },
                    {
                        label: 'destributed',
                        value: 'redis',
                    }
                ],
            },
        },
        {
            name: 'oauth2',
            enabled: false,
            config: {
                server_name: 'local',
            },
        },
        {
            name: 'compression',
            enabled: false,
        },
        {
            name: 'request_transformer',

            enabled: false,
            config: {
                add: {
                    headers: [],
                    querystring: [],
                },
                append: {
                    headers: [],
                    querystring: [],
                },
                replace: {
                    headers: [],
                    querystring: [],
                },
                remove: {
                    headers: []   ,
                    querystring: [],
                },
            },
        },
    ],
};

export default schema;
<|endoftext|>


<commit_before>import React from 'react';
import {DropdownButton, MenuItem} from 'react-bootstrap';
import store from '../store/store.js';
import {themeSwitch} from '../actions/action.js';

const onThemeSwitch = (style) => {
  store.dispatch(themeSwitch(style));
  console.log(store.getState().pager.themeStyle);
};

const render = () => {
  return (

      <DropdownButton title="Theme" id="themeDropdown" bsStyle={'Info'.toLowerCase()}>
        <MenuItem id="themeGreen" onClick={() => {onThemeSwitch('Green');}}>Green</MenuItem>
        <MenuItem id="themeBlue" onClick={() => {onThemeSwitch('Blue');}}>Blue</MenuItem>
        <MenuItem id="themeBlack" onClick={() => {onThemeSwitch('Black');}}>Black</MenuItem>
        <MenuItem id="themeYellow" onClick={() => {onThemeSwitch('Yellow');}}>Yellow</MenuItem>
      </DropdownButton>

  );
};

export default render;
<commit_msg>rm console<commit_after>import React from 'react';
import {DropdownButton, MenuItem} from 'react-bootstrap';
import store from '../store/store.js';
import {themeSwitch} from '../actions/action.js';

const onThemeSwitch = (style) => {
  store.dispatch(themeSwitch(style));
};

const render = () => {
  return (

      <DropdownButton title="Theme" id="themeDropdown" bsStyle={'Info'.toLowerCase()}>
        <MenuItem id="themeGreen" onClick={() => {onThemeSwitch('Green');}}>Green</MenuItem>
        <MenuItem id="themeBlue" onClick={() => {onThemeSwitch('Blue');}}>Blue</MenuItem>
        <MenuItem id="themeBlack" onClick={() => {onThemeSwitch('Black');}}>Black</MenuItem>
        <MenuItem id="themeYellow" onClick={() => {onThemeSwitch('Yellow');}}>Yellow</MenuItem>
      </DropdownButton>

  );
};

export default render;
<|endoftext|>


<commit_before>/*
 * HomePage
 *
 * This is the first thing users see of our App, at the '/' route
 */

import React from 'react';
import { isMobile } from 'react-device-detect';
import _ from 'lodash';
import Helmet from 'react-helmet';
import GeometryCanvasWithOptions from 'components/GeometryCanvasWithOptions';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import Paper from 'material-ui/Paper';
import Chip from 'material-ui/Chip';
import Button from 'material-ui/Button';
import Grid from 'material-ui/Grid';
import { LinearProgress } from 'material-ui/Progress';
import Script from 'react-load-script';
import { Link } from 'react-router';
import Img from 'containers/App/Img';
import Banner from 'components/Header/banner.png';
import { withStyles } from 'material-ui/styles';
import { FaDatabase, FaNewspaperO } from 'react-icons/lib/fa';
import {
  MdWarning,
  MdApps,
  MdKeyboardArrowUp,
  MdKeyboardArrowDown,
  MdChevronRight,
  MdFace,
} from 'react-icons/lib/md';
import Slide from 'material-ui/transitions/Slide';

import axios from 'axios';
import { newGraphQLRoot, whiteLabel, apps } from 'utils/constants';

import { makeSelectRepos, makeSelectLoading, makeSelectError } from 'containers/App/selectors';
import H1 from 'components/H1';
import { withCommas } from 'utils/functions';
import CenteredSection from './CenteredSection';
import { loadRepos } from '../App/actions';
import { changeUsername } from './actions';
import { makeSelectUsername } from './selectors';
import { styles } from './styles';

export class HomePage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
  /**
   * when initial state username is not null, submit the form to load repos
   */
  constructor(props) {
    super(props);
    this.state = {
      geometries: 0,
      reactions: 0,
      publications: 0,
      contributors: 0,
      loading: true,
      error: false,
      truncated: true,
      randomReaction: {},
      randomSystems: [],
      image: 0,
    };
  }

  componentDidMount() {
    if (this.props.username && this.props.username.trim().length > 0) {
      this.props.onSubmitForm();
    }
    axios.post(newGraphQLRoot, {
      query: '{reactions(first: 0) { totalCount edges { node { id } } }}' }).then((response) => {
        if (response.data.data.reactions === null) {
          this.setState({
            loading: false,
            error: true,
          });
        } else {
          this.setState({
            loading: false,
            reactions: response.data.data.reactions.totalCount,
          });
          const nRandom = parseInt(Math.random() * response.data.data.reactions.totalCount, 10);
          axios.post(newGraphQLRoot, {
            query: `{ reactions(first: ${nRandom}, last: 1) {
              totalCount
              edges {
                node {
                  Equation
                  chemicalComposition
                  reactionEnergy
                  systems {
                    energy
                    Cifdata
                  }
                  publication {
                    pubId
                  }
                }
              }
            }
          }
          ` }).then((innerResponse) => {
            const randomReaction = _.get(innerResponse, 'data.data.reactions.edges[0].node');
            const randomSystems = _.orderBy(randomReaction.systems, 'energy');
            this.setState({
              randomReaction,
              randomSystems,
            });

            setInterval(
                () => {
                  this.setState({
                    image: this.state.image + 1,
                  });
                }, 3000);
          });
        }
      });
    axios.post(newGraphQLRoot, {
      query: '{publications(first: 0) { totalCount edges { node { id } } }}' }).then((response) => {
        if (response.data.data.reactions === null) {
          this.setState({
            loading: false,
            error: true,
          });
        } else {
          this.setState({
            loading: false,
            publications: response.data.data.publications.totalCount,
          });
        }
      });

    axios.post(newGraphQLRoot, {
      query: '{publications { edges { node { authors } } }}',
    }).then((response) => {
      const contributors = new Set();
      response.data.data.publications.edges.map((edge) => JSON.parse(edge.node.authors).map((author) => contributors.add(author)));
      this.setState({
        contributors: contributors.size,
      });
    });
  }

  render() {
    return (

        { whiteLabel === true ? null :
        <Helmet
          title="Home Page"
          meta={[
            { name: 'description', content: `Catalysis-Hub.org is a frontend for browsing the SUNCAT CatApp database containing thousands of first-principles calculations related to heterogeneous catalysis reactions on surface systems. Its goal is to allow comprehensive and user-friendly access to raw quantum chemical simulations guided by heterogeneous catalysis concepts and commonly used graphical representations such as scaling relations and activity maps. All reaction energies are derived from periodic plane-wave density functional theory calculations. An increasing number of calculations contain the corresponding optimized geometry as well as further calculational details such as exchange-correlation (XC) functional, basis set quality, and k-point sampling. Ultimately, the goal is to provide fully self-contained data for predicting experimental observations from electronic structure calculations and using software packages such as Quantum Espresso, GPAW, VASP, and FHI-aims. Input and output with other codes is supported through the Atomic Simulation Environment (ASE). It may also serve as a natural starting point for training and developing machine-learning based approaches accelerating quantum chemical simulations.
      Features include search for specific reaction energies, transition states, structures, exploration of scaling relations, activity maps, Pourbaix diagrams and machine learning models, as well as generation of novel bulk and surface structures. Calculations are linked to peer-review publications where available. The database can be queried via a GraphQL API that can also be accessed directly.
      All code pertaining to this project is hosted as open-source under a liberal MIT license on github to encourage derived work and collaboration. The frontend is developed using the React Javascript framework based on react boilerplate. New components (apps) can be quickly spun-off and added to the project. The backend is developed using the Flask Python framework providing the GraphQL API as well as further APIs for specific apps.
      As such Catalysis-Hub.org aims to serve as a starting point for trend studies and atomic based heterogeneous catalysis explorations.` },
                { name: 'robots', content: 'index,follow' },
                { name: 'keywords', content: 'heterogeneous catalysis,metals,density functional theory,scaling relations, activity maps,pourbaix diagrams,machine learning,quantum espresso,vasp,gpaw' },
                { name: 'DC.title', content: 'Catalysis-Hub.org' },
          ]}
        />
        }

          <CenteredSection className={this.props.classes.centeredSection}>
            {whiteLabel ? null :
            <Grid
              container direction={isMobile ? 'column-reverse' : 'row'} justify="space-between"
              className={this.props.classes.welcomeHeader}
            >
              <Grid item xs={isMobile ? 12 : 6}>

                    Welcome to Catalysis-Hub.Org

             Catalysis-Hub.org is a web-platform for sharing data and software for computational catalysis research. The Surface Reactions database (CatApp v2.0) contains thousands of reaction energies and barriers from density functional theory (DFT) calculations on surface systems.

                      Under Publications, reactions and surface geometries can also be browsed for each publication or dataset. With an increasing number of Apps, the platform allows comprehensive and user-friendly access to heterogeneous catalysis concepts and commonly used graphical representations such as scaling relations and activity maps.
                      An increasing number of calculations contain the corresponding optimized geometry as well as further calculational details such as exchange-correlation (XC) functional, basis set quality, and k-point sampling. Ultimately, the goal is to provide fully self-contained data for predicting experimental observations from electronic structure calculations and using software packages such as Quantum Espresso, GPAW, VASP, and FHI-aims. Input and output with other codes is supported through the Atomic Simulation Environment (ASE). It may also serve as a natural starting point for training and developing machine-learning based approaches accelerating quantum chemical simulations.

                      Features include search for specific reaction energies, transition states, structures, exploration of scaling relations, activity maps, Pourbaix diagrams and machine learning models, as well as generation of novel bulk and surface structures. Calculations are linked to peer-review publications where available. The database can be queried via a GraphQL API that can also be accessed directly.

                      All code pertaining to this project is hosted as open-source under a liberal MIT license on github to encourage derived work and collaboration. The frontend is developed using the React Javascript framework based on react boilerplate. New components (apps) can be quickly spun-off and added to the project. The backend is developed using the Flask Python framework providing the GraphQL API as well as further APIs for specific apps.

                      As such Catalysis-Hub.org aims to serve as a starting point for trend studies and atomic based heterogeneous catalysis explorations.

                <Grid container direction="row" justify="space-between">
                  <Grid item>
                    <Link
                      className={this.props.classes.buttonLink}
                      to={'/upload'}
                    >
                      <Button
                        raised
                        color="primary"
                      >
                      Upload Surface Reactions <MdChevronRight />

                      </Button>
                    </Link>
                  </Grid>
                  <Grid item>
                    {this.state.truncated ?
                      <Button
                        mini
                        onClick={() => {
                          this.setState({
                            truncated: false,
                          });
                        }}
                        role="button"
                      >Read More <MdKeyboardArrowDown /></Button>

                      :
                      <Button
                        mini
                        onClick={() => {
                          this.setState({
                            truncated: true,
                          });
                        }}
                        role="button"
                      >
                        Read Less <MdKeyboardArrowUp />
                      </Button>
                  }
                  </Grid>
                </Grid>
              </Grid>
              <Grid item xs={isMobile ? 12 : 6}>
                {_.isEmpty(this.state.randomSystems) ?

                  :
                  <Grid
                    container
                    direction="row"
                    justify="flex-end"
                    style={{
                      height: '280px',
                    }}
                  >
                    <Grid item >
                      <GeometryCanvasWithOptions
                        key={`mc_${this.state.randomReaction.publication.pubId}`}
                        cifdata={this.state.randomSystems[this.state.image % this.state.randomSystems.length].Cifdata}
                        uniqueId={`molecule_${this.state.randomReaction.publication.pubId}`}
                        id={`molecule_${this.state.randomReaction.publication.pubId}`}
                        height={280}
                        width={280}
                        showButtons={false}
                        x={1} y={1} z={2}
                      />
                    </Grid>

                    <Grid item>
                      <Grid
                        container
                        direction="column"
                        justify="space-around"
                        style={{
                          height: '310px',
                        }}
                      >
                        <Grid item>
                          <Link to={`/publications/${this.state.randomReaction.publication.pubId}`}>
                            <Button fab color="primary" height="100%" >
                              <MdChevronRight size={30} />
                            </Button>
                          </Link>
                        </Grid>
                      </Grid>
                    </Grid>
                  </Grid>

                }

              </Grid>
            </Grid>
            }
          </CenteredSection>
          <CenteredSection className={this.props.classes.centeredSection}>
            {this.state.loading ?
Contacting database ... <LinearProgress color="primary" />
 : null }
            {this.state.error ?
<MdWarning />Failed to contact database.
 : null }
          </CenteredSection>
          <CenteredSection className={this.props.classes.centeredSection}>
            <Slide mountOnEnter unmountOnExit in direction="left">

                <Grid container justify="space-between" className={this.props.classes.centerGrid}>

                  <Grid item>
                    <Link to="/energies" className={this.props.classes.textLink}>
                      <Paper
                        className={this.props.classes.homePaper}
                        elevation={0}
                      >

 <FaDatabase size={20} /> Surface Reactions

                          A database of reaction energies and barriers.

                        <Grid container direction="row" justify="space-between">
                          <Grid item>
                            <Chip label={withCommas(this.state.reactions)} />
                          </Grid>
                          <Grid item>

See reactions <MdChevronRight />

                          </Grid>
                        </Grid>
                      </Paper>
                    </Link>
                  </Grid>

                  <Grid item>
                    <Link to="/profile" className={this.props.classes.textLink}>
                      <Paper
                        className={this.props.classes.homePaper}
                        elevation={0}
                      >

 <MdFace size={20} /> Contributors

                          The people (and co-authors) behind the datasets.

                        <Grid container direction="row" justify="space-between">
                          <Grid item>
                            <Chip label={withCommas(this.state.contributors)} />
                          </Grid>
                          <Grid item>

See contributors <MdChevronRight />

                          </Grid>
                        </Grid>
                      </Paper>
                    </Link>
                  </Grid>

                  <Grid item>
                    <Link to="/publications" className={this.props.classes.textLink}>
                      <Paper
                        className={this.props.classes.homePaper}
                        elevation={0}
                      >

 <FaNewspaperO size={20} /> Publications

A collection of scientific publications with geometries.

                        <Grid container direction="row" justify="space-between">
                          <Grid item>
                            <Chip label={this.state.publications} />
                          </Grid>
                          <Grid item className={this.props.classes.bold}>
                            See publications <MdChevronRight />
                          </Grid>
                        </Grid>
                      </Paper>
                    </Link>
                  </Grid>

                  <Grid item>
                    <Link to="/appsIndex" className={this.props.classes.textLink}>
                      <Paper
                        className={this.props.classes.homePaper}
                      >

<MdApps size={20} /> Apps

                          Web apps for exploring calculations
                          and catalysts.

                        <Grid container direction="row" justify="space-between">
                          <Grid item>
                            <Chip label={apps.length} />
                          </Grid>
                          <Grid item>

See our apps <MdChevronRight />

                          </Grid>
                        </Grid>
                      </Paper>
                    </Link>
                  </Grid>

                </Grid>

            </Slide>
          </CenteredSection>


<commit_before>var app = require('express');
var router = app.Router();
var oauthserver = require('oauth2-server');

app.oauth = oauthserver({
	model: require('../model.js'),
	grants: ['password'],
	debug: true
});

/* GET home page. */
router.get('/', app.oauth.authorise(), function(err, req, res, next) {
  if(err) {
      console.error('ERROR GARDEN: ' + err.stack);
      res.redirect('/nodeGarden.js/login');

  } else {
      res.render('index', { title: 'Garden Project JB' });
  }
  res.end();
});

module.exports = router;
<commit_msg>Update index.js<commit_after>var app = require('express');
var router = app.Router();
var oauthserver = require('oauth2-server');

app.oauth = oauthserver({
	model: require('../model.js'),
	grants: ['password'],
	debug: true
});

/* GET home page. */
router.get('/', app.oauth.authorise(), function(err, req, res, next) {
  if(err) {
      console.error('ERROR GARDEN: ' err.status + " " + err.stack);
      res.redirect('/nodeGarden.js/login');
      res.end();

  } else {
      res.render('index', { title: 'Garden Project JB' });
  }
});

module.exports = router;
<|endoftext|>


<commit_before>/*
 * HomePage
 *
 * This is the first thing users see of our App, at the '/' route
 *
 * NOTE: while this component should technically be a stateless functional
 * component (SFC), hot reloading does not currently support SFCs. If hot
 * reloading is not a necessity for you then you can refactor it and remove
 * the linting exception.
 */

import React from 'react';
import { FormattedMessage } from 'react-intl';
import messages from './messages';
import { Link } from 'react-router';
import './home.css'
import Footer from '../../components/Footer';

export default class HomePage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
  render() {
    return (

 What if

there was a platform to collect and compare spatial proteomics datasets.
               A database that offers a user friendly interface that is still accessible by programming languages such as R.

             <button className="headButton"> Get Started </button>

 The problem

                Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod
                tempor invidunt ut labore et dolore magna aliquyam erat,

                Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod
                tempor invidunt ut labore et dolore magna aliquyam erat,

                Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod
                tempor invidunt ut labore et dolore magna aliquyam erat,

 Idea & Foundation

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod
             tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero
               takimata sanctus est Lorem.

 Technology

The SpatialMaps platform is based on Google Firebase as secure cloud database and react.js.

Combining the cloud database with pRolocdata biocoductor package, we offer the opportunity access datasets both via R scripts as well as via the user friendly SpatialMaps web platform.

    );
  }
}
<commit_msg>addded more text blocks to the homepage<commit_after>/*
 * HomePage
 *
 * This is the first thing users see of our App, at the '/' route
 *
 * NOTE: while this component should technically be a stateless functional
 * component (SFC), hot reloading does not currently support SFCs. If hot
 * reloading is not a necessity for you then you can refactor it and remove
 * the linting exception.
 */

import React from 'react';
import { FormattedMessage } from 'react-intl';
import messages from './messages';
import { Link } from 'react-router';
import './home.css'
import Footer from '../../components/Footer';

export default class HomePage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
  render() {
    return (

 What if

there was a platform to collect and compare spatial proteomics datasets.
               A database that offers a user friendly interface that is still accessible by programming languages such as R.

             <button className="headButton"> Get Started </button>

                  Connecting Research
 While reproducable research in the proteomics field prospers,
                we see an opportunity to better connect spatial proteomics data to accelerate the rate of scientific findings.

                  Data Science
 We see spatial proteomics datasets as scarce scientific good, that can reveal scientificly relevant information beyond
                initial findings. Applying the newest machine learning algorithms to explore new leads is only one of its use cases.

                  Accessability
 With the pRoloc package, we provide a sophisticated solution to analyse spatial data. SpatialMaps is fully connected to the R environment
                while providing a simplyfied and straigh forward solution to access and analyse a variety of proteomics datasets.

 Idea & Foundation

After the creation of pRoloc and pRolocdata, SpatialMaps is an integral part of the pRoloc environment.
             While the pRoloc universe was yet a purely R based frameworks, SpatialMaps lowers the treshhold for non-coding scientists to efficiently compare datasets.

 Technology

The SpatialMaps platform is based on Google Firebase as secure cloud database and react.js.

Combining the cloud database with pRolocdata biocoductor package, we offer the opportunity access
                datasets both via R scripts as well as via the user friendly SpatialMaps web platform.

    );
  }
}
<|endoftext|>


<commit_before>/*global   */

/*
 * GET app page.
 */

var util = require('util')
var u = require('lodash')

function isNonEmptyString(e) {
  if (u.isString(e) && e.length) return true
  return false
}

module.exports = function(req, res, next){
  'use strict';
  var app_cfg = req.app.get('app config by name')

  console.log("app_cfg =", util.inspect(app_cfg, {depth:null}))

  var cfg = { 'title'            : req.app.get('title')
            , 'video root names' : u.clone(app_cfg.order)
            , 'controls config'  :
              { skipForwSecs : app_cfg['skip forward seconds'] || 30
              , skipBackSecs : app_cfg['skip backward seconds'] || 10
              }

              /* cfg['load'] = { 'root'    : 'HDD Videos'
               *               , 'subdirs' : ['Films', 'Harry Potter']
               *               , 'file'    : '1 Harry Potter And The Sorcerer's Stone 2001.mp4'
               *               , 'time'    : 2715
               *               }
               */
            , 'load'             : undefined

              /* From video-app.js:21 or so
               * var levels    = ['info', 'warn', 'crit', 'none', 'error']
               * 'none' is a place holder for no logging except error
               * There is really only three optional levels info, warn, and crit.
               */
            , 'debug'            : 'info'
            }

  console.log('index: cfg["video root names"] =', cfg['video root names'])

  console.log('index: req.query = %j', req.query)

  var queryOk = (function checkQuery() {
    var load = {}
    var root, subdirs, file, time
    var rootNames = cfg['video root names']
    console.log('checkQuery: req.query == trueish')
    console.log('checkQuery: ', util.inspect(req.query, {depth:null,colors:true}))
    if ( !Object.keys(req.query).length ) {
      console.log('index: checkQuery: req.query has no keys; fine, skipping the rest of checkQuery.')
      return true
    }

    root = req.query.root
    if (!root) return false
    if ( !rootNames.some(function(e){ return e == root }) ) return false
    load.root = root

    subdirs = req.query.subdirs
    if (!subdirs) return false
    if (!u.isArray(subdirs)) return false
    if ( !subdirs.every(isNonEmptyString) ) return false
    load.subdirs = req.query.subdirs

    file = req.query.file
    if (!file) return false
    if (!isNonEmptyString(file)) return false
    load.file = file

    time = req.query.time
    // we test each false possable except time=0
    if (isNonEmptyString(time) || u.isNumber(time)) {
      if (u.isString(time)) time = parseInt(time, 10)

      if (!isNaN(time)) {
        if (Number.isInteger(time))
          load.time = time
        else {
          load.time = Math.floor(time)
        }
      }
    }

    cfg.load = load

    return true
  })()

  if (!queryOk) {
    console.log('index: POST checkQuery(): BAD query calling next()')
    next()
    // FIXME: maybe I should do: http status 400 bad client request
    // res.status(400).render('bad_query')
    // and implemnets a nicer looking bad_query.jade
    return
  }

  /* FROM the node.js REPL on v5.1.0
   * > rx = /(?:\/\.\.(?![^\/])|^\.\.(?![^\/])|^\.\.$)/
   * /(?:\/\.\.(?![^\/])|^\.\.(?![^\/])|^\.\.$)/
   * > '/..'.match(rx)
   * [ '/..', index: 0, input: '/..' ]
   * > '../'.match(rx)
   * [ '..', index: 0, input: '../' ]
   * > '/../'.match(rx)
   * [ '/..', index: 0, input: '/../' ]  // > '..'.match(rx)
   * [ '..', index: 0, input: '..' ]
   * > '...'.match(rx)
   * null
   * > '..foo'.match(rx)
   * null
   * > 'bar..'.match(rx)
   * null
   * > 'foo/../bar'.match(rx)
   * [ '/..', index: 3, input: 'foo/../bar' ]
   * > 'foo..bar'.match(rx)
   * null
   * > 'foo/..bar'.match(rx)
   * null
   * > 'foo../bar'.match(rx)
   * null
   * > '../foo'.match(rx)
   * [ '..', index: 0, input: '../foo' ]
   * > '../../../../../etc/passwd'.match(rx)
   * [ '..', index: 0, input: '../../../../../etc/passwd' ]
   * > '/../../../../../etc/passwd'.match(rx)
   * [ '/..', index: 0, input: '/../../../../../etc/passwd' ]
   * !!! WE HAVE A WINNER !!!
   */
  // I need a rx that matches a hacker trying to use .. to
  // access files below the video root.
  //
  // Basically, I wanted /(?![^\/])\.\.(?![^\/])/ using the
  // first (?![^\/]) as a "not preceded by" but it does not
  // work as a "not preceded by" only a "not followed by"
  //
  // This sucessful rx is an non-capturing group of three
  // alternates matches (any where in string)
  //   1 - '/..[not followed by any char but /]'
  //   2 - '[beginning]..[not followed by any char but /]'
  //   3 - '[beginning]..[end]'
  var rx
  if (cfg.load) {
    console.log('index: cfg.load = %s', util.inspect(cfg.load, {depth:null,colors:true}))
    rx = /(?:\/\.\.(?![^\/])|^\.\.(?![^\/])|^\.\.$)/;
    // http response code 403 == Forbidden
    // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
    for (let subdir of cfg.load.subdirs) {
      console.log('subdir = %j', subdir)
      if (subdir.match(rx)) {
        console.log('index: %j.match(%s)', subdir, rx.toString())
        res.status(403).end('FUCK OFF')
        return
      }
    }
    console.log('index: subdirs passed')
    if (cfg.load.file.match(rx)) {
      console.log('index: HACKING ATTEMPTY subdir contained ..')
      res.status(403).end('FUCK OFF')
      return
    }
    console.log('index: file passed')
  }

  console.log("index: cfg = %j", { cfg: cfg })

  res.render('index', { pretty: true, cfg: cfg })
};
<commit_msg>increased the debug level from info to warn<commit_after>/*global   */

/*
 * GET app page.
 */

var util = require('util')
var u = require('lodash')

function isNonEmptyString(e) {
  if (u.isString(e) && e.length) return true
  return false
}

module.exports = function(req, res, next){
  'use strict';
  var app_cfg = req.app.get('app config by name')

  console.log("app_cfg =", util.inspect(app_cfg, {depth:null}))

  var cfg = { 'title'            : req.app.get('title')
            , 'video root names' : u.clone(app_cfg.order)
            , 'controls config'  :
              { skipForwSecs : app_cfg['skip forward seconds'] || 30
              , skipBackSecs : app_cfg['skip backward seconds'] || 10
              }

              /* cfg['load'] = { 'root'    : 'HDD Videos'
               *               , 'subdirs' : ['Films', 'Harry Potter']
               *               , 'file'    : '1 Harry Potter And The Sorcerer's Stone 2001.mp4'
               *               , 'time'    : 2715
               *               }
               */
            , 'load'             : undefined

              /* From video-app.js:21 or so
               * var levels    = ['info', 'warn', 'crit', 'none', 'error']
               * 'none' is a place holder for no logging except error
               * There is really only three optional levels info, warn, and crit.
               */
            , 'debug'            : 'warn'
            }

  console.log('index: cfg["video root names"] =', cfg['video root names'])

  console.log('index: req.query = %j', req.query)

  var queryOk = (function checkQuery() {
    var load = {}
    var root, subdirs, file, time
    var rootNames = cfg['video root names']
    console.log('checkQuery: req.query == trueish')
    console.log('checkQuery: ', util.inspect(req.query, {depth:null,colors:true}))
    if ( !Object.keys(req.query).length ) {
      console.log('index: checkQuery: req.query has no keys; fine, skipping the rest of checkQuery.')
      return true
    }

    root = req.query.root
    if (!root) return false
    if ( !rootNames.some(function(e){ return e == root }) ) return false
    load.root = root

    subdirs = req.query.subdirs
    if (!subdirs) return false
    if (!u.isArray(subdirs)) return false
    if ( !subdirs.every(isNonEmptyString) ) return false
    load.subdirs = req.query.subdirs

    file = req.query.file
    if (!file) return false
    if (!isNonEmptyString(file)) return false
    load.file = file

    time = req.query.time
    // we test each false possable except time=0
    if (isNonEmptyString(time) || u.isNumber(time)) {
      if (u.isString(time)) time = parseInt(time, 10)

      if (!isNaN(time)) {
        if (Number.isInteger(time))
          load.time = time
        else {
          load.time = Math.floor(time)
        }
      }
    }

    cfg.load = load

    return true
  })()

  if (!queryOk) {
    console.log('index: POST checkQuery(): BAD query calling next()')
    next()
    // FIXME: maybe I should do: http status 400 bad client request
    // res.status(400).render('bad_query')
    // and implemnets a nicer looking bad_query.jade
    return
  }

  /* FROM the node.js REPL on v5.1.0
   * > rx = /(?:\/\.\.(?![^\/])|^\.\.(?![^\/])|^\.\.$)/
   * /(?:\/\.\.(?![^\/])|^\.\.(?![^\/])|^\.\.$)/
   * > '/..'.match(rx)
   * [ '/..', index: 0, input: '/..' ]
   * > '../'.match(rx)
   * [ '..', index: 0, input: '../' ]
   * > '/../'.match(rx)
   * [ '/..', index: 0, input: '/../' ]  // > '..'.match(rx)
   * [ '..', index: 0, input: '..' ]
   * > '...'.match(rx)
   * null
   * > '..foo'.match(rx)
   * null
   * > 'bar..'.match(rx)
   * null
   * > 'foo/../bar'.match(rx)
   * [ '/..', index: 3, input: 'foo/../bar' ]
   * > 'foo..bar'.match(rx)
   * null
   * > 'foo/..bar'.match(rx)
   * null
   * > 'foo../bar'.match(rx)
   * null
   * > '../foo'.match(rx)
   * [ '..', index: 0, input: '../foo' ]
   * > '../../../../../etc/passwd'.match(rx)
   * [ '..', index: 0, input: '../../../../../etc/passwd' ]
   * > '/../../../../../etc/passwd'.match(rx)
   * [ '/..', index: 0, input: '/../../../../../etc/passwd' ]
   * !!! WE HAVE A WINNER !!!
   */
  // I need a rx that matches a hacker trying to use .. to
  // access files below the video root.
  //
  // Basically, I wanted /(?![^\/])\.\.(?![^\/])/ using the
  // first (?![^\/]) as a "not preceded by" but it does not
  // work as a "not preceded by" only a "not followed by"
  //
  // This sucessful rx is an non-capturing group of three
  // alternates matches (any where in string)
  //   1 - '/..[not followed by any char but /]'
  //   2 - '[beginning]..[not followed by any char but /]'
  //   3 - '[beginning]..[end]'
  var rx
  if (cfg.load) {
    console.log('index: cfg.load = %s', util.inspect(cfg.load, {depth:null,colors:true}))
    rx = /(?:\/\.\.(?![^\/])|^\.\.(?![^\/])|^\.\.$)/;
    // http response code 403 == Forbidden
    // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
    for (let subdir of cfg.load.subdirs) {
      console.log('subdir = %j', subdir)
      if (subdir.match(rx)) {
        console.log('index: %j.match(%s)', subdir, rx.toString())
        res.status(403).end('FUCK OFF')
        return
      }
    }
    console.log('index: subdirs passed')
    if (cfg.load.file.match(rx)) {
      console.log('index: HACKING ATTEMPTY subdir contained ..')
      res.status(403).end('FUCK OFF')
      return
    }
    console.log('index: file passed')
  }

  console.log("index: cfg = %j", { cfg: cfg })

  res.render('index', { pretty: true, cfg: cfg })
};
<|endoftext|>


<commit_before>var RepoBuilder = require('./../builder/RepoBuilder'),
    Schema = require('./../common/Schema'),
    ApiKeyManager = require('./../manager/ApiKeyManager'),
    logger = require('../common/Logger'),
    tmp = require('tmp');

    function HookController(mongoose){

    var apiKeyManager = new ApiKeyManager(mongoose);

    var buildRepo = function(hook, res){
        tmp.dir({prefix: 'intexration-'}, function(err, path) {
            if(err) logger.error('HookController: %s', 'Unable to create temp dir', {error: err});
            else {
                var repoBuilder = new RepoBuilder(hook, path);
                repoBuilder.build().then(function(b){
                    var Build = mongoose.model('Build', Schema.buildSchema);
                    var build = Build(b);
                    build.save(function(err){
                        if(err) logger.error('HookController: %s', 'Unable to store build', {error: err});
                        else {
                            res.json(b);
                        }
                    });
                }, function(err){
                    if(err) logger.error('HookController: %s', 'Unable to build repository', {error: err});
                });
            }
        });
    };

    this.post = function (req, res) {
        var data = req.body;
        apiKeyManager.validate(req.params.key, function(err){
            if(err) {
                res.status(401).json({message: 'Invalid API Key'});
            }
            else{
                if(data.hasOwnProperty('zen')){
                    res.json({message: "WebHook Setup Successful"});
                }else{
                    var Hook = mongoose.model('Hook', Schema.hookSchema);
                    var hk = {
                        owner: data.repository.owner.name,
                        repo: data.repository.name,
                        url: data.repository.url,
                        pusher: data.pusher.name,
                        message: data.head_commit.message,
                        timestamp: Date.now()
                    };
                    res.json(hk);
                    var hook = new Hook(hk);
                    hook.save(function(err){
                        if(err) logger.error('HookController: %s', 'Unable to store hook', {error: err});
                        else{
                            buildRepo(hk, res);
                        }
                    });
                }
            }
        });
    };

    this.getAll = function (req, res) {
        var Hook = mongoose.model('Hook', Schema.hookSchema);
        Hook.find({}, function(err, hooks){
            res.json(hooks);
        });
    };

    this.get = function (req, res) {
        var Hook = mongoose.model('Hook', Schema.hookSchema);
        Hook.find({"owner": req.params.owner, "repo": req.params.repo}, function(err, hooks){
            res.json(hooks);
        });
    }
}

module.exports = HookController;<commit_msg>More logging<commit_after>var RepoBuilder = require('./../builder/RepoBuilder'),
    Schema = require('./../common/Schema'),
    ApiKeyManager = require('./../manager/ApiKeyManager'),
    logger = require('../common/Logger'),
    tmp = require('tmp');

    function HookController(mongoose){

    var apiKeyManager = new ApiKeyManager(mongoose);

    var buildRepo = function(hook){
        tmp.dir({prefix: 'intexration-'}, function(err, path) {
            if(err) logger.error('HookController: %s', 'Unable to create temp dir', {error: err});
            else {
                var repoBuilder = new RepoBuilder(hook, path);
                repoBuilder.build().then(function(b){
                    var Build = mongoose.model('Build', Schema.buildSchema);
                    var build = Build(b);
                    build.save(function(err){
                        if(err) logger.error('HookController: %s', 'Unable to store build', {error: err});
                        else {
                            logger.debug('HookController: %s', 'Build stored', {build: b});
                        }
                    });
                }, function(err){
                    if(err) logger.error('HookController: %s', 'Unable to build repository', {error: err});
                });
            }
        });
    };

    this.post = function (req, res) {
        var data = req.body;
        apiKeyManager.validate(req.params.key, function(err){
            if(err) {
                res.status(401).json({message: 'Invalid API Key'});
            }
            else{
                if(data.hasOwnProperty('zen')){
                    res.json({message: "WebHook Setup Successful"});
                }else{
                    var Hook = mongoose.model('Hook', Schema.hookSchema);
                    var hk = {
                        owner: data.repository.owner.name,
                        repo: data.repository.name,
                        url: data.repository.url,
                        pusher: data.pusher.name,
                        message: data.head_commit.message,
                        timestamp: Date.now()
                    };
                    res.json(hk);
                    var hook = new Hook(hk);
                    hook.save(function(err){
                        if(err) logger.error('HookController: %s', 'Unable to store hook', {error: err});
                        else{
                            logger.debug('HookController: %s', 'Hook stored', {hook: hk});
                            buildRepo(hk, res);
                        }
                    });
                }
            }
        });
    };

    this.getAll = function (req, res) {
        var Hook = mongoose.model('Hook', Schema.hookSchema);
        Hook.find({}, function(err, hooks){
            res.json(hooks);
        });
    };

    this.get = function (req, res) {
        var Hook = mongoose.model('Hook', Schema.hookSchema);
        Hook.find({"owner": req.params.owner, "repo": req.params.repo}, function(err, hooks){
            res.json(hooks);
        });
    }
}

module.exports = HookController;<|endoftext|>


<commit_before>
/*
 * GET home page.
 */

exports.index = function(req, res){
    res.render('index', { title: 'Domsbay.be' });
};<commit_msg>New Title<commit_after>
/*
 * GET home page.
 */

exports.index = function(req, res){
    res.render('index', { title: 'Chat.' });
};<|endoftext|>


<commit_before>var express = require('express');
var request = require('request');
var http = require('http');
var router = express.Router();
var fixtures = require('./fixtures');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'FootScores' });
});

/* GET any leagues matches */
router.get('/fixtures/:id', function(req, res, next) {
  var matches = fixtures.getMatches(req.params.id, function(data) {
    res.render('matches', {matches: data});
  });
});

module.exports = router;
<commit_msg>Change names to be more self-explanatory<commit_after>var express = require('express');
var request = require('request');
var http = require('http');
var router = express.Router();
var fixtures = require('./fixtures');
var database = require('../database/mongo');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'FootScores' });
});

/* GET any leagues matches */
router.get('/fixtures/:id', function(req, res, next) {
  var matches = fixtures.getMatchesByCompetition(req.params.id, function(data) {
    res.render('matches', {matches: data});
  });
});

router.get('/matches', function(req, res, next) {
  database.getConnection(function(db) {
    fixtures.serveMatches(db.collection('partidos'));
  });
  res.render('matches', {matches: {}});
});

module.exports = router;
<|endoftext|>


<commit_before>// Get all of our friend data
var storyData = require('../storyData.json');

exports.view = function(req, res){
	console.log(storyData);
	var random_num = Math.random();

  if(random_num > 0.5)
  {
    res.render("index", storyData);
  }
  else
  {
    res.render("index_alternate", storyData)
  }

};
<commit_msg>final week 9 again<commit_after>// Get all of our friend data
var storyData = require('../storyData.json');

exports.view = function(req, res){
	console.log(storyData);
	//var random_num = Math.random();

  //if(random_num > 0.5)
  //{
    res.render("index", storyData);
  //}
  //else
  //{
   // res.render("index_alternate", storyData)
  //}

};
<|endoftext|>


<commit_before>var path = require('path')
	, fs = require('fs')
	, zlib = require('zlib')
	, events = require('../emitter')
	, url = require('url')
	, send = require('../utils/send')
	, mime = require('mime')

	, publicFolders = []

	, server

	, parsePath = function (urlIn) {
		'use strict';

		return url.parse(urlIn, true);
	}

	, parseRoutes = function (routes) {
		'use strict';

		var wildCardRoutes = {}
			, standardRoutes = {};

		Object.keys(routes).forEach(function (route) {
			var routeVariables = route.match(/:[a-zA-Z]+/g);

			if(routeVariables){
				//generate the regex for laters and
				//	store the verbs and variables belonging to the route
				wildCardRoutes[route] = {
											verbs: routes[route]
											, variables: routeVariables
											, eventId: route
											, regex: new RegExp(route.replace(/:[a-zA-Z]+/g, '([^\/]+)'))
										};
			} else {
				standardRoutes[route] = routes[route];
			}
		});

		return {wildcard: wildCardRoutes, standard: standardRoutes};
	}

	, isRoute = function (pathname, method, routesJson) {
		'use strict';

		return !!(routesJson[pathname] && routesJson[pathname].indexOf(method) !== -1);
	}

	, isWildCardRoute = function (pathname, method, routesJson) {
		'use strict';

		var matchedRoutes = Object.keys(routesJson).filter(function (route) {
					return !!(pathname.match(routesJson[route].regex));
				})
			, matchesVerb;

		if(matchedRoutes.length){
			matchesVerb = routesJson[matchedRoutes[0]].verbs.indexOf(method) !== -1;
		} else {
			matchesVerb = false;
		}

		return matchedRoutes.length > 0 && matchesVerb;
	}

	, parseWildCardRoute = function (pathname, routesJson) {
		'use strict';

		var matchedRoute = Object.keys(routesJson).filter(function (route) {
				return !!(pathname.match(routesJson[route].regex));
			})[0]

			, matches = pathname.match(routesJson[matchedRoute].regex)
			, values = {}
			, routeInfo = routesJson[matchedRoute]
			, i = 0;

		for(i = 0; i < routeInfo.variables.length; i++){
			values[routeInfo.variables[i].substring(1)] = matches[i + 1]; //offset by one to avoid the whole match which is at array[0]
		}

		return {route: routeInfo, values: values};
	}

	, setupStaticRoutes = function (routePathIn, publicPathIn) {
		'use strict';

		var routePath = path.join(process.cwd(), routePathIn)
			, publicPath = publicPathIn;

		//load in all the route handlers
		fs.readdirSync(routePath).forEach(function (file) {
			if(file !== 'index.js'){
				require(path.join(routePath, file));
			}
		});

		//load in all the static routes
		fs.exists(publicPath, function (exists) {
			if(exists){
				fs.readdirSync(publicPath).forEach(function (file) {
					if(fs.statSync(path.join(publicPath, file)).isDirectory()){
						publicFolders.push(file);
					}
				});
			}
		});
	}

	, getCompression = function (header, config) {
		'use strict';

		var type = ''
			, typeArray = header.split(', ')
			, maxq = 0;

		if(typeof config.compress !== 'undefined' && !config.compress){
			// compression turned off... bail
			return 'none';
		}

		if(header.match(/q=/)){
			//we have q values to calculate
			typeArray.forEach(function (qIn) {
				var q = parseFloat(qIn.match('/[0-9]\.[0-9]/')[0], 10);

				if(q > maxq){
					maxq = q;
					type = q.split(';')[0];
				}
			});
		} else {
			if (header.match(/\bgzip\b/)) {
			    type = 'gzip';
			} else if (header.match(/\bdeflate\b/)) {
			    type = 'deflate';
			} else {
			    type = 'none';
			}
		}

		return type;
	};

server = function (serverType, routesJson, config) {
	'use strict';

	var routesObj = parseRoutes(routesJson)
		, publicPath = path.join(process.cwd(), config.publicPath || './public')
		, maxAge = config.maxAge || 31536000
		, routeJSONPath = config.routesPath || '/routes';

	setupStaticRoutes(config.routePath, publicPath);

	return serverType.createServer(function (req, res) {
		var method = req.method.toLowerCase()
			, pathParsed = parsePath(req.url)
			, pathname = pathParsed.pathname
			, compression
			, file
			, connection = {
							req: req
							, res: res
							, query: pathParsed.query
							, params: {}
						};

		//add .send to the response
		res.send = send(req);

		//match the first part of the url... for public stuff
		if (publicFolders.indexOf(pathname.split('/')[1]) !== -1) {
			//static assets y'all
			file = path.join(publicPath, pathname);
			//read in the file and stream it to the client
			fs.exists(file, function (exists) {
				if(exists){
					events.required(['etag:check:' + file, 'etag:get:' + file], function (valid) {
						if(valid[0]){ // does the etag match? YES
							res.statusCode = 304;
							res.end();
						} else { //No match...
							res.setHeader('ETag', valid[1]); //the etag is item 2 in the array

							compression = getCompression(req.headers['accept-encoding'], config);

							if(compression !== 'none'){
								//we have compression!
								res.writeHead(200, {
									'Content-Type': mime.lookup(pathname),
									'Cache-Control': 'maxage=' + maxAge,
									'Content-Encoding': compression
								});

								if(compression === 'deflate'){
									fs.exists(file + '.def', function(exists){
										if(exists){
											fs.createReadStream(file + '.def').pipe(res);
										} else {
											//no compressed file yet...
											fs.createReadStream(file).pipe(zlib.createDeflate()).pipe(res);
											fs.createReadStream(file).pipe(zlib.createDeflate()).pipe(fs.createWriteStream(file + '.def'));
										}
									});
								} else if(compression !== 'none'){
									fs.exists(file + '.tgz', function(exists){
										if(exists){
											fs.createReadStream(file + '.tgz').pipe(res);
										} else {
											//no compressed file yet...
											fs.createReadStream(file).pipe(zlib.createGzip()).pipe(res);
											fs.createReadStream(file).pipe(zlib.createGzip()).pipe(fs.createWriteStream(file + '.tgz'));
										}
									});
								}

								events.emit('static:served', pathname);

							} else {
								//no compression carry on...
								//return with the correct heders for the file type
								res.writeHead(200, {
									'Content-Type': mime.lookup(pathname),
									'Cache-Control': 'maxage=' + maxAge
								});
								fs.createReadStream(file).pipe(res);
								events.emit('static:served', pathname);
							}
						}
					});

					events.emit('etag:check', {file: file, etag: req.headers['if-none-match']});

				} else {
					events.emit('static:missing', pathname);
					events.emit('error:404', connection);
				}
			});
		} else if (isRoute(pathname, method, routesObj.standard)) {
			//matches a route in the routes.json
			events.emit('route:' + pathname + ':' + method, connection);

		} else if (isWildCardRoute(pathname, method, routesObj.wildcard)) {
			var routeInfo = parseWildCardRoute(pathname, routesObj.wildcard);

			connection.params = routeInfo.values;

			//emit the event for the url minus params and include the params
			//	in the params object
			events.emit('route:' + routeInfo.route.eventId + ':' + method, connection);
		} else if(pathname === routeJSONPath){
			res.writeHead(200, {
				'Content-Type': mime.lookup('routes.json')
			});
			fs.createReadStream(path.join(process.cwd(), './routes.json')).pipe(res);
		} else {
			events.emit('error:404', connection);
		}
	});
};

module.exports = {
					server: server
					, parseWildCardRoute: parseWildCardRoute
					, isWildCardRoute: isWildCardRoute
					, parseRoutes: parseRoutes
					, parsePath: parsePath
				};
<commit_msg>fixed the wild card route matching issue<commit_after>var path = require('path')
	, fs = require('fs')
	, zlib = require('zlib')
	, events = require('../emitter')
	, url = require('url')
	, send = require('../utils/send')
	, mime = require('mime')

	, publicFolders = []

	, server

	, parsePath = function (urlIn) {
		'use strict';

		return url.parse(urlIn, true);
	}

	, parseRoutes = function (routes) {
		'use strict';

		var wildCardRoutes = {}
			, standardRoutes = {};

		Object.keys(routes).forEach(function (route) {
			var routeVariables = route.match(/:[a-zA-Z]+/g);

			if(routeVariables){
				//generate the regex for laters and
				//	store the verbs and variables belonging to the route
				wildCardRoutes[route] = {
											verbs: routes[route]
											, variables: routeVariables
											, eventId: route
											, regex: new RegExp('^' + route.replace(/:[a-zA-Z]+/g, '([^\/]+)') + '$')
										};
			} else {
				standardRoutes[route] = routes[route];
			}
		});

		return {wildcard: wildCardRoutes, standard: standardRoutes};
	}

	, isRoute = function (pathname, method, routesJson) {
		'use strict';

		return !!(routesJson[pathname] && routesJson[pathname].indexOf(method) !== -1);
	}

	, isWildCardRoute = function (pathname, method, routesJson) {
		'use strict';

		var matchedRoutes = Object.keys(routesJson).filter(function (route) {
					return !!(pathname.match(routesJson[route].regex));
				})
			, matchesVerb;

		if(matchedRoutes.length){
			matchesVerb = routesJson[matchedRoutes[0]].verbs.indexOf(method) !== -1;
		} else {
			matchesVerb = false;
		}

		return matchedRoutes.length > 0 && matchesVerb;
	}

	, parseWildCardRoute = function (pathname, routesJson) {
		'use strict';

		var matchedRoute = Object.keys(routesJson).filter(function (route) {
				return !!(pathname.match(routesJson[route].regex));
			})[0]

			, matches = pathname.match(routesJson[matchedRoute].regex)
			, values = {}
			, routeInfo = routesJson[matchedRoute]
			, i = 0;

		for(i = 0; i < routeInfo.variables.length; i++){
			values[routeInfo.variables[i].substring(1)] = matches[i + 1]; //offset by one to avoid the whole match which is at array[0]
		}

		return {route: routeInfo, values: values};
	}

	, setupStaticRoutes = function (routePathIn, publicPathIn) {
		'use strict';

		var routePath = path.join(process.cwd(), routePathIn)
			, publicPath = publicPathIn;

		//load in all the route handlers
		fs.readdirSync(routePath).forEach(function (file) {
			if(file !== 'index.js'){
				require(path.join(routePath, file));
			}
		});

		//load in all the static routes
		fs.exists(publicPath, function (exists) {
			if(exists){
				fs.readdirSync(publicPath).forEach(function (file) {
					if(fs.statSync(path.join(publicPath, file)).isDirectory()){
						publicFolders.push(file);
					}
				});
			}
		});
	}

	, getCompression = function (header, config) {
		'use strict';

		var type = ''
			, typeArray = header.split(', ')
			, maxq = 0;

		if(typeof config.compress !== 'undefined' && !config.compress){
			// compression turned off... bail
			return 'none';
		}

		if(header.match(/q=/)){
			//we have q values to calculate
			typeArray.forEach(function (qIn) {
				var q = parseFloat(qIn.match('/[0-9]\.[0-9]/')[0], 10);

				if(q > maxq){
					maxq = q;
					type = q.split(';')[0];
				}
			});
		} else {
			if (header.match(/\bgzip\b/)) {
			    type = 'gzip';
			} else if (header.match(/\bdeflate\b/)) {
			    type = 'deflate';
			} else {
			    type = 'none';
			}
		}

		return type;
	};

server = function (serverType, routesJson, config) {
	'use strict';

	var routesObj = parseRoutes(routesJson)
		, publicPath = path.join(process.cwd(), config.publicPath || './public')
		, maxAge = config.maxAge || 31536000
		, routeJSONPath = config.routesPath || '/routes';

	setupStaticRoutes(config.routePath, publicPath);

	return serverType.createServer(function (req, res) {
		var method = req.method.toLowerCase()
			, pathParsed = parsePath(req.url)
			, pathname = pathParsed.pathname
			, compression
			, file
			, connection = {
							req: req
							, res: res
							, query: pathParsed.query
							, params: {}
						};

		//add .send to the response
		res.send = send(req);

		//match the first part of the url... for public stuff
		if (publicFolders.indexOf(pathname.split('/')[1]) !== -1) {
			//static assets y'all
			file = path.join(publicPath, pathname);
			//read in the file and stream it to the client
			fs.exists(file, function (exists) {
				if(exists){
					events.required(['etag:check:' + file, 'etag:get:' + file], function (valid) {
						if(valid[0]){ // does the etag match? YES
							res.statusCode = 304;
							res.end();
						} else { //No match...
							res.setHeader('ETag', valid[1]); //the etag is item 2 in the array

							compression = getCompression(req.headers['accept-encoding'], config);

							if(compression !== 'none'){
								//we have compression!
								res.writeHead(200, {
									'Content-Type': mime.lookup(pathname),
									'Cache-Control': 'maxage=' + maxAge,
									'Content-Encoding': compression
								});

								if(compression === 'deflate'){
									fs.exists(file + '.def', function(exists){
										if(exists){
											fs.createReadStream(file + '.def').pipe(res);
										} else {
											//no compressed file yet...
											fs.createReadStream(file).pipe(zlib.createDeflate()).pipe(res);
											fs.createReadStream(file).pipe(zlib.createDeflate()).pipe(fs.createWriteStream(file + '.def'));
										}
									});
								} else if(compression !== 'none'){
									fs.exists(file + '.tgz', function(exists){
										if(exists){
											fs.createReadStream(file + '.tgz').pipe(res);
										} else {
											//no compressed file yet...
											fs.createReadStream(file).pipe(zlib.createGzip()).pipe(res);
											fs.createReadStream(file).pipe(zlib.createGzip()).pipe(fs.createWriteStream(file + '.tgz'));
										}
									});
								}

								events.emit('static:served', pathname);

							} else {
								//no compression carry on...
								//return with the correct heders for the file type
								res.writeHead(200, {
									'Content-Type': mime.lookup(pathname),
									'Cache-Control': 'maxage=' + maxAge
								});
								fs.createReadStream(file).pipe(res);
								events.emit('static:served', pathname);
							}
						}
					});

					events.emit('etag:check', {file: file, etag: req.headers['if-none-match']});

				} else {
					events.emit('static:missing', pathname);
					events.emit('error:404', connection);
				}
			});
		} else if (isRoute(pathname, method, routesObj.standard)) {
			//matches a route in the routes.json
			events.emit('route:' + pathname + ':' + method, connection);

		} else if (isWildCardRoute(pathname, method, routesObj.wildcard)) {
			var routeInfo = parseWildCardRoute(pathname, routesObj.wildcard);

			connection.params = routeInfo.values;

			//emit the event for the url minus params and include the params
			//	in the params object
			events.emit('route:' + routeInfo.route.eventId + ':' + method, connection);
		} else if(pathname === routeJSONPath){
			res.writeHead(200, {
				'Content-Type': mime.lookup('routes.json')
			});
			fs.createReadStream(path.join(process.cwd(), './routes.json')).pipe(res);
		} else {
			events.emit('error:404', connection);
		}
	});
};

module.exports = {
					server: server
					, parseWildCardRoute: parseWildCardRoute
					, isWildCardRoute: isWildCardRoute
					, parseRoutes: parseRoutes
					, parsePath: parsePath
				};
<|endoftext|>


<commit_before>
/**
 * Handles the db setup - adds the questions to the database if not there already
 * and handles the db connection
 */

var
	//serialport stuff
	com = require("serialport"),
	SerialPort = com.SerialPort,
	sp = null,
	isConnectionOpen = false,
	buffer = '',

	timer = null,
	uiState = null,

	SocketController = null,

	DELAY_ON_FAIL = 400,
	DELAY_ON_COMPLETE = 400,

	pkg = require('../../package.json');

var MsgController = {

	init : function (app, server, socketController, config) {

		console.log('MsgController :: INIT');

		SocketController = socketController;

		//setup our Arduino connection
		//commented out for testing purposes

		_self.Arduino.setupConnection();

		return _self;

	},

	sendMessage : function (to, msg) {

		console.log('sendMessage :: sending Message', msg);

		if (to === 'server') {

			_self.Arduino.writeOutput(msg);

		}

	},

	Arduino : {

		setupConnection : function () {

			//connect to the arduino through it’s path
			//sp = new SerialPort("/dev/tty.usbserial-A92HH373", {

			/*

			sp = new SerialPort("/dev/tty.usbmodem14111", {
				baudrate: 9600,
	    			parser: require("serialport").parsers.readline('\r\n')
			});

			//wait for our connection to open up
			sp.open(function (e) {
				if (e) {
					console.log('failed to open : '+ e);
				} else {
					_self.Arduino.onSerialOpen();
				}
			});

			*/

		},

		//takes a string and writes it to the arduino
		writeOutput : function (data) {

			sp.write(data, function (error) {
				if (error !== undefined) {
					console.log(error);
				}
			});

		},

		onSerialOpen : function () {

			console.log('arduino : connection opened');
			//now our connection is open, we can read/write as much as we want, so set the state to reflect this
			isConnectionOpen = true;

			//setup the receiver for any data coming through from the arduino
			sp.on('data', _self.Arduino.onDataReceived);

		},

		onDataReceived : function (data) {

			var dataString = data.toString();

			console.log(data);

			switch (dataString) {
				case 'TWEET':
					_self.sendMessage('server', 'notready');
					break;
			}

		}
	},

	//this handles all of our UI connections detected through our socketServer
	//newConnection gets called on every new connection and sets up events for that socket
	UI : {

		newConnection : function (socket) {

			_self.UI.initCustomEvents(socket);

			uiState = 'connected';
			SocketController.emitMsg('connectSuccess');
		},

		initCustomEvents : function (socket) {
			socket.on('tweet-sent', _self.UI.tweetSendHandler);
		},

		tweetSendHandler : function (data) {
			_self.sendMessage('server', data + '\n');
		},

		userLoginHandler : function () {
			console.log('ui : user is ready');

			//see if the arduino is in a ready state
			_self.UI.sendStartSignal();

			//ui is in a loading state while it waits for the arduino to respond that it is ready
			uiState = 'loading';
		},

		userRetryHandler : function () {

			uiState = 'connected';

			_self.UI.userLoginHandler();
		},

		userResetHandler : function () {

			uiState = 'connected';

			socketServer.emitMsg('changeView', { view : 'initial' });
		},

		receiveMsg : function (msg) {

			console.log('ui : message received : ' + msg);

			//dependent on msg, fire different responses
			switch (msg) {
				case 'tweet-sent':
					_self.sendMessage('server', msg);
					break;
				case 'notready':
					_self.UI.sendStartSignal(500);
					break;
				case 'ready':
					socketServer.emitMsg('changeView', { view : 'inPlay' });
					break;
				case 'fail':
					setTimeout(function () {
						socketServer.emitMsg('capture', { state : 'fail' });
					}, DELAY_ON_FAIL);
					break;
				case 'complete':
					setTimeout(function () {
						socketServer.emitMsg('capture', { state : 'complete' });
					}, DELAY_ON_COMPLETE);
					break;
			}

		},

		sendStartSignal : function (delay) {

			console.log('sendStartSignal');

			delay = (delay !== null ? delay : 0);

			//writes 0 to the server to see if its ready
			//waits x milliseconds if delay is set
			timer = setTimeout(function () {
				_self.sendMessage('server', '0');
			}, delay);

			if (uiState === 'connected') {
				SocketController.emitMsg('changeView', { view : 'loader' });
			}

		}
	}
};

var _self = MsgController;

module.exports = MsgController;

<commit_msg>Changing open method<commit_after>
/**
 * Handles the db setup - adds the questions to the database if not there already
 * and handles the db connection
 */

var
	//serialport stuff
	com = require("serialport"),
	SerialPort = com.SerialPort,
	sp = null,
	isConnectionOpen = false,
	buffer = '',

	timer = null,
	uiState = null,

	SocketController = null,

	DELAY_ON_FAIL = 400,
	DELAY_ON_COMPLETE = 400,

	pkg = require('../../package.json');

var MsgController = {

	init : function (app, server, socketController, config) {

		console.log('MsgController :: INIT');

		SocketController = socketController;

		//setup our Arduino connection
		//commented out for testing purposes

		_self.Arduino.setupConnection();

		return _self;

	},

	sendMessage : function (to, msg) {

		console.log('sendMessage :: sending Message', msg);

		if (to === 'server') {

			_self.Arduino.writeOutput(msg);

		}

	},

	Arduino : {

		setupConnection : function () {

			//connect to the arduino through it’s path
			//sp = new SerialPort("/dev/tty.usbserial-A92HH373", {

			sp = new SerialPort("COM11", {
					baudrate: 0,
	    			parser: require("serialport").parsers.readline('\r\n')
			});

			//wait for our connection to open up
			sp.on('open', function (e) {
				if (e) {
					console.log('failed to open : '+ e);
				} else {
					_self.Arduino.onSerialOpen();
				}
			});

		},

		//takes a string and writes it to the arduino
		writeOutput : function (data) {

			sp.write(data, function (error) {
				if (error !== undefined) {
					console.log(error);
				}
			});

		},

		onSerialOpen : function () {

			console.log('arduino : connection opened');
			//now our connection is open, we can read/write as much as we want, so set the state to reflect this
			isConnectionOpen = true;

			//setup the receiver for any data coming through from the arduino
			sp.on('data', _self.Arduino.onDataReceived);

		},

		onDataReceived : function (data) {

			var dataString = data.toString();

			console.log(data);

			switch (dataString) {
				case 'TWEET':
					_self.sendMessage('server', 'notready');
					break;
			}

		}
	},

	//this handles all of our UI connections detected through our socketServer
	//newConnection gets called on every new connection and sets up events for that socket
	UI : {

		newConnection : function (socket) {

			_self.UI.initCustomEvents(socket);

			uiState = 'connected';
			SocketController.emitMsg('connectSuccess');
		},

		initCustomEvents : function (socket) {
			socket.on('tweet-sent', _self.UI.tweetSendHandler);
		},

		tweetSendHandler : function (data) {
			_self.sendMessage('server', data + '\n');
		},

		userLoginHandler : function () {
			console.log('ui : user is ready');

			//see if the arduino is in a ready state
			_self.UI.sendStartSignal();

			//ui is in a loading state while it waits for the arduino to respond that it is ready
			uiState = 'loading';
		},

		userRetryHandler : function () {

			uiState = 'connected';

			_self.UI.userLoginHandler();
		},

		userResetHandler : function () {

			uiState = 'connected';

			socketServer.emitMsg('changeView', { view : 'initial' });
		},

		receiveMsg : function (msg) {

			console.log('ui : message received : ' + msg);

			//dependent on msg, fire different responses
			switch (msg) {
				case 'tweet-sent':
					_self.sendMessage('server', msg);
					break;
				case 'notready':
					_self.UI.sendStartSignal(500);
					break;
				case 'ready':
					socketServer.emitMsg('changeView', { view : 'inPlay' });
					break;
				case 'fail':
					setTimeout(function () {
						socketServer.emitMsg('capture', { state : 'fail' });
					}, DELAY_ON_FAIL);
					break;
				case 'complete':
					setTimeout(function () {
						socketServer.emitMsg('capture', { state : 'complete' });
					}, DELAY_ON_COMPLETE);
					break;
			}

		},

		sendStartSignal : function (delay) {

			console.log('sendStartSignal');

			delay = (delay !== null ? delay : 0);

			//writes 0 to the server to see if its ready
			//waits x milliseconds if delay is set
			timer = setTimeout(function () {
				_self.sendMessage('server', '0');
			}, delay);

			if (uiState === 'connected') {
				SocketController.emitMsg('changeView', { view : 'loader' });
			}

		}
	}
};

var _self = MsgController;

module.exports = MsgController;

<|endoftext|>


<commit_before>var express     = require('express'),
    router      = express.Router(),
    passport    = require('passport'),
    auth        = require('connect-ensure-login');

/* GET home page. */
router.get('/', auth.ensureLoggedIn('/login'), function(req, res, next) {
  console.log(req.currentUser);
  res.render('index');
});

module.exports = router;
<commit_msg>add testing route<commit_after>var express     = require('express'),
    router      = express.Router(),
    passport    = require('passport'),
    auth        = require('connect-ensure-login');
/* GET home page. */
router.get('/', auth.ensureLoggedIn('/login'), function(req, res, next) {
  console.log(req.currentUser);
  res.render('index');
});

router.get('/test',auth.ensureLoggedIn('/login'), function(req, res, next) {
    console.log(req.currentUser);
    res.render('test');
});

router.post('/test', function (req, res, next) {
    console.log('tags is : ' + req.body.tags);

});

module.exports = router;
<|endoftext|>


<commit_before>var express = require('express')
var router = express.Router()
var multer = require('multer')
var dateFormat = require('dateformat')

var db = require('../db')

var storage = multer.diskStorage({
  destination: function (request, file, callback) {
    callback(null, './public/images/blog')
  },
  filename: function (request, file, callback) {
    callback(null, file.originalname)
  }
})
var upload = multer({storage: storage})

// SITE STRUCTURE

// Frontpage - URL - /
router.get('/', function (req, res) {
  db.getRecentBlogs(req.app.get('connection'))
  .then((results) => {
    const viewData = {
      blog: []
    }
    for (var i = 0; i < results.length; i++) {
      const blogEntry = {
        title: results[i].title,
        published_date: dateFormat(results[i].published_date, 'mmmm dd yyyy'),
        image: results[i].image,
        summary: results[i].summary,
        first_name: results[i].first_name,
        last_name: results[i].last_name,
        profile_id: results[i].profile_id,
        tags: results[i].tags,
        slug: results[i].slug}
      viewData.blog.push(blogEntry)
    }
    res.render('index', viewData)
  })
  .catch(function (err) {
    res.status(500).send('DATABASE ERROR: ' + err.message)
  })
})

// Blog section - URL - /blog
router.get('/blog', function (req, res) {
  db.getOldBlogs(req.app.get('connection'))
  .then((results) => {
    const viewData = {
      blog: []
    }
    for (var i = 0; i < results.length; i++) {
      const blogEntry = {
        title: results[i].title,
        published_date: dateFormat(results[i].published_date, 'mmmm dd yyyy'),
        image: results[i].image,
        summary: results[i].summary,
        first_name: results[i].first_name,
        last_name: results[i].last_name,
        profile_id: results[i].profile_id,
        tags: results[i].tags,
        slug: results[i].slug}
      viewData.blog.push(blogEntry)
    }
    res.render('index', viewData)
  })
  .catch(function (err) {
    res.status(500).send('DATABASE ERROR: ' + err.message)
  })
})

// BLOG ROUTER

// Add blog router
router.get('/blog/add', function (req, res) {
  res.render('addBlog')
})

router.post('/blog/add', upload.single('image'), function (req, res) {
  const title = req.body.title
  const slug = req.body.title.replace(/ /g, '-').toLowerCase()
  const body = req.body.body
  const author = req.body.typeahead
  const summary = req.body.summary
  const status = req.body.status
  const tags = req.body.tags
  const today = new Date()
  const date = dateFormat(today, 'yyyy-mm-dd 08:00:00')
  const image = req.file.path.replace('public', '')

  db.addBlogPost(title, slug, body, author, summary, image, status, date, tags, req.app.get('connection'))
  .then(results => {
    res.redirect(`/blog/${results[0].slug}`)
  })
  .catch(function (err) {
    res.status(500).send('DATABASE ERROR: ' + err.message)
  })
})

// Get blog router
router.get('/blog/:id', function (req, res) {
  var blogSlug = req.params.id
  db.getBlogPost(blogSlug, req.app.get('connection'))
  .then((result) => {
    const viewData = {
      title: result[0].title,
      body: result[0].body,
      date: dateFormat(result[0].published_date, 'mmmm dd yyyy'),
      image: result[0].image,
      first_name: result[0].first_name,
      last_name: result[0].last_name,
      profile_id: result[0].profile_id,
      tags: result[0].tags
    }
    res.render('blogPost', viewData)
  })
  .catch(function (err) {
    res.status(500).send('DATABASE ERROR: ' + err.message)
  })
})

// Edit blog router
router.get('/blog/:id/edit', function (req, res) {
  const blogSlug = req.params.id
  db.getBlogPost(blogSlug, req.app.get('connection'))
  .then((result) => {
    console.log(result)
    res.render('addBlog', result[0])
  })
})

//  HELPER ROUTER
router.get('/search', function (req, res) {
  var author = req.query.key
  db.getAuthor(author, req.app.get('connection'))
  .then(function (results) {
    var data = []
    for(prop in results) {
      data.push(results[prop].name)
    }
    res.end(JSON.stringify(data))
  })
  .catch(function (err) {
    res.status(500).send('DATABASE ERROR: ' + err.message)
  })
})
module.exports = router
<commit_msg>Added route for project section<commit_after>var express = require('express')
var router = express.Router()
var multer = require('multer')
var dateFormat = require('dateformat')

var db = require('../db')

var storage = multer.diskStorage({
  destination: function (request, file, callback) {
    callback(null, './public/images/blog')
  },
  filename: function (request, file, callback) {
    callback(null, file.originalname)
  }
})
var upload = multer({storage: storage})

// SITE STRUCTURE

// Frontpage - URL - /
router.get('/', function (req, res) {
  db.getRecentBlogs(req.app.get('connection'))
  .then((results) => {
    const viewData = {
      blog: []
    }
    for (var i = 0; i < results.length; i++) {
      const blogEntry = {
        title: results[i].title,
        published_date: dateFormat(results[i].published_date, 'mmmm dd yyyy'),
        image: results[i].image,
        summary: results[i].summary,
        first_name: results[i].first_name,
        last_name: results[i].last_name,
        profile_id: results[i].profile_id,
        tags: results[i].tags,
        slug: results[i].slug}
      viewData.blog.push(blogEntry)
    }
    res.render('index', viewData)
  })
  .catch(function (err) {
    res.status(500).send('DATABASE ERROR: ' + err.message)
  })
})

// Blog section - URL - /blog
router.get('/blog', function (req, res) {
  db.getOldBlogs(req.app.get('connection'))
  .then((results) => {
    const viewData = {
      blog: []
    }
    for (var i = 0; i < results.length; i++) {
      const blogEntry = {
        title: results[i].title,
        published_date: dateFormat(results[i].published_date, 'mmmm dd yyyy'),
        image: results[i].image,
        summary: results[i].summary,
        first_name: results[i].first_name,
        last_name: results[i].last_name,
        profile_id: results[i].profile_id,
        tags: results[i].tags,
        slug: results[i].slug}
      viewData.blog.push(blogEntry)
    }
    res.render('index', viewData)
  })
  .catch(function (err) {
    res.status(500).send('DATABASE ERROR: ' + err.message)
  })
})

// Projects section - URL - /projects
router.get('/projects', function (req, res) {
  db.getProjects(req.app.get('connection'))
  .then(results => {
    const viewData = {
      project: results
    }
    res.render('projectPost', viewData)
  })
  .catch(function (err) {
    res.status(500).send('DATABASE ERROR: ' + err.message)
  })
})

// BLOG ROUTER

// Add blog router
router.get('/blog/add', function (req, res) {
  res.render('addBlog')
})

router.post('/blog/add', upload.single('image'), function (req, res) {
  const title = req.body.title
  const slug = req.body.title.replace(/ /g, '-').toLowerCase()
  const body = req.body.body
  const author = req.body.typeahead
  const summary = req.body.summary
  const status = req.body.status
  const tags = req.body.tags
  const today = new Date()
  const date = dateFormat(today, 'yyyy-mm-dd 08:00:00')
  const image = req.file.path.replace('public', '')

  db.addBlogPost(title, slug, body, author, summary, image, status, date, tags, req.app.get('connection'))
  .then(results => {
    res.redirect(`/blog/${results[0].slug}`)
  })
  .catch(function (err) {
    res.status(500).send('DATABASE ERROR: ' + err.message)
  })
})

// Get blog router
router.get('/blog/:id', function (req, res) {
  var blogSlug = req.params.id
  db.getBlogPost(blogSlug, req.app.get('connection'))
  .then((result) => {
    const viewData = {
      title: result[0].title,
      body: result[0].body,
      date: dateFormat(result[0].published_date, 'mmmm dd yyyy'),
      image: result[0].image,
      first_name: result[0].first_name,
      last_name: result[0].last_name,
      profile_id: result[0].profile_id,
      tags: result[0].tags
    }
    res.render('blogPost', viewData)
  })
  .catch(function (err) {
    res.status(500).send('DATABASE ERROR: ' + err.message)
  })
})

// Edit blog router
router.get('/blog/:id/edit', function (req, res) {
  const blogSlug = req.params.id
  db.getBlogPost(blogSlug, req.app.get('connection'))
  .then((result) => {
    console.log(result)
    res.render('addBlog', result[0])
  })
})

//  HELPER ROUTER
router.get('/search', function (req, res) {
  var author = req.query.key
  db.getAuthor(author, req.app.get('connection'))
  .then(function (results) {
    var data = []
    for(prop in results) {
      data.push(results[prop].name)
    }
    res.end(JSON.stringify(data))
  })
  .catch(function (err) {
    res.status(500).send('DATABASE ERROR: ' + err.message)
  })
})
module.exports = router
<|endoftext|>