<commit_before>import moment from 'moment';

let state = window.state = {
  // Times
  shiftStartTime: moment('2013-01-12 16:00'),
  closingTime: moment('2013-01-12 22:00'),
  currentTime: moment('2013-01-12 16:30'),

  // Closing
  afterClosingTime: false,
  lockedIn: false,

  // Bedroom items
  alarmRinging: true,
  mirrorSmashed: false,

  // Home bathroom items
  bathroomTowel: "clean",

  // Home kitchen items
  garbageOutside: false,
  fridgeInventory: [
    "beer",
    "milk",
  ],
  cupboardsInventory: [
    "granolaBar",
  ],

  // Till
  amountInTill: 15.75,

  // Work kitchen items
  prepInventory: [
    "knife",
  ],

  // Garage items
  garageDoorOpen: false,

  // Work entrance
  uprightedSign: false,
  managerBailed: false,
  doorLocked: false,

  // Work bathroom
  sinkClean: false,
  floorClean: false,
  toiletClean: false,
  toiletVeryClean: false,
  cleanHands: false,

  // Personal items
  inventory: [],
  wearing: "pajamas",
  wearingHat: false,
  wetUniform: false,
  wetPajamas: false,
  nastyBreath: true,
  showered: false,
  wet: false,
  luck: 10,
  confidence: 10,

  // Car state
  car: {
    running: false,
    atWork: false,
    ruined: false,
  },

  // Phone state
  unreadTexts: 3,

  // Customers
  customers: {
    olderManFed: false,
    oldLady: {
      served: false,
      fed: false,
      angry: false
    },
    alien: {
      served: false,
      fed: false,
      angry: false
    },
    tinfoil: {
      served: false,
      fed: false,
      angry: false
    }
  },

  // Doom
  doom: {
    started: false,
    progress: 0,
  },
};

export function results() {
  let results = [];

  function a(score, description) {
    results.push({score, description});
  }

  if (state.mirrorSmashed) {
    a(-77, "You broke a mirror. That's 7 years bad luck.");
  }

  if (state.nastyBreath) {
    a(-10, "Your breath reeks. Try brushing your teeth next time.");
  } else {
    a(10, "Your breath was minty fresh. Your speech was an olfactory delight.");
  }

  if (state.alarmRinging) {
    a(-10, "You left your alarm ringing! Your landlord says this is the last straw.");
  }

  if (!state.garbageOutside) {
    a(-10, "You didn't take out the trash. A small flock of seagulls has moved into your kitchen.");
  }

  if (state.wetUniform) {
    a(-10, "Your work uniform is wet. Your boss wasn't too pleased with that");
  }

  if (state.wetPajamas) {
    a(-10, "You got yout pajamas wet.");
  }

  if (state.wearingHat) {
    a(5, "You wore your hat.");
  } else {
    a(-5, "You forgot your hat at home.");
  }

  if (state.uprightedSign) {
    a(5, "You fixed the sign outside the store.");
  }

  if (!state.showered) {
    a(-10, "You didn't shower before going to work.");
  } else {
    a(10, "You smell nice.");
  }

  if (state.car.running) {
    a(-10, "You left your car running. It was subsequently stolen. Good luck getting home!");
  }

  if (state.car.ruined) {
    a(-50, "You smashed up your car and garage door.");
  }

  if (state.toiletClean && state.sinkClean && state.floorClean) {
    if(state.toiletVeryClean) {
      a(50, "You cleaned the Circle Burger bathroom to perfection. It's now a popular tourist destination.");
    } else {
      a(20, "You cleaned the Circle Burger bathroom.");
    }
  } else if (!state.toiletClean && !state.sinkClean && !state.floorClean) {
    a(-50, "You left the Circle Burger bathroom filthy.");
  } else {
    if(!state.toiletClean) {
      a(-10, "You forgot to clean the Circle Burger toilet.");
    }
    if(!state.sinkClean) {
      a(-10, "You forgot to clean the Circle Burger sink.");
    }
    if(!state.floorClean) {
      a(-10, "You forgot to clean the Circle Burger floor.");
    }
  }

  return results;
}

export default state;
<commit_msg>Lock youfrself inesathoesahesth483ipte<commit_after>import moment from 'moment';

let state = window.state = {
  // Times
  shiftStartTime: moment('2013-01-12 16:00'),
  closingTime: moment('2013-01-12 22:00'),
  currentTime: moment('2013-01-12 16:30'),

  // Closing
  afterClosingTime: false,
  lockedIn: false,

  // Bedroom items
  alarmRinging: true,
  mirrorSmashed: false,

  // Home bathroom items
  bathroomTowel: "clean",

  // Home kitchen items
  garbageOutside: false,
  fridgeInventory: [
    "beer",
    "milk",
  ],
  cupboardsInventory: [
    "granolaBar",
  ],

  // Till
  amountInTill: 15.75,

  // Work kitchen items
  prepInventory: [
    "knife",
  ],

  // Garage items
  garageDoorOpen: false,

  // Work entrance
  uprightedSign: false,
  managerBailed: false,
  doorLocked: false,

  // Work bathroom
  sinkClean: false,
  floorClean: false,
  toiletClean: false,
  toiletVeryClean: false,
  cleanHands: false,

  // Personal items
  inventory: [],
  wearing: "pajamas",
  wearingHat: false,
  wetUniform: false,
  wetPajamas: false,
  nastyBreath: true,
  showered: false,
  wet: false,
  luck: 10,
  confidence: 10,

  // Car state
  car: {
    running: false,
    atWork: false,
    ruined: false,
  },

  // Phone state
  unreadTexts: 3,

  // Customers
  customers: {
    olderManFed: false,
    oldLady: {
      served: false,
      fed: false,
      angry: false
    },
    alien: {
      served: false,
      fed: false,
      angry: false
    },
    tinfoil: {
      served: false,
      fed: false,
      angry: false
    }
  },

  // Doom
  doom: {
    started: false,
    progress: 0,
  },
};

export function results() {
  let results = [];

  function a(score, description) {
    results.push({score, description});
  }

  if (state.mirrorSmashed) {
    a(-77, "You broke a mirror. That's 7 years bad luck.");
  }

  if (state.nastyBreath) {
    a(-10, "Your breath reeks. Try brushing your teeth next time.");
  } else {
    a(10, "Your breath was minty fresh. Your speech was an olfactory delight.");
  }

  if (state.alarmRinging) {
    a(-10, "You left your alarm ringing! Your landlord says this is the last straw.");
  }

  if (!state.garbageOutside) {
    a(-10, "You didn't take out the trash. A small flock of seagulls has moved into your kitchen.");
  }

  if (state.wetUniform) {
    a(-10, "Your work uniform is wet. Your boss wasn't too pleased with that");
  }

  if (state.wetPajamas) {
    a(-10, "You got yout pajamas wet.");
  }

  if (state.wearingHat) {
    a(5, "You wore your hat.");
  } else {
    a(-5, "You forgot your hat at home.");
  }

  if (state.lockedIn) {
    a(-5, "You locked yourself in the store.");
  } else {
    a(5, "You locked up the store.");
  }

  if (state.uprightedSign) {
    a(5, "You fixed the sign outside the store.");
  }

  if (!state.showered) {
    a(-10, "You didn't shower before going to work.");
  } else {
    a(10, "You smell nice.");
  }

  if (state.car.running) {
    a(-10, "You left your car running. It was subsequently stolen. Good luck getting home!");
  }

  if (state.car.ruined) {
    a(-50, "You smashed up your car and garage door.");
  }

  if (state.toiletClean && state.sinkClean && state.floorClean) {
    if(state.toiletVeryClean) {
      a(50, "You cleaned the Circle Burger bathroom to perfection. It's now a popular tourist destination.");
    } else {
      a(20, "You cleaned the Circle Burger bathroom.");
    }
  } else if (!state.toiletClean && !state.sinkClean && !state.floorClean) {
    a(-50, "You left the Circle Burger bathroom filthy.");
  } else {
    if(!state.toiletClean) {
      a(-10, "You forgot to clean the Circle Burger toilet.");
    }
    if(!state.sinkClean) {
      a(-10, "You forgot to clean the Circle Burger sink.");
    }
    if(!state.floorClean) {
      a(-10, "You forgot to clean the Circle Burger floor.");
    }
  }

  return results;
}

export default state;
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp'),
    inlineCss = require('gulp-inline-css'),
    minifyHTML = require('gulp-minify-html'),
    minifyInline = require('gulp-minify-inline'),
    preprocess = require('gulp-preprocess'),
    rename = require('gulp-rename'),
    klaw = require('klaw'),
    fs = require('fs'),
    Q = require('q'),
    del = require('del'),
    jsonlint = require('jsonlint'),
    inlineimg = require('gulp-inline-images-no-http'),
    path = require('path');

function buildTask(options){
  gulp.task('build', ['dupe', 'less', 'sass', 'postcss', 'lint'], function build() {
    /** Makes templates for a given directory & its configurations.
     * @function makeTemplates
     * @param {String} dir Directory to make templates from.
     * @param {Array} confItems A list of configurations objects (usually persons) to make templates from.
     */
    function makeTemplates(dir, confItems){
      confItems.forEach(function handleConf(conf){
        var cwd = options.workingDir + '/' + dir;
        var stylesheets = [];

        /**
         * Find stylesheets relative to the CWD & generate <link> tags.
         * This way we can automagically inject them into <head>.
         */
        klaw(cwd)
          .on('readable', function walkTemplateDir() {
            var stylesheet;

            while (stylesheet = this.read()) {
              var relativePath = __dirname.substring(0, __dirname.lastIndexOf('/')) + '/tmp/' + dir;
              stylesheets.push(stylesheet.path.replace(relativePath, ''));
            }
          })
          .on('end', function finishedTemplateDirWalk() {
            conf.stylesheets = stylesheets
              .filter(function filterFiles(file) {
                /* Read only CSS files. */
                return (file.match(/.*\.css/)) ? true : false;
              })
              .reduce(function(prev, current, index, acc) {
                var cssPath = path.win32.basename(current)
                return prev += '<link rel="stylesheet" href="' + cssPath + '">';
              }, '');

            options
              .src([cwd + '/**/*.html', '!' + cwd + '/**/*.inc.html'])
              .pipe(preprocess({
                context: conf
              }))
              .pipe(inlineimg())
              .pipe(inlineCss({
                applyTableAttributes: true,
                applyWidthAttributes: true,
                preserveMediaQueries: true,
                removeStyleTags: false
              }))
              .pipe(minifyHTML({quotes: true}))
              .pipe(minifyInline())
              .pipe(rename(function rename(path){
                path.dirname = dir;
                path.basename += '-' + conf.id;
                return path;
              }))
              .pipe(gulp.dest(options.dist));
          })
      });
    }

    /** Clean up & then read 'src' to generate templates (build entry point). */
    del(options.dist)
      .then(function buildStart(){
       /**
        * Loop through dirs and load their conf files.
        * Promisify all 'makeTemplate' calls and when resolved, make a call to the task (`cb`) to let gulp know we're done.
        */
        var files = [];
        var promises = [];

        fs
          .readdirSync('./' + options.workingDir)
          .forEach(function readConfigurations(dir){
            /** NB: For 'watch' to properly work, the cache needs to be deleted before each require. */
            var confPath = '../tmp/' + dir + '/conf.json';
            var current = null;
            var confItems;

            delete require.cache[require.resolve(confPath)];
            current = require(confPath);
            if (current && current.length) {
              confItems = [...current]
            } else {
              confItems = [current]
            }

            promises.push(makeTemplates(dir, confItems));
          });

        Q.all(promises);
      })
      .catch(function (err) { console.log(err) })
  });
}

module.exports = buildTask;
<commit_msg>Update build task<commit_after>'use strict';

