<commit_before>/**
 * @fileoverview Schema format.
 *
 * @externs
 */

/**
 * @constructor
 */
function IndexSchema() {}

/**
 * @type {string}
 */
IndexSchema.prototype.name;

/**
 * @type {string}
 */
IndexSchema.prototype.type;

/**
 * @type {boolean}
 */
IndexSchema.prototype.unique;

/**
 * @type {string}
 */
IndexSchema.prototype.keyPath;

/**
 * @type {boolean}
 */
IndexSchema.prototype.multiEntry;

/**
 * @constructor
 */
var KeyPaths = function() {};

/**
 * @type {string}
 */
KeyPaths.prototype.id;

/**
 * @type {string}
 */
KeyPaths.prototype.etag;

/**
 * @type {string}
 */
KeyPaths.prototype.nextUrl;

/**
 * @type {string}
 */
KeyPaths.prototype.updated;

/**
 * @constructor
 */
var AtomOptions = function() {};

/**
 * @type {string}
 */
AtomOptions.prototype.baseUri;

/**
 * @type {KeyPaths}
 */
AtomOptions.prototype.KeyPaths;

/**
 * @type {string}
 */
AtomOptions.prototype.metaStoreName;

/**
 * @see http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html
 * @extends {AtomOptions}
 * @constructor
 */
var S3Options = function() {};

/**
 * @type {string?}
 */
S3Options.prototype.delimiter;

/**
 * @type {string?}
 */
S3Options.prototype.maxKeys;

/**
 * @type {string?}
 */
S3Options.prototype.prefix;

/**
 * @extends {AtomOptions}
 * @constructor
 */
var GDataOptions = function() {};

/**
 * @type {string?}
 */
GDataOptions.prototype.version;

/**
 * @type {string?}
 */
GDataOptions.prototype.projection;

/**
 * @extends {AtomOptions}
 * @constructor
 */
var ODataOptions = function() {};

/**
 * @constructor
 */
function StoreSyncOptionJson() {}

/**
 * @type {string}
 */
StoreSyncOptionJson.prototype.format;

/**
 * @type {number}
 */
StoreSyncOptionJson.prototype.readRequestTimeout;

/**
 * @type {number}
 */
StoreSyncOptionJson.prototype.writeRequestTimeout;

/**
 * @type {{request: Function}}
 */
StoreSyncOptionJson.prototype.transport;

/**
 * @type {AtomOptions|GDataOptions|ODataOptions|S3Options}
 */
StoreSyncOptionJson.prototype.Options;

/**
 * Entry list fetch strategy. Supported method are
 * ['last-updated', 'descending-key']
 * @type {Array}
 */
StoreSyncOptionJson.prototype.fetchStrategies;

/**
 * @constructor
 */
function StoreSchema() {}

/**
 * @type {string}
 */
StoreSchema.prototype.name;

/**
 * @type {string}
 */
StoreSchema.prototype.keyPath;

/**
 * @type {boolean}
 */
StoreSchema.prototype.autoIncrement;

/**
 * @type {string}
 */
StoreSchema.prototype.type;

/**
 * @type {Array.<!IndexSchema>}
 */
StoreSchema.prototype.indexes;

/**
 * @type {boolean}
 */
StoreSchema.prototype.dispatchEvents;

/**
 * A fixed schema.
 * @type {boolean}
 */
StoreSchema.prototype.fixed;

/**
 * Name of sync
 * @type {StoreSyncOptionJson}
 */
StoreSchema.prototype.Sync;

/**
 * @constructor
 */
function DatabaseSchema() {}

/**
 * @type {number}
 */
DatabaseSchema.prototype.version;

/**
 * @type {Array.<!StoreSchema>}
 */
DatabaseSchema.prototype.stores;
<commit_msg>public read.<commit_after>/**
 * @fileoverview Schema format.
 *
 * @externs
 */

/**
 * @constructor
 */
function IndexSchema() {}

/**
 * @type {string}
 */
IndexSchema.prototype.name;

/**
 * @type {string}
 */
IndexSchema.prototype.type;

/**
 * @type {boolean}
 */
IndexSchema.prototype.unique;

/**
 * @type {string}
 */
IndexSchema.prototype.keyPath;

/**
 * @type {boolean}
 */
IndexSchema.prototype.multiEntry;

/**
 * @constructor
 */
var KeyPaths = function() {};

/**
 * @type {string}
 */
KeyPaths.prototype.id;

/**
 * @type {string}
 */
KeyPaths.prototype.etag;

/**
 * @type {string}
 */
KeyPaths.prototype.nextUrl;

/**
 * @type {string}
 */
KeyPaths.prototype.updated;

/**
 * @constructor
 */
var AtomOptions = function() {};

/**
 * @type {string}
 */
AtomOptions.prototype.baseUri;

/**
 * @type {KeyPaths}
 */
AtomOptions.prototype.KeyPaths;

/**
 * @type {string}
 */
AtomOptions.prototype.metaStoreName;

/**
 * @see http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html
 * @extends {AtomOptions}
 * @constructor
 */
var S3Options = function() {};

/**
 * @type {string?}
 */
S3Options.prototype.delimiter;

/**
 * @type {string?}
 */
S3Options.prototype.maxKeys;

/**
 * @type {string?}
 */
S3Options.prototype.prefix;

/**
 * @extends {AtomOptions}
 * @constructor
 */
var GDataOptions = function() {};

/**
 * @type {string?}
 */
GDataOptions.prototype.version;

/**
 * @type {string?}
 */
GDataOptions.prototype.projection;

/**
 * @extends {AtomOptions}
 * @constructor
 */
var ODataOptions = function() {};

/**
 * @constructor
 */
function StoreSyncOptionJson() {}

/**
 * @type {boolean}
 */
StoreSyncOptionJson.prototype.publicRead;

/**
 * @type {string}
 */
StoreSyncOptionJson.prototype.format;

/**
 * @type {number}
 */
StoreSyncOptionJson.prototype.readRequestTimeout;

/**
 * @type {number}
 */
StoreSyncOptionJson.prototype.writeRequestTimeout;

/**
 * @type {{request: Function}}
 */
StoreSyncOptionJson.prototype.transport;

/**
 * @type {AtomOptions|GDataOptions|ODataOptions|S3Options}
 */
StoreSyncOptionJson.prototype.Options;

/**
 * Entry list fetch strategy. Supported method are
 * ['last-updated', 'descending-key']
 * @type {Array}
 */
StoreSyncOptionJson.prototype.fetchStrategies;

/**
 * @constructor
 */
function StoreSchema() {}

/**
 * @type {string}
 */
StoreSchema.prototype.name;

/**
 * @type {string}
 */
StoreSchema.prototype.keyPath;

/**
 * @type {boolean}
 */
StoreSchema.prototype.autoIncrement;

/**
 * @type {string}
 */
StoreSchema.prototype.type;

/**
 * @type {Array.<!IndexSchema>}
 */
StoreSchema.prototype.indexes;

/**
 * @type {boolean}
 */
StoreSchema.prototype.dispatchEvents;

/**
 * A fixed schema.
 * @type {boolean}
 */
StoreSchema.prototype.fixed;

/**
 * Name of sync
 * @type {StoreSyncOptionJson}
 */
StoreSchema.prototype.Sync;

/**
 * @constructor
 */
function DatabaseSchema() {}

/**
 * @type {number}
 */
DatabaseSchema.prototype.version;

/**
 * @type {Array.<!StoreSchema>}
 */
DatabaseSchema.prototype.stores;
<|endoftext|>


<commit_before>/* eslint-disable arrow-body-style */

import createReducer from 'utils/createReducer';
import Immutable from 'seamless-immutable';
import t from 'tcomb';
import { AuthContext } from './types';

import {
	INITIALIZE,
	INITIALIZE_FINISH,
	LOGIN,
	LOGIN_SUCCESS,
	LOGIN_FAILURE,
	LOGOUT_SUCCESS,
} from './actions';

export default createReducer(
	AuthContext,
	Immutable.from({
		user: null,
		errors: [],
		initializing: false,
		initialized: false,
		authenticating: false,
	}),
	{
		[INITIALIZE]: (state, action) => {
			return state.merge({
				...action.payload,
				initializing: true,
			});
		},
		[INITIALIZE_FINISH]: (state, action) => {
			return state.merge({
				...action.payload,
				initializing: false,
				initialized: true,
			});
		},
		[LOGIN]: (state) => {
			if (state.user) {
				return state;
			}
			return state.merge({
				errors: [],
				authenticating: true,
			});
		},
		[LOGIN_SUCCESS]: [
			t.struct({
				user: t.Object,
			}),
			(state, action) => {
				return state.merge({
					...action.payload,
					authenticating: false,
				});
			}
		],
		[LOGIN_FAILURE]: [
			t.struct({
				error: t.Object,
			}),
			(state, action) => {
				const { error } = action.payload;
				return state
					.update('errors', (errors, newError) => errors.concat([newError]), error)
					.merge({ authenticating: false });
			}
		],
		[LOGOUT_SUCCESS]: (state, action) => {
			return state.merge({
				...action.payload,
				user: null,
			});
		},
	},
	'auth'
);
<commit_msg>chore(modules/auth): lint<commit_after>/* eslint-disable arrow-body-style */

import createReducer from 'utils/createReducer';
import Immutable from 'seamless-immutable';
import t from 'tcomb';
import { AuthContext } from './types';

import {
	INITIALIZE,
	INITIALIZE_FINISH,
	LOGIN,
	LOGIN_SUCCESS,
	LOGIN_FAILURE,
	LOGOUT_SUCCESS,
} from './actions';

export default createReducer(
	AuthContext,
	Immutable.from({
		user: null,
		errors: [],
		initializing: false,
		initialized: false,
		authenticating: false,
	}),
	{
		[INITIALIZE]: (state, action) => {
			return state.merge({
				...action.payload,
				initializing: true,
			});
		},
		[INITIALIZE_FINISH]: (state, action) => {
			return state.merge({
				...action.payload,
				initializing: false,
				initialized: true,
			});
		},
		[LOGIN]: (state) => {
			if (state.user) {
				return state;
			}
			return state.merge({
				errors: [],
				authenticating: true,
			});
		},
		[LOGIN_SUCCESS]: [
			t.struct({
				user: t.Object,
			}),
			(state, action) => {
				return state.merge({
					...action.payload,
					authenticating: false,
				});
			},
		],
		[LOGIN_FAILURE]: [
			t.struct({
				error: t.Object,
			}),
			(state, action) => {
				const { error } = action.payload;
				return state
					.update('errors', (errors, newError) => errors.concat([newError]), error)
					.merge({ authenticating: false });
			},
		],
		[LOGOUT_SUCCESS]: (state, action) => {
			return state.merge({
				...action.payload,
				user: null,
			});
		},
	},
	'auth'
);
<|endoftext|>


<commit_before>/** @jsx React.DOM */

define(
  [
    'react',
    './Header.react',
    './Footer.react'
  ],
  function (React, Header, Footer) {

    return React.createClass({

      render: function () {

        var footer = (
          true ?  : null
        );

        return (

              {this.props.content}

            {footer}

        );
      }

    });

  });
<commit_msg>clean up root component<commit_after>/** @jsx React.DOM */

