<commit_before>var dom = require("../../lib/jsdom/level2/core").dom.level2.core;
var browser = require("../../lib/jsdom/browser/index").browserAugmentation(dom);

exports.tests = {
  notfound_getelementsbyclassname: function(test) {
    var doc = new browser.Document();
    var html = doc.createElement("html");
    doc.appendChild(html);
    var body = doc.createElement("body");
    html.appendChild(body);
    var p = doc.createElement("p");
    p.className = "unknown";
    body.appendChild(p);
    var elements = doc.getElementsByClassName("first-p");
    test.equal(elements.length, 0, "no results");
    test.done();
  },

  basic_getelementsbyclassname: function(test) {
    var doc = new browser.Document();
    var html = doc.createElement("html");
    doc.appendChild(html);
    var body = doc.createElement("body");
    html.appendChild(body);
    var p = doc.createElement("p");
    p.className = "first-p";
    body.appendChild(p);
    var elements = doc.getElementsByClassName("first-p");
    test.equal(elements.item(0), p, 'p and first-p');
    test.done();
  },

  multiple_getelementsbyclassname: function(test) {
    var doc = new browser.Document();
    var html = doc.createElement("html");
    doc.appendChild(html);
    var body = doc.createElement("body");
    html.appendChild(body);
    var p = doc.createElement("p");
    p.className = "first-p second third";
    body.appendChild(p);
    var first = doc.getElementsByClassName("first-p").item(0);
    var second = doc.getElementsByClassName("second").item(0);
    var third = doc.getElementsByClassName("third").item(0);
    test.equal(first, p, 'p and first-p');
    test.equal(second, p, 'p and second');
    test.equal(third, p, 'p and third');
    test.done();
  },

  testclassnameworksasexpected: function(test) {
    var doc = new browser.Document();
    var p = doc.createElement("p");
    p.setAttribute("class", "first-p");
    test.equal(p.className, 'first-p', 'class attribute is same as className');
    p.className += " second";
    test.equal(p.className, 'first-p second', 'className getter/setter');
    test.done();
  },

  basic_getelementbyid: function(test) {
    var doc = new browser.Document();
    var html = doc.createElement("html");
    doc.appendChild(html);
    var body = doc.createElement("body");
    html.appendChild(body);
    var p = doc.createElement("p");
    p.id = "theid";
    body.appendChild(p);
    var element = doc.getElementById("theid");
    test.equal(element, p, "p and #theid");
    test.done();
  },

  nonexistant_getelementbyid: function(test) {
    var doc = new browser.Document();
    var html = doc.createElement("html");
    doc.appendChild(html);
    var body = doc.createElement("body");
    html.appendChild(body);
    var p = doc.createElement("p");
    p.id = "theid";
    body.appendChild(p);
    var element = doc.getElementById("non-existant-id");
    test.equal(element, null, "p and #theid");
    test.done();
  },

  remove_nonexistantattribute: function(test) {
    var doc = new browser.Document();
    var html = doc.createElement("html");
    doc.appendChild(html);
    var body = doc.createElement("body");
    html.appendChild(body);
    test.doesNotThrow(function(){ body.removeAttribute("non-existant"); }), 'setValue_throws_NO_MODIFICATION_ERR';
    test.done();
  },

  render_singletag: function(test) {
    var doc = new browser.Document();
    var p = doc.createElement("p");
    var img = doc.createElement("img");
    p.appendChild(img);
    var out = p.outerHTML;
    test.equal(out.match(/<\/img>/), null, 'end tag not included in output')
    test.done();
  },

  parse_scripttags: function(test) {
    var doc = new browser.Document();
    var head = doc.createElement("head");
    var scriptHtml = '';
    head.innerHTML = scriptHtml;
    test.equal(scriptHtml, head.innerHTML, "original and processed");
    test.done();
  },

  parse_styletags: function(test) {
    var doc = new browser.Document();
    var head = doc.createElement("head");
    var styleHtml = '';
    head.innerHTML = styleHtml;
    test.equal(styleHtml, head.innerHTML, "original and processed");
    test.done();
  },

  parse_doublespacetags: function(test) {
    var doc = new browser.Document();
    var html = '';
    test.doesNotThrow(function(){ doc.innerHTML = html; }), 'setValue_throws_INVALID_CHARACTER_ERR';
    test.done();
  },

  serialize_styleattribute: function(test) {
    var doc = new browser.Document();
		var domToHtml = require('../../lib/jsdom/browser/domtohtml');
    doc.appendChild(doc.createElement('html'));
    doc.documentElement.style.color = 'black';
    doc.documentElement.style.backgroundColor = 'white';
    test.equal(domToHtml.domToHtml(doc), '\r\n', '');
    test.done();
  },

  innerhtml_removeallchildren: function(test) {
    var doc = new browser.HTMLDocument();
    doc.write('

');
    doc.body.innerHTML = '';
    test.equal(doc.body.childNodes.length, 0, 'still has children');
    test.done();
  },

  serialize_html5_doctype: function(test) {
    var dom = new browser.DOMImplementation();
    var doctype = dom.createDocumentType('html');
    var document = dom.createDocument(null, null, doctype);
    var regexp = /^\s*<!DOCTYPE html>/;
    test.ok(regexp.test(document.outerHTML), 'HTML 5 doctype did not serialize correctly');
    test.done();
  },

  serialize_html4_strict_doctype: function(test) {
    var dom = new browser.DOMImplementation();
    var doctype = dom.createDocumentType('html', '-//W3C//DTD HTML 4.01//EN', 'http://www.w3.org/TR/html4/strict.dtd');
    var document = dom.createDocument(null, null, doctype);
    var regexp = /^\s*<!DOCTYPE html PUBLIC "-\/\/W3C\/\/DTD HTML 4.01\/\/EN" "http:\/\/www.w3.org\/TR\/html4\/strict.dtd">/;
    test.ok(regexp.test(document.outerHTML), 'HTML 4 strict doctype did not serialize correctly');
    test.done();
  },

  serialize_system_doctype: function(test) {
    var dom = new browser.DOMImplementation();
    var doctype = dom.createDocumentType('foo', null, 'foo.dtd');
    var document = dom.createDocument(null, null, doctype);
    var regexp = /^\s*<!DOCTYPE foo SYSTEM "foo.dtd">/;
    test.ok(regexp.test(document.outerHTML), 'Doctype did not serialize correctly');
    test.done();
  },

  serialize_doctype_containing_quotes: function(test) {
    var dom = new browser.DOMImplementation();
    var doctype = dom.createDocumentType('foo', null, 'foo "bar".dtd');
    var document = dom.createDocument(null, null, doctype);
    var regexp = /^\s*<!DOCTYPE foo SYSTEM \'foo "bar".dtd\'>/;
    test.ok(regexp.test(document.outerHTML), 'Doctype did not serialize correctly');
    test.done();
  },

  parse_doctype_containing_newline : function() {
    var html = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"\n \
             "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n',
        doc  = new browser.Document();
    doc.innerHTML = html;
    assertTrue('doctype should not be falsy', !!doc.doctype);
  },

  basic_nodelist_indexOf : function() {
    var doc = new browser.Document();

    var html = doc.createElement("html");
    doc.appendChild(html);

    var body = doc.createElement("body");
    html.appendChild(body);

    var p = doc.createElement("p");
    body.appendChild(p);

    var div = doc.createElement("div");
    body.appendChild(div);

    var span = doc.createElement("span");
    body.appendChild(span);

    var index = body.childNodes.indexOf(span);
    assertEquals("indexOf 'span' in childNodes", 2, index);
  },

  nonexistant_nodelist_indexOf : function() {
    var doc = new browser.Document();

    var html = doc.createElement("html");
    doc.appendChild(html);

    var body = doc.createElement("body");
    html.appendChild(body);

    var p = doc.createElement("p");
    body.appendChild(p);

    var div = doc.createElement("div");
    p.appendChild(div);

    var index = body.childNodes.indexOf(div);
    assertEquals("indexOf 'span' in childNodes", -1, index);
  }
};
<commit_msg>rebased from upstream/master and converted new tests<commit_after>var dom = require("../../lib/jsdom/level2/core").dom.level2.core;
var browser = require("../../lib/jsdom/browser/index").browserAugmentation(dom);

exports.tests = {
  notfound_getelementsbyclassname: function(test) {
    var doc = new browser.Document();
    var html = doc.createElement("html");
    doc.appendChild(html);
    var body = doc.createElement("body");
    html.appendChild(body);
    var p = doc.createElement("p");
    p.className = "unknown";
    body.appendChild(p);
    var elements = doc.getElementsByClassName("first-p");
    test.equal(elements.length, 0, "no results");
    test.done();
  },

  basic_getelementsbyclassname: function(test) {
    var doc = new browser.Document();
    var html = doc.createElement("html");
    doc.appendChild(html);
    var body = doc.createElement("body");
    html.appendChild(body);
    var p = doc.createElement("p");
    p.className = "first-p";
    body.appendChild(p);
    var elements = doc.getElementsByClassName("first-p");
    test.equal(elements.item(0), p, 'p and first-p');
    test.done();
  },

  multiple_getelementsbyclassname: function(test) {
    var doc = new browser.Document();
    var html = doc.createElement("html");
    doc.appendChild(html);
    var body = doc.createElement("body");
    html.appendChild(body);
    var p = doc.createElement("p");
    p.className = "first-p second third";
    body.appendChild(p);
    var first = doc.getElementsByClassName("first-p").item(0);
    var second = doc.getElementsByClassName("second").item(0);
    var third = doc.getElementsByClassName("third").item(0);
    test.equal(first, p, 'p and first-p');
    test.equal(second, p, 'p and second');
    test.equal(third, p, 'p and third');
    test.done();
  },

  testclassnameworksasexpected: function(test) {
    var doc = new browser.Document();
    var p = doc.createElement("p");
    p.setAttribute("class", "first-p");
    test.equal(p.className, 'first-p', 'class attribute is same as className');
    p.className += " second";
    test.equal(p.className, 'first-p second', 'className getter/setter');
    test.done();
  },

  basic_getelementbyid: function(test) {
    var doc = new browser.Document();
    var html = doc.createElement("html");
    doc.appendChild(html);
    var body = doc.createElement("body");
    html.appendChild(body);
    var p = doc.createElement("p");
    p.id = "theid";
    body.appendChild(p);
    var element = doc.getElementById("theid");
    test.equal(element, p, "p and #theid");
    test.done();
  },

  nonexistant_getelementbyid: function(test) {
    var doc = new browser.Document();
    var html = doc.createElement("html");
    doc.appendChild(html);
    var body = doc.createElement("body");
    html.appendChild(body);
    var p = doc.createElement("p");
    p.id = "theid";
    body.appendChild(p);
    var element = doc.getElementById("non-existant-id");
    test.equal(element, null, "p and #theid");
    test.done();
  },

  remove_nonexistantattribute: function(test) {
    var doc = new browser.Document();
    var html = doc.createElement("html");
    doc.appendChild(html);
    var body = doc.createElement("body");
    html.appendChild(body);
    test.doesNotThrow(function(){ body.removeAttribute("non-existant"); }), 'setValue_throws_NO_MODIFICATION_ERR';
    test.done();
  },

  render_singletag: function(test) {
    var doc = new browser.Document();
    var p = doc.createElement("p");
    var img = doc.createElement("img");
    p.appendChild(img);
    var out = p.outerHTML;
    test.equal(out.match(/<\/img>/), null, 'end tag not included in output')
    test.done();
  },

  parse_scripttags: function(test) {
    var doc = new browser.Document();
    var head = doc.createElement("head");
    var scriptHtml = '';
    head.innerHTML = scriptHtml;
    test.equal(scriptHtml, head.innerHTML, "original and processed");
    test.done();
  },

  parse_styletags: function(test) {
    var doc = new browser.Document();
    var head = doc.createElement("head");
    var styleHtml = '';
    head.innerHTML = styleHtml;
    test.equal(styleHtml, head.innerHTML, "original and processed");
    test.done();
  },

  parse_doublespacetags: function(test) {
    var doc = new browser.Document();
    var html = '';
    test.doesNotThrow(function(){ doc.innerHTML = html; }), 'setValue_throws_INVALID_CHARACTER_ERR';
    test.done();
  },

  serialize_styleattribute: function(test) {
    var doc = new browser.Document();
		var domToHtml = require('../../lib/jsdom/browser/domtohtml');
    doc.appendChild(doc.createElement('html'));
    doc.documentElement.style.color = 'black';
    doc.documentElement.style.backgroundColor = 'white';
    test.equal(domToHtml.domToHtml(doc), '\r\n', '');
    test.done();
  },

  innerhtml_removeallchildren: function(test) {
    var doc = new browser.HTMLDocument();
    doc.write('

');
    doc.body.innerHTML = '';
    test.equal(doc.body.childNodes.length, 0, 'still has children');
    test.done();
  },

  serialize_html5_doctype: function(test) {
    var dom = new browser.DOMImplementation();
    var doctype = dom.createDocumentType('html');
    var document = dom.createDocument(null, null, doctype);
    var regexp = /^\s*<!DOCTYPE html>/;
    test.ok(regexp.test(document.outerHTML), 'HTML 5 doctype did not serialize correctly');
    test.done();
  },

  serialize_html4_strict_doctype: function(test) {
    var dom = new browser.DOMImplementation();
    var doctype = dom.createDocumentType('html', '-//W3C//DTD HTML 4.01//EN', 'http://www.w3.org/TR/html4/strict.dtd');
    var document = dom.createDocument(null, null, doctype);
    var regexp = /^\s*<!DOCTYPE html PUBLIC "-\/\/W3C\/\/DTD HTML 4.01\/\/EN" "http:\/\/www.w3.org\/TR\/html4\/strict.dtd">/;
    test.ok(regexp.test(document.outerHTML), 'HTML 4 strict doctype did not serialize correctly');
    test.done();
  },

  serialize_system_doctype: function(test) {
    var dom = new browser.DOMImplementation();
    var doctype = dom.createDocumentType('foo', null, 'foo.dtd');
    var document = dom.createDocument(null, null, doctype);
    var regexp = /^\s*<!DOCTYPE foo SYSTEM "foo.dtd">/;
    test.ok(regexp.test(document.outerHTML), 'Doctype did not serialize correctly');
    test.done();
  },

  serialize_doctype_containing_quotes: function(test) {
    var dom = new browser.DOMImplementation();
    var doctype = dom.createDocumentType('foo', null, 'foo "bar".dtd');
    var document = dom.createDocument(null, null, doctype);
    var regexp = /^\s*<!DOCTYPE foo SYSTEM \'foo "bar".dtd\'>/;
    test.ok(regexp.test(document.outerHTML), 'Doctype did not serialize correctly');
    test.done();
  },

  parse_doctype_containing_newline : function(test) {
    var html = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"\n \
             "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n',
        doc  = new browser.Document();
    doc.innerHTML = html;
    test.ok(!!doc.doctype, 'doctype should not be falsy');
    test.done();
  },

  basic_nodelist_indexOf : function(test) {
    var doc = new browser.Document();
    var html = doc.createElement("html");
    doc.appendChild(html);
    var body = doc.createElement("body");
    html.appendChild(body);
    var p = doc.createElement("p");
    body.appendChild(p);
    var div = doc.createElement("div");
    body.appendChild(div);
    var span = doc.createElement("span");
    body.appendChild(span);
    var index = body.childNodes.indexOf(span);
    test.equal(index, 2, "indexOf 'span' in childNodes")
    test.done();
  },

  nonexistant_nodelist_indexOf : function(test) {
    var doc = new browser.Document();
    var html = doc.createElement("html");
    doc.appendChild(html);
    var body = doc.createElement("body");
    html.appendChild(body);
    var p = doc.createElement("p");
    body.appendChild(p);
    var div = doc.createElement("div");
    p.appendChild(div);
    var index = body.childNodes.indexOf(div);
    test.equal(index, -1, "indexOf 'span' in childNodes")
    test.done();
  }
};
<|endoftext|>


<commit_before><commit_msg>feat(endpoint): new removeNext() to remove an interceptor<commit_after><|endoftext|>


<commit_before>module.exports = {
  entry: {
    main: "./src/main.ts",
    background: "./src/background.ts",
    popup: "./src/popup.tsx",
    tooiForMonkeys: "./src/tooiForMonkeys.ts",
  },
  output: {
    filename: "[name].bundle.js",
    path: __dirname + "/dist/js"
  },

  resolve: {
    // Add '.ts' and '.tsx' as resolvable extensions.
    extensions: [".ts", ".tsx"]
  },

  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: [
          { loader: "babel-loader" },
        ],
        exclude: /node_modules/,
      },
    ],
  },

  optimization: {
    minimize: false
  },

  // When importing a module whose path matches one of the following, just
  // assume a corresponding global variable exists and use that instead.
  // This is important because it allows us to avoid bundling all of our
  // dependencies, which allows browsers to cache those libraries between builds.
  externals: {
    "react": "React",
    "react-dom": "ReactDOM"
  }
};
<commit_msg>fix webpack config<commit_after>module.exports = {
  entry: {
    main: "./src/main.ts",
    background: "./src/background.ts",
    popup: "./src/popup.tsx",
    tooiForMonkeys: "./src/tooiForMonkeys.ts",
  },
  output: {
    filename: "[name].bundle.js",
    path: __dirname + "/dist/js"
  },

  resolve: {
    // Add '.ts' and '.tsx' as resolvable extensions.
    extensions: [".ts", ".tsx", ".js", ".json"]
  },

  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: [
          { loader: "babel-loader" },
        ],
        exclude: /node_modules/,
      },
    ],
  },

  optimization: {
    minimize: false
  },

  // When importing a module whose path matches one of the following, just
  // assume a corresponding global variable exists and use that instead.
  // This is important because it allows us to avoid bundling all of our
  // dependencies, which allows browsers to cache those libraries between builds.
  // externals: {
  //   "react": "React",
  //   "react-dom": "ReactDOM"
  // }
};
<|endoftext|>


