<commit_before>BD.Model = Em.Object.extend(Em.Evented, {

    isLoaded: false,
    isNew: false,
    isDeleted: false,
    selfIsDirty: false,
    childIsDirty: false,

    isNotLoaded: Em.computed.not('isLoaded'),

    clientId: null,
    id: null,
    _data: null,
    error: null,
    errors: null,

    init: function() {
        var self = this;
        this._hasManyRecordArrays = {};
        this._deletedEmbeddedRecords = [];
        this._inRecordArrays = {};
        this.set('_data', {
            attributes: {},
            belongsTo: {},
            hasMany: {}
        });
        this.promise = new Em.RSVP.Promise(function(resolve, reject) {
            if (self.get('isLoaded')) {
                resolve(self);
            } else {
                self.one('didLoad', function() {
                    self.set('isLoaded', true);
                    resolve(self);
                });
                self.one('didError', reject);
            }
        });
        BD.store.didInstantiateRecord(this);
        this._super();
    },

    reference: function() {
        return Ember.get(this.constructor, 'root') + ':' + this.get('id');
    }.property('id'),

    eachAttribute: function(callback, binding) {
        Em.get(this.constructor, 'attributes').forEach(function(key, meta) {
            callback.call(binding, key, meta);
        });
    },

    eachBelongsTo: function(callback, binding) {
        Em.get(this.constructor, 'belongsToRelationships').forEach(function(key, meta) {
            callback.call(binding, key, meta);
        });
    },
    _parentRelationship: function() {
        var parentRelationship = null;
        this.eachBelongsTo(function(key, meta) {
            if (meta.options.isParent) {
                parentRelationship = key;
            }
        }, this);
        return parentRelationship;
    }.property(),
    isEmbedded: function() {
        return !!this.get('_parentRelationship');
    }.property(),
    getParent: function() {
        var parentRelationship = this.get('_parentRelationship');
        return parentRelationship ? this.get(parentRelationship) : null;
    },

    eachHasMany: function(callback, binding) {
        Em.get(this.constructor, 'hasManyRelationships').forEach(function(key, meta) {
            callback.call(binding, key, meta);
        });
    },
    eachEmbeddedHasMany: function(callback, binding) {
        this.eachHasMany(function(key, meta) {
            if (meta.options.isEmbedded) {
                callback.call(binding, key, meta)
            }
        })
    },
    eachEmbeddedRecord: function(callback, binding) {
        this.eachEmbeddedHasMany(function(key, meta) {
            //Skip unloaded records
            if (!this.hasManyIsLoaded(key)) {
                return;
            }
            var records = this.get(key);
            records.forEach(function(r) {
                callback.call(binding, r, key, meta);
            });
        }, this)
    },
    hasManyIsLoaded: function(key) {
        return this._hasManyRecordArrays[key];
    },

    didDefineProperty: function(proto, key, value) {
        if (value instanceof Ember.Descriptor) {
            var meta = value.meta();
            if (meta.isAttribute || meta.isBelongsTo) {
                Ember.addObserver(proto, key, null, '_attributeDidChange');
            }
        }
    },
    _attributeDidChange: function(r, key) {
        BD.store.recordAttributeDidChange(this, key);
    },

    loadData: function(serialized) {
        this._serializedData = serialized;
    },
    materializeData: function() {
        var serialized = this._serializedData,
            data = this.get('_data');
        BD.store.suspendRecordAttributeDidChange();
        //Attributes
        this.eachAttribute(function(key, meta) {
            var serverValue = BD.transforms[meta.type].deserialize(serialized[key]);
            if (this.get('selfIsDirty')) {
                var cleanValue = this.clean.data.attributes[key],
                    clientValue = data.attributes[key];
                if (cleanValue !== clientValue) {
                    return;
                }
            }
            data.attributes[key] = serverValue;
            BD.store.recordAttributeDidChange(this, key);
        }, this);
        //BelongsTo
        this.eachBelongsTo(function(key, meta) {
            var serverValue = meta.extractValue(serialized, key);
            if (this.get('selfIsDirty')) {
                var cleanValue = this.clean.data.belongsTo[key],
                    clientValue = data.belongsTo[key];
                if (cleanValue !== clientValue) {
                    return;
                }
            }
            data.belongsTo[key] = serverValue;
            BD.store.recordAttributeDidChange(this, key);
        }, this);
        //HasMany
        this.eachHasMany(function(key, meta) {
            var ids = serialized[BD.singularize(key)+'Ids'];
            if (ids) {
                data.hasMany[key] = ids;
                this.get(key);
            }
        }, this);
        //
        Em.propertyDidChange(this, '_data');
        BD.store.resumeRecordAttributeDidChange();
        //
        delete this._serializedData;
    },

    include: function(include) {
        BD.store.findByIdInclude(this.constructor, this.get('id'), include);
    },

    isDirty: function() {
        return (this.get('selfIsDirty') || this.get('childIsDirty'));
    }.property('selfIsDirty', 'childIsDirty'),
    becomeDirty: function() {
        if (this.get('isUnloaded') || this.get('selfIsDirty')) {
            return;
        }
        var data = this.get('_data'),
            parent;
        this.clean = {
            isNew: this.get('isNew'),
            data: {
                attributes: Em.copy(data.attributes),
                belongsTo: Em.copy(data.belongsTo),
                hasMany: Em.copy(data.hasMany, true)
            }
        };
        this.set('selfIsDirty', true);
        //Dirty parent
        parent = this.getParent();
        if (parent) {
            parent.checkEmbeddedChildrenDirty();
        }
    },
    checkEmbeddedChildrenDirty: function() {
        var childIsDirty = false;
        if (this._deletedEmbeddedRecords.length > 0) {
            childIsDirty = true;
        }
        this.eachEmbeddedRecord(function(r) {
            if (r.get('isDirty')) {
                childIsDirty = true;
            }
        });
        this.set('childIsDirty', childIsDirty);
    },
    didDeleteEmbeddedRecord: function(r) {
        this._deletedEmbeddedRecords.push(r);
        this.checkEmbeddedChildrenDirty();
    },
    becameClean: function() {
        this.checkEmbeddedChildrenDirty();
        if (!this.get('selfIsDirty')) {
            return;
        }
        delete this.clean;
        this.set('selfIsDirty', false);
    },
    didCommit: function(options) {
        this.setProperties(options.properties);
        this.eachHasMany(function(key) {
            if (options.embed.contains(key)) {
                this.get(key).forEach(function(child) {
                    child.becameClean();
                });
            }
        }, this);
        this._deletedEmbeddedRecords.forEach(function(r) {
            r.unload();
        });
        this._deletedEmbeddedRecords = [];
        this.becameClean();
    },
    rollback: function() {
        //Setup data variables
        var selfIsDirty = this.get('selfIsDirty');
        //Rollback embedded records. We have to take these directly from BOTH the dirty- and clean data, if the record itself is dirty
        this.eachEmbeddedRecord(function(r) {
            r.rollback();
        }, this);
        this._deletedEmbeddedRecords.forEach(function(r) {
            r.rollback();
        });
        this._deletedEmbeddedRecords = [];
        this.checkEmbeddedChildrenDirty();
        //Don't continue if this record itself is not dirty
        if (!selfIsDirty) {
            return;
        }
        //Store dirty parent (before we might clean it and set it back the original parent)
        var dirtyParent = this.getParent();
        //Set the data to the clean data
        this.set('_data', this.clean.data);
        //Handle the case where the record is not newly created
        if (!this.clean.isNew) {
            if (this.get('isDeleted')) {
                this.set('isDeleted', false);
            }
            this.becameClean();
        } else {
            //Handle case where record never was created. Then we just unload it
            this.unload();
        }
        //Let parent check child dirtiness
        if (dirtyParent) {
            dirtyParent.checkEmbeddedChildrenDirty();
        }
    },

    didDelete: function() {
        this.eachEmbeddedRecord(function(child) {
            child.didDelete();
        });
        this.unload();
    },

    save: function(options) {
        return BD.store.saveRecord(this, options);
    },

    deleteRecord: function() {
        return BD.store.deleteRecord(this);
    },

    serialize: function(options) {
        options = options || {};
        var serialized = {},
            optionProperties = options.properties || {},
            data = this.get('_data');
        serialized._clientId = this.get('clientId');
        if (!this.get('isNew')) {
            serialized.id = this.get('id');
        }
        this.eachAttribute(function(key, meta) {
            if ((options.includeReadonly || !meta.options.readonly)) {
                var value = optionProperties.hasOwnProperty(key) ? optionProperties[key] : data.attributes[key];
                if (typeof value !== 'undefined') {
                    serialized[key] = BD.transforms[meta.type].serialize(value);
                }
            }
        }, this);
        this.eachBelongsTo(function(key, meta) {
            if ((options.includeReadonly || !meta.options.readonly) && (!options.isEmbedded || !meta.options.isParent)) {
                var id;
                if (optionProperties.hasOwnProperty(key)) {
                    id = optionProperties[key] ? optionProperties[key].get('id') : null;
                } else {
                    id = data.belongsTo[key];
                }
                if (id && typeof id === 'object') {
                    id = BD.store.findByClientId(id.clientId).get(meta.idProperty);
                }
                if (typeof id === 'undefined') {
                    id = null;
                }
                meta.serialize(serialized, key, id);
            }
        }, this);
        if (options.embed) {
            this.eachHasMany(function(key, meta) {
                if (options.embed.contains(key)) {
                    var embeddedRecords = [];
                    this.get(key).forEach(function(child) {
                        embeddedRecords.push(child.serialize({isEmbedded: true}));
                    });
                    serialized[key] = embeddedRecords;
                }
            }, this);
        }
        return serialized;
    },

    didAddToRecordArray: function(recordArray) {
        this._inRecordArrays[Em.guidFor(recordArray)] = recordArray;
    },
    didRemoveFromRecordArray: function(recordArray) {
        delete this._inRecordArrays[Em.guidFor(recordArray)];
    },
    isInRecordArray: function(recordArray) {
        return !!this._inRecordArrays[Em.guidFor(recordArray)]
    },

    unload: function() {
        this.set('isUnloaded', true);
        this.eachBelongsTo(function(name) {
            this.set(name, null);
        }, this);
        this.eachEmbeddedRecord(function(child) {
            child.unload();
        });
        _.each(this._inRecordArrays, function(recordArray) {
            recordArray.removeObject(this);
        }, this);
        BD.store.didUnloadRecord(this);
        this.destroy();
    },

    toString: function toString() {
        return '<'+this.constructor.toString()+':'+this.get('id')+':'+this.get('clientId')+'>';
    }

});

