<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";

  var HINT_ELEMENT_CLASS        = "CodeMirror-hint";
  var ACTIVE_HINT_ELEMENT_CLASS = "CodeMirror-hint-active";

  // This is the old interface, kept around for now to stay
  // backwards-compatible.
  CodeMirror.showHint = function(cm, getHints, options) {
    if (!getHints) return cm.showHint(options);
    if (options && options.async) getHints.async = true;
    var newOpts = {hint: getHints};
    if (options) for (var prop in options) newOpts[prop] = options[prop];
    return cm.showHint(newOpts);
  };

  CodeMirror.defineExtension("showHint", function(options) {
    options = parseOptions(this, this.getCursor("start"), options);
    var selections = this.listSelections()
    if (selections.length > 1) return;
    // By default, don't allow completion when something is selected.
    // A hint function can have a `supportsSelection` property to
    // indicate that it can handle selections.
    if (this.somethingSelected()) {
      if (!options.hint.supportsSelection) return;
      // Don't try with cross-line selections
      for (var i = 0; i < selections.length; i++)
        if (selections[i].head.line != selections[i].anchor.line) return;
    }

    if (this.state.completionActive) this.state.completionActive.close();
    var completion = this.state.completionActive = new Completion(this, options);
    if (!completion.options.hint) return;

    CodeMirror.signal(this, "startCompletion", this);
    completion.update(true);
  });

  function Completion(cm, options) {
    this.cm = cm;
    this.options = options;
    this.widget = null;
    this.debounce = 0;
    this.tick = 0;
    this.startPos = this.cm.getCursor("start");
    this.startLen = this.cm.getLine(this.startPos.line).length - this.cm.getSelection().length;

    var self = this;
    cm.on("cursorActivity", this.activityFunc = function() { self.cursorActivity(); });
  }

  var requestAnimationFrame = window.requestAnimationFrame || function(fn) {
    return setTimeout(fn, 1000/60);
  };
  var cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout;

  Completion.prototype = {
    close: function() {
      if (!this.active()) return;
      this.cm.state.completionActive = null;
      this.tick = null;
      this.cm.off("cursorActivity", this.activityFunc);

      if (this.widget && this.data) CodeMirror.signal(this.data, "close");
      if (this.widget) this.widget.close();
      CodeMirror.signal(this.cm, "endCompletion", this.cm);
    },

    active: function() {
      return this.cm.state.completionActive == this;
    },

    pick: function(data, i) {
      var completion = data.list[i];
      if (completion.hint) completion.hint(this.cm, data, completion);
      else this.cm.replaceRange(getText(completion), completion.from || data.from,
                                completion.to || data.to, "complete");
      CodeMirror.signal(data, "pick", completion);
      this.close();
    },

    cursorActivity: function() {
      if (this.debounce) {
        cancelAnimationFrame(this.debounce);
        this.debounce = 0;
      }

      var pos = this.cm.getCursor(), line = this.cm.getLine(pos.line);
      if (pos.line != this.startPos.line || line.length - pos.ch != this.startLen - this.startPos.ch ||
          pos.ch < this.startPos.ch || this.cm.somethingSelected() ||
          (pos.ch && this.options.closeCharacters.test(line.charAt(pos.ch - 1)))) {
        this.close();
      } else {
        var self = this;
        this.debounce = requestAnimationFrame(function() {self.update();});
        if (this.widget) this.widget.disable();
      }
    },

    update: function(first) {
      if (this.tick == null) return
      var self = this, myTick = ++this.tick
      fetchHints(this.options.hint, this.cm, this.options, function(data) {
        if (self.tick == myTick) self.finishUpdate(data, first)
      })
    },

    finishUpdate: function(data, first) {
      if (this.data) CodeMirror.signal(this.data, "update");

      var picked = (this.widget && this.widget.picked) || (first && this.options.completeSingle);
      if (this.widget) this.widget.close();

      if (data && this.data && isNewCompletion(this.data, data)) return;
      this.data = data;

      if (data && data.list.length) {
        if (picked && data.list.length == 1) {
          this.pick(data, 0);
        } else {
          this.widget = new Widget(this, data);
          CodeMirror.signal(data, "shown");
        }
      }
    }
  };

  function isNewCompletion(old, nw) {
    var moved = CodeMirror.cmpPos(nw.from, old.from)
    return moved > 0 && old.to.ch - old.from.ch != nw.to.ch - nw.from.ch
  }

  function parseOptions(cm, pos, options) {
    var editor = cm.options.hintOptions;
    var out = {};
    for (var prop in defaultOptions) out[prop] = defaultOptions[prop];
    if (editor) for (var prop in editor)
      if (editor[prop] !== undefined) out[prop] = editor[prop];
    if (options) for (var prop in options)
      if (options[prop] !== undefined) out[prop] = options[prop];
    if (out.hint.resolve) out.hint = out.hint.resolve(cm, pos)
    return out;
  }

  function getText(completion) {
    if (typeof completion == "string") return completion;
    else return completion.text;
  }

  function buildKeyMap(completion, handle) {
    var baseMap = {
      Up: function() {handle.moveFocus(-1);},
      Down: function() {handle.moveFocus(1);},
      PageUp: function() {handle.moveFocus(-handle.menuSize() + 1, true);},
      PageDown: function() {handle.moveFocus(handle.menuSize() - 1, true);},
      Home: function() {handle.setFocus(0);},
      End: function() {handle.setFocus(handle.length - 1);},
      Enter: handle.pick,
      Tab: handle.pick,
      Esc: handle.close
    };
    var custom = completion.options.customKeys;
    var ourMap = custom ? {} : baseMap;
    function addBinding(key, val) {
      var bound;
      if (typeof val != "string")
        bound = function(cm) { return val(cm, handle); };
      // This mechanism is deprecated
      else if (baseMap.hasOwnProperty(val))
        bound = baseMap[val];
      else
        bound = val;
      ourMap[key] = bound;
    }
    if (custom)
      for (var key in custom) if (custom.hasOwnProperty(key))
        addBinding(key, custom[key]);
    var extra = completion.options.extraKeys;
    if (extra)
      for (var key in extra) if (extra.hasOwnProperty(key))
        addBinding(key, extra[key]);
    return ourMap;
  }

  function getHintElement(hintsElement, el) {
    while (el && el != hintsElement) {
      if (el.nodeName.toUpperCase() === "LI" && el.parentNode == hintsElement) return el;
      el = el.parentNode;
    }
  }

  function Widget(completion, data) {
    this.completion = completion;
    this.data = data;
    this.picked = false;
    var widget = this, cm = completion.cm;

    var hints = this.hints = document.createElement("ul");
    hints.className = "CodeMirror-hints";
    this.selectedHint = data.selectedHint || 0;

    var completions = data.list;
    for (var i = 0; i < completions.length; ++i) {
      var elt = hints.appendChild(document.createElement("li")), cur = completions[i];
      var className = HINT_ELEMENT_CLASS + (i != this.selectedHint ? "" : " " + ACTIVE_HINT_ELEMENT_CLASS);
      if (cur.className != null) className = cur.className + " " + className;
      elt.className = className;
      if (cur.render) cur.render(elt, data, cur);
      else elt.appendChild(document.createTextNode(cur.displayText || getText(cur)));
      elt.hintId = i;
    }

    var pos = cm.cursorCoords(completion.options.alignWithWord ? data.from : null);
    var left = pos.left, top = pos.bottom, below = true;
    hints.style.left = left + "px";
    hints.style.top = top + "px";
    // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor.
    var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth);
    var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight);
    (completion.options.container || document.body).appendChild(hints);
    var box = hints.getBoundingClientRect(), overlapY = box.bottom - winH;
    var scrolls = hints.scrollHeight > hints.clientHeight + 1
    var startScroll = cm.getScrollInfo();

    if (overlapY > 0) {
      var height = box.bottom - box.top, curTop = pos.top - (pos.bottom - box.top);
      if (curTop - height > 0) { // Fits above cursor
        hints.style.top = (top = pos.top - height) + "px";
        below = false;
      } else if (height > winH) {
        hints.style.height = (winH - 5) + "px";
        hints.style.top = (top = pos.bottom - box.top) + "px";
        var cursor = cm.getCursor();
        if (data.from.ch != cursor.ch) {
          pos = cm.cursorCoords(cursor);
          hints.style.left = (left = pos.left) + "px";
          box = hints.getBoundingClientRect();
        }
      }
    }
    var overlapX = box.right - winW;
    if (overlapX > 0) {
      if (box.right - box.left > winW) {
        hints.style.width = (winW - 5) + "px";
        overlapX -= (box.right - box.left) - winW;
      }
      hints.style.left = (left = pos.left - overlapX) + "px";
    }
    if (scrolls) for (var node = hints.firstChild; node; node = node.nextSibling)
      node.style.paddingRight = cm.display.nativeBarWidth + "px"

    cm.addKeyMap(this.keyMap = buildKeyMap(completion, {
      moveFocus: function(n, avoidWrap) { widget.changeActive(widget.selectedHint + n, avoidWrap); },
      setFocus: function(n) { widget.changeActive(n); },
      menuSize: function() { return widget.screenAmount(); },
      length: completions.length,
      close: function() { completion.close(); },
      pick: function() { widget.pick(); },
      data: data
    }));

    if (completion.options.closeOnUnfocus) {
      var closingOnBlur;
      cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); });
      cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); });
    }

    cm.on("scroll", this.onScroll = function() {
      var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect();
      var newTop = top + startScroll.top - curScroll.top;
      var point = newTop - (window.pageYOffset || (document.documentElement || document.body).scrollTop);
      if (!below) point += hints.offsetHeight;
      if (point <= editor.top || point >= editor.bottom) return completion.close();
      hints.style.top = newTop + "px";
      hints.style.left = (left + startScroll.left - curScroll.left) + "px";
    });

    CodeMirror.on(hints, "dblclick", function(e) {
      var t = getHintElement(hints, e.target || e.srcElement);
      if (t && t.hintId != null) {widget.changeActive(t.hintId); widget.pick();}
    });

    CodeMirror.on(hints, "click", function(e) {
      var t = getHintElement(hints, e.target || e.srcElement);
      if (t && t.hintId != null) {
        widget.changeActive(t.hintId);
        if (completion.options.completeOnSingleClick) widget.pick();
      }
    });

    CodeMirror.on(hints, "mousedown", function() {
      setTimeout(function(){cm.focus();}, 20);
    });

    CodeMirror.signal(data, "select", completions[0], hints.firstChild);
    return true;
  }

  Widget.prototype = {
    close: function() {
      if (this.completion.widget != this) return;
      this.completion.widget = null;
      this.hints.parentNode.removeChild(this.hints);
      this.completion.cm.removeKeyMap(this.keyMap);

      var cm = this.completion.cm;
      if (this.completion.options.closeOnUnfocus) {
        cm.off("blur", this.onBlur);
        cm.off("focus", this.onFocus);
      }
      cm.off("scroll", this.onScroll);
    },

    disable: function() {
      this.completion.cm.removeKeyMap(this.keyMap);
      var widget = this;
      this.keyMap = {Enter: function() { widget.picked = true; }};
      this.completion.cm.addKeyMap(this.keyMap);
    },

    pick: function() {
      this.completion.pick(this.data, this.selectedHint);
    },

    changeActive: function(i, avoidWrap) {
      if (i >= this.data.list.length)
        i = avoidWrap ? this.data.list.length - 1 : 0;
      else if (i < 0)
        i = avoidWrap ? 0  : this.data.list.length - 1;
      if (this.selectedHint == i) return;
      var node = this.hints.childNodes[this.selectedHint];
      node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, "");
      node = this.hints.childNodes[this.selectedHint = i];
      node.className += " " + ACTIVE_HINT_ELEMENT_CLASS;
      if (node.offsetTop < this.hints.scrollTop)
        this.hints.scrollTop = node.offsetTop - 3;
      else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight)
        this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3;
      CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node);
    },

    screenAmount: function() {
      return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1;
    }
  };

  function applicableHelpers(cm, helpers) {
    if (!cm.somethingSelected()) return helpers
    var result = []
    for (var i = 0; i < helpers.length; i++)
      if (helpers[i].supportsSelection) result.push(helpers[i])
    return result
  }

  function fetchHints(hint, cm, options, callback) {
    if (hint.async) {
      hint(cm, callback, options)
    } else {
      var result = hint(cm, options)
      if (result && result.then) result.then(callback)
      else callback(result)
    }
  }

  function resolveAutoHints(cm, pos) {
    var helpers = cm.getHelpers(pos, "hint"), words
    if (helpers.length) {
      var resolved = function(cm, callback, options) {
        var app = applicableHelpers(cm, helpers);
        function run(i) {
          if (i == app.length) return callback(null)
          fetchHints(app[i], cm, options, function(result) {
            if (result && result.list.length > 0) callback(result)
            else run(i + 1)
          })
        }
        run(0)
      }
      resolved.async = true
      resolved.supportsSelection = true
      return resolved
    } else if (words = cm.getHelper(cm.getCursor(), "hintWords")) {
      return function(cm) { return CodeMirror.hint.fromList(cm, {words: words}) }
    } else if (CodeMirror.hint.anyword) {
      return function(cm, options) { return CodeMirror.hint.anyword(cm, options) }
    } else {
      return function() {}
    }
  }

  CodeMirror.registerHelper("hint", "auto", {
    resolve: resolveAutoHints
  });

  CodeMirror.registerHelper("hint", "fromList", function(cm, options) {
    var cur = cm.getCursor(), token = cm.getTokenAt(cur);
    var to = CodeMirror.Pos(cur.line, token.end);
    if (token.string && /\w/.test(token.string[token.string.length - 1])) {
      var term = token.string, from = CodeMirror.Pos(cur.line, token.start);
    } else {
      var term = "", from = to;
    }
    var found = [];
    for (var i = 0; i < options.words.length; i++) {
      var word = options.words[i];
      if (word.slice(0, term.length) == term)
        found.push(word);
    }

    if (found.length) return {list: found, from: from, to: to};
  });

  CodeMirror.commands.autocomplete = CodeMirror.showHint;

  var defaultOptions = {
    hint: CodeMirror.hint.auto,
    completeSingle: true,
    alignWithWord: true,
    closeCharacters: /[\s()\[\]{};:>,]/,
    closeOnUnfocus: true,
    completeOnSingleClick: true,
    container: null,
    customKeys: null,
    extraKeys: null
  };

  CodeMirror.defineOption("hintOptions", null);
});
<commit_msg>Remove unnecessary files<commit_after><|endoftext|>


