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

  define([
      'app',
      'utils/parseLinkHeader',
      'utils/sortBuildList',
      'directives/radialProgressBar',
      'directives/timeSince'], function(app, parseLinkHeader, sortBuildList) {
    var authorBuildListCtrl = function(initialBuildList, $scope, $rootScope, $http, Stream) {

      var stream,
          entrypoint = '/api/0/authors/me/builds/';

      function addBuild(data) {
        $scope.$apply(function() {
          var updated = false,
              item_id = data.id,
              attr, result, item;

          if ($scope.builds.length > 0) {
            result = $.grep($scope.builds, function(e){ return e.id == item_id; });
            if (result.length > 0) {
              item = result[0];
              for (attr in data) {
                // ignore dateModified as we're updating this frequently and it causes
                // the dirty checking behavior in angular to respond poorly
                if (item[attr] != data[attr] && attr != 'dateModified') {
                  updated = true;
                  item[attr] = data[attr];
                }
                if (updated) {
                  item.dateModified = data.dateModified;
                }
              }
            }
          }
          if (!updated) {
            $scope.builds.unshift(data);
            sortBuildList($scope.builds);
            $scope.builds = $scope.builds.slice(0, 100);
          }
        });
      }

      function loadBuildList(url) {
        if (!url) {
          return;
        }
        $http.get(url)
          .success(function(data, status, headers){
            $scope.builds = sortBuildList(data);
            $scope.pageLinks = parseLinkHeader(headers('Link'));
          });
      }

      $scope.loadPreviousPage = function() {
        $(document.body).scrollTop(0);
        loadBuildList($scope.pageLinks.previous);
      };

      $scope.loadNextPage = function() {
        $(document.body).scrollTop(0);
        loadBuildList($scope.pageLinks.next);
      };

      $scope.$watch("pageLinks", function(value) {
        $scope.nextPage = value.next || null;
        $scope.previousPage = value.previous || null;
      });

      $scope.pageLinks = parseLinkHeader(initialBuildList.headers('Link'));

      $scope.builds = sortBuildList(initialBuildList.data.builds);
      $rootScope.pageTitle = 'My Builds';

      $scope.getBuildStatus = function(build) {
        if (build.status.id == 'finished') {
          return build.result.name;
        } else {
          return build.status.name;
        }
      };

      stream = new Stream($scope, entrypoint);
      stream.subscribe('build.update', addBuild);

    };

    app.controller('authorBuildListCtrl', ['initialBuildList', '$scope', '$rootScope', '$http', 'stream', authorBuildListCtrl]);

    return authorBuildListCtrl;
  });
})();
<commit_msg>Bad ref to builds<commit_after>(function(){
  'use strict';

  define([
      'app',
      'utils/parseLinkHeader',
      'utils/sortBuildList',
      'directives/radialProgressBar',
      'directives/timeSince'], function(app, parseLinkHeader, sortBuildList) {
    var authorBuildListCtrl = function(initialBuildList, $scope, $rootScope, $http, Stream) {

      var stream,
          entrypoint = '/api/0/authors/me/builds/';

      function addBuild(data) {
        $scope.$apply(function() {
          var updated = false,
              item_id = data.id,
              attr, result, item;

          if ($scope.builds.length > 0) {
            result = $.grep($scope.builds, function(e){ return e.id == item_id; });
            if (result.length > 0) {
              item = result[0];
              for (attr in data) {
                // ignore dateModified as we're updating this frequently and it causes
                // the dirty checking behavior in angular to respond poorly
                if (item[attr] != data[attr] && attr != 'dateModified') {
                  updated = true;
                  item[attr] = data[attr];
                }
                if (updated) {
                  item.dateModified = data.dateModified;
                }
              }
            }
          }
          if (!updated) {
            $scope.builds.unshift(data);
            sortBuildList($scope.builds);
            $scope.builds = $scope.builds.slice(0, 100);
          }
        });
      }

      function loadBuildList(url) {
        if (!url) {
          return;
        }
        $http.get(url)
          .success(function(data, status, headers){
            $scope.builds = sortBuildList(data);
            $scope.pageLinks = parseLinkHeader(headers('Link'));
          });
      }

      $scope.loadPreviousPage = function() {
        $(document.body).scrollTop(0);
        loadBuildList($scope.pageLinks.previous);
      };

      $scope.loadNextPage = function() {
        $(document.body).scrollTop(0);
        loadBuildList($scope.pageLinks.next);
      };

      $scope.$watch("pageLinks", function(value) {
        $scope.nextPage = value.next || null;
        $scope.previousPage = value.previous || null;
      });

      $scope.pageLinks = parseLinkHeader(initialBuildList.headers('Link'));

      $scope.builds = sortBuildList(initialBuildList.data);
      $rootScope.pageTitle = 'My Builds';

      $scope.getBuildStatus = function(build) {
        if (build.status.id == 'finished') {
          return build.result.name;
        } else {
          return build.status.name;
        }
      };

      stream = new Stream($scope, entrypoint);
      stream.subscribe('build.update', addBuild);

    };

    app.controller('authorBuildListCtrl', ['initialBuildList', '$scope', '$rootScope', '$http', 'stream', authorBuildListCtrl]);

    return authorBuildListCtrl;
  });
})();
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  parser: 'typescript-eslint-parser',
  plugins: ['typescript'],

  settings: {
    'import/resolver': {
      node: {
        extensions: ['.mjs', '.js', '.json', '.ts'],
      },
    },
    'import/extensions': ['.js', '.mjs', '.ts'],

    'import/core-modules': [
      'pob-babel', // import typings
    ],
  },

  rules: {
    'import/extensions': ['error', { extensions: ['ts', 'js'] }],

    // typescript plugin
    'typescript/adjacent-overload-signatures': 'error',
    'typescript/member-ordering': 'error',
    'typescript/no-angle-bracket-type-assertion': 'error',
    'typescript/no-array-constructor': 'error',

    // interface can be used for empty props
    'typescript/no-empty-interface': 'off',
    'typescript/no-namespace': 'error',
    'typescript/no-unused-vars': 'error',
    'typescript/no-use-before-define': 'error',
    'typescript/no-var-requires': 'error',

    // issues
    'no-undef': 'off',
    // https://github.com/eslint/typescript-eslint-parser/issues/414
    'no-restricted-globals': 'off',
    // issue with generics
    'no-unused-vars': 'off',
  },
};
<commit_msg>fix(typescript): disable no-use-before-define<commit_after>'use strict';

module.exports = {
  parser: 'typescript-eslint-parser',
  plugins: ['typescript'],

  settings: {
    'import/resolver': {
      node: {
        extensions: ['.mjs', '.js', '.json', '.ts'],
      },
    },
    'import/extensions': ['.js', '.mjs', '.ts'],

    'import/core-modules': [
      'pob-babel', // import typings
    ],
  },

  rules: {
    'import/extensions': ['error', { extensions: ['ts', 'js'] }],

    /* issues */
    'no-undef': 'off',
    // https://github.com/eslint/typescript-eslint-parser/issues/414
    'no-restricted-globals': 'off',
    // issue with generics
    'no-unused-vars': 'off',
    // issue when reexporting types
    'no-use-before-define': 'off',

    /* typescript plugin */
    'typescript/adjacent-overload-signatures': 'error',
    'typescript/member-ordering': 'error',
    'typescript/no-angle-bracket-type-assertion': 'error',
    'typescript/no-array-constructor': 'error',
    'typescript/no-use-before-define': 'error',
    'typescript/no-var-requires': 'error',

    // interface can be used for empty props
    'typescript/no-empty-interface': 'off',

    /* doesn't work without base rule */
    'typescript/no-namespace': 'off',
    'typescript/no-unused-vars': 'off',
  },
};
<|endoftext|>


<commit_before>/*jslint nomen: false, onevar: false */
/*global window: false, _: false, lib: false */