BD.Model.reopenClass({

    _create: BD.Model.create,
    create: function() {
        throw new Ember.Error("You should not call `create` on a model. Instead, call `createRecord` with the attributes you would like to set.");
    },
    createRecord: function(properties) {
        //Instantiate record
        properties = properties || {};
        var r = this._create({
            isNew: true,
            isLoaded: true
        });
        //Make sure that each hasMany relationship is registered as an empty RecordArray
        var data = r.get('_data');
        r.eachHasMany(function(name) {
            data.hasMany[name] = [];
            r.get(name);
        }, this);
        //Mark the record as dirty and update properties
        r.becomeDirty();
        BD.store.suspendRecordAttributeDidChange();
        r.setProperties(properties);
        BD.store.resumeRecordAttributeDidChange();
        return r;
    },

    root: function() {
        var typeString = this.toString();
        var parts = typeString.split(".");
        var name = parts[parts.length - 1];
        name = name.substring(0, 1).toLowerCase() + name.substring(1);
        return name;
    }.property(),

    attributes: function() {
        var map = Ember.Map.create();
        this.eachComputedProperty(function(key, meta) {
            if (meta.isAttribute) {
                meta.key = key;
                map.set(key, meta);
            }
        });
        return map;
    }.property(),

    belongsToRelationships: function() {
        var map = Ember.Map.create();
        this.eachComputedProperty(function(key, meta) {
            if (meta.isBelongsTo) {
                meta.key = key;
                map.set(key, meta);
            }
        });
        return map;
    }.property(),

    hasManyRelationships: function() {
        var map = Ember.Map.create();
        this.eachComputedProperty(function(key, meta) {
            if (meta.isHasMany) {
                meta.key = key;
                map.set(key, meta);
            }
        });
        return map;
    }.property(),

    find: function(id) {
        return BD.store.find(this, id);
    },
    findMany: function(ids) {
        return BD.store.findMany(this, ids);
    },
    findByUrl: function(url, query) {
        return BD.store.findByUrl(this, url, query);
    },
    findByQuery: function(query) {
        return BD.store.findByQuery(this, query);
    },
    findByIdQuery: function(id, query) {
        return BD.store.findByIdQuery(this, id, query);
    },
    findByIdInclude: function(id, include) {
        return BD.store.findByIdInclude(this, id, include);
    },
    all: function() {
        return BD.store.all(this);
    },
    allLocal: function() {
        return BD.store.allLocal(this);
    },
    filter: function(filter, comparator) {
        return BD.store.filter(this, filter, comparator);
    },
    loadAll: function(dataItems) {
        return BD.store.loadAll(this, dataItems);
    },
    loadMany: function(dataItems) {
        return BD.store.loadMany(this, dataItems);
    },
    load: function(data) {
        return BD.store.load(this, data);
    },

    registerSortMacro: function(name, dependencies, comparator) {
        if (!this.sortMacros) {
            this.sortMacros = {};
        }
        this.sortMacros[name] = {
            dependencies: dependencies,
            comparator: comparator
        };
    },

    getSortMacro: function(name) {
        if (!this.sortMacros) {
            return null;
        }
        return this.sortMacros[name];
    }
});<commit_msg>Fixed BD.Model.filter method signature<commit_after>BD.Model = Em.Object.extend(Em.Evented, {

    isLoaded: false,
    isNew: false,
    isDeleted: false,
    selfIsDirty: false,
    childIsDirty: false,

    isNotLoaded: Em.computed.not('isLoaded'),

    clientId: null,
    id: null,
    _data: null,
    error: null,
    errors: null,

    init: function() {
        var self = this;
        this._hasManyRecordArrays = {};
        this._deletedEmbeddedRecords = [];
        this._inRecordArrays = {};
        this.set('_data', {
            attributes: {},
            belongsTo: {},
            hasMany: {}
        });
        this.promise = new Em.RSVP.Promise(function(resolve, reject) {
            if (self.get('isLoaded')) {
                resolve(self);
            } else {
                self.one('didLoad', function() {
                    self.set('isLoaded', true);
                    resolve(self);
                });
                self.one('didError', reject);
            }
        });
        BD.store.didInstantiateRecord(this);
        this._super();
    },

    reference: function() {
        return Ember.get(this.constructor, 'root') + ':' + this.get('id');
    }.property('id'),

    eachAttribute: function(callback, binding) {
        Em.get(this.constructor, 'attributes').forEach(function(key, meta) {
            callback.call(binding, key, meta);
        });
    },

    eachBelongsTo: function(callback, binding) {
        Em.get(this.constructor, 'belongsToRelationships').forEach(function(key, meta) {
            callback.call(binding, key, meta);
        });
    },
    _parentRelationship: function() {
        var parentRelationship = null;
        this.eachBelongsTo(function(key, meta) {
            if (meta.options.isParent) {
                parentRelationship = key;
            }
        }, this);
        return parentRelationship;
    }.property(),
    isEmbedded: function() {
        return !!this.get('_parentRelationship');
    }.property(),
    getParent: function() {
        var parentRelationship = this.get('_parentRelationship');
        return parentRelationship ? this.get(parentRelationship) : null;
    },

    eachHasMany: function(callback, binding) {
        Em.get(this.constructor, 'hasManyRelationships').forEach(function(key, meta) {
            callback.call(binding, key, meta);
        });
    },
    eachEmbeddedHasMany: function(callback, binding) {
        this.eachHasMany(function(key, meta) {
            if (meta.options.isEmbedded) {
                callback.call(binding, key, meta)
            }
        })
    },
    eachEmbeddedRecord: function(callback, binding) {
        this.eachEmbeddedHasMany(function(key, meta) {
            //Skip unloaded records
            if (!this.hasManyIsLoaded(key)) {
                return;
            }
            var records = this.get(key);
            records.forEach(function(r) {
                callback.call(binding, r, key, meta);
            });
        }, this)
    },
    hasManyIsLoaded: function(key) {
        return this._hasManyRecordArrays[key];
    },

    didDefineProperty: function(proto, key, value) {
        if (value instanceof Ember.Descriptor) {
            var meta = value.meta();
            if (meta.isAttribute || meta.isBelongsTo) {
                Ember.addObserver(proto, key, null, '_attributeDidChange');
            }
        }
    },
    _attributeDidChange: function(r, key) {
        BD.store.recordAttributeDidChange(this, key);
    },

    loadData: function(serialized) {
        this._serializedData = serialized;
    },
    materializeData: function() {
        var serialized = this._serializedData,
            data = this.get('_data');
        BD.store.suspendRecordAttributeDidChange();
        //Attributes
        this.eachAttribute(function(key, meta) {
            var serverValue = BD.transforms[meta.type].deserialize(serialized[key]);
            if (this.get('selfIsDirty')) {
                var cleanValue = this.clean.data.attributes[key],
                    clientValue = data.attributes[key];
                if (cleanValue !== clientValue) {
                    return;
                }
            }
            data.attributes[key] = serverValue;
            BD.store.recordAttributeDidChange(this, key);
        }, this);
        //BelongsTo
        this.eachBelongsTo(function(key, meta) {
            var serverValue = meta.extractValue(serialized, key);
            if (this.get('selfIsDirty')) {
                var cleanValue = this.clean.data.belongsTo[key],
                    clientValue = data.belongsTo[key];
                if (cleanValue !== clientValue) {
                    return;
                }
            }
            data.belongsTo[key] = serverValue;
            BD.store.recordAttributeDidChange(this, key);
        }, this);
        //HasMany
        this.eachHasMany(function(key, meta) {
            var ids = serialized[BD.singularize(key)+'Ids'];
            if (ids) {
                data.hasMany[key] = ids;
                this.get(key);
            }
        }, this);
        //
        Em.propertyDidChange(this, '_data');
        BD.store.resumeRecordAttributeDidChange();
        //
        delete this._serializedData;
    },

    include: function(include) {
        BD.store.findByIdInclude(this.constructor, this.get('id'), include);
    },

    isDirty: function() {
        return (this.get('selfIsDirty') || this.get('childIsDirty'));
    }.property('selfIsDirty', 'childIsDirty'),
    becomeDirty: function() {
        if (this.get('isUnloaded') || this.get('selfIsDirty')) {
            return;
        }
        var data = this.get('_data'),
            parent;
        this.clean = {
            isNew: this.get('isNew'),
            data: {
                attributes: Em.copy(data.attributes),
                belongsTo: Em.copy(data.belongsTo),
                hasMany: Em.copy(data.hasMany, true)
            }
        };
        this.set('selfIsDirty', true);
        //Dirty parent
        parent = this.getParent();
        if (parent) {
            parent.checkEmbeddedChildrenDirty();
        }
    },
    checkEmbeddedChildrenDirty: function() {
        var childIsDirty = false;
        if (this._deletedEmbeddedRecords.length > 0) {
            childIsDirty = true;
        }
        this.eachEmbeddedRecord(function(r) {
            if (r.get('isDirty')) {
                childIsDirty = true;
            }
        });
        this.set('childIsDirty', childIsDirty);
    },
    didDeleteEmbeddedRecord: function(r) {
        this._deletedEmbeddedRecords.push(r);
        this.checkEmbeddedChildrenDirty();
    },
    becameClean: function() {
        this.checkEmbeddedChildrenDirty();
        if (!this.get('selfIsDirty')) {
            return;
        }
        delete this.clean;
        this.set('selfIsDirty', false);
    },
    didCommit: function(options) {
        this.setProperties(options.properties);
        this.eachHasMany(function(key) {
            if (options.embed.contains(key)) {
                this.get(key).forEach(function(child) {
                    child.becameClean();
                });
            }
        }, this);
        this._deletedEmbeddedRecords.forEach(function(r) {
            r.unload();
        });
        this._deletedEmbeddedRecords = [];
        this.becameClean();
    },
    rollback: function() {
        //Setup data variables
        var selfIsDirty = this.get('selfIsDirty');
        //Rollback embedded records. We have to take these directly from BOTH the dirty- and clean data, if the record itself is dirty
        this.eachEmbeddedRecord(function(r) {
            r.rollback();
        }, this);
        this._deletedEmbeddedRecords.forEach(function(r) {
            r.rollback();
        });
        this._deletedEmbeddedRecords = [];
        this.checkEmbeddedChildrenDirty();
        //Don't continue if this record itself is not dirty
        if (!selfIsDirty) {
            return;
        }
        //Store dirty parent (before we might clean it and set it back the original parent)
        var dirtyParent = this.getParent();
        //Set the data to the clean data
        this.set('_data', this.clean.data);
        //Handle the case where the record is not newly created
        if (!this.clean.isNew) {
            if (this.get('isDeleted')) {
                this.set('isDeleted', false);
            }
            this.becameClean();
        } else {
            //Handle case where record never was created. Then we just unload it
            this.unload();
        }
        //Let parent check child dirtiness
        if (dirtyParent) {
            dirtyParent.checkEmbeddedChildrenDirty();
        }
    },

    didDelete: function() {
        this.eachEmbeddedRecord(function(child) {
            child.didDelete();
        });
        this.unload();
    },

    save: function(options) {
        return BD.store.saveRecord(this, options);
    },

    deleteRecord: function() {
        return BD.store.deleteRecord(this);
    },

    serialize: function(options) {
        options = options || {};
        var serialized = {},
            optionProperties = options.properties || {},
            data = this.get('_data');
        serialized._clientId = this.get('clientId');
        if (!this.get('isNew')) {
            serialized.id = this.get('id');
        }
        this.eachAttribute(function(key, meta) {
            if ((options.includeReadonly || !meta.options.readonly)) {
                var value = optionProperties.hasOwnProperty(key) ? optionProperties[key] : data.attributes[key];
                if (typeof value !== 'undefined') {
                    serialized[key] = BD.transforms[meta.type].serialize(value);
                }
            }
        }, this);
        this.eachBelongsTo(function(key, meta) {
            if ((options.includeReadonly || !meta.options.readonly) && (!options.isEmbedded || !meta.options.isParent)) {
                var id;
                if (optionProperties.hasOwnProperty(key)) {
                    id = optionProperties[key] ? optionProperties[key].get('id') : null;
                } else {
                    id = data.belongsTo[key];
                }
                if (id && typeof id === 'object') {
                    id = BD.store.findByClientId(id.clientId).get(meta.idProperty);
                }
                if (typeof id === 'undefined') {
                    id = null;
                }
                meta.serialize(serialized, key, id);
            }
        }, this);
        if (options.embed) {
            this.eachHasMany(function(key, meta) {
                if (options.embed.contains(key)) {
                    var embeddedRecords = [];
                    this.get(key).forEach(function(child) {
                        embeddedRecords.push(child.serialize({isEmbedded: true}));
                    });
                    serialized[key] = embeddedRecords;
                }
            }, this);
        }
        return serialized;
    },

    didAddToRecordArray: function(recordArray) {
        this._inRecordArrays[Em.guidFor(recordArray)] = recordArray;
    },
    didRemoveFromRecordArray: function(recordArray) {
        delete this._inRecordArrays[Em.guidFor(recordArray)];
    },
    isInRecordArray: function(recordArray) {
        return !!this._inRecordArrays[Em.guidFor(recordArray)]
    },

    unload: function() {
        this.set('isUnloaded', true);
        this.eachBelongsTo(function(name) {
            this.set(name, null);
        }, this);
        this.eachEmbeddedRecord(function(child) {
            child.unload();
        });
        _.each(this._inRecordArrays, function(recordArray) {
            recordArray.removeObject(this);
        }, this);
        BD.store.didUnloadRecord(this);
        this.destroy();
    },

    toString: function toString() {
        return '<'+this.constructor.toString()+':'+this.get('id')+':'+this.get('clientId')+'>';
    }

});

