<commit_before>/*global test, ok, equal, deepEqual, _, Supermodel */

test( 'Supermodel exists and is a function', function() {
	ok( Supermodel !== undefined );
	ok( _.isFunction( Supermodel ) );
});

test( 'Model instance has following methods: get, set, observe, unobserve', function () {
	var model = new Supermodel();

	ok( _.isFunction( model.get ) );
	ok( _.isFunction( model.set ) );
	ok( _.isFunction( model.observe ) );
	ok( _.isFunction( model.unobserve ) );
});

test( 'Model instance has empty _data and _observers members', function () {
	var model = new Supermodel();

	ok( _.isObject( model._data ) && _.isEmpty( model._data ) );
	ok( _.isObject( model._observers ) && _.isEmpty( model._observers ) );
});

test( 'Model stores data passed in at initialization on the _data member', function () {
	var data = { foo: 'bar' }, model = new Supermodel( data );

	equal( data, model._data );
});

test( 'Data passed in at initialization can be read with .get()', function () {
	var data = { foo: 'bar' }, model = new Supermodel( data );

	equal( data.foo, model.get( 'foo' ) );
});

test( 'Data can be set using .set() and got using .get()', function () {
	var model = new Supermodel();

	model.set( 'foo', 'bar' );
	equal( model.get( 'foo' ), 'bar' );
});

test( '.get() will fetch nested data', function () {
	var data = { foo: { bar: 'baz' } }, model = new Supermodel( data );

	equal( model.get( 'foo.bar' ), 'baz' );
});

test( '.set() will set nested data', function () {
	var model = new Supermodel();

	model.set( 'foo.bar', 'baz' );

	deepEqual( model._data, { foo: { bar: 'baz' } } );
});

test( '.set() and .get() will work with array or dot notation for numbers', function () {
	var model = new Supermodel();

	model.set( 'foo.bar[0]', 'baz' );
	deepEqual( model._data, { foo: { bar: [ 'baz' ] } } );

	equal( model.get( 'foo.bar[0]' ), 'baz' );
	equal( model.get( 'foo.bar.0' ), 'baz' );
});

test( '.observe() returns an array of observers', function () {
	var model = new Supermodel(), observers;

	observers = model.observe( 'foo', function () {} );
	ok( _.isArray( observers ) && observers[0] );
});

test( 'An observer has: observedKeypath, originalKeypath, callback, previousValue', function () {
	var model, callback, observers, observer;

	model = new Supermodel({
		foo: 'bar'
	});

	callback = function () {};

	observers = model.observe( 'foo', callback );
	observer = observers[0];

	equal( observer.observedKeypath, 'foo' );
	equal( observer.originalKeypath, 'foo' );
	equal( observer.callback, callback );
	equal( observer.previousValue, 'bar' );
});

test( 'Observing "foo" adds an observer to model._observers.foo', function () {
	var model = new Supermodel(), callback = function () {}, observer;

	model.observe( 'foo', callback );
	ok( _.isArray( model._observers.foo ) );
	ok( _.isObject( model._observers.foo[0] ) );

	observer = model._observers.foo[0];

	equal( callback, observer.callback );
});

test( 'Observing "foo", then setting "foo", triggers the callback', function () {
	var model = new Supermodel(), value;

	model.observe( 'foo', function ( val ) {
		value = val;
	});

	model.set( 'foo', 'bar' );
	equal( value, 'bar' );
});

test( 'Observing "foo", then setting "foo" silently, does not trigger the callback', function () {
	var model = new Supermodel(), value;

	model.observe( 'foo', function ( val ) {
		value = val;
	});

	model.set( 'foo', 'bar', true ); // silent=true
	equal( value, undefined );
});

test( 'Observers can be cancelled', function () {
	var model, observers, triggered = 0;

	model = new Supermodel({
		foo: 'bar'
	});

	observers = model.observe( 'foo', function () {
		triggered += 1;
	});

	model.set( 'foo', 'baz' );

	model.unobserve( observers );
	model.set( 'foo', 'bar' );

	equal( triggered, 1 );
});

test( 'Setting an item only triggers callbacks if the value changes', function () {
	var model = new Supermodel(), i = 0;

	model.observe( 'foo', function () {
		i += 1;
	});

	model.set( 'foo', 'bar' );
	model.set( 'foo', 'bar' );

	equal( i, 1 );
});

test( 'Setting an item with force=true triggers callbacks even if there is no change', function () {
	var model = new Supermodel(), i = 0;

	model.observe( 'foo', function () {
		i += 1;
	});

	model.set( 'foo', 'bar', null, true ); // force=true
	model.set( 'foo', 'bar', null, true );

	equal( i, 2 );
});

test( 'Silent > force', function () {
	var model = new Supermodel(), i = 0;

	model.observe( 'foo', function () {
		i += 1;
	});

	model.set( 'foo', 'bar', true, true );
	model.set( 'foo', 'bar', true, true );

	equal( i, 0 );
});

test( 'Callbacks are passed both new and previous value', function () {
	var model = new Supermodel(), oldValue, newValue;

	model.observe( 'foo', function ( n, o ) {
		newValue = n;
		oldValue = o;
	});

	model.set( 'foo', 'bar' );
	equal( newValue, 'bar' );
	equal( oldValue, undefined );

	model.set( 'foo', 'baz' );
	equal( newValue, 'baz' );
	equal( oldValue, 'bar' );
});

test( 'Setting a value causes downstream observers to be notified', function () {
	var model = new Supermodel(), value;

	model.observe( 'foo.bar', function ( val ) {
		value = val;
	});

	model.set( 'foo', { bar: 'baz' } );

	equal( value, 'baz' );
});

test( 'Setting "foo.bar[0]" or "foo.bar.0" on an empty model causes foo.bar to be initialised as an array', function () {
	var model = new Supermodel();

	model.set( 'foo.bar[0]', 'baz' );
	ok( _.isArray( model.get( 'foo.bar' ) ) );

	model.set( 'bar.baz.0', 'foo' );
	ok( _.isArray( model.get( 'bar.baz' ) ) );
});

test( 'Setting multiple keypaths in one go', function () {
	var model = new Supermodel();

	model.set({
		one: 1,
		two: 2,
		three: 3,
		'foo.bar[0]': 'baz'
	});

	equal( model.get( 'one' ), 1 );
	equal( model.get( 'two' ), 2 );
	equal( model.get( 'three' ), 3 );
	equal( model.get( 'foo.bar[0]' ), 'baz' );
});

test( 'Notifications are skipped for values that haven\'t changed when upstream values change', function () {
	var triggered, model = new Supermodel({
		foo: {
			a: 1,
			b: 2,
			bar: 'baz'
		}
	});

	model.observe( 'foo.bar', function () {
		triggered = true;
	});

	model.set( 'foo', { c: 3, d: 4, bar: 'baz' } );

	ok( !triggered );
});<commit_msg>updated tests<commit_after>/*global test, ok, equal, deepEqual, _, Supermodel */

test( 'Supermodel exists and is a function', function() {
	ok( Supermodel !== undefined );
	ok( _.isFunction( Supermodel ) );
});

test( 'Model instance has following methods: get, set, observe, unobserve', function () {
	var model = new Supermodel();

	ok( _.isFunction( model.get ) );
	ok( _.isFunction( model.set ) );
	ok( _.isFunction( model.observe ) );
	ok( _.isFunction( model.unobserve ) );
});

test( 'Model instance has empty _data and _observers members', function () {
	var model = new Supermodel();

	ok( _.isObject( model._data ) && _.isEmpty( model._data ) );
	ok( _.isObject( model._observers ) && _.isEmpty( model._observers ) );
});

test( 'Model stores data passed in at initialization on the _data member', function () {
	var data = { foo: 'bar' }, model = new Supermodel( data );

	equal( data, model._data );
});

test( 'Data passed in at initialization can be read with .get()', function () {
	var data = { foo: 'bar' }, model = new Supermodel( data );

	equal( data.foo, model.get( 'foo' ) );
});

test( 'Data can be set using .set() and got using .get()', function () {
	var model = new Supermodel();

	model.set( 'foo', 'bar' );
	equal( model.get( 'foo' ), 'bar' );
});

test( '.get() will fetch nested data', function () {
	var data = { foo: { bar: 'baz' } }, model = new Supermodel( data );

	equal( model.get( 'foo.bar' ), 'baz' );
});

test( '.set() will set nested data', function () {
	var model = new Supermodel();

	model.set( 'foo.bar', 'baz' );

	deepEqual( model._data, { foo: { bar: 'baz' } } );
});

test( '.set() and .get() will work with array or dot notation for numbers', function () {
	var model = new Supermodel();

	model.set( 'foo.bar[0]', 'baz' );
	deepEqual( model._data, { foo: { bar: [ 'baz' ] } } );

	equal( model.get( 'foo.bar[0]' ), 'baz' );
	equal( model.get( 'foo.bar.0' ), 'baz' );
});

test( '.observe() returns an array of observers', function () {
	var model = new Supermodel(), observers;

	observers = model.observe( 'foo', function () {} );
	ok( _.isArray( observers ) && observers[0] );
});

test( 'An observer has: observedKeypath, originalKeypath, callback, group', function () {
	var model, callback, observers, observer;

	model = new Supermodel({
		foo: 'bar'
	});

	callback = function () {};

	observers = model.observe( 'foo', callback );
	observer = observers[0];

	equal( observer.observedKeypath, 'foo' );
	equal( observer.originalKeypath, 'foo' );
	equal( observer.callback, callback );
	equal( observer.group, observers );
});

test( 'Observing "foo" adds an observer to model._observers.foo', function () {
	var model = new Supermodel(), callback = function () {}, observer;

	model.observe( 'foo', callback );
	ok( _.isArray( model._observers.foo ) );
	ok( _.isObject( model._observers.foo[0] ) );

	observer = model._observers.foo[0];

	equal( callback, observer.callback );
});

test( 'Observing "foo", then setting "foo", triggers the callback', function () {
	var model = new Supermodel(), value;

	model.observe( 'foo', function ( val ) {
		value = val;
	});

	model.set( 'foo', 'bar' );
	equal( value, 'bar' );
});

test( 'Observing "foo", then setting "foo" silently, does not trigger the callback', function () {
	var model = new Supermodel(), value;

	model.observe( 'foo', function ( val ) {
		value = val;
	});

	model.set( 'foo', 'bar', true ); // silent=true
	equal( value, undefined );
});

test( 'Observers can be cancelled', function () {
	var model, observers, triggered = 0;

	model = new Supermodel({
		foo: 'bar'
	});

	observers = model.observe( 'foo', function () {
		triggered += 1;
	});

	model.set( 'foo', 'baz' );

	model.unobserve( observers );
	model.set( 'foo', 'bar' );

	equal( triggered, 1 );
});

test( 'Setting an item only triggers callbacks if the value changes', function () {
	var model = new Supermodel(), i = 0;

	model.observe( 'foo', function () {
		i += 1;
	});

	model.set( 'foo', 'bar' );
	model.set( 'foo', 'bar' );

	equal( i, 1 );
});

test( 'Setting an item with force=true triggers callbacks even if there is no change', function () {
	var model = new Supermodel(), i = 0;

	model.observe( 'foo', function () {
		i += 1;
	});

	model.set( 'foo', 'bar', null, true ); // force=true
	model.set( 'foo', 'bar', null, true );

	equal( i, 2 );
});

test( 'Silent > force', function () {
	var model = new Supermodel(), i = 0;

	model.observe( 'foo', function () {
		i += 1;
	});

	model.set( 'foo', 'bar', true, true );
	model.set( 'foo', 'bar', true, true );

	equal( i, 0 );
});

test( 'Callbacks are passed both new and previous value', function () {
	var model = new Supermodel(), oldValue, newValue;

	model.observe( 'foo', function ( n, o ) {
		newValue = n;
		oldValue = o;
	});

	model.set( 'foo', 'bar' );
	equal( newValue, 'bar' );
	equal( oldValue, undefined );

	model.set( 'foo', 'baz' );
	equal( newValue, 'baz' );
	equal( oldValue, 'bar' );
});