<commit_before>var couchbase = require('couchbase');
var _ = require('lodash');
var testUtil = require('./helpers/utils');
var expect = require('chai').expect;

var lounge = require('../');
var couchUtil = require('../dist/couchdoc.utils');

var bucket;

describe('Model index tests', function () {
  beforeEach(function (done) {
    if (lounge) {
      lounge.disconnect();
    }

    lounge = new lounge.Lounge(); // recreate it

    var cluster = testUtil.getCluser();
    bucket = cluster.openBucket('lounge_test', function (err) {
      if (err) {
        return done(err);
      }

      lounge.connect({
        bucket: bucket
      }, function () {
        bucket.manager().flush(done);
      });
    });
  });

  describe('initial ref value and function creation tests', function () {
    it('should create index values for a simple document', function () {
      var userSchema = new lounge.Schema({
        firstName: String,
        lastName: String,
        email: {type: String, index: true}
      });

      var User = lounge.model('User', userSchema);

      expect(User.findByEmail).to.be.ok;
      expect(User.findByEmail).to.be.an.instanceof(Function);

      var data = {
        firstName: 'Joe',
        lastName: 'Smith',
        email: 'joe@gmail.com'
      };

      var expected = {
        email: {
          path: 'email',
          value: 'joe@gmail.com',
          name: 'email'
        }
      };

      // we have to generate this manually since we don't have access to object internals
      // this has to match how we would use it in CouchDocument, specifically constructor to build the initial list
      var actual = couchUtil.buildRefValues(userSchema.indexes, data);

      expect(actual).to.deep.equal(expected);
    });

    it('should create index values for array and automatically singularize', function () {
      var userSchema = new lounge.Schema({
        firstName: String,
        lastName: String,
        usernames: [{type: String, index: true}]
      });

      var User = lounge.model('User', userSchema);

      expect(User.findByUsername).to.be.ok;
      expect(User.findByUsername).to.be.an.instanceof(Function);

      var data = {
        firstName: 'Joe',
        lastName: 'Smith',
        usernames: ['user1', 'user2']
      };

      var expected = {
        'username': {
          path: 'usernames',
          value: ['user1', 'user2'],
          name: 'username'
        }
      };

      var actualRefs = couchUtil.buildRefValues(userSchema.indexes, data);
      expect(actualRefs).to.deep.equal(expected);
    });

    it('should create index values for array and  respect indexName', function () {
      var userSchema = new lounge.Schema({
        firstName: String,
        lastName: String,
        usernames: [{type: String, index: true, indexName: 'UN'}]
      });

      var User = lounge.model('User', userSchema);

      expect(User.findByUN).to.be.ok;
      expect(User.findByUN).to.be.an.instanceof(Function);

      var data = {
        firstName: 'Joe',
        lastName: 'Smith',
        usernames: ['user1', 'user2']
      };

      var expected = {
        'UN': {
          path: 'usernames',
          value: ['user1', 'user2'],
          name: 'UN'
        }
      };

      var actualRefs = couchUtil.buildRefValues(userSchema.indexes, data);
      expect(actualRefs).to.deep.equal(expected);
    });

    it('should not create index value for a ref field', function () {
      var fooSchema = lounge.schema({
        a: String,
        b: String
      });

      var Foo = lounge.model('Foo', fooSchema);

      var userSchema = lounge.schema({
        firstName: String,
        lastName: String,
        email: {type: String, index: true},
        foo: {type: Foo}
      });

      var User = lounge.model('User', userSchema);

      expect(User.findByEmail).to.be.ok;
      expect(User.findByEmail).to.be.an.instanceof(Function);
      expect(User.findByFoo).to.not.be.ok;
      expect(User.findByFoo).to.not.be.an.instanceof(Function);

      var foo = new Foo({
        a: 'a1',
        b: 'b1'
      });

      var data = {
        firstName: 'Joe',
        lastName: 'Smith',
        email: 'joe@gmail.com',
        foo: foo
      };

      var expected = {
        'email': {
          path: 'email',
          value: 'joe@gmail.com',
          name: 'email'
        }
      };

      var actualRefs = couchUtil.buildRefValues(userSchema.indexes, data);
      expect(actualRefs).to.deep.equal(expected);
    });

    it('should create index value for untruthy values', function () {
      var userSchema = lounge.schema({
        firstName: String,
        lastName: String,
        email: {type: String, index: true}
      });

      var User = lounge.model('User', userSchema);

      expect(User.findByEmail).to.be.ok;
      expect(User.findByEmail).to.be.an.instanceof(Function);

      var data = {
        firstName: 'Joe',
        lastName: 'Smith'
      };

      var expected = {
        'email': {
          path: 'email',
          value: null,
          name: 'email'
        }
      };

      var actualRefs = couchUtil.buildRefValues(userSchema.indexes, data);
      expect(actualRefs).to.deep.equal(expected);
    });
  });
});<commit_msg>fix index tests<commit_after>var couchbase = require('couchbase');
var _ = require('lodash');
var testUtil = require('./helpers/utils');
var expect = require('chai').expect;