BD.Model.reopenClass({

    _create: BD.Model.create,
    create: function() {
        throw new Ember.Error("You should not call `create` on a model. Instead, call `createRecord` with the attributes you would like to set.");
    },
    createRecord: function(properties) {
        //Instantiate record
        properties = properties || {};
        var r = this._create({
            isNew: true,
            isLoaded: true
        });
        //Make sure that each hasMany relationship is registered as an empty RecordArray
        var data = r.get('_data');
        r.eachHasMany(function(name) {
            data.hasMany[name] = [];
            r.get(name);
        }, this);
        //Mark the record as dirty and update properties
        r.becomeDirty();
        BD.store.suspendRecordAttributeDidChange();
        r.setProperties(properties);
        BD.store.resumeRecordAttributeDidChange();
        return r;
    },

    root: function() {
        var typeString = this.toString();
        var parts = typeString.split(".");
        var name = parts[parts.length - 1];
        name = name.substring(0, 1).toLowerCase() + name.substring(1);
        return name;
    }.property(),

    attributes: function() {
        var map = Ember.Map.create();
        this.eachComputedProperty(function(key, meta) {
            if (meta.isAttribute) {
                meta.key = key;
                map.set(key, meta);
            }
        });
        return map;
    }.property(),

    belongsToRelationships: function() {
        var map = Ember.Map.create();
        this.eachComputedProperty(function(key, meta) {
            if (meta.isBelongsTo) {
                meta.key = key;
                map.set(key, meta);
            }
        });
        return map;
    }.property(),

    hasManyRelationships: function() {
        var map = Ember.Map.create();
        this.eachComputedProperty(function(key, meta) {
            if (meta.isHasMany) {
                meta.key = key;
                map.set(key, meta);
            }
        });
        return map;
    }.property(),

    find: function(id) {
        return BD.store.find(this, id);
    },
    findMany: function(ids) {
        return BD.store.findMany(this, ids);
    },
    findByUrl: function(url, query) {
        return BD.store.findByUrl(this, url, query);
    },
    findByQuery: function(query) {
        return BD.store.findByQuery(this, query);
    },
    findByIdQuery: function(id, query) {
        return BD.store.findByIdQuery(this, id, query);
    },
    findByIdInclude: function(id, include) {
        return BD.store.findByIdInclude(this, id, include);
    },
    all: function() {
        return BD.store.all(this);
    },
    allLocal: function() {
        return BD.store.allLocal(this);
    },
    filter: function(options) {
        return BD.store.filter(this, options);
    },
    loadAll: function(dataItems) {
        return BD.store.loadAll(this, dataItems);
    },
    loadMany: function(dataItems) {
        return BD.store.loadMany(this, dataItems);
    },
    load: function(data) {
        return BD.store.load(this, data);
    },

    registerSortMacro: function(name, dependencies, comparator) {
        if (!this.sortMacros) {
            this.sortMacros = {};
        }
        this.sortMacros[name] = {
            dependencies: dependencies,
            comparator: comparator
        };
    },

    getSortMacro: function(name) {
        if (!this.sortMacros) {
            return null;
        }
        return this.sortMacros[name];
    }
});<|endoftext|>


<commit_before>(function() {
  var ui = window.UI;
  var Human = {
    currentPlayer: "",

    choiceSpot: function(board, currentPlayer) {
      this.currentPlayer = currentPlayer;
      var chosenSpot;
      var _this = this;
      $("tr td").click(function(e) {
        chosenSpot = e.target.id;
        if ($("#" + chosenSpot).text() == "") {
          _this.markChosenSpot(board, chosenSpot, _this.currentPlayer);
          _this.changePlayer(_this.currentPlayer);
        }
        else {
          ui.spotErrorMessage();
          return;
        }
      });
    },

    markChosenSpot: function(board, chosenSpot, currentPlayer) {
      $("#" + chosenSpot).text(currentPlayer);
      board.spots[chosenSpot] = currentPlayer;
    },

    changePlayer: function(currentPlayer) {
      this.currentPlayer = currentPlayer == "X" ? "O" : "X";
    }
  };
  window.Human = Human;
})();
<commit_msg>fixed function in human<commit_after>(function() {
  var ui = window.UI;
  var Human = {
    currentPlayer: "",

    choiceSpot: function(board, currentPlayer) {
      var chosenSpot;
      chosenSpot = event.target.id;
      if ($("#" + chosenSpot).text() == "") {
        this.markChosenSpot(board, chosenSpot, currentPlayer);
      }
      else {
        ui.spotErrorMessage();
        return;
      }
    },

    markChosenSpot: function(board, chosenSpot, currentPlayer) {
      $("#" + chosenSpot).text(currentPlayer);
      board.spots[chosenSpot] = currentPlayer;
    },

    changePlayer: function(currentPlayer) {
      return currentPlayer == "X" ? "O" : "X";
    }
  };
  window.Human = Human;
})();
<|endoftext|>


<commit_before>module.exports = {
  BarChart: require('./components/BarChart'),
  Button: require('./components/Button'),
  ButtonGroup: require('./components/ButtonGroup'),
  Calendar: require('./components/Calendar'),
  Column: require('./components/grid/Column'),
  DatePicker: require('./components/DatePicker'),
  DatePickerFullScreen: require('./components/DatePickerFullScreen'),
  DateRangePicker: require('./components/DateRangePicker'),
  DateTimePicker: require('./components/DateTimePicker'),
  DisplayInput: require('./components/DisplayInput'),
  DonutChart: require('./components/DonutChart'),
  Drawer: require('./components/Drawer'),
  FileUpload: require('./components/FileUpload'),
  Icon: require('./components/Icon'),
  Loader: require('./components/Loader'),
  Modal: require('./components/Modal'),
  PageIndicator: require('./components/PageIndicator'),
  ProgressBar: require('./components/ProgressBar'),
  RadioButton: require('./components/RadioButton'),
  RajaIcon: require('./components/RajaIcon'),
  Row: require('./components/grid/Row'),
  RangeSelector: require('./components/RangeSelector'),
  SearchInput: require('./components/SearchInput'),
  Select: require('./components/Select'),
  SelectFullScreen: require('./components/SelectFullScreen'),
  SimpleInput: require('./components/SimpleInput'),
  SimpleSelect: require('./components/SimpleSelect'),
  Spin: require('./components/Spin'),
  TimeBasedLineChart: require('./components/TimeBasedLineChart'),
  ToggleSwitch: require('./components/ToggleSwitch'),
  Tooltip: require('./components/Tooltip'),
  TypeAhead: require('./components/TypeAhead'),

  AppConstants: require('./constants/App'),
  Styles: require('./constants/Style')
};
<commit_msg>require in new Container component<commit_after>module.exports = {
  BarChart: require('./components/BarChart'),
  Button: require('./components/Button'),
  ButtonGroup: require('./components/ButtonGroup'),
  Calendar: require('./components/Calendar'),
  Column: require('./components/grid/Column'),
  Container: require('./components/grid/Container'),
  DatePicker: require('./components/DatePicker'),
  DatePickerFullScreen: require('./components/DatePickerFullScreen'),
  DateRangePicker: require('./components/DateRangePicker'),
  DateTimePicker: require('./components/DateTimePicker'),
  DisplayInput: require('./components/DisplayInput'),
  DonutChart: require('./components/DonutChart'),
  Drawer: require('./components/Drawer'),
  FileUpload: require('./components/FileUpload'),
  Icon: require('./components/Icon'),
  Loader: require('./components/Loader'),
  Modal: require('./components/Modal'),
  PageIndicator: require('./components/PageIndicator'),
  ProgressBar: require('./components/ProgressBar'),
  RadioButton: require('./components/RadioButton'),
  RajaIcon: require('./components/RajaIcon'),
  Row: require('./components/grid/Row'),
  RangeSelector: require('./components/RangeSelector'),
  SearchInput: require('./components/SearchInput'),
  Select: require('./components/Select'),
  SelectFullScreen: require('./components/SelectFullScreen'),
  SimpleInput: require('./components/SimpleInput'),
  SimpleSelect: require('./components/SimpleSelect'),
  Spin: require('./components/Spin'),
  TimeBasedLineChart: require('./components/TimeBasedLineChart'),
  ToggleSwitch: require('./components/ToggleSwitch'),
  Tooltip: require('./components/Tooltip'),
  TypeAhead: require('./components/TypeAhead'),

  AppConstants: require('./constants/App'),
  Styles: require('./constants/Style')
};
<|endoftext|>


<commit_before>const fetch = require('node-fetch');
const { URL } = require('url');
const { Parser } = require('xml2js');
const parser = new Parser();

const sites = require('./sites');
const { version } = require('../package');

class Kaori {
	constructor(customSites = {}) {
		this.sites = Object.assign(customSites, sites);
	}

	_resolveSite(resolvable) {
		if (typeof resolvable !== 'string') return false;
		resolvable = resolvable.toLowerCase();
		for (const site of Object.keys(this.sites)) {
			if (site === resolvable || this.sites[site].aliases.includes(resolvable)) return site;
		}
		return false;
	}

	search(site, { tags = [], limit = 1, random = false } = {}) {
		return new Promise((resolve, reject) => {
			if (!this._resolveSite(site)) return reject(new Error('This site is not supported.'));
			if (!(tags instanceof Array)) return reject(new Error('Tags have to be an Array.'));
			if (typeof limit !== 'number' && !Number.isNaN(limit)) return reject(new Error('Limit has to be a number.'));

			site = this._resolveSite(site);
			limit = parseInt(limit);
			return resolve(this._searchPosts(site, { tags, limit, random }));
		});
	}