const gulp = require('gulp'),
  inlineCss = require('gulp-inline-css'),
  minifyHTML = require('gulp-minify-html'),
  minifyInline = require('gulp-minify-inline'),
  preprocess = require('gulp-preprocess'),
  rename = require('gulp-rename'),
  klaw = require('klaw'),
  fs = require('fs'),
  Q = require('q'),
  del = require('del'),
  jsonlint = require('jsonlint'),
  inlineimg = require('gulp-inline-images-no-http'),
  path = require('path');

function buildTask(options) {
  // Requires: 'dupe', 'less', 'sass', 'postcss', 'lint'.
  gulp.task(
    'build',
    function build(done) {
      /** Makes templates for a given directory & its configurations.
       * @function makeTemplates
       * @param {String} dir Directory to make templates from.
       * @param {Array} confItems A list of configurations objects (usually persons) to make templates from.
       */
      function makeTemplates(dir, confItems) {
        confItems.forEach(function handleConf(conf) {
          var cwd = options.workingDir + '/' + dir;
          var stylesheets = [];

          /**
           * Find stylesheets relative to the CWD & generate <link> tags.
           * This way we can automagically inject them into <head>.
           */
          klaw(cwd)
            .on('readable', function walkTemplateDir() {
              var stylesheet;

              while ((stylesheet = this.read())) {
                var relativePath = __dirname.substring(0, __dirname.lastIndexOf('/')) + '/tmp/' + dir;
                stylesheets.push(stylesheet.path.replace(relativePath, ''));
              }
            })
            .on('end', function finishedTemplateDirWalk() {
              conf.stylesheets = stylesheets
                .filter(function filterFiles(file) {
                  /* Read only CSS files. */
                  return file.match(/.*\.css/) ? true : false;
                })
                .reduce(function(prev, current, index, acc) {
                  var cssPath = path.win32.basename(current);
                  return (prev += '<link rel="stylesheet" href="' + cssPath + '">');
                }, '');

              options
                .src([cwd + '/**/*.html', '!' + cwd + '/**/*.inc.html'])
                .pipe(
                  preprocess({
                    context: conf
                  })
                )
                .pipe(inlineimg())
                .pipe(
                  inlineCss({
                    applyTableAttributes: true,
                    applyWidthAttributes: true,
                    preserveMediaQueries: true,
                    removeStyleTags: false
                  })
                )
                .pipe(minifyHTML({ quotes: true }))
                .pipe(minifyInline())
                .pipe(
                  rename(function rename(path) {
                    path.dirname = dir;
                    path.basename += '-' + conf.id;
                    return path;
                  })
                )
                .pipe(gulp.dest(options.dist));
            });
        });
      }

      /** Clean up & then read 'src' to generate templates (build entry point). */
      del(options.dist)
        .then(function buildStart() {
          /**
           * Loop through dirs and load their conf files.
           * Promisify all 'makeTemplate' calls and when resolved, make a call to the task (`cb`) to let gulp know we're done.
           */
          var files = [];
          var promises = [];

          fs.readdirSync('./' + options.workingDir).forEach(function readConfigurations(dir) {
            /** NB: For 'watch' to properly work, the cache needs to be deleted before each require. */
            var confPath = '../tmp/' + dir + '/conf.json';
            var current = null;
            var confItems;

            delete require.cache[require.resolve(confPath)];
            current = require(confPath);
            if (current && current.length) {
              confItems = [...current];
            } else {
              confItems = [current];
            }

            promises.push(makeTemplates(dir, confItems));
          });

          Q.all(promises);
        })
        .then(() => done())
        .catch((err) => console.log(err));
    }
  );
}

module.exports = buildTask;
<|endoftext|>


<commit_before>'use strict';

var assign           = require('es5-ext/object/assign')
  , normalizeOptions = require('es5-ext/object/normalize-options')
  , forEach          = require('es5-ext/object/for-each')
  , isRegExp         = require('es5-ext/reg-exp/is-reg-exp')
  , startsWith       = require('es5-ext/string/#/starts-with')
  , d                = require('d')
  , autoBind         = require('d/auto-bind')
  , ee               = require('event-emitter')
  , castAttr         = require('dom-ext/element/#/cast-attribute')
  , dispatchEvt      = require('dom-ext/html-element/#/dispatch-event-2')
  , mergeClass       = require('dom-ext/html-element/#/merge-class')
  , once             = require('timers-ext/once')
  , htmlAttrs        = require('../_html-attributes')
  , eventOpts        = require('../_event-options')

  , defineProperty = Object.defineProperty
  , Input;

module.exports = Input = function (document, type/*, options*/) {
	var options = arguments[2], onChange = this.onChange.bind(this);
	this.document = document;
	this.type = type;
	options = this._resolveOptions(options);
	if (options.observable) this.observable = options.observable;
	this.onChange = once(onChange);
	this._resolveDbAttributes(options);
	this._render(options);
	this.dom._dbjsInput = this;
	if (options.name) this.name = options.name;
	if (options.dbOptions.required) this.required = true;
	forEach(options, function (value, name) {
		if (name === 'class') {
			mergeClass.call(this.dom, value);
		} else if (htmlAttrs[name] || startsWith.call(name, 'data-')) {
			castAttr.call(this.dom, name, value);
		} else if (name === 'control') {
			forEach(value, function (value, name) {
				this.castControlAttribute(name, value);
			}, this);
		} else {
			this.castControlAttribute(name, value);
		}
	}, this);
	onChange();
	if (this.control) this.control.addEventListener('change', this.onChange, false);
};

ee(Object.defineProperties(Input.prototype, assign({
	_value: d(''),
	_name: d(''),
	_resolveOptions: d(function (options) {
		if (this._optionsResolved) return options;
		options = normalizeOptions(this.type.inputOptions,
			options && options.dbOptions && options.dbOptions.inputOptions, options);
		defineProperty(this, '_optionsResolved', d(true));
		return options;
	}),
	_resolveDbAttributes: d(function (options) {
		if (this._dbAttributesResolved) return;
		options.dbOptions = Object(options.dbOptions);
		forEach(this.dbAttributes, function (name, dbName) {
			var value;
			if (!name) return;
			if (name === true) name = dbName;
			if (options[name] != null) return;
			if (options.dbOptions[dbName] != null) {
				value = options.dbOptions[dbName];
			} else if (this.type[dbName] != null) {
				value = this.type[dbName];
			} else {
				if (dbName === 'required') return;
				if (this.type[dbName] != null) value = this.type[dbName];
				else return;
			}
			options[name] = value;
		}, this);
		defineProperty(this, '_dbAttributesResolved', d(true));
	}),
	controlAttributes: d({ autofocus: true, disabled: true, tabindex: true }),
	dbAttributes: d({}),
	changed: d(false),
	_required: d(false),
	valid: d(false),
	_render: d(function () {
		this.control = this.dom = this.document.createElement('input');
	}),
	name: d.gs(function () {
		return this._name ? (this._name + this._indexString) : '';
	}, function (name) {
		this._name = name;
		name = this.name;
		if (name) this.control.setAttribute('name', name);
		else this.control.removeAttribute('name');
	}),
	_index: d(null),
	_indexString: d.gs(function () {
		return (this._index == null) ? '' : '[' + this._index + ']';
	}),
	index: d.gs(function () { return this._index; }, function (index) {
		index = (index == null) ? null : (index >>> 0);
		if (index === this._index) return;
		this._index = index;
		this.name = this._name;
	}),
	required: d.gs(function () { return this._required; }, function (value) {
		value = Boolean(value);
		if (this._required === value) return;
		this._required = value;
		this.castControlAttribute('required', value);
		this.onChange();
		this.emit('change:required', value);
	}),
	toDOM: d(function () { return this.dom; }),
	inputValue: d.gs(function () {
		return this.control.value;
	}, function (nu) {
		var old = this.inputValue;
		if (this._value !== nu) {
			this.control.setAttribute('value', this._value = nu);
		}
		if (nu !== old) {
			this.control.value = nu;
			try {
				dispatchEvt.call(this.control, 'change', eventOpts);
			} catch (ignore) {}
		} else {
			this.onChange();
		}
	}),
	value: d.gs(function () {
		return this.type.fromInputValue(this.inputValue);
	}, function (value) {
		value = this.type.toInputValue(value);
		if (value == null) value = '';
		this.inputValue = value;
	}),
	castControlAttribute: d(function (name, value) {
		if (name === 'class') {
			mergeClass.call(this.control, value);
		} else if (!this.controlAttributes[name] && !htmlAttrs[name] &&
				!startsWith.call(name, 'data-')) {
			return;
		}
		if (isRegExp(value)) value = value.source.slice(1, -1);
		castAttr.call(this.control, name, value);
	}),
	destroy: d(function () {
		if (this.form) this.form.removeEventListener('reset', this._onReset, false);
		this.emit('destroy');
	}),
	onChange: d(function () {
		var value, inputValue, changed, valid, emitChanged, emitValid, control;
		control = this.control || (this.controls ? this.controls[Object.keys(this.controls)[0]] : null);
		if (control) {
			if (control.form) {
				if (this.form !== control.form) {
					if (this.form) this.form.removeEventListener('reset', this._onReset, false);
					this.form = control.form;
					this.form.addEventListener('reset', this._onReset, false);
				}
			}
		}
		inputValue = this.inputValue;
		value = this.value;
		changed = (inputValue !== this._value);
		if (value != null) valid = this.type.is(value, this.observable && this.observable.descriptor);
		else if (this.required) valid = false;
		else valid = ((inputValue == null) || !inputValue.trim());

		if (this.changed !== changed) {
			this.changed = changed;
			emitChanged = true;
		}
		if (this.valid !== valid) {
			this.valid = valid;
			emitValid = true;
		}

		this.emit('change', value);
		if (emitChanged) this.emit('change:changed', this.changed);
		if (emitValid) this.emit('change:valid', this.valid);
	})
}, autoBind({
	_onReset: d(function (e) { this.inputValue = this._value; })
}))));
<commit_msg>Support customization of required<commit_after>'use strict';

var assign           = require('es5-ext/object/assign')
  , normalizeOptions = require('es5-ext/object/normalize-options')
  , forEach          = require('es5-ext/object/for-each')
  , isRegExp         = require('es5-ext/reg-exp/is-reg-exp')
  , startsWith       = require('es5-ext/string/#/starts-with')
  , d                = require('d')
  , autoBind         = require('d/auto-bind')
  , ee               = require('event-emitter')
  , castAttr         = require('dom-ext/element/#/cast-attribute')
  , dispatchEvt      = require('dom-ext/html-element/#/dispatch-event-2')
  , mergeClass       = require('dom-ext/html-element/#/merge-class')
  , once             = require('timers-ext/once')
  , htmlAttrs        = require('../_html-attributes')
  , eventOpts        = require('../_event-options')

  , defineProperty = Object.defineProperty
  , Input;

module.exports = Input = function (document, type/*, options*/) {
	var options = arguments[2], onChange = this.onChange.bind(this);
	this.document = document;
	this.type = type;
	options = this._resolveOptions(options);
	if (options.observable) this.observable = options.observable;
	this.onChange = once(onChange);
	this._resolveDbAttributes(options);
	this._render(options);
	this.dom._dbjsInput = this;
	if (options.name) this.name = options.name;
	if (options.required || options.dbOptions.required) this.required = true;
	forEach(options, function (value, name) {
		if (name === 'class') {
			mergeClass.call(this.dom, value);
		} else if (htmlAttrs[name] || startsWith.call(name, 'data-')) {
			castAttr.call(this.dom, name, value);
		} else if (name === 'control') {
			forEach(value, function (value, name) {
				this.castControlAttribute(name, value);
			}, this);
		} else {
			this.castControlAttribute(name, value);
		}
	}, this);
	onChange();
	if (this.control) this.control.addEventListener('change', this.onChange, false);
};

