<commit_before>var _ = require('lodash');
var index = 0;

// number of images to show in the album preview grid
var PREVIEW_COUNT = 4;

var SORT_ALBUMS_BY = {
  'title': function(album) { return album.title; },
  'start-date': function(album) { return album.stats.fromDate; },
  'end-date': function(album) { return album.stats.toDate; }
};

var SORT_MEDIA_BY = {
  'filename': function(file) { return file.filename; },
  'date': function(file) { return file.date; }
};

var PREVIEW_MISSING = {
  urls: {
    thumb: 'public/missing.png'
  }
};

function Album(opts) {
  if (typeof opts === 'string') opts = { title: opts };
  this.id = opts.id || ++index;
  this.title = opts.title || ('Album ' + this.id);
  this.filename = sanitise(this.title);
  this.files = opts.files || [];
  this.albums = opts.albums || [];
  this.depth = 0;
  this.home = false;
  this.stats = null;
  this.previews = null;
  this.allFiles = [];
}

Album.prototype.finalize = function(options) {
  // is this the top-level album?
  this.home = this.depth === 0;
  // finalize all nested albums first (recursive)
  // and set a nested filename
  for (var i = 0; i < this.albums.length; ++i) {
    this.albums[i].filename = this.filename + '-' + this.albums[i].filename;
    this.albums[i].depth = this.depth + 1;
    this.albums[i].finalize();
  }
  // perform stats & other calculations
  // once the nested albums have been finalized too
  this.calculateStats();
  this.calculateSummary();
  this.sort(options);
  this.pickPreviews();
  this.aggregateAllFiles();
};

Album.prototype.calculateStats = function() {
  // nested albums
  var nestedPhotos    = _.map(this.albums, 'stats.photos');
  var nestedVideos    = _.map(this.albums, 'stats.videos');
  var nestedFromDates = _.map(this.albums, 'stats.fromDate');
  var nestedToDates   = _.map(this.albums, 'stats.toDate');
  // current level
  var currentPhotos   = _.filter(this.files, {isVideo: false}).length;
  var currentVideos   = _.filter(this.files, {isVideo: true}).length;
  var currentFromDate = _.map(this.files, 'date');
  var currentToDate   = _.map(this.files, 'date');
  // aggregate all stats
  this.stats = {
    albums:   this.albums.length,
    photos:   _.sum(_.compact(_.concat(nestedPhotos, currentPhotos))) || 0,
    videos:   _.sum(_.compact(_.concat(nestedVideos, currentVideos))) || 0,
    fromDate: _.min(_.compact(_.concat(nestedFromDates, currentFromDate))),
    toDate:   _.max(_.compact(_.concat(nestedToDates, currentToDate)))
  };
  this.stats.total = this.stats.photos + this.stats.videos;
}

Album.prototype.calculateSummary = function() {
  var items = [
    itemCount(this.stats.albums, 'album'),
    itemCount(this.stats.photos, 'photo'),
    itemCount(this.stats.videos, 'video')
  ];
  this.summary = _.compact(items).join(', ');
};

Album.prototype.sort = function(options) {
  this.files = _.orderBy(this.files, SORT_MEDIA_BY[options.sortMediaBy], options.sortMediaDirection);
  this.albums = _.orderBy(this.albums, SORT_ALBUMS_BY[options.sortAlbumsBy], options.sortAlbumsDirection);
  this.albums.forEach(function(nested) {
    nested.sort(options);
  });
};

Album.prototype.pickPreviews = function() {
  // also consider previews from nested albums
  var nestedPicks =  _.flatten(_.map(this.albums, 'previews')).filter(function(file) {
    return file !== PREVIEW_MISSING;
  });
  // then pick the top 4 overall
  var potentialPicks = _.concat(this.files, nestedPicks);
  this.previews = potentialPicks.slice(0, PREVIEW_COUNT);
  // and fill the gap with a placeholder
  var missing = PREVIEW_COUNT - this.previews.length;
  for (var i = 0; i < missing; ++i) {
    this.previews.push(PREVIEW_MISSING);
  }
};

Album.prototype.aggregateAllFiles = function() {
  var nestedFiles = _.flatten(_.map(this.albums, 'allFiles'))
  this.allFiles = _.concat(nestedFiles, this.files);
};

function sanitise(filename) {
  return filename.replace(/[^a-z0-9-_]/ig, '');
}

function itemCount(count, type) {
  if (count === 0) return '';
  var plural = (count > 1) ? 's' : '';
  return '' + count + ' ' + type + plural;
}

// for testing purposes
Album.resetIds = function() {
  index = 0;
};

module.exports = Album;
<commit_msg>Fix unit tests (album.finalise argument should be optional)<commit_after>var _ = require('lodash');
var index = 0;

// number of images to show in the album preview grid
var PREVIEW_COUNT = 4;

var SORT_ALBUMS_BY = {
  'title': function(album) { return album.title; },
  'start-date': function(album) { return album.stats.fromDate; },
  'end-date': function(album) { return album.stats.toDate; }
};

var SORT_MEDIA_BY = {
  'filename': function(file) { return file.filename; },
  'date': function(file) { return file.date; }
};

var PREVIEW_MISSING = {
  urls: {
    thumb: 'public/missing.png'
  }
};

function Album(opts) {
  if (typeof opts === 'string') opts = { title: opts };
  this.id = opts.id || ++index;
  this.title = opts.title || ('Album ' + this.id);
  this.filename = sanitise(this.title);
  this.files = opts.files || [];
  this.albums = opts.albums || [];
  this.depth = 0;
  this.home = false;
  this.stats = null;
  this.previews = null;
  this.allFiles = [];
}

Album.prototype.finalize = function(options) {
  options = options || {};
  // is this the top-level album?
  this.home = this.depth === 0;
  // finalize all nested albums first (recursive)
  // and set a nested filename
  for (var i = 0; i < this.albums.length; ++i) {
    this.albums[i].filename = this.filename + '-' + this.albums[i].filename;
    this.albums[i].depth = this.depth + 1;
    this.albums[i].finalize();
  }
  // perform stats & other calculations
  // once the nested albums have been finalized too
  this.calculateStats();
  this.calculateSummary();
  this.sort(options);
  this.pickPreviews();
  this.aggregateAllFiles();
};

Album.prototype.calculateStats = function() {
  // nested albums
  var nestedPhotos    = _.map(this.albums, 'stats.photos');
  var nestedVideos    = _.map(this.albums, 'stats.videos');
  var nestedFromDates = _.map(this.albums, 'stats.fromDate');
  var nestedToDates   = _.map(this.albums, 'stats.toDate');
  // current level
  var currentPhotos   = _.filter(this.files, {isVideo: false}).length;
  var currentVideos   = _.filter(this.files, {isVideo: true}).length;
  var currentFromDate = _.map(this.files, 'date');
  var currentToDate   = _.map(this.files, 'date');
  // aggregate all stats
  this.stats = {
    albums:   this.albums.length,
    photos:   _.sum(_.compact(_.concat(nestedPhotos, currentPhotos))) || 0,
    videos:   _.sum(_.compact(_.concat(nestedVideos, currentVideos))) || 0,
    fromDate: _.min(_.compact(_.concat(nestedFromDates, currentFromDate))),
    toDate:   _.max(_.compact(_.concat(nestedToDates, currentToDate)))
  };
  this.stats.total = this.stats.photos + this.stats.videos;
}

Album.prototype.calculateSummary = function() {
  var items = [
    itemCount(this.stats.albums, 'album'),
    itemCount(this.stats.photos, 'photo'),
    itemCount(this.stats.videos, 'video')
  ];
  this.summary = _.compact(items).join(', ');
};

Album.prototype.sort = function(options) {
  this.files = _.orderBy(this.files, SORT_MEDIA_BY[options.sortMediaBy], options.sortMediaDirection);
  this.albums = _.orderBy(this.albums, SORT_ALBUMS_BY[options.sortAlbumsBy], options.sortAlbumsDirection);
  this.albums.forEach(function(nested) {
    nested.sort(options);
  });
};

Album.prototype.pickPreviews = function() {
  // also consider previews from nested albums
  var nestedPicks =  _.flatten(_.map(this.albums, 'previews')).filter(function(file) {
    return file !== PREVIEW_MISSING;
  });
  // then pick the top 4 overall
  var potentialPicks = _.concat(this.files, nestedPicks);
  this.previews = potentialPicks.slice(0, PREVIEW_COUNT);
  // and fill the gap with a placeholder
  var missing = PREVIEW_COUNT - this.previews.length;
  for (var i = 0; i < missing; ++i) {
    this.previews.push(PREVIEW_MISSING);
  }
};

Album.prototype.aggregateAllFiles = function() {
  var nestedFiles = _.flatten(_.map(this.albums, 'allFiles'))
  this.allFiles = _.concat(nestedFiles, this.files);
};

function sanitise(filename) {
  return filename.replace(/[^a-z0-9-_]/ig, '');
}

function itemCount(count, type) {
  if (count === 0) return '';
  var plural = (count > 1) ? 's' : '';
  return '' + count + ' ' + type + plural;
}

// for testing purposes
Album.resetIds = function() {
  index = 0;
};

module.exports = Album;
<|endoftext|>


<commit_before>// (function(context){

var Is = require('neuro-is').Is,
    Silence = require('../../mixins/silence').Silence,
    Connector = require('../../mixins/connector').Connector,
    Butler = require('../../mixins/butler').Butler,
    signalFactory = require('../../utils/signalFactory');

var cloneVal = function(val){
    switch(typeOf(val)){
        // Dereference the new val if it's an Array
        case 'array': val = val.slice(); break;
        // Or an Object but not an instance of Class
        case 'object':
            if (!val.$constructor || (val.$constructor && !instanceOf(val.$constructor, Class))){
                val = Object.clone(val);
            }
            break;
    }

    return val;
};

var curryGetter = function(type){
    return function(prop){
        return this[type][prop];
    }.overloadGetter();
};