<commit_before>/**
* Module to seed a database.
*
* @todo re-write to use async to reduce the nested function, and quit on completion
* @todo make model loading more effecient
*
*/

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    async = require('async'),
    _ = require('underscore'),
    fs = require('fs');

var async = require('async');

/**
* Bootstrap our models
* @note this is the same code as found in server.js
*
* @todo we can combine the models require and definintion (below) into one function.
*
*/
var models_path = __dirname + '/app/models';
fs.readdirSync(models_path).forEach(function(file) {
    require(models_path + '/' + file);
});

// Saving in array allows us to call below in doSeed function.
// @todo make dynamic to load models automatically.
var models = {};
models.Quote = mongoose.model('Quote');
models.Application = mongoose.model('Application');
models.User = mongoose.model('User');
models.Vendor = mongoose.model('Vendor');
models.Program = mongoose.model('Program');

/**
* Get our seed data
* @note again this is not the most elegant, we should be doing something
* more automated based on model files... ie: check if seed data exists then add it to our array
*
* @note we sould include some type of functionality to automatically pluralize / depluralize names
* Keep in mind we might need to call in a specific order
*
*/
var resources = {};
resources.User          = require('./seed_data/user').seed();
resources.Vendor        = require('./seed_data/vendor').seed();
resources.Program       = require('./seed_data/program').seed();
resources.Application   = require('./seed_data/application').seed();
resources.Quote         = require('./seed_data/quote').seed();

/**
 * Main application entry file.
 * Please note that the order of loading is important.
 */
var env = process.env.NODE_ENV || 'development',
    config = require('./config/config')[env],
    mongoose = require('mongoose');

// create database connection
var db = mongoose.connect(config.db, function() {
    console.log('Connected to ' + env + ' database!');

    // Drop all our defined collections using async.
    // this prevents from dropping the whole db, which prevents us from logging back in
    // because it drops the high level users collection that mongo uses to register access
    var doDrops = [];

    // loop through resources
/*
    _.each(resources, function(value, key) {

        console.log('Registering ' + key + ' collection for dropping');

        var dropFunction = function(callback) {

            // drop this collection
            db.connection.db.dropCollection(key, function() {
                console.log('Collection ' + key + ' dropped');
                callback();
            });

            console.log(db.connection.collections[key]);

            db.connection.collections[key].drop( function(err) {
                console.log('Collection ' + key + ' dropped');
                callback();
            });

        };

        doDrops.push(dropFunction);

    });
*/

    // here we access the db collections
    // as defined by the database itself.
    // this is instead of dropping the whole database, which disconnects us from mongolab
    _.each(db.connection.collections, function(collection) {

        var name = collection.name;
        console.log('Prepping ' + name + ' for dropping');

        var dropFunction = function(callback) {
            collection.drop( function(err) {
                console.log('Collection ' + name + ' dropped');
                callback();
            });
        }

        doDrops.push(dropFunction);

    });

    var closeAndReconnect = function(callback) {
        // close our connnection
        db.connection.close(function(){
            console.log('Database connection closed, re-opening now...');

            // reconnect to database
            db = mongoose.connect(config.db, function() {
                console.log('Re-connected');
                callback();
            });
        });
    };

    doDrops.push(closeAndReconnect);

    async.series(doDrops, function() {
        // call seeding function
        doSeed();
    });

});

/**
* Function to do the actual seed. Will be called once database is dropped,
* and the connection is closed and re-opened.
*
*/
var doSeed = function() {

    var needsSeed = [];

    // loop through resources
    _.each(resources, function(value, key) {

        console.log('Registering ' + key + ' collection for seeding');

        // loop through our resource items
        _.each(value, function(contents) {

            // carete new Mongoose object
            var item = new models[key](contents);

            // define our seed function, with references to item
            var doThis = function(callback) {

                // save mongo object
                item.save(function(err, data) {
                    if(err) throw(err);
                    console.log(key + ' ' + item._id + ' created.');
                    // async serices will pass param whcih is callbacl
                    // first param is error, second is result
                    callback(null, item);
                });

            };

            // Push to our seeding function array
            needsSeed.push(doThis);

        });

    });

    /**
    * Perform the seed, then exit on success
    * async.series() will run an array of functions.
    * Each should have a callback, which will be the first param
    *
    */
    async.series(needsSeed, function() {
        process.exit();
    });

};<commit_msg>Fix for linting<commit_after>/**
* Module to seed a database.
*
* @todo re-write to use async to reduce the nested function, and quit on completion
* @todo make model loading more effecient
*
*/

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    async = require('async'),
    _ = require('underscore'),
    fs = require('fs');

var async = require('async');

/**
* Bootstrap our models
* @note this is the same code as found in server.js
*
* @todo we can combine the models require and definintion (below) into one function.
*
*/
var models_path = __dirname + '/app/models';
fs.readdirSync(models_path).forEach(function(file) {
    require(models_path + '/' + file);
});

// Saving in array allows us to call below in doSeed function.
// @todo make dynamic to load models automatically.
var models = {};
models.Quote = mongoose.model('Quote');
models.Application = mongoose.model('Application');
models.User = mongoose.model('User');
models.Vendor = mongoose.model('Vendor');
models.Program = mongoose.model('Program');

/**
* Get our seed data
* @note again this is not the most elegant, we should be doing something
* more automated based on model files... ie: check if seed data exists then add it to our array
*
* @note we sould include some type of functionality to automatically pluralize / depluralize names
* Keep in mind we might need to call in a specific order
*
*/
var resources = {};
resources.User          = require('./seed_data/user').seed();
resources.Vendor        = require('./seed_data/vendor').seed();
resources.Program       = require('./seed_data/program').seed();
resources.Application   = require('./seed_data/application').seed();
resources.Quote         = require('./seed_data/quote').seed();

/**
 * Main application entry file.
 * Please note that the order of loading is important.
 */
var env = process.env.NODE_ENV || 'development',
    config = require('./config/config')[env],
    mongoose = require('mongoose');

// create database connection
var db = mongoose.connect(config.db, function() {
    console.log('Connected to ' + env + ' database!');

    // Drop all our defined collections using async.
    // this prevents from dropping the whole db, which prevents us from logging back in
    // because it drops the high level users collection that mongo uses to register access
    var doDrops = [];

    // loop through resources
/*
    _.each(resources, function(value, key) {

        console.log('Registering ' + key + ' collection for dropping');

        var dropFunction = function(callback) {

            // drop this collection
            db.connection.db.dropCollection(key, function() {
                console.log('Collection ' + key + ' dropped');
                callback();
            });

            console.log(db.connection.collections[key]);

            db.connection.collections[key].drop( function(err) {
                console.log('Collection ' + key + ' dropped');
                callback();
            });

        };

        doDrops.push(dropFunction);

    });
*/

    // here we access the db collections
    // as defined by the database itself.
    // this is instead of dropping the whole database, which disconnects us from mongolab
    _.each(db.connection.collections, function(collection) {

        var name = collection.name;
        console.log('Prepping ' + name + ' for dropping');

        var dropFunction = function(callback) {
            collection.drop( function(err) {
                console.log('Collection ' + name + ' dropped');
                callback();
            });
        };

        doDrops.push(dropFunction);

    });

    var closeAndReconnect = function(callback) {
        // close our connnection
        db.connection.close(function(){
            console.log('Database connection closed, re-opening now...');

            // reconnect to database
            db = mongoose.connect(config.db, function() {
                console.log('Re-connected');
                callback();
            });
        });
    };

    doDrops.push(closeAndReconnect);

    async.series(doDrops, function() {
        // call seeding function
        doSeed();
    });

});

