<commit_before>//= require ./extensor

"use strict";

var
    esPhinx,
    Extensor,
    Enumerator;

// IIFE
esPhinx = (function () {

    return function esPhinx (selector, context) {

        var
            Constructor = esPhinx,
            self = this,
            collection;

        if (!(this instanceof Constructor)) {
            return new Constructor(selector, context);
        }

        if (context) {
            if (typeof context === "string") {
                // recursivity
                context = esPhinx(context).first();
            } else if (context instanceof $) {
                context = context.first();
            } else if (!context instanceof Node) {
                throw new Error("An invalid or illegal context was specified.");
            }
        } else {
            context = document;
        }

        if (selector) {
            // recognize tagName
            // ([^<][^ >]+)
            // attributes = selector.match(/[^< ]+[\=]+[^ >]+)|([^< ]+[^ >]/g)
            // get children "".match(/(?:>)(<.+(?=(<\/)))/)[0]
            if (typeof selector === "string") {
                if (/^(?:<)(.+)/.test(selector)) {
                    collection = Array.from((new DOMParser())
                        .parseFromString(selector, "text/html").body
                            .childNodes);
                } else {
                    collection = Array.from(context.querySelectorAll(selector));
                }
            } else if (typeof selector === "function") {
                return esPhinx(context).on("DOMContentLoaded", selector);
            } else if (selector instanceof Node) {
                collection = Array.prototype.slice.call([selector]);
            } else if (selector instanceof esPhinx) {
                return selector;
            } else if (selector instanceof Object) {
                Enumerator.each(selector, function (v, i) {
                    self[i] = v;
                });
                return self;
            }

            collection.forEach(function (value, attr) {
                self[attr] = value;
            });

            Object.defineProperties(self, {
                length: {
                    value: collection.length
                },
                splice: {
                    value: Array.prototype.splice
                },
                [Symbol.iterator]: {
                    value: Array.prototype[Symbol.iterator]
                }
            });

        }

        return self;
    };
}());

(function ($module) {

    Extensor.new($module, {
        extend: function () {
            Extensor.new(this, arguments[0]);
        }
    });

})(esPhinx);

(function ($) {

    $.extend({

        type: function (object) {
            return /[^ ]+(?=\])/g.exec($.prototype.toString.call(object))[0];
        },

        merge: function () {
            var
                self = arguments[0],
                args = Array.from(arguments),
                merged = {},
                i;

            Enumerator.each(self, function (v, i) {
                merged[i] = v;
            });

            for(i = 1; i < args.length; i++) {
                if (args[i] instanceof Object) {
                    Enumerator.each(args[i], function (v, i) {
                        merged[i] = v;
                    });
                }
            }

            return merged;
        }

    });

}(esPhinx));
<commit_msg>improves main<commit_after>//= require ./extensor

"use strict";

var
    esPhinx,
    Extensor,
    Enumerator;

// IIFE
esPhinx = (function () {

    return function esPhinx (selector, context) {

        var
            Constructor = esPhinx,
            self = this,
            length = 0,
            collection;

        if (!(this instanceof Constructor)) {
            return new Constructor(selector, context);
        }

        if (context) {
            if (typeof context === "string") {
                // recursivity
                context = esPhinx(context).first();
            } else if (context instanceof $) {
                context = context.first();
            } else if (!context instanceof Node) {
                throw new Error("An invalid or illegal context was specified.");
            }
        } else {
            context = document;
        }

        if (selector) {
            // recognize tagName
            // ([^<][^ >]+)
            // attributes = selector.match(/[^< ]+[\=]+[^ >]+)|([^< ]+[^ >]/g)
            // get children "".match(/(?:>)(<.+(?=(<\/)))/)[0]
            if (typeof selector === "string") {
                if (/^(?:<)(.+)/.test(selector)) {
                    collection = Array.from((new DOMParser())
                        .parseFromString(selector, "text/html").body
                            .childNodes);
                } else {
                    collection = Array.from(context.querySelectorAll(selector));
                }
            } else if (typeof selector === "function") {
                return esPhinx(context).on("DOMContentLoaded", selector);
            } else if (selector instanceof Node) {
                collection = Array.prototype.slice.call([selector]);
            } else if (selector instanceof esPhinx) {
                return selector;
            } else if (selector instanceof Object) {
                Enumerator.each(selector, function (v, i) {
                    self[i] = v;
                    length += 1;
                });
            }

            if (collection) {
                collection.forEach(function (value, attr) {
                    self[attr] = value;
                });
                length = collection.length;
            }

            Object.defineProperties(self, {
                length: {
                    value: length
                },
                splice: {
                    value: Array.prototype.splice
                },
                [Symbol.iterator]: {
                    value: Array.prototype[Symbol.iterator]
                }
            });

        }

        return self;
    };
}());

(function ($module) {

    Extensor.new($module, {
        extend: function () {
            Extensor.new(this, arguments[0]);
        }
    });

})(esPhinx);

(function ($) {

    $.extend({

        type: function (object) {
            return /[^ ]+(?=\])/g.exec($.prototype.toString.call(object))[0];
        },

        merge: function () {
            var
                self = arguments[0],
                args = Array.from(arguments),
                merged = {},
                i;

            Enumerator.each(self, function (v, i) {
                merged[i] = v;
            });

            for(i = 1; i < args.length; i++) {
                if (args[i] instanceof Object) {
                    Enumerator.each(args[i], function (v, i) {
                        merged[i] = v;
                    });
                }
            }

            return merged;
        }

    });

}(esPhinx));
<|endoftext|>


<commit_before>
import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
import { Link } from 'react-router'
import { createStore, bindActionCreators } from 'redux'
import ReactGA from 'react-ga'

import FontAwesome from 'react-fontawesome'
import Thumbnail from './Thumbnail'

import * as uiActions from '../services/ui/actions'
import * as spotifyActions from '../services/spotify/actions'

class SpotifyAuthenticationFrame extends React.Component{

	constructor(props) {
		super(props);

		this.state = {
			frameUrl: 'https://jamesbarnsley.co.nz/auth.php?action=frame',
			authorizing: false
		}
	}

	componentDidMount(){

		let self = this;

		// listen for incoming messages from the authorization iframe
		// this is triggered when authentication is granted from the popup
		window.addEventListener('message', function(event){

			if(event.data == 'closed'){
				self.setState({
					frameUrl: 'https://jamesbarnsley.co.nz/auth.php?action=frame',
					authorizing: false
				})
			}else if(event.data == 'blocked'){
				self.props.uiActions.createNotification('Popup blocked. Please allow popups and try again.','bad')
			}else{

				// only allow incoming data from our authorized authenticator proxy
				if( !/^https?:\/\/jamesbarnsley\.co\.nz/.test(event.origin) ) return false;

				var data = JSON.parse(event.data);
				self.props.spotifyActions.authorizationGranted( data );
				self.props.spotifyActions.getMe();

				// and turn off our authorizing switch
				self.setState({
					frameUrl: 'https://jamesbarnsley.co.nz/auth.php?action=frame',
					authorizing: false
				})
			}

		}, false);
	}

	startAuthorization(){
		this.setState({
			frameUrl: 'https://jamesbarnsley.co.nz/auth.php?action=authorize&app='+location.protocol+'//'+window.location.host,
			authorizing: true
		})
	}

	renderAuthorizeButton(){
		if( this.state.authorizing ){
			return (
				<button disabled>
					<FontAwesome name="circle-o-notch" spin />

					Authorizing...
				</button>
			);
		}else if( this.props.authorized ){
			return (
				<button className="destructive" onClick={() => this.props.spotifyActions.authorizationRevoked()}>Log out</button>
			);
		}else{
			return (
				<button className="primary" onClick={() => this.startAuthorization()}>Log in</button>
			);
		}
	}

	renderRefreshButton(){
		if( !this.props.authorized || !window._testMode) return null;

		if( this.props.refreshing_token ){
			return (
				<button disabled>
					<FontAwesome name="circle-o-notch" spin />

					Refreshing...
				</button>
			);
		}else{
			return (
				<button onClick={() => this.props.spotifyActions.refreshingToken()}>Refresh token</button>
			);
		}
	}

	render(){
		return (

				{ this.renderAuthorizeButton() }
				{ this.renderRefreshButton() }

		);
	}
}

const mapStateToProps = (state, ownProps) => {
	return {
		authorized: state.spotify.authorized,
		authorizing: state.spotify.authorizing,
		refreshing_token: state.spotify.refreshing_token
	}
}

const mapDispatchToProps = (dispatch) => {
	return {
		uiActions: bindActionCreators(uiActions, dispatch),
		spotifyActions: bindActionCreators(spotifyActions, dispatch)
	}
}

export default connect(mapStateToProps, mapDispatchToProps)(SpotifyAuthenticationFrame)<commit_msg>Show force refresh token even when not in _test<commit_after>
import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
import { Link } from 'react-router'
import { createStore, bindActionCreators } from 'redux'
import ReactGA from 'react-ga'

import FontAwesome from 'react-fontawesome'
import Thumbnail from './Thumbnail'

import * as uiActions from '../services/ui/actions'
import * as spotifyActions from '../services/spotify/actions'

class SpotifyAuthenticationFrame extends React.Component{

	constructor(props) {
		super(props);

		this.state = {
			frameUrl: 'https://jamesbarnsley.co.nz/auth.php?action=frame',
			authorizing: false
		}
	}

	componentDidMount(){

		let self = this;

		// listen for incoming messages from the authorization iframe
		// this is triggered when authentication is granted from the popup
		window.addEventListener('message', function(event){

			if(event.data == 'closed'){
				self.setState({
					frameUrl: 'https://jamesbarnsley.co.nz/auth.php?action=frame',
					authorizing: false
				})
			}else if(event.data == 'blocked'){
				self.props.uiActions.createNotification('Popup blocked. Please allow popups and try again.','bad')
			}else{

				// only allow incoming data from our authorized authenticator proxy
				if( !/^https?:\/\/jamesbarnsley\.co\.nz/.test(event.origin) ) return false;

				var data = JSON.parse(event.data);
				self.props.spotifyActions.authorizationGranted( data );
				self.props.spotifyActions.getMe();

				// and turn off our authorizing switch
				self.setState({
					frameUrl: 'https://jamesbarnsley.co.nz/auth.php?action=frame',
					authorizing: false
				})
			}

		}, false);
	}

	startAuthorization(){
		this.setState({
			frameUrl: 'https://jamesbarnsley.co.nz/auth.php?action=authorize&app='+location.protocol+'//'+window.location.host,
			authorizing: true
		})
	}

	renderAuthorizeButton(){
		if( this.state.authorizing ){
			return (
				<button disabled>
					<FontAwesome name="circle-o-notch" spin />

					Authorizing...
				</button>
			);
		}else if( this.props.authorized ){
			return (
				<button className="destructive" onClick={() => this.props.spotifyActions.authorizationRevoked()}>Log out</button>
			);
		}else{
			return (
				<button className="primary" onClick={() => this.startAuthorization()}>Log in</button>
			);
		}
	}

	renderRefreshButton(){
		if (!this.props.authorized) return null

		if (this.props.refreshing_token){
			return (
				<button disabled>
					<FontAwesome name="circle-o-notch" spin />

					Refreshing...
				</button>
			);
		} else {
			return (
				<button onClick={() => this.props.spotifyActions.refreshingToken()}>Force token refresh</button>
			)
		}
	}

	render(){
		return (

				{ this.renderAuthorizeButton() }
				{ this.renderRefreshButton() }

		);
	}
}

const mapStateToProps = (state, ownProps) => {
	return {
		authorized: state.spotify.authorized,
		authorizing: state.spotify.authorizing,
		refreshing_token: state.spotify.refreshing_token
	}
}

const mapDispatchToProps = (dispatch) => {
	return {
		uiActions: bindActionCreators(uiActions, dispatch),
		spotifyActions: bindActionCreators(spotifyActions, dispatch)
	}
}

export default connect(mapStateToProps, mapDispatchToProps)(SpotifyAuthenticationFrame)<|endoftext|>


<commit_before>/**
 * Module dependencies
 * @type {configuration|exports|module.exports}
 */
var files = require('../../config/files.js')
  , EventManager = require('../../events/EventManager.js')
  , BufferAdapter = require('../../adapters/BufferAdapter.js')
  , Body = require('../../models/Body.js')
  , _ = require('lodash');

/**
 * Constructor for game Body Data Loader
 * @param game
 * @param storage
 * @constructor
 */
var BinaryBody = function BinaryBody(game, storage) {
  this.game = game;
  this._path = files.bodies;
  this.storage = storage;
  EventManager.eventify(this);
};

/**
 * Performs the load of all bodys binary files
 * @param onLoadCallback
 * @returns {*|Phaser.Loader|{}}
 */
BinaryBody.prototype.load = function(onProcessed, onLoaded) {
  this.addListener('onProcessed', this.onProcessed);
  this.addListener('onProcessed', onProcessed);
  this.addListener('onLoaded', onLoaded);

  return this.game.load.binary('bodies', this._path, this.process, this);
};

/**
 * Processes the loaded data object
 * @param key
 * @param data
 * @returns {*}
 */
BinaryBody.prototype.process = function(key, buffer) {
  var reader = new BufferAdapter(buffer, true);
  var header = reader.skipBytes(Body.HEADER_SIZE);
  var count = reader.getNextInt16();

  for(var i in _.range(1, count)) {
    var body = new Body(i);
    body.loader.load(reader);
    this.fire('onProcessed', [body], this);
  }

  this.fire('onLoaded', [this.storage], this);
  return buffer;
};

/**
 * Callback for processed bodys
 * @param body
 */
BinaryBody.prototype.onProcessed = function(body) {
  this.storage.add(body.grh, body);
};

