<commit_before>// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
  "use strict";

  CodeMirror.defineSimpleMode = function(name, states) {
    CodeMirror.defineMode(name, function(config) {
      return CodeMirror.simpleMode(config, states);
    });
  };

  CodeMirror.simpleMode = function(config, states) {
    ensureState(states, "start");
    var states_ = {}, meta = states.meta || {}, hasIndentation = false;
    for (var state in states) if (state != meta && states.hasOwnProperty(state)) {
      var list = states_[state] = [], orig = states[state];
      for (var i = 0; i < orig.length; i++) {
        var data = orig[i];
        list.push(new Rule(data, states));
        if (data.indent || data.dedent) hasIndentation = true;
      }
    }
    var mode = {
      startState: function() {
        return {state: "start", pending: null,
                local: null, localState: null,
                indent: hasIndentation ? [] : null};
      },
      copyState: function(state) {
        var s = {state: state.state, pending: state.pending,
                 local: state.local, localState: null,
                 indent: state.indent && state.indent.slice(0)};
        if (state.localState)
          s.localState = CodeMirror.copyState(state.local.mode, state.localState);
        if (state.stack)
          s.stack = state.stack.slice(0);
        for (var pers = state.persistentStates; pers; pers = pers.next)
          s.persistentStates = {mode: pers.mode,
                                spec: pers.spec,
                                state: pers.state == state.localState ? s.localState : CodeMirror.copyState(pers.mode, pers.state),
                                next: s.persistentStates};
        return s;
      },
      token: tokenFunction(states_, config),
      innerMode: function(state) { return state.local && {mode: state.local.mode, state: state.localState}; },
      indent: indentFunction(states_, meta)
    };
    if (meta) for (var prop in meta) if (meta.hasOwnProperty(prop))
      mode[prop] = meta[prop];
    return mode;
  };

  function ensureState(states, name) {
    if (!states.hasOwnProperty(name))
      throw new Error("Undefined state " + name + " in simple mode");
  }

  function toRegex(val, caret) {
    if (!val) return /(?:)/;
    var flags = "";
    if (val instanceof RegExp) {
      if (val.ignoreCase) flags = "i";
      val = val.source;
    } else {
      val = String(val);
    }
    return new RegExp((caret === false ? "" : "^") + "(?:" + val + ")", flags);
  }

  function asToken(val) {
    if (!val) return null;
    if (val.apply) return val
    if (typeof val == "string") return val.replace(/\./g, " ");
    var result = [];
    for (var i = 0; i < val.length; i++)
      result.push(val[i] && val[i].replace(/\./g, " "));
    return result;
  }

  function Rule(data, states) {
    if (data.next || data.push) ensureState(states, data.next || data.push);
    this.regex = toRegex(data.regex);
    this.token = asToken(data.token);
    this.data = data;
  }

  function tokenFunction(states, config) {
    return function(stream, state) {
      if (state.pending) {
        var pend = state.pending.shift();
        if (state.pending.length == 0) state.pending = null;
        stream.pos += pend.text.length;
        return pend.token;
      }

      if (state.local) {
        if (state.local.end && stream.match(state.local.end)) {
          var tok = state.local.endToken || null;
          state.local = state.localState = null;
          return tok;
        } else {
          var tok = state.local.mode.token(stream, state.localState), m;
          if (state.local.endScan && (m = state.local.endScan.exec(stream.current())))
            stream.pos = stream.start + m.index;
          return tok;
        }
      }

      var curState = states[state.state];
      for (var i = 0; i < curState.length; i++) {
        var rule = curState[i];
        var matches = (!rule.data.sol || stream.sol()) && stream.match(rule.regex);
        if (matches) {
          if (rule.data.next) {
            state.state = rule.data.next;
          } else if (rule.data.push) {
            (state.stack || (state.stack = [])).push(state.state);
            state.state = rule.data.push;
          } else if (rule.data.pop && state.stack && state.stack.length) {
            state.state = state.stack.pop();
          }

          if (rule.data.mode)
            enterLocalMode(config, state, rule.data.mode, rule.token);
          if (rule.data.indent)
            state.indent.push(stream.indentation() + config.indentUnit);
          if (rule.data.dedent)
            state.indent.pop();
          var token = rule.token
          if (token.apply) token = token(matches)
          if (matches.length > 2) {
            state.pending = [];
            for (var j = 2; j < matches.length; j++)
              if (matches[j])
                state.pending.push({text: matches[j], token: rule.token[j - 1]});
            stream.backUp(matches[0].length - (matches[1] ? matches[1].length : 0));
            return token[0];
          } else if (token && token.join) {
            return token[0];
          } else {
            return token;
          }
        }
      }
      stream.next();
      return null;
    };
  }

  function cmp(a, b) {
    if (a === b) return true;
    if (!a || typeof a != "object" || !b || typeof b != "object") return false;
    var props = 0;
    for (var prop in a) if (a.hasOwnProperty(prop)) {
      if (!b.hasOwnProperty(prop) || !cmp(a[prop], b[prop])) return false;
      props++;
    }
    for (var prop in b) if (b.hasOwnProperty(prop)) props--;
    return props == 0;
  }

  function enterLocalMode(config, state, spec, token) {
    var pers;
    if (spec.persistent) for (var p = state.persistentStates; p && !pers; p = p.next)
      if (spec.spec ? cmp(spec.spec, p.spec) : spec.mode == p.mode) pers = p;
    var mode = pers ? pers.mode : spec.mode || CodeMirror.getMode(config, spec.spec);
    var lState = pers ? pers.state : CodeMirror.startState(mode);
    if (spec.persistent && !pers)
      state.persistentStates = {mode: mode, spec: spec.spec, state: lState, next: state.persistentStates};

    state.localState = lState;
    state.local = {mode: mode,
                   end: spec.end && toRegex(spec.end),
                   endScan: spec.end && spec.forceEnd !== false && toRegex(spec.end, false),
                   endToken: token && token.join ? token[token.length - 1] : token};
  }

  function indexOf(val, arr) {
    for (var i = 0; i < arr.length; i++) if (arr[i] === val) return true;
  }

  function indentFunction(states, meta) {
    return function(state, textAfter, line) {
      if (state.local && state.local.mode.indent)
        return state.local.mode.indent(state.localState, textAfter, line);
      if (state.indent == null || state.local || meta.dontIndentStates && indexOf(state.state, meta.dontIndentStates) > -1)
        return CodeMirror.Pass;

      var pos = state.indent.length - 1, rules = states[state.state];
      scan: for (;;) {
        for (var i = 0; i < rules.length; i++) {
          var rule = rules[i];
          if (rule.data.dedent && rule.data.dedentIfLineStart !== false) {
            var m = rule.regex.exec(textAfter);
            if (m && m[0]) {
              pos--;
              if (rule.next || rule.push) rules = states[rule.next || rule.push];
              textAfter = textAfter.slice(m[0].length);
              continue scan;
            }
          }
        }
        break;
      }
      return pos < 0 ? 0 : state.indent[pos];
    };
  }
});
<commit_msg>[mode/simple addon] Fix crash bug<commit_after>// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
  "use strict";

  CodeMirror.defineSimpleMode = function(name, states) {
    CodeMirror.defineMode(name, function(config) {
      return CodeMirror.simpleMode(config, states);
    });
  };

  CodeMirror.simpleMode = function(config, states) {
    ensureState(states, "start");
    var states_ = {}, meta = states.meta || {}, hasIndentation = false;
    for (var state in states) if (state != meta && states.hasOwnProperty(state)) {
      var list = states_[state] = [], orig = states[state];
      for (var i = 0; i < orig.length; i++) {
        var data = orig[i];
        list.push(new Rule(data, states));
        if (data.indent || data.dedent) hasIndentation = true;
      }
    }
    var mode = {
      startState: function() {
        return {state: "start", pending: null,
                local: null, localState: null,
                indent: hasIndentation ? [] : null};
      },
      copyState: function(state) {
        var s = {state: state.state, pending: state.pending,
                 local: state.local, localState: null,
                 indent: state.indent && state.indent.slice(0)};
        if (state.localState)
          s.localState = CodeMirror.copyState(state.local.mode, state.localState);
        if (state.stack)
          s.stack = state.stack.slice(0);
        for (var pers = state.persistentStates; pers; pers = pers.next)
          s.persistentStates = {mode: pers.mode,
                                spec: pers.spec,
                                state: pers.state == state.localState ? s.localState : CodeMirror.copyState(pers.mode, pers.state),
                                next: s.persistentStates};
        return s;
      },
      token: tokenFunction(states_, config),
      innerMode: function(state) { return state.local && {mode: state.local.mode, state: state.localState}; },
      indent: indentFunction(states_, meta)
    };
    if (meta) for (var prop in meta) if (meta.hasOwnProperty(prop))
      mode[prop] = meta[prop];
    return mode;
  };

  function ensureState(states, name) {
    if (!states.hasOwnProperty(name))
      throw new Error("Undefined state " + name + " in simple mode");
  }

  function toRegex(val, caret) {
    if (!val) return /(?:)/;
    var flags = "";
    if (val instanceof RegExp) {
      if (val.ignoreCase) flags = "i";
      val = val.source;
    } else {
      val = String(val);
    }
    return new RegExp((caret === false ? "" : "^") + "(?:" + val + ")", flags);
  }

  function asToken(val) {
    if (!val) return null;
    if (val.apply) return val
    if (typeof val == "string") return val.replace(/\./g, " ");
    var result = [];
    for (var i = 0; i < val.length; i++)
      result.push(val[i] && val[i].replace(/\./g, " "));
    return result;
  }

  function Rule(data, states) {
    if (data.next || data.push) ensureState(states, data.next || data.push);
    this.regex = toRegex(data.regex);
    this.token = asToken(data.token);
    this.data = data;
  }

  function tokenFunction(states, config) {
    return function(stream, state) {
      if (state.pending) {
        var pend = state.pending.shift();
        if (state.pending.length == 0) state.pending = null;
        stream.pos += pend.text.length;
        return pend.token;
      }

      if (state.local) {
        if (state.local.end && stream.match(state.local.end)) {
          var tok = state.local.endToken || null;
          state.local = state.localState = null;
          return tok;
        } else {
          var tok = state.local.mode.token(stream, state.localState), m;
          if (state.local.endScan && (m = state.local.endScan.exec(stream.current())))
            stream.pos = stream.start + m.index;
          return tok;
        }
      }

      var curState = states[state.state];
      for (var i = 0; i < curState.length; i++) {
        var rule = curState[i];
        var matches = (!rule.data.sol || stream.sol()) && stream.match(rule.regex);
        if (matches) {
          if (rule.data.next) {
            state.state = rule.data.next;
          } else if (rule.data.push) {
            (state.stack || (state.stack = [])).push(state.state);
            state.state = rule.data.push;
          } else if (rule.data.pop && state.stack && state.stack.length) {
            state.state = state.stack.pop();
          }

          if (rule.data.mode)
            enterLocalMode(config, state, rule.data.mode, rule.token);
          if (rule.data.indent)
            state.indent.push(stream.indentation() + config.indentUnit);
          if (rule.data.dedent)
            state.indent.pop();
          var token = rule.token
          if (token && token.apply) token = token(matches)
          if (matches.length > 2) {
            state.pending = [];
            for (var j = 2; j < matches.length; j++)
              if (matches[j])
                state.pending.push({text: matches[j], token: rule.token[j - 1]});
            stream.backUp(matches[0].length - (matches[1] ? matches[1].length : 0));
            return token[0];
          } else if (token && token.join) {
            return token[0];
          } else {
            return token;
          }
        }
      }
      stream.next();
      return null;
    };
  }

  function cmp(a, b) {
    if (a === b) return true;
    if (!a || typeof a != "object" || !b || typeof b != "object") return false;
    var props = 0;
    for (var prop in a) if (a.hasOwnProperty(prop)) {
      if (!b.hasOwnProperty(prop) || !cmp(a[prop], b[prop])) return false;
      props++;
    }
    for (var prop in b) if (b.hasOwnProperty(prop)) props--;
    return props == 0;
  }

  function enterLocalMode(config, state, spec, token) {
    var pers;
    if (spec.persistent) for (var p = state.persistentStates; p && !pers; p = p.next)
      if (spec.spec ? cmp(spec.spec, p.spec) : spec.mode == p.mode) pers = p;
    var mode = pers ? pers.mode : spec.mode || CodeMirror.getMode(config, spec.spec);
    var lState = pers ? pers.state : CodeMirror.startState(mode);
    if (spec.persistent && !pers)
      state.persistentStates = {mode: mode, spec: spec.spec, state: lState, next: state.persistentStates};

    state.localState = lState;
    state.local = {mode: mode,
                   end: spec.end && toRegex(spec.end),
                   endScan: spec.end && spec.forceEnd !== false && toRegex(spec.end, false),
                   endToken: token && token.join ? token[token.length - 1] : token};
  }

  function indexOf(val, arr) {
    for (var i = 0; i < arr.length; i++) if (arr[i] === val) return true;
  }

  function indentFunction(states, meta) {
    return function(state, textAfter, line) {
      if (state.local && state.local.mode.indent)
        return state.local.mode.indent(state.localState, textAfter, line);
      if (state.indent == null || state.local || meta.dontIndentStates && indexOf(state.state, meta.dontIndentStates) > -1)
        return CodeMirror.Pass;

      var pos = state.indent.length - 1, rules = states[state.state];
      scan: for (;;) {
        for (var i = 0; i < rules.length; i++) {
          var rule = rules[i];
          if (rule.data.dedent && rule.data.dedentIfLineStart !== false) {
            var m = rule.regex.exec(textAfter);
            if (m && m[0]) {
              pos--;
              if (rule.next || rule.push) rules = states[rule.next || rule.push];
              textAfter = textAfter.slice(m[0].length);
              continue scan;
            }
          }
        }
        break;
      }
      return pos < 0 ? 0 : state.indent[pos];
    };
  }
});
<|endoftext|>


