<commit_before>(function ()
{
  var connector;
  var connectorInfo = { name: "memory", isSynced: false };

  module("connector",
    {
      setup: function()
      {
        var con = shownoteseditor.connectors[connectorInfo.name];
        connector = new con({}, function (){});
      },
      teardown: function()
      {
        connector = null;
      }
    }
  );

  test("findParent - basic",
    function ()
    {
      var root = { notes: {} };
      connector.findParent("", root);
      ok(true);
    }
  );

  test("findParent - 1 deep",
    function ()
    {
      var root = { notes: { "a": { notes: {} } } };
      var parent = connector.findParent("a", root);
      equal(parent, root);
    }
  );

  test("findParent - 2 deep",
    function ()
    {
      var innerNote = { notes: { "b": { notes: {} } } };
      var root = { notes: { "a": innerNote  } };

      var parent = connector.findParent("b", root);
      deepEqual(parent, innerNote);
    }
  );

  test("findParent - not found",
    function ()
    {
      var root = { notes: { "a": { notes: { } }  } };

      var parent = connector.findParent("b", root);
      equal(parent, null);
    }
  );

  test("findParent - multiple",
    function ()
    {
      var innerNote = { notes: { "c": { notes: {} }, "b": { notes: {} } } };
      var root = { notes: { "a": innerNote  } };

      var parent = connector.findParent("b", root);
      deepEqual(innerNote, parent);
    }
  );

  asyncTest("addNote callback",
    function ()
    {
      connector.addNote({},
        function (err, id)
        {
          ok(!err);
          ok(id);
          start();
        }
      );
    }
  );

  asyncTest("addNote event - root",
    function ()
    {
      var addNote = { time: 0, tags: [], text: "b" };
      var called = false;

      connector.bind("noteAdded",
        function (index, note, parentId)
        {
          if(called)
          {
            console.error("addNote event called twice")
            ok(false);
          }

          called = true;
          ok(index, "event - id");
          deepEqual(note, addNote, "event - note ok");
          equal(parentId, "_root", "event - parentId ok");
          start();
        }
      );

      connector.addNote(addNote, function () {});
    }
  );

  asyncTest("addNote event - invalid parent",
    function ()
    {
      connector.addNote({}, "foo",
        function (err)
        {
          equal(err, "parent not found");
          start();
        }
      );
    }
  );

  asyncTest("addNote event - deep",
    function ()
    {
      var addNote1 = { time: 0, tags: [], text: "b1" };
      var addNote2 = { time: 0, tags: [], text: "b2" };
      var called = 0;
      var outerId;

      connector.bind("noteAdded",
        function (index, note, parentId)
        {
          called++;

          if(called == 1)
          {
            // skip first note
            return;
          }
          else if(called > 2)
          {
            console.error("addNote event called trice or more")
            ok(false);
          }

          ok(index, "event - id");
          deepEqual(note, addNote2, "event - note ok");
          equal(parentId, outerId, "event - parentId ok");
          start();
        }
      );

      connector.addNote(addNote1,
        function (err, id)
        {
          outerId = id;
          connector.addNote(addNote2, id, function () {});
        }
      );
    }
  );

  asyncTest("addNote - 1 deep",
    function ()
    {
      var note = { time: 0, tags: [], text: "b" };

      connector.addNote(note,
        function (err, id)
        {
          connector.getNote(id, function (err, gotNote)
            {
              deepEqual(gotNote, note, "Right note added");
              start();
            }
          );
        }
      );
    }
  );

  asyncTest("addNote - 2 deep",
    function ()
    {
      var outerNote = { time: 0, tags: [], text: "b1" };
      var innerNote = { time: 0, tags: [], text: "b2" };
      var outerId;
      var innerId;

      async.series(
        [
          function (cb)
          {
            connector.addNote(outerNote,
              function (err, id)
              {
                outerId = id;
                cb(err);
              }
            );
          },
          function (cb)
          {
            connector.addNote(innerNote, outerId,
              function (err, id)
              {
                innerId = id;
                cb(err);
              }
            );
          },
          function (cb)
          {
            connector.getNotes(function (err, notes)
              {
                var root;

                root = notes.notes;
                var keys = Object.keys(root);
                equal(keys.length, 1, "level 1 - One note added");
                deepEqual(root[outerId].text, outerNote.text, "level 1 - Right note added");

                root = notes.notes[outerId].notes;
                var keys = Object.keys(root);
                equal(keys.length, 1, "level 2 - One note added");
                deepEqual(root[innerId].text, innerNote.text, "level 2 - Right note added");

                cb();
              }
            );
          }
        ],
        start
      );
    }
  );

  asyncTest("removeNote callback",
    function ()
    {
      connector.addNote({ a: "b3", notes: {} },
        function (err, id)
        {
          connector.removeNote(id,
            function ()
            {
              ok(true);
              start();
            }
          );
        }
      );
    }
  );

  asyncTest("removeNote event",
    function ()
    {
      var addNote = { time: 0, tags: [], text: "b" };
      var called = false;
      var addedId = null;

      connector.bind("noteRemoved",
        function (id, note)
        {
          if(called)
          {
            console.error("removeNote callback called twice")
            ok(false);
          }

          called = true;
          equal(id, addedId, "event - index ok");
          deepEqual(note, addNote, "event - note ok");
          start();
        }
      );

      connector.addNote(addNote,
        function (err, id)
        {
          addedId = id;
          connector.removeNote(id, function () {});
        }
      );
    }
  );

  asyncTest("removeNote",
    function ()
    {
      var addNotes =
        [
          { time: 0, tags: [], text: "b1", notes: {} },
          { time: 0, tags: [], text: "b2" },
          { time: 0, tags: [], text: "b3", notes: {} }
        ];

      var ids = [];

      async.series(
        [
          function (cb)
          {
            async.eachSeries(addNotes,
              function (note, cb)
              {
                connector.addNote.call(connector,
                  note,
                  function (err, id)
                  {
                    ids.push(id);
                    cb();
                  }
                );
              },
              cb);
          },
          function (cb)
          {
            connector.removeNote(ids[1], cb); // remove b2
          },
          function (cb)
          {
            connector.getNotes(function (err, notes)
              {
                var keys = Object.keys(notes.notes);
                equal(keys.length, 2, "Note removed");
                deepEqual(notes.notes[keys[0]], addNotes[0], "Note 1 untouched");
                deepEqual(notes.notes[keys[1]], addNotes[2], "Note 3 untouched");
                cb();
              }
            );
          }
        ],
        start
      );
    }
  );

  asyncTest("removeNote - invalid index",
    function ()
    {
      connector.bind("noteRemoved",
        function (index, note)
        {
          ok(false, "Event fired");
        }
      );

      connector.removeNote("foo",
        function (err)
        {
          equal(err, "not found", "Error ok");
          start();
        }
      );
    }
  );

  asyncTest("editNote callback",
    function ()
    {
      connector.addNote({},
        function (err, id)
        {
          connector.editNote(id, { a: "b" },
            function ()
            {
              ok(true);
              start();
            }
          );
        }
      );
    }
  );

  asyncTest("editNote event",
    function ()
    {
      var addNote = { time: 0, tags: [], text: "val1" };
      var editedNote = { time: 0, tags: [], text: "val2" };
      var called = false;
      var addedId = null;

      connector.bind("noteEdited",
        function (id, note, changed)
        {
          if(called)
          {
            console.error("editNote callback called twice")
            ok(false);
          }

          called = true;
          equal(id, addedId, "event - id ok");
          deepEqual(note, editedNote, "event - note ok");
          deepEqual(changed, ["text"], "event - changed ok");
          start();
        }
      );

      connector.addNote(addNote,
        function (err, id)
        {
          addedId = id;
          connector.editNote(id, editedNote, function () {});
        }
      );
    }
  );

  asyncTest("editNote",
    function ()
    {
      var addNote = { time: 0, tags: [], text: "val1" };
      var editedNote = { time: 0, tags: [], text: "val2" };

      connector.addNote(addNote,
        function (err, id)
        {
          connector.editNote(id, editedNote,
            function (err)
            {
              connector.getNote(id, function (err, note)
                {
                  deepEqual(note, editedNote, "Note changed");
                  start();
                }
              );
            }
          );
        }
      );
    }
  );

  asyncTest("editNote - invalid id",
    function ()
    {
      connector.bind("noteEdited",
        function (id, note)
        {
          ok(false, "Event fired");
        }
      );

      connector.editNote(1, {},
        function (err)
        {
          equal(err, "not found", "Error ok");
          start();
        }
      );
    }
  );

  asyncTest("getNote",
    function ()
    {
      var addNote = { time: 0, tags: [], text: "val1" };

      connector.addNote(addNote,
        function (err, id)
        {
          connector.getNote(id,
            function (err, note)
            {
              deepEqual(addNote, note, "Right note returned");
              start();
            }
          );
        }
      );
    }
  );

  asyncTest("getNote - invalid id",
    function ()
    {
      connector.getNote("foo",
        function (err)
        {
          equal(err, "not found", "Error ok");
          start();
        }
      );
    }
  );

  test("getFriendlyJson",
    function ()
    {
      var input = {
        "notes":
        {
          "aaa":
          {
            "time": 20,
            "text": "a",
            "tags": [ "a", "b" ],
            "notes":
            {
              "aaa.1":
              {
                "time": 30,
                "text": "b",
                "tags": [],
                "notes": {}
              }
            }
          },
          "bbb":
          {
            "time": 40,
            "text": "c",
            "tags": [ "a", "b" ],
            "notes": {}
          }
        }
      };

      var expected = [
        {
          "time": 20,
          "text": "a",
          "tags": [ "a", "b" ],
          "notes":
            [
              {
                "time": 30,
                "text": "b",
                "tags": [],
                "notes": []
              }
            ]
        },
        {
          "time": 40,
          "text": "c",
          "tags": [ "a", "b" ],
          "notes": []
        }
      ];

      var actual = connector.getFriendlyJson(input);

      deepEqual(actual, expected);
    }
  );
})();
<commit_msg>fix connector tests<commit_after>(function ()
{
  var connector;
  var connectorInfo = { name: "memory", isSynced: false };

  module("connector",
    {
      setup: function()
      {
        var con = shownoteseditor.connectors[connectorInfo.name];
        connector = new con({}, function (){});
      },
      teardown: function()
      {
        connector = null;
      }
    }
  );

  test("findParent - basic",
    function ()
    {
      var root = { notes: {} };
      connector.findParent("", root);
      ok(true);
    }
  );

  test("findParent - 1 deep",
    function ()
    {
      var root = { notes: { "a": { notes: {} } } };
      var parent = connector.findParent("a", root);
      equal(parent, root);
    }
  );

  test("findParent - 2 deep",
    function ()
    {
      var innerNote = { notes: { "b": { notes: {} } } };
      var root = { notes: { "a": innerNote  } };

      var parent = connector.findParent("b", root);
      deepEqual(parent, innerNote);
    }
  );

  test("findParent - not found",
    function ()
    {
      var root = { notes: { "a": { notes: { } }  } };

      var parent = connector.findParent("b", root);
      equal(parent, null);
    }
  );

  test("findParent - multiple",
    function ()
    {
      var innerNote = { notes: { "c": { notes: {} }, "b": { notes: {} } } };
      var root = { notes: { "a": innerNote  } };

      var parent = connector.findParent("b", root);
      deepEqual(innerNote, parent);
    }
  );

  asyncTest("addNote callback",
    function ()
    {
      connector.addNote({},
        function (err, id)
        {
          ok(!err);
          ok(id);
          start();
        }
      );
    }
  );

  asyncTest("addNote event - root",
    function ()
    {
      var addNote = { time: 0, link: "", tags: [], text: "b" };
      var called = false;

      connector.bind("noteAdded",
        function (index, note, parentId)
        {
          if(called)
          {
            console.error("addNote event called twice")
            ok(false);
          }

          called = true;
          ok(index, "event - id");
          deepEqual(note, addNote, "event - note ok");
          equal(parentId, "_root", "event - parentId ok");
          start();
        }
      );

      connector.addNote(addNote, function () {});
    }
  );

  asyncTest("addNote event - invalid parent",
    function ()
    {
      connector.addNote({}, "foo",
        function (err)
        {
          equal(err, "parent not found");
          start();
        }
      );
    }
  );

  asyncTest("addNote event - deep",
    function ()
    {
      var addNote1 = { time: 0, link: "", tags: [], text: "b1" };
      var addNote2 = { time: 0, link: "", tags: [], text: "b2" };
      var called = 0;
      var outerId;

      connector.bind("noteAdded",
        function (index, note, parentId)
        {
          called++;

          if(called == 1)
          {
            // skip first note
            return;
          }
          else if(called > 2)
          {
            console.error("addNote event called trice or more")
            ok(false);
          }

          ok(index, "event - id");
          deepEqual(note, addNote2, "event - note ok");
          equal(parentId, outerId, "event - parentId ok");
          start();
        }
      );

      connector.addNote(addNote1,
        function (err, id)
        {
          outerId = id;
          connector.addNote(addNote2, id, function () {});
        }
      );
    }
  );

  asyncTest("addNote - 1 deep",
    function ()
    {
      var note = { time: 0, link: "", tags: [], text: "b" };

      connector.addNote(note,
        function (err, id)
        {
          connector.getNote(id, function (err, gotNote)
            {
              deepEqual(gotNote, note, "Right note added");
              start();
            }
          );
        }
      );
    }
  );

  asyncTest("addNote - 2 deep",
    function ()
    {
      var outerNote = { time: 0, link: "", tags: [], text: "b1" };
      var innerNote = { time: 0, link: "", tags: [], text: "b2" };
      var outerId;
      var innerId;

      async.series(
        [
          function (cb)
          {
            connector.addNote(outerNote,
              function (err, id)
              {
                outerId = id;
                cb(err);
              }
            );
          },
          function (cb)
          {
            connector.addNote(innerNote, outerId,
              function (err, id)
              {
                innerId = id;
                cb(err);
              }
            );
          },
          function (cb)
          {
            connector.getNotes(function (err, notes)
              {
                var root;

                root = notes.notes;
                var keys = Object.keys(root);
                equal(keys.length, 1, "level 1 - One note added");
                deepEqual(root[outerId].text, outerNote.text, "level 1 - Right note added");

                root = notes.notes[outerId].notes;
                var keys = Object.keys(root);
                equal(keys.length, 1, "level 2 - One note added");
                deepEqual(root[innerId].text, innerNote.text, "level 2 - Right note added");

                cb();
              }
            );
          }
        ],
        start
      );
    }
  );

  asyncTest("removeNote callback",
    function ()
    {
      connector.addNote({ a: "b3", notes: {} },
        function (err, id)
        {
          connector.removeNote(id,
            function ()
            {
              ok(true);
              start();
            }
          );
        }
      );
    }
  );

  asyncTest("removeNote event",
    function ()
    {
      var addNote = { time: 0, link: "", tags: [], text: "b" };
      var called = false;
      var addedId = null;

      connector.bind("noteRemoved",
        function (id, note)
        {
          if(called)
          {
            console.error("removeNote callback called twice")
            ok(false);
          }

          called = true;
          equal(id, addedId, "event - index ok");
          deepEqual(note, addNote, "event - note ok");
          start();
        }
      );

      connector.addNote(addNote,
        function (err, id)
        {
          addedId = id;
          connector.removeNote(id, function () {});
        }
      );
    }
  );

  asyncTest("removeNote",
    function ()
    {
      var addNotes =
        [
          { time: 0, link: "", tags: [], text: "b1", notes: {} },
          { time: 0, link: "", tags: [], text: "b2" },
          { time: 0, link: "", tags: [], text: "b3", notes: {} }
        ];

      var ids = [];

      async.series(
        [
          function (cb)
          {
            async.eachSeries(addNotes,
              function (note, cb)
              {
                connector.addNote.call(connector,
                  note,
                  function (err, id)
                  {
                    ids.push(id);
                    cb();
                  }
                );
              },
              cb);
          },
          function (cb)
          {
            connector.removeNote(ids[1], cb); // remove b2
          },
          function (cb)
          {
            connector.getNotes(function (err, notes)
              {
                var keys = Object.keys(notes.notes);
                equal(keys.length, 2, "Note removed");
                deepEqual(notes.notes[keys[0]], addNotes[0], "Note 1 untouched");
                deepEqual(notes.notes[keys[1]], addNotes[2], "Note 3 untouched");
                cb();
              }
            );
          }
        ],
        start
      );
    }
  );

  asyncTest("removeNote - invalid index",
    function ()
    {
      connector.bind("noteRemoved",
        function (index, note)
        {
          ok(false, "Event fired");
        }
      );

      connector.removeNote("foo",
        function (err)
        {
          equal(err, "not found", "Error ok");
          start();
        }
      );
    }
  );

  asyncTest("editNote callback",
    function ()
    {
      connector.addNote({},
        function (err, id)
        {
          connector.editNote(id, { a: "b" },
            function ()
            {
              ok(true);
              start();
            }
          );
        }
      );
    }
  );

  asyncTest("editNote event",
    function ()
    {
      var addNote = { time: 0, link: "", tags: [], text: "val1" };
      var editedNote = { time: 0, link: "", tags: [], text: "val2" };
      var called = false;
      var addedId = null;

      connector.bind("noteEdited",
        function (id, note, changed)
        {
          if(called)
          {
            console.error("editNote callback called twice")
            ok(false);
          }

          called = true;
          equal(id, addedId, "event - id ok");
          deepEqual(note, editedNote, "event - note ok");
          deepEqual(changed, ["text"], "event - changed ok");
          start();
        }
      );

      connector.addNote(addNote,
        function (err, id)
        {
          addedId = id;
          connector.editNote(id, editedNote, function () {});
        }
      );
    }
  );

  asyncTest("editNote",
    function ()
    {
      var addNote = { time: 0, link: "", tags: [], text: "val1" };
      var editedNote = { time: 0, link: "", tags: [], text: "val2" };

      connector.addNote(addNote,
        function (err, id)
        {
          connector.editNote(id, editedNote,
            function (err)
            {
              connector.getNote(id, function (err, note)
                {
                  deepEqual(note, editedNote, "Note changed");
                  start();
                }
              );
            }
          );
        }
      );
    }
  );

  asyncTest("editNote - invalid id",
    function ()
    {
      connector.bind("noteEdited",
        function (id, note)
        {
          ok(false, "Event fired");
        }
      );

      connector.editNote(1, {},
        function (err)
        {
          equal(err, "not found", "Error ok");
          start();
        }
      );
    }
  );

  asyncTest("getNote",
    function ()
    {
      var addNote = { time: 0, link: "", tags: [], text: "val1" };

      connector.addNote(addNote,
        function (err, id)
        {
          connector.getNote(id,
            function (err, note)
            {
              deepEqual(addNote, note, "Right note returned");
              start();
            }
          );
        }
      );
    }
  );

  asyncTest("getNote - invalid id",
    function ()
    {
      connector.getNote("foo",
        function (err)
        {
          equal(err, "not found", "Error ok");
          start();
        }
      );
    }
  );

  test("getFriendlyJson",
    function ()
    {
      var input = {
        "notes":
        {
          "aaa":
          {
            "time": 20,
            "text": "a",
            "link": "",
            "tags": [ "a", "b" ],
            "notes":
            {
              "aaa.1":
              {
                "time": 30,
                "text": "b",
                link: "",
                "tags": [],
                "notes": {}
              }
            }
          },
          "bbb":
          {
            "time": 40,
            "text": "c",
            "link": "",
            "tags": [ "a", "b" ],
            "notes": {}
          }
        }
      };

      var expected = [
        {
          "time": 20,
          "text": "a",
          "link": "",
          "tags": [ "a", "b" ],
          "notes":
            [
              {
                "time": 30,
                "text": "b",
                "link": "",
                "tags": [],
                "notes": []
              }
            ]
        },
        {
          "time": 40,
          "text": "c",
          "link": "",
          "tags": [ "a", "b" ],
          "notes": []
        }
      ];

      var actual = connector.getFriendlyJson(input);

      deepEqual(actual, expected);
    }
  );
})();
<|endoftext|>