// lib.model(_public, _protected, attribute_name_one, attribute_name_two, ...)
// makes this object a model object with accessor methods for named attributes,
// events when attribute values change, etc.
//
lib.model = function (_public, _protected, declared_attributes) {
    _protected.attributes = _protected.attributes || {};

    // Event methods:
    // onChange(function () { ... }) and
    // triggerChange()
    lib.hasEvent(_public, _protected, 'change');

    // Allow either lib.model(_p, _p, ['a','b','c']);
    //           or lib.model(_p, _p, 'a', 'b', 'c');
    //
    // The latter is more pleasant to interact with as a human,
    // the former is better for automated interaction.
    if (!_(declared_attributes).isArray()) {
        declared_attributes = _(arguments).toArray().slice(2);
    }

    _(declared_attributes).each(function (name) {
        // If attribute foo is declared, this generates the event methods:
        // onFooChange(function (new_value) { ... }) and
        // triggerFooChange(new_value)
        var change_event_name = name + '_change';
        lib.hasEvent(_public, _protected, change_event_name);
        _public.on(change_event_name, function (new_value) {
            _public.transactionalTrigger('change');
        });

        // Define getter/setter for the attribute.
        // See http://ejohn.org/blog/javascript-getters-and-setters/
        //
        // So you can write (e.g.):
        //     person.name = "Bob";
        //     print(person.name);

        _public.__defineGetter__(name, function () {
            return _protected.attributes[name];
        });
        _public.__defineSetter__(name, function (new_value) {
            return _protected.setAttribute(name, new_value, new_value !== _public[name]);
        });

        // Define delayed setter for the attribute. (see setAttributeLater)
        _public['set' + _(name).camelize() + 'Later'] = function (new_value) {
            _public.setAttributeLater(name, new_value);
        };
    });

    // Set the attribute with the given name to the given value, and trigger the change
    // event if required.
    _protected.setAttribute = function (name, new_value, trigger_change) {
        _protected.attributes[name] = new_value;
        if (trigger_change) {
            _public.transactionalTrigger(name + '_change', new_value);
        }
    };

    // With no arguments, returns a hash of attributes. (Please don't modify it!)
    // With one argument (a hash), bulk-assigns the attributes given in the hash, and
    // doesn't modify attributes not mentioned in the hash.
    _public.attributes = function (new_attributes) {
        return _public.transaction(function () {
            if (typeof(new_attributes) !== 'undefined') {
                for (var attribute in new_attributes) {
                    if (new_attributes.hasOwnProperty(attribute)) {
                        _public[attribute] = new_attributes[attribute];
                    }
                }
            }
            return _protected.attributes;
        });
    };

    _public.unbuild = function () {
        var obj = {};
        _(_protected.attributes).each(function (attr, name) {
            obj[name] = _(attr.unbuild).isFunction() ? attr.unbuild() : attr;
        });
        return obj;
    };

    // Sets the attribute with the first argument's name to the second argument, but delays
    // that action until the current call stack has completed. Useful if we want to trigger
    // a change of value eventually, but don't want it affecting other handlers of the event
    // currently being handled.
    _public.setAttributeLater = function (name, new_value) {
        window.setTimeout(function () {
            _public[name] = new_value;
        }, 0);
    };

    // Bind this model to a particular attribute event of a container model.
    // i.e. when a change event fires on this model, a change event will fire on the container's
    // attribute.
    _public.bindTo = function (parent, attribute) {
        _public.onChange(function () {
            parent.trigger(attribute + '_change', _public);
        });
        parent.trigger(attribute + '_change', _public);
        return _public;
    };

    // If the attribute with name `name` currently has a value of `expected_value`, calls the
    // callback immediately; otherwise waits until the attribute is set to that value, and then
    // calls the callback once. Doesn't call the callback more than once.
    _public.whenEqual = function (name, expected_value, callback) {
        if (_public[name] === expected_value) {
            callback.call(_public);
        } else {
            _protected.when_equal = _protected.when_equal || {};
            if (_protected.when_equal[name]) {
                _protected.when_equal[name].push({expected_value: expected_value, callback: callback});
            } else {
                _protected.when_equal[name] = [{expected_value: expected_value, callback: callback}];

                _public.on(name + '_change', function (new_value) {
                    _protected.when_equal[name] = _(_protected.when_equal[name]).reject(function (item) {
                        if (item.expected_value === new_value) {
                            item.callback.call(_public);
                            return true;
                        }
                    });
                });
            }
        }
        return _public;
    };

    // If the attribute with name `name` currently has a value of `expected_value`, calls the
    // callback immediately. Whenever in future the attribute is changed from something else to
    // `expected_value`, the callback is called again.
    _public.wheneverEqual = function (name, expected_value, callback) {
        if (_public[name] === expected_value) {
            callback.call(_public);
        }
        return _public.on(name + '_change', function (new_value) {
            if (new_value === expected_value) {
                callback.call(_public);
            }
        });
    };

    // Make modifications to the model "atomically". Any listeners will
    // not get notified until after the modifications are complete.
    //
    // This is used by .attributes(), to ensure that when callbacks get
    // fired, the model is in a consistent state on each callback.
    //
    // TODO: We could improve this mechanism to be correctly re-entrant.
    _public.transaction = function (func) {
        if (!_protected.transaction_queue) {
            _protected.transaction_queue = [];
        }
        var ret = func();

        while (_protected.transaction_queue.length) {
            // .splice(0) takes a copy of the contents of the array
            // and empties the array. If anything else does a transactionalTrigger
            // within these callbacks, it'll be added to the emptied _protected.transaction_queue.
            _(_protected.transaction_queue.splice(0)).invoke('call');
        }

        _protected.transaction_queue = null;

        // This happens outside of the transaction so that we can guarantee it happens
        // once (and only once) per transaction. (Otherwise we'd have to run this multiple
        // times in the same transaction if the onChange handlers also triggered changes).
        if (_protected.transaction_triggered_change) {
            _protected.transaction_triggered_change = false;
            _public.triggerChange();
        }
        return ret;
    };

    // Like .trigger(), but if there are transactions in process,
    // defer the triggering until after it completes.
    _public.transactionalTrigger = function () {
        var thiz =  this,
            args = arguments;

        if (_protected.transaction_queue) {
            // We want to debounce the onChange handler within a transaction, though
            // we don't want to debounce other on*Change events.
            if (args[0] === 'change') {
                _protected.transaction_triggered_change = true;
            } else {
                _protected.transaction_queue.push(function () {
                    _public.trigger.apply(thiz, args);
                });
            }
        } else {
            _public.trigger.apply(thiz, args);

        }
    };

    // If a model wants to support deep cloning, it can call cloneable, passing the
    // model's constructor function (which will be used to create cloned instances).
    // This generates a public clone() method on the model.
    _protected.cloneable = function (model_class) {

        // Keep track of original objects and their clones. Because JavaScript coerces
        // all object keys to be strings, this uses an array of [original, clone] pairs
        // which needs to be scanned linearly. Oh noes, O(n^2) badness! :(
        var clone_cache;

        function deepClone(thing) {
            if (typeof(thing) !== 'object' || thing === null) {
                return thing;
            }
            if (_(thing).isArray()) {
                return _(thing).map(deepClone);
            }

            // 'thing' is an object, but not an array. First try the cache, to resolve circular references.
            var cached = _(clone_cache).detect(function (pair) {
                return pair[0] === thing;
            });
            if (cached) {
                return cached[1];
            }

            // Nothing in the cache. Actually clone the thing.
            var clone;
            if (typeof(thing.clone) === 'function') {
                clone = thing.clone({clone_cache: clone_cache});
            } else {
                clone = {};
                clone_cache.push([thing, clone]);

                _(thing).each(function (attr, name) {
                    clone[name] = deepClone(attr);
                });
            }
            return clone;
        }

        _public.clone = function (options) {
            var clone = model_class();
            clone_cache = options && options.clone_cache || [];
            clone_cache.push([_public, clone]);
            _(_protected.attributes).each(function (attr, name) {
                clone[name] = deepClone(attr);
            });
            return clone;
        };
    };

    return _public;
};

// Method to build a new instance of a model from an attributes hash.
//
// To use:
//     models.animal = function(...) {
//         ...
//         lib.model(..., 'name', 'species', 'legs');
//         ...
//     };
//     models.animal.build = lib.model.build;
//
//     var fido = models.animal.build({
//         name: "Fido",
//         species: "dog",
//         legs: 4});
lib.model.build = function (attributes) {
    var obj = this();
    obj.attributes(attributes);
    return obj;
};

// Given a list of attributes, create a simple model that contains them.
lib.model.class_from_attributes = function (attributes) {
    var klass = function () {
        var _public = {}, _protected = {};
        lib.model(_public, _protected, attributes);
        return _public;
    };
    klass.build = lib.model.build;
    return klass;
};

// These are like normal fields except that object eqaulity is used instead
// of exact equality to decide whether or not to fire a change event.
lib.model.usingEquality = function (isEqual) {
    return function (_public, _protected, declared_attributes) {
        lib.model.apply(lib.model, arguments);

        if (!_(declared_attributes).isArray()) {
            declared_attributes = _(arguments).toArray().slice(2);
        }

        _(declared_attributes).each(function (name) {
            _public.__defineSetter__(name, function (new_value) {
                return _protected.setAttribute(name, new_value, !isEqual(new_value, _public[name]));
            });
        });
    };
};
<commit_msg>fix out-of-date comment<commit_after>/*jslint nomen: false, onevar: false */
/*global window: false, _: false, lib: false */