<commit_before>/**
 * @author Kuitos
 * @homepage https://github.com/kuitos/
 * @since 2015-11-03
 */
var fs = require('fs');
var path = require('path');
var indexHtml = fs.readFileSync(path.resolve(__dirname, "./src/index.html"), "utf-8");
var assets = require('./build/assets.json');

indexHtml = indexHtml.replace(/<script.*>.*<\/script>/g, "");
indexHtml = indexHtml.replace(/<link.*>.*<\/link>/g, "");
indexHtml = indexHtml.replace(/<style.*>.*<\/style>/g, "");

var isInlineAssets = process.argv.some(function (argv) {
  return argv === '--inline-source';
});

if (isInlineAssets) {

  indexHtml = indexHtml.replace('<!-- build:css -->', '<style>' + fs.readFileSync(path.resolve(__dirname, '.' + assets.app.css), 'utf-8') + '</style>');
  indexHtml = indexHtml.replace('<!-- build:js -->', '<script>' + fs.readFileSync(path.resolve(__dirname, '.' + assets.app.js), 'utf-8') + '</script>');

} else {

  indexHtml = indexHtml.replace('<!-- build:css -->', '<link rel="stylesheet" href="' + assets.app.css + '">');
  indexHtml = indexHtml.replace('<!-- build:js -->', '<script src="' + assets.app.js + '"></script>');
}

fs.writeFile(path.resolve(__dirname, './index.html'), indexHtml, 'utf-8');
<commit_msg>code optimize<commit_after>/**
 * @author Kuitos
 * @homepage https://github.com/kuitos/
 * @since 2015-11-03
 */
var fs = require('fs');
var path = require('path');
var indexHtml = fs.readFileSync(path.resolve(__dirname, "./src/index.html"), "utf-8");
var assets = require('./build/assets.json');

var interpolator = {

  js: {
    regex    : /<!--\s*build:js\s*-->/,
    inlineTag: 'script',
    outerTag : '<link rel="stylesheet" href="{{js}}">'
  },

  css: {
    regex    : /<!--\s*build:css\s*-->/,
    inlineTag: 'style',
    outerTag : '<script src="{{css}}"></script>'
  }

};

var isInlineAssets = process.argv.some(function (argv) {
  return argv === '--inline-source';
});

['script', 'link', 'style'].forEach(tag => {
  indexHtml = indexHtml.replace(new RegExp(`<${tag}.*>.*</${tag}>`, 'g'), '');
});

if (isInlineAssets) {

  Object.keys(interpolator).forEach(type => {
    var info = interpolator[type];
    indexHtml = indexHtml.replace(info.regex, `<${info.inlineTag}>` + fs.readFileSync(path.resolve(__dirname, `.${assets.app[type]}`), 'utf-8') + `</${info.inlineTag}>`);
  });

} else {

  Object.keys(interpolator).forEach(type => {
    var info = interpolator[type];
    indexHtml = indexHtml.replace(info.regex, info.outerTag.replace(`{{${type}}}`, assets.app[type]));
  });

}

