<commit_before>'use strict';
const { run, isWebpack5 } = require('../utils/test-utils');
const { resolve } = require('path');
const { options: coloretteOptions } = require('colorette');

describe('colorts', () => {
    it('should output by default', () => {
        const { stderr, stdout, exitCode } = run(__dirname);

        expect(stderr).toBeFalsy();
        const output = isWebpack5 ? 'successfully' : 'main.js';
        expect(stdout).toContain(coloretteOptions.enabled ? `\u001b[1m\u001b[32m${output}\u001b[39m\u001b[22m` : output);
        expect(exitCode).toBe(0);
    });

    it('should work with the "stats" option from flags', () => {
        const { stderr, stdout, exitCode } = run(__dirname, ['--stats=verbose']);

        expect(stderr).toBeFalsy();
        const output = isWebpack5 ? 'successfully' : 'main.js';
        expect(stdout).toContain(coloretteOptions.enabled ? `\u001b[1m\u001b[32m${output}\u001b[39m\u001b[22m` : output);
        expect(exitCode).toBe(0);
    });

    it('should work with the "stats" option from flags and from configuration', () => {
        const { stderr, stdout, exitCode } = run(__dirname, [
            '--stats=verbose',
            `--config=${resolve(__dirname, './no-stats.webpack.config.js')}`,
        ]);

        expect(stderr).toBeFalsy();
        const output = isWebpack5 ? 'successfully' : 'main.js';
        expect(stdout).toContain(coloretteOptions.enabled ? `\u001b[1m\u001b[32m${output}\u001b[39m\u001b[22m` : output);
        expect(exitCode).toBe(0);
    });

    it('should work with the "stats" option from flags and from configuration #2', () => {
        const { stderr, stdout, exitCode } = run(__dirname, ['--stats=verbose', '--config=stats-string.webpack.config.js']);

        expect(stderr).toBeFalsy();
        const output = isWebpack5 ? 'successfully' : 'main.js';
        expect(stdout).toContain(coloretteOptions.enabled ? `\u001b[1m\u001b[32m${output}\u001b[39m\u001b[22m` : output);
        expect(exitCode).toBe(0);
    });

    it('should disable colored output with --no-color', () => {
        const { stderr, stdout, exitCode } = run(__dirname, ['--stats=verbose', '--no-color']);

        expect(stderr).toBeFalsy();
        const output = isWebpack5 ? 'successfully' : 'main.js';
        expect(stdout).not.toContain(`\u001b[1m\u001b[32m${output}\u001b[39m\u001b[22m`);
        expect(stdout).toContain(output);
        expect(exitCode).toBe(0);
    });

    it('should work with the "stats" option and --color flags', () => {
        const { stderr, stdout, exitCode } = run(__dirname, ['--stats=verbose', '--color']);

        expect(stderr).toBeFalsy();
        const output = isWebpack5 ? 'successfully' : 'main.js';
        expect(stdout).toContain(`\u001b[1m\u001b[32m${output}\u001b[39m\u001b[22m`);
        expect(exitCode).toBe(0);
    });

    it('should work with the "stats" option from the configuration', () => {
        const { stderr, stdout, exitCode } = run(__dirname, ['--config=stats-string.webpack.config.js']);

        expect(stderr).toBeFalsy();
        const output = isWebpack5 ? 'successfully' : 'main.js';
        expect(stdout).toContain(coloretteOptions.enabled ? `\u001b[1m\u001b[32m${output}\u001b[39m\u001b[22m` : output);
        expect(exitCode).toBe(0);
    });

    it('should work with the "stats" option from the configuration #1', () => {
        const { stderr, stdout, exitCode } = run(__dirname, ['--config=stats-boolean.webpack.config.js']);

        expect(stderr).toBeFalsy();
        const output = isWebpack5 ? 'successfully' : 'main.js';
        expect(stdout).toContain(coloretteOptions.enabled ? `\u001b[1m\u001b[32m${output}\u001b[39m\u001b[22m` : output);
        expect(exitCode).toBe(0);
    });

    it('should work with the "stats" option from the configuration #2', () => {
        const { stderr, stdout, exitCode } = run(__dirname, ['--config=no-stats.webpack.config.js']);

        expect(stderr).toBeFalsy();
        const output = isWebpack5 ? 'successfully' : 'main.js';
        expect(stdout).toContain(coloretteOptions.enabled ? `\u001b[1m\u001b[32m${output}\u001b[39m\u001b[22m` : output);
        expect(exitCode).toBe(0);
    });

    it('should work with the "stats" option from the configuration #3', () => {
        const { stderr, stdout, exitCode } = run(__dirname, ['--config=colors-true.webpack.config.js']);

        expect(stderr).toBeFalsy();
        const output = isWebpack5 ? 'successfully' : 'main.js';
        expect(stdout).toContain(coloretteOptions.enabled ? `\u001b[1m\u001b[32m${output}\u001b[39m\u001b[22m` : output);
        expect(exitCode).toBe(0);
    });

    it('should work with the "stats" option from the configuration #4', () => {
        const { stderr, stdout, exitCode } = run(__dirname, ['--config=colors-false.webpack.config.js']);

        expect(stderr).toBeFalsy();
        const output = isWebpack5 ? 'successfully' : 'main.js';

        expect(stdout).not.toContain(`\u001b[1m\u001b[32m${output}\u001b[39m\u001b[22m`);
        expect(stdout).toContain(output);
        expect(exitCode).toBe(0);
    });

    it('should prioritize --color over colors in config', () => {
        const { stderr, stdout, exitCode } = run(__dirname, ['--config=colors-false.webpack.config.js', '--color']);

        expect(stderr).toBeFalsy();
        const output = isWebpack5 ? 'successfully' : 'main.js';

        expect(stdout).toContain(`\u001b[1m\u001b[32m${output}\u001b[39m\u001b[22m`);
        expect(exitCode).toBe(0);
    });

    it('should prioratize --no-color over colors in config', () => {
        const { stderr, stdout, exitCode } = run(__dirname, ['--config=colors-true.webpack.config.js', '--no-color']);

        expect(stderr).toBeFalsy();
        const output = isWebpack5 ? 'successfully' : 'main.js';

        expect(stdout).not.toContain(`\u001b[1m\u001b[32m${output}\u001b[39m\u001b[22m`);
        expect(stdout).toContain(output);
        expect(exitCode).toBe(0);
    });

    it('should work in multicompiler mode', () => {
        const { stderr, stdout, exitCode } = run(__dirname, ['--config=multiple-configs.js', '--color']);

        expect(stderr).toBeFalsy();
        expect(exitCode).toBe(0);

        if (isWebpack5) {
            expect(stdout).toContain(`\u001b[1mfirst-config`);
            expect(stdout).toContain(`\u001b[1msecond-config`);
            expect(stdout).toContain(`\u001b[1m\u001b[32msuccessfully\u001b[39m\u001b[22m`);
        }
    });
});
<commit_msg>chore: fix typo (#2094)<commit_after>'use strict';
const { run, isWebpack5 } = require('../utils/test-utils');
const { resolve } = require('path');
const { options: coloretteOptions } = require('colorette');

describe('colors related tests', () => {
    it('should output by default', () => {
        const { stderr, stdout, exitCode } = run(__dirname);

        expect(stderr).toBeFalsy();
        const output = isWebpack5 ? 'successfully' : 'main.js';
        expect(stdout).toContain(coloretteOptions.enabled ? `\u001b[1m\u001b[32m${output}\u001b[39m\u001b[22m` : output);
        expect(exitCode).toBe(0);
    });

    it('should work with the "stats" option from flags', () => {
        const { stderr, stdout, exitCode } = run(__dirname, ['--stats=verbose']);

        expect(stderr).toBeFalsy();
        const output = isWebpack5 ? 'successfully' : 'main.js';
        expect(stdout).toContain(coloretteOptions.enabled ? `\u001b[1m\u001b[32m${output}\u001b[39m\u001b[22m` : output);
        expect(exitCode).toBe(0);
    });

    it('should work with the "stats" option from flags and from configuration', () => {
        const { stderr, stdout, exitCode } = run(__dirname, [
            '--stats=verbose',
            `--config=${resolve(__dirname, './no-stats.webpack.config.js')}`,
        ]);

        expect(stderr).toBeFalsy();
        const output = isWebpack5 ? 'successfully' : 'main.js';
        expect(stdout).toContain(coloretteOptions.enabled ? `\u001b[1m\u001b[32m${output}\u001b[39m\u001b[22m` : output);
        expect(exitCode).toBe(0);
    });

    it('should work with the "stats" option from flags and from configuration #2', () => {
        const { stderr, stdout, exitCode } = run(__dirname, ['--stats=verbose', '--config=stats-string.webpack.config.js']);

        expect(stderr).toBeFalsy();
        const output = isWebpack5 ? 'successfully' : 'main.js';
        expect(stdout).toContain(coloretteOptions.enabled ? `\u001b[1m\u001b[32m${output}\u001b[39m\u001b[22m` : output);
        expect(exitCode).toBe(0);
    });

    it('should disable colored output with --no-color', () => {
        const { stderr, stdout, exitCode } = run(__dirname, ['--stats=verbose', '--no-color']);

        expect(stderr).toBeFalsy();
        const output = isWebpack5 ? 'successfully' : 'main.js';
        expect(stdout).not.toContain(`\u001b[1m\u001b[32m${output}\u001b[39m\u001b[22m`);
        expect(stdout).toContain(output);
        expect(exitCode).toBe(0);
    });

    it('should work with the "stats" option and --color flags', () => {
        const { stderr, stdout, exitCode } = run(__dirname, ['--stats=verbose', '--color']);

        expect(stderr).toBeFalsy();
        const output = isWebpack5 ? 'successfully' : 'main.js';
        expect(stdout).toContain(`\u001b[1m\u001b[32m${output}\u001b[39m\u001b[22m`);
        expect(exitCode).toBe(0);
    });

    it('should work with the "stats" option from the configuration', () => {
        const { stderr, stdout, exitCode } = run(__dirname, ['--config=stats-string.webpack.config.js']);

        expect(stderr).toBeFalsy();
        const output = isWebpack5 ? 'successfully' : 'main.js';
        expect(stdout).toContain(coloretteOptions.enabled ? `\u001b[1m\u001b[32m${output}\u001b[39m\u001b[22m` : output);
        expect(exitCode).toBe(0);
    });

    it('should work with the "stats" option from the configuration #1', () => {
        const { stderr, stdout, exitCode } = run(__dirname, ['--config=stats-boolean.webpack.config.js']);

        expect(stderr).toBeFalsy();
        const output = isWebpack5 ? 'successfully' : 'main.js';
        expect(stdout).toContain(coloretteOptions.enabled ? `\u001b[1m\u001b[32m${output}\u001b[39m\u001b[22m` : output);
        expect(exitCode).toBe(0);
    });

    it('should work with the "stats" option from the configuration #2', () => {
        const { stderr, stdout, exitCode } = run(__dirname, ['--config=no-stats.webpack.config.js']);

        expect(stderr).toBeFalsy();
        const output = isWebpack5 ? 'successfully' : 'main.js';
        expect(stdout).toContain(coloretteOptions.enabled ? `\u001b[1m\u001b[32m${output}\u001b[39m\u001b[22m` : output);
        expect(exitCode).toBe(0);
    });

    it('should work with the "stats" option from the configuration #3', () => {
        const { stderr, stdout, exitCode } = run(__dirname, ['--config=colors-true.webpack.config.js']);

        expect(stderr).toBeFalsy();
        const output = isWebpack5 ? 'successfully' : 'main.js';
        expect(stdout).toContain(coloretteOptions.enabled ? `\u001b[1m\u001b[32m${output}\u001b[39m\u001b[22m` : output);
        expect(exitCode).toBe(0);
    });

    it('should work with the "stats" option from the configuration #4', () => {
        const { stderr, stdout, exitCode } = run(__dirname, ['--config=colors-false.webpack.config.js']);

        expect(stderr).toBeFalsy();
        const output = isWebpack5 ? 'successfully' : 'main.js';

        expect(stdout).not.toContain(`\u001b[1m\u001b[32m${output}\u001b[39m\u001b[22m`);
        expect(stdout).toContain(output);
        expect(exitCode).toBe(0);
    });

    it('should prioritize --color over colors in config', () => {
        const { stderr, stdout, exitCode } = run(__dirname, ['--config=colors-false.webpack.config.js', '--color']);

        expect(stderr).toBeFalsy();
        const output = isWebpack5 ? 'successfully' : 'main.js';

        expect(stdout).toContain(`\u001b[1m\u001b[32m${output}\u001b[39m\u001b[22m`);
        expect(exitCode).toBe(0);
    });

    it('should prioratize --no-color over colors in config', () => {
        const { stderr, stdout, exitCode } = run(__dirname, ['--config=colors-true.webpack.config.js', '--no-color']);

        expect(stderr).toBeFalsy();
        const output = isWebpack5 ? 'successfully' : 'main.js';

        expect(stdout).not.toContain(`\u001b[1m\u001b[32m${output}\u001b[39m\u001b[22m`);
        expect(stdout).toContain(output);
        expect(exitCode).toBe(0);
    });

    it('should work in multicompiler mode', () => {
        const { stderr, stdout, exitCode } = run(__dirname, ['--config=multiple-configs.js', '--color']);

        expect(stderr).toBeFalsy();
        expect(exitCode).toBe(0);

        if (isWebpack5) {
            expect(stdout).toContain(`\u001b[1mfirst-config`);
            expect(stdout).toContain(`\u001b[1msecond-config`);
            expect(stdout).toContain(`\u001b[1m\u001b[32msuccessfully\u001b[39m\u001b[22m`);
        }
    });
});
<|endoftext|>


<commit_before>// Home Route
Router.route('/', {
  name: 'home',
  action: function () {
    this.render('home');
    Session.set('page_name','home');
    SEO.set({ title: 'Benefit - ' + Meteor.App.NAME });
  }
});

Router.route('/home', {
  name: 'home',
  action: function () {
    this.render('home');
    Session.set('page_name','productions');
    SEO.set({ title: 'Home - ' + Meteor.App.NAME });
  }
});

Router.route('/news', {
  name: 'news',
  action: function () {
    this.render('news');
    Session.set('page_name','news');
    SEO.set({ title: 'News - ' + Meteor.App.NAME });
  }
});

Router.route('/about', {
  name: 'about',
  action: function () {
    this.render('about');
    Session.set('page_name','about');
    SEO.set({ title: 'About - ' + Meteor.App.NAME });
  }
});

Router.route('/contact', {
  name: 'contact',
  action: function () {
    this.render('contact');
    Session.set('page_name','contact');
    SEO.set({ title: 'Contact - ' + Meteor.App.NAME });
  }
});

Router.route('/calendar', {
  name: 'calendar',
  action: function () {
    this.render('calendar');
    Session.set('page_name','calendar');
    SEO.set({ title: 'Calendar - ' + Meteor.App.NAME });
  }
});

Router.route('/poll', {
  name: 'Poll',
  action: function () {
    this.render('poll');
    Session.set('page_name','poll');
    SEO.set({ title: 'poll - ' + Meteor.App.NAME });
  }
});

Router.route('/gallery', {
  name: 'gallery',
  action: function () {
    this.render('gallery');
    Session.set('page_name','gallery');
    SEO.set({ title: 'Gallery - ' + Meteor.App.NAME });
  }
});

Router.route('/gallery/:id', {
  name: 'gallery.album',
  action: function () {
    this.render('album', {data: {id: this.params.id}});
    SEO.set({ title: 'Album - ' + Meteor.App.NAME });
  }
});
<commit_msg>fixed app crash<commit_after>// Home Route
Router.route('/', {
  name: 'home',
  action: function () {
    this.render('home');
    Session.set('page_name','home');
    SEO.set({ title: 'Benefit - ' + Meteor.App.NAME });
  }
});

Router.route('/news', {
  name: 'news',
  action: function () {
    this.render('news');
    Session.set('page_name','news');
    SEO.set({ title: 'News - ' + Meteor.App.NAME });
  }
});

Router.route('/about', {
  name: 'about',
  action: function () {
    this.render('about');
    Session.set('page_name','about');
    SEO.set({ title: 'About - ' + Meteor.App.NAME });
  }
});

Router.route('/contact', {
  name: 'contact',
  action: function () {
    this.render('contact');
    Session.set('page_name','contact');
    SEO.set({ title: 'Contact - ' + Meteor.App.NAME });
  }
});

Router.route('/calendar', {
  name: 'calendar',
  action: function () {
    this.render('calendar');
    Session.set('page_name','calendar');
    SEO.set({ title: 'Calendar - ' + Meteor.App.NAME });
  }
});

Router.route('/poll', {
  name: 'Poll',
  action: function () {
    this.render('poll');
    Session.set('page_name','poll');
    SEO.set({ title: 'poll - ' + Meteor.App.NAME });
  }
});

Router.route('/gallery', {
  name: 'gallery',
  action: function () {
    this.render('gallery');
    Session.set('page_name','gallery');
    SEO.set({ title: 'Gallery - ' + Meteor.App.NAME });
  }
});

Router.route('/gallery/:id', {
  name: 'gallery.album',
  action: function () {
    this.render('album', {data: {id: this.params.id}});
    SEO.set({ title: 'Album - ' + Meteor.App.NAME });
  }
});
<|endoftext|>


<commit_before>import { connect } from 'react-redux';
import React from 'react';
import ReactPlayer from 'react-player';
import { locToUrl, calcDisplaySize } from '../common/util';
import { loadAnnotation, playFile } from '../annotations';
import { loadEmitter } from '../emitter';

class PreviewVideo extends React.Component {
  playlist = null;
  static propTypes = {
    dispatch: React.PropTypes.func,
    loc: React.PropTypes.object,
    preview: React.PropTypes.object,
    containers: React.PropTypes.array,
    storageaccount: React.PropTypes.string,
  };

  handleLoadState() {
    this.playlist = loadAnnotation();
    loadEmitter(this.playlist);
    const fullpath = locToUrl(this.props.loc);
    const index = fullpath.lastIndexOf('/');
    const containerName = this.props.containers[fullpath.substring(index + 1)];

    const src = `https://${this.props.storageaccount}.blob.core.windows.net/${containerName}/${this.props.preview.name}`;
    playFile(this.playlist, src);
  }

  componentDidMount() {
    this.handleLoadState();
  }

  render() {
    const preImgStyle = {
      position: 'absolute',
      width: '100%',
      textAlign: 'center',
      color: '#ccc',
    };
    const preStyle = {
      position: 'relative',
      display: 'block',
      overflow: 'hidden',
    };
    const playlistStyle = {
      background: '#fff',
    };
    const captionStyle = {
      position: 'absolute',
      width: '100%',
      textAlign: 'center',
      color: '#ccc',
    };
    const imageStyle = {
      position: 'relative',
      display: 'block',
      left: '400px',
      top: '40px',
    };

    const outWidth = window.document.documentElement.clientWidth;
    const outHeight = window.document.documentElement.clientHeight;
    const displaySize = calcDisplaySize(outWidth, outHeight, outWidth, outHeight);
    preStyle.width = `${displaySize.width}px`;
    preStyle.height = `${displaySize.height}px`;
    preStyle.left = `${(outWidth - displaySize.width) / 2}px`;
    preStyle.top = `${(outHeight - displaySize.height) / 2}px`;

    const captionY = (outHeight - displaySize.height) / 2 + displaySize.height;
    captionStyle.top = `${captionY}px`;
    const preImgStyleY = (outHeight - displaySize.height) / 2;
    preImgStyle.top = `${preImgStyleY}px`;

    const fullpath = locToUrl(this.props.loc);
    const index = fullpath.lastIndexOf('/');
    const containerName = this.props.containers[fullpath.substring(index + 1)];

    const src = `https://${this.props.storageaccount}.blob.core.windows.net/${containerName}/${this.props.preview.name}`;
    const imageFileName = this.props.preview.name.substring(0, this.props.preview.name.lastIndexOf('.'));

    const imgsrc = `https://${this.props.storageaccount}.blob.core.windows.net/${containerName}/${imageFileName}.png`;

    return (

                Trim

                Download JSON

          {this.props.preview.name}

    );
  }
}

const mapStateToProps = state => ({
  loc: state.loc,
  preview: state.preview,
  containers: state.containers,
  storageaccount: state.storageaccount,
});

export default connect(mapStateToProps)(PreviewVideo);
<commit_msg>Removing download trimmed file from toolbar<commit_after>import { connect } from 'react-redux';
import React from 'react';
import ReactPlayer from 'react-player';
import { locToUrl, calcDisplaySize } from '../common/util';
import { loadAnnotation, playFile } from '../annotations';
import { loadEmitter } from '../emitter';

class PreviewVideo extends React.Component {
  playlist = null;
  static propTypes = {
    dispatch: React.PropTypes.func,
    loc: React.PropTypes.object,
    preview: React.PropTypes.object,
    containers: React.PropTypes.array,
    storageaccount: React.PropTypes.string,
  };

  handleLoadState() {
    this.playlist = loadAnnotation();
    loadEmitter(this.playlist);
    const fullpath = locToUrl(this.props.loc);
    const index = fullpath.lastIndexOf('/');
    const containerName = this.props.containers[fullpath.substring(index + 1)];

    const src = `https://${this.props.storageaccount}.blob.core.windows.net/${containerName}/${this.props.preview.name}`;
    playFile(this.playlist, src);
  }

  componentDidMount() {
    this.handleLoadState();
  }

  render() {
    const preImgStyle = {
      position: 'absolute',
      width: '100%',
      textAlign: 'center',
      color: '#ccc',
    };
    const preStyle = {
      position: 'relative',
      display: 'block',
      overflow: 'hidden',
    };
    const playlistStyle = {
      background: '#fff',
    };
    const captionStyle = {
      position: 'absolute',
      width: '100%',
      textAlign: 'center',
      color: '#ccc',
    };
    const imageStyle = {
      position: 'relative',
      display: 'block',
      left: '400px',
      top: '40px',
    };

    const outWidth = window.document.documentElement.clientWidth;
    const outHeight = window.document.documentElement.clientHeight;
    const displaySize = calcDisplaySize(outWidth, outHeight, outWidth, outHeight);
    preStyle.width = `${displaySize.width}px`;
    preStyle.height = `${displaySize.height}px`;
    preStyle.left = `${(outWidth - displaySize.width) / 2}px`;
    preStyle.top = `${(outHeight - displaySize.height) / 2}px`;

    const captionY = (outHeight - displaySize.height) / 2 + displaySize.height;
    captionStyle.top = `${captionY}px`;
    const preImgStyleY = (outHeight - displaySize.height) / 2;
    preImgStyle.top = `${preImgStyleY}px`;

    const fullpath = locToUrl(this.props.loc);
    const index = fullpath.lastIndexOf('/');
    const containerName = this.props.containers[fullpath.substring(index + 1)];

    const src = `https://${this.props.storageaccount}.blob.core.windows.net/${containerName}/${this.props.preview.name}`;
    const imageFileName = this.props.preview.name.substring(0, this.props.preview.name.lastIndexOf('.'));

    const imgsrc = `https://${this.props.storageaccount}.blob.core.windows.net/${containerName}/${imageFileName}.png`;

    return (

                Trim

                Download JSON

          {this.props.preview.name}

    );
  }
}

const mapStateToProps = state => ({
  loc: state.loc,
  preview: state.preview,
  containers: state.containers,
  storageaccount: state.storageaccount,
});

export default connect(mapStateToProps)(PreviewVideo);
<|endoftext|>


<commit_before>/*global $, jQuery, i, j, ii*/

var GF = function(CHROMO_STRUCTURE, options) {

  'use strict';

  // Check for invalid parameter CHROMO_STRUCTURE
  if ((typeof CHROMO_STRUCTURE === 'undefined') || (typeof CHROMO_STRUCTURE !== 'object')) {
    // console.error("Invalid parameter passed to GF. You need to pass a chromosome structure.");
    return null;
  }

  // Accept both genes object or chromo->genes object
  if ((typeof CHROMO_STRUCTURE.genes === 'undefined')) {
    CHROMO_STRUCTURE.genes = CHROMO_STRUCTURE;
  }

  ///////////////////////////////////////////////////////////
  //      START OF PRIVATE CLASS METHODS/PROPERTIES
  ///////////////////////////////////////////////////////////

  /** Object that represents all of the class private methods and properties. */
  var gfprivate = {};

  /** Chromosome structure */
  gfprivate.CHROMO_STRUCTURE = CHROMO_STRUCTURE;

  /** Default options */
  gfprivate.DEFAULT_OPTIONS = {
    maxPopulation: 45,
    maxGenerations: 1000,
    mutationProb: 0.05,
    numToSelect: 10,
    exitScore: -1 // -1 always runs until maxGenerations is reached
  };

  /** Setting default options */
  gfprivate.extend(gfprivate.DEFAULT_OPTIONS);

  /** Maximum population size */
  gfprivate.maxPopulation = 45; // default to 45

  /** Maximum number of generations */
  gfprivate.maxGenerations = 100; // default to 100

  /** Mutation probability */
  gfprivate.mutationProb = 0.05; // default to 5%

  /** Selection number (a.k.a. tournament winners) */
  gfprivate.numToSelect = 10; // default to 10 tributes (they volunteer)

  /** Chromosome atrributes */
  gfprivate.chromosome = {
    genes: {},
    score: 0,
    generation: 0
  };

  /** Generation Population Array */
  gfprivate.population = [];

  /** Sort (descending) chromosomes based on score */
  gfprivate.sortPopulation = function() {
    gfprivate.population.sort(function(a, b) {
      return b.score - a.score; // descending score order
    });
  };

  /** Crossover Xgene and Ygene and return crossover */
  gfprivate.crossover = function(Xchromo, Ychromo) {
    var crossedChromo = $.extend({},gfprivate.chromosome), // create new chromosome
        property; // holds the looped property
    for (property in Xchromo.genes) { // loop through all weights
      if (Xchromo.genes.hasOwnProperty(property)) {
        // 50/50 chance of picking a gene from either
        crossedChromo.genes[property] = ((Math.random() > 0.5) ? Xchromo.genes[property] : Ychromo.genes[property]);
      }
    }
    // increase generation
    crossedChromo.generation = Xchromo.generation + 1;
    return $.extend({},crossedChromo);
  };

  /** Mutate individual chromosomes */
  gfprivate.getMutated = function(chromo) {
    var mutatedChromo = $.extend({},chromo),
        property;
    for (property in chromo.genes) {
      if (chromo.genes.hasOwnProperty(property)) {
        mutatedChromo.genes[property] = ((Math.random() < gfprivate.mutationProb) ? Math.random() : chromo.genes[property]);
      }
    }
    return mutatedChromo;
  };

  /** Generates a new random chromosome using the structure provided */
  gfprivate.generateChromosome = function() {
    var newChromosome = gfprivate.CHROMO_STRUCTURE,
        property;
    for (property in newChromosome.genes) {
      if (newChromosome.genes.hasOwnProperty(property)) {
        newChromosome.genes[property] = Math.random();
      }
    }
    return newChromosome;
  };

  /** Default fitness function (should be replaced with custom function by framework user) */
  gfprivate.fitnessFunction = function(genes) {
    var property;
    for (property in genes) {
      if (genes.hasOwnProperty(property)) {
        return genes[property];
      }
    }
  };

  /** Evaluate scores of all chromosomes and sets their score property */
  gfprivate.evaluate = function() {
    for (var i = 0; i < gfprivate.population.length; i += 1) {
      var score = {score: gfprivate.fitnessFunction(gfprivate.population[i].genes)};
      $.extend(gfprivate.population[i],score);
    }
  };

  /** Selects the most fit numToSelect in the population */
  gfprivate.selectFittest = function() {
    gfprivate.sortPopulation();
    if (gfprivate.numToSelect > 0) {
      gfprivate.population.splice(gfprivate.numToSelect);
    } else {
      gfprivate.population.splice(1); // If numToSelect is 0 for somereason, we select 1
    }
  };

  /** Selects random chromosomes in a given population,
   * and then pushes those selected to the main population (which is emptied before hand)
   * @param selectionPop a population to select from */
  gfprivate.selectRandom = function(selectionPop) {
    gfprivate.population = [];
    for (var i = 0; i < gfprivate.maxPopulation; i += 1) {
      var selector = Math.floor(Math.random() * selectionPop.length); // Random number from 0 to selectionPop.length
      gfprivate.population.push(JSON.parse(JSON.stringify($.extend({},selectionPop[selector])))); // add the selected value to the population, TODO Hack solution, replace
    }
  };

  /** The method to be used when extending gfprivate with any options,
   * It just checks for any invalid option values that essentially break everything, and fallsback to
   * some safe (probably default values, or not)
   * etc. */
  gfprivate.extend = function(options) {
    $.extend(gfprivate, options); // first we set whatever we were given
    // Then we check, and fix them if need be
    if (gfprivate.maxPopulation < 10) {
      gfprivate.maxPopulation = 10;
    } else if (gfprivate.numToSelect < 1) {
      gfprivate.numToSelect = 1;
    }
  };

  /** Crossover the entire population in gfprivate.population
 * This method has the efficiency class of O(n^2) but is usually run on the fittest
 * chromosomes selected (which are only 10 by default). Keep this in mind when changing the
 * default ```numToSelect``` option.
 */
  gfprivate.crossPopulation = function() {
    var crossoverPopulation = [];
    // Crosses all n chromosomes with all other n-1 chromosomes
    for (var i = 0; i < gfprivate.population.length; i += 1) {
      for (var ii = 1; ii < gfprivate.population.length - i; ii += 1) {
        // 50/50 chance for selecting genes
        var crossoverChromosome = $.extend({},gfprivate.crossover(gfprivate.population[i], gfprivate.population[ii]));
        crossoverPopulation.push(JSON.parse(JSON.stringify(crossoverChromosome))); // HACK SOLUTION FOR REFERENCE PROBLEM, TODO REPLACE THIS
      }
      crossoverPopulation.push(JSON.parse(JSON.stringify(gfprivate.population[i]))); // Re-add all chromosomes used in crossing
    }
    gfprivate.selectRandom(crossoverPopulation); // randomly select chromosomes in the crossoverPopulation and place them in the population
  };

  /** Mutates the entire population */
  gfprivate.mutatePopulation = function() {
    for (var i = 0; i < gfprivate.population.length; i += 1) {
      gfprivate.population[i] = JSON.parse(JSON.stringify(gfprivate.getMutated(gfprivate.population[i]))); // HACK, TODO FIX
    }
  };

  /** Initializes the population array with a random set of chromosomes. */
  gfprivate.initRandomPop = function() {
    /* CREATE RANDOM POPULATION */
    for (var i = 0; i < gfprivate.maxPopulation; i += 1) {
      // Create new random chromosome
      var newChromosome = $.extend(true, {}, gfprivate.generateChromosome());
      // Add it to the population
      gfprivate.population.push(newChromosome);
    }
  };

  /** Checks if the exit score has been reached
   * @returns boolean */
  gfprivate.exitScoreReached = function() {
    if (gfprivate.exitScore !== -1) {
      if (gfprivate.population[0].score >= gfprivate.exitScore) {
        return true;
      }
    }
    return false;
  };

  /** Runs at the beginning of every generation loop. A.k.a. when the generation is born (and evaluated).
   * This should be changed to fit the special needs of every user.
   * If you want to print/log/view the data after every generation, you would do it here.
   * @param population Array containing all chromosomes in the population
   */
  gfprivate.onNewGen = function(population) {
    // default does nothing
    return;
  };

  ///////////////////////////////////////////////////////////
  //             START OF PUBLIC METHODS/API
  ///////////////////////////////////////////////////////////

  /** Class public methods/properties */
  var gfpublic = {};

  /** Initializes the population with either user provided chromosomes or randomly generates them
   * @param initpop (optional) User provided array of initial chromosomes
   * @param validate (optional) Set true if you want genev to validate your array. It is optional as it could be an expensive process.
   * @returns boolean If you provided ```validate``` as true, it will return false when initialization has failed because of invalid data.
   */
  gfpublic.initPopulation = function(initpop, validate) {
    if (typeof initpop !== 'undefined') {
      if (typeof validate !== 'undefined' && validate === true) {
        // validate that all objects in input initpop contain correct properties (CHROMO_STRUCTURE)
        for (var i = 0; i < initpop; i += 1) {
          var property;
          if (typeof initpop[i].genes === 'undefined') {
            // chromosomes not built properly, they need to have a genes properties
            // TODO need some kind of error handler
            return;
          }
          for (property in gfprivate.CHROMO_STRUCTURE) {
            if (typeof initpop[i].genes[property] === 'undefined') {
              // Missing property discovered one of initpop's chromosomes
              return;
            }
          }
        }
      }
      /* Initialize with provided population */
      gfprivate.population = [];
      gfprivate.population.push(initpop);
    }
    /* Init random if one is not provided */
    gfprivate.initRandomPop();
  };

  /** Evolves the population
 * @param evolveOptions object that accepts options (optional)
 * @param fitfunc a fitness function (optional)
 * @returns void
 */
  gfpublic.evolve = function(evolveOptions, fitfunc) {
    // Update options again.
    gfprivate.extend(evolveOptions);

    // The generation counter
    var generationCount = gfprivate.maxGenerations;

    // Set the fitness function if it was passed in
    if (typeof fitfunc === 'function') {
      gfprivate.fitnessFunction = fitfunc;
    }

    // Abort
    // If the population is not initialized
    if (!gfprivate.population.length) {
      // console.error("No population initialized. Hint: Use .initPopulation before .evolve");
      return;
    }

    // Loops for each generation
    while (generationCount--) {
      /* START EVOLUTION */

      /* EVALUATION PHASE */

      gfprivate.evaluate(); // Test all chromosomes and score them

      /* AFTER EVALUATION CALLBACK */

      if (typeof gfprivate.onNewGen === 'function') {
        gfprivate.onNewGen(gfprivate.population); // run default, or custom function if specified in the options
      }

      /* SELECTION PHASE */

      gfprivate.selectFittest(); // Select most fit chromosomes in terms of score attribute

      /* BREAK CONDITION/SCORE CHECK */

      if (gfprivate.exitScoreReached()) {
        break;
      }

      /* CROSSOVER PHASE */

      gfprivate.crossPopulation();

      /* MUTATION PHASE */

      gfprivate.mutatePopulation();

      /* REPEAT UNTIL LAST GENERATION */
    }

    /* END EVOLUTION */
    gfprivate.evaluate();
    gfprivate.selectFittest();
  };

  /** Resets all options to the defaults */
  gfpublic.resetOptions = function() {
    gfprivate.extend(gfprivate.DEFAULT_OPTIONS);
  };

  /** Returns the population currently in gfprivate.population
 * @returns array Array of chromosomes
 */
  gfpublic.getPopulation = function() {
    return gfprivate.population;
  };

  // Options merging
  // This also adds extra flexibility to users who want more control over
  // genev as it also allows them to replace private methods/properties. (so they're not completely private...)
  // TODO Decide if we want to keep it this way
  gfprivate.extend(options);

  // Return class public methods (a.k.a. make them available for use)
  return gfpublic;
};
<commit_msg>Refactor code Add init setup section<commit_after>/*global $, jQuery, i, j, ii*/

var GF = function(CHROMO_STRUCTURE, options) {

  'use strict';

  // Check for invalid parameter CHROMO_STRUCTURE
  if ((typeof CHROMO_STRUCTURE === 'undefined') || (typeof CHROMO_STRUCTURE !== 'object')) {
    // console.error("Invalid parameter passed to GF. You need to pass a chromosome structure.");
    return null;
  }

  // Accept both genes object or chromo->genes object
  if ((typeof CHROMO_STRUCTURE.genes === 'undefined')) {
    CHROMO_STRUCTURE.genes = CHROMO_STRUCTURE;
  }

  ///////////////////////////////////////////////////////////
  //      START OF PRIVATE CLASS METHODS/PROPERTIES
  ///////////////////////////////////////////////////////////

  /** Object that represents all of the class private methods and properties. */
  var gfprivate = {};

  /** Chromosome structure */
  gfprivate.CHROMO_STRUCTURE = CHROMO_STRUCTURE;

  /** Default options */
  gfprivate.DEFAULT_OPTIONS = {
    maxPopulation: 45,
    maxGenerations: 1000,
    mutationProb: 0.05,
    numToSelect: 10,
    exitScore: -1 // -1 always runs until maxGenerations is reached
  };

  /** Maximum population size */
  gfprivate.maxPopulation = 45; // default to 45

  /** Maximum number of generations */
  gfprivate.maxGenerations = 100; // default to 100

  /** Mutation probability */
  gfprivate.mutationProb = 0.05; // default to 5%

  /** Selection number (a.k.a. tournament winners) */
  gfprivate.numToSelect = 10; // default to 10 tributes (they volunteer)

  /** Chromosome atrributes */
  gfprivate.chromosome = {
    genes: {},
    score: 0,
    generation: 0
  };

  /** Generation Population Array */
  gfprivate.population = [];

  /** Sort (descending) chromosomes based on score */
  gfprivate.sortPopulation = function() {
    gfprivate.population.sort(function(a, b) {
      return b.score - a.score; // descending score order
    });
  };

  /** Crossover Xgene and Ygene and return crossover */
  gfprivate.crossover = function(Xchromo, Ychromo) {
    var crossedChromo = $.extend({},gfprivate.chromosome), // create new chromosome
        property; // holds the looped property
    for (property in Xchromo.genes) { // loop through all weights
      if (Xchromo.genes.hasOwnProperty(property)) {
        // 50/50 chance of picking a gene from either
        crossedChromo.genes[property] = ((Math.random() > 0.5) ? Xchromo.genes[property] : Ychromo.genes[property]);
      }
    }
    // increase generation
    crossedChromo.generation = Xchromo.generation + 1;
    return $.extend({},crossedChromo);
  };

  /** Mutate individual chromosomes */
  gfprivate.getMutated = function(chromo) {
    var mutatedChromo = $.extend({},chromo),
        property;
    for (property in chromo.genes) {
      if (chromo.genes.hasOwnProperty(property)) {
        mutatedChromo.genes[property] = ((Math.random() < gfprivate.mutationProb) ? Math.random() : chromo.genes[property]);
      }
    }
    return mutatedChromo;
  };

  /** Generates a new random chromosome using the structure provided */
  gfprivate.generateChromosome = function() {
    var newChromosome = gfprivate.CHROMO_STRUCTURE,
        property;
    for (property in newChromosome.genes) {
      if (newChromosome.genes.hasOwnProperty(property)) {
        newChromosome.genes[property] = Math.random();
      }
    }
    return newChromosome;
  };

  /** Default fitness function (should be replaced with custom function by framework user) */
  gfprivate.fitnessFunction = function(genes) {
    var property;
    for (property in genes) {
      if (genes.hasOwnProperty(property)) {
        return genes[property];
      }
    }
  };

  /** Evaluate scores of all chromosomes and sets their score property */
  gfprivate.evaluate = function() {
    for (var i = 0; i < gfprivate.population.length; i += 1) {
      var score = {score: gfprivate.fitnessFunction(gfprivate.population[i].genes)};
      $.extend(gfprivate.population[i],score);
    }
  };

  /** Selects the most fit numToSelect in the population */
  gfprivate.selectFittest = function() {
    gfprivate.sortPopulation();
    if (gfprivate.numToSelect > 0) {
      gfprivate.population.splice(gfprivate.numToSelect);
    } else {
      gfprivate.population.splice(1); // If numToSelect is 0 for somereason, we select 1
    }
  };

  /** Selects random chromosomes in a given population,
   * and then pushes those selected to the main population (which is emptied before hand)
   * @param selectionPop a population to select from */
  gfprivate.selectRandom = function(selectionPop) {
    gfprivate.population = [];
    for (var i = 0; i < gfprivate.maxPopulation; i += 1) {
      var selector = Math.floor(Math.random() * selectionPop.length); // Random number from 0 to selectionPop.length
      gfprivate.population.push(JSON.parse(JSON.stringify($.extend({},selectionPop[selector])))); // add the selected value to the population, TODO Hack solution, replace
    }
  };

  /** The method to be used when extending gfprivate with any options,
   * It just checks for any invalid option values that essentially break everything, and fallsback to
   * some safe (probably default values, or not)
   * etc. */
  gfprivate.extend = function(options) {
    $.extend(gfprivate, options); // first we set whatever we were given
    // Then we check, and fix them if need be
    if (gfprivate.maxPopulation < 10) {
      gfprivate.maxPopulation = 10;
    } else if (gfprivate.numToSelect < 1) {
      gfprivate.numToSelect = 1;
    }
  };

  /** Crossover the entire population in gfprivate.population
 * This method has the efficiency class of O(n^2) but is usually run on the fittest
 * chromosomes selected (which are only 10 by default). Keep this in mind when changing the
 * default ```numToSelect``` option.
 */
  gfprivate.crossPopulation = function() {
    var crossoverPopulation = [];
    // Crosses all n chromosomes with all other n-1 chromosomes
    for (var i = 0; i < gfprivate.population.length; i += 1) {
      for (var ii = 1; ii < gfprivate.population.length - i; ii += 1) {
        // 50/50 chance for selecting genes
        var crossoverChromosome = $.extend({},gfprivate.crossover(gfprivate.population[i], gfprivate.population[ii]));
        crossoverPopulation.push(JSON.parse(JSON.stringify(crossoverChromosome))); // HACK SOLUTION FOR REFERENCE PROBLEM, TODO REPLACE THIS
      }
      crossoverPopulation.push(JSON.parse(JSON.stringify(gfprivate.population[i]))); // Re-add all chromosomes used in crossing
    }
    gfprivate.selectRandom(crossoverPopulation); // randomly select chromosomes in the crossoverPopulation and place them in the population
  };

  /** Mutates the entire population */
  gfprivate.mutatePopulation = function() {
    for (var i = 0; i < gfprivate.population.length; i += 1) {
      gfprivate.population[i] = JSON.parse(JSON.stringify(gfprivate.getMutated(gfprivate.population[i]))); // HACK, TODO FIX
    }
  };

  /** Initializes the population array with a random set of chromosomes. */
  gfprivate.initRandomPop = function() {
    /* CREATE RANDOM POPULATION */
    for (var i = 0; i < gfprivate.maxPopulation; i += 1) {
      // Create new random chromosome
      var newChromosome = $.extend(true, {}, gfprivate.generateChromosome());
      // Add it to the population
      gfprivate.population.push(newChromosome);
    }
  };

  /** Checks if the exit score has been reached
   * @returns boolean */
  gfprivate.exitScoreReached = function() {
    if (gfprivate.exitScore !== -1) {
      if (gfprivate.population[0].score >= gfprivate.exitScore) {
        return true;
      }
    }
    return false;
  };

  /** Runs at the beginning of every generation loop. A.k.a. when the generation is born (and evaluated).
   * This should be changed to fit the special needs of every user.
   * If you want to print/log/view the data after every generation, you would do it here.
   * @param population Array containing all chromosomes in the population
   */
  gfprivate.onNewGen = function(population) {
    // default does nothing
    return;
  };

  ///////////////////////////////////////////////////////////
  //             START OF PUBLIC METHODS/API
  ///////////////////////////////////////////////////////////

  /** Class public methods/properties */
  var gfpublic = {};

  /** Initializes the population with either user provided chromosomes or randomly generates them
   * @param initpop (optional) User provided array of initial chromosomes
   * @param validate (optional) Set true if you want genev to validate your array. It is optional as it could be an expensive process.
   * @returns boolean If you provided ```validate``` as true, it will return false when initialization has failed because of invalid data.
   */
  gfpublic.initPopulation = function(initpop, validate) {
    if (typeof initpop !== 'undefined') {
      if (typeof validate !== 'undefined' && validate === true) {
        // validate that all objects in input initpop contain correct properties (CHROMO_STRUCTURE)
        for (var i = 0; i < initpop; i += 1) {
          var property;
          if (typeof initpop[i].genes === 'undefined') {
            // chromosomes not built properly, they need to have a genes properties
            // TODO need some kind of error handler
            return;
          }
          for (property in gfprivate.CHROMO_STRUCTURE) {
            if (typeof initpop[i].genes[property] === 'undefined') {
              // Missing property discovered one of initpop's chromosomes
              return;
            }
          }
        }
      }
      /* Initialize with provided population */
      gfprivate.population = [];
      gfprivate.population.push(initpop);
    }
    /* Init random if one is not provided */
    gfprivate.initRandomPop();
  };

  /** Evolves the population
 * @param evolveOptions object that accepts options (optional)
 * @param fitfunc a fitness function (optional)
 * @returns void
 */
  gfpublic.evolve = function(evolveOptions, fitfunc) {
    // Update options again.
    gfprivate.extend(evolveOptions);

    // The generation counter
    var generationCount = gfprivate.maxGenerations;

    // Set the fitness function if it was passed in
    if (typeof fitfunc === 'function') {
      gfprivate.fitnessFunction = fitfunc;
    }

    // Abort
    // If the population is not initialized
    if (!gfprivate.population.length) {
      // console.error("No population initialized. Hint: Use .initPopulation before .evolve");
      return;
    }

    // Loops for each generation
    while (generationCount--) {
      /* START EVOLUTION */

      /* EVALUATION PHASE */

      gfprivate.evaluate(); // Test all chromosomes and score them

      /* AFTER EVALUATION CALLBACK */

      if (typeof gfprivate.onNewGen === 'function') {
        gfprivate.onNewGen(gfprivate.population); // run default, or custom function if specified in the options
      }

      /* SELECTION PHASE */

      gfprivate.selectFittest(); // Select most fit chromosomes in terms of score attribute

      /* BREAK CONDITION/SCORE CHECK */

      if (gfprivate.exitScoreReached()) {
        break;
      }

      /* CROSSOVER PHASE */

      gfprivate.crossPopulation();

      /* MUTATION PHASE */

      gfprivate.mutatePopulation();

      /* REPEAT UNTIL LAST GENERATION */
    }

    /* END EVOLUTION */
    gfprivate.evaluate();
    gfprivate.selectFittest();
  };

  /** Resets all options to the defaults */
  gfpublic.resetOptions = function() {
    gfprivate.extend(gfprivate.DEFAULT_OPTIONS);
  };

  /** Returns the population currently in gfprivate.population
 * @returns array Array of chromosomes
 */
  gfpublic.getPopulation = function() {
    return gfprivate.population;
  };

  ///////////////////////////////////////////////////////////
  //                INIT SETUP
  ///////////////////////////////////////////////////////////

  /** Setting default options */
  gfprivate.extend(gfprivate.DEFAULT_OPTIONS);

  /* Options merging
  This also adds extra flexibility to users who want more control over
  genev as it also allows them to replace private methods/properties. (so they're not completely private...)
  TODO Decide if we want to keep it this way */
  gfprivate.extend(options);

  // Return class public methods (a.k.a. make them available for use)
  return gfpublic;
};
<|endoftext|>


<commit_before>const helpers = require("./global-setup");
const request = require("request");
const expect = require("chai").expect;

const describe = global.describe;
const it = global.it;
const before = global.before;
const after = global.after;

describe("Vendors", function () {
	helpers.setupTimeout(this);

	var app = null;

	before(function () {
		process.env.MM_CONFIG_FILE = "tests/configs/env.js";
		return helpers
			.startApplication({
				args: ["js/electron.js"]
			})
			.then(function (startedApp) {
				app = startedApp;
			});
	});

	after(function () {
		return helpers.stopApplication(app);
	});

	describe("Get list vendors", function () {
		var vendors = require(__dirname + "/../../vendor/vendor.js");
		Object.keys(vendors).forEach((vendor) => {
			it(`should return 200 HTTP code for vendor "${vendor}"`, function () {
				var urlVendor = "http://localhost:8080/vendor/" + vendors[vendor];
				request.get(urlVendor, function (err, res, body) {
					expect(res.statusCode).to.equal(200);
				});
			});
		});

		Object.keys(vendors).forEach((vendor) => {
			it(`should return 404 HTTP code for vendor https://localhost/"${vendor}"`, function () {
				var urlVendor = "http://localhost:8080/" + vendors[vendor];
				request.get(urlVendor, function (err, res, body) {
					expect(res.statusCode).to.equal(404);
				});
			});
		});
	});
});
<commit_msg>Use es6 notations<commit_after>const helpers = require("./global-setup");
const request = require("request");
const expect = require("chai").expect;

const describe = global.describe;
const it = global.it;
const before = global.before;
const after = global.after;

describe("Vendors", function () {
	helpers.setupTimeout(this);

	var app = null;

	before(function () {
		process.env.MM_CONFIG_FILE = "tests/configs/env.js";
		return helpers
			.startApplication({
				args: ["js/electron.js"]
			})
			.then(function (startedApp) {
				app = startedApp;
			});
	});

	after(function () {
		return helpers.stopApplication(app);
	});

	describe("Get list vendors", function () {
		const vendors = require(__dirname + "/../../vendor/vendor.js");
		Object.keys(vendors).forEach((vendor) => {
			it(`should return 200 HTTP code for vendor "${vendor}"`, function () {
				var urlVendor = "http://localhost:8080/vendor/" + vendors[vendor];
				request.get(urlVendor, function (err, res, body) {
					expect(res.statusCode).to.equal(200);
				});
			});
		});

		Object.keys(vendors).forEach((vendor) => {
			it(`should return 404 HTTP code for vendor https://localhost/"${vendor}"`, function () {
				var urlVendor = "http://localhost:8080/" + vendors[vendor];
				request.get(urlVendor, function (err, res, body) {
					expect(res.statusCode).to.equal(404);
				});
			});
		});
	});
});
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Component.extend({
  actions: {
    addParty: function () {
      var parties = this.get('model.statement.sharingParties');
      if (! parties) {
        // Ember.A will create an "Ember Array" which is a superset of the
        // normal JS Array type except it it key-value observing aware
        //
        // TLDR: If you are creating an array literal wrap it in Ember.A like this
        this.set('model.statement.sharingParties', Ember.A(['one']));
      }
      else {
        // #pushObject is a method on Ember.Array that does the same as #push
        // except it also causes ember to update anything observing the array
        //
        // TLDR: use #pushObject not #push to add values to an ember array
        parties.pushObject('more');
      }
    }
  },
});
<commit_msg>removed helpful but verbose coments<commit_after>import Ember from 'ember';

export default Ember.Component.extend({
  actions: {
    addParty: function () {
      var parties = this.get('model.statement.sharingParties');
      if (! parties) {
        this.set('model.statement.sharingParties', Ember.A(['one']));
      }
      else {
        parties.pushObject('more');
      }
    }
  },
});
<|endoftext|>


<commit_before>/* eslint new-cap: 0 */

'use strict'

const express  = require('express')
const router   = express.Router()

const Users    = require('../models/users')
const Rooms    = require('../models/rooms')
const Messages = require('../models/messages')

/*
 * Validate user. Check if current request has a session that contains a valid userId
 */

const validateUser = (req, res, next) => {
  /*
   * If a non-user tries to create a room, 401 out
   */

  if (req.session.userId && Users.isValid(req.session.userId)) return next()
  else {
    let err401 = new Error('Unauthorized')

    err401.status = 401
    return next(err401)
  }
}

/*
 * GET home page
 * It shows the list of rooms and no.,of people in 'em
 */

router.get('/', (req, res, next) => {
  try {
    // get user from session or create new if one doesn't exist
    const userId       = req.session.userId ? req.session.userId : Users.create(Date.now())
    const userNick     = Users.getNickname(userId)

    // get an array of all rooms and user count in 'em
    const allRoomsObjs = Rooms.getAll().map(room => {
      const temp = Object.create(null)

      temp.id           = room.id
      temp.name         = room.name
      temp.userCount    = room.users.length
      temp.createdBy    = Users.getNickname(room.createdBy)
      temp.createdByYou = room.createdBy === userId

      return temp
    })

    // set userId and nickname in session
    req.session.userId   = userId
    req.session.nickname = userNick

    if (req.xhr) res.json(allRoomsObjs)
    else {
      res.render('index', {
        userNick: userNick,
        rooms: allRoomsObjs
      })
    }
  }
  catch(e) {
    next(e)
  }
})

/*
 * PUT/POST change user nickname
 */

const updateUserNickname = (req, res, next) => {
  try {
    const newNickname = req.body.nickname

    Users.setNickname(req.session.userId, newNickname)

    req.session.nickname = newNickname

    if (req.xhr) res.sendStatus(200)
    else res.redirect('/')
  }
  catch(e) {
    next(e)
  }
}

router.route('/user/nickname')
  .all(validateUser)
  .put(updateUserNickname)
  .post(updateUserNickname)

/*
 * POST create a new room with given name
 */

router.post('/room/create', validateUser, (req, res, next) => {
  try {
    const name      = req.body.roomname
    const userId    = req.session.userId
    const newRoomId = Rooms.create(name, userId)
    const newRoomUrl = '/room/' + newRoomId

    if (req.xhr) {
      res.location(newRoomUrl)
      res.sendStatus(201)
    }
    else res.redirect(newRoomUrl)
  }
  catch(e) {
    next(e)
  }
})

/*
 * GET join a room given by room id
 */

router.get('/room/:id', validateUser, (req, res, next) => {
  try {
    const roomId     = req.params.id
    const roomName   = Rooms.getName(roomId)

    // add user to room
    Rooms.addUser(roomId, req.session.userId)

    // get nickname of users in room
    const userIds    = Rooms.getUsers(roomId) || []
    const users      = userIds.map(Users.getNickname)

    // get messages in room sorted by created at date
    const messageIds = Rooms.getMessages(roomId) || []
    const messages   = messageIds
          .map(msgId => {
            const msg      = Messages.get(msgId)
            let temp       = Object.create(null)

            temp.from      = Users.getNickname(msg.from)
            temp.content   = msg.content
            temp.createdAt = msg.createdAt

            return temp
          })
          .sort((a, b) => a.createdAt - b.createdAt)

    const result = {
      users,
      messages,
      roomId,
      roomName,
      currentUser: req.session.nickname
    }

    if (req.xhr) res.json(result)
    else res.render('chat', result)
  }
  catch(e) {
    next(e)
  }
})

/*
 * POST a new message in a room
 */

router.post('/room/:id', validateUser, (req, res, next) => {
  try {
    const roomId       = req.params.id
    const msgContent   = req.body.message
    const from         = req.session.userId

    // create message
    const createdAt    = Date.now()
    const msgId        = Messages.create(msgContent, roomId, createdAt, from)

    const fromNickname = req.session.nickname || Users.getNickname(from)

    // add message to room
    Rooms.addMessage(roomId, msgId)

    // if xhr, send json otherwise redirect back to chat room
    if (req.xhr) {
      res.json({
        from: fromNickname,
        content: msgContent,
        createdAt
      })
    }
    else res.redirect('/room/' + roomId)
  }
  catch(e) {
    next(e)
  }
})

/*
 * GET Make user leave a room
 */

router.get('/room/:id/leave', validateUser, (req, res, next) => {
  try {
    const roomId = req.params.id
    const userId = req.session.userId

    // remove user from room
    Rooms.removeUser(roomId, userId)

    if (req.xhr) res.sendStatus(200)
    // redirect back to home
    else res.redirect('/')
  }
  catch(e) {
    next(e)
  }
})

/*
 * GET Delete a room
 */

const deleteRoom = (req, res, next) => {
  try {
    const roomId    = req.params.id
    const createdBy = Rooms.getCreatedBy(roomId)

    // delete only if user trying to delete had created the room
    if (req.session.userId === createdBy) {
      Rooms.deleteRoom(roomId)

      if (req.xhr) res.sendStatus(200)
      else res.redirect('/')
    }
    else {
      let err403 = new Error('Forbidden. You did not create the room.')

      err403.status = 403

      throw err403
    }
  }
  catch(e) {
    next(e)
  }
}

router.route('/room/:id/delete')
  .all(validateUser)
  .delete(deleteRoom)
  .get(deleteRoom)

module.exports = router
<commit_msg>Added better error message for the 401<commit_after>/* eslint new-cap: 0 */

'use strict'

const express  = require('express')
const router   = express.Router()

const Users    = require('../models/users')
const Rooms    = require('../models/rooms')
const Messages = require('../models/messages')

/*
 * Validate user. Check if current request has a session that contains a valid userId
 */

const validateUser = (req, res, next) => {
  /*
   * If a non-user tries to create a room, 401 out
   */

  if (req.session.userId && Users.isValid(req.session.userId)) return next()
  else {
    let err401 = new Error('Unauthorized. Visit / once to setup user.')

    err401.status = 401
    return next(err401)
  }
}

/*
 * GET home page
 * It shows the list of rooms and no.,of people in 'em
 */

router.get('/', (req, res, next) => {
  try {
    // get user from session or create new if one doesn't exist
    const userId       = req.session.userId ? req.session.userId : Users.create(Date.now())
    const userNick     = Users.getNickname(userId)

    // get an array of all rooms and user count in 'em
    const allRoomsObjs = Rooms.getAll().map(room => {
      const temp = Object.create(null)

      temp.id           = room.id
      temp.name         = room.name
      temp.userCount    = room.users.length
      temp.createdBy    = Users.getNickname(room.createdBy)
      temp.createdByYou = room.createdBy === userId

      return temp
    })

    // set userId and nickname in session
    req.session.userId   = userId
    req.session.nickname = userNick

    if (req.xhr) res.json(allRoomsObjs)
    else {
      res.render('index', {
        userNick: userNick,
        rooms: allRoomsObjs
      })
    }
  }
  catch(e) {
    next(e)
  }
})

/*
 * PUT/POST change user nickname
 */

const updateUserNickname = (req, res, next) => {
  try {
    const newNickname = req.body.nickname

    Users.setNickname(req.session.userId, newNickname)

    req.session.nickname = newNickname

    if (req.xhr) res.sendStatus(200)
    else res.redirect('/')
  }
  catch(e) {
    next(e)
  }
}

router.route('/user/nickname')
  .all(validateUser)
  .put(updateUserNickname)
  .post(updateUserNickname)

/*
 * POST create a new room with given name
 */

router.post('/room/create', validateUser, (req, res, next) => {
  try {
    const name      = req.body.roomname
    const userId    = req.session.userId
    const newRoomId = Rooms.create(name, userId)
    const newRoomUrl = '/room/' + newRoomId

    if (req.xhr) {
      res.location(newRoomUrl)
      res.sendStatus(201)
    }
    else res.redirect(newRoomUrl)
  }
  catch(e) {
    next(e)
  }
})

/*
 * GET join a room given by room id
 */

router.get('/room/:id', validateUser, (req, res, next) => {
  try {
    const roomId     = req.params.id
    const roomName   = Rooms.getName(roomId)

    // add user to room
    Rooms.addUser(roomId, req.session.userId)

    // get nickname of users in room
    const userIds    = Rooms.getUsers(roomId) || []
    const users      = userIds.map(Users.getNickname)

    // get messages in room sorted by created at date
    const messageIds = Rooms.getMessages(roomId) || []
    const messages   = messageIds
          .map(msgId => {
            const msg      = Messages.get(msgId)
            let temp       = Object.create(null)

            temp.from      = Users.getNickname(msg.from)
            temp.content   = msg.content
            temp.createdAt = msg.createdAt

            return temp
          })
          .sort((a, b) => a.createdAt - b.createdAt)

    const result = {
      users,
      messages,
      roomId,
      roomName,
      currentUser: req.session.nickname
    }

    if (req.xhr) res.json(result)
    else res.render('chat', result)
  }
  catch(e) {
    next(e)
  }
})

/*
 * POST a new message in a room
 */

router.post('/room/:id', validateUser, (req, res, next) => {
  try {
    const roomId       = req.params.id
    const msgContent   = req.body.message
    const from         = req.session.userId

    // create message
    const createdAt    = Date.now()
    const msgId        = Messages.create(msgContent, roomId, createdAt, from)

    const fromNickname = req.session.nickname || Users.getNickname(from)

    // add message to room
    Rooms.addMessage(roomId, msgId)

    // if xhr, send json otherwise redirect back to chat room
    if (req.xhr) {
      res.json({
        from: fromNickname,
        content: msgContent,
        createdAt
      })
    }
    else res.redirect('/room/' + roomId)
  }
  catch(e) {
    next(e)
  }
})

/*
 * GET Make user leave a room
 */

router.get('/room/:id/leave', validateUser, (req, res, next) => {
  try {
    const roomId = req.params.id
    const userId = req.session.userId

    // remove user from room
    Rooms.removeUser(roomId, userId)

    if (req.xhr) res.sendStatus(200)
    // redirect back to home
    else res.redirect('/')
  }
  catch(e) {
    next(e)
  }
})

/*
 * GET/DELETE Delete a room
 */

const deleteRoom = (req, res, next) => {
  try {
    const roomId    = req.params.id
    const createdBy = Rooms.getCreatedBy(roomId)

    // delete only if user trying to delete had created the room
    if (req.session.userId === createdBy) {
      Rooms.deleteRoom(roomId)

      if (req.xhr) res.sendStatus(200)
      else res.redirect('/')
    }
    else {
      let err403 = new Error('Forbidden. You did not create the room.')

      err403.status = 403

      throw err403
    }
  }
  catch(e) {
    next(e)
  }
}

router.route('/room/:id/delete')
  .all(validateUser)
  .delete(deleteRoom)
  .get(deleteRoom)

module.exports = router
<|endoftext|>


<commit_before>/**
 * The purpose of wrappedEval is to limit the set of
 * variables that are in scope when `eval` is called. This
 * makes it easier to prevent eval'd code from accessing
 * things that it shouldn't.
 */
function wrappedEval (code) {
  "use strict"
  var Grove
  return eval(code)
}

var hasOwnProperty = Object.prototype.hasOwnProperty

/**
 * Grove() creates and returns an object representing a
 * Grove computer. It is intended to encapsulate all the
 * interesting logic and state involved in running a
 * Grove system, while keeping that logic isolated from
 * the browser environment (to make it easier to test).
 */
function Grove (
    records,
    printTrustedOutput,
    dataChangeCallback) {

  "use strict"

  // === State variables ==================================

  var data = DataRecorder(records, dataChangeCallback)
  var main = null
  var keysHeld = {}
  var permanentErrorOutput = null

  // === Initialization ===================================

  if (getStartupJs()) {
    try {
      bootFromStartupScript()
    } catch(e) {
      printErrorFromStartup(e)
    }
  } else {
    printStartupJsNotFoundError()
  }

  getGlobalObject().setTimeout(handleClock, 0)

  // === Public interface declaration =====================

  return {
    editEntry:     editEntry,
    getDataAsJSON: getDataAsJSON,
    handleKeyDown: handleKeyDown,
    handleKeyUp:   handleKeyUp,
    handleClock:   handleClock
  }

  // === Public function definitions ======================

  function editEntry(name, content) {
    data = data.write(name, content)
  }

  function getDataAsJSON() {
    return data.toJSON()
  }

  function handleKeyDown(event) {
    var key = event.keyCode
    if (keysHeld[key]) return
    keysHeld[key] = true
    runMainAndPrintOutput({type: 'keyDown', key: key})
  }

  function handleKeyUp(event) {
    var key = event.keyCode
    delete keysHeld[key]
    runMainAndPrintOutput({type: 'keyUp', key: key})
  }

  // === Private functions ================================

  function handleClock() {
    runMainAndPrintOutput({
      type: 'clock',
      time: +new Date()
    })
    getGlobalObject()
      .setTimeout(handleClock, timeUntilNextFrame(+new Date(), 20))
  }

  function runnableStartupScript (src) {
    var scriptText = '(function(){'
      + 'var ' + Object.keys(getGlobalObject())
        .filter(notWhitelistedGlobal).join(',')
      + ';' + src
      + 'return main'
      + '})()'

    return scriptText
  }

  function bootFromStartupScript () {
    var script = runnableStartupScript(getStartupJs())
    main = wrappedEval(script)
    runMainAndPrintOutput({type: 'startup'})
  }

  function runMainAndPrintOutput(event) {
    if (!main) return

    if (permanentErrorOutput) {
      printLineBuffers(permanentErrorOutput)
      return
    }

    var output
    try {
      output = main(event, ReadOnly(data))
    } catch(e) {
      var errorColors = {fg: 'black', bg: 'red', b: 1}
      output = permanentErrorOutput = [
        LineBuffer('The system encountered an error:', errorColors),
        LineBuffer(e.toString(), errorColors),
        LineBuffer('', errorColors),
        LineBuffer('Please take a screenshot and report this problem to', errorColors),
        LineBuffer('the.wizard.ben@gmail.com', errorColors)
      ]
    }

    /* The OS may return null from main() if no re-render
     * needs to be performed. This can be used as a performance
     * optimization since the OS can avoid recomputing the
     * screen buffer. */
    if (output === null) {
      return
    }

    if (output === undefined) {
      output = '' + output
    }

    if (output.records) {
      updateDataRecorder(output.records)
    }

    if (hasOwnProperty.call(output, 'screen')) {
      output = output.screen
    }

    if (output.constructor !== Array) {
      output = [output]
    }

    for (var i = 0; i < output.length; i++) {
      if (output[i].type !== LineBuffer.type) {
        output[i] = LineBuffer(output[i])
      }
    }

    printLineBuffers(output)
  }

  function printErrorFromStartup (e) {
    printTrustedOutput([
      'An error occurred while starting up:',
      htmlEscape(e.toString())
    ])
  }

  function printStartupJsNotFoundError () {
    printLineBuffers([
      LineBuffer("Grove " + VERSION, {u: 1}),
      LineBuffer(""),
      LineBuffer("Welcome! This Grove has no operating system installed yet."),
      LineBuffer("To get up and running quickly, please download a Grove snapshot"),
      LineBuffer("that includes an operating system. Snapshots are available at"),
      LineBuffer(""),
      LineBuffer("    https://github.com/druidic/moss/releases", {fg: 'white'}),
      LineBuffer(""),
      LineBuffer("If you want to install or create a custom operating system,"),
      LineBuffer("please read the guide available at"),
      LineBuffer(""),
      LineBuffer("    https://druidic.github.io/grove/guide", {fg: 'white'}),
      LineBuffer(""),
      LineBuffer("If you run into problems, feel free to contact support:"),
      LineBuffer(""),
      LineBuffer("    the.wizard.ben@gmail.com", {fg: 'white'})
    ])
  }

  function printLineBuffers(lineBuffers) {
    printTrustedOutput(lineBuffers.map(function(buffer) {
      return buffer.toHTML()
    }))
  }

  function getStartupJs() {
    return data.read('startup')
  }

  function getGlobalObject () {
    if (typeof self !== 'undefined') {
      return self
    }
    return global
  }

  function notWhitelistedGlobal(varName) {
    return varName !== 'LineBuffer'
  }

  function updateDataRecorder(newRecords) {
    for (var name in newRecords) {
      if (Object.prototype.hasOwnProperty.call(newRecords, name)) {
        data.write(name, newRecords[name])
      }
    }
  }
}
<commit_msg>Don't mention Moss in the default startup output<commit_after>/**
 * The purpose of wrappedEval is to limit the set of
 * variables that are in scope when `eval` is called. This
 * makes it easier to prevent eval'd code from accessing
 * things that it shouldn't.
 */
function wrappedEval (code) {
  "use strict"
  var Grove
  return eval(code)
}

var hasOwnProperty = Object.prototype.hasOwnProperty

/**
 * Grove() creates and returns an object representing a
 * Grove computer. It is intended to encapsulate all the
 * interesting logic and state involved in running a
 * Grove system, while keeping that logic isolated from
 * the browser environment (to make it easier to test).
 */
function Grove (
    records,
    printTrustedOutput,
    dataChangeCallback) {

  "use strict"

  // === State variables ==================================

  var data = DataRecorder(records, dataChangeCallback)
  var main = null
  var keysHeld = {}
  var permanentErrorOutput = null

  // === Initialization ===================================

  if (getStartupJs()) {
    try {
      bootFromStartupScript()
    } catch(e) {
      printErrorFromStartup(e)
    }
  } else {
    printStartupJsNotFoundError()
  }

  getGlobalObject().setTimeout(handleClock, 0)

  // === Public interface declaration =====================

  return {
    editEntry:     editEntry,
    getDataAsJSON: getDataAsJSON,
    handleKeyDown: handleKeyDown,
    handleKeyUp:   handleKeyUp,
    handleClock:   handleClock
  }

  // === Public function definitions ======================

  function editEntry(name, content) {
    data = data.write(name, content)
  }

  function getDataAsJSON() {
    return data.toJSON()
  }

  function handleKeyDown(event) {
    var key = event.keyCode
    if (keysHeld[key]) return
    keysHeld[key] = true
    runMainAndPrintOutput({type: 'keyDown', key: key})
  }

  function handleKeyUp(event) {
    var key = event.keyCode
    delete keysHeld[key]
    runMainAndPrintOutput({type: 'keyUp', key: key})
  }

  // === Private functions ================================

  function handleClock() {
    runMainAndPrintOutput({
      type: 'clock',
      time: +new Date()
    })
    getGlobalObject()
      .setTimeout(handleClock, timeUntilNextFrame(+new Date(), 20))
  }

  function runnableStartupScript (src) {
    var scriptText = '(function(){'
      + 'var ' + Object.keys(getGlobalObject())
        .filter(notWhitelistedGlobal).join(',')
      + ';' + src
      + 'return main'
      + '})()'

    return scriptText
  }

  function bootFromStartupScript () {
    var script = runnableStartupScript(getStartupJs())
    main = wrappedEval(script)
    runMainAndPrintOutput({type: 'startup'})
  }

  function runMainAndPrintOutput(event) {
    if (!main) return

    if (permanentErrorOutput) {
      printLineBuffers(permanentErrorOutput)
      return
    }

    var output
    try {
      output = main(event, ReadOnly(data))
    } catch(e) {
      var errorColors = {fg: 'black', bg: 'red', b: 1}
      output = permanentErrorOutput = [
        LineBuffer('The system encountered an error:', errorColors),
        LineBuffer(e.toString(), errorColors),
        LineBuffer('', errorColors),
        LineBuffer('Please take a screenshot and report this problem to', errorColors),
        LineBuffer('the.wizard.ben@gmail.com', errorColors)
      ]
    }

    /* The OS may return null from main() if no re-render
     * needs to be performed. This can be used as a performance
     * optimization since the OS can avoid recomputing the
     * screen buffer. */
    if (output === null) {
      return
    }

    if (output === undefined) {
      output = '' + output
    }

    if (output.records) {
      updateDataRecorder(output.records)
    }

    if (hasOwnProperty.call(output, 'screen')) {
      output = output.screen
    }

    if (output.constructor !== Array) {
      output = [output]
    }

    for (var i = 0; i < output.length; i++) {
      if (output[i].type !== LineBuffer.type) {
        output[i] = LineBuffer(output[i])
      }
    }

    printLineBuffers(output)
  }

  function printErrorFromStartup (e) {
    printTrustedOutput([
      'An error occurred while starting up:',
      htmlEscape(e.toString())
    ])
  }

  function printStartupJsNotFoundError () {
    printLineBuffers([
      LineBuffer("Grove " + VERSION, {u: 1}),
      LineBuffer(""),
      LineBuffer("Welcome! This Grove has no operating system installed yet."),
      // TODO: make Moss a real thing
      // LineBuffer("To get up and running quickly, please download a Grove snapshot"),
      // LineBuffer("that includes an operating system. Snapshots are available at"),
      // LineBuffer(""),
      // LineBuffer("    https://github.com/druidic/moss/releases", {fg: 'white'}),
      // LineBuffer(""),
      LineBuffer("If you want to install or create a custom operating system,"),
      LineBuffer("please read the guide available at"),
      LineBuffer(""),
      LineBuffer("    https://druidic.github.io/grove/guide", {fg: 'white'}),
      LineBuffer(""),
      LineBuffer("If you get stuck, feel free to contact support:"),
      LineBuffer(""),
      LineBuffer("    the.wizard.ben@gmail.com", {fg: 'white'})
    ])
  }

  function printLineBuffers(lineBuffers) {
    printTrustedOutput(lineBuffers.map(function(buffer) {
      return buffer.toHTML()
    }))
  }

  function getStartupJs() {
    return data.read('startup')
  }

  function getGlobalObject () {
    if (typeof self !== 'undefined') {
      return self
    }
    return global
  }

  function notWhitelistedGlobal(varName) {
    return varName !== 'LineBuffer'
  }

  function updateDataRecorder(newRecords) {
    for (var name in newRecords) {
      if (Object.prototype.hasOwnProperty.call(newRecords, name)) {
        data.write(name, newRecords[name])
      }
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

var hl = require("./hl")
var http = require('http');
var fs = require("fs");
var url  = require('url');
var util  = require('./util');

var server;

var HiTTP = {};
HiTTP.startServer = function(fileName) {
	if (!fileName) throw Error("No args given: webapp filename");

	var fileContents = fs.readFileSync(fileName, "utf8");
	var result = hl.execute(fileContents);

	server = http.createServer(function (request, response) {
		try {
			if (request.method === "OPTIONS") {
				//console.log("HER: " + JSON.stringify(hl.getScopes(), null, 4));
				var scope = {Todo: {add:{}, all:{}}};
				var responseHeaders = {scope: JSON.stringify(scope)};
				response.writeHead(200, responseHeaders);
				response.end();
			}

			var filePath = url.parse(request.url.substring(1)).pathname;
			var query = url.parse(request.url, true).query;

			console.log(request.url, JSON.stringify(url.parse(request.url, true)));

			query = query.value; // TODO: When maps are supported in hilvl, use the entire query object as argument to the webservice code

			if (filePath == null) {
				response.writeHead(404);
				response.end();
				return;
			}

			filePath = filePath.split("/");
			console.log("FILEPATH", filePath);

			var scopeIndex = 0;
			hl.setScope(scopeIndex); // Important to reset to root scope between all requests

			for (var i in filePath) {
				var serviceName = filePath[i];

				var scopeIndex = hl.searchScope(serviceName);

				if (scopeIndex.scope) scopeIndex = scopeIndex.scope;

				console.log("--", serviceName, scopeIndex);

				if (scopeIndex == undefined) {
					break;
				}

				hl.setScope(scopeIndex);
			}

			if (scopeIndex == undefined) {
				result = "Could not find " + serviceName + " in scope";
				var returnCode = 404;
			} else {
				var result = hl.evaluate({service:serviceName, action:"handleRequest", args: "\""+query+"\""}, true, false);
				result = util.removeQuotes(result);
				var returnCode = 200;
			}
		} catch (e) {
			console.log("ERROR: " + e.message);
			var result = JSON.stringify(e.message);
			var returnCode = 503;
		}

		if (typeof result != "string") result = JSON.stringify(result);

		response.writeHead(returnCode, {"Content-Type": "text/html"});
		response.end(result);
	});

	server.listen(8080);
	console.log("\n" + "Server running at http://127.0.0.1:8080/");
}

HiTTP.stopServer = function() {
	server.close();
	hl.clearScope();
}

if (process.argv[2]) {
	HiTTP.startServer(process.argv[2])
}

module.exports = HiTTP;<commit_msg>Small refactoring<commit_after>'use strict';

var hl = require("./hl")
var http = require('http');
var fs = require("fs");
var url  = require('url');
var util  = require('./util');

var server;

var HiTTP = {};
HiTTP.startServer = function(fileName) {
	if (!fileName) throw Error("No args given: webapp filename");

	var fileContents = fs.readFileSync(fileName, "utf8");
	var result = hl.execute(fileContents);

	server = http.createServer(function (request, response) {
		try {
			if (request.method === "OPTIONS") {
				//console.log("HER: " + JSON.stringify(hl.getScopes(), null, 4));
				var scope = {Todo: {add:{}, all:{}}};
				var responseHeaders = {scope: JSON.stringify(scope)};
				response.writeHead(200, responseHeaders);
				response.end();
			}

			var filePath = url.parse(request.url.substring(1)).pathname;
			var query = url.parse(request.url, true).query;

			console.log(request.url, JSON.stringify(url.parse(request.url, true)));

			query = query.value; // TODO: When maps are supported in hilvl, use the entire query object as argument to the webservice code

			if (filePath == null) {
				response.writeHead(404);
				response.end();
				return;
			}

			filePath = filePath.split("/");
			console.log("FILEPATH", filePath);

			var scopeIndex = 0;
			hl.setScope(scopeIndex); // Important to reset to root scope between all requests

			for (var i in filePath) {
				var serviceName = filePath[i];

				var scopeIndex = hl.searchScope(serviceName);

				if (scopeIndex.scope) scopeIndex = scopeIndex.scope;

				console.log("--", serviceName, scopeIndex);

				if (scopeIndex == undefined) {
					break;
				}

				hl.setScope(scopeIndex);
			}

			if (scopeIndex == undefined) {
				result = "Could not find " + serviceName + " in scope";
				var returnCode = 404;
			} else {
				var result = hl.evaluate({service:serviceName, action:"handleRequest", args: "\""+query+"\""}, true, false);
				var returnCode = 200;
			}
		} catch (e) {
			console.log("ERROR: " + e.message);
			var result = JSON.stringify(e.message);
			var returnCode = 503;
		}

		result = util.removeQuotes(result);

		if (typeof result != "string") result = JSON.stringify(result);

		response.writeHead(returnCode, {"Content-Type": "text/html"});
		response.end(result);
	});

	server.listen(8080);
	console.log("\n" + "Server running at http://127.0.0.1:8080/");
}

HiTTP.stopServer = function() {
	server.close();
	hl.clearScope();
}

if (process.argv[2]) {
	HiTTP.startServer(process.argv[2])
}

module.exports = HiTTP;<|endoftext|>


<commit_before>var OpenSpending = OpenSpending || {};
OpenSpending.App = {} || OpenSpending.App;

OpenSpending.App.Explorer = function(config) {
  var my = {};
  my.config = config;
  my.dataset = null;

  my.initialize = function() {
    var $parent = $(my.config.target);
    $parent.append($(explorerTmpl));
    var $explorer = $parent.find('.explorer');
    my.containerId = my.config.target + ' .explorer .bubbletree';
    my.$breakdown = $explorer.find('#controls-breakdown');
    var $breakdownList = my.$breakdown.find('ol');
    var model = OpenSpending.Model(my.config);

    var datasetObj = new model.Dataset({
      name: my.config.dataset
    });
    datasetObj.fetch({
      success: initBreakdowns,
      dataType: 'jsonp'
    });

    function initBreakdowns(dataset) {
      my.dataset = dataset;
      $.each([1,2,3], function(idx, item) {
        var tselect = $('<select />');
        tselect.append($('<option />').attr('value', '').html(''));
        $.each(dataset.drilldownDimensions(), function(idx, item) {
          tselect.append($('<option />').attr('value', item).html(item));
        });
        $breakdownList.append($('
').append(tselect));
      });
      my.$breakdown.find('button').click(function(e) {
        e.preventDefault();
        my.draw();
      });
    }

    if (my.config.defaults && my.config.defaults.drilldowns) {
      my.config.drilldowns = my.config.defaults.drilldowns;
      my.renderTree(my.containerId);
    } else {
      alert('Please select drilldown from sidebar and hit redraw');
    }
  };

  my.draw = function() {
    var vals = [];
    $.each(my.$breakdown.find('select option:selected'), function(idx, item) {
      var _dim = $(item).text();
      // ignore the empty string
      if (_dim) {
        vals.push(_dim);
      }
    });
    vals = _.uniq(vals);
    my.config.drilldowns = vals;
    if (my.config.drilldowns.length > 0) {
      my.renderTree(my.containerId);
    }
  };

  my.renderTree = function(figId) {
    $('.loading').html('Loading data ');
    $('.loading').show();
    var $tooltip = $('
Tooltip
');
    $(figId).append($tooltip);
    $tooltip.hide();

    var tooltip = function(event) {
      if (event.type == 'SHOW') {
        // show tooltip
        vis4.log(event);
        $tooltip.css({
          left: event.mousePos.x + 4,
          top: event.mousePos.y + 4
        });
        $tooltip.html(event.node.label+' '+event.node.famount+'');
        var bubble = event.target;

        $tooltip.show();
      } else {
        // hide tooltip
        $tooltip.hide();
      }
    };

    var dataLoaded = function(data) {
      $('.loading').hide();
      new OpenSpending.BubbleTree.Loader({
        data: data,
        container: figId,
        rootNodeLabel: 'Grant total',
        bubbleType: 'icon',
        bubbleStyles: {
          // 'cofog': OpenSpending.BubbleTree.Styles.Cofog
        },
        tooltipCallback: tooltip
      });
    };

    // call openspending api for data
    new OpenSpending.Aggregator({
      apiUrl: my.config.endpoint + 'api',
      dataset: my.config.dataset,
      drilldowns: my.config.drilldowns,
      // breakdown: 'region',
      callback: dataLoaded
    });
  };

  explorerTmpl = ' \

 \

 \

 \

Year:
 \

 \

 \

 \

 \

Breakdown by
 \

 \

 \
         <button>Redraw</button> \

 \

 \

 \

 \

 \

 \

 \
  ';

  return my;
};

<commit_msg>[app/explorer-v2,js][xs]: get rid of alert when no default drilldowns as annoying.<commit_after>var OpenSpending = OpenSpending || {};
OpenSpending.App = {} || OpenSpending.App;

OpenSpending.App.Explorer = function(config) {
  var my = {};
  my.config = config;
  my.dataset = null;

  my.initialize = function() {
    var $parent = $(my.config.target);
    $parent.append($(explorerTmpl));
    var $explorer = $parent.find('.explorer');
    my.containerId = my.config.target + ' .explorer .bubbletree';
    my.$breakdown = $explorer.find('#controls-breakdown');
    var $breakdownList = my.$breakdown.find('ol');
    var model = OpenSpending.Model(my.config);

    var datasetObj = new model.Dataset({
      name: my.config.dataset
    });
    datasetObj.fetch({
      success: initBreakdowns,
      dataType: 'jsonp'
    });

    function initBreakdowns(dataset) {
      my.dataset = dataset;
      $.each([1,2,3], function(idx, item) {
        var tselect = $('<select />');
        tselect.append($('<option />').attr('value', '').html(''));
        $.each(dataset.drilldownDimensions(), function(idx, item) {
          tselect.append($('<option />').attr('value', item).html(item));
        });
        $breakdownList.append($('
').append(tselect));
      });
      my.$breakdown.find('button').click(function(e) {
        e.preventDefault();
        my.draw();
      });
    }

    if (my.config.defaults && my.config.defaults.drilldowns) {
      my.config.drilldowns = my.config.defaults.drilldowns;
      my.renderTree(my.containerId);
    } else {
      $('.loading').html('Please select drilldown from sidebar and hit redraw');
    }
  };

  my.draw = function() {
    var vals = [];
    $.each(my.$breakdown.find('select option:selected'), function(idx, item) {
      var _dim = $(item).text();
      // ignore the empty string
      if (_dim) {
        vals.push(_dim);
      }
    });
    vals = _.uniq(vals);
    my.config.drilldowns = vals;
    if (my.config.drilldowns.length > 0) {
      my.renderTree(my.containerId);
    }
  };

  my.renderTree = function(figId) {
    $('.loading').html('Loading data ');
    $('.loading').show();
    var $tooltip = $('
Tooltip
');
    $(figId).append($tooltip);
    $tooltip.hide();

    var tooltip = function(event) {
      if (event.type == 'SHOW') {
        // show tooltip
        vis4.log(event);
        $tooltip.css({
          left: event.mousePos.x + 4,
          top: event.mousePos.y + 4
        });
        $tooltip.html(event.node.label+' '+event.node.famount+'');
        var bubble = event.target;

        $tooltip.show();
      } else {
        // hide tooltip
        $tooltip.hide();
      }
    };

    var dataLoaded = function(data) {
      $('.loading').hide();
      new OpenSpending.BubbleTree.Loader({
        data: data,
        container: figId,
        rootNodeLabel: 'Grant total',
        bubbleType: 'icon',
        bubbleStyles: {
          // 'cofog': OpenSpending.BubbleTree.Styles.Cofog
        },
        tooltipCallback: tooltip
      });
    };

    // call openspending api for data
    new OpenSpending.Aggregator({
      apiUrl: my.config.endpoint + 'api',
      dataset: my.config.dataset,
      drilldowns: my.config.drilldowns,
      // breakdown: 'region',
      callback: dataLoaded
    });
  };

  explorerTmpl = ' \

 \

 \

 \

Year:
 \

 \

 \

 \

 \

Breakdown by
 \

 \

 \
         <button>Redraw</button> \

 \

 \

 \

 \

 \

 \

 \
  ';

  return my;
};

<|endoftext|>