// lib.model(_public, _protected, attribute_name_one, attribute_name_two, ...)
// makes this object a model object with accessor methods for named attributes,
// events when attribute values change, etc.
//
lib.model = function (_public, _protected, declared_attributes) {
    _protected.attributes = _protected.attributes || {};

    // Event methods:
    // onChange(function () { ... }) and
    // triggerChange()
    lib.hasEvent(_public, _protected, 'change');

    // Allow either lib.model(_p, _p, ['a','b','c']);
    //           or lib.model(_p, _p, 'a', 'b', 'c');
    //
    // The latter is more pleasant to interact with as a human,
    // the former is better for automated interaction.
    if (!_(declared_attributes).isArray()) {
        declared_attributes = _(arguments).toArray().slice(2);
    }

    _(declared_attributes).each(function (name) {
        // If attribute foo is declared, this generates the event methods:
        // onFooChange(function (new_value) { ... }) and
        // triggerFooChange(new_value)
        var change_event_name = name + '_change';
        lib.hasEvent(_public, _protected, change_event_name);
        _public.on(change_event_name, function (new_value) {
            _public.transactionalTrigger('change');
        });

        // Define getter/setter for the attribute.
        // See http://ejohn.org/blog/javascript-getters-and-setters/
        //
        // So you can write (e.g.):
        //     person.name = "Bob";
        //     print(person.name);

        _public.__defineGetter__(name, function () {
            return _protected.attributes[name];
        });
        _public.__defineSetter__(name, function (new_value) {
            return _protected.setAttribute(name, new_value, new_value !== _public[name]);
        });

        // Define delayed setter for the attribute. (see setAttributeLater)
        _public['set' + _(name).camelize() + 'Later'] = function (new_value) {
            _public.setAttributeLater(name, new_value);
        };
    });

    // Set the attribute with the given name to the given value, and trigger the change
    // event if required.
    _protected.setAttribute = function (name, new_value, trigger_change) {
        _protected.attributes[name] = new_value;
        if (trigger_change) {
            _public.transactionalTrigger(name + '_change', new_value);
        }
    };

    // With no arguments, returns a hash of attributes. (Please don't modify it!)
    // With one argument (a hash), bulk-assigns the attributes given in the hash, and
    // doesn't modify attributes not mentioned in the hash.
    _public.attributes = function (new_attributes) {
        return _public.transaction(function () {
            if (typeof(new_attributes) !== 'undefined') {
                for (var attribute in new_attributes) {
                    if (new_attributes.hasOwnProperty(attribute)) {
                        _public[attribute] = new_attributes[attribute];
                    }
                }
            }
            return _protected.attributes;
        });
    };

    _public.unbuild = function () {
        var obj = {};
        _(_protected.attributes).each(function (attr, name) {
            obj[name] = _(attr.unbuild).isFunction() ? attr.unbuild() : attr;
        });
        return obj;
    };

    // Sets the attribute with the first argument's name to the second argument, but delays
    // that action until the current call stack has completed. Useful if we want to trigger
    // a change of value eventually, but don't want it affecting other handlers of the event
    // currently being handled.
    _public.setAttributeLater = function (name, new_value) {
        window.setTimeout(function () {
            _public[name] = new_value;
        }, 0);
    };

    // Bind this model to a particular attribute event of a container model.
    // i.e. when a change event fires on this model, a change event will fire on the container's
    // attribute.
    _public.bindTo = function (parent, attribute) {
        _public.onChange(function () {
            parent.trigger(attribute + '_change', _public);
        });
        parent.trigger(attribute + '_change', _public);
        return _public;
    };

    // If the attribute with name `name` currently has a value of `expected_value`, calls the
    // callback immediately; otherwise waits until the attribute is set to that value, and then
    // calls the callback once. Doesn't call the callback more than once.
    _public.whenEqual = function (name, expected_value, callback) {
        if (_public[name] === expected_value) {
            callback.call(_public);
        } else {
            _protected.when_equal = _protected.when_equal || {};
            if (_protected.when_equal[name]) {
                _protected.when_equal[name].push({expected_value: expected_value, callback: callback});
            } else {
                _protected.when_equal[name] = [{expected_value: expected_value, callback: callback}];

                _public.on(name + '_change', function (new_value) {
                    _protected.when_equal[name] = _(_protected.when_equal[name]).reject(function (item) {
                        if (item.expected_value === new_value) {
                            item.callback.call(_public);
                            return true;
                        }
                    });
                });
            }
        }
        return _public;
    };

    // If the attribute with name `name` currently has a value of `expected_value`, calls the
    // callback immediately. Whenever in future the attribute is changed from something else to
    // `expected_value`, the callback is called again.
    _public.wheneverEqual = function (name, expected_value, callback) {
        if (_public[name] === expected_value) {
            callback.call(_public);
        }
        return _public.on(name + '_change', function (new_value) {
            if (new_value === expected_value) {
                callback.call(_public);
            }
        });
    };

    // Make modifications to the model "atomically". Any listeners will
    // not get notified until after the modifications are complete.
    //
    // This is used by .attributes(), to ensure that when callbacks get
    // fired, the model is in a consistent state on each callback.
    //
    // TODO: We could improve this mechanism to be correctly re-entrant.
    _public.transaction = function (func) {
        if (!_protected.transaction_queue) {
            _protected.transaction_queue = [];
        }
        var ret = func();

        while (_protected.transaction_queue.length) {
            // .splice(0) takes a copy of the contents of the array
            // and empties the array. If anything else does a transactionalTrigger
            // within these callbacks, it'll be added to the emptied _protected.transaction_queue.
            _(_protected.transaction_queue.splice(0)).invoke('call');
        }

        _protected.transaction_queue = null;

        // This happens outside of the transaction so that we can guarantee it happens
        // once (and only once) per transaction. (Otherwise we'd have to run this multiple
        // times in the same transaction if the onChange handlers also triggered changes).
        if (_protected.transaction_triggered_change) {
            _protected.transaction_triggered_change = false;
            _public.triggerChange();
        }
        return ret;
    };

    // Like .trigger(), but if there are transactions in process,
    // defer the triggering until after it completes.
    _public.transactionalTrigger = function () {
        var thiz =  this,
            args = arguments;

        if (_protected.transaction_queue) {
            // We want to debounce the onChange handler within a transaction, though
            // we don't want to debounce other on*Change events.
            if (args[0] === 'change') {
                _protected.transaction_triggered_change = true;
            } else {
                _protected.transaction_queue.push(function () {
                    _public.trigger.apply(thiz, args);
                });
            }
        } else {
            _public.trigger.apply(thiz, args);

        }
    };

    // If a model wants to support deep cloning, it can call cloneable, passing the
    // model's constructor function (which will be used to create cloned instances).
    // This generates a public clone() method on the model.
    _protected.cloneable = function (model_class) {

        // Keep track of original objects and their clones. Because JavaScript coerces
        // all object keys to be strings, this uses an array of [original, clone] pairs
        // which needs to be scanned linearly. Oh noes, O(n^2) badness! :(
        var clone_cache;

        function deepClone(thing) {
            if (typeof(thing) !== 'object' || thing === null) {
                return thing;
            }
            if (_(thing).isArray()) {
                return _(thing).map(deepClone);
            }

            // 'thing' is an object, but not an array. First try the cache, to resolve circular references.
            var cached = _(clone_cache).detect(function (pair) {
                return pair[0] === thing;
            });
            if (cached) {
                return cached[1];
            }

            // Nothing in the cache. Actually clone the thing.
            var clone;
            if (typeof(thing.clone) === 'function') {
                clone = thing.clone({clone_cache: clone_cache});
            } else {
                clone = {};
                clone_cache.push([thing, clone]);

                _(thing).each(function (attr, name) {
                    clone[name] = deepClone(attr);
                });
            }
            return clone;
        }

        _public.clone = function (options) {
            var clone = model_class();
            clone_cache = options && options.clone_cache || [];
            clone_cache.push([_public, clone]);
            _(_protected.attributes).each(function (attr, name) {
                clone[name] = deepClone(attr);
            });
            return clone;
        };
    };

    return _public;
};

// Method to build a new instance of a model from an attributes hash.
//
// To use:
//     models.animal = function(...) {
//         ...
//         lib.model(..., 'name', 'species', 'legs');
//         ...
//     };
//     models.animal.build = lib.model.build;
//
//     var fido = models.animal.build({
//         name: "Fido",
//         species: "dog",
//         legs: 4});
lib.model.build = function (attributes) {
    var obj = this();
    obj.attributes(attributes);
    return obj;
};

// Given a list of attributes, create a simple model that contains them.
lib.model.class_from_attributes = function (attributes) {
    var klass = function () {
        var _public = {}, _protected = {};
        lib.model(_public, _protected, attributes);
        return _public;
    };
    klass.build = lib.model.build;
    return klass;
};

// Override the equality checking (by default ===) that is used to decide
// whether or not to trigger a change event when a model's property is assigned to.
// This is particular useful in the case of _.isEqual, which gives you deep object
// equality, though other functions are possible (see lib.timestamps for example).
//
// NOTE: An equivalence relation should be *symmetric* *reflexive* and *transitive*,
// other kinds of function will confuse people.
lib.model.usingEquality = function (isEqual) {
    return function (_public, _protected, declared_attributes) {
        lib.model.apply(lib.model, arguments);

        if (!_(declared_attributes).isArray()) {
            declared_attributes = _(arguments).toArray().slice(2);
        }

        _(declared_attributes).each(function (name) {
            _public.__defineSetter__(name, function (new_value) {
                return _protected.setAttribute(name, new_value, !isEqual(new_value, _public[name]));
            });
        });
    };
};
<|endoftext|>


<commit_before>
/*

  Config.js

*/

var Utils  = require("./utils"),
    config = require(Utils.makePathAbsolute("sneakers.config.js"));

// Things like extensions and mime types should be automated
var defaults = {
  fonts: [
    { path : "./fonts",   url : "/fonts",   ext : ["ttf", "otf", "eot", "woff", "svg"] }
  ],
  images: [
    { path : "./images",  url : "/images"  }
  ],
  scripts: [
    { path : "./scripts", url : "/scripts", ext : "js", bundleFolders : true },
  ],
  styles: [
    { path : "./styles",  url : "/styles",  ext : "css" }
  ],
  statics: [
    { path : "./vendor",  url : "/vendor" }
  ],
  views: [
    { path : "./views",   url : "/", ext : "html" }
  ]
};

module.exports = function() {

  // Copy defaults and attach to globals
  config = Object.assign(defaults, config);

  // Store global variables
  global.vars = config.globals || {};
  if (/^prod/.test(process.env.NODE_ENV))
    global.vars = Object.assign(global.vars, config["globals:production"] || {});

  return config;

}
<commit_msg>config: ignores case for production check<commit_after>
/*

  Config.js

*/

var Utils  = require("./utils"),
    config = require(Utils.makePathAbsolute("sneakers.config.js"));