<commit_before>/* eslint-env mocha */
'use strict';

const should = require('should');
const StringTemplate = require('../lib/string-template');

describe('StringTemplate', () => {
  let string = 'The {{ jumper:adjective }} {{ jumper:color }} {{ jumper:animal }}';

  string += ' jumped {{ preposition }} the... What ever, I\'m hungery';

  const expected = 'The quick red fox jumped over the... What ever, I\'m hungery';
  const notATemplate = 'This isn\'t a template';

  const undefinedSubstitution = 'This template references {{ an:invalid }} variable!';

  const scope = {
    jumper: {
      adjective: 'quick',
      color: 'red',
      animal: 'fox'
    },
    preposition: 'over'
  };

  const template = new StringTemplate(string, scope);

  it('detects valid template strings', () => {
    StringTemplate.isTemplate(string).should.equal(true);
  });

  it('detects invalid template strings', () => {
    StringTemplate.isTemplate(notATemplate).should.equal(false);
  });

  it('substitutes values into a template string correctly', () => {
    template.toString().should.equal(expected);
  });

  it('throws a ReferenceError if a substitutes references an undefined variable', () => {
    const throwsAnError = new StringTemplate(undefinedSubstitution, scope);

    should.throws(() => throwsAnError.toString(), ReferenceError);
  });
});
<commit_msg>PD added toJSON test and string substitutions<commit_after>/* eslint-env mocha */
'use strict';