define(
  [
    'react',
    'backbone',
    './Header.react',
    './Footer.react'
  ],
  function (React, Backbone, Header, Footer) {

    return React.createClass({

      propTypes: {
        profile: React.PropTypes.instanceOf(Backbone.Model).isRequired,
        currentRoute: React.PropTypes.oneOfType([
          React.PropTypes.string,
          React.PropTypes.array
        ])
      },

      render: function () {
        return (

              {this.props.content}

        );
      }

    });

  });
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var async = require('async');
var mongoose = require('mongoose');
var Person = mongoose.model('Person');
var GraphNode = mongoose.model('GraphNode');
var ActivityLink = mongoose.model('ActivityLink');

var getNode = function(person, graphnode) {
    var result = {
        id:       person.id,
        fullName: person.fullName,
        team:     person.team,
        type:     person.getType()
    };

    if (typeof graphnode !== 'undefined') {
        if (typeof graphnode.coordX !== 'undefined') {
            result.coordX = graphnode.coordX;
        }
        if (typeof graphnode.coordY !== 'undefined') {
            result.coordY = graphnode.coordY;
        }
    }

    return result;
};

// TODO: this needs unit testing
// TODO: this function is ridiculously long
var getGraph = function(person, cb) {
    GraphNode
        .find({owner: person.id})
        .populate('target', 'fullName password team')
        .exec(function (err, nodes) {
            if (err) {
                cb(err);
                return;
            }

            var persons = _.pluck(nodes, 'target');
            var friendIds = _.pluck(persons, 'id');

            // transform this into a map for easier random access
            persons = _.indexBy(persons, 'id');
            nodes   = _.indexBy(nodes, function(n) { return n.target.id; });

            // Count the activities between the people in the social graph
            // Get all the activities of the user and the friends
            // (including activities to friends of friends)
            ActivityLink
                .find()
                .or([
                    {source: { $in: friendIds } },
                    {target: { $in: friendIds } }
                ])
                .populate('source')
                .populate('target')
                .exec(function(err, links) {
                    // We need to map these activity links, and transform them into a 2d
                    // structure that maps source/target pairs to counts.
                    var counts = {};
                    _.each(links, function(l) {
                        counts[l.source.id] = counts[l.source.id] || {};
                        if (typeof counts[l.source.id][l.target.id] === 'undefined') {
                            counts[l.source.id][l.target.id] = {
                                open: 0,
                                completed: 0
                            };
                        }
                        counts[l.source.id][l.target.id][l.success ? 'completed' : 'open'] += 1;
                        _.each([l.source, l.target], function(p) {
                            if (typeof persons[p.id] === 'undefined') {
                                persons[p.id] = p;
                            }
                        });
                    });

                    // Convert to the format needed by the frontend
                    var graphLinks = _.map(counts, function(cc, s) {
                        return _.map(cc, function(c, t) {
                            var link = {
                                source: s,
                                target: t
                            };

                            // Add the number of activities if the given person is part of the link
                            if (s === person.id || t === person.id) {
                                link.openActivities = c.open;
                                link.completedActivities = c.completed;
                            }
                            return link;
                        });
                    });
                    graphLinks = _.flatten(graphLinks);

                    async.each(
                        _.toArray(persons),
                        function(p, cb) {
                            p.populateActivityLinks(cb);
                        },
                        function (err) {
                            if (err) {
                                cb(err);
                            } else {
                                var friendIndex = _.indexBy(friendIds);
                                var resultnodes = _.map(persons, function (n) {
                                    var result = getNode(n, nodes[n.id]);
                                    if (result.id === person.id) {
                                        result.relation = 'me';
                                        result.coordX = 0.5;
                                        result.coordY = 0.5;
                                    } else if (friendIndex[result.id]) {
                                        result.relation = 'friend';
                                    } else {
                                        result.relation = 'friendOfFriend';
                                        result.fullName = undefined;
                                    }
                                    return result;
                                });
                                cb(null, {
                                    nodes: _.indexBy(resultnodes, 'id'),
                                    links: graphLinks
                                });
                            }
                        }
                    );
                })
            ;
        })
    ;
};

exports.view = function(req, res, next) {
    // Get the entire social graph for me
    getGraph(req.user, function(err, graph) {
        if (err) {
            return next(err);
        }
        res.send(graph);
    });
};

exports.viewById = function(req, res, next) {
    var personId = req.params.personId;
    Person.findOne({_id: personId}, function(err, person) {
        if (err) {
            return next(err);
        }

        if (!person) {
            res.status(404);
            return next(new Error('Cannot find person with id ' + personId + '.'));
        }

        // Only allowed to query graphs by personId if that person is not a full user
        if (typeof person.password !== 'undefined') {
            res.status(403);
            return next(new Error('Access denied'));
        }

        // Get the graph
        getGraph(person, function(err, graph) {
            if (err) {
                return next(err);
            }
            res.send(graph);
        });
    });
};

exports.update = function(req, res) {
    res.send({ status: 'OK' });
};
<commit_msg>Always include a me person.<commit_after>'use strict';

var _ = require('lodash');
var async = require('async');
var mongoose = require('mongoose');
var Person = mongoose.model('Person');
var GraphNode = mongoose.model('GraphNode');
var ActivityLink = mongoose.model('ActivityLink');

var getNode = function(person, graphnode) {
    var result = {
        id:       person.id,
        fullName: person.fullName,
        team:     person.team,
        type:     person.getType()
    };

    if (typeof graphnode !== 'undefined') {
        if (typeof graphnode.coordX !== 'undefined') {
            result.coordX = graphnode.coordX;
        }
        if (typeof graphnode.coordY !== 'undefined') {
            result.coordY = graphnode.coordY;
        }
    }

    return result;
};

// TODO: this needs unit testing
// TODO: this function is ridiculously long
var getGraph = function(person, cb) {
    GraphNode
        .find({owner: person.id})
        .populate('target', 'fullName password team')
        .exec(function (err, nodes) {
            if (err) {
                cb(err);
                return;
            }

            var persons = _.pluck(nodes, 'target');
            var friendIds = _.pluck(persons, 'id');

            // transform this into a map for easier random access
            persons = _.indexBy(persons, 'id');
            if (typeof persons[person.id] === 'undefined') {
                persons[person.id] = person;
            }
            nodes   = _.indexBy(nodes, function(n) { return n.target.id; });

            // Count the activities between the people in the social graph
            // Get all the activities of the user and the friends
            // (including activities to friends of friends)
            ActivityLink
                .find()
                .or([
                    {source: { $in: friendIds } },
                    {target: { $in: friendIds } }
                ])
                .populate('source')
                .populate('target')
                .exec(function(err, links) {
                    // We need to map these activity links, and transform them into a 2d
                    // structure that maps source/target pairs to counts.
                    var counts = {};
                    _.each(links, function(l) {
                        counts[l.source.id] = counts[l.source.id] || {};
                        if (typeof counts[l.source.id][l.target.id] === 'undefined') {
                            counts[l.source.id][l.target.id] = {
                                open: 0,
                                completed: 0
                            };
                        }
                        counts[l.source.id][l.target.id][l.success ? 'completed' : 'open'] += 1;
                        _.each([l.source, l.target], function(p) {
                            if (typeof persons[p.id] === 'undefined') {
                                persons[p.id] = p;
                            }
                        });
                    });

                    // Convert to the format needed by the frontend
                    var graphLinks = _.map(counts, function(cc, s) {
                        return _.map(cc, function(c, t) {
                            var link = {
                                source: s,
                                target: t
                            };

                            // Add the number of activities if the given person is part of the link
                            if (s === person.id || t === person.id) {
                                link.openActivities = c.open;
                                link.completedActivities = c.completed;
                            }
                            return link;
                        });
                    });
                    graphLinks = _.flatten(graphLinks);

                    async.each(
                        _.toArray(persons),
                        function(p, cb) {
                            p.populateActivityLinks(cb);
                        },
                        function (err) {
                            if (err) {
                                cb(err);
                            } else {
                                var friendIndex = _.indexBy(friendIds);
                                var resultnodes = _.map(persons, function (n) {
                                    var result = getNode(n, nodes[n.id]);
                                    if (result.id === person.id) {
                                        result.relation = 'me';
                                        result.coordX = 0.5;
                                        result.coordY = 0.5;
                                    } else if (friendIndex[result.id]) {
                                        result.relation = 'friend';
                                    } else {
                                        result.relation = 'friendOfFriend';
                                        result.fullName = undefined;
                                    }
                                    return result;
                                });
                                cb(null, {
                                    nodes: _.indexBy(resultnodes, 'id'),
                                    links: graphLinks
                                });
                            }
                        }
                    );
                })
            ;
        })
    ;
};

exports.view = function(req, res, next) {
    // Get the entire social graph for me
    getGraph(req.user, function(err, graph) {
        if (err) {
            return next(err);
        }
        res.send(graph);
    });
};

exports.viewById = function(req, res, next) {
    var personId = req.params.personId;
    Person.findOne({_id: personId}, function(err, person) {
        if (err) {
            return next(err);
        }

        if (!person) {
            res.status(404);
            return next(new Error('Cannot find person with id ' + personId + '.'));
        }

        // Only allowed to query graphs by personId if that person is not a full user
        if (typeof person.password !== 'undefined') {
            res.status(403);
            return next(new Error('Access denied'));
        }

        // Get the graph
        getGraph(person, function(err, graph) {
            if (err) {
                return next(err);
            }
            res.send(graph);
        });
    });
};

exports.update = function(req, res) {
    res.send({ status: 'OK' });
};
<|endoftext|>


<commit_before>import R from 'ramda';

const makeStyleReducer = (key, isStore = false) => function styleReducer(styles) {
  let result = {};
  const storeKey = (isStore) ? 'props' : 'state';
  if (this[storeKey] && this[storeKey][key]) {
    result = this.styles.keys[key].reduce(
      (prev, cur) => {
        const p = prev;
        if (this.styles.styles[cur].hasOwnProperty(key)) {
          p[cur] = this.styles.styles[cur][key];
        }
        return p;
      }, {}
    );
  }
  return R.mergeWith(R.merge, styles, result);
};

const Stylizer = {
  assignStyles: (component, styles) => {
    const c = component;

    if (!c.styles) {
      c.styles = {
        styles,
        keys: {},
        getters: [],
      };
    }
    // assign default getter
    c.styles.getters.push(Stylizer.getters.normal.bind(c));
    // assign default getStyle method
    c.getStyle = Stylizer.funcs.getStyle.bind(c);
  },
  hoverable: (component, keys) => {
    const c = component;

    if (!c.styles) {
      Stylizer.assignStyles(c, {});
    }
    if (!c.state) {
      c.state = {};
    }
    c.state.hover = false;
    c.onMouseOver = Stylizer.funcs.onMouseOver;
    c.onMouseOut = Stylizer.funcs.onMouseOut;
    c.handleOver = c.onMouseOver.bind(c);
    c.handleOut = c.onMouseOut.bind(c);

    c.styles.keys.hover = keys;
    c.styles.getters.push(Stylizer.getters.hover.bind(c));
  },
  selectable: (component, keys) => {
    const c = component;
    if (!c.styles) {
      Stylizer.assignStyles(c, {});
    }
    if (!c.state) {
      c.state = {};
    }
    c.state.selected = false;

    c.styles.keys.selected = keys;
    c.styles.getters.push(Stylizer.getters.selected.bind(c));
  },
  getters: {
    normal(styles) {
      return Object.keys(styles).reduce(
        (prev, cur) => {
          const p = prev;
          p[cur] = ((styles[cur].hasOwnProperty('normal')) ? styles[cur].normal : styles[cur]);
          return p;
        }, {}
      );
    },
    hover: makeStyleReducer('hover'),
    selected: makeStyleReducer('selected', true),
  },

  funcs: {
    getStyle() {
      let styles = Object.assign({}, this.styles.styles);
      this.styles.getters.forEach((func) => {
        styles = func(styles);
      });
      return styles;
    },
    onMouseOver() {
      const state = Object.assign({}, this.state);
      state.hover = true;
      this.setState(state);
    },
    onMouseOut() {
      const state = Object.assign({}, this.state);
      state.hover = false;
      this.setState(state);
    },
  },
};