// Things like extensions and mime types should be automated
var defaults = {
  fonts: [
    { path : "./fonts",   url : "/fonts",   ext : ["ttf", "otf", "eot", "woff", "svg"] }
  ],
  images: [
    { path : "./images",  url : "/images"  }
  ],
  scripts: [
    { path : "./scripts", url : "/scripts", ext : "js", bundleFolders : true },
  ],
  styles: [
    { path : "./styles",  url : "/styles",  ext : "css" }
  ],
  statics: [
    { path : "./vendor",  url : "/vendor" }
  ],
  views: [
    { path : "./views",   url : "/", ext : "html" }
  ]
};

module.exports = function() {

  // Copy defaults and attach to globals
  config = Object.assign(defaults, config);

  // Store global variables
  global.vars = config.globals || {};
  if (/^prod/i.test(process.env.NODE_ENV))
    global.vars = Object.assign(global.vars, config["globals:production"] || {});

  return config;

}
<|endoftext|>


<commit_before>/**
 * eventHandler
 *
 * @author Icewind <icewind (at) derideal (dot) com>
 * @copyright 2009
 * @license http://www.gnu.org/licenses/gpl.html GNU Public License
 * @version 0.1
 */

/*event handling
usage:    document.events.add(node,type,function,arguments);
   or:    node.addEvent(type,function,arguments);
*/

document.events=new Object;
document.events.functions=Array();
document.events.args=Array();

document.events.add=function(element,type,func,args){
	if(!element.eventCallBacks){
		element.eventCallBacks=Array();
	}
	if(!element.eventCallBacks[type]){
		element.eventCallBacks[type]=Array();
	}
	if(args){
		if(!args.push){
			args=[args];
		}
	}
	if(!args){
		args=Array();
	}
	args.push('eventHolder');
	args.push('argHolder');
	if (type && element){

		//wrap the function in a function, otherwise it won't work if func is actually a callBack
		var funcId=document.events.functions.length;
		document.events.functions[funcId]=func;
		document.events.args[funcId]=args;
		eval('var callback=function(event,arg){document.events.callback.call(this,'+funcId+',event,arg)};');
		element.eventCallBacks[type].push(callback);
		if(element.addEventListener){
			var eventType=type;
			if(eventType.substr(0,2)=='on'){
				eventType=eventType.substr(2);
			}
			element.addEventListener(eventType,callback,false);
		}else if(element.attachEvent){
			element.attachEvent(type,callback);
		}
		return callback;
	}
}
document.events.remove=function(element,type,func){
	if(element.removeEventListener){
		if(type.substr(0,2)=='on'){
			type=type.substr(2);
		}
		element.removeEventListener(type,func,false);
	}else if(element.detachEvent){
		element.detachEvent(type,func)
	}
}

document.events.callback=function(funcId,event,arg){
	if(!event)var event=window.event;
	var args=document.events.args[funcId];
	args[args.length-2]=event;
	args[args.length-1]=arg;
	result=document.events.functions[funcId].apply(this,args);
	if(result===false){
		if(event.preventDefault){
			event.preventDefault();
		};
	}
	return result;
}

document.events.trigger=function(element,type,event,args){
	var callbacks=element.eventCallBacks[type];
	for(var i=0;i<callbacks.length;i++){
		callbacks[i].call(element,event,args);
	}
}

Node.prototype.addEvent=function(type,func,arguments){
    return document.events.add(this,type,func,arguments);
}
Node.prototype.removeEvent=function(type,func){
    document.events.remove(this,type,func);
}
Node.prototype.triggerEvent=function(type,event,arg){
    return document.events.trigger(this,type,event,arg);
}<commit_msg>cleanup event handling<commit_after>/*event handling
usage:    document.events.add(node,type,function,arguments);
   or:    node.addEvent(type,function,arguments);
*/

document.events=new Object;
document.events.functions=Array();
document.events.args=Array();

document.events.add=function(element,type,func,args){
	if(args){
		if(!args.push){
			args=[args];
		}
	}
	args=args||[];
	if (type && element){
		args.foreach(function(argument){
			func.bind(argument);
		})
		if(element.addEventListener){
			if(type.substr(0,2)=='on'){
				type=type.substr(2);
			}
			element.addEventListener(type,func,false);
		}else if(element.attachEvent){
			element.attachEvent(type,func);
		}
		return func;
	}
}
document.events.remove=function(element,type,func){
	if(element.removeEventListener){
		if(type.substr(0,2)=='on'){
			type=type.substr(2);
		}
		element.removeEventListener(type,func,false);
	}else if(element.detachEvent){
		element.detachEvent(type,func)
	}
}

Node.prototype.addEvent=function(type,func,args){
    return document.events.add(this,type,func,args);
}
Node.prototype.removeEvent=function(type,func){
    document.events.remove(this,type,func);
}<|endoftext|>


<commit_before>// Copyright 2002-2015, University of Colorado

/**
 * C2H2 Molecule
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( function( require ) {
  'use strict';

  // modules
  var AtomNode = require( 'NITROGLYCERIN/nodes/AtomNode' );
  var Element = require( 'NITROGLYCERIN/Element' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Node = require( 'SCENERY/nodes/Node' );
  var Vector2 = require( 'DOT/Vector2' );

  /**
   * @param {Object} [options]
   * @constructor
   */
  function C2H2Node( options ) {

    options = _.extend( { atomOptions: {} }, options );

    // atoms
    var bigLeftNode = new AtomNode( Element.C, options.atomOptions );
    var bigRightNode = new AtomNode( Element.C, _.extend( {
      x: bigLeftNode.right + ( 0.25 * bigLeftNode.width ),
      y: bigLeftNode.y
    }, options.atomOptions ) );
    var smallLeftNode = new AtomNode( Element.H, _.extend( {
      x: bigLeftNode.left,
      y: bigLeftNode.y
    }, options.atomOptions ) );
    var smallRightNode = new AtomNode( Element.H, _.extend( {
      x: bigRightNode.right,
      y: bigLeftNode.y
    }, options.atomOptions ) );

    options.children = [ new Node( {
      children: [ smallLeftNode, bigLeftNode, bigRightNode, smallRightNode ],
      center: Vector2.ZERO // origin at geometric center
    } ) ];
    Node.call( this, options );
  }

  return inherit( Node, C2H2Node );
} );
<commit_msg>#4 reimplement C2H2 as a subtype of HorizontalMoleculeNode<commit_after>// Copyright 2002-2015, University of Colorado

/**
 * C2H2 Molecule
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( function( require ) {
  'use strict';

  // modules
  var Element = require( 'NITROGLYCERIN/Element' );
  var HorizontalMoleculeNode = require( 'NITROGLYCERIN/nodes/HorizontalMoleculeNode' );
  var inherit = require( 'PHET_CORE/inherit' );

  /**
   * @param {Object} [options]
   * @constructor
   */
  function C2H2Node( options ) {
    options = _.extend( {}, options );
    options.overlapPercent = 0.35;
    HorizontalMoleculeNode.call( this, [ Element.H, Element.C, Element.C, Element.H ], options );
  }

  return inherit( HorizontalMoleculeNode, C2H2Node );
} );
<|endoftext|>


<commit_before>// Copyright 2002-2015, University of Colorado

/**
 * C2H4 Molecule
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( function( require ) {
  'use strict';

  // modules
  var AtomNode = require( 'NITROGLYCERIN/nodes/AtomNode' );
  var Element = require( 'NITROGLYCERIN/Element' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Node = require( 'SCENERY/nodes/Node' );
  var Vector2 = require( 'DOT/Vector2' );

  /**
   * @param {Object} [options]
   * @constructor
   */
  function C2H4Node( options ) {

    options = _.extend( { atomOptions: {} }, options );

    // atoms
    var bigLeftNode = new AtomNode( Element.C, options.atomOptions );
    var bigRightNode = new AtomNode( Element.C, options.atomOptions );
    var smallTopLeftNode = new AtomNode( Element.H, options.atomOptions );
    var smallTopRightNode = new AtomNode( Element.H, options.atomOptions );
    var smallBottomLeftNode = new AtomNode( Element.H, options.atomOptions );
    var smallBottomRightNode = new AtomNode( Element.H, options.atomOptions );

    // layout
    var offsetSmall = smallTopLeftNode.width / 4;
    bigRightNode.x = bigLeftNode.right + ( 0.25 * bigRightNode.width );
    bigRightNode.y = bigLeftNode.y;
    smallTopLeftNode.x = bigLeftNode.left + offsetSmall;
    smallTopLeftNode.y = bigLeftNode.top + offsetSmall;
    smallTopRightNode.x = bigRightNode.right - offsetSmall;
    smallTopRightNode.y = bigRightNode.top + offsetSmall;
    smallBottomLeftNode.x = bigLeftNode.left + offsetSmall;
    smallBottomLeftNode.y = bigLeftNode.bottom - offsetSmall;
    smallBottomRightNode.x = bigRightNode.right - offsetSmall;
    smallBottomRightNode.y = bigRightNode.bottom - offsetSmall;

    options.children = [ new Node( {
      children: [ smallTopRightNode, smallTopLeftNode, bigLeftNode, bigRightNode, smallBottomLeftNode, smallBottomRightNode ],
      center: Vector2.ZERO // origin at geometric center
    } ) ];
    Node.call( this, options );
  }

  return inherit( Node, C2H4Node );
} );
<commit_msg>#4 handle layout in options for C2H4<commit_after>// Copyright 2002-2015, University of Colorado