	_searchPosts(site, { tags, limit, random }) {
		return new Promise((resolve, reject) => {
			const endpoint = this.sites[site].endpoint;
			const userAgent = `Kaori, a npm module for boorus. v${version} (https://github.com/iCrawl/Kaori/)`;
			const options = { headers: { 'User-Agent': userAgent } };
			if (!random) {
				return fetch(`http://${site}${endpoint}tags=${tags.join('+')}&limit=${limit}`, options)
					.then(res => {
						const contentType = res.headers.get('content-type').split(';');
						if (contentType.includes('text/xml')) return this._xml2json(res.text());
						else return res.json();
					})
					.then(images => resolve(this._commonify(images)))
					.catch(err => reject(new Error(`Couldn't fetch the api. ${err}`)));
			} else if (random && sites[site].random) {
				return fetch(`http://${site}${endpoint}tags=${tags.join('+')}+order:random&limit=${limit}`, options)
					.then(res => {
						const contentType = res.headers.get('content-type').split(';');
						if (contentType.includes('text/xml')) return this._xml2json(res.text());
						else return res.json();
					})
					.then(images => resolve(this._commonify(images)))
					.catch(err => reject(new Error(`Couldn't fetch the api. ${err}`)));
			} else {
				return fetch(`http://${site}${endpoint}tags=${tags.join('+')}&limit=100`, options)
					.then(res => {
						const contentType = res.headers.get('content-type').split(';');
						if (contentType.includes('text/xml')) return this._xml2json(res.text());
						else return res.json();
					})
					.then(parsed => this._shuffle(parsed))
					.then(shuffled => resolve(this._commonify(shuffled)))
					.catch(err => reject(new Error(`Couldn't fetch the api. ${err}`)));
			}
		});
	}

	_commonify(images) {
		return new Promise((resolve, reject) => {
			if (typeof images[0] === 'undefined') return reject(new Error('Commonify didn\'t recieve any images.'));
			return this._xml2json(images)
				.then(res => this._common(res))
				.then(image => resolve(image))
				.catch(error => reject(new Error(error)));
		});
	}

	_xml2json(images) {
		return new Promise((resolve, reject) => {
			if (typeof images !== 'object') {
				return parser.parseString(images, (err, res) => {
					if (err) return reject(new Error(err));
					if (typeof res.posts.post === 'undefined') return resolve([]);
					else return resolve(res.posts.post.map(val => val.$));
				});
			} else {
				return resolve(images);
			}
		});
	}

	_common(images) {
		return new Promise(resolve => {
			if (images === []) return resolve([]);
			for (const image of Object.keys(images)) {
				const key = images[image];
				key.common = {
					fileURL: key.file_url.startsWith('/data')
						? `https://danbooru.donmai.us${key.file_url}`
						: !key.file_url.startsWith('http')
							? `https:${key.file_url}`
							: new URL(key.file_url).href,
					id: key.id.toString(),
					tags: typeof key.tags !== 'undefined'
						? key.tags.split(' ').filter(val => val !== '')
						: key.tag_string.split(' ').filter(val => val !== ''),
					score: parseInt(key.score),
					source: key.source,
					rating: key.rating
				};
			}
			return resolve(images);
		});
	}

	_shuffle(array) {
		for (let i = array.length - 1; i > 0; i--) {
			const j = Math.floor(Math.random() * (i + 1));
			const temp = array[i];
			array[i] = array[j];
			array[j] = temp;
		}
		return array;
	}
}

module.exports = Kaori;
<commit_msg>catch danbooru cached images<commit_after>const fetch = require('node-fetch');
const { URL } = require('url');
const { Parser } = require('xml2js');
const parser = new Parser();

const sites = require('./sites');
const { version } = require('../package');

class Kaori {
	constructor(customSites = {}) {
		this.sites = Object.assign(customSites, sites);
	}

	_resolveSite(resolvable) {
		if (typeof resolvable !== 'string') return false;
		resolvable = resolvable.toLowerCase();
		for (const site of Object.keys(this.sites)) {
			if (site === resolvable || this.sites[site].aliases.includes(resolvable)) return site;
		}
		return false;
	}

	search(site, { tags = [], limit = 1, random = false } = {}) {
		return new Promise((resolve, reject) => {
			if (!this._resolveSite(site)) return reject(new Error('This site is not supported.'));
			if (!(tags instanceof Array)) return reject(new Error('Tags have to be an Array.'));
			if (typeof limit !== 'number' && !Number.isNaN(limit)) return reject(new Error('Limit has to be a number.'));

			site = this._resolveSite(site);
			limit = parseInt(limit);
			return resolve(this._searchPosts(site, { tags, limit, random }));
		});
	}

	_searchPosts(site, { tags, limit, random }) {
		return new Promise((resolve, reject) => {
			const endpoint = this.sites[site].endpoint;
			const userAgent = `Kaori, a npm module for boorus. v${version} (https://github.com/iCrawl/Kaori/)`;
			const options = { headers: { 'User-Agent': userAgent } };
			if (!random) {
				return fetch(`http://${site}${endpoint}tags=${tags.join('+')}&limit=${limit}`, options)
					.then(res => {
						const contentType = res.headers.get('content-type').split(';');
						if (contentType.includes('text/xml')) return this._xml2json(res.text());
						else return res.json();
					})
					.then(images => resolve(this._commonify(images)))
					.catch(err => reject(new Error(`Couldn't fetch the api. ${err}`)));
			} else if (random && sites[site].random) {
				return fetch(`http://${site}${endpoint}tags=${tags.join('+')}+order:random&limit=${limit}`, options)
					.then(res => {
						const contentType = res.headers.get('content-type').split(';');
						if (contentType.includes('text/xml')) return this._xml2json(res.text());
						else return res.json();
					})
					.then(images => resolve(this._commonify(images)))
					.catch(err => reject(new Error(`Couldn't fetch the api. ${err}`)));
			} else {
				return fetch(`http://${site}${endpoint}tags=${tags.join('+')}&limit=100`, options)
					.then(res => {
						const contentType = res.headers.get('content-type').split(';');
						if (contentType.includes('text/xml')) return this._xml2json(res.text());
						else return res.json();
					})
					.then(parsed => this._shuffle(parsed))
					.then(shuffled => resolve(this._commonify(shuffled)))
					.catch(err => reject(new Error(`Couldn't fetch the api. ${err}`)));
			}
		});
	}

	_commonify(images) {
		return new Promise((resolve, reject) => {
			if (typeof images[0] === 'undefined') return reject(new Error('Commonify didn\'t recieve any images.'));
			return this._xml2json(images)
				.then(res => this._common(res))
				.then(image => resolve(image))
				.catch(error => reject(new Error(error)));
		});
	}

	_xml2json(images) {
		return new Promise((resolve, reject) => {
			if (typeof images !== 'object') {
				return parser.parseString(images, (err, res) => {
					if (err) return reject(new Error(err));
					if (typeof res.posts.post === 'undefined') return resolve([]);
					else return resolve(res.posts.post.map(val => val.$));
				});
			} else {
				return resolve(images);
			}
		});
	}

	_common(images) {
		return new Promise(resolve => {
			if (images === []) return resolve([]);
			for (const image of Object.keys(images)) {
				const key = images[image];
				key.common = {
					fileURL: key.file_url.startsWith('/data') || key.file_url.startsWith('/cached')
						? `https://danbooru.donmai.us${key.file_url}`
						: !key.file_url.startsWith('http')
							? `https:${key.file_url}`
							: new URL(key.file_url).href,
					id: key.id.toString(),
					tags: typeof key.tags !== 'undefined'
						? key.tags.split(' ').filter(val => val !== '')
						: key.tag_string.split(' ').filter(val => val !== ''),
					score: parseInt(key.score),
					source: key.source,
					rating: key.rating
				};
			}
			return resolve(images);
		});
	}

	_shuffle(array) {
		for (let i = array.length - 1; i > 0; i--) {
			const j = Math.floor(Math.random() * (i + 1));
			const temp = array[i];
			array[i] = array[j];
			array[j] = temp;
		}
		return array;
	}
}

module.exports = Kaori;
<|endoftext|>


<commit_before>import { VNode } from "./vnode";

import { q } from "./qname";

import { prettyXML } from "./pretty";

import { forEach, foldLeft, range, drop } from "./transducers";

import * as multimap from "./multimap";

// import self!
import * as cx from "./inode";

// helpers ---------------
if(!Object.values){
	const objUtil = (obj,f) => {
		const keys = Object.keys(obj);
		var entries = [];
		for (let i = 0; i < keys.length; i++) {
			const key = keys[i];
			entries.push(f(key));
		}
		return entries;
	};
	Object.values = function(o){
		return objUtil(o, key => o[key]);
	};
	Object.entries = function(o){
		return objUtil(o,key => [key, o[key]]);
	};
}
function _inferType(inode){
	if(inode === null) return 12;
	var cc = inode.constructor;
	if(cc == Array) {
		return 6;
	} else if(cc == Object){
		if(inode.$children) {
			return inode.$name == "#document" ? 9 : 1;
		} else if(inode.$value){
			return 2;
		} else if(inode.$comment){
			return 8;
		} else {
			return 6;
		}
	} else if(cc == Number || cc == Boolean) {
		return 12;
	}
	return 3;
}

function _get(children,idx){
	let len = children.length;
	for(let i = 0; i<len; i++){
		if((children[i].$name || i + 1) == idx) return children[i];
	}
}

function _last(a){
	return drop(a,a.length-1);
}

function _elemToString(e){
	const attrFunc = (z,kv) => {
		return z += " "+kv[0]+"=\""+kv[1]+"\"";
	};
	let str = "<"+e.$name;
	let ns = e.$ns;
	if(ns) str += " xmlns" + (ns.prefix ? ":" + ns.prefix : "") + "=\"" + ns.uri + "\"";
	str = foldLeft(Object.entries(e.$attrs),str,attrFunc);
	if(e.$children.length > 0){
		str += ">";
		for(let c of e.$children){
			str += stringify(c);
		}
		str += "</"+e.$name+">";
	} else {
		str += "/>";
	}
	return str;
}

// -----------------------

export function ivalue(type, name, value){
	if(type == 2) {
		return {$name:name,$value:value};
	} else if(type == 8) {
		return {$comment:value};
	}
	return value;
}

export function vnode(inode, parent, depth, indexInParent) {
	var type = _inferType(inode),
		name,
		value;
	if(type == 1 || type == 9){
		name = inode.$name;
	} else if(type == 2) {
		name = inode.$name;
		value = inode.$value;
	} else if (type == 5) {
		name = parent.keys()[indexInParent];
	} else if (type == 6) {
		name = parent.keys()[indexInParent];
	} else if (type == 8) {
		value = inode.$comment;
	} else if(type == 3 || type == 12){
		value = inode;
		name = parent.keys()[indexInParent];
	}
	// return vnode
	return new VNode(
		cx,
		inode,
		type,
		inode && inode.$ns ? q(inode.$ns.uri, name) : name,
		value,
		parent,
		depth,
		indexInParent
	);
}