var lounge = require('../');
var couchUtil = require('../dist/cbdocument.utils');

var bucket;

describe('Model index tests', function () {
  beforeEach(function (done) {
    if (lounge) {
      lounge.disconnect();
    }

    lounge = new lounge.Lounge(); // recreate it

    var cluster = testUtil.getCluser();
    bucket = cluster.openBucket('lounge_test', function (err) {
      if (err) {
        return done(err);
      }

      lounge.connect({
        bucket: bucket
      }, function () {
        bucket.manager().flush(done);
      });
    });
  });

  describe('initial ref value and function creation tests', function () {
    it('should create index values for a simple document', function () {
      var userSchema = new lounge.Schema({
        firstName: String,
        lastName: String,
        email: {type: String, index: true}
      });

      var User = lounge.model('User', userSchema);

      expect(User.findByEmail).to.be.ok;
      expect(User.findByEmail).to.be.an.instanceof(Function);

      var data = {
        firstName: 'Joe',
        lastName: 'Smith',
        email: 'joe@gmail.com'
      };

      var expected = {
        email: {
          path: 'email',
          value: 'joe@gmail.com',
          name: 'email'
        }
      };

      // we have to generate this manually since we don't have access to object internals
      // this has to match how we would use it in CouchDocument, specifically constructor to build the initial list
      var actual = couchUtil.buildRefValues(userSchema.indexes, data);

      expect(actual).to.deep.equal(expected);
    });

    it('should create index values for array and automatically singularize', function () {
      var userSchema = new lounge.Schema({
        firstName: String,
        lastName: String,
        usernames: [{type: String, index: true}]
      });

      var User = lounge.model('User', userSchema);

      expect(User.findByUsername).to.be.ok;
      expect(User.findByUsername).to.be.an.instanceof(Function);

      var data = {
        firstName: 'Joe',
        lastName: 'Smith',
        usernames: ['user1', 'user2']
      };

      var expected = {
        'username': {
          path: 'usernames',
          value: ['user1', 'user2'],
          name: 'username'
        }
      };

      var actualRefs = couchUtil.buildRefValues(userSchema.indexes, data);
      expect(actualRefs).to.deep.equal(expected);
    });

    it('should create index values for array and  respect indexName', function () {
      var userSchema = new lounge.Schema({
        firstName: String,
        lastName: String,
        usernames: [{type: String, index: true, indexName: 'UN'}]
      });

      var User = lounge.model('User', userSchema);

      expect(User.findByUN).to.be.ok;
      expect(User.findByUN).to.be.an.instanceof(Function);

      var data = {
        firstName: 'Joe',
        lastName: 'Smith',
        usernames: ['user1', 'user2']
      };

      var expected = {
        'UN': {
          path: 'usernames',
          value: ['user1', 'user2'],
          name: 'UN'
        }
      };

      var actualRefs = couchUtil.buildRefValues(userSchema.indexes, data);
      expect(actualRefs).to.deep.equal(expected);
    });

    it('should not create index value for a ref field', function () {
      var fooSchema = lounge.schema({
        a: String,
        b: String
      });

      var Foo = lounge.model('Foo', fooSchema);

      var userSchema = lounge.schema({
        firstName: String,
        lastName: String,
        email: {type: String, index: true},
        foo: {type: Foo}
      });

      var User = lounge.model('User', userSchema);

      expect(User.findByEmail).to.be.ok;
      expect(User.findByEmail).to.be.an.instanceof(Function);
      expect(User.findByFoo).to.not.be.ok;
      expect(User.findByFoo).to.not.be.an.instanceof(Function);

      var foo = new Foo({
        a: 'a1',
        b: 'b1'
      });

      var data = {
        firstName: 'Joe',
        lastName: 'Smith',
        email: 'joe@gmail.com',
        foo: foo
      };

      var expected = {
        'email': {
          path: 'email',
          value: 'joe@gmail.com',
          name: 'email'
        }
      };

      var actualRefs = couchUtil.buildRefValues(userSchema.indexes, data);
      expect(actualRefs).to.deep.equal(expected);
    });

    it('should create index value for untruthy values', function () {
      var userSchema = lounge.schema({
        firstName: String,
        lastName: String,
        email: {type: String, index: true}
      });

      var User = lounge.model('User', userSchema);

      expect(User.findByEmail).to.be.ok;
      expect(User.findByEmail).to.be.an.instanceof(Function);

      var data = {
        firstName: 'Joe',
        lastName: 'Smith'
      };

      var expected = {
        'email': {
          path: 'email',
          value: null,
          name: 'email'
        }
      };

      var actualRefs = couchUtil.buildRefValues(userSchema.indexes, data);
      expect(actualRefs).to.deep.equal(expected);
    });
  });
});<|endoftext|>