/**
 * C2H4 Molecule
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( function( require ) {
  'use strict';

  // modules
  var AtomNode = require( 'NITROGLYCERIN/nodes/AtomNode' );
  var Element = require( 'NITROGLYCERIN/Element' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Node = require( 'SCENERY/nodes/Node' );
  var Vector2 = require( 'DOT/Vector2' );

  /**
   * @param {Object} [options]
   * @constructor
   */
  function C2H4Node( options ) {

    options = _.extend( { atomOptions: {} }, options );

    // atoms
    var bigLeftNode = new AtomNode( Element.C, options.atomOptions );
    var smallOffset = 0.165 * bigLeftNode.width;
    var bigRightNode = new AtomNode( Element.C, _.extend( {
      x: bigLeftNode.right + ( 0.25 * bigLeftNode.width ),
      y: bigLeftNode.y
    }, options.atomOptions ) );
    var smallTopLeftNode = new AtomNode( Element.H, _.extend( {
      x: bigLeftNode.left + smallOffset,
      y: bigLeftNode.top + smallOffset
    }, options.atomOptions ) );
    var smallTopRightNode = new AtomNode( Element.H, _.extend( {
      x: bigRightNode.right - smallOffset,
      y: bigRightNode.top + smallOffset
    }, options.atomOptions ) );
    var smallBottomLeftNode = new AtomNode( Element.H, _.extend( {
      x: bigLeftNode.left + smallOffset,
      y: bigLeftNode.bottom - smallOffset
    }, options.atomOptions ) );
    var smallBottomRightNode = new AtomNode( Element.H, _.extend( {
      x: bigRightNode.right - smallOffset,
      y: bigRightNode.bottom - smallOffset
    }, options.atomOptions ) );

    options.children = [ new Node( {
      children: [ smallTopRightNode, smallTopLeftNode, bigLeftNode, bigRightNode, smallBottomLeftNode, smallBottomRightNode ],
      center: Vector2.ZERO // origin at geometric center
    } ) ];
    Node.call( this, options );
  }

  return inherit( Node, C2H4Node );
} );
<|endoftext|>


<commit_before>function Metronome(tempo, beatsPerMeasure, subdivisions){
  this.tempo = Number(tempo);
  this.beatsPerMeasure = Number(beatsPerMeasure);
  this.subdivisions = subdivisions;
  this.interval = null;
  this.tempoInMilliseconds = this.tempoToMilliseconds(this.tempo);
}

Metronome.prototype.start = function(){
  this.interval = window.setInterval(this.changeSoundAndView.bind(this), this.tempoInMilliseconds, this);
}

Metronome.prototype.tempoToMilliseconds = function(tempo){
  return (1000 * 60)/tempo;
}

Metronome.prototype.stop = function(){
  window.clearInterval(this.interval);
  var counter = document.getElementById("metronome-counter");
  counter.innerHTML = "";
}

Metronome.prototype.changeSoundAndView = function(metronome){
  this.moveStick();
  this.updateCounterView();
  playSounds(metronome);
}

playSounds = function(metronome){
  playSound(metronome, 'audio/beep-07.wav');
  for (var i = 0; i < metronome.subdivisions.length; i++){
    createSubdivisions(metronome, metronome.subdivisions[i]);
  }
}

createSubdivisions = function(metronome, divideTheBeatIn){
  var subdivisionsInMilliseconds = (metronome.tempoInMilliseconds)/divideTheBeatIn;
  var i = 1;
  var subdivisions = window.setInterval(function(){ i++;
    playSound(metronome, 'audio/beep-07.wav')
    if (i == divideTheBeatIn){
      clearInterval(subdivisions);}
    }, subdivisionsInMilliseconds)
}

playSound = function(metronome, fileName){
  new Howl({
    urls: [fileName]
  }).play();
}

Metronome.prototype.updateCounterView = function(){
  var counter = document.getElementById("metronome-counter");
  var pastBeat = Number(counter.innerHTML);
  if (pastBeat < this.beatsPerMeasure){
    counter.innerHTML = pastBeat + 1;
  } else {
    counter.innerHTML = 1;
  }
}

Metronome.prototype.moveStick = function(){
  var stick = $("#metronome-stick")
  stick.toggleClass("right");
  if (stick.hasClass("right")){
    degrees = 20;
  } else {
    degrees = -20;
  }
  $("#metronome-stick").stop().animate({ textIndent: degrees }, {
    step: function(degrees) {
        $(this).css('transform',"rotate(" + degrees + "deg)");
    }, duration: this.tempoInMilliseconds
  } );
}<commit_msg>Make playSounds an instance method<commit_after>function Metronome(tempo, beatsPerMeasure, subdivisions){
  this.tempo = Number(tempo);
  this.beatsPerMeasure = Number(beatsPerMeasure);
  this.subdivisions = subdivisions;
  this.interval = null;
  this.tempoInMilliseconds = this.tempoToMilliseconds(this.tempo);
}

Metronome.prototype.start = function(){
  this.interval = window.setInterval(this.changeSoundAndView.bind(this), this.tempoInMilliseconds, this);
}

Metronome.prototype.tempoToMilliseconds = function(tempo){
  return (1000 * 60)/tempo;
}

Metronome.prototype.stop = function(){
  window.clearInterval(this.interval);
  var counter = document.getElementById("metronome-counter");
  counter.innerHTML = "";
}

Metronome.prototype.changeSoundAndView = function(metronome){
  this.moveStick();
  this.updateCounterView();
  this.playSounds();
}

Metronome.prototype.playSounds = function(){
  playSound(this, 'audio/beep-07.wav');
  for (var i = 0; i < this.subdivisions.length; i++){
    createSubdivisions(this, this.subdivisions[i]);
  }
}

createSubdivisions = function(metronome, divideTheBeatIn){
  var subdivisionsInMilliseconds = (metronome.tempoInMilliseconds)/divideTheBeatIn;
  var i = 1;
  var subdivisions = window.setInterval(function(){ i++;
    playSound(metronome, 'audio/beep-07.wav')
    if (i == divideTheBeatIn){
      clearInterval(subdivisions);}
    }, subdivisionsInMilliseconds)
}

playSound = function(metronome, fileName){
  new Howl({
    urls: [fileName]
  }).play();
}

Metronome.prototype.updateCounterView = function(){
  var counter = document.getElementById("metronome-counter");
  var pastBeat = Number(counter.innerHTML);
  if (pastBeat < this.beatsPerMeasure){
    counter.innerHTML = pastBeat + 1;
  } else {
    counter.innerHTML = 1;
  }
}

Metronome.prototype.moveStick = function(){
  var stick = $("#metronome-stick")
  stick.toggleClass("right");
  if (stick.hasClass("right")){
    degrees = 20;
  } else {
    degrees = -20;
  }
  $("#metronome-stick").stop().animate({ textIndent: degrees }, {
    step: function(degrees) {
        $(this).css('transform',"rotate(" + degrees + "deg)");
    }, duration: this.tempoInMilliseconds
  } );
}<|endoftext|>


<commit_before>(function() {
  angular.module('ngBootstrapizeMaven')
  .service('pageCache', function ($http, mvnLinker) {
    var memory = {};

    var pageCache = {
      get: function (path) {
        return memory[path];
      },

      trimPageContent: function (data) {
        if (data.indexOf('<frameset') >= 0) {
          // get only body content, as jquery cannot parse full page
          data = data.substring(data.indexOf('<frameset'), data.lastIndexOf('</frameset>'));
        } else {
          // get only body content, as jquery cannot parse full page
          data = data.substring(data.indexOf('<body'), data.lastIndexOf(''));
        }

        // very shitty - remove 'non-breaking space styling'
        data = data.replace(/( | )/g, '');

        return '
' + data.substr(data.indexOf('>') + 1) + '
';
      },

      load: function (path, successFn, failureFn, relativeTo) {
        path = path.replace(/\/\//g, '/').replace(/:\//g, '://').replace(/^\/?#/, '/maven');

        if (pageCache.get(path)) {
          successFn(pageCache.get(path));
        } else {
          $http.get(path).success(function (pageSrc, status, headers, config) {
            // FIXME: stopping images from loading - but images in content should be loaded!
            pageSrc = pageSrc.replace(/<img /g, '<i ').replace(/<\/img>/g, '');
            // rewrite links so they work in ang-boot-mav-site
            pageSrc = pageSrc.replace(/href=".*?"/g,
              mvnLinker.linkRelativeTo(path.substr(path.indexOf('maven/') + 5)));

            var pageData =  memory[path] = { src: pageSrc };
            pageData.status = status;
            pageData.loadTime = new Date().toString();
            pageData.trimmed = pageCache.trimPageContent(pageSrc);
            pageData.processed = $(pageData.trimmed);

            successFn(pageCache.get(path));
          }).error(function (data, status, headers, config) {
            memory[path] = { data: data, status: status };

            if (failureFn) {
              failureFn(memory[path]);
            }
          });
        }
      }
    };

    return pageCache;
  });
})();<commit_msg>Fix href building<commit_after>(function() {
  angular.module('ngBootstrapizeMaven')
  .service('pageCache', function ($http, mvnLinker) {
    var memory = {};

    var pageCache = {
      get: function (path) {
        return memory[path];
      },

      trimPageContent: function (data) {
        if (data.indexOf('<frameset') >= 0) {
          // get only body content, as jquery cannot parse full page
          data = data.substring(data.indexOf('<frameset'), data.lastIndexOf('</frameset>'));
        } else {
          // get only body content, as jquery cannot parse full page
          data = data.substring(data.indexOf('<body'), data.lastIndexOf(''));
        }

        // very shitty - remove 'non-breaking space styling'
        data = data.replace(/( | )/g, '');

        return '
' + data.substr(data.indexOf('>') + 1) + '
';
      },

      load: function (path, successFn, failureFn, relativeTo) {
        path = path.replace(/\/\//g, '/').replace(/:\//g, '://').replace(/^\/?#/, '/maven');

        if (pageCache.get(path)) {
          successFn(pageCache.get(path));
        } else {
          var relative = path.indexOf('maven/') >= 0 ?
            path.substr(path.indexOf('maven/') + 5) : path.substr('maven/'.length);

          $http.get(path).success(function (pageSrc, status, headers, config) {
            // FIXME: stopping images from loading - but images in content should be loaded!
            pageSrc = pageSrc.replace(/<img /g, '<i ').replace(/<\/img>/g, '');
            // rewrite links so they work in ang-boot-mav-site
            pageSrc = pageSrc.replace(/href=".*?"/g,  mvnLinker.linkRelativeTo(relative));

            var pageData =  memory[path] = { src: pageSrc };
            pageData.status = status;
            pageData.loadTime = new Date().toString();
            pageData.trimmed = pageCache.trimPageContent(pageSrc);
            pageData.processed = $(pageData.trimmed);

            successFn(pageCache.get(path));
          }).error(function (data, status, headers, config) {
            memory[path] = { data: data, status: status };

            if (failureFn) {
              failureFn(memory[path]);
            }
          });
        }
      }
    };

    return pageCache;
  });
})();<|endoftext|>


<commit_before>var waiting = 0;
var timer_id;
var iterations = 0;
var hidden_prop;
var hidden_event;

function create_xhr() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		/* IE 5-6 */
		return new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		return null;
	}
}

