<commit_before>{
	'type': 'game', // game or console
	'name': 'Galaxian',
	'authors': ['Kazunori Swano', 'Koichi Tashiro', 'Shigekazu Ishimura'],
	'company': ['Namco'],
	'year': '1979',
	'date': 'October of 1979',
	'headline': 'The evolution of the Space Invaders',
	'resume': [
		'Um jogo arcade segue a formula de Space Invaders, com um enredo ',
		'simples e bastante objetivo de eliminar uma froto alienígena de ',
		'uma raça chamada GALAXIAN.'
	].join(''),
	'full_text': [
		'Sendo desenvolvido pela Namco em 1979 e lançado no mesmo no Japão,',
		' sua jogabilidade consistia em atirar em uma frota de aliens que ',
		'tentam periodicamente ataques kamikazes, os quais o jogador pode ',
		'desviar se movendo pela vertical. Ademais, sua principal diferença',
		' de sua inspiração é o fato de ser colorido na palheta RGB e ter',
		' uma trilha sonora de fundo, além dos ataques Kamikazes.'
	].join(''),
        'thumbnail': 'thumbnail_example.png',
        'main_img': {'name': 'main_picture.png', 'caption': "description"},
        'images': [
            {'name': 'picture1.png', 'caption': "description1"},
            {'name': 'picture2.png', 'caption': "description2"},
            {'name': 'picture3.png', 'caption': "description3"}
        ],
        'video_gameplay': [
            {'url': 'https://www.youtube.com/watch?v=qKm8UnFCmeg', 'caption': "gameplay", 'type': "youtube"} // type: youtube or vimeo
        ],
        'demos': [
            {'url': 'http://www.letsplaysnes.com/play-galaxian-online-nes/?play=true#content', 'caption': "demo"}
        ],
        'references': [
            {'url': 'http://en.wikipedia.org/wiki/galaxian', 'caption': "Wikipedia"}
        ]
}
},
<commit_msg>Update galaxianpt_temp.js<commit_after>{
	'type': 'game', // game or console
	'name': 'Galaxian',
	'authors': ['Kazunori Swano', 'Koichi Tashiro', 'Shigekazu Ishimura'],
	'company': ['Namco'],
	'year': '1979',
	'date': 'October of 1979',
	'headline': 'The evolution of the Space Invaders',
	'resume': [
		'Um jogo arcade segue a formula de Space Invaders, com um enredo ',
		'simples e bastante objetivo de eliminar uma froto alienígena de ',
		'uma raça chamada GALAXIAN.'
	].join(''),
	'full_text': [
		'Sendo desenvolvido pela Namco em 1979 e lançado no mesmo no Japão,',
		' sua jogabilidade consistia em atirar em uma frota de aliens que ',
		'tentam periodicamente ataques kamikazes, os quais o jogador pode ',
		'desviar se movendo pela vertical. Ademais, sua principal diferença',
		' de sua inspiração é o fato de ser colorido na palheta RGB e ter',
		' uma trilha sonora de fundo, além dos ataques Kamikazes.'
	].join(''),
        'thumbnail': 'thumbnail_example.png',
        'main_img': {'name': 'main_picture.png', 'caption': "description"},
        'images': [
            {'name': 'picture1.png', 'caption': "description1"},
            {'name': 'picture2.png', 'caption': "description2"},
        ],
        'video_gameplay': [
            {'url': 'https://www.youtube.com/watch?v=qKm8UnFCmeg', 'caption': "gameplay", 'type': "youtube"} // type: youtube or vimeo
        ],
        'demos': [
            {'url': 'http://www.letsplaysnes.com/play-galaxian-online-nes/?play=true#content', 'caption': "demo"}
        ],
        'references': [
            {'url': 'http://en.wikipedia.org/wiki/galaxian', 'caption': "Wikipedia"}
        ]
}
},
<|endoftext|>


<commit_before>// ==========================================================================
// Project:   SproutCore - JavaScript Application Framework
// Copyright: ©2006-2009 Sprout Systems, Inc. and contributors.
//            Portions ©2008-2009 Apple, Inc. All rights reserved.
// License:   Licened under MIT license (see license.js)
// ==========================================================================

sc_require('data_sources/data_source');
sc_require('models/record');

/** @class

  TODO: Describe Class

  @extends SC.DataSource
  @since SproutCore 1.0
*/
SC.FixturesDataSource = SC.DataSource.extend( {

  // ..........................................................
  // STANDARD DATA SOURCE METHODS
  //

  /**

    Invoked by the store whenever it needs to load a fresh new batch or
    records or simply refresh based on their storeKeys. This method is
    invoked from the store methods 'findAll' and 'retrieveRecords'.

    findAll() will request all records and load them using
    store.loadRecords(). retrieveRecords() checks if the record is already
    loaded and in a clean state to then just materialize it or if is in an
    empty state, it will call this method to load the required record to
    then materialize it.

    @param {SC.Store} store the requesting store
    @param {Object} fetchKey key describing the request, may be SC.Record
    @param {Hash} params optional additonal fetch params
    @returns {SC.Array} result set with storeKeys.
  */
  fetch: function(store, fetchKey, params) {

    var ret = [], fixtures;

    // TODO: this currently only supports one recordType per SC.Query
    if(SC.instanceOf(fetchKey, SC.Query)) {
      fetchKey = fetchKey.recordType;
    }

    if(SC.typeOf(fetchKey)===SC.T_STRING) {
      fetchKey = SC.objectForPropertyPath(fetchKey);
    }

    if(fetchKey === SC.Record || SC.Record.hasSubclass(fetchKey)) {
      this.loadFixturesFor(store, fetchKey, ret);
    }

    return ret;
  },

  /**
    Load fixtures for a given fetchKey into the store
    and push it to the ret array.

    @param {SC.Store} store
    @param {SC.Record} fetchKey
    @param {SC.Array} ret
  */
  loadFixturesFor: function(store, fetchKey, ret) {
    var dataHashes, i, storeKey, hashes = [];

    dataHashes = this.fixturesFor(fetchKey);

    for(i in dataHashes){
      storeKey = fetchKey.storeKeyFor(i);
      hashes.push(dataHashes[i]);
      ret.push(storeKey);
    }

    // before loading fixtures again, make sure they have not been
    // loaded already, so that SC.Query does not end up in
    // infinite loop
    if(!this.fixturesLoadedFor(fetchKey)) {
      store.loadRecords(fetchKey, hashes);
    }

  },

  /**
    Load fixtures for a given fetchKey into the store
    and push it to the ret array.

    @param {SC.Store} store
    @param {SC.Record} fetchKey
    @param {SC.Array} ret
  */
  loadFixturesFor: function(store, fetchKey, ret) {
    var dataHashes, i, storeKey, hashes = [];
    dataHashes = this.fixturesFor(fetchKey);
    for(i in dataHashes){
      storeKey = fetchKey.storeKeyFor(i);
      hashes.push(dataHashes[i]);
      ret.push(storeKey);
    }
    store.loadRecords(fetchKey, hashes);
  },

  /**
    Retrieve a record from fixtures.

    @param {SC.Store} store
    @param {Number} storeKey
    @param {SC.Array} ret
  */
  retrieveRecord: function(store, storeKey) {
    var ret = [], recordType = SC.Store.recordTypeFor(storeKey),
        id = store.idFor(storeKey),
        hash = this.fixtureForStoreKey(store, storeKey);
    ret.push(storeKey);
    store.dataSourceDidComplete(storeKey, hash, id);

    return ret;
  },

  /**
    Fixture operations complete immediately so you cannot cancel them.

    @param {SC.Store} store
    @param {SC.Array} storeKeys
    @returns {Boolean} YES if handled
  */
  cancel: function(store, storeKeys) {
    return NO;
  },

  /**
    Update the dataHash in this._fixtures

    @param {SC.Store} store
    @param {Number} storeKey
    @returns {Boolean} YES if handled
  */
  updateRecord: function(store, storeKey) {
    this.setFixtureForStoreKey(store, storeKey, store.readDataHash(storeKey));
    store.dataSourceDidComplete(storeKey);
    return YES ;
  },

  /**
    Adds records to this._fixtures.  If the record does not have an id yet,
    then then calls generateIdFor() and sets that.

    @param {SC.Store} store the store
    @param {Number} storeKey the store key
    @returns {Boolean} YES if successful
  */
  createRecord: function(store, storeKey) {
    var id         = store.idFor(storeKey),
        recordType = store.recordTypeFor(storeKey),
        dataHash   = store.readDataHash(storeKey),
        fixtures   = this.fixturesFor(recordType);

    if (!id) id = this.generateIdFor(recordType, dataHash, store, storeKey);
    this._invalidateCachesFor(recordType, storeKey, id);
    fixtures[id] = dataHash;

    store.dataSourceDidComplete(storeKey, null, id);
    return YES ;
  },

  /**
    Removes the data from the fixtures.

    @param {SC.Store} store the store
    @param {Number} storeKey the store key
    @returns {Boolean} YES if successful
  */
  destroyRecord: function(store, storeKey) {
    var id         = store.idFor(storeKey),
        recordType = store.recordTypeFor(storeKey),
        fixtures   = this.fixturesFor(recordType);

    this._invalidateCachesFor(recordType, storeKey, id);
    if (id) delete fixtures[id];
    store.dataSourceDidDestroy(storeKey);
    return YES ;
  },

  // ..........................................................
  // INTERNAL METHODS
  //

  /**
    Generates an id for the passed record type.  You can override this if
    needed.  The default generates a storekey and formats it as a string.
  */
  generateIdFor: function(recordType, dataHash, store, storeKey) {
    return "@id%@".fmt(SC.Store.generateStoreKey());
  },

  /**
    Based on the storeKey it returns the specified fixtures

    @param {SC.Store} store the store
    @param {Number} storeKey the storeKey
    @returns {Hash} data hash or null
  */
  fixtureForStoreKey: function(store, storeKey) {
    var id         = store.idFor(storeKey),
        recordType = store.recordTypeFor(storeKey),
        fixtures   = this.fixturesFor(recordType);
    return fixtures ? fixtures[id] : null;
  },

  /**
    Sets the data hash fixture for the named store key.

    @param {SC.Store} store the store
    @param {Number} storeKey the storeKey
    @param {Hash} dataHash
    @returns {SC.FixturesDataSource} receiver
  */
  setFixtureForStoreKey: function(store, storeKey, dataHash) {
    var id         = store.idFor(storeKey),
        recordType = store.recordTypeFor(storeKey),
        fixtures   = this.fixturesFor(recordType);
    this._invalidateCachesFor(recordType, storeKey, id);
    fixtures[id] = dataHash;
    return this ;
  },

  /**
    Invoked methods to ensure fixtures for a particular record type have been
    loaded.

    @param {SC.Record} recordType
    @returns {Hash} data hashes
  */
  fixturesFor: function(recordType) {
    // get basic fixtures hash.
    if (!this._fixtures) this._fixtures = {};
    var fixtures = this._fixtures[SC.guidFor(recordType)];
    if (fixtures) return fixtures ;

    // need to load fixtures.
    var dataHashes = recordType ? recordType.FIXTURES : null,
        len        = dataHashes ? dataHashes.length : 0,
        primaryKey = recordType ? recordType.prototype.primaryKey : 'guid',
        idx, dataHash, id ;

    this._fixtures[SC.guidFor(recordType)] = fixtures = {} ;
    for(idx=0;idx<len;idx++) {
      dataHash = dataHashes[idx];
      id = dataHash[primaryKey];
      if (!id) id = this.generateIdFor(recordType, dataHash);
      fixtures[id] = dataHash;
    }
    return fixtures;
  },

  /**
    Returns YES is fixtures for a given recordType have already been loaded

    @param {SC.Record} recordType
    @returns {Boolean} storeKeys
  */
  fixturesLoadedFor: function(recordType) {
    if (!this._fixtures) return NO;
    var ret = [], fixtures = this._fixtures[SC.guidFor(recordType)];
    return fixtures ? YES: NO;
  },

  /**
    Invalidates any internal caches based on the recordType and optional
    other parameters.  Currently this only invalidates the storeKeyCache used
    for fetch, but it could invalidate others later as well.

    @param {SC.Record} recordType the type of record modified
    @param {Number} storeKey optional store key
    @param {String} id optional record id
    @returns {SC.FixturesDataSource} receiver
  */
  _invalidateCachesFor: function(recordType, storeKey, id) {
    var cache = this._storeKeyCache;
    if (cache) delete cache[SC.guidFor(recordType)]
    return this ;
  }

});