ee(Object.defineProperties(Input.prototype, assign({
	_value: d(''),
	_name: d(''),
	_resolveOptions: d(function (options) {
		if (this._optionsResolved) return options;
		options = normalizeOptions(this.type.inputOptions,
			options && options.dbOptions && options.dbOptions.inputOptions, options);
		defineProperty(this, '_optionsResolved', d(true));
		return options;
	}),
	_resolveDbAttributes: d(function (options) {
		if (this._dbAttributesResolved) return;
		options.dbOptions = Object(options.dbOptions);
		forEach(this.dbAttributes, function (name, dbName) {
			var value;
			if (!name) return;
			if (name === true) name = dbName;
			if (options[name] != null) return;
			if (options.dbOptions[dbName] != null) {
				value = options.dbOptions[dbName];
			} else if (this.type[dbName] != null) {
				value = this.type[dbName];
			} else {
				if (dbName === 'required') return;
				if (this.type[dbName] != null) value = this.type[dbName];
				else return;
			}
			options[name] = value;
		}, this);
		defineProperty(this, '_dbAttributesResolved', d(true));
	}),
	controlAttributes: d({ autofocus: true, disabled: true, tabindex: true }),
	dbAttributes: d({}),
	changed: d(false),
	_required: d(false),
	valid: d(false),
	_render: d(function () {
		this.control = this.dom = this.document.createElement('input');
	}),
	name: d.gs(function () {
		return this._name ? (this._name + this._indexString) : '';
	}, function (name) {
		this._name = name;
		name = this.name;
		if (name) this.control.setAttribute('name', name);
		else this.control.removeAttribute('name');
	}),
	_index: d(null),
	_indexString: d.gs(function () {
		return (this._index == null) ? '' : '[' + this._index + ']';
	}),
	index: d.gs(function () { return this._index; }, function (index) {
		index = (index == null) ? null : (index >>> 0);
		if (index === this._index) return;
		this._index = index;
		this.name = this._name;
	}),
	required: d.gs(function () { return this._required; }, function (value) {
		value = Boolean(value);
		if (this._required === value) return;
		this._required = value;
		this.castControlAttribute('required', value);
		this.onChange();
		this.emit('change:required', value);
	}),
	toDOM: d(function () { return this.dom; }),
	inputValue: d.gs(function () {
		return this.control.value;
	}, function (nu) {
		var old = this.inputValue;
		if (this._value !== nu) {
			this.control.setAttribute('value', this._value = nu);
		}
		if (nu !== old) {
			this.control.value = nu;
			try {
				dispatchEvt.call(this.control, 'change', eventOpts);
			} catch (ignore) {}
		} else {
			this.onChange();
		}
	}),
	value: d.gs(function () {
		return this.type.fromInputValue(this.inputValue);
	}, function (value) {
		value = this.type.toInputValue(value);
		if (value == null) value = '';
		this.inputValue = value;
	}),
	castControlAttribute: d(function (name, value) {
		if (name === 'class') {
			mergeClass.call(this.control, value);
		} else if (!this.controlAttributes[name] && !htmlAttrs[name] &&
				!startsWith.call(name, 'data-')) {
			return;
		}
		if (isRegExp(value)) value = value.source.slice(1, -1);
		castAttr.call(this.control, name, value);
	}),
	destroy: d(function () {
		if (this.form) this.form.removeEventListener('reset', this._onReset, false);
		this.emit('destroy');
	}),
	onChange: d(function () {
		var value, inputValue, changed, valid, emitChanged, emitValid, control;
		control = this.control || (this.controls ? this.controls[Object.keys(this.controls)[0]] : null);
		if (control) {
			if (control.form) {
				if (this.form !== control.form) {
					if (this.form) this.form.removeEventListener('reset', this._onReset, false);
					this.form = control.form;
					this.form.addEventListener('reset', this._onReset, false);
				}
			}
		}
		inputValue = this.inputValue;
		value = this.value;
		changed = (inputValue !== this._value);
		if (value != null) valid = this.type.is(value, this.observable && this.observable.descriptor);
		else if (this.required) valid = false;
		else valid = ((inputValue == null) || !inputValue.trim());

		if (this.changed !== changed) {
			this.changed = changed;
			emitChanged = true;
		}
		if (this.valid !== valid) {
			this.valid = valid;
			emitValid = true;
		}

		this.emit('change', value);
		if (emitChanged) this.emit('change:changed', this.changed);
		if (emitValid) this.emit('change:valid', this.valid);
	})
}, autoBind({
	_onReset: d(function (e) { this.inputValue = this._value; })
}))));
<|endoftext|>


<commit_before>var typeIcons = {
   amenity: {
     arts_centre: 'arg-gallery',
     atm: 'marker',
     bank: 'bank',
     bar: 'bar',
     bicycle_parking: 'bicycle_parking',
     bicycle_rental: 'bicycle_rental',
     bus_station: 'bus',
     cafe: 'cafe',
     car_wash: 'marker',
     cinema: 'cinema',
     clinic: 'marker',
     courthouse: 'marker',
     compressed_air: 'compressed_air',
     dentist: 'dentist',
     doctors: 'doctor',
     embassy: 'embassy',
     fast_food: 'fast-food',
     ferry_terminal: 'ferry',
     fire_station: 'fire-station',
     fuel: 'fuel',
     hospital: 'hospital',
     kindergarten: 'scooter',
     library: 'library',
     pharmacy: 'pharmacy',
     place_of_worship: 'place_of_worship',
     police: 'police',
     post_office: 'post',
     pub: 'beer',
     restaurant: 'restaurant',
     school: 'school',
     shelter: 'shelter',
     theatre: 'theatre',
     townhall: 'town-hall',
     college: 'college',
     university: 'college',
     default: 'marker'
   },
   man_made: {
     tower: 'marker',
     default: 'marker'
   },
   tourism: {
     attraction: 'attraction',
     information: 'information',
     camp_site: 'campsite',
     caravan_site: 'campsite',
     chalet: 'home',
     hostel: 'home',
     motel: 'home',
     guest_house: 'home',
     apartment: 'home',
     hotel: 'lodging',
     museum: 'museum',
     picnic_site: 'picnic-site',
     viewpoint: 'viewpoint',
     zoo: 'zoo',
     theme_park: 'theme_park',
     default: 'marker'
   },
   historic: {
     archaeological_site: 'hillfort',
     memorial: 'memorial',
     manor: 'marker',
     monastery: 'marker',
     default: 'marker'
   },
   railway: {
     station: 'rail',
     default: 'marker'
   },
   aeroway: {
     terminal: 'airport',
     helipad: 'heliport',
     aerodrome: 'airfield',
     default: 'marker'
   },
   shop: {
     alcohol: 'alcohol-shop',
     car_repair: 'marker',
     bakery: 'bakery',
     bicycle: 'bicycle',
     clothes: 'clothing-store',
     supermarket: 'grocery',
     mall: 'grocery',
     department_store: 'grocery',
     convenience: 'shop',
     hairdresser: 'hairdresser',
     florist: 'florist',
     music: 'music',
     butcher: 'slaughterhouse',
     default: 'shop'
   },
   office: {
     government: 'town-hall',
     notary: 'suitcase',
     lawyer: 'suitcase',
     default: 'suitcase'
   },
   natural: {
     peak: 'mountain',
     default: 'triangle-stroked'
   },
   highway: {
     default: 'square-stroked'
   },
   place: {
     default: 'town'
   },
   leisure: {
     park: 'park',
     default: 'marker'
   },
   landuse: {
     cemetery: 'cemetery',
     default: 'marker'
   },
   default: 'marker'
};

var formatResult = function () {
    return function (feature) {
      var formatted = '';
      /*if (feature.osm_key == 'waterway') {
          formatted = 'Upė ';
      }*/

      if (feature.name) {
          formatted += feature.name;
      }

      if (feature.street) {
          if (formatted.length) {
              formatted += ', ';
          }
          formatted += feature.street;
      }

      if (feature.housenumber) {
          if (formatted.length) {
              formatted += ' ';
          }
          formatted += feature.housenumber;
      }

      if (feature.city) {
          if (formatted.length) {
              formatted += ', ';
          }
          formatted += feature.city;
      }

      if (feature.postcode) {
          // if (feature.osm_key != 'highway') {
            if (formatted.length) {
              formatted += ' ';
            }
            formatted += 'LT-' + feature.postcode;
          // }
      }

      return formatted;
    };
};

var searchEngine = new OpenMapSearchEngine({
    formatResult: formatResult(),
});

var sprite;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        sprite = JSON.parse(this.responseText);
    }
};
xmlhttp.open("GET", "search/sprites/openmaplt.json", true);
xmlhttp.send();

function imgSprite(name, value) {
    var icon = typeIcons.default;
    if (typeIcons[name]) {
      icon = typeIcons[name][value] || typeIcons[name].default;
    }
    return '';
}

$('#searchInput').typeahead({
    minLength: 3,
    hint: false,
    highlight: true,
}, {
    limit: 10,
    display: '_description',
    source: searchEngine.ttAdapter(),
    templates: {
      suggestion: function (context) {
        return '
' + imgSprite(context.properties.osm_key, context.properties.osm_value) + context._description + '
';
      }
    }
});

searchEngine.bindDefaultTypeaheadEvent($('#searchInput'));
<commit_msg>Set default marker on search result<commit_after>var typeIcons = {
   amenity: {
     arts_centre: 'arg-gallery',
     atm: 'marker',
     bank: 'bank',
     bar: 'bar',
     bicycle_parking: 'bicycle_parking',
     bicycle_rental: 'bicycle_rental',
     bus_station: 'bus',
     cafe: 'cafe',
     car_wash: 'marker',
     cinema: 'cinema',
     clinic: 'marker',
     courthouse: 'marker',
     compressed_air: 'compressed_air',
     dentist: 'dentist',
     doctors: 'doctor',
     embassy: 'embassy',
     fast_food: 'fast-food',
     ferry_terminal: 'ferry',
     fire_station: 'fire-station',
     fuel: 'fuel',
     hospital: 'hospital',
     kindergarten: 'scooter',
     library: 'library',
     pharmacy: 'pharmacy',
     place_of_worship: 'place_of_worship',
     police: 'police',
     post_office: 'post',
     pub: 'beer',
     restaurant: 'restaurant',
     school: 'school',
     shelter: 'shelter',
     theatre: 'theatre',
     townhall: 'town-hall',
     college: 'college',
     university: 'college',
     default: 'marker'
   },
   man_made: {
     tower: 'marker',
     default: 'marker'
   },
   tourism: {
     attraction: 'attraction',
     information: 'information',
     camp_site: 'campsite',
     caravan_site: 'campsite',
     chalet: 'home',
     hostel: 'home',
     motel: 'home',
     guest_house: 'home',
     apartment: 'home',
     hotel: 'lodging',
     museum: 'museum',
     picnic_site: 'picnic-site',
     viewpoint: 'viewpoint',
     zoo: 'zoo',
     theme_park: 'theme_park',
     default: 'marker'
   },
   historic: {
     archaeological_site: 'hillfort',
     memorial: 'memorial',
     manor: 'marker',
     monastery: 'marker',
     default: 'marker'
   },
   railway: {
     station: 'rail',
     default: 'marker'
   },
   aeroway: {
     terminal: 'airport',
     helipad: 'heliport',
     aerodrome: 'airfield',
     default: 'marker'
   },
   shop: {
     alcohol: 'alcohol-shop',
     car_repair: 'marker',
     bakery: 'bakery',
     bicycle: 'bicycle',
     clothes: 'clothing-store',
     supermarket: 'grocery',
     mall: 'grocery',
     department_store: 'grocery',
     convenience: 'shop',
     hairdresser: 'hairdresser',
     florist: 'florist',
     music: 'music',
     butcher: 'slaughterhouse',
     default: 'shop'
   },
   office: {
     government: 'town-hall',
     notary: 'suitcase',
     lawyer: 'suitcase',
     default: 'suitcase'
   },
   natural: {
     peak: 'mountain',
     default: 'triangle-stroked'
   },
   highway: {
     default: 'square-stroked'
   },
   place: {
     default: 'town'
   },
   leisure: {
     park: 'park',
     default: 'marker'
   },
   landuse: {
     cemetery: 'cemetery',
     default: 'marker'
   },
   default: 'marker'
};