function fetch_data() {
	/* Include timestamp to prevent IE 5 from caching the response forever */
	var time = new Date().getTime();
	var query = "?" + settings.args.replace(/^\?/, "") + "&t=" + time;

	var pos = location.href.indexOf("?");
	var url = (pos >= 0 ? location.href.substr(0, pos) : location.href) + query;

	var xhr = create_xhr();
	waiting++;
	xhr.open('GET', url, true);
	xhr.onreadystatechange = function (event) {
		if (xhr.readyState == 4) {
			waiting--;
			if (xhr.status == 200) {
				handle_data(xhr.responseText);
			} else if (xhr.status) {
				console.log("Error loading data: "+xhr.status);
			}
			set_timer();
		}
	};
	xhr.send(null);
	iterations++;
}

function handle_data(data) {
	/* Use DOM instead of raw innerHTML to make it work in IE 5 */
	var old_div = document.getElementById("rwho-table-wrapper");
	var new_div = document.createElement("div");
	new_div.innerHTML = data;
	if (window.ActiveXObject) {
		/* In IE, replace the whole <div> to avoid crashes */
		old_div.parentNode.replaceChild(new_div, old_div);
	} else {
		/* Replace just the <tbody> to avoid flickering in Mozilla */
		var old_tbody = old_div.getElementsByTagName("tbody")[0];
		var new_tbody = new_div.getElementsByTagName("tbody")[0];
		old_tbody.parentNode.replaceChild(new_tbody, old_tbody);
	}
}

function is_visible() {
	return hidden_prop ? !document[hidden_prop] : true;
}

function set_timer() {
	var interval = settings.interval;
	if (!is_visible()) {
		interval = Math.max(interval, 120);
	}
	if (iterations > 500) {
		interval *= (iterations / 500);
	}
	if (iterations > 10000) {
		console.log("nobody's looking at us, going to sleep");
		return;
	}
	if (timer_id) {
		clearTimeout(timer_id);
	}
	timer_id = setTimeout(fetch_data, interval * 1000);
}

function update_visibility() {
	if (is_visible()) {
		console.log("page became visible, starting instant update");
		fetch_data();
	} else {
		console.log("page became hidden, adjusting timer");
		set_timer();
	}
}

if (!window.console) {
	window.console = {};
	window.console.log = function(msg) {};
}

if (!create_xhr()) {
	alert("[BUG] no XHR on this browser");
} else if (document.addEventListener) {
	/* Standard DOM (IE 9+) */
	document.addEventListener("DOMContentLoaded", fetch_data, true);

	if (typeof document.hidden !== "undefined") {
		hidden_prop = "hidden";
		hidden_event = "visibilitychange";
	} else if (typeof document.mozHidden !== "undefined") {
		hidden_prop = "mozHidden";
		hidden_event = "mozvisibilitychange";
	} else if (typeof document.msHidden !== "undefined") {
		hidden_prop = "msHidden";
		hidden_event = "msvisibilitychange";
	} else if (typeof document.webkitHidden !== "undefined") {
		hidden_prop = "webkitHidden";
		hidden_event = "webkitvisibilitychange";
	}

	if (hidden_event) {
		document.addEventListener(hidden_event, update_visibility, false);
	}
} else if (document.attachEvent) {
	/* IE 4-8 */
	window.attachEvent("onload", fetch_data);

	/* Create a custom property */
	hidden_prop = "hidden";
	/* This is not optimal, as blurred windows are actually still visible. */
	window.attachEvent("onfocus", function() {
		document[hidden_prop] = false;
		update_visibility();
	});
	window.attachEvent("onblur", function() {
		document[hidden_prop] = true;
		update_visibility();
	});
} else {
	alert("[BUG] no event handler on this browser");
}
<commit_msg>ui-web: add note to self about IE 4/5<commit_after>var waiting = 0;
var timer_id;
var iterations = 0;
var hidden_prop;
var hidden_event;

function create_xhr() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		/* IE 5-6 */
		return new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		return null;
	}
}

function fetch_data() {
	/* Include timestamp to prevent IE 5 from caching the response forever */
	var time = new Date().getTime();
	var query = "?" + settings.args.replace(/^\?/, "") + "&t=" + time;

	var pos = location.href.indexOf("?");
	var url = (pos >= 0 ? location.href.substr(0, pos) : location.href) + query;

	var xhr = create_xhr();
	waiting++;
	xhr.open('GET', url, true);
	xhr.onreadystatechange = function (event) {
		if (xhr.readyState == 4) {
			waiting--;
			if (xhr.status == 200) {
				handle_data(xhr.responseText);
			} else if (xhr.status) {
				console.log("Error loading data: "+xhr.status);
			}
			set_timer();
		}
	};
	xhr.send(null);
	iterations++;
}

function handle_data(data) {
	// if (document.all) /* IE 4-5 */
	// else if (document.getElementById) /* IE 5.5 and later */

	/* Use DOM instead of raw innerHTML to make it work in IE 5.5 */
	var old_div = document.getElementById("rwho-table-wrapper");
	var new_div = document.createElement("div");
	new_div.innerHTML = data;
	if (window.ActiveXObject) {
		/* In IE, replace the whole <div> to avoid crashes */
		old_div.parentNode.replaceChild(new_div, old_div);
	} else {
		/* Replace just the <tbody> to avoid flickering in Mozilla */
		var old_tbody = old_div.getElementsByTagName("tbody")[0];
		var new_tbody = new_div.getElementsByTagName("tbody")[0];
		old_tbody.parentNode.replaceChild(new_tbody, old_tbody);
	}
}

function is_visible() {
	return hidden_prop ? !document[hidden_prop] : true;
}

function set_timer() {
	var interval = settings.interval;
	if (!is_visible()) {
		interval = Math.max(interval, 120);
	}
	if (iterations > 500) {
		interval *= (iterations / 500);
	}
	if (iterations > 10000) {
		console.log("nobody's looking at us, going to sleep");
		return;
	}
	if (timer_id) {
		clearTimeout(timer_id);
	}
	timer_id = setTimeout(fetch_data, interval * 1000);
}

function update_visibility() {
	if (is_visible()) {
		console.log("page became visible, starting instant update");
		fetch_data();
	} else {
		console.log("page became hidden, adjusting timer");
		set_timer();
	}
}

if (!window.console) {
	window.console = {};
	window.console.log = function(msg) {};
}

if (!create_xhr()) {
	alert("[BUG] no XHR on this browser");
} else if (document.addEventListener) {
	/* Standard DOM (IE 9+) */
	document.addEventListener("DOMContentLoaded", fetch_data, true);

	if (typeof document.hidden !== "undefined") {
		hidden_prop = "hidden";
		hidden_event = "visibilitychange";
	} else if (typeof document.mozHidden !== "undefined") {
		hidden_prop = "mozHidden";
		hidden_event = "mozvisibilitychange";
	} else if (typeof document.msHidden !== "undefined") {
		hidden_prop = "msHidden";
		hidden_event = "msvisibilitychange";
	} else if (typeof document.webkitHidden !== "undefined") {
		hidden_prop = "webkitHidden";
		hidden_event = "webkitvisibilitychange";
	}

	if (hidden_event) {
		document.addEventListener(hidden_event, update_visibility, false);
	}
} else if (document.attachEvent) {
	/* IE 4-8 */
	window.attachEvent("onload", fetch_data);

	/* Create a custom property */
	hidden_prop = "hidden";
	/* This is not optimal, as blurred windows are actually still visible. */
	window.attachEvent("onfocus", function() {
		document[hidden_prop] = false;
		update_visibility();
	});
	window.attachEvent("onblur", function() {
		document[hidden_prop] = true;
		update_visibility();
	});
} else {
	alert("[BUG] no event handler on this browser");
}
<|endoftext|>