test( 'Setting a value causes downstream observers to be notified', function () {
	var model = new Supermodel(), value;

	model.observe( 'foo.bar', function ( val ) {
		value = val;
	});

	model.set( 'foo', { bar: 'baz' } );

	equal( value, 'baz' );
});

test( 'Setting "foo.bar[0]" or "foo.bar.0" on an empty model causes foo.bar to be initialised as an array', function () {
	var model = new Supermodel();

	model.set( 'foo.bar[0]', 'baz' );
	ok( _.isArray( model.get( 'foo.bar' ) ) );

	model.set( 'bar.baz.0', 'foo' );
	ok( _.isArray( model.get( 'bar.baz' ) ) );
});

test( 'Setting multiple keypaths in one go', function () {
	var model = new Supermodel();

	model.set({
		one: 1,
		two: 2,
		three: 3,
		'foo.bar[0]': 'baz'
	});

	equal( model.get( 'one' ), 1 );
	equal( model.get( 'two' ), 2 );
	equal( model.get( 'three' ), 3 );
	equal( model.get( 'foo.bar[0]' ), 'baz' );
});

test( 'Notifications are skipped for values that haven\'t changed when upstream values change', function () {
	var triggered, model = new Supermodel({
		foo: {
			a: 1,
			b: 2,
			bar: 'baz'
		}
	});

	model.observe( 'foo.bar', function () {
		triggered = true;
	});

	model.set( 'foo', { c: 3, d: 4, bar: 'baz' } );

	ok( !triggered );
});<|endoftext|>


<commit_before>'use strict';

const colorJS = require('color');

exports.decorateConfig = config => {
  const materialBox = Object.assign(
      {
        scheme: 'solarized-dark',
        backgroundOpacity: 1,
        backgroundVibrancy: false,
        closeOnTheLeft: false,
        activeTabStyle: 'underline',
        lightEffect: false,
      },
      config.materialBox);

  materialBox.user = Object.assign(
      {
        colors: config.colors,
        backgroundColor: config.backgroundColor,
        foregroundColor: config.foregroundColor,
        cursorColor: config.cursorColor,
        borderColor: config.borderColor,
        accentColor: config.colors.blue,
        inactiveTabTitleColor: config.inactiveTabTitleColor ||
            colorJS(config.foregroundColor).alpha(0.3).string(),
        activeTabTitleColor:
            config.activeTabTitleColor || config.foregroundColor,
      },
      (config.materialBox ? config.materialBox.user : {}));

  // Get scheme
  const schemeIndex = {
    // material-box schemes
    'dracula': require('./scheme/dracula.js'),
    'material-darker': require('./scheme/material-darker.js'),
    'material-lighter': require('./scheme/material-lighter.js'),
    'material': require('./scheme/material.js'),
    'monokai': require('./scheme/monokai.js'),
    'solarized-dark': require('./scheme/solarized_dark.js'),
    'solarized-light': require('./scheme/solarized_light.js'),
    'tomorrow-night-blue': require('./scheme/tomorrow-night-blue.js'),
    'tomorrow-night-bright': require('./scheme/tomorrow-night-bright.js'),
    'tomorrow-night-eighties': require('./scheme/tomorrow-night-eighties.js'),
    'tomorrow-night': require('./scheme/tomorrow-night.js'),
    'tomorrow': require('./scheme/tomorrow.js'),

    // user-defined scheme
    'user': materialBox.user,
  };
  const scheme = Object.assign(
      schemeIndex[materialBox.scheme.toLowerCase()] ||
          schemeIndex['solarized-dark'],
      (config.materialBox ? config.materialBox.user : {}));

  // Background opacity
  scheme.backgroundColor = colorJS(scheme.backgroundColor)
                               .alpha(materialBox.backgroundOpacity)
                               .string();
  // Background vibrancy
  if (materialBox.backgroundVibrancy === true) {
    if (colorJS(scheme.backgroundColor).light() === true) {
      exports.onWindow = browserWindow => browserWindow.setVibrancy('light');
    } else {
      exports.onWindow = browserWindow => browserWindow.setVibrancy('dark');
    }
  }

  // Active tab style
  const lightEffect =
      (materialBox.lightEffect ? `box-shadow: 0 0 10px ${scheme.accentColor};` :
                                 '');
  let tabStyle = '';
  switch (materialBox.activeTabStyle.toLowerCase()) {
    case 'preline':
      tabStyle = `
        .tab_tab::after {
          content: "";
          position: absolute;
          pointer-events: none;
          top: 0;
          bottom: -1px;
          left: 0;
          width: 2px;
          height: inherit;
          background: ${scheme.accentColor};
          opacity: 0;
          transition: opacity .16s;
          z-index: 1;
          ${lightEffect}
        }
        .tab_tab.tab_active::after {
          opacity: 1;
          transition-duration: .32s;
          ${lightEffect}
        }`;
      break;
    case 'overline':
      tabStyle = `
      .tab_tab.tab_active {
        border-top: 2px solid ${scheme.accentColor} !important;
      }`;
      break;
    case 'filled':
      tabStyle = `
        .tab_tab.tab_active,
        .tabs_title {
          background: ${scheme.accentColor};
          ${lightEffect}
        }`;
      break;
    default:
      tabStyle = `
        .tab_tab::before {
          content: '';
          position: absolute;
          bottom: 0;
          left: 0;
          right: 0;
          height: 2px;
          background-color: ${scheme.accentColor};
          transform: scaleX(0);
          transition: none;
          ${lightEffect}
        }`;
      break;
  }

  return Object.assign({}, config, {
    colors: scheme.colors,
    backgroundColor: scheme.backgroundColor,
    foregroundColor: scheme.foregroundColor,
    borderColor: scheme.borderColor,
    cursorColor: scheme.cursorColor,
    css: `
    .tab_tab {
      border: none;
      color: ${scheme.inactiveTabTitleColor};
    }
    .tab_tab.tab_active {
      color: ${scheme.activeTabTitleColor};
    }
    .tabs_title {
      color: ${scheme.activeTabTitleColor};
    }
    .hyper_main {
      border: none;
    }
    .tabs_borderShim {
      display: none;
    }
    .tab_tab.tab_active::before {
      transform: scaleX(1);
      transition: all 300ms cubic-bezier(0.0, 0.0, 0.2, 1)
    }
    .tab_textInner {
      text-overflow: ellipsis;
      overflow: hidden;
      max-width: 100%;
      padding: 0px 24px 0 8px;
    }
    .tabs_nav .tab_tab .tab_icon {
      left: 5px;
      right: auto;
      top: 4px;
      border-radius: 2px;
    }
    ${tabStyle}
    ${
      materialBox.closeOnTheLeft === true ?
          '.tab_tab .tab_icon { left: 7px; right: initial; }' :
          ''
    }
    ${config.css || ''}
    `,
    termCSS: `
    ::-webkit-scrollbar {
      width: 2px;
    }
    ::-webkit-scrollbar-thumb {
      border-radius: 0px;
      background-color: ${scheme.accentColor};
    }
    x-screen x-row { font-variant-ligatures: contextual; }
    ${config.termCSS || ''}
    `,
  });
};
<commit_msg>:wrench: Reorder the schemeIndex<commit_after>'use strict';

const colorJS = require('color');

exports.decorateConfig = config => {
  const materialBox = Object.assign(
      {
        scheme: 'solarized-dark',
        backgroundOpacity: 1,
        backgroundVibrancy: false,
        closeOnTheLeft: false,
        activeTabStyle: 'underline',
        lightEffect: false,
      },
      config.materialBox);

  materialBox.user = Object.assign(
      {
        colors: config.colors,
        backgroundColor: config.backgroundColor,
        foregroundColor: config.foregroundColor,
        cursorColor: config.cursorColor,
        borderColor: config.borderColor,
        accentColor: config.colors.blue,
        inactiveTabTitleColor: config.inactiveTabTitleColor ||
            colorJS(config.foregroundColor).alpha(0.3).string(),
        activeTabTitleColor:
            config.activeTabTitleColor || config.foregroundColor,
      },
      (config.materialBox ? config.materialBox.user : {}));

  // Get scheme
  const schemeIndex = {
    // material-box schemes
    'dracula': require('./scheme/dracula.js'),
    'material': require('./scheme/material.js'),
    'material-darker': require('./scheme/material-darker.js'),
    'material-lighter': require('./scheme/material-lighter.js'),
    'monokai': require('./scheme/monokai.js'),
    'solarized-dark': require('./scheme/solarized_dark.js'),
    'solarized-light': require('./scheme/solarized_light.js'),
    'tomorrow': require('./scheme/tomorrow.js'),
    'tomorrow-night': require('./scheme/tomorrow-night.js'),
    'tomorrow-night-blue': require('./scheme/tomorrow-night-blue.js'),
    'tomorrow-night-bright': require('./scheme/tomorrow-night-bright.js'),
    'tomorrow-night-eighties': require('./scheme/tomorrow-night-eighties.js'),

    // user-defined scheme
    'user': materialBox.user,
  };
  const scheme = Object.assign(
      schemeIndex[materialBox.scheme.toLowerCase()] ||
          schemeIndex['solarized-dark'],
      (config.materialBox ? config.materialBox.user : {}));

  // Background opacity
  scheme.backgroundColor = colorJS(scheme.backgroundColor)
                               .alpha(materialBox.backgroundOpacity)
                               .string();
  // Background vibrancy
  if (materialBox.backgroundVibrancy === true) {
    if (colorJS(scheme.backgroundColor).light() === true) {
      exports.onWindow = browserWindow => browserWindow.setVibrancy('light');
    } else {
      exports.onWindow = browserWindow => browserWindow.setVibrancy('dark');
    }
  }

  // Active tab style
  const lightEffect =
      (materialBox.lightEffect ? `box-shadow: 0 0 10px ${scheme.accentColor};` :
                                 '');
  let tabStyle = '';
  switch (materialBox.activeTabStyle.toLowerCase()) {
    case 'preline':
      tabStyle = `
        .tab_tab::after {
          content: "";
          position: absolute;
          pointer-events: none;
          top: 0;
          bottom: -1px;
          left: 0;
          width: 2px;
          height: inherit;
          background: ${scheme.accentColor};
          opacity: 0;
          transition: opacity .16s;
          z-index: 1;
          ${lightEffect}
        }
        .tab_tab.tab_active::after {
          opacity: 1;
          transition-duration: .32s;
          ${lightEffect}
        }`;
      break;
    case 'overline':
      tabStyle = `
      .tab_tab.tab_active {
        border-top: 2px solid ${scheme.accentColor} !important;
      }`;
      break;
    case 'filled':
      tabStyle = `
        .tab_tab.tab_active,
        .tabs_title {
          background: ${scheme.accentColor};
          ${lightEffect}
        }`;
      break;
    default:
      tabStyle = `
        .tab_tab::before {
          content: '';
          position: absolute;
          bottom: 0;
          left: 0;
          right: 0;
          height: 2px;
          background-color: ${scheme.accentColor};
          transform: scaleX(0);
          transition: none;
          ${lightEffect}
        }`;
      break;
  }

  return Object.assign({}, config, {
    colors: scheme.colors,
    backgroundColor: scheme.backgroundColor,
    foregroundColor: scheme.foregroundColor,
    borderColor: scheme.borderColor,
    cursorColor: scheme.cursorColor,
    css: `
    .tab_tab {
      border: none;
      color: ${scheme.inactiveTabTitleColor};
    }
    .tab_tab.tab_active {
      color: ${scheme.activeTabTitleColor};
    }
    .tabs_title {
      color: ${scheme.activeTabTitleColor};
    }
    .hyper_main {
      border: none;
    }
    .tabs_borderShim {
      display: none;
    }
    .tab_tab.tab_active::before {
      transform: scaleX(1);
      transition: all 300ms cubic-bezier(0.0, 0.0, 0.2, 1)
    }
    .tab_textInner {
      text-overflow: ellipsis;
      overflow: hidden;
      max-width: 100%;
      padding: 0px 24px 0 8px;
    }
    .tabs_nav .tab_tab .tab_icon {
      left: 5px;
      right: auto;
      top: 4px;
      border-radius: 2px;
    }
    ${tabStyle}
    ${
      materialBox.closeOnTheLeft === true ?
          '.tab_tab .tab_icon { left: 7px; right: initial; }' :
          ''
    }
    ${config.css || ''}
    `,
    termCSS: `
    ::-webkit-scrollbar {
      width: 2px;
    }
    ::-webkit-scrollbar-thumb {
      border-radius: 0px;
      background-color: ${scheme.accentColor};
    }
    x-screen x-row { font-variant-ligatures: contextual; }
    ${config.termCSS || ''}
    `,
  });
};
<|endoftext|>