var formatResult = function () {
    return function (feature) {
      var formatted = '';
      /*if (feature.osm_key == 'waterway') {
          formatted = 'Upė ';
      }*/

      if (feature.name) {
          formatted += feature.name;
      }

      if (feature.street) {
          if (formatted.length) {
              formatted += ', ';
          }
          formatted += feature.street;
      }

      if (feature.housenumber) {
          if (formatted.length) {
              formatted += ' ';
          }
          formatted += feature.housenumber;
      }

      if (feature.city) {
          if (formatted.length) {
              formatted += ', ';
          }
          formatted += feature.city;
      }

      if (feature.postcode) {
          // if (feature.osm_key != 'highway') {
            if (formatted.length) {
              formatted += ' ';
            }
            formatted += 'LT-' + feature.postcode;
          // }
      }

      return formatted;
    };
};

var searchEngine = new OpenMapSearchEngine({
    formatResult: formatResult(),
});

var sprite;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        sprite = JSON.parse(this.responseText);
    }
};
xmlhttp.open("GET", "search/sprites/openmaplt.json", true);
xmlhttp.send();

function imgSprite(name, value) {
    var icon = typeIcons.default;
    if (typeIcons[name]) {
      icon = typeIcons[name][value] || typeIcons[name].default;
    }
    return '';
}

$('#searchInput').typeahead({
    minLength: 3,
    hint: false,
    highlight: true,
}, {
    limit: 10,
    display: '_description',
    source: searchEngine.ttAdapter(),
    templates: {
      suggestion: function (context) {
        // return '
' + imgSprite(context.properties.osm_key, context.properties.osm_value) + context._description + '
';
        return '
' + imgSprite('', '') + context._description + '
';
      }
    }
});

searchEngine.bindDefaultTypeaheadEvent($('#searchInput'));
<|endoftext|>


<commit_before>import {createSelector} from 'reselect'
import {STATUS} from './constants'
import {getGridLayoutUtil} from  './utils'

const getCells = state => state.game.cells
const getSettings = state => state.game.settings

export const getGridLayout = createSelector(
  getSettings,
  getGridLayoutUtil
)

const getCellCounts = createSelector(
  getSettings,
  getCells,
  (settings, cells) => {
    return Object.keys(cells).reduce((counts, id) => {
      return Object.assign({}, counts, {
        openCellCount: cells[id].open ? counts.openCellCount + 1 : counts.openCellCount,
        openingCellCount: cells[id].opening ? counts.openingCellCount + 1 : counts.openingCellCount,
        flaggedCellCount: cells[id].flagged ? counts.flaggedCellCount + 1 : counts.flaggedCellCount,
        detonatedCellCount: cells[id].detonated ? counts.detonatedCellCount + 1 : counts.detonatedCellCount
      })}, {
      openCellCount: 0,
      openingCellCount: 0,
      flaggedCellCount: 0,
      detonatedCellCount: 0,
      totalCellCount: settings.rowCount * settings.colCount
    })
  }
)

export const getStatus = createSelector(
  getSettings,
  getCellCounts,
  ({mineCount}, cellCounts) => {
    if (cellCounts.detonatedCellCount > 0) return STATUS.FAILED
    if (cellCounts.openCellCount >= cellCounts.totalCellCount - mineCount) return STATUS.CLEARED
    if (cellCounts.openingCellCount > 0) return STATUS.DANGER
    return STATUS.NEUTRAL
  }
)

export const getRemainingFlagsCount = createSelector(
  getSettings,
  getCellCounts,
  ({mineCount}, {flaggedCellCount}) => Math.max(mineCount - flaggedCellCount, 0)
)

export const getGameOver = createSelector(
  getStatus,
  status => status === STATUS.CLEARED || status === STATUS.FAILED
)

export const getStarted = createSelector(
  getCellCounts,
  cellCounts => cellCounts.openCount > 0
)<commit_msg>fix incorrect reference in getStarted selector<commit_after>import {createSelector} from 'reselect'
import {STATUS} from './constants'
import {getGridLayoutUtil} from  './utils'

const getCells = state => state.game.cells
const getSettings = state => state.game.settings

export const getGridLayout = createSelector(
  getSettings,
  getGridLayoutUtil
)

const getCellCounts = createSelector(
  getSettings,
  getCells,
  (settings, cells) => {
    return Object.keys(cells).reduce((counts, id) => {
      return Object.assign({}, counts, {
        openCellCount: cells[id].open ? counts.openCellCount + 1 : counts.openCellCount,
        openingCellCount: cells[id].opening ? counts.openingCellCount + 1 : counts.openingCellCount,
        flaggedCellCount: cells[id].flagged ? counts.flaggedCellCount + 1 : counts.flaggedCellCount,
        detonatedCellCount: cells[id].detonated ? counts.detonatedCellCount + 1 : counts.detonatedCellCount
      })}, {
      openCellCount: 0,
      openingCellCount: 0,
      flaggedCellCount: 0,
      detonatedCellCount: 0,
      totalCellCount: settings.rowCount * settings.colCount
    })
  }
)

export const getStatus = createSelector(
  getSettings,
  getCellCounts,
  ({mineCount}, cellCounts) => {
    if (cellCounts.detonatedCellCount > 0) return STATUS.FAILED
    if (cellCounts.openCellCount >= cellCounts.totalCellCount - mineCount) return STATUS.CLEARED
    if (cellCounts.openingCellCount > 0) return STATUS.DANGER
    return STATUS.NEUTRAL
  }
)

export const getRemainingFlagsCount = createSelector(
  getSettings,
  getCellCounts,
  ({mineCount}, {flaggedCellCount}) => Math.max(mineCount - flaggedCellCount, 0)
)

export const getGameOver = createSelector(
  getStatus,
  status => status === STATUS.CLEARED || status === STATUS.FAILED
)

export const getStarted = createSelector(
  getCellCounts,
  cellCounts => cellCounts.openCellCount > 0
)<|endoftext|>


<commit_before>function ready() {
	// support connecting to localhost or internet
	var USE_LOCALHOST = true;
	var SOCKET = USE_LOCALHOST ? io.connect('http://localhost:4000') : io.connect('http://infinite-depths-4551.herokuapp.com/');
	var COLOR = localStorage.color ? localStorage.color : '#'+(Math.random()*0xFFFFFF<<0).toString(16);

	// The name of the chatroom is based on the url
	var CHATROOM = document.URL.substring(document.URL.lastIndexOf('/') + 1);
	if (CHATROOM.indexOf('?') != -1) CHATROOM = CHATROOM.substring(0, CHATROOM.indexOf('?'));
	if (localStorage.handle) {
		start_chatroom();
	}

	var chatroom_body = document.getElementById('literoomjs');
	var users = document.getElementById('users');
	var user_list = document.getElementById('user_list');
	var room = document.getElementById('room');
	var join_room_button = document.getElementById('send_message');
	var send_message_button = document.getElementById('send_message');
	var message_input = document.getElementById('message');
	var chatbox = document.getElementById('chatbox');

	DefineCSS();

	join_room_button.onclick = function() {
		var name = document.getElementById('user_handle').value();
		localStorage.handle = name;
		start_chatroom();
	};

	send_message_button.onclick = function() {
		var message = message_input.value.trim();
		if (message != '') {
			SOCKET.emit('send_message', message);
			message_input.value = '';
		}
	};

	message_input.onkeyup = function(e) {
		if (e.keyCode === 13) {
			send_message_button.click();
		}
	}

	message_input.keydown = function(e) {
		if (e.keyCode === 13) e.preventDefault();
	};

	function start_chatroom() {

		SOCKET.emit('join_room',
			{
				chatroom: CHATROOM,
				handle: localStorage.handle,
				color: COLOR,
				old_socket_id: localStorage.socket_id
			});

		// hide front page and show chatroom
		document.getElementById('join_room').style.display = 'none';
		document.getElementById('container').style.display = 'block';
		document.getElementById('joined_as').innerHTML = 'Handle: '
			+ '' +  localStorage.handle + '';
		document.getElementById('room_header').innerHTML = 'Room: '
		 	+ '' + CHATROOM + '';
		document.getElementById('user_color').innerHTML = 'Color: '
			+ '' + COLOR + '';
	}

	/* socket functions
	 		sync_chatroom_members
			sync_socket_id
			broadcast_message
			user_typing
			user_stopped_typing
	*/

	SOCKET.on('sync_chatroom_members', function(members){
		if (localStorage.room !== JSON.stringify(members)) {
			user_list.innerHTML = '';
			for (var socket_id in members) {
				add_member(socket_id, members[socket_id].handle, members[socket_id].color);
			}
			localStorage.room = JSON.stringify(members);
		}
	});

	SOCKET.on('joined_room', function(data) {
		localStorage.socket_id = data.socket_id;
		localStorage.color = data.color;
		add_message('you have joined the room \'' + CHATROOM + '\' as \'' + localStorage.handle + '\'', 'system');
	});

	SOCKET.on('broadcast_message', function(data) {
		var room = JSON.parse(localStorage.room);
		add_message(''
		+ room[data.socket_id].handle + '' + ': ' + data.message, 'user');
	});

	SOCKET.on('user_typing', function(socket_id) {
		add_typing_status(socket_id);
	});

	SOCKET.on('user_stopped_typing', function(socket_id) {
		remove_typing_status(socket_id);
	});

	/* chatroom functions
	 		add_member(socket_id, name, color)
			remove_member(socket_id, name)
			add_typing_status(socket_id)
			remove_typing_status(socket_id)
			add_message(message, type)
	*/

	function add_member(socket_id, name, color) {
		user_list.innerHTML += '
' + name
			+ ' ...
';
	}

	function add_message(message, type) {
		if (type == 'system') {
			chatbox.innerHTML += '
' + message + '';
		}else if (type == 'user') {
			message = linkify(message);
			chatbox.innerHTML += '
' + message + '';
		}
		chatbox.scrollTop = chatbox.scrollHeight;
	}

	function DefineCSS() {
		if (literoomjs.chatroom_theme === 'dark') {
			chatroom_body.style.color = 'white';
			message_input.style['background-color'] = 'black';
			message_input.style.color = 'white';
			chatbox.style['background-color'] = 'black';
			users.style['background-color'] = 'black';
			room.style['background-color'] = 'black';
		}

		if (literoomjs.show_connected_users === 'false') {
			users.style.display = 'none';
		}

		document.getElementById('container').style.width = literoomjs.room_width;
		document.getElementById('join_room').style.width = literoomjs.room_width;

		var room_width = (literoomjs.room_width - 100) + 'px';
		room.style.width = room_width;
		chatroom_body.style['font-size'] = literoomjs.font_size + 'px';
	}
}