fs.writeFile(path.resolve(__dirname, './index.html'), indexHtml, 'utf-8');
<|endoftext|>


<commit_before>define(["backbone", "underscore", "jquery", "handlebars", "views/containers/CollectionView",
        "text!templates/appComponents.html", "setImmediate"],
function(Backbone, _, $, Handlebars, CollectionView, template, setImmediate) {

    var AppComponentsView = CollectionView.extend({

        template: Handlebars.compile(template),
        CollectionItemView: undefined, // oggetto sottotipo di AppComponentView
        collectionElSelector: ".appComponentList",
        searchFormElSelector: ".appComponentsOptions .searchForm",
        searchTermElSelector: ".appComponentsOptions .searchTerm",

        isOpened: false, // state if the view (tab) is opened

        // number of milliseconds to pass to the debounce function (e.g. for scroll events)
        debounceDuration: 100,

        events: function() {
            return $.extend({
                "click .openAll": "openAll",
                "click .closeAll": "closeAll",
                "scroll": "loadMoreIfNeeded",
                "click .loadMore": "loadMoreIfNeeded"
            }, CollectionView.prototype.events.apply(this, arguments));
        },

        initialize: function() {
            CollectionView.prototype.initialize.apply(this, arguments);

            // debounce and bind the loadMoreIfNeeded function
            var loadMoreIfNeeded = this.loadMoreIfNeeded;
            this.loadMoreIfNeeded = _.debounce(_.bind(loadMoreIfNeeded, this), this.debounceDuration);

            $(window).on('resize', this.loadMoreIfNeeded);
            this.listenTo(this, "child:close child:hide child:collapsable:close", this.loadMoreIfNeeded);
        },

        // Call this function to notify the view that it has been opened (since is a tab)
        notifyOpened: function() {
            this.isOpened = true;
            this.loadMoreIfNeeded();

            // HACK: give focus to the view, otherwise mousewheel scrolling won't work
            this.render();
        },

        // Call this function to notify the view that it has been opened (since is a tab)
        notifyClosed: function() {
            this.isOpened = false;
        },

        // Load more items if the user reached the bottom of the view
        // Note: the function is automatically debounced and binded on initialize.
        loadMoreIfNeeded: function() {
            setImmediate(_.bind(function() { // wait end of pending browser renders (so to work on updated state)
                if (this.isOpened && this.$el.scrollTop() + this.$el[0].clientHeight == this.$el[0].scrollHeight) {

                    this.showLoadMore(false);

                    this.collection.loadMore(_.bind(function() { // on complete
                        // show load more button (provided as a last resort, manual method, to load more in case
                        // the user is somewhat able to reach the bottom without being catched,
                        // e.g. after an untracked component height drecrease)
                        this.showLoadMore(true);

                        this.loadMoreIfNeeded();
                    }, this));

                }
            }, this));
        },

        // show or hide the load more button
        showLoadMore: function(showOrHide) {
            this.$('.loadMore').toggleClass('hidden', !showOrHide);
        },

        templateData: function() {
            return _.extend({
                'isLoadMoreHidden': this.$('.loadMore').hasClass('hidden') // keep button visiblity between renders
            }, CollectionView.prototype.templateData.apply(this, arguments));
        },

        openAll: function() {
            // don't execute multiple openAll or the operation will slow down
            if (this.openAllInProgress) return;

            // the length can increase during the waiting time caused by the defers,
            // therefore to check if we have opened the last item, we must rely on the original value
            // of when the loop took place (i.e. the number of items to open at that time)
            var collectionItemViewsLength = this.collectionItemViews.length;

            this.forEachItemView(_.bind(function(componentView, i, collectionItemViews) {
                // don't move this outside or the operation will never end if there aren't item views
                this.openAllInProgress = true;
                setImmediate(_.bind(function() { // smooth page reflow (one component view at a time)
                    if (componentView.isShown()) componentView.open();
                    if (i == collectionItemViewsLength-1) {
                        // just opened the last item, operation completed
                        this.openAllInProgress = false;
                    }
                }, this));
            }, this));
        },

        closeAll: function() {
            // don't execute multiple closeAll or the operation will slow down
            if (this.closeAllInProgress) return;

            // see openAll
            var collectionItemViewsLength = this.collectionItemViews.length;

            this.forEachItemView(_.bind(function(componentView, i, collectionItemViews) {
                this.closeAllInProgress = true;
                setImmediate(_.bind(function() { // smooth page reflow (one component view at a time)
                    if (componentView.isShown()) componentView.close();
                    if (i == collectionItemViewsLength-1) {
                        // just closed the last item, operation completed
                        this.closeAllInProgress = false;
                    }
                }, this));
            }, this));
        },

        getComponentView: function(componentIndex) {
            // cerca la vista del componente
            for (var i=0,l=this.collectionItemViews.length; i<l; i++) {
                var currentComponentView = this.collectionItemViews[i];
                var currentComponent = currentComponentView.model;
                if (currentComponent.index === componentIndex) {
                    return currentComponentView;
                }
            }

            return;
        }

    });
    return AppComponentsView;
});
<commit_msg>Default visibility for .loadMore<commit_after>define(["backbone", "underscore", "jquery", "handlebars", "views/containers/CollectionView",
        "text!templates/appComponents.html", "setImmediate"],
function(Backbone, _, $, Handlebars, CollectionView, template, setImmediate) {

    var AppComponentsView = CollectionView.extend({

        template: Handlebars.compile(template),
        CollectionItemView: undefined, // oggetto sottotipo di AppComponentView
        collectionElSelector: ".appComponentList",
        searchFormElSelector: ".appComponentsOptions .searchForm",
        searchTermElSelector: ".appComponentsOptions .searchTerm",

        isOpened: false, // state if the view (tab) is opened

        // number of milliseconds to pass to the debounce function (e.g. for scroll events)
        debounceDuration: 100,

        isLoadMoreHidden: false, // state if the 'load more' button is hidden

        events: function() {
            return $.extend({
                "click .openAll": "openAll",
                "click .closeAll": "closeAll",
                "scroll": "loadMoreIfNeeded",
                "click .loadMore": "loadMoreIfNeeded"
            }, CollectionView.prototype.events.apply(this, arguments));
        },

        initialize: function() {
            CollectionView.prototype.initialize.apply(this, arguments);

            // debounce and bind the loadMoreIfNeeded function
            var loadMoreIfNeeded = this.loadMoreIfNeeded;
            this.loadMoreIfNeeded = _.debounce(_.bind(loadMoreIfNeeded, this), this.debounceDuration);

            $(window).on('resize', this.loadMoreIfNeeded);
            this.listenTo(this, "child:close child:hide child:collapsable:close", this.loadMoreIfNeeded);
        },

        // Call this function to notify the view that it has been opened (since is a tab)
        notifyOpened: function() {
            this.isOpened = true;
            this.loadMoreIfNeeded();

            // HACK: give focus to the view, otherwise mousewheel scrolling won't work
            this.render();
        },

        // Call this function to notify the view that it has been opened (since is a tab)
        notifyClosed: function() {
            this.isOpened = false;
        },

        // Load more items if the user reached the bottom of the view
        // Note: the function is automatically debounced and binded on initialize.
        loadMoreIfNeeded: function() {
            setImmediate(_.bind(function() { // wait end of pending browser renders (so to work on updated state)
                if (this.isOpened && this.$el.scrollTop() + this.$el[0].clientHeight == this.$el[0].scrollHeight) {

                    this.showLoadMore(false);

                    this.collection.loadMore(_.bind(function() { // on complete
                        // show load more button (provided as a last resort, manual method, to load more in case
                        // the user is somewhat able to reach the bottom without being catched,
                        // e.g. after an untracked component height drecrease)
                        this.showLoadMore(true);

                        this.loadMoreIfNeeded();
                    }, this));

                }
            }, this));
        },

        // show or hide the load more button
        showLoadMore: function(showOrHide) {
            this.$('.loadMore').toggleClass('hidden', !showOrHide);
            this.isLoadMoreHidden = !showOrHide;
        },

        templateData: function() {
            return _.extend({
                'isLoadMoreHidden': this.isLoadMoreHidden // keep button visiblity between renders
            }, CollectionView.prototype.templateData.apply(this, arguments));
        },

        openAll: function() {
            // don't execute multiple openAll or the operation will slow down
            if (this.openAllInProgress) return;

            // the length can increase during the waiting time caused by the defers,
            // therefore to check if we have opened the last item, we must rely on the original value
            // of when the loop took place (i.e. the number of items to open at that time)
            var collectionItemViewsLength = this.collectionItemViews.length;

            this.forEachItemView(_.bind(function(componentView, i, collectionItemViews) {
                // don't move this outside or the operation will never end if there aren't item views
                this.openAllInProgress = true;
                setImmediate(_.bind(function() { // smooth page reflow (one component view at a time)
                    if (componentView.isShown()) componentView.open();
                    if (i == collectionItemViewsLength-1) {
                        // just opened the last item, operation completed
                        this.openAllInProgress = false;
                    }
                }, this));
            }, this));
        },

        closeAll: function() {
            // don't execute multiple closeAll or the operation will slow down
            if (this.closeAllInProgress) return;

            // see openAll
            var collectionItemViewsLength = this.collectionItemViews.length;

            this.forEachItemView(_.bind(function(componentView, i, collectionItemViews) {
                this.closeAllInProgress = true;
                setImmediate(_.bind(function() { // smooth page reflow (one component view at a time)
                    if (componentView.isShown()) componentView.close();
                    if (i == collectionItemViewsLength-1) {
                        // just closed the last item, operation completed
                        this.closeAllInProgress = false;
                    }
                }, this));
            }, this));
        },

        getComponentView: function(componentIndex) {
            // cerca la vista del componente
            for (var i=0,l=this.collectionItemViews.length; i<l; i++) {
                var currentComponentView = this.collectionItemViews[i];
                var currentComponent = currentComponentView.model;
                if (currentComponent.index === componentIndex) {
                    return currentComponentView;
                }
            }

            return;
        }

    });
    return AppComponentsView;
});
<|endoftext|>