/**
* Function to do the actual seed. Will be called once database is dropped,
* and the connection is closed and re-opened.
*
*/
var doSeed = function() {

    var needsSeed = [];

    // loop through resources
    _.each(resources, function(value, key) {

        console.log('Registering ' + key + ' collection for seeding');

        // loop through our resource items
        _.each(value, function(contents) {

            // carete new Mongoose object
            var item = new models[key](contents);

            // define our seed function, with references to item
            var doThis = function(callback) {

                // save mongo object
                item.save(function(err, data) {
                    if(err) throw(err);
                    console.log(key + ' ' + item._id + ' created.');
                    // async serices will pass param whcih is callbacl
                    // first param is error, second is result
                    callback(null, item);
                });

            };

            // Push to our seeding function array
            needsSeed.push(doThis);

        });

    });

    /**
    * Perform the seed, then exit on success
    * async.series() will run an array of functions.
    * Each should have a callback, which will be the first param
    *
    */
    async.series(needsSeed, function() {
        process.exit();
    });

};<|endoftext|>


<commit_before>function hide_annotation_form(annoid) {
    $("#annotationform-"+annoid).hide();
    $("#annotations-"+annoid).show();
    $("#selectable-"+annoid).text(gettext("Annotate"));
    $("#annotationrealform-"+annoid)[0].reset();
    $("#editable-"+annoid).show();
    if(annotation_objects[annoid].annotation_count >0){
      $("#annotationtoolbox-"+annoid).show();
    }
}
$(function(){
    var options_bill = {
         serviceUrl:'/bill/auto_complete/',
         minChars:2,
         maxHeight:400,
         width:400,
         deferRequestBy: 100, //miliseconds
         onSelect: function(value, data, me){
            me.siblings("input[name$='bill_id']").val(data);
            me.siblings("input[type$='submit']").removeAttr('disabled'); },
         };

    var options_mk = {
         serviceUrl:'/member/auto_complete/',
         minChars:0,
         maxHeight:400,
         width:150,
         deferRequestBy: 100, //miliseconds
         };

    $('input.bill_input').autocomplete(options_bill);
    $('input.bill_input').keydown(function() {
        $(this).siblings("input[name$='bill_id']").val('');
        $(this).siblings("input[type$='submit']").attr('disabled', 'disabled'); });
    $("input[name$='mk_name']").autocomplete(options_mk);

    $(".annotation-content").each(function(){
        var annoid = $(this).attr("id").split("-")[1];
        annotation_objects[annoid] = new Annotations(annoid);
    });
    for(var a in annotation_objects){
        annotation_objects[a].importQuotes();
        annotation_objects[a].insertQuotes();
    }
    $(".annotationform-link").click(function(e){
      e.preventDefault();
      if (!window.logged_in) {
          var msg = gettext("Sorry, only logged users can annotate.");
          $.jGrowl(msg, {sticky: true});
          return false
      }
      if (!window.permission) {
          var msg = $("#message_permission").html()
          $.jGrowl(msg, {sticky: true});
          return false
      }

      var annoid = $(this).attr("id").split("-")[1];
      annotation_objects[annoid].toggleSelectView();
      if($("#annotations-"+annoid).css("display")=="none"){
        hide_annotation_form(annoid);
      } else{
        if (!$("#annotationform-"+annoid).length) {
            var speech_part = {id: annoid, length: window.parts_lengths[annoid] };
            $("#annotations-"+annoid).before(tmpl("annotationform", {speech_part: speech_part}))
            $(".annotationform-cancel").click(function(e) {
                e.preventDefault();
                var annoid = $(this).attr("id").split("-")[1];
                annotation_objects[annoid].toggleSelectView();
                hide_annotation_form(annoid);
            });
          $("#annotationrealform-"+annoid).submit(function(e){
            var id = $(this).attr("id").split("-")[1];
            if($("#selection_start-"+id).val()=="" || $("#selection_end-"+id).val()==""){
              alert(gettext("Please make a selection."));
              e.preventDefault();
              return false;
            }
            return true;
          });
            $('input[name=color]').colorPicker();
        }
        else
            $("#annotationform-"+annoid).show();
        $(this).text(gettext("Cancel"));
        $("#annotations-"+annoid).hide();
        $("#editable-"+annoid).hide();
        $("#annotationtoolbox-"+annoid).hide();
      }
    });
  $(".markall").click(function(e){
    var aid = $(this).attr("id").split("-")[1];
    if($(this).attr('checked')){
      annotation_objects[aid].updateDefaultAnnotationColor("self");
    } else{
      annotation_objects[aid].updateDefaultAnnotationColor("inherit");
    }
  });
  $(".reallydelete").live("submit", function(e){
    var anno_id = $(this).children('[name=annotation_id]').val();
    var username = $('#annotation-'+anno_id+' a.user-link').html();

    if (!window.is_staff && username != window.username){
        var msg = $("#message_staff").html()
        $.jGrowl(msg, {sticky: true});
        return false
    }
    return confirm(gettext('Delete can not be un-done. Are you sure?'));
  });
  $(".annotationflagselect").change(function(e){
    var id = $(this).parents("form").attr("id").split("-")[1];
    var val = parseInt($(this).val());
    var color = null;
    switch(val){
      case 0: // Put more colors here
        color = "#99ccff"; break;
    }
    if(color != null){
      $("#color_value").val(color);
      $("#annotationcolor-"+id).val(color);
      $("div.color_picker").css("background-color", color);
    }
  });
  $(".toggle").live("click", function(e){
     e.preventDefault();
     var id = $(this).attr("id");
     if (id == ""){
       var url = $(this).attr("href");
       var sel = $("."+url.substring(1,url.length)+"-container");
     } else {var sel = $("#"+id+"-container");}
     sel.toggle();
  });

    /** infinite scroll **/

    (function(){
        var _isFloat = false;
        var _isFooterVisible = false;

        var _isActive = function() {
            return ($(window).width() > 1200 && $(window).height() > 500);
        };

        var _float = function() {
            var appheader = $('#app-header');
            var body = $('body');
            var breadcrumb = $('section.container > ul.breadcrumb');
            var sidebar = $('#content-main > div > div.row > div.span3');
            var appheader_margin_left = appheader.css('margin-left');
            var appheader_margin_right = appheader.css('margin-right');
            var sidebar_left = sidebar.position().left;
            var breadcrumbheight = breadcrumb.height();
            body.addClass('infinity-protocol');
            appheader.css({
                'padding-left' : appheader_margin_left,
                'padding-right' : appheader_margin_right,
                'background' : body.css('background')
            });
            var appheader_height = appheader.height();
            var headerHeight = breadcrumbheight + appheader_height + 25;
            breadcrumb.css({
                'top' : appheader_height + 'px',
                'background' : body.css('background'),
            });
            sidebar.css({
                'top' : headerHeight+'px',
                'left' : sidebar_left + 'px',
                'height' : ($.waypoints('viewportHeight') - headerHeight - 5) + 'px',
            });
        };

        var _unfloat = function() {
            $('body').removeClass('infinity-protocol');
            $('#content-main > div > div.row > div.span3').removeAttr('style');
            $('#app-header').removeAttr('style');
            $('section.container > ul.breadcrumb').removeAttr('style');
        };

        var _showFooterInfinityLoader = function(){
            $('#protocolinfiniloader').removeClass('hidden');
        };

        var _hideFooterInfinityLoader = function(){
            $('#protocolinfiniloader').addClass('hidden');
        };

        var _curPage = null;
        var _baseUrl = null;
        var _getNextPageUrl = function() {
            if (_curPage == null) {
                var re = /page=([0-9]*)/;
                var matches = window.location.href.match(re);
                if (matches != null && matches.length == 2) {
                    _curPage = parseInt(matches[1]);
                    _baseUrl = window.location.href.replace(re, 'page=((PAGE))');
                } else {
                    _curPage = 1;
                    if (window.location.href.indexOf('?')>-1) {
                        _baseUrl = window.location.href + '&page=((PAGE))';
                    } else {
                        _baseUrl = window.location.href + '?page=((PAGE))';
                    };
                };
            };
            _curPage++;
            return _baseUrl.replace('((PAGE))', _curPage);
        };

        var _isFooterAbove = function() {
            var ans = false;
            $.each($.waypoints('above'), function(i, elt) {
                if (elt.id == 'app-footer') {
                    ans = true;
                }
            });
            return ans;
        }

        var _onProtocolWaypoint = function(direction) {
            if (!_isFooterVisible && _isActive()) {
                if (direction == 'down') {
                    _isFloat = true;
                    _float();
                } else if (direction == 'up') {
                    _isFloat = false;
                    _unfloat();
                };
            };
        };

        var _noMorePages = false;
        var _isLoadingNextPage = false;
        var _onFooterWaypoint = function(direction) {
            if (direction == 'down') {
                _isFooterVisible = true;
                _unfloat();
                if (!_noMorePages && !_isLoadingNextPage) {
                    var _nextPage = _getNextPageUrl();
                    _showFooterInfinityLoader();
                    _isLoadingNextPage = true;
                    $("<div>").load(_nextPage+' #committeeprotocol', function(){
                        var html=$(this).find('.protocol').html();
                        html = $.trim(html);
                        $('#committeeprotocol').append(html);
                        if (html.length == 0) {
                            _noMorePages = true;
                        };
                        _hideFooterInfinityLoader();
                        _setFooterWaypoint();
                        if (!_isFooterAbove()) {
                            _onFooterWaypoint('up');
                        }
                        _isLoadingNextPage = false;
                    });
                };
            } else {
                _isFooterVisible = false;
                if (_isFloat && _isActive()) {
                    _float();
                };
            };
        };

        var _onWindowResize = function() {
            if (_isActive()) {
                if (!_isFooterVisible && _isFloat) {
                    _unfloat();
                    _float();
                };
            } else {
                _unfloat();
                _isFloat = false;
            };
        };

        var _setFooterWaypoint = function(){
            $('#app-footer').waypoint('destroy');
            $('#app-footer').waypoint(_onFooterWaypoint, {offset: '130%'});
        };
        _setFooterWaypoint();
        $('.protocol').waypoint(_onProtocolWaypoint, {offset: -50});
        $(window).resize(_onWindowResize);

    })();

});
<commit_msg>Fix js to support Firefox as well<commit_after>function hide_annotation_form(annoid) {
    $("#annotationform-"+annoid).hide();
    $("#annotations-"+annoid).show();
    $("#selectable-"+annoid).text(gettext("Annotate"));
    $("#annotationrealform-"+annoid)[0].reset();
    $("#editable-"+annoid).show();
    if(annotation_objects[annoid].annotation_count >0){
      $("#annotationtoolbox-"+annoid).show();
    }
}
$(function(){
    var options_bill = {
         serviceUrl:'/bill/auto_complete/',
         minChars:2,
         maxHeight:400,
         width:400,
         deferRequestBy: 100, //miliseconds
         onSelect: function(value, data, me){
            me.siblings("input[name$='bill_id']").val(data);
            me.siblings("input[type$='submit']").removeAttr('disabled'); },
         };

    var options_mk = {
         serviceUrl:'/member/auto_complete/',
         minChars:0,
         maxHeight:400,
         width:150,
         deferRequestBy: 100, //miliseconds
         };

    $('input.bill_input').autocomplete(options_bill);
    $('input.bill_input').keydown(function() {
        $(this).siblings("input[name$='bill_id']").val('');
        $(this).siblings("input[type$='submit']").attr('disabled', 'disabled'); });
    $("input[name$='mk_name']").autocomplete(options_mk);

    $(".annotation-content").each(function(){
        var annoid = $(this).attr("id").split("-")[1];
        annotation_objects[annoid] = new Annotations(annoid);
    });
    for(var a in annotation_objects){
        annotation_objects[a].importQuotes();
        annotation_objects[a].insertQuotes();
    }
    $(".annotationform-link").click(function(e){
      e.preventDefault();
      if (!window.logged_in) {
          var msg = gettext("Sorry, only logged users can annotate.");
          $.jGrowl(msg, {sticky: true});
          return false
      }
      if (!window.permission) {
          var msg = $("#message_permission").html()
          $.jGrowl(msg, {sticky: true});
          return false
      }

      var annoid = $(this).attr("id").split("-")[1];
      annotation_objects[annoid].toggleSelectView();
      if($("#annotations-"+annoid).css("display")=="none"){
        hide_annotation_form(annoid);
      } else{
        if (!$("#annotationform-"+annoid).length) {
            var speech_part = {id: annoid, length: window.parts_lengths[annoid] };
            $("#annotations-"+annoid).before(tmpl("annotationform", {speech_part: speech_part}))
            $(".annotationform-cancel").click(function(e) {
                e.preventDefault();
                var annoid = $(this).attr("id").split("-")[1];
                annotation_objects[annoid].toggleSelectView();
                hide_annotation_form(annoid);
            });
          $("#annotationrealform-"+annoid).submit(function(e){
            var id = $(this).attr("id").split("-")[1];
            if($("#selection_start-"+id).val()=="" || $("#selection_end-"+id).val()==""){
              alert(gettext("Please make a selection."));
              e.preventDefault();
              return false;
            }
            return true;
          });
            $('input[name=color]').colorPicker();
        }
        else
            $("#annotationform-"+annoid).show();
        $(this).text(gettext("Cancel"));
        $("#annotations-"+annoid).hide();
        $("#editable-"+annoid).hide();
        $("#annotationtoolbox-"+annoid).hide();
      }
    });
  $(".markall").click(function(e){
    var aid = $(this).attr("id").split("-")[1];
    if($(this).attr('checked')){
      annotation_objects[aid].updateDefaultAnnotationColor("self");
    } else{
      annotation_objects[aid].updateDefaultAnnotationColor("inherit");
    }
  });
  $(".reallydelete").live("submit", function(e){
    var anno_id = $(this).children('[name=annotation_id]').val();
    var username = $('#annotation-'+anno_id+' a.user-link').html();

    if (!window.is_staff && username != window.username){
        var msg = $("#message_staff").html()
        $.jGrowl(msg, {sticky: true});
        return false
    }
    return confirm(gettext('Delete can not be un-done. Are you sure?'));
  });
  $(".annotationflagselect").change(function(e){
    var id = $(this).parents("form").attr("id").split("-")[1];
    var val = parseInt($(this).val());
    var color = null;
    switch(val){
      case 0: // Put more colors here
        color = "#99ccff"; break;
    }
    if(color != null){
      $("#color_value").val(color);
      $("#annotationcolor-"+id).val(color);
      $("div.color_picker").css("background-color", color);
    }
  });
  $(".toggle").live("click", function(e){
     e.preventDefault();
     var id = $(this).attr("id");
     if (id == ""){
       var url = $(this).attr("href");
       var sel = $("."+url.substring(1,url.length)+"-container");
     } else {var sel = $("#"+id+"-container");}
     sel.toggle();
  });

    /** infinite scroll **/

    (function(){
        var _isFloat = false;
        var _isFooterVisible = false;

        var _isActive = function() {
            return ($(window).width() > 1200 && $(window).height() > 500);
        };

        var _float = function() {
            var appheader = $('#app-header');
            var body = $('body');
            var breadcrumb = $('section.container > ul.breadcrumb');
            var sidebar = $('#content-main > div > div.row > div.span3');
            var appheader_margin_left = appheader.offset().left;
            var appheader_margin_right = appheader_margin_left;
            var sidebar_left = sidebar.position().left;
            var breadcrumbheight = breadcrumb.height();
            body.addClass('infinity-protocol');
            appheader.css({
                'padding-left' : appheader_margin_left,
                'padding-right' : appheader_margin_right,
                'background' : body.css('background-color')
            });
            var appheader_height = appheader.height();
            var headerHeight = breadcrumbheight + appheader_height + 25;
            breadcrumb.css({
                'top' : appheader_height + 'px',
                'background' : body.css('background-color'),
            });
            sidebar.css({
                'top' : headerHeight+'px',
                'left' : sidebar_left + 'px',
                'height' : ($.waypoints('viewportHeight') - headerHeight - 5) + 'px',
            });
        };

        var _unfloat = function() {
            $('body').removeClass('infinity-protocol');
            $('#content-main > div > div.row > div.span3').removeAttr('style');
            $('#app-header').removeAttr('style');
            $('section.container > ul.breadcrumb').removeAttr('style');
        };

        var _showFooterInfinityLoader = function(){
            $('#protocolinfiniloader').removeClass('hidden');
        };

        var _hideFooterInfinityLoader = function(){
            $('#protocolinfiniloader').addClass('hidden');
        };

        var _curPage = null;
        var _baseUrl = null;
        var _getNextPageUrl = function() {
            if (_curPage == null) {
                var re = /page=([0-9]*)/;
                var matches = window.location.href.match(re);
                if (matches != null && matches.length == 2) {
                    _curPage = parseInt(matches[1]);
                    _baseUrl = window.location.href.replace(re, 'page=((PAGE))');
                } else {
                    _curPage = 1;
                    if (window.location.href.indexOf('?')>-1) {
                        _baseUrl = window.location.href + '&page=((PAGE))';
                    } else {
                        _baseUrl = window.location.href + '?page=((PAGE))';
                    };
                };
            };
            _curPage++;
            return _baseUrl.replace('((PAGE))', _curPage);
        };

        var _isFooterAbove = function() {
            var ans = false;
            $.each($.waypoints('above'), function(i, elt) {
                if (elt.id == 'app-footer') {
                    ans = true;
                }
            });
            return ans;
        }

        var _onProtocolWaypoint = function(direction) {
            if (!_isFooterVisible && _isActive()) {
                if (direction == 'down') {
                    _isFloat = true;
                    _float();
                } else if (direction == 'up') {
                    _isFloat = false;
                    _unfloat();
                };
            };
        };

        var _noMorePages = false;
        var _isLoadingNextPage = false;
        var _onFooterWaypoint = function(direction) {
            if (direction == 'down') {
                _isFooterVisible = true;
                _unfloat();
                if (!_noMorePages && !_isLoadingNextPage) {
                    var _nextPage = _getNextPageUrl();
                    _showFooterInfinityLoader();
                    _isLoadingNextPage = true;
                    $("<div>").load(_nextPage+' #committeeprotocol', function(){
                        var html=$(this).find('.protocol').html();
                        html = $.trim(html);
                        $('#committeeprotocol').append(html);
                        if (html.length == 0) {
                            _noMorePages = true;
                        };
                        _hideFooterInfinityLoader();
                        _setFooterWaypoint();
                        if (!_isFooterAbove()) {
                            _onFooterWaypoint('up');
                        }
                        _isLoadingNextPage = false;
                    });
                };
            } else {
                _isFooterVisible = false;
                if (_isFloat && _isActive()) {
                    _float();
                };
            };
        };

        var _onWindowResize = function() {
            if (_isActive()) {
                if (!_isFooterVisible && _isFloat) {
                    _unfloat();
                    _float();
                };
            } else {
                _unfloat();
                _isFloat = false;
            };
        };

        var _setFooterWaypoint = function(){
            $('#app-footer').waypoint('destroy');
            $('#app-footer').waypoint(_onFooterWaypoint, {offset: '130%'});
        };
        _setFooterWaypoint();
        $('.protocol').waypoint(_onProtocolWaypoint, {offset: -50});
        $(window).resize(_onWindowResize);

    })();

});
<|endoftext|>