<commit_before>var LETTER_WIDTH = 70,
	LETTER_HEIGHT = 70;

class lee {

	init(levelData) {

				this.levelData = levelData;

	}

	create() {
		// Random start positions that ensure no overlap, based on splitting the screen into quadrants
		var positions = [
			[game.rnd.integerInRange(10, game.world.width/2 - LETTER_WIDTH), game.rnd.integerInRange(10, game.world.height/2 - LETTER_HEIGHT)],
			[game.rnd.integerInRange(game.world.width/2 + 10, game.world.width - (LETTER_WIDTH + 10)),
				game.rnd.integerInRange(10, game.world.height/2 - LETTER_HEIGHT)],
			[game.rnd.integerInRange(10, game.world.width/2 - LETTER_WIDTH),
				game.rnd.integerInRange(game.world.height/2 + 10, game.world.height - (LETTER_HEIGHT + 10))],
			[game.rnd.integerInRange(game.world.width/2 + 10, game.world.width - (LETTER_WIDTH + 10)),
				game.rnd.integerInRange(game.world.height/2 + 10, game.world.height - (LETTER_HEIGHT + 80))]
		];

		this.sounds = this.levelData.sounds;

		this.letterImageKeys = this.levelData.letterImageKeys;

		var letters = game.add.group();

		var letter;
		var lowestLetter = 0;
		var highestLetter = this.levelData.numberOfLetters - 1;

		var totalLetters = highestLetter;

		this.chosenLetter = game.rnd.integerInRange(lowestLetter, highestLetter);

		console.log(this.chosenLetter);

		var currentLetter = this.chosenLetter;

		var firstPosition = game.rnd.integerInRange(lowestLetter, highestLetter-1);

		for (var i = 0; i < 4; i++) {

			letter = letters.create(positions[firstPosition][0], positions[firstPosition][1], this.letterImageKeys[currentLetter], undefined, undefined, i);

			if (i == 0) {

				var instructionLabel = game.add.text(game.world.centerX - 160 , game.world.height-80, 'Encuentra la letra ' + this.letterImageKeys[currentLetter], {fontSize: '50px', fill: '#FFFFFF'});
			}

			// Enable input
			letter.inputEnabled = true;
			letter.input.start(0, true);
			letter.levelData = this.levelData;
			letter.events.onInputUp.add(this.verify, this, 0, this.levelData);

			currentLetter = (currentLetter + 1)%totalLetters;
			firstPosition = (firstPosition + 1)%totalLetters;
		}

		this.scoreText = this.add.text(16, 16, 'Puntaje: ' + this.levelData.score, { fontSize: '32px', fill: '#F0F'});

		if (this.levelData.score < 0) {

			this.scoreText.fill = 'red';

		} else if(this.levelData.score > 0) {

			this.scoreText.fill = 'green';

		}

		this.start();
	}

	verify(sprite, pointer) {

		if (sprite.z == 0) {

			// Winning letter
			this.levelData.score += 1;

		} else {

			// Wrong letter
			this.levelData.score -= 1;
		}

		this.winCondition();
	}

	winCondition() {

		if (this.levelData.score >= 5) {

			this.Win();

		} else {

			game.state.start('gameMaster', true, false, this.levelData);

		}
	}

	start() {

		this.sounds['encuentra'].play();

		this.sounds['encuentra'].onStop.addOnce(() => {

			this.sounds[this.letterImageKeys[this.chosenLetter]].play();

		}, this);

	}

	Win() {

		game.state.start('win', true, false, this.levelData);

	}

}<commit_msg>deleted debugging console log line<commit_after>var LETTER_WIDTH = 70,
	LETTER_HEIGHT = 70;

class lee {

	init(levelData) {

				this.levelData = levelData;

	}

	create() {
		// Random start positions that ensure no overlap, based on splitting the screen into quadrants
		var positions = [
			[game.rnd.integerInRange(10, game.world.width/2 - LETTER_WIDTH), game.rnd.integerInRange(10, game.world.height/2 - LETTER_HEIGHT)],
			[game.rnd.integerInRange(game.world.width/2 + 10, game.world.width - (LETTER_WIDTH + 10)),
				game.rnd.integerInRange(10, game.world.height/2 - LETTER_HEIGHT)],
			[game.rnd.integerInRange(10, game.world.width/2 - LETTER_WIDTH),
				game.rnd.integerInRange(game.world.height/2 + 10, game.world.height - (LETTER_HEIGHT + 10))],
			[game.rnd.integerInRange(game.world.width/2 + 10, game.world.width - (LETTER_WIDTH + 10)),
				game.rnd.integerInRange(game.world.height/2 + 10, game.world.height - (LETTER_HEIGHT + 80))]
		];

		this.sounds = this.levelData.sounds;

		this.letterImageKeys = this.levelData.letterImageKeys;

		var letters = game.add.group();

		var letter;
		var lowestLetter = 0;
		var highestLetter = this.levelData.numberOfLetters - 1;

		var totalLetters = highestLetter;

		this.chosenLetter = game.rnd.integerInRange(lowestLetter, highestLetter);

		var currentLetter = this.chosenLetter;

		var firstPosition = game.rnd.integerInRange(lowestLetter, highestLetter-1);

		for (var i = 0; i < 4; i++) {

			letter = letters.create(positions[firstPosition][0], positions[firstPosition][1], this.letterImageKeys[currentLetter], undefined, undefined, i);

			if (i == 0) {

				var instructionLabel = game.add.text(game.world.centerX - 160 , game.world.height-80, 'Encuentra la letra ' + this.letterImageKeys[currentLetter], {fontSize: '50px', fill: '#FFFFFF'});
			}

			// Enable input
			letter.inputEnabled = true;
			letter.input.start(0, true);
			letter.levelData = this.levelData;
			letter.events.onInputUp.add(this.verify, this, 0, this.levelData);

			currentLetter = (currentLetter + 1)%totalLetters;
			firstPosition = (firstPosition + 1)%totalLetters;
		}

		this.scoreText = this.add.text(16, 16, 'Puntaje: ' + this.levelData.score, { fontSize: '32px', fill: '#F0F'});

		if (this.levelData.score < 0) {

			this.scoreText.fill = 'red';

		} else if(this.levelData.score > 0) {

			this.scoreText.fill = 'green';

		}

		this.start();
	}

	verify(sprite, pointer) {

		if (sprite.z == 0) {

			// Winning letter
			this.levelData.score += 1;

		} else {

			// Wrong letter
			this.levelData.score -= 1;
		}

		this.winCondition();
	}

	winCondition() {

		if (this.levelData.score >= 5) {

			this.Win();

		} else {

			game.state.start('gameMaster', true, false, this.levelData);

		}
	}

	start() {

		this.sounds['encuentra'].play();

		this.sounds['encuentra'].onStop.addOnce(() => {

			this.sounds[this.letterImageKeys[this.chosenLetter]].play();

		}, this);

	}

	Win() {

		game.state.start('win', true, false, this.levelData);

	}

}<|endoftext|>


<commit_before>import $ from "cheerio";
import d3Shape from "d3-shape";
import d3Scale from "d3-scale";

const RECTANGULAR_SEQUENCE = ["M", "L", "L", "L", "L"];
const CIRCULAR_SEQUENCE = ["M", "m", "a", "a"];

const parseSvgPathCommands = (commandStr) => {
  const matches = commandStr.match(
    /[MmLlHhVvCcSsQqTtAaZz]+[^MmLlHhVvCcSsQqTtAaZz]*/g
  );

  return matches.map((match) => {
    const name = match.charAt(0);
    const args = match.substring(1).split(",").map((arg) => {
      return parseFloat(arg, 10);
    });

    return {
      raw: match,
      name,
      args
    };
  });
};

const getPathCommandsFromWrapper = (wrapper) => {
  const commandStr = $(wrapper.html()).attr("d");
  return parseSvgPathCommands(commandStr);
};

const exhibitsShapeSequence = (wrapper, shapeSequence) => {
  const commands = getPathCommandsFromWrapper(wrapper);
  return commands.every((command, index) => {
    return command.name === shapeSequence[index];
  });
};

const calculateD3Path = (props) => {
  const {width, height, padding, scale, interpolation, data} = props;
  const scaleType = `scale${scale[0].toUpperCase() + scale.slice(1)}`;
  const curveType =
    `curve${interpolation[0].toUpperCase() + interpolation.slice(1)}`;

  const domain = data.reduce((prev, datum) => {
    if (datum.x < prev.x[0]) {
      prev.x[0] = datum.x;
    } else if (datum.x > prev.x[1]) {
      prev.x[1] = datum.x;
    }

    if (datum.y < prev.y[0]) {
      prev.y[0] = datum.y;
    } else if (datum.y > prev.y[1]) {
      prev.y[1] = datum.y;
    }

    return prev;
  }, {x: [0, 0], y: [0, 0]});

  const scaleX = d3Scale[scaleType]()
    .domain(domain.x)
    .range([padding, width - padding]);
  const scaleY = d3Scale[scaleType]()
    .domain(domain.y)
    .range([height - padding, padding]);

  return d3Shape.line()
    .curve(d3Shape[curveType])
    .x((d) => scaleX(d.x))
    .y((d) => scaleY(d.y))(data);
};

const expectations = {
  /**
   * Assert the wrapper renders a rectangular shape.
   *
   * @param {ShallowWrapper} wrapper - An enzyme wrapper that wraps a single
   * `path` node.
   * @returns {undefined}
   */
  expectIsRectangular(wrapper) {
    expect(exhibitsShapeSequence(wrapper, RECTANGULAR_SEQUENCE)).to.equal(true);
  },

  /**
   * Assert the wrapper renders a circular shape.
   *
   * @param {ShallowWrapper} wrapper - An enzyme wrapper.
   * @returns {undefined}
   */
  expectIsCircular(wrapper) {
    expect(exhibitsShapeSequence(wrapper, CIRCULAR_SEQUENCE)).to.equal(true);
  },

  /**
   * Assert the wrapper renders a line svg element.
   *
   * @param {ShallowWrapper} wrapper - An enzyme wrapper that wraps a single
   * node.
   * @returns {undefined}
   */
  expectIsALine(wrapper) {
    expect($(wrapper.html()).is("line")).to.equal(true);
  },

  /**
   * Assert the wrapper renders the correct path.
   *
   * @param {ShallowWrapper} wrapper - An enzyme wrapper that wraps a single
   * `path` node.
   * @param {Object} props - Props passed to the component.
   * @param {Number} props.width - The width of the svg.
   * @param {Number} props.height - The height of the svg.
   * @param {Number} props.padding - The padding of the svg.
   * @param {String} props.scale - The type of scale.
   * @param {String} props.interpolation - The type of curve.
   * @param {Array} props.data - The raw data for the chart.
   * @returns {undefined}
   */
  expectCorrectD3Path(wrapper, props) {
    expect(
      $(wrapper.html()).attr("d")
    ).to.equal(
      calculateD3Path(props)
    );
  }
};