function linkify(inputText) {
    var replacedText, replacePattern1, replacePattern2, replacePattern3;

    //URLs starting with http://, https://, or ftp://
    replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
    replacedText = inputText.replace(replacePattern1, '$1');

    //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
    replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
    replacedText = replacedText.replace(replacePattern2, '$1$2');

    //Change email addresses to mailto:: links.
    replacePattern3 = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;
    replacedText = replacedText.replace(replacePattern3, '$1');

    return replacedText;
}
<commit_msg>changed literoomjs to revealing module pattern with only "load" publicly available. also, color selection isn't random anymore.<commit_after>var literoomjs = (function(lrjs) {

	var chatroom_body, users, user_list, room, join_room_button,
		send_message_button, message_input, chatbox;

	var colors = ["#00ffff", "#f5f5dc", "#0000ff", "#00ffff", "#F0E68C", "#9932cc",
		"#e9967a", "#9400d3", "#ff00ff", "#ffd700", "#008000", "#add8e6", "#90ee90",
	    "#ff00ff", "#808000", "#ffa500", "#ffc0cb", "#ff0000"];

	var settings = {
		use_localhost: true,
		chatroom_name: (function() {
			var name = document.URL.substring(document.URL.lastIndexOf('/') + 1);
			if (name.indexOf('?') != -1) name = name.substring(0, name.indexOf('?'));
			return name;
		}()),
		color: (function(){
			if (localStorage.getItem('lrjs-color')) {
				return localStorage.getItem('lrjs-color');
			}else{
				var new_color = colors[Math.floor(colors.length * Math.random())];
				localStorage.setItem('lrjs-color', new_color);
				return new_color;
			}
		}())
	};

	var socket = settings.use_localhost ? io.connect('http://localhost:4000') : io.connect('http://your-server.com/');

	socket.on('sync_chatroom_members', function(members){
		if (localStorage.getItem('lrjs-room') !== JSON.stringify(members)) {
			user_list.innerHTML = '';
			for (var socket_id in members) {
				add_member(socket_id, members[socket_id].handle, members[socket_id].color);
			}
			localStorage.setItem('lrjs-room', JSON.stringify(members));
		}
	});

	socket.on('joined_room', function(data) {
		localStorage.setItem('lrjs-socket_id', data.socket_id);
		localStorage.setItem('lrjs-color', data.color);
		add_message('You have joined the room \'' + settings.chatroom_name + '\' as \'' + localStorage.getItem('lrjs-handle') + '\'', 'system');
	});

	socket.on('broadcast_message', function(data) {
		var room = JSON.parse(localStorage.getItem('lrjs-room'));
		add_message(''
		+ room[data.socket_id].handle + '' + ': ' + data.message, 'user');
	});

	socket.on('user_typing', function(socket_id) {
		add_typing_status(socket_id);
	});

	socket.on('user_stopped_typing', function(socket_id) {
		remove_typing_status(socket_id);
	});

	function startChatroom() {
		socket.emit('join_room', {
			chatroom: settings.chatroom_name,
			handle: localStorage.getItem('lrjs-handle'),
			color: settings.color,
			old_socket_id: localStorage.getItem('lrjs-socket_id')
		});

		// hide front page and show chatroom
		document.getElementById('join_room').style.display = 'none';
		document.getElementById('container').style.display = 'block';
		document.getElementById('joined_as').innerHTML = 'Handle: '
			+ '' +  localStorage.getItem('lrjs-handle') + '';
		document.getElementById('room_header').innerHTML = 'Room: '
		 	+ '' + settings.chatroom_name + '';
		document.getElementById('user_color').innerHTML = 'Color: '
			+ '' + settings.color + '';
	}

	function add_member(socket_id, name, color) {
		user_list.innerHTML += '
' + name
			+ ' ...
';
	}

	function add_message(message, type) {
		if (type == 'system') {
			chatbox.innerHTML += '
' + message + '';
		}else if (type == 'user') {
			message = linkify(message);
			chatbox.innerHTML += '
' + message + '';
		}
		chatbox.scrollTop = chatbox.scrollHeight;
	}

	// makes links clickable in messages
	function linkify(inputText) {
	    var replacedText, replacePattern1, replacePattern2, replacePattern3;

	    replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
	    replacedText = inputText.replace(replacePattern1, '$1');

	    replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
	    replacedText = replacedText.replace(replacePattern2, '$1$2');

	    replacePattern3 = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;
	    replacedText = replacedText.replace(replacePattern3, '$1');

	    return replacedText;
	}

	return ({
		load: function() {
			join_room_button = document.getElementById('join_room_button');
			chatroom_body = document.getElementById('literoomjs');
			users = document.getElementById('users');
			user_list = document.getElementById('user_list');
			room = document.getElementById('room');
			send_message_button = document.getElementById('send_message');
			message_input = document.getElementById('message');
			chatbox = document.getElementById('chatbox');

			if (lrjs.chatroom_theme === 'dark') {
				chatroom_body.style.color = 'white';
				message_input.style['background-color'] = 'black';
				message_input.style.color = 'white';
				chatbox.style['background-color'] = 'black';
				users.style['background-color'] = 'black';
				room.style['background-color'] = 'black';
			}

			if (lrjs.show_connected_users === 'false') {
				users.style.display = 'none';
			}

			document.getElementById('container').style.width = lrjs.room_width;
			document.getElementById('join_room').style.width = lrjs.room_width;

			var room_width = (lrjs.room_width - 100) + 'px';
			room.style.width = room_width;
			chatroom_body.style['font-size'] = lrjs.font_size + 'px';

			join_room_button.onclick = function() {
				var name = document.getElementById('user_handle').value;
				localStorage.setItem('lrjs-handle', name);
				startChatroom();
			};

			send_message_button.onclick = function() {
				var message = message_input.value.trim();
				if (message != '') {
					socket.emit('send_message', message);
					message_input.value = '';
				}
			};

			message_input.onkeyup = function(e) {
				if (e.keyCode === 13) {
					send_message_button.click();
				}
			}

			message_input.keydown = function(e) {
				if (e.keyCode === 13) e.preventDefault();
			};

			if (localStorage.getItem('lrjs-handle')) {
				startChatroom();
			}
		}
	});
}(literoomjs));
<|endoftext|>


<commit_before><commit_msg>fix irc undefined socket<commit_after><|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { FormGroup, Button } from 'reactstrap';
import {
  Field,
  FieldArray,
  formValueSelector,
} from 'redux-form';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as styles from './styles.scss';
import { renderField } from '../libs/helpers';
import InputAndPopover from './InputAndPopover';
import * as actionsTasks from '../../actions/Tasks';
import {
  required,
  maxLength,
  taskHourValidation,
  mixShouldBeLessThenMax,
} from '../libs/validation';

class Task extends React.Component {
  constructor(props) {
    super(props);

    this.handleBlurCheckbox = this.handleBlurCheckbox.bind(this);
    this.handleToggleCheckbox = this.handleToggleCheckbox.bind(this);
  }

  handleToggleCheckbox(field, event) {
    const { store } = this.context;
    const { target: { checked } } = event;
    const { meta: { form }, actionToggleTask } = this.props;

    store.dispatch({
      type: '@@redux-form/CHANGE',
      meta: {
        form,
        touch: true,
        field: `${field}isChecked`,
        persistentSubmitErrors: false,
      },
      payload: checked,
    });

    actionToggleTask({ form, field, checked });
  }

  handleBlurCheckbox(field) {
    const { store } = this.context;
    const { target: { value: payload } } = event;
    const { meta: { form } } = this.props;

    store.dispatch({
      type: '@@redux-form/BLUR',
      meta: {
        form,
        touch: true,
        field: `${field}isChecked`,
      },
      payload,
    });
  }

  render() {
    const {
      level,
      fields,
      meta: { form },
      actionToggleTask,
      actionChangeTaskHours,
      actionRemoveTask,
      actionAddSubTask,
      userCanEditThisEstimate,
    } = this.props;
    const selector = formValueSelector(form);
    const disabled = !userCanEditThisEstimate;
    const showButton = userCanEditThisEstimate;
    const { store: { getState } } = this.context;

    return (
      <FormGroup className={styles.tasks}>
        {fields.map((task, index) => {
          const taskObj = selector(getState(), task);
          const haveSubtask = !!(taskObj.tasks && taskObj.tasks.length);

          return (
            <FormGroup
              key={task}
              name="tasks"
              className={styles.subtasks}
            >

                <Field
                  type="checkbox"
                  disabled={disabled}
                  component={renderField}
                  id={`${task}.isChecked`}
                  name={`${task}.isChecked`}
                  className={styles.subtasks__checkbox}
                  onChange={e => this.handleToggleCheckbox(task, e)}
                  onBlur={e => this.handleBlurCheckbox(task, taskObj, e)}
                />
                <Field
                  type="text"
                  label="Task name:"
                  disabled={disabled}
                  component={renderField}
                  id={`${task}.taskName`}
                  name={`${task}.taskName`}
                  className={styles.subtasks__item}
                  validate={[required, maxLength(100)]}
                />
                <Field
                  type="text"
                  addon={'min'}
                  fieldName="minimumMinutes"
                  component={InputAndPopover}
                  id={`${task}.minimumMinutes`}
                  name={`${task}.minimumMinutes`}
                  className={styles.subtasks__item}
                  disabled={disabled || haveSubtask}
                  actionChangeTaskHours={actionChangeTaskHours}
                  validate={[
                    taskHourValidation(haveSubtask),
                    mixShouldBeLessThenMax(`${task}.maximumMinutes`, haveSubtask),
                  ]}
                />
                <Field
                  type="text"
                  addon={'max'}
                  fieldName="maximumMinutes"
                  component={InputAndPopover}
                  id={`${task}.maximumMinutes`}
                  name={`${task}.maximumMinutes`}
                  className={styles.subtasks__item}
                  disabled={disabled || haveSubtask}
                  validate={[taskHourValidation(haveSubtask)]}
                  actionChangeTaskHours={actionChangeTaskHours}
                />
                {
                  (level < 2 && showButton) &&
                  <Button
                    color="danger"
                    className={styles.subtasks__item}
                    onClick={() => actionAddSubTask({ form, field: `${task}.tasks` })}
                    title="Add subtask"
                  >
                    +
                  </Button>
                }
                {
                  showButton &&
                  <Button
                    color="danger"
                    className={styles.subtasks__item}
                    onClick={() => actionRemoveTask({ index, form, field: task })}
                    title="Delete task (including subtasks)"
                  >
                    ✗
                  </Button>
                }

                <FieldArray
                  level={level + 1}
                  component={Task}
                  name={`${task}.tasks`}
                  actionToggleTask={actionToggleTask}
                  actionRemoveTask={actionRemoveTask}
                  actionChangeTaskHours={actionChangeTaskHours}
                  actionAddSubTask={actionAddSubTask}
                  userCanEditThisEstimate={userCanEditThisEstimate}
                />

            </FormGroup>
          );
        })}
        { (level === 0 && showButton) &&
          <Button
            color="danger"
            onClick={() => fields.push(
              { isChecked: true, minimumMinutes: 0, maximumMinutes: 0 },
            )}
            className={styles.tasks__add}
          >
            Add task
          </Button>
        }
      </FormGroup>
    );
  }
}

Task.contextTypes = {
  store: PropTypes.object,
};

Task.propTypes = {
  level: PropTypes.number.isRequired,
  actionRemoveTask: PropTypes.func.isRequired,
  actionToggleTask: PropTypes.func.isRequired,
  actionAddSubTask: PropTypes.func.isRequired,
  actionChangeTaskHours: PropTypes.func.isRequired,
  userCanEditThisEstimate: PropTypes.bool.isRequired,
  meta: PropTypes.objectOf(PropTypes.any).isRequired,
  fields: PropTypes.objectOf(PropTypes.any).isRequired,
};

function mapStateToProps() {
  return {};
}

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