/**
 * Exports object constructor
 * type {Function}
 */
module.exports = BinaryBody;<commit_msg>Small code clarification fix<commit_after>/**
 * Module dependencies
 * @type {configuration|exports|module.exports}
 */
var files = require('../../config/files.js')
  , EventManager = require('../../events/EventManager.js')
  , BufferAdapter = require('../../adapters/BufferAdapter.js')
  , Body = require('../../models/Body.js')
  , _ = require('lodash');

/**
 * Constructor for game Body Data Loader
 * @param game
 * @param storage
 * @constructor
 */
var BinaryBodyLoader = function BinaryBodyLoader(game, storage) {
  this.game = game;
  this._path = files.bodies;
  this.storage = storage;
  EventManager.eventify(this);
};

/**
 * Performs the load of all bodys binary files
 * @param onLoadCallback
 * @returns {*|Phaser.Loader|{}}
 */
BinaryBodyLoader.prototype.load = function(onProcessed, onLoaded) {
  this.addListener('onProcessed', this.onProcessed);
  this.addListener('onProcessed', onProcessed);
  this.addListener('onLoaded', onLoaded);

  return this.game.load.binary('bodies', this._path, this.process, this);
};

/**
 * Processes the loaded data object
 * @param key
 * @param data
 * @returns {*}
 */
BinaryBodyLoader.prototype.process = function(key, buffer) {
  var reader = new BufferAdapter(buffer, true);
  var header = reader.skipBytes(Body.HEADER_SIZE);
  var count = reader.getNextInt16();

  for(var i in _.range(1, count)) {
    var body = new Body(i);
    body.loader.load(reader);
    this.fire('onProcessed', [body], this);
  }

  this.fire('onLoaded', [this.storage], this);
  return buffer;
};

/**
 * Callback for processed bodys
 * @param body
 */
BinaryBodyLoader.prototype.onProcessed = function(body) {
  this.storage.add(body.grh, body);
};

/**
 * Exports object constructor
 * type {Function}
 */
module.exports = BinaryBodyLoader;<|endoftext|>


<commit_before>var https = require('https'),
    http = require('http'),
    url = require('url'),
    config = require('../config.json'),
    UncachedFixer = require('./UncachedFixer.js').UncachedFixer,
    ZoomLevelFixer = require('./ZoomLevelFixer.js').ZoomLevelFixer;

exports.TileFixerFactory = function() {
    "use strict";
};

exports.TileFixerFactory.createTileMapper = function (url, callback) {
    "use strict";
    exports.TileFixerFactory.getArcGISConfiguration(url, function(err, data) {
        if(err) {
            return callback(err);
        }

        if (data != null && data.tileInfo != null && data.tileInfo.lods != null) {
            //create ZoomLevelFixer
            callback(undefined, new ZoomLevelFixer(url, data.tileInfo));
        } else if (data != null && data.currentVersion != null){
            // create UncachedFixer
            callback(undefined, new UncachedFixer(url));
        } else {
            callback(new Error("Unsupported URL"));
        }
    });
};

exports.TileFixerFactory.getArcGISConfiguration = function (mapserverUrl, callback) {
    "use strict";
    var configUrl = mapserverUrl + '?f=pjson';

    (url.parse(configUrl).protocol === 'https:' ? https : http).get(configUrl, function(res) {
        var body = '';

        res.on('data', function(chunk) {
            body += chunk;
        });

        res.on('end', function() {
            var json;
            try {
                json = JSON.parse(body);
            } catch (e) {
                return callback(e);
            }
            return callback(undefined, json);
        });
    }).on('error', function(e) {
        return callback(e);
    });
};

<commit_msg>JSHINT<commit_after>var https = require('https'),
    http = require('http'),
    url = require('url'),
    UncachedFixer = require('./UncachedFixer.js').UncachedFixer,
    ZoomLevelFixer = require('./ZoomLevelFixer.js').ZoomLevelFixer;

exports.TileFixerFactory = function() {
    "use strict";
};

exports.TileFixerFactory.createTileMapper = function (url, callback) {
    "use strict";
    exports.TileFixerFactory.getArcGISConfiguration(url, function(err, data) {
        if(err) {
            return callback(err);
        }

        if (data != null && data.tileInfo != null && data.tileInfo.lods != null) {
            //create ZoomLevelFixer
            callback(undefined, new ZoomLevelFixer(url, data.tileInfo));
        } else if (data != null && data.currentVersion != null){
            // create UncachedFixer
            callback(undefined, new UncachedFixer(url));
        } else {
            callback(new Error("Unsupported URL"));
        }
    });
};

exports.TileFixerFactory.getArcGISConfiguration = function (mapserverUrl, callback) {
    "use strict";
    var configUrl = mapserverUrl + '?f=pjson';

    (url.parse(configUrl).protocol === 'https:' ? https : http).get(configUrl, function(res) {
        var body = '';

        res.on('data', function(chunk) {
            body += chunk;
        });

        res.on('end', function() {
            var json;
            try {
                json = JSON.parse(body);
            } catch (e) {
                return callback(e);
            }
            return callback(undefined, json);
        });
    }).on('error', function(e) {
        return callback(e);
    });
};

<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Line } from 'react-chartjs-2';

class LineChart extends Component {
  render () {
    const labels = [];
    for (let i = 0; i < 100; i++) {
      labels[i] = '';
    }
    //TODO: create sensible data in ChartModal
    const myData = {
      labels: labels,
      datasets: [{
        data: this.props.data,
        label: this.props.resourceLabel,
        fillColor: 'rgba(163, 68, 93, 0.5)',
				strokeColor: 'rgba(141, 45, 86, 1)',
				pointColor: 'rgba(43, 25, 62, 1)',
        pointRadius: 0,
        borderWidth: 2,
        backgroundColor: 'rgba(163, 68, 93, 0.5)',
        borderColor: 'rgba(141, 45, 86, 1)',
				pointStrokeColor: '#fff'
      }]
    };

    const options = {
      animation: {
        duration: 500,
        easing: 'linear'
      },
      responsive: false,
      legend: {
        display: true,
        labels: {
          fontColor: 'rgba(141, 45, 86, 1)'
        }
        },
      scales: {
        yAxes: [{
          // ticks: {
          //     max: 1,
          //     min: -1
          // }
        }],
        xAxes: [{
          display: false
        }]
      }
    };

    return (

        <Line
          data={myData}
          options={options}
        />

    );
  }
}

LineChart.propTypes = {
  data: PropTypes.array,
  resourceLabel: PropTypes.string,
  sensorLabel: PropTypes.string,
  unit: PropTypes.string
};

export default LineChart;
<commit_msg>Tweak looks of charts<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Line } from 'react-chartjs-2';

class LineChart extends Component {
  render () {
    const labels = [];
    for (let i = 0; i < 100; i++) {
      labels[i] = '';
    }
    //TODO: create sensible data in ChartModal
    const myData = {
      labels: labels,
      datasets: [{
        data: this.props.data,
        label: this.props.resourceLabel,
        fillColor: 'rgba(163, 68, 93, 0.5)',
				strokeColor: 'rgba(141, 45, 86, 1)',
				pointColor: 'rgba(43, 25, 62, 1)',
        pointRadius: 0,
        borderWidth: 2,
        backgroundColor: 'rgba(163, 68, 93, 0.5)',
        borderColor: 'rgba(141, 45, 86, 1)',
				pointStrokeColor: '#fff'
      }]
    };

    const options = {
      animation: {
        duration: 500,
        easing: 'linear'
      },
      responsive: false,
      legend: {
        display: true,
        position: 'top',
        labels: {
          fontColor: 'rgba(141, 45, 86, 1)'
        }
        },
      scales: {
        yAxes: [{
          ticks: {
              max: Math.max(...this.props.data) + 0.5,
              min: Math.min(...this.props.data) - 0.5
          }
        }],
        xAxes: [{
          display: false
        }]
      }
    };

    return (

        <Line
          data={myData}
          options={options}
        />

    );
  }
}

LineChart.propTypes = {
  data: PropTypes.array,
  resourceLabel: PropTypes.string,
  sensorLabel: PropTypes.string,
  unit: PropTypes.string
};

export default LineChart;
<|endoftext|>


<commit_before>'use strict';

var fs     = require('fs');
var path   = require('path');
var Filter = require('broccoli-filter');

function ConfigLoader (inputTree, options) {
  if (!(this instanceof ConfigLoader)) {
    return new ConfigLoader(inputTree, options);
  }

  console.log('starting config loader');
  this.inputTree = inputTree;
  this.options = options || {};
}

ConfigLoader.prototype = Object.create(Filter.prototype);
ConfigLoader.prototype.constructor = ConfigLoader;

ConfigLoader.prototype.extensions = ['js'];
ConfigLoader.prototype.targetExtension = 'js';

ConfigLoader.prototype.processFile = function (srcDir, destDir, relativePath) {
  var outputPath = path.join(destDir, relativePath);
  var configPath = path.join(this.options.project.root, srcDir, relativePath);
  var contents = fs.readFileSync(configPath, {encoding: 'utf8'});
  var wrapperContents = '"use strict";\nvar module = { };\n' + contents + '; return module.exports(env);';
  var configGenerator = new Function('env', wrapperContents);
  var currentConfig = configGenerator(this.options.env);

  var moduleString = 'export default ' + JSON.stringify(currentConfig) + ';';

  fs.writeFileSync(outputPath, moduleString, { encoding: 'utf8' });
};

module.exports = ConfigLoader;
<commit_msg>Remove debugging logging.<commit_after>'use strict';

var fs     = require('fs');
var path   = require('path');
var Filter = require('broccoli-filter');

function ConfigLoader (inputTree, options) {
  if (!(this instanceof ConfigLoader)) {
    return new ConfigLoader(inputTree, options);
  }

  this.inputTree = inputTree;
  this.options = options || {};
}

ConfigLoader.prototype = Object.create(Filter.prototype);
ConfigLoader.prototype.constructor = ConfigLoader;

ConfigLoader.prototype.extensions = ['js'];
ConfigLoader.prototype.targetExtension = 'js';

ConfigLoader.prototype.processFile = function (srcDir, destDir, relativePath) {
  var outputPath = path.join(destDir, relativePath);
  var configPath = path.join(this.options.project.root, srcDir, relativePath);
  var contents = fs.readFileSync(configPath, {encoding: 'utf8'});
  var wrapperContents = '"use strict";\nvar module = { };\n' + contents + '; return module.exports(env);';
  var configGenerator = new Function('env', wrapperContents);
  var currentConfig = configGenerator(this.options.env);

  var moduleString = 'export default ' + JSON.stringify(currentConfig) + ';';

  fs.writeFileSync(outputPath, moduleString, { encoding: 'utf8' });
};

module.exports = ConfigLoader;
<|endoftext|>


<commit_before>'use strict';