const helpers = {
  /**
   * Retrieve the raw svg height of a bar.
   *
   * @param {ShallowWrapper} wrapper - An enzyme wrapper that wraps a single
   * `path` node.
   * @returns {Number} The height of the bar in svg units.
   */
  getBarHeight(wrapper) {
    expectations.expectIsRectangular(wrapper);
    const commands = getPathCommandsFromWrapper(wrapper);
    return Math.abs(commands[0].args[1] - commands[1].args[1]);
  },

  /**
   * Retrieve the raw svg coordinates for the center of a point.
   *
   * @param {ShallowWrapper} wrapper - An enzyme wrapper that wraps a single
   * `path` node.
   * @returns {Array} The x and y coordinates, respectively.
   */
  getSvgPointCoordinates(wrapper) {
    const commands = getPathCommandsFromWrapper(wrapper);
    return commands[0].args;
  },

  /**
   * Convert the raw svg coordinates to scaled Cartesian coordinates.
   *
   * @param {Array} coords - The x and y coordinates, respectively.
   * @param {Object} svgDimensions - The width, height, and padding of the svg.
   * @param {Number} svgDimensions.width - The width of the svg.
   * @param {Number} svgDimensions.height - The height of the svg.
   * @param {Number} svgDimensions.padding - The space between the edge of the
   *   svg and the chart area.
   * @param {Object} domain - The x and y domains.
   * @param {Array} domain.x - The lower and upper x bounds, respectively.
   * @param {Array} domain.y - The lower and upper y bounds, respectively.
   * @returns {Array} The Cartesian x and y coordinates, respectively.
   */
  convertSvgCoordinatesToCartesian(coords, svgDimensions, domain) {
    const { width, height, padding } = svgDimensions;

    const cartesianX = coords[0] - padding;
    const cartesianY = height - coords[1] - padding;

    const chartWidth = width - padding * 2;
    const chartHeight = height - padding * 2;

    const scaledX = cartesianX / chartWidth * (domain.x[1] - domain.x[0]);
    const scaledY = cartesianY / chartHeight * (domain.y[1] - domain.y[0]);

    const shiftedX = scaledX + domain.x[0];
    const shiftedY = scaledY + domain.y[0];

    return [shiftedX, shiftedY];
  },

  /**
   * Determine if the axis is an horizontal axis.
   *
   * @param {ShallowWrapper} wrapper - An enzyme wrapper that wraps a single
   * `line` node.
   * @param {Object} svgDimensions - The dimensions of the axis.
   * @param {Number} svgDimensions.width - The width of the line.
   * @param {Number} svgDimenions.padding - The padding around the line.
   * @returns {Boolean} Whether the wrapper renders an independent axis.
  */
  isHorizontalAxis(wrapper, svgDimensions) {
    const { width, padding } = svgDimensions;
    const {x1, x2, y1, y2} = $(wrapper.html()).attr();

    const isHorizontalLine = (x1 !== x2) && (y1 === y2);
    const isCorrectWidth = (width - padding * 2) === (x2 - x1);

    return isHorizontalLine && isCorrectWidth;
  },

  /**
   * Determine if the axis is a vertical axis.
   *
   * @param {ShallowWrapper} wrapper - An enzyme wrapper that wraps a single
   * `line` node.
   * @param {Object} svgDimensions - The dimensions of the axis.
   * @param {Number} svgDimensions.height - The height of the line.
   * @param {Number} svgDimenions.padding - The padding around the line.
   * @returns {Boolean} Whether the wrapper renders a dependent axis.
  */
  isVerticalAxis(wrapper, svgDimensions) {
    const { height, padding } = svgDimensions;
    const {x1, x2, y1, y2} = $(wrapper.html()).attr();

    const isVerticalLine = (x1 === x2) && (y1 !== y2);
    const isCorrectHeight = (height - padding * 2) === (y2 - y1);

    return isVerticalLine && isCorrectHeight;
  }
};

export default Object.assign({}, expectations, helpers);
<commit_msg>Modify helper to test for area d3 path<commit_after>import $ from "cheerio";
import d3Shape from "d3-shape";
import d3Scale from "d3-scale";

const RECTANGULAR_SEQUENCE = ["M", "L", "L", "L", "L"];
const CIRCULAR_SEQUENCE = ["M", "m", "a", "a"];

const parseSvgPathCommands = (commandStr) => {
  const matches = commandStr.match(
    /[MmLlHhVvCcSsQqTtAaZz]+[^MmLlHhVvCcSsQqTtAaZz]*/g
  );

  return matches.map((match) => {
    const name = match.charAt(0);
    const args = match.substring(1).split(",").map((arg) => {
      return parseFloat(arg, 10);
    });

    return {
      raw: match,
      name,
      args
    };
  });
};

const getPathCommandsFromWrapper = (wrapper) => {
  const commandStr = $(wrapper.html()).attr("d");
  return parseSvgPathCommands(commandStr);
};

const exhibitsShapeSequence = (wrapper, shapeSequence) => {
  const commands = getPathCommandsFromWrapper(wrapper);
  return commands.every((command, index) => {
    return command.name === shapeSequence[index];
  });
};

const calculateD3Path = (props, pathType) => {
  const {width, height, padding, scale, interpolation, data} = props;
  const scaleType = `scale${scale[0].toUpperCase() + scale.slice(1)}`;
  const curveType =
    `curve${interpolation[0].toUpperCase() + interpolation.slice(1)}`;

  const domain = data.reduce((prev, datum) => {
    if (datum.x < prev.x[0]) {
      prev.x[0] = datum.x;
    } else if (datum.x > prev.x[1]) {
      prev.x[1] = datum.x;
    }

    if (datum.y < prev.y[0]) {
      prev.y[0] = datum.y;
    } else if (datum.y > prev.y[1]) {
      prev.y[1] = datum.y;
    }

    return prev;
  }, {x: [0, 0], y: [0, 0]});

  const scaleX = d3Scale[scaleType]()
    .domain(domain.x)
    .range([padding, width - padding]);
  const scaleY = d3Scale[scaleType]()
    .domain(domain.y)
    .range([height - padding, padding]);

  switch (pathType) {
    case "line":
      return d3Shape.line()
        .curve(d3Shape[curveType])
        .x((d) => scaleX(d.x))
        .y((d) => scaleY(d.y))(data);
    case "area":
      return d3Shape.area()
        .curve(d3Shape[curveType])
        .x((d) => scaleX(d.x))
        .y1((d) => scaleY(d.y1))
        .y0((d) => scaleY(d.y0))(data);
  }
};

const expectations = {
  /**
   * Assert the wrapper renders a rectangular shape.
   *
   * @param {ShallowWrapper} wrapper - An enzyme wrapper that wraps a single
   * `path` node.
   * @returns {undefined}
   */
  expectIsRectangular(wrapper) {
    expect(exhibitsShapeSequence(wrapper, RECTANGULAR_SEQUENCE)).to.equal(true);
  },

  /**
   * Assert the wrapper renders a circular shape.
   *
   * @param {ShallowWrapper} wrapper - An enzyme wrapper.
   * @returns {undefined}
   */
  expectIsCircular(wrapper) {
    expect(exhibitsShapeSequence(wrapper, CIRCULAR_SEQUENCE)).to.equal(true);
  },

  /**
   * Assert the wrapper renders a line svg element.
   *
   * @param {ShallowWrapper} wrapper - An enzyme wrapper that wraps a single
   * node.
   * @returns {undefined}
   */
  expectIsALine(wrapper) {
    expect($(wrapper.html()).is("line")).to.equal(true);
  },

  /**
   * Assert the wrapper renders the correct path.
   *
   * @param {ShallowWrapper} wrapper - An enzyme wrapper that wraps a single
   * `path` node.
   * @param {Object} props - Props passed to the component.
   * @param {Number} props.width - The width of the svg.
   * @param {Number} props.height - The height of the svg.
   * @param {Number} props.padding - The padding of the svg.
   * @param {String} props.scale - The type of scale.
   * @param {String} props.interpolation - The type of curve.
   * @param {Array} props.data - The raw data for the chart.
   * @returns {undefined}
   */
  expectCorrectD3Path(wrapper, props) {
    expect(
      $(wrapper.html()).attr("d")
    ).to.equal(
      calculateD3Path(props)
    );
  }
};

const helpers = {
  /**
   * Retrieve the raw svg height of a bar.
   *
   * @param {ShallowWrapper} wrapper - An enzyme wrapper that wraps a single
   * `path` node.
   * @returns {Number} The height of the bar in svg units.
   */
  getBarHeight(wrapper) {
    expectations.expectIsRectangular(wrapper);
    const commands = getPathCommandsFromWrapper(wrapper);
    return Math.abs(commands[0].args[1] - commands[1].args[1]);
  },

  /**
   * Retrieve the raw svg coordinates for the center of a point.
   *
   * @param {ShallowWrapper} wrapper - An enzyme wrapper that wraps a single
   * `path` node.
   * @returns {Array} The x and y coordinates, respectively.
   */
  getSvgPointCoordinates(wrapper) {
    const commands = getPathCommandsFromWrapper(wrapper);
    return commands[0].args;
  },

  /**
   * Convert the raw svg coordinates to scaled Cartesian coordinates.
   *
   * @param {Array} coords - The x and y coordinates, respectively.
   * @param {Object} svgDimensions - The width, height, and padding of the svg.
   * @param {Number} svgDimensions.width - The width of the svg.
   * @param {Number} svgDimensions.height - The height of the svg.
   * @param {Number} svgDimensions.padding - The space between the edge of the
   *   svg and the chart area.
   * @param {Object} domain - The x and y domains.
   * @param {Array} domain.x - The lower and upper x bounds, respectively.
   * @param {Array} domain.y - The lower and upper y bounds, respectively.
   * @returns {Array} The Cartesian x and y coordinates, respectively.
   */
  convertSvgCoordinatesToCartesian(coords, svgDimensions, domain) {
    const { width, height, padding } = svgDimensions;

    const cartesianX = coords[0] - padding;
    const cartesianY = height - coords[1] - padding;

    const chartWidth = width - padding * 2;
    const chartHeight = height - padding * 2;

    const scaledX = cartesianX / chartWidth * (domain.x[1] - domain.x[0]);
    const scaledY = cartesianY / chartHeight * (domain.y[1] - domain.y[0]);

    const shiftedX = scaledX + domain.x[0];
    const shiftedY = scaledY + domain.y[0];

    return [shiftedX, shiftedY];
  },

  /**
   * Determine if the axis is an horizontal axis.
   *
   * @param {ShallowWrapper} wrapper - An enzyme wrapper that wraps a single
   * `line` node.
   * @param {Object} svgDimensions - The dimensions of the axis.
   * @param {Number} svgDimensions.width - The width of the line.
   * @param {Number} svgDimenions.padding - The padding around the line.
   * @returns {Boolean} Whether the wrapper renders an independent axis.
  */
  isHorizontalAxis(wrapper, svgDimensions) {
    const { width, padding } = svgDimensions;
    const {x1, x2, y1, y2} = $(wrapper.html()).attr();

    const isHorizontalLine = (x1 !== x2) && (y1 === y2);
    const isCorrectWidth = (width - padding * 2) === (x2 - x1);

    return isHorizontalLine && isCorrectWidth;
  },

  /**
   * Determine if the axis is a vertical axis.
   *
   * @param {ShallowWrapper} wrapper - An enzyme wrapper that wraps a single
   * `line` node.
   * @param {Object} svgDimensions - The dimensions of the axis.
   * @param {Number} svgDimensions.height - The height of the line.
   * @param {Number} svgDimenions.padding - The padding around the line.
   * @returns {Boolean} Whether the wrapper renders a dependent axis.
  */
  isVerticalAxis(wrapper, svgDimensions) {
    const { height, padding } = svgDimensions;
    const {x1, x2, y1, y2} = $(wrapper.html()).attr();

    const isVerticalLine = (x1 === x2) && (y1 !== y2);
    const isCorrectHeight = (height - padding * 2) === (y2 - y1);

    return isVerticalLine && isCorrectHeight;
  }
};

export default Object.assign({}, expectations, helpers);
<|endoftext|>


<commit_before>// HackerNews API - https://github.com/HackerNews/API

// https://github.com/stefanpenner/es6-promise#auto-polyfill
require('es6-promise').polyfill();
// https://github.com/matthew-andrews/isomorphic-fetch#usage
require('isomorphic-fetch');

function jsonFetch(url) {
  const opts = {
    method: 'get',
    // mode: 'cors',
    // credentials: 'include',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
  };

  return fetch(url, opts)
    .then((response) => {
      const { status } = response;
      if (status >= 400) {
        throw new Error(`Bad response from server with status ${status}`);
      }
      return response.json();
    });
}