var curryGetData = function(type){
    return function(){
        var props = this.keys(),
            obj = {};

        props.each(function(prop){
            // cloneVal will return a cloned of an Array or Object that is not a Class or the val itself
            obj[prop] = cloneVal(this[type](prop));
        }.bind(this));

        return obj;
    };
};

var Model = new Class({
    Implements: [Connector, Butler, Events, Options, Silence],

    primaryKey: undefined,

    _data: {},

    // _defaults: {},

    _changed: false,

    _changedProperties: {},

    _previousData: {},

    _setting: 0,

    options: {
        // onChange: function(){},
        // 'onChange:key': function(){},
        // onDestroy: function(){},
        // onReset: function(){},
        primaryKey: undefined,
        defaults: {}
    },

    initialize: function(data, options){
        if (instanceOf(data, this.constructor)) {
            return data;
        }

        this.setOptions(options);

        this.setup(data, options);
    },

    setup: function(data, options){
        this.primaryKey = this.options.primaryKey;

        // Set the _data defaults silently because listeners shouldn't need to know that the defaults have been defined
        this.silence(function(){
            this.set(this.options.defaults);
        }.bind(this));

        // Just set the data instead of Object merging. This will skip cloning Class instances.
        if (data) { this.set(data); }

        return this;
    },

    /**
     * Store the key/value pair in the Model instance
     * Signal to property referenced change listener if property value is changed
     *
     * @param  {String} prop Property name to be stored
     * @param  {Array|Function|Number|Object|String} val Property value to be stored
     * @return {Class} The Model instance
     */
    __set: function(prop, val){
        // Store the older prop
        var old = this.get(prop);

        if (!Is.Equal(old, val)) {
            this._changed = true;

            // cloneVal will return a cloned of an Array or Object that is not a Class or the val itself
            this._data[prop] = this._changedProperties[prop] = cloneVal(val);
        }

        return this;
    }.overloadSetter(),

    _set: function(prop, val){
        /**
         * Increment/decrement _setting value so that calls to set method in
         * custom setters won't trigger change and setPrevious. Doing so during
         * setting would cause discrepancies in previously stored data.
         */
        this._setting++;

        this.__set(prop, val);

        this._setting--;

        return this;
    },

    /**
     * Store the key/value pair in the Model instance
     *
     * @param  {String} prop Property name to be stored
     * @param  {Array|Function|Number|Object|String} val Property value to be stored
     *         Function property will be invoked with 'call', bound to the Model instance
     * @return {Class} The Model instance
     */
    set: function(prop, val){
        var isSetting;

        if (prop) {

            isSetting = this.isSetting();

            // store the previously changed property
            !isSetting && this._setPrevious(this.getData());

            /**
             * If the prop arg is a Model, then we should get all the data to set
             */
            prop = instanceOf(prop, Model) ? prop.getData() : prop;

            this._set(prop, val);

            if (!isSetting && this._changed) {
                // Signal any changed properties
                this._onChangeProperty(this._changedProperties);

                // Signal change
                this.signalChange();

                // reset changed and changed properties
                this._resetChanged();
            }
        }

        return this;
    },

    isSetting: function(){
        return !!this._setting;
    },

    /**
     * Unset a data property. It can not be erased so it will be set to undefined
     *
     * @param  {String|Array} prop Property name/names to be unset
     * @return {Class} The Model instance
     */
    unset: function(prop){
        var props = {},
            len, i = 0, item;

        prop = Array.from(prop);
        len = prop.length;

        while(len--){
            props[prop[i++]] = void 0;
        }

        // void 0 is used because 'undefined' is a var that can be changed in some browsers
        this.set(props);

        return this;
    },

    reset: function(prop){
        var props = {},
            defaults = this.options.defaults,
            len, i = 0, item;

        if (prop) {
            prop = Array.from(prop);
            len = prop.length;

            while(len--){
                item = prop[i++];
                props[item] = defaults[item];
            }
        } else {
            props = defaults;
        }

        this.set(props);

        this.signalReset();

        return this;
    },

    /**
     * Retrieve the stored property
     *
     * @param  {String} prop Property name to retrieve
     * @return Value referenced by prop param
     */
    get: curryGetter('_data'),

    /**
     * Retrieve entire data object in Model instance
     *
     * @return {Object}
     */
    getData: curryGetData('get'),

    _setPrevious: function(prop, val){
        this._previousData[prop] = val;
        return this;
    }.overloadSetter(),

    getPrevious: curryGetter('_previousData'),

    getPreviousData: curryGetData('getPrevious'),

    _resetChanged: function(){
        if (this._changed) {
            // reset the changed
            this._changed = false;

            // reset changed properties
            this._changedProperties = {};
        }

        return this;
    },

    /**
     * Signal to 'change:prop' listener if model property has changed
     * @param  {String} prop Name of property
     * @return {[type]}
     */
    _onChangeProperty: function(prop, val){
        if (this._changed) {
            this.signalChangeProperty(prop, val, this.getPrevious(prop));
        }

        return this;
    }.overloadSetter(),

    /**
     * Signal to 'destroy' listener if model is to be destroyed
     *
     * @return {[type]}
     */
    destroy: function(){
        this.signalDestroy();

        return this;
    },

    toJSON: function(){
        return this.getData();
    },

    /**
     * Add a listener to the property change
     * @param  {String|Object}  prop    String or object of string/function pairs
     * @param  {Function}   callback    Function that is executed upon event firing
     * @return {Class}  Class instance
     */
    spy: function(prop, callback){
        if ((Type.isString(prop) && prop in this._data) && Type.isFunction(callback)) {
            this.addEvent('change:' + prop, callback);
        }

        return this;
    }.overloadSetter(),

    /**
     * Remove a listener to the property change
     * @param  {String|Object}  prop    String or object of string/function pairs
     * @param  {Function}   callback    Function that is executed upon event firing.
     * @return {Class}  Class instance
     */
    unspy: function(prop, callback){
        if ((Type.isString(prop) && prop in this._data)) {
            this.removeEvents('change:' + prop, callback);
        }

        return this;
    }.overloadSetter()
});

Model.implement(
    signalFactory(
        ['change', 'destroy', 'reset'],
        {
            signalChangeProperty: function(prop, newVal, oldVal){
                !this.isSilent() && this.fireEvent('change:' + prop, [this, prop, newVal, oldVal]);
                return this;
            }
        }
    )
);

['each', 'subset', 'map', 'filter', 'every', 'some', 'keys', 'values', 'getLength', 'keyOf', 'contains', 'toQueryString'].each(function(method){
    Model.implement(method, function(){
        return Object[method].apply( Object, [this._data].append( Array.from(arguments) ) );
    });
});

exports.Model = Model;
// }(typeof exports != 'undefined' ? exports : window));
<commit_msg>Butler is already being implemented somewhere else.<commit_after>// (function(context){

var Is = require('neuro-is').Is,
    Silence = require('../../mixins/silence').Silence,
    Connector = require('../../mixins/connector').Connector,
    signalFactory = require('../../utils/signalFactory');

var cloneVal = function(val){
    switch(typeOf(val)){
        // Dereference the new val if it's an Array
        case 'array': val = val.slice(); break;
        // Or an Object but not an instance of Class
        case 'object':
            if (!val.$constructor || (val.$constructor && !instanceOf(val.$constructor, Class))){
                val = Object.clone(val);
            }
            break;
    }

    return val;
};

var curryGetter = function(type){
    return function(prop){
        return this[type][prop];
    }.overloadGetter();
};

var curryGetData = function(type){
    return function(){
        var props = this.keys(),
            obj = {};

        props.each(function(prop){
            // cloneVal will return a cloned of an Array or Object that is not a Class or the val itself
            obj[prop] = cloneVal(this[type](prop));
        }.bind(this));

        return obj;
    };
};