<commit_before>'use strict'

module.exports = {
  create: () => {},
  index: () => {},
  top: () => {},
  good: () => {},
  showEdit: () => {},
  lock: () => {},
  delete: () => {},
  put: () => {},
  update: () => {},
  collect: () => {},
  de_collect: () => {},
  upload: () => {}
};
<commit_msg>update controller<commit_after>'use strict'

module.exports = {
  create: async(ctx, next) => {
    await ctx.render('topic/edit');
    return next();
  },
  index: () => {},
  top: () => {},
  good: () => {},
  showEdit: () => {},
  lock: () => {},
  delete: () => {},
  put: () => {},
  update: () => {},
  collect: () => {},
  de_collect: () => {},
  upload: () => {}
};
<|endoftext|>


<commit_before>/**
 * Main entrypoint for banknote.
 *
 * Copyright 2015 Ethan Smith
 */

var Backbone = require('backbone'),
    Marionette = require('backbone.marionette'),
    $ = require('jquery'),
    _ = require('underscore'),
    MainLayout = require('./src/view/MainLayout'),
    RegionModal = require('./src/common/modal/RegionModal.js'),
    CategorizedController = require('./src/controller/CategorizedController');
require('./src/common/library/CurrencyInputStyler');

var Banknote = new Marionette.Application();

Banknote.addRegions({
   central: '#app',
   modal: RegionModal
});

Banknote.addInitializer(function(options) {
   $.getJSON('demo.json', function(data) {

      var incomeCollection = new AmountEntryCollection(_.map(data.income, function(note) {
         return new AmountEntry(note);
      }));

      var controller = new CategorizedController({
         title: 'Income Totals'
      });
      Banknote.central.show(controller.render(incomeCollection));
   });
});

Banknote.start();

// Make Banknote available globally
global.Banknote = Banknote;
<commit_msg>Remove unneeded map for collection model<commit_after>/**
 * Main entrypoint for banknote.
 *
 * Copyright 2015 Ethan Smith
 */

var Backbone = require('backbone'),
    Marionette = require('backbone.marionette'),
    $ = require('jquery'),
    _ = require('underscore'),
    MainLayout = require('./src/view/MainLayout'),
    RegionModal = require('./src/common/modal/RegionModal.js'),
    CategorizedController = require('./src/controller/CategorizedController');
require('./src/common/library/CurrencyInputStyler');

var Banknote = new Marionette.Application();

Banknote.addRegions({
   central: '#app',
   modal: RegionModal
});

Banknote.addInitializer(function(options) {
   $.getJSON('demo.json', function(data) {

      var incomeCollection = new AmountEntryCollection(data.income);

      var controller = new CategorizedController({
         title: 'Income Totals'
      });
      Banknote.central.show(controller.render(incomeCollection));
   });
});