const RESERVED_WORDS = {
  JHIPSTER: ['ACCOUNT'],
  JAVA: ['ABSTRACT', 'CONTINUE', 'FOR', 'NEW', 'SWITCH', 'ASSERT', 'DEFAULT', 'GOTO', 'PACKAGE', 'SYNCHRONIZED', 'BOOLEAN', 'DO', 'IF', 'PRIVATE', 'THIS', 'BREAK', 'DOUBLE', 'IMPLEMENTS', 'PROTECTED', 'THROW', 'BYTE', 'ELSE', 'IMPORT', 'PUBLIC', 'THROWS', 'CASE', 'ENUM', 'INSTANCEOF', 'RETURN', 'TRANSIENT', 'CATCH', 'EXTENDS', 'INT', 'SHORT', 'TRY', 'CHAR', 'FINAL', 'INTERFACE', 'STATIC', 'VOID', 'CLASS', 'FINALLY', 'LONG', 'STRICTFP', 'VOLATILE', 'CONST', 'FLOAT', 'NATIVE', 'SUPER', 'WHILE'],
  MYSQL: ['ACCESSIBLE', 'ADD', 'ALL', 'ALTER', 'ANALYZE', 'AND', 'AS', 'ASC', 'ASENSITIVE', 'BEFORE', 'BETWEEN', 'BIGINT', 'BINARY', 'BLOB', 'BOTH', 'BY', 'CALL', 'CASCADE', 'CASE', 'CHANGE', 'CHAR', 'CHARACTER', 'CHECK', 'COLLATE', 'COLUMN', 'CONDITION', 'CONSTRAINT', 'CONTINUE', 'CONVERT', 'CREATE', 'CROSS', 'CURRENT_DATE', 'CURRENT_TIME', 'CURRENT_TIMESTAMP', 'CURRENT_USER', 'CURSOR', 'DATABASE', 'DATABASES', 'DAY_HOUR', 'DAY_MICROSECOND', 'DAY_MINUTE', 'DAY_SECOND', 'DEC', 'DECIMAL', 'DECLARE', 'DEFAULT', 'DELAYED', 'DELETE', 'DESC', 'DESCRIBE', 'DETERMINISTIC', 'DISTINCT', 'DISTINCTROW', 'DIV', 'DOUBLE', 'DROP', 'DUAL', 'EACH', 'ELSE', 'ELSEIF', 'ENCLOSED', 'ESCAPED', 'EXISTS', 'EXIT', 'EXPLAIN', 'FALSE', 'FETCH', 'FLOAT', 'FLOAT4', 'FLOAT8', 'FOR', 'FORCE', 'FOREIGN', 'FROM', 'FULLTEXT', 'GRANT', 'GROUP', 'HAVING', 'HIGH_PRIORITY', 'HOUR_MICROSECOND', 'HOUR_MINUTE', 'HOUR_SECOND', 'IF', 'IGNORE', 'IN', 'INDEX', 'INFILE', 'INNER', 'INOUT', 'INSENSITIVE', 'INSERT', 'INT', 'INT1', 'INT2', 'INT3', 'INT4', 'INT8', 'INTEGER', 'INTERVAL', 'INTO', 'IS', 'ITERATE', 'JOIN', 'KEY', 'KEYS', 'KILL', 'LEADING', 'LEAVE', 'LEFT', 'LIKE', 'LIMIT', 'LINEAR', 'LINES', 'LOAD', 'LOCALTIME', 'LOCALTIMESTAMP', 'LOCK', 'LONG', 'LONGBLOB', 'LONGTEXT', 'LOOP', 'LOW_PRIORITY', 'MASTER_SSL_VERIFY_SERVER_CERT', 'MATCH', 'MAXVALUE', 'MEDIUMBLOB', 'MEDIUMINT', 'MEDIUMTEXT', 'MIDDLEINT', 'MINUTE_MICROSECOND', 'MINUTE_SECOND', 'MOD', 'MODIFIES', 'NATURAL', 'NOT', 'NO_WRITE_TO_BINLOG', 'NULL', 'NUMERIC', 'ON', 'OPTIMIZE', 'OPTION', 'OPTIONALLY', 'OR', 'ORDER', 'OUT', 'OUTER', 'OUTFILE', 'PRECISION', 'PRIMARY', 'PROCEDURE', 'PURGE', 'RANGE', 'READ', 'READS', 'READ_WRITE', 'REAL', 'REFERENCES', 'REGEXP', 'RELEASE', 'RENAME', 'REPEAT', 'REPLACE', 'REQUIRE', 'RESIGNAL', 'RESTRICT', 'RETURN', 'REVOKE', 'RIGHT', 'RLIKE', 'SCHEMA', 'SCHEMAS', 'SECOND_MICROSECOND', 'SELECT', 'SENSITIVE', 'SEPARATOR', 'SET', 'SHOW', 'SIGNAL', 'SMALLINT', 'SPATIAL', 'SPECIFIC', 'SQL', 'SQLEXCEPTION', 'SQLSTATE', 'SQLWARNING', 'SQL_BIG_RESULT', 'SQL_CALC_FOUND_ROWS', 'SQL_SMALL_RESULT', 'SSL', 'STARTING', 'STRAIGHT_JOIN', 'TABLE', 'TERMINATED', 'THEN', 'TINYBLOB', 'TINYINT', 'TINYTEXT', 'TO', 'TRAILING', 'TRIGGER', 'TRUE', 'UNDO', 'UNION', 'UNIQUE', 'UNLOCK', 'UNSIGNED', 'UPDATE', 'USAGE', 'USE', 'USING', 'UTC_DATE', 'UTC_TIME', 'UTC_TIMESTAMP', 'VALUES', 'VARBINARY', 'VARCHAR', 'VARCHARACTER', 'VARYING', 'WHEN', 'WHERE', 'WHILE', 'WITH', 'WRITE', 'XOR', 'YEAR_MONTH', 'ZEROFILL', 'GENERAL', 'IGNORE_SERVER_IDS', 'MASTER_HEARTBEAT_PERIOD', 'MAXVALUE', 'RESIGNAL', 'SIGNAL', 'SLOW'],
  POSTGRESQL: ['ALL', 'ANALYSE', 'ANALYZE', 'AND', 'ANY', 'ARRAY', 'AS', 'ASC', 'ASYMMETRIC', 'AUTHORIZATION', 'BINARY', 'BOTH', 'CASE', 'CAST', 'CHECK', 'COLLATE', 'COLLATION', 'COLUMN', 'CONCURRENTLY', 'CONSTRAINT', 'CREATE', 'CROSS', 'CURRENT_CATALOG', 'CURRENT_DATE', 'CURRENT_ROLE', 'CURRENT_SCHEMA', 'CURRENT_TIME', 'CURRENT_TIMESTAMP', 'CURRENT_USER', 'DEFAULT', 'DEFERRABLE', 'DESC', 'DISTINCT', 'DO', 'ELSE', 'END', 'EXCEPT', 'FALSE', 'FETCH', 'FOR', 'FOREIGN', 'FROM', 'FULL', 'GRANT', 'GROUP', 'HAVING', 'ILIKE', 'IN', 'INITIALLY', 'INNER', 'INTERSECT', 'INTO', 'IS', 'ISNULL', 'JOIN', 'LATERAL', 'LEADING', 'LEFT', 'LIKE', 'LIMIT', 'LOCALTIME', 'LOCALTIMESTAMP', 'NATURAL', 'NOT', 'NOTNULL', 'NULL', 'OFFSET', 'ON', 'ONLY', 'OR', 'ORDER', 'OUTER', 'OVERLAPS', 'PLACING', 'PRIMARY', 'REFERENCES', 'RETURNING', 'RIGHT', 'SELECT', 'SESSION_USER', 'SIMILAR', 'SOME', 'SYMMETRIC', 'TABLE', 'THEN', 'TO', 'TRAILING', 'TRUE', 'UNION', 'UNIQUE', 'USER', 'USING', 'VARIADIC', 'VERBOSE', 'WHEN', 'WHERE', 'WINDOW', 'WITH'],
  CASSANDRA: ['ADD', 'ALL', 'ALTER', 'AND', 'ANY', 'APPLY', 'AS', 'ASC', 'ASCII', 'AUTHORIZE', 'BATCH', 'BEGIN', 'BIGINT', 'BLOB', 'BOOLEAN', 'BY', 'CLUSTERING', 'COLUMNFAMILY', 'COMPACT', 'CONSISTENCY', 'COUNT', 'COUNTER', 'CREATE', 'DECIMAL', 'DELETE', 'DESC', 'DOUBLE', 'DROP', 'EACH_QUORUM', 'FLOAT', 'FROM', 'GRANT', 'IN', 'INDEX', 'CUSTOM', 'INSERT', 'INT', 'INTO', 'KEY', 'KEYSPACE', 'LEVEL', 'LIMIT', 'LOCAL_ONE', 'LOCAL_QUORUM', 'MODIFY', 'NORECURSIVE', 'NOSUPERUSER', 'OF', 'ON', 'ONE', 'ORDER', 'PASSWORD', 'PERMISSION', 'PERMISSIONS', 'PRIMARY', 'QUORUM', 'REVOKE', 'SCHEMA', 'SELECT', 'SET', 'STORAGE', 'SUPERUSER', 'TABLE', 'TEXT', 'TIMESTAMP', 'TIMEUUID', 'THREE', 'TOKEN', 'TRUNCATE', 'TTL', 'TWO', 'TYPE', 'UPDATE', 'USE', 'USER', 'USERS', 'USING', 'UUID', 'VALUES', 'VARCHAR', 'VARINT', 'WHERE', 'WITH', 'WRITETIME', 'DISTINCT', 'BYTE', 'SMALLINT', 'COMPLEX', 'ENUM', 'DATE', 'INTERVAL', 'MACADDR', 'BITSTRING'],
  ORACLE: ['ACCESS', 'ACCOUNT', 'ACTIVATE', 'ADD', 'ADMIN', 'ADVISE', 'AFTER', 'ALL', 'ALL_ROWS', 'ALLOCATE', 'ALTER', 'ANALYZE', 'AND', 'ANY', 'ARCHIVE', 'ARCHIVELOG', 'ARRAY', 'AS', 'ASC', 'AT', 'AUDIT', 'AUTHENTICATED', 'AUTHORIZATION', 'AUTOEXTEND', 'AUTOMATIC', 'BACKUP', 'BECOME', 'BEFORE', 'BEGIN', 'BETWEEN', 'BFILE', 'BITMAP', 'BLOB', 'BLOCK', 'BODY', 'BY', 'CACHE', 'CACHE_INSTANCES', 'CANCEL', 'CASCADE', 'CAST', 'CFILE', 'CHAINED', 'CHANGE', 'CHAR', 'CHAR_CS', 'CHARACTER', 'CHECK', 'CHECKPOINT', 'CHOOSE', 'CHUNK', 'CLEAR', 'CLOB', 'CLONE', 'CLOSE', 'CLOSE_CACHED_OPEN_CURSORS', 'CLUSTER', 'COALESCE', 'COLUMN', 'COLUMNS', 'COMMENT', 'COMMIT', 'COMMITTED', 'COMPATIBILITY', 'COMPILE', 'COMPLETE', 'COMPOSITE_LIMIT', 'COMPRESS', 'COMPUTE', 'CONNECT', 'CONNECT_TIME', 'CONSTRAINT', 'CONSTRAINTS', 'CONTENTS', 'CONTINUE', 'CONTROLFILE', 'CONVERT', 'COST', 'CPU_PER_CALL', 'CPU_PER_SESSION', 'CREATE', 'CURRENT', 'CURRENT_SCHEMA', 'CURREN_USER', 'CURSOR', 'CYCLE', ' ', 'DANGLING', 'DATABASE', 'DATAFILE', 'DATAFILES', 'DATAOBJNO', 'DATE', 'DBA', 'DBHIGH', 'DBLOW', 'DBMAC', 'DEALLOCATE', 'DEBUG', 'DEC', 'DECIMAL', 'DECLARE', 'DEFAULT', 'DEFERRABLE', 'DEFERRED', 'DEGREE', 'DELETE', 'DEREF', 'DESC', 'DIRECTORY', 'DISABLE', 'DISCONNECT', 'DISMOUNT', 'DISTINCT', 'DISTRIBUTED', 'DML', 'DOUBLE', 'DROP', 'DUMP', 'EACH', 'ELSE', 'ENABLE', 'END', 'ENFORCE', 'ENTRY', 'ESCAPE', 'EXCEPT', 'EXCEPTIONS', 'EXCHANGE', 'EXCLUDING', 'EXCLUSIVE', 'EXECUTE', 'EXISTS', 'EXPIRE', 'EXPLAIN', 'EXTENT', 'EXTENTS', 'EXTERNALLY', 'FAILED_LOGIN_ATTEMPTS', 'FALSE', 'FAST', 'FILE', 'FIRST_ROWS', 'FLAGGER', 'FLOAT', 'FLOB', 'FLUSH', 'FOR', 'FORCE', 'FOREIGN', 'FREELIST', 'FREELISTS', 'FROM', 'FULL', 'FUNCTION', 'GLOBAL', 'GLOBALLY', 'GLOBAL_NAME', 'GRANT', 'GROUP', 'GROUPS', 'HASH', 'HASHKEYS', 'HAVING', 'HEADER', 'HEAP', 'IDENTIFIED', 'IDGENERATORS', 'IDLE_TIME', 'IF', 'IMMEDIATE', 'IN', 'INCLUDING', 'INCREMENT', 'INDEX', 'INDEXED', 'INDEXES', 'INDICATOR', 'IND_PARTITION', 'INITIAL', 'INITIALLY', 'INITRANS', 'INSERT', 'INSTANCE', 'INSTANCES', 'INSTEAD', 'INT', 'INTEGER', 'INTERMEDIATE', 'INTERSECT', 'INTO', 'IS', 'ISOLATION', 'ISOLATION_LEVEL', 'KEEP', 'KEY', 'KILL', 'LABEL', 'LAYER', 'LESS', 'LEVEL', 'LIBRARY', 'LIKE', 'LIMIT', 'LINK', 'LIST', 'LOB', 'LOCAL', 'LOCK', 'LOCKED', 'LOG', 'LOGFILE', 'LOGGING', 'LOGICAL_READS_PER_CALL', 'LOGICAL_READS_PER_SESSION', 'LONG', 'MANAGE', 'MASTER', 'MAX', 'MAXARCHLOGS', 'MAXDATAFILES', 'MAXEXTENTS', 'MAXINSTANCES', 'MAXLOGFILES', 'MAXLOGHISTORY', 'MAXLOGMEMBERS', 'MAXSIZE', 'MAXTRANS', 'MAXVALUE', 'MIN', 'MEMBER', 'MINIMUM', 'MINEXTENTS', 'MINUS', 'MINVALUE', 'MLSLABEL', 'MLS_LABEL_FORMAT', 'MODE', 'MODIFY', 'MOUNT', 'MOVE', 'MTS_DISPATCHERS', 'MULTISET', 'NATIONAL', 'NCHAR', 'NCHAR_CS', 'NCLOB', 'NEEDED', 'NESTED', 'NETWORK', 'NEW', 'NEXT', 'NOARCHIVELOG', 'NOAUDIT', 'NOCACHE', 'NOCOMPRESS', 'NOCYCLE', 'NOFORCE', 'NOLOGGING', 'NOMAXVALUE', 'NOMINVALUE', 'NONE', 'NOORDER', 'NOOVERRIDE', 'NOPARALLEL', 'NOPARALLEL', 'NOREVERSE', 'NORMAL', 'NOSORT', 'NOT', 'NOTHING', 'NOWAIT', 'NULL', 'NUMBER', 'NUMERIC', 'NVARCHAR2', 'OBJECT', 'OBJNO', 'OBJNO_REUSE', 'OF', 'OFF', 'OFFLINE', 'OID', 'OIDINDEX', 'OLD', 'ON', 'ONLINE', 'ONLY', 'OPCODE', 'OPEN', 'OPTIMAL', 'OPTIMIZER_GOAL', 'OPTION', 'OR', 'ORDER', 'ORGANIZATION', 'OSLABEL', 'OVERFLOW', 'OWN', 'PACKAGE', 'PARALLEL', 'PARTITION', 'PASSWORD', 'PASSWORD_GRACE_TIME', 'PASSWORD_LIFE_TIME', 'PASSWORD_LOCK_TIME', 'PASSWORD_REUSE_MAX', 'PASSWORD_REUSE_TIME', 'PASSWORD_VERIFY_FUNCTION', 'PCTFREE', 'PCTINCREASE', 'PCTTHRESHOLD', 'PCTUSED', 'PCTVERSION', 'PERCENT', 'PERMANENT', 'PLAN', 'PLSQL_DEBUG', 'POST_TRANSACTION', 'PRECISION', 'PRESERVE', 'PRIMARY', 'PRIOR', 'PRIVATE', 'PRIVATE_SGA', 'PRIVILEGE', 'PRIVILEGES', 'PROCEDURE', 'PROFILE', 'PUBLIC', 'PURGE', 'QUEUE', 'QUOTA', 'RANGE', 'RAW', 'RBA', 'READ', 'READUP', 'REAL', 'REBUILD', 'RECOVER', 'RECOVERABLE', 'RECOVERY', 'REF', 'REFERENCES', 'REFERENCING', 'REFRESH', 'RENAME', 'REPLACE', 'RESET', 'RESETLOGS', 'RESIZE', 'RESOURCE', 'RESTRICTED', 'RETURN', 'RETURNING', 'REUSE', 'REVERSE', 'REVOKE', 'ROLE', 'ROLES', 'ROLLBACK', 'ROW', 'ROWID', 'ROWNUM', 'ROWS', 'RULE', 'SAMPLE', 'SAVEPOINT', 'SB4', 'SCAN_INSTANCES', 'SCHEMA', 'SCN', 'SCOPE', 'SD_ALL', 'SD_INHIBIT', 'SD_SHOW', 'SEGMENT', 'SEG_BLOCK', 'SEG_FILE', 'SELECT', 'SEQUENCE', 'SERIALIZABLE', 'SESSION', 'SESSION_CACHED_CURSORS', 'SESSIONS_PER_USER', 'SET', 'SHARE', 'SHARED', 'SHARED_POOL', 'SHRINK', 'SIZE', 'SKIP', 'SKIP_UNUSABLE_INDEXES', 'SMALLINT', 'SNAPSHOT', 'SOME', 'SORT', 'SPECIFICATION', 'SPLIT', 'SQL_TRACE', 'STANDBY', 'START', 'STATEMENT_ID', 'STATISTICS', 'STOP', 'STORAGE', 'STORE', 'STRUCTURE', 'SUCCESSFUL', 'SWITCH', 'SYS_OP_ENFORCE_NOT_NULL$', 'SYS_OP_NTCIMG$', 'SYNONYM', 'SYSDATE', 'SYSDBA', 'SYSOPER', 'SYSTEM', 'TABLE', 'TABLES', 'TABLESPACE', 'TABLESPACE_NO', 'TABNO', 'TEMPORARY', 'THAN', 'THE', 'THEN', 'THREAD', 'TIMESTAMP', 'TIME', 'TO', 'TOPLEVEL', 'TRACE', 'TRACING', 'TRANSACTION', 'TRANSITIONAL', 'TRIGGER', 'TRIGGERS', 'TRUE', 'TRUNCATE', 'TX', 'TYPE', 'UB2', 'UBA', 'UID', 'UNARCHIVED', 'UNDO', 'UNION', 'UNIQUE', 'UNLIMITED', 'UNLOCK', 'UNRECOVERABLE', 'UNTIL', 'UNUSABLE', 'UNUSED', 'UPDATABLE', 'UPDATE', 'USAGE', 'USE', 'USER', 'USING', 'VALIDATE', 'VALIDATION', 'VALUE', 'VALUES', 'VARCHAR', 'VARCHAR2', 'VARYING', 'VIEW', 'WHEN', 'WHENEVER', 'WHERE', 'WITH', 'WITHOUT', 'WORK', 'WRITE', 'WRITEDOWN', 'WRITEUP', 'XID', 'YEAR', 'ZONE'],
  MONGODB: ['DOCUMENT']
};