var Model = new Class({
    Implements: [Connector, Events, Options, Silence],

    primaryKey: undefined,

    _data: {},

    // _defaults: {},

    _changed: false,

    _changedProperties: {},

    _previousData: {},

    _setting: 0,

    options: {
        // onChange: function(){},
        // 'onChange:key': function(){},
        // onDestroy: function(){},
        // onReset: function(){},
        primaryKey: undefined,
        defaults: {}
    },

    initialize: function(data, options){
        if (instanceOf(data, this.constructor)) {
            return data;
        }

        this.setOptions(options);

        this.setup(data, options);
    },

    setup: function(data, options){
        this.primaryKey = this.options.primaryKey;

        // Set the _data defaults silently because listeners shouldn't need to know that the defaults have been defined
        this.silence(function(){
            this.set(this.options.defaults);
        }.bind(this));

        // Just set the data instead of Object merging. This will skip cloning Class instances.
        if (data) { this.set(data); }

        return this;
    },

    /**
     * Store the key/value pair in the Model instance
     * Signal to property referenced change listener if property value is changed
     *
     * @param  {String} prop Property name to be stored
     * @param  {Array|Function|Number|Object|String} val Property value to be stored
     * @return {Class} The Model instance
     */
    __set: function(prop, val){
        // Store the older prop
        var old = this.get(prop);

        if (!Is.Equal(old, val)) {
            this._changed = true;

            // cloneVal will return a cloned of an Array or Object that is not a Class or the val itself
            this._data[prop] = this._changedProperties[prop] = cloneVal(val);
        }

        return this;
    }.overloadSetter(),

    _set: function(prop, val){
        /**
         * Increment/decrement _setting value so that calls to set method in
         * custom setters won't trigger change and setPrevious. Doing so during
         * setting would cause discrepancies in previously stored data.
         */
        this._setting++;

        this.__set(prop, val);

        this._setting--;

        return this;
    },

    /**
     * Store the key/value pair in the Model instance
     *
     * @param  {String} prop Property name to be stored
     * @param  {Array|Function|Number|Object|String} val Property value to be stored
     *         Function property will be invoked with 'call', bound to the Model instance
     * @return {Class} The Model instance
     */
    set: function(prop, val){
        var isSetting;

        if (prop) {

            isSetting = this.isSetting();

            // store the previously changed property
            !isSetting && this._setPrevious(this.getData());

            /**
             * If the prop arg is a Model, then we should get all the data to set
             */
            prop = instanceOf(prop, Model) ? prop.getData() : prop;

            this._set(prop, val);

            if (!isSetting && this._changed) {
                // Signal any changed properties
                this._onChangeProperty(this._changedProperties);

                // Signal change
                this.signalChange();

                // reset changed and changed properties
                this._resetChanged();
            }
        }

        return this;
    },

    isSetting: function(){
        return !!this._setting;
    },

    /**
     * Unset a data property. It can not be erased so it will be set to undefined
     *
     * @param  {String|Array} prop Property name/names to be unset
     * @return {Class} The Model instance
     */
    unset: function(prop){
        var props = {},
            len, i = 0, item;

        prop = Array.from(prop);
        len = prop.length;

        while(len--){
            props[prop[i++]] = void 0;
        }

        // void 0 is used because 'undefined' is a var that can be changed in some browsers
        this.set(props);

        return this;
    },

    reset: function(prop){
        var props = {},
            defaults = this.options.defaults,
            len, i = 0, item;

        if (prop) {
            prop = Array.from(prop);
            len = prop.length;

            while(len--){
                item = prop[i++];
                props[item] = defaults[item];
            }
        } else {
            props = defaults;
        }

        this.set(props);

        this.signalReset();

        return this;
    },

    /**
     * Retrieve the stored property
     *
     * @param  {String} prop Property name to retrieve
     * @return Value referenced by prop param
     */
    get: curryGetter('_data'),

    /**
     * Retrieve entire data object in Model instance
     *
     * @return {Object}
     */
    getData: curryGetData('get'),

    _setPrevious: function(prop, val){
        this._previousData[prop] = val;
        return this;
    }.overloadSetter(),

    getPrevious: curryGetter('_previousData'),

    getPreviousData: curryGetData('getPrevious'),

    _resetChanged: function(){
        if (this._changed) {
            // reset the changed
            this._changed = false;

            // reset changed properties
            this._changedProperties = {};
        }

        return this;
    },

    /**
     * Signal to 'change:prop' listener if model property has changed
     * @param  {String} prop Name of property
     * @return {[type]}
     */
    _onChangeProperty: function(prop, val){
        if (this._changed) {
            this.signalChangeProperty(prop, val, this.getPrevious(prop));
        }

        return this;
    }.overloadSetter(),

    /**
     * Signal to 'destroy' listener if model is to be destroyed
     *
     * @return {[type]}
     */
    destroy: function(){
        this.signalDestroy();

        return this;
    },

    toJSON: function(){
        return this.getData();
    },

    /**
     * Add a listener to the property change
     * @param  {String|Object}  prop    String or object of string/function pairs
     * @param  {Function}   callback    Function that is executed upon event firing
     * @return {Class}  Class instance
     */
    spy: function(prop, callback){
        if ((Type.isString(prop) && prop in this._data) && Type.isFunction(callback)) {
            this.addEvent('change:' + prop, callback);
        }

        return this;
    }.overloadSetter(),

    /**
     * Remove a listener to the property change
     * @param  {String|Object}  prop    String or object of string/function pairs
     * @param  {Function}   callback    Function that is executed upon event firing.
     * @return {Class}  Class instance
     */
    unspy: function(prop, callback){
        if ((Type.isString(prop) && prop in this._data)) {
            this.removeEvents('change:' + prop, callback);
        }

        return this;
    }.overloadSetter()
});

Model.implement(
    signalFactory(
        ['change', 'destroy', 'reset'],
        {
            signalChangeProperty: function(prop, newVal, oldVal){
                !this.isSilent() && this.fireEvent('change:' + prop, [this, prop, newVal, oldVal]);
                return this;
            }
        }
    )
);

['each', 'subset', 'map', 'filter', 'every', 'some', 'keys', 'values', 'getLength', 'keyOf', 'contains', 'toQueryString'].each(function(method){
    Model.implement(method, function(){
        return Object[method].apply( Object, [this._data].append( Array.from(arguments) ) );
    });
});

exports.Model = Model;
// }(typeof exports != 'undefined' ? exports : window));
<|endoftext|>


<commit_before>import Model from 'ampersand-model'

export default Model.extend({
    url: 'foobar.com',
    props: {
        name: 'string',
        data: 'hash',
        description: 'string',
        id: 'string',
    },
    derived: {
      destroy: {
        deps: [],
        fn: function() {
          this.collection.destroy(this)
        }
      },
      update: {
        deps: [],
        fn: function() {
        }
      },
      appUrl: {
        deps: ['name'],
        fn: function () {
            return '/repo/' + this.name;
        }
      }
    },
    updateData: function(data) {
      this.data = data
      app.firebase.child('repos').child(this.id).set({name: this.name, description:this.description, data: data})
    }
})
<commit_msg>Reverting to older commit on master<commit_after>import Model from 'ampersand-model'

export default Model.extend({
    url: 'foobar.com',
    props: {
        name: 'string',
        data: 'hash',
        id: 'string',
    },
    derived: {
      destroy: {
        deps: [],
        fn: function() {
          this.collection.destroy(this)
        }
      },
      update: {
        deps: [],
        fn: function() {
        }
      },
      appUrl: {
        deps: ['name'],
        fn: function () {
            return 'repo/' + this.name;
        }
      }
    },
    updateData: function(data) {
      this.data = data
      app.firebase.child('repos').child(this.id).set({name: this.name, data: data})
    }
})
<|endoftext|>


<commit_before>var ViewDragger = kity.createClass( "ViewDragger", {
    constructor: function ( minder ) {
        this._minder = minder;
        this._enabled = false;
        this._offset = {
            x: 0,
            y: 0
        };
        this._bind();
    },
    isEnabled: function () {
        return this._enabled;
    },
    setEnabled: function ( value ) {
        var paper = this._minder.getPaper();
        paper.setStyle( 'cursor', value ? 'pointer' : 'default' );
        paper.setStyle( 'cursor', value ? '-webkit-grab' : 'default' );
        this._enabled = value;
    },

    _bind: function () {
        var dragger = this,
            isRootDrag = false,
            startPosition = null,
            lastPosition = null;

        this._minder.on( 'beforemousedown', function ( e ) {
            // 已经被用户打开拖放模式
            if ( dragger.isEnabled() ) {
                startPosition = e.getPosition();
                e.stopPropagation();
            }
            // 点击未选中的根节点临时开启
            else if ( !this.getRoot().isSelected() && e.getTargetNode() == this.getRoot() ) {
                startPosition = e.getPosition();
                dragger.setEnabled( true );
                isRootDrag = true;
            }

        } )

        .on( 'beforemousemove', function ( e ) {
            if ( startPosition ) {
                lastPosition = e.getPosition();

                // 当前偏移加上历史偏移
                var offset = kity.Vector.fromPoints( startPosition, lastPosition );
                offset = kity.Vector.add( dragger._offset, offset );

                this.getRenderContainer().setTransform( new kity.Matrix().translate( offset.x, offset.y ) );
                e.stopPropagation();
            }
        } )

        .on( 'mouseup', function ( e ) {
            if ( startPosition && lastPosition ) {
                // 合并更改的偏移到历史偏移
                dragger._offset.x += lastPosition.x - startPosition.x;
                dragger._offset.y += lastPosition.y - startPosition.y;
            }
            startPosition = null;

            // 临时拖动需要还原状态
            if ( isRootDrag ) {
                dragger.setEnabled( false );
                isRootDrag = false;
            }
        } );
    }
} );

KityMinder.registerModule( 'Hand', function () {
    var ToggleHandCommand = kity.createClass( "ToggleHandCommand", {
        base: Command,
        execute: function ( minder ) {
            minder._viewDragger.setEnabled( !minder._viewDragger.isEnabled() );
        },
        queryState: function ( minder ) {
            return minder._viewDragger.isEnabled() ? 1 : 0;
        }
    } );

    return {
        init: function () {
            this._viewDragger = new ViewDragger( this );
        },
        commands: {
            'hand': ToggleHandCommand
        },
        events: {
            keyup: function ( e ) {
                if ( e.originEvent.keyCode == keymap.Spacebar && this.getSelectedNodes().length === 0 ) {
                    this.execCommand( 'hand' );
                    e.preventDefault();
                }
            }
        }
    };
} );<commit_msg>拖动问题修复<commit_after>var ViewDragger = kity.createClass( "ViewDragger", {
    constructor: function ( minder ) {
        this._minder = minder;
        this._enabled = false;
        this._offset = {
            x: 0,
            y: 0
        };
        this._bind();
    },
    isEnabled: function () {
        return this._enabled;
    },
    setEnabled: function ( value ) {
        var paper = this._minder.getPaper();
        paper.setStyle( 'cursor', value ? 'pointer' : 'default' );
        paper.setStyle( 'cursor', value ? '-webkit-grab' : 'default' );
        this._enabled = value;
    },

    _bind: function () {
        var dragger = this,
            isRootDrag = false,
            lastPosition = null,
            currentPosition = null;

        this._minder.on( 'beforemousedown', function ( e ) {
            // 已经被用户打开拖放模式
            if ( dragger.isEnabled() ) {
                lastPosition = e.getPosition();
                e.stopPropagation();
            }
            // 点击未选中的根节点临时开启
            else if ( e.getTargetNode() == this.getRoot() &&
                (!this.getRoot().isSelected() || !this.isSingleSelect())) {
                lastPosition = e.getPosition();
                dragger.setEnabled( true );
                isRootDrag = true;
            }

        } )

        .on( 'beforemousemove', function ( e ) {
            if ( lastPosition ) {
                currentPosition = e.getPosition();

                // 当前偏移加上历史偏移
                var offset = kity.Vector.fromPoints( lastPosition, currentPosition );

                this.getRenderContainer().translate( offset.x, offset.y );
                e.stopPropagation();
                lastPosition = currentPosition;
            }
        } )

        .on( 'mouseup', function ( e ) {
            lastPosition = null;

            // 临时拖动需要还原状态
            if ( isRootDrag ) {
                dragger.setEnabled( false );
                isRootDrag = false;
            }
        } );
    }
} );