const urlHN = 'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty';
jsonFetch(urlHN)
  .then((stories) => {
    //const storyId = stories[0];
    // const storyIdLength = stories.length;
//    storyScore = {};
    for (var i = 0; i < stories.length; i++) {
      const storyId = stories[i];
      const storyUrl = `https://hacker-news.firebaseio.com/v0/item/${storyId}.json?print=pretty`;
      jsonFetch(storyUrl)
        .then(storyObj => console.log(storyObj.score,storyObj.title));
// TODO: create the if statement and show only news with more than 50 points
    //     .then(storyObj) {
    //       if (storyObj.score > 50) {
    //         storyScore.push(storyObj);
    //    };
    //  };
   }
  })
  .catch((e) => console.error(e));
<commit_msg>linter check<commit_after>// HackerNews API - https://github.com/HackerNews/API

// https://github.com/stefanpenner/es6-promise#auto-polyfill
require('es6-promise').polyfill();
// https://github.com/matthew-andrews/isomorphic-fetch#usage
require('isomorphic-fetch');

function jsonFetch(url) {
  const opts = {
    method: 'get',
    // mode: 'cors',
    // credentials: 'include',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
  };

  return fetch(url, opts)
    .then((response) => {
      const { status } = response;
      if (status >= 400) {
        throw new Error(`Bad response from server with status ${status}`);
      }
      return response.json();
    });
}

const urlHN = 'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty';
jsonFetch(urlHN)
  .then((stories) => {
    // const storyId = stories[0];
    // const storyIdLength = stories.length;
//    storyScore = {};
    let i;
    for (i = 0; i < stories.length; i++) {
      const storyId = stories[i];
      const storyUrl = `https://hacker-news.firebaseio.com/v0/item/${storyId}.json?print=pretty`;
      jsonFetch(storyUrl)
        .then(storyObj => console.log(storyObj.score, storyObj.title));

/*
.then(function (selectedOption) {
             if (selectedOption === 'Yes') {
                 return this.save();
             } else {
                 Q.resolve()
             }
         });
*/
// TODO: create the if statement and show only news with more than 50 points
    //     .then(storyObj) {
    //       if (storyObj.score > 50) {
    //         storyScore.push(storyObj);
    //    };
    //  };
    }
  })
  .catch((e) => console.error(e));
<|endoftext|>