// create default instance for use when configuring
SC.Record.fixtures = SC.FixturesDataSource.create();
<commit_msg>Fixture.fetch would not return store keys after first call<commit_after>// ==========================================================================
// Project:   SproutCore - JavaScript Application Framework
// Copyright: ©2006-2009 Sprout Systems, Inc. and contributors.
//            Portions ©2008-2009 Apple, Inc. All rights reserved.
// License:   Licened under MIT license (see license.js)
// ==========================================================================

sc_require('data_sources/data_source');
sc_require('models/record');

/** @class

  TODO: Describe Class

  @extends SC.DataSource
  @since SproutCore 1.0
*/
SC.FixturesDataSource = SC.DataSource.extend( {

  // ..........................................................
  // STANDARD DATA SOURCE METHODS
  //

  /**

    Invoked by the store whenever it needs to load a fresh new batch or
    records or simply refresh based on their storeKeys. This method is
    invoked from the store methods 'findAll' and 'retrieveRecords'.

    findAll() will request all records and load them using
    store.loadRecords(). retrieveRecords() checks if the record is already
    loaded and in a clean state to then just materialize it or if is in an
    empty state, it will call this method to load the required record to
    then materialize it.

    @param {SC.Store} store the requesting store
    @param {Object} fetchKey key describing the request, may be SC.Record
    @param {Hash} params optional additonal fetch params
    @returns {SC.Array} result set with storeKeys.
  */
  fetch: function(store, fetchKey, params) {

    var ret = [], fixtures;

    // TODO: this currently only supports one recordType per SC.Query
    if(SC.instanceOf(fetchKey, SC.Query)) {
      fetchKey = fetchKey.recordType;
    }

    if(SC.typeOf(fetchKey)===SC.T_STRING) {
      fetchKey = SC.objectForPropertyPath(fetchKey);
    }

    if(fetchKey === SC.Record || SC.Record.hasSubclass(fetchKey)) {
      this.loadFixturesFor(store, fetchKey, ret);
    }

    return ret;
  },

  /**
    Load fixtures for a given fetchKey into the store
    and push it to the ret array.

    @param {SC.Store} store
    @param {SC.Record} fetchKey
    @param {SC.Array} ret
  */
  loadFixturesFor: function(store, fetchKey, ret) {
    var dataHashes, i, storeKey, hashes = [];

    dataHashes = this.fixturesFor(fetchKey);

    for(i in dataHashes){
      storeKey = fetchKey.storeKeyFor(i);
      hashes.push(dataHashes[i]);
      ret.push(storeKey);
    }

    // before loading fixtures again, make sure they have not been
    // loaded already, so that SC.Query does not end up in
    // infinite loop
    if(!this.fixturesLoadedFor(fetchKey)) {
      store.loadRecords(fetchKey, hashes);
    }

  },

  /**
    Load fixtures for a given fetchKey into the store
    and push it to the ret array.

    @param {SC.Store} store
    @param {SC.Record} fetchKey
    @param {SC.Array} ret
  */
  loadFixturesFor: function(store, fetchKey, ret) {
    var dataHashes, i, storeKey, hashes = [];
    dataHashes = this.fixturesFor(fetchKey);
    for(i in dataHashes){
      storeKey = fetchKey.storeKeyFor(i);
      hashes.push(dataHashes[i]);
      ret.push(storeKey);
    }
    store.loadRecords(fetchKey, hashes);
  },

  /**
    Retrieve a record from fixtures.

    @param {SC.Store} store
    @param {Number} storeKey
    @param {SC.Array} ret
  */
  retrieveRecord: function(store, storeKey) {
    var ret = [], recordType = SC.Store.recordTypeFor(storeKey),
        id = store.idFor(storeKey),
        hash = this.fixtureForStoreKey(store, storeKey);
    ret.push(storeKey);
    store.dataSourceDidComplete(storeKey, hash, id);

    return ret;
  },

  /**
    Fixture operations complete immediately so you cannot cancel them.

    @param {SC.Store} store
    @param {SC.Array} storeKeys
    @returns {Boolean} YES if handled
  */
  cancel: function(store, storeKeys) {
    return NO;
  },

  /**
    Update the dataHash in this._fixtures

    @param {SC.Store} store
    @param {Number} storeKey
    @returns {Boolean} YES if handled
  */
  updateRecord: function(store, storeKey) {
    this.setFixtureForStoreKey(store, storeKey, store.readDataHash(storeKey));
    store.dataSourceDidComplete(storeKey);
    return YES ;
  },

  /**
    Adds records to this._fixtures.  If the record does not have an id yet,
    then then calls generateIdFor() and sets that.

    @param {SC.Store} store the store
    @param {Number} storeKey the store key
    @returns {Boolean} YES if successful
  */
  createRecord: function(store, storeKey) {
    var id         = store.idFor(storeKey),
        recordType = store.recordTypeFor(storeKey),
        dataHash   = store.readDataHash(storeKey),
        fixtures   = this.fixturesFor(recordType);

    if (!id) id = this.generateIdFor(recordType, dataHash, store, storeKey);
    this._invalidateCachesFor(recordType, storeKey, id);
    fixtures[id] = dataHash;

    store.dataSourceDidComplete(storeKey, null, id);
    return YES ;
  },

  /**
    Removes the data from the fixtures.

    @param {SC.Store} store the store
    @param {Number} storeKey the store key
    @returns {Boolean} YES if successful
  */
  destroyRecord: function(store, storeKey) {
    var id         = store.idFor(storeKey),
        recordType = store.recordTypeFor(storeKey),
        fixtures   = this.fixturesFor(recordType);

    this._invalidateCachesFor(recordType, storeKey, id);
    if (id) delete fixtures[id];
    store.dataSourceDidDestroy(storeKey);
    return YES ;
  },

  // ..........................................................
  // INTERNAL METHODS
  //

  /**
    Generates an id for the passed record type.  You can override this if
    needed.  The default generates a storekey and formats it as a string.
  */
  generateIdFor: function(recordType, dataHash, store, storeKey) {
    return "@id%@".fmt(SC.Store.generateStoreKey());
  },

  /**
    Based on the storeKey it returns the specified fixtures

    @param {SC.Store} store the store
    @param {Number} storeKey the storeKey
    @returns {Hash} data hash or null
  */
  fixtureForStoreKey: function(store, storeKey) {
    var id         = store.idFor(storeKey),
        recordType = store.recordTypeFor(storeKey),
        fixtures   = this.fixturesFor(recordType);
    return fixtures ? fixtures[id] : null;
  },

  /**
    Sets the data hash fixture for the named store key.

    @param {SC.Store} store the store
    @param {Number} storeKey the storeKey
    @param {Hash} dataHash
    @returns {SC.FixturesDataSource} receiver
  */
  setFixtureForStoreKey: function(store, storeKey, dataHash) {
    var id         = store.idFor(storeKey),
        recordType = store.recordTypeFor(storeKey),
        fixtures   = this.fixturesFor(recordType);
    this._invalidateCachesFor(recordType, storeKey, id);
    fixtures[id] = dataHash;
    return this ;
  },

  /**
    Invoked methods to ensure fixtures for a particular record type have been
    loaded.

    @param {SC.Record} recordType
    @returns {Hash} data hashes
  */
  fixturesFor: function(recordType) {
    // get basic fixtures hash.
    if (!this._fixtures) this._fixtures = {};
    var fixtures = this._fixtures[SC.guidFor(recordType)];
    if (fixtures) return fixtures ;

    // need to load fixtures.
    var dataHashes = recordType ? recordType.FIXTURES : null,
        len        = dataHashes ? dataHashes.length : 0,
        primaryKey = recordType ? recordType.prototype.primaryKey : 'guid',
        idx, dataHash, id ;

    this._fixtures[SC.guidFor(recordType)] = fixtures = {} ;
    for(idx=0;idx<len;idx++) {
      dataHash = dataHashes[idx];
      id = dataHash[primaryKey];
      if (!id) id = this.generateIdFor(recordType, dataHash);
      fixtures[id] = dataHash;
    }
    return fixtures;
  },

  /**
    Returns YES is fixtures for a given recordType have already been loaded

    @param {SC.Record} recordType
    @returns {Boolean} storeKeys
  */
  fixturesLoadedFor: function(recordType) {
    if (!this._fixtures) return NO;
    var ret = [], fixtures = this._fixtures[SC.guidFor(recordType)];
    return fixtures ? YES: NO;
  },

  /**
    Invalidates any internal caches based on the recordType and optional
    other parameters.  Currently this only invalidates the storeKeyCache used
    for fetch, but it could invalidate others later as well.

    @param {SC.Record} recordType the type of record modified
    @param {Number} storeKey optional store key
    @param {String} id optional record id
    @returns {SC.FixturesDataSource} receiver
  */
  _invalidateCachesFor: function(recordType, storeKey, id) {
    var cache = this._storeKeyCache;
    if (cache) delete cache[SC.guidFor(recordType)]
    return this ;
  }

});

// create default instance for use when configuring
SC.Record.fixtures = SC.FixturesDataSource.create();
<|endoftext|>


<commit_before>// see http://vuejs-templates.github.io/webpack for documentation.
var path = require('path');

let isTest = process.env.test;
let isDev = process.env.dev;
let witnesses = [
  // 'ws://172.19.19.148:28090',
  // 'ws://172.19.19.149:28090'
  'wss://node1.gxb.io',
  // 'wss://node5.gxb.io',
  // 'wss://node8.gxb.io',
  'wss://node11.gxb.io',
  'wss://node15.gxb.io',
  'wss://node16.gxb.io',
  'wss://node17.gxb.io'
];
if (isTest) {
  witnesses = ['wss://testnet.gxchain.org'];
}
if (isDev) {
  witnesses = ['ws://47.96.164.78:28090'];
}

