<commit_before>describe('instantsearch', function () {

  var STATES = [
    'Alabama'
  , 'Alaska'
  , 'American Samoa'
  , 'Arizona'
  , 'Arkansas'
  , 'California'
  , 'Colorado'
  , 'Connecticut'
  , 'Delaware'
  , 'District Of Columbia'
  , 'Federated States Of Micronesia'
  , 'Florida'
  , 'Georgia'
  , 'Guam'
  , 'Hawaii'
  , 'Idaho'
  , 'Illinois'
  , 'Indiana'
  , 'Iowa'
  , 'Kansas'
  , 'Kentucky'
  , 'Louisiana'
  , 'Maine'
  , 'Marshall Islands'
  , 'Maryland'
  , 'Massachusetts'
  , 'Michigan'
  , 'Minnesota'
  , 'Mississippi'
  , 'Missouri'
  , 'Montana'
  , 'Nebraska'
  , 'Nevada'
  , 'New Hampshire'
  , 'New Jersey'
  , 'New Mexico'
  , 'New York'
  , 'North Carolina'
  , 'North Dakota'
  , 'Northern Mariana Islands'
  , 'Ohio'
  , 'Oklahoma'
  , 'Oregon'
  , 'Palau'
  , 'Pennsylvania'
  , 'Puerto Rico'
  , 'Rhode Island'
  , 'South Carolina'
  , 'South Dakota'
  , 'Tennessee'
  , 'Texas'
  , 'Utah'
  , 'Vermont'
  , 'Virgin Islands'
  , 'Virginia'
  , 'Washington'
  , 'West Virginia'
  , 'Wisconsin'
  , 'Wyoming'
  ];

  beforeEach(function () {
    this.$sandbox = $('#sandbox');

    this.$input = $('<input>');
    this.$input.appendTo('#sandbox');
  });

  afterEach(function () {
    this.$sandbox.empty();

    this.$sandbox = null;
    this.$input = null;
  });

  describe('when initialized', function () {

    it('replaces input with instant search field', function () {
      var is = this.$input.instantSearch();

      $('#sandbox').html().should.equal(
        '
<input class="instainput" autocomplete="off" spellcheck="false"><input class="instaghost" autocomplete="off" disabled="">
'
      );
    });

  });

  describe('when input keydown event fires', function () {

    describe('and key code is', function () {

      var IGNORED_KEY_CODES = {
        'shift': 16,
        'ctrl': 17,
        'alt': 18,
        'pause/break': 19,
        'caps lock': 20,
        'page up': 33,
        'page down': 34,
        'end': 35,
        'home': 36,
        'left': 37,
        'insert': 45,
        'windows key/cmd': 91,
        'select': 93,
        'f1': 112,
        'f2': 113,
        'f3': 114,
        'f4': 115,
        'f5': 116,
        'f6': 117,
        'f7': 118,
        'f8': 119,
        'f9': 120,
        'f10': 121,
        'f11': 122,
        'f12': 123,
        'f13': 124,
        'f14': 125,
        'f15': 126
      };

      $.each(IGNORED_KEY_CODES, function (key, val) {

        var keyCode = IGNORED_KEY_CODES[key];

        describe(key, function () {

          beforeEach(function () {
            sinon.stub($.InstantSearch.prototype, 'navigate');
            sinon.stub($.InstantSearch.prototype, 'complete');
            sinon.stub($.InstantSearch.prototype, 'trigger');
            sinon.stub($.InstantSearch.prototype, 'search');

            this.$input.instantSearch();
            this.$instainput = $('.instainput');
          });

          afterEach(function () {
            $.InstantSearch.prototype.navigate.restore();
            $.InstantSearch.prototype.complete.restore();
            $.InstantSearch.prototype.trigger.restore();
            $.InstantSearch.prototype.search.restore();

            this.$instainput = null;
          });

          it('does not set input value', function () {
            this.$instainput.trigger($.Event('keydown', { keyCode: keyCode }));

            this.$instainput.val().should.be.empty;
          });

          it('does not navigate', function () {
            this.$instainput.trigger($.Event('keydown', { keyCode: keyCode }));

            $.InstantSearch.prototype.navigate.should.not.have.been.called;
          });

          it('does not complete', function () {
            this.$instainput.trigger($.Event('keydown', { keyCode: keyCode }));

            $.InstantSearch.prototype.complete.should.not.have.been.called;
          });

          it('does not trigger', function () {
            this.$instainput.trigger($.Event('keydown', { keyCode: keyCode }));

            $.InstantSearch.prototype.trigger.should.not.have.been.called;
          });

          it('does not search', function () {
            this.$instainput.trigger($.Event('keydown', { keyCode: keyCode }));

            $.InstantSearch.prototype.search.should.not.have.been.called;
          });

        });

      });

      describe('up', function () {

        var keyCode = 38;

        describe('and no results are displayed', function () {

          beforeEach(function () {
            this.$input.instantSearch();
            this.$instainput = $('.instainput');
          });

          afterEach(function () {
            this.$instainput = null;
          });

          it('does not highlight a result', function () {
            this.$instainput.trigger($.Event('keydown', { keyCode: keyCode }));

            $('.instahighlight').length.should.equal(0);
          });

        });

        describe('and results are displayed', function () {

          beforeEach(function () {
            this.$input.instantSearch({
              source: function (req, res) {
                var re = new RegExp(req.term, 'i'),
                    results;

                results = $.grep(STATES, function (state) {
                  return state.match(re);
                });

                res(results, null);
              }
            });

            this.$instainput = $('.instainput');
            this.$results = $('.instaresults');

            // "O" = 79
            this.$instainput.val("O");
            this.$instainput.trigger($.Event('keydown', { keyCode: 79 }));
          });

          afterEach(function () {
            this.$results.remove();

            this.$instainput = null;
            this.$results = null;
          });

          describe('and without highlight', function () {

            it('highlights last result', function () {
              var results = this.$results.find('.instaresult');

              console.log(this.$results.html());
            });

          });

          describe('and on first result', function () {
          });

          describe('and on last result', function () {
          });

        });

        it('prevents default', function (done) {
          this.$input.instantSearch();
          this.$instainput = $('.instainput');
          this.$instainput.on('keydown', function (e) {
            e.isDefaultPrevented().should.be.true;

            done();
          });
          this.$instainput.trigger($.Event('keydown', { keyCode: keyCode }));
        });

      });

      describe('right', function () {
      });

      describe('down', function () {
      });

      describe('tab', function () {
      });

      describe('return', function () {
      });

      describe('escape', function () {
      });

    });

  });

  describe('when cut event fires', function () {
  });

  describe('when copy event fires', function () {
  });

  describe('when close on blur option is set to true', function () {
  });

  describe('when close on blur option is set to false', function () {
  });

  describe('when mouse enters search result', function () {
  });

  describe('when mouse leaves search result', function () {
  });

  describe('when mousedown event fires on search results', function () {
  });

});
<commit_msg>Add tests for instantsearch initialization.<commit_after>describe('instantsearch', function () {

  var STATES = [
    'Alabama'
  , 'Alaska'
  , 'American Samoa'
  , 'Arizona'
  , 'Arkansas'
  , 'California'
  , 'Colorado'
  , 'Connecticut'
  , 'Delaware'
  , 'District Of Columbia'
  , 'Federated States Of Micronesia'
  , 'Florida'
  , 'Georgia'
  , 'Guam'
  , 'Hawaii'
  , 'Idaho'
  , 'Illinois'
  , 'Indiana'
  , 'Iowa'
  , 'Kansas'
  , 'Kentucky'
  , 'Louisiana'
  , 'Maine'
  , 'Marshall Islands'
  , 'Maryland'
  , 'Massachusetts'
  , 'Michigan'
  , 'Minnesota'
  , 'Mississippi'
  , 'Missouri'
  , 'Montana'
  , 'Nebraska'
  , 'Nevada'
  , 'New Hampshire'
  , 'New Jersey'
  , 'New Mexico'
  , 'New York'
  , 'North Carolina'
  , 'North Dakota'
  , 'Northern Mariana Islands'
  , 'Ohio'
  , 'Oklahoma'
  , 'Oregon'
  , 'Palau'
  , 'Pennsylvania'
  , 'Puerto Rico'
  , 'Rhode Island'
  , 'South Carolina'
  , 'South Dakota'
  , 'Tennessee'
  , 'Texas'
  , 'Utah'
  , 'Vermont'
  , 'Virgin Islands'
  , 'Virginia'
  , 'Washington'
  , 'West Virginia'
  , 'Wisconsin'
  , 'Wyoming'
  ];

  beforeEach(function () {
    this.$sandbox = $('#sandbox');

    this.$input = $('<input>');
    this.$input.appendTo('#sandbox');
  });

  afterEach(function () {
    this.$input.trigger('instantsearch.destroy');
    this.$sandbox.empty();

    this.$sandbox = null;
    this.$input = null;
  });

  describe('when initialized', function () {

    describe('in wrapping input', function () {

      it('wraps input in a div', function () {
        this.$input.instantSearch();

        this.$input[0].parentNode.className.should.equal('instasearch-wrapper');
      });

      it('adds .instainput class to input', function () {
        this.$input.addClass('test');
        this.$input.instantSearch();

        this.$input[0].className.should.equal('test instainput');
      });

      it('sets input autocomplete to \'off\'', function () {
        this.$input.instantSearch();

        this.$input.attr('autocomplete').should.equal('off');
      });

      it('creates a ghost input', function () {
        this.$input.addClass('test');
        this.$input.instantSearch();

        this.$input.next()[0].className.should.equal('test instaghost');
      });

    });

    describe('in appending results container to body', function () {

      it('initially hides results', function () {
        this.$input.instantSearch();

        $('.instaresults').css('display').should.equal('none');
      });

    });

  });

  describe('when input keydown event fires', function () {

    describe('and key code is', function () {

      var IGNORED_KEY_CODES = {
        'shift': 16,
        'ctrl': 17,
        'alt': 18,
        'pause/break': 19,
        'caps lock': 20,
        'page up': 33,
        'page down': 34,
        'end': 35,
        'home': 36,
        'left': 37,
        'insert': 45,
        'windows key/cmd': 91,
        'select': 93,
        'f1': 112,
        'f2': 113,
        'f3': 114,
        'f4': 115,
        'f5': 116,
        'f6': 117,
        'f7': 118,
        'f8': 119,
        'f9': 120,
        'f10': 121,
        'f11': 122,
        'f12': 123,
        'f13': 124,
        'f14': 125,
        'f15': 126
      };

      $.each(IGNORED_KEY_CODES, function (key, val) {

        var keyCode = IGNORED_KEY_CODES[key];

        describe(key, function () {

          beforeEach(function () {
            sinon.stub($.InstantSearch.prototype, 'navigate');
            sinon.stub($.InstantSearch.prototype, 'complete');
            sinon.stub($.InstantSearch.prototype, 'trigger');
            sinon.stub($.InstantSearch.prototype, 'search');

            this.$input.instantSearch();
            this.$instainput = $('.instainput');
          });

          afterEach(function () {
            $.InstantSearch.prototype.navigate.restore();
            $.InstantSearch.prototype.complete.restore();
            $.InstantSearch.prototype.trigger.restore();
            $.InstantSearch.prototype.search.restore();

            this.$instainput = null;
          });

          it('does not set input value', function () {
            this.$instainput.trigger($.Event('keydown', { keyCode: keyCode }));

            this.$instainput.val().should.be.empty;
          });

          it('does not navigate', function () {
            this.$instainput.trigger($.Event('keydown', { keyCode: keyCode }));

            $.InstantSearch.prototype.navigate.should.not.have.been.called;
          });

          it('does not complete', function () {
            this.$instainput.trigger($.Event('keydown', { keyCode: keyCode }));

            $.InstantSearch.prototype.complete.should.not.have.been.called;
          });

          it('does not trigger', function () {
            this.$instainput.trigger($.Event('keydown', { keyCode: keyCode }));

            $.InstantSearch.prototype.trigger.should.not.have.been.called;
          });

          it('does not search', function () {
            this.$instainput.trigger($.Event('keydown', { keyCode: keyCode }));

            $.InstantSearch.prototype.search.should.not.have.been.called;
          });

        });

      });

      describe('up', function () {

        var keyCode = 38;

        describe('and no results are displayed', function () {

          beforeEach(function () {
            this.$input.instantSearch();
            this.$instainput = $('.instainput');
          });

          afterEach(function () {
            this.$instainput = null;
          });

          it('does not highlight a result', function () {
            this.$instainput.trigger($.Event('keydown', { keyCode: keyCode }));

            $('.instahighlight').length.should.equal(0);
          });

        });

        describe('and results are displayed', function () {

          beforeEach(function () {
            this.$input.instantSearch({
              source: function (req, res) {
                var re = new RegExp(req.term, 'i'),
                    results;

                results = $.grep(STATES, function (state) {
                  return state.match(re);
                });

                res(results, null);
              }
            });

            this.$instainput = $('.instainput');
            this.$results = $('.instaresults');

            // "O" = 79
            this.$instainput.val("O");
            this.$instainput.trigger($.Event('keydown', { keyCode: 79 }));
          });

          afterEach(function () {
            this.$results.remove();

            this.$instainput = null;
            this.$results = null;
          });

          describe('and without highlight', function () {

            it('highlights last result', function () {
              var results = this.$results.find('.instaresult');

              console.log(this.$results.html());
            });

          });

          describe('and on first result', function () {
          });

          describe('and on last result', function () {
          });

        });

        it('prevents default', function (done) {
          this.$input.instantSearch();
          this.$instainput = $('.instainput');
          this.$instainput.on('keydown', function (e) {
            e.isDefaultPrevented().should.be.true;

            done();
          });
          this.$instainput.trigger($.Event('keydown', { keyCode: keyCode }));
        });

      });

      describe('right', function () {
      });

      describe('down', function () {
      });

      describe('tab', function () {
      });

      describe('return', function () {
      });

      describe('escape', function () {
      });

    });

  });

  describe('when cut event fires', function () {
  });

  describe('when copy event fires', function () {
  });

  describe('when close on blur option is set to true', function () {
  });

  describe('when close on blur option is set to false', function () {
  });

  describe('when mouse enters search result', function () {
  });

  describe('when mouse leaves search result', function () {
  });

  describe('when mousedown event fires on search results', function () {
  });

  describe('when destroyed', function () {
  });

});
<|endoftext|>


