<commit_before>/*global ko Router */
(function () {
	'use strict';

	var ENTER_KEY = 13;

	// a custom binding to handle the enter key (could go in a separate library)
	ko.bindingHandlers.enterKey = {
		init: function (element, valueAccessor, allBindingsAccessor, data) {
			var wrappedHandler, newValueAccessor;

			// wrap the handler with a check for the enter key
			wrappedHandler = function (data, event) {
				if (event.keyCode === ENTER_KEY) {
					valueAccessor().call(this, data, event);
				}
			};

			// create a valueAccessor with the options that we would want to pass to the event binding
			newValueAccessor = function () {
				return {
					keyup: wrappedHandler
				};
			};

			// call the real event binding's init function
			ko.bindingHandlers.event.init(element, newValueAccessor, allBindingsAccessor, data);
		}
	};

	// wrapper to hasfocus that also selects text and applies focus async
	ko.bindingHandlers.selectAndFocus = {
		init: function (element, valueAccessor, allBindingsAccessor) {
			ko.bindingHandlers.hasfocus.init(element, valueAccessor, allBindingsAccessor);
			ko.utils.registerEventHandler(element, 'focus', function () {
				element.focus();
			});
		},
		update: function (element, valueAccessor) {
			ko.utils.unwrapObservable(valueAccessor()); // for dependency
			// ensure that element is visible before trying to focus
			setTimeout(function () {
				ko.bindingHandlers.hasfocus.update(element, valueAccessor);
			}, 0);
		}
	};

	// represent a single todo item
	var Todo = function (title, completed) {
		this.title = ko.observable(title);
		this.completed = ko.observable(completed);
		this.editing = ko.observable(false);
	};

	// our main view model
	var ViewModel = function (todos) {
		var self = this;

		// map array of passed in todos to an observableArray of Todo objects
		self.todos = ko.observableArray(ko.utils.arrayMap(todos, function (todo) {
			return new Todo(todo.title, todo.completed);
		}));

		// store the new todo value being entered
		self.current = ko.observable();

		self.showMode = ko.observable('all');

		self.filteredTodos = ko.computed(function () {
			switch (self.showMode()) {
			case 'active':
				return self.todos().filter(function (todo) {
					return !todo.completed();
				});
			case 'completed':
				return self.todos().filter(function (todo) {
					return todo.completed();
				});
			default:
				return self.todos();
			}
		});

		// add a new todo, when enter key is pressed
		self.add = function () {
			var current = self.current().trim();
			if (current) {
				self.todos.push(new Todo(current));
				self.current('');
			}
		};

		// remove a single todo
		self.remove = function (todo) {
			self.todos.remove(todo);
		};

		// remove all completed todos
		self.removeCompleted = function () {
			self.todos.remove(function (todo) {
				return todo.completed();
			});
		};

		// edit an item
		self.editItem = function (item) {
			item.editing(true);
		};

		// stop editing an item.  Remove the item, if it is now empty
		self.stopEditing = function (item) {
			item.editing(false);

			if (!item.title().trim()) {
				self.remove(item);
			}
		};

		// count of all completed todos
		self.completedCount = ko.computed(function () {
			return ko.utils.arrayFilter(self.todos(), function (todo) {
				return todo.completed();
			}).length;
		});

		// count of todos that are not complete
		self.remainingCount = ko.computed(function () {
			return self.todos().length - self.completedCount();
		});

		// writeable computed observable to handle marking all complete/incomplete
		self.allCompleted = ko.computed({
			//always return true/false based on the done flag of all todos
			read: function () {
				return !self.remainingCount();
			},
			// set all todos to the written value (true/false)
			write: function (newValue) {
				ko.utils.arrayForEach(self.todos(), function (todo) {
					// set even if value is the same, as subscribers are not notified in that case
					todo.completed(newValue);
				});
			}
		});

		// helper function to keep expressions out of markup
		self.getLabel = function (count) {
			return ko.utils.unwrapObservable(count) === 1 ? 'item' : 'items';
		};

		// internal computed observable that fires whenever anything changes in our todos
		ko.computed(function () {
			// store a clean copy to local storage, which also creates a dependency on the observableArray and all observables in each item
			localStorage.setItem('todos-knockout', ko.toJSON(self.todos));
		}).extend({
			throttle: 500
		}); // save at most twice per second
	};

	// check local storage for todos
	var todos = ko.utils.parseJson(localStorage.getItem('todos-knockout'));

	// bind a new instance of our view model to the page
	var viewModel = new ViewModel(todos || []);
	ko.applyBindings(viewModel);

	// set up filter routing
	/*jshint newcap:false*/
	Router({'/:filter': viewModel.showMode}).init();
}());
<commit_msg>Knockout app - code style<commit_after>/*global ko Router */
(function () {
	'use strict';

	var ENTER_KEY = 13;

	// a custom binding to handle the enter key (could go in a separate library)
	ko.bindingHandlers.enterKey = {
		init: function (element, valueAccessor, allBindingsAccessor, data) {
			var wrappedHandler, newValueAccessor;

			// wrap the handler with a check for the enter key
			wrappedHandler = function (data, event) {
				if (event.keyCode === ENTER_KEY) {
					valueAccessor().call(this, data, event);
				}
			};

			// create a valueAccessor with the options that we would want to pass to the event binding
			newValueAccessor = function () {
				return {
					keyup: wrappedHandler
				};
			};

			// call the real event binding's init function
			ko.bindingHandlers.event.init(element, newValueAccessor, allBindingsAccessor, data);
		}
	};

	// wrapper to hasfocus that also selects text and applies focus async
	ko.bindingHandlers.selectAndFocus = {
		init: function (element, valueAccessor, allBindingsAccessor) {
			ko.bindingHandlers.hasfocus.init(element, valueAccessor, allBindingsAccessor);
			ko.utils.registerEventHandler(element, 'focus', function () {
				element.focus();
			});
		},
		update: function (element, valueAccessor) {
			ko.utils.unwrapObservable(valueAccessor()); // for dependency
			// ensure that element is visible before trying to focus
			setTimeout(function () {
				ko.bindingHandlers.hasfocus.update(element, valueAccessor);
			}, 0);
		}
	};

	// represent a single todo item
	var Todo = function (title, completed) {
		this.title = ko.observable(title);
		this.completed = ko.observable(completed);
		this.editing = ko.observable(false);
	};

	// our main view model
	var ViewModel = function (todos) {
		var self = this;

		// map array of passed in todos to an observableArray of Todo objects
		self.todos = ko.observableArray(ko.utils.arrayMap(todos, function (todo) {
			return new Todo(todo.title, todo.completed);
		}));

		// store the new todo value being entered
		self.current = ko.observable();

		self.showMode = ko.observable('all');

		self.filteredTodos = ko.computed(function () {
			switch (self.showMode()) {
			case 'active':
				return self.todos().filter(function (todo) {
					return !todo.completed();
				});
			case 'completed':
				return self.todos().filter(function (todo) {
					return todo.completed();
				});
			default:
				return self.todos();
			}
		});

		// add a new todo, when enter key is pressed
		self.add = function () {
			var current = self.current().trim();
			if (current) {
				self.todos.push(new Todo(current));
				self.current('');
			}
		};

		// remove a single todo
		self.remove = function (todo) {
			self.todos.remove(todo);
		};

		// remove all completed todos
		self.removeCompleted = function () {
			self.todos.remove(function (todo) {
				return todo.completed();
			});
		};

		// edit an item
		self.editItem = function (item) {
			item.editing(true);
		};

		// stop editing an item.  Remove the item, if it is now empty
		self.stopEditing = function (item) {
			item.editing(false);

			if (!item.title().trim()) {
				self.remove(item);
			}
		};

		// count of all completed todos
		self.completedCount = ko.computed(function () {
			return ko.utils.arrayFilter(self.todos(), function (todo) {
				return todo.completed();
			}).length;
		});

		// count of todos that are not complete
		self.remainingCount = ko.computed(function () {
			return self.todos().length - self.completedCount();
		});

		// writeable computed observable to handle marking all complete/incomplete
		self.allCompleted = ko.computed({
			//always return true/false based on the done flag of all todos
			read: function () {
				return !self.remainingCount();
			},
			// set all todos to the written value (true/false)
			write: function (newValue) {
				ko.utils.arrayForEach(self.todos(), function (todo) {
					// set even if value is the same, as subscribers are not notified in that case
					todo.completed(newValue);
				});
			}
		});

		// helper function to keep expressions out of markup
		self.getLabel = function (count) {
			return ko.utils.unwrapObservable(count) === 1 ? 'item' : 'items';
		};

		// internal computed observable that fires whenever anything changes in our todos
		ko.computed(function () {
			// store a clean copy to local storage, which also creates a dependency on the observableArray and all observables in each item
			localStorage.setItem('todos-knockoutjs', ko.toJSON(self.todos));
		}).extend({
			throttle: 500
		}); // save at most twice per second
	};

	// check local storage for todos
	var todos = ko.utils.parseJson(localStorage.getItem('todos-knockoutjs'));

	// bind a new instance of our view model to the page
	var viewModel = new ViewModel(todos || []);
	ko.applyBindings(viewModel);

	// set up filter routing
	/*jshint newcap:false */
	Router({'/:filter': viewModel.showMode}).init();
})();
<|endoftext|>


<commit_before>// dependencies
var MongoDb = require("mongodb")
  , ObjectId = MongoDb.ObjectID
  ;

//  crud role cache
//  {
//      CRUD_ROLE_ID: CRUD_ROLE_DOCUMENT
//  }
var CrudRoleCache = {};

/**
 *
 *  user-actions#getUserControls
 *
 *  This function returns an object in the following format:
 *  {
 *      SELECTOR: true
 *    , ANOTHER_SELECTOR: false
 *  }
 *
 *  This object will be interpreted on the client side: `SELECTOR` will be visible
 *  and `ANOTHER_SELECTOR` will be hidden.
 *
 *  Example
 *
 *      SERVER                                          CLIENT
 *      Role Object
 *      -----------                                     Selectors
 *      {                                               "[data-action='delete']"
 *          name: ...                                   "[data-action='update']"
 *        , actions: [
 *              {
 *                  template: link.data.template
 *                , filter:   link.data.filter
 *                , selector: link.data.selector
 *              }
 *          ]
 *      }
 *
 *      ----> each action --> Crud
 *
 *      {
 *          "[data-action='update']": true
 *        , "[data-action='delete']": false
 *      }
 *
 *
 * */
exports.getUserControls = function (link) {

    // get allowed actions for this user
    getAllowedActions (link, function (err, responseObject) {

        // handle error
        if (err) {
            return link.send(400, err);
        }

        // success response
        link.send(200, responseObject);
    });
};

/**
 *  user-actions#runAction
 *
 *  This operation runs an user action running the validations
 *  on the server side.
 *
 * */
exports.runAction = function (link) {

    // get allowed actions for this user
    getAllowedActions (link, function (err, responseObject) {

        // handle error
        if (err) {
            return link.send(400, err);
        }

        // get current action
        var cAction = link.data.cAction;

        if (!cAction) {
            return link.send(400, "Missing current action");
        }

        // not allowed
        if (!responseObject[cAction]) {
            return link.send(403, "You are not allowed to run this action.");
        }

        // emit some event. Sombody must listen this event and to handle
        // it correctly
        M.emit("user-actions:run-action", link);
    });
};

/**
 * private: getAllowedActions
 *  This function returns via callback the allowed actions for the
 *  current user.
 *
 */