function isReserved(keyword, type) {
  return keyword != null && type != null && RESERVED_WORDS[type.toUpperCase()] != null
      && RESERVED_WORDS[type.toUpperCase()].indexOf(keyword.toUpperCase()) !== -1;

}

function isReservedClassName(keyword) {
  return isReserved(keyword, 'JHIPSTER') || isReserved(keyword, 'JAVA');
}

function isReservedTableName(keyword, databaseType) {
  if (databaseType.toLowerCase() === 'sql') {
    return isReserved(keyword, 'mysql') || isReserved(keyword, 'postgresql') || isReserved(keyword, 'oracle');
  }
  return isReserved(keyword, databaseType);
}

function isReservedFieldName(keyword, databaseType) {
  return isReserved(keyword, 'JAVA') || isReservedTableName(keyword, databaseType);
}

module.exports = {
  isReserved: isReserved,
  isReservedClassName: isReservedClassName,
  isReservedTableName: isReservedTableName,
  isReservedFieldName: isReservedFieldName,
  JHIPSTER: RESERVED_WORDS.JHIPSTER,
  JAVA: RESERVED_WORDS.JAVA,
  MYSQL: RESERVED_WORDS.MYSQL,
  POSTGRESQL: RESERVED_WORDS.POSTGRESQL,
  CASSANDRA: RESERVED_WORDS.CASSANDRA,
  ORACLE: RESERVED_WORDS.ORACLE,
  MONGODB: RESERVED_WORDS.MONGODB
};
<commit_msg>Simplified conditions<commit_after>'use strict';