<commit_before>import moment from 'moment';

const BYTES_PER_GIGABYTE = 1000000000;
const NANOSECONDS_PER_MILLISECOND = 1000000;

const inGigaBytes = (bytes) => {
  return (bytes / BYTES_PER_GIGABYTE).toFixed(2);
};

const inMilliseconds = (nanoseconds) => {
  return nanoseconds / NANOSECONDS_PER_MILLISECOND;
};

export const humanUptime = (uptimeInNanoseconds) => {
  const milliseconds = inMilliseconds(uptimeInNanoseconds);

  return moment.duration(milliseconds, 'milliseconds').humanize();
};

export const humanMemory = (bytes) => {
  return `${inGigaBytes(bytes)} GB`;
};

export default { humanMemory, humanUptime };
<commit_msg>Calc gigabytes by 1024 (#1075)<commit_after>import moment from 'moment';

const BYTES_PER_GIGABYTE = 1074000000;
const NANOSECONDS_PER_MILLISECOND = 1000000;

const inGigaBytes = (bytes) => {
  return (bytes / BYTES_PER_GIGABYTE).toFixed(2);
};

const inMilliseconds = (nanoseconds) => {
  return nanoseconds / NANOSECONDS_PER_MILLISECOND;
};

export const humanUptime = (uptimeInNanoseconds) => {
  const milliseconds = inMilliseconds(uptimeInNanoseconds);

  return moment.duration(milliseconds, 'milliseconds').humanize();
};

export const humanMemory = (bytes) => {
  return `${inGigaBytes(bytes)} GB`;
};

export default { humanMemory, humanUptime };
<|endoftext|>


<commit_before>import Service, { inject as service } from '@ember/service';
import { computed } from '@ember/object';
import PromiseObject from '../utils/classes/promise-object';
import PromiseArray from '../utils/classes/promise-array';
import { namespace } from '../adapters/application';

export default Service.extend({
  token: service(),
  store: service(),

  leader: computed('activeRegion', function() {
    const token = this.get('token');

    return PromiseObject.create({
      promise: token
        .authorizedRequest(`/${namespace}/status/leader`)
        .then(res => res.json())
        .then(rpcAddr => ({ rpcAddr }))
        .then(leader => {
          // Dirty self so leader can be used as a dependent key
          this.notifyPropertyChange('leader.rpcAddr');
          return leader;
        }),
    });
  }),

  defaultRegion: computed(function() {
    const token = this.get('token');
    return PromiseObject.create({
      promise: token
        .authorizedRawRequest(`/${namespace}/agent/members`)
        .then(res => res.json())
        .then(json => {
          return { region: json.ServerRegion };
        }),
    });
  }),

  regions: computed(function() {
    const token = this.get('token');

    return PromiseArray.create({
      promise: token.authorizedRawRequest(`/${namespace}/regions`).then(res => res.json()),
    });
  }),

  activeRegion: computed('regions.[]', {
    get() {
      const regions = this.get('regions');
      const region = window.localStorage.nomadActiveRegion;

      if (regions.includes(region)) {
        return region;
      }

      // If the region in localStorage is no longer in the cluster, it needs to
      // be cleared from localStorage
      // this.set('activeRegion', null);
      return null;
    },
    set(key, value) {
      if (value == null) {
        window.localStorage.removeItem('nomadActiveRegion');
      } else {
        // All localStorage values are strings. Stringify first so
        // the return value is consistent with what is persisted.
        const strValue = value + '';
        window.localStorage.nomadActiveRegion = strValue;
        return strValue;
      }
    },
  }),

  shouldShowRegions: computed('regions.[]', function() {
    return this.get('regions.length') > 1;
  }),

  shouldIncludeRegion: computed(
    'activeRegion',
    'defaultRegion.region',
    'shouldShowRegions',
    function() {
      return (
        this.get('shouldShowRegions') &&
        this.get('activeRegion') !== this.get('defaultRegion.region')
      );
    }
  ),

  namespaces: computed('activeRegion', function() {
    return PromiseArray.create({
      promise: this.get('store')
        .findAll('namespace')
        .then(namespaces => namespaces.compact()),
    });
  }),

  shouldShowNamespaces: computed('namespaces.[]', function() {
    const namespaces = this.get('namespaces').toArray();
    return namespaces.length && namespaces.some(namespace => namespace.get('id') !== 'default');
  }),

  activeNamespace: computed('namespaces.[]', {
    get() {
      const namespaceId = window.localStorage.nomadActiveNamespace || 'default';
      const namespace = this.get('namespaces').findBy('id', namespaceId);

      if (namespace) {
        return namespace;
      }

      // If the namespace is localStorage is no longer in the cluster, it needs to
      // be cleared from localStorage
      this.set('activeNamespace', null);
      return this.get('namespaces').findBy('id', 'default');
    },
    set(key, value) {
      if (value == null) {
        window.localStorage.removeItem('nomadActiveNamespace');
      } else if (typeof value === 'string') {
        window.localStorage.nomadActiveNamespace = value;
        return this.get('namespaces').findBy('id', value);
      } else {
        window.localStorage.nomadActiveNamespace = value.get('name');
        return value;
      }
    },
  }),

  reset() {
    this.set('activeNamespace', null);
  },
});
<commit_msg>Handle errors when getting regions or the default regions<commit_after>import Service, { inject as service } from '@ember/service';
import { computed } from '@ember/object';
import { copy } from '@ember/object/internals';
import PromiseObject from '../utils/classes/promise-object';
import PromiseArray from '../utils/classes/promise-array';
import { namespace } from '../adapters/application';

// When the request isn't ok (e.g., forbidden) handle gracefully
const jsonWithDefault = defaultResponse => res =>
  res.ok ? res.json() : copy(defaultResponse, true);

export default Service.extend({
  token: service(),
  store: service(),

  leader: computed('activeRegion', function() {
    const token = this.get('token');

    return PromiseObject.create({
      promise: token
        .authorizedRequest(`/${namespace}/status/leader`)
        .then(res => res.json())
        .then(rpcAddr => ({ rpcAddr }))
        .then(leader => {
          // Dirty self so leader can be used as a dependent key
          this.notifyPropertyChange('leader.rpcAddr');
          return leader;
        }),
    });
  }),

  defaultRegion: computed(function() {
    const token = this.get('token');
    return PromiseObject.create({
      promise: token
        .authorizedRawRequest(`/${namespace}/agent/members`)
        .then(jsonWithDefault({}))
        .then(json => {
          return { region: json.ServerRegion };
        }),
    });
  }),

  regions: computed(function() {
    const token = this.get('token');

    return PromiseArray.create({
      promise: token.authorizedRawRequest(`/${namespace}/regions`).then(jsonWithDefault([])),
    });
  }),

  activeRegion: computed('regions.[]', {
    get() {
      const regions = this.get('regions');
      const region = window.localStorage.nomadActiveRegion;

      if (regions.includes(region)) {
        return region;
      }

      // If the region in localStorage is no longer in the cluster, it needs to
      // be cleared from localStorage
      // this.set('activeRegion', null);
      return null;
    },
    set(key, value) {
      if (value == null) {
        window.localStorage.removeItem('nomadActiveRegion');
      } else {
        // All localStorage values are strings. Stringify first so
        // the return value is consistent with what is persisted.
        const strValue = value + '';
        window.localStorage.nomadActiveRegion = strValue;
        return strValue;
      }
    },
  }),

  shouldShowRegions: computed('regions.[]', function() {
    return this.get('regions.length') > 1;
  }),

  shouldIncludeRegion: computed(
    'activeRegion',
    'defaultRegion.region',
    'shouldShowRegions',
    function() {
      return (
        this.get('shouldShowRegions') &&
        this.get('activeRegion') !== this.get('defaultRegion.region')
      );
    }
  ),

  namespaces: computed('activeRegion', function() {
    return PromiseArray.create({
      promise: this.get('store')
        .findAll('namespace')
        .then(namespaces => namespaces.compact()),
    });
  }),

  shouldShowNamespaces: computed('namespaces.[]', function() {
    const namespaces = this.get('namespaces').toArray();
    return namespaces.length && namespaces.some(namespace => namespace.get('id') !== 'default');
  }),

  activeNamespace: computed('namespaces.[]', {
    get() {
      const namespaceId = window.localStorage.nomadActiveNamespace || 'default';
      const namespace = this.get('namespaces').findBy('id', namespaceId);

      if (namespace) {
        return namespace;
      }

      // If the namespace is localStorage is no longer in the cluster, it needs to
      // be cleared from localStorage
      this.set('activeNamespace', null);
      return this.get('namespaces').findBy('id', 'default');
    },
    set(key, value) {
      if (value == null) {
        window.localStorage.removeItem('nomadActiveNamespace');
      } else if (typeof value === 'string') {
        window.localStorage.nomadActiveNamespace = value;
        return this.get('namespaces').findBy('id', value);
      } else {
        window.localStorage.nomadActiveNamespace = value.get('name');
        return value;
      }
    },
  }),

  reset() {
    this.set('activeNamespace', null);
  },
});
<|endoftext|>


<commit_before>import ghUrl from 'github-url-to-object'
import cliPackage from '../../../package.json'
import versionRanges from '../../versionRanges'
import sortObject from 'deep-sort-object'

const manifestPropOrder = [
  'name', 'private', 'version', 'description', 'main', 'author', 'license', 'scripts',
  'keywords', 'dependencies', 'devDependencies'
]

function getCommonManifest(data) {
  const pkg = {
    name: data.name,
    version: '1.0.0',
    description: data.description,
    author: data.author,
    license: data.license,
    devDependencies: {}
  }

  if (pkg.license === 'UNLICENSED') {
    pkg.private = true
  }

  if (data.gitRemote) {
    pkg.repository = {
      type: 'git',
      url: data.gitRemote
    }
  }

  const gh = (data.gitRemote || '').includes('github.com/') && ghUrl(data.gitRemote)
  if (gh) {
    Object.assign(pkg, {
      homepage: `${gh.https_url}#readme`,
      bugs: {url: `${gh.https_url}/issues`}
    })
  }

  return pkg
}

export function createPackageManifest(data) {
  const pkg = Object.assign(getCommonManifest(data), {
    main: 'package.json',
    keywords: ['sanity'],
    scripts: {
      start: 'sanity start',
      test: 'sanity test'
    },
    dependencies: sortObject(
      Object.assign(
        {[cliPackage.name]: `^${cliPackage.version}`},
        versionRanges.core
      )
    )
  })

  return serializeManifest(pkg)
}

function getSanityStyleManifestProps() {
  return {
    main: 'lib/index.js',
    dependencies: versionRanges.plugin.prod,
    devDependencies: versionRanges.plugin.dev,
    scripts: {
      compile: 'babel src --copy-files --out-dir lib',
      prepublish: 'in-publish && npm run compile || not-in-publish',
      postpublish: 'rimraf lib',
      test: 'eslint .'
    }
  }
}

export function createPluginManifest(data, opts = {}) {
  const sanityStyleProps = opts.sanityStyle
    ? getSanityStyleManifestProps()
    : {}

  const pkg = Object.assign(getCommonManifest(data), {
    main: 'src/plugin.js',
    scripts: {test: 'echo "Error: no test specified" && exit 1'},
    keywords: ['sanity', 'sanity-plugin'],
    dependencies: {}
  }, sanityStyleProps)

  return serializeManifest(pkg)
}

function getSanityPluginManifest(data) {
  const prefix = data.name.replace(/^sanity-plugin-/, '')
  return {
    roles: [{
      name: `component:${prefix}/my-component`,
      srcPath: 'src/myComponent.js',
      path: 'lib/myComponent.js'
    }]
  }
}

export function createSanityManifest(data, {isPlugin}) {
  const manifest = isPlugin ? getSanityPluginManifest(data) : {
    api: {
      dataset: data.dataset,
    },

    plugins: [
      '@sanity/base',
      '@sanity/components',
      '@sanity/default-layout',
      '@sanity/default-login',
      '@sanity/desk-tool'
    ],

    roles: [
      {
        name: 'schema:@sanity/base/schema',
        srcPath: './schemas/schema.js',
        path: './schemas/schema.js'
      }
    ]
  }

  return `${JSON.stringify(manifest, null, 2)}\n`
}

function serializeManifest(src) {
  const props = manifestPropOrder.concat(Object.keys(src))
  const ordered = props.reduce((target, prop) => {
    if (typeof src[prop] !== 'undefined' && typeof target[prop] === 'undefined') {
      target[prop] = src[prop]
    }

    return target
  }, {})

  return `${JSON.stringify(ordered, null, 2)}\n`
}
<commit_msg>Bootstrap installations with root property in manifest<commit_after>import ghUrl from 'github-url-to-object'
import cliPackage from '../../../package.json'
import versionRanges from '../../versionRanges'
import sortObject from 'deep-sort-object'

const manifestPropOrder = [
  'name', 'private', 'version', 'description', 'main', 'author', 'license', 'scripts',
  'keywords', 'dependencies', 'devDependencies'
]

function getCommonManifest(data) {
  const pkg = {
    name: data.name,
    version: '1.0.0',
    description: data.description,
    author: data.author,
    license: data.license,
    devDependencies: {}
  }

  if (pkg.license === 'UNLICENSED') {
    pkg.private = true
  }

  if (data.gitRemote) {
    pkg.repository = {
      type: 'git',
      url: data.gitRemote
    }
  }

  const gh = (data.gitRemote || '').includes('github.com/') && ghUrl(data.gitRemote)
  if (gh) {
    Object.assign(pkg, {
      homepage: `${gh.https_url}#readme`,
      bugs: {url: `${gh.https_url}/issues`}
    })
  }

  return pkg
}

export function createPackageManifest(data) {
  const pkg = Object.assign(getCommonManifest(data), {
    main: 'package.json',
    keywords: ['sanity'],
    scripts: {
      start: 'sanity start',
      test: 'sanity test'
    },
    dependencies: sortObject(
      Object.assign(
        {[cliPackage.name]: `^${cliPackage.version}`},
        versionRanges.core
      )
    )
  })

  return serializeManifest(pkg)
}

function getSanityStyleManifestProps() {
  return {
    main: 'lib/index.js',
    dependencies: versionRanges.plugin.prod,
    devDependencies: versionRanges.plugin.dev,
    scripts: {
      compile: 'babel src --copy-files --out-dir lib',
      prepublish: 'in-publish && npm run compile || not-in-publish',
      postpublish: 'rimraf lib',
      test: 'eslint .'
    }
  }
}

export function createPluginManifest(data, opts = {}) {
  const sanityStyleProps = opts.sanityStyle
    ? getSanityStyleManifestProps()
    : {}

  const pkg = Object.assign(getCommonManifest(data), {
    main: 'src/plugin.js',
    scripts: {test: 'echo "Error: no test specified" && exit 1'},
    keywords: ['sanity', 'sanity-plugin'],
    dependencies: {}
  }, sanityStyleProps)

  return serializeManifest(pkg)
}

function getSanityPluginManifest(data) {
  const prefix = data.name.replace(/^sanity-plugin-/, '')
  return {
    roles: [{
      name: `component:${prefix}/my-component`,
      srcPath: 'src/myComponent.js',
      path: 'lib/myComponent.js'
    }]
  }
}

export function createSanityManifest(data, {isPlugin}) {
  const manifest = isPlugin ? getSanityPluginManifest(data) : {
    root: true,

    api: {
      dataset: data.dataset,
    },

    plugins: [
      '@sanity/base',
      '@sanity/components',
      '@sanity/default-layout',
      '@sanity/default-login',
      '@sanity/desk-tool'
    ],

    roles: [
      {
        name: 'schema:@sanity/base/schema',
        srcPath: './schemas/schema.js',
        path: './schemas/schema.js'
      }
    ]
  }

  return `${JSON.stringify(manifest, null, 2)}\n`
}

function serializeManifest(src) {
  const props = manifestPropOrder.concat(Object.keys(src))
  const ordered = props.reduce((target, prop) => {
    if (typeof src[prop] !== 'undefined' && typeof target[prop] === 'undefined') {
      target[prop] = src[prop]
    }

    return target
  }, {})

  return `${JSON.stringify(ordered, null, 2)}\n`
}
<|endoftext|>


<commit_before>var Widgets = {
	connections : [
		{
			id : 1,
			dir1 : "is my classmate",
			dir2 : "is my classmate"
		},
		{
			id: 2,
			dir1 : "is my supervisor",
			dir2 : "is being supervised by me"
		},
		{
			id: 3,
			dir1 : "is being supervised by me",
			dir2 : "is my supervisor"
		},
		{
			id: 4,
			dir1 : "is my lecturer",
			dir2 : "is my student"
		},
		{
			id: 5,
			dir1 : "is my student",
			dir2 : "is my lecturer"
		},
		{
			id: 6,
			dir1 : "is my colleague",
			dir2 : "is my colleague"
		},
		{
			id: 7,
			dir1 : "is my college mate",
			dir2 : "is my college mate"
		},
		{
			id: 8,
			dir1 : "shares an interest with me",
			dir2 : "shares an interest with me"
		},
		{
			id: 9,
			dir1 : "is something else",
			dir2 : "is something else"
		}
	],
	groups:[
		"Administrators",
		"Lecturers & Supervisors",
		"Researchers",
		"Students"],
	layouts : {
		dev :
		{
			name:"Dev Layout",
			widths:[25,50,25]
		},
		twocolumn :
		{
			name:"Two equal columns",
			widths:[50,50]
		},
		threecolumn :
		{
			name:"Three equal columns",
			widths:[33,33,33]
		},
		twocolumnspecial :
		{
			name:"One wide and one narrow column",
			widths:[66,33]
		},
		fourcolumn :
		{
			name:"Four equal columns",
			widths:[25,25,25,25]
		}
		//,
		//onecolumn :
		//{
		//	name:"One column",
		//	widths:[100]
		//}
	},
	widgets: {
		sites :
		{
			description:"Listing of the sites I'm a member of\r\n",
			iframe:0,
			url:"/devwidgets/sites/sites.html",
			name:"Sites",
			id:"sites",
			personalportal:1,
			siteportal:0,
			img:"/dev/img/sites.png"
		},
		myprofile :
		{
			description:"My Personal Profile\r\n",
			iframe:0,
			url:"/devwidgets/myprofile/myprofile.html",
			name:"My Profile",
			id:"myprofile",
			personalportal:1,
			siteportal:0,
			img:"/dev/img/myprofile.png"
		},
		helloworld :
		{
			description:"Sakai Hackathon Example\r\n",
			iframe:0,
			url:"/devwidgets/helloworld/helloworld.html",
			name:"Hello World",
			id:"helloworld",
			personalportal:1,
			siteportal:0,
			img:"/dev/img/myprofile.png"
		},
		sparkline :
		{
			description:"Sparkline\r\n",
			iframe:0,
			url:"/devwidgets/sparkline/sparkline.html",
			name:"Sparkline",
			id:"sparkline",
			personalportal:0,
			siteportal:1,
			img:"/dev/img/sparkline.png"
		},
		createsite :
		{
			description:"Create site\r\n",
			iframe:0,
			url:"/devwidgets/createsite/createsite.html",
			name:"Create Site",
			id:"createsite",
			personalportal:0,
			siteportal:0,
			img:"/dev/img/sites.png"
		},
		myfriends :
		{
			description:"A list of my connections\r\n",
			iframe:0,
			url:"/devwidgets/myfriends/myfriends.html",
			name:"My Connections",
			id:"myfriends",
			personalportal:1,
			siteportal:0,
			img:"/dev/img/myprofile.png",
			multipleinstance: false
		},
		announcementupdates :
		{
			description:"A list of Announcements & Updates\r\n",
			iframe:0,
			url:"/devwidgets/announcementupdates/announcementupdates.html",
			name:"Announcements & Updates",
			id:"announcementupdates",
			personalportal:0,
			siteportal:1,
			img:"/dev/img/myprofile.png",
			multipleinstance: false
		},
		pagemanagement :
		{
			description:"pagemanagement",
			iframe:0,
			url:"/devwidgets/pagemanagement/pagemanagement.html",
			name:"pagemanagement",
			id:"pagemanagement",
			personalportal:0,
			siteportal:0
		},
		mypreferences :
		{
			description:"mypreferences",
			iframe:0,
			url:"/devwidgets/mypreferences/mypreferences.html",
			name:"mypreferences",
			id:"mypreferences",
			personalportal:0,
			siteportal:0
		},
		myinbox :
		{
			description:"myinbox",
			iframe:0,
			url:"/devwidgets/myinbox/myinbox.html",
			name:"myinbox",
			id:"myinbox",
			personalportal:0,
			siteportal:0
		},
		sitemembers :
		{
			description:"Shows a list of all of the members of this site",
			iframe:0,
			url:"/devwidgets/sitemembers/sitemembers.html",
			name:"Site Members",
			id:"sitemembers",
			personalportal:0,
			siteportal:1,
			img:"/devwidgets/sitemembers/images/icon.png"
		},
		chat :
		{
			description:"chat",
			iframe:0,
			url:"/devwidgets/chat/chat.html",
			name:"chat",
			id:"chat",
			personalportal:0,
			siteportal:0
		},
		youtubevideo :
		{
			description:"YouTube Video",
			iframe:0,
			url:"/devwidgets/youtubevideo/youtubevideo.html",
			name:"YouTube Video",
			id:"youtubevideo",
			personalportal:0,
			siteportal:0,
			ca:1,
			img:"/devwidgets/youtubevideo/images/icon.png"
		},
		tangler :
		{
			description:"Tangler Forum",
			iframe:0,
			url:"/devwidgets/tangler/tangler.html",
			name:"Tangler Forum",
			id:"tangler",
			personalportal:0,
			siteportal:0,
			ca:1,
			img:"/devwidgets/tangler/images/tangler.png"
		},
		singlefile :
		{
			description:"Single File Reference",
			iframe:0,
			url:"/devwidgets/singlefile/singlefile.html",
			name:"Single File Reference",
			id:"singlefile",
			personalportal:0,
			siteportal:0,
			ca:0,
			img:"/devwidgets/singlefile/images/singlefile.png"
		},
		comments :
		{
			description:"Comments",
			iframe:0,
			url:"/devwidgets/comments/comments.html",
			name:"Comments",
			id:"comments",
			personalportal:0,
			siteportal:0,
			ca:0,
			img:"/devwidgets/comments/images/icon.png"
		},
		poll :
		{
			description:"Poll",
			iframe:0,
			url:"/devwidgets/poll/poll.html",
			name:"Poll",
			id:"poll",
			personalportal:0,
			siteportal:0,
			ca:0,
			img:"/devwidgets/poll/images/poll.png"
		},
		Resources :
		{
			description:"Resources tool",
			iframe:"0",
			url:"/devwidgets/Resources/Resources.html",
			name:"Resources",
			id:"resources",
			personalportal:0,
			siteportal:0,
			history : {"init":"Resources.initHistory","nav":"Resources.browser.printResources",tag:"Resources.tagging.showTagViewReal"}
		},
		polltracker :
		{
			description:"Track the results of all of the polls on the sites you are a member of",
			iframe:0,
			url:"/devwidgets/polltracker/polltracker.html",
			name:"Poll Tracker",
			id:"polltracker",
			personalportal:1,
			siteportal:0,
			multipleinstance: true,
			img:"/devwidgets/polltracker/images/poll_icon.gif"
		},
		/*
		contactinformation :
		{
			description:"contactinformation",
			iframe:0,
			url:"/devwidgets/contactinformation/contactinformation.html",
			name:"Contact Information",
			id:"contactinformation",
			personalportal:0,
			siteportal:0,
			ca:1,
			img:"/devwidgets/contactinformation/images/icon.jpg"
		},*/
		navigation :
		{
			description:"navigation",
			iframe:0,
			url:"/devwidgets/navigation/navigation.html",
			name:"Navigation",
			id:"navigation",
			personalportal:0,
			siteportal:0,
			ca:0,
			img:"/devwidgets/navigation/images/navigation.png"
		},
		form :
		{
			description:"form",
			iframe:0,
			url:"/devwidgets/form/form.html",
			name:"Form",
			id:"form",
			personalportal:0,
			siteportal:0,
			ca:0,
			img:"/devwidgets/form/images/form.png"
		}/*
,
		timeplot :
		{
			description:"timeplot",
			iframe:0,
			url:"/devwidgets/timeplot/partIA/index.html",
			name:"timeplotr",
			id:"timeplot",
			ca: 1,
			personalportal:0,
			siteportal:0,
			multipleinstance: true,
			img:"/devwidgets/polltracker/images/poll_icon.gif"
		}
*/
	},
	orders:[
		{
			grouptype:"General",
			widgets: ["mycoursesandprojects","messageoftheday","recentactivity"],
			id:1,
			layout: "twocolumnspecial"
		},
		{
			grouptype:"Administrators",
			widgets: ["mycoursesandprojects","messageoftheday","quickannouncement"],
			id:1,
			layout: "twocolumn"
		},
		{
			grouptype:"Lecturers & Supervisors",
			widgets:["mycoursesandprojects","recentactivity"],
			id:2,
			layout: "twocolumnspecial"
		},
		{
			grouptype:"Researchers",
			widgets:["recentactivity","mycoursesandprojects","messageoftheday"],
			id:3,
			layout: "threecolumn"
		},
		{
			grouptype:"Students",
			widgets:["recentactivity","mycoursesandprojects","quickannouncement","messageoftheday","myrssfeed"],
			id:4,
			layout: "fourcolumn"
		}
	]
};

<commit_msg>SAK-15673<commit_after><|endoftext|>


<commit_before>var dataChart = [];
var flag;
function getMetrics(metrics,_flag) {
	flag = _flag;
	dataChart = new Array(metrics.length);
	$.each(metrics, function (i, d) {

		feed = metricURL(gon.metrics[i].feed, gon.start, gon.stop, gon.step);
		$.getJSON(feed, function (data) {
			if (data.error) {
				renderError("chart", data.error);
				stopUpdates();
				doneProgress();
				return false;
			}
			if (data.length === 0) {
				renderError("chart", errorMessage.noData);
				stopUpdates();
				doneProgress();
				return false;
			}
			i = $.map(gon.metrics,function(d){ return d.id;}).indexOf(d);
			dataChart[i] = {data: data, name: d};
			flagComplete();
		});
	});
}

var complete = 0;
initProgress();

function flagComplete() {
	complete++;
	if (complete == metrics.length) {
		doneProgress();
		renderStacked(dataChart);
		unrenderWaiting();
	} else {
		updateProgress();
	}
}
var slider;
function isRight(d) {
	return right_id.indexOf(gon.metrics[d].id) >= 0;
}
function hasRight() {
	return clean(right_id, "").length != 0;
}
function isLeft(d) {
	return right_id.indexOf(gon.metrics[d].id) == 0;
}
function hasLeft() {
	return gon.metrics.length != clean(right_id,"").length
}

function renderStacked(data) {

	var palette = new Rickshaw.Color.Palette({
		scheme: "munin"
	});

	colours = [];

	min = Number.MAX_VALUE; max = Number.MIN_VALUE;

	if (config.renderer == "line") { pad = 1} else {pad = 0}

	left_range = [min,max];
	right_range = [min,max];
	for (n = 0; n < data.length; n++) {
		min = Number.MAX_VALUE; max = Number.MIN_VALUE;
		for (i = 0; i < data[n].data.length; i++) {
			if (typeof data[n].data[i].y == "number") {
				min = Math.min(min, data[n].data[i].y);
				max = Math.max(max, data[n].data[i].y);
			}
		}
		if (isRight(n)) {
			right_range = [ Math.min(min, right_range[0]) - pad , Math.max(max, right_range[1]) + pad ];
		} else {
			left_range = [ Math.min(min, left_range[0]) - pad, Math.max(max, left_range[1]) + pad ];
		}
	}

	if (hasRight()) {
		right_scale = d3.scale.linear().domain(right_range);
	}
	if (hasLeft()) {
		left_scale = d3.scale.linear().domain(left_range);
	}

	// Push scales and their metrics into a rickshaw-eatable array
	series = [];
	for (n = 0; n < data.length; n++) {
		colours[n] = palette.color();
		if (isRight(n)) {
			scale = right_scale;
		} else {
			scale = left_scale;
		}
		series.push({
			color: colours[n],
			data: data[n].data,
			name: data[n].name,
			scale: scale
		});
	}

	// Finally, make the chart
	config.interpolate = "monotone";

	if (flag == "xkcd") {
		config.interpolate = "xkcd";
	}

	graph = new Rickshaw.Graph({
		element: document.querySelector("#chart"),
		width: 700,
		height: 300,
		series: series
	});

	graph.configure(config);

	if (hasLeft()) {
		left_axis = new Rickshaw.Graph.Axis.Y.Scaled({
			element: document.getElementById('y_axis'),
			graph: graph,
			orientation: 'left',
			tickFormat: Rickshaw.Fixtures.Number.formatKMBT_round,
			scale: left_scale
		});
	}

	if (hasRight()) {
		right_axis = new Rickshaw.Graph.Axis.Y.Scaled({
			element: document.getElementById('y_axis_right'),
			graph: graph,
			grid: false,
			orientation: 'right',
			tickFormat: Rickshaw.Fixtures.Number.formatKMBT_round,
			scale: right_scale
		});
	}

	// One X-axis for time
	new Rickshaw.Graph.Axis.Time({
		graph: graph,
		timeFixture: getTimeFixture()
	});

	/////
	dynamicWidth(graph);
	graph.render();

	// Make stacks easier to see by adding an alpha transperancy to both
	// the graph and the legend
	if (config.stack === false && (config.renderer == "area")) {
		$(document.head).append("");
	}

	// X-axis slider for zooming
	slider = new Rickshaw.Graph.RangeSlider.Preview({
		graph: graph,
	        height: 30,
		element: $('#slider')[0],
	        onChangeDo: generate_legend

	});

	var hoverDetail = new Rickshaw.Graph.HoverDetail( {
		graph: graph,
		formatter: function(series, x, y, fx, fy, d) {
			var swatch = '';
			var date = ' '+getD3Time(x)+'';
			var content = swatch + format_metrics[d.order - 1] + ": " + y.toFixed(4) + "
"+ date;
			return content;
		},
		xFormatter: function(x){
			return new Date(x * 1000).toString();
		}
	} );

	generate_legend();
}

function generate_legend() {

	var legend = document.querySelector("#legend-dual");

	function arr_f(a) {
		r = {avg: 0, min: 0, max: 0, std: 0};
		t = a.length;
		r.max = Math.max.apply(Math, a);
		r.min = Math.min.apply(Math, a);
		for(var m, s = 0, l = t; l--; s += a[l]);
		for(m = r.mean = s / t, l = t, s = 0; l--; s += Math.pow(a[l] - m, 2));
		return r.deviation = Math.sqrt(r.variance = s / t), r;
	}

	function fix(a) { return Rickshaw.Fixtures.Number.formatKMBT_round(a);}

	function visibleData(a) {
		if (graph.window.xMin === undefined) {
			min = Number.MIN_VALUE;
		} else { min = graph.window.xMin; }
		if (graph.window.xMax === undefined) {
			max = Number.MAX_VALUE;
		} else { max = graph.window.xMax; }

		return $.map(a, function(d) { if (d.x >= min && d.x <= max) { return d.y;}  });
	}

	left = [];
	right = [];

	for (var i = 0; i < graph.series.length; i++) {
		d = graph.series[i];
		obj = {};
		obj.metric = format_metrics[i];
		obj.colour = d.color;

		obj.ydata = visibleData(d.data);
		obj.sourceURL = gon.metrics[i].sourceURL;
		obj.removeURL = gon.metrics[i].removeURL;
		obj.index = i;
		obj.show_url = "metric_"+i+"_showurl";
		obj.remove_url = "metric_"+i+"_removeurl";

		if (isRight(i)) {
			obj.link = left_links[i];
			obj.tooltip = "Move metric to the left y-axis";
			right.push(obj);
		} else {
			obj.link = right_links[i];
			obj.tooltip = "Move metric to the right y-axis";
			left.push(obj);
		}
	}

	showURLs = [];
	removeURLs = [];

	table = ["
"];

	function rtd(side) {
		c = [];

		["&nbsp","average","deviation","bounds","&nbsp"].forEach(function(d){
			c.push(""+d+"	");
		});

		if ( left.length > 0 && right.length > 0 ) {  c.splice(1,0, ""+side+" Axis	"); }
		else { c.splice(1,0," 	")}
		return c.join("");
	}

	// Stacked graphs will order last to first, so flip the legend, for sanity
	if (config.stack) { left = left.reverse(); right = right.reverse()  }

	if (left[0]) { table.push(rtd("Left"))	}
	left.forEach(function(d){ row = tableize(d); table.push(row) })

	if (right[0]) { table.push("

"); table.push(rtd("Right"))}
	right.forEach(function(d){ row = tableize(d); table.push(row) })

	function tableize(e) { //arr.forEach(function(d) {
		var t = [];
		t.push("
");

		function databit(data, tooltip) {
			s = "" + data + "	";
			return s;
		}

		y = arr_f(e.ydata);

		el = ["&nbsp	"];
		el.push(""+e.metric+"

	");
		el.push(databit(fix(y.mean), y.mean));
		el.push(databit(fix(y.deviation), y.deviation));
		el.push(databit(fix(y.min) + ", " + fix(y.max), y.min +" - "+ y.max));
		el.push("

	");
		t.push(el.join(""));
		showURLs.push([e.show_url, e.sourceURL]);
		removeURLs.push([e.remove_url, e.removeURL]);

		t.push("
");
		return t.join("");
	};

	if (hasRight()) {
		table.push("
Reset Left/Right Axis
");
	} else {
		if (graph.series.length >= 2) {
			table.push("
Click a metric to move it to the Right Axis
");
		}
	}
	table.push("
");

	legend.innerHTML = table.join("\n");

	showURLs.forEach(function(d){
		showURL(d[0],d[1]);
	});

	removeURLs.forEach(function(d) {
		removeURL(d[0],d[1]);
	});

	$("[data-toggle='tooltip-shuffle']").tooltip({
		placement: "bottom",
		container: "body",
		delay: { show: 500 }
	});
}

function updateStacked() {
	intervalID = setInterval(function (d) {

		now = parseInt(Date.now() / 1000);
		span = (gon.stop - gon.start);

		$.each(gon.metrics, function (i, metric) {
			if (metric.live) {
	                        update = metricURL(metric.feed,now-span,now,gon.step);

				$.getJSON(update, function (d) {
					if (d.error) {
						renderError("flash", d.error);
						stopUpdates();
						return false;
					}
					if (d.length === 0) {
						renderError("flash", errorMessage.noData);
						stopUpdates();
						return false;
					}
					graph.series[i].data = d;
					graph.render();
				});
			}
		});

	}, gon.step * 1000);
	return intervalID;
}
<commit_msg>fix padding issues with scaled y axis and stacked graphs<commit_after>var dataChart = [];
var flag;
function getMetrics(metrics,_flag) {
	flag = _flag;
	dataChart = new Array(metrics.length);
	$.each(metrics, function (i, d) {

		feed = metricURL(gon.metrics[i].feed, gon.start, gon.stop, gon.step);
		$.getJSON(feed, function (data) {
			if (data.error) {
				renderError("chart", data.error);
				stopUpdates();
				doneProgress();
				return false;
			}
			if (data.length === 0) {
				renderError("chart", errorMessage.noData);
				stopUpdates();
				doneProgress();
				return false;
			}
			i = $.map(gon.metrics,function(d){ return d.id;}).indexOf(d);
			dataChart[i] = {data: data, name: d};
			flagComplete();
		});
	});
}

var complete = 0;
initProgress();

function flagComplete() {
	complete++;
	if (complete == metrics.length) {
		doneProgress();
		renderStacked(dataChart);
		unrenderWaiting();
	} else {
		updateProgress();
	}
}
var slider;
function isRight(d) {
	return right_id.indexOf(gon.metrics[d].id) >= 0;
}
function hasRight() {
	return clean(right_id, "").length != 0;
}
function isLeft(d) {
	return right_id.indexOf(gon.metrics[d].id) == 0;
}
function hasLeft() {
	return gon.metrics.length != clean(right_id,"").length
}

function renderStacked(data) {

	var palette = new Rickshaw.Color.Palette({
		scheme: "munin"
	});

	colours = [];

	min = Number.MAX_VALUE; max = Number.MIN_VALUE;

	// Padding - depending on the domain, both scalar and ratio padding are used. So set both.
	var scalarPad = 1
	var ratioPad = 0.1

	if (config.renderer != "line") { scalarPad = 0 }

	left_range = [min,max];
	right_range = [min,max];
	for (n = 0; n < data.length; n++) {
		min = Number.MAX_VALUE; max = Number.MIN_VALUE;
		for (i = 0; i < data[n].data.length; i++) {
			if (typeof data[n].data[i].y == "number") {
				min = Math.min(min, data[n].data[i].y);
				max = Math.max(max, data[n].data[i].y);
			}
		}
		if (isRight(n)) {
			right_range = [ Math.min(min, right_range[0]), Math.max(max, right_range[1])];
		} else {
			left_range = [ Math.min(min, left_range[0]), Math.max(max, left_range[1])];
		}
	}

	if (hasRight()) {
		right_range = [right_range[0] - scalarPad, right_range[1] + scalarPad] //Scalar Padding
		right_scale = d3.scale.linear().domain(right_range);
	}

	if (hasLeft()) {
		left_range = [left_range[0] - scalarPad, left_range[1] + scalarPad] //Scalar Padding
		left_scale = d3.scale.linear().domain(left_range);
	}

	// Push scales and their metrics into a rickshaw-eatable array
	series = [];
	for (n = 0; n < data.length; n++) {
		colours[n] = palette.color();
		if (isRight(n)) {
			scale = right_scale;
		} else {
			scale = left_scale;
		}

		series.push({
			color: colours[n],
			data: data[n].data,
			name: data[n].name,
			scale: scale
		});
	}

	// Finally, make the chart
	config.interpolate = "monotone";

	//Ratio Padding - defaults from rickshaw.js
	padY = 0.02
	padX = 0

	if (hasRight() && hasLeft() ) {
		d = [Math.min(left_scale.domain()[0], right_scale.domain()[0]),
	             Math.max(left_scale.domain()[1], right_scale.domain()[1])]
	} else if (hasRight()) {
		d = right_scale.domain()
	} else {
		d = left_scale.domain()
	}

	if (d[0] >= -2 && d[1] <= 2) { // -1 -> 1, plus scalar padding
		padY = ratioPadding
	}

	padArray = {top: padY, right: padX, bottom: padY, left: padX}

	config.padding = padArray

	// ...
	if (flag == "xkcd") {
		config.interpolate = "xkcd";
	}

	graph = new Rickshaw.Graph({
		element: document.querySelector("#chart"),
		width: 700,
		height: 300,
		series: series
	});

	graph.configure(config);

	if (hasLeft()) {
		left_axis = new Rickshaw.Graph.Axis.Y.Scaled({
			element: document.getElementById('y_axis'),
			graph: graph,
			orientation: 'left',
			tickFormat: Rickshaw.Fixtures.Number.formatKMBT_round,
			scale: left_scale
		});
	}

	if (hasRight()) {
		right_axis = new Rickshaw.Graph.Axis.Y.Scaled({
			element: document.getElementById('y_axis_right'),
			graph: graph,
			grid: false,
			orientation: 'right',
			tickFormat: Rickshaw.Fixtures.Number.formatKMBT_round,
			scale: right_scale
		});
	}

	// One X-axis for time
	new Rickshaw.Graph.Axis.Time({
		graph: graph,
		timeFixture: getTimeFixture()
	});

	/////
	dynamicWidth(graph);
	graph.render();

	// Make stacks easier to see by adding an alpha transperancy to both
	// the graph and the legend
	if (config.stack === false && (config.renderer == "area")) {
		$(document.head).append("");
	}

	// X-axis slider for zooming
	slider = new Rickshaw.Graph.RangeSlider.Preview({
		graph: graph,
	        height: 30,
		element: $('#slider')[0],
	        onChangeDo: generate_legend

	});

	var hoverDetail = new Rickshaw.Graph.HoverDetail( {
		graph: graph,
		formatter: function(series, x, y, fx, fy, d) {
			var swatch = '';
			var date = ' '+getD3Time(x)+'';
			var content = swatch + format_metrics[d.order - 1] + ": " + y.toFixed(4) + "
"+ date;
			return content;
		},
		xFormatter: function(x){
			return new Date(x * 1000).toString();
		}
	} );

	generate_legend();
}

function generate_legend() {

	var legend = document.querySelector("#legend-dual");

	function arr_f(a) {
		r = {avg: 0, min: 0, max: 0, std: 0};
		t = a.length;
		r.max = Math.max.apply(Math, a);
		r.min = Math.min.apply(Math, a);
		for(var m, s = 0, l = t; l--; s += a[l]);
		for(m = r.mean = s / t, l = t, s = 0; l--; s += Math.pow(a[l] - m, 2));
		return r.deviation = Math.sqrt(r.variance = s / t), r;
	}

	function fix(a) { return Rickshaw.Fixtures.Number.formatKMBT_round(a);}

	function visibleData(a) {
		if (graph.window.xMin === undefined) {
			min = Number.MIN_VALUE;
		} else { min = graph.window.xMin; }
		if (graph.window.xMax === undefined) {
			max = Number.MAX_VALUE;
		} else { max = graph.window.xMax; }

		return $.map(a, function(d) { if (d.x >= min && d.x <= max) { return d.y;}  });
	}

	left = [];
	right = [];

	for (var i = 0; i < graph.series.length; i++) {
		d = graph.series[i];
		obj = {};
		obj.metric = format_metrics[i];
		obj.colour = d.color;

		obj.ydata = visibleData(d.data);
		obj.sourceURL = gon.metrics[i].sourceURL;
		obj.removeURL = gon.metrics[i].removeURL;
		obj.index = i;
		obj.show_url = "metric_"+i+"_showurl";
		obj.remove_url = "metric_"+i+"_removeurl";

		if (isRight(i)) {
			obj.link = left_links[i];
			obj.tooltip = "Move metric to the left y-axis";
			right.push(obj);
		} else {
			obj.link = right_links[i];
			obj.tooltip = "Move metric to the right y-axis";
			left.push(obj);
		}
	}

	showURLs = [];
	removeURLs = [];

	table = ["
"];

	function rtd(side) {
		c = [];

		["&nbsp","average","deviation","bounds","&nbsp"].forEach(function(d){
			c.push(""+d+"	");
		});

		if ( left.length > 0 && right.length > 0 ) {  c.splice(1,0, ""+side+" Axis	"); }
		else { c.splice(1,0," 	")}
		return c.join("");
	}

	// Stacked graphs will order last to first, so flip the legend, for sanity
	if (config.stack) { left = left.reverse(); right = right.reverse()  }

	if (left[0]) { table.push(rtd("Left"))	}
	left.forEach(function(d){ row = tableize(d); table.push(row) })

	if (right[0]) { table.push("

"); table.push(rtd("Right"))}
	right.forEach(function(d){ row = tableize(d); table.push(row) })

	function tableize(e) { //arr.forEach(function(d) {
		var t = [];
		t.push("
");

		function databit(data, tooltip) {
			s = "" + data + "	";
			return s;
		}

		y = arr_f(e.ydata);

		el = ["&nbsp	"];
		el.push(""+e.metric+"

	");
		el.push(databit(fix(y.mean), y.mean));
		el.push(databit(fix(y.deviation), y.deviation));
		el.push(databit(fix(y.min) + ", " + fix(y.max), y.min +" - "+ y.max));
		el.push("

	");
		t.push(el.join(""));
		showURLs.push([e.show_url, e.sourceURL]);
		removeURLs.push([e.remove_url, e.removeURL]);

		t.push("
");
		return t.join("");
	};

	if (hasRight()) {
		table.push("
Reset Left/Right Axis
");
	} else {
		if (graph.series.length >= 2) {
			table.push("
Click a metric to move it to the Right Axis
");
		}
	}
	table.push("
");

	legend.innerHTML = table.join("\n");

	showURLs.forEach(function(d){
		showURL(d[0],d[1]);
	});

	removeURLs.forEach(function(d) {
		removeURL(d[0],d[1]);
	});

	$("[data-toggle='tooltip-shuffle']").tooltip({
		placement: "bottom",
		container: "body",
		delay: { show: 500 }
	});
}

function updateStacked() {
	intervalID = setInterval(function (d) {

		now = parseInt(Date.now() / 1000);
		span = (gon.stop - gon.start);

		$.each(gon.metrics, function (i, metric) {
			if (metric.live) {
	                        update = metricURL(metric.feed,now-span,now,gon.step);

				$.getJSON(update, function (d) {
					if (d.error) {
						renderError("flash", d.error);
						stopUpdates();
						return false;
					}
					if (d.length === 0) {
						renderError("flash", errorMessage.noData);
						stopUpdates();
						return false;
					}
					graph.series[i].data = d;
					graph.render();
				});
			}
		});

	}, gon.step * 1000);
	return intervalID;
}
<|endoftext|>


<commit_before>import { describe, it } from 'mocha';
import { expect } from 'chai';

import { vector } from '../js/vector';

describe('Vector Library', () => {
  describe('Getters and Setters:', () => {
    const v1 = vector.create(1, 2);
    it('sets the X value', () => {
      expect(v1.getX()).to.equal(1);
    });

    it('sets the Y value', () => {
      expect(v1.getY()).to.equal(2);
    });

    it('sets the angle', () => {
      // this isn't working :(
      v1.setAngle(10);
    });

    it('sets the length', () => {
      v1.setLength(100);
      expect(v1.getLength()).to.equal(100);
    });
  });
  describe('Elementary immutable vector arithmetic works', () => {
    const v1 = vector.create(5, 10);
    const v2 = vector.create(10, 5);
    it('Add', () => {
      const result = v1.add(v2);

      expect(result.getX()).to.equal(15);
      expect(result.getY()).to.equal(15);
    });
    it('Subtract', () => {
      const result = v1.subtract(v2);

      expect(result.getX()).to.equal(-5);
      expect(result.getY()).to.equal(5);
    });
    it('Multipliy', () => {
      const result = v1.multiply(2);

      expect(result.getX()).to.equal(10);
      expect(result.getY()).to.equal(20);
    });
    it('Divide', () => {
      const result = v1.divide(5);

      expect(result.getX()).to.equal(1);
      expect(result.getY()).to.equal(2);
    });
  });
  describe('Elementary muteable vector arithmetic works', () => {
    it('Add', () => {
      const v1 = vector.create(5, 10);
      const v2 = vector.create(10, 5);
      v1.addTo(v2);

      expect(v1.getX()).to.equal(15);
      expect(v1.getY()).to.equal(15);
    });
    it('Subtract', () => {
      const v1 = vector.create(5, 10);
      const v2 = vector.create(10, 5);
      v1.subtractFrom(v2);

      expect(v1.getX()).to.equal(-5);
      expect(v1.getY()).to.equal(5);
    });
    it('Multipliy', () => {
      const v1 = vector.create(5, 10);
      v1.multiplyBy(2);

      expect(v1.getX()).to.equal(10);
      expect(v1.getY()).to.equal(20);
    });
    it('Divide', () => {
      const v1 = vector.create(5, 10);
      v1.divideBy(5);

      expect(v1.getX()).to.equal(1);
      expect(v1.getY()).to.equal(2);
    });
  });
});
<commit_msg>All vector tests green!<commit_after>import { describe, it } from 'mocha';
import { expect } from 'chai';

import { vector } from '../js/vector';

describe('Vector Library', () => {
  describe('Getters and Setters:', () => {
    const v1 = vector.create(1, 2);
    it('sets the X value', () => {
      expect(v1.getX()).to.equal(1);
    });

    it('sets the Y value', () => {
      expect(v1.getY()).to.equal(2);
    });

    it('sets the angle', () => {
      const low30 = 29.5 * (Math.PI / 180);
      const high30 = 30.5 * (Math.PI / 180);
      v1.setAngle(Math.PI / 6);
      expect(v1.getAngle()).to.be.within(low30, high30);
    });

    it('sets the length', () => {
      v1.setLength(100);
      expect(v1.getLength()).to.equal(100);
    });
  });
  describe('Elementary immutable vector arithmetic works', () => {
    const v1 = vector.create(5, 10);
    const v2 = vector.create(10, 5);
    it('Add', () => {
      const result = v1.add(v2);

      expect(result.getX()).to.equal(15);
      expect(result.getY()).to.equal(15);
    });
    it('Subtract', () => {
      const result = v1.subtract(v2);

      expect(result.getX()).to.equal(-5);
      expect(result.getY()).to.equal(5);
    });
    it('Multipliy', () => {
      const result = v1.multiply(2);

      expect(result.getX()).to.equal(10);
      expect(result.getY()).to.equal(20);
    });
    it('Divide', () => {
      const result = v1.divide(5);

      expect(result.getX()).to.equal(1);
      expect(result.getY()).to.equal(2);
    });
  });
  describe('Elementary muteable vector arithmetic works', () => {
    it('Add', () => {
      const v1 = vector.create(5, 10);
      const v2 = vector.create(10, 5);
      v1.addTo(v2);

      expect(v1.getX()).to.equal(15);
      expect(v1.getY()).to.equal(15);
    });
    it('Subtract', () => {
      const v1 = vector.create(5, 10);
      const v2 = vector.create(10, 5);
      v1.subtractFrom(v2);

      expect(v1.getX()).to.equal(-5);
      expect(v1.getY()).to.equal(5);
    });
    it('Multipliy', () => {
      const v1 = vector.create(5, 10);
      v1.multiplyBy(2);

      expect(v1.getX()).to.equal(10);
      expect(v1.getY()).to.equal(20);
    });
    it('Divide', () => {
      const v1 = vector.create(5, 10);
      v1.divideBy(5);

      expect(v1.getX()).to.equal(1);
      expect(v1.getY()).to.equal(2);
    });
  });
});
<|endoftext|>


<commit_before>var RandomForest = require('./random-forest'),
    fs = require('fs');

function readExample(callback) {
  var rawData = require('./stock-data.json');
  var headers = {};
  for (k in rawData)
    for (m in rawData[k])
      headers[m] = true;

  var data = Object.keys(rawData).map(function(k) {
	  return Object.keys(headers).map(function(m) { return rawData[k][m]; });
      });

  return data;
}

function crossValidate(data, nEstimators, useMedian) {
  var nSamples = 99;

  if (useMedian) {
    var sumDiff = [];
    var nObs = [];

    for (var j = 0; j < data[0].length; j++) {
	sumDiff.push(0.0);
	nObs.push(0.0);
    }

  } else {
    var distribution = [];

    for (var j = 0; j < (nSamples + 1); j++)
      distribution.push(j);
  }

  for (var kFold = 0; kFold < 10; kFold++) {
    // Do cross validation
    var trainData = [];
    var testData = [];

    for (var i = 0; i < data.length; i++){
      if (Math.random() < 0.5)
	trainData.push(data[i]);
      else
	testData.push(data[i]);
    }

    // Fit model
    var model = new RandomForest();
    model.train(trainData, nEstimators, useMedian, 100, 10);

    // Predict missing values from the test set
    for (var i = 0; i < testData.length; i++) {
      for (var j = 0; j < testData[i].length; j++) {
	if (testData[i][j] == undefined)
	  continue;

	if (useMedian)
	  nObs[j]++;

	var samples = [];
	for (var sample = 0; sample < nSamples; sample++) {
	  var row = testData[i].slice(0);
	  row[j] = undefined;
	  samples.push(model.fill(row)[j]);
	}
	samples.sort(function(a, b) { return a-b; });

	if (useMedian) {
	  sumDiff[j] += Math.abs(testData[i][j] - samples[Math.floor(samples.length/2)]);
	} else {
	  // Find the bucket of the real value
	  var bucketLo = -1, bucketHi = nSamples;
	  for (var b = 0; b < nSamples; b++) {
	    if (samples[b] < testData[i][j])
	      bucketLo = b;
	    if (samples[b] > testData[i][j] && bucketHi == nSamples)
	      bucketHi = b;
	  }

	  for (var b = bucketLo+1; b < bucketHi+1; b++)
	    distribution[b] += 1.0 / (bucketHi - bucketLo);

	  // console.log(test[i][j] + ' ' + samples + ' ' + bucketLo + '-' + bucketHi);
	}
      }
    }
  }

  console.log(nEstimators + ' ' + (useMedian ? 'median' : 'distribution'));
  if (useMedian) {
    for (var j = 0; j < sumDiff.length; j++) {
      console.log(j + ': ' + (sumDiff[j] / nObs[j]).toFixed(2));
    }
  } else {
    console.log(distribution);
  }

  console.log();
}

var data = readExample();
var nEstimators = [1, 10, 100, 1000];
for (var useMedian = 0; useMedian < 2; useMedian++) {
  for (var i = 0; i < nEstimators.length; i++) {
    crossValidate(data, nEstimators[i], useMedian == 1);
  }
}

<commit_msg>dump good model<commit_after>var RandomForest = require('./random-forest'),
    fs = require('fs');

function readExample(callback) {
  var rawData = require('./stock-data.json');
  var headers = {};
  for (k in rawData)
    for (m in rawData[k])
      headers[m] = true;

  headers = Object.keys(headers);

  var data = Object.keys(rawData).map(function(k) {
	  return headers.map(function(m) { return rawData[k][m]; });
      });

  return {'headers': headers, 'data': data};
}

function crossValidate(data, nEstimators, useMedian) {
  var nSamples = 99;

  if (useMedian) {
    var sumDiff = [];
    var nObs = [];

    for (var j = 0; j < data[0].length; j++) {
	sumDiff.push(0.0);
	nObs.push(0.0);
    }

  } else {
    var distribution = [];

    for (var j = 0; j < (nSamples + 1); j++)
      distribution.push(j);
  }

  // Fit model to dump
  var model = new RandomForest();
  model.train(data, nEstimators, useMedian, 100, 10);
  var serialized = JSON.stringify(model.serialize(), function(key, val) {
    if (val && val.toPrecision)  // reduce file size by stripping digits
      return val.toPrecision(3);
    else
      return val;
  });
  serialized = 'var data = ' + serialized + ';';
  fs.writeFile('model-' + nEstimators + '-' + useMedian + '.js', serialized);

  // Do cross validation
  for (var kFold = 0; kFold < 10; kFold++) {

    var trainData = [];
    var testData = [];

    for (var i = 0; i < data.length; i++){
      if (Math.random() < 0.5)
	trainData.push(data[i]);
      else
	testData.push(data[i]);
    }

    // Fit model
    var model = new RandomForest();
    model.train(trainData, nEstimators, useMedian, 100, 10);

    // Predict missing values from the test set
    for (var i = 0; i < testData.length; i++) {
      for (var j = 0; j < testData[i].length; j++) {
	if (testData[i][j] == undefined)
	  continue;

	if (useMedian)
	  nObs[j]++;

	var samples = [];
	for (var sample = 0; sample < nSamples; sample++) {
	  var row = testData[i].slice(0);
	  row[j] = undefined;
	  samples.push(model.fill(row)[j]);
	}
	samples.sort(function(a, b) { return a-b; });

	if (useMedian) {
	  sumDiff[j] += Math.abs(testData[i][j] - samples[Math.floor(samples.length/2)]);
	} else {
	  // Find the bucket of the real value
	  var bucketLo = -1, bucketHi = nSamples;
	  for (var b = 0; b < nSamples; b++) {
	    if (samples[b] < testData[i][j])
	      bucketLo = b;
	    if (samples[b] > testData[i][j] && bucketHi == nSamples)
	      bucketHi = b;
	  }

	  for (var b = bucketLo+1; b < bucketHi+1; b++)
	    distribution[b] += 1.0 / (bucketHi - bucketLo);

	  // console.log(test[i][j] + ' ' + samples + ' ' + bucketLo + '-' + bucketHi);
	}
      }
    }
  }

  console.log(nEstimators + ' ' + (useMedian ? 'median' : 'distribution'));
  if (useMedian) {
    for (var j = 0; j < sumDiff.length; j++) {
      console.log(j + ': ' + (sumDiff[j] / nObs[j]).toFixed(2));
    }
  } else {
    console.log(distribution);
  }

  console.log();
}

var stuff = readExample();
fs.writeFile('headers.js', 'var headers = ' + JSON.stringify(stuff['headers']) + ';');
/*
var nEstimators = [1, 10, 100, 1000];
for (var useMedian = 0; useMedian < 2; useMedian++) {
  for (var i = 0; i < nEstimators.length; i++) {
    crossValidate(stuff['data'], nEstimators[i], useMedian == 1);
  }
}

*/
<|endoftext|>


<commit_before>/**
 * @fileoverview Tests for no-typos
 */
'use strict';

// -----------------------------------------------------------------------------
// Requirements
// -----------------------------------------------------------------------------

const rule = require('../../../lib/rules/no-typos');
const RuleTester = require('eslint').RuleTester;

const parserOptions = {
  ecmaVersion: 6,
  ecmaFeatures: {
    jsx: true
  }
};

// -----------------------------------------------------------------------------
// Tests
// -----------------------------------------------------------------------------

const ERROR_MESSAGE = 'Typo in static class property declaration';

const ruleTester = new RuleTester();
ruleTester.run('no-typos', rule, {

  valid: [{
    code: [
      'class First {',
      '  static PropTypes = {key: "myValue"};',
      '  static ContextTypes = {key: "myValue"};',
      '  static ChildContextTypes = {key: "myValue"};',
      '  static DefaultProps = {key: "myValue"};',
      '}'
    ].join('\n'),
    parser: 'babel-eslint',
    parserOptions: parserOptions
  },
  {
    code: [
      'class First {}',
      'First.PropTypes = {key: "myValue"};',
      'First.ContextTypes = {key: "myValue"};',
      'First.ChildContextTypes = {key: "myValue"};',
      'First.DefaultProps = {key: "myValue"};'
    ].join('\n'),
    parserOptions: parserOptions
  }, {
    code: [
      'class First extends React.Component {',
      '  static propTypes = {key: "myValue"};',
      '  static contextTypes = {key: "myValue"};',
      '  static childContextTypes = {key: "myValue"};',
      '  static defaultProps = {key: "myValue"};',
      '}'
    ].join('\n'),
    parser: 'babel-eslint',
    parserOptions: parserOptions
  }, {
    code: [
      'class First extends React.Component {}',
      'First.propTypes = {key: "myValue"};',
      'First.contextTypes = {key: "myValue"};',
      'First.childContextTypes = {key: "myValue"};',
      'First.defaultProps = {key: "myValue"};'
    ].join('\n'),
    parserOptions: parserOptions
  }, {
    code: [
      'class MyClass {',
      '  propTypes = {key: "myValue"};',
      '  contextTypes = {key: "myValue"};',
      '  childContextTypes = {key: "myValue"};',
      '  defaultProps = {key: "myValue"};',
      '}'
    ].join('\n'),
    parser: 'babel-eslint',
    parserOptions: parserOptions
  }, {
    code: [
      'class MyClass {',
      '  PropTypes = {key: "myValue"};',
      '  ContextTypes = {key: "myValue"};',
      '  ChildContextTypes = {key: "myValue"};',
      '  DefaultProps = {key: "myValue"};',
      '}'
    ].join('\n'),
    parser: 'babel-eslint',
    parserOptions: parserOptions
  }, {
    code: [
      'class MyClass {',
      '  proptypes = {key: "myValue"};',
      '  contexttypes = {key: "myValue"};',
      '  childcontextypes = {key: "myValue"};',
      '  defaultprops = {key: "myValue"};',
      '}'
    ].join('\n'),
    parser: 'babel-eslint',
    parserOptions: parserOptions
  }, {
    code: [
      'class MyClass {',
      '  static PropTypes() {};',
      '  static ContextTypes() {};',
      '  static ChildContextTypes() {};',
      '  static DefaultProps() {};',
      '}'
    ].join('\n'),
    parser: 'babel-eslint',
    parserOptions: parserOptions
  }, {
    code: [
      'class MyClass {',
      '  static proptypes() {};',
      '  static contexttypes() {};',
      '  static childcontexttypes() {};',
      '  static defaultprops() {};',
      '}'
    ].join('\n'),
    parser: 'babel-eslint',
    parserOptions: parserOptions
  }, {
    code: [
      'class MyClass {}',
      'MyClass.prototype.PropTypes = function() {};',
      'MyClass.prototype.ContextTypes = function() {};',
      'MyClass.prototype.ChildContextTypes = function() {};',
      'MyClass.prototype.DefaultProps = function() {};'
    ].join('\n'),
    parserOptions: parserOptions
  }, {
    code: [
      'class MyClass {}',
      'MyClass.PropTypes = function() {};',
      'MyClass.ContextTypes = function() {};',
      'MyClass.ChildContextTypes = function() {};',
      'MyClass.DefaultProps = function() {};'
    ].join('\n'),
    parserOptions: parserOptions
  }, {
    code: [
      'function MyRandomFunction() {}',
      'MyRandomFunction.PropTypes = {};',
      'MyRandomFunction.ContextTypes = {};',
      'MyRandomFunction.ChildContextTypes = {};',
      'MyRandomFunction.DefaultProps = {};'
    ].join('\n'),
    parserOptions: parserOptions
  }, {
    code: [
      'class First extends React.Component {}',
      'First["prop" + "Types"] = {};',
      'First["context" + "Types"] = {};',
      'First["childContext" + "Types"] = {};',
      'First["default" + "Props"] = {};'
    ].join('\n'),
    parserOptions: parserOptions
  }, {
    code: [ // This case is currently not supported
      'class First extends React.Component {}',
      'First["PROP" + "TYPES"] = {};',
      'First["CONTEXT" + "TYPES"] = {};',
      'First["CHILDCONTEXT" + "TYPES"] = {};',
      'First["DEFAULT" + "PROPS"] = {};'
    ].join('\n'),
    parserOptions: parserOptions
  }],

  invalid: [{
    code: [
      'class Component extends React.Component {',
      '  static PropTypes = {};',
      '}'
    ].join('\n'),
    parser: 'babel-eslint',
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'class Component extends React.Component {}',
      'Component.PropTypes = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'function MyComponent() { return (
{this.props.myProp}
) }',
      'MyComponent.PropTypes = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'class Component extends React.Component {',
      '  static proptypes = {};',
      '}'
    ].join('\n'),
    parser: 'babel-eslint',
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'class Component extends React.Component {}',
      'Component.proptypes = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'function MyComponent() { return (
{this.props.myProp}
) }',
      'MyComponent.proptypes = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'class Component extends React.Component {',
      '  static ContextTypes = {};',
      '}'
    ].join('\n'),
    parser: 'babel-eslint',
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'class Component extends React.Component {}',
      'Component.ContextTypes = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'function MyComponent() { return (
{this.props.myProp}
) }',
      'MyComponent.ContextTypes = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'class Component extends React.Component {',
      '  static contexttypes = {};',
      '}'
    ].join('\n'),
    parser: 'babel-eslint',
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'class Component extends React.Component {}',
      'Component.contexttypes = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'function MyComponent() { return (
{this.props.myProp}
) }',
      'MyComponent.contexttypes = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'class Component extends React.Component {',
      '  static ChildContextTypes = {};',
      '}'
    ].join('\n'),
    parser: 'babel-eslint',
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'class Component extends React.Component {}',
      'Component.ChildContextTypes = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'function MyComponent() { return (
{this.props.myProp}
) }',
      'MyComponent.ChildContextTypes = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'class Component extends React.Component {',
      '  static childcontexttypes = {};',
      '}'
    ].join('\n'),
    parser: 'babel-eslint',
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'class Component extends React.Component {}',
      'Component.childcontexttypes = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'function MyComponent() { return (
{this.props.myProp}
) }',
      'MyComponent.childcontexttypes = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'class Component extends React.Component {',
      '  static DefaultProps = {};',
      '}'
    ].join('\n'),
    parser: 'babel-eslint',
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'class Component extends React.Component {}',
      'Component.DefaultProps = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'function MyComponent() { return (
{this.props.myProp}
) }',
      'MyComponent.DefaultProps = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'class Component extends React.Component {',
      '  static defaultprops = {};',
      '}'
    ].join('\n'),
    parser: 'babel-eslint',
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'class Component extends React.Component {}',
      'Component.defaultprops = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'function MyComponent() { return (
{this.props.myProp}
) }',
      'MyComponent.defaultprops = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }]
});
<commit_msg>Add another valid test case<commit_after>/**
 * @fileoverview Tests for no-typos
 */
'use strict';

// -----------------------------------------------------------------------------
// Requirements
// -----------------------------------------------------------------------------

const rule = require('../../../lib/rules/no-typos');
const RuleTester = require('eslint').RuleTester;

const parserOptions = {
  ecmaVersion: 6,
  ecmaFeatures: {
    jsx: true
  }
};

// -----------------------------------------------------------------------------
// Tests
// -----------------------------------------------------------------------------

const ERROR_MESSAGE = 'Typo in static class property declaration';

const ruleTester = new RuleTester();
ruleTester.run('no-typos', rule, {

  valid: [{
    code: [
      'class First {',
      '  static PropTypes = {key: "myValue"};',
      '  static ContextTypes = {key: "myValue"};',
      '  static ChildContextTypes = {key: "myValue"};',
      '  static DefaultProps = {key: "myValue"};',
      '}'
    ].join('\n'),
    parser: 'babel-eslint',
    parserOptions: parserOptions
  },
  {
    code: [
      'class First {}',
      'First.PropTypes = {key: "myValue"};',
      'First.ContextTypes = {key: "myValue"};',
      'First.ChildContextTypes = {key: "myValue"};',
      'First.DefaultProps = {key: "myValue"};'
    ].join('\n'),
    parserOptions: parserOptions
  }, {
    code: [
      'class First extends React.Component {',
      '  static propTypes = {key: "myValue"};',
      '  static contextTypes = {key: "myValue"};',
      '  static childContextTypes = {key: "myValue"};',
      '  static defaultProps = {key: "myValue"};',
      '}'
    ].join('\n'),
    parser: 'babel-eslint',
    parserOptions: parserOptions
  }, {
    code: [
      'class First extends React.Component {}',
      'First.propTypes = {key: "myValue"};',
      'First.contextTypes = {key: "myValue"};',
      'First.childContextTypes = {key: "myValue"};',
      'First.defaultProps = {key: "myValue"};'
    ].join('\n'),
    parserOptions: parserOptions
  }, {
    code: [
      'class MyClass {',
      '  propTypes = {key: "myValue"};',
      '  contextTypes = {key: "myValue"};',
      '  childContextTypes = {key: "myValue"};',
      '  defaultProps = {key: "myValue"};',
      '}'
    ].join('\n'),
    parser: 'babel-eslint',
    parserOptions: parserOptions
  }, {
    code: [
      'class MyClass {',
      '  PropTypes = {key: "myValue"};',
      '  ContextTypes = {key: "myValue"};',
      '  ChildContextTypes = {key: "myValue"};',
      '  DefaultProps = {key: "myValue"};',
      '}'
    ].join('\n'),
    parser: 'babel-eslint',
    parserOptions: parserOptions
  }, {
    code: [
      'class MyClass {',
      '  proptypes = {key: "myValue"};',
      '  contexttypes = {key: "myValue"};',
      '  childcontextypes = {key: "myValue"};',
      '  defaultprops = {key: "myValue"};',
      '}'
    ].join('\n'),
    parser: 'babel-eslint',
    parserOptions: parserOptions
  }, {
    code: [
      'class MyClass {',
      '  static PropTypes() {};',
      '  static ContextTypes() {};',
      '  static ChildContextTypes() {};',
      '  static DefaultProps() {};',
      '}'
    ].join('\n'),
    parser: 'babel-eslint',
    parserOptions: parserOptions
  }, {
    code: [
      'class MyClass {',
      '  static proptypes() {};',
      '  static contexttypes() {};',
      '  static childcontexttypes() {};',
      '  static defaultprops() {};',
      '}'
    ].join('\n'),
    parser: 'babel-eslint',
    parserOptions: parserOptions
  }, {
    code: [
      'class MyClass {}',
      'MyClass.prototype.PropTypes = function() {};',
      'MyClass.prototype.ContextTypes = function() {};',
      'MyClass.prototype.ChildContextTypes = function() {};',
      'MyClass.prototype.DefaultProps = function() {};'
    ].join('\n'),
    parserOptions: parserOptions
  }, {
    code: [
      'class MyClass {}',
      'MyClass.PropTypes = function() {};',
      'MyClass.ContextTypes = function() {};',
      'MyClass.ChildContextTypes = function() {};',
      'MyClass.DefaultProps = function() {};'
    ].join('\n'),
    parserOptions: parserOptions
  }, {
    code: [
      'function MyRandomFunction() {}',
      'MyRandomFunction.PropTypes = {};',
      'MyRandomFunction.ContextTypes = {};',
      'MyRandomFunction.ChildContextTypes = {};',
      'MyRandomFunction.DefaultProps = {};'
    ].join('\n'),
    parserOptions: parserOptions
  }, {
    code: [
      'class First extends React.Component {}',
      'First["prop" + "Types"] = {};',
      'First["context" + "Types"] = {};',
      'First["childContext" + "Types"] = {};',
      'First["default" + "Props"] = {};'
    ].join('\n'),
    parserOptions: parserOptions
  }, {
    code: [ // This case is currently not supported
      'class First extends React.Component {}',
      'First["PROP" + "TYPES"] = {};',
      'First["CONTEXT" + "TYPES"] = {};',
      'First["CHILDCONTEXT" + "TYPES"] = {};',
      'First["DEFAULT" + "PROPS"] = {};'
    ].join('\n'),
    parserOptions: parserOptions
  }, {
    code: [ // This case is currently not supported
      'const propTypes = "PROPTYPES"',
      'const contextTypes = "CONTEXTTYPES"',
      'const childContextTypes = "CHILDCONTEXTTYPES"',
      'const defautProps = "DEFAULTPROPS"',
      '',
      'class First extends React.Component {}',
      'First[propTypes] = {};',
      'First[contextTypes] = {};',
      'First[childContextTypes] = {};',
      'First[defautProps] = {};'
    ].join('\n'),
    parserOptions: parserOptions
  }],

  invalid: [{
    code: [
      'class Component extends React.Component {',
      '  static PropTypes = {};',
      '}'
    ].join('\n'),
    parser: 'babel-eslint',
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'class Component extends React.Component {}',
      'Component.PropTypes = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'function MyComponent() { return (
{this.props.myProp}
) }',
      'MyComponent.PropTypes = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'class Component extends React.Component {',
      '  static proptypes = {};',
      '}'
    ].join('\n'),
    parser: 'babel-eslint',
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'class Component extends React.Component {}',
      'Component.proptypes = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'function MyComponent() { return (
{this.props.myProp}
) }',
      'MyComponent.proptypes = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'class Component extends React.Component {',
      '  static ContextTypes = {};',
      '}'
    ].join('\n'),
    parser: 'babel-eslint',
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'class Component extends React.Component {}',
      'Component.ContextTypes = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'function MyComponent() { return (
{this.props.myProp}
) }',
      'MyComponent.ContextTypes = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'class Component extends React.Component {',
      '  static contexttypes = {};',
      '}'
    ].join('\n'),
    parser: 'babel-eslint',
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'class Component extends React.Component {}',
      'Component.contexttypes = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'function MyComponent() { return (
{this.props.myProp}
) }',
      'MyComponent.contexttypes = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'class Component extends React.Component {',
      '  static ChildContextTypes = {};',
      '}'
    ].join('\n'),
    parser: 'babel-eslint',
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'class Component extends React.Component {}',
      'Component.ChildContextTypes = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'function MyComponent() { return (
{this.props.myProp}
) }',
      'MyComponent.ChildContextTypes = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'class Component extends React.Component {',
      '  static childcontexttypes = {};',
      '}'
    ].join('\n'),
    parser: 'babel-eslint',
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'class Component extends React.Component {}',
      'Component.childcontexttypes = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'function MyComponent() { return (
{this.props.myProp}
) }',
      'MyComponent.childcontexttypes = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'class Component extends React.Component {',
      '  static DefaultProps = {};',
      '}'
    ].join('\n'),
    parser: 'babel-eslint',
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'class Component extends React.Component {}',
      'Component.DefaultProps = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'function MyComponent() { return (
{this.props.myProp}
) }',
      'MyComponent.DefaultProps = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'class Component extends React.Component {',
      '  static defaultprops = {};',
      '}'
    ].join('\n'),
    parser: 'babel-eslint',
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'class Component extends React.Component {}',
      'Component.defaultprops = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }, {
    code: [
      'function MyComponent() { return (
{this.props.myProp}
) }',
      'MyComponent.defaultprops = {}'
    ].join('\n'),
    parserOptions: parserOptions,
    errors: [{message: ERROR_MESSAGE}]
  }]
});
<|endoftext|>