function getAllowedActions (link, callback) {

    // this object will be sent back to client
    var responseObject = {}

        // get the data sent from client
      , data = link.data = Object(link.data);

    // missing item id
    if (!data.itemId) {
        return callback ("Missing item id.");
    }

    // missing template id
    if (!data.templateId) {
        return callback ("Missing template id.");
    }

    // get the crud role
    getRoleObject(link, function (err, crudRole) {

        // handle error
        if (err) {
            return callback (err);
        }

        // get role actions
        var actions = crudRole.actions;

        // each action
        for (var i = 0, l = actions.length, complete = 0; i < l; ++i) {

            // anonymous function
            (function (cAction) {

                // set the _id of the current item
                cAction.filter._id = String(data.itemId);

                // also, the template
                cAction.filter._tp = ObjectId(cAction.template);

                // create the crud object
                var crudObject = {
                    templateId: data.templateId
                  , query: cAction.filter
                  , role: link.session.crudRole
                  , session: link.session
                };

                // find the items via crud
                M.emit("crud.read", crudObject, function (err, items) {

                    // handle error
                    if (err) {
                        return callback (err);
                    }

                    // convert cursor to array
                    items.toArray(function (err, items) {

                        // handle error
                        if (err) {
                            return callback (err);
                        }

                        // set a true/false value for this selector
                        responseObject[cAction.selector] = Boolean(items.length);

                        // complete?
                        if (++complete === l) {
                            callback (null, responseObject);
                        }
                    })
                });
            })(actions[i]);
        }
    });
}

/**
 * private: getRoleObject
 *
 *  This function callbacks the crud role object from the database
 *  using CRUD or from CrudRoleCache object.
 *
 *  Arguments
 *    @link: the Mono link object
 *    @callback: the callback function
 *
 * */
function getRoleObject (link, callback) {

    // stringify the crud role
    var stringifiedCrudRole = link.session.crudRole.toString()
      , crudRoleInCache = CrudRoleCache[stringifiedCrudRole]
      ;

    // the crud role already is in cache
    if (crudRoleInCache) {
        return callback (null, crudRoleInCache);
    }

    // create the crud object
    var crudObject = {
        templateId: "000000000000000000000002"
      , query: {
          _id: stringifiedCrudRole
        }
      , role: link.session.crudRole
      , session: link.session
    };

    // find the items via crud
    M.emit("crud.read", crudObject, function (err, crudRoleObject) {

        // handle error
        if (err) {
            return callback (err);
        }

        // convert cursor to array
        crudRoleObject.toArray(function (err, items) {

            // handle error
            if (err) {
                return callback (err);
            }

            // handle error
            if (!items || !items.length) {
                return callback ("No crud role found with this id.");
            }

            // get the first element from array
            crudRoleObject = items[0];

            // save the new crud role in cache
            CrudRoleCache[stringifiedCrudRole] = crudRoleObject;

            // callback
            callback (null, crudRoleObject);
        });
    });
}
<commit_msg>Send allowed actions object and link.data<commit_after>// dependencies
var MongoDb = require("mongodb")
  , ObjectId = MongoDb.ObjectID
  ;

//  crud role cache
//  {
//      CRUD_ROLE_ID: CRUD_ROLE_DOCUMENT
//  }
var CrudRoleCache = {};

/**
 *
 *  user-actions#getUserControls
 *
 *  This function returns an object in the following format:
 *  {
 *      SELECTOR: true
 *    , ANOTHER_SELECTOR: false
 *  }
 *
 *  This object will be interpreted on the client side: `SELECTOR` will be visible
 *  and `ANOTHER_SELECTOR` will be hidden.
 *
 *  Example
 *
 *      SERVER                                          CLIENT
 *      Role Object
 *      -----------                                     Selectors
 *      {                                               "[data-action='delete']"
 *          name: ...                                   "[data-action='update']"
 *        , actions: [
 *              {
 *                  template: link.data.template
 *                , filter:   link.data.filter
 *                , selector: link.data.selector
 *              }
 *          ]
 *      }
 *
 *      ----> each action --> Crud
 *
 *      {
 *          "[data-action='update']": true
 *        , "[data-action='delete']": false
 *      }
 *
 *
 * */
exports.getUserControls = function (link) {

    // get allowed actions for this user
    getAllowedActions (link, function (err, responseObject) {

        // handle error
        if (err) {
            return link.send(400, err);
        }

        // success response
        link.send(200, responseObject);
    });
};

/**
 *  user-actions#runAction
 *
 *  This operation runs an user action running the validations
 *  on the server side.
 *
 * */
exports.runAction = function (link) {

    // get allowed actions for this user
    getAllowedActions (link, function (err, responseObject) {

        // handle error
        if (err) {
            return link.send(400, err);
        }

        // get current action
        var cAction = link.data.cAction;

        if (!cAction) {
            return link.send(400, "Missing current action");
        }

        // not allowed
        if (!responseObject[cAction]) {
            return link.send(403, "You are not allowed to run this action.");
        }

        // emit some event. Sombody must listen this event and to handle
        // it correctly
        M.emit("user-actions:run-action", link, responseObject, link.data);
    });
};

/**
 * private: getAllowedActions
 *  This function returns via callback the allowed actions for the
 *  current user.
 *
 */
function getAllowedActions (link, callback) {

    // this object will be sent back to client
    var responseObject = {}

        // get the data sent from client
      , data = link.data = Object(link.data);

    // missing item id
    if (!data.itemId) {
        return callback ("Missing item id.");
    }

    // missing template id
    if (!data.templateId) {
        return callback ("Missing template id.");
    }

    // get the crud role
    getRoleObject(link, function (err, crudRole) {

        // handle error
        if (err) {
            return callback (err);
        }

        // get role actions
        var actions = crudRole.actions;

        // each action
        for (var i = 0, l = actions.length, complete = 0; i < l; ++i) {

            // anonymous function
            (function (cAction) {

                // set the _id of the current item
                cAction.filter._id = String(data.itemId);

                // also, the template
                cAction.filter._tp = ObjectId(cAction.template);

                // create the crud object
                var crudObject = {
                    templateId: data.templateId
                  , query: cAction.filter
                  , role: link.session.crudRole
                  , session: link.session
                };

                // find the items via crud
                M.emit("crud.read", crudObject, function (err, items) {

                    // handle error
                    if (err) {
                        return callback (err);
                    }

                    // convert cursor to array
                    items.toArray(function (err, items) {

                        // handle error
                        if (err) {
                            return callback (err);
                        }

                        // set a true/false value for this selector
                        responseObject[cAction.selector] = Boolean(items.length);

                        // complete?
                        if (++complete === l) {
                            callback (null, responseObject);
                        }
                    })
                });
            })(actions[i]);
        }
    });
}

/**
 * private: getRoleObject
 *
 *  This function callbacks the crud role object from the database
 *  using CRUD or from CrudRoleCache object.
 *
 *  Arguments
 *    @link: the Mono link object
 *    @callback: the callback function
 *
 * */
function getRoleObject (link, callback) {

    // stringify the crud role
    var stringifiedCrudRole = link.session.crudRole.toString()
      , crudRoleInCache = CrudRoleCache[stringifiedCrudRole]
      ;

    // the crud role already is in cache
    if (crudRoleInCache) {
        return callback (null, crudRoleInCache);
    }

    // create the crud object
    var crudObject = {
        templateId: "000000000000000000000002"
      , query: {
          _id: stringifiedCrudRole
        }
      , role: link.session.crudRole
      , session: link.session
    };

    // find the items via crud
    M.emit("crud.read", crudObject, function (err, crudRoleObject) {

        // handle error
        if (err) {
            return callback (err);
        }

        // convert cursor to array
        crudRoleObject.toArray(function (err, items) {

            // handle error
            if (err) {
                return callback (err);
            }

            // handle error
            if (!items || !items.length) {
                return callback ("No crud role found with this id.");
            }

            // get the first element from array
            crudRoleObject = items[0];

            // save the new crud role in cache
            CrudRoleCache[stringifiedCrudRole] = crudRoleObject;

            // callback
            callback (null, crudRoleObject);
        });
    });
}
<|endoftext|>


<commit_before>// @flow

/* eslint-disable no-console */

import path from 'path';
import { green } from 'chalk';
import inquirer from 'inquirer';
import createConfig from '../createConfig';
import { fileExists } from '../util/fs';
import { printErrors } from '../printErrors';

import typeof Yargs from 'yargs';
import type { BaseArgs } from './index';

const name = 'init';
const description = 'Creates a .amazeeio.yml config in the current working directory';

export async function setup(yargs: Yargs): Promise<Object> {
  return yargs.usage(`$0 ${name} - ${description}`).options({
    overwrite: { describe: 'Overwrite the configuration file if it exists', default: false },
    sitegroup: { describe: 'Name of sitegroup to configure', type: 'string', alias: 's' },
  }).argv;
}

type Args = BaseArgs & {
  overwrite: ?boolean,
  sitegroup: ?string,
};

export async function run({
  cwd,
  overwrite: overwriteOption,
  sitegroup,
  clog = console.log,
}: Args): Promise<number> {
  const filepath = path.join(cwd, '.amazeeio.yml');

  const exists = await fileExists(filepath);

  if (!overwriteOption && exists) {
    const { overwrite } = await inquirer.prompt([
      {
        type: 'confirm',
        name: 'overwrite',
        message: `File '${filepath}' already exists! Overwrite?`,
        default: false,
      },
    ]);
    if (!overwrite) return printErrors(clog, `Not overwriting existing file '${filepath}'.`);
  }

  const configInput = sitegroup
    ? { sitegroup }
    : await inquirer.prompt([
      {
        type: 'input',
        name: 'sitegroup',
        message: 'Enter the name of the sitegroup to configure.',
        validate: input => (input ? Boolean(input) : 'Please enter a sitegroup.'),
      },
    ]);

  try {
    clog(`Creating file '${filepath}'...`);
    await createConfig(filepath, configInput);
    clog(green('Configuration file created!'));
  } catch (e) {
    return printErrors(clog, `Error occurred while writing to ${filepath}:`, e);
  }

  return 0;
}

export default {
  setup,
  name,
  description,
  run,
};
<commit_msg>Handle `--overwrite false` option (also for tests)<commit_after>// @flow

/* eslint-disable no-console */

import path from 'path';
import { green } from 'chalk';
import R from 'ramda';
import inquirer from 'inquirer';
import createConfig from '../createConfig';
import { fileExists } from '../util/fs';
import { printErrors } from '../printErrors';

import typeof Yargs from 'yargs';
import type { BaseArgs } from './index';

const name = 'init';
const description =
  'Creates a .amazeeio.yml config in the current working directory';

type GetOverwriteOptionArgs = {
  exists: boolean,
  filepath: string,
  overwriteOption?: boolean,
};

const getOverwriteOption = async (
  args: GetOverwriteOptionArgs,
): Promise<boolean> =>
  R.cond([
    // If the file doesn't exist, the file doesn't need to be overwritten
    [R.propEq('exists', false), R.F],
    // If the overwrite option for the command has been specified, use the value of that
    [
      R.propSatisfies(
        // Option is not null or undefined
        overwriteOption => overwriteOption != null,
        'overwriteOption',
      ),
      R.prop('overwriteOption'),
    ],
    // If none of the previous conditions have been satisfied, ask the user if they want to overwrite the file
    [
      R.T,
      async ({ filepath }) => {
        const { overwrite } = await inquirer.prompt([
          {
            type: 'confirm',
            name: 'overwrite',
            message: `File '${filepath}' already exists! Overwrite?`,
            default: false,
          },
        ]);
        return overwrite;
      },
    ],
  ])(args);