const should = require('should');
const StringTemplate = require('../lib/string-template');

describe('StringTemplate', () => {
  let string = 'The {{jumper:adjective}} {{ jumper:color }} {{jumper:animal}}';

  string += ' jumped {{ preposition }} the... What ever, I\'m hungery';

  const expected = 'The quick red fox jumped over the... What ever, I\'m hungery';
  const notATemplate = 'This isn\'t a template';

  const undefinedSubstitution = 'This template references {{ an:invalid }} variable!';

  const scope = {
    jumper: {
      adjective: 'quick',
      color: 'red',
      animal: 'fox'
    },
    preposition: 'over'
  };

  const template = new StringTemplate(string, scope);

  it('detects valid template strings', () => {
    StringTemplate.isTemplate(string).should.equal(true);
  });

  it('detects invalid template strings', () => {
    StringTemplate.isTemplate(notATemplate).should.equal(false);
  });

  it('toJSON converts to a string correctly', () => {
    template.toJSON().should.equal(expected);
  });

  it('substitutes values into a template string correctly', () => {
    template.toString().should.equal(expected);
  });

  it('throws a ReferenceError if a substitutes references an undefined variable', () => {
    const throwsAnError = new StringTemplate(undefinedSubstitution, scope);

    should.throws(() => throwsAnError.toString(), ReferenceError);
  });
});
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert');
var fs = require('fs');
var gulp = require('gulp');
var path = require('path');
var registerTasks = require('../../../tasks/index');
var sinon = require('sinon');

describe('Build Tasks', function() {
  before(function() {
    this.initialCwd_ = process.cwd();
    process.chdir(path.join(__dirname, 'assets'));

    gulp.task('soy', sinon.stub().yields());
  });

  after(function() {
    process.chdir(this.initialCwd_);
  });

  it('should build js files into a single bundle with globals', function(done) {
    registerTasks({
      bundleFileName: 'foo.js',
      globalName: 'foo'
    });

    gulp.start('build:globals', function() {
      var contents = fs.readFileSync('build/foo.js', 'utf8');
      eval.call(global, contents);

      assert.ok(global.foo);
      assert.ok(global.foo.Bar);
      assert.ok(global.foo.Foo);

      var foo = new global.foo.Foo();
      assert.ok(foo instanceof global.foo.Bar);

      done();
    });
  });

  it('should trigger "end" event even when build:globals throws error for invalid js', function(done) {
    registerTasks({
      buildSrc: 'invalidSrc/Invalid.js',
      bundleFileName: 'invalid.js',
      globalName: 'invalid'
    });
    sinon.stub(console, 'error');

    gulp.start('build:globals', function() {
      assert.strictEqual(1, console.error.callCount);
      done();
    });
  });
});
<commit_msg>Adds test for watch:globals task<commit_after>'use strict';

var assert = require('assert');
var fs = require('fs');
var gulp = require('gulp');
var path = require('path');
var registerTasks = require('../../../tasks/index');
var sinon = require('sinon');

describe('Build Tasks', function() {
  before(function() {
    this.initialCwd_ = process.cwd();
    process.chdir(path.join(__dirname, 'assets'));

    gulp.task('soy', function(done) {
      done();
    });
  });

  after(function() {
    process.chdir(this.initialCwd_);
  });

  it('should build js files into a single bundle with globals', function(done) {
    registerTasks({
      bundleFileName: 'foo.js',
      globalName: 'foo'
    });

    gulp.start('build:globals', function() {
      var contents = fs.readFileSync('build/foo.js', 'utf8');
      eval.call(global, contents);

      assert.ok(global.foo);
      assert.ok(global.foo.Bar);
      assert.ok(global.foo.Foo);

      var foo = new global.foo.Foo();
      assert.ok(foo instanceof global.foo.Bar);

      done();
    });
  });

  it('should trigger "end" event even when build:globals throws error for invalid js', function(done) {
    registerTasks({
      buildSrc: 'invalidSrc/Invalid.js',
      bundleFileName: 'invalid.js',
      globalName: 'invalid'
    });
    sinon.stub(console, 'error');

    gulp.start('build:globals', function() {
      assert.strictEqual(1, console.error.callCount);
      done();
    });
  });

  it('should watch for file changes on watch:globals', function(done) {
    registerTasks();
    sinon.stub(gulp, 'watch');

    gulp.start('watch:globals', function() {
      assert.strictEqual(2, gulp.watch.callCount);
      assert.strictEqual('src/**/*.js', gulp.watch.args[0][0]);
      assert.deepEqual(['globals'], gulp.watch.args[0][1]);
      assert.strictEqual('src/**/*.soy', gulp.watch.args[1][0]);
      assert.deepEqual(['soy'], gulp.watch.args[1][1]);

      gulp.watch.restore();
      done();
    });
    gulp.stop();
  });
});
<|endoftext|>


<commit_before>var matrix3d = require('../lib/matrix-3d');
var assert = require('assert');
var data = [90, 180];

var r = matrix3d.d2r(data[0]);
console.log("Radian: " + r);
var d = matrix3d.r2d(r);
assert.equal(d, data[0]);

<commit_msg>translation<commit_after>var matrix3d = require('../lib/matrix-3d');
var assert = require('assert');
var data = [90, 180];

var r = matrix3d.d2r(data[0]);
console.log("Radian: " + r);
var d = matrix3d.r2d(r);
console.log("Degree: " + d);
assert.equal(d, data[0]);

<|endoftext|>


<commit_before>require('./harness');

connection.on('ready', function() {
  puts("connected to " + connection.serverProperties.product);

  var exchange = connection.exchange('node-queue-args', {type: 'fanout'});
  exchange.on('close', function(err) {
      console.log(err);
  });

  connection.queue('node-queue-args-queue', {
      'arguments': {'x-expires': 3600000}
  }, function(q) {
    puts("queue declared");
    var conn = amqp.createConnection({});

    conn.on('ready', function() {
      var q = conn.queue('node-queue-args-queue', {
          'arguments': {'x-expires': 3600001}
        }, function(q2) {
          puts("second queue declared");
      });
      q.on('error', function(err) {
        assert.equal(err.code, 406);
        assert.ok(err.message.indexOf('PRECONDITION_FAILED') == 0);
        connection.end();
        conn.end();
      });
    });
  });
});
<commit_msg>queue arguments test cleanup<commit_after>require('./harness');

connection.on('ready', function() {
  puts("connected to " + connection.serverProperties.product);

  connection.queue('node-queue-args-queue', {
      'arguments': {'x-expires': 3600000}
  }, function(q) {
    puts("queue declared");
    var conn = amqp.createConnection({});

    conn.on('ready', function() {
      var q = conn.queue('node-queue-args-queue', {
          'arguments': {'x-expires': 3600001}
        }, function(q2) {
          puts("second queue declared");
      });
      q.on('error', function(err) {
        assert.equal(err.code, 406);
        assert.ok(err.message.indexOf('PRECONDITION_FAILED') == 0);
        connection.end();
        conn.end();
      });
    });
  });
});
<|endoftext|>


<commit_before>var expect = require('chai').expect;
var setup  = require(__dirname + '/lib/setup');
var fs     = require('fs');
var objects     = null;
var states      = null;
var onStatesChanged = null;
var dataDir = __dirname + '/../tmp/data';

function cleanDbs() {
    if (fs.existsSync(dataDir + '/objects.json')) {
        fs.unlinkSync(dataDir + '/objects.json');
    }
    if (fs.existsSync(dataDir + '/objects.json.bak')) {
        fs.unlinkSync(dataDir + '/objects.json.bak');
    }
    if (fs.existsSync(dataDir + '/states.json')) {
        fs.unlinkSync(dataDir + '/states.json');
    }
    if (fs.existsSync(dataDir + '/states.json.bak')) {
        fs.unlinkSync(dataDir + '/states.json.bak');
    }
}

