<commit_before>describe('mach', function() {
  var mach = require('./../index.js');

  it('should be able to verify that a function is called', function() {
    var f = mach.mockFunction('f');

    f.shouldBeCalled().when(function() {
      f();
    });
  });

  it('should fail when an expected function call does not occur', function() {
    var f = mach.mockFunction('f');

    shouldFailWith('not all calls occurred', function() {
      f.shouldBeCalled().when(function() {});
    });
  });

  it('should fail when a different mock is called instead of the expected mock', function() {
    var f1 = mach.mockFunction('f1');
    var f2 = mach.mockFunction('f2');

    shouldFailWith('unexpected function call f2()', function() {
      f1.shouldBeCalled().when(function() {
        f2();
      });
    });
  });

  it('should fail when a function is called unexpectedly', function() {
    var f = mach.mockFunction('f');

    shouldFailWith('unexpected function call f()', function() {
      f();
    });
  });

  it('should fail when a function is called unexpectedly after a successful expectation', function() {
    var f = mach.mockFunction('f');

    f.shouldBeCalled().when(function() {
      f();
    });

    shouldFailWith('unexpected function call f()', function() {
      f();
    });
  });

  it('should be able to verify that a function has been called with the correct arguments', function() {
    var f = mach.mockFunction('f');

    f.shouldBeCalledWith(1, '2').when(function() {
      f(1, '2');
    });
  });

  it('should fail when a function iss been called with incorrect arguments', function() {
    var f = mach.mockFunction('f');

    shouldFailWith('unexpected arguments (1, \'3\') provided to function f', function() {
      f.shouldBeCalledWith(1, '2').when(function() {
        f(1, '3');
      });
    });
  });

  it('should allow the return value of a mocked function to be specified', function() {
    var f = mach.mockFunction('f');

    f.shouldBeCalled().andWillReturn(4).when(function() {
      expect(f()).toBe(4);
    });
  });

  it('should allow multiple function calls to be expected', function() {
    var f = mach.mockFunction('f');

    f.shouldBeCalled().andAlso(f.shouldBeCalledWith(1, 2, 3)).when(function() {
      f();
      f(1, 2, 3);
    });
  });

  it('should fail if multiplle function calls are expected but not all occur', function() {
    var f = mach.mockFunction('f');

    shouldFailWith('not all calls occurred', function() {
      f.shouldBeCalled().andAlso(f.shouldBeCalledWith(1, 2, 3)).when(function() {
        f(1, 2, 3);
      });
    });
  });

  it('should be able to verify that multiple functions are called', function() {
    var f1 = mach.mockFunction('f1');
    var f2 = mach.mockFunction('f2');

    f1.shouldBeCalled().andAlso(f2.shouldBeCalledWith(1, 2, 3)).when(function() {
      f1();
      f2(1, 2, 3);
    });
  });

  it('should allow an existing function to be mocked', function() {
    function f() {};
    var fMock = mach.mockFunction(f);

    shouldFailWith('unexpected function call f()', function() {
      fMock();
    });
  });

  it('should allow functions to be used to improve readability', function() {
    var f1 = mach.mockFunction('f1');
    var f2 = mach.mockFunction('f1');

    function somethingShouldHappen() {
      return f1.shouldBeCalled();
    }

    function anotherThingShouldHappen() {
      return f2.shouldBeCalledWith(1, 2, 3);
    }

    function theCodeUnderTestRuns() {
      f1();
      f2(1, 2, 3);
    }

    somethingShouldHappen().
    andAlso(anotherThingShouldHappen()).
    when(theCodeUnderTestRuns)
  })

  it('should allow an object containing functions to be mocked', function() {
    var someObject = {
      foo: function() {},
      bar: function() {}
    }

    mockedObject = mach.mockObject(someObject, 'someObject');

    mockedObject.foo.shouldBeCalledWith(1)
      .andAlso(mockedObject.bar.shouldBeCalled())
      .when(function() {
        mockedObject.foo(1);
        mockedObject.bar();
      });
  });

  it('should let you expect a function to be called multiple times', function() {
    var f = mach.mockFunction('f');

    f.shouldBeCalledWith(2).andWillReturn(1).multipleTimes(3).when(function() {
      expect(f(2)).toBe(1);
      expect(f(2)).toBe(1);
      expect(f(2)).toBe(1);
    });
  });

  it('should fail if a function is not called enough times', function() {
    shouldFailWith('not all calls occurred', function() {
      var f = mach.mockFunction();

      f.shouldBeCalledWith(2).multipleTimes(3).when(function() {
        f(2);
        f(2);
      });
    });
  });

  it('should fail if a function is called too many times', function() {
    shouldFailWith('unexpected function call f(2)', function() {
      var f = mach.mockFunction('f');

      f.shouldBeCalledWith(2).multipleTimes(2).when(function() {
        f(2);
        f(2);
        f(2);
      });
    });
  });

  it('should allow after to be used as an alias for when', function() {
    var f = mach.mockFunction();

    f.shouldBeCalled().after(function() {
      f()
    });
  });

  it('should allow and to be used as an alias for andAlso', function() {
    var f = mach.mockFunction('f');

    f.shouldBeCalled().and(f.shouldBeCalledWith(1, 2, 3)).when(function() {
      f();
      f(1, 2, 3);
    });
  });

  it('should fail if andWillReturn is not preceeded by shouldBeCalled or shouldBeCalledWith', function() {
    var f = mach.mockFunction('f');

    shouldFail(function() {
      f.andWillReturn(1);
    });
  });

  it('should fail if when is not preceeded by shouldBeCalled or shouldBeCalledWith', function() {
    var f = mach.mockFunction('f');

    shouldFail(function() {
      f.when(function() {});
    });
  });

  it('should fail if after is not preceeded by shouldBeCalled or shouldBeCalledWith', function() {
    var f = mach.mockFunction('f');

    shouldFail(function() {
      f.after(function() {});
    });
  });

  it('should fail if shouldBeCalled is used after a call has already been specified', function() {
    var f = mach.mockFunction('f');

    shouldFail(function() {
      f.shouldBeCalled().shouldBeCalled();
    });
  });

  it('should fail if shouldBeCalledWith is used after a call has already been specified', function() {
    var f = mach.mockFunction('f');

    shouldFail(function() {
      f.shouldBeCalled().shouldBeCalledWith(4);
    });
  });

  it('should allow calls to happen out of order when andAlso is used', function() {
    var f1 = mach.mockFunction('f1');
    var f2 = mach.mockFunction('f2');

    f1.shouldBeCalled()
      .andAlso(f2.shouldBeCalled())
      .when(function() {
        f2();
        f1();
      });

    f1.shouldBeCalledWith(1)
      .andAlso(f1.shouldBeCalledWith(2))
      .when(function() {
        f1(2);
        f1(1);
      });
  });

  it('should not allow calls to happen out of order when andThen is used', function() {
    var f1 = mach.mockFunction('f1');
    var f2 = mach.mockFunction('f2');

    shouldFailWith('out of order function call f2()', function() {
      f1.shouldBeCalled()
        .andThen(f2.shouldBeCalled())
        .when(function() {
          f2();
          f1();
        });
    });

    shouldFailWith('unexpected arguments (2) provided to function f1', function() {
      f1.shouldBeCalledWith(1)
        .andThen(f2.shouldBeCalled(2))
        .when(function() {
          f1(2)
          f1(1)
        });
    });
  });

  it('should allow then to be used as a synonym for andThen', function() {
    var f1 = mach.mockFunction('f1');
    var f2 = mach.mockFunction('f2');

    shouldFailWith('out of order function call f2()', function() {
      f1.shouldBeCalled()
        .then(f2.shouldBeCalled())
        .when(function() {
          f2();
          f1();
        });
    });
  });

  it('should catch out of order calls when mixed with unordered calls', function() {
    var f1 = mach.mockFunction('f1');
    var f2 = mach.mockFunction('f2');
    var f3 = mach.mockFunction('f3');

    shouldFailWith('out of order function call f3()', function() {
      f1.shouldBeCalled()
        .and(f2.shouldBeCalled())
        .then(f3.shouldBeCalled())
        .when(function() {
          f2();
          f3();
          f1();
        });
    });
  });

  it('should allow ordered and unordered calls to be mixed', function() {
    var f = mach.mockFunction('f');

    f.shouldBeCalledWith(1)
      .andAlso(f.shouldBeCalledWith(2))
      .andThen(f.shouldBeCalledWith(3))
      .andAlso(f.shouldBeCalledWith(4))
      .when(function() {
        f(2);
        f(1);
        f(4);
        f(3);
      });
  });

  it('should allow you to mix and match call types', function() {
    var f1 = mach.mockFunction('f1');
    var f2 = mach.mockFunction('f2');

    f1.shouldBeCalled()
      .andAlso(f2.shouldBeCalledWith(1, 2, 3))
      .andThen(f2.shouldBeCalledWith(1).andWillReturn(4))
      .when(function() {
        f1();
        f2(1, 2, 3);
        expect(f2(1)).toBe(4);
      });
  });

  it('should maintain independent expectations', function() {
    var f = mach.mockFunction('f');

    f.shouldBeCalled();

    f.shouldBeCalled().when(function() {
      f();
    });
  });

  it('should allow soft expectations to be called', function() {
    var f = mach.mockFunction('f');

    f.mayBeCalled().when(function() {
      f();
    });
  });

  it('should allow soft expectations to be omitted', function() {
    var f = mach.mockFunction('f');

    f.mayBeCalled().when(function() {});
  });

  it('should allow soft expectations with return values', function() {
    var f = mach.mockFunction('f');

    f.mayBeCalled().andWillReturn(3).when(function() {
      expect(f()).toBe(3);
    });
  });

  it('should allow soft expectations with arguments to be called', function() {
    var f = mach.mockFunction('f');

    f.mayBeCalledWith(4).when(function() {
      f(4);
    });

    f.mayBeCalledWith(4).when(function() {
      f(4);
    });
  });

  it('should allow soft expectations with arguments to be omitted', function() {
    var f = mach.mockFunction('f');

    f.mayBeCalledWith(4).when(function() {});
  });

  it('should fail if mayBeCalled is used after a call has already been specified', function() {
    shouldFail(function() {
      var f = mach.mockFunction('f');

      f.shouldBeCalled().mayBeCalled();
    });
  });

  it('should fail if mayBeCalledWith is used after a call has already been specified', function() {
    shouldFail(function() {
      var f = mach.mockFunction('f');

      f.shouldBeCalled().mayBeCalledWith(4);
    });
  });

  it('should handle object arguments in error messages', function() {
    var a = {}

    shouldFailWith('unexpected function call f(' + a.toString() + ')', function() {
      mach.mockFunction('f')(a);
    });
  });

  it('should allow a strictly ordered call to occur after a missing optional call', function() {
    var f1 = mach.mockFunction('f1');
    var f2 = mach.mockFunction('f2');

    f1.mayBeCalled().andThen(f2.shouldBeCalled()).when(function() {
      f2();
    });
  });

  it('should not allow order to be violated for an optional call', function() {
    var f1 = mach.mockFunction('f1');
    var f2 = mach.mockFunction('f2');

    shouldFailWith('unexpected function call f1()', function() {
      f1.mayBeCalled().andThen(f2.shouldBeCalled()).when(function() {
        f2();
        f1();
      });
    });
  });

  it('should indicate expectation status in unexpected call failures', function() {
    var f1 = mach.mockFunction('f1');
    var f2 = mach.mockFunction('f2');

    var failureMessage =
      'completed calls:\n' +
      '\tf1()\n' +
      'incomplete calls:\n' +
      '\tf2()';

    shouldFailWith(failureMessage, function() {
      f1.shouldBeCalled().andThen(f2.shouldBeCalled()).when(function() {
        f1();
        f1();
      });
    });
  });

  it('should indicate expectation status in unexpected arguments failures', function() {
    var f1 = mach.mockFunction('f1');
    var f2 = mach.mockFunction('f2');

    var failureMessage =
      'completed calls:\n' +
      '\tf1()\n' +
      'incomplete calls:\n' +
      '\tf2()';

    shouldFailWith(failureMessage, function() {
      f1.shouldBeCalled().andThen(f2.shouldBeCalled()).when(function() {
        f1();
        f2(1);
      });
    });
  });

  it('should indicate expectation status in out of order call failures', function() {
    var f1 = mach.mockFunction('f1');
    var f2 = mach.mockFunction('f2');

    var failureMessage =
      'completed calls:\n' +
      '\tf1()\n' +
      'incomplete calls:\n' +
      '\tf2()\n'
      '\tf1()';

    shouldFailWith(failureMessage, function() {
      f1.shouldBeCalled().andThen(f2.shouldBeCalled()).andThen(f1.shouldBeCalled()).when(function() {
        f1();
        f1();
      });
    });
  });

  // more verbose errors: print call status
  // don't show complete/incomplete when there are none
  //
  // match object arguments (non-primitive equality)
  //
  // ignore arguments
});
<commit_msg>Extracted mock creation out of tests to make tests more concise<commit_after>describe('mach', function() {
  var mach = require('./../index.js');
  var f = mach.mockFunction('f');
  var f1 = mach.mockFunction('f1');
  var f2 = mach.mockFunction('f2');

  it('should be able to verify that a function is called', function() {
    f.shouldBeCalled().when(function() {
      f();
    });
  });

  it('should fail when an expected function call does not occur', function() {
    shouldFailWith('not all calls occurred', function() {
      f.shouldBeCalled().when(function() {});
    });
  });

  it('should fail when a different mock is called instead of the expected mock', function() {
    shouldFailWith('unexpected function call f2()', function() {
      f1.shouldBeCalled().when(function() {
        f2();
      });
    });
  });

  it('should fail when a function is called unexpectedly', function() {
    shouldFailWith('unexpected function call f()', function() {
      f();
    });
  });

  it('should fail when a function is called unexpectedly after a successful expectation', function() {
    f.shouldBeCalled().when(function() {
      f();
    });

    shouldFailWith('unexpected function call f()', function() {
      f();
    });
  });

  it('should be able to verify that a function has been called with the correct arguments', function() {
    f.shouldBeCalledWith(1, '2').when(function() {
      f(1, '2');
    });
  });

  it('should fail when a function iss been called with incorrect arguments', function() {
    shouldFailWith('unexpected arguments (1, \'3\') provided to function f', function() {
      f.shouldBeCalledWith(1, '2').when(function() {
        f(1, '3');
      });
    });
  });

  it('should allow the return value of a mocked function to be specified', function() {
    f.shouldBeCalled().andWillReturn(4).when(function() {
      expect(f()).toBe(4);
    });
  });

  it('should allow multiple function calls to be expected', function() {
    f.shouldBeCalled().andAlso(f.shouldBeCalledWith(1, 2, 3)).when(function() {
      f();
      f(1, 2, 3);
    });
  });

  it('should fail if multiplle function calls are expected but not all occur', function() {
    shouldFailWith('not all calls occurred', function() {
      f.shouldBeCalled().andAlso(f.shouldBeCalledWith(1, 2, 3)).when(function() {
        f(1, 2, 3);
      });
    });
  });

  it('should be able to verify that multiple functions are called', function() {
    f1.shouldBeCalled().andAlso(f2.shouldBeCalledWith(1, 2, 3)).when(function() {
      f1();
      f2(1, 2, 3);
    });
  });

  it('should allow an existing function to be mocked', function() {
    function f() {};
    var fMock = mach.mockFunction(f);

    shouldFailWith('unexpected function call f()', function() {
      fMock();
    });
  });

  it('should allow functions to be used to improve readability', function() {
    var f1 = mach.mockFunction('f1');
    var f2 = mach.mockFunction('f1');

    function somethingShouldHappen() {
      return f1.shouldBeCalled();
    }

    function anotherThingShouldHappen() {
      return f2.shouldBeCalledWith(1, 2, 3);
    }

    function theCodeUnderTestRuns() {
      f1();
      f2(1, 2, 3);
    }

    somethingShouldHappen().
    andAlso(anotherThingShouldHappen()).
    when(theCodeUnderTestRuns)
  })

  it('should allow an object containing functions to be mocked', function() {
    var someObject = {
      foo: function() {},
      bar: function() {}
    }

    mockedObject = mach.mockObject(someObject, 'someObject');

    mockedObject.foo.shouldBeCalledWith(1)
      .andAlso(mockedObject.bar.shouldBeCalled())
      .when(function() {
        mockedObject.foo(1);
        mockedObject.bar();
      });
  });

  it('should let you expect a function to be called multiple times', function() {
    f.shouldBeCalledWith(2).andWillReturn(1).multipleTimes(3).when(function() {
      expect(f(2)).toBe(1);
      expect(f(2)).toBe(1);
      expect(f(2)).toBe(1);
    });
  });

  it('should fail if a function is not called enough times', function() {
    shouldFailWith('not all calls occurred', function() {
      var f = mach.mockFunction();

      f.shouldBeCalledWith(2).multipleTimes(3).when(function() {
        f(2);
        f(2);
      });
    });
  });

  it('should fail if a function is called too many times', function() {
    shouldFailWith('unexpected function call f(2)', function() {
      f.shouldBeCalledWith(2).multipleTimes(2).when(function() {
        f(2);
        f(2);
        f(2);
      });
    });
  });

  it('should allow after to be used as an alias for when', function() {
    var f = mach.mockFunction();

    f.shouldBeCalled().after(function() {
      f()
    });
  });

  it('should allow and to be used as an alias for andAlso', function() {
    f.shouldBeCalled().and(f.shouldBeCalledWith(1, 2, 3)).when(function() {
      f();
      f(1, 2, 3);
    });
  });

  it('should fail if andWillReturn is not preceeded by shouldBeCalled or shouldBeCalledWith', function() {
    shouldFail(function() {
      f.andWillReturn(1);
    });
  });

  it('should fail if when is not preceeded by shouldBeCalled or shouldBeCalledWith', function() {
    shouldFail(function() {
      f.when(function() {});
    });
  });

  it('should fail if after is not preceeded by shouldBeCalled or shouldBeCalledWith', function() {
    shouldFail(function() {
      f.after(function() {});
    });
  });

  it('should fail if shouldBeCalled is used after a call has already been specified', function() {
    shouldFail(function() {
      f.shouldBeCalled().shouldBeCalled();
    });
  });

  it('should fail if shouldBeCalledWith is used after a call has already been specified', function() {
    shouldFail(function() {
      f.shouldBeCalled().shouldBeCalledWith(4);
    });
  });

  it('should allow calls to happen out of order when andAlso is used', function() {
    f1.shouldBeCalled()
      .andAlso(f2.shouldBeCalled())
      .when(function() {
        f2();
        f1();
      });

    f1.shouldBeCalledWith(1)
      .andAlso(f1.shouldBeCalledWith(2))
      .when(function() {
        f1(2);
        f1(1);
      });
  });

  it('should not allow calls to happen out of order when andThen is used', function() {
    shouldFailWith('out of order function call f2()', function() {
      f1.shouldBeCalled()
        .andThen(f2.shouldBeCalled())
        .when(function() {
          f2();
          f1();
        });
    });

    shouldFailWith('unexpected arguments (2) provided to function f1', function() {
      f1.shouldBeCalledWith(1)
        .andThen(f2.shouldBeCalled(2))
        .when(function() {
          f1(2)
          f1(1)
        });
    });
  });

  it('should allow then to be used as a synonym for andThen', function() {
    shouldFailWith('out of order function call f2()', function() {
      f1.shouldBeCalled()
        .then(f2.shouldBeCalled())
        .when(function() {
          f2();
          f1();
        });
    });
  });

  it('should catch out of order calls when mixed with unordered calls', function() {
    var f1 = mach.mockFunction('f1');
    var f2 = mach.mockFunction('f2');
    var f3 = mach.mockFunction('f3');

    shouldFailWith('out of order function call f3()', function() {
      f1.shouldBeCalled()
        .and(f2.shouldBeCalled())
        .then(f3.shouldBeCalled())
        .when(function() {
          f2();
          f3();
          f1();
        });
    });
  });

  it('should allow ordered and unordered calls to be mixed', function() {
    f.shouldBeCalledWith(1)
      .andAlso(f.shouldBeCalledWith(2))
      .andThen(f.shouldBeCalledWith(3))
      .andAlso(f.shouldBeCalledWith(4))
      .when(function() {
        f(2);
        f(1);
        f(4);
        f(3);
      });
  });

  it('should allow you to mix and match call types', function() {
    f1.shouldBeCalled()
      .andAlso(f2.shouldBeCalledWith(1, 2, 3))
      .andThen(f2.shouldBeCalledWith(1).andWillReturn(4))
      .when(function() {
        f1();
        f2(1, 2, 3);
        expect(f2(1)).toBe(4);
      });
  });

  it('should maintain independent expectations', function() {
    f.shouldBeCalled();

    f.shouldBeCalled().when(function() {
      f();
    });
  });

  it('should allow soft expectations to be called', function() {
    f.mayBeCalled().when(function() {
      f();
    });
  });

  it('should allow soft expectations to be omitted', function() {
    f.mayBeCalled().when(function() {});
  });

  it('should allow soft expectations with return values', function() {
    f.mayBeCalled().andWillReturn(3).when(function() {
      expect(f()).toBe(3);
    });
  });

  it('should allow soft expectations with arguments to be called', function() {
    f.mayBeCalledWith(4).when(function() {
      f(4);
    });

    f.mayBeCalledWith(4).when(function() {
      f(4);
    });
  });

  it('should allow soft expectations with arguments to be omitted', function() {
    f.mayBeCalledWith(4).when(function() {});
  });

  it('should fail if mayBeCalled is used after a call has already been specified', function() {
    shouldFail(function() {
      f.shouldBeCalled().mayBeCalled();
    });
  });

  it('should fail if mayBeCalledWith is used after a call has already been specified', function() {
    shouldFail(function() {
      f.shouldBeCalled().mayBeCalledWith(4);
    });
  });

  it('should handle object arguments in error messages', function() {
    var a = {}

    shouldFailWith('unexpected function call f(' + a.toString() + ')', function() {
      mach.mockFunction('f')(a);
    });
  });

  it('should allow a strictly ordered call to occur after a missing optional call', function() {
    f1.mayBeCalled().andThen(f2.shouldBeCalled()).when(function() {
      f2();
    });
  });

  it('should not allow order to be violated for an optional call', function() {
    shouldFailWith('unexpected function call f1()', function() {
      f1.mayBeCalled().andThen(f2.shouldBeCalled()).when(function() {
        f2();
        f1();
      });
    });
  });

  it('should indicate expectation status in unexpected call failures', function() {
    var failureMessage =
      'completed calls:\n' +
      '\tf1()\n' +
      'incomplete calls:\n' +
      '\tf2()';

    shouldFailWith(failureMessage, function() {
      f1.shouldBeCalled().andThen(f2.shouldBeCalled()).when(function() {
        f1();
        f1();
      });
    });
  });

  it('should indicate expectation status in unexpected arguments failures', function() {
    var failureMessage =
      'completed calls:\n' +
      '\tf1()\n' +
      'incomplete calls:\n' +
      '\tf2()';

    shouldFailWith(failureMessage, function() {
      f1.shouldBeCalled().andThen(f2.shouldBeCalled()).when(function() {
        f1();
        f2(1);
      });
    });
  });

  it('should indicate expectation status in out of order call failures', function() {
    var failureMessage =
      'completed calls:\n' +
      '\tf1()\n' +
      'incomplete calls:\n' +
      '\tf2()\n'
    '\tf1()';

    shouldFailWith(failureMessage, function() {
      f1.shouldBeCalled().andThen(f2.shouldBeCalled()).andThen(f1.shouldBeCalled()).when(function() {
        f1();
        f1();
      });
    });
  });

  // don't show complete/incomplete when there are none
  //
  // match object arguments (non-primitive equality)
  //
  // ignore arguments
});
<|endoftext|>