KityMinder.registerModule( 'Hand', function () {
    var ToggleHandCommand = kity.createClass( "ToggleHandCommand", {
        base: Command,
        execute: function ( minder ) {
            minder._viewDragger.setEnabled( !minder._viewDragger.isEnabled() );
        },
        queryState: function ( minder ) {
            return minder._viewDragger.isEnabled() ? 1 : 0;
        }
    } );

    return {
        init: function () {
            this._viewDragger = new ViewDragger( this );
        },
        commands: {
            'hand': ToggleHandCommand
        },
        events: {
            keyup: function ( e ) {
                if ( e.originEvent.keyCode == keymap.Spacebar && this.getSelectedNodes().length === 0 ) {
                    this.execCommand( 'hand' );
                    e.preventDefault();
                }
            }
        }
    };
} );<|endoftext|>


<commit_before>//  QUICK REFERENCES
/*
 TYPES
    RAML: https://github.com/raml-org/raml-spec/blob/master/versions/raml-10/raml-10.md/#raml-data-types
    parser: https://github.com/raml-org/raml-js-parser-2/blob/master/documentation/GettingStarted.md#types

 */

var raml = require('raml-1-parser');
var _ = require('lodash');
var hljs = require('highlight.js');
var chalk = require('chalk');
var markdown = require('markdown').markdown;

var ramlo = {};

function produceDescription(api) {
    var description = api.description();

    return description && description.value();
}

function produceDocumentations(api) {
    var apiDocumentations = [];
    var ramlDocumentations = api.documentation();

    _.forEach(ramlDocumentations, function (documentation) {
        var content = documentation.content();

        apiDocumentations.push({
            title: documentation.title(),
            content: content && content.value()
        });
    });

    return apiDocumentations;
}

function produceResources(api) {
    var apiResources = [];
    var ramlResources = api.allResources();

    var namesArr = [];

    _.forEach(ramlResources, function (resource) {
        var uri = resource.completeRelativeUri();
        var name = resource.displayName() || capitalizeFirstLetter(uri.replace('/', ''));
        var description = "";
        var annotations =  produceAnnotations(resource);
        var type = "";

        if(resource.description()){
            description = resource.description().value();
        }

        //make sure there are no duplicates
        if(namesArr.indexOf(name) < 0 ) {

            namesArr.push(name);

            apiResources.push({
                uri: uri,
                name: name,
                description: description,
                type: type,
                endpoints: _.flattenDeep(produceEndpoints(resource)),
                annotations: annotations
            });
        }
    });

    return  apiResources;
}

function produceEndpoints(resource) {
    var endpoints = [];
    var ramlNestedResources = resource.resources();
    var ramlMethods = resource.methods();

    _.forEach(ramlMethods, function (method) {
        var description = method.description() && markdown.toHTML(method.description().value());

        var securedBy =  method.securedBy() || "";

        var annotations = produceAnnotations(method);

        //console.log( "securedBy " + securedBy );

        endpoints.push({
            uri: resource.completeRelativeUri(),
            method: method.method(),
            securedBy : securedBy,
            description: description,
            uriParameters: produceUriParameters(resource),
            queryParameters: produceQueryParameters(method),
            requestBody: produceRequestBody(method),
            responseBody: produceResponseBody(method),
            responseExample: produceResponseExample(method),
            annotations: annotations
        });

    });

    if (ramlNestedResources.length) {
        _.forEach(ramlNestedResources, function (resource) {
            endpoints.push(produceEndpoints(resource));
        })
    }

    return endpoints;
}

function produceUriParameters(resource) {
    var apiUriParameters = {
        /* default values */
        thead: {
            name: false,
            type: false,
            description: false
        },
        tbody: []
    };
    var ramlUriParameters = resource.uriParameters();

    _.forEach(ramlUriParameters, function (parameter) {
        var description = parameter.description();

        //check if type exists
        if (apiUriParameters.thead.type == false && parameter.type() != null) {
            apiUriParameters.thead.type = true;
        }

        //check if description exists
        if (apiUriParameters.thead.description == false && description != null) {
            apiUriParameters.thead.description = true;
        }

        //check if example exists
        if (apiUriParameters.thead.name == false && parameter.name() != null) {
            apiUriParameters.thead.name = true;
        }

        apiUriParameters["tbody"].push({
            name: parameter.name(),
            type: parameter.type(),
            description: description && description.value()
        });
    });

    return apiUriParameters;
}

function produceQueryParameters(method) {
    var apiQueryParameters = {
        /* default values */
        thead: {
            name: false,
            type: false,
            description: false,
            example: false,
            default: false,
            minLength: false,
            maxLength: false
        },
        tbody: []
    };
    var ramlQueryParameters = method.queryParameters();

    _.forEach(ramlQueryParameters, function (parameter) {
        var description = parameter.description();
        var minLength = "";
        var maxLength = "";

        //check if name exists
        if (apiQueryParameters.thead.name == false && parameter.name() != null) {
            apiQueryParameters.thead.name = true;
        }

        //check if type exists
        if (apiQueryParameters.thead.type == false && parameter.type() != null) {
            apiQueryParameters.thead.type = true;
        }

        //check if description exists
        if (apiQueryParameters.thead.description == false && description != null) {
            apiQueryParameters.thead.description = true;
        }

        //check if example exists
        if (apiQueryParameters.thead.example == false && parameter.example() != null) {
            apiQueryParameters.thead.example = true;
        }

        //check if default exists
        if (apiQueryParameters.thead.default == false && parameter.default() != null) {
            apiQueryParameters.thead.default = true;
        }

        try {
            /* note: parameter.minLength() & parameter.maxLength() throws an error if no minLength | maxLength exists
             it is an error from the parser, try...catch solves the problem
             */
            if (apiQueryParameters.thead.minLength == false && parameter.minLength() != null) {
                apiQueryParameters.thead.minLength = true;
                minLength = parameter.minLength();
            }
        }
        catch (err) {
        }

        try {
            if (apiQueryParameters.thead.maxLength == false && parameter.maxLength() != null) {
                apiQueryParameters.thead.maxLength = true;
                maxLength = parameter.maxLength();
            }
        }
        catch (err) {
        }

        apiQueryParameters["tbody"].push({
            name: parameter.name(),
            type: parameter.type(),
            isRequired: parameter.required(),
            description: description && description.value(),
            example: parameter.example(),
            default: parameter.default(),
            minLength: minLength,
            maxLength: maxLength,
            repeat: parameter.repeat()
        });
    });

    return apiQueryParameters;
}

function produceRequestBody(method) {
    var apiBodySchema = {
        thead: {},
        tbody: []
    };

    var ramlBody = method.body();

    if (Object.keys(ramlBody).length > 0) {

        //expecting only 1 value to be valid
        //there should NOT be 2 or more "body" declarations

        _.forEach(ramlBody, function (body) {

            if (body.schemaContent() != null) {
                var sp = produceSchemaParameters( body.schemaContent() );

                //make sure that "body" key was valid
                if (sp["tbody"].length > 0) {
                    apiBodySchema = sp;
                }
            }
        });
    }

    return apiBodySchema;
}

function produceResponseBody(method) {
    var ramlResponses = method.responses();
    var ramlBodies;
    var schemaProperties = [];

    _.forEach(ramlResponses, function (response) {

        if (response.code().value() === '200') {
            ramlBodies = response.body();

            _.forEach(ramlBodies, function (body) {

                //check if NULL before calling produceSchemaParameters()
                var sch = body.schemaContent();

                if (sch != null && typeof sch != "undefined") {

                    var sp = produceSchemaParameters(sch);

                    if (sp["tbody"].length > 0) {
                        schemaProperties = sp;
                    }
                }

                //get
                try{
                    var type = body.toJSON();

                    //this key is inserted by json parser, we don't need it
                    if(type["__METADATA__"] != null){
                        delete type["__METADATA__"];
                    }

                    schemaProperties["type"] = type;

                }
                catch (err){
                    //console.log(err);
                }
            });
        }
    });

    return schemaProperties;
}

function produceResponseExample(method) {
    var apiExample = {};
    var apiExamples = [];
    var ramlResponses = method.responses();
    var ramlBodies;

    _.forEach(ramlResponses, function (response) {
        if (response.code().value() !== undefined) {
            ramlBodies = response.body();

            _.forEach(ramlBodies, function (body) {
                apiExample = {
                    response: body.toJSON().example,
                    code: response.code().value()
                };
                if (apiExample.response !== undefined) {
                    try{
                        apiExample.response = apiExample.response && hljs.highlight('json', apiExample.response).value;
                        apiExamples = apiExamples.concat(apiExample);
                    }
                    catch(err){

                    }
                }
            });
        }
    });

    if (apiExamples.length === 0) {
        return undefined;
    }
    else {
        return apiExamples;
    }
}

function produceSchemaParameters(schemaContent) {

    var schemaProperties = {
        thead: {
            name: true,
            required : false,
            type: false,
            description: false
        },
        tbody: []
    };

    //before calling JSON.parse, make sure the string is valid json
    //using try/catch solved errors, ex. https://github.com/raml-apis/Instagram
    try {
        var schemaObject = _.isObject(schemaContent) ? schemaContent : JSON.parse(schemaContent);
        var nestedProperties;

        if (_.has(schemaObject, 'items')) {
            schemaObject = schemaObject.items;
        }

        if (_.has(schemaObject, 'properties')) {
            _.forOwn(schemaObject.properties, function (value, key) {
                nestedProperties = [];

                if (_.has(value, 'items')) {
                    value = value.items;
                }

                if (_.has(value, 'properties')) {
                    nestedProperties = produceSchemaParameters(value);
                }

                if (_.has(value, 'required')) {
                    //check if description exists
                    if (schemaProperties.thead.description == false && value.description != null) {
                        schemaProperties.thead.required = true;
                    }
                }

                //check if description exists
                if (schemaProperties.thead.description == false && value.description != null) {
                    schemaProperties.thead.description = true;
                }

                if (schemaProperties.thead.type == false && value.type != null) {
                    schemaProperties.thead.type = true;
                }

                schemaProperties["tbody"].push({
                    name: key,
                    type: value.type,
                    description: value.description,
                    isRequired: value.required,
                    nestedProperties: nestedProperties
                });
            });
        }
    }
    catch (err) {
        //console.log(err, schemaContent);
        //console.log("////////////////////////////////////////////////////");
    }

    return schemaProperties;
}