export async function setup(yargs: Yargs): Promise<Object> {
  return yargs.usage(`$0 ${name} - ${description}`).options({
    overwrite: {
      describe: 'Overwrite the configuration file if it exists',
      type: 'boolean',
    },
    sitegroup: {
      describe: 'Name of sitegroup to configure',
      type: 'string',
      alias: 's',
    },
  }).argv;
}

type Args = BaseArgs & {
  overwrite: ?boolean,
  sitegroup: ?string,
};

export async function run({
  cwd,
  overwrite: overwriteOption,
  sitegroup,
  clog = console.log,
}: Args): Promise<number> {
  const filepath = path.join(cwd, '.amazeeio.yml');

  const exists = await fileExists(filepath);

  const overwrite = await getOverwriteOption({
    exists,
    filepath,
    overwriteOption,
  });

  if (exists && !overwrite) {
    return printErrors(clog, `Not overwriting existing file '${filepath}'.`);
  }

  const configInput = sitegroup
    ? { sitegroup }
    : await inquirer.prompt([
      {
        type: 'input',
        name: 'sitegroup',
        message: 'Enter the name of the sitegroup to configure.',
        validate: input =>
            input ? Boolean(input) : 'Please enter a sitegroup.',
      },
    ]);

  try {
    clog(`Creating file '${filepath}'...`);
    await createConfig(filepath, configInput);
    clog(green('Configuration file created!'));
  } catch (e) {
    return printErrors(clog, `Error occurred while writing to ${filepath}:`, e);
  }

  return 0;
}

export default {
  setup,
  name,
  description,
  run,
};
<|endoftext|>


<commit_before>/*
 * AOS (Animate on scroll ) - wowjs alternative
 * made to animate elements on scroll
 */

;(function(window, document, undefined) {

  /**
   * Private variables
   */
  var $aosElements = null;
  var windowHeight = 0;
  var aosElementsPositions = [];
  var scrollTop = 0;

  /**
   * Default options
   */
  var options = {
    /*
     * Lonely offset
     * Mayby one day there he'll find some friends
     */
    offset: 120
  };

  /**
   * Scroll logic
   * and all that funny things
   * are right here
   */
  var handleScroll = function(){
    scrollTop = $(window).scrollTop();

    $.each(aosElementsPositions, function(i, elPos) {
      if (scrollTop >= elPos - windowHeight) {
        $aosElements.eq(i).addClass('aos-animate');
      } else {
        $aosElements.eq(i).removeClass('aos-animate');
      }
    });
  };

  /**
   * And maybe here as well
   */
  var init = function(settings){
    /* Looking for some guest */
    $aosElements = $('[aos]');
    windowHeight = $(window).height();
    /* Clearing area to make place for some chicks */
    aosElementsPositions = [];

    /*
     * Merge user settings with default settings
     */
    options = $.extend({}, options, settings);

    /* Invite everyone */
    $aosElements.addClass('aos-init').each(function(i, el){
      /* Yeah, dancefloor isn't empty now! */
      var elementOffsetTop = $(el).offset().top;
      var offset = options.offset;
      var extraOffset = $(el).attr('aos-offset');

      if (extraOffset && !isNaN(extraOffset)) {
        offset = parseInt(extraOffset);
      }

      aosElementsPositions.push(elementOffsetTop + offset);
    });

    /**
     * Start the real party
     * PARTY HARD
     */
    handleScroll();

    /*
     * Let them keep dancing, they're having fun
     * seriously
     */
    $(window).on('scroll', _debounce(handleScroll, 15, true));

  };

  /**
   * Public API
   */
  var AOS = {
    init: init
  };

  /**
   * Expose AOS as a global
   * or requre.js module
   */
  if(typeof define === 'function' && define.amd) {
    define([], function () {
      return AOS;
    });
  } else if (typeof module !== 'undefined' && module.exports) {
    module.exports = AOS;
  } else {
    window.AOS = AOS;
  }

  /*
   * Underscore helpers
   * Don't touch it
   */
  var _now = Date.now || function() {
      return new Date().getTime();
  };
  var _debounce = function(func, wait, immediate) {
      var timeout, args, context, timestamp, result;

      var later = function() {
        var last = _now() - timestamp;

        if (last < wait && last > 0) {
          timeout = setTimeout(later, wait - last);
        } else {
          timeout = null;
          if (!immediate) {
            result = func.apply(context, args);
            if (!timeout) context = args = null;
          }
        }
      };

      return function() {
        context = this;
        args = arguments;
        timestamp = _now();
        var callNow = immediate && !timeout;
        if (!timeout) timeout = setTimeout(later, wait);
        if (callNow) {
          result = func.apply(context, args);
          context = args = null;
        }

        return result;
      };
  };

})(window, document);<commit_msg>Added TODO list with new features<commit_after>/*
 * AOS (Animate on scroll) - wowjs alternative
 * made to animate elements on scroll in both directions
 *
 * TODO:
 * - add anchor option to elements,
 *   (as optional attribute)
 *   to check offset of anchor element
 *   instead of actual element, to trigger animation
 * - add easing customization
 *   (as global setting and as optional attribute on element)
 * - add delay customization
 *   (as global setting and as optional attribute on element)
 */

;(function(window, document, undefined) {

  /**
   * Private variables
   */
  var $aosElements = null;
  var windowHeight = 0;
  var aosElementsPositions = [];
  var scrollTop = 0;

  /**
   * Default options
   */
  var options = {
    /*
     * Lonely offset
     * Mayby one day there he'll find some friends
     */
    offset: 120
  };

  /**
   * Scroll logic
   * and all that funny things
   * are right here
   */
  var handleScroll = function(){
    scrollTop = $(window).scrollTop();

    $.each(aosElementsPositions, function(i, elPos) {
      if (scrollTop >= elPos - windowHeight) {
        $aosElements.eq(i).addClass('aos-animate');
      } else {
        $aosElements.eq(i).removeClass('aos-animate');
      }
    });
  };

  /**
   * And maybe here as well
   */
  var init = function(settings){
    /* Looking for some guest */
    $aosElements = $('[aos]');
    windowHeight = $(window).height();
    /* Clearing area to make place for some chicks */
    aosElementsPositions = [];

    /*
     * Merge user settings with default settings
     */
    options = $.extend({}, options, settings);

    /* Invite everyone */
    $aosElements.addClass('aos-init').each(function(i, el){
      /* Yeah, dancefloor isn't empty now! */
      var elementOffsetTop = $(el).offset().top;
      var offset = options.offset;
      var extraOffset = $(el).attr('aos-offset');

      if (extraOffset && !isNaN(extraOffset)) {
        offset = parseInt(extraOffset);
      }

      aosElementsPositions.push(elementOffsetTop + offset);
    });

    /**
     * Start the real party
     * PARTY HARD
     */
    handleScroll();

    /*
     * Let them keep dancing, they're having fun
     * seriously
     */
    $(window).on('scroll', _debounce(handleScroll, 15, true));

  };

  /**
   * Public API
   */
  var AOS = {
    init: init
  };

  /**
   * Expose AOS as a global
   * or requre.js module
   */
  if(typeof define === 'function' && define.amd) {
    define([], function () {
      return AOS;
    });
  } else if (typeof module !== 'undefined' && module.exports) {
    module.exports = AOS;
  } else {
    window.AOS = AOS;
  }

  /*
   * Underscore helpers
   * Don't touch it
   */
  var _now = Date.now || function() {
      return new Date().getTime();
  };
  var _debounce = function(func, wait, immediate) {
      var timeout, args, context, timestamp, result;

      var later = function() {
        var last = _now() - timestamp;

        if (last < wait && last > 0) {
          timeout = setTimeout(later, wait - last);
        } else {
          timeout = null;
          if (!immediate) {
            result = func.apply(context, args);
            if (!timeout) context = args = null;
          }
        }
      };

      return function() {
        context = this;
        args = arguments;
        timestamp = _now();
        var callNow = immediate && !timeout;
        if (!timeout) timeout = setTimeout(later, wait);
        if (callNow) {
          result = func.apply(context, args);
          context = args = null;
        }

        return result;
      };
  };

})(window, document);<|endoftext|>


<commit_before>export const EVENTS = [
  {
    link: "/events/february-2022-kattis-competition",
    title: "Kattis Competition",
    dates: [
      {
        time: new Date(2022, 1, 11),
        title: "Pre-Comp. Info Session @ 5pm",
      },
      {
        time: new Date(2022, 1, 11),
        title: "Begins @ 6pm",
      },
      {
        time: new Date(2022, 1, 11),
        title: "Ends @ 10pm",
      },
    ],
  },
  {
    link: "/events/february-2022-picoCAD-competition",
    title: "picoCAD Competition",
    dates: [
      {
        time: new Date(2022, 1, 19),
        title: "Competition Begins",
      },
      {
        time: new Date(2022, 1, 19),
        title: "Competition Ends",
      },
    ],
  },
  {
    link: "/events/february-2022-gmod-prop-hunt",
    title: "Garry's Mod Prop Hunt Night",
    dates: [
      {
        time: new Date(2022, 1, 25),
        title: "Begins @ 7pm",
      },
    ],
  },
  {
    link: "/events/january-2022-xonotic",
    title: "Xonotic Night",
    dates: [
      {
        time: new Date(2022, 0, 13),
        title: "Xonotic Night",
      },
    ],
  },
  {
    link: "/events/hacktoberfest-2021",
    title: "Hacktoberfest 2021",
    dates: [
      {
        time: new Date(2021, 9, 1),
        title: "Hacktoberfest Begins",
      },
      {
        time: new Date(2021, 9, 28),
        title: "Workshop",
      },
      {
        time: new Date(2021, 9, 31),
        title: "Hacktoberfest Ends",
      },
    ],
  },
  {
    link: "/events/fall-2021-clothing",
    title: "Fall 2021 Clothing Order",
    dates: [
      {
        time: new Date(2021, 8, 24),
        title: "Clothing Order Available",
      },
      {
        time: new Date(2021, 9, 11),
        title: "Clothing Order Availability Ends",
      },
    ],
  },
  {
    link: "/events/fall-2021-election",
    title: "Fall 2021 Election",
    dates: [
      {
        time: new Date(2021, 8, 20),
        title: "Applications Open",
      },
      {
        time: new Date(2021, 8, 27),
        title: "Applications Close",
      },
      {
        time: new Date(2021, 8, 30),
        title: "Campaigning Starts",
      },
      {
        time: new Date(2021, 9, 5),
        title: "Campaigning Ends",
      },
      {
        time: new Date(2021, 9, 6),
        title: "Results posted",
      },
    ],
  },
  {
    link: "/events/fall-2021-info-session",
    title: "Info Session",
    dates: [
      {
        time: new Date(2021, 8, 27),
        title: "Info Session in EN2007",
      },
    ],
  },
];
<commit_msg>fix end date for picoCAD comp<commit_after>export const EVENTS = [
  {
    link: "/events/february-2022-kattis-competition",
    title: "Kattis Competition",
    dates: [
      {
        time: new Date(2022, 1, 11),
        title: "Pre-Comp. Info Session @ 5pm",
      },
      {
        time: new Date(2022, 1, 11),
        title: "Begins @ 6pm",
      },
      {
        time: new Date(2022, 1, 11),
        title: "Ends @ 10pm",
      },
    ],
  },
  {
    link: "/events/february-2022-picoCAD-competition",
    title: "picoCAD Competition",
    dates: [
      {
        time: new Date(2022, 1, 19),
        title: "Competition Begins",
      },
      {
        time: new Date(2022, 1, 27),
        title: "Competition Ends",
      },
    ],
  },
  {
    link: "/events/february-2022-gmod-prop-hunt",
    title: "Garry's Mod Prop Hunt Night",
    dates: [
      {
        time: new Date(2022, 1, 25),
        title: "Begins @ 7pm",
      },
    ],
  },
  {
    link: "/events/january-2022-xonotic",
    title: "Xonotic Night",
    dates: [
      {
        time: new Date(2022, 0, 13),
        title: "Xonotic Night",
      },
    ],
  },
  {
    link: "/events/hacktoberfest-2021",
    title: "Hacktoberfest 2021",
    dates: [
      {
        time: new Date(2021, 9, 1),
        title: "Hacktoberfest Begins",
      },
      {
        time: new Date(2021, 9, 28),
        title: "Workshop",
      },
      {
        time: new Date(2021, 9, 31),
        title: "Hacktoberfest Ends",
      },
    ],
  },
  {
    link: "/events/fall-2021-clothing",
    title: "Fall 2021 Clothing Order",
    dates: [
      {
        time: new Date(2021, 8, 24),
        title: "Clothing Order Available",
      },
      {
        time: new Date(2021, 9, 11),
        title: "Clothing Order Availability Ends",
      },
    ],
  },
  {
    link: "/events/fall-2021-election",
    title: "Fall 2021 Election",
    dates: [
      {
        time: new Date(2021, 8, 20),
        title: "Applications Open",
      },
      {
        time: new Date(2021, 8, 27),
        title: "Applications Close",
      },
      {
        time: new Date(2021, 8, 30),
        title: "Campaigning Starts",
      },
      {
        time: new Date(2021, 9, 5),
        title: "Campaigning Ends",
      },
      {
        time: new Date(2021, 9, 6),
        title: "Results posted",
      },
    ],
  },
  {
    link: "/events/fall-2021-info-session",
    title: "Info Session",
    dates: [
      {
        time: new Date(2021, 8, 27),
        title: "Info Session in EN2007",
      },
    ],
  },
];
<|endoftext|>