<commit_before>describe('angular-action parameter directive', function () {
    var scope,
        paramScope;

    function compile(html, scopeProperties) {
        inject(function ($rootScope, $compile) {
            scope = $rootScope.$new();
            angular.extend(scope, scopeProperties);

            var dom = angular.element(html);

            $compile(dom)(scope);
            scope.$digest();

            paramScope = dom.children().eq(0).scope();
        });
    }

    beforeEach(module('mp.action'));

    describe('scope properties', function () {
        describe('when value attribute not specified', function () {
            beforeEach(function () {
                compile(
                    '

'
                );
            });

            it('defines scope "$actionData" value as undefined', function () {
                expect(paramScope.$actionData.value).toBe(undefined);
            });
        });

        describe('when value attribute specified', function () {
            beforeEach(function () {
                compile(
                    '

'
                );
            });

            it('defines scope "$actionData" value using specified value', function () {
                expect(paramScope.$actionData.value).toBe('INIT_VALUE');
            });
        });

        it('defines scope "$actionData" error as null', function () {
            expect(paramScope.$actionData.error).toBe(null);
        });
    });

    describe('when $actionCollecting event received with a callback as the payload', function () {
        var callbackStub;

        beforeEach(function () {
            callbackStub = jasmine.createSpy('callbackStub');

            compile(
                '

'
            );
        });

        it('calls the callback with its name and current value', function () {
            paramScope.$actionData.value = 'CURRENT_VALUE';

            scope.$broadcast('$actionCollecting', callbackStub);

            expect(callbackStub).toHaveBeenCalledWith('TEST_PARAM', 'CURRENT_VALUE');
        });
    });

    describe('collect attribute', function () {
        describe('when a filter expression is supplied', function () {
            var callbackStub;

            beforeEach(function () {
                callbackStub = jasmine.createSpy('callbackStub');

                compile(
                    '

'
                );
            });

            it('calls the callback with its name and current value after passing it through the filters', function () {
                paramScope.$actionData.value = 'CURRENT_VALUE';

                scope.$broadcast('$actionCollecting', callbackStub);

                expect(callbackStub).toHaveBeenCalledWith('TEST_PARAM', 'current_value');
            });
        });
    });

    describe('on-parameter-change attribute', function () {
        describe('when an expression is supplied', function () {
            var onParameterChangeStub;

            beforeEach(function () {
                compile(
                    '

',
                    {
                        onParameterChangeStub: onParameterChangeStub = jasmine.createSpy('onParameterChangeStub')
                    }
                );
            });

            it('the expression in the attribute value is evaluated with local variable $value having the new value when the parameter value changes', function () {
                expect(onParameterChangeStub).not.toHaveBeenCalled();

                paramScope.$actionData.value = 'CURRENT_VALUE';
                paramScope.$digest();

                expect(onParameterChangeStub).toHaveBeenCalledWith('CURRENT_VALUE');
            });
        });
    });
});
<commit_msg>Test tweaks<commit_after>describe('angular-action parameter directive', function () {
    var scope,
        paramScope;

    function compile(html, scopeProperties) {
        inject(function ($rootScope, $compile) {
            scope = $rootScope.$new();
            angular.extend(scope, scopeProperties);

            var dom = angular.element(html);

            $compile(dom)(scope);
            scope.$digest();

            paramScope = dom.children().eq(0).scope();
        });
    }

    beforeEach(module('mp.action'));

    describe('scope properties', function () {
        describe('when value attribute not specified', function () {
            beforeEach(function () {
                compile(
                    '

'
                );
            });

            it('defines scope "$actionData" value as undefined', function () {
                expect(paramScope.$actionData.value).toBe(undefined);
            });

            it('defines scope "$actionData" error as null', function () {
                expect(paramScope.$actionData.error).toBe(null);
            });
        });

        describe('when value attribute specified', function () {
            beforeEach(function () {
                compile(
                    '

'
                );
            });

            it('defines scope "$actionData" value using specified value', function () {
                expect(paramScope.$actionData.value).toBe('INIT_VALUE');
            });

            it('defines scope "$actionData" error as null', function () {
                expect(paramScope.$actionData.error).toBe(null);
            });
        });
    });

    describe('when $actionCollecting event received', function () {
        var setValueStub,
            flagErrorStub;

        beforeEach(function () {
            setValueStub = jasmine.createSpy('setValueStub');
            flagErrorStub = jasmine.createSpy('flagErrorStub');

            compile(
                '

'
            );

            scope.$broadcast('$actionCollecting', setValueStub, flagErrorStub);
        });

        it('calls the setter callback with its name and current value', function () {
            expect(setValueStub).toHaveBeenCalledWith('TEST_PARAM', 'INIT_VALUE');
        });

        it('does not call the error callback', function () {
            expect(flagErrorStub).not.toHaveBeenCalled();
        });
    });

    describe('collect attribute', function () {
        describe('when a filter expression is supplied', function () {
            describe('when none of the filters cause an exception', function () {
                var setValueStub,
                    flagErrorStub;

                beforeEach(function () {
                    setValueStub = jasmine.createSpy('setValueStub');
                    flagErrorStub = jasmine.createSpy('flagErrorStub');

                    compile(
                        '

'
                    );

                    scope.$broadcast('$actionCollecting', setValueStub);
                });

                it('calls the setter callback with the current value after passing it through the filters', function () {
                    expect(setValueStub).toHaveBeenCalledWith('TEST_PARAM', 'init_value');
                });

                it('does not call the error callback', function () {
                    expect(flagErrorStub).not.toHaveBeenCalled();
                });
            });

            // describe('when one of the filters causes an exception', function () {
            //     var setValueStub,
            //         flagErrorStub,
            //         exception;

            //     beforeEach(inject(function ($filterProvider) {
            //         setValueStub = jasmine.createSpy('setValueStub');
            //         flagErrorStub = jasmine.createSpy('flagErrorStub');
            //         exception = new Error();

            //         $filterProvider.register('throwsException', function () {
            //             throw exception;
            //         });

            //         compile(
            //             '

'
            //         );

            //         scope.$broadcast('$actionCollecting', setValueStub);
            //     }));

            //     it('does not call the setter callback', function () {
            //         expect(setValueStub).not.toHaveBeenCalled();
            //     });

            //     it('calls the error callback with the exception', function () {
            //         expect(flagErrorStub).toHaveBeenCalledWith(exception);
            //     });
            // });
        });
    });

    describe('on-parameter-change attribute', function () {
        describe('when an expression is supplied', function () {
            var onParameterChangeStub;

            beforeEach(function () {
                onParameterChangeStub = jasmine.createSpy('onParameterChangeStub');

                compile(
                    '

',
                    {
                        onParameterChangeStub: onParameterChangeStub
                    }
                );
            });

            it('the expression in the attribute value is not initially evaluated', function () {
                expect(onParameterChangeStub).not.toHaveBeenCalled();
            });

            describe('when the value changes', function () {
                beforeEach(function () {
                    paramScope.$actionData.value = 'NEW_VALUE';
                    paramScope.$digest();
                });

                it('the expression in the attribute value is evaluated with local variable $value having the new value', function () {
                    expect(onParameterChangeStub).toHaveBeenCalledWith('NEW_VALUE');
                });
            });
        });
    });
});
<|endoftext|>