<commit_before>AUI.add('dialog', function(A) {

var L = A.Lang,
	isBoolean = L.isBoolean,
	isArray = L.isArray,
	isObject = L.isObject,

	BLANK = '',
	BODY_CONTENT = 'bodyContent',
	BOUNDING_BOX = 'boundingBox',
	BUTTON = 'button',
	BUTTONS = 'buttons',
	CLOSE = 'close',
	CONSTRAIN_TO_VIEWPORT = 'constrain2view',
	CONTAINER = 'container',
	DD = 'dd',
	DEFAULT = 'default',
	DESTROY_ON_CLOSE = 'destroyOnClose',
	DIALOG = 'dialog',
	DOT = '.',
	DRAGGABLE = 'draggable',
	DRAG_INSTANCE = 'dragInstance',
	FOOTER_CONTENT = 'footerContent',
	HD = 'hd',
	ICON = 'icon',
	IO = 'io',
	LOADING = 'loading',
	MODAL = 'modal',
	STACK = 'stack',
	TOOLS = 'tools',

	getCN = A.ClassNameManager.getClassName,

	CSS_DIALOG_BUTTON = getCN(DIALOG, BUTTON),
	CSS_DIALOG_BUTTON_CONTAINER = getCN(DIALOG, BUTTON, CONTAINER),
	CSS_DIALOG_BUTTON_DEFAULT = getCN(DIALOG, BUTTON, DEFAULT),
	CSS_DIALOG_HD = getCN(DIALOG, HD),
	CSS_ICON_LOADING = getCN(ICON, LOADING),
	CSS_PREFIX = getCN(DD),

	NODE_BLANK_TEXT = document.createTextNode(''),

	TPL_BUTTON = '<button class="' + CSS_DIALOG_BUTTON + '"></button>',
	TPL_BUTTON_CONTAINER = '

';

var Dialog = function(config) {};

A.mix(
	Dialog,
	{
		NAME: DIALOG,

		ATTRS: {
			bodyContent: {
				value: NODE_BLANK_TEXT
			},

			buttons: {
				value: [],
				validator: isArray
			},

			close: {
				value: true
			},

			constrain2view: {
				value: false,
				validator: isBoolean
			},

			destroyOnClose: {
				value: false,
				validator: isBoolean
			},

			draggable: {
				lazyAdd: true,
				value: true,
				setter: function(v) {
					return this._setDraggable(v);
				}
			},

			dragInstance: {
				value: null
			},

			headerContent: {
				writeOnce: true,
				getter: function() {
					return this.titleContainter;
				}
			},

			modal: {
				setter: function(v) {
					return this._setModal(v);
				},
				lazyAdd: false,
				value: false,
				validator: isBoolean
			},

			stack: {
				lazyAdd: true,
				value: true,
				setter: function(v) {
					return this._setStack(v);
				},
				validator: isBoolean
			}
		}
	}
);

Dialog.prototype = {
	initializer: function(config) {
		var instance = this;
		var tools = instance.get(TOOLS);
		var close = instance.get(CLOSE);
		var buttons = instance.get(BUTTONS);

		if (buttons && buttons.length && !instance.get(FOOTER_CONTENT)) {
			instance.set(FOOTER_CONTENT, NODE_BLANK_TEXT);
		}

		if (close) {
			var closeConfig = {
				icon: CLOSE,
				id: CLOSE,
				handler: {
					fn: instance.close,
					context: instance
				}
			};

			if (tools) {
				tools.push(closeConfig);
			}

			instance.set(TOOLS, tools);
		}

		instance.after('render', instance._afterRenderer);
	},

	bindUI: function() {
		var instance = this;

		instance.publish('close', { defaultFn: instance._close });
	},

	destructor: function() {
		var instance = this;
		var boundingBox = instance.get(BOUNDING_BOX);

		A.Event.purgeElement(boundingBox);
	},

	/*
	* Methods
	*/
	close: function() {
		var instance = this;

		instance.fire('close');
	},

	_afterRenderer: function() {
		var instance = this;

		instance._initButtons();

		// forcing lazyAdd:true attrs call the setter
		instance.get(STACK);
		instance.get(DRAGGABLE);
		instance.get(IO);
	},

	_close: function() {
		var instance = this;

		if (instance.get(DESTROY_ON_CLOSE)) {
			instance.destroy();
		}
		else {
			instance.hide();
		}

		if (instance.get(MODAL)) {
			A.DialogMask.hide();
		}
	},

	_initButtons: function() {
		var instance = this;

		var buttons = instance.get(BUTTONS);
		var container = A.Node.create(TPL_BUTTON_CONTAINER);
		var nodeModel = A.Node.create(TPL_BUTTON);

		A.each(
			buttons,
			function(button, i) {
				var node = nodeModel.cloneNode();

				if (button.isDefault) {
					node.addClass(CSS_DIALOG_BUTTON_DEFAULT);
				}

				if (button.handler) {
					node.on('click', button.handler, instance);
				}

				node.html(button.text || BLANK);

				container.append(node);
			}
		);

		if (buttons.length) {
			instance.set(FOOTER_CONTENT, container);
		}
	},

	_setDraggable: function(value) {
		var instance = this;
		var boundingBox = instance.get(BOUNDING_BOX);

		var destroyDraggable = function() {
			var dragInstance = instance.get(DRAG_INSTANCE);

			if (dragInstance) {
				// TODO - YUI3 has a bug when destroy and recreates
				dragInstance.destroy();
				dragInstance.unplug(A.Plugin.DDConstrained);
			}
		};

		A.DD.DDM.CSS_PREFIX = CSS_PREFIX;

		if (value) {
			var defaults = {
				node: boundingBox,
				handles: [ DOT + CSS_DIALOG_HD ]
			};

			var dragOptions = A.merge(defaults, instance.get(DRAGGABLE) || {});

			// change the drag scope callback to execute using the dialog scope
			if (dragOptions.on) {
				A.each(
					dragOptions.on,
					function(fn, eventName) {
						dragOptions.on[eventName] = A.bind(fn, instance);
					}
				);
			}

			destroyDraggable();

			var dragInstance = new A.DD.Drag(dragOptions);

			dragInstance.plug(
				A.Plugin.DDConstrained,
				{
					constrain2view: instance.get(CONSTRAIN_TO_VIEWPORT)
				}
			);

			instance.set(DRAG_INSTANCE, dragInstance);
		}
		else {
			destroyDraggable();
		}

		return value;
	},

	_setModal: function(value) {
		var instance = this;

		if (value) {
			A.DialogMask.show();
		}
		else {
			A.DialogMask.hide();
		}

		return value;
	},

	_setStack: function(value) {
		var instance = this;

		if (value) {
			A.DialogManager.register(instance);
		}
		else {
			A.DialogManager.remove(instance);
		}

		return value;
	},

	/*
	* Attribute Listeners
	*/
	_afterSetVisible: function(event) {
		var instance = this;

		if (instance.get(MODAL)) {
			if (event.newVal) {
				A.DialogMask.show();
			}
			else {
				A.DialogMask.hide();
			}
		}
	}
};

A.Dialog = A.Base.build(DIALOG, A.Panel, [Dialog, A.WidgetPosition, A.WidgetStack, A.WidgetPositionExt]);

A.DialogManager = new A.OverlayManager(
	{
		zIndexBase: 1000
	}
);

A.mix(
	A.DialogManager,
	{
		findByChild: function(child) {
			return A.Widget.getByNode(child);
		},

		closeByChild: function(child) {
			return A.DialogManager.findByChild(child).close();
		},

		refreshByChild: function(child, io) {
			var dialog = A.DialogManager.findByChild(child);

			if (dialog && dialog.io) {
				dialog.io.start();
			}
		}
	}
);

A.DialogMask = new A.OverlayMask().render();

}, '@VERSION', { requires: [ 'aui-base', 'panel', 'overlay-manager', 'overlay-mask', 'dd-constrain', 'io-plugin', 'dialog-css' ] });<commit_msg>Dialog autoPurge elements recursively on destroy<commit_after>AUI.add('dialog', function(A) {

var L = A.Lang,
	isBoolean = L.isBoolean,
	isArray = L.isArray,
	isObject = L.isObject,

	BLANK = '',
	BODY_CONTENT = 'bodyContent',
	BOUNDING_BOX = 'boundingBox',
	BUTTON = 'button',
	BUTTONS = 'buttons',
	CLOSE = 'close',
	CONSTRAIN_TO_VIEWPORT = 'constrain2view',
	CONTAINER = 'container',
	DD = 'dd',
	DEFAULT = 'default',
	DESTROY_ON_CLOSE = 'destroyOnClose',
	DIALOG = 'dialog',
	DOT = '.',
	DRAGGABLE = 'draggable',
	DRAG_INSTANCE = 'dragInstance',
	FOOTER_CONTENT = 'footerContent',
	HD = 'hd',
	ICON = 'icon',
	IO = 'io',
	LOADING = 'loading',
	MODAL = 'modal',
	STACK = 'stack',
	TOOLS = 'tools',

	getCN = A.ClassNameManager.getClassName,

	CSS_DIALOG_BUTTON = getCN(DIALOG, BUTTON),
	CSS_DIALOG_BUTTON_CONTAINER = getCN(DIALOG, BUTTON, CONTAINER),
	CSS_DIALOG_BUTTON_DEFAULT = getCN(DIALOG, BUTTON, DEFAULT),
	CSS_DIALOG_HD = getCN(DIALOG, HD),
	CSS_ICON_LOADING = getCN(ICON, LOADING),
	CSS_PREFIX = getCN(DD),

	NODE_BLANK_TEXT = document.createTextNode(''),

	TPL_BUTTON = '<button class="' + CSS_DIALOG_BUTTON + '"></button>',
	TPL_BUTTON_CONTAINER = '

';

var Dialog = function(config) {};

A.mix(
	Dialog,
	{
		NAME: DIALOG,

		ATTRS: {
			bodyContent: {
				value: NODE_BLANK_TEXT
			},

			buttons: {
				value: [],
				validator: isArray
			},

			close: {
				value: true
			},

			constrain2view: {
				value: false,
				validator: isBoolean
			},

			destroyOnClose: {
				value: false,
				validator: isBoolean
			},

			draggable: {
				lazyAdd: true,
				value: true,
				setter: function(v) {
					return this._setDraggable(v);
				}
			},

			dragInstance: {
				value: null
			},

			headerContent: {
				writeOnce: true,
				getter: function() {
					return this.titleContainter;
				}
			},

			modal: {
				setter: function(v) {
					return this._setModal(v);
				},
				lazyAdd: false,
				value: false,
				validator: isBoolean
			},

			stack: {
				lazyAdd: true,
				value: true,
				setter: function(v) {
					return this._setStack(v);
				},
				validator: isBoolean
			}
		}
	}
);

Dialog.prototype = {
	initializer: function(config) {
		var instance = this;
		var tools = instance.get(TOOLS);
		var close = instance.get(CLOSE);
		var buttons = instance.get(BUTTONS);

		if (buttons && buttons.length && !instance.get(FOOTER_CONTENT)) {
			instance.set(FOOTER_CONTENT, NODE_BLANK_TEXT);
		}

		if (close) {
			var closeConfig = {
				icon: CLOSE,
				id: CLOSE,
				handler: {
					fn: instance.close,
					context: instance
				}
			};

			if (tools) {
				tools.push(closeConfig);
			}

			instance.set(TOOLS, tools);
		}

		instance.after('render', instance._afterRenderer);
	},

	bindUI: function() {
		var instance = this;

		instance.publish('close', { defaultFn: instance._close });
	},

	destructor: function() {
		var instance = this;
		var boundingBox = instance.get(BOUNDING_BOX);

		A.Event.purgeElement(boundingBox, true);
	},

	/*
	* Methods
	*/
	close: function() {
		var instance = this;

		instance.fire('close');
	},

	_afterRenderer: function() {
		var instance = this;

		instance._initButtons();

		// forcing lazyAdd:true attrs call the setter
		instance.get(STACK);
		instance.get(DRAGGABLE);
		instance.get(IO);
	},

	_close: function() {
		var instance = this;

		if (instance.get(DESTROY_ON_CLOSE)) {
			instance.destroy();
		}
		else {
			instance.hide();
		}

		if (instance.get(MODAL)) {
			A.DialogMask.hide();
		}
	},

	_initButtons: function() {
		var instance = this;

		var buttons = instance.get(BUTTONS);
		var container = A.Node.create(TPL_BUTTON_CONTAINER);
		var nodeModel = A.Node.create(TPL_BUTTON);

		A.each(
			buttons,
			function(button, i) {
				var node = nodeModel.cloneNode();

				if (button.isDefault) {
					node.addClass(CSS_DIALOG_BUTTON_DEFAULT);
				}

				if (button.handler) {
					node.on('click', button.handler, instance);
				}

				node.html(button.text || BLANK);

				container.append(node);
			}
		);

		if (buttons.length) {
			instance.set(FOOTER_CONTENT, container);
		}
	},

	_setDraggable: function(value) {
		var instance = this;
		var boundingBox = instance.get(BOUNDING_BOX);

		var destroyDraggable = function() {
			var dragInstance = instance.get(DRAG_INSTANCE);

			if (dragInstance) {
				// TODO - YUI3 has a bug when destroy and recreates
				dragInstance.destroy();
				dragInstance.unplug(A.Plugin.DDConstrained);
			}
		};

		A.DD.DDM.CSS_PREFIX = CSS_PREFIX;

		if (value) {
			var defaults = {
				node: boundingBox,
				handles: [ DOT + CSS_DIALOG_HD ]
			};

			var dragOptions = A.merge(defaults, instance.get(DRAGGABLE) || {});

			// change the drag scope callback to execute using the dialog scope
			if (dragOptions.on) {
				A.each(
					dragOptions.on,
					function(fn, eventName) {
						dragOptions.on[eventName] = A.bind(fn, instance);
					}
				);
			}

			destroyDraggable();

			var dragInstance = new A.DD.Drag(dragOptions);

			dragInstance.plug(
				A.Plugin.DDConstrained,
				{
					constrain2view: instance.get(CONSTRAIN_TO_VIEWPORT)
				}
			);

			instance.set(DRAG_INSTANCE, dragInstance);
		}
		else {
			destroyDraggable();
		}

		return value;
	},

	_setModal: function(value) {
		var instance = this;

		if (value) {
			A.DialogMask.show();
		}
		else {
			A.DialogMask.hide();
		}

		return value;
	},

	_setStack: function(value) {
		var instance = this;

		if (value) {
			A.DialogManager.register(instance);
		}
		else {
			A.DialogManager.remove(instance);
		}

		return value;
	},

	/*
	* Attribute Listeners
	*/
	_afterSetVisible: function(event) {
		var instance = this;

		if (instance.get(MODAL)) {
			if (event.newVal) {
				A.DialogMask.show();
			}
			else {
				A.DialogMask.hide();
			}
		}
	}
};

A.Dialog = A.Base.build(DIALOG, A.Panel, [Dialog, A.WidgetPosition, A.WidgetStack, A.WidgetPositionExt]);

A.DialogManager = new A.OverlayManager(
	{
		zIndexBase: 1000
	}
);

A.mix(
	A.DialogManager,
	{
		findByChild: function(child) {
			return A.Widget.getByNode(child);
		},

		closeByChild: function(child) {
			return A.DialogManager.findByChild(child).close();
		},

		refreshByChild: function(child, io) {
			var dialog = A.DialogManager.findByChild(child);

			if (dialog && dialog.io) {
				dialog.io.start();
			}
		}
	}
);

A.DialogMask = new A.OverlayMask().render();

}, '@VERSION', { requires: [ 'aui-base', 'panel', 'overlay-manager', 'overlay-mask', 'dd-constrain', 'io-plugin', 'dialog-css' ] });<|endoftext|>


<commit_before>function createTests(newTest){
  newTest("This has a \nnewline", {width: 1});
  newTest("\tHi\nHI", {width: 1});
  newTest("A little test!", {format: "CODE128", width: 1});
  newTest("ABCDEFG", {format: "CODE39", width: 1, mod43: true});
  newTest("A little test", {format: "CODE39", width: 1});
  newTest("12345", {format: "EAN5", width: 1});
  newTest("52", {format: "EAN2", width: 1});
  newTest("423514346455", {format: "UPC", width: 2, textMargin: 0});
  newTest("5901234123457", {format: "EAN13", fontSize: 20, textMargin: 0, lastChar: ">"});
  newTest("590123412345", {format: "EAN13", width: 2, fontSize: 16});
  newTest("590123412345", {format: "EAN13", width: 3});
  newTest("96385074", {format: "EAN8", width: 1});
  newTest("9638507", {format: "EAN8", width: 1});
  newTest("98765432109213", {format: "ITF14", width: 1});
  newTest("12345", {format: "pharmacode", width: 1});
  newTest("133742", {format: "CODE128C", width: 1});
  newTest("12345674", {format: "MSI", width: 1});
  newTest("12345674", {format: "GenericBarcode", width: 1});
  newTest("Such customize!", {
    width: 1,
    height:	50,
    format:	"CODE128",
    displayValue: true,
    fontOptions: "bold",
    font: "cursive",
    textAlign: "right",
    textMargin: 20,
    fontSize: 28,
    background: "#f00",
    lineColor: "#0ff",
    margin: 10,
    marginTop: 60,
    marginBottom: 5,
    marginLeft: 60,
    marginRight: 30
  });
}
<commit_msg>Added a visual test for the text option<commit_after>function createTests(newTest){
  newTest("This has a \nnewline", {width: 1});
  newTest("\tHi\nHI", {width: 1});
  newTest("Not valid", {width: 1, text: "Valid"});
  newTest("A little test!", {format: "CODE128", width: 1});
  newTest("ABCDEFG", {format: "CODE39", width: 1, mod43: true});
  newTest("A little test", {format: "CODE39", width: 1});
  newTest("12345", {format: "EAN5", width: 1});
  newTest("52", {format: "EAN2", width: 1});
  newTest("423514346455", {format: "UPC", width: 2, textMargin: 0});
  newTest("5901234123457", {format: "EAN13", fontSize: 20, textMargin: 0, lastChar: ">"});
  newTest("590123412345", {format: "EAN13", width: 2, fontSize: 16});
  newTest("590123412345", {format: "EAN13", width: 3});
  newTest("96385074", {format: "EAN8", width: 1});
  newTest("9638507", {format: "EAN8", width: 1});
  newTest("98765432109213", {format: "ITF14", width: 1});
  newTest("12345", {format: "pharmacode", width: 1});
  newTest("133742", {format: "CODE128C", width: 1});
  newTest("12345674", {format: "MSI", width: 1});
  newTest("12345674", {format: "GenericBarcode", width: 1});
  newTest("Such customize!", {
    width: 1,
    height:	50,
    format:	"CODE128",
    displayValue: true,
    fontOptions: "bold",
    font: "cursive",
    textAlign: "right",
    textMargin: 20,
    fontSize: 28,
    background: "#f00",
    lineColor: "#0ff",
    margin: 10,
    marginTop: 60,
    marginBottom: 5,
    marginLeft: 60,
    marginRight: 30
  });
}
<|endoftext|>


