<commit_before>var test = require('tape');
var ViewSwitcher = require('../ampersand-view-switcher');
var View = require('ampersand-view');

var makeTestView = function(options) {
    options = options || {};
    return View.extend({
        template: '

',
        autoRender: true,
        render: function () {
            this.renderWithTemplate();
            this.switcher = new ViewSwitcher(this.queryByHook('container'), options);
        }
    });
};

var ItemView = View.extend({
    template: 'hey',
    autoRender: true
});

var SelfInsertingView = View.extend({
    insertSelf: true,
    render: function () {}
});

test('basics', function (t) {
    var Base = makeTestView();
    var base = new Base();
    var c1 = new ItemView();
    var c2 = new ItemView();
    t.ok(base.el);
    base.switcher.set(c1);
    t.equal(base.el.firstChild, c1.el);
    base.switcher.set(c2);
    t.equal(base.el.firstChild, c2.el);
    t.end();
});

test('calls `empty` when appropriate', function (t) {
    var count = 0;
    var NewView = makeTestView({
        empty: function () { count++; }
    });
    var c1 = new ItemView();
    var c2 = new ItemView();
    var base = new NewView();
    t.equal(count, 1, 'should be called at first');
    base.switcher.set(c1);
    base.switcher.clear();
    t.equal(count, 2, 'should be called when clear is called');
    base.switcher.set(c2);
    c2.remove();
    t.equal(count, 3, 'should be called when view is removed');
    t.end();
});

test('self inserting views can be set without throwing exceptions', function (t) {
    var Base = makeTestView();
    var base = new Base();
    var v1 = new SelfInsertingView();
    base.render();
    t.doesNotThrow(function() {
        base.switcher.set(v1);
    });
    t.end();
});

test('`options.hide', function(t) {
    t.plan(3);
    var TestView = makeTestView({
        hide: function(oldView) {
            t.equal(oldView, c1, 'first param should be previous view');
        }
    });
    var base = new TestView();
    var c1 = new ItemView();
    var c2 = new ItemView();
    base.switcher.set(c1);
    base.switcher.set(c2);
    t.equal(c1.el.parentNode, null, 'the previous view was removed');
    t.equal(base.el.firstChild, c2.el, 'the current view was set');
});

test('`option.hide` with `waitForRemove`', function(t) {
    t.plan(4);
    var TestView = makeTestView({
        waitForRemove: true,
        hide: function(oldView, cb) {
            t.equal(oldView, c1, 'first param should be previous view');
            t.ok(typeof cb === 'function', 'second param is callback');
            cb();
        }
    });
    var base = new TestView();
    var c1 = new ItemView();
    var c2 = new ItemView();
    base.switcher.set(c1);
    base.switcher.set(c2);
    t.equal(c1.el.parentNode, null, 'the previous view was removed');
    t.equal(base.el.firstChild, c2.el, 'the current view was set');
});
<commit_msg>Better tests coverage for show/hide methods<commit_after>var test = require('tape');
var ViewSwitcher = require('../ampersand-view-switcher');
var View = require('ampersand-view');

var makeTestView = function(options) {
    options = options || {};
    return View.extend({
        template: '

',
        autoRender: true,
        render: function () {
            this.renderWithTemplate();
            this.switcher = new ViewSwitcher(this.queryByHook('container'), options);
        }
    });
};

var ItemView = View.extend({
    template: 'hey',
    autoRender: true
});

var SelfInsertingView = View.extend({
    insertSelf: true,
    render: function () {}
});

test('basics', function (t) {
    var Base = makeTestView();
    var base = new Base();
    var c1 = new ItemView();
    var c2 = new ItemView();
    t.ok(base.el);
    base.switcher.set(c1);
    t.equal(base.el.firstChild, c1.el);
    base.switcher.set(c2);
    t.equal(base.el.firstChild, c2.el);
    t.end();
});

test('calls `empty` when appropriate', function (t) {
    var count = 0;
    var NewView = makeTestView({
        empty: function () { count++; }
    });
    var c1 = new ItemView();
    var c2 = new ItemView();
    var base = new NewView();
    t.equal(count, 1, 'should be called at first');
    base.switcher.set(c1);
    base.switcher.clear();
    t.equal(count, 2, 'should be called when clear is called');
    base.switcher.set(c2);
    c2.remove();
    t.equal(count, 3, 'should be called when view is removed');
    t.end();
});

test('self inserting views can be set without throwing exceptions', function (t) {
    var Base = makeTestView();
    var base = new Base();
    var v1 = new SelfInsertingView();
    base.render();
    t.doesNotThrow(function() {
        base.switcher.set(v1);
    });
    t.end();
});

test('`options.show`', function (t) {
    var TestView = makeTestView({
        show: function (newView) {
            t.equal(newView, c1, 'first param should be new view');
        }
    });
    var base = new TestView();
    var c1 = new ItemView();
    base.switcher.set(c1);
    t.equal(base.el.firstChild, c1.el, 'the current view was set');
    t.end();
});

test('`options.hide`', function (t) {
    var TestView = makeTestView({
        hide: function (oldView) {
            t.equal(oldView, c1, 'first param should be previous view');
        }
    });
    var base = new TestView();
    var c1 = new ItemView();
    var c2 = new ItemView();
    base.switcher.set(c1);
    base.switcher.set(c2);
    t.equal(c1.el.parentNode, null, 'the previous view was removed');
    t.equal(base.el.firstChild, c2.el, 'the current view was set');
    t.end();
});

test('`option.hide` with `waitForRemove`', function (t) {
    var TestView = makeTestView({
        waitForRemove: true,
        hide: function (oldView, cb) {
            t.equal(oldView, c1, 'first param should be previous view');
            t.ok(typeof cb === 'function', 'second param is callback');
            cb();
        }
    });
    var base = new TestView();
    var c1 = new ItemView();
    var c2 = new ItemView();
    base.switcher.set(c1);
    base.switcher.set(c2);
    t.equal(c1.el.parentNode, null, 'the previous view was removed');
    t.equal(base.el.firstChild, c2.el, 'the current view was set');
    t.end();
});

test('`option.show` and `option.hide` used together', function (t) {
    var showCount = 0;
    var hideCount = 0;
    var TestView = makeTestView({
        show: function () {
            showCount++;
        },
        hide: function () {
            hideCount++;
        }
    });
    var base = new TestView();
    var c1 = new ItemView();
    var c2 = new ItemView();
    base.switcher.set(c1);
    t.equal(base.el.firstChild, c1.el, 'first view was set');
    base.switcher.set(c2);
    t.equal(c1.el.parentNode, null, 'first view was removed');
    t.equal(base.el.firstChild, c2.el, 'second view was set');
    t.equal(showCount, 2, 'show should be called for every view we set');
    t.equal(hideCount, 1, 'hide should be called only once, after first view has been set');
    t.end();
});
<|endoftext|>