Banknote.start();

// Make Banknote available globally
global.Banknote = Banknote;
<|endoftext|>


<commit_before>// Require libs
var express = require('express'),
    nano = require('nano'),
    config = require('./lib/config'),
    middleware = require('./lib/middleware'),
    routes = require('./routes/index'),
    Radio = require('./lib/radio'),
    MpdPool = require('./lib/mpd_pool'),
    AlarmClock = require('./lib/alarm_clock'),
    Settings = require('./lib/settings');

var settings = new Settings(nano(config.storage.settings));

var mpdPool = new MpdPool({
    host: config.mpd.host,
    port: config.mpd.port,
    reconnect: true,
    timeout: 100
});

var radio = new Radio(mpdPool, {
    stations: config.radioStations,
    defaultStation: config.defaultRadioStation
});

radio.on('ready', function() {
    // Initialize entire application
    var app = express();

    // Initialize alarm clock
    var alarm = new AlarmClock();

    // Get the current alarm time from the storage.
    settings.get('alarm_time', function(error, time) {
        if (error) {
            throw error;
        }

        if (time) {
            alarm.setTime(time.hour, time.minute);
        } else {
            // There is no alarm time stored. Use a default one.
            alarm.setTime(9, 45);
        }
    });

    // Get the current state of alarm clock.
    settings.get('alarm_enabled', function(error, isEnabled) {
        if (error) {
            throw error;
        }

        if (isEnabled) {
            alarm.run();
        }
    });

    alarm.on('ring', function() {
        if (!radio.isPlaying()) {
            // Time to wake up. Turn on the radio
            radio.fadeIn();
        }
    });

    // Use Handlebars template engine
    app.set('view engine', 'handlebars');
    app.engine('handlebars', require('hbs').__express);

    // Serve static files
    app.use(express.static(__dirname + '/public'));

    // Mount routes
    app.use('/', routes(radio, alarm, settings));

    // Mount other middleware
    app.use(middleware.notFound);
    app.use(middleware.serverError);

    // Initialize HTTP server
    app.listen(
        config.server.port,
        function() {
            console.log('Application is up on port ' + config.server.port.toString());
        }
    );
});
<commit_msg>Add notice about HTTP server initialization order<commit_after>// Require libs
var express = require('express'),
    nano = require('nano'),
    config = require('./lib/config'),
    middleware = require('./lib/middleware'),
    routes = require('./routes/index'),
    Radio = require('./lib/radio'),
    MpdPool = require('./lib/mpd_pool'),
    AlarmClock = require('./lib/alarm_clock'),
    Settings = require('./lib/settings');

var settings = new Settings(nano(config.storage.settings));

var mpdPool = new MpdPool({
    host: config.mpd.host,
    port: config.mpd.port,
    reconnect: true,
    timeout: 100
});

var radio = new Radio(mpdPool, {
    stations: config.radioStations,
    defaultStation: config.defaultRadioStation
});

radio.on('ready', function() {
    // Initialize entire application
    var app = express();

    // Initialize alarm clock
    var alarm = new AlarmClock();

    // Actually the http server should be initialize AFTER all callbacks of
    // "settings.get" method will be ran. This is not done in that way because
    // of simplicity. In most cases it should not brings any problems because
    // "settings.get" method is really fast and finishes before the HTTP server
    // is up and running.
    // TODO: Initialize HTTP server only when all "settings.get" callbacks will
    // be ran.

    // Get the current alarm time from the storage.
    settings.get('alarm_time', function(error, time) {
        if (error) {
            throw error;
        }

        if (time) {
            alarm.setTime(time.hour, time.minute);
        } else {
            // There is no alarm time stored. Use a default one.
            alarm.setTime(9, 45);
        }
    });

    // Get the current state of alarm clock.
    settings.get('alarm_enabled', function(error, isEnabled) {
        if (error) {
            throw error;
        }

        if (isEnabled) {
            alarm.run();
        }
    });

    alarm.on('ring', function() {
        if (!radio.isPlaying()) {
            // Time to wake up. Turn on the radio
            radio.fadeIn();
        }
    });

    // Use Handlebars template engine
    app.set('view engine', 'handlebars');
    app.engine('handlebars', require('hbs').__express);

    // Serve static files
    app.use(express.static(__dirname + '/public'));

    // Mount routes
    app.use('/', routes(radio, alarm, settings));

    // Mount other middleware
    app.use(middleware.notFound);
    app.use(middleware.serverError);

    // Initialize HTTP server
    app.listen(
        config.server.port,
        function() {
            console.log('Application is up on port ' + config.server.port.toString());
        }
    );
});
<|endoftext|>


<commit_before>var fs       = require('fs');
var express  = require('express');
bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var mongoose = require('mongoose')
var app = module.exports = express();

// Connect to database
var configDB = require('./config/database.js')
mongoose.connect(configDB.url);

// Configuring Passport
var passport = require('passport');
require('./config/passport')(passport)
var expressSession = require('express-session');