export default connect(mapStateToProps, mapDispatchToProps)(Task);
<commit_msg>deleted task duration requirement<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { FormGroup, Button } from 'reactstrap';
import {
  Field,
  FieldArray,
  formValueSelector,
} from 'redux-form';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as styles from './styles.scss';
import { renderField } from '../libs/helpers';
import InputAndPopover from './InputAndPopover';
import * as actionsTasks from '../../actions/Tasks';
import {
  required,
  maxLength,
  taskHourValidation,
  mixShouldBeLessThenMax,
} from '../libs/validation';

class Task extends React.Component {
  constructor(props) {
    super(props);

    this.handleBlurCheckbox = this.handleBlurCheckbox.bind(this);
    this.handleToggleCheckbox = this.handleToggleCheckbox.bind(this);
  }

  handleToggleCheckbox(field, event) {
    const { store } = this.context;
    const { target: { checked } } = event;
    const { meta: { form }, actionToggleTask } = this.props;

    store.dispatch({
      type: '@@redux-form/CHANGE',
      meta: {
        form,
        touch: true,
        field: `${field}isChecked`,
        persistentSubmitErrors: false,
      },
      payload: checked,
    });

    actionToggleTask({ form, field, checked });
  }

  handleBlurCheckbox(field) {
    const { store } = this.context;
    const { target: { value: payload } } = event;
    const { meta: { form } } = this.props;

    store.dispatch({
      type: '@@redux-form/BLUR',
      meta: {
        form,
        touch: true,
        field: `${field}isChecked`,
      },
      payload,
    });
  }

  render() {
    const {
      level,
      fields,
      meta: { form },
      actionToggleTask,
      actionChangeTaskHours,
      actionRemoveTask,
      actionAddSubTask,
      userCanEditThisEstimate,
    } = this.props;
    const selector = formValueSelector(form);
    const disabled = !userCanEditThisEstimate;
    const showButton = userCanEditThisEstimate;
    const { store: { getState } } = this.context;

    return (
      <FormGroup className={styles.tasks}>
        {fields.map((task, index) => {
          const taskObj = selector(getState(), task);
          const haveSubtask = !!(taskObj.tasks && taskObj.tasks.length);

          return (
            <FormGroup
              key={task}
              name="tasks"
              className={styles.subtasks}
            >

                <Field
                  type="checkbox"
                  disabled={disabled}
                  component={renderField}
                  id={`${task}.isChecked`}
                  name={`${task}.isChecked`}
                  className={styles.subtasks__checkbox}
                  onChange={e => this.handleToggleCheckbox(task, e)}
                  onBlur={e => this.handleBlurCheckbox(task, taskObj, e)}
                />
                <Field
                  type="text"
                  label="Task name:"
                  disabled={disabled}
                  component={renderField}
                  id={`${task}.taskName`}
                  name={`${task}.taskName`}
                  className={styles.subtasks__item}
                  validate={[required, maxLength(100)]}
                />
                <Field
                  type="text"
                  addon={'min'}
                  fieldName="minimumMinutes"
                  component={InputAndPopover}
                  id={`${task}.minimumMinutes`}
                  name={`${task}.minimumMinutes`}
                  className={styles.subtasks__item}
                  disabled={disabled || haveSubtask}
                  actionChangeTaskHours={actionChangeTaskHours}
                  validate={[
                    // taskHourValidation(haveSubtask),
                    mixShouldBeLessThenMax(`${task}.maximumMinutes`, haveSubtask),
                  ]}
                />
                <Field
                  type="text"
                  addon={'max'}
                  fieldName="maximumMinutes"
                  component={InputAndPopover}
                  id={`${task}.maximumMinutes`}
                  name={`${task}.maximumMinutes`}
                  className={styles.subtasks__item}
                  disabled={disabled || haveSubtask}
                  validate={[
                    // taskHourValidation(haveSubtask),
                  ]}
                  actionChangeTaskHours={actionChangeTaskHours}
                />
                {
                  (level < 2 && showButton) &&
                  <Button
                    color="danger"
                    className={styles.subtasks__item}
                    onClick={() => actionAddSubTask({ form, field: `${task}.tasks` })}
                    title="Add subtask"
                  >
                    +
                  </Button>
                }
                {
                  showButton &&
                  <Button
                    color="danger"
                    className={styles.subtasks__item}
                    onClick={() => actionRemoveTask({ index, form, field: task })}
                    title="Delete task (including subtasks)"
                  >
                    ✗
                  </Button>
                }

                <FieldArray
                  level={level + 1}
                  component={Task}
                  name={`${task}.tasks`}
                  actionToggleTask={actionToggleTask}
                  actionRemoveTask={actionRemoveTask}
                  actionChangeTaskHours={actionChangeTaskHours}
                  actionAddSubTask={actionAddSubTask}
                  userCanEditThisEstimate={userCanEditThisEstimate}
                />

            </FormGroup>
          );
        })}
        { (level === 0 && showButton) &&
          <Button
            color="danger"
            onClick={() => fields.push(
              { isChecked: true, minimumMinutes: 0, maximumMinutes: 0 },
            )}
            className={styles.tasks__add}
          >
            Add task
          </Button>
        }
      </FormGroup>
    );
  }
}

Task.contextTypes = {
  store: PropTypes.object,
};

Task.propTypes = {
  level: PropTypes.number.isRequired,
  actionRemoveTask: PropTypes.func.isRequired,
  actionToggleTask: PropTypes.func.isRequired,
  actionAddSubTask: PropTypes.func.isRequired,
  actionChangeTaskHours: PropTypes.func.isRequired,
  userCanEditThisEstimate: PropTypes.bool.isRequired,
  meta: PropTypes.objectOf(PropTypes.any).isRequired,
  fields: PropTypes.objectOf(PropTypes.any).isRequired,
};

function mapStateToProps() {
  return {};
}

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

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


<commit_before>'use strict';

var util = require('util'),
  Store = require('../base'),
  _ = require('lodash'),
  async = require('async'),
  mongo = Store.use('mongodb'),
  mongoVersion = Store.use('mongodb/package.json').version,
  isNew = mongoVersion.indexOf('1.') !== 0,
  ObjectID = isNew ? mongo.ObjectID : mongo.BSONPure.ObjectID,
  debug = require('debug')('eventstore:store:mongodb');

function Mongo(options) {
  options = options || {};

  Store.call(this, options);

  var defaults = {
    host: 'localhost',
    port: 27017,
    dbName: 'eventstore',
    eventsCollectionName: 'events',
    snapshotsCollectionName: 'snapshots',
    transactionsCollectionName: 'transactions'//,
    // heartbeat: 60 * 1000
  };

  _.defaults(options, defaults);

  var defaultOpt = {
    auto_reconnect: false,
    ssl: false
  };

  options.options = options.options || {};

  _.defaults(options.options, defaultOpt);

  this.options = options;
}

util.inherits(Mongo, Store);