export function emptyINode(type, name, attrs, ns) {
	var inode = type == 5 ? [] : {};
	if(type == 1 || type == 9){
		inode.$name = name;
		inode.$attrs = attrs;
		inode.$ns = ns;
		inode.$children = [];
	}
	return inode;
}

export function emptyAttrMap(init){
	return init || {};
}

export function get(inode,idx,type,cache){
	type = type || _inferType(inode);
	if(type == 1 || type == 9){
		if(cache) return cache[idx];
		return _get(inode.$children,idx);
	}
	return inode[idx];
}

export function next(inode, node, type){
	type = type || _inferType(inode);
	var idx = node.indexInParent;
	if(type == 1 || type == 9) {
		return inode.$children[idx+1];
	}
	if(type == 5) return inode[idx+1];
	if(type == 6) {
		var vals = Object.values(inode);
		return vals[idx+1];
	}
}

export function push(inode,val,type){
	type = type || _inferType(inode);
	if(type == 1 || type == 9){
		inode.$children.push(val[1]);
	} else if(type == 5) {
		inode.push(val);
	} else if(type == 6){
		inode[val[0]] = val[1];
	}
	return inode;
}

export function set(inode /*,key,val,type*/){
	// used to restore immutable parents, never modifies mutable
	return inode;
}

export function removeChild(inode,child,type){
	type = type || _inferType(inode);
	if(type == 1 || type == 9){
		inode.$children.splice(child.indexInParent,1);
	} else if(type == 5) {
		inode.splice(child.indexInParent,1);
	} else if(type == 6){
		delete inode[child.name];
	}
	return inode;
}

export function cached(inode,type){
	type = type || _inferType(inode);
	if(type == 1 || type == 9) {
		let children = inode.$children, len = children.length, cache = multimap.default();
		for(let i = 0; i<len; i++){
			cache.push([children[i].$name || i + 1,children[i]]);
		}
		return cache;
	}
	if(type == 5) {
		return {
			keys : function(){
				return range(inode.length).toArray();
			}
		};
	}
	if(type == 6) {
		return {
			keys : function(){
				return Object.keys(inode);
			}
		};
	}
}

export function keys(inode,type){
	type = type || _inferType(inode);
	if(type == 1 || type == 9) {
		let children = inode.$children, len = children.length, keys = [];
		for(let i = 0; i<len; i++){
			keys[i] = children[i].$name || i + 1;
		}
		return keys;
	}
	if(type == 5) return range(inode.length).toArray();
	if(type == 6) return Object.keys(inode);
	return [];
}

export function values(inode,type){
	type = type || _inferType(inode);
	if(type == 1 || type == 9) return inode.$children;
	if (type == 2) return [[inode.$name,inode.$value]];
	if(type == 6) return Object.values(inode);
	if (type == 8) return [inode.$comment];
	return inode;
}

export function finalize(inode){
	return inode;
}

export function setAttribute(inode,key,val){
	if(inode.$attrs) inode.$attrs[key]  = val;
	return inode;
}

export function getAttribute(inode,key){
	if(inode.$attrs) return inode.$attrs[key];
}

export function count(inode, type){
	type = type || _inferType(inode);
	if(type == 1 || type == 9){
		return inode.$children.length;
	} else if(type == 5) {
		return inode.length;
	} else if(type == 6){
		return Object.keys(inode).length;
	}
	return 0;
}

export function first(inode,type){
	type = type || _inferType(inode);
	if(type == 1 || type == 9){
		return inode.$children[0];
	} else if(type == 5) {
		return inode[0];
	} else if(type == 6){
		return Object.values(inode)[0];
	}
}

export function last(inode,type){
	type = type || _inferType(inode);
	if(type == 1 || type == 9) return _last(inode.$children);
	if(type == 5) return _last(inode);
	if(type == 6) {
		return _last(Object.values(inode));
	}
}

export function attrEntries(inode){
	if(inode.$attrs) return Object.entries(inode.$attrs);
	return [];
}

export function modify(inode, node, ref, type){
	type = type || _inferType(inode);
	if(type == 1 || type == 9){
		if (ref !== undefined) {
			inode.$children.splice(ref.indexInParent,0,node.inode);
		} else {
			inode.$children.push(node.inode);
		}
	} else if(type == 5){
		if (ref !== undefined) {
			inode.splice(ref.indexInParent,0,node.inode);
		} else {
			inode.push(node.inode);
		}
	} else if(type == 6){
		inode[node.name] = node.inode;
	}
	return inode;
}

export function stringify(inode, type, root = true, key) {
	var str = "";
	type = type || _inferType(inode);
	if (type == 1 || type == 9) {
		str += _elemToString(inode);
	} else if (type == 5) {
		let val = forEach(inode, c => stringify(c)).join("");
		if(key) {
			str += "<" + key + " json:type=\"array\"" + (val ? ">" + val + "</" + key + ">" : "/>");
		} else {
			str += "<json:array" + (val ? ">" + val + "</json:array>" : "/>");
		}
	} else if (type == 6) {
		let val = forEach(Object.entries(inode), c => stringify(c[1], null, false, c[0])).join("");
		if(key) {
			str += "<" + key + " json:type=\"map\"" + (val ? ">" + val + "</" + key + ">" : "/>");
		} else {
			str += "<json:map" + (val ? ">" + val + "</json:map>" : "/>");
		}
	} else {
		let val = inode === null ? "null" : inode.toString();
		if(key) {
			str += "<" + key + (type == 12 ? " json:type=\"literal\"" : "") + (val ? ">" + val + "</" + key + ">" : "/>");
		} else {
			str += type == 12 ? "<json:literal>" + val + "</json:literal>" : val;
		}
	}
	return root ? prettyXML(str) : str;
}

export const getType = _inferType;
<commit_msg>lazy children iter<commit_after>import { VNode } from "./vnode";

import { q } from "./qname";

import { prettyXML } from "./pretty";

import { forEach, foldLeft, range, drop } from "./transducers";

import * as multimap from "./multimap";

// import self!
import * as cx from "./inode";

// helpers ---------------
if(!Object.values){
	const objUtil = (obj,f) => {
		const keys = Object.keys(obj);
		var entries = [];
		for (let i = 0; i < keys.length; i++) {
			const key = keys[i];
			entries.push(f(key));
		}
		return entries;
	};
	Object.values = function(o){
		return objUtil(o, key => o[key]);
	};
	Object.entries = function(o){
		return objUtil(o,key => [key, o[key]]);
	};
}
function _inferType(inode){
	if(inode === null) return 12;
	var cc = inode.constructor;
	if(cc == Array) {
		return 6;
	} else if(cc == Object){
		if(inode.$children) {
			return inode.$name == "#document" ? 9 : 1;
		} else if(inode.$value){
			return 2;
		} else if(inode.$comment){
			return 8;
		} else {
			return 6;
		}
	} else if(cc == Number || cc == Boolean) {
		return 12;
	}
	return 3;
}

function* _get(children, idx) {
	let len = children.length;
	for (let i = 0; i < len; i++) {
		if ((children[i].$name || i + 1) == idx) {
			yield children[i];
		}
	}
}

function _last(a){
	return drop(a,a.length-1);
}

function _elemToString(e){
	const attrFunc = (z,kv) => {
		return z += " "+kv[0]+"=\""+kv[1]+"\"";
	};
	let str = "<"+e.$name;
	let ns = e.$ns;
	if(ns) str += " xmlns" + (ns.prefix ? ":" + ns.prefix : "") + "=\"" + ns.uri + "\"";
	str = foldLeft(Object.entries(e.$attrs),str,attrFunc);
	if(e.$children.length > 0){
		str += ">";
		for(let c of e.$children){
			str += stringify(c);
		}
		str += "</"+e.$name+">";
	} else {
		str += "/>";
	}
	return str;
}

// -----------------------

export function ivalue(type, name, value){
	if(type == 2) {
		return {$name:name,$value:value};
	} else if(type == 8) {
		return {$comment:value};
	}
	return value;
}

export function vnode(inode, parent, depth, indexInParent) {
	var type = _inferType(inode),
		name,
		value;
	if(type == 1 || type == 9){
		name = inode.$name;
	} else if(type == 2) {
		name = inode.$name;
		value = inode.$value;
	} else if (type == 5) {
		name = parent.keys()[indexInParent];
	} else if (type == 6) {
		name = parent.keys()[indexInParent];
	} else if (type == 8) {
		value = inode.$comment;
	} else if(type == 3 || type == 12){
		value = inode;
		name = parent.keys()[indexInParent];
	}
	// return vnode
	return new VNode(
		cx,
		inode,
		type,
		inode && inode.$ns ? q(inode.$ns.uri, name) : name,
		value,
		parent,
		depth,
		indexInParent
	);
}

export function emptyINode(type, name, attrs, ns) {
	var inode = type == 5 ? [] : {};
	if(type == 1 || type == 9){
		inode.$name = name;
		inode.$attrs = attrs;
		inode.$ns = ns;
		inode.$children = [];
	}
	return inode;
}

export function emptyAttrMap(init){
	return init || {};
}

export function get(inode,idx,type,cache){
	type = type || _inferType(inode);
	if(type == 1 || type == 9){
		if(cache) return cache[idx];
		return _get(inode.$children,idx);
	}
	return inode[idx];
}

export function next(inode, node, type){
	type = type || _inferType(inode);
	var idx = node.indexInParent;
	if(type == 1 || type == 9) {
		return inode.$children[idx+1];
	}
	if(type == 5) return inode[idx+1];
	if(type == 6) {
		var vals = Object.values(inode);
		return vals[idx+1];
	}
}

export function push(inode,val,type){
	type = type || _inferType(inode);
	if(type == 1 || type == 9){
		inode.$children.push(val[1]);
	} else if(type == 5) {
		inode.push(val);
	} else if(type == 6){
		inode[val[0]] = val[1];
	}
	return inode;
}

export function set(inode /*,key,val,type*/){
	// used to restore immutable parents, never modifies mutable
	return inode;
}

export function removeChild(inode,child,type){
	type = type || _inferType(inode);
	if(type == 1 || type == 9){
		inode.$children.splice(child.indexInParent,1);
	} else if(type == 5) {
		inode.splice(child.indexInParent,1);
	} else if(type == 6){
		delete inode[child.name];
	}
	return inode;
}

export function cached(inode,type){
	type = type || _inferType(inode);
	if(type == 1 || type == 9) {
		let children = inode.$children, len = children.length, cache = multimap.default();
		for(let i = 0; i<len; i++){
			cache.push([children[i].$name || i + 1,children[i]]);
		}
		return cache;
	}
	if(type == 5) {
		return {
			keys : function(){
				return range(inode.length).toArray();
			}
		};
	}
	if(type == 6) {
		return {
			keys : function(){
				return Object.keys(inode);
			}
		};
	}
}

export function keys(inode,type){
	type = type || _inferType(inode);
	if(type == 1 || type == 9) {
		let children = inode.$children, len = children.length, keys = [];
		for(let i = 0; i<len; i++){
			keys[i] = children[i].$name || i + 1;
		}
		return keys;
	}
	if(type == 5) return range(inode.length).toArray();
	if(type == 6) return Object.keys(inode);
	return [];
}