<commit_before>const gutil = require("gulp-util");
const path = require('path');
const through = require("through2");
const fs = require('fs');
const fse = require('fs-extra');
const chalk = require("chalk");
const requireReg = /require\(['"]([\w\d_\-\.\/]+)['"]\)/ig;
const dest_node_modules_dir_name = 'modules';

let config = {
    'gwcn-src': 'src',
    'gwcn-dest': 'dist',
    'gwcn-node_modules': '../node_modules',
    'gwcn-log': false
};

const gwcn = {
    cache: {

    },
    gulp: {

    },
    srcToDest: function(source) {
        let temp = source.replace(this.currentDir, '');
        temp = temp.replace(config['gwcn-src'], config['gwcn-dest']);
        return path.join(this.currentDir, temp);
    },
    destToSrc: function(source) {
        let temp = source.replace(this.currentDir, '');
        temp = temp.replace(config['gwcn-dest'], config['gwcn-src']);
        return path.join(this.currentDir, temp);
    },
    isFile(p) {
        p = (typeof(p) === 'object') ? path.join(p.dir, p.base) : p;
        if (!fs.existsSync(p)) {
            return false;
        }
        return fs.statSync(p).isFile();
    },
    isDir(p) {
        if (!fs.existsSync(p)) {
            return false;
        }
        return fs.statSync(p).isDirectory();
    },

    currentDir: process.cwd(),
    destDir: function() {
        return path.join(this.currentDir, config['gwcn-dest']);
    },
    srcDir: function() {
        return path.join(this.currentDir, config['gwcn-src']);
    },
    dest_node_modules_dir: function() {
        return path.join(this.destDir(), dest_node_modules_dir_name);
    },
    src_node_modules_dir: function() {
        return path.join(this.srcDir(), config['gwcn-node_modules']);
    },

    fixNPM: function(code) {
        code = code.replace(/([\w\[\]a-d\.]+)\s*instanceof Function/g, function(matchs, word) {
            return ' typeof ' + word + " ==='function' ";
        });
        code = code.replace(/'use strict';\n?/g, '');

        if (/[^\w_]process\.\w/.test(code) && !/typeof process/.test(code)) {
            code = `var process={};${code}`;
        }

        if (/global|window/.test(code)) {
            code = "var global=window=require('gulp-wxa-copy-npm/global');" + code;
        }
        return code;
    },
    npmHack(filename, code) {
        switch (filename) {
            case 'lodash.js':
            case '_global.js':
                code = code.replace('Function(\'return this\')()', 'this');
                break;
            case '_html.js':
                code = 'module.exports = false;';
                break;
            case '_microtask.js':
                code = code.replace('if(Observer)', 'if(false && Observer)');
                // IOS 1.10.2 Promise BUG
                code = code.replace('Promise && Promise.resolve', 'false && Promise && Promise.resolve');
                break;
        }
        return code;
    },
    copyNPMDeps: function(code, destPath, currentNodeSrcDir, isNPM) {
        let err = null;
        let dest_node_modules_dir = this.dest_node_modules_dir();
        let destDir = path.parse(destPath).dir;
        console.log('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
        console.log('destPath', destPath)
        let libs = [];
        code.replace(requireReg, (match, lib) => {
            libs.push(lib);
        });

        for (let i = 0; i < libs.length; i++) {
            let lib = libs[i];
            if (err) {
                return '';
            }
            let ext = '';

            let resolved = lib;

            let dep;

            let relative = '';
            console.log('lib', lib);

            if (lib == '../core-js/symbol/iterator') {
                let ttt = 111;
            }

            if (lib[0] === '.') { // require('./something'');
                if (!isNPM) {
                    continue;
                }
                ext = '.js';
                dep = path.join(currentNodeSrcDir, lib);
                relative = '';
            } else if (lib.indexOf('/') === -1 || lib.indexOf('/') === lib.length - 1) { // require('asset');
                let pkg = this.getPkgConfig(lib, this.gulp.enc);
                if (!pkg) {
                    err = new gutil.PluginError('gulp-wxa-copy-npm', 'Package not found:' + lib);
                    break;
                }
                ext = pkg.main || 'index.js';
                if (pkg.browser && typeof pkg.browser === 'string') {
                    ext = pkg.browser;
                }
                dep = path.join(this.src_node_modules_dir(), lib);
                relative = path.relative(destDir, dest_node_modules_dir);
            } else { // require('babel-runtime/regenerator')
                dep = path.join(this.src_node_modules_dir(), lib);
                if (this.isDir(dep) && this.isFile(dep + path.sep + 'index.js')) {
                    ext = path.sep + 'index.js';
                } else if (this.isFile(dep + '.js')) {
                    ext = '.js';
                } else if (this.isFile(dep)) {
                    ext = '';
                } else {
                    err = new gutil.PluginError('gulp-wxa-copy-npm', 'File not found:' + dep);
                    break;
                }
                relative = path.relative(destDir, dest_node_modules_dir);
            }
            resolved = path.join(relative, lib+ext);

            if (lib != resolved) {
                config['gwcn-log'] && gutil.log(`Replace file: ${destDir} depences: from(${chalk.cyan(lib)}) to(${chalk.cyan(resolved)})`);
            }

            let npmPathString = dep + ext;
            let npmPath = path.parse(npmPathString);
            if (this.cache[destPath]) {
                code = code.replace(lib, resolved);
                continue;
            }

            let depCode = fs.readFileSync(npmPathString, {
                encoding: this.gulp.enc
            });

            let outPath = path.join(this.currentDir, config['gwcn-dest'], dest_node_modules_dir_name, npmPathString.replace(this.src_node_modules_dir(), ''));
            config['gwcn-log'] && gutil.log(`Copy npm depences: from(${chalk.cyan(npmPathString)}) to(${chalk.cyan(outPath)}) ...`);
            console.log('outPath', outPath)
            console.log('resolved', resolved)

            code = code.replace(lib, resolved);

            if (resolved.indexOf('symbol.js') > -1 || lib.indexOf('symbol.js') > -1 || code.indexOf('symbol.js') > -1) {
                var aaa = 333;
            }

            err = this.copyNPMDeps(depCode, outPath, npmPath.dir, true).err;
        }

        if (isNPM && !this.cache[destPath]) {
            code = this.npmHack(path.parse(destPath).base, code);
            code = this.fixNPM(code);
            code = this.doPlugins(code, destPath);
            fse.outputFileSync(destPath, code, {
                encoding: this.gulp.enc
            });
            this.cache[destPath] = true;
        }

        return {
            code: code,
            err: err
        };
    },
    getPkgConfig(lib, enc) {
        let pkg = fs.readFileSync(path.join(this.src_node_modules_dir(), lib, 'package.json'), enc);
        try {
            pkg = JSON.parse(pkg);
        } catch (e) {
            pkg = null;
        }
        return pkg;
    },
    doPlugins: function(depCode, destPath) {
        let result = depCode;
        let plugins = config.plugins;
        if (config.plugins) {
            for (let i = 0; i < plugins.length; i++) {
                let plugin = plugins[i];
                result = plugin(result, destPath, gwcn.gulp);
            }
        }
        return result;
    }
}

module.exports = function(options) {

    config = Object.assign(config, options);
    return through.obj(function(file, enc, callback) {
        gutil.log(chalk.cyan('Copying npm depences...'));
        gwcn.gulp.file = file;
        gwcn.gulp.enc = enc;
        gwcn.gulp.callback = callback;
        let sourceCode = file._contents.toString(enc);
        let {
            err,
            code
        } = gwcn.copyNPMDeps(sourceCode, gwcn.srcToDest(file.path), gwcn.src_node_modules_dir(), false);
        // let transformCode = gwcn.replaceNPMDeps(sourceCode, gwcn.srcToDest(file.path))
        file._contents = new Buffer(code);
        // err maybe null
        callback(err, file);
    });
}<commit_msg>可以正确的使用npm<commit_after>const gutil = require("gulp-util");
const path = require('path');
const through = require("through2");
const fs = require('fs');
const fse = require('fs-extra');
const chalk = require("chalk");
const requireReg = /require\(['"]([\w\d_\-\.\/]+)['"]\)/ig;
const dest_node_modules_dir_name = 'gwcn-modules';

let config = {
    'gwcn-src': 'src',
    'gwcn-dest': 'dist',
    'gwcn-node_modules': '../node_modules',
    'gwcn-log': false
};

const gwcn = {
    cache: {

    },
    gulp: {

    },
    srcToDest: function(source) {
        let temp = source.replace(this.currentDir, '');
        temp = temp.replace(config['gwcn-src'], config['gwcn-dest']);
        return path.join(this.currentDir, temp);
    },
    destToSrc: function(source) {
        let temp = source.replace(this.currentDir, '');
        temp = temp.replace(config['gwcn-dest'], config['gwcn-src']);
        return path.join(this.currentDir, temp);
    },
    isFile(p) {
        p = (typeof(p) === 'object') ? path.join(p.dir, p.base) : p;
        if (!fs.existsSync(p)) {
            return false;
        }
        return fs.statSync(p).isFile();
    },
    isDir(p) {
        if (!fs.existsSync(p)) {
            return false;
        }
        return fs.statSync(p).isDirectory();
    },

    currentDir: process.cwd(),
    destDir: function() {
        return path.join(this.currentDir, config['gwcn-dest']);
    },
    srcDir: function() {
        return path.join(this.currentDir, config['gwcn-src']);
    },
    dest_node_modules_dir: function() {
        return path.join(this.destDir(), dest_node_modules_dir_name);
    },
    src_node_modules_dir: function() {
        return path.join(this.srcDir(), config['gwcn-node_modules']);
    },

    fixGlobalAndWindow: function(code) {
        if (/global|window/.test(code)) {
            code = "var global=window=require('gulp-wxa-copy-npm/global');" + code;
        }
        return code;
    },

    fixNPM: function(code) {
        code = code.replace(/([\w\[\]a-d\.]+)\s*instanceof Function/g, function(matchs, word) {
            return ' typeof ' + word + " ==='function' ";
        });
        code = code.replace(/'use strict';\n?/g, '');

        if (/[^\w_]process\.\w/.test(code) && !/typeof process/.test(code)) {
            code = `var process={};${code}`;
        }
        return code;
    },

    npmHack(filename, code) {
        switch (filename) {
            case 'lodash.js':
            case '_global.js':
                code = code.replace('Function(\'return this\')()', 'this');
                break;
            case '_html.js':
                code = 'module.exports = false;';
                break;
            case '_microtask.js':
                code = code.replace('if(Observer)', 'if(false && Observer)');
                // IOS 1.10.2 Promise BUG
                code = code.replace('Promise && Promise.resolve', 'false && Promise && Promise.resolve');
                break;
        }
        return code;
    },
    copyNPMDeps: function(code, destPath, currentNodeSrcDir, isNPM) {
        let err = null;
        let dest_node_modules_dir = this.dest_node_modules_dir();
        let destDir = path.parse(destPath).dir;
        let libs = [];
        let matchs = [];
        code = this.fixGlobalAndWindow(code);

        code.replace(requireReg, (match, lib) => {
            libs.push(lib);
            matchs.push(match);
        });

        for (let i = 0; i < libs.length; i++) {
            let lib = libs[i];
            let match = matchs[i];
            if (err) {
                break;
            }
            let ext = '';

            let resolved = lib;

            let dep;

            let relative = '';

            if (lib[0] === '.') { // require('./something'');
                if (!isNPM) {
                    continue;
                }
                ext = '.js';
                dep = path.join(currentNodeSrcDir, lib);
                relative = '';
            } else if (lib.indexOf('/') === -1 || lib.indexOf('/') === lib.length - 1) { // require('asset');
                let pkg = this.getPkgConfig(lib, this.gulp.enc);
                if (!pkg) {
                    err = new gutil.PluginError('gulp-wxa-copy-npm', 'Package not found:' + lib);
                    break;
                }
                ext = pkg.main || 'index.js';
                if (pkg.browser && typeof pkg.browser === 'string') {
                    ext = pkg.browser;
                }
                if (ext.indexOf('./') == 0) {
                    ext = ext.replace('./', '');
                }
                ext = path.sep + ext;
                dep = path.join(this.src_node_modules_dir(), lib);
                relative = path.relative(destDir, dest_node_modules_dir);
            } else { // require('babel-runtime/regenerator')
                dep = path.join(this.src_node_modules_dir(), lib);
                if (this.isDir(dep) && this.isFile(dep + path.sep + 'index.js')) {
                    ext = path.sep + 'index.js';
                } else if (this.isFile(dep + '.js')) {
                    ext = '.js';
                } else if (this.isFile(dep)) {
                    ext = '';
                } else {
                    err = new gutil.PluginError('gulp-wxa-copy-npm', 'File not found:' + dep);
                    break;
                }
                relative = path.relative(destDir, dest_node_modules_dir);
            }
            resolved = path.join(relative, lib + ext);

            if (lib != resolved) {
                config['gwcn-log'] && gutil.log(`Replace file: ${destDir} depences: from(${chalk.cyan(lib)}) to(${chalk.cyan(resolved)})`);
            }

            let npmPathString = dep + ext;
            let npmPath = path.parse(npmPathString);

            let outPath = path.join(this.currentDir, config['gwcn-dest'], dest_node_modules_dir_name, npmPathString.replace(this.src_node_modules_dir(), ''));
            config['gwcn-log'] && gutil.log(`Copy npm depences: from(${chalk.cyan(npmPathString)}) to(${chalk.cyan(outPath)}) ...`);

            code = code.replace(match, `require('${resolved}')`);

            if (this.cache[outPath]) {
                continue;
            }

            let depCode = fs.readFileSync(npmPathString, {
                encoding: this.gulp.enc
            });

            err = this.copyNPMDeps(depCode, outPath, npmPath.dir, true).err;
        }

        if (isNPM && !this.cache[destPath] && !err) {
            code = this.npmHack(path.parse(destPath).base, code);
            code = this.fixNPM(code);
            code = this.doPlugins(code, destPath);
            fse.outputFileSync(destPath, code, {
                encoding: this.gulp.enc
            });
            this.cache[destPath] = true;
        }

        return {
            code: code,
            err: err
        };
    },
    getPkgConfig(lib, enc) {
        let pkg = fs.readFileSync(path.join(this.src_node_modules_dir(), lib, 'package.json'), enc);
        try {
            pkg = JSON.parse(pkg);
        } catch (e) {
            pkg = null;
        }
        return pkg;
    },
    doPlugins: function(depCode, destPath) {
        let result = depCode;
        let plugins = config.plugins;
        if (config.plugins) {
            for (let i = 0; i < plugins.length; i++) {
                let plugin = plugins[i];
                result = plugin(result, destPath, gwcn.gulp);
            }
        }
        return result;
    }
}

module.exports = function(options) {

    config = Object.assign(config, options);
    return through.obj(function(file, enc, callback) {
        gutil.log(chalk.cyan('Copying npm depences...'));
        gwcn.gulp.file = file;
        gwcn.gulp.enc = enc;
        gwcn.gulp.callback = callback;
        let sourceCode = file._contents.toString(enc);
        let {
            err,
            code
        } = gwcn.copyNPMDeps(sourceCode, gwcn.srcToDest(file.path), gwcn.src_node_modules_dir(), false);
        // let transformCode = gwcn.replaceNPMDeps(sourceCode, gwcn.srcToDest(file.path))
        file._contents = new Buffer(code);
        // err maybe null
        callback(err, file);
    });
}<|endoftext|>


<commit_before>var map = null;

$(document).on('pageshow', '#map', function() {
    // draw the map once
    if (map == null) drawMap();
});

function drawMap() {
    $('#map_canvas').css('height', 500);

    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var mapOptions = {
	center: latlng,
	zoom: 8,
	mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
}<commit_msg>Create markers based on retrieved posts<commit_after>var map = null;

$(document).on('pageshow', '#map', function() {
    // Draw the map once
    if (map == null) initMap();
});

function initMap() {
    $('#map_canvas').css('height', 500);

    var latlng = new google.maps.LatLng(34.87728, 135.576798); // kutc
    var mapOptions = {
	center: latlng,
	zoom: 8,
	mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);

    // Get posts and create markers
    var api_uri = 'http://mpmc.dip.jp/~otknoy/michishiki_api_server/select.py';
    $.getJSON(api_uri, function(json) {
	for (var i = 0; i < json.length; i++) {
	    createMarker(map, json[i].title, json[i].latitude, json[i].longitude);
	}
    });
}

function createMarker(map, title, latitude, longitude) {
    var latlng = new google.maps.LatLng(latitude, longitude);
    var marker = new google.maps.Marker({
	position: latlng,
	map: map,
	title : title
	});
    return marker;
}<|endoftext|>


<commit_before>import * as columnService from 'core/column/column.service';
import AppError from 'core/infrastructure/error';

export default function rangeBuilder(model) {
	function rangeRows(startCell, endCell) {
		const rows = model.view().rows;
		if (!endCell) {
			return [rows[startCell.rowIndex]];
		}

		const startIndex = Math.min(startCell.rowIndex, endCell.rowIndex);
		const endIndex = Math.max(startCell.rowIndex, endCell.rowIndex);
		return rows.slice(startIndex, endIndex + 1);
	}

	function rangeColumns(startCell, endCell) {
		const columns = columnService.lineView(model.view().columns);
		if (!endCell) {
			return [columns.find(c => c.model === startCell.column).model];
		}

		const startIndex = Math.min(startCell.columnIndex, endCell.columnIndex);
		const endIndex = Math.max(startCell.columnIndex, endCell.columnIndex);
		return columns.slice(startIndex, endIndex + 1).map(column => column.model);
	}

	function rangeCells(startCell, endCell) {
		if (!endCell) {
			return [{
				column: startCell.column,
				row: startCell.row
			}];
		}

		const rows = model.view().rows;
		const columns = columnService.lineView(model.view().columns);

		const startRowIndex = Math.min(startCell.rowIndex, endCell.rowIndex);
		const endRowIndex = Math.max(startCell.rowIndex, endCell.rowIndex);

		const startColumnIndex = Math.min(startCell.columnIndex, endCell.columnIndex);
		const endColumnIndex = Math.max(startCell.columnIndex, endCell.columnIndex);

		const rowsSelected = rows.slice(startRowIndex, endRowIndex + 1);
		const columnsSelected = columns.slice(startColumnIndex, endColumnIndex + 1);

		const items = [];
		rowsSelected.forEach(row => {
			columnsSelected
				.filter(column => column.model.type !== 'row-indicator')
				.forEach(column => {
					items.push({
						column: column.model,
						row: row
					});
				});
		});

		return items;
	}

	function rangeMix(startCell, endCell) {
		const mixUnit = startCell.column.type === 'row-indicator' ? 'row' : 'cell';
		const range = (mixUnit === 'row' ? rangeRows(startCell, endCell) : rangeCells(startCell, endCell));
		return range
			.map(item => ({
				item: item,
				unit: mixUnit
			}));
	}

	const rangeMap = {
		'row': rangeRows,
		'columns': rangeColumns,
		'cell': rangeCells,
		'mix': rangeMix,
	};

	return (...args) => {
		const selection = model.selection();
		const getRange = rangeMap[selection.unit];
		if (!getRange) {
			throw new AppError('range.builder', `Invalid unit ${selection.unit}`);
		}

		return getRange(...args);
	};
}<commit_msg>fix range for column unit<commit_after>import * as columnService from 'core/column/column.service';
import AppError from 'core/infrastructure/error';

export default function rangeBuilder(model) {
	function rangeRows(startCell, endCell) {
		const rows = model.view().rows;
		if (!endCell) {
			return [rows[startCell.rowIndex]];
		}

		const startIndex = Math.min(startCell.rowIndex, endCell.rowIndex);
		const endIndex = Math.max(startCell.rowIndex, endCell.rowIndex);
		return rows.slice(startIndex, endIndex + 1);
	}

	function rangeColumns(startCell, endCell) {
		const columns = columnService.lineView(model.view().columns);
		if (!endCell) {
			return [columns.find(c => c.model === startCell.column).model];
		}

		const startIndex = Math.min(startCell.columnIndex, endCell.columnIndex);
		const endIndex = Math.max(startCell.columnIndex, endCell.columnIndex);
		return columns.slice(startIndex, endIndex + 1).map(column => column.model);
	}

	function rangeCells(startCell, endCell) {
		if (!endCell) {
			return [{
				column: startCell.column,
				row: startCell.row
			}];
		}

		const rows = model.view().rows;
		const columns = columnService.lineView(model.view().columns);

		const startRowIndex = Math.min(startCell.rowIndex, endCell.rowIndex);
		const endRowIndex = Math.max(startCell.rowIndex, endCell.rowIndex);

		const startColumnIndex = Math.min(startCell.columnIndex, endCell.columnIndex);
		const endColumnIndex = Math.max(startCell.columnIndex, endCell.columnIndex);

		const rowsSelected = rows.slice(startRowIndex, endRowIndex + 1);
		const columnsSelected = columns.slice(startColumnIndex, endColumnIndex + 1);

		const items = [];
		rowsSelected.forEach(row => {
			columnsSelected
				.filter(column => column.model.type !== 'row-indicator')
				.forEach(column => {
					items.push({
						column: column.model,
						row: row
					});
				});
		});

		return items;
	}

	function rangeMix(startCell, endCell) {
		const mixUnit = startCell.column.type === 'row-indicator' ? 'row' : 'cell';
		const range = (mixUnit === 'row' ? rangeRows(startCell, endCell) : rangeCells(startCell, endCell));
		return range
			.map(item => ({
				item: item,
				unit: mixUnit
			}));
	}

	const rangeMap = {
		'row': rangeRows,
		'column': rangeColumns,
		'cell': rangeCells,
		'mix': rangeMix,
	};

	return (...args) => {
		const selection = model.selection();
		const getRange = rangeMap[selection.unit];
		if (!getRange) {
			throw new AppError('range.builder', `Invalid unit ${selection.unit}`);
		}

		return getRange(...args);
	};
}<|endoftext|>


<commit_before>'use strict'
module.exports = writeFile
module.exports.sync = writeFileSync
module.exports._getTmpname = getTmpname // for testing
module.exports._cleanupOnExit = cleanupOnExit

var fs = require('graceful-fs')
var MurmurHash3 = require('imurmurhash')
var onExit = require('signal-exit')
var path = require('path')
var activeFiles = {}

// if we run inside of a worker_thread, `process.pid` is not unique
/* istanbul ignore next */
var threadId = (function getId () {
  try {
    var workerThreads = require('worker_threads')

    /// if we are in main thread, this is set to `0`
    return workerThreads.threadId
  } catch (e) {
    // worker_threads are not available, fallback to 0
    return 0
  }
})()

var invocations = 0
function getTmpname (filename) {
  return filename + '.' +
    MurmurHash3(__filename)
      .hash(String(process.pid))
      .hash(String(threadId))
      .hash(String(++invocations))
      .result()
}

function cleanupOnExit (tmpfile) {
  return function () {
    try {
      fs.unlinkSync(typeof tmpfile === 'function' ? tmpfile() : tmpfile)
    } catch (_) {}
  }
}

function writeFile (filename, data, options, callback) {
  if (options) {
    if (options instanceof Function) {
      callback = options
      options = {}
    } else if (typeof options === 'string') {
      options = { encoding: options }
    }
  } else {
    options = {}
  }

  var Promise = options.Promise || global.Promise
  var truename
  var fd
  var tmpfile
  var removeOnExit = cleanupOnExit(() => tmpfile)
  var absoluteName = path.resolve(filename)

  new Promise(function serializeSameFile (resolve) {
    // make a queue if it doesn't already exist
    if (!activeFiles[absoluteName]) activeFiles[absoluteName] = []

    activeFiles[absoluteName].push(resolve) // add this job to the queue
    if (activeFiles[absoluteName].length === 1) resolve() // kick off the first one
  }).then(function getRealPath () {
    return new Promise(function (resolve) {
      fs.realpath(filename, function (_, realname) {
        truename = realname || filename
        tmpfile = getTmpname(truename)
        resolve()
      })
    })
  }).then(function stat () {
    return new Promise(function stat (resolve) {
      if (options.mode && options.chown) resolve()
      else {
        // Either mode or chown is not explicitly set
        // Default behavior is to copy it from original file
        fs.stat(truename, function (err, stats) {
          if (err || !stats) resolve()
          else {
            options = Object.assign({}, options)

            if (options.mode == null) {
              options.mode = stats.mode
            }
            if (options.chown == null && process.getuid) {
              options.chown = { uid: stats.uid, gid: stats.gid }
            }
            resolve()
          }
        })
      }
    })
  }).then(function thenWriteFile () {
    return new Promise(function (resolve, reject) {
      fs.open(tmpfile, 'w', options.mode, function (err, _fd) {
        fd = _fd
        if (err) reject(err)
        else resolve()
      })
    })
  }).then(function write () {
    return new Promise(function (resolve, reject) {
      if (Buffer.isBuffer(data)) {
        fs.write(fd, data, 0, data.length, 0, function (err) {
          if (err) reject(err)
          else resolve()
        })
      } else if (data != null) {
        fs.write(fd, String(data), 0, String(options.encoding || 'utf8'), function (err) {
          if (err) reject(err)
          else resolve()
        })
      } else resolve()
    })
  }).then(function syncAndClose () {
    if (options.fsync !== false) {
      return new Promise(function (resolve, reject) {
        fs.fsync(fd, function (err) {
          if (err) reject(err)
          else fs.close(fd, resolve)
        })
      })
    }
  }).then(function chown () {
    if (options.chown) {
      return new Promise(function (resolve, reject) {
        fs.chown(tmpfile, options.chown.uid, options.chown.gid, function (err) {
          if (err) reject(err)
          else resolve()
        })
      })
    }
  }).then(function chmod () {
    if (options.mode) {
      return new Promise(function (resolve, reject) {
        fs.chmod(tmpfile, options.mode, function (err) {
          if (err) reject(err)
          else resolve()
        })
      })
    }
  }).then(function rename () {
    return new Promise(function (resolve, reject) {
      fs.rename(tmpfile, truename, function (err) {
        if (err) reject(err)
        else resolve()
      })
    })
  }).then(function success () {
    callback()
  }).catch(function fail (err) {
    removeOnExit()
    fs.unlink(tmpfile, function () {
      callback(err)
    })
  }).then(function checkQueue () {
    activeFiles[absoluteName].shift() // remove the element added by serializeSameFile
    if (activeFiles[absoluteName].length > 0) {
      activeFiles[absoluteName][0]() // start next job if one is pending
    } else delete activeFiles[absoluteName]
  })
}

function writeFileSync (filename, data, options) {
  if (typeof options === 'string') options = { encoding: options }
  else if (!options) options = {}
  try {
    filename = fs.realpathSync(filename)
  } catch (ex) {
    // it's ok, it'll happen on a not yet existing file
  }
  var tmpfile = getTmpname(filename)

  try {
    if (!options.mode || !options.chown) {
      // Either mode or chown is not explicitly set
      // Default behavior is to copy it from original file
      try {
        var stats = fs.statSync(filename)
        options = Object.assign({}, options)
        if (!options.mode) {
          options.mode = stats.mode
        }
        if (!options.chown && process.getuid) {
          options.chown = { uid: stats.uid, gid: stats.gid }
        }
      } catch (ex) {
        // ignore stat errors
      }
    }

    var removeOnExit = onExit(cleanupOnExit(tmpfile))
    var fd = fs.openSync(tmpfile, 'w', options.mode)
    if (Buffer.isBuffer(data)) {
      fs.writeSync(fd, data, 0, data.length, 0)
    } else if (data != null) {
      fs.writeSync(fd, String(data), 0, String(options.encoding || 'utf8'))
    }
    if (options.fsync !== false) {
      fs.fsyncSync(fd)
    }
    fs.closeSync(fd)
    if (options.chown) fs.chownSync(tmpfile, options.chown.uid, options.chown.gid)
    if (options.mode) fs.chmodSync(tmpfile, options.mode)
    fs.renameSync(tmpfile, filename)
    removeOnExit()
  } catch (err) {
    removeOnExit()
    try { fs.unlinkSync(tmpfile) } catch (e) {}
    throw err
  }
}
<commit_msg>Cleanup onExit handler cleanup<commit_after>'use strict'
module.exports = writeFile
module.exports.sync = writeFileSync
module.exports._getTmpname = getTmpname // for testing
module.exports._cleanupOnExit = cleanupOnExit

var fs = require('graceful-fs')
var MurmurHash3 = require('imurmurhash')
var onExit = require('signal-exit')
var path = require('path')
var activeFiles = {}

// if we run inside of a worker_thread, `process.pid` is not unique
/* istanbul ignore next */
var threadId = (function getId () {
  try {
    var workerThreads = require('worker_threads')

    /// if we are in main thread, this is set to `0`
    return workerThreads.threadId
  } catch (e) {
    // worker_threads are not available, fallback to 0
    return 0
  }
})()

var invocations = 0
function getTmpname (filename) {
  return filename + '.' +
    MurmurHash3(__filename)
      .hash(String(process.pid))
      .hash(String(threadId))
      .hash(String(++invocations))
      .result()
}

function cleanupOnExit (tmpfile) {
  return function () {
    try {
      fs.unlinkSync(typeof tmpfile === 'function' ? tmpfile() : tmpfile)
    } catch (_) {}
  }
}

function writeFile (filename, data, options, callback) {
  if (options) {
    if (options instanceof Function) {
      callback = options
      options = {}
    } else if (typeof options === 'string') {
      options = { encoding: options }
    }
  } else {
    options = {}
  }

  var Promise = options.Promise || global.Promise
  var truename
  var fd
  var tmpfile
  /* istanbul ignore next -- The closure only gets called when onExit triggers */
  var removeOnExitHandler = onExit(cleanupOnExit(() => tmpfile))
  var absoluteName = path.resolve(filename)

  new Promise(function serializeSameFile (resolve) {
    // make a queue if it doesn't already exist
    if (!activeFiles[absoluteName]) activeFiles[absoluteName] = []

    activeFiles[absoluteName].push(resolve) // add this job to the queue
    if (activeFiles[absoluteName].length === 1) resolve() // kick off the first one
  }).then(function getRealPath () {
    return new Promise(function (resolve) {
      fs.realpath(filename, function (_, realname) {
        truename = realname || filename
        tmpfile = getTmpname(truename)
        resolve()
      })
    })
  }).then(function stat () {
    return new Promise(function stat (resolve) {
      if (options.mode && options.chown) resolve()
      else {
        // Either mode or chown is not explicitly set
        // Default behavior is to copy it from original file
        fs.stat(truename, function (err, stats) {
          if (err || !stats) resolve()
          else {
            options = Object.assign({}, options)

            if (options.mode == null) {
              options.mode = stats.mode
            }
            if (options.chown == null && process.getuid) {
              options.chown = { uid: stats.uid, gid: stats.gid }
            }
            resolve()
          }
        })
      }
    })
  }).then(function thenWriteFile () {
    return new Promise(function (resolve, reject) {
      fs.open(tmpfile, 'w', options.mode, function (err, _fd) {
        fd = _fd
        if (err) reject(err)
        else resolve()
      })
    })
  }).then(function write () {
    return new Promise(function (resolve, reject) {
      if (Buffer.isBuffer(data)) {
        fs.write(fd, data, 0, data.length, 0, function (err) {
          if (err) reject(err)
          else resolve()
        })
      } else if (data != null) {
        fs.write(fd, String(data), 0, String(options.encoding || 'utf8'), function (err) {
          if (err) reject(err)
          else resolve()
        })
      } else resolve()
    })
  }).then(function syncAndClose () {
    if (options.fsync !== false) {
      return new Promise(function (resolve, reject) {
        fs.fsync(fd, function (err) {
          if (err) reject(err)
          else fs.close(fd, resolve)
        })
      })
    }
  }).then(function chown () {
    if (options.chown) {
      return new Promise(function (resolve, reject) {
        fs.chown(tmpfile, options.chown.uid, options.chown.gid, function (err) {
          if (err) reject(err)
          else resolve()
        })
      })
    }
  }).then(function chmod () {
    if (options.mode) {
      return new Promise(function (resolve, reject) {
        fs.chmod(tmpfile, options.mode, function (err) {
          if (err) reject(err)
          else resolve()
        })
      })
    }
  }).then(function rename () {
    return new Promise(function (resolve, reject) {
      fs.rename(tmpfile, truename, function (err) {
        if (err) reject(err)
        else resolve()
      })
    })
  }).then(function success () {
    removeOnExitHandler()
    callback()
  }).catch(function fail (err) {
    removeOnExitHandler()
    fs.unlink(tmpfile, function () {
      callback(err)
    })
  }).then(function checkQueue () {
    activeFiles[absoluteName].shift() // remove the element added by serializeSameFile
    if (activeFiles[absoluteName].length > 0) {
      activeFiles[absoluteName][0]() // start next job if one is pending
    } else delete activeFiles[absoluteName]
  })
}

function writeFileSync (filename, data, options) {
  if (typeof options === 'string') options = { encoding: options }
  else if (!options) options = {}
  try {
    filename = fs.realpathSync(filename)
  } catch (ex) {
    // it's ok, it'll happen on a not yet existing file
  }
  var tmpfile = getTmpname(filename)

  try {
    if (!options.mode || !options.chown) {
      // Either mode or chown is not explicitly set
      // Default behavior is to copy it from original file
      try {
        var stats = fs.statSync(filename)
        options = Object.assign({}, options)
        if (!options.mode) {
          options.mode = stats.mode
        }
        if (!options.chown && process.getuid) {
          options.chown = { uid: stats.uid, gid: stats.gid }
        }
      } catch (ex) {
        // ignore stat errors
      }
    }

    var cleanup = cleanupOnExit(tmpfile)
    var removeOnExitHandler = onExit(cleanup)
    var fd = fs.openSync(tmpfile, 'w', options.mode)
    if (Buffer.isBuffer(data)) {
      fs.writeSync(fd, data, 0, data.length, 0)
    } else if (data != null) {
      fs.writeSync(fd, String(data), 0, String(options.encoding || 'utf8'))
    }
    if (options.fsync !== false) {
      fs.fsyncSync(fd)
    }
    fs.closeSync(fd)
    if (options.chown) fs.chownSync(tmpfile, options.chown.uid, options.chown.gid)
    if (options.mode) fs.chmodSync(tmpfile, options.mode)
    fs.renameSync(tmpfile, filename)
    removeOnExitHandler()
  } catch (err) {
    removeOnExitHandler()
    cleanup()
    throw err
  }
}
<|endoftext|>


<commit_before>var Map = {};
Map.map = null;
Map.markers = null;

$(document).on('pageshow', '#map', function() {
    Map.initMap();
});

Map.initMap = function() {
    Map.markers = [];

    $('#map-canvas').css('height', 500);
    Map.map = Map.createMap('map-canvas', 34.87728, 135.576798); // kutc

    utils.getCurrentLocation().done(function(location) {
	var pos = new google.maps.LatLng(location.latitude,
					 location.longitude);

	Map.currentLocation = Map.createMarker(Map.map, 'Current location',
					       location.latitude, location.longitude, false);
    });

    Map.infoWindow = new google.maps.InfoWindow;

    utils.fetchPosts().done(function(json) {
	for (var i = 0; i < json.length; i++) {
	    var marker = Map.createMarker(Map.map, json[i].title,
					  json[i].latitude, json[i].longitude, false);
	    marker.data = json[i];
	    Map.markers.push(marker);

	    google.maps.event.addListener(marker, 'click', function() {
		var content = Map.jsonToContent(this.data);
		Map.infoWindow.setContent(content);
		Map.infoWindow.open(Map.map, this);
	    });
	}
    });
};

Map.createMap = function(id, lat, lng) {
    var mapOptions = {
	center: new google.maps.LatLng(lat, lng),
	zoom: 8,
	mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById(id), mapOptions);
    return map;
};

Map.createMarker = function(map, title, lat, lng, draggable) {
    var marker = new google.maps.Marker({
	position: new google.maps.LatLng(lat, lng),
	map: map,
	title : title,
	draggable: draggable
    });
    return marker;
};

Map.jsonToContent = function(json) {
    var title = json.title;
    var created_at = json.created_at;
    var posted_by = json.posted_by;
    var comment = json.comment;

    var content =
	    '
' +
	    '
' + title + '
' +
	    '
' + created_at + '
' +
	    '
' + posted_by + '
' +
	    '
' + comment + '
' +
	    '
';

    return content;
};<commit_msg>Fetch posts if map bounds are changed<commit_after>var Map = {};
Map.map = null;
Map.markers = [];

$(document).on('pageshow', '#map', function() {
    Map.initMap();
});

Map.initMap = function() {
    $('#map-canvas').css('height', 500);
    Map.map = Map.createMap('map-canvas', 34.87728, 135.576798); // kutc

    utils.getCurrentLocation().done(function(location) {
	var pos = new google.maps.LatLng(location.latitude,
					 location.longitude);

	Map.currentLocation = Map.createMarker(Map.map, 'Current location',
					       location.latitude, location.longitude, false);
    });

    Map.infoWindow = new google.maps.InfoWindow;

    google.maps.event.addListener(Map.map, 'bounds_changed', function() {
	var mapBounds = Map.map.getBounds();
	var sw = mapBounds.getSouthWest();
	var ne = mapBounds.getNorthEast();
	var options = {
	    'lat1': sw.lat(), 'lng1': sw.lng(),
	    'lat2': ne.lat(), 'lng2': ne.lng()
	};
	utils.fetchPosts(options).done(function(json) {
	    // remove existing markers
	    Map.markers.forEach(function(marker, i) {
		marker.setMap(null);
	    });
	    Map.markers = [];

	    for (var i = 0; i < json.length; i++) {
		var marker = Map.createMarker(Map.map, json[i].title,
					      json[i].latitude, json[i].longitude, false);
		marker.data = json[i];
		Map.markers.push(marker);

		google.maps.event.addListener(marker, 'click', function() {
		    var content = Map.jsonToContent(this.data);
		    Map.infoWindow.setContent(content);
		    Map.infoWindow.open(Map.map, this);
		});
	    }
	});

    });
};

Map.createMap = function(id, lat, lng) {
    var mapOptions = {
	center: new google.maps.LatLng(lat, lng),
	zoom: 8,
	mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById(id), mapOptions);
    return map;
};

Map.createMarker = function(map, title, lat, lng, draggable) {
    var marker = new google.maps.Marker({
	position: new google.maps.LatLng(lat, lng),
	map: map,
	title : title,
	draggable: draggable
    });
    return marker;
};

Map.jsonToContent = function(json) {
    var title = json.title;
    var created_at = json.created_at;
    var posted_by = json.posted_by;
    var comment = json.comment;

    var content =
	    '
' +
	    '
' + title + '
' +
	    '
' + created_at + '
' +
	    '
' + posted_by + '
' +
	    '
' + comment + '
' +
	    '
';

    return content;
};<|endoftext|>


<commit_before>'use strict';

var tape = require('tape');

exports = module.exports = function exports(name, harness, fake) {
  (fake || tape)(name, function(testObj) {
    var tests = [];

    function describe(child, harness) {
      tests.push(function() {
        exports(name + ' ' + child, harness, function() {
          testObj.test.apply(testObj, arguments);
        });
      });
    }

    function it(desc, test) {
      tests.push(function() {
        var assert = makeAsserter(testObj, name + ' ' + desc);

        try {
          test(assert);
        } catch (e) {
          testObj.error(e);
        }
      });
    }

    describe.skip =
    it.skip = function(desc) {
      tests.push(function() {
        testObj.skip(name + ' ' + desc);
      });
    };

    harness(it, describe);

    testObj.plan(tests.length);

    for (var i = 0; i < tests.length; i++) {
      tests[i]();
    }
  });
};

exports.skip = function(name, harness) {
  exports(name, harness, function() {
    tape.skip.apply(tape, arguments);
  });
};

exports.only = function(name, harness) {
  exports(name, harness, function() {
    tape.only.apply(tape, arguments);
  });
};

function makeAsserter(t, msg) {
  var assert = {};

  assert.skip = function() {
    t.skip(msg);
  };

  assert.fail = function() {
    t.fail(msg);
  };

  assert.pass = function() {
    t.pass(msg);
  };

  assert.skip = function() {
    t.skip(msg);
  };

  assert.ok =
  assert['true'] =
  assert.assert = function(value) {
    t.ok(value, msg);
  };

  assert.notOk =
  assert['false'] =
  assert.notok = function(value) {
    t.notOk(value, msg);
  };

  assert.error =
  assert.ifError =
  assert.ifErr =
  assert.iferror = function(err) {
    t.error(err, msg);
  };

  assert.equals =
  assert.isEqual =
  assert.is =
  assert.strictEqual =
  assert.strictEquals =
  assert.equal = function(actual, expected) {
    t.equal(actual, expected, msg);
  };

  assert.notEquals =
  assert.notStrictEqual =
  assert.notStrictEquals =
  assert.isNotEqual =
  assert.isNot =
  assert.not =
  assert.doesNotEqual =
  assert.isInequal =
  assert.notEqual = function(actual, expected) {
    t.notEqual(actual, expected, msg);
  };

  assert.deepEqual =
  assert.isEquivalent =
  assert.same =
  assert.deepEqual = function(actual, expected) {
    t.deepEqual(actual, expected, msg);
  };

  assert.notEquivalent =
  assert.notDeeply =
  assert.notSame =
  assert.isNotDeepEqual =
  assert.isNotDeeply =
  assert.isNotEquivalent =
  assert.isInequivalent =
  assert.notDeepEqual = function(actual, expected) {
    t.notDeepEqual(actual, expected, msg);
  };

  assert.notLooseEqual =
  assert.notLooseEquals =
  assert.deepLooseEqual = function(actual, expected) {
    t.deepLooseEqual(actual, expected, msg);
  };

  assert.notDeepLooseEqual = function(actual, expected) {
    t.notDeepLooseEqual(actual, expected, msg);
  };

  assert.throws = function(actual, expected) {
    t.throws(actual, expected, msg);
  };

  assert.doesNotThrow = function(actual, expected) {
    t.doesNotThrow(actual, expected, msg);
  };

  return assert;
}
<commit_msg>fix typo where notLooseEqual is being assigned to deepLooseEqual<commit_after>'use strict';

var tape = require('tape');

exports = module.exports = function exports(name, harness, fake) {
  (fake || tape)(name, function(testObj) {
    var tests = [];

    function describe(child, harness) {
      tests.push(function() {
        exports(name + ' ' + child, harness, function() {
          testObj.test.apply(testObj, arguments);
        });
      });
    }

    function it(desc, test) {
      tests.push(function() {
        var assert = makeAsserter(testObj, name + ' ' + desc);

        try {
          test(assert);
        } catch (e) {
          testObj.error(e);
        }
      });
    }

    describe.skip =
    it.skip = function(desc) {
      tests.push(function() {
        testObj.skip(name + ' ' + desc);
      });
    };

    harness(it, describe);

    testObj.plan(tests.length);

    for (var i = 0; i < tests.length; i++) {
      tests[i]();
    }
  });
};

exports.skip = function(name, harness) {
  exports(name, harness, function() {
    tape.skip.apply(tape, arguments);
  });
};

exports.only = function(name, harness) {
  exports(name, harness, function() {
    tape.only.apply(tape, arguments);
  });
};

function makeAsserter(t, msg) {
  var assert = {};

  assert.skip = function() {
    t.skip(msg);
  };

  assert.fail = function() {
    t.fail(msg);
  };

  assert.pass = function() {
    t.pass(msg);
  };

  assert.skip = function() {
    t.skip(msg);
  };

  assert.ok =
  assert['true'] =
  assert.assert = function(value) {
    t.ok(value, msg);
  };

  assert.notOk =
  assert['false'] =
  assert.notok = function(value) {
    t.notOk(value, msg);
  };

  assert.error =
  assert.ifError =
  assert.ifErr =
  assert.iferror = function(err) {
    t.error(err, msg);
  };

  assert.equals =
  assert.isEqual =
  assert.is =
  assert.strictEqual =
  assert.strictEquals =
  assert.equal = function(actual, expected) {
    t.equal(actual, expected, msg);
  };

  assert.notEquals =
  assert.notStrictEqual =
  assert.notStrictEquals =
  assert.isNotEqual =
  assert.isNot =
  assert.not =
  assert.doesNotEqual =
  assert.isInequal =
  assert.notEqual = function(actual, expected) {
    t.notEqual(actual, expected, msg);
  };

  assert.deepEqual =
  assert.isEquivalent =
  assert.same =
  assert.deepEqual = function(actual, expected) {
    t.deepEqual(actual, expected, msg);
  };

  assert.notEquivalent =
  assert.notDeeply =
  assert.notSame =
  assert.isNotDeepEqual =
  assert.isNotDeeply =
  assert.isNotEquivalent =
  assert.isInequivalent =
  assert.notDeepEqual = function(actual, expected) {
    t.notDeepEqual(actual, expected, msg);
  };

  assert.looseEqual =
  assert.looseEquals =
  assert.deepLooseEqual = function(actual, expected) {
    t.deepLooseEqual(actual, expected, msg);
  };

  assert.notLooseEqual =
  assert.notLooseEquals =
  assert.notDeepLooseEqual = function(actual, expected) {
    t.notDeepLooseEqual(actual, expected, msg);
  };

  assert.throws = function(actual, expected) {
    t.throws(actual, expected, msg);
  };

  assert.doesNotThrow = function(actual, expected) {
    t.doesNotThrow(actual, expected, msg);
  };

  return assert;
}
<|endoftext|>