<commit_before>export default (element, config, globals) => {
    const layout = {
        menu: menu => ({
            'list-style': 'none',
            'padding': 0,
            'margin': 0,

            item: item => ({
                'display': 'inline-block',
                'margin-left': !item.isFirstchild && config.menu.item.gutter,

                link: link => ({
                    'text-decoration': 'none',
                    'display': 'block',
                    'position': 'relative',
                    'z-index': 2
                }),

                dropdown: dropdown => ({
                    'visibility': 'hidden',
                    'opacity': 0,
                }),

                ':hover': {
                    dropdown: [item.getComponent('dropdown'), {
                        'visibility': 'visible',
                        'opacity': 1
                    }]
                }
            }),
        }),

        dropdown: dropdown => ({
            'list-style': 'none',
            'padding': 0,
            'margin': 0,
            'position': 'absolute',
            'text-align': 'left',
            'z-index': 1,

            item: item => ({
                'position': 'relative',

                link: link => ({
                    'display': 'block',
                    'text-decoration': 'none',
                    'border-top-color': item.isFirstChild && 'transparent'
                }),

                ':hover': {
                    dropdown: [item.getComponent('dropdown'), {
                        'visibility': 'visible',
                        'opacity': 1
                    }],

                    nextSibling: [item.nextSibling, {
                        link: {
                            'border-top-color': 'transparent'
                        }
                    }]
                }
            }),

            dropdown: dropdown => ({
                'transform': config.dropdown.placement === 'left' ? 'translateX(-100%)' : 'translateX(100%)',
                'top': 0
            })
        }),
    }

    return [config, layout];
};<commit_msg>updating layout<commit_after>export default (element, config, globals) => {
    const layout = {
        menu: menu => ({
            'list-style': 'none',
            'padding': 0,
            'margin': 0,

            item: item => ({
                'display': 'inline-block',
                'margin-left': !item.isFirstchild && config.menu.item.gutter,

                link: link => ({
                    'text-decoration': 'none',
                    'display': 'block',
                    'position': 'relative',
                    'z-index': 2
                }),

                ':hover': {
                    dropdown: [item.getComponent('dropdown'), {
                        'visibility': 'visible',
                        'opacity': 1
                    }]
                }
            }),
        }),

        dropdown: dropdown => ({
            'list-style': 'none',
            'padding': 0,
            'margin': 0,
            'position': 'absolute',
            'text-align': 'left',
            'z-index': 1,
            'visibility': 'hidden',
            'opacity': 0,

            item: item => ({
                'position': 'relative',

                link: link => ({
                    'display': 'block',
                    'text-decoration': 'none',
                    'border-top-color': item.isFirstChild && 'transparent'
                }),

                nextSibling: [item.nextSibling, {
                    link: {
                        'border-top': config.dropdown.item.link['border-top']
                    }
                }],

                ':hover': {
                    dropdown: [item.getComponent('dropdown'), {
                        'visibility': 'visible',
                        'opacity': 1
                    }],

                    nextSibling: [item.nextSibling, {
                        link: {
                            disableCascade: true,
                            'border-top-color': 'transparent'
                        }
                    }]
                }
            }),

            dropdown: dropdown => ({
                'transform': config.dropdown.placement === 'left' ? 'translateX(-100%)' : 'translateX(100%)',
                'top': 0
            })
        }),
    }

    return [config, layout];
};<|endoftext|>


<commit_before>/*jshint node: true */
/*globals describe, it, beforeEach */
'use strict';
var expect = require('expect.js');
var Database = require('../');
var ArangoError = require('../lib/error');
var db = new Database();

var testDbName = 'test__database_0';

describe('database', function () {
  beforeEach(function (done) {
    db.dropDatabase(testDbName, function () {
      done();
    });
  });
  describe('createDatabase', function () {
    it('returns a new database object with the given name', function (done) {
      db.createDatabase(testDbName, function (err, database) {
        expect(err).not.to.be.ok();
        expect(database).to.be.a(Database);
        expect(database.name).to.equal(testDbName);
        done();
      });
    });
    it('creates a new database with the given name', function (done) {
      db.createDatabase(testDbName, function (err) {
        expect(err).not.to.be.ok();
        db.database(testDbName, false, function (err2, database) {
          expect(err2).not.to.be.ok();
          expect(database.name).to.equal(testDbName);
          done();
        });
      });
    });
    it('returns an ArangoError if the db already exists', function (done) {
      db.createDatabase(testDbName, function (err) {
        expect(err).not.to.be.ok();
        db.createDatabase(testDbName, function (err2, database) {
          expect(err2).to.be.an(ArangoError);
          expect(database).not.to.be.ok();
          done();
        });
      });
    });
  });
  describe('database', function () {
    describe('with autoCreate:false', function () {
      it('returns the database if it exists', function (done) {
        db.createDatabase(testDbName, function (err) {
          expect(err).not.to.be.ok();
          db.database(testDbName, false, function (err2, database) {
            expect(err2).not.to.be.ok();
            expect(database.name).to.equal(testDbName);
            done();
          });
        });
      });
      it('returns an ArangoError if the db does not exist', function (done) {
        db.database('this_db_does_not_exist', false, function (err, database) {
          expect(err).to.be.an(ArangoError);
          expect(database).not.to.be.ok();
          done();
        });
      });
    });
    describe('with autoCreate:true', function () {
      it('returns the database if it exists', function (done) {
        db.createDatabase(testDbName, function (err) {
          expect(err).not.to.be.ok();
          db.database(testDbName, false, function (err2, database) {
            expect(err2).not.to.be.ok();
            expect(database.name).to.equal(testDbName);
            done();
          });
        });
      });
      it('creates the database if it does not exist', function (done) {
        db.database(testDbName, true, function (err, database) {
          expect(err).not.to.be.ok();
          expect(database.name).to.equal(testDbName);
          done();
        });
      });
    });
  });
  describe('databases', function () {
    it('returns all the databases', function (done) {
      db.databases(function (err, dbs) {
        expect(err).not.to.be.ok();
        expect(dbs).to.be.an(Array);
        expect(dbs).to.have.property('length', 1);
        expect(dbs[0]).to.be.a(Database);
        expect(dbs[0].name).to.equal('_system');
        db.createDatabase(testDbName, function (err2) {
          expect(err2).not.to.be.ok();
          db.databases(function (err3, dbs2) {
            expect(err3).not.to.be.ok();
            var dbNames = dbs2.map(function (db) {
              return db.name;
            });
            expect(dbNames.sort()).to.eql(['_system', testDbName]);
            done();
          });
        });
      });
    });
  });
  describe('dropDatabase', function () {
    it('drops the database if it exists', function (done) {
      db.createDatabase(testDbName, function (err) {
        expect(err).not.to.be.ok();
        db.dropDatabase(testDbName, function (err1) {
          expect(err1).not.to.be.ok();
          db.database(testDbName, false, function (err2, database) {
            expect(err2).to.be.an(ArangoError);
            expect(database).not.to.be.ok();
            done();
          });
        });
      });
    });
    it('returns an ArangoError if the db does not exist', function (done) {
      db.dropDatabase('this_db_does_not_exist', function (err) {
        expect(err).to.be.an(ArangoError);
        done();
      });
    });
  });
});<commit_msg>Whitespace.<commit_after>/*jshint node: true */
/*globals describe, it, beforeEach */
'use strict';
var expect = require('expect.js');
var Database = require('../');
var ArangoError = require('../lib/error');
var db = new Database();
var testDbName = 'test__database_0';

describe('database', function () {
  beforeEach(function (done) {
    db.dropDatabase(testDbName, function () {
      done();
    });
  });
  describe('createDatabase', function () {
    it('returns a new database object with the given name', function (done) {
      db.createDatabase(testDbName, function (err, database) {
        expect(err).not.to.be.ok();
        expect(database).to.be.a(Database);
        expect(database.name).to.equal(testDbName);
        done();
      });
    });
    it('creates a new database with the given name', function (done) {
      db.createDatabase(testDbName, function (err) {
        expect(err).not.to.be.ok();
        db.database(testDbName, false, function (err2, database) {
          expect(err2).not.to.be.ok();
          expect(database.name).to.equal(testDbName);
          done();
        });
      });
    });
    it('returns an ArangoError if the db already exists', function (done) {
      db.createDatabase(testDbName, function (err) {
        expect(err).not.to.be.ok();
        db.createDatabase(testDbName, function (err2, database) {
          expect(err2).to.be.an(ArangoError);
          expect(database).not.to.be.ok();
          done();
        });
      });
    });
  });
  describe('database', function () {
    describe('with autoCreate:false', function () {
      it('returns the database if it exists', function (done) {
        db.createDatabase(testDbName, function (err) {
          expect(err).not.to.be.ok();
          db.database(testDbName, false, function (err2, database) {
            expect(err2).not.to.be.ok();
            expect(database.name).to.equal(testDbName);
            done();
          });
        });
      });
      it('returns an ArangoError if the db does not exist', function (done) {
        db.database('this_db_does_not_exist', false, function (err, database) {
          expect(err).to.be.an(ArangoError);
          expect(database).not.to.be.ok();
          done();
        });
      });
    });
    describe('with autoCreate:true', function () {
      it('returns the database if it exists', function (done) {
        db.createDatabase(testDbName, function (err) {
          expect(err).not.to.be.ok();
          db.database(testDbName, false, function (err2, database) {
            expect(err2).not.to.be.ok();
            expect(database.name).to.equal(testDbName);
            done();
          });
        });
      });
      it('creates the database if it does not exist', function (done) {
        db.database(testDbName, true, function (err, database) {
          expect(err).not.to.be.ok();
          expect(database.name).to.equal(testDbName);
          done();
        });
      });
    });
  });
  describe('databases', function () {
    it('returns all the databases', function (done) {
      db.databases(function (err, dbs) {
        expect(err).not.to.be.ok();
        expect(dbs).to.be.an(Array);
        expect(dbs).to.have.property('length', 1);
        expect(dbs[0]).to.be.a(Database);
        expect(dbs[0].name).to.equal('_system');
        db.createDatabase(testDbName, function (err2) {
          expect(err2).not.to.be.ok();
          db.databases(function (err3, dbs2) {
            expect(err3).not.to.be.ok();
            var dbNames = dbs2.map(function (db) {
              return db.name;
            });
            expect(dbNames.sort()).to.eql(['_system', testDbName]);
            done();
          });
        });
      });
    });
  });
  describe('dropDatabase', function () {
    it('drops the database if it exists', function (done) {
      db.createDatabase(testDbName, function (err) {
        expect(err).not.to.be.ok();
        db.dropDatabase(testDbName, function (err1) {
          expect(err1).not.to.be.ok();
          db.database(testDbName, false, function (err2, database) {
            expect(err2).to.be.an(ArangoError);
            expect(database).not.to.be.ok();
            done();
          });
        });
      });
    });
    it('returns an ArangoError if the db does not exist', function (done) {
      db.dropDatabase('this_db_does_not_exist', function (err) {
        expect(err).to.be.an(ArangoError);
        done();
      });
    });
  });
});<|endoftext|>