export function values(inode,type){
	type = type || _inferType(inode);
	if(type == 1 || type == 9) return inode.$children;
	if (type == 2) return [[inode.$name,inode.$value]];
	if(type == 6) return Object.values(inode);
	if (type == 8) return [inode.$comment];
	return inode;
}

export function finalize(inode){
	return inode;
}

export function setAttribute(inode,key,val){
	if(inode.$attrs) inode.$attrs[key]  = val;
	return inode;
}

export function getAttribute(inode,key){
	if(inode.$attrs) return inode.$attrs[key];
}

export function count(inode, type){
	type = type || _inferType(inode);
	if(type == 1 || type == 9){
		return inode.$children.length;
	} else if(type == 5) {
		return inode.length;
	} else if(type == 6){
		return Object.keys(inode).length;
	}
	return 0;
}

export function first(inode,type){
	type = type || _inferType(inode);
	if(type == 1 || type == 9){
		return inode.$children[0];
	} else if(type == 5) {
		return inode[0];
	} else if(type == 6){
		return Object.values(inode)[0];
	}
}

export function last(inode,type){
	type = type || _inferType(inode);
	if(type == 1 || type == 9) return _last(inode.$children);
	if(type == 5) return _last(inode);
	if(type == 6) {
		return _last(Object.values(inode));
	}
}

export function attrEntries(inode){
	if(inode.$attrs) return Object.entries(inode.$attrs);
	return [];
}

export function modify(inode, node, ref, type){
	type = type || _inferType(inode);
	if(type == 1 || type == 9){
		if (ref !== undefined) {
			inode.$children.splice(ref.indexInParent,0,node.inode);
		} else {
			inode.$children.push(node.inode);
		}
	} else if(type == 5){
		if (ref !== undefined) {
			inode.splice(ref.indexInParent,0,node.inode);
		} else {
			inode.push(node.inode);
		}
	} else if(type == 6){
		inode[node.name] = node.inode;
	}
	return inode;
}

export function stringify(inode, type, root = true, key) {
	var str = "";
	type = type || _inferType(inode);
	if (type == 1 || type == 9) {
		str += _elemToString(inode);
	} else if (type == 5) {
		let val = forEach(inode, c => stringify(c)).join("");
		if(key) {
			str += "<" + key + " json:type=\"array\"" + (val ? ">" + val + "</" + key + ">" : "/>");
		} else {
			str += "<json:array" + (val ? ">" + val + "</json:array>" : "/>");
		}
	} else if (type == 6) {
		let val = forEach(Object.entries(inode), c => stringify(c[1], null, false, c[0])).join("");
		if(key) {
			str += "<" + key + " json:type=\"map\"" + (val ? ">" + val + "</" + key + ">" : "/>");
		} else {
			str += "<json:map" + (val ? ">" + val + "</json:map>" : "/>");
		}
	} else {
		let val = inode === null ? "null" : inode.toString();
		if(key) {
			str += "<" + key + (type == 12 ? " json:type=\"literal\"" : "") + (val ? ">" + val + "</" + key + ">" : "/>");
		} else {
			str += type == 12 ? "<json:literal>" + val + "</json:literal>" : val;
		}
	}
	return root ? prettyXML(str) : str;
}

export const getType = _inferType;
<|endoftext|>


<commit_before>udefine(['root', 'eventmap', 'gameboard/key'], function(root, EventMap, Key) {

  var Input = {};

  Input.define = Key.define;
  Input.key = new EventMap();

  root.addEventListener('keydown', function(evt) {
    Input.key.trigger('down', evt.keyCode);
  }, true);
  root.addEventListener('keyup', function(evt) {
    Input.key.trigger('up', evt.keyCode);
  }, true);

  return Input;

}); <commit_msg>The context of the an event is a key<commit_after>udefine(['root', 'eventmap', 'gameboard/key'], function(root, EventMap, Key) {

  var Input = {};

  Input.define = Key.define;
  Input.key = new EventMap();

  root.addEventListener('keydown', function(evt) {
    Input.key.trigger({
      name: 'down',
      context: Key
    }, evt.keyCode);
  }, true);

  root.addEventListener('keyup', function(evt) {
    Input.key.trigger({
      name: 'up',
      context: Key
    }, evt.keyCode);
  }, true);

  return Input;
});
<|endoftext|>


<commit_before>(function(root) {
    'use strict';

    /**
    * Helper for handling user mouse input.
    * @class Mouse
    * @constructor
    * @param {Function} onClick - A function to handle mouse click events. function(x, y){}
    * @param {Function} onHover - A function to handle mouse hover events. function(x, y){}
    */
    var Mouse = function Mouse(onClick, onHover) {
        this.onClick = onClick;
        this.onHover = onHover;
    };

    Mouse.prototype = {
        constructor: Mouse,

        /**
        * A function to handle tile mouse click events.
        * @method onClick
        * @param {Number} x - Mouse x coord relative to window.
        * @param {Number} y - Mouse y coord relative to window.
        */
        onClick: null,

        /**
        * A function to handle tile mouse hover events
        * @method onHover
        * @param {Number} x - Mouse x coord relative to window.
        * @param {Number} y - Mouse y coord relative to window.
        */
        onHover: null,

        /**
        * The dom element being rendered to and listened to for mouse events.
        * @property _boundElement
        * @protected
        * @type HTMLElement
        */
        _boundElement: null,

        /**
        * Hander for mouse events
        * @method handleEvent
        * @param {Event} e - mouse event
        */
        handleEvent: function(e){
            if(e.type === 'mousemove' && this.onHover){
                this.onHover(e.clientX, e.clientY);
            }
            else if(e.type === 'mouseenter' && this.onHover){
                this.onHover(e.clientX, e.clientY);
            }
            else if(e.type === 'mouseleave' && this.onHover){
                this.onHover(false);
            }
            else if(e.type === 'click' && this.onClick){
                this.onClick(e.clientX, e.clientY);
            }
        },

        /**
        * Hander for mouse move events
        * @method mouseMove
        * @param {Event} e - mouse event
        */
        mouseMove: function(e) {
            if(this.onHover){
                var coords = this.game.renderer.mouseToTileCoords(e.clientX, e.clientY);
                this.onHover(coords);
            }
        },

        /**
        * Binds event listener for mouse events.
        * @method startListening
        * @param {HTMLElement} element - The dom element being rendered to.
        */
        startListening: function(element){
            if(this._boundElement){
                this.stopListening();
            }

            element.addEventListener('mousemove', this);
            element.addEventListener('mouseenter', this);
            element.addEventListener('mouseleave', this);
            element.addEventListener('click', this);

            this._boundElement = element;
        },

        /**
        * Unbinds event listener for mouse events.
        * @method stopListening
        */
        stopListening: function(){
            if(!this._boundElement){
                return false;
            }
            var el = this._boundElement;
            el.removeEventListener('mousemove', this);
            el.removeEventListener('mouseenter', this);
            el.removeEventListener('mouseleave', this);
            el.removeEventListener('click', this);
        }
    };

    root.RL.Mouse = Mouse;

}(this));
<commit_msg>comment fix<commit_after>(function(root) {
    'use strict';

    /**
    * Helper for handling user mouse input.
    * @class Mouse
    * @constructor
    * @param {Function} onClick - A function to handle mouse click events. function(x, y){}
    * @param {Function} onHover - A function to handle mouse hover events. function(x, y){}
    */
    var Mouse = function Mouse(onClick, onHover) {
        this.onClick = onClick;
        this.onHover = onHover;
    };

    Mouse.prototype = {
        constructor: Mouse,

        /**
        * A function to handle tile mouse click events.
        * @method onClick
        * @param {Number} x - Mouse x coord relative to window.
        * @param {Number} y - Mouse y coord relative to window.
        */
        onClick: null,

        /**
        * A function to handle tile mouse hover events
        * @method onHover
        * @param {Number} x - Mouse x coord relative to window.
        * @param {Number} y - Mouse y coord relative to window.
        */
        onHover: null,

        /**
        * The dom element being rendered to and listened to for mouse events.
        * @property _boundElement
        * @protected
        * @type {HTMLElement}
        */
        _boundElement: null,

        /**
        * Hander for mouse events
        * @method handleEvent
        * @param {Event} e - mouse event
        */
        handleEvent: function(e){
            if(e.type === 'mousemove' && this.onHover){
                this.onHover(e.clientX, e.clientY);
            }
            else if(e.type === 'mouseenter' && this.onHover){
                this.onHover(e.clientX, e.clientY);
            }
            else if(e.type === 'mouseleave' && this.onHover){
                this.onHover(false);
            }
            else if(e.type === 'click' && this.onClick){
                this.onClick(e.clientX, e.clientY);
            }
        },

        /**
        * Hander for mouse move events
        * @method mouseMove
        * @param {Event} e - mouse event
        */
        mouseMove: function(e) {
            if(this.onHover){
                var coords = this.game.renderer.mouseToTileCoords(e.clientX, e.clientY);
                this.onHover(coords);
            }
        },

        /**
        * Binds event listener for mouse events.
        * @method startListening
        * @param {HTMLElement} element - The dom element being rendered to.
        */
        startListening: function(element){
            if(this._boundElement){
                this.stopListening();
            }

            element.addEventListener('mousemove', this);
            element.addEventListener('mouseenter', this);
            element.addEventListener('mouseleave', this);
            element.addEventListener('click', this);

            this._boundElement = element;
        },

        /**
        * Unbinds event listener for mouse events.
        * @method stopListening
        */
        stopListening: function(){
            if(!this._boundElement){
                return false;
            }
            var el = this._boundElement;
            el.removeEventListener('mousemove', this);
            el.removeEventListener('mouseenter', this);
            el.removeEventListener('mouseleave', this);
            el.removeEventListener('click', this);
        }
    };

    root.RL.Mouse = Mouse;

}(this));
<|endoftext|>


<commit_before>var si;