<commit_before>/*
TODO: Needs Review and Spec
*/

module.exports = {

	upload: function (req, res) {
		var knox = require('knox-s3');
		var keystone = req.keystone;
		var Types = keystone.Field.Types;

		if (!keystone.security.csrf.validate(req, req.body.authenticity_token)) {
			return res.status(403).send({ error: { message: 'invalid csrf' } });
		}

		if (req.files && req.files.file) {

			var s3Config = keystone.get('s3 config');

			var file = req.files.file;
			var path = s3Config.s3path ? s3Config.s3path + '/' : '';

			var headers = Types.S3File.prototype.generateHeaders.call({ s3config: s3Config, options: {} }, null, file);

			var s3Client = knox.createClient(s3Config);

			s3Client.putFile(file.path, path + file.name, headers, function (err, s3Response) {
				var sendResult = function () {
					if (err) {
						return res.send({ error: { message: err.message } });
					}

					if (s3Response) {
						if (s3Response.statusCode !== 200) {
							return res.send({ error: { message: 'Amazon returned Http Code: ' + s3Response.statusCode } });
						} else {
							if (s3Config.root) {
								return res.send({ image: { url: s3Config.root + '/' + file.name } });
							} else {
								var region = 's3';
								if (s3Config.region && s3Config.region !== 'us-east-1') {
									region = 's3-' + s3Config.region;
								}
								return res.send({ image: { url: 'https://' + region + '.amazonaws.com/' + s3Config.bucket + '/' + file.name } });
							}
						}
					}
				};

				res.format({
					html: sendResult,
					json: sendResult,
				});
			});

		} else {
			res.json({ error: { message: 'No image selected' } });
		}
	},
};
<commit_msg>Build S3 upload name when not present (#4871)<commit_after>/*
TODO: Needs Review and Spec
*/

module.exports = {

	upload: function (req, res) {
		var knox = require('knox-s3');
		var keystone = req.keystone;
		var Types = keystone.Field.Types;

		if (!keystone.security.csrf.validate(req, req.body.authenticity_token)) {
			return res.status(403).send({ error: { message: 'invalid csrf' } });
		}

		if (req.files && req.files.file) {

			var s3Config = keystone.get('s3 config');

			var file = req.files.file;
			var path = s3Config.s3path ? s3Config.s3path + '/' : '';

			if (!file.name) {
				var extension;
				if (file.originalname) {
					extension = file.originalname.match(/.*(\..*)/);
				}
				file.name = file.filename + (extension ? extension[1] : '');
			}

			var headers = Types.S3File.prototype.generateHeaders.call({ s3config: s3Config, options: {} }, null, file);

			var s3Client = knox.createClient(s3Config);

			s3Client.putFile(file.path, path + file.name, headers, function (err, s3Response) {
				var sendResult = function () {
					if (err) {
						return res.send({ error: { message: err.message } });
					}

					if (s3Response) {
						if (s3Response.statusCode !== 200) {
							return res.send({ error: { message: 'Amazon returned Http Code: ' + s3Response.statusCode } });
						} else {
							if (s3Config.root) {
								return res.send({ image: { url: s3Config.root + '/' + file.name } });
							} else {
								var region = 's3';
								if (s3Config.region && s3Config.region !== 'us-east-1') {
									region = 's3-' + s3Config.region;
								}
								return res.send({ image: { url: 'https://' + region + '.amazonaws.com/' + s3Config.bucket + '/' + file.name } });
							}
						}
					}
				};

				res.format({
					html: sendResult,
					json: sendResult,
				});
			});

		} else {
			res.json({ error: { message: 'No image selected' } });
		}
	},
};
<|endoftext|>


<commit_before>// Copyright 2018, University of Colorado Boulder

/**
 * View-specific Properties and properties for the 'Vertex Form' screen.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( require => {
  'use strict';

  // modules
  const BooleanProperty = require( 'AXON/BooleanProperty' );
  const graphingQuadratics = require( 'GRAPHING_QUADRATICS/graphingQuadratics' );
  const GQQueryParameters = require( 'GRAPHING_QUADRATICS/common/GQQueryParameters' );
  const GQViewProperties = require( 'GRAPHING_QUADRATICS/common/view/GQViewProperties' );
  const Tandem = require( 'TANDEM/Tandem' );

  class VertexFormViewProperties extends GQViewProperties {

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

      options = _.extend( {
        equationForm: 'vertex',
        tandem: Tandem.required
      }, options );

      super( options );

      // @public
      this.vertexVisibleProperty = new BooleanProperty( false, {
        tandem: options.tandem.createTandem( 'vertexVisibleProperty' ),
        phetioInstanceDocumentation: 'whether the vertex manipulator is visible'
      } );

      // @public
      this.axisOfSymmetryVisibleProperty = new BooleanProperty( GQQueryParameters.checkAll, {
        tandem: options.tandem.createTandem( 'axisOfSymmetryVisibleProperty' ),
        phetioInstanceDocumentation: 'whether the axis of symmetry is visible'
      } );
    }

    /**
     * @public
     * @override
     */
    reset() {
      super.reset();
      this.vertexVisibleProperty.reset();
      this.axisOfSymmetryVisibleProperty.reset();
    }
  }

  return graphingQuadratics.register( 'VertexFormViewProperties', VertexFormViewProperties );
} );

 <commit_msg>allow ?checkAll to override Vertex checkbox state, #40<commit_after>// Copyright 2018, University of Colorado Boulder

/**
 * View-specific Properties and properties for the 'Vertex Form' screen.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( require => {
  'use strict';

  // modules
  const BooleanProperty = require( 'AXON/BooleanProperty' );
  const graphingQuadratics = require( 'GRAPHING_QUADRATICS/graphingQuadratics' );
  const GQQueryParameters = require( 'GRAPHING_QUADRATICS/common/GQQueryParameters' );
  const GQViewProperties = require( 'GRAPHING_QUADRATICS/common/view/GQViewProperties' );
  const Tandem = require( 'TANDEM/Tandem' );

  class VertexFormViewProperties extends GQViewProperties {

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

      options = _.extend( {
        equationForm: 'vertex',
        tandem: Tandem.required
      }, options );

      super( options );

      // @public
      this.vertexVisibleProperty = new BooleanProperty( GQQueryParameters.checkAll, {
        tandem: options.tandem.createTandem( 'vertexVisibleProperty' ),
        phetioInstanceDocumentation: 'whether the vertex manipulator is visible'
      } );

      // @public
      this.axisOfSymmetryVisibleProperty = new BooleanProperty( GQQueryParameters.checkAll, {
        tandem: options.tandem.createTandem( 'axisOfSymmetryVisibleProperty' ),
        phetioInstanceDocumentation: 'whether the axis of symmetry is visible'
      } );
    }

    /**
     * @public
     * @override
     */
    reset() {
      super.reset();
      this.vertexVisibleProperty.reset();
      this.axisOfSymmetryVisibleProperty.reset();
    }
  }

  return graphingQuadratics.register( 'VertexFormViewProperties', VertexFormViewProperties );
} );

 <|endoftext|>