<commit_before>(function(Modules) {
  "use strict";

  Modules.TemplateFolderForm = function() {

    this.start = function(templateFolderForm) {
      this.$form = $(templateFolderForm);

      this.$stickyBottom = this.$form.find('#sticky_template_forms');

      this.$stickyBottom.append(this.nothingSelectedButtons);
      this.$stickyBottom.append(this.itemsSelectedButtons);

      // all the diff states that we want to show or hide
      this.states = {
        nothingSelectedButtons: this.$form.find('#nothing_selected'),
        itemsSelectedButtons: this.$form.find('#items_selected'),
        moveToFolderRadios: this.$form.find('#move_to_folder_radios'),
        addNewFolderName: this.$form.find('#add_new_folder_form'),
        moveToNewFolderName: this.$form.find('#move_to_new_folder_form'),
      };
      // first off show the new template / new folder buttons
      this.currentState = 'nothingSelectedButtons';

      this.$form.on('change', 'input[type=checkbox]', () => this.templateFolderCheckboxChanged());

      this.render();
    };

    this.templateFolderCheckboxChanged = function(event) {
      let numSelected = this.countSelectedCheckboxes();

      if (this.currentState === 'nothingSelectedButtons' && numSelected !== 0) {
        this.currentState = 'itemsSelectedButtons';
      } else if (this.currentState === 'itemsSelectedButtons' && numSelected === 0) {
        this.currentState = 'nothingSelectedButtons';
      }

      this.render();
    };

    this.countSelectedCheckboxes = function() {
      return this.$form.find('input[type=checkbox]:checked').length;
    };

    this.render = function() {
      let numSelected = this.countSelectedCheckboxes();

      // hide everything, unless they are the currentState
      Object.entries(this.states).forEach(([state, $el]) => (state === this.currentState ? $el.show() : $el.hide()));
    };

    this.nothingSelectedButtons = function() {
      return `

          <button class="button-secondary" value="new_template">New template</button>
          <button class="button-secondary" value="new_folder">New folder</button>

      `;
    };

    this.itemsSelectedButtons = function() {
      return `

          <button class="button-secondary" value="move_to_folder">Move</button>
          <button class="button-secondary" value="add_to_new_folder">Add to a new folder</button>

      `;
    };
  };

})(window.GOVUK.Modules);
<commit_msg>go to forms on click of action buttons, and detatch and reattach els<commit_after>(function(Modules) {
  "use strict";

  Modules.TemplateFolderForm = function() {

    this.start = function(templateFolderForm) {
      this.$form = $(templateFolderForm);

      this.$stickyBottom = this.$form.find('#sticky_template_forms');

      this.$stickyBottom.append(this.nothingSelectedButtons);
      this.$stickyBottom.append(this.itemsSelectedButtons);

      // all the diff states that we want to show or hide
      this.states = {
        nothingSelectedButtons: this.$form.find('#nothing_selected'),
        itemsSelectedButtons: this.$form.find('#items_selected'),

        moveToFolderRadios: this.$form.find('#move_to_folder_radios'),
        moveToNewFolderForm: this.$form.find('#move_to_new_folder_form'),

        addNewFolderForm: this.$form.find('#add_new_folder_form'),
        addNewTemplateForm: this.$form.find('#add_new_template_form'),

      };

      // first off show the new template / new folder buttons
      this.currentState = 'nothingSelectedButtons';

      this.$form.on('click', 'button.button-secondary', (event) => this.actionButtonClicked(event));
      this.$form.on('change', 'input[type=checkbox]', () => this.templateFolderCheckboxChanged());

      this.render();
    };

    this.actionButtonClicked = function(event) {
      event.preventDefault();
      this.currentState = $(event.currentTarget).val();

      this.render();
    };

    this.templateFolderCheckboxChanged = function() {
      let numSelected = this.countSelectedCheckboxes();

      if (this.currentState === 'nothingSelectedButtons' && numSelected !== 0) {
        this.currentState = 'itemsSelectedButtons';
      } else if (this.currentState === 'itemsSelectedButtons' && numSelected === 0) {
        this.currentState = 'nothingSelectedButtons';
      }

      this.render();
    };

    this.countSelectedCheckboxes = function() {
      return this.$form.find('input[type=checkbox]:checked').length;
    };

    this.render = function() {
      let numSelected = this.countSelectedCheckboxes();

      // detach everything, unless they are the currentState
      Object.entries(this.states).forEach(
        ([state, $el]) => (state === this.currentState ? this.$stickyBottom.append($el) : $el.detach())
      );
    };

    this.nothingSelectedButtons = function() {
      return `

          <button class="button-secondary" value="addNewTemplateForm">New template</button>
          <button class="button-secondary" value="addNewFolderForm">New folder</button>

      `;
    };

    this.itemsSelectedButtons = function() {
      return `

          <button class="button-secondary" value="moveToFolderRadios">Move</button>
          <button class="button-secondary" value="moveToNewFolderForm">Add to a new folder</button>

      `;
    };
  };

})(window.GOVUK.Modules);
<|endoftext|>


<commit_before>/* global Settings, UI, Timer, API, chrome */

/**
 * This file is part of Random User-Agent Browser Extension
 * @link https://github.com/tarampampam/random-user-agent
 *
 * Copyright (C) 2016 tarampampam <github.com/tarampampam>
 *
 * Everyone is permitted to copy and distribute verbatim or modified copies of this license
 * document, and changing it is allowed as long as the name is changed.
 *
 * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING,
 * DISTRIBUTION AND MODIFICATION
 *
 * 0. You just DO WHAT THE FUCK YOU WANT TO.
 */

"use strict";

(function () {

  /**
   * Auto User-Agent renew timer
   *
   * @type Timer
   */
  var useragent_renew_timer = new Timer('User-Agent renew timer', function () {
    API.useragent.renew();
  });

  var updateIconForSite = function(site) {
    var state = 'disabled';
    if (API.settings.getEnabled()) state = API.exceptions.uriMatch({uri: site}) ? 'inactive' : 'active';
    UI.changeStateIcon(state)
  }

  /**
   * Declare actions on settings changes
   *
   * @param   {string} name
   * @param   {mixed} value
   * @returns {void}
   */
  Settings.onSet = function (name, value) {
    switch (name) {
      case 'enabled':
        UI.changeStateIcon(value === true ? 'active' : 'disabled');
        break;
      case 'renew_interval':
        useragent_renew_timer.setInterval(value);
        console.log('"' + useragent_renew_timer.getName() + '" updated to "' + value + '"');
        break;
      case 'renew_enabled':
        value === true && useragent_renew_timer.start() || useragent_renew_timer.stop();
        console.log('"' + useragent_renew_timer.getName() + '" changed state to "' + value + '"');
        break;
    }
    //console.log('Property "' + name + '" write "' + value + '" action');
  };

  /**
   * Load extension settings
   */
  if (!Settings.hasOwnProperty('isLoaded') || Settings.isLoaded !== true) {
    Settings.load(function () {
      if (API.settings.getRenewOnstartupEnabled()) {
        API.useragent.renew();
      }
      useragent_renew_timer.setInterval(API.settings.getRenewIntervalInMicroseconds());
      if (API.settings.getRenewEnabled()) {
        useragent_renew_timer.start();
      }
      UI.changeStateIcon(API.settings.getEnabled() === true ? 'active' : 'disabled');
    });
  }

  /**
   * Auto settings sync
   */
  chrome.storage.onChanged.addListener(function () {
    if (Settings.sync === true) {
      Settings.load(function () {
        console.info('Settings synchronized');
      });
    }
  });

  chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    if (changeInfo.status == 'loading') updateIconForSite(tab.url);
  });

  chrome.tabs.onActivated.addListener(function(activeInfo) {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      updateIconForSite(tabs[0].url);
    });
  });

})();
<commit_msg>Update background.js<commit_after>/* global Settings, UI, Timer, API, chrome */

/**
 * This file is part of Random User-Agent Browser Extension
 * @link https://github.com/tarampampam/random-user-agent
 *
 * Copyright (C) 2016 tarampampam <github.com/tarampampam>
 *
 * Everyone is permitted to copy and distribute verbatim or modified copies of this license
 * document, and changing it is allowed as long as the name is changed.
 *
 * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING,
 * DISTRIBUTION AND MODIFICATION
 *
 * 0. You just DO WHAT THE FUCK YOU WANT TO.
 */

"use strict";

(function () {

  /**
   * Auto User-Agent renew timer
   *
   * @type Timer
   */
  var useragent_renew_timer = new Timer('User-Agent renew timer', function () {
    API.useragent.renew();
  });

  var updateIconForSite = function(site) {
    var state = 'disabled';
    if (API.settings.getEnabled()) state = API.exceptions.uriMatch({uri: site}) ? 'inactive' : 'active';
    UI.changeStateIcon(state)
  }

  /**
   * Declare actions on settings changes
   *
   * @param   {string} name
   * @param   {mixed} value
   * @returns {void}
   */
  Settings.onSet = function (name, value) {
    switch (name) {
      case 'enabled':
        UI.changeStateIcon(value === true ? 'active' : 'disabled');
        break;
      case 'renew_interval':
        useragent_renew_timer.setInterval(value);
        console.log('"' + useragent_renew_timer.getName() + '" updated to "' + value + '"');
        break;
      case 'renew_enabled':
        value === true && useragent_renew_timer.start() || useragent_renew_timer.stop();
        console.log('"' + useragent_renew_timer.getName() + '" changed state to "' + value + '"');
        break;
    }
    //console.log('Property "' + name + '" write "' + value + '" action');
  };

  /**
   * Load extension settings
   */
  if (!Settings.hasOwnProperty('isLoaded') || Settings.isLoaded !== true) {
    Settings.load(function () {
      if (API.settings.getRenewOnstartupEnabled()) {
        API.useragent.renew();
      }
      useragent_renew_timer.setInterval(API.settings.getRenewIntervalInMicroseconds());
      if (API.settings.getRenewEnabled()) {
        useragent_renew_timer.start();
      }
      UI.changeStateIcon(API.settings.getEnabled() === true ? 'active' : 'disabled');
    });
  }

  /**
   * Auto settings sync
   */
  chrome.storage.onChanged.addListener(function () {
    if (Settings.sync === true) {
      Settings.load(function () {
        console.info('Settings synchronized');
      });
    }
  });

  chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    if (changeInfo.status === 'loading') updateIconForSite(tab.url);
  });

  chrome.tabs.onActivated.addListener(function(activeInfo) {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      updateIconForSite(tabs[0].url);
    });
  });

})();
<|endoftext|>


<commit_before>const configuration = require('src/config/configuration').getInstance();
const Cache = require('src/tmdb/cache');
const TMDB = require('src/tmdb/tmdb');
const cache = new Cache();
const tmdb = new TMDB(cache, configuration.get('tmdb', 'apiKey'));

// there should be a translate function from query params to
// tmdb list that is valid. Should it be a helper function or does it
// belong in tmdb.
// + could also have default value that are sent to the client.
//   * have the same class create a getListNames() and a fetchList()
// * dicover list might be overkill_https://tinyurl.com/y7f8ragw
// + trending! https://tinyurl.com/ydywrqox
//   by all, mediatype, or person. Can also define time periode to
//   get more trending view of what people are checking out.
// + newly created (tv/latest).
// + movie/latest
//

function getTmdbMovieList(res, listname, page) {
  Promise.resolve()
  .then(() => tmdb.movieList(listname, page))
  .then((response) => res.send(response))
  .catch((error) => {
    res.status(500).send({ success: false, error: error.message });
  })
}

function getTmdbShowList(res, listname, page) {
  Promise.resolve()
  .then(() => tmdb.showList(listname, page))
  .then((response) => res.send(response))
  .catch((error) => {
    res.status(500).send({ success: false, error: error.message });
  })
}

exports.nowPlayingMovies = (req, res) => {
  const { page } = req.query;
  const listname = 'miscNowPlayingMovies'

  getTmdbMovieList(res, listname, page);
}

exports.popularMovies = (req, res) => {
  const { page } = req.query;
  const listname = 'miscPopularMovies'

  getTmdbMovieList(res, listname, page);
}

exports.topRatedMovies = (req, res) => {
  const { page } = req.query;
  const listname = 'miscTopRatedMovies'

  getTmdbMovieList(res, listname, page);
}

exports.upcomingMovies = (req, res) => {
  const { page } = req.query;
  const listname = 'miscUpcomingMovies'

  getTmdbMovieList(res, listname, page);
}

exports.nowPlayingShows = (req, res) => {
  const { page } = req.query;
  const listname = 'tvOnTheAir'

  getTmdbShowList(res, listname, page);
}

exports.popularShows = (req, res) => {
  const { page } = req.query;
  const listname = 'miscPopularTvs'

  getTmdbShowList(res, listname, page);
}