export default Stylizer;
<commit_msg>feat(stylizer): add method dependOnProp, that apply styles dependent on property value<commit_after>import R from 'ramda';

const makeStyleReducer = (key, isStore = false) => function styleReducer(styles) {
  let result = {};
  const storeKey = (isStore) ? 'props' : 'state';
  if (this[storeKey] && this[storeKey][key]) {
    const val = this[storeKey][key];
    result = this.styles.keys[key].reduce(
      (prev, cur) => {
        let p = prev;
        const hasStyles = this.styles.styles[cur].hasOwnProperty(key);
        if (hasStyles) {
          const hasPropStyle = (
            typeof this.styles.styles[cur][key] === 'object' &&
            this.styles.styles[cur][key].hasOwnProperty(val)
          );
          let updateWith;
          if (hasPropStyle) {
            updateWith = this.styles.styles[cur][key][val];
          } else {
            updateWith = this.styles.styles[cur][key];
          }

          p = R.assoc(cur, updateWith, prev);
        }
        return p;
      }, {}
    );
  }
  return R.mergeWith(R.merge, styles, result);
};

const Stylizer = {
  init: (component) => {
    const c = component;
    if (!c.styles) {
      Stylizer.assignStyles(c, {});
    }
    if (!c.state) {
      c.state = {};
    }
  },
  assignStyles: (component, styles) => {
    const c = component;

    if (!c.styles) {
      c.styles = {
        styles,
        keys: {},
        getters: [],
      };
    }
    // assign default getters
    c.styles.getters.push(Stylizer.getters.normal.bind(c));
    // assign default getStyle method
    c.getStyle = Stylizer.funcs.getStyle.bind(c);
  },
  hoverable: (component, keys) => {
    const c = component;
    Stylizer.init(c);
    c.state.hover = false;

    c.onMouseOver = Stylizer.funcs.onMouseOver;
    c.onMouseOut = Stylizer.funcs.onMouseOut;
    c.handleOver = c.onMouseOver.bind(c);
    c.handleOut = c.onMouseOut.bind(c);

    c.styles.keys.hover = keys;
    c.styles.getters.push(Stylizer.getters.hover.bind(c));
  },
  selectable: (component, keys) => {
    const c = component;
    Stylizer.init(c);
    c.state.selected = false;

    c.styles.keys.selected = keys;
    c.styles.getters.push(Stylizer.getters.selected.bind(c));
  },
  dependOnProp: (component, propName, keys) => {
    const c = component;
    Stylizer.init(c);

    c.styles.keys[propName] = keys;
    c.styles.getters.push(Stylizer.getters.dependOnProp(c, propName));
  },
  getters: {
    normal(styles) {
      return Object.keys(styles).reduce(
        (prev, cur) => {
          const p = prev;
          p[cur] = ((styles[cur].hasOwnProperty('normal')) ? styles[cur].normal : styles[cur]);
          return p;
        }, {}
      );
    },
    hover: makeStyleReducer('hover'),
    selected: makeStyleReducer('selected', true),
    dependOnProp: (component, propName) => makeStyleReducer(propName, true).bind(component),
  },

  funcs: {
    getStyle() {
      let styles = Object.assign({}, this.styles.styles);
      this.styles.getters.forEach((func) => {
        styles = func(styles);
      });
      return styles;
    },
    onMouseOver() {
      const state = Object.assign({}, this.state);
      state.hover = true;
      this.setState(state);
    },
    onMouseOut() {
      const state = Object.assign({}, this.state);
      state.hover = false;
      this.setState(state);
    },
  },
};

export default Stylizer;
<|endoftext|>


<commit_before>var React = require('react-native');
var styles = require("../styles.js");

var { View, Text, TextInput, TouchableOpacity, } = React;

class PostForm extends React.Component {

  constructor(props) {

    // Create blank state.input that we reference
    // below, app crashes without this.

    this.state = {
      input: '',
      lastPosition: {
        coords: {
          longitude : 0,
          latitude : 0,
          altitude : 0,
          accuracy: 0,
        }
      }
    };
  }

  componentDidMount() {

   var watchOptions = {
    enableHighAccuracy: true,
    maximumAge: 30000,
    timeout: 27000
   };

   var watchSucess = (lastPosition) => {
     this.setState({lastPosition});
   }

   var watchError = (error) => console.error(error);

   navigator.geolocation.getCurrentPosition(
     (initialPosition) => this.setState({initialPosition}),
     (error) => console.error(error)
   );

   this.watchID = navigator.geolocation.watchPosition(
    watchSucess, watchError, watchOptions
   );

  }

  componentWillUnmount() {
    navigator.geolocation.clearWatch(this.watchID);
  }

  render() {

    // Render input box and feedback.

    return (
      <View style={{ top: 100 }}>

        <TextInput
          style={styles.textInput}
          onChangeText={(text) => this.setState({input: text})}
        />
        <TouchableOpacity
          style={styles.wrapper}
          onPress={() => this._postMessage()}>
          <Text style={styles.button}>
            Post
          </Text>
        </TouchableOpacity>
        <Text>
        longitude is {JSON.stringify(this.state.lastPosition.coords.longitude)}
        </Text>
        <Text>
        latitude is {JSON.stringify(this.state.lastPosition.coords.latitude)}
        </Text>
        <Text>
        accuracy is {JSON.stringify(this.state.lastPosition.coords.accuracy)}
        </Text>
      </View>
    );
  }

  // Post Message to server

  _postMessage() {

    var currentPosition = this.state.lastPosition.coords;
    // this url is for testing purposes
    // see github.com/levity-io/POST-bin
    // for a POST request catcher

    fetch('http://uncovery.ngrok.com/', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        x: currentPosition.latitude,
        y: currentPosition.longitude,
        z: currentPosition.altitude,
        message: this.state.input,
      }),
    })
  }

};

module.exports = PostForm;<commit_msg>Updated post form styles. User bounces back on post.<commit_after>var React = require('react-native');
var styles = require("../styles.js");

var { View, Text, TextInput, TouchableOpacity, } = React;

class PostForm extends React.Component {

  constructor(props) {

    // Create blank state.input that we reference
    // below, app crashes without this.

    this.state = {
      input: '',
      buttonText: 'Mark',
      lastPosition: {
        coords: {
          longitude : 0,
          latitude : 0,
          altitude : 0,
          accuracy: 0,
        }
      }
    };
  }

  componentDidMount() {

   var watchOptions = {
    enableHighAccuracy: true,
    maximumAge: 30000,
    timeout: 27000
   };

   var watchSucess = (lastPosition) => {
     this.setState({lastPosition});
   }

   var watchError = (error) => console.error(error);

   navigator.geolocation.getCurrentPosition(
     (initialPosition) => this.setState({initialPosition}),
     (error) => console.error(error)
   );

   this.watchID = navigator.geolocation.watchPosition(
    watchSucess, watchError, watchOptions
   );

  }

  componentWillUnmount() {
    navigator.geolocation.clearWatch(this.watchID);
  }

  render() {

    // Render input box and feedback.

    return (
      <View style={{ top: 100, padding:20, justifyContent: 'center', }}>

        <TextInput
          editable={true}
          enablesReturnKeyAutomatically={true}
          placeholder={'Your mark...'}
          style={styles.textInput}
          onChangeText={(text) => this.setState({input: text})}
        />
        <TouchableOpacity
          style={styles.wrapper}
          onPress={() => this._postMessage()}>
          <Text style={styles.button}>
            {this.state.buttonText}
          </Text>
        </TouchableOpacity>
      </View>
    );
  }

  // Post Message to server

  _postMessage() {

    var navBar = this.props.navigator;
    var currentPosition = this.state.lastPosition.coords;
    // this url is for testing purposes
    // see github.com/levity-io/POST-bin
    // for a POST request catcher

    fetch('http://uncovery.ngrok.com/', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        x: currentPosition.latitude,
        y: currentPosition.longitude,
        z: currentPosition.altitude,
        message: this.state.input,
      })
    }).then((responseText) => {
      // Bounce back to main window
      navBar.pop();
    })
  }

};

module.exports = PostForm;<|endoftext|>


<commit_before>/**
 * @fileoverview Schema format.
 *
 * @externs
 */

/**
 * Inverted index for full text serach.
 * @constructor
 */
function InvIndex() {}

/**
 * @type {string}
 */
InvIndex.prototype.storeName;

/**
 * @type {string}
 */
InvIndex.prototype.keyPath;

/**
 * @type {number?}
 */
InvIndex.prototype.weight;

/**
 * @constructor
 */
function FullTextCatalog() {}

/**
 * @type {string}
 */
FullTextCatalog.prototype.name;

/**
 * @type {Array.<InvIndex>}
 */
FullTextCatalog.prototype.sources;

/**
 * @type {string}
 */
FullTextCatalog.prototype.lang;

/**
 * @type {Array.<string>}
 */
FullTextCatalog.prototype.normalizers;

/**
 * @constructor
 */
function IndexSchema() {}

/**
 * @type {string}
 */
IndexSchema.prototype.name;

/**
 * @type {string}
 */
IndexSchema.prototype.type;

/**
 * @type {boolean}
 */
IndexSchema.prototype.unique;

/**
 * @type {string}
 */
IndexSchema.prototype.keyPath;

/**
 * @type {boolean}
 */
IndexSchema.prototype.multiEntry;

/**
 * Index key generator. Generator function will be invoked when a record value
 * is about to 'add' or 'put' to the object store. Returning a valid IDBKey
 * or undefined will set to the record value while ignoring invalid IDBKeys.
 * @type {Function}
 */
IndexSchema.prototype.generator;

/**
 * @constructor
 */
var KeyPaths = function() {};

/**
 * @type {string}
 */
KeyPaths.prototype.id;

/**
 * @type {string}
 */
KeyPaths.prototype.etag;

/**
 * @type {string}
 */
KeyPaths.prototype.nextUrl;

/**
 * @type {string}
 */
KeyPaths.prototype.updated;

/**
 * @constructor
 */
var AtomOptions = function() {};

/**
 * @see http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html
 * @constructor
 */
var S3Options = function() {};

/**
 * @type {string?}
 */
S3Options.prototype.delimiter;

/**
 * @type {string?}
 */
S3Options.prototype.prefix;

/**
 * Bucket name.
 * @type {string}
 */
S3Options.prototype.bucket;

/**
 * @type {string?}
 */
S3Options.prototype.maxKeys;

/**
 * @extends {AtomOptions}
 * @constructor
 */