function capitalizeFirstLetter(string) {
    return string[0].toUpperCase() + string.slice(1);
}

function produceSecuredBy(api) {

    var securedBy =  {};

    var secured = {};

    try{
        securedBy = api.securedBy();

        securedBy.name = securedBy[0].securitySchemeName();

        var scsh = api.securitySchemes();

        _.forOwn( scsh, function(val, key){

            if(val.name() == securedBy.name){

                secured = val.toJSON();

                //console.log(secured.describedBy.queryParameters.access_token);
            }

        });
    }
    catch (err){
        //console.log(err);
    }
    return secured;
}

function produceProtocols(api) {

    var protocols   = " ";
    var protArr     = [];
    try {
        protocols = api.protocols();

        _.forEach(protocols, function (p) {
            protArr.push( p );
        });

        protocols = "Protocols: " + protArr.join(", ");
    }
    catch (err) {
        //console.log( err );
    }
    return protocols;
}

function produceBaseUriParameters(api) {
    var baseUriParameters = [];
    try{
        var u = api.baseUriParameters();

        // Let's enumerate all URI parameters
        _.forOwn(u, function (parameter) {

            //api.baseUriParameters() function returns also 'version'
            // which can be retrieved from api.version()
            if(parameter.name() != "version") {
                try {
                    baseUriParameters.push( parameter.toJSON() );
                }
                catch (err) {
                }
            }
        });
    }
    catch (err){
        //console.log(err);
    }
    return baseUriParameters;
}

function produceAllSecuritySchemes(api){

    var securitySchemes = [];

    try{

        var scsh = api.securitySchemes();

        _.forOwn( scsh, function(val, key){

            /*
            //data in responses could be organized better to be more dynamic
            //to be checked later on
            if(val.describedBy != null){
                if(val.describedBy.responses != null){
                    console.log( produceSchemaParameters(val.describedBy.responses) )
                }
            }*/
            securitySchemes.push( val.toJSON() );
        });
    }
    catch (err){
        //console.log(err);
    }
    return securitySchemes;

}

function getAllResourceTypes(api){
    try {
        api.resourceTypes().forEach(function (resourceType) {
            console.log(resourceType.name())

            resourceType.methods().forEach(function(method){
                console.log("\t"+method.method())

                method.responses().forEach(function (response) {
                    console.log("\t\t" + response.code().value())
                })
            })
        })
    }
    catch (e) {
        console.log( e );
    }
}

function printHierarchy(runtimeType,indent){
    indent = indent || "";
    var typeName = runtimeType.nameId();
    console.log(indent + typeName);
    runtimeType.superTypes().forEach(function(st){
        printHierarchy(st, indent + "  ");
    });
}

function produceAnnotations(method) {

    var annotations = [];

    try{
        method.annotations().forEach(function(aRef){

            var a = {};

            var name = aRef.name();
            var structure = aRef.structuredValue().toJSON();

            //forEach
            a[name] = {
                "value" : structure
            };

            try{
                a[name].type = aRef.type();
            }
            catch (err){  }

            annotations.push( a  );
        });
    }
    catch(err){ }

    return annotations;
}

function prepareSchemas(_schemas) {

    var schemas = [];

    _.forOwn(_schemas , function (value, key) {
        _.forOwn(value , function (schema, k) {

            var ob = {};

            var sch = JSON.parse(schema);

            ob[k] = sch;

            schemas.push( ob );
        });
    });

    return schemas;
}

function produceArrayOfCustomTypes(types) {

    var arr = [];

    _.forEach( types, function (obj) {
        _.forOwn(obj, function (val, key) {
             arr.push(key);
        });
    });

    return arr;
}

///////////

module.exports = function (ramlFile) {
    var api;
    var apiBaseUri = "";
    var baseUriParameters = [];
    var types = [];
    var resourceTypes = "";
    var json  = {};
    var schemas = [];
    var typeNamesArray = [];

    try {
        api = raml.loadApiSync(ramlFile).expand(); //expand() fixed the problem with traits

        json = api.toJSON();
    }
    catch (e) {
        console.log(chalk.red('provided file is not a correct RAML file!'));

        process.exit(1);
    }

    try {
        apiBaseUri = api.baseUri().value().replace('{version}', api.version());
    }
    catch (err) {
        //console.log("BaseUri" + err);
    }

    // https://github.com/raml-org/raml-spec/blob/master/versions/raml-10/raml-10.md/#overview
    if(json.types != null && typeof json.types != "undefined"){ //faster than try...catch
        types = json.types;
        typeNamesArray = produceArrayOfCustomTypes(types);
    }

    if(json.schemas != null && typeof json.schemas != "undefined"){ //faster than try...catch
        schemas = json.schemas;

        schemas = prepareSchemas(schemas);
    }

    if(json.resourceTypes != null && typeof json.resourceTypes != "undefined"){ //faster than try...catch
        resourceTypes = json.resourceTypes;
    }

    /*
    try{
        api.annotationTypes().forEach(function(aType){
            console.log("  name:",aType.name());
            console.log("  type:",aType.type());
        });
    }
    catch(err){}
    */

    ramlo.ramlVersion        = api.RAMLVersion();
    ramlo.apiTitle           = api.title();
    ramlo.apiProtocol        = produceProtocols(api);
    ramlo.apiDescription     = produceDescription(api);
    ramlo.apiSecuritySchemes = produceAllSecuritySchemes(api);
    ramlo.apiSecuredBy       = produceSecuredBy(api); //work in progress
    ramlo.apiBaseUri         = apiBaseUri;
    ramlo.baseUriParameters  = produceBaseUriParameters(api);
    ramlo.apiDocumentations  = produceDocumentations(api);
    ramlo.apiResources       = produceResources(api);
    ramlo.apiAllTypes        = types;
    ramlo.typeNamesArray     = typeNamesArray;
    ramlo.apiAllSchemas      = schemas;

    //console.log(ramlo.apiSecuritySchemes);

    return ramlo;
};<commit_msg>Fix duplicated resources<commit_after>//  QUICK REFERENCES
/*
 TYPES
    RAML: https://github.com/raml-org/raml-spec/blob/master/versions/raml-10/raml-10.md/#raml-data-types
    parser: https://github.com/raml-org/raml-js-parser-2/blob/master/documentation/GettingStarted.md#types

 */

var raml = require('raml-1-parser');
var _ = require('lodash');
var hljs = require('highlight.js');
var chalk = require('chalk');
var markdown = require('markdown').markdown;

var ramlo = {};

function produceDescription(api) {
    var description = api.description();
    return description && description.value();
}

function produceDocumentations(api) {
    var apiDocumentations = [];
    var ramlDocumentations = api.documentation();

    _.forEach(ramlDocumentations, function (documentation) {
        var content = documentation.content();

        apiDocumentations.push({
            title: documentation.title(),
            content: content && content.value()
        });
    });

    return apiDocumentations;
}

function produceResources(api) {
    var apiResources = [];
    var ramlResources = api.resources();

    var namesArr = [];

    _.forEach(ramlResources, function (resource) {
        var uri = resource.completeRelativeUri();
        var name = resource.displayName() || capitalizeFirstLetter(uri.replace('/', ''));
        var description = "";
        var annotations =  produceAnnotations(resource);
        var type = "";

        if(resource.description()){
            description = resource.description().value();
        }

        //make sure there are no duplicates
        if(namesArr.indexOf(name) < 0 ) {

            namesArr.push(name);

            apiResources.push({
                uri: uri,
                name: name,
                description: description,
                type: type,
                endpoints: _.flattenDeep(produceEndpoints(resource)),
                annotations: annotations
            });
        }
    });

    return  apiResources;
}

function produceEndpoints(resource) {
    var endpoints = [];
    var ramlNestedResources = resource.resources();
    var ramlMethods = resource.methods();

    _.forEach(ramlMethods, function (method) {
        var description = method.description() && markdown.toHTML(method.description().value());

        var securedBy =  method.securedBy() || "";

        var annotations = produceAnnotations(method);

        //console.log( "securedBy " + securedBy );

        endpoints.push({
            uri: resource.completeRelativeUri(),
            method: method.method(),
            securedBy : securedBy,
            description: description,
            uriParameters: produceUriParameters(resource),
            queryParameters: produceQueryParameters(method),
            requestBody: produceRequestBody(method),
            responseBody: produceResponseBody(method),
            responseExample: produceResponseExample(method),
            annotations: annotations
        });

    });

    if (ramlNestedResources.length) {
        _.forEach(ramlNestedResources, function (resource) {
            endpoints.push(produceEndpoints(resource));
        })
    }

    return endpoints;
}

function produceUriParameters(resource) {
    var apiUriParameters = {
        /* default values */
        thead: {
            name: false,
            type: false,
            description: false
        },
        tbody: []
    };
    var ramlUriParameters = resource.uriParameters();

    _.forEach(ramlUriParameters, function (parameter) {
        var description = parameter.description();

        //check if type exists
        if (apiUriParameters.thead.type == false && parameter.type() != null) {
            apiUriParameters.thead.type = true;
        }

        //check if description exists
        if (apiUriParameters.thead.description == false && description != null) {
            apiUriParameters.thead.description = true;
        }

        //check if example exists
        if (apiUriParameters.thead.name == false && parameter.name() != null) {
            apiUriParameters.thead.name = true;
        }

        apiUriParameters["tbody"].push({
            name: parameter.name(),
            type: parameter.type(),
            description: description && description.value()
        });
    });

    return apiUriParameters;
}