<commit_before>module.exports = {
    packageWarningMsg: packageWarningMsg,
    isHaveChecked: isHaveChecked,
    inTripletExpressionHaveChecked: inTripletExpressionHaveChecked,
    inIfStatementHaveChecked: inIfStatementHaveChecked,
    isLogicalRightExpression: isLogicalRightExpression,
    isLeftExpressionHaveChecked: isLeftExpressionHaveChecked,
    isArgumentsHit: isArgumentsHit
}
function packageWarningMsg (object) {
    var msg = ''
    if (object.object.name && object.property.name) {
        msg = object.object.name + '.' + object.property.name
            + ' could be null, would cause NullReferenceException error'
    }
    return msg
}
function isHaveChecked (parent, node) {
    return inTripletExpressionHaveChecked(parent, node) || inIfStatementHaveChecked(parent, node)
        || inUnaryOrBinaryExpressionHaveChecked(parent, node);
}

function inUnaryOrBinaryExpressionHaveChecked (parent, node) {
    var result = false;
    var types = ['UnaryExpression', 'BinaryExpression'];
    if (types.includes(node.parent.type) && node.parent.parent.right === node.parent) {
        var hitLintObjectName = getObjectNameDeeply(node);
        result = isLeftExpressionHaveChecked(parent, node.parent, hitLintObjectName);
    }
    return result;
}

function inTripletExpressionHaveChecked (rootparent, node) {
    var result = false;
    if (node.parent.type === 'ConditionalExpression') {
        var test = node.parent.test;
        if (test && test.object && test.property) {
            var testObjectName = getObjectNameDeeply({object: test});
            var hitLintObjectName = getObjectNameDeeply(node);
            result = testObjectName === hitLintObjectName;
        } else if (test && test.left && test.right) {
            return isLeftExpressionHaveChecked(rootparent, test.right);
        }
    }
    return result;
}
function inIfStatementHaveChecked (rootparent, node) {
    var result = false;
    var findCount = 0;
    var parent = node.parent;
    while (!result && parent.parent && findCount < 3) {
        parent = findBlockParentNodeRecursively(parent);
        result = unitIfExpressionChecked(parent, node);
        findCount++;
        if (parent) {
            parent = parent.parent;
        } else {
            parent = null;
            break;
        }
    }
    return result;
}

function findBlockParentNodeRecursively (parent) {
    while (parent.type !== 'BlockStatement') {
        parent = parent.parent;
        if (!parent) break;
    }
    return parent;
}

function unitIfExpressionChecked (parent, node) {
    var result = false;
    if (parent && parent.parent && parent.parent.type === 'IfStatement' && parent.parent.test && parent.parent.alternate
 !== parent) {
        var testObjectName = '';
        var hitLintObjectName = getObjectNameDeeply(node);
        var testNode = parent.parent.test;
        if (testNode.left && testNode.right) {
            var right = testNode.right
            if (right.object && right.property) {
                testObjectName = getObjectNameDeeply(right);
                if (testObjectName !== hitLintObjectName && testNode.left.left) {
                    return isLeftExpressionHaveChecked(rootparent, testNode.right, hitLintObjectName)
                }
            } else if (right.left) {
                testObjectName = getObjectNameDeeply(right.left);
            } else if (right.right) {
                testObjectName = getObjectNameDeeply(right.right);
            } else {
                testObjectName = getObjectNameDeeply(testNode.left);
            }
        } else if (testNode.object) {
            testObjectName = `${testNode.object.name}.${testNode.property.name}`;
        }
        result = testObjectName === hitLintObjectName;
    }
    return result;
}

function isLeftExpressionHaveChecked (rootparent, node, hitName) {
    var result = false;
    var hitLintObjectName = hitName ? hitName : getObjectNameDeeply(node);
    var testObjectName = '';
    if (node.parent && node.parent.left) {
        var leftNode = node.parent.left;
        if (!leftNode.left && leftNode.object && leftNode.property) {
            testObjectName = getObjectNameDeeply({object: leftNode});
            result = testObjectName === hitLintObjectName;
        } else if (!leftNode.left && leftNode.argument && leftNode.argument.object && leftNode.argument.property) {
            testObjectName = getObjectNameDeeply({object: leftNode.argument});
            result = testObjectName === hitLintObjectName;
        } else {
            if (leftNode.right && leftNode.right.type === 'MemberExpression' && leftNode.right.object
                && leftNode.right.property) {
                    testObjectName = getObjectNameDeeply({object: leftNode.right});
                    if (testObjectName === hitLintObjectName) {
                        result = true;
                        return result;
                    }
            }
            var tempLeft = leftNode.left;
            while (tempLeft && tempLeft.left) {
                tempLeft = tempLeft.left;
                if (tempLeft) {
                    tempRight = tempLeft.parent.right;
                    if (tempRight.object && tempRight.property) {
                        testObjectName = getObjectNameDeeply({object: tempRight});
                        if (testObjectName === hitLintObjectName) {
                            result = true;
                            break;
                        }
                    }
                } else {
                    tempLeft = tempLeft.parent;
                    break;
                }
            }
            if (!result && tempLeft && tempLeft.object && tempLeft.property) {
                testObjectName = getObjectNameDeeply({object: tempLeft});
                result = testObjectName === hitLintObjectName;
            }
        }
    }
    return result;
}

// TODO: use traverseTree to make code clean
// function traverseLogicalTree (node) {
//     if (node.left) {
//         traverseLogicalTree(node.left);
//         traverseLogicalTree(node.right);
//     } else {
//         console.log (node)
//     }
// }

function isLogicalRightExpression (parent, node) {
    if (node.parent.type === 'LogicalExpression' && node.parent.right === node) {
        return isLeftExpressionHaveChecked(parent, node);
    } else {
        let checkNode = node.parent.parent;
        while (checkNode.type !== 'LogicalExpression') {
            checkNode = checkNode.parent;
            if (!checkNode.parent) {
                checkNode = null;
                break;
            }
        }
        if (checkNode && checkNode.right) {
            return isLeftExpressionHaveChecked(parent, checkNode.right);
        }
        return false;
    }
}

function isArgumentsHit (node) {
    var result = false;
    if (node.parent && node.parent.arguments && node.parent.arguments[0] && node.parent.arguments[0] === node) {
        result = true;
    }
    return result;
}

function getObjectNameDeeply (node) {
    var name = '';
    if (node.object && node.object.name && node.property && node.property.name) {
        name = `${node.object.name}.${node.property.name}`
    } else {
        var target = node.object;
        if (target && target.object && target.property && target.object.name && target.property.name) {
            name = `${target.object.name}.${target.property.name}`;
        } else if (target && target.object && !target.object.name && target.object.type === 'ThisExpression') {
            name = `this.${target.property.name}`;
        } else if (target && target.object && !target.object.name && target.object.object && target.object.property) {
            name = `${target.object.object.name}.${target.object.property.name}`;
        }
    }
    return name;
}
<commit_msg>fix(util): forget pass rootparent<commit_after>module.exports = {
    packageWarningMsg: packageWarningMsg,
    isHaveChecked: isHaveChecked,
    inTripletExpressionHaveChecked: inTripletExpressionHaveChecked,
    inIfStatementHaveChecked: inIfStatementHaveChecked,
    isLogicalRightExpression: isLogicalRightExpression,
    isLeftExpressionHaveChecked: isLeftExpressionHaveChecked,
    isArgumentsHit: isArgumentsHit
}
function packageWarningMsg (object) {
    var msg = ''
    if (object.object.name && object.property.name) {
        msg = object.object.name + '.' + object.property.name
            + ' could be null, would cause NullReferenceException error'
    }
    return msg
}
function isHaveChecked (parent, node) {
    return inTripletExpressionHaveChecked(parent, node) || inIfStatementHaveChecked(parent, node)
        || inUnaryOrBinaryExpressionHaveChecked(parent, node);
}

function inUnaryOrBinaryExpressionHaveChecked (parent, node) {
    var result = false;
    var types = ['UnaryExpression', 'BinaryExpression'];
    if (types.includes(node.parent.type) && node.parent.parent.right === node.parent) {
        var hitLintObjectName = getObjectNameDeeply(node);
        result = isLeftExpressionHaveChecked(parent, node.parent, hitLintObjectName);
    }
    return result;
}

function inTripletExpressionHaveChecked (rootparent, node) {
    var result = false;
    if (node.parent.type === 'ConditionalExpression') {
        var test = node.parent.test;
        if (test && test.object && test.property) {
            var testObjectName = getObjectNameDeeply({object: test});
            var hitLintObjectName = getObjectNameDeeply(node);
            result = testObjectName === hitLintObjectName;
        } else if (test && test.left && test.right) {
            return isLeftExpressionHaveChecked(rootparent, test.right);
        }
    }
    return result;
}
function inIfStatementHaveChecked (rootparent, node) {
    var result = false;
    var findCount = 0;
    var parent = node.parent;
    while (!result && parent.parent && findCount < 3) {
        parent = findBlockParentNodeRecursively(parent);
        result = unitIfExpressionChecked(rootparent, parent, node);
        findCount++;
        if (parent) {
            parent = parent.parent;
        } else {
            parent = null;
            break;
        }
    }
    return result;
}

function findBlockParentNodeRecursively (parent) {
    while (parent.type !== 'BlockStatement') {
        parent = parent.parent;
        if (!parent) break;
    }
    return parent;
}