<commit_before>function getSeed() {
    // Seed function - currently it should return unique background per url.

    // var date = new Date();
    // return date.toDateString() + ' ' + date.getHours();

    return window.location.href

}

function changeBackground() {
    var pattern = Trianglify({
        seed: getSeed(),
        x_colors: 'Spectral',
        y_colors: 'random',
        width: min(3000, window.innerWidth),
        height: min(6000, $(document).height() + 100)
    });

    // umm yeah, hacks, who does not love them?!
    document.body.style.backgroundImage = 'url('+ pattern.png() + ')';
}

$(window).resize(
    _.debounce(changeBackground, 2000)
);
<commit_msg>am retard. please fix.<commit_after>function getSeed() {
    // Seed function - currently it should return unique background per url.

    // var date = new Date();
    // return date.toDateString() + ' ' + date.getHours();

    return window.location.href

}

function changeBackground() {
    var pattern = Trianglify({
        seed: getSeed(),
        x_colors: 'Spectral',
        y_colors: 'random',
        width: Math.min(3000, window.innerWidth),
        height: Math.min(6000, $(document).height() + 100)
    });

    // umm yeah, hacks, who does not love them?!
    document.body.style.backgroundImage = 'url('+ pattern.png() + ')';
}

$(window).resize(
    _.debounce(changeBackground, 2000)
);
<|endoftext|>


<commit_before>requirejs.config({
    baseUrl: '../../src',
    shim: {},
    paths: {
        jquery: '../vendor/jquery/dist/jquery'
    },
    packages: []
});

requirejs(['Snowflake'],
    /**
     * Prepares and adds a snowflake to the page
     * @param Snowflake
     */
    function (Snowflake) {
        new Snowflake(150, 150, document.getElementById('blizzard'));
    }
);<commit_msg>Displaying 30 snowflakes per page<commit_after>requirejs.config({
    baseUrl: '../../src',
    shim: {},
    paths: {
        jquery: '../vendor/jquery/dist/jquery'
    },
    packages: []
});

requirejs(['Snowflake'],
    /**
     * Prepares and adds a snowflake to the page
     * @param Snowflake
     */
    function (Snowflake) {
        for (var i = 0; i < 30; i++) {
            new Snowflake(150, 150, document.getElementById('blizzard'));
        }
    }
);<|endoftext|>


<commit_before>function Map(width, height) {
    this.width = width;
    this.height = height;
    this.critters = {}
    this.grid = (function() {
            var arr = [];
            for (var i = 0; i < this.width; i++) {
                var row = [];
                for (var j = 0; j < this.height; j++) {
                    row.push('_');
                }
                arr.push(row);
            }
            return arr;
        }).bind(this)();
    this.gridReference = this.grid
}

Map.prototype.generateRooms = function(rooms) {
    var that = this;
    // var randomX = Math.floor(Math.random() * this.width);
    // var randomY = Math.floor(Math.random() * this.height);
   // console.log(randomX, randomY)
    function helperGeneratePosition() {
        var randomX = Math.floor(Math.random() * that.width);
        var randomY = Math.floor(Math.random() * that.height);
        return [randomX, randomY];
    }
    function helperGenerateRoomSize() {
        var randomWidth = Math.floor(Math.random() * 3) + 2;
        var randomHeight = Math.floor(Math.random() * 3) + 2;
        return [randomWidth, randomHeight];
    }
    function generateRoom() {
        var randomPosition = helperGeneratePosition();
        var x = randomPosition[0];
        var y = randomPosition[1];
        var randomSize = helperGenerateRoomSize();
        var width = randomSize[0];
        var height = randomSize[1];
        if (x + width > that.width || y + height > that.height) {
           // console.log('Rerendering...');
           generateRoom();
        }
        else {
            for (var i = x; i < x + width; i++) {
                for (var j = y; j < y + height; j++) {
                    that.grid[i][j] = 'X';
                }
            }
        }
    }
    for (i = 0; i < rooms; i++) {
        generateRoom()
    }
}

Map.prototype.checkOverlap = function(x, y, width, height) {
    var that = this;
    console.log('Check overlap');
    console.log(this.grid)
    for (var i = x; i < x + width; i++) {
        for (var j = y; j < y + height; j++) {
            if (that.grid[i][j] !== '_') {
                return false
            }
            return true;
        }
    }
}

// Use random coordinate generator to generate initial x and y coordinate for critter
function Critter(x, y, type, map) {
    this.map = map;
    this.health = 100;
    this.type = type;
    this.x = x;
    this.y = y;
    this.symbol = 'O';
}
/*  Critter movement
    Reference: Right is +; Down is +
    Run in Critter.prototype.comeAlive
*/
Critter.prototype._moveRight = function() {
    this.x++;
}
Critter.prototype._moveLeft = function() {
    this.x--;
}
Critter.prototype._moveUp = function() {
    this.y--;
}
Critter.prototype._moveDown = function() {
    this.y++;
}

/*
    Generates a random direction for critter to travel
    and moves critter in that direction as long as there is no obstacle.
    Grid is updated with Map method _updateGrid after each move
*/
Critter.prototype.comeAlive = function() {
    console.log('Coming alive');

    this.map._addCrittersToMap(this);
    var that = this;
    var moves = [
                    this._moveRight.bind(this),
                    this._moveLeft.bind(this),
                    this._moveUp.bind(this),
                    this._moveDown.bind(this)
                ];

    function _generateCoordinateInBound() {

        var random = Math.floor(Math.random() * 4);

        if ((that.x == 0 && random == 1) || (random == 1 && that.map.grid[that.x - 1][that.y] !== '_')) {
            _generateCoordinateInBound();
        }
        else if ((that.x == 9 && random == 0) || (random == 0 && that.map.grid[that.x + 1][that.y] !== '_')) { //  Set random to adjust with map width using Redux and state when transferring to React
            _generateCoordinateInBound();
        }
        else if ((that.y == 0 && random  == 2) || (random == 2 && that.map.grid[that.x][that.y - 1] !== '_')) {
            _generateCoordinateInBound();
        }
        else if ((that.y == 9 && random  == 3) || (random == 3 && that.map.grid[that.x][that.y + 1] !== '_')) {
            _generateCoordinateInBound();
        }
        else {
            var x = that.x;
            var y = that.y;
            _moveCritter(random);

             that.map.grid[x][y] = '_';
            //console.log('after _moveCritter')
        }
       //console.log(that.x, that.y);

    }
   // _generateCoordinateInBound()

      setInterval(_generateCoordinateInBound, 1000);

    function _moveCritter(func) {
        console.log('from this');

        moves[func]();
        console.log('MAP');
        that.map._updateGrid()
    }

    //moves[1] // Temporarily removed; probably for testing
    console.log('Current position - x: ' + this.x + ' y: ' + this.y)
}

// Find out how to place critter on grid of map instance
// Not in use at the moment
Map.prototype.critterLocation = function(type, x, y) {
    console.log('Critter location working')
    console.log(this.grid)
    this.grid[x][y] = type;
}

// Run every time new critter is added to map
// Try to implement this into Critter constructor
// Creates an inventory of 'critters' in the Map instance
Map.prototype._addCrittersToMap = function(critter) {
    this.critters[critter.type] = critter;
}

// Refreshes grid to reflect new location of critter
Map.prototype._updateGrid = function() {
    console.log(this.grid);
    var critters = this.critters;
    for (var critter in critters) {
        //console.log(critters[critter])
        var x = critters[critter].x;
        var y = critters[critter].y;

        this.grid[x][y] = critters[critter].symbol;

    }
    //console.log(this)
}

var map1 = new Map(10, 10);
var firstCritter = new Critter(9, 2, 'firstCritter', map1);
firstCritter.comeAlive();

var critter2 = new Critter(1,1, 'critter2', map1);
critter2.comeAlive();
//map1._addCrittersToMap(firstCritter);

// var secondCritter = new Critter(1, 1, 'secondCritter');
// secondCritter.comeAlive();
// map._addCrittersToMap(secondCritter);

// var thirdCritter = new Critter(1, 9, 'thirdCritter');
// thirdCritter.comeAlive();
// map._addCrittersToMap(thirdCritter);