describe('States-Redis: Test states', function() {
    before('States-Redis: Start js-controller', function (_done) {
        this.timeout(2000);
        cleanDbs();

        setup.startController({
                objects: {
                    dataDir: dataDir,
                    onChange:function (id, obj) {
                        console.log('object changed. ' + id);
                    }
                },
                states: {
                    type: 'redis',
                    host: '127.0.0.1',
                    port: 6379,
                    onChange: function (id, state) {
                        console.log('Redis-state changed. ' + id);
                        if (onStatesChanged) onStatesChanged(id, state);
                    }
                }
            },
            function (_objects, _states) {
                objects = _objects;
                states  = _states;
                states.subscribe('*');
                expect(objects).to.be.ok;
                expect(states).to.be.ok;
                _done();
            }
        );
    });

    it('States-Redis: should setState', function (done) {
        var testID = 'testObject.0.test1';
        onStatesChanged = function (id, state) {
            if (id === testID) {
                expect(state).to.be.ok;
                expect(state.val).to.be.equal(1);
                expect(state.ack).to.be.false;
                expect(state.ts).to.be.ok;
                expect(state.q).to.be.equal(0);

                states.getState(testID, function (err, state) {
                    expect(err).to.be.not.ok;
                    expect(state).to.be.ok;
                    expect(state.val).to.be.equal(1);
                    expect(state.ack).to.be.false;
                    expect(state.ts).to.be.ok;
                    expect(state.q).to.be.equal(0);
                    done();
                });
            }
        };

        states.setState(testID, 1, function (err) {
            expect(err).to.be.not.ok;
        });
    });

    after('States-Redis: Stop js-controller', function (done) {
        this.timeout(5000);
        setup.stopController(function () {
            done();
        });
    });
});
<commit_msg>increase timeouts a bit<commit_after>var expect = require('chai').expect;
var setup  = require(__dirname + '/lib/setup');
var fs     = require('fs');
var objects     = null;
var states      = null;
var onStatesChanged = null;
var dataDir = __dirname + '/../tmp/data';

function cleanDbs() {
    if (fs.existsSync(dataDir + '/objects.json')) {
        fs.unlinkSync(dataDir + '/objects.json');
    }
    if (fs.existsSync(dataDir + '/objects.json.bak')) {
        fs.unlinkSync(dataDir + '/objects.json.bak');
    }
    if (fs.existsSync(dataDir + '/states.json')) {
        fs.unlinkSync(dataDir + '/states.json');
    }
    if (fs.existsSync(dataDir + '/states.json.bak')) {
        fs.unlinkSync(dataDir + '/states.json.bak');
    }
}

describe('States-Redis: Test states', function() {
    before('States-Redis: Start js-controller', function (_done) {
        this.timeout(5000);
        cleanDbs();

        setup.startController({
                objects: {
                    dataDir: dataDir,
                    onChange:function (id, obj) {
                        console.log('object changed. ' + id);
                    }
                },
                states: {
                    type: 'redis',
                    host: '127.0.0.1',
                    port: 6379,
                    onChange: function (id, state) {
                        console.log('Redis-state changed. ' + id);
                        if (onStatesChanged) onStatesChanged(id, state);
                    }
                }
            },
            function (_objects, _states) {
                objects = _objects;
                states  = _states;
                states.subscribe('*');
                expect(objects).to.be.ok;
                expect(states).to.be.ok;
                _done();
            }
        );
    });

    it('States-Redis: should setState', function (done) {
        this.timeout(5000);

        var testID = 'testObject.0.test1';
        onStatesChanged = function (id, state) {
            if (id === testID) {
                expect(state).to.be.ok;
                expect(state.val).to.be.equal(1);
                expect(state.ack).to.be.false;
                expect(state.ts).to.be.ok;
                expect(state.q).to.be.equal(0);

                states.getState(testID, function (err, state) {
                    expect(err).to.be.not.ok;
                    expect(state).to.be.ok;
                    expect(state.val).to.be.equal(1);
                    expect(state.ack).to.be.false;
                    expect(state.ts).to.be.ok;
                    expect(state.q).to.be.equal(0);
                    done();
                });
            }
        };

        states.setState(testID, 1, function (err) {
            expect(err).to.be.not.ok;
        });
    });

    after('States-Redis: Stop js-controller', function (done) {
        this.timeout(5000);
        setup.stopController(function () {
            done();
        });
    });
});
<|endoftext|>


<commit_before>console.log('1..1')
console.log('ok')
<commit_msg>remove unused fixture<commit_after><|endoftext|>


<commit_before>var chai = require('chai')
var expect = chai.expect

var sessionStore = require('../session-store.js')
var TestManager = require('../test-manager.js')

describe('SessionStore#', function() {

	before(TestManager.tearDown)
	before(TestManager.setUp)
	after(TestManager.tearDown)

	describe('clearExpiredSessions(cb)', function() {

		var fixtures = require('../fixtures/sessions')
		var num_expired = fixtures.length - 2

		before(TestManager.populateSessions)

		before(function(done) {

			// Change some of the sessions' expires time.

			var expiration = sessionStore.options.expiration

			var sql = 'UPDATE `sessions` SET expires = ? LIMIT ' + num_expired
			var expires = ( new Date( Date.now() - (expiration + 15000) ) ) / 1000
			var params = [ expires ]

			sessionStore.connection.query(sql, params, function(error) {

				if (error)
					return done(new Error(error))

				done()

			})

		})

		after(TestManager.clearSessions)

		it('should clear expired sessions', function(done) {

			sessionStore.clearExpiredSessions(function(error) {

				if (error)
					return done(new Error(error))

				sessionStore.length(function(error, count) {

					if (error)
						return done(new Error(error))

					expect(count).to.equal(fixtures.length - num_expired)

					done()

				})

			})

		})

	})

	describe('setExpirationInterval(interval)', function() {

		var originalClearExpiredSessionsMethod

		before(function() {

			originalClearExpiredSessionsMethod = sessionStore.clearExpiredSessions

		})

		after(function() {

			sessionStore.clearExpirationInterval()

		})

		after(function() {

			sessionStore.clearExpiredSessions = originalClearExpiredSessionsMethod

		})

		it('should correctly set the check expiration interval time', function(done) {

			var numCalls = 0, intervalTime = 24

			// Override the clearExpiredSessions method.
			sessionStore.clearExpiredSessions = function() {

				numCalls++

			}

			sessionStore.setExpirationInterval(intervalTime)

			var testTime = (intervalTime * 5) + 10

			setTimeout(function() {

				var numCallsExpected = Math.floor(testTime / intervalTime)

				expect(numCalls).to.equal(numCallsExpected)

				done()

			}, testTime)

		})

	})

})<commit_msg>Refactored expiration interval timing test<commit_after>var chai = require('chai')
var expect = chai.expect

var sessionStore = require('../session-store.js')
var TestManager = require('../test-manager.js')

describe('SessionStore#', function() {

	before(TestManager.tearDown)
	before(TestManager.setUp)
	after(TestManager.tearDown)

	describe('clearExpiredSessions(cb)', function() {

		var fixtures = require('../fixtures/sessions')
		var num_expired = fixtures.length - 2

		before(TestManager.populateSessions)

		before(function(done) {

			// Change some of the sessions' expires time.

			var expiration = sessionStore.options.expiration

			var sql = 'UPDATE `sessions` SET expires = ? LIMIT ' + num_expired
			var expires = ( new Date( Date.now() - (expiration + 15000) ) ) / 1000
			var params = [ expires ]

			sessionStore.connection.query(sql, params, function(error) {

				if (error)
					return done(new Error(error))

				done()

			})

		})

		after(TestManager.clearSessions)

		it('should clear expired sessions', function(done) {

			sessionStore.clearExpiredSessions(function(error) {

				if (error)
					return done(new Error(error))

				sessionStore.length(function(error, count) {

					if (error)
						return done(new Error(error))

					expect(count).to.equal(fixtures.length - num_expired)

					done()

				})

			})

		})

	})

	describe('setExpirationInterval(interval)', function() {

		var originalClearExpiredSessionsMethod

		before(function() {

			originalClearExpiredSessionsMethod = sessionStore.clearExpiredSessions

		})

		after(function() {

			sessionStore.clearExpirationInterval()

		})

		after(function() {

			sessionStore.clearExpiredSessions = originalClearExpiredSessionsMethod

		})

		it('should correctly set the check expiration interval time', function(done) {

			var numCalls = 0,
				numCallsExpected = 5,
				intervalTime = 14

			var paddingTime = (intervalTime * 1.5)

			// Override the clearExpiredSessions method.
			sessionStore.clearExpiredSessions = function() {

				numCalls++

			}

			sessionStore.setExpirationInterval(intervalTime)

			// Timeouts will never execute before the time given.
			// But they are not 100% guaranteed to execute exactly when you would expect.
			setTimeout(function() {

				expect(numCalls >= numCallsExpected).to.equal(true)

				done()

			}, (intervalTime * numCallsExpected) + paddingTime)

		})

	})

})<|endoftext|>