var GDataOptions = function() {};

/**
 * @type {string?}
 */
GDataOptions.prototype.version;

/**
 * @type {string}
 */
GDataOptions.prototype.kind;

/**
 * @type {string?}
 */
GDataOptions.prototype.projection;

/**
 * Maximum number of results to be retrieved
 * https://developers.google.com/gdata/docs/2.0/reference#Queries
 * @type {string}
 */
GDataOptions.prototype.maxResults;

/**
 * @type {string}
 */
GDataOptions.prototype.domain;

/**
 * @type {string}
 */
GDataOptions.prototype.siteName;

/**
 * @extends {GDataOptions}
 * @constructor
 */
var GDataJsonOptions = function() {};

/**
 * Base uri path post fix. This can be found in "path" of resources method in
 * Google API discovery.
 * @type {string}
 */
GDataJsonOptions.prototype.prefix;

/**
 * @extends {AtomOptions}
 * @constructor
 */
var ODataOptions = function() {};

/**
 * Synchronization option for a store.
 * @constructor
 */
function StoreSyncOptionJson() {}

/**
 * Backend service format. Valid values are 'rest', 's3', 'gcs', 'atom',
 * 'odata', 'gdata'.
 * @type {string}
 */
StoreSyncOptionJson.prototype.format;

/**
 * Base URI.
 * @type {string}
 */
StoreSyncOptionJson.prototype.baseUri;

/**
 * Immutable database.
 * @type {boolean}
 */
StoreSyncOptionJson.prototype.immutable;

/**
 * HTTP transport. This is compatible with Google Javascript Client request
 * https://developers.google.com/api-client-library/javascript/reference/referencedocs#gapiclientrequest
 * @type {{request: Function}}
 */
StoreSyncOptionJson.prototype.transport;

/**
 * By default, meta data store are stripped, when read from the database.
 * @type {boolean} Set true to keep meta data.
 */
StoreSyncOptionJson.prototype.keepMeta;

/**
 * Store name which store meta data.
 * If specified, metaData must not specified.
 * @type {string}
 */
StoreSyncOptionJson.prototype.metaStoreName;

/**
 * Meta data data field if it is recorded inline.
 * If specified, metaStoreName must not specified.
 * @type {string}
 */
StoreSyncOptionJson.prototype.metaDataName;

/**
 * Key paths of metadata.
 * @type {{
 *   date: string,
 *   etag: string,
 *   expires: string,
 *   key: string,
 *   updated: string
 * }?}
 */
StoreSyncOptionJson.prototype.metaData;

/**
 * Indicate prefetch to be performed.
 * @type {string} valid options are 'meta' and 'full'.
 */
StoreSyncOptionJson.prototype.prefetch;

/**
 * Prefetch refractory period interval in milliseconds.
 * @type {number}
 */
StoreSyncOptionJson.prototype.prefetchRefractoryPeriod;

/**
 * Backend specific sync options.
 * @type {AtomOptions|GDataOptions|ODataOptions|S3Options}
 */
StoreSyncOptionJson.prototype.Options;

/**
 * Entry list fetch strategy. Supported method are
 * ['last-updated', 'descending-key']
 * @type {Array}
 */
StoreSyncOptionJson.prototype.fetchStrategies;

/**
 * @constructor
 */
function StoreSchema() {}

/**
 * @type {string}
 */
StoreSchema.prototype.name;

/**
 * @type {string}
 */
StoreSchema.prototype.keyPath;

/**
 * @type {boolean}
 */
StoreSchema.prototype.autoIncrement;

/**
 * @type {string}
 */
StoreSchema.prototype.type;

/**
 * @type {Array.<!IndexSchema>}
 */
StoreSchema.prototype.indexes;

/**
 * @type {boolean}
 */
StoreSchema.prototype.dispatchEvents;

/**
 * A fixed schema.
 * @type {boolean}
 */
StoreSchema.prototype.fixed;

/**
 * Name of sync
 * @type {StoreSyncOptionJson}
 */
StoreSchema.prototype.Sync;

/**
 * @constructor
 */
function MetaData() {}

/**
 * @type {string}
 */
MetaData.prototype.id;

/**
 * @type {string}
 */
MetaData.prototype.etag;

/**
 * @type {number}
 */
MetaData.prototype.updated;

/**
 * @type {number}
 */
MetaData.prototype.expires;

/**
 * @type {number}
 */
MetaData.prototype.date;

/**
 * @constructor
 */
function DatabaseSchema() {}

/**
 * @type {number}
 */
DatabaseSchema.prototype.version;

/**
 * @type {Array.<!FullTextCatalog>}
 */
DatabaseSchema.prototype.fullTextCatalogs;

/**
 * @type {Array.<!StoreSchema>}
 */
DatabaseSchema.prototype.stores;
<commit_msg>meta data always store in seperate store.<commit_after>/**
 * @fileoverview Schema format.
 *
 * @externs
 */

/**
 * Inverted index for full text serach.
 * @constructor
 */
function InvIndex() {}

/**
 * @type {string}
 */
InvIndex.prototype.storeName;

/**
 * @type {string}
 */
InvIndex.prototype.keyPath;

/**
 * @type {number?}
 */
InvIndex.prototype.weight;

/**
 * @constructor
 */
function FullTextCatalog() {}

/**
 * @type {string}
 */
FullTextCatalog.prototype.name;

/**
 * @type {Array.<InvIndex>}
 */
FullTextCatalog.prototype.sources;

/**
 * @type {string}
 */
FullTextCatalog.prototype.lang;

/**
 * @type {Array.<string>}
 */
FullTextCatalog.prototype.normalizers;

/**
 * @constructor
 */
function IndexSchema() {}

/**
 * @type {string}
 */
IndexSchema.prototype.name;

/**
 * @type {string}
 */
IndexSchema.prototype.type;

/**
 * @type {boolean}
 */
IndexSchema.prototype.unique;

/**
 * @type {string}
 */
IndexSchema.prototype.keyPath;

/**
 * @type {boolean}
 */
IndexSchema.prototype.multiEntry;

/**
 * Index key generator. Generator function will be invoked when a record value
 * is about to 'add' or 'put' to the object store. Returning a valid IDBKey
 * or undefined will set to the record value while ignoring invalid IDBKeys.
 * @type {Function}
 */
IndexSchema.prototype.generator;

/**
 * @constructor
 */
var KeyPaths = function() {};

/**
 * @type {string}
 */
KeyPaths.prototype.id;

/**
 * @type {string}
 */
KeyPaths.prototype.etag;

/**
 * @type {string}
 */
KeyPaths.prototype.nextUrl;

/**
 * @type {string}
 */
KeyPaths.prototype.updated;

/**
 * @constructor
 */
var AtomOptions = function() {};

/**
 * @see http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html
 * @constructor
 */
var S3Options = function() {};

/**
 * @type {string?}
 */
S3Options.prototype.delimiter;

/**
 * @type {string?}
 */
S3Options.prototype.prefix;

/**
 * Bucket name.
 * @type {string}
 */
S3Options.prototype.bucket;

/**
 * @type {string?}
 */
S3Options.prototype.maxKeys;

/**
 * @extends {AtomOptions}
 * @constructor
 */
var GDataOptions = function() {};

/**
 * @type {string?}
 */
GDataOptions.prototype.version;

/**
 * @type {string}
 */
GDataOptions.prototype.kind;

/**
 * @type {string?}
 */
GDataOptions.prototype.projection;

/**
 * Maximum number of results to be retrieved
 * https://developers.google.com/gdata/docs/2.0/reference#Queries
 * @type {string}
 */
GDataOptions.prototype.maxResults;

/**
 * @type {string}
 */
GDataOptions.prototype.domain;

/**
 * @type {string}
 */
GDataOptions.prototype.siteName;

/**
 * @extends {GDataOptions}
 * @constructor
 */
var GDataJsonOptions = function() {};

/**
 * Base uri path post fix. This can be found in "path" of resources method in
 * Google API discovery.
 * @type {string}
 */
GDataJsonOptions.prototype.prefix;

/**
 * @extends {AtomOptions}
 * @constructor
 */
var ODataOptions = function() {};

/**
 * Synchronization option for a store.
 * @constructor
 */
function StoreSyncOptionJson() {}

/**
 * Backend service format. Valid values are 'rest', 's3', 'gcs', 'atom',
 * 'odata', 'gdata'.
 * @type {string}
 */
StoreSyncOptionJson.prototype.format;

/**
 * Base URI.
 * @type {string}
 */
StoreSyncOptionJson.prototype.baseUri;

/**
 * Immutable database.
 * @type {boolean}
 */
StoreSyncOptionJson.prototype.immutable;

/**
 * HTTP transport. This is compatible with Google Javascript Client request
 * https://developers.google.com/api-client-library/javascript/reference/referencedocs#gapiclientrequest
 * @type {{request: Function}}
 */
StoreSyncOptionJson.prototype.transport;

/**
 * Store name which store meta data.
 * If specified, metaData must not specified.
 * @type {string}
 */
StoreSyncOptionJson.prototype.metaStoreName;

/**
 * Key paths of metadata.
 * @type {{
 *   date: string,
 *   etag: string,
 *   expires: string,
 *   key: string,
 *   updated: string
 * }?}
 */
StoreSyncOptionJson.prototype.metaData;

/**
 * Indicate prefetch to be performed.
 * @type {string} valid options are 'meta' and 'full'.
 */
StoreSyncOptionJson.prototype.prefetch;

/**
 * Prefetch refractory period interval in milliseconds.
 * @type {number}
 */
StoreSyncOptionJson.prototype.prefetchRefractoryPeriod;

/**
 * Backend specific sync options.
 * @type {AtomOptions|GDataOptions|ODataOptions|S3Options}
 */
StoreSyncOptionJson.prototype.Options;

/**
 * Entry list fetch strategy. Supported method are
 * ['last-updated', 'descending-key']
 * @type {Array}
 */
StoreSyncOptionJson.prototype.fetchStrategies;

/**
 * @constructor
 */
function StoreSchema() {}

/**
 * @type {string}
 */
StoreSchema.prototype.name;

/**
 * @type {string}
 */
StoreSchema.prototype.keyPath;

/**
 * @type {boolean}
 */
StoreSchema.prototype.autoIncrement;

/**
 * @type {string}
 */
StoreSchema.prototype.type;

/**
 * @type {Array.<!IndexSchema>}
 */
StoreSchema.prototype.indexes;

/**
 * @type {boolean}
 */
StoreSchema.prototype.dispatchEvents;

/**
 * A fixed schema.
 * @type {boolean}
 */
StoreSchema.prototype.fixed;

/**
 * Name of sync
 * @type {StoreSyncOptionJson}
 */
StoreSchema.prototype.Sync;

/**
 * @constructor
 */
function MetaData() {}

/**
 * @type {string}
 */
MetaData.prototype.id;

/**
 * @type {string}
 */
MetaData.prototype.etag;

/**
 * @type {number}
 */
MetaData.prototype.updated;

/**
 * @type {number}
 */
MetaData.prototype.expires;

/**
 * @type {number}
 */
MetaData.prototype.date;

/**
 * @constructor
 */
function DatabaseSchema() {}

/**
 * @type {number}
 */
DatabaseSchema.prototype.version;

/**
 * @type {Array.<!FullTextCatalog>}
 */