const RESERVED_WORDS = {
  JHIPSTER: ['ACCOUNT'],
  JAVA: ['ABSTRACT', 'CONTINUE', 'FOR', 'NEW', 'SWITCH', 'ASSERT', 'DEFAULT', 'GOTO', 'PACKAGE', 'SYNCHRONIZED', 'BOOLEAN', 'DO', 'IF', 'PRIVATE', 'THIS', 'BREAK', 'DOUBLE', 'IMPLEMENTS', 'PROTECTED', 'THROW', 'BYTE', 'ELSE', 'IMPORT', 'PUBLIC', 'THROWS', 'CASE', 'ENUM', 'INSTANCEOF', 'RETURN', 'TRANSIENT', 'CATCH', 'EXTENDS', 'INT', 'SHORT', 'TRY', 'CHAR', 'FINAL', 'INTERFACE', 'STATIC', 'VOID', 'CLASS', 'FINALLY', 'LONG', 'STRICTFP', 'VOLATILE', 'CONST', 'FLOAT', 'NATIVE', 'SUPER', 'WHILE'],
  MYSQL: ['ACCESSIBLE', 'ADD', 'ALL', 'ALTER', 'ANALYZE', 'AND', 'AS', 'ASC', 'ASENSITIVE', 'BEFORE', 'BETWEEN', 'BIGINT', 'BINARY', 'BLOB', 'BOTH', 'BY', 'CALL', 'CASCADE', 'CASE', 'CHANGE', 'CHAR', 'CHARACTER', 'CHECK', 'COLLATE', 'COLUMN', 'CONDITION', 'CONSTRAINT', 'CONTINUE', 'CONVERT', 'CREATE', 'CROSS', 'CURRENT_DATE', 'CURRENT_TIME', 'CURRENT_TIMESTAMP', 'CURRENT_USER', 'CURSOR', 'DATABASE', 'DATABASES', 'DAY_HOUR', 'DAY_MICROSECOND', 'DAY_MINUTE', 'DAY_SECOND', 'DEC', 'DECIMAL', 'DECLARE', 'DEFAULT', 'DELAYED', 'DELETE', 'DESC', 'DESCRIBE', 'DETERMINISTIC', 'DISTINCT', 'DISTINCTROW', 'DIV', 'DOUBLE', 'DROP', 'DUAL', 'EACH', 'ELSE', 'ELSEIF', 'ENCLOSED', 'ESCAPED', 'EXISTS', 'EXIT', 'EXPLAIN', 'FALSE', 'FETCH', 'FLOAT', 'FLOAT4', 'FLOAT8', 'FOR', 'FORCE', 'FOREIGN', 'FROM', 'FULLTEXT', 'GRANT', 'GROUP', 'HAVING', 'HIGH_PRIORITY', 'HOUR_MICROSECOND', 'HOUR_MINUTE', 'HOUR_SECOND', 'IF', 'IGNORE', 'IN', 'INDEX', 'INFILE', 'INNER', 'INOUT', 'INSENSITIVE', 'INSERT', 'INT', 'INT1', 'INT2', 'INT3', 'INT4', 'INT8', 'INTEGER', 'INTERVAL', 'INTO', 'IS', 'ITERATE', 'JOIN', 'KEY', 'KEYS', 'KILL', 'LEADING', 'LEAVE', 'LEFT', 'LIKE', 'LIMIT', 'LINEAR', 'LINES', 'LOAD', 'LOCALTIME', 'LOCALTIMESTAMP', 'LOCK', 'LONG', 'LONGBLOB', 'LONGTEXT', 'LOOP', 'LOW_PRIORITY', 'MASTER_SSL_VERIFY_SERVER_CERT', 'MATCH', 'MAXVALUE', 'MEDIUMBLOB', 'MEDIUMINT', 'MEDIUMTEXT', 'MIDDLEINT', 'MINUTE_MICROSECOND', 'MINUTE_SECOND', 'MOD', 'MODIFIES', 'NATURAL', 'NOT', 'NO_WRITE_TO_BINLOG', 'NULL', 'NUMERIC', 'ON', 'OPTIMIZE', 'OPTION', 'OPTIONALLY', 'OR', 'ORDER', 'OUT', 'OUTER', 'OUTFILE', 'PRECISION', 'PRIMARY', 'PROCEDURE', 'PURGE', 'RANGE', 'READ', 'READS', 'READ_WRITE', 'REAL', 'REFERENCES', 'REGEXP', 'RELEASE', 'RENAME', 'REPEAT', 'REPLACE', 'REQUIRE', 'RESIGNAL', 'RESTRICT', 'RETURN', 'REVOKE', 'RIGHT', 'RLIKE', 'SCHEMA', 'SCHEMAS', 'SECOND_MICROSECOND', 'SELECT', 'SENSITIVE', 'SEPARATOR', 'SET', 'SHOW', 'SIGNAL', 'SMALLINT', 'SPATIAL', 'SPECIFIC', 'SQL', 'SQLEXCEPTION', 'SQLSTATE', 'SQLWARNING', 'SQL_BIG_RESULT', 'SQL_CALC_FOUND_ROWS', 'SQL_SMALL_RESULT', 'SSL', 'STARTING', 'STRAIGHT_JOIN', 'TABLE', 'TERMINATED', 'THEN', 'TINYBLOB', 'TINYINT', 'TINYTEXT', 'TO', 'TRAILING', 'TRIGGER', 'TRUE', 'UNDO', 'UNION', 'UNIQUE', 'UNLOCK', 'UNSIGNED', 'UPDATE', 'USAGE', 'USE', 'USING', 'UTC_DATE', 'UTC_TIME', 'UTC_TIMESTAMP', 'VALUES', 'VARBINARY', 'VARCHAR', 'VARCHARACTER', 'VARYING', 'WHEN', 'WHERE', 'WHILE', 'WITH', 'WRITE', 'XOR', 'YEAR_MONTH', 'ZEROFILL', 'GENERAL', 'IGNORE_SERVER_IDS', 'MASTER_HEARTBEAT_PERIOD', 'MAXVALUE', 'RESIGNAL', 'SIGNAL', 'SLOW'],
  POSTGRESQL: ['ALL', 'ANALYSE', 'ANALYZE', 'AND', 'ANY', 'ARRAY', 'AS', 'ASC', 'ASYMMETRIC', 'AUTHORIZATION', 'BINARY', 'BOTH', 'CASE', 'CAST', 'CHECK', 'COLLATE', 'COLLATION', 'COLUMN', 'CONCURRENTLY', 'CONSTRAINT', 'CREATE', 'CROSS', 'CURRENT_CATALOG', 'CURRENT_DATE', 'CURRENT_ROLE', 'CURRENT_SCHEMA', 'CURRENT_TIME', 'CURRENT_TIMESTAMP', 'CURRENT_USER', 'DEFAULT', 'DEFERRABLE', 'DESC', 'DISTINCT', 'DO', 'ELSE', 'END', 'EXCEPT', 'FALSE', 'FETCH', 'FOR', 'FOREIGN', 'FROM', 'FULL', 'GRANT', 'GROUP', 'HAVING', 'ILIKE', 'IN', 'INITIALLY', 'INNER', 'INTERSECT', 'INTO', 'IS', 'ISNULL', 'JOIN', 'LATERAL', 'LEADING', 'LEFT', 'LIKE', 'LIMIT', 'LOCALTIME', 'LOCALTIMESTAMP', 'NATURAL', 'NOT', 'NOTNULL', 'NULL', 'OFFSET', 'ON', 'ONLY', 'OR', 'ORDER', 'OUTER', 'OVERLAPS', 'PLACING', 'PRIMARY', 'REFERENCES', 'RETURNING', 'RIGHT', 'SELECT', 'SESSION_USER', 'SIMILAR', 'SOME', 'SYMMETRIC', 'TABLE', 'THEN', 'TO', 'TRAILING', 'TRUE', 'UNION', 'UNIQUE', 'USER', 'USING', 'VARIADIC', 'VERBOSE', 'WHEN', 'WHERE', 'WINDOW', 'WITH'],
  CASSANDRA: ['ADD', 'ALL', 'ALTER', 'AND', 'ANY', 'APPLY', 'AS', 'ASC', 'ASCII', 'AUTHORIZE', 'BATCH', 'BEGIN', 'BIGINT', 'BLOB', 'BOOLEAN', 'BY', 'CLUSTERING', 'COLUMNFAMILY', 'COMPACT', 'CONSISTENCY', 'COUNT', 'COUNTER', 'CREATE', 'DECIMAL', 'DELETE', 'DESC', 'DOUBLE', 'DROP', 'EACH_QUORUM', 'FLOAT', 'FROM', 'GRANT', 'IN', 'INDEX', 'CUSTOM', 'INSERT', 'INT', 'INTO', 'KEY', 'KEYSPACE', 'LEVEL', 'LIMIT', 'LOCAL_ONE', 'LOCAL_QUORUM', 'MODIFY', 'NORECURSIVE', 'NOSUPERUSER', 'OF', 'ON', 'ONE', 'ORDER', 'PASSWORD', 'PERMISSION', 'PERMISSIONS', 'PRIMARY', 'QUORUM', 'REVOKE', 'SCHEMA', 'SELECT', 'SET', 'STORAGE', 'SUPERUSER', 'TABLE', 'TEXT', 'TIMESTAMP', 'TIMEUUID', 'THREE', 'TOKEN', 'TRUNCATE', 'TTL', 'TWO', 'TYPE', 'UPDATE', 'USE', 'USER', 'USERS', 'USING', 'UUID', 'VALUES', 'VARCHAR', 'VARINT', 'WHERE', 'WITH', 'WRITETIME', 'DISTINCT', 'BYTE', 'SMALLINT', 'COMPLEX', 'ENUM', 'DATE', 'INTERVAL', 'MACADDR', 'BITSTRING'],
  ORACLE: ['ACCESS', 'ACCOUNT', 'ACTIVATE', 'ADD', 'ADMIN', 'ADVISE', 'AFTER', 'ALL', 'ALL_ROWS', 'ALLOCATE', 'ALTER', 'ANALYZE', 'AND', 'ANY', 'ARCHIVE', 'ARCHIVELOG', 'ARRAY', 'AS', 'ASC', 'AT', 'AUDIT', 'AUTHENTICATED', 'AUTHORIZATION', 'AUTOEXTEND', 'AUTOMATIC', 'BACKUP', 'BECOME', 'BEFORE', 'BEGIN', 'BETWEEN', 'BFILE', 'BITMAP', 'BLOB', 'BLOCK', 'BODY', 'BY', 'CACHE', 'CACHE_INSTANCES', 'CANCEL', 'CASCADE', 'CAST', 'CFILE', 'CHAINED', 'CHANGE', 'CHAR', 'CHAR_CS', 'CHARACTER', 'CHECK', 'CHECKPOINT', 'CHOOSE', 'CHUNK', 'CLEAR', 'CLOB', 'CLONE', 'CLOSE', 'CLOSE_CACHED_OPEN_CURSORS', 'CLUSTER', 'COALESCE', 'COLUMN', 'COLUMNS', 'COMMENT', 'COMMIT', 'COMMITTED', 'COMPATIBILITY', 'COMPILE', 'COMPLETE', 'COMPOSITE_LIMIT', 'COMPRESS', 'COMPUTE', 'CONNECT', 'CONNECT_TIME', 'CONSTRAINT', 'CONSTRAINTS', 'CONTENTS', 'CONTINUE', 'CONTROLFILE', 'CONVERT', 'COST', 'CPU_PER_CALL', 'CPU_PER_SESSION', 'CREATE', 'CURRENT', 'CURRENT_SCHEMA', 'CURREN_USER', 'CURSOR', 'CYCLE', ' ', 'DANGLING', 'DATABASE', 'DATAFILE', 'DATAFILES', 'DATAOBJNO', 'DATE', 'DBA', 'DBHIGH', 'DBLOW', 'DBMAC', 'DEALLOCATE', 'DEBUG', 'DEC', 'DECIMAL', 'DECLARE', 'DEFAULT', 'DEFERRABLE', 'DEFERRED', 'DEGREE', 'DELETE', 'DEREF', 'DESC', 'DIRECTORY', 'DISABLE', 'DISCONNECT', 'DISMOUNT', 'DISTINCT', 'DISTRIBUTED', 'DML', 'DOUBLE', 'DROP', 'DUMP', 'EACH', 'ELSE', 'ENABLE', 'END', 'ENFORCE', 'ENTRY', 'ESCAPE', 'EXCEPT', 'EXCEPTIONS', 'EXCHANGE', 'EXCLUDING', 'EXCLUSIVE', 'EXECUTE', 'EXISTS', 'EXPIRE', 'EXPLAIN', 'EXTENT', 'EXTENTS', 'EXTERNALLY', 'FAILED_LOGIN_ATTEMPTS', 'FALSE', 'FAST', 'FILE', 'FIRST_ROWS', 'FLAGGER', 'FLOAT', 'FLOB', 'FLUSH', 'FOR', 'FORCE', 'FOREIGN', 'FREELIST', 'FREELISTS', 'FROM', 'FULL', 'FUNCTION', 'GLOBAL', 'GLOBALLY', 'GLOBAL_NAME', 'GRANT', 'GROUP', 'GROUPS', 'HASH', 'HASHKEYS', 'HAVING', 'HEADER', 'HEAP', 'IDENTIFIED', 'IDGENERATORS', 'IDLE_TIME', 'IF', 'IMMEDIATE', 'IN', 'INCLUDING', 'INCREMENT', 'INDEX', 'INDEXED', 'INDEXES', 'INDICATOR', 'IND_PARTITION', 'INITIAL', 'INITIALLY', 'INITRANS', 'INSERT', 'INSTANCE', 'INSTANCES', 'INSTEAD', 'INT', 'INTEGER', 'INTERMEDIATE', 'INTERSECT', 'INTO', 'IS', 'ISOLATION', 'ISOLATION_LEVEL', 'KEEP', 'KEY', 'KILL', 'LABEL', 'LAYER', 'LESS', 'LEVEL', 'LIBRARY', 'LIKE', 'LIMIT', 'LINK', 'LIST', 'LOB', 'LOCAL', 'LOCK', 'LOCKED', 'LOG', 'LOGFILE', 'LOGGING', 'LOGICAL_READS_PER_CALL', 'LOGICAL_READS_PER_SESSION', 'LONG', 'MANAGE', 'MASTER', 'MAX', 'MAXARCHLOGS', 'MAXDATAFILES', 'MAXEXTENTS', 'MAXINSTANCES', 'MAXLOGFILES', 'MAXLOGHISTORY', 'MAXLOGMEMBERS', 'MAXSIZE', 'MAXTRANS', 'MAXVALUE', 'MIN', 'MEMBER', 'MINIMUM', 'MINEXTENTS', 'MINUS', 'MINVALUE', 'MLSLABEL', 'MLS_LABEL_FORMAT', 'MODE', 'MODIFY', 'MOUNT', 'MOVE', 'MTS_DISPATCHERS', 'MULTISET', 'NATIONAL', 'NCHAR', 'NCHAR_CS', 'NCLOB', 'NEEDED', 'NESTED', 'NETWORK', 'NEW', 'NEXT', 'NOARCHIVELOG', 'NOAUDIT', 'NOCACHE', 'NOCOMPRESS', 'NOCYCLE', 'NOFORCE', 'NOLOGGING', 'NOMAXVALUE', 'NOMINVALUE', 'NONE', 'NOORDER', 'NOOVERRIDE', 'NOPARALLEL', 'NOPARALLEL', 'NOREVERSE', 'NORMAL', 'NOSORT', 'NOT', 'NOTHING', 'NOWAIT', 'NULL', 'NUMBER', 'NUMERIC', 'NVARCHAR2', 'OBJECT', 'OBJNO', 'OBJNO_REUSE', 'OF', 'OFF', 'OFFLINE', 'OID', 'OIDINDEX', 'OLD', 'ON', 'ONLINE', 'ONLY', 'OPCODE', 'OPEN', 'OPTIMAL', 'OPTIMIZER_GOAL', 'OPTION', 'OR', 'ORDER', 'ORGANIZATION', 'OSLABEL', 'OVERFLOW', 'OWN', 'PACKAGE', 'PARALLEL', 'PARTITION', 'PASSWORD', 'PASSWORD_GRACE_TIME', 'PASSWORD_LIFE_TIME', 'PASSWORD_LOCK_TIME', 'PASSWORD_REUSE_MAX', 'PASSWORD_REUSE_TIME', 'PASSWORD_VERIFY_FUNCTION', 'PCTFREE', 'PCTINCREASE', 'PCTTHRESHOLD', 'PCTUSED', 'PCTVERSION', 'PERCENT', 'PERMANENT', 'PLAN', 'PLSQL_DEBUG', 'POST_TRANSACTION', 'PRECISION', 'PRESERVE', 'PRIMARY', 'PRIOR', 'PRIVATE', 'PRIVATE_SGA', 'PRIVILEGE', 'PRIVILEGES', 'PROCEDURE', 'PROFILE', 'PUBLIC', 'PURGE', 'QUEUE', 'QUOTA', 'RANGE', 'RAW', 'RBA', 'READ', 'READUP', 'REAL', 'REBUILD', 'RECOVER', 'RECOVERABLE', 'RECOVERY', 'REF', 'REFERENCES', 'REFERENCING', 'REFRESH', 'RENAME', 'REPLACE', 'RESET', 'RESETLOGS', 'RESIZE', 'RESOURCE', 'RESTRICTED', 'RETURN', 'RETURNING', 'REUSE', 'REVERSE', 'REVOKE', 'ROLE', 'ROLES', 'ROLLBACK', 'ROW', 'ROWID', 'ROWNUM', 'ROWS', 'RULE', 'SAMPLE', 'SAVEPOINT', 'SB4', 'SCAN_INSTANCES', 'SCHEMA', 'SCN', 'SCOPE', 'SD_ALL', 'SD_INHIBIT', 'SD_SHOW', 'SEGMENT', 'SEG_BLOCK', 'SEG_FILE', 'SELECT', 'SEQUENCE', 'SERIALIZABLE', 'SESSION', 'SESSION_CACHED_CURSORS', 'SESSIONS_PER_USER', 'SET', 'SHARE', 'SHARED', 'SHARED_POOL', 'SHRINK', 'SIZE', 'SKIP', 'SKIP_UNUSABLE_INDEXES', 'SMALLINT', 'SNAPSHOT', 'SOME', 'SORT', 'SPECIFICATION', 'SPLIT', 'SQL_TRACE', 'STANDBY', 'START', 'STATEMENT_ID', 'STATISTICS', 'STOP', 'STORAGE', 'STORE', 'STRUCTURE', 'SUCCESSFUL', 'SWITCH', 'SYS_OP_ENFORCE_NOT_NULL$', 'SYS_OP_NTCIMG$', 'SYNONYM', 'SYSDATE', 'SYSDBA', 'SYSOPER', 'SYSTEM', 'TABLE', 'TABLES', 'TABLESPACE', 'TABLESPACE_NO', 'TABNO', 'TEMPORARY', 'THAN', 'THE', 'THEN', 'THREAD', 'TIMESTAMP', 'TIME', 'TO', 'TOPLEVEL', 'TRACE', 'TRACING', 'TRANSACTION', 'TRANSITIONAL', 'TRIGGER', 'TRIGGERS', 'TRUE', 'TRUNCATE', 'TX', 'TYPE', 'UB2', 'UBA', 'UID', 'UNARCHIVED', 'UNDO', 'UNION', 'UNIQUE', 'UNLIMITED', 'UNLOCK', 'UNRECOVERABLE', 'UNTIL', 'UNUSABLE', 'UNUSED', 'UPDATABLE', 'UPDATE', 'USAGE', 'USE', 'USER', 'USING', 'VALIDATE', 'VALIDATION', 'VALUE', 'VALUES', 'VARCHAR', 'VARCHAR2', 'VARYING', 'VIEW', 'WHEN', 'WHENEVER', 'WHERE', 'WITH', 'WITHOUT', 'WORK', 'WRITE', 'WRITEDOWN', 'WRITEUP', 'XID', 'YEAR', 'ZONE'],
  MONGODB: ['DOCUMENT']
};

function isReserved(keyword, type) {
  return keyword != null && type != null && RESERVED_WORDS[type.toUpperCase()] != null
      && RESERVED_WORDS[type.toUpperCase()].indexOf(keyword.toUpperCase()) !== -1;

}

function isReservedClassName(keyword) {
  return isReserved(keyword, 'JHIPSTER') || isReserved(keyword, 'JAVA');
}

function isReservedTableName(keyword, databaseType) {
  return (databaseType.toLowerCase() === 'sql')
      ?  isReserved(keyword, 'mysql') || isReserved(keyword, 'postgresql') || isReserved(keyword, 'oracle')
      : isReserved(keyword, databaseType);
}

function isReservedFieldName(keyword, databaseType) {
  return isReserved(keyword, 'JAVA') || isReservedTableName(keyword, databaseType);
}

module.exports = {
  isReserved: isReserved,
  isReservedClassName: isReservedClassName,
  isReservedTableName: isReservedTableName,
  isReservedFieldName: isReservedFieldName,
  JHIPSTER: RESERVED_WORDS.JHIPSTER,
  JAVA: RESERVED_WORDS.JAVA,
  MYSQL: RESERVED_WORDS.MYSQL,
  POSTGRESQL: RESERVED_WORDS.POSTGRESQL,
  CASSANDRA: RESERVED_WORDS.CASSANDRA,
  ORACLE: RESERVED_WORDS.ORACLE,
  MONGODB: RESERVED_WORDS.MONGODB
};
<|endoftext|>


<commit_before>const Driver = require('../../driver');
const AnalogSensor = require("./analog-sensor");