module.exports = {
  build: {
    env: require('./prod.env'),
    index: path.resolve(__dirname, '../dist/index.html'),
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    productionSourceMap: false,
    witnesses: witnesses,
    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],
    // Run the build command with an extra argument to
    // View the bundle analyzer report after build finishes:
    // `npm run build --report`
    // Set to `true` or `false` to always turn it on or off
    bundleAnalyzerReport: process.env.npm_config_report
  },
  dev: {
    env: require('./dev.env'),
    port: 8080,
    autoOpenBrowser: true,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    witnesses: [
      'wss://testnet.gxchain.org'
      // 'wss://node5.gxb.io',
      // 'wss://node8.gxb.io',
      // 'wss://node11.gxb.io',
      // 'wss://node15.gxb.io',
      // 'wss://node16.gxb.io',
      // 'wss://node17.gxb.io'
    ],
    // CSS Sourcemaps off by default because relative paths are "buggy"
    // with this option, according to the CSS-Loader README
    // (https://github.com/webpack/css-loader#sourcemaps)
    // In our experience, they generally work as expected,
    // just be aware of this issue when enabling this option.
    cssSourceMap: false
  }
};
<commit_msg>chore: update witness list<commit_after>// see http://vuejs-templates.github.io/webpack for documentation.
var path = require('path');

let isTest = process.env.test;
let isDev = process.env.dev;
let witnesses = [
  // 'ws://172.19.19.148:28090',
  // 'ws://172.19.19.149:28090'
  'wss://node1.gxb.io',
  'wss://node5.gxb.io',
  'wss://node8.gxb.io',
  'wss://node11.gxb.io',
  'wss://node15.gxb.io',
  'wss://node16.gxb.io',
  'wss://node17.gxb.io'
];
if (isTest) {
  witnesses = ['wss://testnet.gxchain.org'];
}
if (isDev) {
  witnesses = ['ws://47.96.164.78:28090'];
}

module.exports = {
  build: {
    env: require('./prod.env'),
    index: path.resolve(__dirname, '../dist/index.html'),
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    productionSourceMap: false,
    witnesses: witnesses,
    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],
    // Run the build command with an extra argument to
    // View the bundle analyzer report after build finishes:
    // `npm run build --report`
    // Set to `true` or `false` to always turn it on or off
    bundleAnalyzerReport: process.env.npm_config_report
  },
  dev: {
    env: require('./dev.env'),
    port: 8080,
    autoOpenBrowser: true,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    witnesses: [
      'wss://testnet.gxchain.org'
      // 'wss://node5.gxb.io',
      // 'wss://node8.gxb.io',
      // 'wss://node11.gxb.io',
      // 'wss://node15.gxb.io',
      // 'wss://node16.gxb.io',
      // 'wss://node17.gxb.io'
    ],
    // CSS Sourcemaps off by default because relative paths are "buggy"
    // with this option, according to the CSS-Loader README
    // (https://github.com/webpack/css-loader#sourcemaps)
    // In our experience, they generally work as expected,
    // just be aware of this issue when enabling this option.
    cssSourceMap: false
  }
};
<|endoftext|>


<commit_before>'use strict'

function FPSControls(camera) {
    this.__init__(camera)
}

FPSControls.prototype = {
    camera            : null,
    pitch             : null,
    yaw               : null,
    enabled           : null,

    // Movement.
    up                : null,
    down              : null,
    left              : null,
    right             : null,

    velocity          : null,
    acceleration      : null,

    flying_on         : null,
    left_right        : null,

    walking_direction : null,

    direction_object3D : null,

    // Camera view.
    max_upward_view   : null,
    max_downward_view : null,
    direction_vector  : null,

    // Mouse movement variables.
    buffer_mouse_movement: null,

    // Used to make mouse movement feel smoother.
    mouse_movement_x_buffer: null,
    mouse_movement_y_buffer: null,

    // Constants.
    half_pie          : null,
    max_view_angle    : null,
    diagonal_penalty  : null,
    ground_normal     : null,

    __init__: function(camera) {
        // Constants.
        this.half_pie         = Math.PI / 2
        this.max_view_angle   = this.half_pie * 0.9
        this.diagonal_penalty = Math.sqrt(.5)
        this.ground_normal    = new THREE.Vector3(0, 1, 0)

        this.buffer_mouse_movement = true

        this.camera = camera
        this.camera.rotation.set(0, 0, 0)
        this.camera.eulerOrder = 'ZYX'
        this.camera.up = new THREE.Vector3(0, 1, 0)

        this.pitch = new THREE.Object3D()
        this.pitch.add(camera)

        this.direction_object3D = new THREE.Object3D()
        this.direction_object3D.add(this.camera)

        this.yaw = new THREE.Object3D()
        this.yaw.add(this.pitch)

        this.enabled = false
        this.flying_on = true

        this.velocity = new THREE.Vector3()

        this.mouse_movement_x_buffer = new SmoothStepLowerLimitZero(this.yaw.rotation.y, 0.025)
        this.mouse_movement_y_buffer = new SmoothStepLowerLimitZero(this.pitch.rotation.x, 0.025)

        // TODO : Add smooth step to the movement buffers!!!

        document.addEventListener('keypress', this.on_key_press.bind(this), false)
        document.addEventListener('mousemove', this.on_mouse_move.bind(this), false)
        document.addEventListener('keydown', this.on_key_down.bind(this), false)
        document.addEventListener('keyup', this.on_key_up.bind(this), false)
    },

    toggle_flying: function() {
        this.flying_on = !this.flying_on
        if (this.flying_on) {
            this.velocity.y = 0
        }
    },

    toggle_mouse_movement_system: function() {
        this.buffer_mouse_movement = !this.buffer_mouse_movement
    },

    fly_left: function(delta) {
        this.velocity.x += 200 * delta * this.left_right.x
        this.velocity.y += 200 * delta * this.left_right.y
        this.velocity.z += 200 * delta * this.left_right.z
    },

    fly_right: function(delta) {
        this.velocity.x -= 200 * delta * this.left_right.x
        this.velocity.y -= 200 * delta * this.left_right.y
        this.velocity.z -= 200 * delta * this.left_right.z
    },

    fly_forward: function(delta) {
        this.velocity.x += 200 * delta * this.direction_vector.x
        this.velocity.y += 200 * delta * this.direction_vector.y
        this.velocity.z += 200 * delta * this.direction_vector.z
    },

    fly_backward: function(delta) {
        this.velocity.x -= 200 * delta * this.direction_vector.x
        this.velocity.y -= 200 * delta * this.direction_vector.y
        this.velocity.z -= 200 * delta * this.direction_vector.z
    },

    move_forward: function(delta) {
        this.velocity.x += 200 * delta * this.direction_vector.x
        this.velocity.z += 200 * delta * this.direction_vector.z
    },

    move_backward: function(delta) {
        this.velocity.x -= 200 * delta * this.direction_vector.x
        this.velocity.z -= 200 * delta * this.direction_vector.z
    },

    move_left: function(delta) {
        this.velocity.x += 200 * delta * this.left_right.x
        this.velocity.z += 200 * delta * this.left_right.z
    },

    move_right: function(delta) {
        this.velocity.x -= 200 * delta * this.left_right.x
        this.velocity.z -= 200 * delta * this.left_right.z
    },

    physics: function(delta) {
        if (this.enabled) {

            if (this.buffer_mouse_movement) {
                this.mouse_movement_x_buffer.update(delta)
                this.mouse_movement_y_buffer.update(delta)
            }
            this.update_mouse_view_position()

            if (this.flying_on) {
                // Flying code.
                if (this.space) {
                    this.velocity.y += 200.0 * delta
                }
                if (this.shift) {
                    this.velocity.y -= 200.0 * delta
                }

                if ((this.up ^ this.down) & (this.left ^ this.right)) {
                    if (this.up) {
                        this.fly_forward(delta * this.diagonal_penalty)
                    } else {
                        this.fly_backward(delta * this.diagonal_penalty)
                    }
                    if (this.left) {
                        this.fly_left(delta * this.diagonal_penalty)
                    } else {
                        this.fly_right(delta * this.diagonal_penalty)
                    }
                } else if (this.up ^ this.down) {
                    if (this.up) {
                        this.fly_forward(delta)
                    } else {
                        this.fly_backward(delta)
                    }
                } else if (this.left ^ this.right) {
                    if (this.left) {
                        this.fly_left(delta)
                    } else {
                        this.fly_right(delta)
                    }
                }
                this.velocity.y *= (1 - delta * 15)
                //this.yaw.position.y += this.velocity.y
                this.direction_object3D.position.y += this.velocity.y
            } else {
                // Walking code.
                if ((this.up ^ this.down) & (this.left ^ this.right)) {
                    if (this.up) {
                        this.move_forward(delta * this.diagonal_penalty)
                    } else {
                        this.move_backward(delta * this.diagonal_penalty)
                    }
                    if (this.left) {
                        this.move_left(delta * this.diagonal_penalty)
                    } else {
                        this.move_right(delta * this.diagonal_penalty)
                    }
                } else if (this.up ^ this.down) {
                    if (this.up) {
                        this.fly_forward(delta)
                    } else {
                        this.fly_backward(delta)
                    }
                } else if (this.left ^ this.right) {
                    if (this.left) {
                        this.move_left(delta)
                    } else {
                        this.move_right(delta)
                    }
                }
                /*
                if (this.velocity.y != 0) {
                    this.velocity.y -= 9.8 * delta * 10
                    this.velocity.y *= (1 - delta * 15)
                    this.yaw.position.y += this.velocity.y
                    if (this.yaw.position.y <= 10) {
                        this.yaw.position.y = 10
                        this.velocity.y = 0
                    }
                }
                */
            }
            // Both flying and walking treat the following lines the same.
            this.velocity.x *= (1 - delta * 15)
            this.velocity.z *= (1 - delta * 15)
            this.direction_object3D.position.x += this.velocity.x
            this.direction_object3D.position.z += this.velocity.z
            //this.yaw.position.x += this.velocity.x
            //this.yaw.position.z += this.velocity.z
        }
    },

    get_position: function() {
        return this.direction_object3D.position
        //return this.yaw.position
    },

    get_velocity: function() {
        return this.velocity
    },

    enable: function() {
        this.enabled = true
    },

    disable: function() {
        this.enabled = false
    },

    on_key_press: function(event) {
        switch(event.which) {
        case 102: // f
            this.toggle_flying()
            break
        case 109: // m
            this.toggle_mouse_movement_system()
            break
        }
    },

    on_key_down: function(event) {
        switch(event.keyCode) {
        case 38: // up
        case 87: // w
            this.up = true
            break
        case 37: // left
        case 65: // a
            this.left = true
            break
        case 40: // down
        case 83: // s
            this.down = true
            break
        case 39: // right
        case 68: // d
            this.right = true
            break
        case 32: // space
            this.space = true
            break
        case 16: // shift
            this.shift = true
            break
        }
    },

    on_key_up: function(event) {
        switch(event.keyCode) {
        case 38: // up
        case 87: // w
            this.up = false
            break
        case 37: // left
        case 65: // a
            this.left = false
            break
        case 40: // down
        case 83: // s
            this.down = false
            break
        case 39: // right
        case 68: // d
            this.right = false
            break
        case 32: // space
            this.space = false
            break
        case 16: // shift
            this.shift = false
            break
        }
    },

    look_at: function(position_vector_to_look_at) {
        //var look_at = new THREE.Vector3(position_vector_to_look_at.x, position_vector_to_look_at.y, position_vector_to_look_at.z)
        //look_at.sub(this.yaw.position)
        //look_at.normalize()

        //this.direction_object3D.lookAt(position_vector_to_look_at)

        // TODO : clear current mouse movement buffers

        //this.yaw.lookAt(position_vector_to_look_at)
        //this.pitch.lookAt(position_vector_to_look_at)

        //this.yaw.rotation.y   = look_at.y * TWO_PIE
        //this.pitch.rotation.x = look_at.x * TWO_PIE
    },

    update_mouse_view_position: function() {
        if (this.buffer_mouse_movement) {
            this.yaw.rotation.y = this.mouse_movement_x_buffer.get_current_value()
            this.pitch.rotation.x = this.mouse_movement_y_buffer.get_current_value()
        }

        this.pitch.rotation.x = Math.max(-this.max_view_angle, Math.min(this.max_view_angle, this.pitch.rotation.x))

        this.direction_vector = this.get_direction()
        this.direction_vector.normalize()

        this.left_right = new THREE.Vector3(0, 1, 0)
        this.left_right.cross(this.direction_vector)
        this.left_right.normalize()

        if (!this.flying_on) {
            this.walking_direction = new THREE.Vector3(this.direction_vector.x, this.direction_vector.y, this.direction_vector.z)
            this.walking_direction = this.walking_direction.projectOnPlane(this.ground_normal)
            this.walking_direction.normalize()
        }

        // Now actually update the camera.
        //var look_at = new THREE.Vector3(this.direction_vector.x * 2000, this.direction_vector.y * 2000, this.direction_vector.z * 2000)
        //this.direction_object3D.lookAt(look_at)
    },

    on_mouse_move: function(event) {
        console.log('Rotation Y : ' + this.yaw.rotation.y)
        console.log('Rotation X : ' + this.pitch.rotation.x)
        console.log('---')

        if (this.enabled) {
            var movement_x = event.movementX || event.mozMovementX || event.webkitMovementX || 0
            var movement_y = event.movementY || event.mozMovementY || event.webkitMovementY || 0

            if (this.buffer_mouse_movement) {
                this.mouse_movement_x_buffer.add_force(movement_x * -0.002)
                this.mouse_movement_y_buffer.add_force(movement_y * -0.002)
            } else {
                this.yaw.rotation.y   -= movement_x * 0.002
                this.pitch.rotation.x -= movement_y * 0.002
            }
        }
    },

    get_object: function() {
        //return this.direction_object3D
        return this.yaw
    },

    get_direction: function() {
        var direction = new THREE.Vector3(0, 0, -1)
        var rotation  = new THREE.Euler(this.pitch.rotation.x, this.yaw.rotation.y, 0, 'YXZ')
        return direction.applyEuler(rotation)
    }

}<commit_msg>General updates 23<commit_after>'use strict'