$(function() {
    $(".pa-1").click(function() {
        $(".pa-1").addClass('pa-button-active');
        si = 1;
        for (var i=1; i<19; i++) {
            if (i === 1) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-2").click(function() {
        $(".pa-2").addClass('pa-button-active');
        si = 2;
        for (var i=1; i<19; i++) {
            if (i === 2) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-3").click(function() {
        $(".pa-3").addClass('pa-button-active');
        si = 3;
        for (var i=1; i<19; i++) {
            if (i === 3) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-4").click(function() {
        $(".pa-4").addClass('pa-button-active');
        si = 4;
        for (var i=1; i<19; i++) {
            if (i === 4) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-5").click(function() {
        $(".pa-5").addClass('pa-button-active');
        si = 5;
        for (var i=1; i<19; i++) {
            if (i === 5) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-6").click(function() {
        $(".pa-6").addClass('pa-button-active');
        si = 6;
        for (var i=1; i<19; i++) {
            if (i === 6) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-7").click(function() {
        $(".pa-7").addClass('pa-button-active');
        si = 7;
        for (var i=1; i<19; i++) {
            if (i === 7) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-8").click(function() {
        $(".pa-8").addClass('pa-button-active');
        si = 8;
        for (var i=1; i<19; i++) {
            if (i === 8) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-9").click(function() {
        $(".pa-9").addClass('pa-button-active');
        si = 9;
        for (var i=1; i<19; i++) {
            if (i === 9) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-10").click(function() {
        $(".pa-10").addClass('pa-button-active');
        si = 10;
        for (var i=1; i<19; i++) {
            if (i === 10) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-11").click(function() {
        $(".pa-11").addClass('pa-button-active');
        si = 11;
        for (var i=1; i<19; i++) {
            if (i === 11) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-12").click(function() {
        $(".pa-12").addClass('pa-button-active');
        si = 12;
        for (var i=1; i<19; i++) {
            if (i === 12) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-13").click(function() {
        $(".pa-13").addClass('pa-button-active');
        si = 13;
        for (var i=1; i<19; i++) {
            if (i === 13) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-14").click(function() {
        $(".pa-14").addClass('pa-button-active');
        si = 14;
        for (var i=1; i<19; i++) {
            if (i === 14) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-15").click(function() {
        $(".pa-15").addClass('pa-button-active');
        si = 15;
        for (var i=1; i<19; i++) {
            if (i === 15) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-16").click(function() {
        $(".pa-16").addClass('pa-button-active');
        si = 16;
        for (var i=1; i<19; i++) {
            if (i === 16) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-17").click(function() {
        $(".pa-17").addClass('pa-button-active');
        si = 17;
        for (var i=1; i<19; i++) {
            if (i === 17) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-18").click(function() {
        $(".pa-18").addClass('pa-button-active');
        si = 18;
        for (var i=1; i<19; i++) {
            if (i === 18) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function () {
    if(si===1) {
        $(".pa-button").hide();
    }
});<commit_msg>testing pa.js with switch function<commit_after>var si;

$(function() {
    $(".pa-1").click(function() {
        $(".pa-1").addClass('pa-button-active');
        si = 1;
        for (var i=1; i<19; i++) {
            if (i === 1) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-2").click(function() {
        $(".pa-2").addClass('pa-button-active');
        si = 2;
        for (var i=1; i<19; i++) {
            if (i === 2) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-3").click(function() {
        $(".pa-3").addClass('pa-button-active');
        si = 3;
        for (var i=1; i<19; i++) {
            if (i === 3) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-4").click(function() {
        $(".pa-4").addClass('pa-button-active');
        si = 4;
        for (var i=1; i<19; i++) {
            if (i === 4) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-5").click(function() {
        $(".pa-5").addClass('pa-button-active');
        si = 5;
        for (var i=1; i<19; i++) {
            if (i === 5) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-6").click(function() {
        $(".pa-6").addClass('pa-button-active');
        si = 6;
        for (var i=1; i<19; i++) {
            if (i === 6) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-7").click(function() {
        $(".pa-7").addClass('pa-button-active');
        si = 7;
        for (var i=1; i<19; i++) {
            if (i === 7) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-8").click(function() {
        $(".pa-8").addClass('pa-button-active');
        si = 8;
        for (var i=1; i<19; i++) {
            if (i === 8) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-9").click(function() {
        $(".pa-9").addClass('pa-button-active');
        si = 9;
        for (var i=1; i<19; i++) {
            if (i === 9) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-10").click(function() {
        $(".pa-10").addClass('pa-button-active');
        si = 10;
        for (var i=1; i<19; i++) {
            if (i === 10) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-11").click(function() {
        $(".pa-11").addClass('pa-button-active');
        si = 11;
        for (var i=1; i<19; i++) {
            if (i === 11) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-12").click(function() {
        $(".pa-12").addClass('pa-button-active');
        si = 12;
        for (var i=1; i<19; i++) {
            if (i === 12) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-13").click(function() {
        $(".pa-13").addClass('pa-button-active');
        si = 13;
        for (var i=1; i<19; i++) {
            if (i === 13) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-14").click(function() {
        $(".pa-14").addClass('pa-button-active');
        si = 14;
        for (var i=1; i<19; i++) {
            if (i === 14) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-15").click(function() {
        $(".pa-15").addClass('pa-button-active');
        si = 15;
        for (var i=1; i<19; i++) {
            if (i === 15) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-16").click(function() {
        $(".pa-16").addClass('pa-button-active');
        si = 16;
        for (var i=1; i<19; i++) {
            if (i === 16) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-17").click(function() {
        $(".pa-17").addClass('pa-button-active');
        si = 17;
        for (var i=1; i<19; i++) {
            if (i === 17) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function() {
    $(".pa-18").click(function() {
        $(".pa-18").addClass('pa-button-active');
        si = 18;
        for (var i=1; i<19; i++) {
            if (i === 18) { continue; }
            $(".pa-" + i ).removeClass('pa-button-active');
        }
    });
});

$(function () {
    if(si===1) {
        $(".pa-button").hide();
    };
});<|endoftext|>


<commit_before>(function (document) {

  /* Configuracao dos simbolos */
  document.getElementById('form_alfabeto').addEventListener('submit', function (e) {
    e.returnValue = false;
    var tabela = document.getElementById('alfabeto'),
      simbolo = document.getElementById('simbolo');
    if (simbolo && simbolo.value.length > 0) {
      simbolos.push(simbolo.value);
      alfabeto.tBodies[0].innerHTML += '
' + simbolo.value + '	Remover
';
      simbolo.value = '';
      simbolo.focus();
    }
  });

  document.getElementById('configurar_estados').addEventListener('click', function () {
    document.getElementById('configuracao_alfabeto').classList.add('hidden');

    var cabecalho = '';
    for (var i = 0; i < simbolos.length; i++) {
      cabecalho += '' + simbolos[i] + '	';
    }

    document.getElementById('automato').tHead.rows[0].innerHTML += cabecalho;

    document.getElementById('configuracao_estados').classList.remove('hidden');
  });

  document.getElementById('alfabeto').addEventListener('click', function (e) {
    var target = e.target;
    if (target.classList.contains('alfabeto-remover')) {
      var valor = target.dataset.val;
      if (valor) {
        for (var i = 0; i < simbolos.length; i++) {
          if (valor === simbolos[i]) {
            simbolos.splice(i, 1);
            break;
          }
        }
        if (target.parentNode && target.parentNode.parentNode) {
          target.parentNode.parentNode.remove();
        }
      }
    }
  });

  var gerarOptionEstado = function (indice) {
    var option = document.createElement('option');
    option.text = '{q' + indice + '}';
    option.value = 'q' + indice;

    return option;
  };

  var popularNovosEstados = function () {
    var selects = document.querySelectorAll('#automato select');
    if (selects && selects.length > 0) {
      var i = 0,
        qtd = selects.length;

      for (; i < qtd; i++) {
        for (var x = 0; x < estados.length; x++) {
          if (document.querySelector('#' + selects[i].id + ' option[value=q' + estados[x].id + ']') === null) {
            selects[i].add(gerarOptionEstado(estados[x].id));
          }
        }
      }
    }
  };

  var novoEstado = function (callback) {
    var qtdEstados = estados.length;
    var linha = '
{q' + qtdEstados + '}	';
    for (var i = 0; i < simbolos.length; i++) {
      linha += '<select id="q' + qtdEstados + '_' + simbolos[i] + '"><option value="">NULL</option><option value="0">Novo estado</option></select>	';
    }
    linha += '
';

    var el = document.createElement('tr');

    el.innerHTML = linha;

    document.getElementById('automato').appendChild(el);

    estados.push({
      id: qtdEstados
    });

    popularNovosEstados();

    if (callback && typeof callback === 'function') {
      callback(qtdEstados);
    }
  };

  /* Configuracao dos estados */
  document.getElementById('novo_estado').addEventListener('click', function () {
    novoEstado();
  });

  document.getElementById('automato').addEventListener('change', function (e) {
    var target = e.target;
    if (target && target.tagName === 'SELECT') {
      if (target.value === '0') {
        // Criar novo estado
        novoEstado(function (estado) {
          document.getElementById(target.id).value = 'q' + estado;

            // Cria vinculo de estado
            var id = target.id.replace('q', ''),
              estadoSimbolo = id.split('_');

            if (estadoSimbolo.length === 2) {
              if (estados[estadoSimbolo[0]]) {
                // Os ids são separados por estado_simbolo, por isso:
                // estadoSimbolo[0] = estado
                // estadoSimbolo[1] = simbolo

                //Vincula no estado com id estadoSimbolo[0], no simbolo estadoSimbolo[1], o estado selecionado
                estados[estadoSimbolo[0]][estadoSimbolo[1]] = 'q' + estado;
              }
            }

        });
      }
      else if (target.value !== '') {
        // Cria vinculo de estado
        var id = target.id.replace('q', ''),
          estadoSimbolo = id.split('_');

        if (estadoSimbolo.length === 2) {
          if (estados[estadoSimbolo[0]]) {
            // Os ids são separados por estado_simbolo, por isso:
            // estadoSimbolo[0] = estado
            // estadoSimbolo[1] = simbolo

            //Vincula no estado com id estadoSimbolo[0], no simbolo estadoSimbolo[1], o estado selecionado
            estados[estadoSimbolo[0]][estadoSimbolo[1]] = target.value;
          }
        }
      }
    }
  });

  document.getElementById('salvar_estados').addEventListener('click', function () {
    var linhas = document.getElementById('automato').tBodies[0].rows;
  });

  // Execucoes iniciais
  document.getElementById('simbolo').focus();

}(document));
<commit_msg>Realizando a exclusao de transicoes<commit_after>(function (document) {

  /* Configuracao dos simbolos */
  document.getElementById('form_alfabeto').addEventListener('submit', function (e) {
    e.returnValue = false;
    var tabela = document.getElementById('alfabeto'),
      simbolo = document.getElementById('simbolo');
    if (simbolo && simbolo.value.length > 0) {
      simbolos.push(simbolo.value);
      alfabeto.tBodies[0].innerHTML += '
' + simbolo.value + '	Remover
';
      simbolo.value = '';
      simbolo.focus();
    }
  });

  document.getElementById('configurar_estados').addEventListener('click', function () {
    document.getElementById('configuracao_alfabeto').classList.add('hidden');

    var cabecalho = '';
    for (var i = 0; i < simbolos.length; i++) {
      cabecalho += '' + simbolos[i] + '	';
    }

    document.getElementById('automato').tHead.rows[0].innerHTML += cabecalho;

    document.getElementById('configuracao_estados').classList.remove('hidden');
  });

  document.getElementById('alfabeto').addEventListener('click', function (e) {
    var target = e.target;
    if (target.classList.contains('alfabeto-remover')) {
      var valor = target.dataset.val;
      if (valor) {
        for (var i = 0; i < simbolos.length; i++) {
          if (valor === simbolos[i]) {
            simbolos.splice(i, 1);
            break;
          }
        }
        if (target.parentNode && target.parentNode.parentNode) {
          target.parentNode.parentNode.remove();
        }
      }
    }
  });

  var gerarOptionEstado = function (indice) {
    var option = document.createElement('option');
    option.text = '{q' + indice + '}';
    option.value = 'q' + indice;

    return option;
  };

  var popularNovosEstados = function () {
    var selects = document.querySelectorAll('#automato select');
    if (selects && selects.length > 0) {
      var i = 0,
        qtd = selects.length;

      for (; i < qtd; i++) {
        for (var x = 0; x < estados.length; x++) {
          if (document.querySelector('#' + selects[i].id + ' option[value=q' + estados[x].id + ']') === null) {
            selects[i].add(gerarOptionEstado(estados[x].id));
          }
        }
      }
    }
  };

  var novoEstado = function (callback) {
    var qtdEstados = estados.length;
    var linha = '
{q' + qtdEstados + '}	';
    for (var i = 0; i < simbolos.length; i++) {
      linha += '<select id="q' + qtdEstados + '_' + simbolos[i] + '"><option value="">NULL</option><option value="0">Novo estado</option></select>	';
    }
    linha += '
';

    var el = document.createElement('tr');

    el.innerHTML = linha;

    document.getElementById('automato').appendChild(el);

    estados.push({
      id: qtdEstados
    });

    popularNovosEstados();

    if (callback && typeof callback === 'function') {
      callback(qtdEstados);
    }
  };

  /* Configuracao dos estados */
  document.getElementById('novo_estado').addEventListener('click', function () {
    novoEstado();
  });

  var incluirTransicoesEstados = function (target, estado) {
    // Cria vinculo de estado
    var id = target.id.replace('q', ''),
      estadoSimbolo = id.split('_');

    if (estadoSimbolo.length === 2) {
      if (estados[estadoSimbolo[0]]) {
        // Os ids são separados por estado_simbolo, por isso:
        // estadoSimbolo[0] = estado
        // estadoSimbolo[1] = simbolo

        //Vincula no estado com id estadoSimbolo[0], no simbolo estadoSimbolo[1], o estado selecionado
        estados[estadoSimbolo[0]][estadoSimbolo[1]] = estado;
      }
    }
  };

  document.getElementById('automato').addEventListener('change', function (e) {
    var target = e.target;
    if (target && target.tagName === 'SELECT') {
      if (target.value === '0') {
        // Criar novo estado
        novoEstado(function (estado) {
          document.getElementById(target.id).value = 'q' + estado;
          incluirTransicoesEstados(target, 'q' + estado);
        });
      }
      else if (target.value !== '') {
        // Cria transicao em estados
        incluirTransicoesEstados(target, target.value);
      }
      else {
        // Remove completamente transicao
        var id = target.id.replace('q', ''),
          estadoSimbolo = id.split('_');

        delete estados[estadoSimbolo[0]][estadoSimbolo[1]];
      }
    }
  });

  document.getElementById('salvar_estados').addEventListener('click', function () {
    var linhas = document.getElementById('automato').tBodies[0].rows;
  });

  // Execucoes iniciais
  document.getElementById('simbolo').focus();

}(document));
<|endoftext|>


<commit_before>// Export some functions:

esEngine.version = version;

esEngine.ArrayOfBitArray = ArrayOfBitArray;
esEngine.BufferedIndexRecycler = BufferedIndexRecycler;

esEngine._cDefs = esEngine_cDefs;
esEngine.ComponentDef = ComponentDef;

esEngine._sDefs = esEngine_sDefs;
esEngine.SystemDef = SystemDef;

// Following part is taken from: https://github.com/jquery/jquery/blob/master/src/exports.js

if ( typeof module === "object" && typeof module.exports === "object" ) {
	// Expose esEngine as module.exports in loaders that implement the Node
	// module pattern (including browserify). Do not create the global, since
	// the user will be storing it themselves locally, and globals are frowned
	// upon in the Node module world.
	module.exports = esEngine;
} else {
	// Register as a named AMD module, since esEngine can be concatenated with other
	// files that may use define, but not via a proper concatenation script that
	// understands anonymous AMD modules. A named AMD is safest and most robust
	// way to register. Lowercase esengine is used because AMD module names are
	// derived from file names, and esEngine is normally delivered in a lowercase
	// file name. Do this after creating the global so that if an AMD module wants
	// to call noConflict to hide this version of esEngine, it will work.
	if ( typeof define === "function" && define.amd ) {
		define( "esengine", [], function () { return esEngine; } );
	}
}
// If there is a window object, that at least has a document property,
// define esEngine identifier.
if ( typeof window === "object" && typeof window.document === "object" ) {
	window.esEngine = esEngine;
}

})( this, Object, String, Array );
<commit_msg>Don't export the lists of cDefs and sDefs They are not in the API<commit_after>// Export some functions:

esEngine.version = version;

esEngine.ArrayOfBitArray = ArrayOfBitArray;
esEngine.BufferedIndexRecycler = BufferedIndexRecycler;

//esEngine._cDefs = esEngine_cDefs;
esEngine.ComponentDef = ComponentDef;

//esEngine._sDefs = esEngine_sDefs;
esEngine.SystemDef = SystemDef;

// Following part is taken from: https://github.com/jquery/jquery/blob/master/src/exports.js

if ( typeof module === "object" && typeof module.exports === "object" ) {
	// Expose esEngine as module.exports in loaders that implement the Node
	// module pattern (including browserify). Do not create the global, since
	// the user will be storing it themselves locally, and globals are frowned
	// upon in the Node module world.
	module.exports = esEngine;
} else {
	// Register as a named AMD module, since esEngine can be concatenated with other
	// files that may use define, but not via a proper concatenation script that
	// understands anonymous AMD modules. A named AMD is safest and most robust
	// way to register. Lowercase esengine is used because AMD module names are
	// derived from file names, and esEngine is normally delivered in a lowercase
	// file name. Do this after creating the global so that if an AMD module wants
	// to call noConflict to hide this version of esEngine, it will work.
	if ( typeof define === "function" && define.amd ) {
		define( "esengine", [], function () { return esEngine; } );
	}
}
// If there is a window object, that at least has a document property,
// define esEngine identifier.
if ( typeof window === "object" && typeof window.document === "object" ) {
	window.esEngine = esEngine;
}

})( this, Object, String, Array );
<|endoftext|>


<commit_before>"use strict";

var _ = require("./utils");

_.NeuUGen = require("./ugen");
_.NeuDC   = require("./dc");

function NeuParam(synth, name, value) {
  this.name = name;

  this.$synth   = synth;
  this.$context = synth.$context;
  this.$outlet  = null;

  this._params = [];
  this._value  = _.finite(value);
}
_.inherits(NeuParam, _.NeuUGen);

NeuParam.prototype._connect = function(to) {
  var param;

  if (_.isAudioParam(to)) {
    param = to;
  } else {
    this.$outlet = this.$context.createGain();
    _.connect({ from: new _.NeuDC(this.$context, 1), to: this.$outlet });
    param = this.$outlet.gain;
  }

  this._params.push(param);
  param.setValueAtTime(this._value, 0);
};

NeuParam.prototype.valueOf = function() {
  return this._params.length ? this._params[0].value : /* istanbul ignore next */ 0;
};

NeuParam.prototype.set = function(value) {
  value = _.finite(value);

  var startTime = this.$context.currentTime;

  this._params.forEach(function(param) {
    param.setValueAtTime(value, startTime);
  });

  return this;
};

NeuParam.prototype.setAt = function(value, startTime) {
  value     = _.finite(value);
  startTime = _.finite(startTime);

  this._params.forEach(function(param) {
    param.setValueAtTime(value, startTime);
  });

  return this;
};

NeuParam.prototype.linTo = function(value, endTime) {
  value   = _.finite(value);
  endTime = _.finite(endTime);

  this._params.forEach(function(param) {
    param.linearRampToValueAtTime(value, endTime);
  });

  return this;
};

NeuParam.prototype.expTo = function(value, endTime) {
  value   = _.finite(value);
  endTime = _.finite(endTime);

  this._params.forEach(function(param) {
    param.exponentialRampToValueAtTime(value, endTime);
  });

  return this;
};

NeuParam.prototype.targetAt = function(target, startTime, timeConstant) {
  target       = _.finite(target);
  startTime    = _.finite(startTime);
  timeConstant = _.finite(timeConstant);

  this._params.forEach(function(param) {
    param.setTargetAtTime(target, startTime, timeConstant);
  });

  return this;
};

NeuParam.prototype.curveAt = function(values, startTime, duration) {
  startTime = _.finite(startTime);
  duration  = _.finite(duration);

  this._params.forEach(function(param) {
    param.setValueCurveAtTime(values, startTime, duration);
  });

  return this;
};

NeuParam.prototype.cancel = function(startTime) {
  startTime = _.finite(startTime);

  this._params.forEach(function(param) {
    param.cancelScheduledValues(startTime);
  });

  return this;
};

module.exports = NeuParam;
<commit_msg>fix NeuParam connect<commit_after>"use strict";

var _ = require("./utils");

_.NeuUGen = require("./ugen");
_.NeuDC   = require("./dc");

function NeuParam(synth, name, value) {
  this.name = name;

  this.$synth   = synth;
  this.$context = synth.$context;
  this.$outlet  = null;

  this._params = [];
  this._connected = [];
  this._value = _.finite(value);
}
_.inherits(NeuParam, _.NeuUGen);

NeuParam.prototype._connect = function(to) {
  // FIXME: test!!!
  if (this._connected.indexOf(to) === -1) {
    this._connected.push(to);
    if (_.isAudioParam(to)) {
      this._params.push(to);
      to.setValueAtTime(this._value, 0);
    } else {
      if (this.$outlet == null) {
        this.$outlet = this.$context.createGain();
        _.connect({ from: new _.NeuDC(this.$context, 1), to: this.$outlet });
        this._params.push(this.$outlet.gain);
        this.$outlet.gain.setValueAtTime(this._value, 0);
      }
      _.connect({ from: this.$outlet, to: to });
    }
  }
};

NeuParam.prototype.valueOf = function() {
  return this._params.length ? this._params[0].value : /* istanbul ignore next */ 0;
};

NeuParam.prototype.set = function(value) {
  value = _.finite(value);

  var startTime = this.$context.currentTime;

  this._params.forEach(function(param) {
    param.setValueAtTime(value, startTime);
  });

  return this;
};

NeuParam.prototype.setAt = function(value, startTime) {
  value     = _.finite(value);
  startTime = _.finite(startTime);

  this._params.forEach(function(param) {
    param.setValueAtTime(value, startTime);
  });

  return this;
};

NeuParam.prototype.linTo = function(value, endTime) {
  value   = _.finite(value);
  endTime = _.finite(endTime);

  this._params.forEach(function(param) {
    param.linearRampToValueAtTime(value, endTime);
  });

  return this;
};

NeuParam.prototype.expTo = function(value, endTime) {
  value   = _.finite(value);
  endTime = _.finite(endTime);

  this._params.forEach(function(param) {
    param.exponentialRampToValueAtTime(value, endTime);
  });

  return this;
};

NeuParam.prototype.targetAt = function(target, startTime, timeConstant) {
  target       = _.finite(target);
  startTime    = _.finite(startTime);
  timeConstant = _.finite(timeConstant);

  this._params.forEach(function(param) {
    param.setTargetAtTime(target, startTime, timeConstant);
  });

  return this;
};

NeuParam.prototype.curveAt = function(values, startTime, duration) {
  startTime = _.finite(startTime);
  duration  = _.finite(duration);

  this._params.forEach(function(param) {
    param.setValueCurveAtTime(values, startTime, duration);
  });

  return this;
};

NeuParam.prototype.cancel = function(startTime) {
  startTime = _.finite(startTime);

  this._params.forEach(function(param) {
    param.cancelScheduledValues(startTime);
  });

  return this;
};

module.exports = NeuParam;
<|endoftext|>