const TemperatureSensor = module.exports = class TemperatureSensor extends AnalogSensor {
  /**
   * A TemperatureSensor Driver
   *
   * @constructor temperature
   * @param {Object} opts options object
   * @param {String|Number} opts.bValue the bValue for thermistor

   */
  constructor(opts) {
    super(opts);

    this.bValue = opts.bValue || 4275;
    this.commands = {
      celsius: this.celsius
    };
  }

  /**
   * Gets the current value from the Analog Sensor
   *
   * @param {Function} [callback] invoked with `err, value` as args
   * @return {Number} the current temperature value
   * @publish
   */
  celsius(callback) {
    var val = this.analogVal;

    var temp= val * 0.4887585532746823069403714565;

    if (typeof callback === "function") {
      callback(null, temp);
    }
    console.log("temp:" + temp);

    return temp;
  }
}
<commit_msg>beautify<commit_after>const Driver = require('../../driver');
const AnalogSensor = require("./analog-sensor");

const TemperatureSensor = module.exports = class TemperatureSensor extends AnalogSensor {
  /**
   * A TemperatureSensor Driver
   *
   * @constructor temperature
   * @param {Object} opts options object
   * @param {String|Number} opts.bValue the bValue for thermistor

   */
  constructor(opts) {
    super(opts);

    this.bValue = opts.bValue || 4275;
    this.commands = {
      celsius: this.celsius
    };
  }

  /**
   * Gets the current value from the Analog Sensor
   *
   * @param {Function} [callback] invoked with `err, value` as args
   * @return {Number} the current temperature value
   * @publish
   */
  celsius(callback) {
    var val = this.analogVal;

    var temp = val * 0.4887585532746823069403714565;

    if (typeof callback === "function") {
      callback(null, temp);
    }
    console.log("temp:" + temp);

    return temp;
  }
}
<|endoftext|>


<commit_before>// go.campaign.dialogue.states
// ===========================
// Structures for each dialogue state type

(function(exports) {
  var maybeByName = go.utils.maybeByName,
      GridView = go.components.grid.GridView,
      ConfirmView = go.components.views.ConfirmView,
      Template = go.components.templating.Template;

  var plumbing = go.components.plumbing;

  var states = plumbing.states,
      StateView = states.StateView,
      StateViewCollection = states.StateViewCollection;

  var endpoints = plumbing.endpoints,
      ParametricEndpointView = endpoints.ParametricEndpointView,
      AligningEndpointCollection = endpoints.AligningEndpointCollection;

  var DialogueEndpointView = ParametricEndpointView.extend();

  var EntryEndpointView = DialogueEndpointView.extend({
    side: 'left',
    isSource: false
  });

  var ExitEndpointView = DialogueEndpointView.extend({
    side: 'right',
    isTarget: false
  });

  // Base 'mode' for state views. Each mode acts as a 'delegate view',
  // targeting a dialogue view's element and acting according to the mode type
  // (for eg, `edit`) and state type (for eg, `freetext`).
  var DialogueStateModeView = Backbone.View.extend({
    jst: _.template(''),

    initialize: function(options) {
      this.state = options.state;

      var data = {
        mode: this,
        state: this.state,
        model: this.state.model
      };

      this.template = new Template({
        el: this.$el,
        jst: this.jst,
        data: data,
        partials: {
          body: new Template(
            _({data: data}).extend(
            _(this).result('bodyOptions')))
        }
      });
    },

    bodyOptions: {},

    destroy: function() {
      this.$el.remove();
      return this;
    },

    detach: function() {
      this.$el.detach();
      return this;
    },

    render: function() {
      this.template.render();
      return this;
    }
  });

  // Mode allowing the user to make changes to the dialogue state. Acts as a
  // base for each state type's `edit` mode
  var DialogueStateEditView = DialogueStateModeView.extend({
    jst: 'JST.campaign_dialogue_states_modes_edit',

    className: 'edit mode',

    events: {
      'click .ok': 'onOk',
      'click .cancel': 'onCancel',
      'change .type': 'onTypeChange',
      'change .name': 'onNameChange'
    },

    resetModal: new ConfirmView({
      optional: true,
      content: "Changing the message's type will break its connections " +
               "and reset its content."
    }),

    initialize: function(options) {
      DialogueStateEditView.__super__.initialize.call(this, options);
      this.backupModel();

      this.on('activate', this.backupModel, this);
    },

    onOk: function(e) {
      e.preventDefault();
      this.state.preview();
    },

    onCancel: function(e) {
      e.preventDefault();
      this.cancel();
      this.state.preview();
    },

    onTypeChange: function(e) {
      var $option = $(e.target);

      // Using `on` is okay, since the events are unbound when either of the
      // buttons are clicked. Simply using `once` won't work, since the event
      // for the unclicked button will remain bound.
      this.resetModal
        .on(
          'ok',
          function() { this.state.reset($option.val()); }, this)
        .on(
          'cancel',
          function() { this.$('.type').val(this.state.typeName); }, this)
        .show();
    },

    onNameChange: function(e) {
      this.state.model.set('name', $(e.target).val(), {silent: true});
      return this;
    },

    // Keep a backup to restore the model for when the user cancels the edit
    backupModel: function() {
      this.modelBackup = this.state.model.toJSON();
      return this;
    },

    cancel: function() {
      var model = this.state.model;
      if (this.modelBackup) { model.set(this.modelBackup); }
      return this;
    },

    render: function() {
      DialogueStateEditView.__super__.render.call(this);
      this.$('.type').val(this.state.typeName);
      return this;
    }
  });

  // Mode for a 'read-only' preview of the dialogue state. Acts as a base for
  // each state type's `preview` mode
  var DialogueStatePreviewView = DialogueStateModeView.extend({
    jst: 'JST.campaign_dialogue_states_modes_preview',

    className: 'preview mode',

    events: {
      'click .edit-switch': 'onEditSwitch'
    },

    onEditSwitch: function(e) {
      e.preventDefault();
      this.state.edit();
    }
  });

  // Base view for dialogue states. Dynamically switches between modes
  // (`edit`, `preview`).
  var DialogueStateView = StateView.extend({
    switchModeDefaults: {render: true, silent: false},

    className: function() { return 'box item state ' + this.typeName || ''; },

    editModeType: DialogueStateEditView,
    previewModeType: DialogueStatePreviewView,

    endpointType: DialogueEndpointView,
    endpointCollectionType: AligningEndpointCollection,

    subtypes: {
      dummy: 'go.campaign.dialogue.states.dummy.DummyStateView',
      choice: 'go.campaign.dialogue.states.choice.ChoiceStateView',
      freetext: 'go.campaign.dialogue.states.freetext.FreeTextStateView',
      end: 'go.campaign.dialogue.states.end.EndStateView'
    },

    events: {
      'mousedown .titlebar': 'onTitlebarHold',
      'click .titlebar .remove': 'onRemove'
    },

    initialize: function(options) {
      StateView.prototype.initialize.call(this, options);

      if (!this.model.has('ordinal')) {
        this.model.set('ordinal', this.collection.size(), {silent: true});
      }

      this.modes = {
        edit: new this.editModeType({state: this}),
        preview: new this.previewModeType({state: this})
      };

      this.switchMode(options.mode || 'preview', {render: false});
    },

    onTitlebarHold: function(e) {
      if (this.isConnected()) { this.$el.addClass('locked'); }
      else { this.$el.removeClass('locked'); }
    },

    onRemove: function(e) {
      e.preventDefault();
      this.collection.remove(this);
    },

    // 'Resets' a state to a new type by removing the current state, and
    // replacing it with a new state in the same position
    reset: function(type) {
      // TODO warn the user of the destruction involved
      this.collection.reset(this, type);
    },

    switchMode: function(modeName, options) {
      options = _(options || {}).defaults(this.switchModeDefaults);
      var mode = this.modes[modeName] || this.modes.preview;

      if (this.mode) {
        if (!options.silent) { this.mode.trigger('deactivate'); }
        this.mode.detach();
      }

      this.mode = mode;
      this.modeName = modeName;

      if (!options.silent) { this.mode.trigger('activate'); }
      if (options.render) {
        this.render();
        jsPlumb.repaintEverything();
      }
      return this;
    },

    preview: function(options) {
      return this.switchMode('preview', options);
    },

    edit: function(options) {
      return this.switchMode('edit', options);
    },

    render: function() {
      this.mode
        .render()
        .$el
        .appendTo(this.$el);

      this.endpoints.render();
      return this;
    }
  });

  var DialogueStateGridView = GridView.extend({
    className: 'grid container boxes',

    events: {
      'click .add': 'onAddClick'
    },

    sortableOptions: {
      items: '.item:not(.add-container)',
      cancel: '.locked,input',
      handle: '.titlebar',
      placeholder: 'placeholder',
      sort: function() { jsPlumb.repaintEverything(); },
      stop: function() { jsPlumb.repaintEverything(); }
    },

    initialize: function(options) {
      DialogueStateGridView.__super__.initialize.call(this, options);

      this.states = options.states;
      this.states.eachItem(
        function(id, state) { this.addState(id, state, {sort: false}); },
        this);
      this.items.sort();

      var $add = $('<button>')
        .addClass('add btn btn-primary')
        .text('+');

      var $addContainer = $('<div>')
        .addClass('item add-container')
        .append($add);

      this.add('add-btn', $addContainer, {index: Infinity});

      this.listenTo(this.states, 'add', this.addState);
      this.listenTo(this.states, 'remove', this.remove);
      this.on('reorder', this.onReorder, this);
    },

    onAddClick: function(e) {
      e.preventDefault();
      this.states.add();
    },

    onReorder: function(keys) {
      // The grid items have their indices reset when the user sorts the items
      // in the UI. We need to ensure the add button stays at the end, so we
      // need to change it back to `Infinity` each reorder
      this.items
        .get('add-btn')
        .data('grid:index', Infinity);

      // Remove the add button from the keys
      keys.pop();

      this.states.rearrange(keys);
    },

    addState: function(id, state, options) {
      options = _(options || {}).defaults({index: state.model.get('ordinal')});
      return this.add(id, state, options);
    }
  });

  var DialogueStateCollection = StateViewCollection.extend({
    type: DialogueStateView,

    ordered: true,
    comparator: function(state) { return state.model.get('ordinal'); },

    arrangeable: true,
    arranger: function(state, ordinal) {
      state.model.set('ordinal', ordinal, {silent: true});
    },

    defaultMode: 'preview',

    viewOptions: function() {
      var opts = DialogueStateCollection.__super__.viewOptions.call(this);
      return _({mode: this.defaultMode}).defaults(opts);
    },

    modelDefaults: function() {
      return {
        type: 'choice',
        name: '',
        ordinal: this.size()
      };
    },

    constructor: function(options) {
      DialogueStateCollection.__super__.constructor.call(this, options);
      this.grid = new DialogueStateGridView({states: this});

      // Change the default mode to edit once initialisation is done so new
      // states can be rendered in edit mode.
      this.defaultMode = 'edit';
    },

    // Removes a state and creates a new state of a different type in the same
    // position as the old state
    reset: function(state, type) {
      this.remove(state);

      this.add({
        model: {
          type: type,
          name: state.model.get('name'),
          ordinal: state.model.get('ordinal')
        }
      });

      return this;
    },

    render: function() {
      this.view.$el.append(this.grid.$el);
      this.grid.render();

      this.each(function(s) { s.render(); });
      return this;
    }
  });

  _(exports).extend({
    EntryEndpointView: EntryEndpointView,
    ExitEndpointView: ExitEndpointView,

    DialogueStateModeView: DialogueStateModeView,
    DialogueStatePreviewView: DialogueStatePreviewView,
    DialogueStateEditView: DialogueStateEditView,

    DialogueStateView: DialogueStateView,
    DialogueStateGridView: DialogueStateGridView,
    DialogueStateCollection: DialogueStateCollection
  });
})(go.campaign.dialogue.states = {});
<commit_msg>Change DialogueStateModeView to extend TemplateView instead of comprising it<commit_after>// go.campaign.dialogue.states
// ===========================
// Structures for each dialogue state type