<commit_before>/*
shoestring unit tests - using qUnit
*/
(function(undefined){

module( 'Extensions' );
test( '`.live()` is an alias of `.on()`', function() {
	ok( shoestring( "body" ).live == shoestring( "body" ).on );
});

test( '`.closest()`', function() {
	var $fixture = shoestring( '#qunit-fixture' );
	$fixture.html( '

' );

	equal( $fixture.find( '.child' ).closest( '.parent' ).length, 1, 'Closest returns only one element.' );

	ok( $fixture.find( '.child' ).closest( '.parent' ).is( '.first' ), 'Closest returns from the bottom up.' );
});

test( '`.insertAfter()`', function() {
	var $fixture = shoestring( '#qunit-fixture' ),
		$sibling;

	$fixture.html( '

' );
	$sibling = shoestring( '#sibling' );

	shoestring( '
' ).insertAfter( $sibling );

	equal( $fixture.children().length, 2, 'Has two children.' );
	ok( $sibling.next().is( '#insertAfter' ), 'Inserted properly.' );
});

test( '`.insertBefore()`', function() {
	var $fixture = shoestring( '#qunit-fixture' ),
		$sibling;

	$fixture.html( '

' );
	$sibling = shoestring( '#sibling' );

	shoestring( '
' ).insertBefore( $sibling );

	equal( $fixture.children().length, 2, 'Has two children.' );
	ok( $sibling.prev().is( '#insertBefore' ), 'Inserted properly.' );
});

test( '`.html()`', function() {
	var $fixture = shoestring( '#qunit-fixture' ),
		htmlStr = '

';

	$fixture.html( htmlStr );
	equal( $fixture[0].innerHTML, htmlStr, '.html(str) set properly.' );
	equal( $fixture.html(), htmlStr, '.html() get properly.' );
});

test( '`.siblings()`', function() {
	var $fixture = shoestring( '#qunit-fixture' );
	$fixture.html( '

' );

	strictEqual( $( '#imaginary_element' ).siblings().length, 0, '.siblings runs on an empty set.' );
	equal( $( '#sibling' ).siblings().length, 2, '.siblings returns non-empty set.' );
});

})();<commit_msg>ensure closest returns the current element on match<commit_after>/*
shoestring unit tests - using qUnit
*/
(function(undefined){

module( 'Extensions' );
test( '`.live()` is an alias of `.on()`', function() {
	ok( shoestring( "body" ).live == shoestring( "body" ).on );
});

test( '`.closest()`', function() {
	var $fixture = shoestring( '#qunit-fixture' );
	$fixture.html( '

' );

	var $child = $fixture.find( '.child' );

	equal( $child[0], $child.closest( '.child' )[0], 'Closest returns current element on match' );

	equal( $child.closest( '.parent' ).length, 1, 'Closest returns only one element.' );

	ok( $child.closest( '.parent' ).is( '.first' ), 'Closest returns from the bottom up.' );
});

test( '`.insertAfter()`', function() {
	var $fixture = shoestring( '#qunit-fixture' ),
		$sibling;

	$fixture.html( '

' );
	$sibling = shoestring( '#sibling' );

	shoestring( '
' ).insertAfter( $sibling );

	equal( $fixture.children().length, 2, 'Has two children.' );
	ok( $sibling.next().is( '#insertAfter' ), 'Inserted properly.' );
});

test( '`.insertBefore()`', function() {
	var $fixture = shoestring( '#qunit-fixture' ),
		$sibling;

	$fixture.html( '

' );
	$sibling = shoestring( '#sibling' );

	shoestring( '
' ).insertBefore( $sibling );

	equal( $fixture.children().length, 2, 'Has two children.' );
	ok( $sibling.prev().is( '#insertBefore' ), 'Inserted properly.' );
});

test( '`.html()`', function() {
	var $fixture = shoestring( '#qunit-fixture' ),
		htmlStr = '

';

	$fixture.html( htmlStr );
	equal( $fixture[0].innerHTML, htmlStr, '.html(str) set properly.' );
	equal( $fixture.html(), htmlStr, '.html() get properly.' );
});

test( '`.siblings()`', function() {
	var $fixture = shoestring( '#qunit-fixture' );
	$fixture.html( '

' );

	strictEqual( $( '#imaginary_element' ).siblings().length, 0, '.siblings runs on an empty set.' );
	equal( $( '#sibling' ).siblings().length, 2, '.siblings returns non-empty set.' );
});

})();
<|endoftext|>


<commit_before>var State = require('../../src/lib/state.js');

describe('state', function() {

    it('should be defined', function() {
        expect(State).toBeDefined();
    });

    it('creating a new state object', function(){

        var obj = State.create('someName');

        expect(obj).toEqual(jasmine.any(Object));
        expect(obj.id).toBeDefined();
        expect(obj.state).toBe(0);
    });

    it('should replace GARDR_UNIQUE_ID with a unique id', function () {
        var opts = {url: 'http://test.com/?misc=GARDR_UNIQUE_ID&foo=bar'};
        var url1 = State.create('test_unique', opts).getData().url;
        var url2 = State.create('test_unique2', opts).getData().url;
        expect(url1.indexOf('GARDR_UNIQUE_ID')).toEqual(-1);
        expect(url1).not.toEqual(url2.url);
    });

    it('should also replace PASTIES_UNIQUE_ID for backwards compatibility', function () {
        var opts = {url: 'http://test.com/?misc=PASTIES_UNIQUE_ID&foo=bar'};
        var url1 = State.create('test_unique', opts).getData().url;
        var url2 = State.create('test_unique2', opts).getData().url;
        expect(url1.indexOf('PASTIES_UNIQUE_ID')).toEqual(-1);
        expect(url1).not.toEqual(url2.url);
    });

    it('should not use a regexp with global flag to replace unique token. \n\
        See http://stackoverflow.com/questions/3827456/what-is-wrong-with-my-date-regex/3827500#3827500', function () {
        expect(State._UNIQUE_TOKEN_REGEX.global).toBeFalsy();
    })

    it('creating two states with same name should have unique ids', function () {
        expect(State.create('unique').id).not.toEqual(State.create('unique').id);
    });

});
<commit_msg>Added missing semicolon<commit_after>var State = require('../../src/lib/state.js');

describe('state', function() {

    it('should be defined', function() {
        expect(State).toBeDefined();
    });

    it('creating a new state object', function(){

        var obj = State.create('someName');

        expect(obj).toEqual(jasmine.any(Object));
        expect(obj.id).toBeDefined();
        expect(obj.state).toBe(0);
    });

    it('should replace GARDR_UNIQUE_ID with a unique id', function () {
        var opts = {url: 'http://test.com/?misc=GARDR_UNIQUE_ID&foo=bar'};
        var url1 = State.create('test_unique', opts).getData().url;
        var url2 = State.create('test_unique2', opts).getData().url;
        expect(url1.indexOf('GARDR_UNIQUE_ID')).toEqual(-1);
        expect(url1).not.toEqual(url2.url);
    });

    it('should also replace PASTIES_UNIQUE_ID for backwards compatibility', function () {
        var opts = {url: 'http://test.com/?misc=PASTIES_UNIQUE_ID&foo=bar'};
        var url1 = State.create('test_unique', opts).getData().url;
        var url2 = State.create('test_unique2', opts).getData().url;
        expect(url1.indexOf('PASTIES_UNIQUE_ID')).toEqual(-1);
        expect(url1).not.toEqual(url2.url);
    });

    it('should not use a regexp with global flag to replace unique token. \n\
        See http://stackoverflow.com/questions/3827456/what-is-wrong-with-my-date-regex/3827500#3827500', function () {
        expect(State._UNIQUE_TOKEN_REGEX.global).toBeFalsy();
    });

    it('creating two states with same name should have unique ids', function () {
        expect(State.create('unique').id).not.toEqual(State.create('unique').id);
    });

});
<|endoftext|>


<commit_before>/**
 * Wait until the test condition is true or a timeout occurs. Useful for waiting
 * on a server response or for a ui change (fadeIn, etc.) to occur.
 *
 * @param testFx javascript condition that evaluates to a boolean,
 * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
 * as a callback function.
 * @param onReady what to do when testFx condition is fulfilled,
 * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
 * as a callback function.
 * @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used.
 */
function waitFor(testFx, onReady, timeOutMillis) {
    var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 30001, //< Default Max Timout is 3s
        start = new Date().getTime(),
        condition = false,
        interval = setInterval(function() {
            if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
                // If not time-out yet and condition not yet fulfilled
                condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code
            } else {
                if(!condition) {
                    // If condition still not fulfilled (timeout but condition is 'false')
                    console.log("'waitFor()' timeout");
                    phantom.exit(1);
                } else {
                    // Condition fulfilled (timeout and/or condition is 'true')
                    console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms.");
                    typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled
                    clearInterval(interval); //< Stop this interval
                }
            }
        }, 100); //< repeat check every 250ms
};

if (phantom.args.length === 0 || phantom.args.length > 2) {
    console.log('Usage: run-qunit.js URL');
    phantom.exit(1);
}

var page = require('webpage').create();

// Route "console.log()" calls from within the Page context to the main Phantom context (i.e. current "this")
page.onConsoleMessage = function(msg) {
    console.log(msg);
};

page.open(phantom.args[0], function(status){
    if (status !== "success") {
        console.log("Unable to access network");
        phantom.exit(1);
    } else {
        waitFor(function(){
            return page.evaluate(function(){
                var el = document.getElementById('qunit-testresult');
                if (el && el.innerText.match('completed')) {
                    return true;
                }
                return false;
            });
        }, function(){
            var failedNum = page.evaluate(function(){
                var el = document.getElementById('qunit-testresult');
                console.log(el.innerText);
                try {
                    return el.getElementsByClassName('failed')[0].innerHTML;
                } catch (e) { }
                return 10000;
            });
            phantom.exit((parseInt(failedNum, 10) > 0) ? 1 : 0);
        });
    }
});
<commit_msg>update runqunit<commit_after>var system = require('system');
/**
 * Wait until the test condition is true or a timeout occurs. Useful for waiting
 * on a server response or for a ui change (fadeIn, etc.) to occur.
 *
 * @param testFx javascript condition that evaluates to a boolean,
 * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
 * as a callback function.
 * @param onReady what to do when testFx condition is fulfilled,
 * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
 * as a callback function.
 * @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used.
 */
function waitFor(testFx, onReady, timeOutMillis) {
    var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 30001, //< Default Max Timout is 3s
        start = new Date().getTime(),
        condition = false,
        interval = setInterval(function() {
            if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
                // If not time-out yet and condition not yet fulfilled
                condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code
            } else {
                if(!condition) {
                    // If condition still not fulfilled (timeout but condition is 'false')
                    console.log("'waitFor()' timeout");
                    phantom.exit(1);
                } else {
                    // Condition fulfilled (timeout and/or condition is 'true')
                    console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms.");
                    typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled
                    clearInterval(interval); //< Stop this interval
                }
            }
        }, 100); //< repeat check every 250ms
};

if (system.args.length === 0 || system.args.length > 2) {
    console.log('Usage: runqunit.js URL');
    phantom.exit(1);
}

var page = require('webpage').create();

// Route "console.log()" calls from within the Page context to the main Phantom context (i.e. current "this")
page.onConsoleMessage = function(msg) {
    console.log(msg);
};

page.open(system.args[0], function(status){
    if (status !== "success") {
        console.log("Unable to access network");
        phantom.exit(1);
    } else {
        waitFor(function(){
            return page.evaluate(function(){
                var el = document.getElementById('qunit-testresult');
                if (el && el.innerText.match('completed')) {
                    return true;
                }
                return false;
            });
        }, function(){
            var failedNum = page.evaluate(function(){
                var el = document.getElementById('qunit-testresult');
                console.log(el.innerText);
                try {
                    return el.getElementsByClassName('failed')[0].innerHTML;
                } catch (e) { }
                return 10000;
            });
            phantom.exit((parseInt(failedNum, 10) > 0) ? 1 : 0);
        });
    }
});
<|endoftext|>


<commit_before>exports.config = {
  services: ['sauce'],
  user: process.env.NODE_PEOPLE_WEB_SAUCE_USERNAME,
  key: process.env.NODE_PEOPLE_WEB_SAUCE_ACCESS_KEY,
  sauceConnect: true,
  specs: ['./test/e2e/**/*.js'],
  exclude: [],
  maxInstances: 1,
  capabilities: [{
    maxInstances: 1,
    browserName: 'firefox',
    platform: 'Windows 10',
    version: '49.0'
  },
  {
    maxInstances: 1,
    browserName: 'internet explorer',
    platform: 'Windows 7',
    version: '8.0'
  }
],
  sync: false,
  logLevel: 'verbose',
  coloredLogs: true,
  screenshotPath: './errorShots/',
  baseUrl: 'http://localhost:3000',
  waitforTimeout: 10000,
  connectionRetryTimeout: 90000,
  connectionRetryCount: 3,
  framework: 'mocha',
  mochaOpts: {
    ui: 'bdd'
  }
}
<commit_msg>updated for standard<commit_after>exports.config = {
  services: ['sauce'],
  user: process.env.NODE_PEOPLE_WEB_SAUCE_USERNAME,
  key: process.env.NODE_PEOPLE_WEB_SAUCE_ACCESS_KEY,
  sauceConnect: true,
  specs: ['./test/e2e/**/*.js'],
  exclude: [],
  maxInstances: 1,
  capabilities: [{
    maxInstances: 1,
    browserName: 'firefox',
    platform: 'Windows 10',
    version: '49.0'
  },
  {
    maxInstances: 1,
    browserName: 'internet explorer',
    platform: 'Windows 7',
    version: '8.0'
  }],
  sync: false,
  logLevel: 'verbose',
  coloredLogs: true,
  screenshotPath: './errorShots/',
  baseUrl: 'http://localhost:3000',
  waitforTimeout: 10000,
  connectionRetryTimeout: 90000,
  connectionRetryCount: 3,
  framework: 'mocha',
  mochaOpts: {
    ui: 'bdd'
  }
}
<|endoftext|>


<commit_before>import ContentScroller from "ui/scrolling/ContentScroller";

export default class FixedItemListScroller extends ContentScroller {
    constructor({
        target, contentContainer, itemHeight, itemList, minPrerenderedItems, maxPrerenderedItems
    }, deps) {
        super({target, contentContainer}, deps);
        this._itemHeight = itemHeight;
        this._itemList = itemList;
        this._displayedItems = new Array(300);
        this._displayedItems.length = 0;
        this._minPrerenderedItems = minPrerenderedItems || 15;
        this._maxPrerenderedItems = maxPrerenderedItems || 100;
        this._sentinel = this._page.createElement(`div`).setStyles({
            width: `1px`,
            height: `1px`,
            position: `absolute`,
            transform: `translate3d(0, 0, 0)`
        }).setText(` `).prependTo(this.$contentContainer());
    }

    $sentinel() {
        return this._sentinel;
    }

    length() {
        return this._itemList.length;
    }

    physicalHeight() {
        return this.length() * this.itemHeight();
    }

    itemHeight() {
        return this._itemHeight;
    }

    resize() {
        this.$sentinel().setTransform(`translate3d(0px, ${this.physicalHeight()}px, 0px)`);
        super.resize();
        this._onScroll();
    }

    itemsVisibleInContainer() {
        return Math.ceil(this.contentHeight() / this.itemHeight());
    }

    contentHeight() {
        let rect = this._rect;
        if (rect.height === 0) {
            this._rect = rect = this.$contentContainer()[0].getBoundingClientRect();
        }
        return rect.height;
    }

    coordsToIndexRange(startY, endY) {
        const top = this._top;
        const scrollTop = this.getScrollTop();
        const itemHeight = this.itemHeight();

        startY = startY - top + scrollTop;
        endY = endY - top + scrollTop;

        let startIndex = Math.min(this.length() - 1, Math.max(0, (startY / itemHeight) | 0));
        let endIndex = Math.min(this.length() - 1, Math.max(0, (endY / itemHeight) | 0));

        if (startIndex < 0 || endIndex < 0) {
            return null;
        }

        if (startIndex > endIndex) {
            const tmp = startIndex;
            startIndex = endIndex;
            endIndex = tmp;
        }

        return {
            startIndex,
            endIndex
        };
    }

    getEdgeByCoordinateWithinMargin(y, margin) {
        const top = this._top;
        const bottom = this._top + this.contentHeight();
        if (y <= top + margin) {
            return -1;
        } else if (y >= bottom - margin) {
            return 1;
        } else {
            return 0;
        }
    }

    mapYCoordinate(y) {
        const top = this._top;
        return Math.min(this.contentHeight(), Math.max(0, y - top)) + this.getScrollTop();
    }

    indexByYCoordinate(y) {
        let index = (this.mapYCoordinate(y) / this.itemHeight()) | 0;
        index = Math.min(this.length() - 1, Math.max(0, index));
        return index;
    }

    itemByYCoordinate(y) {
        const index = this.indexByYCoordinate(y);
        if (index < 0) return null;
        return this._itemList[index];
    }

    itemByRect(rect) {
        return this.itemByYCoordinate(rect.top + rect.height / 2);
    }

    yByIndex(index) {
        index = Math.min(this.length() - 1, Math.max(0, index));
        if (index <= 0) return 0;
        return index * this.itemHeight();
    }

    _onScroll(forced = false) {
        const scrollTop = super._onScroll(forced);
        const {_itemHeight: itemHeight, _displayedItems: displayedItems} = this;

        const contentHeight = this.contentHeight();

        if (displayedItems.length > 2 && !forced) {
            const virtualStart = displayedItems[0].getIndex();
            const virtualEnd = displayedItems[displayedItems.length - 1].getIndex();

            const screenStart = scrollTop / itemHeight;
            const screenEnd = (scrollTop + contentHeight) / itemHeight;

            const {_minPrerenderedItems: minPrerenderedItems} = this;
            if (screenStart > (virtualStart + minPrerenderedItems) &&
                screenEnd < (virtualEnd - minPrerenderedItems)) {
                return scrollTop;
            }
        }

        const {_itemList: items, _maxPrerenderedItems: maxPrerenderedItems} = this;
        const container = this.$contentContainer();
        const itemsBefore = Math.min(items.length, scrollTop / itemHeight | 0);
        const itemsWithin = Math.min(items.length, Math.ceil(contentHeight / itemHeight));

        const start = Math.max(itemsBefore - maxPrerenderedItems, 0);
        const end = Math.min(items.length - 1, itemsWithin + itemsBefore + maxPrerenderedItems);

        const detachedDomNodes = [];

        for (let i = 0; i < displayedItems.length; ++i) {
            const index = displayedItems[i].getIndex();
            if (!(start <= index && index <= end) && displayedItems[i].isVisible()) {
                detachedDomNodes.push(displayedItems[i].detach());
            }
        }

        for (let i = start; i <= end; ++i) {
            const item = items[i];
            if (!item.isVisible()) {
                item.attach(container, detachedDomNodes.length > 0 ? detachedDomNodes.pop() : null);
            }
            displayedItems[i - start] = item;
        }

        for (let i = 0; i < detachedDomNodes.length; ++i) {
            detachedDomNodes[i].remove();
        }

        displayedItems.length = end - start + 1;
        return scrollTop;
    }
}
<commit_msg>fix optimization check<commit_after>import ContentScroller from "ui/scrolling/ContentScroller";

export default class FixedItemListScroller extends ContentScroller {
    constructor({
        target, contentContainer, itemHeight, itemList, minPrerenderedItems, maxPrerenderedItems
    }, deps) {
        super({target, contentContainer}, deps);
        this._itemHeight = itemHeight;
        this._itemList = itemList;
        this._displayedItems = new Array(300);
        this._displayedItems.length = 0;
        this._minPrerenderedItems = minPrerenderedItems || 15;
        this._maxPrerenderedItems = maxPrerenderedItems || 100;
        this._sentinel = this._page.createElement(`div`).setStyles({
            width: `1px`,
            height: `1px`,
            position: `absolute`,
            transform: `translate3d(0, 0, 0)`
        }).setText(` `).prependTo(this.$contentContainer());
    }

    $sentinel() {
        return this._sentinel;
    }

    length() {
        return this._itemList.length;
    }

    physicalHeight() {
        return this.length() * this.itemHeight();
    }

    itemHeight() {
        return this._itemHeight;
    }

    resize() {
        this.$sentinel().setTransform(`translate3d(0px, ${this.physicalHeight()}px, 0px)`);
        super.resize();
        this._onScroll();
    }

    itemsVisibleInContainer() {
        return Math.ceil(this.contentHeight() / this.itemHeight());
    }

    contentHeight() {
        let rect = this._rect;
        if (rect.height === 0) {
            this._rect = rect = this.$contentContainer()[0].getBoundingClientRect();
        }
        return rect.height;
    }

    coordsToIndexRange(startY, endY) {
        const top = this._top;
        const scrollTop = this.getScrollTop();
        const itemHeight = this.itemHeight();

        startY = startY - top + scrollTop;
        endY = endY - top + scrollTop;

        let startIndex = Math.min(this.length() - 1, Math.max(0, (startY / itemHeight) | 0));
        let endIndex = Math.min(this.length() - 1, Math.max(0, (endY / itemHeight) | 0));

        if (startIndex < 0 || endIndex < 0) {
            return null;
        }

        if (startIndex > endIndex) {
            const tmp = startIndex;
            startIndex = endIndex;
            endIndex = tmp;
        }

        return {
            startIndex,
            endIndex
        };
    }

    getEdgeByCoordinateWithinMargin(y, margin) {
        const top = this._top;
        const bottom = this._top + this.contentHeight();
        if (y <= top + margin) {
            return -1;
        } else if (y >= bottom - margin) {
            return 1;
        } else {
            return 0;
        }
    }

    mapYCoordinate(y) {
        const top = this._top;
        return Math.min(this.contentHeight(), Math.max(0, y - top)) + this.getScrollTop();
    }

    indexByYCoordinate(y) {
        let index = (this.mapYCoordinate(y) / this.itemHeight()) | 0;
        index = Math.min(this.length() - 1, Math.max(0, index));
        return index;
    }

    itemByYCoordinate(y) {
        const index = this.indexByYCoordinate(y);
        if (index < 0) return null;
        return this._itemList[index];
    }

    itemByRect(rect) {
        return this.itemByYCoordinate(rect.top + rect.height / 2);
    }

    yByIndex(index) {
        index = Math.min(this.length() - 1, Math.max(0, index));
        if (index <= 0) return 0;
        return index * this.itemHeight();
    }

    _onScroll(forced = false) {
        const scrollTop = super._onScroll(forced);
        const {_itemHeight: itemHeight, _displayedItems: displayedItems} = this;

        const contentHeight = this.contentHeight();

        if (displayedItems.length > 2 && !forced) {

            const virtualStart = displayedItems[0].getIndex();
            const virtualEnd = displayedItems[displayedItems.length - 1].getIndex();

            const screenStart = Math.ceil(scrollTop / itemHeight);
            const screenEnd = Math.floor((scrollTop + contentHeight) / itemHeight);

            if (screenStart >= virtualStart && screenEnd <= virtualEnd) {
                return scrollTop;
            }
        }

        const {_itemList: items, _maxPrerenderedItems: maxPrerenderedItems} = this;
        const container = this.$contentContainer();
        const itemsBefore = Math.min(items.length, scrollTop / itemHeight | 0);
        const itemsWithin = Math.min(items.length, Math.ceil(contentHeight / itemHeight));

        const start = Math.max(itemsBefore - maxPrerenderedItems, 0);
        const end = Math.min(items.length - 1, itemsWithin + itemsBefore + maxPrerenderedItems);

        const detachedDomNodes = [];

        for (let i = 0; i < displayedItems.length; ++i) {
            const index = displayedItems[i].getIndex();
            if (!(start <= index && index <= end) && displayedItems[i].isVisible()) {
                detachedDomNodes.push(displayedItems[i].detach());
            }
        }

        for (let i = start; i <= end; ++i) {
            const item = items[i];
            if (!item.isVisible()) {
                item.attach(container, detachedDomNodes.length > 0 ? detachedDomNodes.pop() : null);
            }
            displayedItems[i - start] = item;
        }

        for (let i = 0; i < detachedDomNodes.length; ++i) {
            detachedDomNodes[i].remove();
        }

        displayedItems.length = end - start + 1;
        return scrollTop;
    }
}
<|endoftext|>


<commit_before>jQuery(function($) {
  $('select[name="projects"]').select2();
  $('select[name="project"]').select2();

  $('.actions .subActions').hide();
  $('.nestedAction .open').click(function() {
    $('.actions > button, .actions .open').hide();
    $(this).closest('.nestedAction').find('.subActions').show();
    return false;
  });

  $('.subActions .cancel').click(function() {
    $(this).closest('.nestedAction').find('.subActions').hide();
    $('.actions > button, .actions .open').show();
    return false;
  });

  $('textarea[name="comment"]').atwho({
    at: '@',
    data: window.buggyData.userNames,
  }).atwho({
    at: '#',
    data: window.buggyData.openBugs,
    displayTpl: '
#${number} ${title}
',
    insertTpl: '#${number}',
    searchKey: 'number',
    callbacks: {
      // We don't want to match at the beginning of the line, because that will
      // be a markdown header instead of a bug mention.
      matcher: function(flag, subtext) {
        var regexp = /^.*\S.*[ \t\f\v]#(\d*)$/gim;
        var match = regexp.exec(subtext);
        if (match)
          return match[1];
        else
          return null;
      }
    }
  });

  // Only allow one request to preview markdown to the server at a time, but
  // always do a preview with the latest content too.
  var requestPending = false;
  var requestCancelled = false;

  function doPreview($container) {
    if (requestPending) {
      requestCancelled = true;
      return;
    }
    requestPending = true;

    var markdown = $container.find('[name="comment"]').val();

    $.post(window.buggyData.previewMarkdownUrl, {preview: markdown}, function(resp) {
      $container.find('.previewTarget').html(resp).show();
      requestPending = false;
      if (requestCancelled) {
        requestCancelled = false;
        doPreview($container);
      }
    });
  }

  $('.previewMarkdown').click(function() {
    var $container = $(this).closest('.commentMarkdown');

    $container.find('[name="comment"]').on('keyup', function() {
      doPreview($container);
    });
    doPreview($container);

    return false;
  });

  // Pjax
  var pjaxRequestPending = false;
  var pjaxRequestCanceled = false;

  $(document).on('pjax:beforeSend', function() {
    pjaxRequestPending = true;
    pjaxRequestCanceled = false;
    $('#pjax-container').addClass('loading');
  });

  $(document).on('pjax:complete', function() {
    pjaxRequestPending = false;
    $('#add-preset-url').val(location.pathname + location.search);

    if (pjaxRequestCanceled) {
      pjaxRequestCanceled = false;
      pjaxSubmit();
    } else {
      pjaxRequestCanceled = false;
    }

    $('#pjax-container').removeClass('loading');
  });

  $(document).on('pjax:end', function() {
    setActiveBulkActions();
    $('.subActions').hide();
    $('.actions > button, .actions .open').show();
  });

  function pjaxSubmit() {
    if (pjaxRequestPending) {
      pjaxRequestCanceled = true;
      return;
    } else {
      $('form[data-pjax]').submit();
    }
  }

  $(document).on('click', 'a[data-pjax]', function(event) {
    $.pjax.click(event, '#pjax-container');
  });

  $(document).on('submit', 'form[data-pjax]', function(event) {
    $.pjax.submit(event, '#pjax-container');
  });
  $('form[data-pjax] :input:not(#id_search)').on('change', pjaxSubmit);
  $('form[data-pjax] #id_search').on('keyup', pjaxSubmit);

  $(document).on('pjax:popstate', location.reload);

  // Bulk Actions
  function intersection(arrays) {
    if (arrays.length > 0) {
      return arrays.reduce(function(previous, current){
        return previous.filter(function(element){
          return current.indexOf(element) > -1;
        });
      });
    } else {
      return [];
    }
  }

  function bugCountDescription(n) {
    if (n === 0) {
      return 'No bugs selected';
    } else if (n === 1) {
      return '1 bug selected';
    } else {
      return n + ' bugs selected';
    }
  }

  function setActiveBulkActions() {
    var bugNumbers = $('input[name=bugs]:checked').closest('tr').map(function(i, x) {
      return $(x).data('number');
    }).get();
    $('.offCanvasForm').toggleClass('active', bugNumbers.length > 0);
    $('#selected-count').text(bugCountDescription(bugNumbers.length));
    $('#check_all_bugs').prop(
      'checked', $('input[name=bugs]:checked').length === $('input[name=bugs]').length
    );
    var actionLists = bugNumbers.map(function(x) { return window.buggyData.bugActions[x]; });
    var allowedActions = intersection(actionLists);
    $('button[name=action]').each(function(i, e) {
      $(e).prop('disabled', allowedActions.indexOf(e.value) < 0);
    });
    $('.nestedAction > button').each(function(i, e) {
      var hasActiveChildren = $(e).siblings('.subActions').find('button[name=action]:enabled').length > 0;
      $(e).prop('disabled', !hasActiveChildren);
    });
  }

  $('#check_all_bugs').change(function() {
    $('input[name=bugs]').prop('checked', $(this).prop('checked'));
  });
  $('input[name=bugs], #check_all_bugs').change(setActiveBulkActions);

  $('input[name=bugs]').change(function() {
    $(this).closest('tr').toggleClass('checked', $(this).prop('checked'));
  });

  setActiveBulkActions();
});

jQuery.pjax.defaults.scrollTo = false;
jQuery.pjax.defaults.timeout = 2500;
<commit_msg>Fix bulk action js after javascript update<commit_after>jQuery(function($) {
  $('select[name="projects"]').select2();
  $('select[name="project"]').select2();

  $('.actions .subActions').hide();
  $('.nestedAction .open').click(function() {
    $('.actions > button, .actions .open').hide();
    $(this).closest('.nestedAction').find('.subActions').show();
    return false;
  });

  $('.subActions .cancel').click(function() {
    $(this).closest('.nestedAction').find('.subActions').hide();
    $('.actions > button, .actions .open').show();
    return false;
  });

  $('textarea[name="comment"]').atwho({
    at: '@',
    data: window.buggyData.userNames,
  }).atwho({
    at: '#',
    data: window.buggyData.openBugs,
    displayTpl: '
#${number} ${title}
',
    insertTpl: '#${number}',
    searchKey: 'number',
    callbacks: {
      // We don't want to match at the beginning of the line, because that will
      // be a markdown header instead of a bug mention.
      matcher: function(flag, subtext) {
        var regexp = /^.*\S.*[ \t\f\v]#(\d*)$/gim;
        var match = regexp.exec(subtext);
        if (match)
          return match[1];
        else
          return null;
      }
    }
  });

  // Only allow one request to preview markdown to the server at a time, but
  // always do a preview with the latest content too.
  var requestPending = false;
  var requestCancelled = false;

  function doPreview($container) {
    if (requestPending) {
      requestCancelled = true;
      return;
    }
    requestPending = true;

    var markdown = $container.find('[name="comment"]').val();

    $.post(window.buggyData.previewMarkdownUrl, {preview: markdown}, function(resp) {
      $container.find('.previewTarget').html(resp).show();
      requestPending = false;
      if (requestCancelled) {
        requestCancelled = false;
        doPreview($container);
      }
    });
  }

  $('.previewMarkdown').click(function() {
    var $container = $(this).closest('.commentMarkdown');

    $container.find('[name="comment"]').on('keyup', function() {
      doPreview($container);
    });
    doPreview($container);

    return false;
  });

  // Pjax
  var pjaxRequestPending = false;
  var pjaxRequestCanceled = false;

  $(document).on('pjax:beforeSend', function() {
    pjaxRequestPending = true;
    pjaxRequestCanceled = false;
    $('#pjax-container').addClass('loading');
  });

  $(document).on('pjax:complete', function() {
    pjaxRequestPending = false;
    $('#add-preset-url').val(location.pathname + location.search);

    if (pjaxRequestCanceled) {
      pjaxRequestCanceled = false;
      pjaxSubmit();
    } else {
      pjaxRequestCanceled = false;
    }

    $('#pjax-container').removeClass('loading');
  });

  $(document).on('pjax:end', function() {
    setActiveBulkActions();
    $('.subActions').hide();
    $('.actions > button, .actions .open').show();
  });

  function pjaxSubmit() {
    if (pjaxRequestPending) {
      pjaxRequestCanceled = true;
      return;
    } else {
      $('form[data-pjax]').submit();
    }
  }

  $(document).on('click', 'a[data-pjax]', function(event) {
    $.pjax.click(event, '#pjax-container');
  });

  $(document).on('submit', 'form[data-pjax]', function(event) {
    $.pjax.submit(event, '#pjax-container');
  });
  $('form[data-pjax] :input:not(#id_search)').on('change', pjaxSubmit);
  $('form[data-pjax] #id_search').on('keyup', pjaxSubmit);

  $(document).on('pjax:popstate', location.reload);

  // Bulk Actions
  function intersection(arrays) {
    if (arrays.length > 0) {
      return arrays.reduce(function(previous, current){
        return previous.filter(function(element){
          return current.indexOf(element) > -1;
        });
      });
    } else {
      return [];
    }
  }

  function bugCountDescription(n) {
    if (n === 0) {
      return 'No bugs selected';
    } else if (n === 1) {
      return '1 bug selected';
    } else {
      return n + ' bugs selected';
    }
  }

  function setActiveBulkActions() {
    var bugNumbers = $('input[name=bugs]:checked').closest('tr').map(function(i, x) {
      return $(x).data('number');
    }).get();
    $('.offCanvasForm').toggleClass('active', bugNumbers.length > 0);
    $('#selected-count').text(bugCountDescription(bugNumbers.length));
    $('#check_all_bugs').prop(
      'checked', $('input[name=bugs]:checked').length === $('input[name=bugs]').length
    );
    var actionLists = bugNumbers.map(function(x) { return window.buggyData.bugActions[x]; });
    var allowedActions = intersection(actionLists);
    $('button[name=action]').each(function(i, e) {
      $(e).prop('disabled', allowedActions.indexOf(e.value) < 0);
    });
    $('.nestedAction > button').each(function(i, e) {
      var hasActiveChildren = $(e).siblings('.subActions').find('button[name=action]:enabled').length > 0;
      $(e).prop('disabled', !hasActiveChildren);
    });
  }

  $(document).on('change', '#check_all_bugs', function() {
    $('input[name=bugs]').prop('checked', $(this).prop('checked'));
  });
  $(document).on('change', 'input[name=bugs], #check_all_bugs', setActiveBulkActions);

  $(document).on('change', 'input[name=bugs]', function() {
    $(this).closest('tr').toggleClass('checked', $(this).prop('checked'));
  });

  setActiveBulkActions();
});

jQuery.pjax.defaults.scrollTo = false;
jQuery.pjax.defaults.timeout = 2500;
<|endoftext|>


<commit_before>// local imports
import addPerformanceModeHandlers from './addPerformanceModeHandlers'

/**
 * Creates a store enhancer based off an (optional) throttle time.
 * @arg {object} [options={calculateInitialState}] - Options object.
 * @arg {boolean} [options.calculateInitialState=true] - True if the responsive
 * state must be calculated initially, false otherwise.
 * @returns {function} - The store enhancer (which adds event listeners to
 * dispatch actions on window resize).
 */
export default ({ calculateInitialState = true } = {}) => {
    // return the store enhancer (an enhanced version of `createStore`)
    return (createStore) => (...args) => {
        // create the store
        const store = createStore(...args)

        // if there is a `window`
        if (typeof window !== 'undefined') {
            // add the handlers that only fire when the responsive state changes
            addPerformanceModeHandlers({store, window, calculateInitialState})
        }

        // return the store so that the call is transparent
        return store
    }
}
<commit_msg>Check for specific prop of window before adding window handlers<commit_after>// local imports
import addPerformanceModeHandlers from './addPerformanceModeHandlers'

/**
 * Creates a store enhancer based off an (optional) throttle time.
 * @arg {object} [options={calculateInitialState}] - Options object.
 * @arg {boolean} [options.calculateInitialState=true] - True if the responsive
 * state must be calculated initially, false otherwise.
 * @returns {function} - The store enhancer (which adds event listeners to
 * dispatch actions on window resize).
 */
export default ({ calculateInitialState = true } = {}) => {
    // return the store enhancer (an enhanced version of `createStore`)
    return (createStore) => (...args) => {
        // create the store
        const store = createStore(...args)

        // if there is a `window`
        if (typeof window !== 'undefined' && typeof window.matchMedia !== 'undefined') {
            // add the handlers that only fire when the responsive state changes
            addPerformanceModeHandlers({store, window, calculateInitialState})
        }

        // return the store so that the call is transparent
        return store
    }
}
<|endoftext|>


<commit_before>hgots.controller('LogsController', [ '$scope', '$http', 'HGOTSServicesShared', '$sce', '$timeout', '$activityIndicator', function($scope, $http, HGOTSServicesShared, $sce, $timeout, $activityIndicator) {
  var apiPrefix = HGOTSServicesShared.apiPrefix;

  function zerofy(num) {
    if ( num < 10 ) {
      return "0" + num;
    } else {
      return num;
    }
  }
  function dateForInput(date) {
    return date.getFullYear() + "-" + zerofy( date.getMonth() + 1 ) + "-" + zerofy( date.getDate() );
  }

  $scope.$watch('dateModel', function() {
    $scope.date = new Date($scope.dateModel);
    $scope.loadLog();
  });
  // starting date is always today
  $scope.dateModel = dateForInput(new Date());

  function parseRawContent(content) {
    content = content.split('\n');
    return content.filter(function(line) {
      return ( line.length > 0 );
    });
  }
  function parseContentLines(lines) {
    lines = lines.map(function(line) {
      var dateRegex = /[0-9]+:[0-9]+:[0-9]+/;
      var dateSurplusRegex = /:\ /;
      var errorRegex = /\[Error: .*]/g;

      var startRegex = /v[0-9]*\.[0-9]*\.[0-9]*\ started/;

      line = line.replace(dateRegex, '$&');
      line = line.replace(errorRegex, '$&');

      if ( line.search(startRegex) !== -1 ) {
        line += '';
      }

      return line;
    });

    return lines;
  }

  $scope.loadLog = function() {
    var date = $scope.date;

    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();

    var url = apiPrefix + '/log/' + year + '/' + month + '/' + day;

    $activityIndicator.startAnimating();
    $http({ url: url, method: 'GET' }).success(function(response) {
      if ( !response.log ) {
        //console.log("No log file found.");
        $scope.logLines = null;
        return;
      }

      if ( $scope.date !== date ) {
        return;
      }

      $timeout(function() {
        var log = response.log;
        var content = parseRawContent(log.content);
        var lines = parseContentLines(content);
        $scope.logLines = lines;

        $activityIndicator.stopAnimating();
      }, 100);

    }).error(function(err) {
      console.error("Error loading log file:", err);
      $activityIndicator.stopAnimating();
    });
  };
  // helper for ng-bind-html
  $scope.trustAsHtml = function(html) {
    return $sce.trustAsHtml(html);
  };
}]);
<commit_msg>Refined ui behavior.<commit_after>hgots.controller('LogsController', [ '$scope', '$http', 'HGOTSServicesShared', '$sce', '$timeout', '$activityIndicator', function($scope, $http, HGOTSServicesShared, $sce, $timeout, $activityIndicator) {
  var apiPrefix = HGOTSServicesShared.apiPrefix;

  function zerofy(num) {
    if ( num < 10 ) {
      return "0" + num;
    } else {
      return num;
    }
  }
  function dateForInput(date) {
    return date.getFullYear() + "-" + zerofy( date.getMonth() + 1 ) + "-" + zerofy( date.getDate() );
  }

  $scope.$watch('dateModel', function() {
    $scope.date = new Date($scope.dateModel);
    $scope.loadLog();
  });
  // starting date is always today
  $scope.dateModel = dateForInput(new Date());

  function parseRawContent(content) {
    content = content.split('\n');
    return content.filter(function(line) {
      return ( line.length > 0 );
    });
  }
  function parseContentLines(lines) {
    lines = lines.map(function(line) {
      var dateRegex = /[0-9]+:[0-9]+:[0-9]+/;
      var dateSurplusRegex = /:\ /;
      var errorRegex = /\[Error: .*]/g;

      var startRegex = /v[0-9]*\.[0-9]*\.[0-9]*\ started/;

      line = line.replace(dateRegex, '$&');
      line = line.replace(errorRegex, '$&');

      if ( line.search(startRegex) !== -1 ) {
        line += '';
      }

      return line;
    });

    return lines;
  }

  $scope.loadLog = function() {
    var date = $scope.date;

    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();

    var url = apiPrefix + '/log/' + year + '/' + month + '/' + day;

    $scope.logLines = [];
    $activityIndicator.startAnimating();
    $http({ url: url, method: 'GET' }).success(function(response) {
      if ( !response.log ) {
        $activityIndicator.stopAnimating(0);
        console.log("0");
        $scope.logLines = null;
        return;
      }
      if ( $scope.date !== date ) {
        return;
      }

      $timeout(function() {
        var log = response.log;
        var content = parseRawContent(log.content);
        var lines = parseContentLines(content);
        $scope.logLines = lines;

        $activityIndicator.stopAnimating();
      }, 100);

    }).error(function(err) {
      console.error("Error loading log file:", err);
      $activityIndicator.stopAnimating();
    });
  };
  // helper for ng-bind-html
  $scope.trustAsHtml = function(html) {
    return $sce.trustAsHtml(html);
  };
}]);
<|endoftext|>