function produceQueryParameters(method) {
    var apiQueryParameters = {
        /* default values */
        thead: {
            name: false,
            type: false,
            description: false,
            example: false,
            default: false,
            minLength: false,
            maxLength: false
        },
        tbody: []
    };
    var ramlQueryParameters = method.queryParameters();

    _.forEach(ramlQueryParameters, function (parameter) {
        var description = parameter.description();
        var minLength = "";
        var maxLength = "";

        //check if name exists
        if (apiQueryParameters.thead.name == false && parameter.name() != null) {
            apiQueryParameters.thead.name = true;
        }

        //check if type exists
        if (apiQueryParameters.thead.type == false && parameter.type() != null) {
            apiQueryParameters.thead.type = true;
        }

        //check if description exists
        if (apiQueryParameters.thead.description == false && description != null) {
            apiQueryParameters.thead.description = true;
        }

        //check if example exists
        if (apiQueryParameters.thead.example == false && parameter.example() != null) {
            apiQueryParameters.thead.example = true;
        }

        //check if default exists
        if (apiQueryParameters.thead.default == false && parameter.default() != null) {
            apiQueryParameters.thead.default = true;
        }

        try {
            /* note: parameter.minLength() & parameter.maxLength() throws an error if no minLength | maxLength exists
             it is an error from the parser, try...catch solves the problem
             */
            if (apiQueryParameters.thead.minLength == false && parameter.minLength() != null) {
                apiQueryParameters.thead.minLength = true;
                minLength = parameter.minLength();
            }
        }
        catch (err) {
        }

        try {
            if (apiQueryParameters.thead.maxLength == false && parameter.maxLength() != null) {
                apiQueryParameters.thead.maxLength = true;
                maxLength = parameter.maxLength();
            }
        }
        catch (err) {
        }

        apiQueryParameters["tbody"].push({
            name: parameter.name(),
            type: parameter.type(),
            isRequired: parameter.required(),
            description: description && description.value(),
            example: parameter.example(),
            default: parameter.default(),
            minLength: minLength,
            maxLength: maxLength,
            repeat: parameter.repeat()
        });
    });

    return apiQueryParameters;
}

function produceRequestBody(method) {
    var apiBodySchema = {
        thead: {},
        tbody: []
    };

    var ramlBody = method.body();

    if (Object.keys(ramlBody).length > 0) {

        //expecting only 1 value to be valid
        //there should NOT be 2 or more "body" declarations

        _.forEach(ramlBody, function (body) {

            if (body.schemaContent() != null) {
                var sp = produceSchemaParameters( body.schemaContent() );

                //make sure that "body" key was valid
                if (sp["tbody"].length > 0) {
                    apiBodySchema = sp;
                }
            }
        });
    }

    return apiBodySchema;
}

function produceResponseBody(method) {
    var ramlResponses = method.responses();
    var ramlBodies;
    var schemaProperties = [];

    _.forEach(ramlResponses, function (response) {

        if (response.code().value() === '200') {
            ramlBodies = response.body();

            _.forEach(ramlBodies, function (body) {

                //check if NULL before calling produceSchemaParameters()
                var sch = body.schemaContent();

                if (sch != null && typeof sch != "undefined") {

                    var sp = produceSchemaParameters(sch);

                    if (sp["tbody"].length > 0) {
                        schemaProperties = sp;
                    }
                }

                //get
                try{
                    var type = body.toJSON();

                    //this key is inserted by json parser, we don't need it
                    if(type["__METADATA__"] != null){
                        delete type["__METADATA__"];
                    }

                    schemaProperties["type"] = type;

                }
                catch (err){
                    //console.log(err);
                }
            });
        }
    });

    return schemaProperties;
}

function produceResponseExample(method) {
    var apiExample = {};
    var apiExamples = [];
    var ramlResponses = method.responses();
    var ramlBodies;

    _.forEach(ramlResponses, function (response) {
        if (response.code().value() !== undefined) {
            ramlBodies = response.body();

            _.forEach(ramlBodies, function (body) {
                apiExample = {
                    response: body.toJSON().example,
                    code: response.code().value()
                };
                if (apiExample.response !== undefined) {
                    try{
                        apiExample.response = apiExample.response && hljs.highlight('json', apiExample.response).value;
                        apiExamples = apiExamples.concat(apiExample);
                    }
                    catch(err){

                    }
                }
            });
        }
    });

    if (apiExamples.length === 0) {
        return undefined;
    }
    else {
        return apiExamples;
    }
}

function produceSchemaParameters(schemaContent) {

    var schemaProperties = {
        thead: {
            name: true,
            required : false,
            type: false,
            description: false
        },
        tbody: []
    };

    //before calling JSON.parse, make sure the string is valid json
    //using try/catch solved errors, ex. https://github.com/raml-apis/Instagram
    try {
        var schemaObject = _.isObject(schemaContent) ? schemaContent : JSON.parse(schemaContent);
        var nestedProperties;

        if (_.has(schemaObject, 'items')) {
            schemaObject = schemaObject.items;
        }

        if (_.has(schemaObject, 'properties')) {
            _.forOwn(schemaObject.properties, function (value, key) {
                nestedProperties = [];

                if (_.has(value, 'items')) {
                    value = value.items;
                }

                if (_.has(value, 'properties')) {
                    nestedProperties = produceSchemaParameters(value);
                }

                if (_.has(value, 'required')) {
                    //check if description exists
                    if (schemaProperties.thead.description == false && value.description != null) {
                        schemaProperties.thead.required = true;
                    }
                }

                //check if description exists
                if (schemaProperties.thead.description == false && value.description != null) {
                    schemaProperties.thead.description = true;
                }

                if (schemaProperties.thead.type == false && value.type != null) {
                    schemaProperties.thead.type = true;
                }

                schemaProperties["tbody"].push({
                    name: key,
                    type: value.type,
                    description: value.description,
                    isRequired: value.required,
                    nestedProperties: nestedProperties
                });
            });
        }
    }
    catch (err) {
        //console.log(err, schemaContent);
        //console.log("////////////////////////////////////////////////////");
    }

    return schemaProperties;
}

function capitalizeFirstLetter(string) {
    return string[0].toUpperCase() + string.slice(1);
}

function produceSecuredBy(api) {

    var securedBy =  {};

    var secured = {};

    try{
        securedBy = api.securedBy();

        securedBy.name = securedBy[0].securitySchemeName();

        var scsh = api.securitySchemes();

        _.forOwn( scsh, function(val, key){

            if(val.name() == securedBy.name){

                secured = val.toJSON();

                //console.log(secured.describedBy.queryParameters.access_token);
            }

        });
    }
    catch (err){
        //console.log(err);
    }
    return secured;
}

function produceProtocols(api) {

    var protocols   = " ";
    var protArr     = [];
    try {
        protocols = api.protocols();

        _.forEach(protocols, function (p) {
            protArr.push( p );
        });

        protocols = "Protocols: " + protArr.join(", ");
    }
    catch (err) {
        //console.log( err );
    }
    return protocols;
}

function produceBaseUriParameters(api) {
    var baseUriParameters = [];
    try{
        var u = api.baseUriParameters();

        // Let's enumerate all URI parameters
        _.forOwn(u, function (parameter) {

            //api.baseUriParameters() function returns also 'version'
            // which can be retrieved from api.version()
            if(parameter.name() != "version") {
                try {
                    baseUriParameters.push( parameter.toJSON() );
                }
                catch (err) {
                }
            }
        });
    }
    catch (err){
        //console.log(err);
    }
    return baseUriParameters;
}

function produceAllSecuritySchemes(api){

    var securitySchemes = [];

    try{

        var scsh = api.securitySchemes();

        _.forOwn( scsh, function(val, key){

            /*
            //data in responses could be organized better to be more dynamic
            //to be checked later on
            if(val.describedBy != null){
                if(val.describedBy.responses != null){
                    console.log( produceSchemaParameters(val.describedBy.responses) )
                }
            }*/
            securitySchemes.push( val.toJSON() );
        });
    }
    catch (err){
        //console.log(err);
    }
    return securitySchemes;

}

function getAllResourceTypes(api){
    try {
        api.resourceTypes().forEach(function (resourceType) {
            console.log(resourceType.name())

            resourceType.methods().forEach(function(method){
                console.log("\t"+method.method())

                method.responses().forEach(function (response) {
                    console.log("\t\t" + response.code().value())
                })
            })
        })
    }
    catch (e) {
        console.log( e );
    }
}

function printHierarchy(runtimeType,indent){
    indent = indent || "";
    var typeName = runtimeType.nameId();
    console.log(indent + typeName);
    runtimeType.superTypes().forEach(function(st){
        printHierarchy(st, indent + "  ");
    });
}

function produceAnnotations(method) {

    var annotations = [];

    try{
        method.annotations().forEach(function(aRef){

            var a = {};

            var name = aRef.name();
            var structure = aRef.structuredValue().toJSON();

            //forEach
            a[name] = {
                "value" : structure
            };

            try{
                a[name].type = aRef.type();
            }
            catch (err){  }

            annotations.push( a  );
        });
    }
    catch(err){ }

    return annotations;
}

function prepareSchemas(_schemas) {

    var schemas = [];

    _.forOwn(_schemas , function (value, key) {
        _.forOwn(value , function (schema, k) {

            var ob = {};

            var sch = JSON.parse(schema);

            ob[k] = sch;

            schemas.push( ob );
        });
    });

    return schemas;
}

function produceArrayOfCustomTypes(types) {

    var arr = [];

    _.forEach( types, function (obj) {
        _.forOwn(obj, function (val, key) {
             arr.push(key);
        });
    });

    return arr;
}

///////////