<commit_before>/* ************************************ */
/* Define helper functions */
/* ************************************ */
function getDisplayElement() {
  $('

').appendTo('body')
  return $('

').appendTo('body')
}

function fillArray(value, len) {
  if (len === 0) return [];
  var a = [value];
  while (a.length * 2 <= len) a = a.concat(a);
  if (a.length < len) a = a.concat(a.slice(0, len - a.length));
  return a;
}

/* ************************************ */
/* Define experimental variables */
/* ************************************ */

/* ************************************ */
/* Set up jsPsych blocks */
/* ************************************ */

/* define static blocks */

var welcome_block = {
  type: 'text',
  text: '

Welcome to this survey.

 Press enter to begin.

',
  cont_key: [13],
  data: {
    exp_id: "mpq_control"
  }
};

var instructions_block = {
  type: 'poldrack-instructions',
  pages: [
    '

Please answer each question by clicking "True" or "False" following the questions to indicate whether they are descriptive of you and your actions. There are no right or wrong answers, and no trick questions. Work quickly and do not think too long about the exact meaning of the question.

',
  ],
  allow_keys: false,
  show_clickable_nav: true,
  timing_post_trial: 1000,
  data: {
    exp_id: "mpq_control"
  }
};

var opts = ["True", "False"]

var all_pages = [
  ["Stop one activity before completing it.", "Take time to consider all aspects.",
    "Think before doing.", "Stop and think.", "Fast and careless.", "Never reckless.",
    "Buy something without thinking.", "Value rational approach."
  ],
  ["Spur of the moment.", "Careful reasoning.", "Not as cautious.", "Cautious person.",
    "Spontaneous person.", "Do first thing that comes to mind.", "Close track of money.",
    "Play things by ear."
  ],
  ["Know how to proceed.", "Very level-headed.", "Organize my work.", "Often start projects.",
    "I am methodical.", "Not have detailed plans.", "Have a good idea of what I'm going to do.",
    "Like to find out what to expect."
  ]
]

var all_options = [fillArray(opts, 8), fillArray(opts, 8), fillArray(opts, 8)]

//higher - more impulsiveness
var score_scale = {
  "True": 2,
  "False": 1
}

var survey_block = {
  type: "poldrack-survey-multi-choice",
  exp_id: "mpq_control",
  horizontal: true,
  preamble: '',
  pages: all_pages,
  options: all_options,
  scale: score_scale,
  show_clickable_nav: true,
  allow_backward: true,
  required: [fillArray(true, 8), fillArray(true, 8), fillArray(true, 8)],
  reverse_score: [
    [false, true, true, true, false, true, false, true],
    [false, true, false, true, false, false, true, false],
    [true, true, true, false, true, false, true, true]
  ],
};

var end_block = {
  type: 'text',
  text: '

Congratulations for completing this task!

Press enter to continue.

',
  cont_key: [13],
  data: {
    exp_id: "mpq_control"
  }
};

//Set up experiment
var mpq_control_experiment = []
mpq_control_experiment.push(welcome_block);
mpq_control_experiment.push(instructions_block);
mpq_control_experiment.push(survey_block);
mpq_control_experiment.push(end_block);<commit_msg>Fixed issue #153 by adding preamble to each page.<commit_after>/* ************************************ */
/* Define helper functions */
/* ************************************ */
function getDisplayElement() {
  $('

').appendTo('body')
  return $('

').appendTo('body')
}

function fillArray(value, len) {
  if (len === 0) return [];
  var a = [value];
  while (a.length * 2 <= len) a = a.concat(a);
  if (a.length < len) a = a.concat(a.slice(0, len - a.length));
  return a;
}

/* ************************************ */
/* Define experimental variables */
/* ************************************ */

/* ************************************ */
/* Set up jsPsych blocks */
/* ************************************ */

/* define static blocks */

var welcome_block = {
  type: 'text',
  text: '

Welcome to this survey.

 Press enter to begin.

',
  cont_key: [13],
  data: {
    exp_id: "mpq_control"
  }
};

var instructions_block = {
  type: 'poldrack-instructions',
  pages: [
    '

Please answer each question by clicking "True" or "False" following the questions to indicate whether they are descriptive of you and your actions. There are no right or wrong answers, and no trick questions. Work quickly and do not think too long about the exact meaning of the question.

',
  ],
  allow_keys: false,
  show_clickable_nav: true,
  timing_post_trial: 1000,
  data: {
    exp_id: "mpq_control"
  }
};

var opts = ["True", "False"]

var all_pages = [
  ["Stop one activity before completing it.", "Take time to consider all aspects.",
    "Think before doing.", "Stop and think.", "Fast and careless.", "Never reckless.",
    "Buy something without thinking.", "Value rational approach."
  ],
  ["Spur of the moment.", "Careful reasoning.", "Not as cautious.", "Cautious person.",
    "Spontaneous person.", "Do first thing that comes to mind.", "Close track of money.",
    "Play things by ear."
  ],
  ["Know how to proceed.", "Very level-headed.", "Organize my work.", "Often start projects.",
    "I am methodical.", "Not have detailed plans.", "Have a good idea of what I'm going to do.",
    "Like to find out what to expect."
  ]
]

var all_options = [fillArray(opts, 8), fillArray(opts, 8), fillArray(opts, 8)]

//higher - more impulsiveness
var score_scale = {
  "True": 2,
  "False": 1
}

var survey_block = {
  type: "poldrack-survey-multi-choice",
  exp_id: "mpq_control",
  horizontal: true,
  preamble: 'Is it true or false that you generally...',
  pages: all_pages,
  options: all_options,
  scale: score_scale,
  show_clickable_nav: true,
  allow_backward: true,
  required: [fillArray(true, 8), fillArray(true, 8), fillArray(true, 8)],
  reverse_score: [
    [false, true, true, true, false, true, false, true],
    [false, true, false, true, false, false, true, false],
    [true, true, true, false, true, false, true, true]
  ],
};

var end_block = {
  type: 'text',
  text: '

Congratulations for completing this task!

Press enter to continue.

',
  cont_key: [13],
  data: {
    exp_id: "mpq_control"
  }
};

//Set up experiment
var mpq_control_experiment = []
mpq_control_experiment.push(welcome_block);
mpq_control_experiment.push(instructions_block);
mpq_control_experiment.push(survey_block);
mpq_control_experiment.push(end_block);<|endoftext|>


<commit_before>// Karma configuration
// Generated on Tue May 24 2016 11:03:15 GMT+0200 (CEST)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['wiredep', 'mocha', 'chai', 'sinon', 'chai-sinon'],

    wiredep: {
      dependencies: true,
      devDependencies: true
    },

    // list of files / patterns to load in the browser
    files: [
      'tests-mock-data/**/*.js',
	  'src/app.loading.js',
      'src/app.utils.js',
      'src/app.module.js',
      'src/**/*.module.js',
      'src/**/*.js'
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
        'src/**/!(*.spec).js': ['coverage']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['dots', 'coverage'],

    /*coverageReporter: {
      type: 'lcovonly',
      dir: '../../',
      file: 'webui-coverage.info',
      subdir: '.'
    },*/

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['PhantomJS'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
}
<commit_msg>Enable karma coverage report<commit_after>// Karma configuration
// Generated on Tue May 24 2016 11:03:15 GMT+0200 (CEST)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['wiredep', 'mocha', 'chai', 'sinon', 'chai-sinon'],

    wiredep: {
      dependencies: true,
      devDependencies: true
    },

    // list of files / patterns to load in the browser
    files: [
      'tests-mock-data/**/*.js',
	  'src/app.loading.js',
      'src/app.utils.js',
      'src/app.module.js',
      'src/**/*.module.js',
      'src/**/*.js'
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
        'src/**/!(*.spec).js': ['coverage']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['dots', 'coverage'],

    coverageReporter: {
      type: 'lcovonly',
      dir: '.',
      file: 'webui-coverage.info'
    },

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['PhantomJS'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
}
<|endoftext|>


<commit_before>describe('INThread', function() {
  var haveOwnPromise = window.hasOwnProperty('Promise');
  var inbox;
  var server;
  var namespace;

  var mockNotFound = {
    "message": "404: Not Found",
    "type": "api_error"
  };

  var mockNamespace = {
    "account": "fake_account_id",
    "email_address": "fake.email@inboxapp.co",
    "id": "fake_namespace_id",
    "namespace": "fake_namespace_id",
    "object": "namespace",
    "provider": "FakeProvider"
  };

  var mockThread1 = {
    "id": "fake_thread_id1",
    "object": "thread",
    "namespace": "fake_namespace_id",
    "subject": "Mock Thread 1",
    "last_message_timestamp": 1398229259,
    "participants": [
      {
        "name": "Ben Bitdiddle",
        "email": "ben.bitdiddle@gmail.com"
      },
      {
        "name": "Bill Rogers",
        "email": "wrogers@mit.edu"
      }
    ],
    "snippet": "Test thread 1...",
    "tags": [
      {
        "name": "inbox",
        "id": "f0idlvozkrpj3ihxze7obpivh",
        "object": "tag"
      },
      {
        "name": "unread",
        "id": "8keda28h8ijj2nogpj83yjep8",
        "object": "tag"
      }
    ],
    "messages": [
      "251r594smznew6yhiocht2v29",
      "7upzl8ss738iz8xf48lm84q3e",
      "ah5wuphj3t83j260jqucm9a28"
    ],
    "drafts": []
  };

  var mappedThread1 = {
    "id": "fake_thread_id1",
    "object": "thread",
    "namespaceID": "fake_namespace_id",
    "subject": "Mock Thread 1",
    "lastMessageDate": new Date(1398229259000),
    "participants": [
      {
        "name": "Ben Bitdiddle",
        "email": "ben.bitdiddle@gmail.com"
      },
      {
        "name": "Bill Rogers",
        "email": "wrogers@mit.edu"
      }
    ],
    "snippet": "Test thread 1...",
    "tagData": [
      {
        "name": "inbox",
        "id": "f0idlvozkrpj3ihxze7obpivh",
        "object": "tag"
      },
      {
        "name": "unread",
        "id": "8keda28h8ijj2nogpj83yjep8",
        "object": "tag"
      }
    ],
    "messageIDs": [
      "251r594smznew6yhiocht2v29",
      "7upzl8ss738iz8xf48lm84q3e",
      "ah5wuphj3t83j260jqucm9a28"
    ],
    "draftIDs": []
  };

  var mockThread1Updated = __extend(mockThread1, {
    "messages": [
      "251r594smznew6yhiocht2v29",
      "7upzl8ss738iz8xf48lm84q3e",
      "ah5wuphj3t83j260jqucm9a28",
      "ag9afs86as9g8gasfasfsaf98"
    ]
  });

  var mappedThread1Updated = __extend(mappedThread1, {
    "messageIDs": [
      "251r594smznew6yhiocht2v29",
      "7upzl8ss738iz8xf48lm84q3e",
      "ah5wuphj3t83j260jqucm9a28",
      "ag9afs86as9g8gasfasfsaf98"
    ]
  });

  var mockThread1Updated2 = __extend({}, mockThread1);
  mockThread1Updated2.messages = [
    "ag9afs86as9g8gasfasfsaf98"
  ];

  var mappedThread1Updated2 = __extend({}, mappedThread1);
  mappedThread1Updated2.messageIDs = [
    "ag9afs86as9g8gasfasfsaf98"
  ];

  var mockThread2 = {
    "id": "fake_thread_id2",
    "object": "thread",
    "namespace": "fake_namespace_id",
    "subject": "Mock Thread 2",
    "last_message_timestamp": 1399238467,
    "participants": [
      {
        "name": "Ben Bitdiddle",
        "email": "ben.bitdiddle@gmail.com"
      },
      {
        "name": "Bill Rogers",
        "email": "wrogers@mit.edu"
      }
    ],
    "snippet": "Test thread 2...",
    "tags": [
      {
        "name": "inbox",
        "id": "f0idlvozkrpj3ihxze7obpivh"
      }
    ],
    "messages": [
      "251r594smznew6yhiocht2v29",
      "7upzl8ss738iz8xf48lm84q3e"
    ],
    "drafts": []
  };

  var mappedThread2 = {
    "id": "fake_thread_id2",
    "object": "thread",
    "namespaceID": "fake_namespace_id",
    "subject": "Mock Thread 2",
    "lastMessageDate": new Date(1399238467000),
    "participants": [
      {
        "name": "Ben Bitdiddle",
        "email": "ben.bitdiddle@gmail.com"
      },
      {
        "name": "Bill Rogers",
        "email": "wrogers@mit.edu"
      }
    ],
    "snippet": "Test thread 2...",
    "tagData": [
      {
        "name": "inbox",
        "id": "f0idlvozkrpj3ihxze7obpivh"
      }
    ],
    "messageIDs": [
      "251r594smznew6yhiocht2v29",
      "7upzl8ss738iz8xf48lm84q3e"
    ],
    "draftIDs": []
  };

  var mockThreads = [
    mockThread1,
    mockThread2
  ];

  beforeEach(function() {
    window.Promise = mockPromises.getMockPromise(window.Promise);
    server = sinon.fakeServer.create();
    inbox = new InboxAPI({
      appId: '',
      baseUrl: 'http://api.inboxapp.co/'
    });
    namespace = new INNamespace(inbox, mockNamespace);
  });

  afterEach(function() {
    server.restore();
    if (haveOwnPromise) {
      window.Promise = mockPromises.getOriginalPromise();
    } else {
      delete window.Promise;
    }
  });

  it('should be a child class of INModelObject', function() {
    expect(new INThread() instanceof INModelObject).toBe(true);
  });

  describe('when unsynced', function() {
    it('should have null resourcePath()', function() {
      expect ((new INThread(inbox, null, 'fake_namespace_id')).resourcePath()).toBe(null);
    });
  });

  describe('when synced', function() {
    it('should have resourcePath() like <baseUrl>/n/<namespaceId>/threads/<threadId>', function() {
      expect ((new INThread(inbox, mockThread1)).resourcePath()).toBe('http://api.inboxapp.co/n/fake_namespace_id/threads/fake_thread_id1');
    });
  });

  describe('InboxNamespace#threads()', function() {
    it('should resolve promise with an Array of INThreads', function() {
      var fulfilled = jasmine.createSpy('load').andCallFake(function(threads) {
        expect(threads.length).toBe(2);
        expect(threads[0] instanceof INThread).toBe(true);
        expect(threads[1] instanceof INThread).toBe(true);
      });
      var promise = namespace.threads().then(fulfilled);
      server.respond([200, { "Content-Type": "application/json" }, JSON.stringify(mockThreads)]);
      mockPromises.executeForPromise(promise);
      expect(fulfilled).toHaveBeenCalled();
    });

    it('should copy mapped property values into resources', function() {
      var fulfilled = jasmine.createSpy('load').andCallFake(function(threads) {
        expect(threads[0]).toContainObject(mappedThread1);
        //expect(threads[1]).toContainObject(mappedThread2);
      });
      var promise = namespace.threads().then(fulfilled);
      server.respond([200, { "Content-Type": "application/json" }, JSON.stringify(mockThreads)]);
      mockPromises.executeForPromise(promise);
      expect(fulfilled).toHaveBeenCalled();
    });

    it('should not resolve promise on error status', function() {
      var promise = namespace.threads();
      server.respond([404, { "Content-Type": "application/json" }, JSON.stringify(mockNotFound)]);
      mockPromises.executeForPromise(promise);
      expect(promise.isFulfilled()).not.toBe(true);
      expect(promise.isRejected()).toBe(true);
    });

    it('should update passed array of namespaces', function() {
      var oldThreads = [mockThread1];
      var fulfilled = jasmine.createSpy('load').andCallFake(function(threads) {
        expect(threads.length).toBe(2);
        expect(threads).toBe(oldThreads);
        expect(threads[0]).toBe(oldThreads[0]);
        expect(threads[1]).toContainObject(mappedThread2);
        expect(threads[1] instanceof INThread).toBe(true);
      });
      var promise = namespace.threads(oldThreads).then(fulfilled);
      server.respond([200, { "Content-Type": "application/json" }, JSON.stringify(mockThreads)]);
      mockPromises.executeForPromise(promise);
      expect(fulfilled).toHaveBeenCalled();
    });
  });

  describe('InboxNamespace#thread()', function() {
    it('should resolve promise with INThread', function() {
      var fulfilled = jasmine.createSpy('load').andCallFake(function(thread) {
        expect(thread instanceof INThread).toBe(true);
      });
      var promise = namespace.thread('fake_thread_1').then(fulfilled);
      server.respond([200, { "Content-Type": "application/json" }, JSON.stringify(mockThread1)]);
      mockPromises.executeForPromise(promise);
      expect(fulfilled).toHaveBeenCalled();
    });

    it('should copy mapped property values into new resource', function() {
      var fulfilled = jasmine.createSpy('load').andCallFake(function(thread) {
        expect(thread).toContainObject(mappedThread2);
      });
      var promise = namespace.thread('fake_thread_2').then(fulfilled);
      server.respond([200, { "Content-Type": "application/json" }, JSON.stringify(mockThread2)]);
      mockPromises.executeForPromise(promise);
      expect(fulfilled).toHaveBeenCalled();
    });

    it('should not resolve promise on error status', function() {
      var promise = namespace.thread('124124124123');
      server.respond([404, { "Content-Type": "application/json" }, JSON.stringify(mockNotFound)]);
      mockPromises.executeForPromise(promise);
      expect(promise.isFulfilled()).not.toBe(true);
      expect(promise.isRejected()).toBe(true);
    });
  });

  describe('reload method', function() {
    var thread;
    beforeEach(function() {
      thread = new INThread(namespace, mockThread1);
    });

    it('should resolve with original Thread object', function() {
      var fulfilled = jasmine.createSpy('load').andCallFake(function(newThread) {
        expect(newThread).toBe(thread);
      });
      var promise = thread.reload().then(fulfilled);
      server.respond([200, { "Content-Type": "application/json" }, JSON.stringify(mockThread1Updated)]);
      mockPromises.executeForPromise(promise);
      expect(fulfilled).toHaveBeenCalled();
    });

    it('should resolve including properties from original Thread', function() {
      var fulfilled = jasmine.createSpy('load').andCallFake(function(newThread) {
        expect(newThread).toContainObject(mappedThread1Updated);
      });
      var promise = thread.reload().then(fulfilled);
      server.respond([200, { "Content-Type": "application/json" }, JSON.stringify(mockThread1Updated)]);
      mockPromises.executeForPromise(promise);
      expect(fulfilled).toHaveBeenCalled();
    });

    it('should resolve including properties from updated Thread', function() {
      var fulfilled = jasmine.createSpy('load').andCallFake(function(newThread) {
        expect(newThread).toContainObject(mappedThread1Updated);
        expect(newThread.messageIDs.length).toBe(4);
        expect(newThread.messageIDs[3]).toBe('ag9afs86as9g8gasfasfsaf98');
      });
      var promise = thread.reload().then(fulfilled);
      server.respond([200, { "Content-Type": "application/json" }, JSON.stringify(mockThread1Updated)]);
      mockPromises.executeForPromise(promise);
      expect(fulfilled).toHaveBeenCalled();
    });

    it('should resolve removing properties deleted in updated Thread', function() {
      var fulfilled = jasmine.createSpy('load').andCallFake(function(newThread) {
        expect(newThread).toContainObject(mappedThread1Updated2);
        expect(newThread.messageIDs.length).toBe(1);
        expect(newThread.messageIDs[0]).toBe('ag9afs86as9g8gasfasfsaf98');
      });
      var promise = thread.reload().then(fulfilled);
      server.respond([200, { "Content-Type": "application/json" }, JSON.stringify(mockThread1Updated2)]);
      mockPromises.executeForPromise(promise);
      expect(fulfilled).toHaveBeenCalled();
    });
  });
});
<commit_msg>test(threads.spec.js): fix spec description<commit_after>describe('INThread', function() {
  var haveOwnPromise = window.hasOwnProperty('Promise');
  var inbox;
  var server;
  var namespace;

  var mockNotFound = {
    "message": "404: Not Found",
    "type": "api_error"
  };

  var mockNamespace = {
    "account": "fake_account_id",
    "email_address": "fake.email@inboxapp.co",
    "id": "fake_namespace_id",
    "namespace": "fake_namespace_id",
    "object": "namespace",
    "provider": "FakeProvider"
  };

  var mockThread1 = {
    "id": "fake_thread_id1",
    "object": "thread",
    "namespace": "fake_namespace_id",
    "subject": "Mock Thread 1",
    "last_message_timestamp": 1398229259,
    "participants": [
      {
        "name": "Ben Bitdiddle",
        "email": "ben.bitdiddle@gmail.com"
      },
      {
        "name": "Bill Rogers",
        "email": "wrogers@mit.edu"
      }
    ],
    "snippet": "Test thread 1...",
    "tags": [
      {
        "name": "inbox",
        "id": "f0idlvozkrpj3ihxze7obpivh",
        "object": "tag"
      },
      {
        "name": "unread",
        "id": "8keda28h8ijj2nogpj83yjep8",
        "object": "tag"
      }
    ],
    "messages": [
      "251r594smznew6yhiocht2v29",
      "7upzl8ss738iz8xf48lm84q3e",
      "ah5wuphj3t83j260jqucm9a28"
    ],
    "drafts": []
  };

  var mappedThread1 = {
    "id": "fake_thread_id1",
    "object": "thread",
    "namespaceID": "fake_namespace_id",
    "subject": "Mock Thread 1",
    "lastMessageDate": new Date(1398229259000),
    "participants": [
      {
        "name": "Ben Bitdiddle",
        "email": "ben.bitdiddle@gmail.com"
      },
      {
        "name": "Bill Rogers",
        "email": "wrogers@mit.edu"
      }
    ],
    "snippet": "Test thread 1...",
    "tagData": [
      {
        "name": "inbox",
        "id": "f0idlvozkrpj3ihxze7obpivh",
        "object": "tag"
      },
      {
        "name": "unread",
        "id": "8keda28h8ijj2nogpj83yjep8",
        "object": "tag"
      }
    ],
    "messageIDs": [
      "251r594smznew6yhiocht2v29",
      "7upzl8ss738iz8xf48lm84q3e",
      "ah5wuphj3t83j260jqucm9a28"
    ],
    "draftIDs": []
  };

  var mockThread1Updated = __extend(mockThread1, {
    "messages": [
      "251r594smznew6yhiocht2v29",
      "7upzl8ss738iz8xf48lm84q3e",
      "ah5wuphj3t83j260jqucm9a28",
      "ag9afs86as9g8gasfasfsaf98"
    ]
  });

  var mappedThread1Updated = __extend(mappedThread1, {
    "messageIDs": [
      "251r594smznew6yhiocht2v29",
      "7upzl8ss738iz8xf48lm84q3e",
      "ah5wuphj3t83j260jqucm9a28",
      "ag9afs86as9g8gasfasfsaf98"
    ]
  });

  var mockThread1Updated2 = __extend({}, mockThread1);
  mockThread1Updated2.messages = [
    "ag9afs86as9g8gasfasfsaf98"
  ];

  var mappedThread1Updated2 = __extend({}, mappedThread1);
  mappedThread1Updated2.messageIDs = [
    "ag9afs86as9g8gasfasfsaf98"
  ];

  var mockThread2 = {
    "id": "fake_thread_id2",
    "object": "thread",
    "namespace": "fake_namespace_id",
    "subject": "Mock Thread 2",
    "last_message_timestamp": 1399238467,
    "participants": [
      {
        "name": "Ben Bitdiddle",
        "email": "ben.bitdiddle@gmail.com"
      },
      {
        "name": "Bill Rogers",
        "email": "wrogers@mit.edu"
      }
    ],
    "snippet": "Test thread 2...",
    "tags": [
      {
        "name": "inbox",
        "id": "f0idlvozkrpj3ihxze7obpivh"
      }
    ],
    "messages": [
      "251r594smznew6yhiocht2v29",
      "7upzl8ss738iz8xf48lm84q3e"
    ],
    "drafts": []
  };

  var mappedThread2 = {
    "id": "fake_thread_id2",
    "object": "thread",
    "namespaceID": "fake_namespace_id",
    "subject": "Mock Thread 2",
    "lastMessageDate": new Date(1399238467000),
    "participants": [
      {
        "name": "Ben Bitdiddle",
        "email": "ben.bitdiddle@gmail.com"
      },
      {
        "name": "Bill Rogers",
        "email": "wrogers@mit.edu"
      }
    ],
    "snippet": "Test thread 2...",
    "tagData": [
      {
        "name": "inbox",
        "id": "f0idlvozkrpj3ihxze7obpivh"
      }
    ],
    "messageIDs": [
      "251r594smznew6yhiocht2v29",
      "7upzl8ss738iz8xf48lm84q3e"
    ],
    "draftIDs": []
  };

  var mockThreads = [
    mockThread1,
    mockThread2
  ];

  beforeEach(function() {
    window.Promise = mockPromises.getMockPromise(window.Promise);
    server = sinon.fakeServer.create();
    inbox = new InboxAPI({
      appId: '',
      baseUrl: 'http://api.inboxapp.co/'
    });
    namespace = new INNamespace(inbox, mockNamespace);
  });

  afterEach(function() {
    server.restore();
    if (haveOwnPromise) {
      window.Promise = mockPromises.getOriginalPromise();
    } else {
      delete window.Promise;
    }
  });

  it('should be a child class of INModelObject', function() {
    expect(new INThread() instanceof INModelObject).toBe(true);
  });

  describe('when unsynced', function() {
    it('should have null resourcePath()', function() {
      expect ((new INThread(inbox, null, 'fake_namespace_id')).resourcePath()).toBe(null);
    });
  });

  describe('when synced', function() {
    it('should have resourcePath() like <baseUrl>/n/<namespaceId>/threads/<threadId>', function() {
      expect ((new INThread(inbox, mockThread1)).resourcePath()).toBe('http://api.inboxapp.co/n/fake_namespace_id/threads/fake_thread_id1');
    });
  });

  describe('InboxNamespace#threads()', function() {
    it('should resolve promise with an Array of INThreads', function() {
      var fulfilled = jasmine.createSpy('load').andCallFake(function(threads) {
        expect(threads.length).toBe(2);
        expect(threads[0] instanceof INThread).toBe(true);
        expect(threads[1] instanceof INThread).toBe(true);
      });
      var promise = namespace.threads().then(fulfilled);
      server.respond([200, { "Content-Type": "application/json" }, JSON.stringify(mockThreads)]);
      mockPromises.executeForPromise(promise);
      expect(fulfilled).toHaveBeenCalled();
    });

    it('should copy mapped property values into resources', function() {
      var fulfilled = jasmine.createSpy('load').andCallFake(function(threads) {
        expect(threads[0]).toContainObject(mappedThread1);
        //expect(threads[1]).toContainObject(mappedThread2);
      });
      var promise = namespace.threads().then(fulfilled);
      server.respond([200, { "Content-Type": "application/json" }, JSON.stringify(mockThreads)]);
      mockPromises.executeForPromise(promise);
      expect(fulfilled).toHaveBeenCalled();
    });

    it('should not resolve promise on error status', function() {
      var promise = namespace.threads();
      server.respond([404, { "Content-Type": "application/json" }, JSON.stringify(mockNotFound)]);
      mockPromises.executeForPromise(promise);
      expect(promise.isFulfilled()).not.toBe(true);
      expect(promise.isRejected()).toBe(true);
    });

    it('should update passed array of threads', function() {
      var oldThreads = [mockThread1];
      var fulfilled = jasmine.createSpy('load').andCallFake(function(threads) {
        expect(threads.length).toBe(2);
        expect(threads).toBe(oldThreads);
        expect(threads[0]).toBe(oldThreads[0]);
        expect(threads[1]).toContainObject(mappedThread2);
        expect(threads[1] instanceof INThread).toBe(true);
      });
      var promise = namespace.threads(oldThreads).then(fulfilled);
      server.respond([200, { "Content-Type": "application/json" }, JSON.stringify(mockThreads)]);
      mockPromises.executeForPromise(promise);
      expect(fulfilled).toHaveBeenCalled();
    });
  });

  describe('InboxNamespace#thread()', function() {
    it('should resolve promise with INThread', function() {
      var fulfilled = jasmine.createSpy('load').andCallFake(function(thread) {
        expect(thread instanceof INThread).toBe(true);
      });
      var promise = namespace.thread('fake_thread_1').then(fulfilled);
      server.respond([200, { "Content-Type": "application/json" }, JSON.stringify(mockThread1)]);
      mockPromises.executeForPromise(promise);
      expect(fulfilled).toHaveBeenCalled();
    });

    it('should copy mapped property values into new resource', function() {
      var fulfilled = jasmine.createSpy('load').andCallFake(function(thread) {
        expect(thread).toContainObject(mappedThread2);
      });
      var promise = namespace.thread('fake_thread_2').then(fulfilled);
      server.respond([200, { "Content-Type": "application/json" }, JSON.stringify(mockThread2)]);
      mockPromises.executeForPromise(promise);
      expect(fulfilled).toHaveBeenCalled();
    });

    it('should not resolve promise on error status', function() {
      var promise = namespace.thread('124124124123');
      server.respond([404, { "Content-Type": "application/json" }, JSON.stringify(mockNotFound)]);
      mockPromises.executeForPromise(promise);
      expect(promise.isFulfilled()).not.toBe(true);
      expect(promise.isRejected()).toBe(true);
    });
  });

  describe('reload method', function() {
    var thread;
    beforeEach(function() {
      thread = new INThread(namespace, mockThread1);
    });

    it('should resolve with original Thread object', function() {
      var fulfilled = jasmine.createSpy('load').andCallFake(function(newThread) {
        expect(newThread).toBe(thread);
      });
      var promise = thread.reload().then(fulfilled);
      server.respond([200, { "Content-Type": "application/json" }, JSON.stringify(mockThread1Updated)]);
      mockPromises.executeForPromise(promise);
      expect(fulfilled).toHaveBeenCalled();
    });

    it('should resolve including properties from original Thread', function() {
      var fulfilled = jasmine.createSpy('load').andCallFake(function(newThread) {
        expect(newThread).toContainObject(mappedThread1Updated);
      });
      var promise = thread.reload().then(fulfilled);
      server.respond([200, { "Content-Type": "application/json" }, JSON.stringify(mockThread1Updated)]);
      mockPromises.executeForPromise(promise);
      expect(fulfilled).toHaveBeenCalled();
    });

    it('should resolve including properties from updated Thread', function() {
      var fulfilled = jasmine.createSpy('load').andCallFake(function(newThread) {
        expect(newThread).toContainObject(mappedThread1Updated);
        expect(newThread.messageIDs.length).toBe(4);
        expect(newThread.messageIDs[3]).toBe('ag9afs86as9g8gasfasfsaf98');
      });
      var promise = thread.reload().then(fulfilled);
      server.respond([200, { "Content-Type": "application/json" }, JSON.stringify(mockThread1Updated)]);
      mockPromises.executeForPromise(promise);
      expect(fulfilled).toHaveBeenCalled();
    });

    it('should resolve removing properties deleted in updated Thread', function() {
      var fulfilled = jasmine.createSpy('load').andCallFake(function(newThread) {
        expect(newThread).toContainObject(mappedThread1Updated2);
        expect(newThread.messageIDs.length).toBe(1);
        expect(newThread.messageIDs[0]).toBe('ag9afs86as9g8gasfasfsaf98');
      });
      var promise = thread.reload().then(fulfilled);
      server.respond([200, { "Content-Type": "application/json" }, JSON.stringify(mockThread1Updated2)]);
      mockPromises.executeForPromise(promise);
      expect(fulfilled).toHaveBeenCalled();
    })
  });
});
<|endoftext|>


<commit_before>const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const bookSchema = new Schema({
  title: { type: String, required: true },
  type: { type: String, required: true },
  author: { type: String, required: false },
  numberPages: { type: Number, required: false },
  dateOfPub: { type: Number, required: false },
  url: { type: String, required: false },
  // isbn is the orderable number from a bookstore
  isbn: { type: String, required: false },
  siteLocation: { type: String, required: false },
  numberOfCopies: { type: Number, required: false },
  access: { type: String, required: false },
  comments: { type: String, required: false },
  checkedOutBy: { type: String, required: false },
  checkedOutByName: { type: String, required: false }
});

module.exports = mongoose.model('Book', bookSchema);
<commit_msg>books datestamps<commit_after>const mongoose = require('mongoose');

const options = {
  timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }
};

const Schema = mongoose.Schema;

const bookSchema = new Schema({
  title: { type: String, required: true },
  type: { type: String, required: true },
  author: { type: String, required: false },
  numberPages: { type: Number, required: false },
  dateOfPub: { type: Number, required: false },
  url: { type: String, required: false },
  // isbn is the orderable number from a bookstore
  isbn: { type: String, required: false },
  siteLocation: { type: String, required: false },
  numberOfCopies: { type: Number, required: false },
  access: { type: String, required: false },
  comments: { type: String, required: false },
  checkedOutBy: { type: String, required: false },
  checkedOutByName: { type: String, required: false }
}, options);

module.exports = mongoose.model('Book', bookSchema);
<|endoftext|>


<commit_before>angular.module('daypageModule')
.controller('daypageCtrl', function($scope, queryAPI, $stateParams, $ionicNavBarDelegate, $rootScope, signinFac, $ionicPopover) {

  var pageID = $stateParams.dayID.replace(/:/g,"");

  queryAPI.getDayById([pageID])
  .then(function(data) {
    if (data.status.code === 100) {
      queryAPI.cleanDay(data.result)
      .then(function (daysObject) {
        $scope.dayObj = daysObject[0];

        if ($scope.dayObj.tagArray.length > 0) {
          queryAPI.getDayByTag($scope.dayObj.tagArray, 3)
          .then(function(data) {
            if(data.status.code === 100) {
              queryAPI.cleanDay(data.result)
              .then(function (daysObject) {
                $scope.relatedDays = daysObject;
              });
            } else {
              console.log('Error retrieving DaysByTag: ' + data.status.code);
            }
          }, function (status) {
            console.log(status);
          });
        }

      });
    } else {
      console.log('Error retrieving DayByID: ' + data.status.code);
    }
  }, function (status) {
    console.log(status);
  });

  $scope.goBack = function () {
    $ionicNavBarDelegate.back();
  };

  $scope.setCategoryName = function (categoryname) {
    console.log(categoryname);
    console.log("setting cat name to: " + categoryname);
    $rootScope.currentCategory = {
      'name': categoryname
    };
  };

  $scope.bookmarkDay = function () {
    if ($scope.dayObj) {
      var profileData = {
        'type': 'days'
      };

      if ($scope.dayObj.bookmarked) {
        profileData.remove = [$scope.dayObj.id];
        if (typeof $rootScope.userData.pc_days !== 'undefined') {
          while ($rootScope.userData.pc_days.indexOf($scope.dayObj.id.toString()) !== -1) {
            $rootScope.userData.pc_days.splice($rootScope.userData.pc_days.indexOf($scope.dayObj.id.toString()),1)
          };
          console.log('days bookmarks: ', $rootScope.userData.pc_days);
        }
      } else {
        profileData.add = [$scope.dayObj.id];
        if (typeof $rootScope.userData.pc_days !== 'undefined') {
          if($rootScope.userData.pc_days.indexOf($scope.dayObj.id.toString()) === -1) {
            $rootScope.userData.pc_days.push($scope.dayObj.id.toString());
            console.log('days bookmarks: ', $rootScope.userData.pc_days);
          }
        }
      }

      $scope.dayObj.bookmarked = !$scope.dayObj.bookmarked;

      signinFac.updateBookmarks(profileData)
      .then(function (status) {
        console.log(status);
      }, function (status) {
        console.log(status);
        //        $scope.dayObj.bookmarked = !$scope.dayObj.bookmarked;
      });
    }
    else {
      console.log("Can't bookmark, no day loaded yet");
    }
  };

  $ionicPopover.fromTemplateUrl('modals/showMore.html', {
    scope: $scope,
  }).then(function(popover) {
    $scope.popover = popover;
  });

  $scope.openPopover = function($event) {
    $scope.popover.show($event);
    console.log('Opening showMore popover');
  };
  $scope.closePopover = function() {
    $scope.popover.hide();
    console.log('Closing showMore popover');
  };
  //Cleanup the popover when we're done with it!
  $scope.$on('$destroy', function() {
    $scope.popover.remove();
    console.log('Destroying showMore popover');
  });
});
<commit_msg>Increased related content to 4 days and automatically filter out the parent page (day pages won't recommend themselves as related content on their own page)<commit_after>angular.module('daypageModule')
.controller('daypageCtrl', function($scope, queryAPI, $stateParams, $rootScope, signinFac, $ionicPopover) {

  var pageID = $stateParams.dayID.replace(/:/g,"");

  queryAPI.getDayById([pageID])
  .then(function(data) {
    if (data.status.code === 100) {
      queryAPI.cleanDay(data.result)
      .then(function (daysObject) {
        $scope.dayObj = daysObject[0];

        if ($scope.dayObj.tagArray.length > 0) {
          queryAPI.getDayByTag($scope.dayObj.tagArray, 5)
          .then(function(data) {
            if(data.status.code === 100) {
              var responseLength = data.result.length;
              var removeEntry = -1;
              if (responseLength) {
                for (var i=0; i<responseLength;i++) {
                  if ($scope.dayObj.id === data.result[i].id) {
                    removeEntry = i;
                  }
                }

                if (removeEntry !== -1) {
                  data.result.splice(removeEntry, 1);
                } else {
                  data.result.splice(data.result.length - 1, 1);
                }
              }
              queryAPI.cleanDay(data.result)
              .then(function (daysObject) {
                $scope.relatedDays = daysObject;
              });
            } else {
              console.log('Error retrieving DaysByTag: ' + data.status.code);
            }
          }, function (status) {
            console.log(status);
          });
        }

      });
    } else {
      console.log('Error retrieving DayByID: ' + data.status.code);
    }
  }, function (status) {
    console.log(status);
  });

  //  $scope.goBack = function () {
  //    $ionicHistory.goBack();
  //  };

  //  $ionicNavBarDelegate.showBackButton(true);

  $scope.setCategoryName = function (categoryname) {
    console.log(categoryname);
    console.log("setting cat name to: " + categoryname);
    $rootScope.currentCategory = {
      'name': categoryname
    };
  };

  $scope.bookmarkDay = function () {
    if ($scope.dayObj) {
      var profileData = {
        'type': 'days'
      };

      if ($scope.dayObj.bookmarked) {
        profileData.remove = [$scope.dayObj.id];
        if (typeof $rootScope.userData.pc_days !== 'undefined') {
          while ($rootScope.userData.pc_days.indexOf($scope.dayObj.id.toString()) !== -1) {
            $rootScope.userData.pc_days.splice($rootScope.userData.pc_days.indexOf($scope.dayObj.id.toString()),1)
          };
          console.log('days bookmarks: ', $rootScope.userData.pc_days);
        }
      } else {
        profileData.add = [$scope.dayObj.id];
        if (typeof $rootScope.userData.pc_days !== 'undefined') {
          if($rootScope.userData.pc_days.indexOf($scope.dayObj.id.toString()) === -1) {
            $rootScope.userData.pc_days.push($scope.dayObj.id.toString());
            console.log('days bookmarks: ', $rootScope.userData.pc_days);
          }
        }
      }

      $scope.dayObj.bookmarked = !$scope.dayObj.bookmarked;

      signinFac.updateBookmarks(profileData)
      .then(function (status) {
        console.log(status);
      }, function (status) {
        console.log(status);
        //        $scope.dayObj.bookmarked = !$scope.dayObj.bookmarked;
      });
    }
    else {
      console.log("Can't bookmark, no day loaded yet");
    }
  };

  $ionicPopover.fromTemplateUrl('modals/showMore.html', {
    scope: $scope,
  }).then(function(popover) {
    $scope.popover = popover;
  });

  $scope.openPopover = function($event) {
    $scope.popover.show($event);
    console.log('Opening showMore popover');
  };
  $scope.closePopover = function() {
    $scope.popover.hide();
    console.log('Closing showMore popover');
  };
  //Cleanup the popover when we're done with it!
  $scope.$on('$destroy', function() {
    $scope.popover.remove();
    console.log('Destroying showMore popover');
  });
});
<|endoftext|>


<commit_before>const path = require('path');
console.log('__dirname', path.resolve(__dirname));
<commit_msg>chore: format<commit_after>const path = require("path")
console.log("__dirname", path.resolve(__dirname))
<|endoftext|>


<commit_before>/**
* Sync images and the images table from the online database before
* launching the Meteor application
*/
if (Meteor.isServer) {

  /**
  * Kiosk mode
  *
  * If in Kioks mode, try and sync the images and images data down to the
  * local copy of the application from the online editor.
  */
  if (
    Meteor.settings &&
    Meteor.settings.public &&
    Meteor.settings.public.kiosk == 'true'
  ) {

    // Load modules for executing external commands
    fs = Npm.require('fs');
    exec = Npm.require('child_process').exec;
    cmd = Meteor.wrapAsync(exec);

    // Customizable path for the application. Allows us to download the images
    // from S3 to any defined path.
    var installPath = Meteor.settings.public.installPath;

    // Sync down the images.json database file from S3. A server process
    // saves this file there. We use it to repopulate the database after
    // Meteor reset. This way, the local kiosk application always gets the
    // latest data from the server each time the application starts up.
    cmd(
      'aws s3 sync s3://sd-scrapbook/db ' + installPath + '/meteor/private',
      Meteor.bindEnvironment(
        function (error, stdout, stderr) {
          if (error) {
            throw new Meteor.Error('error...');
          } else {
            console.log('Downloading images.json');

            // Import the database once the file is pulled down from S3
            importImages();
          }
        }
      )
    );

    // Sync down the image thumbanils
    cmd(
      'aws s3 sync s3://sd-scrapbook/thumbs ' + installPath + '/meteor/public/images/s3/thumbs',
      Meteor.bindEnvironment(
        function (error, stdout, stderr) {
          if (error) {
            throw new Meteor.Error('error...');
          } else {
            console.log('Sync thumbnails done');
          }
        }
      )
    );

    // Sync down the full sized images
    cmd(
      'aws s3 sync s3://sd-scrapbook/originals ' +
      installPath + '/meteor/public/images/s3/originals',

      Meteor.bindEnvironment(
        function (error, stdout, stderr) {
          if (error) {
            throw new Meteor.Error('error...');
          } else {
            console.log('Sync originals done');
          }
        }
      )
    );

    /**
    * Load data into the local database if none is present
    **

    /**
    * Locations
    */
    Locations.remove({});
    if (Locations.find().count() === 0) {

      var anzaBorrego = Locations.insert({
        title: 'Anza Borrego',
        link: 'anza-borrego',
        description: 'Anza-Borrego Desert State Park (ABDSP) is a state park located within the Colorado Desert of southern California, United States.',
        latitude: '33.100595',
        longitude: '-116.151306',
        dsLocId: '1',
      });

      var clevelandNationalForest = Locations.insert({
        title: 'Cleveland National Forest',
        link: 'cleveland-nat',
        description: 'Cleveland National Forest encompasses 460,000 acres (720 sq mi (1,900 km2)), mostly of chaparral, with a few riparian areas.',
        latitude: '32.758856',
        longitude: '-116.674749',
        dsLocId: '2',
      });

      var coloradoRiver = Locations.insert({
        title: 'Colorado River',
        link: 'colorado-river',
        description: '',
        latitude: '33.410193',
        longitude: '-114.693563',
        dsLocId: '3',
      });

      var imperialValley = Locations.insert({
        title: 'Imperial Valley',
        link: 'imperial-valley',
        description: '',
        latitude: '32.793580',
        longitude: '-114.973715',
        dsLocId: '4',
      });

      var joshuaTree = Locations.insert({
        title: 'Joshua Tree',
        link: 'joshua-tree',
        description: '',
        latitude: '33.795570',
        longitude: '-115.621892',
        dsLocId: '5',
      });

      var sdNorthCoast = Locations.insert({
        title: 'San Diego - North Coast',
        link: 'san-diego-north',
        description: '',
        latitude: '32.968837',
        longitude: '-117.254309',
        dsLocId: '6',
      });

      // This isn't visible because of the map cropping
      var mojaveDesert = Locations.insert({
        title: 'Mojave Desert',
        link: 'mojave-desert',
        description: '',
        latitude: '34.336705',
        longitude: '-115.899297',
        dsLocId: '7',
      });

      var northSDCounty = Locations.insert({
        title: 'North San Diego County',
        link: 'north-san-diego-county',
        description: '',
        latitude: '33.366311',
        longitude: '-117.214997',
        dsLocId: '8',
      });

      var orangeCounty = Locations.insert({
        title: 'Orange County',
        link: 'orange-county',
        description: '',
        latitude: '33.810516',
        longitude: '-117.820227',
        dsLocId: '9',
      });

      var palomarMountain = Locations.insert({
        title: 'Palomar Mountain',
        link: 'palomar-mountain',
        description: '',
        latitude: '33.398098',
        longitude: '-116.781367',
        dsLocId: '10',
      });

      var saltonSea = Locations.insert({
        title: 'Salton Sea',
        link: 'salton-sea',
        description: '',
        latitude: '33.287301',
        longitude: '-115.529622',
        dsLocId: '11',
      });

      var sanBerardino = Locations.insert({
        title: 'San Bernardino Mountains',
        link: 'san-bernardino',
        description: '',
        latitude: '34.131438',
        longitude: '-116.538973',
        dsLocId: '12',
      });

      var sanDiegoCoast = Locations.insert({
        title: 'San Diego - Coast',
        link: 'san-diego-coast',
        description: '',
        latitude: '32.694081',
        longitude: '-117.232840',
        dsLocId: '13',
      });

      var sanDiegoInland = Locations.insert({
        title: 'San Diego - Inland',
        link: 'san-diego-inland',
        description: '',
        latitude: '32.832099',
        longitude: '-117.097372',
        dsLocId: '14',
      });

      var sanGabriel = Locations.insert({
        title: 'San Gabriel Mountains',
        link: 'san-gabriel',
        description: '',
        latitude: '34.3288927',
        longitude: '-118.04672',
        dsLocId: '15',
      });

      var sanJacinto = Locations.insert({
        title: 'San Jacinto Mountains',
        link: 'san-jacinto',
        description: '',
        latitude: '33.8418194',
        longitude: '-116.9809458',
        dsLocId: '16',
      });

      var santaMonica = Locations.insert({
        title: 'Santa Monica Mountains and Coast',
        link: 'santa-monica',
        description: '',
        latitude: '33.923742',
        longitude: '-118.816882',
        dsLocId: '17',
      });

      var southSDCounty = Locations.insert({
        title: 'South San Diego County',
        link: 'south-san-diego',
        description: '',
        latitude: '32.536355',
        longitude: '-116.301214',
        dsLocId: '18',
      });

      var losAngeles = Locations.insert({
        title: 'Los Angeles',
        link: 'los-angeles',
        description: '',
        latitude: '33.663533',
        longitude: '-118.293658',
        dsLocId: '19',
      });

      var riverside = Locations.insert({
        title: 'Riverside',
        link: 'riverside',
        description: '',
        latitude: '33.894096',
        longitude: '-117.357879',
        dsLocId: '20',
      });

      var channelIslands = Locations.insert({
        title: 'Channel Islands',
        link: 'channel-islands',
        description: '',
        latitude: '33.823736',
        longitude: '-119.687298',
        dsLocId: '21',
      });

    }

  }
}
/**
* If the images collection has been reset, reload the latest data from a local
* JSON file.
*
* This process is used in the kiosk update from the remote version of the
* tool. When the kiosk starts up each morning we reset the database and
* then load the latest data from the online database if it has changed.
*
* The download process for this file is not handled within this application.
*/
function importImages() {
  if (Images.find().count() === 0) {
    console.log('Importing private/images.json to db');
    var data = JSON.parse(Assets.getText('images.json'));
    data.forEach(function (item, index, array) {
      Images.insert(item);
    });
  }
}
<commit_msg>Better async method for loading images<commit_after>Meteor.methods({
  getLatestImageThumbs: function () {
    // Customizable path for the application. Allows us to download the images
    // from S3 to any defined path.
    cmd = loadExec();
    var resultCmd = cmd(
      'aws s3 sync s3://sd-scrapbook/thumbs ' +
      Meteor.settings.public.installPath +
      '/meteor/public/images/s3/thumbs', {}
    );
    return resultCmd;
  },

  getLatestImageOriginals: function () {
    // Customizable path for the application. Allows us to download the images
    // from S3 to any defined path.
    cmd = loadExec();
    var resultCmd = cmd(
      'aws s3 sync s3://sd-scrapbook/originals ' +
      Meteor.settings.public.installPath +
      '/meteor/public/images/s3/originals', {}
    );
    return resultCmd;
  },

  getLatestImageData: function () {
    // Sync down the images.json database file from S3. A server process
    // saves this file there. We use it to repopulate the database after
    // Meteor reset. This way, the local kiosk application always gets the
    // latest data from the server each time the application starts up.
    cmd = loadExec();
    var resultCmd = cmd(
      'aws s3 sync s3://sd-scrapbook/db ' +
      Meteor.settings.public.installPath +
      '/meteor/private', {}
    );
    return resultCmd;
  },

});

/**
 * Load modules for executing external commands
 *
 * Sets up a function (cmd) that allows us to call exec calls on the server
 * side, so that we can set up file assets before modifying the database.
 */
function loadExec() {
  fs = Npm.require('fs');
  exec = Npm.require('child_process').exec;
  cmd = Meteor.wrapAsync(exec);
  return cmd;
}

/**
* If the images collection has been reset, reload the latest data from a local
* JSON file.
*
* This process is used in the kiosk update from the remote version of the
* tool. When the kiosk starts up each morning we reset the database and
* then load the latest data from the online database if it has changed.
*
* The download process for this file is not handled within this application.
*/
function importImages() {
  if (Images.find().count() === 0) {
    console.log('Importing private/images.json to db');
    var data = JSON.parse(Assets.getText('images.json'));
    data.forEach(function (item, index, array) {
      Images.insert(item);
    });
  }
}

/**
* Sync images and the images table from the online database before
* launching the Meteor application
*/
if (Meteor.isServer) {

  /**
  * Kiosk mode
  *
  * If in Kioks mode, try and sync the images and images data down to the
  * local copy of the application from the online editor.
  */
  if (
    Meteor.settings &&
    Meteor.settings.public &&
    Meteor.settings.public.kiosk == 'true'
  ) {

    Meteor.call('getLatestImageThumbs', function (error, response) {
      if (error) {
        console.log(error);
      } else {
        console.log(response);
      }
    });

    Meteor.call('getLatestImageOriginals', function (error, response) {
      if (error) {
        console.log(error);
      } else {
        console.log(response);
      }
    });

    Meteor.call('getLatestImageData', function (error, response) {
      if (error) {
        console.log(error);
      } else {
        console.log(response);
      }
    });

    /**
     * Load data into the local database if none is present
     */
    importImages();

    /**
    * Locations
    */
    Locations.remove({});
    if (Locations.find().count() === 0) {

      var anzaBorrego = Locations.insert({
        title: 'Anza Borrego',
        link: 'anza-borrego',
        description: 'Anza-Borrego Desert State Park (ABDSP) is a state park ' +
          'located within the Colorado Desert of southern California, United States.',
        latitude: '33.100595',
        longitude: '-116.151306',
        dsLocId: '1',
      });

      var clevelandNationalForest = Locations.insert({
        title: 'Cleveland National Forest',
        link: 'cleveland-nat',
        description: 'Cleveland National Forest encompasses 460,000 acres ' +
          '(720 sq mi (1,900 km2)), mostly of chaparral, with a few riparian areas.',
        latitude: '32.758856',
        longitude: '-116.674749',
        dsLocId: '2',
      });

      var coloradoRiver = Locations.insert({
        title: 'Colorado River',
        link: 'colorado-river',
        description: '',
        latitude: '33.410193',
        longitude: '-114.693563',
        dsLocId: '3',
      });

      var imperialValley = Locations.insert({
        title: 'Imperial Valley',
        link: 'imperial-valley',
        description: '',
        latitude: '32.793580',
        longitude: '-114.973715',
        dsLocId: '4',
      });

      var joshuaTree = Locations.insert({
        title: 'Joshua Tree',
        link: 'joshua-tree',
        description: '',
        latitude: '33.795570',
        longitude: '-115.621892',
        dsLocId: '5',
      });

      var sdNorthCoast = Locations.insert({
        title: 'San Diego - North Coast',
        link: 'san-diego-north',
        description: '',
        latitude: '32.968837',
        longitude: '-117.254309',
        dsLocId: '6',
      });

      // This isn't visible because of the map cropping
      var mojaveDesert = Locations.insert({
        title: 'Mojave Desert',
        link: 'mojave-desert',
        description: '',
        latitude: '34.336705',
        longitude: '-115.899297',
        dsLocId: '7',
      });

      var northSDCounty = Locations.insert({
        title: 'North San Diego County',
        link: 'north-san-diego-county',
        description: '',
        latitude: '33.366311',
        longitude: '-117.214997',
        dsLocId: '8',
      });

      var orangeCounty = Locations.insert({
        title: 'Orange County',
        link: 'orange-county',
        description: '',
        latitude: '33.810516',
        longitude: '-117.820227',
        dsLocId: '9',
      });

      var palomarMountain = Locations.insert({
        title: 'Palomar Mountain',
        link: 'palomar-mountain',
        description: '',
        latitude: '33.398098',
        longitude: '-116.781367',
        dsLocId: '10',
      });

      var saltonSea = Locations.insert({
        title: 'Salton Sea',
        link: 'salton-sea',
        description: '',
        latitude: '33.287301',
        longitude: '-115.529622',
        dsLocId: '11',
      });

      var sanBerardino = Locations.insert({
        title: 'San Bernardino Mountains',
        link: 'san-bernardino',
        description: '',
        latitude: '34.131438',
        longitude: '-116.538973',
        dsLocId: '12',
      });

      var sanDiegoCoast = Locations.insert({
        title: 'San Diego - Coast',
        link: 'san-diego-coast',
        description: '',
        latitude: '32.694081',
        longitude: '-117.232840',
        dsLocId: '13',
      });

      var sanDiegoInland = Locations.insert({
        title: 'San Diego - Inland',
        link: 'san-diego-inland',
        description: '',
        latitude: '32.832099',
        longitude: '-117.097372',
        dsLocId: '14',
      });

      var sanGabriel = Locations.insert({
        title: 'San Gabriel Mountains',
        link: 'san-gabriel',
        description: '',
        latitude: '34.3288927',
        longitude: '-118.04672',
        dsLocId: '15',
      });

      var sanJacinto = Locations.insert({
        title: 'San Jacinto Mountains',
        link: 'san-jacinto',
        description: '',
        latitude: '33.8418194',
        longitude: '-116.9809458',
        dsLocId: '16',
      });

      var santaMonica = Locations.insert({
        title: 'Santa Monica Mountains and Coast',
        link: 'santa-monica',
        description: '',
        latitude: '33.923742',
        longitude: '-118.816882',
        dsLocId: '17',
      });

      var southSDCounty = Locations.insert({
        title: 'South San Diego County',
        link: 'south-san-diego',
        description: '',
        latitude: '32.536355',
        longitude: '-116.301214',
        dsLocId: '18',
      });

      var losAngeles = Locations.insert({
        title: 'Los Angeles',
        link: 'los-angeles',
        description: '',
        latitude: '33.663533',
        longitude: '-118.293658',
        dsLocId: '19',
      });

      var riverside = Locations.insert({
        title: 'Riverside',
        link: 'riverside',
        description: '',
        latitude: '33.894096',
        longitude: '-117.357879',
        dsLocId: '20',
      });

      var channelIslands = Locations.insert({
        title: 'Channel Islands',
        link: 'channel-islands',
        description: '',
        latitude: '33.823736',
        longitude: '-119.687298',
        dsLocId: '21',
      });

    }

  }
}
<|endoftext|>


<commit_before>var moderatorProfilePageSize = DEFAULT_PAGE_SIZE;
var moderatorProfileCurrPageNumber = 0;

var moderatorProfileSortDirection = false;
var moderatorProfileOrderBy = MODERATOR_PROFIL_DEFAULT_SORT_FIELD;

$(document).ready(function() {
    showUsersProfiles();
    populateConflictTable();

    $('#moderator_profilesnum').on('change', function() {
        moderatorProfilePageSize = $('#moderator_profilesnum').val();
        moderatorProfileCurrPageNumber = 0;
        showProfilesPage(moderatorProfileCurrPageNumber);
    });

    $("#moderator_profile_title").click(function(){
        sortUsersProfiles("firstName","moderator_profile_title");
    });

    $("#moderator_profile_login").click(function(){
        sortUsersProfiles("user.login","moderator_profile_login");
    });

    $("#moderator_profile_telephone").click(function(){
        sortUsersProfiles("telephone","moderator_profile_telephone");
    });

    $('#search_profiles').keypress(function(e) {
        if (e.keyCode == ENTER_BUTTON_CODE) {
            showUsersProfiles();
            return false;
        }
    });
});

function showUsersProfiles() {
    var queryParams = '';

    if($('#search_profiles').val()!=""){
        queryParams += (queryParams.length==0)?"searchParam="+$('#search_profiles').val():"&searchParam="+$('#search_profiles').val();
    }

    showProfilesPagination(queryParams);

    queryParams += (queryParams.length==0)?"pageSize="+moderatorProfilePageSize:"&pageSize="+moderatorProfilePageSize;
    queryParams += "&pageNumber=" + moderatorProfileCurrPageNumber + "&sortDirection=" +
        ((moderatorProfileSortDirection)?"desc":"asc") + "&orderBy=" + moderatorProfileOrderBy;

    $.ajax({
        url: MODERATOR_PROFILE_DATA_URL,
        type: "GET",
        data:  queryParams,
        async: false,
        dataType:'json',

        success: function(data) {
            var html = '';
            var dataSize = data.length;

            if(dataSize > 0) {
                for (var i = 0; i < dataSize; i++) {
                    html += '
' + data[i].firstName + ' ' + data[i].lastName + '	' +
                        '' + data[i].userLogin + '	' +
                        '' + data[i].telephone + '	' +
                        '' +
                        '
' +
                        '<button data-toggle="dropdown" class="btn btn-default dropdown-toggle">Status</button>' +
                        '
' +
                        '
Unchecked
' +
                        '
Checked
' +
                        '
In progress
' +
                        '
Denied
' +
                        '
' +
                        '
' +
                        '
';
                }

                $('#moderator_profile_message').html('');
                $('#moderator_profile_items').show();
                $('#moderator_profiles').html(html);
                $('#moderator_profile_pagination').show();
            } else {
                $('#moderator_profile_message').html('
No profiles found
').show();
                $('#moderator_profile_items').hide();
                $('#moderator_profile_pagination').hide();
            }
        }
    });
}

function addConfirmListender(buttonId,userId,status) {
    $("#"+buttonId).unbind('click');
    $("#"+buttonId).click(function(){
        setProfileStatus(userId, status);
        $("#moderator_profile_status").modal('hide');
    });
}

function setProfileStatus(userId, statusName) {
    var queryParams = 'statusName='+statusName;

    $.ajax({
        url: MODERATOR_PROFILE_STATUS_URL + '/' + userId,
        type: "POST",
        data:  queryParams,
        dataType:'json',

        success: function(data) {
            showUsersProfiles();
        }
    });
}

function populateConflictTable() {
    $.getJSON(MODERATOR_URL + CONFLICTS, function (data) {
        var html = '';
        var len = data.length;
        for (var i = 0; i < len; i++) {
            html += '
' + data[i].title + '	' +
                '' + data[i].customerName + '	' +
                '' + data[i].sellerName + '	' +
                '<button class="btn btn-default" type="button">Action</button>
';
        }

        $('#conflict_table').html(html);
    });
}

function showProfilesPagination(queryParams) {
    $.ajax({
        url: MODERATOR_PROFILES_NUMBER_URL,
        async: false,
        type: "GET",
        data:  queryParams,
        dataType:'json',

        success: function(data) {
            var dataSize = data.profilesNumber;
            var pageNumber = Math.ceil(dataSize / moderatorProfilePageSize);

            if(dataSize > 0 && moderatorProfilePageSize < dataSize) {
                var html = '';
                html += '
«
';
                for(var z=1;z<=pageNumber;z++) {
                    html += '
'+z+'
';
                }
                html += '
»
';

                $('.moderator_profile_page_pagination').html(html).show();
                $('#moderator_profile_pagination').show();

                if(moderatorProfileCurrPageNumber != 0) {
                    document.getElementById('profiles_prev_page').setAttribute("onclick", "showProfilesPage("+(moderatorProfileCurrPageNumber-1)+");");
                }

                if(moderatorProfileCurrPageNumber != pageNumber-1) {
                    document.getElementById('profiles_next_page').setAttribute("onclick", "showProfilesPage("+(moderatorProfileCurrPageNumber+1)+");");
                }
            } else {
                $('#moderator_profile_pagination').hide();
            }
        },
        error:function(){
            $('#moderator_profile_pagination').hide();
        }
    });
}

function showProfilesPage(pageNumber) {
    moderatorProfileCurrPageNumber = pageNumber;
    showUsersProfiles();
}

function sortUsersProfiles(orderByField, elementId) {
    moderatorProfileSortDirection = (moderatorProfileOrderBy == orderByField) ? !moderatorProfileSortDirection : false;
    moderatorProfileOrderBy = orderByField;

    $('#moderator_profile_items .sortable').removeClass('glyphicon-chevron-up').removeClass('glyphicon-chevron-down');
    if(moderatorProfileSortDirection == false) {
        $('#'+elementId+' .sortable').addClass('glyphicon-chevron-up').removeClass('glyphicon-chevron-down');
    } else {
        $('#'+elementId+' .sortable').addClass('glyphicon-chevron-down').removeClass('glyphicon-chevron-up');
    }

    showUsersProfiles();
}
<commit_msg>Fixed bug<commit_after>var moderatorProfilePageSize = DEFAULT_PAGE_SIZE;
var moderatorProfileCurrPageNumber = 0;

var moderatorProfileSortDirection = false;
var moderatorProfileOrderBy = MODERATOR_PROFIL_DEFAULT_SORT_FIELD;
var ENTER_BUTTON_CODE = 13;

$(document).ready(function() {
    showUsersProfiles();
    populateConflictTable();

    $('#moderator_profilesnum').on('change', function() {
        moderatorProfilePageSize = $('#moderator_profilesnum').val();
        moderatorProfileCurrPageNumber = 0;
        showProfilesPage(moderatorProfileCurrPageNumber);
    });

    $("#moderator_profile_title").click(function(){
        sortUsersProfiles("firstName","moderator_profile_title");
    });

    $("#moderator_profile_login").click(function(){
        sortUsersProfiles("user.login","moderator_profile_login");
    });

    $("#moderator_profile_telephone").click(function(){
        sortUsersProfiles("telephone","moderator_profile_telephone");
    });

    $('#search_profiles').keypress(function(e) {
        if (e.keyCode == ENTER_BUTTON_CODE) {
            moderatorProfilePageSize = $('#moderator_profilesnum').val();
            moderatorProfileCurrPageNumber = 0;
            showProfilesPage(moderatorProfileCurrPageNumber);
            return false;
        }
    });
});

function showUsersProfiles() {
    var queryParams = '';

    if($('#search_profiles').val()!=""){
        queryParams += (queryParams.length==0)?"searchParam="+$('#search_profiles').val():"&searchParam="+$('#search_profiles').val();
    }

    showProfilesPagination(queryParams);

    queryParams += (queryParams.length==0)?"pageSize="+moderatorProfilePageSize:"&pageSize="+moderatorProfilePageSize;
    queryParams += "&pageNumber=" + moderatorProfileCurrPageNumber + "&sortDirection=" +
        ((moderatorProfileSortDirection)?"desc":"asc") + "&orderBy=" + moderatorProfileOrderBy;

    $.ajax({
        url: MODERATOR_PROFILE_DATA_URL,
        type: "GET",
        data:  queryParams,
        async: false,
        dataType:'json',

        success: function(data) {
            var html = '';
            var dataSize = data.length;

            if(dataSize > 0) {
                for (var i = 0; i < dataSize; i++) {
                    html += '
' + data[i].firstName + ' ' + data[i].lastName + '	' +
                        '' + data[i].userLogin + '	' +
                        '' + data[i].telephone + '	' +
                        '' +
                        '
' +
                        '<button data-toggle="dropdown" class="btn btn-default dropdown-toggle">Status</button>' +
                        '
' +
                        '
Unchecked
' +
                        '
Checked
' +
                        '
In progress
' +
                        '
Denied
' +
                        '
' +
                        '
' +
                        '
';
                }

                $('#moderator_profile_message').html('');
                $('#moderator_profile_items').show();
                $('#moderator_profiles').html(html);
                $('#moderator_profile_pagination').show();
            } else {
                $('#moderator_profile_message').html('
No profiles found
').show();
                $('#moderator_profile_items').hide();
                $('#moderator_profile_pagination').hide();
            }
        }
    });
}

function addConfirmListender(buttonId,userId,status) {
    $("#"+buttonId).unbind('click');
    $("#"+buttonId).click(function(){
        setProfileStatus(userId, status);
        $("#moderator_profile_status").modal('hide');
    });
}

function setProfileStatus(userId, statusName) {
    var queryParams = 'statusName='+statusName;

    $.ajax({
        url: MODERATOR_PROFILE_STATUS_URL + '/' + userId,
        type: "POST",
        data:  queryParams,
        dataType:'json',

        success: function(data) {
            showUsersProfiles();
        }
    });
}

function populateConflictTable() {
    $.getJSON(MODERATOR_URL + CONFLICTS, function (data) {
        var html = '';
        var len = data.length;
        for (var i = 0; i < len; i++) {
            html += '
' + data[i].title + '	' +
                '' + data[i].customerName + '	' +
                '' + data[i].sellerName + '	' +
                '<button class="btn btn-default" type="button">Action</button>
';
        }

        $('#conflict_table').html(html);
    });
}

function showProfilesPagination(queryParams) {
    $.ajax({
        url: MODERATOR_PROFILES_NUMBER_URL,
        async: false,
        type: "GET",
        data:  queryParams,
        dataType:'json',

        success: function(data) {
            var dataSize = data.profilesNumber;
            var pageNumber = Math.ceil(dataSize / moderatorProfilePageSize);

            if(dataSize > 0 && moderatorProfilePageSize < dataSize) {
                var html = '';
                html += '
«
';
                for(var z=1;z<=pageNumber;z++) {
                    html += '
'+z+'
';
                }
                html += '
»
';

                $('.moderator_profile_page_pagination').html(html).show();
                $('#moderator_profile_pagination').show();

                if(moderatorProfileCurrPageNumber != 0) {
                    document.getElementById('profiles_prev_page').setAttribute("onclick", "showProfilesPage("+(moderatorProfileCurrPageNumber-1)+");");
                }

                if(moderatorProfileCurrPageNumber != pageNumber-1) {
                    document.getElementById('profiles_next_page').setAttribute("onclick", "showProfilesPage("+(moderatorProfileCurrPageNumber+1)+");");
                }
            } else {
                $('.moderator_profile_page_pagination').html('').hide();
                $('#moderator_profile_pagination').hide();
            }
        },
        error:function(){
            $('#moderator_profile_pagination').hide();
        }
    });
}

function showProfilesPage(pageNumber) {
    moderatorProfileCurrPageNumber = pageNumber;
    showUsersProfiles();
}

function sortUsersProfiles(orderByField, elementId) {
    moderatorProfileSortDirection = (moderatorProfileOrderBy == orderByField) ? !moderatorProfileSortDirection : false;
    moderatorProfileOrderBy = orderByField;

    $('#moderator_profile_items .sortable').removeClass('glyphicon-chevron-up').removeClass('glyphicon-chevron-down');
    if(moderatorProfileSortDirection == false) {
        $('#'+elementId+' .sortable').addClass('glyphicon-chevron-up').removeClass('glyphicon-chevron-down');
    } else {
        $('#'+elementId+' .sortable').addClass('glyphicon-chevron-down').removeClass('glyphicon-chevron-up');
    }

    showUsersProfiles();
}
<|endoftext|>


<commit_before>/* globals describe it beforeEach */
'use strict'

const chai = require('chai')
const requireInject = require('require-inject')
const sinon = require('sinon')
const sinonChai = require('sinon-chai')

const expect = chai.expect
chai.use(sinonChai)

describe('main', function () {
  let stubs
  let getUrl
  let git
  let github
  let logger
  let parseArguments

  beforeEach('create stubs', function () {
    getUrl = sinon.stub().returns('some url')
    git = {
      getSemverTags: sinon.stub()
    }
    github = sinon.spy()
    logger = {
      debug: sinon.spy(),
      info: sinon.spy(),
      error: sinon.spy()
    }
    parseArguments = sinon.stub().returns({
      logLevel: 'debug'
    })
    stubs = {}
    stubs[require.resolve('../lib/arguments')] = {
      parseArguments
    }
    stubs[require.resolve('../lib/git')] = git
    stubs[require.resolve('../lib/github')] = github
    stubs[require.resolve('../lib/logging')] = {
      logger
    }
    stubs[require.resolve('../lib/util')] = {
      getUrl
    }
  })

  it('exits when no tags are found in repository', function () {
    git.getSemverTags.returns([])
    const main = requireInject('../lib/main', stubs)
    expect(main()).to.equal(1)
    expect(logger.error).to.have.been.calledWith('No tags found in repository')
  })
})
<commit_msg>Add semver compliant tag test<commit_after>/* globals describe it beforeEach */
'use strict'

const chai = require('chai')
const requireInject = require('require-inject')
const sinon = require('sinon')
const sinonChai = require('sinon-chai')

const expect = chai.expect
chai.use(sinonChai)

describe('main', function () {
  let stubs
  let getUrl
  let git
  let github
  let logger
  let parseArguments

  beforeEach('create stubs', function () {
    getUrl = sinon.stub().returns('some url')
    git = {
      getSemverTags: sinon.stub()
    }
    github = sinon.spy()
    logger = {
      debug: sinon.spy(),
      info: sinon.spy(),
      error: sinon.spy()
    }
    parseArguments = sinon.stub()
    stubs = {}
    stubs[require.resolve('../lib/arguments')] = {
      parseArguments
    }
    stubs[require.resolve('../lib/git')] = git
    stubs[require.resolve('../lib/github')] = github
    stubs[require.resolve('../lib/logging')] = {
      logger
    }
    stubs[require.resolve('../lib/util')] = {
      getUrl
    }
  })

  it('returns when no tags are found in repository', function () {
    git.getSemverTags.returns([])
    parseArguments.returns({logLevel: 'debug'})
    const main = requireInject('../lib/main', stubs)
    expect(main()).to.equal(1)
    expect(logger.error).to.have.been.calledWith('No tags found in repository')
  })

  it('returns when tag is not semver compliant', function () {
    git.getSemverTags.returns(['a tag', 'another tag'])
    const tag = 'not a semver tag'
    parseArguments.returns({
      logLevel: 'debug',
      tag
    })
    const main = requireInject('../lib/main', stubs)
    expect(main()).to.equal(1)
    expect(logger.error).to.have.been.calledWith(
      'Tag not semver compliant: %s', tag)
  })
})
<|endoftext|>


<commit_before>'use strict';

const assert = require('assert');

describe('Chat', function () {
	it('should run formatText correctly', function () {
		assert.strictEqual(
			Chat.formatText(`hi **__bold italics__** ^^superscript^^ \\\\subscript\\\\ bye`),
			`hi <b><i>bold italics</i></b> <sup>superscript</sup> <sub>subscript</sub> bye`
		);
		assert.strictEqual(
			Chat.formatText(`hi \`\` \` \`\` bye`),
			`hi <code>\`</code> bye`
		);
		assert.strictEqual(
			Chat.formatText(`hi \`\`inside __not__ formatted\`\` bye`),
			`hi <code>inside __not__ formatted</code> bye`
		);
		// assert.strictEqual(
		// 	Chat.formatText(`hi spoiler: bye`),
		// 	`hi <span class="spoiler">bye</span>`
		// );
		// assert.strictEqual(
		// 	Chat.formatText(`hi google.com/__a__ bye`),
		// 	`hi <a href="google.com/__a__">google.com/__a__</a> bye`
		// );
	});
});
<commit_msg>Improve chat formatter tests<commit_after>'use strict';

const assert = require('assert');

describe('Chat', function () {
	it('should run formatText correctly', function () {
		assert.strictEqual(
			Chat.formatText(`hi **__bold italics__** ^^superscript^^ \\\\subscript\\\\ normal ~~strikethrough~~ bye`),
			`hi <b><i>bold italics</i></b> <sup>superscript</sup> <sub>subscript</sub> normal <s>strikethrough</s> bye`
		);
		assert.strictEqual(
			Chat.formatText(`__**reverse nesting**__`),
			`<i><b>reverse nesting</b></i>`
		);
		assert.strictEqual(
			Chat.formatText(`__**bad nesting__**`),
			`<i>**bad nesting</i>**`
		);
		assert.strictEqual(
			Chat.formatText(`hi \`\` \` \`\` bye`),
			`hi <code>\`</code> bye`
		);
		assert.strictEqual(
			Chat.formatText(`hi \`\`inside __not__ formatted\`\` bye`),
			`hi <code>inside __not__ formatted</code> bye`
		);
		// assert.strictEqual(
		// 	Chat.formatText(`hi spoiler: bye`),
		// 	`hi <span class="spoiler">bye</span>`
		// );
		// assert.strictEqual(
		// 	Chat.formatText(`hi google.com/__a__ bye`),
		// 	`hi <a href="google.com/__a__">google.com/__a__</a> bye`
		// );
	});
});
<|endoftext|>


<commit_before>angular.module('exploreModule')
.controller('exploreCtrl', function($scope, queryAPI, $rootScope, $ionicLoading, $rootScope) {

  $scope.pageLoading = {
    status: true,
    loading: $ionicLoading.show({
      template: '

',
      noBackdrop: false
    })
  }

  queryAPI.getTags()
  .then(function(data) {
    if(data.status.code === 100) {
      $scope.pageLoading.status = false;
      $ionicLoading.hide();

      $rootScope.categoryList = [];
      var tags = data.result;

      $rootScope.categoryListFull = {};
      var lookupParent = {};
      for (var tag in tags) {
        obj = tags[tag];
        if (obj.parent === "0") {
          $rootScope.categoryList.push(obj);
          $rootScope.categoryList[$rootScope.categoryList.length-1].children = [];
          lookupParent[obj.term_id] = obj;
          lookupParent[obj.term_id].elementInArray = $rootScope.categoryList.length-1;
        };

        $rootScope.categoryListFull[obj.slug] = obj;
      };

      for (var tag in tags) {
        obj = tags[tag];
        if (lookupParent[obj.parent]) {
          $rootScope.categoryList[lookupParent[obj.parent].elementInArray].children.push(obj);
        };
      };

      $rootScope.categoryList = queryAPI.cleanCategory($rootScope.categoryList);
      queryAPI.setCategoryColors();

    } else {
      $scope.pageLoading.status = false;
      $ionicLoading.hide();
      $rootScope.categoryList = [];
      console.log('Error retrieving Tags: ' + data.status.code);
    }
  }, function (status) {
    $scope.pageLoading.status = false;
    $ionicLoading.hide();
    $rootScope.categoryList = [];
    console.log(status);
  });

});
<commit_msg>Filling tag list with bookmarked or not<commit_after>angular.module('exploreModule')
.controller('exploreCtrl', function($scope, queryAPI, $rootScope, $ionicLoading, $rootScope) {

  $scope.pageLoading = {
    status: true,
    loading: $ionicLoading.show({
      template: '

',
      noBackdrop: false
    })
  }

  queryAPI.getTags()
  .then(function(data) {
    if(data.status.code === 100) {
      $scope.pageLoading.status = false;
      $ionicLoading.hide();

      $rootScope.categoryList = [];
      var tags = data.result;

      $rootScope.categoryListFull = {};
      var lookupParent = {};
      for (var tag in tags) {
        obj = tags[tag];

        if ($rootScope.userData.pc_tags.indexOf(obj.slug) === -1) {
          console.log('not bookmarked: ' + obj.slug);
          obj.bookmarked = false;
        } else {
          console.log('bookmarked: ' + obj.slug);
          obj.bookmarked = true;
        }

        if (obj.parent === "0") {
          $rootScope.categoryList.push(obj);
          $rootScope.categoryList[$rootScope.categoryList.length-1].children = [];
          lookupParent[obj.term_id] = obj;
          lookupParent[obj.term_id].elementInArray = $rootScope.categoryList.length-1;
        };

        $rootScope.categoryListFull[obj.slug] = obj;
      };

      for (var tag in tags) {
        obj = tags[tag];
        if (lookupParent[obj.parent]) {
          $rootScope.categoryList[lookupParent[obj.parent].elementInArray].children.push(obj);
        };
      };

      $rootScope.categoryList = queryAPI.cleanCategory($rootScope.categoryList);
      queryAPI.setCategoryColors();

    } else {
      $scope.pageLoading.status = false;
      $ionicLoading.hide();
      $rootScope.categoryList = [];
      console.log('Error retrieving Tags: ' + data.status.code);
    }
  }, function (status) {
    $scope.pageLoading.status = false;
    $ionicLoading.hide();
    $rootScope.categoryList = [];
    console.log(status);
  });

});
<|endoftext|>


<commit_before>/* eslint-disable import/no-commonjs */

const { ErrorWithStack } = require('jest-util');
const JSDOMEnvironment = require('jest-environment-jsdom');

class CustomEnvironment extends JSDOMEnvironment {
  constructor(config, context) {
    super(config, context);

    Object.assign(context.console, {
      error(...args) {
        throw new ErrorWithStack(
          `Unexpected call of console.error() with:\n\n${args.join(', ')}`,
          this.error,
        );
      },

      warn(...args) {
        throw new ErrorWithStack(
          `Unexpected call of console.warn() with:\n\n${args.join(', ')}`,
          this.warn,
        );
      },
    });

    const { testEnvironmentOptions } = config;
    const { IS_EE } = testEnvironmentOptions;
    this.global.gon = {
      ee: IS_EE,
    };

    this.rejectedPromises = [];

    this.global.promiseRejectionHandler = error => {
      this.rejectedPromises.push(error);
    };

    this.global.fixturesBasePath = `${process.cwd()}/${
      IS_EE ? 'ee/' : ''
    }spec/javascripts/fixtures`;

    // Not yet supported by JSDOM: https://github.com/jsdom/jsdom/issues/317
    this.global.document.createRange = () => ({
      setStart: () => {},
      setEnd: () => {},
      commonAncestorContainer: {
        nodeName: 'BODY',
        ownerDocument: this.global.document,
      },
    });
  }

  async teardown() {
    await new Promise(setImmediate);

    if (this.rejectedPromises.length > 0) {
      throw new ErrorWithStack(
        `Unhandled Promise rejections: ${this.rejectedPromises.join(', ')}`,
        this.teardown,
      );
    }

    await super.teardown();
  }
}

module.exports = CustomEnvironment;
<commit_msg>Prefer an absolute path over cwd()<commit_after>/* eslint-disable import/no-commonjs */

const path = require('path');
const { ErrorWithStack } = require('jest-util');
const JSDOMEnvironment = require('jest-environment-jsdom');

const ROOT_PATH = path.resolve(__dirname, '../..');

class CustomEnvironment extends JSDOMEnvironment {
  constructor(config, context) {
    super(config, context);

    Object.assign(context.console, {
      error(...args) {
        throw new ErrorWithStack(
          `Unexpected call of console.error() with:\n\n${args.join(', ')}`,
          this.error,
        );
      },

      warn(...args) {
        throw new ErrorWithStack(
          `Unexpected call of console.warn() with:\n\n${args.join(', ')}`,
          this.warn,
        );
      },
    });

    const { testEnvironmentOptions } = config;
    const { IS_EE } = testEnvironmentOptions;
    this.global.gon = {
      ee: IS_EE,
    };

    this.rejectedPromises = [];

    this.global.promiseRejectionHandler = error => {
      this.rejectedPromises.push(error);
    };

    this.global.fixturesBasePath = `${ROOT_PATH}/${IS_EE ? 'ee/' : ''}spec/javascripts/fixtures`;

    // Not yet supported by JSDOM: https://github.com/jsdom/jsdom/issues/317
    this.global.document.createRange = () => ({
      setStart: () => {},
      setEnd: () => {},
      commonAncestorContainer: {
        nodeName: 'BODY',
        ownerDocument: this.global.document,
      },
    });
  }

  async teardown() {
    await new Promise(setImmediate);

    if (this.rejectedPromises.length > 0) {
      throw new ErrorWithStack(
        `Unhandled Promise rejections: ${this.rejectedPromises.join(', ')}`,
        this.teardown,
      );
    }

    await super.teardown();
  }
}

module.exports = CustomEnvironment;
<|endoftext|>