function FPSControls(camera) {
    this.__init__(camera)
}

FPSControls.prototype = {
    camera            : null,
    pitch             : null,
    yaw               : null,
    enabled           : null,

    // Movement.
    up                : null,
    down              : null,
    left              : null,
    right             : null,

    velocity          : null,
    acceleration      : null,

    flying_on         : null,
    left_right        : null,

    walking_direction : null,

    direction_object3D : null,

    // Camera view.
    max_upward_view   : null,
    max_downward_view : null,
    direction_vector  : null,

    // Mouse movement variables.
    buffer_mouse_movement: null,

    // Used to make mouse movement feel smoother.
    mouse_movement_x_buffer: null,
    mouse_movement_y_buffer: null,

    // Constants.
    half_pie          : null,
    max_view_angle    : null,
    diagonal_penalty  : null,
    ground_normal     : null,

    __init__: function(camera) {
        // Constants.
        this.half_pie         = Math.PI / 2
        this.max_view_angle   = this.half_pie * 0.9
        this.diagonal_penalty = Math.sqrt(.5)
        this.ground_normal    = new THREE.Vector3(0, 1, 0)

        this.buffer_mouse_movement = true

        this.camera = camera
        this.camera.rotation.set(0, 0, 0)
        this.camera.eulerOrder = 'ZYX'
        this.camera.up = new THREE.Vector3(0, 1, 0)

        this.pitch = new THREE.Object3D()
        this.pitch.add(camera)

        this.direction_object3D = new THREE.Object3D()
        //this.direction_object3D.add(this.camera)

        this.yaw = new THREE.Object3D()
        this.yaw.add(this.pitch)

        this.enabled = false
        this.flying_on = true

        this.velocity = new THREE.Vector3()

        this.mouse_movement_x_buffer = new SmoothStepLowerLimitZero(this.yaw.rotation.y, 0.025)
        this.mouse_movement_y_buffer = new SmoothStepLowerLimitZero(this.pitch.rotation.x, 0.025)

        // TODO : Add smooth step to the movement buffers!!!

        document.addEventListener('keypress', this.on_key_press.bind(this), false)
        document.addEventListener('mousemove', this.on_mouse_move.bind(this), false)
        document.addEventListener('keydown', this.on_key_down.bind(this), false)
        document.addEventListener('keyup', this.on_key_up.bind(this), false)
    },

    toggle_flying: function() {
        this.flying_on = !this.flying_on
        if (this.flying_on) {
            this.velocity.y = 0
        }
    },

    toggle_mouse_movement_system: function() {
        this.buffer_mouse_movement = !this.buffer_mouse_movement
    },

    fly_left: function(delta) {
        this.velocity.x += 200 * delta * this.left_right.x
        this.velocity.y += 200 * delta * this.left_right.y
        this.velocity.z += 200 * delta * this.left_right.z
    },

    fly_right: function(delta) {
        this.velocity.x -= 200 * delta * this.left_right.x
        this.velocity.y -= 200 * delta * this.left_right.y
        this.velocity.z -= 200 * delta * this.left_right.z
    },

    fly_forward: function(delta) {
        this.velocity.x += 200 * delta * this.direction_vector.x
        this.velocity.y += 200 * delta * this.direction_vector.y
        this.velocity.z += 200 * delta * this.direction_vector.z
    },

    fly_backward: function(delta) {
        this.velocity.x -= 200 * delta * this.direction_vector.x
        this.velocity.y -= 200 * delta * this.direction_vector.y
        this.velocity.z -= 200 * delta * this.direction_vector.z
    },

    move_forward: function(delta) {
        this.velocity.x += 200 * delta * this.direction_vector.x
        this.velocity.z += 200 * delta * this.direction_vector.z
    },

    move_backward: function(delta) {
        this.velocity.x -= 200 * delta * this.direction_vector.x
        this.velocity.z -= 200 * delta * this.direction_vector.z
    },

    move_left: function(delta) {
        this.velocity.x += 200 * delta * this.left_right.x
        this.velocity.z += 200 * delta * this.left_right.z
    },

    move_right: function(delta) {
        this.velocity.x -= 200 * delta * this.left_right.x
        this.velocity.z -= 200 * delta * this.left_right.z
    },

    physics: function(delta) {
        if (this.enabled) {

            if (this.buffer_mouse_movement) {
                this.mouse_movement_x_buffer.update(delta)
                this.mouse_movement_y_buffer.update(delta)
            }
            this.update_mouse_view_position()

            if (this.flying_on) {
                // Flying code.
                if (this.space) {
                    this.velocity.y += 200.0 * delta
                }
                if (this.shift) {
                    this.velocity.y -= 200.0 * delta
                }

                if ((this.up ^ this.down) & (this.left ^ this.right)) {
                    if (this.up) {
                        this.fly_forward(delta * this.diagonal_penalty)
                    } else {
                        this.fly_backward(delta * this.diagonal_penalty)
                    }
                    if (this.left) {
                        this.fly_left(delta * this.diagonal_penalty)
                    } else {
                        this.fly_right(delta * this.diagonal_penalty)
                    }
                } else if (this.up ^ this.down) {
                    if (this.up) {
                        this.fly_forward(delta)
                    } else {
                        this.fly_backward(delta)
                    }
                } else if (this.left ^ this.right) {
                    if (this.left) {
                        this.fly_left(delta)
                    } else {
                        this.fly_right(delta)
                    }
                }
                this.velocity.y *= (1 - delta * 15)
                this.yaw.position.y += this.velocity.y
                //this.direction_object3D.position.y += this.velocity.y
            } else {
                // Walking code.
                if ((this.up ^ this.down) & (this.left ^ this.right)) {
                    if (this.up) {
                        this.move_forward(delta * this.diagonal_penalty)
                    } else {
                        this.move_backward(delta * this.diagonal_penalty)
                    }
                    if (this.left) {
                        this.move_left(delta * this.diagonal_penalty)
                    } else {
                        this.move_right(delta * this.diagonal_penalty)
                    }
                } else if (this.up ^ this.down) {
                    if (this.up) {
                        this.fly_forward(delta)
                    } else {
                        this.fly_backward(delta)
                    }
                } else if (this.left ^ this.right) {
                    if (this.left) {
                        this.move_left(delta)
                    } else {
                        this.move_right(delta)
                    }
                }

                if (this.velocity.y != 0) {
                    this.velocity.y -= 9.8 * delta * 10
                    this.velocity.y *= (1 - delta * 15)
                    this.yaw.position.y += this.velocity.y
                    if (this.yaw.position.y <= 10) {
                        this.yaw.position.y = 10
                        this.velocity.y = 0
                    }
                }

            }
            // Both flying and walking treat the following lines the same.
            this.velocity.x *= (1 - delta * 15)
            this.velocity.z *= (1 - delta * 15)
            //this.direction_object3D.position.x += this.velocity.x
            //this.direction_object3D.position.z += this.velocity.z
            this.yaw.position.x += this.velocity.x
            this.yaw.position.z += this.velocity.z
        }
    },

    get_position: function() {
        //return this.direction_object3D.position
        return this.yaw.position
    },

    get_velocity: function() {
        return this.velocity
    },

    enable: function() {
        this.enabled = true
    },

    disable: function() {
        this.enabled = false
    },

    on_key_press: function(event) {
        switch(event.which) {
        case 102: // f
            this.toggle_flying()
            break
        case 109: // m
            this.toggle_mouse_movement_system()
            break
        }
    },

    on_key_down: function(event) {
        switch(event.keyCode) {
        case 38: // up
        case 87: // w
            this.up = true
            break
        case 37: // left
        case 65: // a
            this.left = true
            break
        case 40: // down
        case 83: // s
            this.down = true
            break
        case 39: // right
        case 68: // d
            this.right = true
            break
        case 32: // space
            this.space = true
            break
        case 16: // shift
            this.shift = true
            break
        }
    },

    on_key_up: function(event) {
        switch(event.keyCode) {
        case 38: // up
        case 87: // w
            this.up = false
            break
        case 37: // left
        case 65: // a
            this.left = false
            break
        case 40: // down
        case 83: // s
            this.down = false
            break
        case 39: // right
        case 68: // d
            this.right = false
            break
        case 32: // space
            this.space = false
            break
        case 16: // shift
            this.shift = false
            break
        }
    },

    look_at: function(position_vector_to_look_at) {
        //var look_at = new THREE.Vector3(position_vector_to_look_at.x, position_vector_to_look_at.y, position_vector_to_look_at.z)
        //look_at.sub(this.yaw.position)
        //look_at.normalize()

        //this.direction_object3D.lookAt(position_vector_to_look_at)

        // TODO : clear current mouse movement buffers

        //this.yaw.lookAt(position_vector_to_look_at)
        //this.pitch.lookAt(position_vector_to_look_at)

        //this.yaw.rotation.y   = look_at.y * TWO_PIE
        //this.pitch.rotation.x = look_at.x * TWO_PIE
    },

    update_mouse_view_position: function() {
        if (this.buffer_mouse_movement) {
            this.yaw.rotation.y = this.mouse_movement_x_buffer.get_current_value()
            this.pitch.rotation.x = this.mouse_movement_y_buffer.get_current_value()
        }

        this.pitch.rotation.x = Math.max(-this.max_view_angle, Math.min(this.max_view_angle, this.pitch.rotation.x))

        this.direction_vector = this.get_direction()
        this.direction_vector.normalize()

        this.left_right = new THREE.Vector3(0, 1, 0)
        this.left_right.cross(this.direction_vector)
        this.left_right.normalize()

        if (!this.flying_on) {
            this.walking_direction = new THREE.Vector3(this.direction_vector.x, this.direction_vector.y, this.direction_vector.z)
            this.walking_direction = this.walking_direction.projectOnPlane(this.ground_normal)
            this.walking_direction.normalize()
        }

        // Now actually update the camera.
        //var look_at = new THREE.Vector3(this.direction_vector.x * 2000, this.direction_vector.y * 2000, this.direction_vector.z * 2000)
        //this.direction_object3D.lookAt(look_at)
    },

    on_mouse_move: function(event) {
        console.log('Rotation Y : ' + this.yaw.rotation.y)
        console.log('Rotation X : ' + this.pitch.rotation.x)
        console.log('---')

        if (this.enabled) {
            var movement_x = event.movementX || event.mozMovementX || event.webkitMovementX || 0
            var movement_y = event.movementY || event.mozMovementY || event.webkitMovementY || 0

            if (this.buffer_mouse_movement) {
                this.mouse_movement_x_buffer.add_force(movement_x * -0.002)
                this.mouse_movement_y_buffer.add_force(movement_y * -0.002)
            } else {
                this.yaw.rotation.y   -= movement_x * 0.002
                this.pitch.rotation.x -= movement_y * 0.002
            }
        }
    },

    get_object: function() {
        //return this.direction_object3D
        return this.yaw
    },

    get_direction: function() {
        var direction = new THREE.Vector3(0, 0, -1)
        var rotation  = new THREE.Euler(this.pitch.rotation.x, this.yaw.rotation.y, 0, 'YXZ')
        return direction.applyEuler(rotation)
    }

}<|endoftext|>