module.exports = function (ramlFile) {
    var api;
    var apiBaseUri = "";
    var baseUriParameters = [];
    var types = [];
    var resourceTypes = "";
    var json  = {};
    var schemas = [];
    var typeNamesArray = [];

    try {
        api = raml.loadApiSync(ramlFile).expand(); //expand() fixed the problem with traits

        json = api.toJSON();
    }
    catch (e) {
        console.log(chalk.red('provided file is not a correct RAML file!'));

        process.exit(1);
    }

    try {
        apiBaseUri = api.baseUri().value().replace('{version}', api.version());
    }
    catch (err) {
        //console.log("BaseUri" + err);
    }

    // https://github.com/raml-org/raml-spec/blob/master/versions/raml-10/raml-10.md/#overview
    if(json.types != null && typeof json.types != "undefined"){ //faster than try...catch
        types = json.types;
        typeNamesArray = produceArrayOfCustomTypes(types);
    }

    if(json.schemas != null && typeof json.schemas != "undefined"){ //faster than try...catch
        schemas = json.schemas;

        schemas = prepareSchemas(schemas);
    }

    if(json.resourceTypes != null && typeof json.resourceTypes != "undefined"){ //faster than try...catch
        resourceTypes = json.resourceTypes;
    }

    /*
    try{
        api.annotationTypes().forEach(function(aType){
            console.log("  name:",aType.name());
            console.log("  type:",aType.type());
        });
    }
    catch(err){}
    */

    ramlo.ramlVersion        = api.RAMLVersion();
    ramlo.apiTitle           = api.title();
    ramlo.apiProtocol        = produceProtocols(api);
    ramlo.apiDescription     = produceDescription(api);
    ramlo.apiSecuritySchemes = produceAllSecuritySchemes(api);
    ramlo.apiSecuredBy       = produceSecuredBy(api); //work in progress
    ramlo.apiBaseUri         = apiBaseUri;
    ramlo.baseUriParameters  = produceBaseUriParameters(api);
    ramlo.apiDocumentations  = produceDocumentations(api);
    ramlo.apiResources       = produceResources(api);
    ramlo.apiAllTypes        = types;
    ramlo.typeNamesArray     = typeNamesArray;
    ramlo.apiAllSchemas      = schemas;

    //console.log(ramlo.apiSecuritySchemes);

    return ramlo;
};<|endoftext|>


<commit_before>import { select, event } from 'd3-selection'

const wheelDeltaMode = { pixel: 0, line: 1, page: 2 }
    , wheelEventType = discoverWheelEventType()

export function createMouseWheel() {
  function mouseWheel(s) {
    s.each(mouseWheelEach)
  }

  return mouseWheel

  function mouseWheelEach(d, i) {
    const target = select(this)
            .select('.zambezi-grid-body')
              .on(wheelEventType, onWheel)

    function onWheel() {
      const freeRows = d.rows.free
          , actualHeight = freeRows.actualHeight
          , measuredHeight = freeRows.measuredHeight
          , minScroll = 0
          , maxScroll = measuredHeight - actualHeight
          , scroll = Math.max(
              minScroll
            , Math.min(
                d.scroll.top - wheelDelta()
              , maxScroll
              )
            )
          , isInternalGridScroll = scroll > minScroll && scroll < maxScroll
          , scrollEvent = { top: scroll , left: d.scroll.left }

      if (isInternalGridScroll) event.preventDefault()

      target.dispatch('grid-scroll',  { bubbles: true, detail: scrollEvent })
          .dispatch('redraw',  { bubbles: true })

      function wheelDelta() {
        return (
          event.deltaY * (event.deltaMode === wheelDeltaMode.line ? -40 : -1)
          ||  event.wheelDeltaY
          ||  event.wheelDelta
          ||  0
        )
      }
    }
  }
}

function discoverWheelEventType() {
  return (
    'onwheel' in document.createElement('div')  ? 'wheel'       // Modern browsers
  : document.onmousewheel !== undefined         ? 'mousewheel'  // Webkit and IE
  : 'DOMMouseScroll'                                            // default (old Firefox)
  )
}

<commit_msg>Whitespace cleanup.<commit_after>import { select, event } from 'd3-selection'

const wheelDeltaMode = { pixel: 0, line: 1, page: 2 }
    , wheelEventType = discoverWheelEventType()

export function createMouseWheel() {
  function mouseWheel(s) {
    s.each(mouseWheelEach)
  }

  return mouseWheel

  function mouseWheelEach(d, i) {
    const target = select(this)
            .select('.zambezi-grid-body')
              .on(wheelEventType, onWheel)

    function onWheel() {
      const freeRows = d.rows.free
          , actualHeight = freeRows.actualHeight
          , measuredHeight = freeRows.measuredHeight
          , minScroll = 0
          , maxScroll = measuredHeight - actualHeight
          , scroll = Math.max(
              minScroll
            , Math.min(
                d.scroll.top - wheelDelta()
              , maxScroll
              )
            )
          , isInternalGridScroll = scroll > minScroll && scroll < maxScroll
          , scrollEvent = { top: scroll , left: d.scroll.left }

      if (isInternalGridScroll) event.preventDefault()

      target.dispatch('grid-scroll',  { bubbles: true, detail: scrollEvent })
          .dispatch('redraw',  { bubbles: true })

      function wheelDelta() {
        return (
          event.deltaY * (event.deltaMode === wheelDeltaMode.line ? -40 : -1)
          ||  event.wheelDeltaY
          ||  event.wheelDelta
          ||  0
        )
      }
    }
  }
}

function discoverWheelEventType() {
  return (
    'onwheel' in document.createElement('div')  ? 'wheel'       // Modern browsers
  : document.onmousewheel !== undefined         ? 'mousewheel'  // Webkit and IE
  : 'DOMMouseScroll'                                            // default (old Firefox)
  )
}
<|endoftext|>


<commit_before>import React from 'react'
import Link from 'gatsby-link'
import Img from 'gatsby-image'
import get from 'lodash/get'
import Helmet from 'react-helmet'
import Banner from '../components/Banner/banner'
import Article from '../components/Article/article'

class Index extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    const siteTitle = get(this, 'props.data.site.siteMetadata.title')
    const siteDescription = get(
      this,
      'props.data.site.siteMetadata.description'
    )
    const posts = get(this, 'props.data.allMarkdownRemark.edges')
    let articles = posts.filter(x => x.node.frontmatter.layout === 'post')
    articles = articles.slice(0, 3)
    let portfolio = posts.filter(x => x.node.frontmatter.layout === 'portfolio')
    portfolio = portfolio.slice(0, 4)

    return (

        <Helmet
          title={`Website Development and SEO | ${siteTitle}`}
          description={`${siteDescription}`}
        />

        <Banner />

Portfolio

                Over my career, I have had the opportunity to work on a diverse
                assortment of projects. Here is a small sampling of some of
                recent ones.

                {portfolio.map(({ node }) => (

                    <Link
                      to={'/portfolio' + node.frontmatter.path}
                      className="image"
                    >

                    </Link>

{node.frontmatter.title}

{node.frontmatter.abstract}

                    <Link
                      to={'/portfolio' + node.frontmatter.path}
                      className="special"
                    >
                      View Project
                    </Link>

                ))}

                  <Link to="/portfolio" className="button">
                    View More Projects
                  </Link>

    )
  }
}

export default Index

export const pageQuery = graphql`
  query IndexQuery {
    site {
      siteMetadata {
        title
        description
      }
    }
    allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) {
      edges {
        node {
          excerpt
          fields {
            slug
          }
          frontmatter {
            date(formatString: "DD MMMM, YYYY")
            title
            abstract
            layout
            path
            thumbnail {
              childImageSharp {
                sizes(maxWidth: 500, maxHeight: 300, cropFocus: NORTH) {
                  srcSetWebp
                  aspectRatio
                  sizes
                  srcSet
                }
              }
            }
          }
        }
      }
    }
  }
`
<commit_msg>bug fix<commit_after>import React from 'react'
import Link from 'gatsby-link'
import Img from 'gatsby-image'
import get from 'lodash/get'
import Helmet from 'react-helmet'
import Banner from '../components/Banner/banner'
import Article from '../components/Article/article'

class Index extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    const siteTitle = get(this, 'props.data.site.siteMetadata.title')
    const siteDescription = get(
      this,
      'props.data.site.siteMetadata.description'
    )
    const posts = get(this, 'props.data.allMarkdownRemark.edges')
    let articles = posts.filter(x => x.node.frontmatter.layout === 'post')
    articles = articles.slice(0, 3)
    let portfolio = posts.filter(x => x.node.frontmatter.layout === 'portfolio')
    portfolio = portfolio.slice(0, 4)

    return (

        <Helmet
          title={`Website Development and SEO | ${siteTitle}`}
          description={`${siteDescription}`}
        />

        <Banner />

Portfolio

                Over my career, I have had the opportunity to work on a diverse
                assortment of projects. Here is a small sampling of some of
                recent ones.

                {portfolio.map(({ node }) => (

                    <Link
                      to={'/portfolio' + node.frontmatter.path}
                      className="image"
                    >

                    </Link>

{node.frontmatter.title}

{node.frontmatter.abstract}

                    <Link
                      to={'/portfolio' + node.frontmatter.path}
                      className="special"
                    >
                      View Project
                    </Link>

                ))}

                  <Link to="/portfolio" className="button">
                    View More Projects
                  </Link>

    )
  }
}

export default Index

export const pageQuery = graphql`
  query IndexQuery {
    site {
      siteMetadata {
        title
        description
      }
    }
    allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) {
      edges {
        node {
          excerpt
          fields {
            slug
          }
          frontmatter {
            date(formatString: "DD MMMM, YYYY")
            title
            abstract
            layout
            path
            thumbnail {
              childImageSharp {
                sizes(maxWidth: 500, maxHeight: 400, cropFocus: NORTH) {
                  srcSetWebp
                  aspectRatio
                  sizes
                  srcSet
                }
              }
            }
          }
        }
      }
    }
  }
`
<|endoftext|>


<commit_before>import React from 'react'
import Link from 'gatsby-link'