(function(exports) {
  var maybeByName = go.utils.maybeByName,
      GridView = go.components.grid.GridView,
      ConfirmView = go.components.views.ConfirmView,
      TemplateView = go.components.views.TemplateView;

  var plumbing = go.components.plumbing;

  var states = plumbing.states,
      StateView = states.StateView,
      StateViewCollection = states.StateViewCollection;

  var endpoints = plumbing.endpoints,
      ParametricEndpointView = endpoints.ParametricEndpointView,
      AligningEndpointCollection = endpoints.AligningEndpointCollection;

  var DialogueEndpointView = ParametricEndpointView.extend();

  var EntryEndpointView = DialogueEndpointView.extend({
    side: 'left',
    isSource: false
  });

  var ExitEndpointView = DialogueEndpointView.extend({
    side: 'right',
    isTarget: false
  });

  // Base 'mode' for state views. Each mode acts as a 'delegate view',
  // targeting a dialogue view's element and acting according to the mode type
  // (for eg, `edit`) and state type (for eg, `freetext`).
  var DialogueStateModeView = TemplateView.extend({
    jst: _.template(''),

    data: function() {
      return {
        mode: this,
        state: this.state,
        model: this.state.model
      };
    },

    bodyOptions: {},

    initialize: function(options) {
      DialogueStateModeView.__super__.initialize.call(this, options);
      this.state = options.state;

      this.partials.body = new TemplateView(
        _({data: this.data.bind(this)}).extend(
        _(this).result('bodyOptions')));
    },

    destroy: function() {
      this.$el.remove();
      return this;
    },

    detach: function() {
      this.$el.detach();
      return this;
    }
  });

  // Mode allowing the user to make changes to the dialogue state. Acts as a
  // base for each state type's `edit` mode
  var DialogueStateEditView = DialogueStateModeView.extend({
    jst: 'JST.campaign_dialogue_states_modes_edit',

    className: 'edit mode',

    events: {
      'click .ok': 'onOk',
      'click .cancel': 'onCancel',
      'change .type': 'onTypeChange',
      'change .name': 'onNameChange'
    },

    resetModal: new ConfirmView({
      optional: true,
      content: "Changing the message's type will break its connections " +
               "and reset its content."
    }),

    initialize: function(options) {
      DialogueStateEditView.__super__.initialize.call(this, options);
      this.backupModel();

      this.on('activate', this.backupModel, this);
    },

    onOk: function(e) {
      e.preventDefault();
      this.state.preview();
    },

    onCancel: function(e) {
      e.preventDefault();
      this.cancel();
      this.state.preview();
    },

    onTypeChange: function(e) {
      var $option = $(e.target);

      // Using `on` is okay, since the events are unbound when either of the
      // buttons are clicked. Simply using `once` won't work, since the event
      // for the unclicked button will remain bound.
      this.resetModal
        .on(
          'ok',
          function() { this.state.reset($option.val()); }, this)
        .on(
          'cancel',
          function() { this.$('.type').val(this.state.typeName); }, this)
        .show();
    },

    onNameChange: function(e) {
      this.state.model.set('name', $(e.target).val(), {silent: true});
      return this;
    },

    // Keep a backup to restore the model for when the user cancels the edit
    backupModel: function() {
      this.modelBackup = this.state.model.toJSON();
      return this;
    },

    cancel: function() {
      var model = this.state.model;
      if (this.modelBackup) { model.set(this.modelBackup); }
      return this;
    },

    render: function() {
      DialogueStateEditView.__super__.render.call(this);
      this.$('.type').val(this.state.typeName);
      return this;
    }
  });

  // Mode for a 'read-only' preview of the dialogue state. Acts as a base for
  // each state type's `preview` mode
  var DialogueStatePreviewView = DialogueStateModeView.extend({
    jst: 'JST.campaign_dialogue_states_modes_preview',

    className: 'preview mode',

    events: {
      'click .edit-switch': 'onEditSwitch'
    },

    onEditSwitch: function(e) {
      e.preventDefault();
      this.state.edit();
    }
  });

  // Base view for dialogue states. Dynamically switches between modes
  // (`edit`, `preview`).
  var DialogueStateView = StateView.extend({
    switchModeDefaults: {render: true, silent: false},

    className: function() { return 'box item state ' + this.typeName || ''; },

    editModeType: DialogueStateEditView,
    previewModeType: DialogueStatePreviewView,

    endpointType: DialogueEndpointView,
    endpointCollectionType: AligningEndpointCollection,

    subtypes: {
      dummy: 'go.campaign.dialogue.states.dummy.DummyStateView',
      choice: 'go.campaign.dialogue.states.choice.ChoiceStateView',
      freetext: 'go.campaign.dialogue.states.freetext.FreeTextStateView',
      end: 'go.campaign.dialogue.states.end.EndStateView'
    },

    events: {
      'mousedown .titlebar': 'onTitlebarHold',
      'click .titlebar .remove': 'onRemove'
    },

    initialize: function(options) {
      StateView.prototype.initialize.call(this, options);

      if (!this.model.has('ordinal')) {
        this.model.set('ordinal', this.collection.size(), {silent: true});
      }

      this.modes = {
        edit: new this.editModeType({state: this}),
        preview: new this.previewModeType({state: this})
      };

      this.switchMode(options.mode || 'preview', {render: false});
    },

    onTitlebarHold: function(e) {
      if (this.isConnected()) { this.$el.addClass('locked'); }
      else { this.$el.removeClass('locked'); }
    },

    onRemove: function(e) {
      e.preventDefault();
      this.collection.remove(this);
    },

    // 'Resets' a state to a new type by removing the current state, and
    // replacing it with a new state in the same position
    reset: function(type) {
      // TODO warn the user of the destruction involved
      this.collection.reset(this, type);
    },

    switchMode: function(modeName, options) {
      options = _(options || {}).defaults(this.switchModeDefaults);
      var mode = this.modes[modeName] || this.modes.preview;

      if (this.mode) {
        if (!options.silent) { this.mode.trigger('deactivate'); }
        this.mode.detach();
      }

      this.mode = mode;
      this.modeName = modeName;

      if (!options.silent) { this.mode.trigger('activate'); }
      if (options.render) {
        this.render();
        jsPlumb.repaintEverything();
      }
      return this;
    },

    preview: function(options) {
      return this.switchMode('preview', options);
    },

    edit: function(options) {
      return this.switchMode('edit', options);
    },

    render: function() {
      this.mode
        .render()
        .$el
        .appendTo(this.$el);

      this.endpoints.render();
      return this;
    }
  });

  var DialogueStateGridView = GridView.extend({
    className: 'grid container boxes',

    events: {
      'click .add': 'onAddClick'
    },

    sortableOptions: {
      items: '.item:not(.add-container)',
      cancel: '.locked,input',
      handle: '.titlebar',
      placeholder: 'placeholder',
      sort: function() { jsPlumb.repaintEverything(); },
      stop: function() { jsPlumb.repaintEverything(); }
    },

    initialize: function(options) {
      DialogueStateGridView.__super__.initialize.call(this, options);

      this.states = options.states;
      this.states.eachItem(
        function(id, state) { this.addState(id, state, {sort: false}); },
        this);
      this.items.sort();

      var $add = $('<button>')
        .addClass('add btn btn-primary')
        .text('+');

      var $addContainer = $('<div>')
        .addClass('item add-container')
        .append($add);

      this.add('add-btn', $addContainer, {index: Infinity});

      this.listenTo(this.states, 'add', this.addState);
      this.listenTo(this.states, 'remove', this.remove);
      this.on('reorder', this.onReorder, this);
    },

    onAddClick: function(e) {
      e.preventDefault();
      this.states.add();
    },

    onReorder: function(keys) {
      // The grid items have their indices reset when the user sorts the items
      // in the UI. We need to ensure the add button stays at the end, so we
      // need to change it back to `Infinity` each reorder
      this.items
        .get('add-btn')
        .data('grid:index', Infinity);

      // Remove the add button from the keys
      keys.pop();

      this.states.rearrange(keys);
    },

    addState: function(id, state, options) {
      options = _(options || {}).defaults({index: state.model.get('ordinal')});
      return this.add(id, state, options);
    }
  });

  var DialogueStateCollection = StateViewCollection.extend({
    type: DialogueStateView,

    ordered: true,
    comparator: function(state) { return state.model.get('ordinal'); },

    arrangeable: true,
    arranger: function(state, ordinal) {
      state.model.set('ordinal', ordinal, {silent: true});
    },

    defaultMode: 'preview',

    viewOptions: function() {
      var opts = DialogueStateCollection.__super__.viewOptions.call(this);
      return _({mode: this.defaultMode}).defaults(opts);
    },

    modelDefaults: function() {
      return {
        type: 'choice',
        name: '',
        ordinal: this.size()
      };
    },

    constructor: function(options) {
      DialogueStateCollection.__super__.constructor.call(this, options);
      this.grid = new DialogueStateGridView({states: this});

      // Change the default mode to edit once initialisation is done so new
      // states can be rendered in edit mode.
      this.defaultMode = 'edit';
    },

    // Removes a state and creates a new state of a different type in the same
    // position as the old state
    reset: function(state, type) {
      this.remove(state);

      this.add({
        model: {
          type: type,
          name: state.model.get('name'),
          ordinal: state.model.get('ordinal')
        }
      });

      return this;
    },

    render: function() {
      this.view.$el.append(this.grid.$el);
      this.grid.render();

      this.each(function(s) { s.render(); });
      return this;
    }
  });

  _(exports).extend({
    EntryEndpointView: EntryEndpointView,
    ExitEndpointView: ExitEndpointView,

    DialogueStateModeView: DialogueStateModeView,
    DialogueStatePreviewView: DialogueStatePreviewView,
    DialogueStateEditView: DialogueStateEditView,

    DialogueStateView: DialogueStateView,
    DialogueStateGridView: DialogueStateGridView,
    DialogueStateCollection: DialogueStateCollection
  });
})(go.campaign.dialogue.states = {});
<|endoftext|>


<commit_before>/*
 *
 * (c) Copyright Ascensio System Limited 2010-2017
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
*/
/**
 *    Chat.js
 *
 *    Controller
 *
 *    Created by Maxim Kadushkin on 27 February 2014
 *    Copyright (c) 2014 Ascensio System SIA. All rights reserved.
 *
 */

define([
    'core',
    'common/main/lib/collection/Users',
    'common/main/lib/collection/ChatMessages',
    'common/main/lib/view/Chat'
], function () {
    'use strict';

    Common.Controllers.Chat = Backbone.Controller.extend(_.extend({
        models: [],
        collections: [
            'Common.Collections.Users',
            'Common.Collections.ChatMessages'
        ],
        views: [
            'Common.Views.Chat'
        ],

        initialize: function() {
            this.addListeners({
                'Common.Views.Chat': {
                    'message:add': _.bind(this.onSendMessage, this)
                }
            });

            var me = this;
            Common.NotificationCenter.on('layout:changed', function(area){
                Common.Utils.asyncCall(function(e) {
                    if ( e == 'toolbar' && me.panelChat.$el.is(':visible') ) {
                        me.panelChat.updateLayout(true);
                        me.panelChat.setupAutoSizingTextBox();
                    }
                }, this, area);
            });
        },

        events: {
        },

        onLaunch: function() {
            this.panelChat = this.createView('Common.Views.Chat', {
                storeUsers: this.getApplication().getCollection('Common.Collections.Users'),
                storeMessages: this.getApplication().getCollection('Common.Collections.ChatMessages')
            });
        },

        setMode: function(mode) {
            this.mode = mode;

            if (this.api) {
                if (this.mode.canCoAuthoring && this.mode.canChat)
                    this.api.asc_registerCallback('asc_onCoAuthoringChatReceiveMessage', _.bind(this.onReceiveMessage, this));

                if ( !this.mode.isEditDiagram && !this.mode.isEditMailMerge ) {
                    this.api.asc_registerCallback('asc_onAuthParticipantsChanged', _.bind(this.onUsersChanged, this));
                    this.api.asc_registerCallback('asc_onConnectionStateChanged', _.bind(this.onUserConnection, this));
                    this.api.asc_coAuthoringGetUsers();
                }

                if (this.mode.canCoAuthoring && this.mode.canChat)
                    this.api.asc_coAuthoringChatGetMessages();
            }
            return this;
        },

        setApi: function(api) {
            this.api = api;

            return this;
        },

        onUsersChanged: function(users){
            if (!this.mode.canLicense || !this.mode.canCoAuthoring) {
                var len = 0;
                for (name in users) {
                    if (undefined !== name) len++;
                }
                if (len>1 && this._isCoAuthoringStopped==undefined) {
                    this._isCoAuthoringStopped = true;
                    this.api.asc_coAuthoringDisconnect();
                    Common.NotificationCenter.trigger('api:disconnect');
                /*
                    setTimeout(_.bind(function(){
                        Common.UI.alert({
                            closable: false,
                            title: this.notcriticalErrorTitle,
                            msg: this.textUserLimit,
                            iconCls: 'warn',
                            buttons: ['ok']
                        });
                    }, this), 100);
                */
                    return;
                }
            }

            var usersStore = this.getApplication().getCollection('Common.Collections.Users');

            if (usersStore) {
                var arrUsers = [], name, user;

                for (name in users) {
                    if (undefined !== name) {
                        user = users[name];
                        if (user) {
                            arrUsers.push(new Common.Models.User({
                                id          : user.asc_getId(),
                                username    : user.asc_getUserName(),
                                online      : true,
                                color       : user.asc_getColor(),
                                view        : user.asc_getView()
                            }));
                        }
                    }
                }

                usersStore[usersStore.size() > 0 ? 'add' : 'reset'](arrUsers);
            }
        },

        onUserConnection: function(change){
            var usersStore = this.getApplication().getCollection('Common.Collections.Users');

            if (usersStore){
                var user = usersStore.findUser(change.asc_getId());
                if (!user) {
                    usersStore.add(new Common.Models.User({
                        id          : change.asc_getId(),
                        username    : change.asc_getUserName(),
                        online      : change.asc_getState(),
                        color       : change.asc_getColor(),
                        view        : change.asc_getView()
                    }));
                } else {
                    user.set({online: change.asc_getState()});
                }
            }
        },

        onReceiveMessage: function(messages, clear){
            var msgStore = this.getApplication().getCollection('Common.Collections.ChatMessages');

            if ( msgStore ) {
                var array = [];
                messages.forEach(function(msg) {
                    array.push(new Common.Models.ChatMessage({
                        userid      : msg.user,
                        message     : msg.message,
                        username    : msg.username
                    }));
                });

                msgStore[(msgStore.size() < 1 || clear) ? 'reset' : 'add'](array);
            }
        },

        onSendMessage: function(panel, text){
            if (text.length > 0){
                var splitString = function(string, chunkSize) {
                    var chunks = [];

                    while (string) {
                        if (string.length < chunkSize) {
                            chunks.push(string);
                            break;
                        } else {
                            chunks.push(string.substr(0, chunkSize));
                            string = string.substr(chunkSize);
                        }
                    }

                    return chunks;
                };

                var me = this;
                splitString(text, 2048).forEach(function(message) {
                    me.api.asc_coAuthoringChatSendMessage(message);
                });
            }
        },

        notcriticalErrorTitle: 'Warning',
        textUserLimit: 'You are using ONLYOFFICE Editors free version.
Only two users can co-edit the document simultaneously.
Want more? Consider buying ONLYOFFICE Editors Pro version.
Read more'
    }, Common.Controllers.Chat || {}));
});<commit_msg>Fix Bug 31420.<commit_after>/*
 *
 * (c) Copyright Ascensio System Limited 2010-2017
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
*/
/**
 *    Chat.js
 *
 *    Controller
 *
 *    Created by Maxim Kadushkin on 27 February 2014
 *    Copyright (c) 2014 Ascensio System SIA. All rights reserved.
 *
 */