<commit_before>

(function () {
    'use strict';

    var userData, taggle;
    var newUserData = {};
    var ITEM_PER_PAGE = 20;
    var keyword = 'All';
    var clipId = null;
    var pageNum = 0;
    var isCompleteLoading = false;
    var isLoading = false;
    var container = '#feed_list_panel';
    var $loaderCircle = $('#loaderCircle');
    var wookmark = undefined;
    var options = {
        offset: 12, // Optional, the distance between grid items
        itemWidth: 251 // Optional, the width of a grid item
    };

    var button = $('', {
        src: '/images/card_delete_icon.png',
        class: 'site-delete-btn'
    });

    function init() {
        userData = g_data.user;

        taggle = new Taggle('keyword-box', {
            tags: userData.keywords,
            placeholder: '태그 입력',
            duplicateTagClass: 'bounce'
        });

        $(".board").click(function(){
            $(".myclip_title").text($(this).data('title'));
            $('.myclip_title').attr('data-id');
            clearBoardList();
            clipId = $(this).data('id');
            $('#board_feed_list_container').removeClass('hide');
            initWookmark();
        });

        $('.board-setting-btn').click(function () {

            if ( $('.board_delete_btn').css('display') == 'none'){
                $(this).text("종료하기");
                $('.board_delete_btn').show();
            }
            else{
                $('.board_delete_btn').hide();
                $(this).text("보드관리");
            }
        });

        $(".myclip-bar-title-box").click(function(){
            location.reload(true);
        });

        $(".board_delete_btn").click(function(){
            var boardId = $(this).parent().parent().data('id');
            console.log(boardId);
            if(confirm("정말 삭제하시겠습니까?")){
                console.log("삭제됨");
                var params = {};
                HttpUtil.deleteData('/clip/delete/id/'+boardId, params, function(err, data) {
                    if(err != null){
                        alert(data);
                        return false;
                    }
                    location.reload(true);
                    return false;
                });
            }
            else{
                console.log("삭제되지않음");
                return false;
            }
        });

        $('#keyword_setting_btn').click(function() {
            $('#setting_modal').modal('show');
            initModal();
        });

        $('.sidebar-setting-icon').click(function() {
            $('#profile_modal').modal('show');
            initUserSettingModal();
        });

        if (userData.feeds.length === 0) {
            alert("등록된 사이트가 없습니다. 키워드 관리로 이동합니다.");
            $('#keyword_setting_btn').trigger('click');
        }
        if (userData.keywords.length === 0) {
            alert("등록된 키워드가 없습니다. 키워드 관리로 이동합니다.");
            $('#keyword_setting_btn').trigger('click');
        }
    }

    function initModalSiteItems() {
        $('.site_list').empty();
        $.unique($('.site_list'));
        for (var i=0; i<newUserData.feeds.length; i++) {
            $('.site_list').append('
' + newUserData.feeds[i] + '
');

        }
        $('.site_list > li').append(button);
    }

    function initModal() {
        $.extend(true, newUserData, userData);

        initModalSiteItems();

        $('#modal_add_btn').unbind('click').click(function() {
            HttpUtil.postData('/feed/check', {feed: $('#modal_input_site').val()}, function(err, result) {
                if (err) return alert('등록할 수 없는 사이트입니다.(RSS를 지원하는 사이트만 추가 가능합니다.)');
                alert("추가되었습니다.");
                newUserData.feeds.push(result);
                initModal();
                $('#modal_input_site').val('');
            });
        });

        $('.site-delete-btn').unbind('click').click(function() {
            var feedIndex = newUserData.feeds.indexOf($(this).parent().text());
            newUserData.feeds.splice(feedIndex, 1);
            $(this).parent().remove();
            console.log(newUserData.feeds);
            console.log('성공');
        });

        $('#modal_key_btn').unbind('click').click(function() {
            newUserData.keywords = taggle.getTagValues();
            HttpUtil.putData('/user/id/'+newUserData._id, {feeds: newUserData.feeds, keywords: newUserData.keywords},
                function(err, result) {
                if (err) return alert(err);
                alert("등록되었습니다.");
                location.reload(true);
            });
        });
    }

    //프로필 설정 모달
    function initUserSettingModal() {

        $('#logout_btn').click(function() {
            HttpUtil.postData('/user/logout', {}, function (err) {
                if (err || null) return alert('로그아웃 실패!');
                alert("로그아웃 되었습니다!");
                location.href = "/signin";
            });
        });

        $('#fileupload').fileupload({
            dataType: 'json',
            done: function (e, data) {
                var result = data.result;
                var image = result.data;
                $('.profile-image-box').attr('src', image);
                $('#fileupload').attr('value',image);
                console.log(image);
            }
        });

        $('#profile_name_input').val(userData.name);
        $(document).ready(function() {

            $("#profile_name_input").keyup(function(event){
                if (!(event.keyCode >=37 && event.keyCode<=40)) {
                    var inputVal = $(this).val();
                    $(this).val(inputVal.replace(/[^a-z0-9]/gi,''));
                }

            });
        });

        $('#change_pw_input').val(userData.pw);
        $('#change_pw_confirm').val(userData.pw);

        $('#modal_save_btn').click(function() {
            var minLength = 6;
            var $textarea = $('#change_pw_input');
            var userId = userData._id;
            var params = {
                name: $('#profile_name_input').val() ,
                pw : $('#change_pw_input').val(),
                profileUrl: $('#fileupload').attr('value')
            };
            var name = $('#profile_name_input').val();
            var passwordVal = $('#change_pw_input').val();
            var checkVal = $('#change_pw_confirm').val();
            var hasError = false;
            var image = $('#fileupload').val();
            //HttpUtil.putData('/upload/'+image, params, function (err) {
            //    if (err) return alert('사진 변경 실패');
            //});

            HttpUtil.putData('/user/id/'+userId, params, function (err) {
                if (err || null) return alert('저장 실패!');

                var blank_pattern = /[\s]/g;
                if( blank_pattern.test(name) == true){
                    alert(' 공백은 사용할 수 없습니다.');
                    return false;
                }

                if(name == "") return alert('이름을 입력해주세요.');

                if($textarea.val().length < minLength) {
                    alert('비밀번호를 6자 이상으로 입력해 주세요.');
                    return false;
                }

                if(checkVal.length < minLength) {
                    alert('비밀번호를 6자 이상으로 입력해 주세요.');
                    return false;
                }

                if (passwordVal != checkVal ) {
                    $("#change_pw_input").after(function() {
                        alert('비밀번호가 다릅니다.');
                        $("#change_pw_input").focus();
                        return false;
                    });
                    hasError = true;
                }
                else{
                    alert("저장되었습니다.");
                    location.href = "/user";
                    return true;
                }
            });
        });

    }

    function initWookmark() {
        /**
         * When scrolled all the way to the bottom, add more tiles.
         */
        function onScroll(event) {
            // Only check when we're not still waiting for data.
            if(!isLoading) {
                // Check if we're within 100 pixels of the bottom edge of the broser window.
                var closeToBottom = ($(window).scrollTop() + $(window).height() > $(document).height() - 100);
                if (closeToBottom) {
                    loadData();
                }
            }
        }
        /**
         * Refreshes the layout after all images have loaded
         */
        function applyLayout() {
            imagesLoaded(container, function () {
                if (wookmark === undefined) {
                    wookmark = new Wookmark(container, options);
                } else {
                    wookmark.initItems();
                    wookmark.layout(true);
                }
                $loaderCircle.hide();
            });

        }

        /**
         * Loads data from the API.
         */
        function loadData() {
            if (isCompleteLoading) return;
            var params = {
                pageNum: pageNum,
                perPage: ITEM_PER_PAGE
            };
            if (keyword !== 'All') {
                params.keyword = keyword;
            }
            if (clipId !== null) {
                params.clipId = clipId;
            }
            isLoading = true;
            $loaderCircle.show();

            HttpUtil.getData('/feed/user', params, function(err, data) {
                onLoadData(data);
                bindEvent();
            });
        }

        /**
         * Receives data from the API, creates HTML for images and updates the layout
         */
        function onLoadData(feedData) {
            isLoading = false;
            // Increment pageNum index for future calls.
            pageNum++;
            var length = feedData && feedData.length;
            var html = '';
            var i;

            if (!length) {
                isCompleteLoading = true;
                $loaderCircle.hide();
                return;
            }

            // Create HTML for the images.
            for(i=0; i<length; i++) {
                feedData[i].image = getFeedBoxImageSrc(feedData[i].description);
                html += getFeedBoxHtml(feedData[i]);
            }

            // Add image HTML to the pageNum.
            $(container).append(html);
            // Apply layout.
            applyLayout();
        }

        // Capture scroll event.
        $(document).unbind('scroll').bind('scroll', onScroll);
        // Load first data from the API.
        loadData();
    }

    function bindEvent() {
        $('#feed_list_panel > li > .clip-icon-circle').unbind('click').click(function() {
            var $feedItem = $(this).parent();
            var feed = { feed: $feedItem.data('id') };

            if ($(this).hasClass('on')) {
                $(this).removeClass('on');
                $('#sidebar_clip_list').find('li[data-id='+feed.id+']').remove();
            } else {
                $(this).addClass('on');
                feed.title = $feedItem.find('.title-txt').text();
                feed.src = $feedItem.find('.title-img').attr('src');
                $('#sidebar_clip_list').append(getSmallFeedBoxHtml(feed));
            }
            return false;
        });
    }

    function getFeedBoxImageSrc(description) {
        var defaultImageSrc = '/images/card_no_image.png';
        if (!description) return defaultImageSrc;
        return $(description).find('img').first().attr('src') || defaultImageSrc;
    }

    function getFeedBoxHtml(feed) {
        var html =
            '
'+
            ''+
            ''+
            ''+
            '
'+
            ''+
            '
'+
            '
'+
            '
'+feed.title+'
'+
            '
'+
            '
'+
            '
'+
            ''+
            ''+feed.keywordString+
            ''+
            '
'+
            '
';
        if (feed.isCliped) {
            html += '';
        }
        html += '
'+
            '
'+
            '
';
        return html;
    }

    function resetWookmark() {
        pageNum = 0;
        isCompleteLoading = false;
        isLoading = false;
        $(container).empty();
        initWookmark();
    }

    function clearBoardList() {
        $('.boards > .board').remove();
    }

    $(document).ready(function() {
        init();
    });
}());

<commit_msg>Update user<commit_after>

(function () {
    'use strict';

    var userData, taggle;
    var newUserData = {};
    var ITEM_PER_PAGE = 20;
    var keyword = 'All';
    var clipId = null;
    var pageNum = 0;
    var isCompleteLoading = false;
    var isLoading = false;
    var container = '#feed_list_panel';
    var $loaderCircle = $('#loaderCircle');
    var wookmark = undefined;
    var options = {
        offset: 12, // Optional, the distance between grid items
        itemWidth: 251 // Optional, the width of a grid item
    };

    var button = $('', {
        src: '/images/card_delete_icon.png',
        class: 'site-delete-btn'
    });

    function init() {
        userData = g_data.user;

        taggle = new Taggle('keyword-box', {
            tags: userData.keywords,
            placeholder: '태그 입력',
            duplicateTagClass: 'bounce'
        });

        $(".board").click(function(){
            $(".myclip_title").text($(this).data('title'));
            $('.myclip_title').attr('data-id');
            clearBoardList();
            clipId = $(this).data('id');
            $('#board_feed_list_container').removeClass('hide');
            initWookmark();
        });

        $('.board-setting-btn').click(function () {

            if ( $('.board_delete_btn').css('display') == 'none'){
                $(this).text("종료하기");
                $('.board_delete_btn').show();
            }
            else{
                $('.board_delete_btn').hide();
                $(this).text("보드관리");
            }
        });

        $(".myclip-bar-title-box").click(function(){
            location.reload(true);
        });

        $(".board_delete_btn").click(function(){
            var boardId = $(this).parent().parent().data('id');
            console.log(boardId);
            if(confirm("정말 삭제하시겠습니까?")){
                console.log("삭제됨");
                var params = {};
                HttpUtil.deleteData('/clip/delete/id/'+boardId, params, function(err, data) {
                    if(err != null){
                        alert(data);
                        return false;
                    }
                    location.reload(true);
                    return false;
                });
            }
            else{
                console.log("삭제되지않음");
                return false;
            }
        });

        $('#keyword_setting_btn').click(function() {
            $('#setting_modal').modal('show');
            initModal();
        });

        $('.sidebar-setting-icon').click(function() {
            $('#profile_modal').modal('show');
            initUserSettingModal();
        });

        if (userData.feeds.length === 0) {
            alert("등록된 사이트가 없습니다. 키워드 관리로 이동합니다.");
            $('#keyword_setting_btn').trigger('click');
        }
        if (userData.feeds.length > 0 && userData.keywords.length === 0) {
            alert("등록된 키워드가 없습니다. 키워드 관리로 이동합니다.");
            $('#keyword_setting_btn').trigger('click');
        }
    }

    function initModalSiteItems() {
        $('.site_list').empty();
        $.unique($('.site_list'));
        for (var i=0; i<newUserData.feeds.length; i++) {
            $('.site_list').append('
' + newUserData.feeds[i] + '
');

        }
        $('.site_list > li').append(button);
    }

    function initModal() {
        $.extend(true, newUserData, userData);

        initModalSiteItems();

        $('#modal_add_btn').unbind('click').click(function() {
            HttpUtil.postData('/feed/check', {feed: $('#modal_input_site').val()}, function(err, result) {
                if (err) return alert('등록할 수 없는 사이트입니다.(RSS를 지원하는 사이트만 추가 가능합니다.)');
                alert("추가되었습니다.");
                newUserData.feeds.push(result);
                initModal();
                $('#modal_input_site').val('');
            });
        });

        $('.site-delete-btn').unbind('click').click(function() {
            var feedIndex = newUserData.feeds.indexOf($(this).parent().text());
            newUserData.feeds.splice(feedIndex, 1);
            $(this).parent().remove();
            console.log(newUserData.feeds);
            console.log('성공');
        });

        $('#modal_key_btn').unbind('click').click(function() {
            newUserData.keywords = taggle.getTagValues();
            HttpUtil.putData('/user/id/'+newUserData._id, {feeds: newUserData.feeds, keywords: newUserData.keywords},
                function(err, result) {
                if (err) return alert(err);
                alert("등록되었습니다.");
                location.reload(true);
            });
        });
    }

    //프로필 설정 모달
    function initUserSettingModal() {

        $('#logout_btn').click(function() {
            HttpUtil.postData('/user/logout', {}, function (err) {
                if (err || null) return alert('로그아웃 실패!');
                alert("로그아웃 되었습니다!");
                location.href = "/signin";
            });
        });

        $('#fileupload').fileupload({
            dataType: 'json',
            done: function (e, data) {
                var result = data.result;
                var image = result.data;
                $('.profile-image-box').attr('src', image);
                $('#fileupload').attr('value',image);
                console.log(image);
            }
        });

        $('#profile_name_input').val(userData.name);
        $(document).ready(function() {

            $("#profile_name_input").keyup(function(event){
                if (!(event.keyCode >=37 && event.keyCode<=40)) {
                    var inputVal = $(this).val();
                    $(this).val(inputVal.replace(/[^a-z0-9]/gi,''));
                }

            });
        });

        $('#change_pw_input').val(userData.pw);
        $('#change_pw_confirm').val(userData.pw);

        $('#modal_save_btn').click(function() {
            var minLength = 6;
            var $textarea = $('#change_pw_input');
            var userId = userData._id;
            var params = {
                name: $('#profile_name_input').val() ,
                pw : $('#change_pw_input').val(),
                profileUrl: $('#fileupload').attr('value')
            };
            var name = $('#profile_name_input').val();
            var passwordVal = $('#change_pw_input').val();
            var checkVal = $('#change_pw_confirm').val();
            var hasError = false;
            var image = $('#fileupload').val();
            //HttpUtil.putData('/upload/'+image, params, function (err) {
            //    if (err) return alert('사진 변경 실패');
            //});

            HttpUtil.putData('/user/id/'+userId, params, function (err) {
                if (err || null) return alert('저장 실패!');

                var blank_pattern = /[\s]/g;
                if( blank_pattern.test(name) == true){
                    alert(' 공백은 사용할 수 없습니다.');
                    return false;
                }

                if(name == "") return alert('이름을 입력해주세요.');

                if($textarea.val().length < minLength) {
                    alert('비밀번호를 6자 이상으로 입력해 주세요.');
                    return false;
                }

                if(checkVal.length < minLength) {
                    alert('비밀번호를 6자 이상으로 입력해 주세요.');
                    return false;
                }

                if (passwordVal != checkVal ) {
                    $("#change_pw_input").after(function() {
                        alert('비밀번호가 다릅니다.');
                        $("#change_pw_input").focus();
                        return false;
                    });
                    hasError = true;
                }
                else{
                    alert("저장되었습니다.");
                    location.href = "/user";
                    return true;
                }
            });
        });

    }

    function initWookmark() {
        /**
         * When scrolled all the way to the bottom, add more tiles.
         */
        function onScroll(event) {
            // Only check when we're not still waiting for data.
            if(!isLoading) {
                // Check if we're within 100 pixels of the bottom edge of the broser window.
                var closeToBottom = ($(window).scrollTop() + $(window).height() > $(document).height() - 100);
                if (closeToBottom) {
                    loadData();
                }
            }
        }
        /**
         * Refreshes the layout after all images have loaded
         */
        function applyLayout() {
            imagesLoaded(container, function () {
                if (wookmark === undefined) {
                    wookmark = new Wookmark(container, options);
                } else {
                    wookmark.initItems();
                    wookmark.layout(true);
                }
                $loaderCircle.hide();
            });

        }

        /**
         * Loads data from the API.
         */
        function loadData() {
            if (isCompleteLoading) return;
            var params = {
                pageNum: pageNum,
                perPage: ITEM_PER_PAGE
            };
            if (keyword !== 'All') {
                params.keyword = keyword;
            }
            if (clipId !== null) {
                params.clipId = clipId;
            }
            isLoading = true;
            $loaderCircle.show();

            HttpUtil.getData('/feed/user', params, function(err, data) {
                onLoadData(data);
                bindEvent();
            });
        }

        /**
         * Receives data from the API, creates HTML for images and updates the layout
         */
        function onLoadData(feedData) {
            isLoading = false;
            // Increment pageNum index for future calls.
            pageNum++;
            var length = feedData && feedData.length;
            var html = '';
            var i;

            if (!length) {
                isCompleteLoading = true;
                $loaderCircle.hide();
                return;
            }

            // Create HTML for the images.
            for(i=0; i<length; i++) {
                feedData[i].image = getFeedBoxImageSrc(feedData[i].description);
                html += getFeedBoxHtml(feedData[i]);
            }

            // Add image HTML to the pageNum.
            $(container).append(html);
            // Apply layout.
            applyLayout();
        }

        // Capture scroll event.
        $(document).unbind('scroll').bind('scroll', onScroll);
        // Load first data from the API.
        loadData();
    }

    function bindEvent() {
        $('#feed_list_panel > li > .clip-icon-circle').unbind('click').click(function() {
            var $feedItem = $(this).parent();
            var feed = { feed: $feedItem.data('id') };

            if ($(this).hasClass('on')) {
                $(this).removeClass('on');
                $('#sidebar_clip_list').find('li[data-id='+feed.id+']').remove();
            } else {
                $(this).addClass('on');
                feed.title = $feedItem.find('.title-txt').text();
                feed.src = $feedItem.find('.title-img').attr('src');
                $('#sidebar_clip_list').append(getSmallFeedBoxHtml(feed));
            }
            return false;
        });
    }

    function getFeedBoxImageSrc(description) {
        var defaultImageSrc = '/images/card_no_image.png';
        if (!description) return defaultImageSrc;
        return $(description).find('img').first().attr('src') || defaultImageSrc;
    }

    function getFeedBoxHtml(feed) {
        var html =
            '
'+
            ''+
            ''+
            ''+
            '
'+
            ''+
            '
'+
            '
'+
            '
'+feed.title+'
'+
            '
'+
            '
'+
            '
'+
            ''+
            ''+feed.keywordString+
            ''+
            '
'+
            '
';
        if (feed.isCliped) {
            html += '';
        }
        html += '
'+
            '
'+
            '
';
        return html;
    }

    function resetWookmark() {
        pageNum = 0;
        isCompleteLoading = false;
        isLoading = false;
        $(container).empty();
        initWookmark();
    }

    function clearBoardList() {
        $('.boards > .board').remove();
    }

    $(document).ready(function() {
        init();
    });
}());

<|endoftext|>


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

    $.fn.textEditor =
    	function ()
    	{
    		var self = this;

    	};

    $.fn.singleLineEditor =
    	function (commit_cb)
    	{
    		var self = this;

    		self.attr("contenteditable", "true");
            self.keydown(
                function (event)
                {
					if (event.which == 13)
					{
						if (commit_cb)
							commit_cb(this);
						event.preventDefault();
					}
					else
						self.addClass("urgent");
                }
            );
            return self;
       	};

    $.fn.textWithBreaks =
    	function (newtext)
    	{
    		if (newtext)
    		{
    			/* Set */

    			this.empty();
            	var paras = newtext.split("\n");
            	for (var i = 0; i < paras.length; i++)
            		this.append($("<p/>").text(paras[i]));
    		}
    		else
    		{
    			/* Get */

        		var st = [];

        		var c = this.children();
        		if (c.length == 0)
        			return this.text();

        		c.each(
        			function(i, e)
        			{
        				var s = $(e).text().trim();
        				if (s !== "")
        					st.push(s);
        			}
        		);

        		return st.join("\n");
    		}
    	};

	String.prototype.hashCode = function()
	{
	    var hash = 0, i, char;
	    if (this.length == 0)
	    	return hash;
	    for (i = 0; i < this.length; i++)
	    {
	        char = this.charCodeAt(i);
	        hash = ((hash<<5)-hash)+char;
	        hash = hash & hash; // Convert to 32bit integer
	    }
	    return (hash & 0x7fffffff);
	};
}
)();
<commit_msg>More robust paragraph detection in text entry boxes.<commit_after>(function()
{
    "use strict";

    $.fn.textEditor =
    	function ()
    	{
    		var self = this;

    	};

    $.fn.singleLineEditor =
    	function (commit_cb)
    	{
    		var self = this;

    		self.attr("contenteditable", "true");
            self.keydown(
                function (event)
                {
					if (event.which == 13)
					{
						if (commit_cb)
							commit_cb(this);
						event.preventDefault();
					}
					else
						self.addClass("urgent");
                }
            );
            return self;
       	};

    $.fn.textWithBreaks =
    	function (newtext)
    	{
    		if (newtext)
    		{
    			/* Set */

    			this.empty();
            	var paras = newtext.split("\n");
            	for (var i = 0; i < paras.length; i++)
            		this.append($("<p/>").text(paras[i]));
    		}
    		else
    		{
    			/* Get */

        		var st = [];

			var append = function()
			{
				switch (this.nodeType)
				{
					case Node.ELEMENT_NODE:
						$(this).contents().each(append);
						st.push("\n");
						break;

					default:
						st.push($(this).text());
						break;
				}
			};

			this.contents().each(append);
			var s = st.join("").replace(/\n+/, "\n");
			return s;
    		}
    	};

	String.prototype.hashCode = function()
	{
	    var hash = 0, i, char;
	    if (this.length == 0)
	    	return hash;
	    for (i = 0; i < this.length; i++)
	    {
	        char = this.charCodeAt(i);
	        hash = ((hash<<5)-hash)+char;
	        hash = hash & hash; // Convert to 32bit integer
	    }
	    return (hash & 0x7fffffff);
	};
}
)();
<|endoftext|>