<commit_before>/**
	The MIT License (MIT)

	Copyright (c) 2014 MyChannel-Apps.de

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.

	@author		Adrian Preuß <Bizarrus>, Christoph Kühl <djchrisnet>
*/

var Hooks = (new function() {
	var _hooks	= {};
	var _debug	= false;

	this.addFilter = function(name, callback, priority) {
		this.add(name, callback, priority, true);
	};

	this.addAction = function(name, callback, priority) {
		this.add(name, callback, priority);
	};

	this.add = function(name, callback, priority, is_filter) {
		priority	= (priority == undefined ? 10 : priority); // default Priority is 10
		is_filter	= (is_filter == undefined ? false : is_filter);

		if(_hooks[priority] == undefined) {
			_hooks[priority] = [];
		}

		if(_debug) {
			if(Logger == undefined) {
				KnuddelsServer.getDefaultLogger().info('[Hooks] Adding "' + name + '" with Priority of ' + priority);
			} else {
				Logger.info('[Hooks] Adding "' + name + '" with Priority of ' + priority);
			}
		}

		_hooks[priority].push({
			name:		name,
			callback:	callback,
			is_filter:	is_filter
		});
	};

	this.remove = function(name, priority) {
		priority = (priority == undefined ? 10 : priority); // default Priority is 10

		if(_debug) {
			if(Logger == undefined) {
				KnuddelsServer.getDefaultLogger().info('[Hooks] Removing "' + name + '" with Priority of ' + priority);
			} else {
				Logger.info('[Hooks] Removing "' + name + '" with Priority of ' + priority);
			}
		}

		if(!Object.prototype.each) {
			for(var index in _hooks[priority]) {
				var hook = _hooks[priority][index];

				if(hook.name == name) {
					delete _hooks[priority][index];
				}
			}
		} else {
			_hooks[priority].each(function(hook, index) {
				if(hook.name == name) {
					delete _hooks[priority][index];
				}
			});
		}
	};

	this.applyFilter = function(name) {
		var args		= [];
		var args_length	= arguments.size();

		for(var index = 0; index < args_length; ++index) {
			var argument = arguments[index];

			if(argument == undefined || argument == null) {
				continue;
			}

			args.push(argument);
		}

		args.splice(1, 0, true);

		return this.do.apply(this, args);
	};

	this.do = function(name, is_filter) {
		if(_debug) {
			if(Logger == undefined) {
				KnuddelsServer.getDefaultLogger().info('[Hooks] ' + JSON.stringify(arguments));
			} else {
				Logger.info('[Hooks] ' + JSON.stringify(arguments));
			}
		}

		var is_filter_set	= (is_filter == undefined || typeof(is_filter) != 'boolean');
		var args			= [];
		var args_length		= arguments.size();
		var output			= undefined;

		for(var index = 0; index < args_length; ++index) {
			var argument = arguments[index];

			if(argument == undefined || argument == null) {
				continue;
			}

			args.push(argument);
		}

		// remove the arguments
		args.shift();

		if(!is_filter_set) {
			args.shift();
		}

		output			= args[0];

		if(_debug) {
			if(Logger == undefined) {
				KnuddelsServer.getDefaultLogger().info('[Hooks] Execute "' + name + '" with params: ' + JSON.stringify(args));
			} else {
				Logger.info('[Hooks] Execute "' + name + '" with params: ' + JSON.stringify(args));
			}
		}

		// sort by priority
		if(!Array.prototype.sort) {
			if(Logger == undefined) {
				KnuddelsServer.getDefaultLogger().warn('Hooks won\'t sort by Priority because Array.sort(); is not available. Please import framework/tools/Array.js!');
			} else {
				Logger.warn('Hooks won\'t sort by Priority because Array.sort(); is not available. Please import framework/tools/Array.js!');
			}
		} else {
			_hooks.sort('index', 'ASC');
		}

		if(!Object.prototype.each) {
			for(var priority in _hooks) {
				var hooks = _hooks[priority];

				if(_debug) {
					if(Logger == undefined) {
						KnuddelsServer.getDefaultLogger().info('[Hooks] Each: PRIORITY ' + priority);
					} else {
						Logger.info('[Hooks] Each: PRIORITY ' + priority);
					}
				}

				for(var index in hooks) {
					var hook = hooks[index];

					if(hook.name == name) {
						if(typeof(output) != 'array') {
							output = [ output ];
						}

						output = hook.callback.apply(this, ((is_filter_set ? false : is_filter) ? output : args));
					}
				});
			}
		} else {
			_hooks.each(function(hooks, priority) {
				if(_debug) {
					if(Logger == undefined) {
						KnuddelsServer.getDefaultLogger().info('[Hooks] Each: PRIORITY ' + priority);
					} else {
						Logger.info('[Hooks] Each: PRIORITY ' + priority);
					}
				}

				hooks.each(function(hook) {
					if(hook.name == name) {
						if(typeof(output) != 'array') {
							output = [ output ];
						}

						output = hook.callback.apply(this, ((is_filter_set ? false : is_filter) ? output : args));
					}
				});
			});
		}

		return output;
	};

	this.toString = function() {
		return '[KFramework Hooks]';
	};
}());<commit_msg>Hooks: fix syntax error<commit_after>/**
	The MIT License (MIT)

	Copyright (c) 2014 MyChannel-Apps.de

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.

	@author		Adrian Preuß <Bizarrus>, Christoph Kühl <djchrisnet>
*/

var Hooks = (new function() {
	var _hooks	= {};
	var _debug	= false;

	this.addFilter = function(name, callback, priority) {
		this.add(name, callback, priority, true);
	};

	this.addAction = function(name, callback, priority) {
		this.add(name, callback, priority);
	};

	this.add = function(name, callback, priority, is_filter) {
		priority	= (priority == undefined ? 10 : priority); // default Priority is 10
		is_filter	= (is_filter == undefined ? false : is_filter);

		if(_hooks[priority] == undefined) {
			_hooks[priority] = [];
		}

		if(_debug) {
			if(Logger == undefined) {
				KnuddelsServer.getDefaultLogger().info('[Hooks] Adding "' + name + '" with Priority of ' + priority);
			} else {
				Logger.info('[Hooks] Adding "' + name + '" with Priority of ' + priority);
			}
		}

		_hooks[priority].push({
			name:		name,
			callback:	callback,
			is_filter:	is_filter
		});
	};

	this.remove = function(name, priority) {
		priority = (priority == undefined ? 10 : priority); // default Priority is 10

		if(_debug) {
			if(Logger == undefined) {
				KnuddelsServer.getDefaultLogger().info('[Hooks] Removing "' + name + '" with Priority of ' + priority);
			} else {
				Logger.info('[Hooks] Removing "' + name + '" with Priority of ' + priority);
			}
		}

		if(!Object.prototype.each) {
			for(var index in _hooks[priority]) {
				var hook = _hooks[priority][index];

				if(hook.name == name) {
					delete _hooks[priority][index];
				}
			}
		} else {
			_hooks[priority].each(function(hook, index) {
				if(hook.name == name) {
					delete _hooks[priority][index];
				}
			});
		}
	};

	this.applyFilter = function(name) {
		var args		= [];
		var args_length	= arguments.size();

		for(var index = 0; index < args_length; ++index) {
			var argument = arguments[index];

			if(argument == undefined || argument == null) {
				continue;
			}

			args.push(argument);
		}

		args.splice(1, 0, true);

		return this.do.apply(this, args);
	};

	this.do = function(name, is_filter) {
		if(_debug) {
			if(Logger == undefined) {
				KnuddelsServer.getDefaultLogger().info('[Hooks] ' + JSON.stringify(arguments));
			} else {
				Logger.info('[Hooks] ' + JSON.stringify(arguments));
			}
		}

		var is_filter_set	= (is_filter == undefined || typeof(is_filter) != 'boolean');
		var args			= [];
		var args_length		= arguments.size();
		var output			= undefined;

		for(var index = 0; index < args_length; ++index) {
			var argument = arguments[index];

			if(argument == undefined || argument == null) {
				continue;
			}

			args.push(argument);
		}

		// remove the arguments
		args.shift();

		if(!is_filter_set) {
			args.shift();
		}

		output			= args[0];

		if(_debug) {
			if(Logger == undefined) {
				KnuddelsServer.getDefaultLogger().info('[Hooks] Execute "' + name + '" with params: ' + JSON.stringify(args));
			} else {
				Logger.info('[Hooks] Execute "' + name + '" with params: ' + JSON.stringify(args));
			}
		}

		// sort by priority
		if(!Array.prototype.sort) {
			if(Logger == undefined) {
				KnuddelsServer.getDefaultLogger().warn('Hooks won\'t sort by Priority because Array.sort(); is not available. Please import framework/tools/Array.js!');
			} else {
				Logger.warn('Hooks won\'t sort by Priority because Array.sort(); is not available. Please import framework/tools/Array.js!');
			}
		} else {
			_hooks.sort('index', 'ASC');
		}

		if(!Object.prototype.each) {
			for(var priority in _hooks) {
				var hooks = _hooks[priority];

				if(_debug) {
					if(Logger == undefined) {
						KnuddelsServer.getDefaultLogger().info('[Hooks] Each: PRIORITY ' + priority);
					} else {
						Logger.info('[Hooks] Each: PRIORITY ' + priority);
					}
				}

				for(var index in hooks) {
					var hook = hooks[index];

					if(hook.name == name) {
						if(typeof(output) != 'array') {
							output = [ output ];
						}

						output = hook.callback.apply(this, ((is_filter_set ? false : is_filter) ? output : args));
					}
				};
			}
		} else {
			_hooks.each(function(hooks, priority) {
				if(_debug) {
					if(Logger == undefined) {
						KnuddelsServer.getDefaultLogger().info('[Hooks] Each: PRIORITY ' + priority);
					} else {
						Logger.info('[Hooks] Each: PRIORITY ' + priority);
					}
				}

				hooks.each(function(hook) {
					if(hook.name == name) {
						if(typeof(output) != 'array') {
							output = [ output ];
						}

						output = hook.callback.apply(this, ((is_filter_set ? false : is_filter) ? output : args));
					}
				});
			});
		}

		return output;
	};

	this.toString = function() {
		return '[KFramework Hooks]';
	};
}());<|endoftext|>