exports.topRatedShows = (req, res) => {
  const { page } = req.query;
  const listname = 'miscTopRatedTvs'

  getTmdbShowList(res, listname, page);
}
<commit_msg>listController first defines all async functions as constant variables then module exports them all as a dict<commit_after>const configuration = require('src/config/configuration').getInstance();
const Cache = require('src/tmdb/cache');
const TMDB = require('src/tmdb/tmdb');
const cache = new Cache();
const tmdb = new TMDB(cache, configuration.get('tmdb', 'apiKey'));

// there should be a translate function from query params to
// tmdb list that is valid. Should it be a helper function or does it
// belong in tmdb.
// + could also have default value that are sent to the client.
//   * have the same class create a getListNames() and a fetchList()
// * dicover list might be overkill_https://tinyurl.com/y7f8ragw
// + trending! https://tinyurl.com/ydywrqox
//   by all, mediatype, or person. Can also define time periode to
//   get more trending view of what people are checking out.
// + newly created (tv/latest).
// + movie/latest
//

function getTmdbMovieList(res, listname, page) {
  Promise.resolve()
  .then(() => tmdb.movieList(listname, page))
  .then((response) => res.send(response))
  .catch((error) => {
    res.status(500).send({ success: false, error: error.message });
  })
}

function getTmdbShowList(res, listname, page) {
  Promise.resolve()
  .then(() => tmdb.showList(listname, page))
  .then((response) => res.send(response))
  .catch((error) => {
    res.status(500).send({ success: false, error: error.message });
  })
}

const respondWithUnknownError = (res, error) => {
  // console.log('Unknown error:', error)
  res.status(500).send({ success: false, error: 'Unhandled error occured'})
}

const nowPlayingMovies = (req, res) => {
  const { page } = req.query;
  const listname = 'miscNowPlayingMovies'

  return tmdb.movieList(listname, page)
    .then(nowPlayingMovieList => res.send(nowPlayingMovieList))
    .catch(error => respondUnknownError(res, error))
}

const popularMovies = (req, res) => {
  const { page } = req.query;
  const listname = 'miscPopularMovies'

  getTmdbMovieList(res, listname, page);
}

const topRatedMovies = (req, res) => {
  const { page } = req.query;
  const listname = 'miscTopRatedMovies'

  getTmdbMovieList(res, listname, page);
}

const upcomingMovies = (req, res) => {
  const { page } = req.query;
  const listname = 'miscUpcomingMovies'

  getTmdbMovieList(res, listname, page);
}

const nowPlayingShows = (req, res) => {
  const { page } = req.query;
  const listname = 'tvOnTheAir'

  getTmdbShowList(res, listname, page);
}

const popularShows = (req, res) => {
  const { page } = req.query;
  const listname = 'miscPopularTvs'

  getTmdbShowList(res, listname, page);
}

const topRatedShows = (req, res) => {
  const { page } = req.query;
  const listname = 'miscTopRatedTvs'

  getTmdbShowList(res, listname, page);
}

module.exports = {
  nowPlayingMovies,
  popularMovies,
  topRatedMovies,
  upcomingMovies,
  nowPlayingShows,
  popularShows,
  topRatedShows
}
<|endoftext|>


<commit_before>const Discord = require('discord.js');
module.exports = member => {
    const modlog = member.guild.channels.find('name', 'pie-log');
    //${member.user.username}
    const embed = new Discord.RichEmbed()
    .setTimestamp()
    .setColor(0xff0000)
    .setTitle("User Left")
    .setThumbnail(`${member.user.avatarURL}`)
    .setDescription(`\n`)
    .addField("Username:",`${member.user.username} (${member.user})`,true)
    .addField("Highest Role:",`${member.user.guildmember.highestRole}`,false)
  .setFooter(`User: ${member.user.username}`,`${member.user.avatarURL}`);
  member.guild.channels.get(modlog.id).send({embed}).catch(console.error);
  };
<commit_msg>Update guildMemberRemove.js<commit_after>const Discord = require('discord.js');
module.exports = member => {
    const modlog = member.guild.channels.find('name', 'pie-log');
    //${member.user.username}
    const embed = new Discord.RichEmbed()
    .setTimestamp()
    .setColor(0xff0000)
    .setTitle("User Left")
    .setThumbnail(`${member.user.avatarURL}`)
    .setDescription(`\n`)
    .addField("Username:",`${member.user.username} (${member.user})`,true)
    .addField("Highest Role:",`${member.guildmember.highestRole}`,false)
  .setFooter(`User: ${member.user.username}`,`${member.user.avatarURL}`);
  member.guild.channels.get(modlog.id).send({embed}).catch(console.error);
  };
<|endoftext|>


<commit_before>// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt

cur_frm.cscript.get_states=function(doc, dt, dn) {
	return $c('runserverobj', args={'method': 'check_state', 'docs':doc},
		function(r, rt) {
			if(r.message)
				set_field_options('state', r.message);
		}
	);
}

cur_frm.cscript.country = function(doc, dt, dn) {
	cur_frm.cscript.get_states(doc, dt, dn);
}

if(cur_frm.fields_dict['territory']) {
	cur_frm.fields_dict['territory'].get_query = function(doc, dt, dn) {
		return {
			filters: {
				'is_group': "No"
			}
		}
	}
}

cur_frm.cscript.render_contact_row = function(wrapper, data) {
	// prepare data
	data.fullname = (data.first_name || '')
		+ (data.last_name ? ' ' + data.last_name : '');
	data.primary = data.is_primary_contact ? ' [Primary]' : '';

	// prepare description
	var description = [];
	$.each([
		['phone', 'Tel'],
		['mobile_no', 'Mobile'],
		['email_id', 'Email'],
		['department', 'Department'],
		['designation', 'Designation']],
		function(i, v) {
			if(v[0] && data[v[0]]) {
				description.push(repl('
%(label)s:
 %(value)s', {
					label: v[1],
					value: data[v[0]],
				}));
			}
		});
	data.description = description.join('
');

	cur_frm.cscript.render_row_in_wrapper(wrapper, data, 'Contact');
}