<commit_before>var webpack = require("webpack");
module.exports = {
    watchDelay: 500,
    output: {
        filename: "[name].js",
        sourceMapFilename: 'map/[file].map'
    },
    devtool: '#source-map',
    resolve: {
        modulesDirectories: ["bower_components","node_modules"],
        alias: {
            bower: 'bower_components'
        }
    },
    module: {
        preLoaders: [
            {
                test: /\.js$/,
                exclude: /(node_modules|bower_component)/,
                loader: "jshint-loader"
            }
        ],
        loaders: [
            { test: /\.html$/, loader: 'html-loader' },
            //{ test: /angular\.js$/, loader: 'exports?angular' },
        ]
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin('common','common.js'),
        new webpack.ResolverPlugin(
            new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
        ),
        new webpack.optimize.AggressiveMergingPlugin(),
        new webpack.optimize.DedupePlugin(),
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            _: 'lodash'
        })
    ]
};<commit_msg>非同期読み込みしたときにパスが切れてしまうためpublicPathの設定を追加<commit_after>var webpack = require("webpack");
module.exports = {
    watchDelay: 500,
    output: {
        filename: "[name].js",
        sourceMapFilename: 'map/[file].map',
        publicPath: "/js/"
    },
    devtool: '#source-map',
    resolve: {
        modulesDirectories: ["bower_components","node_modules"],
        alias: {
            bower: 'bower_components'
        }
    },
    module: {
        preLoaders: [
            {
                test: /\.js$/,
                exclude: /(node_modules|bower_component)/,
                loader: "jshint-loader"
            }
        ],
        loaders: [
            { test: /\.html$/, loader: 'html-loader' },
            //{ test: /angular\.js$/, loader: 'exports?angular' },
        ]
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin('common','common.js'),
        new webpack.ResolverPlugin(
            new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
        ),
        new webpack.optimize.AggressiveMergingPlugin(),
        new webpack.optimize.DedupePlugin(),
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            _: 'lodash'
        })
    ]
};<|endoftext|>