<commit_before>(function () {
    window.angular
        .module("ScrumPokerTable")
        .factory("DeskHubService", [
            "$rootScope", "$q", "$http", "$timeout", "Hub", function($rootScope, $q, $http, $timeout, Hub) {

                var connected = false;
                var deskHub = new Hub("deskHub", {
                    listeners: {
                        "deskChanged": function (desk) {
                            console.log(desk);
                            $rootScope.$broadcast("deskChanged", desk);
                            $rootScope.$apply();
                        }
                    },

                    methods: [
                        "joinAsUser",
                        "joinAsMaster",
                        "leave",
                        "setUserCard",
                        "setDeskState"
                    ],

                    transport: ["longPolling"],
                    queryParams: { "api": "1.0" },
                    errorHandler: function(error) {
                        console.error(error);
                        $rootScope.$broadcast("deskHubConnectionState", "error");
                        $rootScope.$apply();
                    },

                    stateChanged: function(state) {
                        connected = false;
                        console.info(state);
                        switch (state.newState) {
                            case $.signalR.connectionState.connecting:
                                $rootScope.$broadcast("deskHubConnectionState", "connecting");
                                break;
                            case $.signalR.connectionState.connected:
                                connected = true;
                                $rootScope.$broadcast("deskHubConnectionState", "connected");
                                $rootScope.$apply();
                                break;
                            case $.signalR.connectionState.reconnecting:
                                $rootScope.$broadcast("deskHubConnectionState", "reconnecting");
                                $rootScope.$apply();
                                break;
                            case $.signalR.connectionState.disconnected:
                                $rootScope.$broadcast("deskHubConnectionState", "disconnected");
                                $rootScope.$apply();
                                break;
                        }
                    }
                });

                return {

                    //WebAPI methods

                    createDesk: function (cards) {
                        return $http.put("api/1.0/desk/", cards).then(function (response) {
                            return response.data;
                        });
                    },

                    deleteDesk: function (deskName) {
                        return $http.delete("api/1.0/desk/" + deskName).then(function (response) {
                            return response.data;
                        });
                    },

                    getDesk: function (deskName) {
                        return $http.get("api/1.0/desk/" + deskName).then(function (response) {
                            return response.data;
                        });
                    },

                    //Hub methods

                    joinAsUser: function (deskName, userName) {
                        return $q.when(deskHub.joinAsUser(deskName, userName));
                    },

                    joinAsMaster: function (deskName) {
                        return $q.when(deskHub.joinAsMaster(deskName));
                    },

                    leave: function (deskName) {
                        return $q.when(deskHub.leave(deskName));
                    },

                    setUserCard: function (deskName, userName, card) {
                        return $q.when(deskHub.setUserCard(deskName, userName, card));
                    },

                    setDeskState: function (deskName, newState) {
                        return $q.when(deskHub.setDeskState(deskName, newState));
                    },

                    hasConnection: function () {
                        return connected;
                    },

                    reconnect: function() {
                        $timeout(function () {
                            deskHub.connect();
                        }, 2000);

                    }

                };
            }
        ]);

})();<commit_msg>removed force-longpolling option<commit_after>(function () {
    window.angular
        .module("ScrumPokerTable")
        .factory("DeskHubService", [
            "$rootScope", "$q", "$http", "$timeout", "Hub", function($rootScope, $q, $http, $timeout, Hub) {

                var connected = false;
                var deskHub = new Hub("deskHub", {
                    listeners: {
                        "deskChanged": function (desk) {
                            console.log(desk);
                            $rootScope.$broadcast("deskChanged", desk);
                            $rootScope.$apply();
                        }
                    },

                    methods: [
                        "joinAsUser",
                        "joinAsMaster",
                        "leave",
                        "setUserCard",
                        "setDeskState"
                    ],

                    //transport: ["longPolling"],
                    queryParams: { "api": "1.0" },
                    errorHandler: function(error) {
                        console.error(error);
                        $rootScope.$broadcast("deskHubConnectionState", "error");
                        $rootScope.$apply();
                    },

                    stateChanged: function(state) {
                        connected = false;
                        console.info(state);
                        switch (state.newState) {
                            case $.signalR.connectionState.connecting:
                                $rootScope.$broadcast("deskHubConnectionState", "connecting");
                                break;
                            case $.signalR.connectionState.connected:
                                connected = true;
                                $rootScope.$broadcast("deskHubConnectionState", "connected");
                                $rootScope.$apply();
                                break;
                            case $.signalR.connectionState.reconnecting:
                                $rootScope.$broadcast("deskHubConnectionState", "reconnecting");
                                $rootScope.$apply();
                                break;
                            case $.signalR.connectionState.disconnected:
                                $rootScope.$broadcast("deskHubConnectionState", "disconnected");
                                $rootScope.$apply();
                                break;
                        }
                    }
                });

                return {

                    //WebAPI methods

                    createDesk: function (cards) {
                        return $http.put("api/1.0/desk/", cards).then(function (response) {
                            return response.data;
                        });
                    },

                    deleteDesk: function (deskName) {
                        return $http.delete("api/1.0/desk/" + deskName).then(function (response) {
                            return response.data;
                        });
                    },

                    getDesk: function (deskName) {
                        return $http.get("api/1.0/desk/" + deskName).then(function (response) {
                            return response.data;
                        });
                    },

                    //Hub methods

                    joinAsUser: function (deskName, userName) {
                        return $q.when(deskHub.joinAsUser(deskName, userName));
                    },

                    joinAsMaster: function (deskName) {
                        return $q.when(deskHub.joinAsMaster(deskName));
                    },

                    leave: function (deskName) {
                        return $q.when(deskHub.leave(deskName));
                    },

                    setUserCard: function (deskName, userName, card) {
                        return $q.when(deskHub.setUserCard(deskName, userName, card));
                    },

                    setDeskState: function (deskName, newState) {
                        return $q.when(deskHub.setDeskState(deskName, newState));
                    },

                    hasConnection: function () {
                        return connected;
                    },

                    reconnect: function() {
                        $timeout(function () {
                            deskHub.connect();
                        }, 2000);

                    }

                };
            }
        ]);

})();<|endoftext|>


<commit_before>'use strict';

/**
 * Simple timeout function checking for
 * a) failed login
 * b) successful loaded
 */
function checkStatus() {
    let err    = document.querySelector('p.main-error');
    let loaded = document.querySelector('a[title="New Post"]');

    if (err && ((err.childElementCount && err.childElementCount > 0) || (err.textContent && err.textContent.length > 0))) {
        // Noooo, login errors!
        console.log(`login-error`);
    } else if (loaded) {
        // Yay, successfully loaded - let's give the renderer 200 more ms
        // for rendering
        setTimeout(() => console.log('loaded'), 200);
    } else {
        setTimeout(checkStatus, 100);
    }
}

/**
 * We defer to the actual click on the login button
 * before we check whether or not the login actually
 * succeeded
 */
function init() {
    const element = document.querySelector('button.login');

    if (element) {
        element.off('click');
        element.on('click', () => {
            console.log('login-check-again');
            setTimeout(checkStatus, 100);
        });
    } else {
        setTimeout(init, 100);
    }
}

/**
 * Init
 */
setTimeout(init, 100);<commit_msg>:wrench: Fix login issues<commit_after>'use strict';

/**
 * Simple timeout function checking for
 * a) failed login
 * b) successful loaded
 */
function checkStatus() {
    let err    = document.querySelector('p.main-error');
    let loaded = document.querySelector('a[title="New Post"]');

    if (err && ((err.childElementCount && err.childElementCount > 0) || (err.textContent && err.textContent.length > 0))) {
        // Noooo, login errors!
        console.log(`login-error`);
    } else if (loaded) {
        // Yay, successfully loaded - let's give the renderer 200 more ms
        // for rendering
        setTimeout(() => console.log('loaded'), 200);
    } else {
        setTimeout(checkStatus, 100);
    }
}

/**
 * We defer to the actual click on the login button
 * before we check whether or not the login actually
 * succeeded
 */
function init() {
    const element = document.querySelector('button.login');
    const $element = (window.$) ? window.$(element) : null;
    const clickHandler = () => {
        console.log('login-check-again');
        setTimeout(checkStatus, 100);
    };

    if ($element) {
        $element.off('click');
        $element.on('click', clickHandler);
    } else if (element) {
        element.removeEventListener('click', clickHandler);
        element.addEventListener('click', clickHandler);
    } else {
        setTimeout(init, 100);
    }
}

/**
 * Init
 */
setTimeout(init, 100);
<|endoftext|>


<commit_before>var acorn;
var ps;

var buttonDown = false;
var zoomed = -50;

var rot =[0,0];
var curCoords = [0,0];

/*window.onresize = function(){
  ps.resize(window.innerWidth/2, window.innerHeight/2);
  ps.background([0,0,0,1]);
  ps.pointSize(5);
};*/