// var fourthCritter = new Critter(9, 1, 'fourthCritter');
// fourthCritter.comeAlive();
// map._addCrittersToMap(fourthCritter);

// var fifthCritter = new Critter(9, 4, 'fifthCritter');
// fifthCritter.comeAlive();
// map._addCrittersToMap(fifthCritter);

// var sixthCritter = new Critter(9, 3, 'sixthCritter');
// sixthCritter.comeAlive();
// map._addCrittersToMap(sixthCritter);

// map1.updateGrid(); // Places critter on map before spawning obstacles

// Spawns obstacles/rooms
map1.generateRooms(3);
// map1.generateRooms();
// map1.generateRooms();
//map.critter(5,5); // Places an 'O' on coordinate [5, 5]
//map.critterLocation('0', 2, 2) // Places 'O' on coordinate [2,2]

//console.log(firstCritter.comeAlive());

// Update map every second
// Initial render of all critters and obstacles before setInterval is responsible for updating grid
// map1.updateGrid();

<commit_msg>Critters can be created and rendered by Map.prototype.spawnCritters. Method accepts critter type and quantity<commit_after>function Map(width, height) {
    this.width = width;
    this.height = height;
    this.critters = {}
    this.grid = (function() {
            var arr = [];
            for (var i = 0; i < this.width; i++) {
                var row = [];
                for (var j = 0; j < this.height; j++) {
                    row.push('_');
                }
                arr.push(row);
            }
            return arr;
        }).bind(this)();
    this.gridReference = this.grid
}

/* GENERATING RANDOM ROOMS/OBSTACLES(TESTING) */

Map.prototype.generateRooms = function(rooms) {
    var that = this;
    // var randomX = Math.floor(Math.random() * this.width);
    // var randomY = Math.floor(Math.random() * this.height);
   // console.log(randomX, randomY)
    function helperGeneratePosition() {
        var randomX = Math.floor(Math.random() * that.width);
        var randomY = Math.floor(Math.random() * that.height);
        return [randomX, randomY];
    }
    function helperGenerateRoomSize() {
        var randomWidth = Math.floor(Math.random() * 3) + 2;
        var randomHeight = Math.floor(Math.random() * 3) + 2;
        return [randomWidth, randomHeight];
    }
    function generateRoom() {
        var randomPosition = helperGeneratePosition();
        var x = randomPosition[0];
        var y = randomPosition[1];
        var randomSize = helperGenerateRoomSize();
        var width = randomSize[0];
        var height = randomSize[1];
        if (x + width > that.width || y + height > that.height) {
           // console.log('Rerendering...');
           generateRoom();
        }
        else {
            for (var i = x; i < x + width; i++) {
                for (var j = y; j < y + height; j++) {
                    that.grid[i][j] = 'X';
                }
            }
        }
    }
    for (i = 0; i < rooms; i++) {
        generateRoom()
    }
}

/* MAP METHODS USED BY CRITTER TO TRANSLATE CRITTERS ON MAP */
// Not in use at the moment
Map.prototype.critterLocation = function(type, x, y) {
    console.log('Critter location working')
    console.log(this.grid)
    this.grid[x][y] = type;
}

// Run every time new critter is added to map
// Try to implement this into Critter constructor
// Creates an inventory of 'critters' in the Map instance
Map.prototype._addCrittersToMap = function(critter) {
    this.critters[critter.type] = critter;
}

// Refreshes grid to reflect new location of critter
Map.prototype._updateGrid = function() {
    console.log(this.grid);
    var critters = this.critters;
    for (var critter in critters) {
        //console.log(critters[critter])
        var x = critters[critter].x;
        var y = critters[critter].y;

        this.grid[x][y] = critters[critter].symbol;
    }
}

/* CREATE A CRITTER */
// Use random coordinate generator to generate initial x and y coordinate for critter
function Critter(x, y, type, map) {
    this.map = map;
    this.health = 100;
    this.type = type;
    this.x = x;
    this.y = y;
    this.symbol = 'O';
}
/*  Critter movement
    Reference: Right is +; Down is +
    Run in Critter.prototype.comeAlive
*/
Critter.prototype._moveRight = function() {
    this.x++;
}
Critter.prototype._moveLeft = function() {
    this.x--;
}
Critter.prototype._moveUp = function() {
    this.y--;
}
Critter.prototype._moveDown = function() {
    this.y++;
}

/*
    Generates a random direction for critter to travel
    and moves critter in that direction as long as there is no obstacle.
    Grid is updated with Map method _updateGrid after each move
*/
Critter.prototype.comeAlive = function() {
    console.log(this.type + ' is coming alive');

    this.map._addCrittersToMap(this);
    var that = this;
    var moves = [
                    this._moveRight.bind(this),
                    this._moveLeft.bind(this),
                    this._moveUp.bind(this),
                    this._moveDown.bind(this)
                ];

    function _generateCoordinateInBound() {

        var random = Math.floor(Math.random() * 4);

        if ((that.x == 0 && random == 1) || (random == 1 && that.map.grid[that.x - 1][that.y] !== '_')) {
            _generateCoordinateInBound();
        }
        else if ((that.x == 9 && random == 0) || (random == 0 && that.map.grid[that.x + 1][that.y] !== '_')) { //  Set random to adjust with map width using Redux and state when transferring to React
            _generateCoordinateInBound();
        }
        else if ((that.y == 0 && random  == 2) || (random == 2 && that.map.grid[that.x][that.y - 1] !== '_')) {
            _generateCoordinateInBound();
        }
        else if ((that.y == 9 && random  == 3) || (random == 3 && that.map.grid[that.x][that.y + 1] !== '_')) {
            _generateCoordinateInBound();
        }
        else {
            var x = that.x;
            var y = that.y;
            _moveCritter(random);

             that.map.grid[x][y] = '_';
        }

    }

      setInterval(_generateCoordinateInBound, 1000);

    function _moveCritter(func) {
        console.log('from this');
        moves[func]();
        that.map._updateGrid()
    }
}

// Create a function that accepts 2 parameters: type and number
// Randomly spawn on an empty space on the map the given number of types of critter

Map.prototype.spawnCritters = function(type, number) {
    var that = this;
    var critter,
        coordinates,
        x = _getRandomLatitude(),
        y = _getRandomLongitude()

    console.log(that)
    function _getRandomLatitude() {
        return Math.floor(Math.random() * that.width);
    }

    function _getRandomLongitude() {
        return Math.floor(Math.random() * that.height);
    }
    // while (this.grid[x][y] !== '_') {
    //     console.log('running')
    //     x = _getRandomLongitude();
    //     y = _getRandomLatitude();
    // }
    function verifyCoordinates() {
        console.log('verifying...')
        var x = _getRandomLatitude();
        var y = _getRandomLongitude();
        console.log(x, y)
        if (that.grid[x][y] !== '_') {
            verifyCoordinates();
        }
        else {
            return new Critter(x, y, type+i, that).comeAlive();
        }
    }

    for (i = 0; i < number; i++) {
        coordinates = verifyCoordinates();

        //new Critter(coordinates[0], coordinates[1], type+i, this).comeAlive();
    }
}

var map1 = new Map(10, 10);
// var firstCritter = new Critter(9, 2, 'firstCritter', map1).comeAlive();

// var critter2 = new Critter(1,1, 'critter2', map1);
// critter2.comeAlive();
map1.generateRooms(5);
map1.spawnCritters('rat', 1);

// Spawns obstacles/rooms

<|endoftext|>


<commit_before>// ==UserScript==
// @name        toolset
// @namespace   samsquanchhunter14@gmail.com
// @include     http://aimgames.forummotion.com/*
// @version     1.5
// @grant       none
// ==/UserScript==

//won't work in bchat (yet)
//probably doesn't work as an userscript (this shit should be in onload)
var chatboxElement = document.getElementById('frame_chatbox').contentWindow.document.getElementById('chatbox');

var messages = chatboxElement.children;

/**
 * Returns the user who posted 'msgDOM' chatbox message
 */
function msgSender(msgDOM) {
	if (msgDOM.getElementsByClassName('user-msg')[0] !== undefined) //if this is not a "user joined"/"user dc'ed"/"user left" message
		return msgDOM.getElementsByClassName('user-msg')[0].getElementsByClassName('chatbox-username')[0].innerHTML;
	else
		return null;
}

/**
 * Returns the timestamp of 'msgDOM' chatbox message in HH:MM:SS format
 */