define([
    'core',
    'common/main/lib/collection/Users',
    'common/main/lib/collection/ChatMessages',
    'common/main/lib/view/Chat'
], function () {
    'use strict';

    Common.Controllers.Chat = Backbone.Controller.extend(_.extend({
        models: [],
        collections: [
            'Common.Collections.Users',
            'Common.Collections.ChatMessages'
        ],
        views: [
            'Common.Views.Chat'
        ],

        initialize: function() {
            this.addListeners({
                'Common.Views.Chat': {
                    'message:add': _.bind(this.onSendMessage, this)
                }
            });

            var me = this;
            Common.NotificationCenter.on('layout:changed', function(area){
                Common.Utils.asyncCall(function(e) {
                    if ( e == 'toolbar' && me.panelChat.$el.is(':visible') ) {
                        me.panelChat.updateLayout(true);
                        me.panelChat.setupAutoSizingTextBox();
                    }
                }, this, area);
            });
        },

        events: {
        },

        onLaunch: function() {
            this.panelChat = this.createView('Common.Views.Chat', {
                storeUsers: this.getApplication().getCollection('Common.Collections.Users'),
                storeMessages: this.getApplication().getCollection('Common.Collections.ChatMessages')
            });
        },

        setMode: function(mode) {
            this.mode = mode;

            if (this.api) {
                if (this.mode.canCoAuthoring && this.mode.canChat)
                    this.api.asc_registerCallback('asc_onCoAuthoringChatReceiveMessage', _.bind(this.onReceiveMessage, this));

                if ( !this.mode.isEditDiagram && !this.mode.isEditMailMerge ) {
                    this.api.asc_registerCallback('asc_onAuthParticipantsChanged', _.bind(this.onUsersChanged, this));
                    this.api.asc_registerCallback('asc_onConnectionStateChanged', _.bind(this.onUserConnection, this));
                    this.api.asc_coAuthoringGetUsers();
                }

                if (this.mode.canCoAuthoring && this.mode.canChat)
                    this.api.asc_coAuthoringChatGetMessages();
            }
            return this;
        },

        setApi: function(api) {
            this.api = api;

            return this;
        },

        onUsersChanged: function(users, currentUserId){
            if (!this.mode.canLicense || !this.mode.canCoAuthoring) {
                var len = 0;
                for (name in users) {
                    if (undefined !== name) len++;
                }
                if (len>1 && this._isCoAuthoringStopped==undefined) {
                    this._isCoAuthoringStopped = true;
                    this.api.asc_coAuthoringDisconnect();
                    Common.NotificationCenter.trigger('api:disconnect');
                /*
                    setTimeout(_.bind(function(){
                        Common.UI.alert({
                            closable: false,
                            title: this.notcriticalErrorTitle,
                            msg: this.textUserLimit,
                            iconCls: 'warn',
                            buttons: ['ok']
                        });
                    }, this), 100);
                */
                    return;
                }
            }

            var usersStore = this.getApplication().getCollection('Common.Collections.Users');

            if (usersStore) {
                var arrUsers = [], name, user;

                for (name in users) {
                    if (undefined !== name) {
                        user = users[name];
                        if (user) {
                            var usermodel = new Common.Models.User({
                                id          : user.asc_getId(),
                                username    : user.asc_getUserName(),
                                online      : true,
                                color       : user.asc_getColor(),
                                view        : user.asc_getView()
                            });
                            arrUsers[(user.asc_getId() == currentUserId ) ? 'unshift' : 'push'](usermodel);
                        }
                    }
                }

                usersStore[usersStore.size() > 0 ? 'add' : 'reset'](arrUsers);
            }
        },

        onUserConnection: function(change){
            var usersStore = this.getApplication().getCollection('Common.Collections.Users');

            if (usersStore){
                var user = usersStore.findUser(change.asc_getId());
                if (!user) {
                    usersStore.add(new Common.Models.User({
                        id          : change.asc_getId(),
                        username    : change.asc_getUserName(),
                        online      : change.asc_getState(),
                        color       : change.asc_getColor(),
                        view        : change.asc_getView()
                    }));
                } else {
                    user.set({online: change.asc_getState()});
                }
            }
        },

        onReceiveMessage: function(messages, clear){
            var msgStore = this.getApplication().getCollection('Common.Collections.ChatMessages');

            if ( msgStore ) {
                var array = [];
                messages.forEach(function(msg) {
                    array.push(new Common.Models.ChatMessage({
                        userid      : msg.user,
                        message     : msg.message,
                        username    : msg.username
                    }));
                });

                msgStore[(msgStore.size() < 1 || clear) ? 'reset' : 'add'](array);
            }
        },

        onSendMessage: function(panel, text){
            if (text.length > 0){
                var splitString = function(string, chunkSize) {
                    var chunks = [];

                    while (string) {
                        if (string.length < chunkSize) {
                            chunks.push(string);
                            break;
                        } else {
                            chunks.push(string.substr(0, chunkSize));
                            string = string.substr(chunkSize);
                        }
                    }

                    return chunks;
                };

                var me = this;
                splitString(text, 2048).forEach(function(message) {
                    me.api.asc_coAuthoringChatSendMessage(message);
                });
            }
        },

        notcriticalErrorTitle: 'Warning',
        textUserLimit: 'You are using ONLYOFFICE Editors free version.
Only two users can co-edit the document simultaneously.
Want more? Consider buying ONLYOFFICE Editors Pro version.
Read more'
    }, Common.Controllers.Chat || {}));
});<|endoftext|>


<commit_before>// javascript for the httpclient
url = "/http/proxy/";

$(document).ready(function(){
	$('#form').submit(function(){ sendMsg(); return false; });
	setInterval("checkMsgs()", 500);
});

function sendMsg() {
	if ($('#phone').val().length > 0 && $('#message').val().length > 0) {
		req = url + $('#phone').val() + "/" + $('#message').val();
		$.getJSON(
			req,
			function (response) { if (response) {
				snippet = '
' + response.phone + '	«	' + decode(response.message) + '	' + decode(response.message).length + ' characters
';
				$('#log').append(snippet);
				fixClasses();
				$('div.tester').scrollTo('#log tr:last', 800);
				$('#message').val("");
			}}
		);
	}
}

function fixClasses(){
	$('#log tr').removeClass('first');
	$('#log tr').removeClass('last');
	$('#log tr:first').addClass('first');
	$('#log tr:last').addClass('last');
}

function decode(str) {
	str = str.replace(/%23/gi, "#");
	str = str.replace(/%24/gi, "$");
	str = str.replace(/%26/gi, "&");
	str = str.replace(/%3D/gi, "=");
	str = str.replace(/%3B/gi, ";");
	str = str.replace(/%2C/gi, ",");
	str = str.replace(/%3A/gi, ":");
	str = str.replace(/%3F/gi, "?");
	str = decodeURI(str);
	return str;
}

function checkMsgs() {
	if ($('#phone').val().length > 0) {
		req = url + $('#phone').val() + "/json_resp";
		$.getJSON(
			req,
			function (response) { if (response) {
				snippet = '
' + response.phone + '	»	' + decode(response.message) + '	' + decode(response.message).length + ' characters
';
				$('#log').append(snippet);
				fixClasses();
				$('div.tester').scrollTo('#log tr:last', 800);
			}}

		);
	}
}
<commit_msg>adding logic to url escape the messages in the tester<commit_after>// javascript for the httpclient
url = "/http/proxy/";

$(document).ready(function(){
	$('#form').submit(function(){ sendMsg(); return false; });
	setInterval("checkMsgs()", 500);
});

function sendMsg() {
	if ($('#phone').val().length > 0 && $('#message').val().length > 0) {
		req = url + $('#phone').val() + "/" + escape($('#message').val());
		$.getJSON(
			req,
			function (response) { if (response) {
				snippet = '
' + response.phone + '	«	' + decode(response.message) + '	' + decode(response.message).length + ' characters
';
				$('#log').append(snippet);
				fixClasses();
				$('div.tester').scrollTo('#log tr:last', 800);
				$('#message').val("");
			}}
		);
	}
}

function fixClasses(){
	$('#log tr').removeClass('first');
	$('#log tr').removeClass('last');
	$('#log tr:first').addClass('first');
	$('#log tr:last').addClass('last');
}

function decode(str) {
	str = str.replace(/%23/gi, "#");
	str = str.replace(/%24/gi, "$");
	str = str.replace(/%26/gi, "&");
	str = str.replace(/%3D/gi, "=");
	str = str.replace(/%3B/gi, ";");
	str = str.replace(/%2C/gi, ",");
	str = str.replace(/%3A/gi, ":");
	str = str.replace(/%3F/gi, "?");
	str = decodeURI(str);
	return str;
}

function checkMsgs() {
	if ($('#phone').val().length > 0) {
		req = url + $('#phone').val() + "/json_resp";
		$.getJSON(
			req,
			function (response) { if (response) {
				snippet = '
' + response.phone + '	»	' + decode(response.message) + '	' + decode(response.message).length + ' characters
';
				$('#log').append(snippet);
				fixClasses();
				$('div.tester').scrollTo('#log tr:last', 800);
			}}

		);
	}
}
<|endoftext|>


<commit_before>var get = Ember.get, set = Ember.set;
var application, controller, buttonDropdown;

module("Bootstrap.ButtonDropdown", {
  setup: function() {
    application = Ember.Application.create();
    controller = Ember.ArrayController.create({
        content: Ember.A([
            Ember.Object.create({ label: 'First Link', actionName: 'testAction' }),
            Ember.Object.create({ label: 'Second Link', actionName: 'anotherAction', disabled: true })
        ])
    });
    buttonDropdown = Bootstrap.ButtonDropdown.create({ controller: controller });
  },
  teardown: function() {
    Ember.run(function() {
      destroyIfNecessary(buttonDropdown);
      destroyIfNecessary(application);
    });
  }
});

test("a button dropdown can be created and appended to DOM", function() {
    appendIntoDOM(buttonDropdown);
    ok(isAppendedToDOM(buttonDropdown), 'a button dropdown has a layer in the DOM');
});

test("can accept a list of items to use for the dropdown", function() {
    buttonDropdown.set('items', controller.get('content'));
    equal(buttonDropdown.get('items.length'), 2, 'is aware of the items from the controller');
});

test("can accept a label for the dropdown's title", function() {
    buttonDropdown.set('label', 'My Label');
    equal(buttonDropdown.get('label'), 'My Label', 'is able to set a title for the dropdown');
});

test("can append an item to the dropdown", function() {
    buttonDropdown.set('items', controller.get('content'));
    appendIntoDOM(buttonDropdown);
    var view = buttonDropdown.$();
    equal(view.find('li').length, 2);

    Ember.run(function() {
        controller.get('content').pushObject(Ember.Object.create({ label: 'Third Link', actionName: 'noop' }));
    });

    equal(view.find('li').length, 3);
});

test("can remove an item from the dropdown", function() {
    buttonDropdown.set('items', controller.get('content'));
    appendIntoDOM(buttonDropdown);
    var view = buttonDropdown.$();
    equal(view.find('li').length, 2);

    Ember.run(function() {
        var secondObject = controller.get('content').findProperty('label', 'Second Link');
        controller.get('content').removeObject(secondObject);
    });

    equal(view.find('li').length, 1);
});<commit_msg>Added comments to the two new tests<commit_after>var get = Ember.get, set = Ember.set;
var application, controller, buttonDropdown;

module("Bootstrap.ButtonDropdown", {
  setup: function() {
    application = Ember.Application.create();
    controller = Ember.ArrayController.create({
        content: Ember.A([
            Ember.Object.create({ label: 'First Link', actionName: 'testAction' }),
            Ember.Object.create({ label: 'Second Link', actionName: 'anotherAction', disabled: true })
        ])
    });
    buttonDropdown = Bootstrap.ButtonDropdown.create({ controller: controller });
  },
  teardown: function() {
    Ember.run(function() {
      destroyIfNecessary(buttonDropdown);
      destroyIfNecessary(application);
    });
  }
});

test("a button dropdown can be created and appended to DOM", function() {
    appendIntoDOM(buttonDropdown);
    ok(isAppendedToDOM(buttonDropdown), 'a button dropdown has a layer in the DOM');
});

test("can accept a list of items to use for the dropdown", function() {
    buttonDropdown.set('items', controller.get('content'));
    equal(buttonDropdown.get('items.length'), 2, 'is aware of the items from the controller');
});

test("can accept a label for the dropdown's title", function() {
    buttonDropdown.set('label', 'My Label');
    equal(buttonDropdown.get('label'), 'My Label', 'is able to set a title for the dropdown');
});

test("can append an item to the dropdown", function() {
    buttonDropdown.set('items', controller.get('content'));
    appendIntoDOM(buttonDropdown);
    var view = buttonDropdown.$();
    equal(view.find('li').length, 2);

    Ember.run(function() {
        controller.get('content').pushObject(Ember.Object.create({ label: 'Third Link', actionName: 'noop' }));
    });

    equal(view.find('li').length, 3);
});

test("can remove an item from the dropdown", function() {
    buttonDropdown.set('items', controller.get('content'));
    appendIntoDOM(buttonDropdown);
    var view = buttonDropdown.$();
    equal(view.find('li').length, 2, 'Can add an element from the dropdown list');

    Ember.run(function() {
        var secondObject = controller.get('content').findProperty('label', 'Second Link');
        controller.get('content').removeObject(secondObject);
    });

    equal(view.find('li').length, 1, 'Can remove an element from the dropdown list');
});<|endoftext|>