function unitIfExpressionChecked (rootparent, parent, node) {
    var result = false;
    if (parent && parent.parent && parent.parent.type === 'IfStatement' && parent.parent.test && parent.parent.alternate
 !== parent) {
        var testObjectName = '';
        var hitLintObjectName = getObjectNameDeeply(node);
        var testNode = parent.parent.test;
        if (testNode.left && testNode.right) {
            var right = testNode.right
            if (right.object && right.property) {
                testObjectName = getObjectNameDeeply(right);
                if (testObjectName !== hitLintObjectName && testNode.left.left) {
                    return isLeftExpressionHaveChecked(rootparent, testNode.right, hitLintObjectName)
                }
            } else if (right.left) {
                testObjectName = getObjectNameDeeply(right.left);
            } else if (right.right) {
                testObjectName = getObjectNameDeeply(right.right);
            } else {
                testObjectName = getObjectNameDeeply(testNode.left);
            }
        } else if (testNode.object) {
            testObjectName = `${testNode.object.name}.${testNode.property.name}`;
        }
        result = testObjectName === hitLintObjectName;
    }
    return result;
}

function isLeftExpressionHaveChecked (rootparent, node, hitName) {
    var result = false;
    var hitLintObjectName = hitName ? hitName : getObjectNameDeeply(node);
    var testObjectName = '';
    if (node.parent && node.parent.left) {
        var leftNode = node.parent.left;
        if (!leftNode.left && leftNode.object && leftNode.property) {
            testObjectName = getObjectNameDeeply({object: leftNode});
            result = testObjectName === hitLintObjectName;
        } else if (!leftNode.left && leftNode.argument && leftNode.argument.object && leftNode.argument.property) {
            testObjectName = getObjectNameDeeply({object: leftNode.argument});
            result = testObjectName === hitLintObjectName;
        } else {
            if (leftNode.right && leftNode.right.type === 'MemberExpression' && leftNode.right.object
                && leftNode.right.property) {
                    testObjectName = getObjectNameDeeply({object: leftNode.right});
                    if (testObjectName === hitLintObjectName) {
                        result = true;
                        return result;
                    }
            }
            var tempLeft = leftNode.left;
            while (tempLeft && tempLeft.left) {
                tempLeft = tempLeft.left;
                if (tempLeft) {
                    tempRight = tempLeft.parent.right;
                    if (tempRight.object && tempRight.property) {
                        testObjectName = getObjectNameDeeply({object: tempRight});
                        if (testObjectName === hitLintObjectName) {
                            result = true;
                            break;
                        }
                    }
                } else {
                    tempLeft = tempLeft.parent;
                    break;
                }
            }
            if (!result && tempLeft && tempLeft.object && tempLeft.property) {
                testObjectName = getObjectNameDeeply({object: tempLeft});
                result = testObjectName === hitLintObjectName;
            }
        }
    }
    return result;
}

// TODO: use traverseTree to make code clean
// function traverseLogicalTree (node) {
//     if (node.left) {
//         traverseLogicalTree(node.left);
//         traverseLogicalTree(node.right);
//     } else {
//         console.log (node)
//     }
// }

function isLogicalRightExpression (parent, node) {
    if (node.parent.type === 'LogicalExpression' && node.parent.right === node) {
        return isLeftExpressionHaveChecked(parent, node);
    } else {
        let checkNode = node.parent.parent;
        while (checkNode.type !== 'LogicalExpression') {
            checkNode = checkNode.parent;
            if (!checkNode.parent) {
                checkNode = null;
                break;
            }
        }
        if (checkNode && checkNode.right) {
            return isLeftExpressionHaveChecked(parent, checkNode.right);
        }
        return false;
    }
}

function isArgumentsHit (node) {
    var result = false;
    if (node.parent && node.parent.arguments && node.parent.arguments[0] && node.parent.arguments[0] === node) {
        result = true;
    }
    return result;
}

function getObjectNameDeeply (node) {
    var name = '';
    if (node.object && node.object.name && node.property && node.property.name) {
        name = `${node.object.name}.${node.property.name}`
    } else {
        var target = node.object;
        if (target && target.object && target.property && target.object.name && target.property.name) {
            name = `${target.object.name}.${target.property.name}`;
        } else if (target && target.object && !target.object.name && target.object.type === 'ThisExpression') {
            name = `this.${target.property.name}`;
        } else if (target && target.object && !target.object.name && target.object.object && target.object.property) {
            name = `${target.object.object.name}.${target.object.property.name}`;
        }
    }
    return name;
}
<|endoftext|>


<commit_before>define(function () {
    return new Phaser.Game(1000, 500, Phaser.Canvas);
});
<commit_msg>fix webgl renderer -> canvas renderer<commit_after>define(function () {
    return new Phaser.Game(1000, 500, Phaser.CANVAS);
});
<|endoftext|>


<commit_before>'use strict';

var validUrl = require('valid-url');
var Url = require('../models/url.js');

	function genId(len) {
		var i;
		var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
		var id = '';
		for (i=0;i<len;i++) {
			id += chars.charAt(Math.floor(Math.random() * chars.length));
		}
		return id;
	}

function ApiHandler () {

	this.getOriginalUrl = function (req, res) {
		Url
			.findByIdAndUpdate(req.params.id, { $inc: { 'counter': 1 } }, {select:{_id:0,}}, function(err, result) {
				if (err) { throw err; }

				if (result !== null) {
					res.redirect(result.original_url);
				}
				else {
					res.json({error: "This url is not in database."});
				}
			});
	};

	this.addUrl = function (req, res, next) {
		var fullUrl = req.params.protocol + '//' + req.params.url;
		if (validUrl.isUri(fullUrl)) {
		    //valid url
		    	Url.findOneAndUpdate({"original_url": fullUrl},
			{$setOnInsert:
				{
					"_id": genId(6),
					"original_url": fullUrl,
					"counter": 0
				}
			} ,
			{upsert: true, 'new': true},
			function(err, result){
				if (err) {
					if (err.name === 'MongoError' && err.code === 11000) {
			        // Duplicate username
			        // TODO Notify on key duplication - need to increment genId
			        // for more combinations
			        console.log("key duplication - need to increment genId for more combinations");
			        res.status(500).send({ error: 'Internal server error, try once again. If error persist contact support' });
			      }
					else {
						throw err;
					}
				}
				res.json({ "original_url":result.original_url, "short_url":req.protocol + '://' + req.get('host') + '/' + result._id});
			});
		  } else {
		  	//url invalid
		    res.json({error: "Wrong url format, make sure you have a valid protocol and real site."});
		  }

		// var url = new Url ({
		// 	"_id": genId(6),
		// 	"original_url": req.params.protocol + '//' + req.params.url
		// });

		// url.save(function(err, result){
		// 	if (err) {
		// 		if (err.name === 'MongoError' && err.code === 11000) {
		//         // Duplicate username
		//         // TODO Notify on key duplication - need to increment genId
		//         // for more combinations
		//         console.log("key duplication - need to increment genId for more combinations");
		//         res.status(500).send({ error: 'Internal server error, try once again. If error persist contact support' });
		//       }
		// 		else {
		// 			throw err;
		// 		}
		// 	}
		// 	res.json({ "original_url":result.original_url, "short_url":req.protocol + '://' + req.get('host') + '/' + result._id});
		// });
	};
}

module.exports = ApiHandler;
<commit_msg>Changed valid-url method to isWebUri<commit_after>'use strict';

var validUrl = require('valid-url');
var Url = require('../models/url.js');

	function genId(len) {
		var i;
		var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
		var id = '';
		for (i=0;i<len;i++) {
			id += chars.charAt(Math.floor(Math.random() * chars.length));
		}
		return id;
	}

function ApiHandler () {

	this.getOriginalUrl = function (req, res) {
		Url
			.findByIdAndUpdate(req.params.id, { $inc: { 'counter': 1 } }, {select:{_id:0,}}, function(err, result) {
				if (err) { throw err; }

				if (result !== null) {
					res.redirect(result.original_url);
				}
				else {
					res.json({error: "This url is not in database."});
				}
			});
	};

	this.addUrl = function (req, res, next) {
		var fullUrl = req.params.protocol + '//' + req.params.url;
		if (validUrl.isWebUri(fullUrl)) {
		    //valid url
		    	Url.findOneAndUpdate({"original_url": fullUrl},
			{$setOnInsert:
				{
					"_id": genId(6),
					"original_url": fullUrl,
					"counter": 0
				}
			} ,
			{upsert: true, 'new': true},
			function(err, result){
				if (err) {
					if (err.name === 'MongoError' && err.code === 11000) {
			        // Duplicate username
			        // TODO Notify on key duplication - need to increment genId
			        // for more combinations
			        console.log("key duplication - need to increment genId for more combinations");
			        res.status(500).send({ error: 'Internal server error, try once again. If error persist contact support' });
			      }
					else {
						throw err;
					}
				}
				res.json({ "original_url":result.original_url, "short_url":req.protocol + '://' + req.get('host') + '/' + result._id});
			});
		  } else {
		  	//url invalid
		    res.json({error: "Wrong url format, make sure you have a valid protocol and real site."});
		  }

		// var url = new Url ({
		// 	"_id": genId(6),
		// 	"original_url": req.params.protocol + '//' + req.params.url
		// });

		// url.save(function(err, result){
		// 	if (err) {
		// 		if (err.name === 'MongoError' && err.code === 11000) {
		//         // Duplicate username
		//         // TODO Notify on key duplication - need to increment genId
		//         // for more combinations
		//         console.log("key duplication - need to increment genId for more combinations");
		//         res.status(500).send({ error: 'Internal server error, try once again. If error persist contact support' });
		//       }
		// 		else {
		// 			throw err;
		// 		}
		// 	}
		// 	res.json({ "original_url":result.original_url, "short_url":req.protocol + '://' + req.get('host') + '/' + result._id});
		// });
	};
}

module.exports = ApiHandler;
<|endoftext|>