//
// Home page of portfolio site
//
const IndexPage = () => (

Front End Developer

Located in Melbourne & passionate about all things web!

      When it comes to building websites or building any form of web
      application, I take a carefully planned approach ensuring that all facets
      are developed with diligence. Aspects such as browser compatibility,
      rigorous testing, code quality and performance standards are all important
      to me.

      Below are some of the projects I have worked on as the primary developer
      both at Chromatix Digital Agency and other freelance work. International
      Internships was one of my biggest achievements last year as it took out
      the 2016 National Winner in Education at the Australian Web Awards.

)

export default IndexPage
<commit_msg>Pull homepage content from WP<commit_after>import React from 'react'
import Link from 'gatsby-link'

//
// Home page of portfolio site
//
const IndexPage = ({ data }) => {
  const homepage = data.wordpressPage

  return (

  )
}

export default IndexPage

// Pull the homepage content from Wordpress
export const homePageQuery = graphql`
query homePageQuery {
  wordpressPage(slug: {eq: "home-page"}) {
    content
  }
}
`<|endoftext|>


<commit_before>var atlatl = {
	App: function() {
		var that = this;

		this.routes = {};
		this.controllers = {};

		this.serve = function() {
			var route = window.location.hash.substring(1);

			if(route == '') {
				route = '/';
			}

			var controller = this.routes[route];

			if(this.controllers[controller]) {
				return this.controllers[controller]();
			} else {
				console.log("Unknown route '" + route + "'")
			}
		}

		window.onhashchange = function(e) {
			that.serve();
			return false;
		}
	},

	ajax: function(settings) {
        this.stateChange = function(object) {
            if(that.request.readyState == 4) {
				var result = null;
				if(that.type == 'json') {
					result = JSON.parse(that.request.responseText);
				} else {
					result = that.request.responseText;
				}
                that.success(result);
			}
        };

        this.getRequest = function() {
            if(window.ActiveXObject) {
                return new ActiveXObject('Microsoft.XMLHTTP');
            }
			else if(window.XMLHttpRequest) {
                return new XMLHttpRequest();
			}
            return false;
        };

		function preparePost(data) {
			var post = '';
			for(var key in data) {
				if(post.length > 0) post+= '&';
				post+= encodeURIComponent(key) + '=' + encodeURIComponent(data[key]);
			}

			return post;
		}

		// Defaults
		var that = this;
		this.method = 'GET';
		this.data = {};
		this.type = 'raw';
		this.success = null;
		this.error = null;
        this.request = this.getRequest();

		// Reading the provided settings.
		if(!settings.url) {
			console.log('No URL provided!');
			return false;
		}
		this.url = settings.url;
		if(settings.method) this.method = settings.method.toUpperCase();
		if(settings.data) this.data = settings.data;
		if(settings.type) this.type = settings.type.toLowerCase();
		if(settings.success) this.success = settings.success;
		if(settings.error) this.error = settings.error;

        if(this.request) {
            var req = this.request;
	        req.onreadystatechange = this.stateChange;
	        req.open(this.method, this.url, true);
	        req.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
		    req.setRequestHeader('Connection', 'close');

			if(this.data) {
	        	req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
				req.send(preparePost(this.data));
			} else {
				req.send();
			}
        }
	}
}<commit_msg>Started working on models. Much more work needed!<commit_after>window.atlatl = {
	App: function() {
		var that = this;

		this.routes = {};
		this.controllers = {};

		this.serve = function() {
			var route = window.location.hash.substring(1);

			if(route == '') {
				route = '/';
			}

			var controller = this.routes[route];

			if(this.controllers[controller]) {
				return this.controllers[controller]();
			} else {
				console.log("Unknown route '" + route + "'")
			}
		}

		window.onhashchange = function(e) {
			that.serve();
			return false;
		}
	},

	Model: function(endpoint) {
		var that = this;
		this.endpoint = endpoint;
		this.id = null;

		this.fetch = function(id, callback) {
			if(id) {
				atlatl.ajax({
					url: (this.endpoint + '/' + id),
					type: 'JSON',
					method: 'GET',
					success: callback
				});
			} else {
				atlatl.ajax({
					url: this.endpoint,
					type: 'JSON',
					method: 'GET',
					success: callback
				})
			}
		};

		this.save = function(callback) {
			atlatl.ajax({
				url: this.endpoint,
				type: 'JSON',
				method: (that.id ? 'PUT' : 'POST'),
				data: that.data,
				success: callback
			});
		};

		this.drop = function(callback) {
			atlatl.ajax({
				url: this.endpoint,
				type: 'JSON',
				method: 'DELETE',
				data: that.data,
				success: callback
			})
		}
	},

	ajax: function(settings) {
        this.stateChange = function(object) {
            if(that.request.readyState == 4) {
				var result = null;
				if(that.type == 'json') {
					result = JSON.parse(that.request.responseText);
				} else {
					result = that.request.responseText;
				}
                that.success(result);
			}
        };

        this.getRequest = function() {
            if(window.ActiveXObject) {
                return new ActiveXObject('Microsoft.XMLHTTP');
            }
			else if(window.XMLHttpRequest) {
                return new XMLHttpRequest();
			}
            return false;
        };

		function preparePost(data) {
			var post = '';
			for(var key in data) {
				if(post.length > 0) post+= '&';
				post+= encodeURIComponent(key) + '=' + encodeURIComponent(data[key]);
			}

			return post;
		}

		// Defaults
		var that = this;
		this.method = 'GET';
		this.data = {};
		this.type = 'raw';
		this.success = null;
		this.error = null;
        this.request = this.getRequest();

		// Reading the provided settings.
		if(!settings.url) {
			console.log('No URL provided!');
			return false;
		}
		this.url = settings.url;
		if(settings.method) this.method = settings.method.toUpperCase();
		if(settings.data) this.data = settings.data;
		if(settings.type) this.type = settings.type.toLowerCase();
		if(settings.success) this.success = settings.success;
		if(settings.error) this.error = settings.error;

        if(this.request) {
            var req = this.request;
	        req.onreadystatechange = this.stateChange;
	        req.open(this.method, this.url, true);
	        req.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
		    req.setRequestHeader('Connection', 'close');

			if(this.data) {
	        	req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
				req.send(preparePost(this.data));
			} else {
				req.send();
			}
        }
	}
}<|endoftext|>


<commit_before>/*jshint node: true, -W106 */
'use strict';

/*
* Name : index.js
* Module : SystemTest
* Location : /SystemTest
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-06-27   Filippo Rampado    Initial code
* =========================================================
*/
var Helper=require('./helper.js');

console.log('Hello Norris');

var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io')(server);

// Includo e creo l'ustanza di Norris
var Norris = require('../norris-nrti.js');
var norris = new Norris(app,io,'/norris','http://norris-nrti-dev.herokuapp.com');

var page1=Helper.newPage(norris, 'page1', 'Pagina creazione grafici');
var page2=Helper.newPage(norris, 'page2', 'Pagina aggiornamento grafici');

//var barChart=Helper.newBarChart(page2, 'Test aggiornamento dati Bar Chart');
//var lineChart=Helper.newLineChart(page2, 'Test aggiornamento dati Line Chart');
var mapChart=Helper.newMapChart(page2, 'Test aggiornamento dati Map Chart');
//var table=Helper.newTable(page2, 'Test aggiornamento dati Table');

var TS1 = require('./TS1.js');
var TS2 = require('./TS2.js');
var TS3 = require('./TS3.js');
var TS4 = require('./TS4.js');
var TS5 = require('./TS5.js');
var TS6 = require('./TS6.js');
var TS7 = require('./TS7.js');
var TS8 = require('./TS8.js');
var TS9 = require('./TS9.js');

TS1(norris);
TS2(page1);
TS3(page1);
TS4(page1);
TS5(page1);
//TS6(barChart);
//TS7(lineChart);
TS8(mapChart);
//TS9(table);

/////////////////////////////////////////////
app.get('/', function (req, res) {
	var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
	console.log(' Test di sistema '+ fullUrl);
	res.send(' Test di sistema '+ fullUrl);
});

var port = process.env.PORT || 3000;
server.listen(port);<commit_msg>remove all other stuff<commit_after>/*jshint node: true, -W106 */
'use strict';

/*
* Name : index.js
* Module : SystemTest
* Location : /SystemTest
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-06-27   Filippo Rampado    Initial code
* =========================================================
*/
var Helper=require('./helper.js');

console.log('Hello Norris');

var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io')(server);

// Includo e creo l'ustanza di Norris
var Norris = require('../norris-nrti.js');
var norris = new Norris(app,io,'/norris','http://norris-nrti-dev.herokuapp.com');

var page1=Helper.newPage(norris, 'page1', 'Pagina creazione grafici');
var page2=Helper.newPage(norris, 'page2', 'Pagina aggiornamento grafici');

//var barChart=Helper.newBarChart(page2, 'Test aggiornamento dati Bar Chart');
//var lineChart=Helper.newLineChart(page2, 'Test aggiornamento dati Line Chart');
var mapChart=Helper.newMapChart(page2, 'Test aggiornamento dati Map Chart');
//var table=Helper.newTable(page2, 'Test aggiornamento dati Table');

var TS1 = require('./TS1.js');
var TS2 = require('./TS2.js');
var TS3 = require('./TS3.js');
var TS4 = require('./TS4.js');
var TS5 = require('./TS5.js');
var TS6 = require('./TS6.js');
var TS7 = require('./TS7.js');
var TS8 = require('./TS8.js');
var TS9 = require('./TS9.js');

TS1(norris);
/*TS2(page1);
TS3(page1);
TS4(page1);
TS5(page1);*/
//TS6(barChart);
//TS7(lineChart);
TS8(mapChart);
//TS9(table);

/////////////////////////////////////////////
app.get('/', function (req, res) {
	var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
	console.log(' Test di sistema '+ fullUrl);
	res.send(' Test di sistema '+ fullUrl);
});

var port = process.env.PORT || 3000;
server.listen(port);<|endoftext|>