function msgTimestamp(msgDOM) {
	return msgDOM.getElementsByClassName('date-and-time')[0].innerHTML.substring(1, msgDOM.getElementsByClassName('date-and-time')[0].innerHTML.length-1);
}

/**
 * Returns true if 'strg' is dubs and in HH:MM:SS format
 */
function isDubs(strg) {
	strg = strg.substring(6,8); // HH:MM:SS format
	if (strg == "11")
		return true;
	if (strg == "22")
		return true;
	if (strg == "33")
		return true;
	if (strg == "44")
		return true;
	if (strg == "55")
		return true;
	if (strg == "66")
		return true;
	if (strg == "77")
		return true;
	if (strg == "88")
		return true;
	if (strg == "99")
		return true;
	if (strg == "00")
		return true;
	return false;
}

var oldMessagesAmount = messages.length;
/**
 * Returns the amount of new messages since the last time this function was called
 */
function newMsgs() {
	return messages.length - oldMessagesAmount;
}
function resetNewMsgs() {
	oldMessagesAmount = messages.length;
}

/**
 * CHECK 'EM (call this once every chat update)
 */
function checkDubs() {
	for (var i = 0; i < messages.length; i++) { //DON'T DO A FOREACH (VAR X IN Y) IN HTMLCOLLECTIONS IT WILL THROW AN ERROR
		if (isDubs(msgTimestamp(messages[i]))) {
			var dubsSpan = document.createElement('span');
			dubsSpan.style = "color:red";
			dubsSpan.innerHTML = ' CHECK \'EM';
			messages[i].children[0].appendChild(dubsSpan);
		}
	}
}

var boxElement = document.createElement('div'); //box element that holds the new msg ribbon
boxElement.className = 'box'; //not element.class
boxElement.style = 'position: fixed;left: 1%;top: 2%;';
var ribbonElement = document.createElement('div'); //new msg ribbon
ribbonElement.className = 'ribbon'; //not element.class
var ribbonText = document.createElement('span'); //new msg string (X new msgs)
ribbonElement.appendChild(ribbonText);
/**
 * Makes the 'new message!' box
 */
function makeBox() {
  console.log('is at cbox - ' + getScrollTop() + ' new msgs - ' + newMsgs());
  if (getScrollTop() <= 1700) { //are we not at cbox (doesnt work in bchat, may bug in different resolutions) --- 1700 is scroll top 1400 is scroll bottom in my resolution
    ////// QUESTION >>>> IS THIS SLOW? THIS SEEMS TO UPDATE THE DOM EVERY TIME THE FUNCTION IS CALLED; IS IT FASTER TO CHECK IF THE INNERHTML NEEDS TO BE CHANGED?
    if (newMsgs() === 1)
    	ribbonText.innerHTML = '1 new msg';
    else
    	ribbonText.innerHTML = newMsgs() + ' new msgs';
    if (newMsgs() > 0) { //note MSG NUMBER CAN BE UNDER 0!!! since the non-archive chat removes old messages or something... this may be a problem (if someone posts 1 msg and 1 is removed the new msg counter is not displayed)
      if (boxElement.children[0] === undefined) //if the box element doesnt already exist
        boxElement.appendChild(ribbonElement);
    }
    else if (boxElement.children[0] !== undefined) //if the box element wasnt added or was removed before
      boxElement.removeChild(ribbonElement);
  }/* else {
    remBox();
  }*/
}
/**
 * Removes the box (faster-ish than doing it 2x a second - do it onscroll)
 */
function remBox() {
  if (getScrollTop() > 1700) {
    resetNewMsgs(); //resets the new msgs counter; you shouldnt do this once newMsgs() is called since this function is called 2x a second so the "new msg" ribbon would only appear for half a second then disappear as the new msg counter would be 0....
    if (boxElement.children[0] !== undefined) //if the box element wasnt added or was removed before
      boxElement.removeChild(ribbonElement);
  }
}

// css for the 'new msg' ribbon
var ribbonCSS = "@import url(\'http://fonts.googleapis.com/css?family=Noto+Sans:400,700\');.box{width: 0px;height: 0px;position: relative;border: 0px solid #BBB;background: #EEE;font-family: \'Noto Sans\', sans-serif}.ribbon{width: 200px;background: #e43;position: absolute;top: 0px;left: -10px;text-align: center;line-height: 50px;letter-spacing: 1px;color: #ff0000;font-size: 18px}.ribbon span{width: 200px;background: #e43;position: absolute;top: 25px;left: -50px;text-align: center;line-height: 50px;letter-spacing: 1px;color: #f0f0f0;transform: rotate(-45deg);-webkit-transform: rotate(-45deg);font-size: 18px}.ribbon span::before{content: \"\";position:absolute;left:0px;top:100%;z-index:-1;border-left:3px solid #8F0808;border-right:3px solid transparent;border-bottom:3px solid transparent;border-top:3px solid #8F0808}.ribbon span::after{content:\"\";position:absolute;right:0px;top:100%;z-index:-1;border-left:3px solid transparent;border-right:3px solid #8F0808;border-bottom:3px solid transparent;border-top:3px solid #8F0808}";

var gstyle;
function injectCSS(css) {
    var head;
    head = document.getElementsByTagName('head')[0];
    if (!head) { return; }
    gstyle = document.createElement('style');
    gstyle.type = 'text/css';
    gstyle.innerHTML = css;
    head.appendChild(gstyle);
}
/* doesnt work wtf
function isScrolledIntoView(el) {
    var elemTop = el.getBoundingClientRect().top;
    var elemBottom = el.getBoundingClientRect().bottom;

    var isVisible = (getScrollTop() >= window.scrollY) && (elemBottom <= window.innerHeight);
    return isVisible;
}
*/
function getScrollTop() { //// http://stackoverflow.com/questions/6691558/how-do-i-make-a-div-follow-me-as-i-scroll-down-the-page
    if (window.scrollY !== undefined)
      return window.scrollY;

    if (typeof window.pageYOffset !== 'undefined' ) {
      // Most browsers
      return window.pageYOffset;
    }

    var d = document.documentElement;
    if (d.clientHeight) {
      // IE in standards mode
      return d.scrollTop;
    }

    // IE in quirks mode
    return document.body.scrollTop;
}

window.addEventListener('load', function() {
  // inject our css
  injectCSS(ribbonCSS);

  // make an empty div where the box will go
  document.body.appendChild(boxElement);

  // get the count of new msgs
  setInterval(makeBox, 500);

  ////KEEPS BOX AT THE TOP OF THE SCREEN
  window.addEventListener('scroll', function() {
    remBox();
    //make the box scroll with the screen
    var box = document.getElementById('box'),
    scroll = getScrollTop();

    if (box !== null) {
      if (scroll <= 28) {
        box.style.top = "30px";
      } else {
        box.style.top = (scroll + 2) + "px";
      }
    }
  }, false);

}, false);
// += works too

function getUserTagsOnDocument() {
  var atags = document.getElementsByTagName('a')
  var utags = [ ];
  for (var i in atags) {
  	if (atags[i] && atags[i].href && atags[i].href.match(/\/u/))
  		utags[utags.length] = atags[i];
  }
  return utags;
}
<commit_msg>Update alive_toolset.js<commit_after>// ==UserScript==
// @name        toolset
// @namespace   samsquanchhunter14@gmail.com
// @include     http://aimgames.forummotion.com/*
// @version     1.13
// @grant       none
// ==/UserScript==

//won't work in bchat (yet)
//probably doesn't work as an userscript (this shit should be in onload)
var chatboxElement = document.getElementById('frame_chatbox').contentWindow.document.getElementById('chatbox');

var messages = chatboxElement.children;

/**
 * Returns the user who posted 'msgDOM' chatbox message
 */
function msgSender(msgDOM) {
	if (msgDOM.getElementsByClassName('user-msg')[0] !== undefined) //if this is not a "user joined"/"user dc'ed"/"user left" message
		return msgDOM.getElementsByClassName('user-msg')[0].getElementsByClassName('chatbox-username')[0].innerHTML;
	else
		return null;
}

/**
 * Returns the timestamp of 'msgDOM' chatbox message in HH:MM:SS format
 */
function msgTimestamp(msgDOM) {
	return msgDOM.getElementsByClassName('date-and-time')[0].innerHTML.substring(1, msgDOM.getElementsByClassName('date-and-time')[0].innerHTML.length-1);
}

/**
 * Returns true if 'strg' is dubs and in HH:MM:SS format
 */