<commit_before>var win2 = Titanium.UI.currentWindow;
var _name = '';
var _koef = 0;
var _jmbg = '';

// odredi platformu...
var isAndroid = Ti.Platform.osname == 'android';

var db = Titanium.Database.open('bringout');
db.execute('CREATE TABLE IF NOT EXISTS bringout (id INTEGER PRIMARY KEY, name TEXT, jmbg TEXT, koef INT)');

//create data entry view
var pregled = Ti.UI.createView({
  backgroundColor:'#0060AA',
  width:'100%',
  height:100,
  top:0
});

var kontrola = Ti.UI.createView({
  width:470,
  height:'auto'
});

var btnSnimi = Titanium.UI.createButton({
	title:'Snimi',
	width:180,
	height:60,
	right:20,
	top:5,
	color:'white',
	backgroundColor:'black',
	borderRadius:10,
	borderColor:'white',
	borderWidth:2,
	enabled:false
});
kontrola.add(btnSnimi);

var tf_name = Titanium.UI.createTextField({
	width:250,
	height:60,
	left:0,
	top:5,
	font:{fontSize:20,fontFamily:'Helvetica Neue'},
	//borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED,
	autocorrect:false,
	hintText:'naziv...'
});

var tf_jmbg = Titanium.UI.createTextField({
	width:250,
	height:60,
	left:0,
	top:70,
	font:{fontSize:20,fontFamily:'Helvetica Neue'},
	//borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED,
	autocorrect:false,
	hintText:'jmbg...'
});

var tf_koef = Titanium.UI.createTextField({
	width:100,
	height:60,
	right:100,
	top:70,
	font:{fontSize:20,fontFamily:'Helvetica Neue'},
	//borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED,
	autocorrect:false,
	hintText:'koef...'
});

tf_name.addEventListener('return', function() {
	tf_name.blur();
});

tf_jmbg.addEventListener('return', function() {
	tf_jmbg.blur();
});

tf_koef.addEventListener('return', function() {
	tf_koef.blur();
});

tf_koef.addEventListener('click', function() {

	if (isAndroid) {
		koef_dlg.androidView = null;
	}
	tf_koef.blur();
	koef_dlg.show();
});

tf_name.addEventListener("change", function(e) {
  _name = e.value;
  if (_name == '') {
    btnSnimi.enabled = false;
  }
  else {
    btnSnimi.enabled = true;
  }
});

tf_jmbg.addEventListener("change", function(e) {
  _jmbg = e.value;
});

tf_koef.addEventListener("change", function(e) {
  _koef = e.value;
});

kontrola.add(tf_name);
kontrola.add(tf_jmbg);
kontrola.add(tf_koef);

pregled.add(kontrola);
win2.add(kontrola);

// koeficijent dijalog
var koef_dlg_opt = {
	options:['0.5', '1', '1.5', '2', '2.2', '2.3', '2.4', '5', '7'],
	destructive:1,
	cancel:2,
	title:'odabir koeficijenta'
};

var koef_dlg = Titanium.UI.createOptionDialog(koef_dlg_opt);

// add event listener
koef_dlg.addEventListener('click',function(e)
{
	// setuj vrijednost u text field koeficijent
	tf_koef.value = koef_dlg_opt.options[e.index];

});

// funkcija za refresh baze...
// učitava sve zapise sql tabele
function refresh_data( oDb ){

	var aData = [];
	var rows = oDb.execute('SELECT * FROM bringout');
	while (rows.isValidRow()) {
  		aData.push({
  			title: rows.fieldByName('name'), hasChild:true,
  			id: rows.fieldByName('id'),
  			jmbg: rows.fieldByName('jmbg'),
  			koef: rows.fieldByName('koef'),
  			color:'green'
  			});

		rows.next();
	};
rows.close();

return aData;
};

var pregled_tabele = Titanium.UI.createTableView({
	// odmah pri pokretanju tableview komponente učitaj stanje sql tabele
	data:refresh_data( db ),
	headerTitle:'pregled tabele',
	allowsSelection:true,
	top:170
});

pregled_tabele.addEventListener('click', function(e) {
	alert('Trenutni zapis: ' + e.rowData.id + ' - ' + e.rowData.title + ' - ' + e.rowData.jmbg + ' - ' + e.rowData.koef);
});

Titanium.UI.currentWindow.add(pregled_tabele);

btnSnimi.addEventListener("click", function(e) {
  if (btnSnimi.enabled) {
    db.execute('INSERT INTO bringout (name, jmbg, koef) VALUES(?,?,?)', _name, _jmbg, _koef );
    pregled_tabele.setData( refresh_data( db ) );

    _naziv = "";
    _jmbg = "";
    _koef = "";

    tf_name.value = "";
    tf_name.blur();

    tf_koef.value = "";
    tf_koef.blur();

    tf_jmbg.value = "";
    tf_jmbg.blur();

    btnSnimi.enabled = false;
  }
});

<commit_msg>prilagodjavanje za htc bravo, android emulator 800<commit_after>var win2 = Titanium.UI.currentWindow;
var _name = '';
var _koef = 0;
var _jmbg = '';

// odredi platformu...
var isAndroid = Ti.Platform.osname == 'android';

var db = Titanium.Database.open('bringout');
db.execute('CREATE TABLE IF NOT EXISTS bringout (id INTEGER PRIMARY KEY, name TEXT, jmbg TEXT, koef INT)');

//create data entry view
var pregled = Ti.UI.createView({
  backgroundColor:'#0060AA',
  width:'100%',
  height:100,
  top:0
});

var kontrola = Ti.UI.createView({
  width:470,
  height:'auto'
});

var btnSnimi = Titanium.UI.createButton({
	title:'Snimi',
	width:180,
	height:60,
	right:20,
	top:5,
	color:'white',
	backgroundColor:'black',
	borderRadius:10,
	borderColor:'white',
	borderWidth:2,
	enabled:false
});
kontrola.add(btnSnimi);

var tf_name = Titanium.UI.createTextField({
	width:250,
	height:60,
	left:0,
	top:5,
	font:{fontSize:20,fontFamily:'Helvetica Neue'},
	//borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED,
	autocorrect:false,
	hintText:'naziv...'
});

var tf_jmbg = Titanium.UI.createTextField({
	width:250,
	height:60,
	left:0,
	top:70,
	font:{fontSize:20,fontFamily:'Helvetica Neue'},
	//borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED,
	autocorrect:false,
	hintText:'jmbg...'
});

var tf_koef = Titanium.UI.createTextField({
	width:100,
	height:60,
	right:100,
	top:70,
	font:{fontSize:20,fontFamily:'Helvetica Neue'},
	//borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED,
	autocorrect:false,
	hintText:'koef...'
});

tf_name.addEventListener('return', function() {
	tf_name.blur();
});

tf_jmbg.addEventListener('return', function() {
	tf_jmbg.blur();
});

tf_koef.addEventListener('return', function() {
	tf_koef.blur();
});

tf_koef.addEventListener('click', function() {

	if (isAndroid) {
		koef_dlg.androidView = null;
	}
	tf_koef.blur();
	koef_dlg.show();
});

tf_name.addEventListener("change", function(e) {
  _name = e.value;
  if (_name == '') {
    btnSnimi.enabled = false;
  }
  else {
    btnSnimi.enabled = true;
  }
});

tf_jmbg.addEventListener("change", function(e) {
  _jmbg = e.value;
});

tf_koef.addEventListener("change", function(e) {
  _koef = e.value;
});

kontrola.add(tf_name);
kontrola.add(tf_jmbg);
kontrola.add(tf_koef);

pregled.add(kontrola);
win2.add(kontrola);

// koeficijent dijalog
var koef_dlg_opt = {
	options:['0.5', '1', '1.5', '2', '2.2', '2.3', '2.4', '5', '7'],
	destructive:1,
	cancel:2,
	title:'odabir koeficijenta'
};

var koef_dlg = Titanium.UI.createOptionDialog(koef_dlg_opt);

// add event listener
koef_dlg.addEventListener('click',function(e)
{
	// setuj vrijednost u text field koeficijent
	tf_koef.value = koef_dlg_opt.options[e.index];

});

// funkcija za refresh baze...
// učitava sve zapise sql tabele
function refresh_data( oDb ){

	var aData = [];
	var rows = oDb.execute('SELECT * FROM bringout');
	while (rows.isValidRow()) {
  		aData.push({
  			title: rows.fieldByName('name'), hasChild:true,
  			id: rows.fieldByName('id'),
  			jmbg: rows.fieldByName('jmbg'),
  			koef: rows.fieldByName('koef'),
  			color:'green'
  			});

		rows.next();
	};
rows.close();

return aData;
};

var pregled_tabele = Titanium.UI.createTableView({
	// odmah pri pokretanju tableview komponente učitaj stanje sql tabele
	data:refresh_data( db ),
	headerTitle:'pregled tabele',
	allowsSelection:true,
	top:170
});

pregled_tabele.addEventListener('click', function(e) {
	alert('Trenutni zapis: ' + e.rowData.id + ' - ' + e.rowData.title + ' - ' + e.rowData.jmbg + ' - ' + e.rowData.koef);
});

Titanium.UI.currentWindow.add(pregled_tabele);

btnSnimi.addEventListener("click", function(e) {
  if (btnSnimi.enabled) {
    db.execute('INSERT INTO bringout (name, jmbg, koef) VALUES(?,?,?)', _name, _jmbg, _koef );
    pregled_tabele.setData( refresh_data( db ) );

    _naziv = "";
    _jmbg = "";
    _koef = "";

    tf_name.value = "";
    tf_name.blur();

    tf_koef.value = "";
    tf_koef.blur();

    tf_jmbg.value = "";
    tf_jmbg.blur();

    btnSnimi.enabled = false;
  }
});