_.extend(Mongo.prototype, {

  connect: function (callback) {
    var self = this;

    var options = this.options;

    var connectionUrl;

    if (options.url) {
      connectionUrl = options.url;
    } else {
      var members = options.servers
        ? options.servers
        : [{host: options.host, port: options.port}];

      var memberString = _(members).map(function(m) { return m.host + ':' + m.port });
      var authString = options.username && options.password
        ? options.username + ':' + options.password
        : '';
      var optionsString = options.authSource
        ? '?authSource=' + options.authSource
        : '';

      connectionUrl = 'mongodb://' + authString + memberString + '/' + options.database + optionsString;
    }

    var client = new mongo.MongoClient();

    client.connect(connectionUrl, options.options, function(err, db) {
      if (err) {
        debug(err);
        if (callback) callback(err);
        return;
      }

      self.db = db;

      self.db.on('close', function() {
        self.emit('disconnect');
        self.stopHeartbeat();
      });

      function finish (err) {
        if (err) {
          debug(err);
          if (callback) callback(err);
          return;
        }

        self.events = self.db.collection(options.eventsCollectionName);
        self.events.ensureIndex({ aggregateId: 1, streamRevision: 1 },
          function (err) { if (err) { debug(err); } });
        self.events.ensureIndex({ commitStamp: 1 },
          function (err) { if (err) { debug(err); } });
        self.events.ensureIndex({ dispatched: 1 }, { sparse: true },
          function (err) { if (err) { debug(err); } });
        self.events.ensureIndex({ commitStamp: 1, streamRevision: 1, commitSequence: 1 },
          function (err) { if (err) { debug(err); } });

        self.snapshots = self.db.collection(options.snapshotsCollectionName);
        self.snapshots.ensureIndex({ aggregateId: 1, revision: -1 },
          function (err) { if (err) { debug(err); } });

        self.transactions = self.db.collection(options.transactionsCollectionName);
        self.transactions.ensureIndex({ aggregateId: 1, 'events.streamRevision': 1 },
          function (err) { if (err) { debug(err); } });

        self.emit('connect');
        if (self.options.heartbeat) {
          self.startHeartbeat();
        }
        if (callback) callback(null, self);
      }

      finish();
    });
  },

  stopHeartbeat: function () {
    if (this.heartbeatInterval) {
      clearInterval(this.heartbeatInterval);
      delete this.heartbeatInterval;
    }
  },

  startHeartbeat: function () {
    var self = this;

    var gracePeriod = Math.round(this.options.heartbeat / 2);
    this.heartbeatInterval = setInterval(function () {
      var graceTimer = setTimeout(function () {
        if (self.heartbeatInterval) {
          console.error((new Error ('Heartbeat timeouted after ' + gracePeriod + 'ms (mongodb)')).stack);
          self.disconnect();
        }
      }, gracePeriod);

      self.db.command({ ping: 1 }, function (err) {
        if (graceTimer) clearTimeout(graceTimer);
        if (err) {
          console.error(err.stack || err);
          self.db.close(function () {});
        }
      });
    }, this.options.heartbeat);
  },

  disconnect: function (callback) {
    this.stopHeartbeat();

    if (!this.db) {
      if (callback) callback(null);
      return;
    }

    this.db.close(function (err) {
      if (err) {
        debug(err);
      }
      if (callback) callback(err);
    });
  },

  clear: function (callback) {
    var self = this;
    async.parallel([
      function (callback) {
        self.events.remove({}, callback);
      },
      function (callback) {
        self.snapshots.remove({}, callback);
      },
      function (callback) {
        self.transactions.remove({}, callback);
      }
    ], function (err) {
      if (err) {
        debug(err);
      }
      if (callback) callback(err);
    });
  },

  getNewId: function(callback) {
    callback(null, new ObjectID().toString());
  },

  addEvents: function (events, callback) {
    if (events.length === 0) {
      if (callback) { callback(null); }
      return;
    }

    var commitId = events[0].commitId;

    var noAggregateId = false,
      invalidCommitId = false;

    _.forEach(events, function (evt) {
      if (!evt.aggregateId) {
        noAggregateId = true;
      }

      if (!evt.commitId || evt.commitId !== commitId) {
        invalidCommitId = true;
      }

      evt._id = evt.id;
      evt.dispatched = false;
    });

    if (noAggregateId) {
      var errMsg = 'aggregateId not defined!';
      debug(errMsg);
      if (callback) callback(new Error(errMsg));
      return;
    }

    if (invalidCommitId) {
      var errMsg = 'commitId not defined or different!';
      debug(errMsg);
      if (callback) callback(new Error(errMsg));
      return;
    }

    var self = this;

    if (events.length === 1) {
      return this.events.insert(events, callback);
    }

    var tx = {
      _id: commitId,
      events: events,
      aggregateId: events[0].aggregateId,
      aggregate: events[0].aggregate,
      context: events[0].context
    };

    this.transactions.insert(tx, function (err) {
      if (err) {
        debug(err);
        if (callback) callback(err);
        return;
      }

      self.events.insert(events, function (err) {
        if (err) {
          debug(err);
          if (callback) callback(err);
          return;
        }

        self.removeTransactions(events[events.length - 1]);

        if (callback) { callback(null); }
      });
    });
  },

  getEvents: function (query, skip, limit, callback) {
    var findStatement = {};

    if (query.aggregate) {
      findStatement.aggregate = query.aggregate;
    }

    if (query.context) {
      findStatement.context = query.context;
    }

    if (query.aggregateId) {
      findStatement.aggregateId = query.aggregateId;
    }

    if (limit === -1) {
      return this.events.find(findStatement, { sort: [['commitStamp', 'asc'], ['streamRevision', 'asc'], ['commitSequence', 'asc']] }).skip(skip).toArray(callback);
    }

    this.events.find(findStatement, { sort: [['commitStamp', 'asc'], ['streamRevision', 'asc'], ['commitSequence', 'asc']] }).skip(skip).limit(limit).toArray(callback);
  },

  getEventsSince: function (date, skip, limit, callback) {
    var findStatement = { commitStamp: { '$gte': date } };

    if (limit === -1) {
      return this.events.find(findStatement, { sort: [['commitStamp', 'asc'], ['streamRevision', 'asc'], ['commitSequence', 'asc']] }).skip(skip).toArray(callback);
    }

    this.events.find(findStatement, { sort: [['commitStamp', 'asc'], ['streamRevision', 'asc'], ['commitSequence', 'asc']] }).skip(skip).limit(limit).toArray(callback);
  },

  getEventsByRevision: function (query, revMin, revMax, callback) {
    if (!query.aggregateId) {
      var errMsg = 'aggregateId not defined!';
      debug(errMsg);
      if (callback) callback(new Error(errMsg));
      return;
    }

    var streamRevOptions = { '$gte': revMin, '$lt': revMax };
    if (revMax === -1) {
      streamRevOptions = { '$gte': revMin };
    }

    var findStatement = {
      aggregateId: query.aggregateId,
      streamRevision: streamRevOptions
    };

    if (query.aggregate) {
      findStatement.aggregate = query.aggregate;
    }

    if (query.context) {
      findStatement.context = query.context;
    }

    var self = this;

    this.events.find(findStatement, { sort: [['commitStamp', 'asc'], ['streamRevision', 'asc'], ['commitSequence', 'asc']] }).toArray(function (err, res) {
      if (err) {
        debug(err);
        return callback(err);
      }

      if (!res || res.length === 0) {
        return callback(null, []);
      }

      var lastEvt = res[res.length - 1];

      var txOk = (revMax === -1 && !lastEvt.restInCommitStream) ||
                 (revMax !== -1 && (lastEvt.streamRevision === revMax - 1 || !lastEvt.restInCommitStream));

      if (txOk) {
        // the following is usually unnecessary
        self.removeTransactions(lastEvt);

        return callback(null, res);
      }

      self.repairFailedTransaction(lastEvt, function (err) {
        if (err) {
          if (err.message.indexOf('missing tx entry') >= 0) {
            return callback(null, res);
          }
          debug(err);
          return callback(err);
        }

        self.getEventsByRevision(query, revMin, revMax, callback);
      });
    });
  },

  getUndispatchedEvents: function (query, callback) {
    var findStatement = {
      dispatched: false
    };

    if (query && query.aggregate) {
      findStatement.aggregate = query.aggregate;
    }

    if (query && query.context) {
      findStatement.context = query.context;
    }

    if (query && query.aggregateId) {
      findStatement.aggregateId = query.aggregateId;
    }

    this.events.find(findStatement, { sort: [['commitStamp', 'asc'], ['streamRevision', 'asc'], ['commitSequence', 'asc']] }).toArray(callback);
  },

  setEventToDispatched: function (id, callback) {
    var updateCommand = { '$unset' : { 'dispatched': null } };
    this.events.update({'_id' : id}, updateCommand, callback);
  },

  addSnapshot: function(snap, callback) {
    if (!snap.aggregateId) {
      var errMsg = 'aggregateId not defined!';
      debug(errMsg);
      if (callback) callback(new Error(errMsg));
      return;
    }

    snap._id = snap.id;
    this.snapshots.insert(snap, callback);
  },

  getSnapshot: function (query, revMax, callback) {
    if (!query.aggregateId) {
      var errMsg = 'aggregateId not defined!';
      debug(errMsg);
      if (callback) callback(new Error(errMsg));
      return;
    }

    var findStatement = {
      aggregateId: query.aggregateId
    };

    if (query.aggregate) {
      findStatement.aggregate = query.aggregate;
    }

    if (query.context) {
      findStatement.context = query.context;
    }

    if (revMax > -1) {
      findStatement.revision = { '$lte': revMax };
    }

    this.snapshots.findOne(findStatement, { sort: [['revision', 'desc'], ['version', 'desc'], ['commitStamp', 'desc']] }, callback);
  },

  removeTransactions: function (evt, callback) {
    if (!evt.aggregateId) {
      var errMsg = 'aggregateId not defined!';
      debug(errMsg);
      if (callback) callback(new Error(errMsg));
      return;
    }

    var findStatement = { aggregateId: evt.aggregateId };

    if (evt.aggregate) {
      findStatement.aggregate = evt.aggregate;
    }

    if (evt.context) {
      findStatement.context = evt.context;
    }

    // the following is usually unnecessary
    this.transactions.remove(findStatement, function (err) {
      if (err) {
        debug(err);
      }
      if (callback) { callback(err); }
    });
  },

  getPendingTransactions: function (callback) {
    var self = this;
    this.transactions.find({}).toArray(function (err, txs) {
      if (err) {
        debug(err);
        return callback(err);
      }

      if (txs.length === 0) {
        return callback(null, txs);
      }

      var goodTxs = [];

      async.map(txs, function (tx, clb) {
        var findStatement = { commitId: tx._id, aggregateId: tx.aggregateId };

        if (tx.aggregate) {
          findStatement.aggregate = tx.aggregate;
        }

        if (tx.context) {
          findStatement.context = tx.context;
        }

        self.events.findOne(findStatement, function (err, evt) {
          if (err) {
            return clb(err);
          }

          if (evt) {
            goodTxs.push(evt);
          } else {
            self.transactions.remove({ _id: tx._id }, function (err) {
              if (err) {
                debug(err);
              }
            });
          }

          clb(null);
        });
      }, function (err) {
        if (err) {
          debug(err);
          return callback(err);
        }

        callback(null, goodTxs);
      })
    });
  },

  getLastEvent: function (query, callback) {
    if (!query.aggregateId) {
      var errMsg = 'aggregateId not defined!';
      debug(errMsg);
      if (callback) callback(new Error(errMsg));
      return;
    }

    var findStatement = { aggregateId: query.aggregateId };

    if (query.aggregate) {
      findStatement.aggregate = query.aggregate;
    }

    if (query.context) {
      findStatement.context = query.context;
    }

    this.events.findOne(findStatement, { sort: [['commitStamp', 'desc'], ['streamRevision', 'desc'], ['commitSequence', 'desc']] }, callback);
  },

  repairFailedTransaction: function (lastEvt, callback) {
    var self = this;

    //var findStatement = {
    //  aggregateId: lastEvt.aggregateId,
    //  'events.streamRevision': lastEvt.streamRevision + 1
    //};
    //
    //if (lastEvt.aggregate) {
    //  findStatement.aggregate = lastEvt.aggregate;
    //}
    //
    //if (lastEvt.context) {
    //  findStatement.context = lastEvt.context;
    //}

    //this.transactions.findOne(findStatement, function (err, tx) {
    this.transactions.findOne({ _id: lastEvt.commitId }, function (err, tx) {
      if (err) {
        debug(err);
        return callback(err);
      }

      if (!tx) {
        var err = new Error('missing tx entry for aggregate ' + lastEvt.aggregateId);
        debug(err);
        return callback(err);
      }

      var missingEvts = tx.events.slice(tx.events.length - lastEvt.restInCommitStream);

      self.events.insert(missingEvts, function (err) {
        if (err) {
          debug(err);
          return callback(err);
        }

        self.removeTransactions(lastEvt);

        callback(null);
      });
    });
  }

});

module.exports = Mongo;
<commit_msg>fix auth string<commit_after>'use strict';

var util = require('util'),
  Store = require('../base'),
  _ = require('lodash'),
  async = require('async'),
  mongo = Store.use('mongodb'),
  mongoVersion = Store.use('mongodb/package.json').version,
  isNew = mongoVersion.indexOf('1.') !== 0,
  ObjectID = isNew ? mongo.ObjectID : mongo.BSONPure.ObjectID,
  debug = require('debug')('eventstore:store:mongodb');

function Mongo(options) {
  options = options || {};

  Store.call(this, options);

  var defaults = {
    host: 'localhost',
    port: 27017,
    dbName: 'eventstore',
    eventsCollectionName: 'events',
    snapshotsCollectionName: 'snapshots',
    transactionsCollectionName: 'transactions'//,
    // heartbeat: 60 * 1000
  };

  _.defaults(options, defaults);

  var defaultOpt = {
    auto_reconnect: false,
    ssl: false
  };

  options.options = options.options || {};

  _.defaults(options.options, defaultOpt);

  this.options = options;
}

util.inherits(Mongo, Store);