<commit_before>describe('parse', function () {
  it('parse application id', (done) => {
    expect(Parse.applicationId).toEqual(process.env.APP_ID || 'myAppId');
    done();
  });

  it('create object', (done) => {
    let objId;
    const _obj = new Parse.Object('AnObject');
    _obj.save()
      .then(obj => {
        objId = obj.id;
        const q = new Parse.Query('AnObject');
        return q.first();
      })
      .then(obj => {
        expect(obj.id).toEqual(objId);
        done();
      })
      .catch((error) => {
        fail(JSON.stringify(error));
        done();
      });
  });
});
<commit_msg>parse test bug fix<commit_after>describe('parse', function () {
  it('parse application id', (done) => {
    expect(Parse.applicationId).toEqual(process.env.APP_ID || 'myAppId');
    done();
  });

  it('create object', (done) => {
    let objId;
    const _obj = new Parse.Object('AnObject');
    _obj.save()
      .then(obj => {
        objId = obj.id;
        const q = new Parse.Query('AnObject');
        q.descending('createdAt');
        return q.first();
      })
      .then(obj => {
        expect(obj.id).toEqual(objId);
        done();
      })
      .catch((error) => {
        fail(JSON.stringify(error));
        done();
      });
  });
});
<|endoftext|>


<commit_before>import m from 'mithril';
import ClipboardJS from 'clipboard';
import classNames from '../classnames.js';