<|endoftext|>


<commit_before>
  .config(function ($stateProvider, $urlRouterProvider) {
    $stateProvider
      .state('home', {
        url: "/",
        templateUrl: 'partials/main.html',
        controller: 'MainCtrl'
      });

    $urlRouterProvider.otherwise('/');
  })
<commit_msg>Fix singlequote in template<commit_after>
  .config(function ($stateProvider, $urlRouterProvider) {
    $stateProvider
      .state('home', {
        url: '/',
        templateUrl: 'partials/main.html',
        controller: 'MainCtrl'
      });

    $urlRouterProvider.otherwise('/');
  })
<|endoftext|>


<commit_before>'use strict'

import React, {
  Component,
  DatePickerAndroid,
  Image,
  StyleSheet,
  Switch,
  Text,
  TextInput,
  TouchableWithoutFeedback,
  TimePickerAndroid,
  View
} from 'react-native';

import Button from '../components/button';
import Header from '../components/header';

import ButtonStyles from '../styles/button-styles';

class CreateEvent extends Component {

  constructor(props) {
    super(props);
    this.state = {
      loaded: true,

      title: '',
      publicEvent: true,
      dateStart: 'pick a start date',
      dateEnd: 'pick an end date',
      timeStart: 'pick a start time',
      timeEnd: 'pick an end time',
      description: ''
    }
  }

  async showDatePicker(stateKey, options, start) {
    try {
      var newState = {};
      var tempDate = new Date();
      var tempDateStr = tempDate.toLocaleDateString();
      const {action, year, month, day} = await DatePickerAndroid.open(options);

      if (action === DatePickerAndroid.dismissedAction) {
        if(start) {
          tempDateStr = this.state.dateStart;
        } else {
          tempDateStr = this.state.dateEnd;
        }
      } else {
        tempDate = new Date(year, month, day);
        tempDateStr = tempDate.toLocaleDateString();
      }
      if(start) {
        this.setState({dateStart: tempDateStr});
      } else {
        this.setState({dateEnd: tempDateStr});
      }
    } catch ({code, message}) {
      console.warn(`Error in example '${stateKey}': `, message);
    }
  }

  async showTimePicker(stateKey, start) {
    var tempMin, tempHour;
    try {
      const {action, minute, hour} = await TimePickerAndroid.open();
      tempMin = minute;
      tempHour = hour;
      var tempTimeStr = '';

      if (action === TimePickerAndroid.dismissedAction) {
        if(start) {
          tempTimeStr = this.state.timeStart;
        } else {
          tempTimeStr = this.state.timeEnd;
        }
      } else if(action === TimePickerAndroid.timeSetAction){
        tempTimeStr = this.formatTime(hour, minute);

      }
      if(start) {
        this.setState({timeStart: tempTimeStr});
      } else {
        this.setState({timeEnd: tempTimeStr});
      }
    } catch ({code, message}) {
      console.warn(`Error in example '${stateKey}': `, message);
    }
  }

  formatTime(hour, minute) {
    return hour + ':' + (minute < 10 ? '0' + minute : minute);
  }

  render(){
    return(
      <View style = {{flex: 1}}>
        {this.renderPageTitle()}
        {this.renderToggle()}
        {this.renderTitleInput()}
        {this.renderDateTimeInput()}
        {this.renderDescriptionInput()}
        {this.renderButtons()}
      </View>
    );
  }

  renderPageTitle(){
    return(
      <Header
        navigator = {this.props.navigator}
        text = "Create a New Event"
        hasBack = {true}
      />
    );
  }

  renderToggle(){
    return(
      <View style = {{flexDirection:'row'}}>
        <Switch
          onTintColor = "#0000ff"
          onValueChange = {(value) => this.setState({publicEvent: value})}
          style = {{marginBottom: 10}}
          value = {this.state.publicEvent}
        />
        <Text>
          {this.state.publicEvent ? ' Public Event' : 'Private Event'}
        </Text>
      </View>
    );
  }

  renderTitleInput(){
    return(
      <TextInput
        blurOnSubmit = {true}
        onChangeText = {(text) => this.setState({title: text})}
        value = {this.state.title}
        placeholder = {"Give Your Event a Title."}
        placeholderTextColor = 'black'
        underlineColorAndroid = 'black'
      />
    );
  }

  renderDateTimeInput(){
    return (
      <View>

        <Text style = {{color:'white'}}>
          Start:
        </Text>

        <View style = {{ flexDirection:'row'}}>
          <TouchableWithoutFeedback onPress = {
            this.showDatePicker.bind(this, 'min', {
              date: this.state.minDate,
              minDate: new Date(),
            }, true)
          }>
            <Text style = {{color:'black'}}>
              {this.state.dateStart}
            </Text>
          </TouchableWithoutFeedback>

          <TouchableWithoutFeedback
            onPress = {this.showTimePicker.bind(this, true)}>
            <Text style = {{color:'black'}}>{this.state.timeStart}</Text>
          </TouchableWithoutFeedback>

        </View>

        <Text style = {{color:'white'}}>
          End:
        </Text>
        <View style = {{ flexDirection:'row'}}>
          <View style = {{ flexDirection:'row'}}>
            <TouchableWithoutFeedback onPress = {
              this.showDatePicker.bind(this, 'min', {
                date: this.state.minDate,
                minDate: new Date(this.state.dateStart),
              }, false )
            }>
              <Text style = {{color:'black'}}>
                {this.state.dateEnd}
              </Text>
            </TouchableWithoutFeedback>
          </View>
        </View>
      </View>
    );
  }

  renderDescriptionInput(){
    var limit = 100;
    var remainder = limit - this.state.description.length;
    var remainderColor = remainder > 5 ? 'blue' : 'red';

    return (
      <View>
        <TextInput
          maxLength = {limit}
          multiline = {true}
          style = {Header.body, {color:'black'}}
          onChangeText = {(text) => this.setState({description: text})}
          value = {this.state.description}
          placeholder = {"Leave a short description of your event for your guests:"}
          placeholderTextColor = 'black'
          underlineColorAndroid = 'black'
        />
        <Text style = {{color: remainderColor}}>
          {remainder}
        </Text>
      </View>
    );
  }

  renderButtons(){
    return (
      <View style = {{alignItems: 'center'}}>
        <Button
          text = "Invite Friends!"
          onPress = {this.createGuestList.bind(this)}
          button_styles = {ButtonStyles.primary_button}
          button_text_styles = {ButtonStyles.primary_button_text}
        />

        <Button
          text = "Create Event!"
          onPress = {this.createEvent.bind(this)}
          button_styles = {ButtonStyles.primary_button}
          button_text_styles = {ButtonStyles.primary_button_text}
        />

      <Button
        text = "Clear"
        onPress = {this.clearEvent.bind(this)}
        button_styles = {ButtonStyles.primary_button}
        button_text_styles = {ButtonStyles.primary_button_text}
      />

    </View>
    );
  }

  createGuestList(){
    alert('friends list unimplemented')
  }

  createEvent(){

    alert(this.state.title)
    alert('this event is a public event: ' + this.state.publicEvent);
    alert('start: ' + this.state.dateStart + ' end: ' + this.state.dateEnd);
    alert(this.state.description);
  }

  clearEvent(){
    alert('Cleared :(');
    this.setState({
      title: '',
      publicEvent: true,
      dateStart: 'pick a start date',
      dateEnd: 'pick an end date',
      timeStart: 'pick a start time',
      timeEnd: 'pick an end time',
      description: ''
    })

  }
}

module.exports = CreateEvent;
<commit_msg>added time functionality, color changing inputs, minor bug fixes<commit_after>'use strict'

import React, {
  Component,
  DatePickerAndroid,
  Image,
  StyleSheet,
  Switch,
  Text,
  TextInput,
  TouchableWithoutFeedback,
  TimePickerAndroid,
  View
} from 'react-native';

import Button from '../components/button';
import Header from '../components/header';

import ButtonStyles from '../styles/button-styles';

var dateStartStr = 'pick a start date';
var dateEndStr = 'pick an end date';
var timeStartStr = 'pick a start time';
var timeEndStr = 'pick an end time';
class CreateEvent extends Component {

  constructor(props) {
    super(props);
    this.state = {
      title: '',
      publicEvent: true,
      dateStart: dateStartStr,
      dateEnd: dateEndStr,
      timeStart: timeStartStr,
      timeEnd: timeEndStr,
      description: ''
    }
  }

  async showDatePicker(stateKey, options, start) {
    try {
      var newState = {};
      var tempDate = new Date();
      var tempDateStr = tempDate.toLocaleDateString();
      const {action, year, month, day} = await DatePickerAndroid.open(options);

      if (action === DatePickerAndroid.dismissedAction) {
        if(start) {
          tempDateStr = this.state.dateStart;
        } else {
          tempDateStr = this.state.dateEnd;
        }
      } else {
        tempDate = new Date(year, month, day);
        tempDateStr = tempDate.toLocaleDateString();
      }
      if(start) {
        this.setState({dateStart: tempDateStr});
      } else {
        this.setState({dateEnd: tempDateStr});
      }
    } catch ({code, message}) {
      console.warn(`Error in example '${stateKey}': `, message);
    }
  }

  async showTimePicker(stateKey, start) {

    var tempMin, tempHour;
    try {
      const {action, minute, hour} = await TimePickerAndroid.open();
      tempMin = minute;
      tempHour = hour;
      var tempTimeStr = '';
      if (action === TimePickerAndroid.dismissedAction) {
        if(start) {
          tempTimeStr = this.state.timeStart;
        } else {
          tempTimeStr = this.state.timeEnd;
        }
      } else if(action === TimePickerAndroid.timeSetAction){
        tempTimeStr = this.formatTime(hour, minute);

      }
      if(start) {
        this.setState({timeStart: tempTimeStr});
      } else {
        this.setState({timeEnd: tempTimeStr});
      }
    } catch ({code, message}) {
      console.warn(`Error in example '${stateKey}': `, message);
    }
  }

  formatTime(hour, minute) {
    var str = '';
    var hStr = '';
    var mStr = '';
    var isAM = false;

    if(hour == 0){
      hStr = 12;
    }
    else if(hour > 12){
      hStr = hour-12;
    }
    else{
      hStr = hour;
    }
    if( hour < 12 && hour >= 0 ){
      isAM = true;
    }
    return hStr + ':' + (minute < 10 ? '0' + minute : minute) + (isAM ? ' am' : ' pm');
  }

  render(){
    return(
      <View style = {{flex: 1}}>
        {this.renderPageTitle()}
        {this.renderToggle()}
        {this.renderTitleInput()}
        {this.renderDateTimeInput()}
        {this.renderDescriptionInput()}
        {this.renderButtons()}
      </View>
    );
  }

  renderPageTitle(){
    return(
      <Header
        navigator = {this.props.navigator}
        text = "Create a New Event"
        hasBack = {true}
      />
    );
  }

  renderToggle(){
    return(
      <View style = {{alignSelf:'flex-end', flexDirection:'column'}}>

        <Switch
          onTintColor = "#0000ff"
          onValueChange = {(value) => this.setState({publicEvent: value})}
          style = {{marginBottom: 10}}
          value = {this.state.publicEvent}
        />
        <Text style={{color:'black'}}>
          {this.state.publicEvent ? ' Public Event' : 'Private Event'}
        </Text>
      </View>
    );
  }

  renderTitleInput(){
    return(
      <TextInput
        blurOnSubmit = {true}
        onChangeText = {(text) => this.setState({title: text})}
        value = {this.state.title}
        placeholder = {"Give Your Event a Title."}
        placeholderTextColor = 'gray'
        underlineColorAndroid = 'black'
      />
    );
  }