app.use(expressSession({
  cookie: { maxAge: 1800000 }, //30 min
  secret: 'mySecretKey',
  resave: true,
  saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static(__dirname + '/public'));

app.set('views', __dirname + '/views');
app.set('view engine', 'jade');

// GOOGLE LOGIN
app.get('/auth/google',
  passport.authenticate('google', {
    scope : 'email'
  }));

app.get('/auth/google/callback',
    passport.authenticate('google', {
        successRedirect : '/',
        failureRedirect : '/'
    }));

// route for logging out
app.get('/logout', function(req, res) {
    req.logout();
    res.redirect('/');
});

// route middleware to make sure a user is logged in
function isLoggedIn(req, res, next) {
  // if user is authenticated in the session, carry on
  if (req.isAuthenticated()) return next();
  // if they aren't redirect them to the home page
  res.redirect('/');
}

// route middleware to make sure a user is member
function isMember(req, res, next) {

  if (!req.user) {
    res.render('errors', {
      'message': 'You are not logged in.',
      'user':   req.user ? req.user.google : false
    })
  }

  // if user is member, carry on
  if (req.user.google.email.indexOf('@rosedu.org') > -1) return next();
  // if they aren't redirect them to the home page
  res.render('errors', {
      'message': 'Sorry, you are not a Rosedu member :(',
      'user':   req.user ? req.user.google : false
    })
}

var Event = require('./config/models/events')

// Base routes
app.get('/', function (req, res) {
  Event.find().exec(gotEvents)

  // Mark our members
  if (req.user && req.user.google.email.indexOf('@rosedu.org') > -1)
    req.user.google['isMember'] = true

  function gotEvents(err, events) {
    res.render('index', {
      'user':   req.user ? req.user.google : false,
      'events': events
    })
  }
})

app.post('/add', isMember, function (req, res) {
  new Event({
    'name':        req.body.name,
    'date':        req.body.date,
    'location':    req.body.location,
    'email':       req.body.email,
    'description': req.body.description
  }).save(function(err) {
    console.log("* Event added.")
    res.redirect('/')
  })
})

app.get('/edit', isMember, function (req, res) {
  Event.findOne({'_id': req.query.id}).exec(gotEvent)

  function gotEvent(err, theEvent) {
    res.render('edit', {
      'event': theEvent,
      'user': req.user.google
    })
  }
})

// 404 page
app.use(function(req, res, next) {
  res.status(404).render('errors', {
    'message': '404 page not found',
    'user':   req.user ? req.user.google : false
  });
});
app.use(app.router);

// Launch server
app.listen(process.env.PORT || 3000, function() {
  console.log('Server listening on port 3000.');
});
<commit_msg>app.js various changes<commit_after>var fs       = require('fs');
var express  = require('express');
bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var mongoose = require('mongoose')
var app = module.exports = express();

// Connect to database
var configDB = require('./config/database.js')
mongoose.connect(configDB.url);

// Configuring Passport
var passport = require('passport');
require('./config/passport')(passport)
var expressSession = require('express-session');

app.use(expressSession({
  cookie: { maxAge: 1800000 }, //30 min
  secret: 'mySecretKey',
  resave: true,
  saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.urlencoded({extended: true}));
app.use('/public', express.static(__dirname + '/public'));
app.use('/bower', express.static(__dirname + '/bower_components'));

app.set('views', __dirname + '/views');
app.set('view engine', 'jade');

// GOOGLE LOGIN
app.get('/auth/google',
  passport.authenticate('google', {
    scope : 'email'
  }));

app.get('/auth/google/callback',
    passport.authenticate('google', {
        successRedirect : '/',
        failureRedirect : '/'
    }));

// route for logging out
app.get('/logout', function(req, res) {
    req.logout();
    res.redirect('/');
});

// route middleware to make sure a user is logged in
function isLoggedIn(req, res, next) {
  // if user is authenticated in the session, carry on
  if (req.isAuthenticated()) return next();
  // if they aren't redirect them to the home page
  res.redirect('/');
}

// route middleware to make sure a user is member
function isMember(req, res, next) {

  if (!req.user) {
    res.render('errors', {
      'message': 'You are not logged in',
      'user':   false
    });

    return;
  }

  // if user is member, carry on
  if (req.user.google.email.indexOf('@rosedu.org') > -1) return next();
  // if they aren't redirect them to the home page
  res.render('errors', {
      'message': 'Sorry, you are not a Rosedu member :(',
      'user':   req.user ? req.user.google : false
    })
}

var Event = require('./config/models/events')

// Base routes
app.get('/', function (req, res) {
  Event.find().exec(gotEvents)

  // Mark our members
  if (req.user && req.user.google.email.indexOf('@rosedu.org') > -1)
    req.user.google['isMember'] = true

  function gotEvents(err, events) {
    res.render('index', {
      'user':   req.user ? req.user.google : false,
      'events': events
    })
  }
})

app.post('/add', isMember, function (req, res) {
  new Event({
    'name':        req.body.name,
    'date':        req.body.date,
    'location':    req.body.location,
    'email':       req.body.email,
    'link':        req.body.link,
    'description': req.body.description
  }).save(function(err) {
    console.log("* Event added.")
    res.redirect('/')
  })
})

app.get('/edit', isMember, function (req, res) {
  Event.findOne({'_id': req.query.id}).exec(gotEvent)

  function gotEvent(err, theEvent) {
    res.render('edit', {
      'event': theEvent,
      'user': req.user.google
    })
  }
})

// 404 page
app.use(function(req, res, next) {
  res.status(404).render('errors', {
    'message': '404 page not found',
    'user':   req.user ? req.user.google : false
  });
});
app.use(app.router);

// Launch server
app.listen(process.env.PORT || 3000, function() {
  console.log('Server listening on port 3000.');
});
<|endoftext|>


<commit_before>/**
 * @module controllers/game
 */

const Game = require('../models/game');
const User = require('../models/user');
const has = require('has');

/**
 * Internal helper method for validating that a chosen name is unique.
 * @param {String} newName - the requested Game name field value
 */
function validateNameUnique(newName) {
  return Game.where('name', newName).count('name')
    .then(count => (count === 0));
}

/**
 * Get all Games in the database
 * @param  {Express.Request}   req  - the request object
 * @param  {Express.Response}  res  - the response object
 */
function getGames(req, res) {
  const fetchBody = {};
  if (req.query) {
    if (req.query.withRelated) fetchBody.withRelated = req.query.withRelated;
  }
  return Game.fetchAll(fetchBody)
  .then(collection => res.json(collection.serialize()))
  .catch(
    /* istanbul ignore next */
    (err) => {
      const regMatch = err.message.match(/([a-zA-Z]*) is not defined on the model/);
      if (regMatch) {
        res.status(400)
        .json({
          error: 'InvalidRelation',
          message: `'${regMatch[1]}' is not a valid relation on this model.`,
        });
      } else {
        // Unknown error
        console.error(err);
        res.status(500).json({
          error: 'UnknownError',
          request: req.body,
        });
      }
    }
  );
}

/**
 * Get the Game matching the 'id' param of the request from the database.
 * @param {Express.Request} req   - the request object
 * @param {Express.Response} res  - the response object
 */
function getGameById(req, res) {
  const fetchBody = {};
  if (req.query) {
    if (req.query.withRelated) fetchBody.withRelated = req.query.withRelated;
  }
  return Game.where('id', req.params.id).fetch(fetchBody)
  .then((game) => {
    if (game) {
      res.status(200).json(game.serialize());
    } else {
      res.status(404).json({
        error: 'Game with the associated ID was not found',
        request: req.params,
      });
    }
  })
  .catch(
    /* istanbul ignore next */
    (err) => {
      const regMatch = err.message.match(/([a-zA-Z]*) is not defined on the model/);
      if (regMatch) {
        res.status(400)
        .json({
          error: 'InvalidRelation',
          message: `'${regMatch[1]}' is not a valid relation on this model.`,
        });
      } else {
        // Unknown error
        console.error(err);
        res.status(500).json({
          error: 'UnknownError',
          request: req.body,
        });
      }
    }
  );
}

/**
 * Pre-req: verifyProfessor middleware
 * Controller to update an existing Game
 * @param {Express.Request} req  - the request object
 * @param {Express.Response} res - the response object
 */
function updateGame(req, res) {
  const gameId = req.params.id;
  const user = req.user;
  const updatedFields = req.body;

  function validateUpdateRequests() {
    if (Object.getOwnPropertyNames(updatedFields).length === 0) {
      res.status(204).send();
      return false;
    }

    if (has(updatedFields, 'id')) {
      res.status(400).json({
        error: 'You may not alter the read-only "id" field',
        request: updatedFields,
      });
      return false;
    }

    if (has(updatedFields, 'max_round')) {
      if (updatedFields.max_round < 0) {
        res.status(400).json({
          error: 'The "max_round" field may not be a negative integer.',
          request: updatedFields,
        });
        return false;
      }
    }

    if (has(updatedFields, 'current_round')) {
      if (updatedFields.current_round < 0) {
        res.status(400).json({
          error: 'The "current_round" field may not be a negative integer.',
          request: updatedFields,
        });
        return false;
      }
    }

    if (has(updatedFields, 'round_phase')) {
      if (updatedFields.round_phase < 0) {
        res.status(400).json({
          error: 'The "round_phase" field may not be a negative integer.',
          request: updatedFields,
        });
        return false;
      }
    }

    if (has(updatedFields, 'created_at')) {
      res.status(400).json({
        error: 'You may not alter the read-only "created_at" field',
        request: updatedFields,
      });
      return false;
    }

    if (has(updatedFields, 'name')) {
      // Don't allow empty or all whitespace names
      if (updatedFields.name.replace(/\s/g, '') === '') {
        res.status(400).json({
          error: '"name" field cannot be an empty string.',
          request: updatedFields,
        });
        return false;
      }
      const namePromise = validateNameUnique(updatedFields.name).then((isValid) => {
        if (!isValid) {
          throw new Error('Game with Name exists');
        }
      })
      .catch((err) => {
        if (err.message === 'Game with Name exists') {
          res.status(400).json({
            error: 'There is already a Game with that name. Please choose a unique name.',
            request: updatedFields,
          });
          return false;
        }
        console.error(err);
        res.status(500).json({
          error: 'UnknownError',
          request: updatedFields,
        });
        return false;
      });
      return Promise.resolve(namePromise);
    }

    if (has(updatedFields, 'storyteller_id')) {
      // New storyteller must be is_admin or in Professors role.
      const storytellerId = updatedFields.storyteller_id;
      const existingUserQuery = User.where('id', storytellerId);

      return existingUserQuery.fetch({
        withRelated: ['roles'],
      }).then((targetUser) => {
        if (!targetUser) {
          res.status(400).json({
            error: 'A User whose "id" field matches the "storyteller_id" field of the request could not be found.',
            request: updatedFields,
          });
          return false;
        }
        const targetUserRoles = targetUser.related('roles').toJSON();
        let isProf = false;
        targetUserRoles.forEach((role) => {
          if (role.name === 'Professor') isProf = true;
        });

        if (!isProf && !(targetUser.attributes.is_admin)) {
          res.status(400).json({
            error: 'You cannot make a non-Admin User a storyteller if they are not in the Professor role',
            request: updatedFields,
          });
          return false;
        }
        return true;
      });
    }
    return true;
  }

  // Fetch the game and make sure the storyteller_id matches the user id.
  // If it doesn't, disallow non-admin users from updating.
  let existingGameQuery = Game.where('id', gameId);

  if (!req.user.is_admin) existingGameQuery = existingGameQuery.where('storyteller_id', user.id);
  existingGameQuery.fetch().then((game) => {
    if (!game) {
      res.status(404).json({
        error: 'Game with the associated ID was not found',
        request: req.body,
      });
    } else if (validateUpdateRequests()) {
      game.save(updatedFields)
      .then(() => existingGameQuery.fetch()
      .then((updatedGame) => {
        res.status(200).json(updatedGame.serialize());
      })
      )
      .catch(
        /* istanbul ignore next */
        (err) => {
          console.error(err);
          res.status(500).json({
            error: 'UnknownError',
            request: updatedFields,
          });
        }
      );
    }
  });

  Promise.resolve(existingGameQuery);
}

/**
 * Controller to create a new Game
 * @param  {Express.request}   req  - the request object
 * @param  {Express.Response}   res  - the response object
 */
function createGame(req, res) {
  // Check for required fields
  const newGameReq = req.body;
  if (!has(newGameReq, 'name')) {
    res.status(400).json({
      error: 'Missing required "name" field.',
      request: newGameReq,
    });
    return null;
  }
  if (!has(newGameReq, 'max_round')) {
    res.status(400).json({
      error: 'Missing required "max_round" field.',
      request: newGameReq,
    });
    return null;
  }
  // Don't allow empty or all whitespace names
  if (newGameReq.name.replace(/\s/g, '') === '') {
    res.status(400).json({
      error: '"name" field cannot be an empty string.',
      request: newGameReq,
    });
    return null;
  }

  return validateNameUnique(newGameReq.name).then((isValid) => {
    if (!isValid) {
      throw new Error('Game with Name exists');
    } else {
      // Set storyteller to admin/professor making the request
      newGameReq.storyteller_id = req.user.id;

      return Game.forge(newGameReq).save()
      .then(game =>
        // Retrieve the newly created game and return it in the response body.
        Game.where('id', game.id).fetch()
        .then(newGame => res.status(201).json(newGame.serialize()))
      )
      .catch(
        /* istanbul ignore next */
        (err) => {
          console.error(err);
          return res.status(500).json({
            error: 'UnknownError',
            request: newGameReq,
          });
        }
      );
    }
  })
  .catch((err) => {
    /* istanbul ignore else */
    if (err.message === 'Game with Name exists') {
      res.status(400).json({
        error: 'There is already a Game with that name. Please choose a unique name.',
        request: newGameReq,
      });
    } else {
      console.error(err);
      res.status(500).json({
        error: 'UnknownError',
        request: newGameReq,
      });
    }
    return null;
  });
}

module.exports = {
  getGames,
  updateGame,
  getGameById,
  createGame,
};
<commit_msg>Allow optional 'storyteller_id' query param for filtering by storyteller.<commit_after>/**
 * @module controllers/game
 */

const Game = require('../models/game');
const User = require('../models/user');
const has = require('has');

/**
 * Internal helper method for validating that a chosen name is unique.
 * @param {String} newName - the requested Game name field value
 */
function validateNameUnique(newName) {
  return Game.where('name', newName).count('name')
    .then(count => (count === 0));
}

/**
 * Get all Games in the database
 * @param  {Express.Request}   req  - the request object
 * @param  {Express.Response}  res  - the response object
 */
function getGames(req, res) {
  const fetchBody = {};
  let knexQuery = Game;
  if (req.query) {
    // Optional model relations
    if (req.query.withRelated) fetchBody.withRelated = req.query.withRelated;
    // Filter by storyteller_id
    if (req.query.storyteller_id) knexQuery = knexQuery.where('storyteller_id', req.query.storyteller_id);
  }
  return knexQuery.fetchAll(fetchBody)
  .then(collection => res.json(collection.serialize()))
  .catch(
    /* istanbul ignore next */
    (err) => {
      const regMatch = err.message.match(/([a-zA-Z]*) is not defined on the model/);
      if (regMatch) {
        res.status(400)
        .json({
          error: 'InvalidRelation',
          message: `'${regMatch[1]}' is not a valid relation on this model.`,
        });
      } else {
        // Unknown error
        console.error(err);
        res.status(500).json({
          error: 'UnknownError',
          request: req.body,
        });
      }
    }
  );
}

/**
 * Get the Game matching the 'id' param of the request from the database.
 * @param {Express.Request} req   - the request object
 * @param {Express.Response} res  - the response object
 */
function getGameById(req, res) {
  const fetchBody = {};
  if (req.query) {
    if (req.query.withRelated) fetchBody.withRelated = req.query.withRelated;
  }
  return Game.where('id', req.params.id).fetch(fetchBody)
  .then((game) => {
    if (game) {
      res.status(200).json(game.serialize());
    } else {
      res.status(404).json({
        error: 'Game with the associated ID was not found',
        request: req.params,
      });
    }
  })
  .catch(
    /* istanbul ignore next */
    (err) => {
      const regMatch = err.message.match(/([a-zA-Z]*) is not defined on the model/);
      if (regMatch) {
        res.status(400)
        .json({
          error: 'InvalidRelation',
          message: `'${regMatch[1]}' is not a valid relation on this model.`,
        });
      } else {
        // Unknown error
        console.error(err);
        res.status(500).json({
          error: 'UnknownError',
          request: req.body,
        });
      }
    }
  );
}

/**
 * Pre-req: verifyProfessor middleware
 * Controller to update an existing Game
 * @param {Express.Request} req  - the request object
 * @param {Express.Response} res - the response object
 */
function updateGame(req, res) {
  const gameId = req.params.id;
  const user = req.user;
  const updatedFields = req.body;

  function validateUpdateRequests() {
    if (Object.getOwnPropertyNames(updatedFields).length === 0) {
      res.status(204).send();
      return false;
    }

    if (has(updatedFields, 'id')) {
      res.status(400).json({
        error: 'You may not alter the read-only "id" field',
        request: updatedFields,
      });
      return false;
    }

    if (has(updatedFields, 'max_round')) {
      if (updatedFields.max_round < 0) {
        res.status(400).json({
          error: 'The "max_round" field may not be a negative integer.',
          request: updatedFields,
        });
        return false;
      }
    }

    if (has(updatedFields, 'current_round')) {
      if (updatedFields.current_round < 0) {
        res.status(400).json({
          error: 'The "current_round" field may not be a negative integer.',
          request: updatedFields,
        });
        return false;
      }
    }

    if (has(updatedFields, 'round_phase')) {
      if (updatedFields.round_phase < 0) {
        res.status(400).json({
          error: 'The "round_phase" field may not be a negative integer.',
          request: updatedFields,
        });
        return false;
      }
    }

    if (has(updatedFields, 'created_at')) {
      res.status(400).json({
        error: 'You may not alter the read-only "created_at" field',
        request: updatedFields,
      });
      return false;
    }

    if (has(updatedFields, 'name')) {
      // Don't allow empty or all whitespace names
      if (updatedFields.name.replace(/\s/g, '') === '') {
        res.status(400).json({
          error: '"name" field cannot be an empty string.',
          request: updatedFields,
        });
        return false;
      }
      const namePromise = validateNameUnique(updatedFields.name).then((isValid) => {
        if (!isValid) {
          throw new Error('Game with Name exists');
        }
      })
      .catch((err) => {
        if (err.message === 'Game with Name exists') {
          res.status(400).json({
            error: 'There is already a Game with that name. Please choose a unique name.',
            request: updatedFields,
          });
          return false;
        }
        console.error(err);
        res.status(500).json({
          error: 'UnknownError',
          request: updatedFields,
        });
        return false;
      });
      return Promise.resolve(namePromise);
    }

    if (has(updatedFields, 'storyteller_id')) {
      // New storyteller must be is_admin or in Professors role.
      const storytellerId = updatedFields.storyteller_id;
      const existingUserQuery = User.where('id', storytellerId);

      return existingUserQuery.fetch({
        withRelated: ['roles'],
      }).then((targetUser) => {
        if (!targetUser) {
          res.status(400).json({
            error: 'A User whose "id" field matches the "storyteller_id" field of the request could not be found.',
            request: updatedFields,
          });
          return false;
        }
        const targetUserRoles = targetUser.related('roles').toJSON();
        let isProf = false;
        targetUserRoles.forEach((role) => {
          if (role.name === 'Professor') isProf = true;
        });

        if (!isProf && !(targetUser.attributes.is_admin)) {
          res.status(400).json({
            error: 'You cannot make a non-Admin User a storyteller if they are not in the Professor role',
            request: updatedFields,
          });
          return false;
        }
        return true;
      });
    }
    return true;
  }

  // Fetch the game and make sure the storyteller_id matches the user id.
  // If it doesn't, disallow non-admin users from updating.
  let existingGameQuery = Game.where('id', gameId);

  if (!req.user.is_admin) existingGameQuery = existingGameQuery.where('storyteller_id', user.id);
  existingGameQuery.fetch().then((game) => {
    if (!game) {
      res.status(404).json({
        error: 'Game with the associated ID was not found',
        request: req.body,
      });
    } else if (validateUpdateRequests()) {
      game.save(updatedFields)
      .then(() => existingGameQuery.fetch()
      .then((updatedGame) => {
        res.status(200).json(updatedGame.serialize());
      })
      )
      .catch(
        /* istanbul ignore next */
        (err) => {
          console.error(err);
          res.status(500).json({
            error: 'UnknownError',
            request: updatedFields,
          });
        }
      );
    }
  });

  Promise.resolve(existingGameQuery);
}

/**
 * Controller to create a new Game
 * @param  {Express.request}   req  - the request object
 * @param  {Express.Response}   res  - the response object
 */
function createGame(req, res) {
  // Check for required fields
  const newGameReq = req.body;
  if (!has(newGameReq, 'name')) {
    res.status(400).json({
      error: 'Missing required "name" field.',
      request: newGameReq,
    });
    return null;
  }
  if (!has(newGameReq, 'max_round')) {
    res.status(400).json({
      error: 'Missing required "max_round" field.',
      request: newGameReq,
    });
    return null;
  }
  // Don't allow empty or all whitespace names
  if (newGameReq.name.replace(/\s/g, '') === '') {
    res.status(400).json({
      error: '"name" field cannot be an empty string.',
      request: newGameReq,
    });
    return null;
  }

  return validateNameUnique(newGameReq.name).then((isValid) => {
    if (!isValid) {
      throw new Error('Game with Name exists');
    } else {
      // Set storyteller to admin/professor making the request
      newGameReq.storyteller_id = req.user.id;

      return Game.forge(newGameReq).save()
      .then(game =>
        // Retrieve the newly created game and return it in the response body.
        Game.where('id', game.id).fetch()
        .then(newGame => res.status(201).json(newGame.serialize()))
      )
      .catch(
        /* istanbul ignore next */
        (err) => {
          console.error(err);
          return res.status(500).json({
            error: 'UnknownError',
            request: newGameReq,
          });
        }
      );
    }
  })
  .catch((err) => {
    /* istanbul ignore else */
    if (err.message === 'Game with Name exists') {
      res.status(400).json({
        error: 'There is already a Game with that name. Please choose a unique name.',
        request: newGameReq,
      });
    } else {
      console.error(err);
      res.status(500).json({
        error: 'UnknownError',
        request: newGameReq,
      });
    }
    return null;
  });
}

module.exports = {
  getGames,
  updateGame,
  getGameById,
  createGame,
};
<|endoftext|>


<commit_before>var irc = require("irc"),
    colors = require("colors");

var logger = require("./lib/log.js"),
    irc = require("./lib/irc.js");
var config = require("./config/config.js");

//tests
log(config.name);
<commit_msg>fix... again...<commit_after>var irc = require("irc"),
    colors = require("colors");

var logger = require("./lib/log.js"),
    irc = require("./lib/irc.js");
var config = require("./config/config.js");

//tests
logger.log(config.name);
<|endoftext|>


<commit_before>var gm = require('gm').subClass({ imageMagick: true });
var fs = require('fs');

/**
 * Set defaults
 * @type {{imageType: String("png"), bg_color: String("999"), fg_color: String("666")}}
 */
var defaults = {
  imageType: "png",
  bgColor: "e1e1e1",
  color: "181818"
};

var max_age = 3153600;
var expiryDate = new Date(0);

module.exports = function(app){
  app.get('/gen/:dimension.:imageType', function(req, res, next) {
    var dim = req.params.dimension.split('x');
    var width, height, foreground, background, imageType, text;

    if(dim.length === 1) {
      width = height = dim[0] * 1;
    } else {
      width = dim[0] * 1;
      height = dim[1] * 1;
    }
    if(isNaN(width) || isNaN(height)) return next();

    if(typeof req.query.color !== 'undefined') {
      foreground = req.query.color;
    } else {
      foreground = defaults.color;
    }
    if(foreground[0] !== '#') foreground = '#' + foreground;

    if(typeof req.query.bg !== 'undefined') {
      background = req.query.bg;
    } else {
      background = defaults.bgColor;
    }
    if(background[0] !== '#') background = '#' + background;

    if(typeof req.params.imageType !== 'undefined') {
      imageType = req.params.imageType;
    } else {
      imageType = defaults.imageType;
    }
    imageType = imageType.toLowerCase();

    if(typeof req.query.text !== 'undefined') {
      // TODO handle case when the text is too long for the image
      text = req.query.text;
      //text = width + " x " + height;
    } else {
      text = width + " x " + height;
    }

    res.setHeader("Content-Type", "image/" + imageType);
    res.setHeader("Cache-Control", "public, max-age=" + max_age)
    res.setHeader("Expires", expiryDate);
    res.setHeader("Last-Modified", expiryDate);

    gm(width, height, background)
      .fill(foreground)
      .font("Arial", 20)
      .drawText(0, 0, text, "center")
      .toBuffer(imageType, function(err, buffer) {
        if(err) {
          console.log(err);
          next();
        }
        res.send(buffer);
      });

  });
};<commit_msg>Update home.js<commit_after>var gm = require('gm').subClass({ imageMagick: true });
var fs = require('fs');

/**
 * Set defaults
 * @type {{imageType: String("png"), bg_color: String("999"), fg_color: String("666")}}
 */
var defaults = {
  imageType: "png",
  bgColor: "e1e1e1",
  color: "181818"
};

var max_age = 3153600;
var expiryDate = new Date(0);

module.exports = function(app){
  app.get('/gen/:dimension.:imageType', function(req, res, next) {
    var dim = req.params.dimension.split('x');
    var width, height, foreground, background, imageType, text, delay;

      if (typeof req.query.delay !== "undefined") {
        delay = req.query.delay;
      } else {
        delay = false;
      }

    if(dim.length === 1) {
      width = height = dim[0] * 1;
    } else {
      width = dim[0] * 1;
      height = dim[1] * 1;
    }
    if(isNaN(width) || isNaN(height)) return next();

    if(typeof req.query.color !== 'undefined') {
      foreground = req.query.color;
    } else {
      foreground = defaults.color;
    }
    if(foreground[0] !== '#') foreground = '#' + foreground;

    if(typeof req.query.bg !== 'undefined') {
      background = req.query.bg;
    } else {
      background = defaults.bgColor;
    }
    if(background[0] !== '#') background = '#' + background;

    if(typeof req.params.imageType !== 'undefined') {
      imageType = req.params.imageType;
    } else {
      imageType = defaults.imageType;
    }
    imageType = imageType.toLowerCase();

    if(typeof req.query.text !== 'undefined') {
      // TODO handle case when the text is too long for the image
      text = req.query.text;
      //text = width + " x " + height;
    } else {
      text = width + " x " + height;
    }

    res.setHeader("Content-Type", "image/" + imageType);
    res.setHeader("Cache-Control", "public, max-age=" + max_age)
    res.setHeader("Expires", expiryDate);
    res.setHeader("Last-Modified", expiryDate);

    gm(width, height, background)
      .fill(foreground)
      .font("Arial", 20)
      .drawText(0, 0, text, "center")
      .toBuffer(imageType, function(err, buffer) {
        if(err) {
          console.log(err);
          next();
        }
        if (delay) {
            setTimeout(function() {
              res.send(buffer);
            }, delay);
          } else {
            res.send(buffer);
          }
      });

  });
};
<|endoftext|>


<commit_before>//Adapted from https://github.com/olalonde/node-yelp

// Request API access: http://www.yelp.com/developers/getting_started/api_access
var Yelp = require('yelp');
var http = require("http");
var express = require("express");
var app = express();

var yelp = new Yelp({
  // consumer_key: 'your-consumer-key',
  consumer_key: "",
  // consumer_secret: 'consumer-secret',
  consumer_secret: "",
  // token: 'token',
  token: "",
  // token_secret: 'token-secret',
  token_secret: "",
});

// See http://www.yelp.com/developers/documentation/v2/search_api
var returnedData;
app.set('json callback name', 'cb');
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});
app.get('*', function (req, res, next){
  console.log(req.url);
  var incData = req.url.split(",");
  console.log(incData);
  var inx1 = incData[1].toString();
  console.log(inx1);
  var inx3 = incData[3].toString();
  console.log(inx3);
  var inx5 = incData[5].toString();
  yelp.search({ term: inx1, location: inx3, offset: inx5 })
  .then(function (data) {
    res.jsonp(data);
    //returnedData = data;
    console.log("Success!____________________");
    //console.log(returnedData)
  })
  .catch(function (err) {
    console.error(err);
  });

  //next();
});

app.listen(3000, function () {
  console.log("Listening on port 3000")
});
<commit_msg>Corrections for consistency, removed excess<commit_after>//Adapted from https://github.com/olalonde/node-yelp

// Request API access: http://www.yelp.com/developers/getting_started/api_access
var Yelp = require("yelp");
var http = require("http");
var express = require("express");
var app = express();

var yelp = new Yelp({
  // consumer_key: 'your-consumer-key',
  consumer_key: "",
  // consumer_secret: 'consumer-secret',
  consumer_secret: "",
  // token: 'token',
  token: "",
  // token_secret: 'token-secret',
  token_secret: "",
});

// See http://www.yelp.com/developers/documentation/v2/search_api
var returnedData;
app.set("json callback name", "cb");

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.get("*", function (req, res, next){
  console.log(req.url);
  var incData = req.url.split(",");
  console.log(incData);
  var inx1 = incData[1].toString();
  console.log(inx1);
  var inx3 = incData[3].toString();
  console.log(inx3);
  var inx5 = incData[5].toString();
  yelp.search({ term: inx1, location: inx3, offset: inx5 })
  .then(function (data) {
    res.jsonp(data);
    console.log("Success!____________________");
  })
  .catch(function (err) {
    console.error(err);
  });

  //next();
});

app.listen(3000, function () {
  console.log("Listening on port 3000")
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import moment from 'npm:moment';
import $ from 'jquery';

export default Ember.Controller.extend({
  spendingsMeter: 0.00,
  sumByCategory: null,
  pollingInterval: 10000,
  currencyRates: null,

  init () {
    this.set('currentMonthDisplaying', {
      month: parseInt(moment().format('MM')),
      year: parseInt(moment().format('YYYY')),
      isInPast: false
    });
    Ember.run.once(() => {
      this.onPoll();
    });
    this.startPolling();
  },

  displayCurrencyRates: function () {
    return this.get('currencyRates');
  }.property('currencyRates'),

  schedulePollEvent (event, interval) {
    var eventInterval = interval || this.get('pollingInterval');
    return Ember.run.later(() => {
      event.apply(this);
      this.set('timer', this.schedulePollEvent(event));
    }, eventInterval);
  },

  startPolling (interval) {
    this.set('timer', this.schedulePollEvent(this.get('onPoll'), interval));
  },

  stopPolling () {
    Ember.run.cancel(this.get('timer'));
  },

  onPoll () {
    const _this = this;
    return $.get('http://api.fixer.io/latest?base=USD')
      .then(response => _this.set('currencyRates', response))
      .catch(err => console.log(err));
  },

  dataToDisplay: function () {
    let month = this.get('currentMonthDisplaying').month;
    let year = this.get('currentMonthDisplaying').year;
    let timePeriodsList = [];

    // Filter expenses for current month and generate timePeriodsList while you at it.
    let filteredData = this.get('model').filter(item => {
      // Save values to be reused
      let timePeriod = [item.get('year'), item.get('month')];

      // Determine if timeperiod is alredy on the list
      let notOnList = timePeriodsList.every(arr => {
        if (arr[0] !== timePeriod[0]) {
          return true;
        } else {
          // if arr[0] === timePeriod[0]
          return arr[1] !== timePeriod[1];
        }
      });

      // Save if not on list
      if (notOnList) {
        timePeriodsList.push(timePeriod);
      }

      // Returns false if expense is not for current month
      return timePeriod[0] === year && timePeriod[1] === month;
    });

    this.set('timePeriodsList', timePeriodsList);
    return filteredData;
  }.property('model.@each'),

  updateSpendingsMeter: function (data) {
    let sumCounted = 0;
    let sumByCategory = [];
    this.get('dataToDisplay').forEach(item => {
      let sum = item.get('sum');
      let category = item.get('category');

      if (sumByCategory.findBy('category', category)) {
        sumByCategory.findBy('category', category).sum += parseFloat(sum);
      } else {
        sumByCategory.pushObject({
          category,
          sum: parseFloat(sum)
        });
      }
      sumCounted += parseFloat(sum);
    });
    this.set('spendingsMeter', sumCounted);
    this.set('sumByCategory', sumByCategory);
    return;
  }.observes('model.@each.sum'),

  formatedChartData: function () {
    const data = [
      ['Category', 'Spendings']
    ];

    this.get('sumByCategory').forEach(category => {
      data.push(
        [category.category, category.sum]
      );
    });
    return data;
  }.property('sumByCategory'),

  actions: {

    timePeriodHasChanged (timePeriod) {
      this.set('currentMonthDisplaying', timePeriod);
      this.set('model', this.store.findAll('expense'));
    },

    saveRecord (record) {
      let setTimePeriodRecord = record;

      // If timeperiod is in past it will set correct month and year for expense on save
      // otherwise default value is set in model
      if (this.get('currentMonthDisplaying').isInPast) {
        setTimePeriodRecord.month = this.get('currentMonthDisplaying').month;
        setTimePeriodRecord.year = this.get('currentMonthDisplaying').year;
      }

      let expense = this.store.createRecord('expense', setTimePeriodRecord);
      expense.save();
    }
  }
});
<commit_msg>refactor: Use ajax instead of get for polling.<commit_after>import Ember from 'ember';
import moment from 'npm:moment';
import $ from 'jquery';

export default Ember.Controller.extend({
  spendingsMeter: 0.00,
  sumByCategory: null,
  pollingInterval: 10000,
  currencyRates: null,

  init () {
    this.set('currentMonthDisplaying', {
      month: parseInt(moment().format('MM')),
      year: parseInt(moment().format('YYYY')),
      isInPast: false
    });
    Ember.run.once(() => {
      this.onPoll();
    });
    this.startPolling();
  },

  displayCurrencyRates: function () {
    return this.get('currencyRates');
  }.property('currencyRates'),

  schedulePollEvent (event, interval) {
    var eventInterval = interval || this.get('pollingInterval');
    return Ember.run.later(() => {
      event.apply(this);
      this.set('timer', this.schedulePollEvent(event));
    }, eventInterval);
  },

  startPolling (interval) {
    this.set('timer', this.schedulePollEvent(this.get('onPoll'), interval));
  },

  stopPolling () {
    Ember.run.cancel(this.get('timer'));
  },

  onPoll () {
    const _this = this;
    return $.ajax('http://api.fixer.io/latest?base=USD', {
      dataType: 'jsonp'
    })
      .done(response => {
        _this.set('currencyRates', response);
      })
      .fail(err => console.log(err));
  },

  dataToDisplay: function () {
    let month = this.get('currentMonthDisplaying').month;
    let year = this.get('currentMonthDisplaying').year;
    let timePeriodsList = [];

    // Filter expenses for current month and generate timePeriodsList while you at it.
    let filteredData = this.get('model').filter(item => {
      // Save values to be reused
      let timePeriod = [item.get('year'), item.get('month')];

      // Determine if timeperiod is alredy on the list
      let notOnList = timePeriodsList.every(arr => {
        if (arr[0] !== timePeriod[0]) {
          return true;
        } else {
          // if arr[0] === timePeriod[0]
          return arr[1] !== timePeriod[1];
        }
      });

      // Save if not on list
      if (notOnList) {
        timePeriodsList.push(timePeriod);
      }

      // Returns false if expense is not for current month
      return timePeriod[0] === year && timePeriod[1] === month;
    });

    this.set('timePeriodsList', timePeriodsList);
    return filteredData;
  }.property('model.@each'),

  updateSpendingsMeter: function (data) {
    let sumCounted = 0;
    let sumByCategory = [];
    this.get('dataToDisplay').forEach(item => {
      let sum = item.get('sum');
      let category = item.get('category');

      if (sumByCategory.findBy('category', category)) {
        sumByCategory.findBy('category', category).sum += parseFloat(sum);
      } else {
        sumByCategory.pushObject({
          category,
          sum: parseFloat(sum)
        });
      }
      sumCounted += parseFloat(sum);
    });
    this.set('spendingsMeter', sumCounted);
    this.set('sumByCategory', sumByCategory);
    return;
  }.observes('model.@each.sum'),

  formatedChartData: function () {
    const data = [
      ['Category', 'Spendings']
    ];

    this.get('sumByCategory').forEach(category => {
      data.push(
        [category.category, category.sum]
      );
    });
    return data;
  }.property('sumByCategory'),

  actions: {

    timePeriodHasChanged (timePeriod) {
      this.set('currentMonthDisplaying', timePeriod);
      this.set('model', this.store.findAll('expense'));
    },

    saveRecord (record) {
      let setTimePeriodRecord = record;

      // If timeperiod is in past it will set correct month and year for expense on save
      // otherwise default value is set in model
      if (this.get('currentMonthDisplaying').isInPast) {
        setTimePeriodRecord.month = this.get('currentMonthDisplaying').month;
        setTimePeriodRecord.year = this.get('currentMonthDisplaying').year;
      }

      let expense = this.store.createRecord('expense', setTimePeriodRecord);
      expense.save();
    }
  }
});
<|endoftext|>


<commit_before>var path = require('path');
var express = require('express');

var app = express();

// All environments
app.set('port', process.env.PORT || 3000);
app.set('views', './views');
app.set('view engine', 'pug');

// Set static path
app.use(express.static(path.join(__dirname, 'assets')));

// Routes
app.get('/', function (req, res) {
	res.render('index');
});

app.get('/demo', function (req, res) {
	res.render('demo');
});

app.get('/documentation', function (req, res) {
	res.render('documentation');
});

app.get('/settings', function (req, res) {
	res.render('settings');
});

app.listen(app.get('port'), function () {
	console.log('Express server listening on port ' + app.get('port'))
}
<commit_msg>fixed build error<commit_after>var path = require('path');
var express = require('express');

var app = express();

// All environments
app.set('port', process.env.PORT || 3000);
app.set('views', './views');
app.set('view engine', 'pug');

// Set static path
app.use(express.static(path.join(__dirname, 'assets')));

// Routes
app.get('/', function (req, res) {
	res.render('index');
});

app.get('/demo', function (req, res) {
	res.render('demo');
});

app.get('/documentation', function (req, res) {
	res.render('documentation');
});

app.get('/settings', function (req, res) {
	res.render('settings');
});

app.listen(app.get('port'), function () {
	console.log('Express server listening on port ' + app.get('port'));
});
<|endoftext|>