_.extend(Mongo.prototype, {

  connect: function (callback) {
    var self = this;

    var options = this.options;

    var connectionUrl;

    if (options.url) {
      connectionUrl = options.url;
    } else {
      var members = options.servers
        ? options.servers
        : [{host: options.host, port: options.port}];

      var memberString = _(members).map(function(m) { return m.host + ':' + m.port });
      var authString = options.username && options.password
        ? options.username + ':' + options.password + '@'
        : '';
      var optionsString = options.authSource
        ? '?authSource=' + options.authSource
        : '';

      connectionUrl = 'mongodb://' + authString + memberString + '/' + options.dbName + optionsString;
    }

    var client = new mongo.MongoClient();

    client.connect(connectionUrl, options.options, function(err, db) {
      if (err) {
        debug(err);
        if (callback) callback(err);
        return;
      }

      self.db = db;

      self.db.on('close', function() {
        self.emit('disconnect');
        self.stopHeartbeat();
      });

      function finish (err) {
        if (err) {
          debug(err);
          if (callback) callback(err);
          return;
        }

        self.events = self.db.collection(options.eventsCollectionName);
        self.events.ensureIndex({ aggregateId: 1, streamRevision: 1 },
          function (err) { if (err) { debug(err); } });
        self.events.ensureIndex({ commitStamp: 1 },
          function (err) { if (err) { debug(err); } });
        self.events.ensureIndex({ dispatched: 1 }, { sparse: true },
          function (err) { if (err) { debug(err); } });
        self.events.ensureIndex({ commitStamp: 1, streamRevision: 1, commitSequence: 1 },
          function (err) { if (err) { debug(err); } });

        self.snapshots = self.db.collection(options.snapshotsCollectionName);
        self.snapshots.ensureIndex({ aggregateId: 1, revision: -1 },
          function (err) { if (err) { debug(err); } });

        self.transactions = self.db.collection(options.transactionsCollectionName);
        self.transactions.ensureIndex({ aggregateId: 1, 'events.streamRevision': 1 },
          function (err) { if (err) { debug(err); } });

        self.emit('connect');
        if (self.options.heartbeat) {
          self.startHeartbeat();
        }
        if (callback) callback(null, self);
      }

      finish();
    });
  },

  stopHeartbeat: function () {
    if (this.heartbeatInterval) {
      clearInterval(this.heartbeatInterval);
      delete this.heartbeatInterval;
    }
  },

  startHeartbeat: function () {
    var self = this;

    var gracePeriod = Math.round(this.options.heartbeat / 2);
    this.heartbeatInterval = setInterval(function () {
      var graceTimer = setTimeout(function () {
        if (self.heartbeatInterval) {
          console.error((new Error ('Heartbeat timeouted after ' + gracePeriod + 'ms (mongodb)')).stack);
          self.disconnect();
        }
      }, gracePeriod);

      self.db.command({ ping: 1 }, function (err) {
        if (graceTimer) clearTimeout(graceTimer);
        if (err) {
          console.error(err.stack || err);
          self.db.close(function () {});
        }
      });
    }, this.options.heartbeat);
  },

  disconnect: function (callback) {
    this.stopHeartbeat();

    if (!this.db) {
      if (callback) callback(null);
      return;
    }

    this.db.close(function (err) {
      if (err) {
        debug(err);
      }
      if (callback) callback(err);
    });
  },

  clear: function (callback) {
    var self = this;
    async.parallel([
      function (callback) {
        self.events.remove({}, callback);
      },
      function (callback) {
        self.snapshots.remove({}, callback);
      },
      function (callback) {
        self.transactions.remove({}, callback);
      }
    ], function (err) {
      if (err) {
        debug(err);
      }
      if (callback) callback(err);
    });
  },

  getNewId: function(callback) {
    callback(null, new ObjectID().toString());
  },

  addEvents: function (events, callback) {
    if (events.length === 0) {
      if (callback) { callback(null); }
      return;
    }

    var commitId = events[0].commitId;

    var noAggregateId = false,
      invalidCommitId = false;

    _.forEach(events, function (evt) {
      if (!evt.aggregateId) {
        noAggregateId = true;
      }

      if (!evt.commitId || evt.commitId !== commitId) {
        invalidCommitId = true;
      }

      evt._id = evt.id;
      evt.dispatched = false;
    });

    if (noAggregateId) {
      var errMsg = 'aggregateId not defined!';
      debug(errMsg);
      if (callback) callback(new Error(errMsg));
      return;
    }

    if (invalidCommitId) {
      var errMsg = 'commitId not defined or different!';
      debug(errMsg);
      if (callback) callback(new Error(errMsg));
      return;
    }

    var self = this;

    if (events.length === 1) {
      return this.events.insert(events, callback);
    }

    var tx = {
      _id: commitId,
      events: events,
      aggregateId: events[0].aggregateId,
      aggregate: events[0].aggregate,
      context: events[0].context
    };

    this.transactions.insert(tx, function (err) {
      if (err) {
        debug(err);
        if (callback) callback(err);
        return;
      }

      self.events.insert(events, function (err) {
        if (err) {
          debug(err);
          if (callback) callback(err);
          return;
        }

        self.removeTransactions(events[events.length - 1]);

        if (callback) { callback(null); }
      });
    });
  },

  getEvents: function (query, skip, limit, callback) {
    var findStatement = {};

    if (query.aggregate) {
      findStatement.aggregate = query.aggregate;
    }

    if (query.context) {
      findStatement.context = query.context;
    }

    if (query.aggregateId) {
      findStatement.aggregateId = query.aggregateId;
    }

    if (limit === -1) {
      return this.events.find(findStatement, { sort: [['commitStamp', 'asc'], ['streamRevision', 'asc'], ['commitSequence', 'asc']] }).skip(skip).toArray(callback);
    }

    this.events.find(findStatement, { sort: [['commitStamp', 'asc'], ['streamRevision', 'asc'], ['commitSequence', 'asc']] }).skip(skip).limit(limit).toArray(callback);
  },

  getEventsSince: function (date, skip, limit, callback) {
    var findStatement = { commitStamp: { '$gte': date } };

    if (limit === -1) {
      return this.events.find(findStatement, { sort: [['commitStamp', 'asc'], ['streamRevision', 'asc'], ['commitSequence', 'asc']] }).skip(skip).toArray(callback);
    }

    this.events.find(findStatement, { sort: [['commitStamp', 'asc'], ['streamRevision', 'asc'], ['commitSequence', 'asc']] }).skip(skip).limit(limit).toArray(callback);
  },

  getEventsByRevision: function (query, revMin, revMax, callback) {
    if (!query.aggregateId) {
      var errMsg = 'aggregateId not defined!';
      debug(errMsg);
      if (callback) callback(new Error(errMsg));
      return;
    }

    var streamRevOptions = { '$gte': revMin, '$lt': revMax };
    if (revMax === -1) {
      streamRevOptions = { '$gte': revMin };
    }

    var findStatement = {
      aggregateId: query.aggregateId,
      streamRevision: streamRevOptions
    };

    if (query.aggregate) {
      findStatement.aggregate = query.aggregate;
    }

    if (query.context) {
      findStatement.context = query.context;
    }

    var self = this;

    this.events.find(findStatement, { sort: [['commitStamp', 'asc'], ['streamRevision', 'asc'], ['commitSequence', 'asc']] }).toArray(function (err, res) {
      if (err) {
        debug(err);
        return callback(err);
      }

      if (!res || res.length === 0) {
        return callback(null, []);
      }

      var lastEvt = res[res.length - 1];

      var txOk = (revMax === -1 && !lastEvt.restInCommitStream) ||
                 (revMax !== -1 && (lastEvt.streamRevision === revMax - 1 || !lastEvt.restInCommitStream));

      if (txOk) {
        // the following is usually unnecessary
        self.removeTransactions(lastEvt);

        return callback(null, res);
      }

      self.repairFailedTransaction(lastEvt, function (err) {
        if (err) {
          if (err.message.indexOf('missing tx entry') >= 0) {
            return callback(null, res);
          }
          debug(err);
          return callback(err);
        }

        self.getEventsByRevision(query, revMin, revMax, callback);
      });
    });
  },

  getUndispatchedEvents: function (query, callback) {
    var findStatement = {
      dispatched: false
    };

    if (query && query.aggregate) {
      findStatement.aggregate = query.aggregate;
    }

    if (query && query.context) {
      findStatement.context = query.context;
    }

    if (query && query.aggregateId) {
      findStatement.aggregateId = query.aggregateId;
    }

    this.events.find(findStatement, { sort: [['commitStamp', 'asc'], ['streamRevision', 'asc'], ['commitSequence', 'asc']] }).toArray(callback);
  },

  setEventToDispatched: function (id, callback) {
    var updateCommand = { '$unset' : { 'dispatched': null } };
    this.events.update({'_id' : id}, updateCommand, callback);
  },

  addSnapshot: function(snap, callback) {
    if (!snap.aggregateId) {
      var errMsg = 'aggregateId not defined!';
      debug(errMsg);
      if (callback) callback(new Error(errMsg));
      return;
    }

    snap._id = snap.id;
    this.snapshots.insert(snap, callback);
  },

  getSnapshot: function (query, revMax, callback) {
    if (!query.aggregateId) {
      var errMsg = 'aggregateId not defined!';
      debug(errMsg);
      if (callback) callback(new Error(errMsg));
      return;
    }

    var findStatement = {
      aggregateId: query.aggregateId
    };

    if (query.aggregate) {
      findStatement.aggregate = query.aggregate;
    }

    if (query.context) {
      findStatement.context = query.context;
    }

    if (revMax > -1) {
      findStatement.revision = { '$lte': revMax };
    }

    this.snapshots.findOne(findStatement, { sort: [['revision', 'desc'], ['version', 'desc'], ['commitStamp', 'desc']] }, callback);
  },

  removeTransactions: function (evt, callback) {
    if (!evt.aggregateId) {
      var errMsg = 'aggregateId not defined!';
      debug(errMsg);
      if (callback) callback(new Error(errMsg));
      return;
    }

    var findStatement = { aggregateId: evt.aggregateId };

    if (evt.aggregate) {
      findStatement.aggregate = evt.aggregate;
    }

    if (evt.context) {
      findStatement.context = evt.context;
    }

    // the following is usually unnecessary
    this.transactions.remove(findStatement, function (err) {
      if (err) {
        debug(err);
      }
      if (callback) { callback(err); }
    });
  },

  getPendingTransactions: function (callback) {
    var self = this;
    this.transactions.find({}).toArray(function (err, txs) {
      if (err) {
        debug(err);
        return callback(err);
      }

      if (txs.length === 0) {
        return callback(null, txs);
      }

      var goodTxs = [];

      async.map(txs, function (tx, clb) {
        var findStatement = { commitId: tx._id, aggregateId: tx.aggregateId };

        if (tx.aggregate) {
          findStatement.aggregate = tx.aggregate;
        }

        if (tx.context) {
          findStatement.context = tx.context;
        }

        self.events.findOne(findStatement, function (err, evt) {
          if (err) {
            return clb(err);
          }

          if (evt) {
            goodTxs.push(evt);
          } else {
            self.transactions.remove({ _id: tx._id }, function (err) {
              if (err) {
                debug(err);
              }
            });
          }

          clb(null);
        });
      }, function (err) {
        if (err) {
          debug(err);
          return callback(err);
        }

        callback(null, goodTxs);
      })
    });
  },

  getLastEvent: function (query, callback) {
    if (!query.aggregateId) {
      var errMsg = 'aggregateId not defined!';
      debug(errMsg);
      if (callback) callback(new Error(errMsg));
      return;
    }

    var findStatement = { aggregateId: query.aggregateId };

    if (query.aggregate) {
      findStatement.aggregate = query.aggregate;
    }

    if (query.context) {
      findStatement.context = query.context;
    }

    this.events.findOne(findStatement, { sort: [['commitStamp', 'desc'], ['streamRevision', 'desc'], ['commitSequence', 'desc']] }, callback);
  },

  repairFailedTransaction: function (lastEvt, callback) {
    var self = this;

    //var findStatement = {
    //  aggregateId: lastEvt.aggregateId,
    //  'events.streamRevision': lastEvt.streamRevision + 1
    //};
    //
    //if (lastEvt.aggregate) {
    //  findStatement.aggregate = lastEvt.aggregate;
    //}
    //
    //if (lastEvt.context) {
    //  findStatement.context = lastEvt.context;
    //}

    //this.transactions.findOne(findStatement, function (err, tx) {
    this.transactions.findOne({ _id: lastEvt.commitId }, function (err, tx) {
      if (err) {
        debug(err);
        return callback(err);
      }

      if (!tx) {
        var err = new Error('missing tx entry for aggregate ' + lastEvt.aggregateId);
        debug(err);
        return callback(err);
      }

      var missingEvts = tx.events.slice(tx.events.length - lastEvt.restInCommitStream);

      self.events.insert(missingEvts, function (err) {
        if (err) {
          debug(err);
          return callback(err);
        }

        self.removeTransactions(lastEvt);

        callback(null);
      });
    });
  }

});

module.exports = Mongo;
<|endoftext|>


<commit_before><commit_msg>Modefied Test.<commit_after><|endoftext|>


<commit_before>(function(module, define) {

function inferScriptType(filename) {
  var mime = mimeForFilename(filename);
  if (/^text\/x-pencilcode/.test(mime)) {
    mime = 'text/coffeescript';
  }
  // Script type attributes do not understand encoding.
  return mime.replace(/;.*$/, '');
}

function wrapTurtle(doc, domain, pragmasOnly, setupScript) {
  var result, j, scripts = [], script_pattern =
    /(?:^|\n)#[^\S\n]*@script[^\S\n<>]+(\S+|"[^"\n]*"|'[^'\n]*')/g,
    text = doc.data,
    meta = effectiveMeta(doc.meta), src;
  // Add the default scripts.
  for (j = 0; j < meta.libs.length; ++j) {
    var src = meta.libs[j].src;
    if (/{site}/.test(src)) {
      src = src.replace(/{site}/g, domain);
      // Note that for local scripts we use crossorigin="anonymous" so that
      // we can get // more detailed error information (e.g., CoffeeScript
      // compilation // errors, using CORS rules.)  More discussion:
      // http://blog.errorception.com/2012/12/catching-cross-domain-js-errors.html
      scripts.push(
        '