function isDubs(strg) {
	strg = strg.substring(6,8); // HH:MM:SS format
	if (strg == "11")
		return true;
	if (strg == "22")
		return true;
	if (strg == "33")
		return true;
	if (strg == "44")
		return true;
	if (strg == "55")
		return true;
	if (strg == "66")
		return true;
	if (strg == "77")
		return true;
	if (strg == "88")
		return true;
	if (strg == "99")
		return true;
	if (strg == "00")
		return true;
	return false;
}

var oldMessagesAmount = messages.length;
/**
 * Returns the amount of new messages since the last time this function was called
 */
function newMsgs() {
	return messages.length - oldMessagesAmount;
}
function resetNewMsgs() {
	oldMessagesAmount = messages.length;
}

/**
 * CHECK 'EM (call this once every chat update)
 */
function checkDubs() {
	for (var i = 0; i < messages.length; i++) { //DON'T DO A FOREACH (VAR X IN Y) IN HTMLCOLLECTIONS IT WILL THROW AN ERROR
		if (isDubs(msgTimestamp(messages[i]))) {
			var dubsSpan = document.createElement('span');
			dubsSpan.style = "color:red";
			dubsSpan.innerHTML = ' CHECK \'EM';
			messages[i].children[0].appendChild(dubsSpan);
		}
	}
}

var boxElement = document.createElement('div'); //box element that holds the new msg ribbon
boxElement.className = 'box'; //not element.class
boxElement.style = 'position: fixed;left: 1%;top: 2%;';
var ribbonElement = document.createElement('div'); //new msg ribbon
ribbonElement.className = 'ribbon'; //not element.class
var ribbonText = document.createElement('span'); //new msg string (X new msgs)
ribbonElement.appendChild(ribbonText);
/**
 * Makes the 'new message!' box
 */
function makeBox() {
  console.log('is at cbox - ' + getScrollTop() + ' new msgs - ' + newMsgs());
  if (getScrollTop() <= 1700) { //are we not at cbox (doesnt work in bchat, may bug in different resolutions) --- 1700 is scroll top 1400 is scroll bottom in my resolution
    ////// QUESTION >>>> IS THIS SLOW? THIS SEEMS TO UPDATE THE DOM EVERY TIME THE FUNCTION IS CALLED; IS IT FASTER TO CHECK IF THE INNERHTML NEEDS TO BE CHANGED?
    if (newMsgs() === 1)
    	ribbonText.innerHTML = '1 new msg';
    else
    	ribbonText.innerHTML = newMsgs() + ' new msgs';
    if (newMsgs() > 0) { //note MSG NUMBER CAN BE UNDER 0!!! since the non-archive chat removes old messages or something... this may be a problem (if someone posts 1 msg and 1 is removed the new msg counter is not displayed)
      if (boxElement.children[0] === undefined) //if the box element doesnt already exist
        boxElement.appendChild(ribbonElement);
    }
    else if (boxElement.children[0] !== undefined) //if the box element wasnt added or was removed before
      boxElement.removeChild(ribbonElement);
  }/* else {
    remBox();
  }*/
}
/**
 * Removes the box (faster-ish than doing it 2x a second - do it onscroll)
 */
function remBox() {
  if (getScrollTop() > 1700) {
    resetNewMsgs(); //resets the new msgs counter; you shouldnt do this once newMsgs() is called since this function is called 2x a second so the "new msg" ribbon would only appear for half a second then disappear as the new msg counter would be 0....
    if (boxElement.children[0] !== undefined) //if the box element wasnt added or was removed before
      boxElement.removeChild(ribbonElement);
  }
}

// css for the 'new msg' ribbon
var ribbonCSS = "@import url(\'http://fonts.googleapis.com/css?family=Noto+Sans:400,700\');.box{width: 0px;height: 0px;position: relative;border: 0px solid #BBB;background: #EEE;font-family: \'Noto Sans\', sans-serif}.ribbon{width: 200px;background: #e43;position: absolute;top: 0px;left: -10px;text-align: center;line-height: 50px;letter-spacing: 1px;color: #ff0000;font-size: 18px}.ribbon span{width: 200px;background: #e43;position: absolute;top: 25px;left: -50px;text-align: center;line-height: 50px;letter-spacing: 1px;color: #f0f0f0;transform: rotate(-45deg);-webkit-transform: rotate(-45deg);font-size: 18px}.ribbon span::before{content: \"\";position:absolute;left:0px;top:100%;z-index:-1;border-left:3px solid #8F0808;border-right:3px solid transparent;border-bottom:3px solid transparent;border-top:3px solid #8F0808}.ribbon span::after{content:\"\";position:absolute;right:0px;top:100%;z-index:-1;border-left:3px solid transparent;border-right:3px solid #8F0808;border-bottom:3px solid transparent;border-top:3px solid #8F0808}";

var gstyle;
function injectCSS(css) {
    var head;
    head = document.getElementsByTagName('head')[0];
    if (!head) { return; }
    gstyle = document.createElement('style');
    gstyle.type = 'text/css';
    gstyle.innerHTML = css;
    head.appendChild(gstyle);
}
/* doesnt work wtf
function isScrolledIntoView(el) {
    var elemTop = el.getBoundingClientRect().top;
    var elemBottom = el.getBoundingClientRect().bottom;

    var isVisible = (getScrollTop() >= window.scrollY) && (elemBottom <= window.innerHeight);
    return isVisible;
}
*/
function getScrollTop() { //// http://stackoverflow.com/questions/6691558/how-do-i-make-a-div-follow-me-as-i-scroll-down-the-page
    if (window.scrollY !== undefined)
      return window.scrollY;

    if (typeof window.pageYOffset !== 'undefined' ) {
      // Most browsers
      return window.pageYOffset;
    }

    var d = document.documentElement;
    if (d.clientHeight) {
      // IE in standards mode
      return d.scrollTop;
    }

    // IE in quirks mode
    return document.body.scrollTop;
}

function getUserTagsOnDocument() {
  var atags = document.getElementsByTagName('a')
  var utags = [ ];
  for (var i in atags) {
  	if (atags[i] && atags[i].href && atags[i].href.match(/\/u/))
  		utags[utags.length] = atags[i];
  }
  return utags;
}

/**
 * Calls function 'callback' with the page 'url''s contents
 */
function getPageContents(callback, url, params) { ////// http://stackoverflow.com/a/28728475
  http = new XMLHttpRequest();
  if (params !== undefined) {
    http.open('POST', url, true);
    http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  } else {
    http.open('GET', url, true);
  }
  http.onreadystatechange = function () {
    if (http.readyState == 4 && http.status == 200) {
      callback(http.responseText);
      //console.log(http.responseText)
    }
  }
  http.send(params);
}

/**
 * Profile details from the last time getProfileDetails() (actually getProfileDetailsCallback) was called (profile-advanced-details element)
 */
var lastHoveredProfileDetails;
/**
 * Temporary doc stuff that i can browse in browser console (allan please remove eventually)
 */
var tempdoc;
/**
 * used for getProfileDetails
 */
function getProfileDetailsCallback(response) {
  //errors for some reason
  //var parser = new DOMParser();
  //tempdoc = parser.parseFromString(response, "text/xml");

  //unsafe or whatever
  //if (document.implementation.createHTMLDocument) //new browsers
  	tempdoc = document.implementation.createHTMLDocument();
  //else //ie8 and below
  //	tempdoc = new ActiveXObject("htmlfile");

  //really fucked but works
  //console.log('resp' + response);
  tempdoc.body.innerHTML = response;

  lastHoveredProfileDetails = tempdoc.getElementById('profile-advanced-details');
}

/**
 * Makes 'lastHoveredProfileDetails' contain profile details from an user's profile link. (e.g http://aimgames.forummotion.com/u1426)
 */
function getProfileDetails(profileLink) {
  getPageContents(getProfileDetailsCallback, profileLink);
};

window.addEventListener('load', function() {
  // inject our css
  injectCSS(ribbonCSS);

  // make an empty div where the box will go
  document.body.appendChild(boxElement);

  // get the count of new msgs
  setInterval(makeBox, 500);

  ////KEEPS BOX AT THE TOP OF THE SCREEN
  window.addEventListener('scroll', function() {
    remBox();
    //make the box scroll with the screen
    var box = document.getElementById('box'),
    scroll = getScrollTop();

    if (box !== null) {
      if (scroll <= 28) {
        box.style.top = "30px";
      } else {
        box.style.top = (scroll + 2) + "px";
      }
    }
  }, false);

}, false);
// += works too
<|endoftext|>