// The area of the game UI consisting of game UI controls and status messages
class DashboardComponent {

  oninit({ attrs: { game, session } }) {
    this.game = game;
    this.session = session;
  }

  // Prepare game players by creating new players (if necessary) and deciding
  // which player has the starting move
  setPlayers(gameType) {
    if (this.game.players.length > 0) {
      // Reset new games before choosing number of players (no need to reset
      // the very first game)
      this.game.resetGame();
    }
    this.game.setPlayers(gameType);
  }

  startGame(newStartingPlayer) {
    this.game.startGame({
      startingPlayer: newStartingPlayer
    });
  }

  endGame(roomCode) {
    if (roomCode) {
      // The local player ID and room code will be automatically passed by the
      // session.emit() function
      this.session.emit('end-game');
    } else {
      this.game.endGame();
    }
  }

  returnToHome() {
    this.session.disconnect();
    // Redirect to homepage and clear all app state
    window.location.href = '/';
  }

  closeRoom() {
    this.session.status = 'closingRoom';
    this.session.emit('close-room', {}, () => {
      this.returnToHome();
    });
  }

  declineNewGame() {
    this.session.status = 'leavingRoom';
    this.session.emit('decline-new-game', {}, () => {
      this.returnToHome();
    });
  }

  createNewPlayer() {
    this.session.status = 'newPlayer';
  }

  setNewPlayerName(inputEvent) {
    this.newPlayerName = inputEvent.target.value;
    inputEvent.redraw = false;
  }

  submitNewPlayer(submitEvent, roomCode) {
    submitEvent.preventDefault();
    if (roomCode) {
      this.addNewPlayerToGame(roomCode);
    } else {
      this.startOnlineGame();
    }
  }

  addNewPlayerToGame(roomCode) {
    this.session.status = 'connecting';
    const submittedPlayer = { name: this.newPlayerName, color: 'blue' };
    this.session.emit('add-player', { roomCode, player: submittedPlayer }, ({ game, localPlayer }) => {
      this.game.restoreFromServer({ game, localPlayer });
      m.redraw();
    });
  }

  startOnlineGame() {
    this.session.connect();
    // Construct a placeholder player with the name we entered and the default
    // first player color
    const submittedPlayer = { name: this.newPlayerName, color: 'red' };
    // Request a new room and retrieve the room code returned from the server
    this.session.emit('open-room', { player: submittedPlayer }, ({ roomCode, game, localPlayer }) => {
      this.game.restoreFromServer({ game, localPlayer });
      console.log('new room', roomCode);
      m.route.set(`/room/${roomCode}`);
    });
  }

  requestNewOnlineGame() {
    this.session.status = 'connecting';
    this.session.emit('request-new-game', { winner: this.game.winner }, ({ localPlayer }) => {
      if (this.session.status === 'requestingNewGame') {
        this.game.requestingPlayer = localPlayer;
      }
      m.redraw();
    });
  }

  configureCopyControl({ dom }) {
    this.shareLinkCopier = new ClipboardJS(dom);
  }

  view({ attrs: { roomCode } }) {
    return m('div#game-dashboard', {
      class: classNames({ 'prompting-for-input': this.session.status === 'newPlayer' })
    }, [
      m('p#game-message',

        this.session.status === 'connecting' ?
          'Connecting to server...' :
        this.session.status === 'roomNotFound' ?
          'This room does not exist or has been closed by the host.' :
        this.session.status === 'closingRoom' ?
          'Closing room...' :
        this.session.status === 'leavingRoom' ?
          'Leaving room...' :
        this.session.disconnected ?
          'Lost connection. Trying to reconnect...' :

        // If the other player disconnects
        this.session.disconnectedPlayer && this.session.disconnectedPlayer.lastDisconnectReason === 'newGameDeclined' ?
          `${this.session.disconnectedPlayer.name} has declined to play again.` :
        this.session.disconnectedPlayer ?
          `${this.session.disconnectedPlayer.name} has disconnected.` :

        // If the other player reconnects
        this.session.reconnectedPlayer ?
          `${this.session.reconnectedPlayer.name} has reconnected.` :

        // If the current player needs to enter a name
        this.session.status === 'newPlayer' ?
          m('label[for=new-player-name]', 'Enter your player name:') :

        this.session.status === 'waitingForPlayers' ?
          [
            'Waiting for other player...',
            m('div#share-controls', [
              m('input[type=text]#share-link', {
                value: window.location.href,
                onclick: ({ target }) => target.select()
              }),
              m('button#copy-share-link', {
                'data-clipboard-text': window.location.href,
                oncreate: ({ dom }) => this.configureCopyControl({ dom })
              }, 'Copy')
            ])
          ] :

        // If the local player has requested a new game
        this.session.status === 'requestingNewGame' ?
          `Asking ${this.game.getOtherPlayer(this.game.requestingPlayer).name} to play again...` :
        // Inform the other player if a player requests a new game
        this.session.status === 'newGameRequested' ?
          `${this.game.requestingPlayer.name} asks to play again.` :
        // If user has not started any game yet
        this.game.players.length === 0 ?
          'Welcome! How many players?' :
        // If a game is in progress
        this.game.currentPlayer ?
          `${this.game.currentPlayer.name}, your turn!` :
        // If a player wins the game
        this.game.winner ?
          `${this.game.winner.name} wins! Play again?` :
        // If the grid is completely full
        this.game.grid.checkIfFull() ?
          'We\'ll call it a draw! Play again?' :
        // If the user just chose a number of players for the game to be started
        !this.session.socket && this.game.type !== null ?
          'Which player should start first?' :
        // If either player ends the game early
        roomCode && this.game.requestingPlayer ?
          `${this.game.requestingPlayer.name} has ended the game.` :
        // Otherwise, if game was ended manually by the user
        'Game ended. Play again?'
      ),

      // If P1 is still waiting for players, offer P1 the option to close room
      this.session.status === 'waitingForPlayers' ? [
        m('button.warn', { onclick: () => this.closeRoom() }, 'Close Room')
      ] :

      // If game is in progress, allow user to end game at any time
      this.game.inProgress && this.session.status !== 'watchingGame' && !this.session.disconnected ? [
        m('button.warn', { onclick: () => this.endGame(roomCode) }, 'End Game')
      ] :

      // If an online game is not in progress (i.e. it was ended early, or there
      // is a winner/tie), allow the user to play again
      this.session.socket && this.game.players.length === 2 && this.session.status !== 'connecting' && this.session.status !== 'watchingGame' && !this.session.disconnectedPlayer && !this.session.reconnectedPlayer && !this.session.disconnected ? [

        // Play Again / Yes
        m('button', {
          onclick: () => this.requestNewOnlineGame(),
          disabled: this.session.status === 'requestingNewGame'
        }, this.session.status === 'newGameRequested' ? 'Yes!' : this.session.status === 'requestingNewGame' ? 'Pending' : 'Play Again'),

        // No Thanks
        this.session.status !== 'requestingNewGame' ? m('button.warn', {
          onclick: () => this.declineNewGame(),
          disabled: this.session.status === 'requestingNewGame'
        }, this.session.status === 'newGameRequested' ? 'Nah' : this.session.status !== 'requestingNewGame' ? 'No Thanks' : null) : null

      ] :

      // Prompt a player to enter their name when starting an online game, or
      // when joining an existing game for the first time
      this.session.status === 'newPlayer' ? [
        m('form', {
          onsubmit: (submitEvent) => this.submitNewPlayer(submitEvent, roomCode)
        }, [
          m('input[type=text][autocomplete=off]#new-player-name', {
            name: 'new-player-name',
            autofocus: true,
            required: true,
            oninput: (inputEvent) => this.setNewPlayerName(inputEvent)
          }),
          m('button[type=submit]', roomCode ? 'Join Game' : 'Start Game')
        ])
      ] :

      !this.session.socket ? [

        // If number of players has been chosen, ask user to choose starting player
        this.game.type !== null ?
          this.game.players.map((player) => {
            return m('button', {
              onclick: () => this.startGame(player)
            }, player.name);
          }) :

          // Select a number of human players
          [
            m('button', {
              onclick: () => this.setPlayers({ gameType: '1P' })
            }, '1 Player'),
            m('button', {
              onclick: () => this.setPlayers({ gameType: '2P' })
            }, '2 Players'),
            m('button', {
              onclick: () => this.createNewPlayer()
            }, 'Online')
          ]

        ] : null
    ]);
  }

}

export default DashboardComponent;
<commit_msg>Add break within roomNotFound message<commit_after>import m from 'mithril';
import ClipboardJS from 'clipboard';
import classNames from '../classnames.js';

// The area of the game UI consisting of game UI controls and status messages
class DashboardComponent {

  oninit({ attrs: { game, session } }) {
    this.game = game;
    this.session = session;
  }

  // Prepare game players by creating new players (if necessary) and deciding
  // which player has the starting move
  setPlayers(gameType) {
    if (this.game.players.length > 0) {
      // Reset new games before choosing number of players (no need to reset
      // the very first game)
      this.game.resetGame();
    }
    this.game.setPlayers(gameType);
  }

  startGame(newStartingPlayer) {
    this.game.startGame({
      startingPlayer: newStartingPlayer
    });
  }

  endGame(roomCode) {
    if (roomCode) {
      // The local player ID and room code will be automatically passed by the
      // session.emit() function
      this.session.emit('end-game');
    } else {
      this.game.endGame();
    }
  }

  returnToHome() {
    this.session.disconnect();
    // Redirect to homepage and clear all app state
    window.location.href = '/';
  }

  closeRoom() {
    this.session.status = 'closingRoom';
    this.session.emit('close-room', {}, () => {
      this.returnToHome();
    });
  }

  declineNewGame() {
    this.session.status = 'leavingRoom';
    this.session.emit('decline-new-game', {}, () => {
      this.returnToHome();
    });
  }

  createNewPlayer() {
    this.session.status = 'newPlayer';
  }

  setNewPlayerName(inputEvent) {
    this.newPlayerName = inputEvent.target.value;
    inputEvent.redraw = false;
  }

  submitNewPlayer(submitEvent, roomCode) {
    submitEvent.preventDefault();
    if (roomCode) {
      this.addNewPlayerToGame(roomCode);
    } else {
      this.startOnlineGame();
    }
  }

  addNewPlayerToGame(roomCode) {
    this.session.status = 'connecting';
    const submittedPlayer = { name: this.newPlayerName, color: 'blue' };
    this.session.emit('add-player', { roomCode, player: submittedPlayer }, ({ game, localPlayer }) => {
      this.game.restoreFromServer({ game, localPlayer });
      m.redraw();
    });
  }

  startOnlineGame() {
    this.session.connect();
    // Construct a placeholder player with the name we entered and the default
    // first player color
    const submittedPlayer = { name: this.newPlayerName, color: 'red' };
    // Request a new room and retrieve the room code returned from the server
    this.session.emit('open-room', { player: submittedPlayer }, ({ roomCode, game, localPlayer }) => {
      this.game.restoreFromServer({ game, localPlayer });
      console.log('new room', roomCode);
      m.route.set(`/room/${roomCode}`);
    });
  }