  renderDateTimeInput(){
    return (
      <View>
        <View style={{flexDirection:'row', justifyContent:'space-around', alignItems:'center'}}>
          <Text style={{color:'black', textDecorationLine:'underline'}}>
            date
          </Text>
          <Text style={{color:'black', textDecorationLine:'underline'}}>
            time
          </Text>
        </View>
        <Text style = {{color:'black'}}>
          Event Starts:
        </Text>
        <View style = {{borderWidth: 1,          borderColor:'blue',justifyContent:'space-around', flexDirection:'row'}}>
          <TouchableWithoutFeedback onPress = {
            this.showDatePicker.bind(this, 'min', {
              date: this.state.minDate,
              minDate: new Date(),
            }, true)
          }>
            <Text style = { [ {color:'gray'}, this.state.dateStart != dateStartStr && {color:'black'} ] }>
              {this.state.dateStart}
            </Text>
          </TouchableWithoutFeedback>
          <TouchableWithoutFeedback
            onPress = {this.showTimePicker.bind(this, true)}>
            <Text style = { [ {color:'gray'}, this.state.timeStart != timeStartStr && {color:'black'} ] }>
              {this.state.timeStart}
            </Text>
          </TouchableWithoutFeedback>

        </View>
        <Text style = {{color:'black'}}>
          Event Ends:
        </Text>

        <View style = {{borderWidth: 1, borderColor:'blue', justifyContent:'space-around', flexDirection:'row'}}>

          <TouchableWithoutFeedback onPress = {
            this.showDatePicker.bind(this, 'min', {
              date: this.state.minDate,
              minDate: new Date(this.state.dateStart),
            }, false )
          }>
            <Text style = { [ {color:'gray'}, this.state.dateEnd != dateEndStr && {color:'black'} ] }>
              {this.state.dateEnd}
            </Text>
          </TouchableWithoutFeedback>
          <TouchableWithoutFeedback
            onPress = {this.showTimePicker.bind(this)}>
            <Text style = { [ {color:'gray'}, this.state.timeEnd != timeEndStr && {color:'black'} ] }>
              {this.state.timeEnd}
            </Text>
          </TouchableWithoutFeedback>
        </View>
      </View>
    );
  }

  renderDescriptionInput(){
    var limit = 1000;
    var remainder = limit - this.state.description.length;
    var remainderColor = remainder > 5 ? 'blue' : 'red';

    return (
      <View>
        <TextInput
          maxLength = {limit}
          multiline = {true}
          style = {{color:'black'}}
          onChangeText = {(text) => this.setState({description: text})}
          value = {this.state.description}
          placeholder = {"Leave a short description of your event for your guests: (maximum "+limit+" characters.)"}
          placeholderTextColor = 'grey'
          underlineColorAndroid = 'black'
        />
        <Text style = {{color: remainderColor}}>
          remaining: {remainder}
        </Text>
      </View>
    );
  }

  renderButtons(){
    return (
      <View style = {{alignItems: 'center'}}>
        <Button
          text = "Invite Friends!"
          onPress = {this.createGuestList.bind(this)}
          button_styles = {ButtonStyles.primary_button}
          button_text_styles = {ButtonStyles.primary_button_text}
        />

        <Button
          text = "Create Event!"
          onPress = {this.createEvent.bind(this)}
          button_styles = {ButtonStyles.primary_button}
          button_text_styles = {ButtonStyles.primary_button_text}
        />

      <Button
        text = "Clear"
        onPress = {this.clearEvent.bind(this)}
        button_styles = {ButtonStyles.primary_button}
        button_text_styles = {ButtonStyles.primary_button_text}
      />

    </View>
    );
  }

  createGuestList(){
    alert('friends list unimplemented')
  }

  createEvent(){
    alert(
      'title: '+ this.state.title + "\n" +
      (this.state.publicEvent? 'public ':'private') + " event \n" +
      'start date: ' + this.state.dateStart + "\n" +
      'end date: ' + this.state.dateEnd + "\n" +
      'start time: ' + this.state.timeStart + "\n" +
      'end time: ' + this.state.timeEnd + "\n" +
      'description: ' + this.state.description
    );
  }

  clearEvent(){
    alert('Cleared :(');
    this.setState({
      title: '',
      publicEvent: true,
      dateStart: dateStartStr,
      dateEnd: dateEndStr,
      timeStart: timeStartStr,
      timeEnd: timeEndStr,
      description: ''
    })

  }
}

module.exports = CreateEvent;
<|endoftext|>


<commit_before>// Import React
import React from "react";

// Import Spectacle Core tags
import {
  BlockQuote,
  Cite,
  Deck,
  Heading,
  ListItem,
  List,
  Quote,
  Slide,
  Text,
  Image,
  Appear,
  CodePane,
  Fill
} from "spectacle";

// Import image preloader util
import preloader from "spectacle/lib/utils/preloader";

// Import theme
import createTheme from "spectacle/lib/themes/default";

// Require CSS
require("normalize.css");
require("spectacle/lib/themes/default/index.css");

const images = {
  anchorman: require("../assets/anchorman.jpg"),
  reactiveDog: require("../assets/reactive_dog.jpg"),
  starlordConfused: require("../assets/starlord_confused.jpg"),
  nightmare: require("../assets/nightmare.jpg")
};

preloader(images);

const theme = createTheme({
  primary: "white",
  secondary: "#1F2022",
  tertiary: "#03A9FC",
  quartenary: "#CECECE"
}, {
  primary: "Monaco",
  secondary: "Helvetica"
});