DatabaseSchema.prototype.fullTextCatalogs;

/**
 * @type {Array.<!StoreSchema>}
 */
DatabaseSchema.prototype.stores;
<|endoftext|>


<commit_before>
/**
 * Get details for lecture with PIN
 *
 * @param PIN       Lecture PIN
 * @param success   Function callback on received response
 */
function getLectureDetails(PIN, success) {
    var URL = '/lectures/' + PIN + '/';
    $.getJSON(URL, success);
}

/**
 * Find a cookie
 *
 * @param name  Name of the cookie to find
 * @return      Cookie value as string or null if cookie does not exist
 */
function getCookie(name) {
    var cookieVal = null;
    if (document.cookie && document.cookie !== "") {
        var cookies = document.cookie.split(";");
        for (var i = 0; i < cookies.length; i++) {
            var cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === name + '=') {
                console.log(cookie);
                cookieVal = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieVal;
}

/**
 * POST a form with csrftoken header
 *
 * @param action    URL to post to
 * @param form_el   DOM form element to send
 * @param success   Function callback on received response
 */
function csrfPOST(action, form_el, success) {
    var csrftoken = getCookie("csrftoken");
    if (csrftoken === null) {
        console.log("CSRF cookie not found!");
        return;
    }
    $.ajax({
        url: action,
        type: "POST",
        headers: {"X-CSRFToken": csrftoken},
        data: form_el.serialize(),
        dataType: "json",
        success: success
    });
}

/**
 * Get list of questions for lecture
 */
function getQuestions() {
    var api_url = '/lectures/' + $('#pinInput').val() + '/questions/';
    $.getJSON(api_url, function (data) {
        console.log(data);
        if (data.success) {
            // TODO Update question list
            // Empty list of existing questions
            $("#question_list").empty();
            // Add questions to list
            var iterations = Math.min(5, data.questions.length);
            for (var i = 0; i < iterations; i++) {
                var question = data.questions[i];
                var list_element = $("<li>");
                var upvote_button = $("<button>");
                var glyphicon_up = $("<span>");
                glyphicon_up.attr({
                    class: 'glyphicon glyphicon-menu-up glyph-upvote'
                });
                upvote_button.attr({
                    type: 'button',
                    class: 'upvote-button',
                    onclick: 'upvoteQuestion.call(this)',
                    value: question.question_id
                });
                upvote_button.append(glyphicon_up);
                upvote_button.append(question.question_votes);
                list_element.append(upvote_button);
                list_element.append('- ');
                list_element.append(question.question_text);
                $("#question_list").append(list_element);
            }
        }
    });
}
<commit_msg>getQuestions now runs markQuestions at the end<commit_after>
/**
 * Get details for lecture with PIN
 *
 * @param PIN       Lecture PIN
 * @param success   Function callback on received response
 */
function getLectureDetails(PIN, success) {
    var URL = '/lectures/' + PIN + '/';
    $.getJSON(URL, success);
}

/**
 * Find a cookie
 *
 * @param name  Name of the cookie to find
 * @return      Cookie value as string or null if cookie does not exist
 */
function getCookie(name) {
    var cookieVal = null;
    if (document.cookie && document.cookie !== "") {
        var cookies = document.cookie.split(";");
        for (var i = 0; i < cookies.length; i++) {
            var cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === name + '=') {
                console.log(cookie);
                cookieVal = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieVal;
}

/**
 * POST a form with csrftoken header
 *
 * @param action    URL to post to
 * @param form_el   DOM form element to send
 * @param success   Function callback on received response
 */
function csrfPOST(action, form_el, success) {
    var csrftoken = getCookie("csrftoken");
    if (csrftoken === null) {
        console.log("CSRF cookie not found!");
        return;
    }
    $.ajax({
        url: action,
        type: "POST",
        headers: {"X-CSRFToken": csrftoken},
        data: form_el.serialize(),
        dataType: "json",
        success: success
    });
}

/**
 * Get list of questions for lecture
 */
function getQuestions() {
    var api_url = '/lectures/' + $('#pinInput').val() + '/questions/';
    $.getJSON(api_url, function (data) {
        console.log(data);
        if (data.success) {
            // TODO Update question list
            // Empty list of existing questions
            $("#question_list").empty();
            // Add questions to list
            var iterations = Math.min(5, data.questions.length);
            for (var i = 0; i < iterations; i++) {
                var question = data.questions[i];
                var list_element = $("<li>");
                var upvote_button = $("<button>");
                var glyphicon_up = $("<span>");
                glyphicon_up.attr({
                    class: 'glyphicon glyphicon-menu-up glyph-upvote'
                });
                upvote_button.attr({
                    type: 'button',
                    class: 'upvote-button',
                    onclick: 'upvoteQuestion.call(this)',
                    value: question.question_id
                });
                upvote_button.append(glyphicon_up);
                upvote_button.append(question.question_votes);
                list_element.append(upvote_button);
                list_element.append('- ');
                list_element.append(question.question_text);
                $("#question_list").append(list_element);
            }
            markQuestion();
        }
    });
}
<|endoftext|>


<commit_before>function doClick(e) {
	var api_user="ralcocer";
	var api_key="mymagic";
	//var api_user="<youruser>";
	//var api_key="<yourpassword>";

	var sendgrid  = require('tisendgrid')(api_user, api_key);

	var cb_onsuccess=function(e){
		console.log('Success: ' + e)
	}

	var cb_onerror=function(err,status,body){
		console.log('Error: ' + err + '; Status: ' + status + '; Body: ' + body);
	}

	var email={
	  		to:       	'to@email.com',
	  		toname: 	'to name',
	  		from:  	   	'from@email.com',
	  		fromname: 	'from name',
	  		subject:  	'Hello World',
	  		text:     	'My first email through SendGrid.',
	  		html: 	  	'This is a test!!!'
		}

    /*testFileObj = Titanium.Filesystem.getFile('appicon.png');
    testFileBin = f1.read();
    email.image=testFileBin;*/

	sendgrid.send(email,cb_onsuccess,cb_onerror);
}

$.index.open();
<commit_msg>cleanup<commit_after>function doClick(e) {
	var api_user="<youruser>";
	var api_key="<yourpassword>";

	var sendgrid  = require('tisendgrid')(api_user, api_key);

	var cb_onsuccess=function(e){
		console.log('Success: ' + e)
	}

	var cb_onerror=function(err,status,body){
		console.log('Error: ' + err + '; Status: ' + status + '; Body: ' + body);
	}

	var email={
	  		to:       	'to@email.com',
	  		toname: 	'to name',
	  		from:  	   	'from@email.com',
	  		fromname: 	'from name',
	  		subject:  	'Hello World',
	  		text:     	'My first email through SendGrid.',
	  		html: 	  	'This is a test!!!'
		}

    /*testFileObj = Titanium.Filesystem.getFile('appicon.png');
    testFileBin = f1.read();
    email.image=testFileBin;*/

	sendgrid.send(email,cb_onsuccess,cb_onerror);
}

$.index.open();
<|endoftext|>


<commit_before>(function() {
  var root = this,   // Root object, this is going to be the window for now
      document = this.document, // Safely store a document here for us to use
      editableNodes = document.querySelectorAll(".g-body article"),
      textMenu = document.querySelectorAll(".g-body .text-menu")[0],
      optionsNode = document.querySelectorAll(".g-body .text-menu .options")[0],
      urlInput = document.querySelectorAll(".g-body .text-menu .url-input")[0],
      isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1,

      previouslySelectedText,

      grande = {
        bind: function() {
          bindTextSelectionEvents();
          bindTextStylingEvents();
        },
        select: function() {
          triggerTextSelection();
        }
      },

      tagClassMap = {
        "b": "bold",
        "i": "italic",
        "h1": "header1",
        "h2": "header2",
        "a": "url",
        "blockquote": "quote"
      };

  function bindTextSelectionEvents() {
    var i,
        len,
        node;

    // Trigger on both mousedown and mouseup so that the click on the menu
    // feels more instantaneously active
    document.onmousedown = triggerTextSelection;
    document.onmouseup = function(event) {
      setTimeout(function() {
        triggerTextSelection(event);
      }, 1);
    };
    document.onkeyup = triggerTextParse;

    // Handle window resize events
    root.onresize = triggerTextSelection;

    urlInput.onblur = triggerUrlBlur;
    urlInput.onkeydown = triggerUrlSet;

    for (i = 0, len = editableNodes.length; i < len; i++) {
      node = editableNodes[i];
      node.onmousedown = node.onkeyup = node.onmouseup = triggerTextSelection;
    }
  }

  function iterateTextMenuButtons(callback) {
    var textMenuButtons = document.querySelectorAll(".g-body .text-menu button"),
        i,
        len,
        node;

    for (i = 0, len = textMenuButtons.length; i < len; i++) {
      node = textMenuButtons[i];

      (function(n) {
        callback(n);
      })(node);
    }
  }

  function bindTextStylingEvents() {
    iterateTextMenuButtons(function(node) {
      node.onmousedown = function(event) {
        triggerTextStyling(node);
      };
    });
  }

  function getFocusNode() {
    return root.getSelection().focusNode;
  }

  function reloadMenuState() {
    var className,
        focusNode = getFocusNode(),
        tagClass,
        reTag;

    iterateTextMenuButtons(function(node) {
      className = node.className;

      for (var tag in tagClassMap) {
        tagClass = tagClassMap[tag];
        reTag = new RegExp(tagClass);

        if (reTag.test(className)) {
          if (hasParentWithTag(focusNode, tag)) {
            node.className = tagClass + " active";
          } else {
            node.className = tagClass;
          }

          break;
        }
      }
    });
  }

  function triggerTextParse(event) {
    var sel = window.getSelection(),
        textProp,
        subject,
        insertedNode,
        unwrap,
        node,
        parent,
        range;

    // FF will return sel.anchorNode to be the parentNode when the triggered keyCode is 13
    if (!sel.isCollapsed || !sel.anchorNode || sel.anchorNode.nodeName === "ARTICLE") {
      return;
    }

    if (sel.anchorNode.nodeType === Node.TEXT_NODE) {
      textProp = "data";
    } else if (isFirefox) {
      textProp = "textContent";
    } else {
      textProp = "innerText";
    }

    subject = sel.anchorNode[textProp];

    if (subject.match(/^-\s/) && sel.anchorNode.parentNode.nodeName !== 'LI') {
      document.execCommand('insertUnorderedList');
      sel.anchorNode[textProp] = sel.anchorNode[textProp].substring(2);

      insertedNode = sel.anchorNode;
      while (insertedNode.parentNode) {
        if (insertedNode.nodeName.toLowerCase() === 'ul') {
          break;
        }
        insertedNode = insertedNode.parentNode;
      }
    }

    if (subject.match(/^1\.\s/) && sel.anchorNode.parentNode.nodeName !== 'LI') {
      document.execCommand('insertOrderedList');
      sel.anchorNode[textProp] = sel.anchorNode[textProp].substring(3);

      insertedNode = sel.anchorNode;
      while (insertedNode.parentNode) {
        if (insertedNode.nodeName.toLowerCase() === 'ol') {
          break;
        }
        insertedNode = insertedNode.parentNode;
      }
    }

    unwrap = insertedNode &&
            ['ul', 'ol'].indexOf(insertedNode.nodeName.toLocaleLowerCase()) >= 0 &&
            ['p', 'div'].indexOf(insertedNode.parentNode.nodeName.toLocaleLowerCase()) >= 0;

    if (unwrap) {
      node = sel.anchorNode;
      parent = insertedNode.parentNode;
      insertedNode.parentNode.parentNode.insertBefore(insertedNode, insertedNode.parentNode);
      parent.parentNode.removeChild(parent);

      range = document.createRange();
      range.setStart(node, 0);
      range.setEnd(node, 0);
      sel.removeAllRanges();
      sel.addRange(range);
    }
  }

  function triggerTextStyling(node) {
    var className = node.className,
        tagClass,
        reTag;

    for (var tag in tagClassMap) {
      tagClass = tagClassMap[tag];
      reTag = new RegExp(tagClass);

      if (reTag.test(className)) {
        switch(tag) {
          case "b":
          case "i":
            document.execCommand(tagClass, false);
            return;

          case "h1":
          case "h2":
          case "h3":
          case "blockquote":
            toggleFormatBlock(tag);
            return;

          case "a":
            toggleUrlInput();
            optionsNode.className = "options url-mode";
            return;
        }
      }
    }

    triggerTextSelection();
  }

  function triggerUrlBlur(event) {
    var url = urlInput.value;

    optionsNode.className = "options";
    window.getSelection().addRange(previouslySelectedText);

    document.execCommand("unlink", false);

    if (url === "") {
      return false;
    }

    if (!url.match("^(http|https)://")) {
      url = "http://" + url;
    }

    document.execCommand("createLink", false, url);

    urlInput.value = "";
  }

  function triggerUrlSet(event) {
    if (event.keyCode === 13) {
      event.preventDefault();
      event.stopPropagation();

      urlInput.blur();
    }
  }

  function toggleFormatBlock(tag) {
    if (hasParentWithTag(getFocusNode(), tag)) {
      document.execCommand("formatBlock", false, "p");
      document.execCommand("outdent");
    } else {
      document.execCommand("formatBlock", false, tag);
    }
  }

  function toggleUrlInput() {
    setTimeout(function() {
      var url = getParentHref(getFocusNode());

      if (typeof url !== "undefined") {
        urlInput.value = url;
      } else {
        document.execCommand("createLink", false, "/");
      }

      previouslySelectedText = window.getSelection().getRangeAt(0);

      urlInput.focus();
    }, 150);
  }

  function hasParentWithTag(node, nodeType) {
    while (node.parentNode) {
      if (node.nodeName.toLowerCase() === nodeType) {
        return true;
      }
      node = node.parentNode;
    }

    return false;
  }

  function getParentHref(node) {
    while (node.parentNode) {
      if (typeof node.href !== "undefined") {
        return node.href;
      }

      node = node.parentNode;
    }
  }

  function triggerTextSelection() {
      var selectedText = root.getSelection(),
          range,
          clientRectBounds;

      // The selected text is collapsed, push the menu out of the way
      if (selectedText.isCollapsed) {
        setTextMenuPosition(-999, -999);
      } else {
        range = selectedText.getRangeAt(0);
        clientRectBounds = range.getBoundingClientRect();

        // Every time we show the menu, reload the state
        reloadMenuState();
        setTextMenuPosition(
          clientRectBounds.top - 5 + root.pageYOffset,
          (clientRectBounds.left + clientRectBounds.right) / 2
        );
      }
  }

  function setTextMenuPosition(top, left) {
    textMenu.style.top = top + "px";
    textMenu.style.left = left + "px";
  }

  root.grande = grande;

  if (typeof root.sinon !== "undefined") {
    root.bindTextSelectionEvents = bindTextSelectionEvents;
  }

}).call(this);
<commit_msg>Remove this don't need to do this in application code<commit_after>(function() {
  var root = this,   // Root object, this is going to be the window for now
      document = this.document, // Safely store a document here for us to use
      editableNodes = document.querySelectorAll(".g-body article"),
      textMenu = document.querySelectorAll(".g-body .text-menu")[0],
      optionsNode = document.querySelectorAll(".g-body .text-menu .options")[0],
      urlInput = document.querySelectorAll(".g-body .text-menu .url-input")[0],
      isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1,

      previouslySelectedText,

      grande = {
        bind: function() {
          bindTextSelectionEvents();
          bindTextStylingEvents();
        },
        select: function() {
          triggerTextSelection();
        }
      },

      tagClassMap = {
        "b": "bold",
        "i": "italic",
        "h1": "header1",
        "h2": "header2",
        "a": "url",
        "blockquote": "quote"
      };

  function bindTextSelectionEvents() {
    var i,
        len,
        node;

    // Trigger on both mousedown and mouseup so that the click on the menu
    // feels more instantaneously active
    document.onmousedown = triggerTextSelection;
    document.onmouseup = function(event) {
      setTimeout(function() {
        triggerTextSelection(event);
      }, 1);
    };
    document.onkeyup = triggerTextParse;

    // Handle window resize events
    root.onresize = triggerTextSelection;

    urlInput.onblur = triggerUrlBlur;
    urlInput.onkeydown = triggerUrlSet;

    for (i = 0, len = editableNodes.length; i < len; i++) {
      node = editableNodes[i];
      node.onmousedown = node.onkeyup = node.onmouseup = triggerTextSelection;
    }
  }

  function iterateTextMenuButtons(callback) {
    var textMenuButtons = document.querySelectorAll(".g-body .text-menu button"),
        i,
        len,
        node;

    for (i = 0, len = textMenuButtons.length; i < len; i++) {
      node = textMenuButtons[i];

      (function(n) {
        callback(n);
      })(node);
    }
  }

  function bindTextStylingEvents() {
    iterateTextMenuButtons(function(node) {
      node.onmousedown = function(event) {
        triggerTextStyling(node);
      };
    });
  }

  function getFocusNode() {
    return root.getSelection().focusNode;
  }

  function reloadMenuState() {
    var className,
        focusNode = getFocusNode(),
        tagClass,
        reTag;

    iterateTextMenuButtons(function(node) {
      className = node.className;

      for (var tag in tagClassMap) {
        tagClass = tagClassMap[tag];
        reTag = new RegExp(tagClass);

        if (reTag.test(className)) {
          if (hasParentWithTag(focusNode, tag)) {
            node.className = tagClass + " active";
          } else {
            node.className = tagClass;
          }

          break;
        }
      }
    });
  }

  function triggerTextParse(event) {
    var sel = window.getSelection(),
        textProp,
        subject,
        insertedNode,
        unwrap,
        node,
        parent,
        range;

    // FF will return sel.anchorNode to be the parentNode when the triggered keyCode is 13
    if (!sel.isCollapsed || !sel.anchorNode || sel.anchorNode.nodeName === "ARTICLE") {
      return;
    }

    if (sel.anchorNode.nodeType === Node.TEXT_NODE) {
      textProp = "data";
    } else if (isFirefox) {
      textProp = "textContent";
    } else {
      textProp = "innerText";
    }

    subject = sel.anchorNode[textProp];

    if (subject.match(/^-\s/) && sel.anchorNode.parentNode.nodeName !== 'LI') {
      document.execCommand('insertUnorderedList');
      sel.anchorNode[textProp] = sel.anchorNode[textProp].substring(2);

      insertedNode = sel.anchorNode;
      while (insertedNode.parentNode) {
        if (insertedNode.nodeName.toLowerCase() === 'ul') {
          break;
        }
        insertedNode = insertedNode.parentNode;
      }
    }

    if (subject.match(/^1\.\s/) && sel.anchorNode.parentNode.nodeName !== 'LI') {
      document.execCommand('insertOrderedList');
      sel.anchorNode[textProp] = sel.anchorNode[textProp].substring(3);

      insertedNode = sel.anchorNode;
      while (insertedNode.parentNode) {
        if (insertedNode.nodeName.toLowerCase() === 'ol') {
          break;
        }
        insertedNode = insertedNode.parentNode;
      }
    }

    unwrap = insertedNode &&
            ['ul', 'ol'].indexOf(insertedNode.nodeName.toLocaleLowerCase()) >= 0 &&
            ['p', 'div'].indexOf(insertedNode.parentNode.nodeName.toLocaleLowerCase()) >= 0;

    if (unwrap) {
      node = sel.anchorNode;
      parent = insertedNode.parentNode;
      insertedNode.parentNode.parentNode.insertBefore(insertedNode, insertedNode.parentNode);
      parent.parentNode.removeChild(parent);

      range = document.createRange();
      range.setStart(node, 0);
      range.setEnd(node, 0);
      sel.removeAllRanges();
      sel.addRange(range);
    }
  }

  function triggerTextStyling(node) {
    var className = node.className,
        tagClass,
        reTag;

    for (var tag in tagClassMap) {
      tagClass = tagClassMap[tag];
      reTag = new RegExp(tagClass);

      if (reTag.test(className)) {
        switch(tag) {
          case "b":
          case "i":
            document.execCommand(tagClass, false);
            return;

          case "h1":
          case "h2":
          case "h3":
          case "blockquote":
            toggleFormatBlock(tag);
            return;

          case "a":
            toggleUrlInput();
            optionsNode.className = "options url-mode";
            return;
        }
      }
    }

    triggerTextSelection();
  }

  function triggerUrlBlur(event) {
    var url = urlInput.value;

    optionsNode.className = "options";
    window.getSelection().addRange(previouslySelectedText);

    document.execCommand("unlink", false);

    if (url === "") {
      return false;
    }

    if (!url.match("^(http|https)://")) {
      url = "http://" + url;
    }

    document.execCommand("createLink", false, url);

    urlInput.value = "";
  }

  function triggerUrlSet(event) {
    if (event.keyCode === 13) {
      event.preventDefault();
      event.stopPropagation();

      urlInput.blur();
    }
  }

  function toggleFormatBlock(tag) {
    if (hasParentWithTag(getFocusNode(), tag)) {
      document.execCommand("formatBlock", false, "p");
      document.execCommand("outdent");
    } else {
      document.execCommand("formatBlock", false, tag);
    }
  }

  function toggleUrlInput() {
    setTimeout(function() {
      var url = getParentHref(getFocusNode());

      if (typeof url !== "undefined") {
        urlInput.value = url;
      } else {
        document.execCommand("createLink", false, "/");
      }

      previouslySelectedText = window.getSelection().getRangeAt(0);

      urlInput.focus();
    }, 150);
  }

  function hasParentWithTag(node, nodeType) {
    while (node.parentNode) {
      if (node.nodeName.toLowerCase() === nodeType) {
        return true;
      }
      node = node.parentNode;
    }

    return false;
  }

  function getParentHref(node) {
    while (node.parentNode) {
      if (typeof node.href !== "undefined") {
        return node.href;
      }

      node = node.parentNode;
    }
  }

  function triggerTextSelection() {
      var selectedText = root.getSelection(),
          range,
          clientRectBounds;

      // The selected text is collapsed, push the menu out of the way
      if (selectedText.isCollapsed) {
        setTextMenuPosition(-999, -999);
      } else {
        range = selectedText.getRangeAt(0);
        clientRectBounds = range.getBoundingClientRect();

        // Every time we show the menu, reload the state
        reloadMenuState();
        setTextMenuPosition(
          clientRectBounds.top - 5 + root.pageYOffset,
          (clientRectBounds.left + clientRectBounds.right) / 2
        );
      }
  }

  function setTextMenuPosition(top, left) {
    textMenu.style.top = top + "px";
    textMenu.style.left = left + "px";
  }

  root.grande = grande;

}).call(this);
<|endoftext|>


<commit_before>import React, { PropTypes, Component } from 'react';
import ReactDOM from 'react-dom';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import levenshtein from './../lib/levenshtein';
import axios from 'axios';
import helperFunctions from '../utils/helperFunctions';

class CodeGhost extends Component {
  constructor(props) {
    super(props);

    this.state = {
      currentLevel: null,
      replayStarted : false
    };

    this.highScoreUser = '';
    this.pendingGetRequest = false;
  }

  static propTypes = {
    minifiedPuzzle: PropTypes.string,
    calculateProgress: PropTypes.func,
    fetchRecordUsername: PropTypes.func
  };

  componentDidMount() {
    this.record = {};

    this.editor = ace.edit('codeGhost');
    this.editor.setShowPrintMargin(false);
    this.editor.setOptions({
      fontSize: '10.5pt',
      minLines: 14,
      maxLines: 14,
      dragEnabled: false
    });
    this.editor.setTheme("ace/theme/tomorrow_night");
    this.editor.getSession().setMode("ace/mode/javascript");
    this.editor.getSession().setUseWorker(false);
    this.editor.setReadOnly(true);
    this.editor.$blockScrolling = Infinity;
    this.editor.setHighlightActiveLine(false);

    // Disables Selection of Text to Prevent Copy/Paste
    // Comment out for development purposes
    this.editor.on('changeSelection', function(e) {
      this.editor.selection.setSelectionRange({
        start: {
          row: 0,
          column: 0
        },
        end: {
          row: 0,
          column: 0
        }
      });
    }.bind(this));

    this.editor.getSession().on("change", function(e) {
      var value = this.editor.getSession().getValue();

      var code = value.replace(/\s/g,'');

      this.props.calculateProgress(code, true);
    }.bind(this));
  }

  // Plays back replay stored in this.record on game start
  startGhostReplay() {

    this.playbackClosure = function(value) {
      return function() {
        this.editor.setValue(value);
      }.bind(this);
    }.bind(this);

    var mark = null;

    for (var timeStamp in this.record) {
      if (mark) {
        var timeout = timeStamp - mark;
      } else {
        var timeout = 0;
        mark = timeStamp;
      }

      setTimeout(this.playbackClosure(this.record[timeStamp]), timeout);
    }
  }

  // Generates a fake ghost replay when there is no recording
  generateFakeGhost() {
    let fakeRecord = {};

    let startTime = new Date().getTime();
    let currentTime = new Date().getTime();

    for (let i = 0; i < this.props.currentPuzzle.length; i++) {
      fakeRecord[currentTime] = this.props.currentPuzzle.slice(0,i);
      currentTime += Math.random() * (1000 - 100) + 100;
    }

    fakeRecord.duration = currentTime - startTime;

    return fakeRecord;
  }

  componentDidUpdate() {
    if (this.props.currentLanguage.language === 'py') {
      this.editor.getSession().setMode("ace/mode/python");
    } else if (this.props.currentLanguage.language === 'js') {
      this.editor.getSession().setMode("ace/mode/javascript");
    } else if (this.props.currentLanguage.language === 'go') {
      this.editor.getSession().setMode("ace/mode/golang");
    }

    if (this.props.currentLevel && !this.pendingGetRequest) {
      if (Object.keys(this.record).length === 0 || this.props.currentLevel.currentLevel !== this.previousLevel) {
        this.pendingGetRequest = true;

        axios.get('api/getHighScore/?promptName=' + this.props.currentLevel.currentLevel)
          .then(function(res) {
            if (res.data !== '') {
              this.record = {};
              this.record = JSON.parse(res.data.recording).recording;
              this.props.fetchRecordUsername(res.data.username);
              this.pendingGetRequest = false;

            } else {
              this.record = this.generateFakeGhost();
              this.props.fetchRecordUsername('NimbleBot')

              this.pendingGetRequest = false;
            }
            this.previousLevel = this.props.currentLevel.currentLevel;
          }.bind(this));

      }
    }

    // On game start, start the ghost replay
    if (this.props.singleGame === 'STARTED_GAME' && !this.state.replayStarted) {
      this.startGhostReplay();
      this.setState({
        replayStarted: true
      });
    } else if (this.props.singleGame === null && this.state.replayStarted) { // If game was reset
      this.editor.setValue('');

      this.setState({
        replayStarted: false
      });

      // Clears all settimeouts if any still exist
      var id = window.setTimeout(function() {}, 0);
      while (id--) {
        window.clearTimeout(id);
      }
    }
  }

  render() {
    const style = {fontSize: '14px !important', border: '5px solid #181818'};

    return React.DOM.div({
      id: 'codeGhost',
      style: style,
      className: 'col-sm-6'
    });
  }
}

function mapStateToProps(state) {
  return {
    singleGame: state.singleGame,
    currentLevel: state.currentLevel,
    currentLanguage: state.currentLanguage
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({
  }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(CodeGhost);
<commit_msg>[fix] speeds up nimble bot a bit to 10-600ms between each key<commit_after>import React, { PropTypes, Component } from 'react';
import ReactDOM from 'react-dom';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import levenshtein from './../lib/levenshtein';
import axios from 'axios';
import helperFunctions from '../utils/helperFunctions';

class CodeGhost extends Component {
  constructor(props) {
    super(props);

    this.state = {
      currentLevel: null,
      replayStarted : false
    };

    this.highScoreUser = '';
    this.pendingGetRequest = false;
  }

  static propTypes = {
    minifiedPuzzle: PropTypes.string,
    calculateProgress: PropTypes.func,
    fetchRecordUsername: PropTypes.func
  };

  componentDidMount() {
    this.record = {};

    this.editor = ace.edit('codeGhost');
    this.editor.setShowPrintMargin(false);
    this.editor.setOptions({
      fontSize: '10.5pt',
      minLines: 14,
      maxLines: 14,
      dragEnabled: false
    });
    this.editor.setTheme("ace/theme/tomorrow_night");
    this.editor.getSession().setMode("ace/mode/javascript");
    this.editor.getSession().setUseWorker(false);
    this.editor.setReadOnly(true);
    this.editor.$blockScrolling = Infinity;
    this.editor.setHighlightActiveLine(false);

    // Disables Selection of Text to Prevent Copy/Paste
    // Comment out for development purposes
    this.editor.on('changeSelection', function(e) {
      this.editor.selection.setSelectionRange({
        start: {
          row: 0,
          column: 0
        },
        end: {
          row: 0,
          column: 0
        }
      });
    }.bind(this));

    this.editor.getSession().on("change", function(e) {
      var value = this.editor.getSession().getValue();

      var code = value.replace(/\s/g,'');

      this.props.calculateProgress(code, true);
    }.bind(this));
  }

  // Plays back replay stored in this.record on game start
  startGhostReplay() {

    this.playbackClosure = function(value) {
      return function() {
        this.editor.setValue(value);
      }.bind(this);
    }.bind(this);

    var mark = null;

    for (var timeStamp in this.record) {
      if (mark) {
        var timeout = timeStamp - mark;
      } else {
        var timeout = 0;
        mark = timeStamp;
      }

      setTimeout(this.playbackClosure(this.record[timeStamp]), timeout);
    }
  }

  // Generates a fake ghost replay when there is no recording
  generateFakeGhost() {
    let fakeRecord = {};

    let startTime = new Date().getTime();
    let currentTime = new Date().getTime();

    for (let i = 0; i < this.props.currentPuzzle.length; i++) {
      fakeRecord[currentTime] = this.props.currentPuzzle.slice(0,i);
      currentTime += Math.random() * (600 - 10) + 10;
    }

    fakeRecord.duration = currentTime - startTime;

    return fakeRecord;
  }

  componentDidUpdate() {
    if (this.props.currentLanguage.language === 'py') {
      this.editor.getSession().setMode("ace/mode/python");
    } else if (this.props.currentLanguage.language === 'js') {
      this.editor.getSession().setMode("ace/mode/javascript");
    } else if (this.props.currentLanguage.language === 'go') {
      this.editor.getSession().setMode("ace/mode/golang");
    }

    if (this.props.currentLevel && !this.pendingGetRequest) {
      if (Object.keys(this.record).length === 0 || this.props.currentLevel.currentLevel !== this.previousLevel) {
        this.pendingGetRequest = true;

        axios.get('api/getHighScore/?promptName=' + this.props.currentLevel.currentLevel)
          .then(function(res) {
            if (res.data !== '') {
              this.record = {};
              this.record = JSON.parse(res.data.recording).recording;
              this.props.fetchRecordUsername(res.data.username);
              this.pendingGetRequest = false;

            } else {
              this.record = this.generateFakeGhost();
              this.props.fetchRecordUsername('NimbleBot')

              this.pendingGetRequest = false;
            }
            this.previousLevel = this.props.currentLevel.currentLevel;
          }.bind(this));

      }
    }

    // On game start, start the ghost replay
    if (this.props.singleGame === 'STARTED_GAME' && !this.state.replayStarted) {
      this.startGhostReplay();
      this.setState({
        replayStarted: true
      });
    } else if (this.props.singleGame === null && this.state.replayStarted) { // If game was reset
      this.editor.setValue('');

      this.setState({
        replayStarted: false
      });

      // Clears all settimeouts if any still exist
      var id = window.setTimeout(function() {}, 0);
      while (id--) {
        window.clearTimeout(id);
      }
    }
  }

  render() {
    const style = {fontSize: '14px !important', border: '5px solid #181818'};

    return React.DOM.div({
      id: 'codeGhost',
      style: style,
      className: 'col-sm-6'
    });
  }
}

function mapStateToProps(state) {
  return {
    singleGame: state.singleGame,
    currentLevel: state.currentLevel,
    currentLanguage: state.currentLanguage
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({
  }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(CodeGhost);
<|endoftext|>


<commit_before>// Access "books" collection locally.
var myBooks = Alloy.Collections.books;

function addBook(e) {
  var addBookController = Alloy.createController('addbook');
  var addBookView = addBookController.getView();

  // On iOS, open the book view in the navigation window.
  if (OS_IOS) {
    $.navGroupWin.openWindow(addBookView);
  }

  // On Android, simply open the window.
  if (OS_ANDROID) {
    addBookView.open();
  }
};

function showBook(e) {
  var selectedBook = e.source;
  var args = {
    title: selectedBook.title,
    author: selectedBook.author
  };

  // Get the book view from the book controller.
  var bookController = Alloy.createController('bookdetails', args);
  var bookView = bookController.getView();

  // On iOS, open the book view in the navigation window.
  if (OS_IOS) {
    $.navGroupWin.openWindow(bookView);
  }

  // On Android, simply open the window.
  if (OS_ANDROID) {
    bookView.open();
  }

  Ti.API.error(JSON.stringify(e.source));
};

// Create a "book" model.
var book = Alloy.createModel('books', {
  title : 'Great Expectations',
  author: 'Charles Dickens'
});

// Add book model to the collection.
myBooks.add(book);

// Persiste the book in the database.
book.save();

// Display the contens of the collection.
Ti.API.info(myBooks.toJSON());

// Create platform-specific window handling.
// Android uses a simple window as the top-level view in index.xml,
// iOS uses a Navigation window.
if (OS_IOS) {
  $.navGroupWin.open();
}

if (OS_ANDROID) {
  $.index.open();
}
<commit_msg>Fetch existing books from the database when app is loaded<commit_after>// Access "books" collection locally.
var myBooks = Alloy.Collections.books;
myBooks.fetch();

// Display the contens of the collection.
Ti.API.info(myBooks.toJSON());

function addBook(e) {
  var addBookController = Alloy.createController('addbook');
  var addBookView = addBookController.getView();

  // On iOS, open the book view in the navigation window.
  if (OS_IOS) {
    $.navGroupWin.openWindow(addBookView);
  }

  // On Android, simply open the window.
  if (OS_ANDROID) {
    addBookView.open();
  }
};

function showBook(e) {
  var selectedBook = e.source;
  var args = {
    title: selectedBook.title,
    author: selectedBook.author
  };

  // Get the book view from the book controller.
  var bookController = Alloy.createController('bookdetails', args);
  var bookView = bookController.getView();

  // On iOS, open the book view in the navigation window.
  if (OS_IOS) {
    $.navGroupWin.openWindow(bookView);
  }

  // On Android, simply open the window.
  if (OS_ANDROID) {
    bookView.open();
  }

  Ti.API.error(JSON.stringify(e.source));
};

// Create platform-specific window handling.
// Android uses a simple window as the top-level view in index.xml,
// iOS uses a Navigation window.
if (OS_IOS) {
  $.navGroupWin.open();
}

if (OS_ANDROID) {
  $.index.open();
}
<|endoftext|>


<commit_before>var bwClockHour = null;
var bwClockMinute = null;
var bwClockRequestedType = null;
var bwClockCurrentType = null;

function bwClockLaunch(type) {
  if ((document.getElementById("clock").className == "shown") && (bwClockCurrentType == type)) {
    changeClass("clock","invisible"); // if the clock with the same type is showing, toggle it off
  } else { // otherwise, turn it on and display the correct type
    bwClockRequestedType = type;
    bwClockCurrentType = type;
    changeClass("clock","shown");
    // the following is for Internet Explorer.  IE draws "windowed" objects
    // and unwindowed objects on seperate "planes"; windowed objects are always
    // drawn obove unwindowed objects and select boxes are "windowed";
    // this is required to make IE not overwrite the clock div with
    // the select boxes that fall below it on the page.  Note: we set them
    // to display:hidden (not none) so their space is still occupied (and the
    // browser window doesn't shift around)
   changeClass("eventFormPrefLocationList","hidden");
   changeClass("eventFormLocationList","hidden");
   changeClass("eventFormSponsorList","hidden");
   changeClass("eventFormPrefSponsorList","hidden");
    bwClockIndicator = document.getElementById("bwClockDateTypeIndicator");
    if (type == 'eventStartDate') {
      bwClockIndicator.innerHTML = "Start Time"
    } else {
      bwClockIndicator.innerHTML = "End Time"
    }
  }
}

function bwClockClose() {
  changeClass("clock","invisible");
  changeClass("eventFormPrefLocationList","shown");
  changeClass("eventFormLocationList","shown");
  changeClass("eventFormSponsorList","shown");
  changeClass("eventFormPrefSponsorList","shown");
}

function bwClockUpdateDateTimeForm(type,val) {
  if (bwClockRequestedType) {
    try {
      if (type == 'minute') {
        var fieldName = bwClockRequestedType + ".minute"
        window.document.peForm[fieldName].value = val;
        bwClockMinute = val;
      } else {
        var fieldName = bwClockRequestedType + ".hour"
        window.document.peForm[fieldName].value = val;
        bwClockHour = val;
      }
      if (bwClockHour && bwClockMinute) {
        document.getElementById("bwClockTime").innerHTML = bwClockHour + ":" + bwClockMinute + " , " + bwClockConvertAmPm(bwClockHour) + ":" + bwClockMinute + " " + bwClockGetAmPm(bwClockHour);
      } else if (bwClockMinute) {
        document.getElementById("bwClockTime").innerHTML = ":" + bwClockMinute;
      } else {
        document.getElementById("bwClockTime").innerHTML = bwClockHour + " , " + bwClockConvertAmPm(bwClockHour) + " " + bwClockGetAmPm(bwClockHour);
      }
    } catch(e) {
      alert("There was an error:\n" + e );
    }
  } else {
    alert("The date type is null.");
  }
}

function bwClockConvertAmPm(hour24) {
  hour24 = parseInt(hour24,10);
  if (hour24 == 0) {
    return 12;
  } else if (hour24 > 12) {
    return hour24 - 12;
  } else {
    return hour24;
  }
}

function bwClockGetAmPm(hour24) {
  hour24 = parseInt(hour24,10);
  if (hour24 < 12) {
    return 'a.m.';
  } else {
    return 'p.m.';
  }
}
<commit_msg>admin client: fix up 24 hour clock<commit_after>var bwClockHour = null;
var bwClockMinute = null;
var bwClockRequestedType = null;
var bwClockCurrentType = null;

function bwClockLaunch(type) {
  if ((document.getElementById("clock").className == "shown") && (bwClockCurrentType == type)) {
    changeClass("clock","invisible"); // if the clock with the same type is showing, toggle it off
  } else { // otherwise, turn it on and display the correct type
    bwClockRequestedType = type;
    bwClockCurrentType = type;
    changeClass("clock","shown");
    // the following is for Internet Explorer.  IE draws "windowed" objects
    // and unwindowed objects on seperate "planes"; windowed objects are always
    // drawn obove unwindowed objects and select boxes are "windowed";
    // this is required to make IE not overwrite the clock div with
    // the select boxes that fall below it on the page.  Note: we set them
    // to display:hidden (not none) so their space is still occupied (and the
    // browser window doesn't shift around)
   changeClass("eventFormPrefLocationList","hidden");
   changeClass("eventFormLocationList","hidden");
   changeClass("eventFormContactList","hidden");
   changeClass("eventFormPrefContactList","hidden");
    bwClockIndicator = document.getElementById("bwClockDateTypeIndicator");
    if (type == 'eventStartDate') {
      bwClockIndicator.innerHTML = "Start Time"
    } else {
      bwClockIndicator.innerHTML = "End Time"
    }
  }
}

function bwClockClose() {
  changeClass("clock","invisible");
  changeClass("eventFormPrefLocationList","shown");
  changeClass("eventFormLocationList","shown");
  changeClass("eventFormContactList","shown");
  changeClass("eventFormPrefContactList","shown");
}

function bwClockUpdateDateTimeForm(type,val) {
  if (bwClockRequestedType) {
    try {
      if (type == 'minute') {
        var fieldName = bwClockRequestedType + ".minute"
        window.document.peForm[fieldName].value = val;
        bwClockMinute = val;
      } else {
        var fieldName = bwClockRequestedType + ".hour"
        window.document.peForm[fieldName].value = val;
        bwClockHour = val;
      }
      if (bwClockHour && bwClockMinute) {
        document.getElementById("bwClockTime").innerHTML = bwClockHour + ":" + bwClockMinute + " , " + bwClockConvertAmPm(bwClockHour) + ":" + bwClockMinute + " " + bwClockGetAmPm(bwClockHour);
      } else if (bwClockMinute) {
        document.getElementById("bwClockTime").innerHTML = ":" + bwClockMinute;
      } else {
        document.getElementById("bwClockTime").innerHTML = bwClockHour + " , " + bwClockConvertAmPm(bwClockHour) + " " + bwClockGetAmPm(bwClockHour);
      }
    } catch(e) {
      alert("There was an error:\n" + e );
    }
  } else {
    alert("The date type is null.");
  }
}

function bwClockConvertAmPm(hour24) {
  hour24 = parseInt(hour24,10);
  if (hour24 == 0) {
    return 12;
  } else if (hour24 > 12) {
    return hour24 - 12;
  } else {
    return hour24;
  }
}

function bwClockGetAmPm(hour24) {
  hour24 = parseInt(hour24,10);
  if (hour24 < 12) {
    return 'a.m.';
  } else {
    return 'p.m.';
  }
}
<|endoftext|>


<commit_before>function loginUser(){
	//variable https gets the module appcelerator.https
	var https = require("appcelerator.https");

	//function in the module called User.login
	//checks if it is a valid user with the cloud service

	var securityManager = https.createX509CertificatePinningSecurityManager([
    {
        url: "https://coelm2/TNdevelopment/mobile/EricaTest.nsf/HelloWorld.xsp", //URL of the server to contact
        serverCertificate: "CGA.der" // X.509 certificate in DER format to verify the server's identity'
    }
	]);

	// Create an HTTP client the same way you always have
	// but pass in the optional Security Manager that was created previously.
	httpClient = Ti.Network.createHTTPClient({
	    onload: function(e) {
	        Ti.API.info("Received text: " + this.responseText);
	    },
	    onerror: function(e) {
	        Ti.API.error(e.error);
	    },
	    timeout : 5000,
	    // Set this property before calling the `open` method.
	    securityManager: securityManager
	});
	httpClient.open("GET","https://coelm2/TNdevelopment/mobile/EricaTest.nsf/HelloWorld.xsp");
	httpClient.send();

}

function openNewUser(){
	var newWindow = Alloy.createController('newuser').getView();
	newWindow.open();
}

function resetUser(){
	var newWindow = Alloy.createController('resetuser').getView();
	newWindow.open();
}

$.index.open();<commit_msg>adding some code for accepting username and password<commit_after>function loginUser(){
	//variable https gets the module appcelerator.https
	var https = require("appcelerator.https");

	//function in the module called User.login
	//checks if it is a valid user with the cloud service

	var securityManager = https.createX509CertificatePinningSecurityManager([
	    {
	        url: "https://coelm2/TNdevelopment/mobile/EricaTest.nsf/HelloWorld.xsp", //URL of the server to contact
	        serverCertificate: "CGA.der" // X.509 certificate in DER format to verify the server's identity'
	    },
	    {
	        url: "https://coelm2/TNdevelopment/mobile/EricaTest.nsf/HelloWorld.xsp", //URL of the server to contact
	        serverCertificate: "coelm2.der" // X.509 certificate in DER format to verify the server's identity'
	    }
	]);

	// Create an HTTP client the same way you always have
	// but pass in the optional Security Manager that was created previously.
	httpClient = Ti.Network.createHTTPClient({
	    onload: function(e) {
	        Ti.API.info("Received text: " + this.responseText);
	    },
	    onerror: function(e) {
	        Ti.API.error(e.error);
	    },
	    timeout : 5000,
	    // Set this property before calling the `open` method.
	    securityManager: securityManager
	});
	httpClient.username($.txtUserName.value);
		        Ti.API.info("Received username: " + $.txtUserName.value);
	httpClient.password($.txtPwd.value);
	httpClient.open("GET","https://coelm2/TNdevelopment/mobile/EricaTest.nsf/HelloWorld.xsp");

	httpClient.send();

}

function openNewUser(){
	var newWindow = Alloy.createController('newuser').getView();
	newWindow.open();
}

function resetUser(){
	var newWindow = Alloy.createController('resetuser').getView();
	newWindow.open();
}

$.index.open();<|endoftext|>