function addPNG(){
  var img = document.createElement('img');
  img.setAttribute("width", "100");
  document.getElementById('thumbnails').appendChild(img);
  img.src = ps.getPNG();
}

/*
  Remove all screenshots
*/
function clearPNG(){
  var test = document.getElementById('thumbnails');

  while(test.childNodes){
    test.removeChild(test.childNodes[0]);
  }
}

function zoom(amt){
  var invert = document.getElementById('invertScroll').checked ? -1: 1;
  zoomed += amt * 2 * invert;
  if(buttonDown){
    addPNG();
  }
}

function mousePressed(){
  curCoords[0] = ps.mouseX;
  curCoords[1] = ps.mouseY;
  buttonDown = true;
}

function mouseReleased(){
  buttonDown = false;
}

function keyDown(){
  document.getElementById('key').innerHTML = key;
  ps.println(key);
}

function render() {

  var deltaX = ps.mouseX - curCoords[0];
  var deltaY = ps.mouseY - curCoords[1];

  if(buttonDown){
    rot[0] += deltaX / ps.width * 5;
    rot[1] += deltaY / ps.height * 5;

    curCoords[0] = ps.mouseX;
    curCoords[1] = ps.mouseY;
  }

  // transform point cloud
  ps.translate(0,0,zoomed);

  ps.rotateY(rot[0]);
  ps.rotateX(rot[1]);

  var c = acorn.getCenter();
  ps.translate(-c[0],-c[1],-c[2]);

  // redraw
  ps.clear();
  ps.render();

  var status = document.getElementById('fileStatus');
  switch(acorn.status){
    case 1: status.innerHTML = "status: STARTED";break;
    case 2: status.innerHTML = "status: STREAMING";break;
    case 3: status.innerHTML = "status: COMPLETE";break;
    default:break;
  }

  var fps = Math.floor(ps.frameRate);
  if(fps < 1){
    fps = "< 1";
  }

  status.innerHTML += "
" + acorn.getPointCount() + " points @ " + fps + " FPS";
}

function start(){
  ps = new PointStream();
  document.getElementById('debug').innerHTML += "XB PointStream Version: " + ps.getVersion();

  ps.setup(document.getElementById('canvas'), render);

  ps.background([0,0,0,0.5]);
  ps.pointSize(5);

  ps.onMouseScroll = zoom;
  ps.onMousePressed = mousePressed;
  ps.onMouseReleased = mouseReleased;
  ps.keyDown = keyDown;

  acorn = ps.loadFile({path:"acorn.asc"});
}
<commit_msg>added fix for patch<commit_after>var acorn;
var ps;

var buttonDown = false;
var zoomed = -50;

var rot =[0,0];
var curCoords = [0,0];

/*window.onresize = function(){
  ps.resize(window.innerWidth/2, window.innerHeight/2);
  ps.background([0,0,0,1]);
  ps.pointSize(5);
};*/

function addPNG(){
  var img = document.createElement('img');
  img.setAttribute("width", "100");
  document.getElementById('thumbnails').appendChild(img);
  img.src = ps.getPNG();
}

/*
  Remove all screenshots
*/
function clearPNG(){
  var thumbnails = document.getElementById('thumbnails');

  while(thumbnails.childNodes.length > 0){
    thumbnails.removeChild(thumbnails.childNodes[0]);
  }
}

function zoom(amt){
  var invert = document.getElementById('invertScroll').checked ? -1: 1;
  zoomed += amt * 2 * invert;
  if(buttonDown){
    addPNG();
  }
}

function mousePressed(){
  curCoords[0] = ps.mouseX;
  curCoords[1] = ps.mouseY;
  buttonDown = true;
}

function mouseReleased(){
  buttonDown = false;
}

function keyDown(){
  document.getElementById('key').innerHTML = key;
  ps.println(key);
}

function render() {

  var deltaX = ps.mouseX - curCoords[0];
  var deltaY = ps.mouseY - curCoords[1];

  if(buttonDown){
    rot[0] += deltaX / ps.width * 5;
    rot[1] += deltaY / ps.height * 5;

    curCoords[0] = ps.mouseX;
    curCoords[1] = ps.mouseY;
  }

  // transform point cloud
  ps.translate(0,0,zoomed);

  ps.rotateY(rot[0]);
  ps.rotateX(rot[1]);

  var c = acorn.getCenter();
  ps.translate(-c[0],-c[1],-c[2]);

  // redraw
  ps.clear();
  ps.render();

  var status = document.getElementById('fileStatus');
  switch(acorn.status){
    case 1: status.innerHTML = "status: STARTED";break;
    case 2: status.innerHTML = "status: STREAMING";break;
    case 3: status.innerHTML = "status: COMPLETE";break;
    default:break;
  }

  var fps = Math.floor(ps.frameRate);
  if(fps < 1){
    fps = "< 1";
  }

  status.innerHTML += "
" + acorn.getPointCount() + " points @ " + fps + " FPS";
}

function start(){
  ps = new PointStream();
  document.getElementById('debug').innerHTML += "XB PointStream Version: " + ps.getVersion();

  ps.setup(document.getElementById('canvas'), render);

  ps.background([0,0,0,0.5]);
  ps.pointSize(5);

  ps.onMouseScroll = zoom;
  ps.onMousePressed = mousePressed;
  ps.onMouseReleased = mouseReleased;
  ps.keyDown = keyDown;

  acorn = ps.loadFile({path:"acorn.asc"});
}
<|endoftext|>


<commit_before>export default function (gulp, rootPath) {
  const fs = require('fs');
  const rimraf = require('rimraf');
  const mkdirp = require('mkdirp');
  const R = require('ramda');
  const Promise = require('songbird');
  const childProcess = require('child_process');

  const REPOS_CACHE = `${rootPath}/.projects-cache.json`;
  const REPOS_DIR = `${rootPath}/repos`;

  function loadReposFromGitHub() {
    const request = require('request');

    const opts = {
      url: 'https://api.github.com/orgs/syntaxhighlighter/repos?per_page=300',
      json: true,
      headers: { 'User-Agent': 'node.js' },
    };

    return new Promise((resolve, reject) =>
      request(opts, (err, response) => {
        if (err) return reject(err);
        const json = response.body;
        fs.writeFile(REPOS_CACHE, JSON.stringify(json, null, 2));
        resolve(json);
      })
    );
  }

  const exec = (cmd, opts) =>
    Promise.resolve(cmd)
      .then(console.log)
      .then(() => childProcess.exec.promise(cmd, opts))
      .catch(err => { throw new Error(err.message + '\n\n' + cmd) });

  const git = (cmd, cwd) => exec(`git ${cmd}`, {cwd});
  const loadReposFromCache = () => fs.readFile.promise(REPOS_CACHE, 'utf8').then(JSON.parse);
  const loadRepos = () => loadReposFromCache().error(loadReposFromGitHub).then(R.map(R.pick(['ssh_url', 'name'])));
  const cloneRepo = repo => git(`clone '${repo.ssh_url}'`, REPOS_DIR);
  const pathToRepo = repo => `${REPOS_DIR}/${repo.name}`;
  const ln = (source, dest) => rimraf.promise(dest).finally(() => exec(`ln -s ${source} ${dest} || true`));
  const linkNodeModulesIntoRepos = repo => ln(`${rootPath}/node_modules`, `${pathToRepo(repo)}/node_modules`);
  const linkReposIntoNodeModules = repo => ln(pathToRepo(repo), `${rootPath}/node_modules/${repo.name}`);

  gulp.task('setup-project:clone-repos', 'Clones all repositories from SyntaxHighlighter GitHub organization', () =>
    loadRepos()
      .then(R.filter(repo => !fs.existsSync(pathToRepo(repo))))
      .then(R.filter(repo => repo.name !== 'syntaxhighlighter'))
      .then(R.map(R.curry(cloneRepo)))
      .then(Promise.all)
  );

  gulp.task('setup-project:link-node_modules-into-repos', 'Links `./node_modules` into every clonned repository', ['setup-project:clone-repos'], () =>
    loadRepos()
      .then(R.filter(repo => repo.name !== 'syntaxhighlighter'))
      .then(R.map(R.curry(linkNodeModulesIntoRepos)))
      .then(Promise.all)
  );

  gulp.task('setup-project:link-repos-into-node_modules', 'Links every clonned repository into `./node_modules`', ['setup-project:clone-repos'], () =>
    loadRepos()
      .then(R.filter(repo => repo.name !== 'syntaxhighlighter'))
      .then(R.map(R.curry(linkReposIntoNodeModules)))
      .then(Promise.all)
  );

  gulp.task(
    'setup-project',
    'Sets up project for development. RUN THIS FIRST!',
    [
      'setup-project:clone-repos',
      'setup-project:link-node_modules-into-repos',
      'setup-project:link-repos-into-node_modules'
    ]
  );
}
<commit_msg>Adds `gulp setup-project:unlink-repos-from-node_modules` command<commit_after>export default function (gulp, rootPath) {
  const fs = require('fs');
  const rimraf = require('rimraf');
  const mkdirp = require('mkdirp');
  const R = require('ramda');
  const Promise = require('songbird');
  const childProcess = require('child_process');

  const REPOS_CACHE = `${rootPath}/.projects-cache.json`;
  const REPOS_DIR = `${rootPath}/repos`;

  function loadReposFromGitHub() {
    const request = require('request');

    const opts = {
      url: 'https://api.github.com/orgs/syntaxhighlighter/repos?per_page=300',
      json: true,
      headers: { 'User-Agent': 'node.js' },
    };

    return new Promise((resolve, reject) =>
      request(opts, (err, response) => {
        if (err) return reject(err);
        const json = response.body;
        fs.writeFile(REPOS_CACHE, JSON.stringify(json, null, 2));
        resolve(json);
      })
    );
  }

  const exec = (cmd, opts) =>
    Promise.resolve(cmd)
      .then(console.log)
      .then(() => childProcess.exec.promise(cmd, opts))
      .catch(err => { throw new Error(err.message + '\n\n' + cmd) });

  const git = (cmd, cwd) => exec(`git ${cmd}`, {cwd});
  const loadReposFromCache = () => fs.readFile.promise(REPOS_CACHE, 'utf8').then(JSON.parse);
  const loadRepos = () => loadReposFromCache().error(loadReposFromGitHub).then(R.map(R.pick(['ssh_url', 'name'])));
  const cloneRepo = repo => git(`clone '${repo.ssh_url}'`, REPOS_DIR);
  const pathToRepo = repo => `${REPOS_DIR}/${repo.name}`;
  const ln = (source, dest) => rimraf.promise(dest).finally(() => exec(`ln -s ${source} ${dest} || true`));
  const linkNodeModulesIntoRepos = repo => ln(`${rootPath}/node_modules`, `${pathToRepo(repo)}/node_modules`);
  const linkReposIntoNodeModules = repo => ln(pathToRepo(repo), `${rootPath}/node_modules/${repo.name}`);
  const unlinkReposFromNodeModules = repo => fs.promise.unlink(`${rootPath}/node_modules/${repo.name}`);

  gulp.task('setup-project:clone-repos', 'Clones all repositories from SyntaxHighlighter GitHub organization', () =>
    loadRepos()
      .then(R.filter(repo => !fs.existsSync(pathToRepo(repo))))
      .then(R.filter(repo => repo.name !== 'syntaxhighlighter'))
      .then(R.map(R.curry(cloneRepo)))
      .then(Promise.all)
  );

  gulp.task('setup-project:link-node_modules-into-repos', 'Links `./node_modules` into every clonned repository', ['setup-project:clone-repos'], () =>
    loadRepos()
      .then(R.filter(repo => repo.name !== 'syntaxhighlighter'))
      .then(R.map(R.curry(linkNodeModulesIntoRepos)))
      .then(Promise.all)
  );

  gulp.task('setup-project:link-repos-into-node_modules', 'Links every clonned repository into `./node_modules`', ['setup-project:clone-repos'], () =>
    loadRepos()
      .then(R.filter(repo => repo.name !== 'syntaxhighlighter'))
      .then(R.map(R.curry(linkReposIntoNodeModules)))
      .then(Promise.all)
  );

  gulp.task('setup-project:unlink-repos-from-node_modules', 'Unlinks every clonned repository from `./node_modules`', () =>
    loadRepos()
      .then(R.filter(repo => repo.name !== 'syntaxhighlighter'))
      .then(R.map(R.curry(unlinkReposFromNodeModules)))
      .then(Promise.all)
  );

  gulp.task(
    'setup-project',
    'Sets up project for development. RUN THIS FIRST!',
    [
      'setup-project:clone-repos',
      'setup-project:link-node_modules-into-repos',
      'setup-project:link-repos-into-node_modules'
    ]
  );
}
<|endoftext|>