export default class Presentation extends React.Component {
  render() {
    return (
      <Deck transition={["zoom", "slide"]} transitionDuration={500} theme={theme}>
        <Slide transition={["zoom"]} bgColor="primary">
          <Heading size={1} fit caps lineHeight={1} textColor="secondary">
            Reactive Programming
          </Heading>
          <Appear>
            <Heading size={6} caps lineHeight={1} textColor="secondary">
              - OR -
            </Heading>
          </Appear>
          <Appear>
            <Image src={images.starlordConfused.replace("/", "")} height="500px" width="500px" display="block" />
          </Appear>
        </Slide>

        <Slide transition={["slide"]} bgColor="secondary">
          <Heading size={6} textColor="primary" caps>What it does by definition...</Heading>
          \n
          <Appear>
            <Text size={6} textColor="primary">
                Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
            </Text>
          </Appear>
        </Slide>

        <Slide transition={["slide"]} bgColor="tertiary">
          <Heading size={4} textColor="primary">Feels like</Heading>
          <Image src={images.anchorman.replace("/", "")} height="500px" width="800px" />
        </Slide>

        <Slide transition={["slide"]} bgColor="secondary">
          <Heading size={4} textColor="primary" caps>Huh?</Heading>
          <List>
            <Appear>
              <ListItem textColor="primary" textSize="1.2em">
                Reactive programming is programming with asynchronous data streams.
              </ListItem>
            </Appear>
            <Appear>
              <ListItem textColor="primary" textSize="1.2em">
                Streams are object pipelines (data/events/objects), which you can observe and react to.
              </ListItem>
            </Appear>
            <Appear>
              <ListItem textColor="primary" textSize="1.2em">
                Streams are observables.
              </ListItem>
            </Appear>
            <Appear>
              <ListItem textColor="primary" textSize="1.2em">
                Observers are methods that implement actions based on the observed stream.
              </ListItem>
            </Appear>
            <Appear>
              <ListItem textColor="primary" textSize="1.2em">
                Streams(Observables) can be created and composed using operators
              </ListItem>
            </Appear>
          </List>
        </Slide>

        <Slide transition={["slide"]} bgColor="tertiary">
          <Heading size={4} textColor="primary" caps>Why?</Heading>
          <List>
            <Appear>
              <ListItem textColor="primary" textSize="1em">
                Managing user events flow is hard
              </ListItem>
            </Appear>
            <Appear>
              <ListItem textColor="primary" textSize="1em">
                Managing broadcast events is harder
              </ListItem>
            </Appear>
            <Appear>
              <ListItem textColor="primary" textSize="1em">
                Managing both is a NIGHTMARE
              </ListItem>
            </Appear>
            <Appear>
              <ListItem textColor="primary" textSize="1em">
                The bad news is you have to handle both
              </ListItem>
            </Appear>
          </List>
          <Appear>
            <Image src={images.nightmare.replace("/", "")} width="400" height="300" />
          </Appear>
        </Slide>

        <Slide transition={["slide"]} bgColor="secondary">
          <Heading size={4} textColor="primary" caps>How?</Heading>
          <List>
            <Appear>
              <ListItem textColor="primary" textSize="1em">
                The fundament of the implementation in reactive programming is the Observer Pattern.
              </ListItem>
            </Appear>
            <Appear>
              <ListItem textColor="primary" textSize="1em">
                The most popular library is Rx. It has multiple language implementations (JS, Python, Java, Scala, C# etc.)
              </ListItem>
            </Appear>
            <Appear>
              <ListItem textColor="primary" textSize="1em">
                RP can be useful both in UI and on the server side as a logical progression in event driven systems
              </ListItem>
            </Appear>
            <Appear>
              <ListItem textColor="primary" textSize="1em">
                These libraries provide great tools for composing and aggregating data streams through operators.
              </ListItem>
            </Appear>
          </List>
        </Slide>

        <Slide transition={["slide"]} bgColor="tertiary">
          <Heading size={4} textColor="primary" caps>When?</Heading>
          <List>
            <Appear>
              <ListItem textColor="primary">
                You have an UI with complex events on components
              </ListItem>
            </Appear>
            <Appear>
              <ListItem textColor="primary">
                You have a server side app that needs to have side effects based on async service calls.
              </ListItem>
            </Appear>
            <Appear>
              <ListItem textColor="primary">
                As a rule of thumb whenever the system has asynchronous API calls and side effects based on these calls then there can be gains using the reactive approach
              </ListItem>
            </Appear>
          </List>
        </Slide>

        <Slide transition={["slide"]} bgColor="secondary">
          <Heading size={4} textColor="primary" caps>When (Examples)?</Heading>
          <List>
            <Appear>
              <ListItem textColor="primary">
                A grid-like component with functionality similar to MS Excel
              </ListItem>
            </Appear>
            <Appear>
              <ListItem textColor="primary">
                An interactive shared dashboard
              </ListItem>
            </Appear>
            <Appear>
              <ListItem textColor="primary">
                A web text editor
              </ListItem>
            </Appear>
            <Appear>
              <ListItem textColor="primary">
                A highly concurrent message queue
              </ListItem>
            </Appear>
          </List>
        </Slide>

        <Slide transition={["slide"]} bgColor="tertiary">
          <Heading size={4} textColor="primary" caps>Some Code Using Rx</Heading>
          <Heading size={6} textColor="primary" caps>...and Hello World</Heading>
          <CodePane
            lang="javascript"
            source={require("raw-loader!../assets/deck.example")}
            textSize="0.7em"
            margin="20px auto"
          />
        </Slide>

        <Slide transition={["fade"]} bgColor="secondary" textColor="primary">

          <Quote>
            <Image src={images.reactiveDog.replace("/", "")} width="500" height="500" />
          </Quote>
          Every Reactive Programmer Ever

        </Slide>
      </Deck>
    );
  }
}
<commit_msg>Fix font size issue<commit_after>// Import React
import React from "react";

// Import Spectacle Core tags
import {
  BlockQuote,
  Cite,
  Deck,
  Heading,
  ListItem,
  List,
  Quote,
  Slide,
  Text,
  Image,
  Appear,
  CodePane,
  Fill
} from "spectacle";

// Import image preloader util
import preloader from "spectacle/lib/utils/preloader";

// Import theme
import createTheme from "spectacle/lib/themes/default";

// Require CSS
require("normalize.css");
require("spectacle/lib/themes/default/index.css");

const images = {
  anchorman: require("../assets/anchorman.jpg"),
  reactiveDog: require("../assets/reactive_dog.jpg"),
  starlordConfused: require("../assets/starlord_confused.jpg"),
  nightmare: require("../assets/nightmare.jpg")
};

preloader(images);

const theme = createTheme({
  primary: "white",
  secondary: "#1F2022",
  tertiary: "#03A9FC",
  quartenary: "#CECECE"
}, {
  primary: "Monaco",
  secondary: "Helvetica"
});

export default class Presentation extends React.Component {
  render() {
    return (
      <Deck transition={["zoom", "slide"]} transitionDuration={500} theme={theme}>
        <Slide transition={["zoom"]} bgColor="primary">
          <Heading size={1} fit caps lineHeight={1} textColor="secondary">
            Reactive Programming
          </Heading>
          <Appear>
            <Heading size={6} caps lineHeight={1} textColor="secondary">
              - OR -
            </Heading>
          </Appear>
          <Appear>
            <Image src={images.starlordConfused.replace("/", "")} height="500px" width="500px" display="block" />
          </Appear>
        </Slide>

        <Slide transition={["slide"]} bgColor="secondary">
          <Heading size={6} textColor="primary" caps>What it does by definition...</Heading>
          \n
          <Appear>
            <Text size={6} textColor="primary">
                Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
            </Text>
          </Appear>
        </Slide>

        <Slide transition={["slide"]} bgColor="tertiary">
          <Heading size={4} textColor="primary">Feels like</Heading>
          <Image src={images.anchorman.replace("/", "")} height="500px" width="800px" />
        </Slide>

        <Slide transition={["slide"]} bgColor="secondary">
          <Heading size={4} textColor="primary" caps>Huh?</Heading>
          <List>
            <Appear>
              <ListItem textColor="primary" textSize="1.2em">
                Reactive programming is programming with asynchronous data streams.
              </ListItem>
            </Appear>
            <Appear>
              <ListItem textColor="primary" textSize="1.2em">
                Streams are object pipelines (data/events/objects), which you can observe and react to.
              </ListItem>
            </Appear>
            <Appear>
              <ListItem textColor="primary" textSize="1.2em">
                Streams are observables.
              </ListItem>
            </Appear>
            <Appear>
              <ListItem textColor="primary" textSize="1.2em">
                Observers are methods that implement actions based on the observed stream.
              </ListItem>
            </Appear>
            <Appear>
              <ListItem textColor="primary" textSize="1.2em">
                Streams(Observables) can be created and composed using operators
              </ListItem>
            </Appear>
          </List>
        </Slide>

        <Slide transition={["slide"]} bgColor="tertiary">
          <Heading size={4} textColor="primary" caps>Why?</Heading>
          <List>
            <Appear>
              <ListItem textColor="primary" textSize="1.2em">
                Managing user events flow is hard
              </ListItem>
            </Appear>
            <Appear>
              <ListItem textColor="primary" textSize="1.2em">
                Managing broadcast events is harder
              </ListItem>
            </Appear>
            <Appear>
              <ListItem textColor="primary" textSize="1.2em">
                Managing both is a NIGHTMARE
              </ListItem>
            </Appear>
            <Appear>
              <ListItem textColor="primary" textSize="1.2em">
                The bad news is you have to handle both
              </ListItem>
            </Appear>
          </List>
          <Appear>
            <Image src={images.nightmare.replace("/", "")} width="400" height="300" />
          </Appear>
        </Slide>

        <Slide transition={["slide"]} bgColor="secondary">
          <Heading size={4} textColor="primary" caps>How?</Heading>
          <List>
            <Appear>
              <ListItem textColor="primary" textSize="1em">
                The fundament of the implementation in reactive programming is the Observer Pattern.
              </ListItem>
            </Appear>
            <Appear>
              <ListItem textColor="primary" textSize="1em">
                The most popular library is Rx. It has multiple language implementations (JS, Python, Java, Scala, C# etc.)
              </ListItem>
            </Appear>
            <Appear>
              <ListItem textColor="primary" textSize="1em">
                RP can be useful both in UI and on the server side as a logical progression in event driven systems
              </ListItem>
            </Appear>
            <Appear>
              <ListItem textColor="primary" textSize="1em">
                These libraries provide great tools for composing and aggregating data streams through operators.
              </ListItem>
            </Appear>
          </List>
        </Slide>

        <Slide transition={["slide"]} bgColor="tertiary">
          <Heading size={4} textColor="primary" caps>When?</Heading>
          <List>
            <Appear>
              <ListItem textColor="primary">
                You have an UI with complex events on components
              </ListItem>
            </Appear>
            <Appear>
              <ListItem textColor="primary">
                You have a server side app that needs to have side effects based on async service calls.
              </ListItem>
            </Appear>
            <Appear>
              <ListItem textColor="primary">
                As a rule of thumb whenever the system has asynchronous API calls and side effects based on these calls then there can be gains using the reactive approach
              </ListItem>
            </Appear>
          </List>
        </Slide>

        <Slide transition={["slide"]} bgColor="secondary">
          <Heading size={4} textColor="primary" caps>When (Examples)?</Heading>
          <List>
            <Appear>
              <ListItem textColor="primary">
                A grid-like component with functionality similar to MS Excel
              </ListItem>
            </Appear>
            <Appear>
              <ListItem textColor="primary">
                An interactive shared dashboard
              </ListItem>
            </Appear>
            <Appear>
              <ListItem textColor="primary">
                A web text editor
              </ListItem>
            </Appear>
            <Appear>
              <ListItem textColor="primary">
                A highly concurrent message queue
              </ListItem>
            </Appear>
          </List>
        </Slide>

        <Slide transition={["slide"]} bgColor="tertiary">
          <Heading size={4} textColor="primary" caps>Some Code Using Rx</Heading>
          <Heading size={6} textColor="primary" caps>...and Hello World</Heading>
          <CodePane
            lang="javascript"
            source={require("raw-loader!../assets/deck.example")}
            textSize="0.7em"
            margin="20px auto"
          />
        </Slide>

        <Slide transition={["fade"]} bgColor="secondary" textColor="primary">

          <Quote>
            <Image src={images.reactiveDog.replace("/", "")} width="500" height="500" />
          </Quote>
          Every Reactive Programmer Ever

        </Slide>
      </Deck>
    );
  }
}
<|endoftext|>


<commit_before>(function(window){

    function anything() {

        this.version = "0.0.1"

    }

    function addTwoThings(thingOne,thingTwo) {

        return thingOne+thingTwo

    }
    function subtractTwoThings(thingOne,thingTwo) {

        return thingOne-thingTwo

    }
    function divideTwoThings(thingOne,thingTwo) {

        return thingOne/thingTwo

    }
    function multiplyTwoThings(thingOne,thingTwo) {

        return thingOne*thingTwo

    }

    //Functions go here
    var doTheThing = function() {
        var test = 1+1;

        console.log(test);
        console.log('Thing is done');
    };

    var flipText = function(text)
    {
        var flipDict={'A':'∀','B':'𐐒','C':'Ɔ','E':'Ǝ','F':'Ⅎ','G':'פ','H':'H','I':'I','J':'ſ','L':'˥','M':'W','N':'И','P':'Ԁ','R':'ᴚ','T':'⊥','U':'∩','V':'Λ','Y':'⅄','a':'ɐ','b':'q','c':'ɔ','d':'p','e':'ǝ','f':'ɟ','g':'ƃ','h':'ɥ','i':'ᴉ','j':'ɾ','k':'ʞ','m':'ɯ','n':'u','p':'d','q':'b','r':'ɹ','t':'ʇ','u':'n','v':'ʌ','w':'ʍ','y':'ʎ','1':'Ɩ','2':'ᄅ','3':'Ɛ','4':'ㄣ','5':'ϛ','6':'9','7':'ㄥ','8':'8','9':'6','0':'0','.':'˙',',':'\'','\'':',','"':',,','`':',','<':'>','>':'<','∴':'∵','&':'⅋','_':'‾','?':'¿','!':'¡','[':']',']':'[','(':')',')':'(','{':'}','}':'{'};
        for (var i in flipDict) {
            flipDict[flipDict[i]] = i
        }
        var r = []
        for (var ix = 0; ix < text.length; ix++) {
            var c = text.charAt(ix)
            var f = flipDict[c]
            r.push(typeof f != 'undefined'? f : c);
        }
        return r.reverse().join('');
    }

    var getOffMyLawn = function(message)
    {
        alert(message);
    }

    var greetHannah = function()
    {
        alert("Hey. Uhh.. Hello.")
    }

    function hash(message) {
        return message.length.toString(16);
    }

    /**
    * Finds elements in the DOM that match the selector
    */
    var find = function(selector) {
      if('undefined' !== typeof document.querySelector)
        return document.querySelector(selector)

      return undefined;
    }

    var noop = function () {
    };

    var self = function () {
        return this;
    }

    var Δ = function () {
        return new anything();
    }

    //Just in case you need to check if something equals 5...
    var isNumber5 = function(num)
    {
      return num == 5;
    }

    var addRealFunctionalityOnTheFly = function () {
      var script   = document.createElement("script");
      script.type  = "text/javascript";
      script.src   = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js";
      document.body.appendChild(script);
    };

    var getRandomNumber = function ()
    {
        return 4; // chosen by fair dice roll
                  // guaranteed to be random
    }

    var getTrueRandomNumber = function () {
        return getRandomNumber(); // I don't know what you were expecting
    }

    var everything = function()
    {
      return 42;
    }

    var twoString = function()
	{
		return "2";
	}

  var fizzbuzz = function(){
      // fire an ultra-difficult algorithm to either print Fizz, Buzz, FizzBuzz or the number
      for(var i = 1; i <= 100; i++){
        if(i%3 == 0 && i%5 == 0){
          console.log("FizzBuzz");
        }else if (i%5 == 0) {
          console.log("Buzz");
        }else if (i%3 == 0) {
          console.log("Fizz");
        }else{
          console.log(i);
        }
      }
    }

    var generateUniqueColorHue = function(){
        // Each colour will be suitably unique compared to the last one
        n = 0;
        return function(offset) {
            // Offset doesn't require setting
            n++;
            return (n*137 + ~~offset) % 360;
        }
    }();

    //Return true if today is Christmas
    var isChristmas = function()
    {
        var today = new(Date);
        // Months are 0 indexed
        return (today.getMonth() == 11 && today.getDate() == 25);
    }

    //When you need something but you don't know what
    var something = function(){
        var keys = Object.keys(anything.prototype);
        var r = this.getRandomNumber(keys.length);
        return anything.prototype[keys[r]].bind(this);
    }

    //prototypes go here
    anything.prototype.doTheThing = doTheThing;
    anything.prototype.flipText = flipText;
    anything.prototype.getOffMyLawn = getOffMyLawn;
    anything.prototype.greetHannah = greetHannah;
    anything.prototype.hash = hash;
    anything.prototype.find = find;
    anything.prototype.noop = noop;
    anything.prototype.self = self;
    anything.prototype.Δ = Δ;
    anything.prototype.isNumber5 = isNumber5;
    anything.prototype.addRealFunctionalityOnTheFly = addRealFunctionalityOnTheFly;
    anything.prototype.getRandomNumber = getRandomNumber;
    anything.prototype.getTrueRandomNumber = getTrueRandomNumber;
    anything.prototype.everything = everything;
    anything.prototype.twoString = twoString;
    anything.prototype.fizzbuzz = fizzbuzz;
    anything.prototype.generateUniqueColorHue = generateUniqueColorHue;
    anything.prototype.isChristmas = isChristmas;
    anything.prototype.something = something;

    //put that shit where everyone can see it.
    if(typeof(window.Δ) === 'undefined'){
        window.Δ = new anything();
    }
    else{
        console.log("Δ already defined.");
    }
})(window);
<commit_msg>added changes by @toish<commit_after>(function(window){

    function anything() {

        this.version = "0.0.1"

    }

    //Functions go here
    var doTheThing = function() {
        var test = 1+1;

        console.log(test);
        console.log('Thing is done');
    };

    var flipText = function(text)
    {
        var flipDict={'A':'∀','B':'𐐒','C':'Ɔ','E':'Ǝ','F':'Ⅎ','G':'פ','H':'H','I':'I','J':'ſ','L':'˥','M':'W','N':'И','P':'Ԁ','R':'ᴚ','T':'⊥','U':'∩','V':'Λ','Y':'⅄','a':'ɐ','b':'q','c':'ɔ','d':'p','e':'ǝ','f':'ɟ','g':'ƃ','h':'ɥ','i':'ᴉ','j':'ɾ','k':'ʞ','m':'ɯ','n':'u','p':'d','q':'b','r':'ɹ','t':'ʇ','u':'n','v':'ʌ','w':'ʍ','y':'ʎ','1':'Ɩ','2':'ᄅ','3':'Ɛ','4':'ㄣ','5':'ϛ','6':'9','7':'ㄥ','8':'8','9':'6','0':'0','.':'˙',',':'\'','\'':',','"':',,','`':',','<':'>','>':'<','∴':'∵','&':'⅋','_':'‾','?':'¿','!':'¡','[':']',']':'[','(':')',')':'(','{':'}','}':'{'};
        for (var i in flipDict) {
            flipDict[flipDict[i]] = i
        }
        var r = []
        for (var ix = 0; ix < text.length; ix++) {
            var c = text.charAt(ix)
            var f = flipDict[c]
            r.push(typeof f != 'undefined'? f : c);
        }
        return r.reverse().join('');
    }

    var getOffMyLawn = function(message)
    {
        alert(message);
    }

    var greetHannah = function()
    {
        alert("Hey. Uhh.. Hello.")
    }

    function hash(message) {
        return message.length.toString(16);
    }

    /**
    * Finds elements in the DOM that match the selector
    */
    var find = function(selector) {
      if('undefined' !== typeof document.querySelector)
        return document.querySelector(selector)

      return undefined;
    }

    var noop = function () {
    };

    var self = function () {
        return this;
    }

    var Δ = function () {
        return new anything();
    }

    //Just in case you need to check if something equals 5...
    var isNumber5 = function(num)
    {
      return num == 5;
    }

    var addRealFunctionalityOnTheFly = function () {
      var script   = document.createElement("script");
      script.type  = "text/javascript";
      script.src   = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js";
      document.body.appendChild(script);
    };

    var getRandomNumber = function ()
    {
        return 4; // chosen by fair dice roll
                  // guaranteed to be random
    }

    var everything = function()
    {
      return 42;
    }

    var twoString = function()
	{
		return "2";
	}

  var fizzbuzz = function(){
      // fire an ultra-difficult algorithm to either print Fizz, Buzz, FizzBuzz or the number
      for(var i = 1; i <= 100; i++){
        if(i%3 == 0 && i%5 == 0){
          console.log("FizzBuzz");
        }else if (i%5 == 0) {
          console.log("Buzz");
        }else if (i%3 == 0) {
          console.log("Fizz");
        }else{
          console.log(i);
        }
      }
    }

    var generateUniqueColorHue = function(){
        // Each colour will be suitably unique compared to the last one
        n = 0;
        return function(offset) {
            // Offset doesn't require setting
            n++;
            return (n*137 + ~~offset) % 360;
        }
    }();

    //Return true if today is Christmas
    var isChristmas = function()
    {
        var today = new(Date);
        // Months are 0 indexed
        return (today.getMonth() == 11 && today.getDate() == 25);
    }

    function negMod( n, m ) {
        return ((n % m) + m) % m;
    }

    var RGBtoCMYK = function( rgb ) {
        if ((typeof rgb) == "string" && rgb[0] == "#" && (rgb.length == 7 || rgb.length == 4)){
            if (rgb.length == 4) {
                rgb = "#"+rgb[1]+rgb[1]+rgb[2]+rgb[2]+rgb[3]+rgb[3];
            }
            newrgb = {r:0, g:0, b:0};
            newrgb.r = parseInt(rgb.substring(1,3), 16);
            newrgb.g = parseInt(rgb.substring(3,5), 16);
            newrgb.b = parseInt(rgb.substring(5,8), 16);
            rgb = newrgb;
        }
        var r = rgb['r']/255;
        var g = rgb['g']/255;
        var b = rgb['b']/255;
        var k = 1 - (Math.max(r, g, b));
        if (k != 1) {
            var c = ((1 - r) - k) / (1 - k);
            var m = ((1 - g) - k) / (1 - k);
            var y = ((1 - b) - k) / (1 - k);
        } else {
            var c = 0;
            var m = 0;
            var y = 0;
        }
        return {c: c, m: m, y: y, k: k};
    }

    var CMYKtoRGB = function( cmyk ) {
        var r = 255 * (1-cmyk.c) * (1-cmyk.k);
        var g = 255 * (1-cmyk.m) * (1-cmyk.k);
        var b = 255 * (1-cmyk.y) * (1-cmyk.k);
        return {r: r, g: g, b: b};
    }

    var RGBtoHSL = function( rgb ) {
        if ((typeof rgb) == "string" && rgb[0] == "#" && (rgb.length == 7 || rgb.length == 4)){
            if (rgb.length == 4) {
                rgb = "#"+rgb[1]+rgb[1]+rgb[2]+rgb[2]+rgb[3]+rgb[3];
            }
            newrgb = {r:0, g:0, b:0};
            newrgb.r = parseInt(rgb.substring(1,3), 16);
            newrgb.g = parseInt(rgb.substring(3,5), 16);
            newrgb.b = parseInt(rgb.substring(5,8), 16);
            rgb = newrgb;
        }
        var r = rgb['r'] / 255;
        var g = rgb['g'] / 255;
        var b = rgb['b'] / 255;
        var rgbOrdered = [r,g,b].sort();
        var l = ((rgbOrdered[0] + rgbOrdered[2]) / 2) * 100;
        var s, h;
        if (rgbOrdered[0] == rgbOrdered[2]) {
            s = 0;
            h = 0;
        } else {
            if (l >= 50) {
                s = ((rgbOrdered[2] - rgbOrdered[0])/((2.0 - rgbOrdered[2]) - rgbOrdered[0])) * 100;
            } else {
                s = ((rgbOrdered[2] - rgbOrdered[0])/(rgbOrdered[2] + rgbOrdered[0])) * 100;
            }
            if (rgbOrdered[2] == r) {
                h = ((g-b)/(rgbOrdered[2] - rgbOrdered[0])) * 60;
            } else if (rgbOrdered[2] == g) {
                h = (2+((b-r)/(rgbOrdered[2] - rgbOrdered[0]))) * 60;
            } else {
                h = (4+((r-g)/(rgbOrdered[2] - rgbOrdered[0]))) * 60;
            }
            if (h < 0) {
                h += 360;
            } else if (h > 360) {
                h = h % 360;
            }
        };
        return {
            h: h,
            s: s,
            l: l
        };
    }

    var HSLtoRGB = function( hsl ) {
        if (hsl.s == 0) {
            var grey = (hsl.l / 100) * 255;
            return {
                r: grey,
                g: grey,
                b: grey
            }
        } else {
            if (hsl.l >= 50) {
                tempOne = ((hsl.l/100) + (hsl.s/100)) - ((hsl.l/100) * (hsl.s/100));
            } else {
                tempOne = (hsl.l/100) * (1 + (hsl.s/100));
            }
            tempTwo = (2 * (hsl.l/100)) - tempOne;
            tempHue = hsl.h / 360;
            tempR = (tempHue + 0.333) % 1;
            tempG = tempHue;
            tempB = negMod((tempHue - 0.333), 1);
            var r,g,b;
            if ((6 * tempR) < 1) {
                r = tempTwo + ((tempOne - tempTwo) * 6 * tempR);
            } else if ((2 * tempR) < 1) {
                r = tempOne;
            } else if ((3 * tempR) < 2) {
                r = tempTwo + ((tempOne - tempTwo) * ((0.666 - tempR) * 6));
            } else {
                r = tempTwo;
            }
            if ((6 * tempG) < 1) {
                g = tempTwo + ((tempOne - tempTwo) * 6 * tempG);
            } else if ((2 * tempG) < 1) {
                g = tempOne;
            } else if ((3 * tempG) < 2) {
                g = tempTwo + ((tempOne - tempTwo) * ((0.666 - tempG) * 6));
            } else {
                g = tempTwo;
            }
            if ((6 * tempB) < 1) {
                b = tempTwo + ((tempOne - tempTwo) * 6 * tempB);
            } else if ((2 * tempB) < 1) {
                b = tempOne;
            } else if ((3 * tempB) < 2) {
                b = tempTwo + ((tempOne - tempTwo) * ((0.666 - tempB) * 6));
            } else {
                b = tempTwo;
            }
            if (r < 0) r = 0;
            if (g < 0) g = 0;
            if (b < 0) b = 0;
            return {
                r: r * 255,
                g: g * 255,
                b: b * 255
            }
        }
    }

    var CMYKtoHSL = function( cmyk ) {
        var rgb = CMYKtoRGB(cmyk);
        return RGBtoHSL(rgb);
    }

    var HSLtoCMYK = function( hsl ) {
        var rgb = HSLtoRGB(hsl);
        return RGBtoCMYK(rgb);
    }

    //prototypes go here
    anything.prototype.doTheThing = doTheThing;
    anything.prototype.flipText = flipText;
    anything.prototype.getOffMyLawn = getOffMyLawn;
    anything.prototype.greetHannah = greetHannah;
    anything.prototype.hash = hash;
    anything.prototype.find = find;
    anything.prototype.noop = noop;
    anything.prototype.self = self;
    anything.prototype.Δ = Δ;
    anything.prototype.isNumber5 = isNumber5;
    anything.prototype.addRealFunctionalityOnTheFly = addRealFunctionalityOnTheFly;
    anything.prototype.getRandomNumber = getRandomNumber;
    anything.prototype.everything = everything;
    anything.prototype.twoString = twoString;
    anything.prototype.fizzbuzz = fizzbuzz;
    anything.prototype.generateUniqueColorHue = generateUniqueColorHue;
    anything.prototype.isChristmas = isChristmas;
    anything.prototype.RGBtoCMYK = RGBtoCMYK;
    anything.prototype.CMYKtoRGB = CMYKtoRGB;
    anything.prototype.RGBtoHSL = RGBtoHSL;
    anything.prototype.HSLtoRGB = HSLtoRGB;
    anything.prototype.CMYKtoHSL = CMYKtoHSL;
    anything.prototype.HSLtoCMYK = HSLtoCMYK;

    //put that shit where everyone can see it.
    if(typeof(window.Δ) === 'undefined'){
        window.Δ = new anything();
    }
    else{
        console.log("Δ already defined.");
    }
})(window);
<|endoftext|>