<commit_before><commit_msg>Skip double init of gateway subdevices<commit_after><|endoftext|>


<commit_before>const { isPrime } = require("../lib");

describe("isPrime", () => {
  test("7 is prime", () => {
    expect(isPrime(7)).toBe(true);
  });

  test("1 is not prime", () => {
    expect(isPrime(1)).toBe(false);
  });

  test("49 is not prime", () => {
    expect(isPrime(49)).toBe(false);
  });

  test("95279 is prime", () => {
    expect(isPrime(95279)).toBe(true);
  });
});
<commit_msg>Implements new test cases for isPrime (#347)<commit_after>const { isPrime } = require("../lib");

describe("isPrime", () => {
  test("7 is prime", () => {
    expect(isPrime(7)).toBe(true);
  });

  test("1 is not prime", () => {
    expect(isPrime(1)).toBe(false);
  });

  test("49 is not prime", () => {
    expect(isPrime(49)).toBe(false);
  });

  test("95279 is prime", () => {
    expect(isPrime(95279)).toBe(true);
  });

  test("2 is prime", () => {
    expect(isPrime(2)).toBe(true);
  });

  test("0 is not prime", () => {
    expect(isPrime(0)).toBe(false);
  });
});
<|endoftext|>


<commit_before>'use strict';

//git repository
//https://github.com/champnakub/CameraApp.git

// Declare app level module which depends on views, and components
var App = angular.module('myApp', [
    'ngRoute',

    'myApp.version',
    //VIEW SECTION
    'myApp.ItemView',
    'myApp.LoginView',
    'myApp.CameraView',
    'myApp.WSTestView',

    //ANGULAR LIBRARY SECTION
    'angular-carousel',
    'angular-websql',
    'cfp.loadingBar'
]);

//constant for underscore.js
App.factory('_', ['$window', function($window) {
  return $window._; // assumes underscore has already been loaded on the page
}]);

//constant for webservice
App.constant('WebService', {
   url : 'http://beau888.dyndns.org:222/DataService/'
});

//controller
App.controller('MainController', ['$scope', '$webSql', function ($scope, $webSql) {

        console.log('-----------------------WELCOME TO CHAMP WORLD-----------------------');
        console.log('-----------------------APP INSTANTIATED-----------------------');

        //instantiate web database
        //@param1 = Database Name
        //@param2 = Version Number
        //@param3 = Text Description
        //@param4 = Size of Database
        $scope.db = $webSql.openDatabase('CameraApp', '1.0', 'CameraApp DB', 2 * 1024 * 1024);
    }]);

//routing modules
App.config(['$routeProvider', function ($routeProvider) {
        $routeProvider.
                when('/cameraView', {
                    templateUrl: 'camera_components/camera.html',
                    controller: 'CameraCtrl'
                }).

                when('/loginView', {
                    templateUrl: 'login_components/login.html',
                    controller: 'LoginCtrl'
                }).

                when('/itemView', {
                    templateUrl: 'item_components/item.html',
                    controller: 'ItemCtrl'
                }).

                when('/wsTestView', {
                    templateUrl: 'webservice_components/ws.html',
                    controller: 'WSCtrl'
                }).

                otherwise({redirectTo: '/wsTestView'});
    }]);

<commit_msg>Update 11/28/2015<commit_after>'use strict';

//git repository
//https://github.com/champnakub/CameraApp.git

// Declare app level module which depends on views, and components
var App = angular.module('myApp', [
    'ngRoute',
    'myApp.version',
    //VIEW SECTION
    'myApp.ItemView',
    'myApp.LoginView',
    'myApp.CameraView',
    'myApp.WSTestView',
    //ANGULAR LIBRARY SECTION
    'angular-carousel',
    'angular-websql',
    'cfp.loadingBar'
]);

//constant for underscore.js
App.factory('_', ['$window', function ($window) {
        return $window._; // assumes underscore has already been loaded on the page
    }]);

//constant for webservice
App.constant('WebService', {
    url: 'http://beau888.dyndns.org:222/DataService/'
});

//controller
App.controller('MainController', ['$scope', '$webSql', function ($scope, $webSql) {

        console.log('-----------------------WELCOME TO CHAMP WORLD-----------------------');
        console.log('-----------------------APP INSTANTIATED-----------------------');

        //instantiate web database
        //@param1 = Database Name
        //@param2 = Version Number
        //@param3 = Text Description
        //@param4 = Size of Database
        $scope.db = $webSql.openDatabase('CameraApp', '1.0', 'CameraApp DB', 2 * 1024 * 1024);

        //create table [* CUSTOMER]
        //@ method [GetCustomerData()]
        $scope.db.createTable('CUSTOMER', {
            "ID": {
                "type": "INTEGER",
                "null": "NOT NULL", // default is "NULL" (if not defined)
                "primary": true, // primary
                "auto_increment": true // auto increment
            },
            "Code": {
                "type": "TEXT",
                "null": "NOT NULL"
            },
            "Description": {
                "type": "TEXT",
                "null": "NOT NULL"
            }
        });

        //create table [* Project]
        //@ method [getProjectData()]
        $scope.db.createTable('Project', {
            "ID": {
                "type": "INTEGER",
                "null": "NOT NULL", // default is "NULL" (if not defined)
                "primary": true, // primary
                "auto_increment": true // auto increment
            },
            "Customer": {
                "type": "TEXT",
                "null": "NOT NULL"
            },
            "Code": {
                "type": "TEXT",
                "null": "NOT NULL"
            },
            "Description": {
                "type": "TEXT",
                "null": "NOT NULL"
            }
        });

        //create table [* Building]
        //@ method [getBuildingData()]
        $scope.db.createTable('Building', {
            "ID": {
                "type": "INTEGER",
                "null": "NOT NULL", // default is "NULL" (if not defined)
                "primary": true, // primary
                "auto_increment": true // auto increment
            },
            "Code": {
                "type": "TEXT",
                "null": "NOT NULL"
            },
            "Project": {
                "type": "TEXT",
                "null": "NOT NULL"
            },
            "Description": {
                "type": "TEXT",
                "null": "NOT NULL"
            }
        });
    }]);

//routing modules
App.config(['$routeProvider', function ($routeProvider) {
        $routeProvider.
                when('/cameraView', {
                    templateUrl: 'camera_components/camera.html',
                    controller: 'CameraCtrl'
                }).
                when('/loginView', {
                    templateUrl: 'login_components/login.html',
                    controller: 'LoginCtrl'
                }).
                when('/itemView', {
                    templateUrl: 'item_components/item.html',
                    controller: 'ItemCtrl'
                }).
                when('/wsTestView', {
                    templateUrl: 'webservice_components/ws.html',
                    controller: 'WSCtrl'
                }).
                otherwise({redirectTo: '/wsTestView'});
    }]);

<|endoftext|>


<commit_before>'use strict';

var util = require('util');
var _ = require('lodash');
var uuid = require('node-uuid');
var dbman = require('../../dbman');
var emailer = require('../../emailer');
var geocoder = require('../../geocoder');
var debug = require('../../debug');

var log = debug.getLogger({ prefix: '[route.volunteer]-  '});
var users = dbman.getCollection('users');

function updateUserDocument(req, res, id, callback) {
    var data = req.body;

    var geoQuery = util.format('%s %s, %s %s',
        data.address, data.city, data.state, data.zip);

    geocoder.send(geoQuery, function (response) {
        var result = response.results[0];
        data.team = uuid.v4();
        data.location = result.geometry.location;
        data.formattedAddress = result.formatted_address;

        var query = { _id: id };
        var cmd = {
            $set: {
                role: 'volunteer',
                volunteer: data
            }
        };
        var opt = { w: 1, new: true };

        users.findAndModify(query, null, cmd, opt, function (err, updated) {
            if (err || !updated) {
                log('POST: Error updating user document:\n\n%s\n\n', err);
                callback(err);
            } else {
                log('POST: Successfully updated user document');
                log('POST: Updating user session');
                callback(null, updated);
            }
        });
    });
}

module.exports = {

    get: function (req, res) {
        if (req.session.user.volunteer) {
            var path = '/volunteer/account';
            log('GET: Volunteer session detected, redirecting to: %s', path);
            res.redirect(path);
        } else {
            res.render('volunteer', {
                title: 'Volunteer Registration'
            });
        }
    },

    post: function (req, res) {
        var userId = req.session.user._id;
        updateUserDocument(req, res, userId, function (err, doc) {
            if (err) {
                res.send(400);
            } else {
                emailer.send({
                    to: doc.email,
                    subject: 'Volunteer Account Registration',
                    template: 'volunteer',
                    locals: {
                        user: doc,
                        volunteer: doc.volunteer
                    }
                });
                _.merge(req.session.user, doc);
                res.send(200, 'ok');
            }
        });
    },

    success: function (req, res) {
        res.render('hero-unit', {
            title: 'Successful Registration',
            header: 'Thanks!',
            message: 'You should receive an e-mail confirming your registration was successful. Thank you for volunteering to serve your Auburn community through Big Event.'
        });
    },

    failure: function (req, res) {
        res.render('hero-unit', {
            title: 'Registration Failed',
            header: 'Sorry!',
            message: 'There was a problem with the registration. Please try again later.'
        });
    },

    account: {
        get: function (req, res) {

            res.render('volunteer-account', {
                title: 'Volunteer Control Panel',
                user: req.session.user,
                volunteer: req.session.user.volunteer
            });
        },

        post: function (req, res) {
            var userId = req.session.user._id;
            updateUserDocument(req, res, userId, function (err, doc) {
                if (err) {
                    res.send(400);
                } else {
                    emailer.send({
                        to: doc.email,
                        subject: 'Volunteer Account Update',
                        template: 'volunteer-account',
                        locals: {
                            user: doc,
                            volunteer: doc.volunteer
                        }
                    });
                    _.merge(req.session.user, doc);
                    res.send(200, 'ok');
                }
            });
        },

        success: function (req, res) {
            res.render('hero-unit', {
                title: 'Successfully Updated',
                header: 'Thanks!',
                message: 'You have successfully updated your data. You should receive an e-mail confirmation as well. Thank you for volunteering to serve your Auburn community through Big Event.'
            });
        },

        failure: function (req, res) {
            res.render('hero-unit', {
                title: 'Registration Failed',
                header: 'Sorry!',
                message: 'There was a problem updating your data. Please try again later.'
            });
        },

        delete: function (req, res) {
            var query = { _id: req.session.user._id };
            var cmd = {
                $unset: {
                    volunteer: ''
                },
                $set: {
                    role: 'user'
                }
            };
            var opt = { w: 1 };

            users.update(query, cmd, opt, function (err, result) {
                if (err || !result) {
                    res.render('hero-unit', {
                        title: 'Volunteer Account Removal Failed',
                        header: 'Sorry!',
                        message: 'There was a problem removing your account data at this time. Please try again later.'
                    });
                } else {
                    res.render('hero-unit', {
                        title: 'Volunteer Account Removed',
                        header: 'Volunteer Account Removed',
                        message: 'Your volunteer account data was successfully deleted and you are no longer registered to volunteer on the day of the event. Thank you for your interest in Big Event and in serving your Auburn community. You can register again '
                    });
                    req.session.role = 'user';
                    delete req.session.user.volunteer;
                }
            });
        },

        staff: {
            get: function (req, res) {
                users.findOne({_id: req.params.id}, function(err, record) {
                    if(err || !record) {
                        log('STAFF.GET: Record not found for id %s', req.params.id);
                        res.render('hero-unit', {
                            title: 'Volunteer Not Found',
                            header: 'Volunteer Not Found',
                            message: 'No volunteer with id ' + req.params.id + ' could be found in the database.'
                        });
                    } else {
                        log('STAFF.GET: Record found');
                        res.render('volunteer-account', {
                            title: 'Volunteer Account',
                            user: record,
                            volunteer: record.volunteer
                        });
                    }
                });
            },

            post: function (req, res) {
                var userId = req.params.id;
                updateUserDocument(req, res, userId, function (err, doc) {
                    if (err) {
                        res.send(400);
                    } else {
                        emailer.send({
                            to: doc.email,
                            subject: 'Volunteer Account Update',
                            template: 'volunteer-account',
                            locals: {
                                user: doc,
                                volunteer: doc.volunteer
                            }
                        });
                        res.send(200, 'staff');
                    }
                });
            },

            delete: function (req, res) {
                res.send(200);
            },
        }
    }
};
<commit_msg>Fixed the route that deletes an entry on the staff side.<commit_after>'use strict';

var util = require('util');
var _ = require('lodash');
var uuid = require('node-uuid');
var dbman = require('../../dbman');
var emailer = require('../../emailer');
var geocoder = require('../../geocoder');
var debug = require('../../debug');

var log = debug.getLogger({ prefix: '[route.volunteer]-  '});
var users = dbman.getCollection('users');

function updateUserDocument(req, res, id, callback) {
    var data = req.body;

    var geoQuery = util.format('%s %s, %s %s',
        data.address, data.city, data.state, data.zip);

    geocoder.send(geoQuery, function (response) {
        var result = response.results[0];
        data.team = uuid.v4();
        data.location = result.geometry.location;
        data.formattedAddress = result.formatted_address;

        var query = { _id: id };
        var cmd = {
            $set: {
                role: 'volunteer',
                volunteer: data
            }
        };
        var opt = { w: 1, new: true };

        users.findAndModify(query, null, cmd, opt, function (err, updated) {
            if (err || !updated) {
                log('POST: Error updating user document:\n\n%s\n\n', err);
                callback(err);
            } else {
                log('POST: Successfully updated user document');
                log('POST: Updating user session');
                callback(null, updated);
            }
        });
    });
}

module.exports = {

    get: function (req, res) {
        if (req.session.user.volunteer) {
            var path = '/volunteer/account';
            log('GET: Volunteer session detected, redirecting to: %s', path);
            res.redirect(path);
        } else {
            res.render('volunteer', {
                title: 'Volunteer Registration'
            });
        }
    },

    post: function (req, res) {
        var userId = req.session.user._id;
        updateUserDocument(req, res, userId, function (err, doc) {
            if (err) {
                res.send(400);
            } else {
                emailer.send({
                    to: doc.email,
                    subject: 'Volunteer Account Registration',
                    template: 'volunteer',
                    locals: {
                        user: doc,
                        volunteer: doc.volunteer
                    }
                });
                _.merge(req.session.user, doc);
                res.send(200, 'ok');
            }
        });
    },

    success: function (req, res) {
        res.render('hero-unit', {
            title: 'Successful Registration',
            header: 'Thanks!',
            message: 'You should receive an e-mail confirming your registration was successful. Thank you for volunteering to serve your Auburn community through Big Event.'
        });
    },

    failure: function (req, res) {
        res.render('hero-unit', {
            title: 'Registration Failed',
            header: 'Sorry!',
            message: 'There was a problem with the registration. Please try again later.'
        });
    },

    account: {
        get: function (req, res) {

            res.render('volunteer-account', {
                title: 'Volunteer Control Panel',
                user: req.session.user,
                volunteer: req.session.user.volunteer
            });
        },

        post: function (req, res) {
            var userId = req.session.user._id;
            updateUserDocument(req, res, userId, function (err, doc) {
                if (err) {
                    res.send(400);
                } else {
                    emailer.send({
                        to: doc.email,
                        subject: 'Volunteer Account Update',
                        template: 'volunteer-account',
                        locals: {
                            user: doc,
                            volunteer: doc.volunteer
                        }
                    });
                    _.merge(req.session.user, doc);
                    res.send(200, 'ok');
                }
            });
        },

        success: function (req, res) {
            res.render('hero-unit', {
                title: 'Successfully Updated',
                header: 'Thanks!',
                message: 'You have successfully updated your data. You should receive an e-mail confirmation as well. Thank you for volunteering to serve your Auburn community through Big Event.'
            });
        },

        failure: function (req, res) {
            res.render('hero-unit', {
                title: 'Registration Failed',
                header: 'Sorry!',
                message: 'There was a problem updating your data. Please try again later.'
            });
        },

        delete: function (req, res) {
            var query = { _id: req.session.user._id };
            var cmd = {
                $unset: {
                    volunteer: ''
                },
                $set: {
                    role: 'user'
                }
            };
            var opt = { w: 1 };

            users.update(query, cmd, opt, function (err, result) {
                if (err || !result) {
                    res.render('hero-unit', {
                        title: 'Volunteer Account Removal Failed',
                        header: 'Sorry!',
                        message: 'There was a problem removing your account data at this time. Please try again later.'
                    });
                } else {
                    res.render('hero-unit', {
                        title: 'Volunteer Account Removed',
                        header: 'Volunteer Account Removed',
                        message: 'Your volunteer account data was successfully deleted and you are no longer registered to volunteer on the day of the event. Thank you for your interest in Big Event and in serving your Auburn community. You can register again '
                    });
                    req.session.role = 'user';
                    delete req.session.user.volunteer;
                }
            });
        },

        staff: {
            get: function (req, res) {
                users.findOne({_id: req.params.id}, function(err, record) {
                    if(err || !record) {
                        log('STAFF.GET: Record not found for id %s', req.params.id);
                        res.render('hero-unit', {
                            title: 'Volunteer Not Found',
                            header: 'Volunteer Not Found',
                            message: 'No volunteer with id ' + req.params.id + ' could be found in the database.'
                        });
                    } else {
                        log('STAFF.GET: Record found');
                        res.render('volunteer-account', {
                            title: 'Volunteer Account',
                            user: record,
                            volunteer: record.volunteer
                        });
                    }
                });
            },

            post: function (req, res) {
                var userId = req.params.id;
                updateUserDocument(req, res, userId, function (err, doc) {
                    if (err) {
                        res.send(400);
                    } else {
                        emailer.send({
                            to: doc.email,
                            subject: 'Volunteer Account Update',
                            template: 'volunteer-account',
                            locals: {
                                user: doc,
                                volunteer: doc.volunteer
                            }
                        });
                        res.send(200, 'staff');
                    }
                });
            },

            delete: function (req, res) {
                var query = { _id: req.params.id };
                var cmd = {
                    $unset: {
                        volunteer: ''
                    },
                    $set: {
                        role: 'user'
                    }
                };
                var opt = { w: 1 };

                users.update(query, cmd, opt, function (err, result) {
                    if (err || !result) {
                        res.render('hero-unit', {
                            title: 'Volunteer Account Removal Failed',
                            header: 'Sorry!',
                            message: 'There was a problem removing the account data at this time. Please try again later.'
                        });
                    } else {
                        res.redirect('/staff/staffHomePage');
                    }
                });
            },
        }
    }
};
<|endoftext|>