<commit_before>/**
 * Module Name: Github
 * Description: Retrieves interesting Github information
 */
var request = require('request'),
    _ = require('underscore')._;

var github = function(dbot) {
    var commands = {
        '~repocount': function(event) {
        // TODO: add handling for non existent user
            var reqUrl = "https://api.github.com/users/" + event.params[1] + "/repos";
            request(reqUrl, function(error, response, body) {
            var result = JSON.parse(body);
			event.reply(event.params[1] + " has " + result.length + " public repositories.");
            });
        },
        '~repo': function(event) {
            var repo = "";
            if (typeof event.params[1] == 'undefined') {
                repo = dbot.config.github.defaultrepo;
            } else {
                repo = event.params[1];
            }

            var reqUrl = "https://api.github.com/";
            reqUrl += "repos/" + repo;

            request(reqUrl, function(error, response, body) {
                var data = JSON.parse(body);
                if (data["fork"] == true) {
                   event.reply(dbot.t("forkedrepo",data);
                } else {
                    event.reply(dbot.t("unforkedrepo",data);
                }
                // TODO: move this shizz into an api call
                var longurl = "http://github.com/" + repo;
                request({method: 'POST', uri: 'http://git.io', form:{url: longurl}}, function(error, response, body){
                    event.reply(dbot.t('location')+" "+response.headers["location"]);
                });
            });
        },
        '~gstatus': function(event) {
            var reqUrl = "https://status.github.com/api/last-message.json";
            request(reqUrl, function(error,response,body){
                var data = JSON.parse(body);
                event.reply(dbot.t("status"+data["status"]));
                event.reply(data["body"]);
            });
        },
        '~milestone': function(event) {
            var repo = dbot.config.github.defaultrepo;
            var reqUrl = "https://api.github.com/repos/";
            reqUrl += repo + "/milestones";

            request(reqUrl, function(error, response, body) {
                var data = JSON.parse(body);
                for (var section in data) {
                    var milestone = data[section];
                    if (milestone["title"] == event.params[1]){
                        var str = "Milestone " + milestone["title"];
                        var progress = milestone["closed_issues"] / (milestone["open_issues"] + milestone["closed_issues"]);
                        progress = Math.round(progress*100);
                        var bar = "[";
                        for (var i = 1; i < 10; i++) {
                            if  ((progress / (i*10)) > 1) {
                                bar += "█";
                            } else {
                                bar += " ";
                            }
                        }
                        bar += "]";
                        str += " is " + bar + progress + "% complete";

                        var longurl = "http://github.com/" + repo + "/issues?milestone=" + milestone["number"];
                        request({method: 'POST', uri: 'http://git.io', form:{url: longurl}}, function(error, response, body){
                            event.reply(response.headers["location"]);
                        });
                        event.reply(str);
                        break;
                    }
                }
           });
        },
/*        '~repo': function(event) {
            var repo = "";
            if (typeof event.params[1] == 'undefined') {
                repo = dbot.config.github.defaultrepo;
            } else {
                repo = event.params[1];
            }

            var reqUrl = "https://api.github.com/";
            reqUrl += "repos/" + repo;

            request(reqUrl, function(error, response, body) {
                var data = JSON.parse(body);
                var str = "";
                str += data["name"] + " is a ";
                if (data["fork"] == true) {
                    str += "forked ";
                }
                str += data["language"];
                str += " repo with ";
                str += data["open_issues"] + " unresolved issues. ";
                str += "[" + data["forks"] + "F " + data["watchers"] + "W]";

                event.reply(str);
            });
        },*/
        '~repocount': function(event) {
        // TODO: add handling for non existent user
            var reqUrl = "https://api.github.com/users/" + event.params[1] + "/repos";
            request(reqUrl, function(error, response, body) {
            var result = JSON.parse(body);
			event.reply(event.params[1] + " has " + result.length + " public repositories.");
            });
        }
    };
    this.commands = commands;

    this.on = 'PRIVMSG';
};

exports.fetch = function(dbot) {
    return new github(dbot);
};
<commit_msg>parentheses<commit_after>/**
 * Module Name: Github
 * Description: Retrieves interesting Github information
 */
var request = require('request'),
    _ = require('underscore')._;

var github = function(dbot) {
    var commands = {
        '~repocount': function(event) {
        // TODO: add handling for non existent user
            var reqUrl = "https://api.github.com/users/" + event.params[1] + "/repos";
            request(reqUrl, function(error, response, body) {
            var result = JSON.parse(body);
			event.reply(event.params[1] + " has " + result.length + " public repositories.");
            });
        },
        '~repo': function(event) {
            var repo = "";
            if (typeof event.params[1] == 'undefined') {
                repo = dbot.config.github.defaultrepo;
            } else {
                repo = event.params[1];
            }

            var reqUrl = "https://api.github.com/";
            reqUrl += "repos/" + repo;

            request(reqUrl, function(error, response, body) {
                var data = JSON.parse(body);
                if (data["fork"] == true) {
                   event.reply(dbot.t("forkedrepo",data));
                } else {
                    event.reply(dbot.t("unforkedrepo",data));
                }
                // TODO: move this shizz into an api call
                var longurl = "http://github.com/" + repo;
                request({method: 'POST', uri: 'http://git.io', form:{url: longurl}}, function(error, response, body){
                    event.reply(dbot.t('location')+" "+response.headers["location"]);
                });
            });
        },
        '~gstatus': function(event) {
            var reqUrl = "https://status.github.com/api/last-message.json";
            request(reqUrl, function(error,response,body){
                var data = JSON.parse(body);
                event.reply(dbot.t("status"+data["status"]));
                event.reply(data["body"]);
            });
        },
        '~milestone': function(event) {
            var repo = dbot.config.github.defaultrepo;
            var reqUrl = "https://api.github.com/repos/";
            reqUrl += repo + "/milestones";

            request(reqUrl, function(error, response, body) {
                var data = JSON.parse(body);
                for (var section in data) {
                    var milestone = data[section];
                    if (milestone["title"] == event.params[1]){
                        var str = "Milestone " + milestone["title"];
                        var progress = milestone["closed_issues"] / (milestone["open_issues"] + milestone["closed_issues"]);
                        progress = Math.round(progress*100);
                        var bar = "[";
                        for (var i = 1; i < 10; i++) {
                            if  ((progress / (i*10)) > 1) {
                                bar += "█";
                            } else {
                                bar += " ";
                            }
                        }
                        bar += "]";
                        str += " is " + bar + progress + "% complete";

                        var longurl = "http://github.com/" + repo + "/issues?milestone=" + milestone["number"];
                        request({method: 'POST', uri: 'http://git.io', form:{url: longurl}}, function(error, response, body){
                            event.reply(response.headers["location"]);
                        });
                        event.reply(str);
                        break;
                    }
                }
           });
        },
/*        '~repo': function(event) {
            var repo = "";
            if (typeof event.params[1] == 'undefined') {
                repo = dbot.config.github.defaultrepo;
            } else {
                repo = event.params[1];
            }

            var reqUrl = "https://api.github.com/";
            reqUrl += "repos/" + repo;

            request(reqUrl, function(error, response, body) {
                var data = JSON.parse(body);
                var str = "";
                str += data["name"] + " is a ";
                if (data["fork"] == true) {
                    str += "forked ";
                }
                str += data["language"];
                str += " repo with ";
                str += data["open_issues"] + " unresolved issues. ";
                str += "[" + data["forks"] + "F " + data["watchers"] + "W]";

                event.reply(str);
            });
        },*/
        '~repocount': function(event) {
        // TODO: add handling for non existent user
            var reqUrl = "https://api.github.com/users/" + event.params[1] + "/repos";
            request(reqUrl, function(error, response, body) {
            var result = JSON.parse(body);
			event.reply(event.params[1] + " has " + result.length + " public repositories.");
            });
        }
    };
    this.commands = commands;

    this.on = 'PRIVMSG';
};

exports.fetch = function(dbot) {
    return new github(dbot);
};
<|endoftext|>


<commit_before>/*if (typeof exports === 'undefined'){
	this.address = 'int.clarencewoo.com';
	this.port = 8083;
} else {
	exports.port = 8083;
	exports.address = '104.236.18.111';
}
*/
if (typeof exports === 'undefined'){
	this.address = '127.0.0.1';
	this.port = 8083;
} else {
	exports.port = 8083;
	exports.address = '127.0.0.1';
}<commit_msg>IE websocket debugged<commit_after>if (typeof exports === 'undefined'){
	this.address = 'int.clarencewoo.com';
	this.port = 8083;
} else {
	exports.port = 8083;
	exports.address = '104.236.18.111';
}
/*
if (typeof exports === 'undefined'){
	this.address = '127.0.0.1';
	this.port = 8083;
} else {
	exports.port = 8083;
	exports.address = '127.0.0.1';
}*/<|endoftext|>


<commit_before>/*global Ember*/
/*global DS*/
(function () {
  'use strict';

  DS.LSQueue = Ember.Object.extend ({

		queue : [new Ember.RSVP.resolve()],

		attach : function (callback) {
			var self = this;
			var queueKey = self.queue.length;

			self.queue[queueKey] = new Ember.RSVP.Promise(function(resolve, reject) {
				self.queue[queueKey - 1].then (function () {
					callback(resolve, reject);
				});
			});

			return self.queue[queueKey];
		},

	});

  DS.LSSerializer = DS.JSONSerializer.extend({

    serializeHasMany: function(record, json, relationship) {
      var key = relationship.key,
          relationshipType = DS.RelationshipChange.determineRelationshipType(record.constructor, relationship);

      if (relationshipType === 'manyToNone' ||
          relationshipType === 'manyToMany' ||
          relationshipType === 'manyToOne') {
        json[key] = record.get(key).mapBy('id');
      // TODO support for polymorphic manyToNone and manyToMany relationships
      }
    },

    /**
     * Extracts whatever was returned from the adapter.
     *
     * If the adapter returns relationships in an embedded way, such as follows:
     *
     * ```js
     * {
     *   "id": 1,
     *   "title": "Rails Rambo",
     *
     *   "_embedded": {
     *     "comment": [{
     *       "id": 1,
     *       "comment_title": "FIRST"
     *     }, {
     *       "id": 2,
     *       "comment_title": "Rails is unagi"
     *     }]
     *   }
     * }
     *
     * this method will create separated JSON for each resource and then push
     * them individually to the Store.
     *
     * In the end, only the main resource will remain, containing the ids of its
     * relationships. Given the relations are already in the Store, we will
     * return a JSON with the main resource alone. The Store will sort out the
     * associations by itself.
     *
     * @method extractSingle
     * @private
     * @param {DS.Store} store the returned store
     * @param {DS.Model} type the type/model
     * @param {Object} payload returned JSON
     */
    extractSingle: function(store, type, payload) {
      if (payload && payload._embedded) {
        for (var relation in payload._embedded) {
          var relType = type.typeForRelationship(relation);
          var typeName = relType.typeKey,
              embeddedPayload = payload._embedded[relation];

          if (embeddedPayload) {
            if (Ember.isArray(embeddedPayload)) {
              store.pushMany(typeName, embeddedPayload);
            } else {
              store.push(typeName, embeddedPayload);
            }
          }
        }

        delete payload._embedded;
      }

      return this.normalize(type, payload);
    },

    /**
     * This is exactly the same as extractSingle, but used in an array.
     *
     * @method extractSingle
     * @private
     * @param {DS.Store} store the returned store
     * @param {DS.Model} type the type/model
     * @param {Array} payload returned JSONs
     */
    extractArray: function(store, type, payload) {
      var serializer = this;

      return payload.map(function(record) {
        var extracted = serializer.extractSingle(store, type, record);
        return serializer.normalize(type, record);
      });
    }

  });

  DS.LSAdapter = DS.Adapter.extend(Ember.Evented, {
	 queue : DS.LSQueue.create(),

    /**
      This is the main entry point into finding records. The first parameter to
      this method is the model's name as a string.

      @method find
      @param {DS.Model} type
      @param {Object|String|Integer|null} id
      */
    find: function(store, type, id, opts) {
      var adapter = this;

      return new Ember.RSVP.Promise(function(resolve, reject) {
          var allowRecursive = true;
         adapter._namespaceForType(type).then (function (namespace) {
        	  /**
               * In the case where there are relationships, this method is called again
               * for each relation. Given the relations have references to the main
               * object, we use allowRecursive to avoid going further into infinite
               * recursiveness.
               *
               * Concept from ember-indexdb-adapter
               */
              if (opts && typeof opts.allowRecursive !== 'undefined') {
                allowRecursive = opts.allowRecursive;
              }

            var record = Ember.A(namespace.records[id]);

            if (allowRecursive) {
              adapter.loadRelationships(type, record).then(function(finalRecord) {
                resolve(finalRecord);
              });
            } else {
              if (!record) {
                reject();
              } else {
                resolve(record);
              }
            }
          });
      });
    },

    findMany: function (store, type, ids) {
      var adapter = this;

      return new Ember.RSVP.Promise(function(resolve, reject) {
    	adapter._namespaceForType(type).then (function (namespace) {
    		var results = [];

            for (var i = 0; i < ids.length; i++) {
              results.push(Ember.copy(namespace.records[ids[i]]));
            }

            resolve(results);
    	});
      }).then(function(records) {
        if (records.get('length')) {
          return adapter.loadRelationshipsForMany(type, records);
        } else {
          return records;
        }
      });
    },

    // Supports queries that look like this:
    //
    //   {
    //     <property to query>: <value or regex (for strings) to match>,
    //     ...
    //   }
    //
    // Every property added to the query is an "AND" query, not "OR"
    //
    // Example:
    //
    //  match records with "complete: true" and the name "foo" or "bar"
    //
    //    { complete: true, name: /foo|bar/ }
    findQuery: function (store, type, query, recordArray) {
        var adapter = this;
    	return new Ember.RSVP.Promise(function(resolve, reject) {
    	  adapter._namespaceForType(type).then (function (namespace) {
	    	  results = this.query(namespace.records, query);

	          if (results.get('length')) {
	            results = adapter.loadRelationshipsForMany(type, results);
	          }

	          resolve(results);
    	 });
      })

    },

    query: function (records, query) {
      var results = [],
          id, record, property, test, push;
      for (id in records) {
        record = records[id];
        for (property in query) {
          test = query[property];
          push = false;
          if (Object.prototype.toString.call(test) === '[object RegExp]') {
            push = test.test(record[property]);
          } else {
            push = record[property] === test;
          }
        }
        if (push) {
          results.push(record);
        }
      }
      return results;
    },

    findAll: function (store, type) {
    	var adapter = this;
    	return new Ember.RSVP.Promise(function(resolve, reject) {
    	  adapter._namespaceForType(type).then (function (namespace) {
    		  var results = [];

		      for (var id in namespace.records) {
		        results.push(Ember.copy(namespace.records[id]));
		      }
		      resolve(results);
    	  });
    	});
    },

    createRecord: function (store, type, record) {
    	var adapter = this;
    	return this.queue.attach(function(resolve, reject) {
    		adapter._namespaceForType(type).then (function (namespaceRecords) {
    			var recordHash = record.serialize({includeId: true});

    		      namespaceRecords.records[recordHash.id] = recordHash;
    		      adapter.persistData(type, namespaceRecords).then (function () {
    		    	  resolve();
    		      });
    		});
    	});
    },

    updateRecord: function (store, type, record) {
    	var adapter = this;
    	return this.queue.attach(function(resolve, reject) {
    		adapter._namespaceForType(type).then (function (namespaceRecords) {
		         var id = record.get('id');

		      namespaceRecords.records[id] = record.serialize({ includeId: true });

		      adapter.persistData(type, namespaceRecords).then (function () {
		    	  resolve();
		      });
    		});
    	});
    },

    deleteRecord: function (store, type, record) {
    	var adapter = this;
    	return this.queue.attach(function(resolve, reject) {
    		adapter._namespaceForType(type).then (function (namespaceRecords) {
		         var id = record.get('id');

		      delete namespaceRecords.records[id];

		      adapter.persistData(type, namespaceRecords);
		      resolve();
    		});
    	});
    },

    generateIdForRecord: function () {
      return Math.random().toString(32).slice(2).substr(0, 5);
    },

    // private

    adapterNamespace: function () {
      return this.get('namespace') || 'DS.LSAdapter';
    },

    loadData: function () {
    	var adapter = this;
        return new Ember.RSVP.Promise(function(resolve, reject) {
  	      window.localforage.getItem(adapter.adapterNamespace()).then (function (storage) {
  	    	resolve(storage ? JSON.parse(storage) : {});
  	      });
        });
    },

    persistData: function(type, data) {
    	var adapter = this;
      var modelNamespace = this.modelNamespace(type);
      return new Ember.RSVP.Promise(function(resolve, reject) {
    	  adapter.loadData().then(function (localStorageData) {
	    	  localStorageData[modelNamespace] = data;
	          window.localforage.setItem(adapter.adapterNamespace(), JSON.stringify(localStorageData)).then (function () {
	        	  resolve();
	          });
	      });
      });

    },

    _namespaceForType: function (type) {
      var namespace = this.modelNamespace(type);
      var adapter = this;
      return new Ember.RSVP.Promise(function(resolve, reject) {
	      window.localforage.getItem(adapter.adapterNamespace()).then (function (storage) {
	    	  var ns = storage ? JSON.parse(storage)[namespace] || {records: {}} : {records: {}};
	    	  resolve(ns);
	      });
      });
    },

    modelNamespace: function(type) {
      return type.url || type.typeKey;
    },

    /**
     * This takes a record, then analyzes the model relationships and replaces
     * ids with the actual values.
     *
     * Stolen from ember-indexdb-adapter
     *
     * Consider the following JSON is entered:
     *
     * ```js
     * {
     *   "id": 1,
     *   "title": "Rails Rambo",
     *   "comments": [1, 2]
     * }
     *
     * This will return:
     *
     * ```js
     * {
     *   "id": 1,
     *   "title": "Rails Rambo",
     *   "comments": [1, 2]
     *
     *   "_embedded": {
     *     "comment": [{
     *       "_id": 1,
     *       "comment_title": "FIRST"
     *     }, {
     *       "_id": 2,
     *       "comment_title": "Rails is unagi"
     *     }]
     *   }
     * }
     *
     * This way, whenever a resource returned, its relationships will be also
     * returned.
     *
     * @method loadRelationships
     * @private
     * @param {DS.Model} type
     * @param {Object} record
     */
    loadRelationships: function(type, record) {
      var adapter = this;

      return new Ember.RSVP.Promise(function(resolve, reject) {
        var resultJSON = {},
            typeKey = type.typeKey,
            relationshipNames, relationships,
            relationshipPromises = [];

        relationshipNames = Ember.get(type, 'relationshipNames');
        relationships = relationshipNames.belongsTo;
        relationships = relationships.concat(relationshipNames.hasMany);

        relationships.forEach(function(relationName) {
          var relationModel = type.typeForRelationship(relationName),
              relationEmbeddedId = record[relationName],
              relationProp  = adapter.relationshipProperties(type, relationName),
              relationType  = relationProp.kind,
              /**
               * This is the relationship field.
               */
              promise, embedPromise;

          var opts = {allowRecursive: false};

          /**
           * embeddedIds are ids of relations that are included in the main
           * payload, such as:
           *
           * {
           *    cart: {
           *      id: "s85fb",
           *      customer: "rld9u"
           *    }
           * }
           *
           * In this case, cart belongsTo customer and its id is present in the
           * main payload. We find each of these records and add them to _embedded.
           */
          if (relationEmbeddedId) {
            if (relationType == 'belongsTo' || relationType == 'hasOne') {
              promise = adapter.find(null, relationModel, relationEmbeddedId, opts)
            } else if (relationType == 'hasMany') {
              promise = adapter.findMany(null, relationModel, relationEmbeddedId, opts)
            }

            embedPromise = new Ember.RSVP.Promise(function(resolve, reject) {
              promise.then(function(relationRecord) {
                var finalPayload = adapter.addEmbeddedPayload(record, relationName, relationRecord)
                resolve(finalPayload);
              });
            });

            relationshipPromises.push(embedPromise);
          }
        });

        Ember.RSVP.all(relationshipPromises).then(function() {
          resolve(record);
        });
      });
    },

    /**
     * Given the following payload,
     *
     *   {
     *      cart: {
     *        id: "1",
     *        customer: "2"
     *      }
     *   }
     *
     * With `relationshipName` being `customer` and `relationshipRecord`
     *
     *   {id: "2", name: "Rambo"}
     *
     * This method returns the following payload:
     *
     *   {
     *      cart: {
     *        id: "1",
     *        customer: "2"
     *      },
     *      _embedded: {
     *        customer: {
     *          id: "2",
     *          name: "Rambo"
     *        }
     *      }
     *   }
     *
     * which is then treated by the serializer later.
     *
     * @method addEmbeddedPayload
     * @private
     * @param {Object} payload
     * @param {String} relationshipName
     * @param {Object} relationshipRecord
     */
    addEmbeddedPayload: function(payload, relationshipName, relationshipRecord) {
      var objectHasId = (relationshipRecord && relationshipRecord.id),
          arrayHasIds = (relationshipRecord.length && relationshipRecord.everyBy("id")),
          isValidRelationship = (objectHasId || arrayHasIds);

      if (isValidRelationship) {
        if (!payload['_embedded']) {
          payload['_embedded'] = {}
        }

        payload['_embedded'][relationshipName] = relationshipRecord;
        if (relationshipRecord.length) {
          payload[relationshipName] = relationshipRecord.mapBy('id');
        } else {
          payload[relationshipName] = relationshipRecord.id;
        }
      }

      if (this.isArray(payload[relationshipName])) {
        payload[relationshipName] = payload[relationshipName].filter(function(id) {
          return id;
        });
      }

      return payload;
    },

    isArray: function(value) {
      return Object.prototype.toString.call(value) === '[object Array]';
    },

    /**
     * Same as `loadRelationships`, but for an array of records.
     *
     * @method loadRelationshipsForMany
     * @private
     * @param {DS.Model} type
     * @param {Object} recordsArray
     */
    loadRelationshipsForMany: function(type, recordsArray) {
      var adapter = this;

      return new Ember.RSVP.Promise(function(resolve, reject) {
        var recordsWithRelationships = [],
            recordsToBeLoaded = [],
            promises = [];

        /**
         * Some times Ember puts some stuff in arrays. We want to clean it so
         * we know exactly what to iterate over.
         */
        for (var i in recordsArray) {
          if (recordsArray.hasOwnProperty(i)) {
            recordsToBeLoaded.push(recordsArray[i]);
          }
        }

        var loadNextRecord = function(record) {
          /**
           * Removes the first item from recordsToBeLoaded
           */
          recordsToBeLoaded = recordsToBeLoaded.slice(1);

          var promise = adapter.loadRelationships(type, record);

          promise.then(function(recordWithRelationships) {
            recordsWithRelationships.push(recordWithRelationships);

            if (recordsToBeLoaded[0]) {
              loadNextRecord(recordsToBeLoaded[0]);
            } else {
              resolve(recordsWithRelationships);
            }
          });
        }

        /**
         * We start by the first record
         */
        loadNextRecord(recordsToBeLoaded[0]);
      });
    },

    /**
     *
     * @method relationshipProperties
     * @private
     * @param {DS.Model} type
     * @param {String} relationName
     */
    relationshipProperties: function(type, relationName) {
      var relationships = Ember.get(type, 'relationshipsByName');
      if (relationName) {
        return relationships.get(relationName);
      } else {
        return relationships;
      }
    }
  });
}());
<commit_msg>findQuery reference to this/adapter bug<commit_after>/*global Ember*/
/*global DS*/
(function () {
  'use strict';

  DS.LSQueue = Ember.Object.extend ({

		queue : [new Ember.RSVP.resolve()],

		attach : function (callback) {
			var self = this;
			var queueKey = self.queue.length;

			self.queue[queueKey] = new Ember.RSVP.Promise(function(resolve, reject) {
				self.queue[queueKey - 1].then (function () {
					callback(resolve, reject);
				});
			});

			return self.queue[queueKey];
		},

	});

  DS.LSSerializer = DS.JSONSerializer.extend({

    serializeHasMany: function(record, json, relationship) {
      var key = relationship.key,
          relationshipType = DS.RelationshipChange.determineRelationshipType(record.constructor, relationship);

      if (relationshipType === 'manyToNone' ||
          relationshipType === 'manyToMany' ||
          relationshipType === 'manyToOne') {
        json[key] = record.get(key).mapBy('id');
      // TODO support for polymorphic manyToNone and manyToMany relationships
      }
    },

    /**
     * Extracts whatever was returned from the adapter.
     *
     * If the adapter returns relationships in an embedded way, such as follows:
     *
     * ```js
     * {
     *   "id": 1,
     *   "title": "Rails Rambo",
     *
     *   "_embedded": {
     *     "comment": [{
     *       "id": 1,
     *       "comment_title": "FIRST"
     *     }, {
     *       "id": 2,
     *       "comment_title": "Rails is unagi"
     *     }]
     *   }
     * }
     *
     * this method will create separated JSON for each resource and then push
     * them individually to the Store.
     *
     * In the end, only the main resource will remain, containing the ids of its
     * relationships. Given the relations are already in the Store, we will
     * return a JSON with the main resource alone. The Store will sort out the
     * associations by itself.
     *
     * @method extractSingle
     * @private
     * @param {DS.Store} store the returned store
     * @param {DS.Model} type the type/model
     * @param {Object} payload returned JSON
     */
    extractSingle: function(store, type, payload) {
      if (payload && payload._embedded) {
        for (var relation in payload._embedded) {
          var relType = type.typeForRelationship(relation);
          var typeName = relType.typeKey,
              embeddedPayload = payload._embedded[relation];

          if (embeddedPayload) {
            if (Ember.isArray(embeddedPayload)) {
              store.pushMany(typeName, embeddedPayload);
            } else {
              store.push(typeName, embeddedPayload);
            }
          }
        }

        delete payload._embedded;
      }

      return this.normalize(type, payload);
    },

    /**
     * This is exactly the same as extractSingle, but used in an array.
     *
     * @method extractSingle
     * @private
     * @param {DS.Store} store the returned store
     * @param {DS.Model} type the type/model
     * @param {Array} payload returned JSONs
     */
    extractArray: function(store, type, payload) {
      var serializer = this;

      return payload.map(function(record) {
        var extracted = serializer.extractSingle(store, type, record);
        return serializer.normalize(type, record);
      });
    }

  });

  DS.LSAdapter = DS.Adapter.extend(Ember.Evented, {
	 queue : DS.LSQueue.create(),

    /**
      This is the main entry point into finding records. The first parameter to
      this method is the model's name as a string.

      @method find
      @param {DS.Model} type
      @param {Object|String|Integer|null} id
      */
    find: function(store, type, id, opts) {
      var adapter = this;

      return new Ember.RSVP.Promise(function(resolve, reject) {
          var allowRecursive = true;
         adapter._namespaceForType(type).then (function (namespace) {
        	  /**
               * In the case where there are relationships, this method is called again
               * for each relation. Given the relations have references to the main
               * object, we use allowRecursive to avoid going further into infinite
               * recursiveness.
               *
               * Concept from ember-indexdb-adapter
               */
              if (opts && typeof opts.allowRecursive !== 'undefined') {
                allowRecursive = opts.allowRecursive;
              }

            var record = Ember.A(namespace.records[id]);

            if (allowRecursive) {
              adapter.loadRelationships(type, record).then(function(finalRecord) {
                resolve(finalRecord);
              });
            } else {
              if (!record) {
                reject();
              } else {
                resolve(record);
              }
            }
          });
      });
    },

    findMany: function (store, type, ids) {
      var adapter = this;

      return new Ember.RSVP.Promise(function(resolve, reject) {
    	adapter._namespaceForType(type).then (function (namespace) {
    		var results = [];

            for (var i = 0; i < ids.length; i++) {
              results.push(Ember.copy(namespace.records[ids[i]]));
            }

            resolve(results);
    	});
      }).then(function(records) {
        if (records.get('length')) {
          return adapter.loadRelationshipsForMany(type, records);
        } else {
          return records;
        }
      });
    },

    // Supports queries that look like this:
    //
    //   {
    //     <property to query>: <value or regex (for strings) to match>,
    //     ...
    //   }
    //
    // Every property added to the query is an "AND" query, not "OR"
    //
    // Example:
    //
    //  match records with "complete: true" and the name "foo" or "bar"
    //
    //    { complete: true, name: /foo|bar/ }
    findQuery: function (store, type, query, recordArray) {
        var adapter = this;
    	return new Ember.RSVP.Promise(function(resolve, reject) {
    	  adapter._namespaceForType(type).then (function (namespace) {
	    	  var results = adapter.query(namespace.records, query);

	          if (results.get('length')) {
	            results = adapter.loadRelationshipsForMany(type, results);
	          }

	          resolve(results);
    	 });
      })

    },

    query: function (records, query) {
      var results = [],
          id, record, property, test, push;
      for (id in records) {
        record = records[id];
        for (property in query) {
          test = query[property];
          push = false;
          if (Object.prototype.toString.call(test) === '[object RegExp]') {
            push = test.test(record[property]);
          } else {
            push = record[property] === test;
          }
        }
        if (push) {
          results.push(record);
        }
      }
      return results;
    },

    findAll: function (store, type) {
    	var adapter = this;
    	return new Ember.RSVP.Promise(function(resolve, reject) {
    	  adapter._namespaceForType(type).then (function (namespace) {
    		  var results = [];

		      for (var id in namespace.records) {
		        results.push(Ember.copy(namespace.records[id]));
		      }
		      resolve(results);
    	  });
    	});
    },

    createRecord: function (store, type, record) {
    	var adapter = this;
    	return this.queue.attach(function(resolve, reject) {
    		adapter._namespaceForType(type).then (function (namespaceRecords) {
    			var recordHash = record.serialize({includeId: true});

    		      namespaceRecords.records[recordHash.id] = recordHash;
    		      adapter.persistData(type, namespaceRecords).then (function () {
    		    	  resolve();
    		      });
    		});
    	});
    },

    updateRecord: function (store, type, record) {
    	var adapter = this;
    	return this.queue.attach(function(resolve, reject) {
    		adapter._namespaceForType(type).then (function (namespaceRecords) {
		         var id = record.get('id');

		      namespaceRecords.records[id] = record.serialize({ includeId: true });

		      adapter.persistData(type, namespaceRecords).then (function () {
		    	  resolve();
		      });
    		});
    	});
    },

    deleteRecord: function (store, type, record) {
    	var adapter = this;
    	return this.queue.attach(function(resolve, reject) {
    		adapter._namespaceForType(type).then (function (namespaceRecords) {
		         var id = record.get('id');

		      delete namespaceRecords.records[id];

		      adapter.persistData(type, namespaceRecords);
		      resolve();
    		});
    	});
    },

    generateIdForRecord: function () {
      return Math.random().toString(32).slice(2).substr(0, 5);
    },

    // private

    adapterNamespace: function () {
      return this.get('namespace') || 'DS.LSAdapter';
    },

    loadData: function () {
    	var adapter = this;
        return new Ember.RSVP.Promise(function(resolve, reject) {
  	      window.localforage.getItem(adapter.adapterNamespace()).then (function (storage) {
  	    	resolve(storage ? JSON.parse(storage) : {});
  	      });
        });
    },

    persistData: function(type, data) {
    	var adapter = this;
      var modelNamespace = this.modelNamespace(type);
      return new Ember.RSVP.Promise(function(resolve, reject) {
    	  adapter.loadData().then(function (localStorageData) {
	    	  localStorageData[modelNamespace] = data;
	          window.localforage.setItem(adapter.adapterNamespace(), JSON.stringify(localStorageData)).then (function () {
	        	  resolve();
	          });
	      });
      });

    },

    _namespaceForType: function (type) {
      var namespace = this.modelNamespace(type);
      var adapter = this;
      return new Ember.RSVP.Promise(function(resolve, reject) {
	      window.localforage.getItem(adapter.adapterNamespace()).then (function (storage) {
	    	  var ns = storage ? JSON.parse(storage)[namespace] || {records: {}} : {records: {}};
	    	  resolve(ns);
	      });
      });
    },

    modelNamespace: function(type) {
      return type.url || type.typeKey;
    },

    /**
     * This takes a record, then analyzes the model relationships and replaces
     * ids with the actual values.
     *
     * Stolen from ember-indexdb-adapter
     *
     * Consider the following JSON is entered:
     *
     * ```js
     * {
     *   "id": 1,
     *   "title": "Rails Rambo",
     *   "comments": [1, 2]
     * }
     *
     * This will return:
     *
     * ```js
     * {
     *   "id": 1,
     *   "title": "Rails Rambo",
     *   "comments": [1, 2]
     *
     *   "_embedded": {
     *     "comment": [{
     *       "_id": 1,
     *       "comment_title": "FIRST"
     *     }, {
     *       "_id": 2,
     *       "comment_title": "Rails is unagi"
     *     }]
     *   }
     * }
     *
     * This way, whenever a resource returned, its relationships will be also
     * returned.
     *
     * @method loadRelationships
     * @private
     * @param {DS.Model} type
     * @param {Object} record
     */
    loadRelationships: function(type, record) {
      var adapter = this;

      return new Ember.RSVP.Promise(function(resolve, reject) {
        var resultJSON = {},
            typeKey = type.typeKey,
            relationshipNames, relationships,
            relationshipPromises = [];

        relationshipNames = Ember.get(type, 'relationshipNames');
        relationships = relationshipNames.belongsTo;
        relationships = relationships.concat(relationshipNames.hasMany);

        relationships.forEach(function(relationName) {
          var relationModel = type.typeForRelationship(relationName),
              relationEmbeddedId = record[relationName],
              relationProp  = adapter.relationshipProperties(type, relationName),
              relationType  = relationProp.kind,
              /**
               * This is the relationship field.
               */
              promise, embedPromise;

          var opts = {allowRecursive: false};

          /**
           * embeddedIds are ids of relations that are included in the main
           * payload, such as:
           *
           * {
           *    cart: {
           *      id: "s85fb",
           *      customer: "rld9u"
           *    }
           * }
           *
           * In this case, cart belongsTo customer and its id is present in the
           * main payload. We find each of these records and add them to _embedded.
           */
          if (relationEmbeddedId) {
            if (relationType == 'belongsTo' || relationType == 'hasOne') {
              promise = adapter.find(null, relationModel, relationEmbeddedId, opts)
            } else if (relationType == 'hasMany') {
              promise = adapter.findMany(null, relationModel, relationEmbeddedId, opts)
            }

            embedPromise = new Ember.RSVP.Promise(function(resolve, reject) {
              promise.then(function(relationRecord) {
                var finalPayload = adapter.addEmbeddedPayload(record, relationName, relationRecord)
                resolve(finalPayload);
              });
            });

            relationshipPromises.push(embedPromise);
          }
        });

        Ember.RSVP.all(relationshipPromises).then(function() {
          resolve(record);
        });
      });
    },

    /**
     * Given the following payload,
     *
     *   {
     *      cart: {
     *        id: "1",
     *        customer: "2"
     *      }
     *   }
     *
     * With `relationshipName` being `customer` and `relationshipRecord`
     *
     *   {id: "2", name: "Rambo"}
     *
     * This method returns the following payload:
     *
     *   {
     *      cart: {
     *        id: "1",
     *        customer: "2"
     *      },
     *      _embedded: {
     *        customer: {
     *          id: "2",
     *          name: "Rambo"
     *        }
     *      }
     *   }
     *
     * which is then treated by the serializer later.
     *
     * @method addEmbeddedPayload
     * @private
     * @param {Object} payload
     * @param {String} relationshipName
     * @param {Object} relationshipRecord
     */
    addEmbeddedPayload: function(payload, relationshipName, relationshipRecord) {
      var objectHasId = (relationshipRecord && relationshipRecord.id),
          arrayHasIds = (relationshipRecord.length && relationshipRecord.everyBy("id")),
          isValidRelationship = (objectHasId || arrayHasIds);

      if (isValidRelationship) {
        if (!payload['_embedded']) {
          payload['_embedded'] = {}
        }

        payload['_embedded'][relationshipName] = relationshipRecord;
        if (relationshipRecord.length) {
          payload[relationshipName] = relationshipRecord.mapBy('id');
        } else {
          payload[relationshipName] = relationshipRecord.id;
        }
      }

      if (this.isArray(payload[relationshipName])) {
        payload[relationshipName] = payload[relationshipName].filter(function(id) {
          return id;
        });
      }

      return payload;
    },

    isArray: function(value) {
      return Object.prototype.toString.call(value) === '[object Array]';
    },

    /**
     * Same as `loadRelationships`, but for an array of records.
     *
     * @method loadRelationshipsForMany
     * @private
     * @param {DS.Model} type
     * @param {Object} recordsArray
     */
    loadRelationshipsForMany: function(type, recordsArray) {
      var adapter = this;

      return new Ember.RSVP.Promise(function(resolve, reject) {
        var recordsWithRelationships = [],
            recordsToBeLoaded = [],
            promises = [];

        /**
         * Some times Ember puts some stuff in arrays. We want to clean it so
         * we know exactly what to iterate over.
         */
        for (var i in recordsArray) {
          if (recordsArray.hasOwnProperty(i)) {
            recordsToBeLoaded.push(recordsArray[i]);
          }
        }

        var loadNextRecord = function(record) {
          /**
           * Removes the first item from recordsToBeLoaded
           */
          recordsToBeLoaded = recordsToBeLoaded.slice(1);

          var promise = adapter.loadRelationships(type, record);

          promise.then(function(recordWithRelationships) {
            recordsWithRelationships.push(recordWithRelationships);

            if (recordsToBeLoaded[0]) {
              loadNextRecord(recordsToBeLoaded[0]);
            } else {
              resolve(recordsWithRelationships);
            }
          });
        }

        /**
         * We start by the first record
         */
        loadNextRecord(recordsToBeLoaded[0]);
      });
    },

    /**
     *
     * @method relationshipProperties
     * @private
     * @param {DS.Model} type
     * @param {String} relationName
     */
    relationshipProperties: function(type, relationName) {
      var relationships = Ember.get(type, 'relationshipsByName');
      if (relationName) {
        return relationships.get(relationName);
      } else {
        return relationships;
      }
    }
  });
}());
<|endoftext|>


<commit_before>function reloadGame() {
  $('body').on("click", 'button', function(e) {
    e.preventDefault()
    console.log( $(this) )
    console.log("resetting game")
    $(".column-div").remove()
    minePositions = {}
    clueNumbers = {}
    listOfClueNumbers = [[],[],[],[],[],[],[],[],[]]
    listOfAllOtherTiles = []
    createBoard()
    randomizeMinePositions()
    putNumbersAroundMines(minePositions)
    getAllNotMinesTiles()
    $('.overlay').remove()
  })
}

/*
  Check if coordinates are inside or outside the allowed area.

  These get the coordinates of the adjacent tiles in different
  directions from the tile that was clicked.
  If the coordinates are NOT outside the edge of the grid,
  then it returns an array with [column, row].
  If not, it returns 'undefined'.
*/

function checkTileAbove(column, row) {
  let tileAbove = row + 1
  if (tileAbove < board.length) {
    return [column, tileAbove]
  }
}

function checkNorthEastTile(column, row) {
  let tileOnRight = column + 1
  let tileAbove = row + 1
  if ( (tileAbove < board.length) && (tileOnRight < board.length) ) {
    return [tileOnRight, tileAbove]
  }
}

function checkTileOnRight(column, row) {
  let tileOnRight = column + 1
  if (tileOnRight < board.length) {
    return [tileOnRight, row]
  }
}

function checkSouthEastTile(column, row) {
  let tileOnRight = column + 1
  let tileBelow = row - 1
  if ( (tileOnRight < board.length) && (tileBelow >= 0) ) {
    return [tileOnRight, tileBelow]
  }
}

function checkTileBelow(column, row) {
  let tileBelow = row - 1
  if (tileBelow >= 0) {
    return [column, tileBelow]
  }
}

function checkSouthWestTile(column, row) {
  let tileOnLeft = column - 1
  let tileBelow = row - 1
  if ( (tileBelow >= 0) && (tileOnLeft >= 0) ) {
    return [tileOnLeft, tileBelow]
  }
}

function checkTileOnLeft(column, row) {
  let tileOnLeft = column - 1
  if (tileOnLeft >= 0) {
    return [tileOnLeft, row]
  }
}

function checkNorthWestTile(column, row) {
  let tileOnLeft = column - 1
  let tileAbove = row + 1
  if ( (tileOnLeft >= 0) && (tileAbove < board.length) ) {
    return [tileOnLeft, tileAbove]
  }
}<commit_msg>Remove console.log debug code from helper.js.<commit_after>function reloadGame() {
  $('body').on("click", 'button', function(e) {
    e.preventDefault()

    $(".column-div").remove()
    minePositions = {}
    clueNumbers = {}
    listOfClueNumbers = [[],[],[],[],[],[],[],[],[]]
    listOfAllOtherTiles = []
    createBoard()
    randomizeMinePositions()
    putNumbersAroundMines(minePositions)
    getAllNotMinesTiles()
    $('.overlay').remove()
  })
}

/*
  Check if coordinates are inside or outside the allowed area.

  These get the coordinates of the adjacent tiles in different
  directions from the tile that was clicked.
  If the coordinates are NOT outside the edge of the grid,
  then it returns an array with [column, row].
  If not, it returns 'undefined'.
*/

function checkTileAbove(column, row) {
  let tileAbove = row + 1
  if (tileAbove < board.length) {
    return [column, tileAbove]
  }
}

function checkNorthEastTile(column, row) {
  let tileOnRight = column + 1
  let tileAbove = row + 1
  if ( (tileAbove < board.length) && (tileOnRight < board.length) ) {
    return [tileOnRight, tileAbove]
  }
}

function checkTileOnRight(column, row) {
  let tileOnRight = column + 1
  if (tileOnRight < board.length) {
    return [tileOnRight, row]
  }
}

function checkSouthEastTile(column, row) {
  let tileOnRight = column + 1
  let tileBelow = row - 1
  if ( (tileOnRight < board.length) && (tileBelow >= 0) ) {
    return [tileOnRight, tileBelow]
  }
}

function checkTileBelow(column, row) {
  let tileBelow = row - 1
  if (tileBelow >= 0) {
    return [column, tileBelow]
  }
}

function checkSouthWestTile(column, row) {
  let tileOnLeft = column - 1
  let tileBelow = row - 1
  if ( (tileBelow >= 0) && (tileOnLeft >= 0) ) {
    return [tileOnLeft, tileBelow]
  }
}

function checkTileOnLeft(column, row) {
  let tileOnLeft = column - 1
  if (tileOnLeft >= 0) {
    return [tileOnLeft, row]
  }
}

function checkNorthWestTile(column, row) {
  let tileOnLeft = column - 1
  let tileAbove = row + 1
  if ( (tileOnLeft >= 0) && (tileAbove < board.length) ) {
    return [tileOnLeft, tileAbove]
  }
}<|endoftext|>


<commit_before>import React from 'react';
import { props, t } from '../utils';
import { warn } from '../utils/log';
import Popover from '../popover/Popover';

/**
 * ### Text view which, if string content is too large, trims it and shows the full content on "hover" with a `Popover` (or custom component if any)
 */
@props({
  /**
   * in case you want to use a custom component (like a `Tooltip`) to render the full content which is passed as the first argument
   */
  children: t.maybe(t.Function),
  /**
   * this is the full string
   */
  label: t.String,
  id: t.maybe(t.String),
  className: t.maybe(t.String),
  style: t.maybe(t.Object)
}, { strict: false })
export default class TextOverflow extends React.Component {

  constructor(props) {
    super(props);
    this.state = { isOverflowing: false };
  }

  componentDidMount = () => this.verifyOverflow();

  componentDidUpdate = () => this.verifyOverflow();

  componentWillReceiveProps = (nextProps) => {
    if (nextProps.label !== this.props.label) {
      this.reset();
    }
  };

  reset = () => this.setState({ isOverflowing: false });

  logWarnings = () => {
    warn(() => {
      const node = React.findDOMNode(this.refs.text).parentNode;
      const { width, flex } = node.style;
      const flexBasis = flex ? flex.split(' ')[2] : null;
      if (width !== '100%' && flexBasis !== '100%') {
        return ['WARNING: TextOverflow\'s parent doesn\'t have "width: 100%" nor "flex-basis: 100%"', node];
      }
    });
  };

  verifyOverflow = (_state) => {
    const state = _state || this.state;
    if (state.isOverflowing === false) {
      const text = React.findDOMNode(this.refs.text);
      const { parentNode: parent } = text;

      const { offsetWidth: textOffsetWidth, scrollWidth: textScrollWidth } = text;
      const { width: parentWidth, 'max-width': parentMaxWidth } = window.getComputedStyle(parent);

      const isOverflowing = (textOffsetWidth < textScrollWidth) ||
        (textOffsetWidth === textScrollWidth && parseFloat(parentWidth) >= parseFloat(parentMaxWidth));

      if (isOverflowing) {
        this.setState({ isOverflowing: true }, this.logWarnings);
      } else {
        this.logWarnings();
      }
    }
  };

  getTextSpan = () => {
    const { label } = this.props;
    const style = {
      display: 'block',
      whiteSpace: 'nowrap',
      width: '100%',
      overflow: 'hidden',
      OTextOverflow: 'ellipsis', // Opera
      textOverflow: 'ellipsis'
    };
    return {label};
  };

  templateOverflow = () => {
    const { children, label, style, ...other } = this.props;

    if (children) {
      return children(this.getTextSpan());
    } else {
      const props = {
        ...other,
        popover: {
          content: label,
          event: 'hover'
        },
        style: {
          width: '100%',
          ...style
        }
      };

      return <Popover { ...props }>{this.getTextSpan()}</Popover>;
    }
  };

  templeteStandard = () => {
    const { children, label, style, ...other } = this.props;
    const props = {
      ...other,
      style: {
        width: '100%',
        ...style
      }
    };

    return
{this.getTextSpan()}
;
  };

  render() {
    return this.state.isOverflowing ? this.templateOverflow() : this.templeteStandard();
  }

}
<commit_msg>check if window exists to avoid crash during server-side render<commit_after>import React from 'react';
import { props, t } from '../utils';
import { warn } from '../utils/log';
import Popover from '../popover/Popover';

/**
 * ### Text view which, if string content is too large, trims it and shows the full content on "hover" with a `Popover` (or custom component if any)
 */
@props({
  /**
   * in case you want to use a custom component (like a `Tooltip`) to render the full content which is passed as the first argument
   */
  children: t.maybe(t.Function),
  /**
   * this is the full string
   */
  label: t.String,
  id: t.maybe(t.String),
  className: t.maybe(t.String),
  style: t.maybe(t.Object)
}, { strict: false })
export default class TextOverflow extends React.Component {

  constructor(props) {
    super(props);
    this.state = { isOverflowing: false };
  }

  componentDidMount = () => this.verifyOverflow();

  componentDidUpdate = () => this.verifyOverflow();

  componentWillReceiveProps = (nextProps) => {
    if (nextProps.label !== this.props.label) {
      this.reset();
    }
  };

  reset = () => this.setState({ isOverflowing: false });

  logWarnings = () => {
    warn(() => {
      const node = React.findDOMNode(this.refs.text).parentNode;
      const { width, flex } = node.style;
      const flexBasis = flex ? flex.split(' ')[2] : null;
      if (width !== '100%' && flexBasis !== '100%') {
        return ['WARNING: TextOverflow\'s parent doesn\'t have "width: 100%" nor "flex-basis: 100%"', node];
      }
    });
  };

  verifyOverflow = (_state) => {
    const state = _state || this.state;
    if (state.isOverflowing === false && window) {
      const text = React.findDOMNode(this.refs.text);
      const { parentNode: parent } = text;

      const { offsetWidth: textOffsetWidth, scrollWidth: textScrollWidth } = text;
      const { width: parentWidth, 'max-width': parentMaxWidth } = window.getComputedStyle(parent);

      const isOverflowing = (textOffsetWidth < textScrollWidth) ||
        (textOffsetWidth === textScrollWidth && parseFloat(parentWidth) >= parseFloat(parentMaxWidth));

      if (isOverflowing) {
        this.setState({ isOverflowing: true }, this.logWarnings);
      } else {
        this.logWarnings();
      }
    }
  };

  getTextSpan = () => {
    const { label } = this.props;
    const style = {
      display: 'block',
      whiteSpace: 'nowrap',
      width: '100%',
      overflow: 'hidden',
      OTextOverflow: 'ellipsis', // Opera
      textOverflow: 'ellipsis'
    };
    return {label};
  };

  templateOverflow = () => {
    const { children, label, style, ...other } = this.props;

    if (children) {
      return children(this.getTextSpan());
    } else {
      const props = {
        ...other,
        popover: {
          content: label,
          event: 'hover'
        },
        style: {
          width: '100%',
          ...style
        }
      };

      return <Popover { ...props }>{this.getTextSpan()}</Popover>;
    }
  };

  templeteStandard = () => {
    const { children, label, style, ...other } = this.props;
    const props = {
      ...other,
      style: {
        width: '100%',
        ...style
      }
    };

    return
{this.getTextSpan()}
;
  };

  render() {
    return this.state.isOverflowing ? this.templateOverflow() : this.templeteStandard();
  }

}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2012 B3Partners B.V.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

Ext.Loader.setConfig({enabled: true});
Ext.Loader.setPath('Ext.ux', uxpath);
Ext.require([
    'Ext.grid.*',
    'Ext.data.*',
    'Ext.util.*',
    'Ext.ux.grid.GridHeaderFilters',
    'Ext.toolbar.Paging'
]);

Ext.onReady(function(){

    Ext.define('TableRow', {
        extend: 'Ext.data.Model',
        fields: [
            {name: 'name', type: 'string'},
            {name: 'description', type: 'string'},
            {name: 'editable', type: 'boolean'}
        ]
    });

    var store = Ext.create('Ext.data.Store', {
        pageSize: 10,
        model: 'TableRow',
        remoteSort: true,
        remoteFilter: true,
        proxy: {
            type: 'ajax',
            url: gridurl,
            reader: {
                type: 'json',
                root: 'gridrows',
                totalProperty: 'totalCount'
            },
            simpleSortMode: true
        },
        autoLoad: true
    });

    var grid = Ext.create('Ext.grid.Panel', Ext.merge(defaultGridConfig, {
        id: 'editGrid',
        store: store,
        columns: [
            {
                id: 'name',
                text: "Naam",
                dataIndex: 'name',
                flex: 1,
                filter: {
                    xtype: 'textfield'
                }
            },{
                id: 'description',
                text: "Extra informatie",
                dataIndex: 'description',
                flex: 1,
                filter: {
                    xtype: 'textfield'
                }
            },{
                id: 'edit',
                header: '',
                dataIndex: 'name',
                flex: 1,
                renderer: function(value) {
                    return Ext.String.format('Bewerken', value) +
                           ' | ' +
                           Ext.String.format('Verwijderen', value);
                },
                sortable: false
            }
        ],
        bbar: Ext.create('Ext.PagingToolbar', {
            store: store,
            displayInfo: true,
            displayMsg: 'Groep {0} - {1} of {2}',
            emptyMsg: "Geen groepen weer te geven"
        }),
        plugins: [
            Ext.create('Ext.ux.grid.GridHeaderFilters', {
                enableTooltip: false
            })
        ],
        renderTo: 'grid-container'
    }));

});

function editObject(objId) {
    Ext.get('editFrame').dom.src = editurl + '?group=' + objId;
    var gridCmp = Ext.getCmp('editGrid')
    gridCmp.getSelectionModel().select(gridCmp.getStore().find('id', objId));
    return false;
}

function removeObject(objId) {
    // How are we going to remove items? In the iframe or directly trough ajax?
    Ext.get('editFrame').dom.src = deleteurl + '?group=' + objId;
    var gridCmp = Ext.getCmp('editGrid')
    gridCmp.getSelectionModel().select(gridCmp.getStore().find('id', objId));
    return false;
}

<commit_msg>Bij niet bewerkbare groepen de links voor Bewerken & Verwijderen niet tonen<commit_after>/*
 * Copyright (C) 2012 B3Partners B.V.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

Ext.Loader.setConfig({enabled: true});
Ext.Loader.setPath('Ext.ux', uxpath);
Ext.require([
    'Ext.grid.*',
    'Ext.data.*',
    'Ext.util.*',
    'Ext.ux.grid.GridHeaderFilters',
    'Ext.toolbar.Paging'
]);

Ext.onReady(function(){

    Ext.define('TableRow', {
        extend: 'Ext.data.Model',
        fields: [
            {name: 'name', type: 'string'},
            {name: 'description', type: 'string'},
            {name: 'editable', type: 'boolean'}
        ]
    });

    var store = Ext.create('Ext.data.Store', {
        pageSize: 10,
        model: 'TableRow',
        remoteSort: true,
        remoteFilter: true,
        proxy: {
            type: 'ajax',
            url: gridurl,
            reader: {
                type: 'json',
                root: 'gridrows',
                totalProperty: 'totalCount'
            },
            simpleSortMode: true
        },
        autoLoad: true
    });

    var grid = Ext.create('Ext.grid.Panel', Ext.merge(defaultGridConfig, {
        id: 'editGrid',
        store: store,
        columns: [
            {
                id: 'name',
                text: "Naam",
                dataIndex: 'name',
                flex: 1,
                filter: {
                    xtype: 'textfield'
                }
            },{
                id: 'description',
                text: "Extra informatie",
                dataIndex: 'description',
                flex: 1,
                filter: {
                    xtype: 'textfield'
                }
            },{
                id: 'edit',
                header: '',
                dataIndex: 'name',
                flex: 1,
                renderer: function(value, obj, rec) {
                    if(rec.get('editable')) {
                        return Ext.String.format('Bewerken', value) +
                               ' | ' +
                               Ext.String.format('Verwijderen', value);
                    }
                    return 'Deze groep mag niet worden bewerkt of verwijderd';
                },
                sortable: false
            }
        ],
        bbar: Ext.create('Ext.PagingToolbar', {
            store: store,
            displayInfo: true,
            displayMsg: 'Groep {0} - {1} of {2}',
            emptyMsg: "Geen groepen weer te geven"
        }),
        plugins: [
            Ext.create('Ext.ux.grid.GridHeaderFilters', {
                enableTooltip: false
            })
        ],
        renderTo: 'grid-container'
    }));

});

function editObject(objId) {
    Ext.get('editFrame').dom.src = editurl + '?group=' + objId;
    var gridCmp = Ext.getCmp('editGrid')
    gridCmp.getSelectionModel().select(gridCmp.getStore().find('id', objId));
    return false;
}

function removeObject(objId) {
    // How are we going to remove items? In the iframe or directly trough ajax?
    Ext.get('editFrame').dom.src = deleteurl + '?group=' + objId;
    var gridCmp = Ext.getCmp('editGrid')
    gridCmp.getSelectionModel().select(gridCmp.getStore().find('id', objId));
    return false;
}

<|endoftext|>


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

    const defaultWidth = 1280,
        defaultHeight = 720,
        compactWidth = 230,
        compactHeight = 500;

    class ToolbarCtrl {
        constructor($scope, $timeout, currentWindowService) {
            this.$scope = $scope;
            this.$timeout = $timeout;
            this.currentWindowService = currentWindowService;
            this.store = null;
            this.window = null;
            this.maximised = false;
            this.oldSize = null;
            currentWindowService.ready(() => {
                var boundReady = this.onReady.bind(this);
                boundReady();
                this._watch();
            });

            this.maximisedEvent = () => {
                this.$timeout(() => {
                    this.maximised = true;
                });
            };

            this.restoredEvent = () => {
                this.$timeout(() => {
                    this.maximised = false;
                });
            };
        }

        isCompact() {
            if (!this.store && window.storeService) {
                this.store = window.storeService.open(window.name);
            }

            return this.store && this.store.isCompact();
        }

        onReady() {
            this.window = this.currentWindowService.getCurrentWindow();
            this.window.addEventListener('maximized', this.maximisedEvent);
            this.window.addEventListener('restored', this.restoredEvent);
        }

        minimiseClick() {
            this.window.minimize();
        }

        maximiseClick() {
            this.window.maximize();
        }

        normalSizeClick() {
            this.window.restore();
            this.window.resizeTo(defaultWidth, defaultHeight, 'top-right');
        }

        _compactChanged() {
            var becomingCompact = this.isCompact();
            if (becomingCompact && window.outerWidth !== compactWidth) {
                this.oldSize = [window.outerWidth, window.outerHeight];
            }

            window.windowService.updateOptions(this.window, becomingCompact);

            if (becomingCompact) {
                this.window.resizeTo(compactWidth, compactHeight, 'top-right');
            }
            else if (this.maximised) {
                this.window.maximize();
            }
            else {
                var width = defaultWidth,
                    height = defaultHeight;
                if (this.oldSize) {
                    width = this.oldSize[0];
                    height = this.oldSize[1];
                }

                this.window.resizeTo(width, height, 'top-right');
            }
        }

        compactClick() {
            if (!this.store) {
                this.store = window.storeService.open(window.name);
            }

            this.store.toggleCompact();
        }

        closeClick() {
            this.window.removeEventListener('maximized', this.maximisedEvent);
            this.window.removeEventListener('restored', this.restoredEvent);
            this.window.close();
        }

        _watch() {
            this.$scope.$watch(
                () => this.isCompact(),
                () => this._compactChanged());
        }
    }
    ToolbarCtrl.$inject = ['$scope', '$timeout', 'currentWindowService'];

    angular.module('stockflux.toolbar')
        .controller('ToolbarCtrl', ToolbarCtrl);
}());
<commit_msg>Fix order of event binding<commit_after>(function() {
    'use strict';

    const defaultWidth = 1280,
        defaultHeight = 720,
        compactWidth = 230,
        compactHeight = 500;

    class ToolbarCtrl {
        constructor($scope, $timeout, currentWindowService) {
            this.$scope = $scope;
            this.$timeout = $timeout;
            this.currentWindowService = currentWindowService;
            this.store = null;
            this.window = null;
            this.maximised = false;
            this.oldSize = null;

            this.maximisedEvent = () => {
                this.$timeout(() => {
                    this.maximised = true;
                });
            };

            this.restoredEvent = () => {
                this.$timeout(() => {
                    this.maximised = false;
                });
            };

            currentWindowService.ready(() => {
                var boundReady = this.onReady.bind(this);
                boundReady();
                this._watch();
            });
        }

        isCompact() {
            if (!this.store && window.storeService) {
                this.store = window.storeService.open(window.name);
            }

            return this.store && this.store.isCompact();
        }

        onReady() {
            this.window = this.currentWindowService.getCurrentWindow();
            this.window.addEventListener('maximized', this.maximisedEvent);
            this.window.addEventListener('restored', this.restoredEvent);
        }

        minimiseClick() {
            this.window.minimize();
        }

        maximiseClick() {
            this.window.maximize();
        }

        normalSizeClick() {
            this.window.restore();
            this.window.resizeTo(defaultWidth, defaultHeight, 'top-right');
        }

        _compactChanged() {
            var becomingCompact = this.isCompact();
            if (becomingCompact && window.outerWidth !== compactWidth) {
                this.oldSize = [window.outerWidth, window.outerHeight];
            }

            window.windowService.updateOptions(this.window, becomingCompact);

            if (becomingCompact) {
                this.window.resizeTo(compactWidth, compactHeight, 'top-right');
            }
            else if (this.maximised) {
                this.window.maximize();
            }
            else {
                var width = defaultWidth,
                    height = defaultHeight;
                if (this.oldSize) {
                    width = this.oldSize[0];
                    height = this.oldSize[1];
                }

                this.window.resizeTo(width, height, 'top-right');
            }
        }

        compactClick() {
            if (!this.store) {
                this.store = window.storeService.open(window.name);
            }

            this.store.toggleCompact();
        }

        closeClick() {
            this.window.removeEventListener('maximized', this.maximisedEvent);
            this.window.removeEventListener('restored', this.restoredEvent);
            this.window.close();
        }

        _watch() {
            this.$scope.$watch(
                () => this.isCompact(),
                () => this._compactChanged());
        }
    }
    ToolbarCtrl.$inject = ['$scope', '$timeout', 'currentWindowService'];

    angular.module('stockflux.toolbar')
        .controller('ToolbarCtrl', ToolbarCtrl);
}());
<|endoftext|>


<commit_before>var gitHub = {};

/*
 * Make sure that github is logged in before calling callback
 * if there is an error, call errorCallback with an error param
 */
gitHub.ensureLogin = function(callback, errorCallback) {
    // Determine if there is a current oauth session
    var session = hello('github').getAuthResponse();
    var currentTime = (new Date()).getTime() / 1000;
    var online = session && session.access_token && session.expires > currentTime;

    if(online) {
        // If there is an active session, perform the callback
        callback();
    }
    else {
        // Otherwise, login
        var options = {};
        options.scope = ['user', 'repo', 'gist'];
        options.force = false;

        hello('github', options).login().then(function() {
            // Then call the callback
            callback()
        },
        function(e) {
            // If there was an error, send it to the callback
            errorCallback(e);
        });
    }
}

/*
 * Get all of the user's repositories
 */
gitHub.getRepos = function(done, error) {
    /*
     * Handle a repo response from GitHub
     */
    var addAllRepos = function(target, json, done, error) {
        // Add all returned repos to the list
        json.data.forEach(function(data) {
            var repo = {};
            repo.id = data.id;
            repo.owner = data.owner.login;
            repo.name = data.name;
            repo.full_name = data.full_name;
            repo.description = data.description;
            repo.url = data.url;
            repo.branches_url = data.branches_url;
            repo.git_commits_url = data.git_commits_url;
            repo.default_branch = data.default_branch;
            repo.permissions = data.permissions;
            target.push(repo);
        });

        // If there are more pages of repos,
        if (json.paging && json.paging.next) {
            // Request the next page of repos
            hello('github').api(json.paging.next).then(
                function(response){
                    console.log("retrieving next page of repos...");
                    // and handle the repos
                    addAllRepos(target, response, done, error);
                },
                function(e) {
                    // If there is an error, report it
                    error(e);
                });
        }
        else {
            // If there are no more pages of repos, send them to the caller
            done(target);
        }
    }

    // Clear out the list of repos
    gitHub.repos = [];

    // Make sure that the user is logged in
    gitHub.ensureLogin (function () {
        // Then request the user's repos
        hello('github').api('/user/repos').then(
            function(response){
                // Once the repos are received, add them to the repo list
                addAllRepos(gitHub.repos, response, done, error);
            },
            function (e) {
                // If there was an error, report it
                error(e);
            });
    },
    function(e) {
        // If there was an error logging in, report it
        error(e);
    });
};

/*
 * Load the files from a github repo into a FileManager
 */
gitHub.loadRepo = function(fileManager, repo) {
    var branch = repo.branches_url.replace(/\{.*\}/, "/" + repo.default_branch);
    hello('github').api(branch).then(function(response) {
        fileManager.empty();
        var folder = fileManager.getRootFolder();
        gitHub.loadTree(folder, response.commit.commit.tree.url, fileManager);
    },
    function(e) {
        alert('Error loading Repo branch: ' + e.error.message);
    });
};

gitHub.loadTree = function(folder, tree, fileManager) {
    hello('github').api(tree).then(function(response) {
        response.tree.forEach(item)(function(item){
            if (item.type === "tree") {
                console.log("Tree: " + item.path);
                var subFolder = Folder(item.path, tree);
                gitHub.loadTree(subFolder, item.url, fileManager);
            }
            else if (item.type == "blob") {
                gitHub.loadFile(folder, item.path, item.url);
            }
        });

        fileManager.updateDisplay();

        // If there are more pages of items in the tree,
        if (response.paging && response.paging.next) {
            gitHub.loadTree(folder, response.paging.next, fileManager);
        }
    },
    function (e){
        alert("Error loading tree: " + e.error.message);
    });
};

gitHub.loadFile = function(folder, name, url) {
    hello('github').api(url).then(function(response) {
        console.log("File: " + name);

        var content = window.btoa(response.content);
        var file = SourceFile(name, content);
        folder.addFile(file);
    },
    function(e) {
        alert("Error loading file: " + e.error.message);
    });
};

/*
 * Callback for auth session starts
 */
function sessionStart() {
    hello('github').api('/me').then(function(json) {
        gitHub.username = json.login;
        gitHub.repos_url = json.repos_url;
    },
    function(e) {

    });
}

/*
 * Prepare for oauth login to github
 */
hello.init({github: 'b80ec7eaa799156bba33'},
           {redirect_uri: 'https://run.mycode.run/redirect.html',
            oauth_proxy: 'https://auth-server.herokuapp.com/proxy'});

hello.on('auth.login', sessionStart);<commit_msg>adding hello.js library for connection to github<commit_after>var gitHub = {};

/*
 * Make sure that github is logged in before calling callback
 * if there is an error, call errorCallback with an error param
 */
gitHub.ensureLogin = function(callback, errorCallback) {
    // Determine if there is a current oauth session
    var session = hello('github').getAuthResponse();
    var currentTime = (new Date()).getTime() / 1000;
    var online = session && session.access_token && session.expires > currentTime;

    if(online) {
        // If there is an active session, perform the callback
        callback();
    }
    else {
        // Otherwise, login
        var options = {};
        options.scope = ['user', 'repo', 'gist'];
        options.force = false;

        hello('github', options).login().then(function() {
            // Then call the callback
            callback()
        },
        function(e) {
            // If there was an error, send it to the callback
            errorCallback(e);
        });
    }
}

/*
 * Get all of the user's repositories
 */
gitHub.getRepos = function(done, error) {
    /*
     * Handle a repo response from GitHub
     */
    var addAllRepos = function(target, json, done, error) {
        // Add all returned repos to the list
        json.data.forEach(function(data) {
            var repo = {};
            repo.id = data.id;
            repo.owner = data.owner.login;
            repo.name = data.name;
            repo.full_name = data.full_name;
            repo.description = data.description;
            repo.url = data.url;
            repo.branches_url = data.branches_url;
            repo.git_commits_url = data.git_commits_url;
            repo.default_branch = data.default_branch;
            repo.permissions = data.permissions;
            target.push(repo);
        });

        // If there are more pages of repos,
        if (json.paging && json.paging.next) {
            // Request the next page of repos
            hello('github').api(json.paging.next).then(
                function(response){
                    console.log("retrieving next page of repos...");
                    // and handle the repos
                    addAllRepos(target, response, done, error);
                },
                function(e) {
                    // If there is an error, report it
                    error(e);
                });
        }
        else {
            // If there are no more pages of repos, send them to the caller
            done(target);
        }
    }

    // Clear out the list of repos
    gitHub.repos = [];

    // Make sure that the user is logged in
    gitHub.ensureLogin (function () {
        // Then request the user's repos
        hello('github').api('/user/repos').then(
            function(response){
                // Once the repos are received, add them to the repo list
                addAllRepos(gitHub.repos, response, done, error);
            },
            function (e) {
                // If there was an error, report it
                error(e);
            });
    },
    function(e) {
        // If there was an error logging in, report it
        error(e);
    });
};

/*
 * Load the files from a github repo into a FileManager
 */
gitHub.loadRepo = function(fileManager, repo) {
    var branch = repo.branches_url.replace(/\{.*\}/, "/" + repo.default_branch);
    hello('github').api(branch).then(function(response) {
        fileManager.empty();
        var folder = fileManager.getRootFolder();
        gitHub.loadTree(folder, response.commit.commit.tree.url, fileManager);
    },
    function(e) {
        alert('Error loading Repo branch: ' + e.error.message);
    });
};

gitHub.loadTree = function(folder, tree, fileManager) {
    console.log(tree);
    hello('github').api(tree).then(function(response) {
        response.tree.forEach(item)(function(item){
            if (item.type === "tree") {
                console.log("Tree: " + item.path);
                var subFolder = Folder(item.path, tree);
                gitHub.loadTree(subFolder, item.url, fileManager);
            }
            else if (item.type == "blob") {
                gitHub.loadFile(folder, item.path, item.url);
            }
        });

        fileManager.updateDisplay();

        // If there are more pages of items in the tree,
        if (response.paging && response.paging.next) {
            gitHub.loadTree(folder, response.paging.next, fileManager);
        }
    },
    function (e){
        alert("Error loading tree: " + e.error.message);
    });
};

gitHub.loadFile = function(folder, name, url) {
    hello('github').api(url).then(function(response) {
        console.log("File: " + name);

        var content = window.btoa(response.content);
        var file = SourceFile(name, content);
        folder.addFile(file);
    },
    function(e) {
        alert("Error loading file: " + e.error.message);
    });
};

/*
 * Callback for auth session starts
 */
function sessionStart() {
    hello('github').api('/me').then(function(json) {
        gitHub.username = json.login;
        gitHub.repos_url = json.repos_url;
    },
    function(e) {

    });
}

/*
 * Prepare for oauth login to github
 */
hello.init({github: 'b80ec7eaa799156bba33'},
           {redirect_uri: 'https://run.mycode.run/redirect.html',
            oauth_proxy: 'https://auth-server.herokuapp.com/proxy'});

hello.on('auth.login', sessionStart);<|endoftext|>


<commit_before>/* @flow */

import React from 'react';
import { connect } from 'react-redux';
import { actions } from 'react-redux-form';
import _get from 'lodash.get';

const alertIcons = {
  danger: ,
  warning: ,
  success: ,
};

const TextInputComponent = ({
  label,
  value,
  onChange,
  style,
  type = 'text',
  prefix,
  suffix,
  placeholder,
  alerts,
}: {
  label: ?string,
  value: ?string,
  onChange: (newValue: string) => void,
  style: ?Object,
  type: string,
  prefix: ?string,
  suffix: ?string,
  placeholder: ?string,
  alerts: ?Array<Object>,
}) => {
  const hasAddons = prefix || suffix;

  let alert = null;
  const overrideStyle = {};
  if (type === 'number' && alerts) {
    const numValue = parseFloat(value);

    alert = alerts.find(al =>
      ((al.range[0] == null || numValue >= al.range[0])
        && (al.range[1] == null || al.range[1] > numValue)));

    if (style && style.width) {
      overrideStyle.width = style.width + 32;
    }
  }

  return (

      {label && {label}}

        {prefix &&

            {prefix}

        }

          <input
            type={type}
            className="input"
            style={{
              ...style,
              ...overrideStyle,
            }}
            placeholder={placeholder}
            value={value || ''}
            onChange={e => onChange(e.target.value)}
          />
          {alert ? alertIcons[alert.type] : }

        {suffix &&

            {suffix}

        }

  );
};

const mapStateToProps = (state, ownProps) => ({
  value: _get(state, ownProps.model),
});
const mapDispatchToProps = (dispatch, ownProps) => ({
  onChange: (newValue) => dispatch(actions.change(ownProps.model, newValue)),
});

export const TextInput = connect(
  mapStateToProps, mapDispatchToProps
)(TextInputComponent);
<commit_msg>(refs #103) Add readonly prop to TextInput<commit_after>/* @flow */

import React from 'react';
import { connect } from 'react-redux';
import { actions } from 'react-redux-form';
import _get from 'lodash.get';

const alertIcons = {
  danger: ,
  warning: ,
  success: ,
};

const ReadOnly = ({
  label,
  value,
  prefix,
  suffix,
}: {
  label: ?string,
  value: ?string,
  prefix: ?string,
  suffix: ?string,
}) => (

    {label && {label}}

{[prefix, value, suffix].join(' ')}

);

const TextInputComponent = ({
  label,
  value,
  onChange,
  style,
  type = 'text',
  prefix,
  suffix,
  placeholder,
  alerts,
  readonly = false,
}: {
  label: ?string,
  value: ?string,
  onChange: (newValue: string) => void,
  style: ?Object,
  type: string,
  prefix: ?string,
  suffix: ?string,
  placeholder: ?string,
  alerts: ?Array<Object>,
  readonly: boolean,
}) => {
  if (readonly) {
    return <ReadOnly label={label} value={value} prefix={prefix} suffix={suffix} />;
  }

  const hasAddons = prefix || suffix;

  let alert = null;
  const overrideStyle = {};
  if (type === 'number' && alerts) {
    const numValue = parseFloat(value);

    alert = alerts.find(al =>
      ((al.range[0] == null || numValue >= al.range[0])
        && (al.range[1] == null || al.range[1] > numValue)));

    if (style && style.width) {
      overrideStyle.width = style.width + 32;
    }
  }

  return (

      {label && {label}}

        {prefix &&

            {prefix}

        }

          <input
            type={type}
            className="input"
            style={{
              ...style,
              ...overrideStyle,
            }}
            placeholder={placeholder}
            value={value || ''}
            onChange={e => onChange(e.target.value)}
          />
          {alert ? alertIcons[alert.type] : }

        {suffix &&

            {suffix}

        }

  );
};

const mapStateToProps = (state, ownProps) => ({
  value: _get(state, ownProps.model),
});
const mapDispatchToProps = (dispatch, ownProps) => ({
  onChange: (newValue) => dispatch(actions.change(ownProps.model, newValue)),
});

export const TextInput = connect(
  mapStateToProps, mapDispatchToProps
)(TextInputComponent);
<|endoftext|>


<commit_before>angular.module('<%- moduleName %>')
  .controller('<%- moduleName %><%- state.name %>Controller',
		  ['$rootScope','$scope','$state','$stateParams','$location', 'RestService', 'SocketService',
		   function ($rootScope,$scope,$state,$stateParams,$location, RestService, SocketService) {
			  <%var directiveData = {};
			  var createDirectives = function(dataObject, elements){
			  	for(element in elements){
			  		if(elements[element].components){
			  			dataObject[element] = {};
			  			createDirectives(dataObject[element], elements[element].components.elements);
			  		}else{
			  			var elementData = elements[element];
			  			dataObject[element] = elementData;
			  			dataObject[element]['answer'] = '';
			  		}
			  	}%>
			  <%}
			  createDirectives(directiveData, state.components.elements);%>

			  $scope.directiveData = <%= JSON.stringify(directiveData,null,2)%>;

			  $scope.getData = function(nestedArray){
			    console.log(nestedArray);
			  }

			  var answers = {};
        function returnAnswers(dataObject, answersObject){
          switch(dataObject.constructor.name.toLowerCase()) {
            case 'array':
              for(var i=0; i<dataObject.length; i++){
                answersObject[i] = {};
                returnAnswers(dataObject[i], answersObject[i]);
              }
              break;
          }
          for(key in dataObject){
            if(dataObject[key]){
              if(dataObject[key].answer || dataObject[key].answer == ''){
                if(dataObject[key].typeRef){
                  dataObject[key].answer = dataObject[key].answer._id;
                }
                answersObject[key] = dataObject[key].answer;
              }else{
                switch(dataObject[key].constructor.name.toLowerCase()) {
                  case 'array':
                    answersObject[key] = [];
                    returnAnswers(dataObject[key], answersObject[key]);
                    break;
                  case 'object':
                    answersObject[key] = {};
                    returnAnswers(dataObject[key], answersObject[key]);
                    break;
                }
              }
            }
          }
          return answers;
        }

$scope.submitForm = function(type){
	var data = returnAnswers($scope.directiveData, answers);
	type = type.replace('_', '').toLowerCase();
	if(type == 'init'){
		$scope.init<%- moduleName %>Conversation(data);
	}else{
		var conversation = 'on_' + type.replace(/\./g,'');
		console.log(conversation);
		$scope[conversation](data);
	}
}
}]);<commit_msg>removed blank objects and empty strings<commit_after>angular.module('<%- moduleName %>')
  .controller('<%- moduleName %><%- state.name %>Controller',
		  ['$rootScope','$scope','$state','$stateParams','$location', 'RestService', 'SocketService',
		   function ($rootScope,$scope,$state,$stateParams,$location, RestService, SocketService) {
			  <%var directiveData = {};
			  var createDirectives = function(dataObject, elements){
			  	for(element in elements){
			  		if(elements[element].components){
			  			dataObject[element] = {};
			  			createDirectives(dataObject[element], elements[element].components.elements);
			  		}else{
			  			var elementData = elements[element];
			  			dataObject[element] = elementData;
			  			dataObject[element]['answer'] = '';
			  		}
			  	}%>
			  <%}
			  createDirectives(directiveData, state.components.elements);%>

			  $scope.directiveData = <%= JSON.stringify(directiveData,null,2)%>;

			  $scope.getData = function(nestedArray){
			    console.log(nestedArray);
			  }

			  var answers = {};
			  function returnAnswers(dataObject, answersObject, prevObject, prevKey){
          switch(dataObject.constructor.name.toLowerCase()) {
            case 'array':
              for(var i=0; i<dataObject.length; i++){
                answersObject[i] = {};
                returnAnswers(dataObject[i], answersObject[i], answersObject, key);
              }
              break;
          }
          for(key in dataObject){
            if(dataObject[key]){
              if(dataObject[key].answer){
                if(dataObject[key].typeRef){
                  dataObject[key].answer = dataObject[key].answer._id;
                }
                if(dataObject[key].answer != ''){
                  answersObject[key] = dataObject[key].answer;
                }else{
                  delete answersObject[key];
                }
              }else{
                switch(dataObject[key].constructor.name.toLowerCase()) {
                case 'array':
                  answersObject[key] = [];
                  returnAnswers(dataObject[key], answersObject[key], answersObject, key);
                  break;
                case 'object':
                  if(key != 'ui'){
                    answersObject[key] = {};
                    returnAnswers(dataObject[key], answersObject[key], answersObject, key);
                  }
                  break;
                default:
                  if(prevObject && prevObject[prevKey]){
                    delete prevObject[prevKey];
                  }
                  break;
              }
              }
            }
          }
          return answers;
        }
        function cleanData(answerObject){
          for(key in answerObject){
              if(answerObject[key].constructor.name.toLowerCase() == 'object'){
                if($.isEmptyObject(answerObject[key])){
                  delete answerObject[key];
                }else{
                  cleanData(answerObject[key]);
                }
              }
          }
          return answerObject
       }
$scope.submitForm = function(type){
	var data = returnAnswers($scope.directiveData, answers);
	data = cleanData(data);
	type = type.replace('_', '').toLowerCase();
	if(type == 'init'){
		$scope.init<%- moduleName %>Conversation(data);
	}else{
		var conversation = 'on_' + type.replace(/\./g,'');
		console.log(conversation);
		$scope[conversation](data);
	}
}
}]);<|endoftext|>