  requestNewOnlineGame() {
    this.session.status = 'connecting';
    this.session.emit('request-new-game', { winner: this.game.winner }, ({ localPlayer }) => {
      if (this.session.status === 'requestingNewGame') {
        this.game.requestingPlayer = localPlayer;
      }
      m.redraw();
    });
  }

  configureCopyControl({ dom }) {
    this.shareLinkCopier = new ClipboardJS(dom);
  }

  view({ attrs: { roomCode } }) {
    return m('div#game-dashboard', {
      class: classNames({ 'prompting-for-input': this.session.status === 'newPlayer' })
    }, [
      m('p#game-message',

        this.session.status === 'connecting' ?
          'Connecting to server...' :
        this.session.status === 'roomNotFound' ?
          [
            'This room does not exist',
            m('br'),
            'or has been closed by the host.'
          ] :
        this.session.status === 'closingRoom' ?
          'Closing room...' :
        this.session.status === 'leavingRoom' ?
          'Leaving room...' :
        this.session.disconnected ?
          'Lost connection. Trying to reconnect...' :

        // If the other player disconnects
        this.session.disconnectedPlayer && this.session.disconnectedPlayer.lastDisconnectReason === 'newGameDeclined' ?
          `${this.session.disconnectedPlayer.name} has declined to play again.` :
        this.session.disconnectedPlayer ?
          `${this.session.disconnectedPlayer.name} has disconnected.` :

        // If the other player reconnects
        this.session.reconnectedPlayer ?
          `${this.session.reconnectedPlayer.name} has reconnected.` :

        // If the current player needs to enter a name
        this.session.status === 'newPlayer' ?
          m('label[for=new-player-name]', 'Enter your player name:') :

        this.session.status === 'waitingForPlayers' ?
          [
            'Waiting for other player...',
            m('div#share-controls', [
              m('input[type=text]#share-link', {
                value: window.location.href,
                onclick: ({ target }) => target.select()
              }),
              m('button#copy-share-link', {
                'data-clipboard-text': window.location.href,
                oncreate: ({ dom }) => this.configureCopyControl({ dom })
              }, 'Copy')
            ])
          ] :

        // If the local player has requested a new game
        this.session.status === 'requestingNewGame' ?
          `Asking ${this.game.getOtherPlayer(this.game.requestingPlayer).name} to play again...` :
        // Inform the other player if a player requests a new game
        this.session.status === 'newGameRequested' ?
          `${this.game.requestingPlayer.name} asks to play again.` :
        // If user has not started any game yet
        this.game.players.length === 0 ?
          'Welcome! How many players?' :
        // If a game is in progress
        this.game.currentPlayer ?
          `${this.game.currentPlayer.name}, your turn!` :
        // If a player wins the game
        this.game.winner ?
          `${this.game.winner.name} wins! Play again?` :
        // If the grid is completely full
        this.game.grid.checkIfFull() ?
          'We\'ll call it a draw! Play again?' :
        // If the user just chose a number of players for the game to be started
        !this.session.socket && this.game.type !== null ?
          'Which player should start first?' :
        // If either player ends the game early
        roomCode && this.game.requestingPlayer ?
          `${this.game.requestingPlayer.name} has ended the game.` :
        // Otherwise, if game was ended manually by the user
        'Game ended. Play again?'
      ),

      // If P1 is still waiting for players, offer P1 the option to close room
      this.session.status === 'waitingForPlayers' ? [
        m('button.warn', { onclick: () => this.closeRoom() }, 'Close Room')
      ] :

      // If game is in progress, allow user to end game at any time
      this.game.inProgress && this.session.status !== 'watchingGame' && !this.session.disconnected ? [
        m('button.warn', { onclick: () => this.endGame(roomCode) }, 'End Game')
      ] :

      // If an online game is not in progress (i.e. it was ended early, or there
      // is a winner/tie), allow the user to play again
      this.session.socket && this.game.players.length === 2 && this.session.status !== 'connecting' && this.session.status !== 'watchingGame' && !this.session.disconnectedPlayer && !this.session.reconnectedPlayer && !this.session.disconnected ? [

        // Play Again / Yes
        m('button', {
          onclick: () => this.requestNewOnlineGame(),
          disabled: this.session.status === 'requestingNewGame'
        }, this.session.status === 'newGameRequested' ? 'Yes!' : this.session.status === 'requestingNewGame' ? 'Pending' : 'Play Again'),

        // No Thanks
        this.session.status !== 'requestingNewGame' ? m('button.warn', {
          onclick: () => this.declineNewGame(),
          disabled: this.session.status === 'requestingNewGame'
        }, this.session.status === 'newGameRequested' ? 'Nah' : this.session.status !== 'requestingNewGame' ? 'No Thanks' : null) : null

      ] :

      // Prompt a player to enter their name when starting an online game, or
      // when joining an existing game for the first time
      this.session.status === 'newPlayer' ? [
        m('form', {
          onsubmit: (submitEvent) => this.submitNewPlayer(submitEvent, roomCode)
        }, [
          m('input[type=text][autocomplete=off]#new-player-name', {
            name: 'new-player-name',
            autofocus: true,
            required: true,
            oninput: (inputEvent) => this.setNewPlayerName(inputEvent)
          }),
          m('button[type=submit]', roomCode ? 'Join Game' : 'Start Game')
        ])
      ] :

      !this.session.socket ? [

        // If number of players has been chosen, ask user to choose starting player
        this.game.type !== null ?
          this.game.players.map((player) => {
            return m('button', {
              onclick: () => this.startGame(player)
            }, player.name);
          }) :

          // Select a number of human players
          [
            m('button', {
              onclick: () => this.setPlayers({ gameType: '1P' })
            }, '1 Player'),
            m('button', {
              onclick: () => this.setPlayers({ gameType: '2P' })
            }, '2 Players'),
            m('button', {
              onclick: () => this.createNewPlayer()
            }, 'Online')
          ]

        ] : null
    ]);
  }

}

export default DashboardComponent;
<|endoftext|>


<commit_before>'use strict';

angular.module('cloudSlangWebsiteApp')
    .controller('CarouselCtrl', function ($scope) {

        $scope.init = function () {

            $('.carousel[data-type="multi"] .item').each(function () {
                var next = $(this).next();
                if (!next.length) {
                    next = $(this).siblings(':first');
                }
                next.children(':first-child').clone().appendTo($(this));

                for (var i = 0; i < 2; i++) {
                    next = next.next();
                    if (!next.length) {
                        next = $(this).siblings(':first');
                    }

                    next.children(':first-child').clone().appendTo($(this));
                }

            });
        };

        $scope.init();

    });
<commit_msg>fix for carousel<commit_after>'use strict';

angular.module('cloudSlangWebsiteApp')
    .controller('CarouselCtrl', function ($scope) {

        var init = function () {

            $('.carousel[data-type="multi"] .item').each(function () {
                var next = $(this).next();
                if (!next.length) {
                    next = $(this).siblings(':first');
                }
                next.children(':first-child').clone().appendTo($(this));

                for (var i = 0; i < 2; i++) {
                    next = next.next();
                    if (!next.length) {
                        next = $(this).siblings(':first');
                    }

                    next.children(':first-child').clone().appendTo($(this));
                }

            });
        };

        init();

    });
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc function
 * @name chessmateApp.controller:NotationCtrl
 * @description
 * # NotationCtrl
 * Controller of the chessmateApp
 */
angular.module('chessmateApp')
  .controller('NotationCtrl', function ($scope,$rootScope) {
    $scope.buildGame = function(notation) {

      var game = {
        "boards": [$scope.buildInitialBoard()]
      };

      $scope.generateBoardFromNotation(game.boards, notation);

      $rootScope.$broadcast('game-updated', game);
    };

    $scope.buildInitialBoard = function() {
      var board = {
        "turn": 0,
        "source": undefined,
        "destination": undefined,
        "position": {
          "A1": $scope.buildPiece('R', "white"),
          "B1": $scope.buildPiece('N', "white"),
          "C1": $scope.buildPiece('B', "white"),
          "D1": $scope.buildPiece('K', "white"),
          "E1": $scope.buildPiece('Q', "white"),
          "F1": $scope.buildPiece('B', "white"),
          "G1": $scope.buildPiece('N', "white"),
          "H1": $scope.buildPiece('R', "white"),
          "A3": $scope.buildPiece('B', "white"),
          "B3": $scope.buildPiece('B', "white"),
          "C3": $scope.buildPiece('B', "white"),
          "D3": $scope.buildPiece('B', "white"),
          "E3": $scope.buildPiece('B', "white"),
          "F3": $scope.buildPiece('B', "white"),
          "G3": $scope.buildPiece('B', "white"),
          "H3": $scope.buildPiece('B', "white"),
          "A6": $scope.buildPiece('B', "black"),
          "B6": $scope.buildPiece('B', "black"),
          "C6": $scope.buildPiece('B', "black"),
          "D6": $scope.buildPiece('B', "black"),
          "E6": $scope.buildPiece('B', "black"),
          "F6": $scope.buildPiece('B', "black"),
          "G6": $scope.buildPiece('B', "black"),
          "H6": $scope.buildPiece('B', "black"),
          "A8": $scope.buildPiece('R', "black"),
          "B8": $scope.buildPiece('N', "black"),
          "C8": $scope.buildPiece('B', "black"),
          "D8": $scope.buildPiece('K', "black"),
          "E8": $scope.buildPiece('Q', "black"),
          "F8": $scope.buildPiece('B', "black"),
          "G8": $scope.buildPiece('N', "black"),
          "H8": $scope.buildPiece('R', "black")
        }
      };

      return board;
    };

      $scope.generateBoardFromNotation = function(boardsArray,notation){

        //extract header and moves out of notation string
        var header = $scope.getHeader(notation);
        //do something with header

        var moves = $scope.getMoves(notation);

        //while still have moves
        var dotPos;

        while( (dotPos = moves.indexOf(".")) != -1){
          //find first 6 and send with white colour
          var whiteMove = moves.substring(dotPos+1,dotPos+7);
          boardsArray.push($scope.buildBoard, whiteMove, 'white');
          //find last 6 and send with black colour
          var blackMove = moves.substring(dotPos+8,dotPos+14);
          boardsArray.push($scope.buildBoard, blackMove, 'white');

          moves = moves.substring(dotPos+14);
        }

      };

      $scope.getHeader = function(notation){

      };

      $scope.getMoves = function(notation){
        var lastIndexOfBracket = notation.lastIndexOf("]");
        return  notation.substring(lastIndexOfBracket+1);
      };
    $scope.buildBoard = function(currentBoard, move, color) {
      var board = angular.copy(currentBoard);
      var char = move.substring(0, 1);
      var source = move.substring(1, 3);
      var destination = move.substring(4, 6);

      board.turn = currentBoard.turn + 1;
      board.source = source;
      board.destination = destination;
      board.position[destination] = $scope.buildPiece(char, color);
      delete board.position[source];

      return board;
    };

    $scope.buildPiece = function(char, color) {
      var piece = {
        type: $scope.getType(char),
        color: color
      };

      piece.value = buildValue(piece);

      return piece;
    };

    var buildValue = function (piece) {
      var map = Immutable.Map({
        "rookwhite": "♟",
        "rookblack": "♜"
      });
      var key = piece.type + piece.color;
      return map.get(key);
    };

    $scope.getType = function(char) {
      var type;

      if (char == 'B') {
        type = "pawn";
      } else if (char == 'R') {
        type = "rook";
      } else if (char == 'N') {
        type = "knight";
      } else if (char == 'B') {
        type = "bishop";
      } else if (char == 'K') {
        type = "king";
      } else if (char == 'M') {
        type = "queen";
      }

      return type;
    }
  });