cur_frm.cscript.render_address_row = function(wrapper, data) {
	// prepare data
	data.fullname = data.address_type;
	data.primary = '';
	if (data.is_primary_address) data.primary += ' [Preferred for Billing]';
	if (data.is_shipping_address) data.primary += ' [Preferred for Shipping]';

	// prepare address
	var address = [];
	$.each(['address_line1', 'address_line2', 'city', 'state', 'country', 'pincode'],
		function(i, v) {
			if(data[v]) address.push(data[v]);
		});

	data.address = address.join('
');
	data.address = "
" + data.address + "
";

	// prepare description
	var description = [];
	$.each([
		['address', 'Address'],
		['phone', 'Tel'],
		['fax', 'Fax'],
		['email_id', 'Email']],
		function(i, v) {
			if(data[v[0]]) {
				description.push(repl('
%(label)s:
 %(value)s', {
					label: v[1],
					value: data[v[0]],
				}));
			}
		});
	data.description = description.join('
');

	cur_frm.cscript.render_row_in_wrapper(wrapper, data, 'Address');

	$(wrapper).find('p.address-list').css({
		'padding-left': '10px',
		'margin-bottom': '-10px'
	});
}

cur_frm.cscript.render_row_in_wrapper = function(wrapper, data, doctype) {
	// render
	var $wrapper = $(wrapper);

	data.doctype = doctype.toLowerCase();

	$wrapper.append(repl("\

%(fullname)s%(primary)s
\

\

%(description)s
\

delete this %(doctype)s
\

", data));

	// make link
	$wrapper.find('h4 a.link_type').click(function() {
		loaddoc(doctype, data.name);
	});

	// css
	$wrapper.css({ 'margin': '0px' });
	$wrapper.find('div.description').css({
		'padding': '5px 2px',
		'line-height': '150%',
	});
	$wrapper.find('h6').css({ 'display': 'inline-block' });

	// show delete
	var $delete_doc = $wrapper.find('a.delete');
	if (frappe.model.can_delete(doctype))
		$delete_doc.toggle(true);
	else
		$delete_doc.toggle(false);

	$delete_doc.css({ 'padding-left': '0px' });

	$delete_doc.click(function() {
		cur_frm.cscript.delete_doc(doctype, data.name);
		return false;
	});
}

cur_frm.cscript.delete_doc = function(doctype, name) {
	// confirm deletion
	var go_ahead = confirm(__("Delete {0} {1}?", [doctype, name]));
	if (!go_ahead) return;

	return frappe.call({
		method: 'frappe.model.delete_doc',
		args: {
			dt: doctype,
			dn: name
		},
		callback: function(r) {
			//console.log(r);
			if (!r.exc) {
				// run the correct list
				var list_name = doctype.toLowerCase() + '_list';
				cur_frm[list_name].run();
			}
		}
	});
}

// Render List
cur_frm.cscript.render_list = function(doc, doctype, wrapper, ListView, make_new_doc) {
	frappe.model.with_doctype(doctype, function(r) {
		if((r && r['403']) || frappe.boot.user.all_read.indexOf(doctype)===-1) {
			return;
		}
		var RecordListView = frappe.views.RecordListView.extend({
			default_docstatus: ['0', '1', '2'],
			default_filters: [
				[doctype, doc.doctype.toLowerCase().replace(" ", "_"), '=', doc.name],
			],
		});

		if (make_new_doc) {
			RecordListView = RecordListView.extend({
				make_new_doc: make_new_doc,
			});
		}

		var record_list_view = new RecordListView(doctype, wrapper, ListView);
		if (!cur_frm[doctype.toLowerCase().replace(" ", "_") + "_list"]) {
			cur_frm[doctype.toLowerCase().replace(" ", "_") + "_list"] = record_list_view;
		}
	});
}
<commit_msg>Fixed address deletion issue<commit_after>// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt

cur_frm.cscript.get_states=function(doc, dt, dn) {
	return $c('runserverobj', args={'method': 'check_state', 'docs':doc},
		function(r, rt) {
			if(r.message)
				set_field_options('state', r.message);
		}
	);
}

cur_frm.cscript.country = function(doc, dt, dn) {
	cur_frm.cscript.get_states(doc, dt, dn);
}

if(cur_frm.fields_dict['territory']) {
	cur_frm.fields_dict['territory'].get_query = function(doc, dt, dn) {
		return {
			filters: {
				'is_group': "No"
			}
		}
	}
}

cur_frm.cscript.render_contact_row = function(wrapper, data) {
	// prepare data
	data.fullname = (data.first_name || '')
		+ (data.last_name ? ' ' + data.last_name : '');
	data.primary = data.is_primary_contact ? ' [Primary]' : '';

	// prepare description
	var description = [];
	$.each([
		['phone', 'Tel'],
		['mobile_no', 'Mobile'],
		['email_id', 'Email'],
		['department', 'Department'],
		['designation', 'Designation']],
		function(i, v) {
			if(v[0] && data[v[0]]) {
				description.push(repl('
%(label)s:
 %(value)s', {
					label: v[1],
					value: data[v[0]],
				}));
			}
		});
	data.description = description.join('
');

	cur_frm.cscript.render_row_in_wrapper(wrapper, data, 'Contact');
}

cur_frm.cscript.render_address_row = function(wrapper, data) {
	// prepare data
	data.fullname = data.address_type;
	data.primary = '';
	if (data.is_primary_address) data.primary += ' [Preferred for Billing]';
	if (data.is_shipping_address) data.primary += ' [Preferred for Shipping]';

	// prepare address
	var address = [];
	$.each(['address_line1', 'address_line2', 'city', 'state', 'country', 'pincode'],
		function(i, v) {
			if(data[v]) address.push(data[v]);
		});

	data.address = address.join('
');
	data.address = "
" + data.address + "
";

	// prepare description
	var description = [];
	$.each([
		['address', 'Address'],
		['phone', 'Tel'],
		['fax', 'Fax'],
		['email_id', 'Email']],
		function(i, v) {
			if(data[v[0]]) {
				description.push(repl('
%(label)s:
 %(value)s', {
					label: v[1],
					value: data[v[0]],
				}));
			}
		});
	data.description = description.join('
');

	cur_frm.cscript.render_row_in_wrapper(wrapper, data, 'Address');

	$(wrapper).find('p.address-list').css({
		'padding-left': '10px',
		'margin-bottom': '-10px'
	});
}

cur_frm.cscript.render_row_in_wrapper = function(wrapper, data, doctype) {
	// render
	var $wrapper = $(wrapper);

	data.doctype = doctype.toLowerCase();

	$wrapper.append(repl("\

%(fullname)s%(primary)s
\

\

%(description)s
\

delete this %(doctype)s
\

", data));

	// make link
	$wrapper.find('h4 a.link_type').click(function() {
		loaddoc(doctype, data.name);
	});

	// css
	$wrapper.css({ 'margin': '0px' });
	$wrapper.find('div.description').css({
		'padding': '5px 2px',
		'line-height': '150%',
	});
	$wrapper.find('h6').css({ 'display': 'inline-block' });

	// show delete
	var $delete_doc = $wrapper.find('a.delete');
	if (frappe.model.can_delete(doctype))
		$delete_doc.toggle(true);
	else
		$delete_doc.toggle(false);

	$delete_doc.css({ 'padding-left': '0px' });

	$delete_doc.click(function() {
		cur_frm.cscript.delete_doc(doctype, data.name);
		return false;
	});
}

cur_frm.cscript.delete_doc = function(doctype, name) {
	// confirm deletion
	var go_ahead = confirm(__("Delete {0} {1}?", [doctype, name]));
	if (!go_ahead) return;

	frappe.model.delete_doc(doctype, name, function(r) {
		if (!r.exc) {
			var list_name = doctype.toLowerCase() + '_list';
			cur_frm[list_name].run();
		}
	});
}

// Render List
cur_frm.cscript.render_list = function(doc, doctype, wrapper, ListView, make_new_doc) {
	frappe.model.with_doctype(doctype, function(r) {
		if((r && r['403']) || frappe.boot.user.all_read.indexOf(doctype)===-1) {
			return;
		}
		var RecordListView = frappe.views.RecordListView.extend({
			default_docstatus: ['0', '1', '2'],
			default_filters: [
				[doctype, doc.doctype.toLowerCase().replace(" ", "_"), '=', doc.name],
			],
		});

		if (make_new_doc) {
			RecordListView = RecordListView.extend({
				make_new_doc: make_new_doc,
			});
		}

		var record_list_view = new RecordListView(doctype, wrapper, ListView);
		if (!cur_frm[doctype.toLowerCase().replace(" ", "_") + "_list"]) {
			cur_frm[doctype.toLowerCase().replace(" ", "_") + "_list"] = record_list_view;
		}
	});
}
<|endoftext|>


<commit_before>process.exit(

    0.00 // budget.js - keeping the books for @brooklyn_js
         // by @jedschmidt and @brianloveswords

         // for details, see our accountant:
         // https://travis-ci.org/brooklynjs/brooklynjs.github.io

         // BrooklynJS #1, 2013-11-14T19:00Z at @61Local
         // featuring @nakajima, @jandet, @SaraJChipps, and @jeresig

+ 360.00 // ticket sales  @peatix
+ 350.00 // sponsorship   @github

- 360.00 // bar tab       @61local
-  81.00 // tickets       @peatix
-  51.00 // banners       @BuildASign
-  50.00 // venue         @61local
-  32.00 // VGA adapter   @amazon
-  21.00 // nametags      @staples
-  14.00 // domain        @namecheap

-  50.50 // donation      @GirlsWhoCode
-  50.50 // donation      @ScriptEdnyc

         // BrooklynJS #2, 2013-12-16T19:00Z at @61Local
         // featuring @tbuchok, @vinceallenvince, @buritica, @benjamn, and @reconbot
         // with a surprise appearance by @jedschmidt's barbershop quartet

+ 665.00 // ticket sales  @peatix
+ 450.00 // sponsorship   @crushlovely

- 644.38 // bar tab       @61local
- 107.00 // tickets       @peatix
-  65.18 // stickers      @diginate
-  50.00 // venue         @61local
-  29.55 // VGA cable     @amazon
-   7.49 // paper tickets @amazon

- 105.70 // donation      @GirlsWhoCode
- 105.70 // donation      @ScriptEdnyc

)
<commit_msg>add numbers from brooklyn js the third<commit_after>process.exit(

     0.00 // budget.js - keeping the books for @brooklyn_js
	  // by @jedschmidt and @brianloveswords

	  // for details, see our accountant:
	  // https://travis-ci.org/brooklynjs/brooklynjs.github.io

	  // BrooklynJS #1, 2013-11-14T19:00Z at @61Local
	  // featuring @nakajima, @jandet, @SaraJChipps, and @jeresig

+  360.00 // ticket sales  @peatix
+  350.00 // sponsorship   @github

-  360.00 // bar tab       @61local
-   81.00 // ticketing     @peatix
-   51.00 // banners       @BuildASign
-   50.00 // venue         @61local
-   32.00 // VGA adapter   @amazon
-   21.00 // nametags      @staples
-   14.00 // domain        @namecheap

-   50.50 // donation      @GirlsWhoCode
-   50.50 // donation      @ScriptEdnyc

	  // BrooklynJS #2, 2013-12-16T19:00Z at @61Local
	  // featuring @tbuchok, @vinceallenvince, @buritica, @benjamn, and @reconbot
	  // with special musical guest, @jedschmidt's barbershop quartet, the four fives

+  665.00 // ticket sales  @peatix
+  450.00 // sponsorship   @crushlovely

-  644.38 // bar tab       @61local
-  107.00 // ticketing     @peatix
-   65.18 // stickers      @diginate
-   50.00 // venue         @61local
-   29.55 // VGA cable     @amazon
-    7.49 // paper tickets @amazon

-  105.70 // donation      @GirlsWhoCode
-  105.70 // donation      @ScriptEdnyc

	  // BrooklynJS #3, 2014-01-22T19:00Z at @61Local
	  // featuring @thlorenz, @donohoe, @mathisonian, and @jennschiffer
	  // with special musical guest, @csvsoundsystem

+  970.00 // ticket sales  @peatix
+ 1500.00 // sponsorship   @nodejitsu, @digitalocean, and @harvest

-  800.00 // bar tab       @61local
-  136.99 // ticketing     @peatix
-  237.57 // tokens        @CuboNewYork521
-   79.59 // stickers      @diginate
-   50.00 // venue         @61local
-   10.99 // 3.5mm cable   @amazon

-  577.43 // donation      @GirlsWhoCode
-  577.43 // donation      @ScriptEdnyc
)
<|endoftext|>


<commit_before>function EMULATE(hostframe) {
  function post(msg) {
    msg.for="emu";
    ideframe.contentWindow.postMessage(msg,"*");
  }
  window.addEventListener('message', function(e) {
    var event = e.data;
    if (typeof event!="object" || event.from!="emu") return;
    console.log("HOST MESSAGE ---------------------------------------");
    console.log(event);
    console.log("-----------------------------------------------");

    switch (event.type) {
      case "init":
        console.log("EMU frame initialised");
        if (Espruino.onready)
          Espruino.onready();
        post({type:"initialised"});
        break;
      case "getPorts": // get port data
        if (Espruino.onportscb) {
          Espruino.onportscb(function(ports) {
            post({type:"ports", data: ports});
          });
        } else
          post({type:"ports", data: Espruino.onports?Espruino.onports():[]});
        break;
      case "connect": // request to connect
        if (Espruino.onconnect) {
          Espruino.onconnect(/*path*/event.data, function() {
            post({type:"connected"})
          });
        } else {
          post({type:"connected"}); // let's just say we were connected immediately
        }
        break;
      case "disconnect": // request to disconnect
        post({type:"disconnected"}); // let's just say we were disconnected immediately
        if (Espruino.ondisconnect)
          Espruino.ondisconnect();
        break;
      case "write": // data to write
        if (typeof event.data!="string") throw new Error("write event should have been given a string");
        if (Espruino.onwritecb) {
          Espruino.onwritecb(event.data, function() {
            post({type:"written"});
          });
        } else {
          if (Espruino.onwrite)
            Espruino.onwrite(event.data);
          // post that we've written, but after a delay
          setTimeout(function() {
            post({type:"written"});
          }, 100);
        }
        break;
      default:
        console.error("Unknown event type ",event.type);
        break;
    }
  });
  var Espruino = {
    // tell the IDE to connect to the given port
    connect : function(port) {
      post({type:"connect",data:port});
    },
    // tell the IDE it's disconnected
    disconnect : function() {
      post({type:"disconnected"});
    },
    // Data received from device - d should be a string
    received : function(d) {
      if (typeof d!="string") throw new Error("Espruino.received should be given a string");
      post({type:"receive",data:d});
    },
    // Set the maximum number of bytes that 'onwrite/onwritecb' should be called with
    setMaxWriteLength : function(l) {
      if (typeof l!="number") throw new Error("Espruino.received should be given a number");
      post({type:"setMaxWriteLength",data:l});
    },
    // ------------------ all the below are optional
    // called when the IDE is ready
    onready : undefined,
    // called with (path, callback) when IDE requests a connection. Should call callback when connected
    onconnect : undefined,
    // called with (data) when data should be written to the device. Use this or `onwritecb`
    onwrite : undefined,
    // called with (data,callback) when data should be written to the device. callback should be called when data has been written. Use this or `onwrite`
    onwritecb : undefined,
    // called when the user requests a disconnect
    ondisconnect : undefined,
  };
  return Espruino;
}
<commit_msg>un-needed file<commit_after><|endoftext|>


<commit_before>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
// @ts-check
(function () {
	'use strict';

	const ipcRenderer = require('electron').ipcRenderer;

	var firstLoad = true;
	var loadTimeout;

	const initData = {
		initialScrollProgress: undefined
	};

	function styleBody(body) {
		if (!body) {
			return;
		}
		body.classList.remove('vscode-light', 'vscode-dark', 'vscode-high-contrast');
		body.classList.add(initData.activeTheme);
	}

	/**
	 * @return {HTMLIFrameElement}
	 */
	function getActiveFrame() {
		return document.getElementById('active-frame');
	}

	/**
	 * @return {HTMLIFrameElement}
	 */
	function getPendingFrame() {
		return document.getElementById('pending-frame');
	}

	/**
	 * @param {MouseEvent} event
	 */
	function handleInnerClick(event) {
		if (!event || !event.view || !event.view.document) {
			return;
		}
		/** @type {any} */
		var node = event.target;
		while (node) {
			if (node.tagName && node.tagName.toLowerCase() === 'a' && node.href) {
				var baseElement = event.view.document.getElementsByTagName("base")[0];
				if (node.getAttribute("href") === "#") {
					event.view.scrollTo(0, 0);
				} else if (node.hash && (node.getAttribute("href") === node.hash || (baseElement && node.href.indexOf(baseElement.href) >= 0))) {
					var scrollTarget = event.view.document.getElementById(node.hash.substr(1, node.hash.length - 1));
					if (scrollTarget) {
						scrollTarget.scrollIntoView();
					}
				} else {
					ipcRenderer.sendToHost("did-click-link", node.href);
				}
				event.preventDefault();
				break;
			}
			node = node.parentNode;
		}
	}

	var isHandlingScroll = false;
	function handleInnerScroll(event) {
		if (isHandlingScroll) {
			return;
		}

		const progress = event.target.body.scrollTop / event.target.body.clientHeight;
		if (isNaN(progress)) {
			return;
		}

		isHandlingScroll = true;
		window.requestAnimationFrame(function () {
			try {
				ipcRenderer.sendToHost('did-scroll', progress);
			} catch (e) {
				// noop
			}
			isHandlingScroll = false;
		});
	}

	document.addEventListener('DOMContentLoaded', function () {
		ipcRenderer.on('baseUrl', function (event, value) {
			initData.baseUrl = value;
		});

		ipcRenderer.on('styles', function (event, value, activeTheme) {
			initData.styles = value;
			initData.activeTheme = activeTheme;

			// webview
			var target = getActiveFrame();
			if (!target) {
				return;
			}
			var body = target.contentDocument.getElementsByTagName('body');
			styleBody(body[0]);

			// iframe
			var defaultStyles = target.contentDocument.getElementById('_defaultStyles');
			if (defaultStyles) {
				defaultStyles.innerHTML = initData.styles;
			}
		});

		// propagate focus
		ipcRenderer.on('focus', function () {
			const target = getActiveFrame();
			if (target) {
				target.contentWindow.focus();
			}
		});

		// update iframe-contents
		ipcRenderer.on('content', function (_event, data) {
			const options = data.options;
			const text = data.contents.join('\n');
			const newDocument = new DOMParser().parseFromString(text, 'text/html');

			// know what happens here
			const stats = {
				scriptTags: newDocument.documentElement.querySelectorAll('script').length,
				inputTags: newDocument.documentElement.querySelectorAll('input').length,
				styleTags: newDocument.documentElement.querySelectorAll('style').length,
				linkStyleSheetTags: newDocument.documentElement.querySelectorAll('link[rel=stylesheet]').length,
				stringLen: text.length
			};

			// set base-url if applicable
			if (initData.baseUrl && newDocument.head.getElementsByTagName('base').length === 0) {
				const baseElement = newDocument.createElement('base');
				baseElement.href = initData.baseUrl;
				newDocument.head.appendChild(baseElement);
			}

			// apply default styles
			const defaultStyles = newDocument.createElement('style');
			defaultStyles.id = '_defaultStyles';
			defaultStyles.innerHTML = initData.styles;
			if (newDocument.head.hasChildNodes()) {
				newDocument.head.insertBefore(defaultStyles, newDocument.head.firstChild);
			} else {
				newDocument.head.appendChild(defaultStyles);
			}

			styleBody(newDocument.body);

			const frame = getActiveFrame();

			// keep current scrollTop around and use later
			var setInitialScrollPosition;
			if (firstLoad) {
				firstLoad = false;
				setInitialScrollPosition = function (body, window) {
					body.scrollTop = 0;
					if (!isNaN(initData.initialScrollProgress)) {
						window.addEventListener('load', function () {
							if (body.scrollTop === 0) {
								body.scrollTop = body.clientHeight * initData.initialScrollProgress;
							}
						});
					}
				};
			} else {
				const scrollY = frame.contentDocument && frame.contentDocument.body ? frame.contentDocument.body.scrollTop : 0;
				setInitialScrollPosition = function (body) {
					if (body.scrollTop === 0) {
						body.scrollTop = scrollY;
					}
				};
			}

			// Clean up old pending frames and set current one as new one
			const previousPendingFrame = getPendingFrame();
			if (previousPendingFrame) {
				previousPendingFrame.setAttribute('id', '');
				document.body.removeChild(previousPendingFrame);
			}

			const newFrame = document.createElement('iframe');
			newFrame.setAttribute('id', 'pending-frame');
			newFrame.setAttribute('frameborder', '0');
			newFrame.setAttribute('sandbox', options.allowScripts ? 'allow-scripts allow-forms allow-same-origin' : 'allow-same-origin');
			newFrame.style.cssText = "display: block; margin: 0; overflow: hidden; position: absolute; width: 100%; height: 100%; visibility: hidden";
			document.body.appendChild(newFrame);

			// write new content onto iframe
			newFrame.contentDocument.open('text/html', 'replace');
			newFrame.contentWindow.onbeforeunload = function () {
				console.log('prevented webview navigation');
				return false;
			};

			var onLoad = function (contentDocument, contentWindow) {
				if (contentDocument.body) {
					// Workaround for https://github.com/Microsoft/vscode/issues/12865
					// check new scrollTop and reset if neccessary
					setInitialScrollPosition(contentDocument.body, contentWindow);

					// Bubble out link clicks
					contentDocument.body.addEventListener('click', handleInnerClick);
				}

				const newFrame = getPendingFrame();
				if (newFrame && newFrame.contentDocument === contentDocument) {
					const oldActiveFrame = getActiveFrame();
					if (oldActiveFrame) {
						document.body.removeChild(oldActiveFrame);
					}
					newFrame.setAttribute('id', 'active-frame');
					newFrame.style.visibility = 'visible';
					contentWindow.addEventListener('scroll', handleInnerScroll);
				}
			};

			clearTimeout(loadTimeout);
			loadTimeout = undefined;
			loadTimeout = setTimeout(function() {
				clearTimeout(loadTimeout);
				loadTimeout = undefined;
				onLoad(newFrame.contentDocument, newFrame.contentWindow);
			}, 200);

			newFrame.contentWindow.addEventListener('load', function(e) {
				if (loadTimeout) {
					clearTimeout(loadTimeout);
					loadTimeout = undefined;
					onLoad(e.target, this);
				}
			});

			// set DOCTYPE for newDocument explicitly as DOMParser.parseFromString strips it off
			// and DOCTYPE is needed in the iframe to ensure that the user agent stylesheet is correctly overridden
			newFrame.contentDocument.write('<!DOCTYPE html>');
			newFrame.contentDocument.write(newDocument.documentElement.innerHTML);
			newFrame.contentDocument.close();

			ipcRenderer.sendToHost('did-set-content', stats);
		});

		// Forward message to the embedded iframe
		ipcRenderer.on('message', function (event, data) {
			const target = getActiveFrame();
			if (target) {
				target.contentWindow.postMessage(data, document.location.origin);
			}
		});

		ipcRenderer.on('initial-scroll-position', function (event, progress) {
			initData.initialScrollProgress = progress;
		});

		// forward messages from the embedded iframe
		window.onmessage = function (message) {
			ipcRenderer.sendToHost(message.data.command, message.data.data);
		};

		// signal ready
		ipcRenderer.sendToHost('webview-ready', process.pid);
	});
}());<commit_msg>Fix possible race condition when posting messages to the webview<commit_after>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
// @ts-check
(function () {
	'use strict';

	const ipcRenderer = require('electron').ipcRenderer;

	// state
	var firstLoad = true;
	var loadTimeout;
	var pendingMessages = [];

	const initData = {
		initialScrollProgress: undefined
	};

	function styleBody(body) {
		if (!body) {
			return;
		}
		body.classList.remove('vscode-light', 'vscode-dark', 'vscode-high-contrast');
		body.classList.add(initData.activeTheme);
	}

	/**
	 * @return {HTMLIFrameElement}
	 */
	function getActiveFrame() {
		return document.getElementById('active-frame');
	}

	/**
	 * @return {HTMLIFrameElement}
	 */
	function getPendingFrame() {
		return document.getElementById('pending-frame');
	}

	/**
	 * @param {MouseEvent} event
	 */
	function handleInnerClick(event) {
		if (!event || !event.view || !event.view.document) {
			return;
		}
		/** @type {any} */
		var node = event.target;
		while (node) {
			if (node.tagName && node.tagName.toLowerCase() === 'a' && node.href) {
				var baseElement = event.view.document.getElementsByTagName("base")[0];
				if (node.getAttribute("href") === "#") {
					event.view.scrollTo(0, 0);
				} else if (node.hash && (node.getAttribute("href") === node.hash || (baseElement && node.href.indexOf(baseElement.href) >= 0))) {
					var scrollTarget = event.view.document.getElementById(node.hash.substr(1, node.hash.length - 1));
					if (scrollTarget) {
						scrollTarget.scrollIntoView();
					}
				} else {
					ipcRenderer.sendToHost("did-click-link", node.href);
				}
				event.preventDefault();
				break;
			}
			node = node.parentNode;
		}
	}

	var isHandlingScroll = false;
	function handleInnerScroll(event) {
		if (isHandlingScroll) {
			return;
		}

		const progress = event.target.body.scrollTop / event.target.body.clientHeight;
		if (isNaN(progress)) {
			return;
		}

		isHandlingScroll = true;
		window.requestAnimationFrame(function () {
			try {
				ipcRenderer.sendToHost('did-scroll', progress);
			} catch (e) {
				// noop
			}
			isHandlingScroll = false;
		});
	}

	document.addEventListener('DOMContentLoaded', function () {
		ipcRenderer.on('baseUrl', function (event, value) {
			initData.baseUrl = value;
		});

		ipcRenderer.on('styles', function (event, value, activeTheme) {
			initData.styles = value;
			initData.activeTheme = activeTheme;

			// webview
			var target = getActiveFrame();
			if (!target) {
				return;
			}
			var body = target.contentDocument.getElementsByTagName('body');
			styleBody(body[0]);

			// iframe
			var defaultStyles = target.contentDocument.getElementById('_defaultStyles');
			if (defaultStyles) {
				defaultStyles.innerHTML = initData.styles;
			}
		});

		// propagate focus
		ipcRenderer.on('focus', function () {
			const target = getActiveFrame();
			if (target) {
				target.contentWindow.focus();
			}
		});

		// update iframe-contents
		ipcRenderer.on('content', function (_event, data) {
			const options = data.options;
			const text = data.contents.join('\n');
			const newDocument = new DOMParser().parseFromString(text, 'text/html');

			// know what happens here
			const stats = {
				scriptTags: newDocument.documentElement.querySelectorAll('script').length,
				inputTags: newDocument.documentElement.querySelectorAll('input').length,
				styleTags: newDocument.documentElement.querySelectorAll('style').length,
				linkStyleSheetTags: newDocument.documentElement.querySelectorAll('link[rel=stylesheet]').length,
				stringLen: text.length
			};

			// set base-url if applicable
			if (initData.baseUrl && newDocument.head.getElementsByTagName('base').length === 0) {
				const baseElement = newDocument.createElement('base');
				baseElement.href = initData.baseUrl;
				newDocument.head.appendChild(baseElement);
			}

			// apply default styles
			const defaultStyles = newDocument.createElement('style');
			defaultStyles.id = '_defaultStyles';
			defaultStyles.innerHTML = initData.styles;
			if (newDocument.head.hasChildNodes()) {
				newDocument.head.insertBefore(defaultStyles, newDocument.head.firstChild);
			} else {
				newDocument.head.appendChild(defaultStyles);
			}

			styleBody(newDocument.body);

			const frame = getActiveFrame();

			// keep current scrollTop around and use later
			var setInitialScrollPosition;
			if (firstLoad) {
				firstLoad = false;
				setInitialScrollPosition = function (body, window) {
					body.scrollTop = 0;
					if (!isNaN(initData.initialScrollProgress)) {
						window.addEventListener('load', function () {
							if (body.scrollTop === 0) {
								body.scrollTop = body.clientHeight * initData.initialScrollProgress;
							}
						});
					}
				};
			} else {
				const scrollY = frame.contentDocument && frame.contentDocument.body ? frame.contentDocument.body.scrollTop : 0;
				setInitialScrollPosition = function (body) {
					if (body.scrollTop === 0) {
						body.scrollTop = scrollY;
					}
				};
			}

			// Clean up old pending frames and set current one as new one
			const previousPendingFrame = getPendingFrame();
			if (previousPendingFrame) {
				previousPendingFrame.setAttribute('id', '');
				document.body.removeChild(previousPendingFrame);
			}
			pendingMessages = [];

			const newFrame = document.createElement('iframe');
			newFrame.setAttribute('id', 'pending-frame');
			newFrame.setAttribute('frameborder', '0');
			newFrame.setAttribute('sandbox', options.allowScripts ? 'allow-scripts allow-forms allow-same-origin' : 'allow-same-origin');
			newFrame.style.cssText = "display: block; margin: 0; overflow: hidden; position: absolute; width: 100%; height: 100%; visibility: hidden";
			document.body.appendChild(newFrame);

			// write new content onto iframe
			newFrame.contentDocument.open('text/html', 'replace');
			newFrame.contentWindow.onbeforeunload = function () {
				console.log('prevented webview navigation');
				return false;
			};

			var onLoad = function (contentDocument, contentWindow) {
				if (contentDocument.body) {
					// Workaround for https://github.com/Microsoft/vscode/issues/12865
					// check new scrollTop and reset if neccessary
					setInitialScrollPosition(contentDocument.body, contentWindow);

					// Bubble out link clicks
					contentDocument.body.addEventListener('click', handleInnerClick);
				}

				const newFrame = getPendingFrame();
				if (newFrame && newFrame.contentDocument === contentDocument) {
					const oldActiveFrame = getActiveFrame();
					if (oldActiveFrame) {
						document.body.removeChild(oldActiveFrame);
					}
					newFrame.setAttribute('id', 'active-frame');
					newFrame.style.visibility = 'visible';
					contentWindow.addEventListener('scroll', handleInnerScroll);

					pendingMessages.forEach(function(data) {
						contentWindow.postMessage(data, document.location.origin);
					});
					pendingMessages = [];
				}
			};

			clearTimeout(loadTimeout);
			loadTimeout = undefined;
			loadTimeout = setTimeout(function () {
				clearTimeout(loadTimeout);
				loadTimeout = undefined;
				onLoad(newFrame.contentDocument, newFrame.contentWindow);
			}, 200);

			newFrame.contentWindow.addEventListener('load', function (e) {
				if (loadTimeout) {
					clearTimeout(loadTimeout);
					loadTimeout = undefined;
					onLoad(e.target, this);
				}
			});

			// set DOCTYPE for newDocument explicitly as DOMParser.parseFromString strips it off
			// and DOCTYPE is needed in the iframe to ensure that the user agent stylesheet is correctly overridden
			newFrame.contentDocument.write('<!DOCTYPE html>');
			newFrame.contentDocument.write(newDocument.documentElement.innerHTML);
			newFrame.contentDocument.close();

			ipcRenderer.sendToHost('did-set-content', stats);
		});

		// Forward message to the embedded iframe
		ipcRenderer.on('message', function (event, data) {
			const pending = getPendingFrame();
			if (pending) {
				pendingMessages.push(data);
			} else {
				const target = getActiveFrame();
				if (target) {
					target.contentWindow.postMessage(data, document.location.origin);
				}
			}
		});

		ipcRenderer.on('initial-scroll-position', function (event, progress) {
			initData.initialScrollProgress = progress;
		});

		// forward messages from the embedded iframe
		window.onmessage = function (message) {
			ipcRenderer.sendToHost(message.data.command, message.data.data);
		};

		// signal ready
		ipcRenderer.sendToHost('webview-ready', process.pid);
	});
}());<|endoftext|>


<commit_before>/*global PROCED:false, async:false*/
pc.script.create('workQueue', function (app) { //context / app can be taken as argument
	//var maxFrameComputingTime = 10;
	//var size = 5;
	var size = 7;
	var zoneCount = Math.ceil(size / 2);
	//var size = 7;

	var workerCount = 1;

	var wrappingArray = PROCED.wrappingArray(size);
	var chunkArray = [];
	var camera;
	var objCreator;
	var oldPosX, oldPosY, oldPosZ;
	var first = true;

	var queue;

	var WorkQueue = function (entity) {
		this.entity = entity;
	};
	var that;
	WorkQueue.prototype = {
		initialize: function() {
			that = this;
			objCreator = this.entity.script.objcreator;
			camera = app.root.findByName('Camera');

			var t0 = performance.now();
			this.loadWorld();
			this.startWorld();
			var t1 = performance.now();
			console.log('initialized in %d milliseconds', t1 - t0);

		},
		loadWorld: function() {
			this.sampler = 'perlin';

			this.middlePosition = [
				size / 2 * objCreator.chunkSizeX * objCreator.scaleFactor,
				size / 2 * objCreator.chunkSizeY * objCreator.scaleFactor,
				size / 2 * objCreator.chunkSizeZ * objCreator.scaleFactor
			];

			var that = this;
			for(var x = 0; x < size; x++) {
				for(var y = 0; y < size; y++) {
					for(var z = 0; z < size; z++) {
						/*
						var closure = function(x,y,z) {
							return function() {
							*/
								chunkArray[getIdx(x,y,z)] = objCreator.addNewEntity([x,y,z], true, that.sampler);
								/*
							};
						};
						closure(x,y,z)();
						*/
						//requestAnimationFrame(closure(x,y,z), 0);
					}
				}
			}
		},
		middlePosition: null,
		sampler: 'sin',
		updateEnabled: false,
		startWorld: function() {
			camera.script.first_person_camera.setPosition(this.middlePosition);
			camera.script.first_person_camera.mouseLook = true;
			camera.script.first_person_camera.moveForwardLock = false;

			this.initializeZones();
			this.initializeQueue();
		},
		vecEqual: function(fst, snd) {
			return fst.x === snd.x && fst.y === snd.y && fst.z === snd.z;
		},
		getAvg: function(list) {
			var sum = 0;
			var i;
			for(i = 0; i < list.length; i++) {
				sum += list[i];
			}
			return sum / i;
		},
		update: function() {
			var cameraPos = camera.getPosition();
			var xChunkPos = Math.floor(cameraPos.x / objCreator.chunkSizeX / objCreator.scaleFactor);
			var yChunkPos = Math.floor(cameraPos.y / objCreator.chunkSizeY / objCreator.scaleFactor);
			var zChunkPos = Math.floor(cameraPos.z / objCreator.chunkSizeZ / objCreator.scaleFactor);
			if(first) {
				oldPosX = xChunkPos;
				oldPosY = yChunkPos;
				oldPosZ = zChunkPos;
				first = false;
				return;
			}

			if(xChunkPos > oldPosX) {
				oldPosX = xChunkPos;
				console.log('x plus');
				wrappingArray.dirXPlus();
			}
			else if(xChunkPos < oldPosX) {
				oldPosX = xChunkPos;
				console.log('x minus');
				wrappingArray.dirXMinus();
			}

			if(yChunkPos > oldPosY) {
				oldPosY = yChunkPos;
				console.log('y plus');
				wrappingArray.dirYPlus();
			}
			else if(yChunkPos < oldPosY) {
				console.log(yChunkPos + ' ' + oldPosY);
				oldPosY = yChunkPos;
				console.log('y minus');
				wrappingArray.dirYMinus();
			}

			if(zChunkPos > oldPosZ) {
				oldPosZ = zChunkPos;
				console.log('z plus');
				wrappingArray.dirZPlus();
			}
			else if(zChunkPos < oldPosZ) {
				oldPosZ = zChunkPos;
				console.log('z minus');
				wrappingArray.dirZMinus();
			}
		},
		initializeZones: function() {
			wrappingArray.setZoneFunction(zoneCount - 2, function (arrayCell, worldCoords) {
				queue.push({
					type: 'draw',
					arrayCell: arrayCell,
					worldCoords: worldCoords
				}, 1);
			}, function() {});

			wrappingArray.setZoneFunction(zoneCount - 1, function() {}, function (arrayCell, worldCoords) {
				var wrappedIdx = getIdx(arrayCell[0], arrayCell[1], arrayCell[2]);
				var entity = chunkArray[wrappedIdx];
				//if(chunkArray[wrappedIdx] && chunkArray[wrappedIdx].script && chunkArray[wrappedIdx].script.procedural && that.vecEqual(chunkArray[wrappedIdx].script.procedural.chunkPos, worldCoords)) {
					/*
					console.log('---------------------');
					console.log('destroying:');
					console.log('arrayCell', arrayCell);
					console.log('worldCoords', worldCoords);
					console.log('---------------------');
					*/
					queue.push({
						type: 'destroy',
						entity: entity
					}, 2);
				//}
			});
		},
		initializeQueue: function() {
			queue = async.priorityQueue(function(task, callback) {
				switch(task.type) {
				case 'draw':
					requestAnimationFrame(function() {
						that.handleDraw(task, callback);
					}, 0);
					break;
				case 'load':
					requestAnimationFrame(function() {
						that.handleLoad(task, callback);
					}, 0);
					break;
				case 'destroy':
					requestAnimationFrame(function() {
						that.handleDestroy(task, callback);
					}, 0);

				}
			}, workerCount);
		},
		handleDestroy: function(obj, callback) {
			if(!obj.entity) {
				return callback();
			}
			obj.entity.destroy();
			callback();
		},
		handleDraw: function(obj, callback) {
			//console.log('handle draw');
			var wrappedIdx = getIdx(obj.arrayCell[0], obj.arrayCell[1], obj.arrayCell[2]);
			if(chunkArray[wrappedIdx] && chunkArray[wrappedIdx].script && chunkArray[wrappedIdx].script.procedural && that.vecEqual(chunkArray[wrappedIdx].script.procedural.chunkPos, obj.worldCoords)) {
				//console.log('already loaded');
				if(chunkArray[wrappedIdx].script.procedural.state === 'loaded') {
					chunkArray[wrappedIdx].script.procedural.addComponents();
				}
				else {
					//If f.ex drawn, this will do nothing
					//If in the process of loading, it will continue to draw it afterwards
					//a bit non-robust
					chunkArray[wrappedIdx].script.procedural.visible = true;
				}
			}
			else {
				//console.log('draw new');
				chunkArray[wrappedIdx] = that.entity.script.objcreator.addNewEntity([obj.worldCoords.x, obj.worldCoords.y, obj.worldCoords.z], true, this.sampler);
			}

			callback();
		},
		handleLoad: function(obj, callback) {
			//console.log('handle load');
			var wrappedIdx = getIdx(obj.arrayCell[0], obj.arrayCell[1], obj.arrayCell[2]);
			if(chunkArray[wrappedIdx] && chunkArray[wrappedIdx].script  && chunkArray[wrappedIdx].script.procedural && that.vecEqual(chunkArray[wrappedIdx].script.procedural.chunkPos, obj.worldCoords)) {
				//Nothing to do, already loaded / loading
				return callback();
			}
			else {
				requestAnimationFrame(function() {
					chunkArray[wrappedIdx] = that.entity.script.objcreator.addNewEntity([obj.worldCoords.x, obj.worldCoords.y, obj.worldCoords.z], false, this.sampler);
					callback();
				});
			}
		}
	};

	function getIdx(x, y, z) {
		return x + size * (y + size * z);
	}

	return WorkQueue;
});
<commit_msg>Delete on overwrite<commit_after>/*global PROCED:false, async:false*/
pc.script.create('workQueue', function (app) { //context / app can be taken as argument
	//var maxFrameComputingTime = 10;
	//var size = 5;
	var size = 7;
	var zoneCount = Math.ceil(size / 2);
	//var size = 7;

	var workerCount = 1;

	var wrappingArray = PROCED.wrappingArray(size);
	var chunkArray = [];
	var camera;
	var objCreator;
	var oldPosX, oldPosY, oldPosZ;
	var first = true;

	var queue;

	var WorkQueue = function (entity) {
		this.entity = entity;
	};
	var that;
	WorkQueue.prototype = {
		initialize: function() {
			that = this;
			objCreator = this.entity.script.objcreator;
			camera = app.root.findByName('Camera');

			var t0 = performance.now();
			this.loadWorld();
			this.startWorld();
			var t1 = performance.now();
			console.log('initialized in %d milliseconds', t1 - t0);

		},
		loadWorld: function() {
			this.sampler = 'perlin';

			this.middlePosition = [
				size / 2 * objCreator.chunkSizeX * objCreator.scaleFactor,
				size / 2 * objCreator.chunkSizeY * objCreator.scaleFactor,
				size / 2 * objCreator.chunkSizeZ * objCreator.scaleFactor
			];

			var that = this;
			for(var x = 0; x < size; x++) {
				for(var y = 0; y < size; y++) {
					for(var z = 0; z < size; z++) {
						/*
						var closure = function(x,y,z) {
							return function() {
							*/
								chunkArray[getIdx(x,y,z)] = objCreator.addNewEntity([x,y,z], true, that.sampler);
								/*
							};
						};
						closure(x,y,z)();
						*/
						//requestAnimationFrame(closure(x,y,z), 0);
					}
				}
			}
		},
		middlePosition: null,
		sampler: 'sin',
		updateEnabled: false,
		startWorld: function() {
			camera.script.first_person_camera.setPosition(this.middlePosition);
			camera.script.first_person_camera.mouseLook = true;
			camera.script.first_person_camera.moveForwardLock = false;

			this.initializeZones();
			this.initializeQueue();
		},
		vecEqual: function(fst, snd) {
			return fst.x === snd.x && fst.y === snd.y && fst.z === snd.z;
		},
		getAvg: function(list) {
			var sum = 0;
			var i;
			for(i = 0; i < list.length; i++) {
				sum += list[i];
			}
			return sum / i;
		},
		update: function() {
			var cameraPos = camera.getPosition();
			var xChunkPos = Math.floor(cameraPos.x / objCreator.chunkSizeX / objCreator.scaleFactor);
			var yChunkPos = Math.floor(cameraPos.y / objCreator.chunkSizeY / objCreator.scaleFactor);
			var zChunkPos = Math.floor(cameraPos.z / objCreator.chunkSizeZ / objCreator.scaleFactor);
			if(first) {
				oldPosX = xChunkPos;
				oldPosY = yChunkPos;
				oldPosZ = zChunkPos;
				first = false;
				return;
			}

			if(xChunkPos > oldPosX) {
				oldPosX = xChunkPos;
				console.log('x plus');
				wrappingArray.dirXPlus();
			}
			else if(xChunkPos < oldPosX) {
				oldPosX = xChunkPos;
				console.log('x minus');
				wrappingArray.dirXMinus();
			}

			if(yChunkPos > oldPosY) {
				oldPosY = yChunkPos;
				console.log('y plus');
				wrappingArray.dirYPlus();
			}
			else if(yChunkPos < oldPosY) {
				console.log(yChunkPos + ' ' + oldPosY);
				oldPosY = yChunkPos;
				console.log('y minus');
				wrappingArray.dirYMinus();
			}

			if(zChunkPos > oldPosZ) {
				oldPosZ = zChunkPos;
				console.log('z plus');
				wrappingArray.dirZPlus();
			}
			else if(zChunkPos < oldPosZ) {
				oldPosZ = zChunkPos;
				console.log('z minus');
				wrappingArray.dirZMinus();
			}
		},
		initializeZones: function() {
			wrappingArray.setZoneFunction(zoneCount - 2, function (arrayCell, worldCoords) {
				queue.push({
					type: 'draw',
					arrayCell: arrayCell,
					worldCoords: worldCoords
				}, 1);
			}, function() {});
		},
		initializeQueue: function() {
			queue = async.priorityQueue(function(task, callback) {
				switch(task.type) {
				case 'draw':
					requestAnimationFrame(function() {
						that.handleDraw(task, callback);
					}, 0);
					break;
				case 'load':
					requestAnimationFrame(function() {
						that.handleLoad(task, callback);
					}, 0);
					break;
				case 'destroy':
					requestAnimationFrame(function() {
						that.handleDestroy(task, callback);
					}, 0);

				}
			}, workerCount);
		},
		handleDestroy: function(obj, callback) {
			if(!obj.entity) {
				return callback();
			}
			obj.entity.destroy();
			callback();
		},
		handleDraw: function(obj, callback) {
			//console.log('handle draw');
			var wrappedIdx = getIdx(obj.arrayCell[0], obj.arrayCell[1], obj.arrayCell[2]);
			if(chunkArray[wrappedIdx] && chunkArray[wrappedIdx].script && chunkArray[wrappedIdx].script.procedural && that.vecEqual(chunkArray[wrappedIdx].script.procedural.chunkPos, obj.worldCoords)) {
				//console.log('already loaded');
				if(chunkArray[wrappedIdx].script.procedural.state === 'loaded') {
					chunkArray[wrappedIdx].script.procedural.addComponents();
				}
				else {
					//If f.ex drawn, this will do nothing
					//If in the process of loading, it will continue to draw it afterwards
					//a bit non-robust
					chunkArray[wrappedIdx].script.procedural.visible = true;
				}
			}
			else {
				//console.log('draw new');
				var entity = chunkArray[wrappedIdx];
				if(entity) {
					queue.push({
						type: 'destroy',
						entity: entity
					}, 2);
				}
				chunkArray[wrappedIdx] = that.entity.script.objcreator.addNewEntity([obj.worldCoords.x, obj.worldCoords.y, obj.worldCoords.z], true, this.sampler);
			}

			callback();
		},
		handleLoad: function(obj, callback) {
			//console.log('handle load');
			var wrappedIdx = getIdx(obj.arrayCell[0], obj.arrayCell[1], obj.arrayCell[2]);
			if(chunkArray[wrappedIdx] && chunkArray[wrappedIdx].script  && chunkArray[wrappedIdx].script.procedural && that.vecEqual(chunkArray[wrappedIdx].script.procedural.chunkPos, obj.worldCoords)) {
				//Nothing to do, already loaded / loading
				return callback();
			}
			else {
				requestAnimationFrame(function() {
					chunkArray[wrappedIdx] = that.entity.script.objcreator.addNewEntity([obj.worldCoords.x, obj.worldCoords.y, obj.worldCoords.z], false, this.sampler);
					callback();
				});
			}
		}
	};

	function getIdx(x, y, z) {
		return x + size * (y + size * z);
	}

	return WorkQueue;
});
<|endoftext|>


<commit_before>const { chain, some } = require("lodash");

const checkSubjectWith = ({ subject = {} }) => {
  const {
    mustHaveLengthBetween,
    mustMatch,
    mustNotMatch
  } = subject;
  const [ minSubjectLen, maxSubjectLen ] = mustHaveLengthBetween || [];

  return ({ commit: { message }, sha }) => {
    const shortSha = sha.slice(0, 7);
    const commitSubject = message.split("\n")[0];

    if (mustHaveLengthBetween) {
      if (commitSubject.length > maxSubjectLen) { return `Subject for ${shortSha} is too long.`; }
      if (commitSubject.length < minSubjectLen) {
        return `Subject for ${shortSha} is too short.`;
      }
    }
    if (
      mustMatch && !mustMatch.test(commitSubject) ||
      mustNotMatch && mustNotMatch.test(commitSubject)
    ) {
      return `Subject for ${shortSha} does not meet content requirements.`
    }
  };
};

const checkSubjects = (commitConfig, commitEntries) => chain(commitEntries)
  .map(checkSubjectWith(commitConfig))
  .find()
  .value();

const checkMessageWith = ({ subject = {}, message = {} }) => {
  const {
    maxLines,
    minLines,
    enforceEmptySecondLine,
    linesMustHaveLengthBetween
  } = message;

  return ({ commit: { message }, sha }) => {
    const shortSha = sha.slice(0, 7);

    const commitLines = message.split("\n");

    if (maxLines && commitLines.length > maxLines) {
      return `Commit message for ${shortSha} is too long.`
    }
    if (minLines && commitLines.length < minLines) {
      return `Commit message for ${shortSha} is too short.`
    }
    if (enforceEmptySecondLine && commitLines.length > 1 && commitLines[1].trim !== "") {
      return `Commit message for ${shortSha} must have empty second line.`;
    }
    if (linesMustHaveLengthBetween) {
      const [ minLineLen, maxLineLen ] = linesMustHaveLengthBetween;
      const hasExtraLongLine = some(lines.slice(1), line => line.length > maxLineLen);
      const hasTooShortLine = some(lines.slice(2), line => line.length < minLineLen);

      if (hasExtraLongLine) {
        return `Commit message lines much be shorter than ${maxLineLen} for ${shortSha}.`;
      }
      if (hasTooShortLine) {
        return `Commit message lines much be longer than ${minLineLen} for ${shortSha}.`;
      }
    }
  };
};

const checkMessages = (commitConfig, commitEntries) => chain(commitEntries)
  .map(checkMessageWith(commitConfig))
  .find()
  .value();

module.exports = async (pullRequestData, config, gh) => {
  if (!config.commit) { return; }

  const { repoPath, pullRequestNumber, sha } = pullRequestData;
  const commitEntries = await gh.getPullRequestCommits(repoPath, pullRequestNumber);

  const subjectFailureMessage = checkSubjects(config.commit, commitEntries);
  await gh.updateCommit(repoPath, sha, "subject", subjectFailureMessage);

  const messageFailureMessage = checkMessages(config.commit, commitEntries);
  await gh.updateCommit(repoPath, sha, "msg", messageFailureMessage);
};
<commit_msg>Fix typo.<commit_after>const { chain, some } = require("lodash");

const checkSubjectWith = ({ subject = {} }) => {
  const {
    mustHaveLengthBetween,
    mustMatch,
    mustNotMatch
  } = subject;
  const [ minSubjectLen, maxSubjectLen ] = mustHaveLengthBetween || [];

  return ({ commit: { message }, sha }) => {
    const shortSha = sha.slice(0, 7);
    const commitSubject = message.split("\n")[0];

    if (mustHaveLengthBetween) {
      if (commitSubject.length > maxSubjectLen) { return `Subject for ${shortSha} is too long.`; }
      if (commitSubject.length < minSubjectLen) {
        return `Subject for ${shortSha} is too short.`;
      }
    }
    if (
      mustMatch && !mustMatch.test(commitSubject) ||
      mustNotMatch && mustNotMatch.test(commitSubject)
    ) {
      return `Subject for ${shortSha} does not meet content requirements.`
    }
  };
};

const checkSubjects = (commitConfig, commitEntries) => chain(commitEntries)
  .map(checkSubjectWith(commitConfig))
  .find()
  .value();

const checkMessageWith = ({ subject = {}, message = {} }) => {
  const {
    maxLines,
    minLines,
    enforceEmptySecondLine,
    linesMustHaveLengthBetween
  } = message;

  return ({ commit: { message }, sha }) => {
    const shortSha = sha.slice(0, 7);

    const commitLines = message.split("\n");

    if (maxLines && commitLines.length > maxLines) {
      return `Commit message for ${shortSha} is too long.`
    }
    if (minLines && commitLines.length < minLines) {
      return `Commit message for ${shortSha} is too short.`
    }
    if (enforceEmptySecondLine && commitLines.length > 1 && commitLines[1].trim !== "") {
      return `Commit message for ${shortSha} must have empty second line.`;
    }
    if (linesMustHaveLengthBetween) {
      const [ minLineLen, maxLineLen ] = linesMustHaveLengthBetween;
      const hasExtraLongLine = some(commitLines.slice(1), line => line.length > maxLineLen);
      const hasTooShortLine = some(commitLines.slice(2), line => line.length < minLineLen);

      if (hasExtraLongLine) {
        return `Commit message lines much be shorter than ${maxLineLen} for ${shortSha}.`;
      }
      if (hasTooShortLine) {
        return `Commit message lines much be longer than ${minLineLen} for ${shortSha}.`;
      }
    }
  };
};

const checkMessages = (commitConfig, commitEntries) => chain(commitEntries)
  .map(checkMessageWith(commitConfig))
  .find()
  .value();

module.exports = async (pullRequestData, config, gh) => {
  if (!config.commit) { return; }

  const { repoPath, pullRequestNumber, sha } = pullRequestData;
  const commitEntries = await gh.getPullRequestCommits(repoPath, pullRequestNumber);

  const subjectFailureMessage = checkSubjects(config.commit, commitEntries);
  await gh.updateCommit(repoPath, sha, "subject", subjectFailureMessage);

  const messageFailureMessage = checkMessages(config.commit, commitEntries);
  await gh.updateCommit(repoPath, sha, "msg", messageFailureMessage);
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Form } from 'formsy-react';
import { Container, Button, Label, Segment } from 'semantic-ui-react';
import { Dropdown } from '../src';

const styles = {
  root: {
    marginTop: 18,
  },
};

const options = [
  { text: 'Hat', value: 'hat' },
  { text: 'Scarf', value: 'scarf' },
  { text: 'Jacket', value: 'jacket' },
  { text: 'T-Shirt', value: 't_shirt' },
  { text: 'Gloves', value: 'gloves' },
  { text: 'Watch', value: 'watch' },
  { text: 'Belt', value: 'belt' },
  { text: 'Pants', value: 'pants' },
  { text: 'Shoes', value: 'shoes' },
  { text: 'Socks', value: 'socks' },
];

export default class CheckboxExamples extends Component {
  onValidSubmit = (formData) => alert(JSON.stringify(formData)) // eslint-disable-line

  render() {
    const errorLabel = ;

    const dropdownSingle = (
      <Dropdown
        name="dropdownSingle"
        placeholder="Select Product"
        search
        selection
        required
        validationErrors={{
          isDefaultRequiredValue: 'You need to select a product',
        }}
        errorLabel="div"
        options={ options }
      />
    );

    const singleSelectWithDefaultValue = (
      <Dropdown
        name="singleSelectWithDefaultValue"
        placeholder="Select Product"
        search
        selection
        defaultValue="gloves"
        required
        validationErrors={{
          isDefaultRequiredValue: 'You need to select a product',
        }}
        errorLabel={ errorLabel }
        options={ options }
      />
    );

    const dropdownMultiple = (
      <Dropdown
        name="dropdownMultiple"
        placeholder="Select Product"
        multiple
        search
        selection
        validations={{
          customValidation: (values, value) => !(!value || value.length < 4),
        }}
        validationErrors={{
          customValidation: 'You need to select at least FOUR products',
        }}
        errorLabel={ errorLabel }
        options={ options }
      />
    );

    const multipleWithDefaultValues = (
      <Dropdown
        name="multipleWithDefaultValues"
        placeholder="Select Product"
        multiple
        search
        selection
        defaultValue={['scarf', 'jacket']}
        validations={{
          customValidation: (values, value) => !(!value || value.length < 2),
        }}
        validationErrors={{
          customValidation: 'You need to select at least TWO products',
        }}
        errorLabel={ errorLabel }
        options={ options }
      />
    );

    return (
      <Container style={ styles.root }>
        <Form
          noValidate
          onValidSubmit={ this.onValidSubmit }
          ref={ref => this.form = ref }
        >
          <Segment>

 Single-select

            { dropdownSingle }
          </Segment>

          <Segment>

 Single-select with default value

            { singleSelectWithDefaultValue }
          </Segment>

          <Segment>

 Multi-select (Four selections minimum)

            { dropdownMultiple }
          </Segment>

          <Segment>

 Multi-select with default values (Two selections minimum)

            { multipleWithDefaultValues }
          </Segment>

          <Button
            content="Submit"
            style={ styles.formElement }
            color="orange"
          />
          <Button
            type="button"
            onClick={ () => this.form.reset({
              singleSelectWithDefaultValue: 'gloves',
              multipleWithDefaultValues: ['scarf', 'jacket'],
            })}
            content="Reset"
            color="black"
          />
        </Form>
      </Container>
    );
  }
}
<commit_msg>Change errorLabel form stirng to element<commit_after>import React, { Component } from 'react';
import { Form } from 'formsy-react';
import { Container, Button, Label, Segment } from 'semantic-ui-react';
import { Dropdown } from '../src';

const styles = {
  root: {
    marginTop: 18,
  },
};

const options = [
  { text: 'Hat', value: 'hat' },
  { text: 'Scarf', value: 'scarf' },
  { text: 'Jacket', value: 'jacket' },
  { text: 'T-Shirt', value: 't_shirt' },
  { text: 'Gloves', value: 'gloves' },
  { text: 'Watch', value: 'watch' },
  { text: 'Belt', value: 'belt' },
  { text: 'Pants', value: 'pants' },
  { text: 'Shoes', value: 'shoes' },
  { text: 'Socks', value: 'socks' },
];

export default class CheckboxExamples extends Component {
  onValidSubmit = (formData) => alert(JSON.stringify(formData)) // eslint-disable-line

  render() {
    const errorLabel = ;

    const dropdownSingle = (
      <Dropdown
        name="dropdownSingle"
        placeholder="Select Product"
        search
        selection
        required
        validationErrors={{
          isDefaultRequiredValue: 'You need to select a product',
        }}
        errorLabel={ errorLabel }
        options={ options }
      />
    );

    const singleSelectWithDefaultValue = (
      <Dropdown
        name="singleSelectWithDefaultValue"
        placeholder="Select Product"
        search
        selection
        defaultValue="gloves"
        required
        validationErrors={{
          isDefaultRequiredValue: 'You need to select a product',
        }}
        errorLabel={ errorLabel }
        options={ options }
      />
    );

    const dropdownMultiple = (
      <Dropdown
        name="dropdownMultiple"
        placeholder="Select Product"
        multiple
        search
        selection
        validations={{
          customValidation: (values, value) => !(!value || value.length < 4),
        }}
        validationErrors={{
          customValidation: 'You need to select at least FOUR products',
        }}
        errorLabel={ errorLabel }
        options={ options }
      />
    );

    const multipleWithDefaultValues = (
      <Dropdown
        name="multipleWithDefaultValues"
        placeholder="Select Product"
        multiple
        search
        selection
        defaultValue={['scarf', 'jacket']}
        validations={{
          customValidation: (values, value) => !(!value || value.length < 2),
        }}
        validationErrors={{
          customValidation: 'You need to select at least TWO products',
        }}
        errorLabel={ errorLabel }
        options={ options }
      />
    );

    return (
      <Container style={ styles.root }>
        <Form
          noValidate
          onValidSubmit={ this.onValidSubmit }
          ref={ref => this.form = ref }
        >
          <Segment>

 Single-select

            { dropdownSingle }
          </Segment>

          <Segment>

 Single-select with default value

            { singleSelectWithDefaultValue }
          </Segment>

          <Segment>

 Multi-select (Four selections minimum)

            { dropdownMultiple }
          </Segment>

          <Segment>

 Multi-select with default values (Two selections minimum)

            { multipleWithDefaultValues }
          </Segment>

          <Button
            content="Submit"
            style={ styles.formElement }
            color="orange"
          />
          <Button
            type="button"
            onClick={ () => this.form.reset({
              singleSelectWithDefaultValue: 'gloves',
              multipleWithDefaultValues: ['scarf', 'jacket'],
            })}
            content="Reset"
            color="black"
          />
        </Form>
      </Container>
    );
  }
}
<|endoftext|>


<commit_before>module.exports = dragDropAsBuffer

var dragDrop = require('./')
var parallel = require('run-parallel')
var blobToBuffer = require('blob-to-buffer')

function dragDropAsBuffer (elem, cb) {
  return dragDrop(elem, function (files, pos) {
    var tasks = files.map(function (file) {
      return function (cb) {
        blobToBuffer(file, function (err, buffer) {
          if (err) return cb(err)
          buffer.name = file.name
          buffer.size = file.size
          buffer.type = file.type
          buffer.lastModifiedDate = file.lastModifiedDate
          cb(null, buffer)
        })
      }
    })
    parallel(tasks, function (err, results) {
      if (err) throw err
      cb(results, pos)
    })
  })
}
<commit_msg>buffer version: add missing `fullPath` property<commit_after>module.exports = dragDropAsBuffer

var dragDrop = require('./')
var parallel = require('run-parallel')
var blobToBuffer = require('blob-to-buffer')

function dragDropAsBuffer (elem, cb) {
  return dragDrop(elem, function (files, pos) {
    var tasks = files.map(function (file) {
      return function (cb) {
        blobToBuffer(file, function (err, buffer) {
          if (err) return cb(err)
          buffer.name = file.name
          buffer.fullPath = file.fullPath
          buffer.size = file.size
          buffer.type = file.type
          buffer.lastModifiedDate = file.lastModifiedDate
          cb(null, buffer)
        })
      }
    })
    parallel(tasks, function (err, results) {
      if (err) throw err
      cb(results, pos)
    })
  })
}
<|endoftext|>


<commit_before>const assert = require('chai').assert;
const EventEmitter = require('../event-emitter');

describe('event emitter class', () => {

    // create a global event emitter to use between tests
    let ee = new EventEmitter();

    // define a callback to register with events
    let callback = function() {};

    it('creates an empty state object', () => {
        assert.deepEqual(ee.events, {});
    });

    it('adds a new event type to the hash, registers handler fn', () => {
        ee.addListener('TEST', callback);
        assert.isOk(ee.events['TEST'])
        assert.deepEqual(ee.events['TEST'], [callback]);
    });

    it('returns false if you try to register a non-function', () => {
        let response = ee.addListener('FAIL', 'string');
        assert.isOk(ee.events['FAIL'])
        assert.isFalse(response);
    });

    it('returns the function to unsubscribe', () => {
        let othercb = function() {};
        // make sure there's only one cb in the TEST event array
        assert.equal(ee.events['TEST'].length, 1);
        // add a new listener and capture it's unsubscribe function
        const removeMe = ee.addListener('TEST', othercb);
        // make sure the cb is in the array
        assert.equal(ee.events['TEST'].length, 2);
        removeMe();
        // make sure this cb isn't in there anymore
        assert.equal(ee.events['TEST'].length, 1);
        assert.notInclude(ee.events['TEST'], othercb);
    });

    it('removes all listeners for a given event type', () => {
        ee.addListener('REMOVEME', callback);
        ee.addListener('REMOVEME', callback);
        ee.addListener('REMOVEME', callback);
        assert.equal(ee.events['REMOVEME'].length, 3);
        let returnedEE = ee.removeAllListeners('REMOVEME');
        assert.equal(ee.events['REMOVEME'].length, 0);
        // removeAll returns a ref to the EE class itself
        assert.deepEqual(EventEmitter, returnedEE);
    });

});<commit_msg>Adds a failing test for removeListener, writing method now.<commit_after>const assert = require('chai').assert;
const EventEmitter = require('../event-emitter');

describe('event emitter class', () => {

    // create a global event emitter to use between tests
    let ee = new EventEmitter();

    // define a callback to register with events
    let callback = function() {};

    it('creates an empty state object', () => {
        assert.deepEqual(ee.events, {});
    });

    it('adds a new event type to the hash, registers handler fn', () => {
        ee.addListener('TEST', callback);
        assert.isOk(ee.events['TEST'])
        assert.deepEqual(ee.events['TEST'], [callback]);
    });

    it('returns false if you try to register a non-function', () => {
        let response = ee.addListener('FAIL', 'string');
        assert.isOk(ee.events['FAIL'])
        assert.isFalse(response);
    });

    it('returns the function to unsubscribe', () => {
        let othercb = function() {};
        // make sure there's only one cb in the TEST event array
        assert.equal(ee.events['TEST'].length, 1);
        // add a new listener and capture it's unsubscribe function
        const removeMe = ee.addListener('TEST', othercb);
        // make sure the cb is in the array
        assert.equal(ee.events['TEST'].length, 2);
        removeMe();
        // make sure this cb isn't in there anymore
        assert.equal(ee.events['TEST'].length, 1);
        assert.notInclude(ee.events['TEST'], othercb);
    });

    it('removes all listeners for a given event type', () => {
        ee.addListener('REMOVEME', callback);
        ee.addListener('REMOVEME', callback);
        ee.addListener('REMOVEME', callback);
        assert.equal(ee.events['REMOVEME'].length, 3);
        let returnedEE = ee.removeAllListeners('REMOVEME');
        assert.equal(ee.events['REMOVEME'].length, 0);
        // removeAll returns a ref to the EE class itself
        assert.deepEqual(EventEmitter, returnedEE);
    });

    it('removes the correct listener on remove', () => {
        let localcb = function() { return 'different function' };
        ee.addListener('removeOne', callback);
        ee.addListener('removeOne', localcb);
        assert.equal(ee.events['removeOne'].length, 2);
        ee.removeListener('removeOne', localcb);
        assert.equal(ee.events['removeOne'].length, 1);
        // only the cb should be left in the array
        assert.deepEqual(ee.events['removeOne'], [callback]);
    });

});<|endoftext|>