<commit_before>/**
 * Created by anonymoussc on 23/11/15 23:46.
 */

'use strict';

angular
    .module('app.controllers')
    .controller('LayoutCtrl', function($scope, $timeout, $mdSidenav, $log) {
        $scope.toggleLeft = buildDelayedToggler('left');
        $scope.toggleRight = buildToggler('right');
        $scope.isOpenRight = function(){
            return $mdSidenav('right').isOpen();
        };
        /**
         * Supplies a function that will continue to operate until the
         * time is up.
         */
        function debounce(func, wait, context) {
            var timer;
            return function debounced() {
                var context = $scope,
                    args = Array.prototype.slice.call(arguments);
                $timeout.cancel(timer);
                timer = $timeout(function() {
                    timer = undefined;
                    func.apply(context, args);
                }, wait || 10);
            };
        }
        /**
         * Build handler to open/close a SideNav; when animation finishes
         * report completion in console
         */
        function buildDelayedToggler(navID) {
            return debounce(function() {
                $mdSidenav(navID)
                    .toggle()
                    .then(function() {
                        $log.debug("toggle " + navID + " is done");
                    });
            }, 200);
        }
        function buildToggler(navID) {
            return function() {
                $mdSidenav(navID)
                    .toggle()
                    .then(function() {
                        $log.debug("toggle " + navID + " is done");
                    });
            };
        }
    });<commit_msg>Update layout.js<commit_after>/**
 * Created by anonymoussc on 23/11/15 23:46.
 */

(function() {
    'use strict';

    angular
        .module('app.controllers')
        .controller('LayoutCtrl', function($scope, $timeout, $mdSidenav, $log) {
            $scope.toggleLeft  = buildDelayedToggler('left');
            $scope.toggleRight = buildToggler('right');
            $scope.isOpenRight = function() {
                return $mdSidenav('right').isOpen();
            };

            /**
             * Supplies a function that will continue to operate until the
             * time is up.
             */
            function debounce(func, wait, context) {
                var timer;
                return function debounced() {
                    var context = $scope,
                        args    = Array.prototype.slice.call(arguments);
                    $timeout.cancel(timer);
                    timer       = $timeout(function() {
                        timer = undefined;
                        func.apply(context, args);
                    }, wait || 10);
                };
            }

            /**
             * Build handler to open/close a SideNav; when animation finishes
             * report completion in console
             */
            function buildDelayedToggler(navID) {
                return debounce(function() {
                    $mdSidenav(navID)
                        .toggle()
                        .then(function() {
                            $log.debug("toggle " + navID + " is done");
                        });
                }, 200);
            }

            function buildToggler(navID) {
                return function() {
                    $mdSidenav(navID)
                        .toggle()
                        .then(function() {
                            $log.debug("toggle " + navID + " is done");
                        });
                };
            }
        });

})();

<|endoftext|>


<commit_before>frappe.ui.form.ControlCode = frappe.ui.form.ControlText.extend({
	make_input() {
		if (this.editor) return;
		this.load_lib().then(() => this.make_ace_editor());
	},

	make_ace_editor() {
		if (this.editor) return;
		this.ace_editor_target = $('

')
			.appendTo(this.input_area);

		this.expanded = false;
		this.$expand_button = $(`<button class="btn btn-xs btn-default">${__('Expand')}</button>`).click(() => {
			this.expanded = !this.expanded;
			this.refresh_height();
			this.toggle_label();
		}).appendTo(this.$input_wrapper);
		// styling
		this.ace_editor_target.addClass('border rounded');
		this.ace_editor_target.css('height', 300);

		// initialize
		const ace = window.ace;
		this.editor = ace.edit(this.ace_editor_target.get(0));
		this.editor.setTheme('ace/theme/tomorrow');
		this.set_language();

		// events
		this.editor.session.on('change', frappe.utils.debounce(() => {
			const input_value = this.get_input_value();
			this.parse_validate_and_set_in_model(input_value);
		}, 300));
	},

	refresh_height() {
		this.ace_editor_target.css('height', this.expanded ? 600 : 300);
		this.editor.resize();
	},

	toggle_label() {
		const button_label = this.expanded ? __('Collapse') : __('Expand');
		this.$expand_button && this.$expand_button.text(button_label);
	},

	set_language() {
		const language_map = {
			'Javascript': 'ace/mode/javascript',
			'JS': 'ace/mode/javascript',
			'Python': 'ace/mode/python',
			'Py': 'ace/mode/python',
			'HTML': 'ace/mode/html',
			'CSS': 'ace/mode/css',
			'Markdown': 'ace/mode/markdown',
			'SCSS': 'ace/mode/scss',
			'JSON': 'ace/mode/json',
			'Golang': 'ace/mode/golang',
			'Go': 'ace/mode/golang'
		};
		const language = this.df.options;

		const valid_languages = Object.keys(language_map);
		if (language && !valid_languages.includes(language)) {
			// eslint-disable-next-line
			console.warn(`Invalid language option provided for field "${this.df.label}". Valid options are ${valid_languages.join(', ')}.`);
		}

		const ace_language_mode = language_map[language] || '';
		this.editor.session.setMode(ace_language_mode);
		this.editor.setKeyboardHandler('ace/keyboard/vscode');
	},

	parse(value) {
		if (value == null) {
			value = "";
		}
		return value;
	},

	set_formatted_input(value) {
		return this.load_lib().then(() => {
			if (!this.editor) return;
			if (!value) value = '';
			if (value === this.get_input_value()) return;
			this.editor.session.setValue(value);
		});
	},

	get_input_value() {
		return this.editor ? this.editor.session.getValue() : '';
	},

	load_lib() {
		if (this.library_loaded) return this.library_loaded;

		if (frappe.boot.developer_mode) {
			this.root_lib_path = '/assets/frappe/node_modules/ace-builds/src-noconflict/';
		} else {
			this.root_lib_path = '/assets/frappe/node_modules/ace-builds/src-min-noconflict/';
		}

		this.library_loaded = new Promise(resolve => {
			frappe.require(this.root_lib_path + 'ace.js', () => {
				window.ace.config.set('basePath', this.root_lib_path);
				resolve();
			});
		});

		return this.library_loaded;
	}
});
<commit_msg>fix: disable print margin in ace editor<commit_after>frappe.ui.form.ControlCode = frappe.ui.form.ControlText.extend({
	make_input() {
		if (this.editor) return;
		this.load_lib().then(() => this.make_ace_editor());
	},

	make_ace_editor() {
		if (this.editor) return;
		this.ace_editor_target = $('

')
			.appendTo(this.input_area);

		this.expanded = false;
		this.$expand_button = $(`<button class="btn btn-xs btn-default">${__('Expand')}</button>`).click(() => {
			this.expanded = !this.expanded;
			this.refresh_height();
			this.toggle_label();
		}).appendTo(this.$input_wrapper);
		// styling
		this.ace_editor_target.addClass('border rounded');
		this.ace_editor_target.css('height', 300);

		// initialize
		const ace = window.ace;
		this.editor = ace.edit(this.ace_editor_target.get(0));
		this.editor.setTheme('ace/theme/tomorrow');
		this.editor.setOption("showPrintMargin", false)
		this.set_language();

		// events
		this.editor.session.on('change', frappe.utils.debounce(() => {
			const input_value = this.get_input_value();
			this.parse_validate_and_set_in_model(input_value);
		}, 300));
	},

	refresh_height() {
		this.ace_editor_target.css('height', this.expanded ? 600 : 300);
		this.editor.resize();
	},

	toggle_label() {
		const button_label = this.expanded ? __('Collapse') : __('Expand');
		this.$expand_button && this.$expand_button.text(button_label);
	},

	set_language() {
		const language_map = {
			'Javascript': 'ace/mode/javascript',
			'JS': 'ace/mode/javascript',
			'Python': 'ace/mode/python',
			'Py': 'ace/mode/python',
			'HTML': 'ace/mode/html',
			'CSS': 'ace/mode/css',
			'Markdown': 'ace/mode/markdown',
			'SCSS': 'ace/mode/scss',
			'JSON': 'ace/mode/json',
			'Golang': 'ace/mode/golang',
			'Go': 'ace/mode/golang'
		};
		const language = this.df.options;

		const valid_languages = Object.keys(language_map);
		if (language && !valid_languages.includes(language)) {
			// eslint-disable-next-line
			console.warn(`Invalid language option provided for field "${this.df.label}". Valid options are ${valid_languages.join(', ')}.`);
		}

		const ace_language_mode = language_map[language] || '';
		this.editor.session.setMode(ace_language_mode);
		this.editor.setKeyboardHandler('ace/keyboard/vscode');
	},

	parse(value) {
		if (value == null) {
			value = "";
		}
		return value;
	},

	set_formatted_input(value) {
		return this.load_lib().then(() => {
			if (!this.editor) return;
			if (!value) value = '';
			if (value === this.get_input_value()) return;
			this.editor.session.setValue(value);
		});
	},

	get_input_value() {
		return this.editor ? this.editor.session.getValue() : '';
	},

	load_lib() {
		if (this.library_loaded) return this.library_loaded;

		if (frappe.boot.developer_mode) {
			this.root_lib_path = '/assets/frappe/node_modules/ace-builds/src-noconflict/';
		} else {
			this.root_lib_path = '/assets/frappe/node_modules/ace-builds/src-min-noconflict/';
		}

		this.library_loaded = new Promise(resolve => {
			frappe.require(this.root_lib_path + 'ace.js', () => {
				window.ace.config.set('basePath', this.root_lib_path);
				resolve();
			});
		});

		return this.library_loaded;
	}
});
<|endoftext|>