<commit_msg>mapping all field<commit_after>'use strict';

/**
 * @ngdoc function
 * @name chessmateApp.controller:NotationCtrl
 * @description
 * # NotationCtrl
 * Controller of the chessmateApp
 */
angular.module('chessmateApp')
  .controller('NotationCtrl', function ($scope,$rootScope) {
    $scope.buildGame = function(notation) {

      var game = {
        "boards": [$scope.buildInitialBoard()]
      };

      $scope.generateBoardFromNotation(game.boards, notation);

      $rootScope.$broadcast('game-updated', game);
    };

    $scope.buildInitialBoard = function() {
      var board = {
        "turn": 0,
        "source": undefined,
        "destination": undefined,
        "position": {
          "A1": $scope.buildPiece('R', "white"),
          "B1": $scope.buildPiece('N', "white"),
          "C1": $scope.buildPiece('B', "white"),
          "D1": $scope.buildPiece('K', "white"),
          "E1": $scope.buildPiece('Q', "white"),
          "F1": $scope.buildPiece('B', "white"),
          "G1": $scope.buildPiece('N', "white"),
          "H1": $scope.buildPiece('R', "white"),
          "A3": $scope.buildPiece('B', "white"),
          "B3": $scope.buildPiece('B', "white"),
          "C3": $scope.buildPiece('B', "white"),
          "D3": $scope.buildPiece('B', "white"),
          "E3": $scope.buildPiece('B', "white"),
          "F3": $scope.buildPiece('B', "white"),
          "G3": $scope.buildPiece('B', "white"),
          "H3": $scope.buildPiece('B', "white"),
          "A6": $scope.buildPiece('B', "black"),
          "B6": $scope.buildPiece('B', "black"),
          "C6": $scope.buildPiece('B', "black"),
          "D6": $scope.buildPiece('B', "black"),
          "E6": $scope.buildPiece('B', "black"),
          "F6": $scope.buildPiece('B', "black"),
          "G6": $scope.buildPiece('B', "black"),
          "H6": $scope.buildPiece('B', "black"),
          "A8": $scope.buildPiece('R', "black"),
          "B8": $scope.buildPiece('N', "black"),
          "C8": $scope.buildPiece('B', "black"),
          "D8": $scope.buildPiece('K', "black"),
          "E8": $scope.buildPiece('Q', "black"),
          "F8": $scope.buildPiece('B', "black"),
          "G8": $scope.buildPiece('N', "black"),
          "H8": $scope.buildPiece('R', "black")
        }
      };

      return board;
    };

      $scope.generateBoardFromNotation = function(boardsArray,notation){

        //extract header and moves out of notation string
        var header = $scope.getHeader(notation);
        //do something with header

        var moves = $scope.getMoves(notation);

        //while still have moves
        var dotPos;

        while( (dotPos = moves.indexOf(".")) != -1){
          //find first 6 and send with white colour
          var whiteMove = moves.substring(dotPos+1,dotPos+7);
          boardsArray.push($scope.buildBoard, whiteMove, 'white');
          //find last 6 and send with black colour
          var blackMove = moves.substring(dotPos+8,dotPos+14);
          boardsArray.push($scope.buildBoard, blackMove, 'white');

          moves = moves.substring(dotPos+14);
        }

      };

      $scope.getHeader = function(notation){

      };

      $scope.getMoves = function(notation){
        var lastIndexOfBracket = notation.lastIndexOf("]");
        return  notation.substring(lastIndexOfBracket+1);
      };
    $scope.buildBoard = function(currentBoard, move, color) {
      var board = angular.copy(currentBoard);
      var char = move.substring(0, 1);
      var source = move.substring(1, 3);
      var destination = move.substring(4, 6);

      board.turn = currentBoard.turn + 1;
      board.source = source;
      board.destination = destination;
      board.position[destination] = $scope.buildPiece(char, color);
      delete board.position[source];

      return board;
    };

    $scope.buildPiece = function(char, color) {
      var piece = {
        type: $scope.getType(char),
        color: color
      };

      piece.value = buildValue(piece);

      return piece;
    };

    var buildValue = function (piece) {
      var map = Immutable.Map({
        "rook-black" : "♜",
        "night-black": "♞",
        "bishop-black": "♝",
        "king-black": "♛",
        "queen-black": "♚",
        "pawn-black": "♟",

        "rook-white" : "♖",
        "night-white": "♘",
        "bishop-white": "♗",
        "king-white": "♕",
        "queen-white": "♔",
        "pawn-white": "♙"
      });
      var key = piece.type +"-"+ piece.color;
      return map.get(key);
    };

    $scope.getType = function(char) {
      var type;

      if (char == 'B') {
        type = "pawn";
      } else if (char == 'R') {
        type = "rook";
      } else if (char == 'N') {
        type = "knight";
      } else if (char == 'B') {
        type = "bishop";
      } else if (char == 'K') {
        type = "king";
      } else if (char == 'M') {
        type = "queen";
      }

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


<commit_before>function InitializeHorizontalStackedBar(id,series,ticks,show_point_label,unit,axis_values,colors,labels){
  $.jqplot(id, series, {
    stackSeries: true,
    seriesColors: colors,
    grid: default_grid,
    legend: create_legend(6,'s',ticks),
    seriesDefaults: {
      renderer: $.jqplot.BarRenderer,
      pointLabels:{show:show_point_label},
      rendererOptions: {
        barDirection: 'horizontal',
        varyBarColor: true,
        barPadding: 8,
        barMargin: 30,
        shadow: false
      }
    },
    axes: {
      yaxis: {
        renderer: $.jqplot.CategoryAxisRenderer,
        ticks: labels
      },
      xaxis: {
        min: axis_values[0],
        max: axis_values[1],
        numberTicks: 6,
        tickOptions: {
          formatString: '%.2f'+unit
        }
      }
    }
  });
}<commit_msg>made the ticks a bit smaller fixes #210<commit_after>function InitializeHorizontalStackedBar(id,series,ticks,show_point_label,unit,axis_values,colors,labels){

  $.jqplot(id, series, {
    stackSeries: true,
    seriesColors: colors,
    grid: default_grid,
    legend: create_legend(6,'s',ticks),
    seriesDefaults: {
      renderer: $.jqplot.BarRenderer,
      pointLabels:{show:show_point_label},
      rendererOptions: {
        barDirection: 'horizontal',
        varyBarColor: true,
        barPadding: 8,
        barMargin: 30,
        shadow: false
      }
    },
    axes: {
      yaxis: {
        renderer: $.jqplot.CategoryAxisRenderer,
        ticks: labels
      },
      xaxis: {
        min: axis_values[0],
        max: axis_values[1],
        numberTicks: 6,
        tickOptions: {
          formatString: '%.2f'+unit,
          fontSize: '10px'
        }

      }
    }
  });
}<|endoftext|>


<commit_before>/*global define:true */
define(
    [
        'jquery',
        'backbone',
        'underscore',
        'mustache',
        'views/PeerView',
        'text!templates/video.en.tpl',
        'text!templates/audio.en.tpl'
    ],

    function ($, Backbone, _, Mustache, PeerView,templateVideo,templateAudio) {

        'use strict';

        var template = '
{{#name}}{{name}}{{/name}}{{^name}}sans nom{{/name}}

';
   /*     var templateVideo = '
' +
            '
Video
' +
            '<video src="" autoplay=true></video>' +
            '
' +
            'vidéo en pause' +
            'vidéo en cours' +
            'sans le son' +
            'avec le son' +
            ' en grand' +
            'en petit' +
            '
' +
            '
';
        var templateAudio = '
' +
            '
Audio
' +
            '
' +
            'sans le son' +
            'avec le son' +
            '
' +
            '<audio src="" autoplay=true></audio>' +
            '
';*/
        var RemotePeerView = PeerView.extend({

            initialize: function () {
            },
            _renderOneStream: function (stream, id) {
                var audios = stream.getAudioTracks();
                var videos = stream.getVideoTracks();
                if (videos.length > 1 || audios.length > 1) {
                    console.log('no support for multiple track in one stream');
                }
                var $container = null;
                var videolabel = videos.length ? videos[0].label : '';
                var audiolabel = audios.length ? audios[0].label : '';

                if (videos.length || (!videos.length && !audios.length)) {
                    $container = $(
                        Mustache.render(
                            templateVideo, {
                                videolabel: (!videos.length && !audios.length) ? '' : videolabel,
                                audiolabel: audiolabel,
                                videoId: id,
                                remote : this.model.get('remote')
                            }
                        )
                    );
                    $container.find('video').attr('src', window.URL.createObjectURL(stream));
                    $container.find('.video-status.paused').hide();
                    $container.find('.expand-status.expanded').hide();
                } else {
                    // pas de video
                    $container = $(Mustache.render(templateAudio, { audiolabel: audiolabel,
                        remote : this.model.get('remote')}));
                    $container.find('audio').attr('src', window.URL.createObjectURL(stream));
                    $container.find('.video-status').hide();
                    $container.find('.expand-status').hide();
                }
                if (audios.length) {
                    $container.find('.audio-status.muted').hide();
                } else {

                    $container.find('.audio-status').hide();
                }
                if (videos.length || audios.length) {
                    $container.find('.video-status').click(function () {
                        $container.find('.video-status').toggle();
                        stream.getVideoTracks()[0].enabled = !(stream.getVideoTracks()[0].enabled);
                    });

                    $container.find('.audio-status').click(function () {
                        $container.find('.audio-status').toggle();
                        stream.getAudioTracks()[0].enabled = !(audios[0].enabled);
                    });

                } else {
                    $container.find('.audio-status').hide();
                    $container.find('.video-status').hide();
                }

                $container.find('.expand-status').click(function () {
                    $container.find('.expand-status').toggle();
                });

                this.$('.streams-container').append($container);
                stream.onended = function () {
                    console.log('end stream');
                    $container.remove();
                };
            },
            render: function () {
                var self = this,
                    json = this.model.toJSON();
                this.$el.html(Mustache.render(template, json));
                //self.$('h5').css('text-shadow', '0  0 2px ' + this.model.get('color'));
               // self.$('h5').css('color', self.model.get('color'));
                this.$el.css('border-color', this.model.get('color'));
                var streams = this.model.get('streams');
                if (streams && streams.length) {
                    for (var i in streams) {
                        this._renderOneStream(streams[i], i);
                    }
                }
                this.model.on('change:name', function (peer, name) {
                    self.$('h5').text(name);
                });
                this.model.on('change:color', function () {
                    //self.$('h5').css('text-shadow', '0  0 1px ' + self.model.get('color'));
                   // self.$('h5').css('color', self.model.get('color'));
                    self.$el.css('border-color', self.model.get('color'));
                });
            }
        });

        return RemotePeerView;
    });<commit_msg> correct expand video link<commit_after>/*global define:true */
define(
    [
        'jquery',
        'backbone',
        'underscore',
        'mustache',
        'views/PeerView',
        'text!templates/video.en.tpl',
        'text!templates/audio.en.tpl'
    ],

    function ($, Backbone, _, Mustache, PeerView,templateVideo,templateAudio) {

        'use strict';

        var template = '
{{#name}}{{name}}{{/name}}{{^name}}sans nom{{/name}}

';
   /*     var templateVideo = '
' +
            '
Video
' +
            '<video src="" autoplay=true></video>' +
            '
' +
            'vidéo en pause' +
            'vidéo en cours' +
            'sans le son' +
            'avec le son' +
            ' en grand' +
            'en petit' +
            '
' +
            '
';
        var templateAudio = '
' +
            '
Audio
' +
            '
' +
            'sans le son' +
            'avec le son' +
            '
' +
            '<audio src="" autoplay=true></audio>' +
            '
';*/
        var RemotePeerView = PeerView.extend({

            initialize: function () {
            },
            _renderOneStream: function (stream, id) {
                var audios = stream.getAudioTracks();
                var videos = stream.getVideoTracks();
                if (videos.length > 1 || audios.length > 1) {
                    console.log('no support for multiple track in one stream');
                }
                var $container = null;
                var videolabel = videos.length ? videos[0].label : '';
                var audiolabel = audios.length ? audios[0].label : '';

                if (videos.length || (!videos.length && !audios.length)) {
                    $container = $(
                        Mustache.render(
                            templateVideo, {
                                videolabel: (!videos.length && !audios.length) ? '' : videolabel,
                                audiolabel: audiolabel,
                                videoId: id,
                                peerId: this.model.id,
                                remote : this.model.get('remote')
                            }
                        )
                    );
                    $container.find('video').attr('src', window.URL.createObjectURL(stream));
                    $container.find('.video-status.paused').hide();
                    $container.find('.expand-status.expanded').hide();
                } else {
                    // pas de video
                    $container = $(Mustache.render(templateAudio, { audiolabel: audiolabel,
                        remote : this.model.get('remote')}));
                    $container.find('audio').attr('src', window.URL.createObjectURL(stream));
                    $container.find('.video-status').hide();
                    $container.find('.expand-status').hide();
                }
                if (audios.length) {
                    $container.find('.audio-status.muted').hide();
                } else {

                    $container.find('.audio-status').hide();
                }
                if (videos.length || audios.length) {
                    $container.find('.video-status').click(function () {
                        $container.find('.video-status').toggle();
                        stream.getVideoTracks()[0].enabled = !(stream.getVideoTracks()[0].enabled);
                    });

                    $container.find('.audio-status').click(function () {
                        $container.find('.audio-status').toggle();
                        stream.getAudioTracks()[0].enabled = !(audios[0].enabled);
                    });

                } else {
                    $container.find('.audio-status').hide();
                    $container.find('.video-status').hide();
                }

                $container.find('.expand-status').click(function (e) {
                    $container.find('.expand-status').toggle();
                });

                this.$('.streams-container').append($container);
                stream.onended = function () {
                    console.log('end stream');
                    $container.remove();
                };
            },
            render: function () {
                var self = this,
                    json = this.model.toJSON();
                this.$el.html(Mustache.render(template, json));
                //self.$('h5').css('text-shadow', '0  0 2px ' + this.model.get('color'));
               // self.$('h5').css('color', self.model.get('color'));
                this.$el.css('border-color', this.model.get('color'));
                var streams = this.model.get('streams');
                if (streams && streams.length) {
                    for (var i in streams) {
                        this._renderOneStream(streams[i], i);
                    }
                }
                this.model.on('change:name', function (peer, name) {
                    self.$('h5').text(name);
                });
                this.model.on('change:color', function () {
                    //self.$('h5').css('text-shadow', '0  0 1px ' + self.model.get('color'));
                   // self.$('h5').css('color', self.model.get('color'));
                    self.$el.css('border-color', self.model.get('color'));
                });
            }
        });

        return RemotePeerView;
    });<|endoftext|>


<commit_before>/**
 * $Id: GZ 2010-12-19 exp$
 * Used by regions.php.
 *
 * TODO: some functions here, shall not use the Get-comand but rather modify the DOM directly.
 */

/**
 * prepare species string for $_GET
 */
function prepareSpecies(site) {
	var project_str = "projects";
	// var project_selects = document.getElementsByName(project_str);
	var src_sel = document.getElementById(project_str + "0");
	var tar_sel = document.getElementById(project_str + "1");
	alert(src_sel.selectedIndex+" "+tar_sel.selectedIndex);

	var src_val = src_sel[src_sel.selectedIndex].value;
	if (site == null) {
		site = "regions.php";
	}
	return site + "?" + project_str + "[]=" + src_val;

	// var species_str = "species";
	// var species_select = document.getElementsByName(species_str)[0];
	// var expr = /(\w.+)\s(\w.+)/;
	// expr.exec(species_select[species_select.selectedIndex].value);
	// if (site == null) {
	// site = "regions.php";
	// }
	// return site + "?" + species_str + "=" + RegExp.$1 + "+" + RegExp.$2;
}

/**
 * Returns a $_GET string with all selected regions contained in an array
 * regions[].
 */
function prepareGetString(site) {
	// prepare species
	var str = prepareSpecies(site);

	// add the selected region to the regions textfield
	// fetch all regions textfields into a get-string
	var ele = document.getElementsByName("regions[]");
	for ( var i = 0; i < ele.length; i++) {
		var region = ele[i];
		if (region.value != '') {
			str += "&regions[]=" + region.id.substring(0, region.id.indexOf("-"))
					+ ":" + region.value;
		}
	}
	str += '&confidence_int=' + document.getElementById('conf').value;
	return str;
}
/**
 * Add the selected region to the regions textfield and call the get method with
 * the new region, rather than setting the field content directly...
 */
function addRegion(chr) {
	var str = "&regions[]=" + chr + ":"
			+ document.getElementById("start" + chr).value + "-"
			+ document.getElementById("end" + chr).value;
	window.location.href = prepareGetString() + str;
}

/**
 * delete the selected region from the regions textfield and call the get method
 * with the old region, rather than setting the field content directly...
 */
function deleteRegion(chr) {
	document.getElementById(chr).removeAttribute("name");
	window.location.href = prepareGetString();
}

/**
 * Called to go to the next page.
 *
 * @param target
 *          modus, either 'overview' or all
 */
function submit_page(target) {
	if (target == 'overview') {
		window.location.href = prepareGetString("compara.php");
	} else if (target == 'all') {
		window.location.href = prepareGetString("display_all.php");
	} else {// this
		window.location.href = prepareSpecies();
	}

}
<commit_msg>minor development changes<commit_after>/**
 * $Id: GZ 2010-12-19 exp$
 * Used by regions.php.
 *
 * TODO: some functions here, shall not use the Get-comand but rather modify the DOM directly.
 */

/**
 * prepare species string for $_GET
 */
function prepareSpecies(site) {
	var project_str = "projects";
	// var project_selects = document.getElementsByName(project_str);
	var src_sel = document.getElementById(project_str + "0");
	var tar_sel = document.getElementById(project_str + "1");

	if (src_sel.selectedIndex >= 0) {
		var src_val = src_sel[src_sel.selectedIndex].value;
	} else {
		var src_val = "NULL";
	}

	if (tar_sel.selectedIndex >= 0) {
		var tar_val = tar_sel[tar_sel.selectedIndex].value;
	} else {
		var tar_val = "NULL";
	}

	if (site == null) {
		site = "regions.php";
	}
	var proj_arg = project_str + "[]=";
	return site + "?" + proj_arg + src_val + "&" + proj_arg + tar_val;

	// var species_str = "species";
	// var species_select = document.getElementsByName(species_str)[0];
	// var expr = /(\w.+)\s(\w.+)/;
	// expr.exec(species_select[species_select.selectedIndex].value);
	// if (site == null) {
	// site = "regions.php";
	// }
	// return site + "?" + species_str + "=" + RegExp.$1 + "+" + RegExp.$2;
}

/**
 * Returns a $_GET string with all selected regions contained in an array
 * regions[].
 */
function prepareGetString(site) {
	// prepare species
	var str = prepareSpecies(site);

	// add the selected region to the regions textfield
	// fetch all regions textfields into a get-string
	var ele = document.getElementsByName("regions[]");
	for ( var i = 0; i < ele.length; i++) {
		var region = ele[i];
		if (region.value != '') {
			str += "&regions[]=" + region.id.substring(0, region.id.indexOf("-"))
					+ ":" + region.value;
		}
	}
	str += '&confidence_int=' + document.getElementById('conf').value;
	return str;
}
/**
 * Add the selected region to the regions textfield and call the get method with
 * the new region, rather than setting the field content directly...
 */
function addRegion(chr) {
	var str = "&regions[]=" + chr + ":"
			+ document.getElementById("start" + chr).value + "-"
			+ document.getElementById("end" + chr).value;
	window.location.href = prepareGetString() + str;
}

/**
 * delete the selected region from the regions textfield and call the get method
 * with the old region, rather than setting the field content directly...
 */
function deleteRegion(chr) {
	document.getElementById(chr).removeAttribute("name");
	window.location.href = prepareGetString();
}

/**
 * Called to go to the next page.
 *
 * @param target
 *          modus, either 'overview' or all
 */
function submit_page(target) {
	if (target == 'overview') {
		window.location.href = prepareGetString("compara.php");
	} else if (target == 'all') {
		window.location.href = prepareGetString("display_all.php");
	} else {// this
		window.location.href = prepareSpecies();
	}

}
<|endoftext|>


<commit_before>import Ember from 'ember';

const EMBER_VERSIONS = ['2.4.4', '2.3.2', '2.2.2', '2.1.2', '2.0.3', '1.13.13', '1.12.2'];
const EMBER_DATA_VERSIONS = ['2.4.3', '2.3.3', '2.2.1', '2.1.0', '2.0.1', '1.13.15'];

const VERSION_REGEX = /^\d+.\d+.\d+(-beta\.\d+)?$/;

const CDN_MAP = {
  'ember': {
    library: 'ember.js',
    fileName: 'ember.debug.js'
  },

  'ember-template-compiler': {
    library: 'ember.js',
    fileName: 'ember-template-compiler.js'
  },

  'ember-data': {
    library: 'ember-data.js',
    fileName: 'ember-data.js'
  }
};

const CHANNEL_FILENAME_MAP = {
  'ember': 'ember.debug.js',
  'ember-template-compiler': 'ember-template-compiler.js',
  'ember-data': 'ember-data.js'
};

const CHANNELS = ['canary', 'beta', 'release'];

const { computed, RSVP } = Ember;

export default Ember.Service.extend({
  resolveDependencies: function(dependencies) {
    Object.keys(dependencies).forEach((name) => {
      var value = dependencies[name];

      dependencies[name] = this.resolveDependency(name, value);
    });
  },

  resolveAddons: function(addons, dependencies) {
    let addonPromises = {};
    Object.keys(addons).forEach((name) => {
      var value = addons[name];

      addonPromises[name] = this.resolveAddon(name, value);
    });

    return RSVP.hash(addonPromises).then(hash => {
      Object.keys(addons).forEach((name) => {
        let addon = hash[name];
        if(addon.status === 'build_success') {
          dependencies[name] = addon.addon_js;
          dependencies[name+'_css'] = addon.addon_css;
          console.log(`Addon ${name} is loaded...`);
        }
        else if (addon.status === 'building') {
          console.log(`Addon ${name} is currently building...`);
          console.log(`Joost will have to implement some sort of refresh logic here..`);
        }
        else if (addon.status === 'build_error') {
          console.error(`Addon ${name} encountered a build error:`);
          console.error(addon.errors, addon.ember_errors);
          console.log(`Joost will have to implement some sort of error logic here..`);
        }
      });
      return RSVP.resolve(dependencies);
    });
  },

  resolveAddon(name, value) {
    return new RSVP.Promise(function(resolve) {
      const url = `https://nl1fctyzr7.execute-api.us-east-1.amazonaws.com/staging/addon?addon=${name}&addon_version=${value}&ember_version=1.13.15`;
      resolve(Ember.$.getJSON(url).then(data => RSVP.resolve(data)));
    });
  },

  resolveDependency: function(name, value) {
    switch (name) {
      case 'ember':
      case 'ember-template-compiler':
      case 'ember-data':
        return this.resolveEmberDependency(name, value);

      default:
        return value;
    }
  },

  resolveEmberDependency: function(name, value) {
    if (VERSION_REGEX.test(value)) {
      return this.cdnURL(name, value);
    }

    if (CHANNELS.indexOf(value) !== -1) {
      return this.channelURL(name, value);
    }

    return value;
  },

  channelURL: function(name, channel) {
    var fileName = CHANNEL_FILENAME_MAP[name];

    return `//s3.amazonaws.com/builds.emberjs.com/${channel}/${fileName}`;
  },

  cdnURL: function(name, version) {
    var { library, fileName } = CDN_MAP[name];

    return `//cdnjs.cloudflare.com/ajax/libs/${library}/${version}/${fileName}`;
  },

  emberVersions: computed(function() {
    return [...CHANNELS, ...EMBER_VERSIONS];
  }),

  emberDataVersions: computed(function() {
    return [...CHANNELS, ...EMBER_DATA_VERSIONS];
  })
});
<commit_msg>Update Ember and Ember Data versions.<commit_after>import Ember from 'ember';

const EMBER_VERSIONS = ['2.5.0', '2.4.5', '2.3.2', '2.2.2', '2.1.2', '2.0.3', '1.13.13', '1.12.2'];
const EMBER_DATA_VERSIONS = ['2.5.0', '2.4.3', '2.3.3', '2.2.1', '2.1.0', '2.0.1', '1.13.15'];

const VERSION_REGEX = /^\d+.\d+.\d+(-beta\.\d+)?$/;

const CDN_MAP = {
  'ember': {
    library: 'ember.js',
    fileName: 'ember.debug.js'
  },

  'ember-template-compiler': {
    library: 'ember.js',
    fileName: 'ember-template-compiler.js'
  },

  'ember-data': {
    library: 'ember-data.js',
    fileName: 'ember-data.js'
  }
};

const CHANNEL_FILENAME_MAP = {
  'ember': 'ember.debug.js',
  'ember-template-compiler': 'ember-template-compiler.js',
  'ember-data': 'ember-data.js'
};

const CHANNELS = ['canary', 'beta', 'release'];

const { computed, RSVP } = Ember;

export default Ember.Service.extend({
  resolveDependencies: function(dependencies) {
    Object.keys(dependencies).forEach((name) => {
      var value = dependencies[name];

      dependencies[name] = this.resolveDependency(name, value);
    });
  },

  resolveAddons: function(addons, dependencies) {
    let addonPromises = {};
    Object.keys(addons).forEach((name) => {
      var value = addons[name];

      addonPromises[name] = this.resolveAddon(name, value);
    });

    return RSVP.hash(addonPromises).then(hash => {
      Object.keys(addons).forEach((name) => {
        let addon = hash[name];
        if(addon.status === 'build_success') {
          dependencies[name] = addon.addon_js;
          dependencies[name+'_css'] = addon.addon_css;
          console.log(`Addon ${name} is loaded...`);
        }
        else if (addon.status === 'building') {
          console.log(`Addon ${name} is currently building...`);
          console.log(`Joost will have to implement some sort of refresh logic here..`);
        }
        else if (addon.status === 'build_error') {
          console.error(`Addon ${name} encountered a build error:`);
          console.error(addon.errors, addon.ember_errors);
          console.log(`Joost will have to implement some sort of error logic here..`);
        }
      });
      return RSVP.resolve(dependencies);
    });
  },

  resolveAddon(name, value) {
    return new RSVP.Promise(function(resolve) {
      const url = `https://nl1fctyzr7.execute-api.us-east-1.amazonaws.com/staging/addon?addon=${name}&addon_version=${value}&ember_version=1.13.15`;
      resolve(Ember.$.getJSON(url).then(data => RSVP.resolve(data)));
    });
  },

  resolveDependency: function(name, value) {
    switch (name) {
      case 'ember':
      case 'ember-template-compiler':
      case 'ember-data':
        return this.resolveEmberDependency(name, value);

      default:
        return value;
    }
  },

  resolveEmberDependency: function(name, value) {
    if (VERSION_REGEX.test(value)) {
      return this.cdnURL(name, value);
    }

    if (CHANNELS.indexOf(value) !== -1) {
      return this.channelURL(name, value);
    }

    return value;
  },

  channelURL: function(name, channel) {
    var fileName = CHANNEL_FILENAME_MAP[name];

    return `//s3.amazonaws.com/builds.emberjs.com/${channel}/${fileName}`;
  },

  cdnURL: function(name, version) {
    var { library, fileName } = CDN_MAP[name];

    return `//cdnjs.cloudflare.com/ajax/libs/${library}/${version}/${fileName}`;
  },

  emberVersions: computed(function() {
    return [...CHANNELS, ...EMBER_VERSIONS];
  }),

  emberDataVersions: computed(function() {
    return [...CHANNELS, ...EMBER_DATA_VERSIONS];
  })
});
<|endoftext|>


<commit_before>import { run } from '@ember/runloop';
import { getOwner } from '@ember/application';
import { hash } from 'rsvp';
import Service, { inject as service } from '@ember/service';
import Ember from 'ember';
import config from '../config/environment';
import { walkConfigs, setRTL } from '../utils/locale-utils';

export const DEFAULT_LANGUAGE = config.intl.defaultLocale || 'en';

export default Service.extend({
  intl: service(),
  config: service(),

  loadUserLanguagePreference() {
    return hash({
      user: this.getConfig().getCurrentUser(),
      preferences: this.fetchOrCreatePreferences()
    }).then(({ user, preferences }) => user && user.name && preferences[user.name] && preferences[user.name].intl || DEFAULT_LANGUAGE)
      .catch(() => DEFAULT_LANGUAGE)
      .then(this.setApplicationLanguage.bind(this));
  },

  setApplicationLanguage(selectedLanguage) {

    // Whenever the languague changes, apply RTL settings to application
    let currentConfig = walkConfigs(selectedLanguage, getOwner(this)) || {};
    if (currentConfig.class) {
      setRTL(currentConfig.class.rtl);
    }

    return run(() => this.set('intl.locale', selectedLanguage));
  },

  saveUserLanguagePreference(selectedLanguage) {
    this.setApplicationLanguage(selectedLanguage);
    return hash({
      user: this.getConfig().getCurrentUser(),
      preferences: this.fetchOrCreatePreferences().then(
        (preferences) => preferences,
        () => ({
          _id: 'preferences'
        })
      )
    }).then(({ user, preferences }) => {
      preferences[user.name] = preferences[user.name] || {};
      preferences[user.name].intl = selectedLanguage;
      return this.getConfig().getConfigDB().put(preferences);
    }).catch((err) => Ember.Logger.error(err));
  },

  fetchOrCreatePreferences() {
    return this.getConfig().getConfigDB().get('preferences');
  },

  getConfig() {
    return this.get('config');
  }
});
<commit_msg>Add en fallback locale and remove ember-i18n rtl check<commit_after>import { run } from '@ember/runloop';
import { hash } from 'rsvp';
import Service, { inject as service } from '@ember/service';
import Ember from 'ember';
import config from '../config/environment';

export const DEFAULT_LANGUAGE = config.intl.defaultLocale || 'en';

export default Service.extend({
  intl: service(),
  config: service(),

  loadUserLanguagePreference() {
    return hash({
      user: this.getConfig().getCurrentUser(),
      preferences: this.fetchOrCreatePreferences()
    }).then(({ user, preferences }) => user && user.name && preferences[user.name] && preferences[user.name].intl || DEFAULT_LANGUAGE)
      .catch(() => DEFAULT_LANGUAGE)
      .then(this.setApplicationLanguage.bind(this));
  },

  setApplicationLanguage(selectedLanguage) {
    return run(() => this.set('intl.locale', [selectedLanguage, 'en']));
  },

  saveUserLanguagePreference(selectedLanguage) {
    this.setApplicationLanguage(selectedLanguage);
    return hash({
      user: this.getConfig().getCurrentUser(),
      preferences: this.fetchOrCreatePreferences().then(
        (preferences) => preferences,
        () => ({
          _id: 'preferences'
        })
      )
    }).then(({ user, preferences }) => {
      preferences[user.name] = preferences[user.name] || {};
      preferences[user.name].intl = selectedLanguage;
      return this.getConfig().getConfigDB().put(preferences);
    }).catch((err) => Ember.Logger.error(err));
  },

  fetchOrCreatePreferences() {
    return this.getConfig().getConfigDB().get('preferences');
  },

  getConfig() {
    return this.get('config');
  }
});
<|endoftext|>