text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title>Sinon.JS - Documentation</title>
    <link rel="stylesheet" type="text/css" href="Sinon.JS%20-%20Documentation_files/sinon.css">

Sinon.JS

        Standalone test spies, stubs and mocks for JavaScript.

        No dependencies, works with any unit testing framework.

Documentation

Spies

Stubs

Mocks

Fake timers

Fake XHR and server

Assertions

Matchers

Sandboxing

Utils

      This page contains the entire Sinon.JS API documentation along with brief
      introductions to the concepts Sinon implements. Please ask questions on
      the mailing list if
      you're stuck. I also really appreciate suggestions to improve the
      documentation so Sinon.JS is easier to work with. Get in touch!

Test spies API reference

sinon.spy()

spy API

spy call API

What is a test spy?

        A test spy is a function that records arguments, return value, the value
        of this and exception thrown (if any) for all its calls. A
        test spy can be an anonymous function or it can wrap an existing
        function.

When to use spies?

        Test spies are useful to test both callbacks and how certain
        functions/methods are used throughout the system under test. The
        following simplified example shows how to use spies to test how a
        function handles a callback:

"test should call subscribers on publish": function () {
    var callback = sinon.spy();
    PubSub.subscribe("message", callback);

    PubSub.publishSync("message");

    assertTrue(callback.called);
}

Spying on existing methods

        sinon.spy can also spy on existing functions. When doing
        so, the original function will behave just as normal (including when
        used as a constructor) but you will have access to data about all
        calls. The following is a slightly contrived example:

{
    setUp: function () {
        sinon.spy(jQuery, "ajax");
    },

    tearDown: function () {
        jQuery.ajax.restore(); // Unwraps the spy
    },

    "test should inspect jQuery.getJSON's usage of jQuery.ajax": function () {
        jQuery.getJSON("/some/resource");

        assert(jQuery.ajax.calledOnce);
        assertEquals("/some/resource", jQuery.ajax.getCall(0).args[0].url);
        assertEquals("json", jQuery.ajax.getCall(0).args[0].dataType);
    }
}

Creating spies: sinon.spy()

var spy = sinon.spy();

          Creates an anonymous function that records arguments, this value,
          exceptions and return values for all calls.

var spy = sinon.spy(myFunc);

Spies on the provided function

var spy = sinon.spy(object, "method");

          Creates a spy for object.method
          and replaces the original method with the spy. The spy acts exactly
          like the original method in all cases.  The original method can be
          restored by calling object.method.restore().  The
          returned spy is the function object which replaced the original
          method. spy === object.method.

Spy API

        Spies provide a rich interface to inspect their usage. The above
        examples showed the calledOnce boolean property as well as
        the getCall method and the returned
        object's args property. There are three ways of inspecting
        call data.

        The preferred approach is to use the spy's calledWith
        method (and friends) because it keeps your test from being too specific
        about which call did what and so on. It will return true if
        the spy was ever called with the provided arguments.

"test should call subscribers with message as first argument" : function () {
    var message = 'an example message';
    var spy = sinon.spy();

    PubSub.subscribe(message, spy);
    PubSub.publishSync(message, "some payload");

    assert(spy.calledWith(message));
}

        If you want to be specific, you can directly check the first argument of
        the first call. There are two ways of achieving this:

"test should call subscribers with message as first argument" : function () {
    var message = 'an example message';
    var spy = sinon.spy();

    PubSub.subscribe(message, spy);
    PubSub.publishSync(message, "some payload");

    assertEquals(message, spy.args[0][0]);
}

"test should call subscribers with message as first argument" : function () {
    var message = 'an example message';
    var spy = sinon.spy();

    PubSub.subscribe(message, spy);
    PubSub.publishSync(message, "some payload");

    assertEquals(message, spy.getCall(0).args[0]);
}

        The first example uses the two-dimensional args array
        directly on the spy, while the second example fetches the first call
        object and then accesses it's args array. Which one to use
        is a matter of preference, but the recommended approach is going with
        spy.calledWith(arg1, arg2, ...) unless there's a need to
        make the tests highly specific.

Spy API

        Spy objects are objects returned from sinon.spy(). When
        spying on existing methods with sinon.spy(object, method),
        the following properties and methods are also available
        on object.method.

spy.withArgs(arg1[, arg2, ...]);

          Creates a spy that only records calls when the received arguments
          matche those passed to withArgs. This is useful to be
          more expressive in your assertions, where you can access the spy with
          the same call:

"test should call method once with each argument": function () {
    var object = { method: function () {} };
    var spy = sinon.spy(object, "method");
    spy.withArgs(42);
    spy.withArgs(1);

    object.method(42);
    object.method(1);

    assert(spy.withArgs(42).calledOnce);
    assert(spy.withArgs(1).calledOnce);
}

spy.callCount

The number of recorded calls.

spy.called

true if the spy was called at least once

spy.calledOnce

true if spy was called exactly once

spy.calledTwice

true if the spy was called exactly twice

spy.calledThrice

true if the spy was called exactly thrice

spy.firstCall

The first call

spy.secondCall

The second call

spy.thirdCall

The third call

spy.lastCall

The last call

spy.calledBefore(anotherSpy);

Returns true if the spy was called before anotherSpy

spy.calledAfter(anotherSpy);

Returns true if the spy was called after anotherSpy

spy.calledOn(obj);

          Returns true if the spy was called at least once with obj
          as this.

spy.alwaysCalledOn(obj);

          Returns true if the spy was always called with obj
          as this.

spy.calledWith(arg1, arg2, ...);

          Returns true if spy was called at least once with the provided
          arguments. Can be used for partial matching, Sinon only checks the provided
          arguments against actual arguments, so a call that received the provided arguments
          (in the same spots) and possibly others as well will return true.

spy.alwaysCalledWith(arg1, arg2, ...);

          Returns true if spy was always called with the provided arguments
          (and possibly others).

spy.calledWithExactly(arg1, arg2, ...);

          Returns true if spy was called at least once with the provided arguments
          and no others.

spy.alwaysCalledWithExactly(arg1, arg2, ...);

          Returns true if spy was always called with the exact provided arguments.

spy.calledWithMatch(arg1, arg2, ...);

          Returns true if spy was called with matching arguments
          (and possibly others). This behaves the same as
          spy.calledWith(sinon.match(arg1), sinon.match(arg2), ...).

spy.alwaysCalledWithMatch(arg1, arg2, ...);

          Returns true if spy was always called with matching arguments
          (and possibly others). This behaves the same as
          spy.alwaysCalledWith(sinon.match(arg1), sinon.match(arg2), ...).

spy.calledWithNew();

          Returns true if spy/stub was called the new
          operator. Beware that this is inferred based on the value of
          the this object and the spy
          function's prototype, so it may give false positives if
          you actively return the right kind of object.

spy.notCalledWith(arg1, arg2, ...);

          Returns true if the spy/stub was called at least once
          with arguments not matching the provided ones.

spy.neverCalledWith(arg1, arg2, ...);

          Returns true if the spy/stub was never called with
          the provided arguments.

spy.notCalledWithMatch(arg1, arg2, ...);

          Returns true if the spy/stub was called at least once
          with arguments not matching the provided ones. This behaves the same as
          spy.notCalledWith(sinon.match(arg1), sinon.match(arg2), ...).

spy.neverCalledWithMatch(arg1, arg2, ...);

          Returns true if the spy/stub was never called with
          matching arguments. This behaves the same as
          spy.neverCalledWith(sinon.match(arg1), sinon.match(arg2), ...).

spy.threw();

Returns true if spy threw an exception at least once.

spy.threw("TypeError");

Returns true if spy threw an exception of the provided type at least once.

spy.threw(obj);

Returns true if spy threw the provided exception object at least once.

spy.alwaysThrew();

Returns true if spy always threw an exception.

spy.alwaysThrew("TypeError");

Returns true if spy always threw an exception of the provided type.

spy.alwaysThrew(obj);

Returns true if spy always threw the provided exception object.

spy.returned(obj);

          Returns true if spy returned the provided value at least once.
          Uses deep comparison for objects and arrays.
          Use spy.returned(sinon.match.same(obj)) for strict
          comparison (see matchers).

spy.alwaysReturned(obj);

Returns true if spy always returned the provided value.

var spyCall = spy.getCall(n);

            Returns the nth call. Accessing
            individual calls helps with more detailed behavior verification when
            the spy is called more than once. Example:

sinon.spy(jQuery, "ajax");
jQuery.ajax("/stuffs");
var spyCall = jQuery.ajax.getCall(0);

assertEquals("/stuffs", spyCall.args[0]);

spy.thisValues

          Array of this objects, spy.thisValues[0] is the this
          object for the first call.

spy.args

          Array of arguments received, spy.args[0] is an array of
          arguments recevied in the first call.

spy.exceptions

          Array of exception objects thrown, spy.exceptions[0] is
          the exception thrown by the first call. If the call did not throw an
          error, the value at the call's location in .exceptions
          will be 'undefined'.

spy.returnValues

          Array of return values, spy.returnValues[0] is the return
          value of the first call. If the call did not explicitly return a
          value, the value at the call's location in .returnValues
          will be 'undefined'.

spy.reset()

          Resets the state of a spy.

spy.printf("format string", [arg1, arg2, ...])

          Returns the passed format string with the following replacements performed:

%n: the name of the spy ("spy" by default)

%c: the number of times the spy was called, in words ("once", "twice", etc.)

%C: a list of string representations of the calls to the spy, with each call prefixed by a newline and four spaces

%t: a comma-delimited list of this values the spy was called on

%<var>n</var>: the formatted value of the <var>n</var>th argument passed to printf

%*: a comma-delimited list of the (non-format string) arguments passed to printf

Individual spy calls

var spyCall = spy.getCall(n)

            Returns the nth call. Accessing
            individual calls helps with more detailed behavior verification when
            the spy is called more than once. Example:

sinon.spy(jQuery, "ajax");
jQuery.ajax("/stuffs");
var spyCall = jQuery.ajax.getCall(0);

assertEquals("/stuffs", spyCall.args[0]);

spyCall.calledOn(obj);

Returns true if obj was this for this call.

spyCall.calledWith(arg1, arg2, ...);

Returns true if call received provided arguments (and possibly others).

spyCall.calledWithExactly(arg1, arg2, ...);

Returns true if call received provided arguments and no others.

spyCall.calledWithMatch(arg1, arg2, ...);

Returns true if call received matching arguments (and possibly others). This behaves the same as spyCall.calledWith(sinon.match(arg1), sinon.match(arg2), ...).

spyCall.notCalledWith(arg1, arg2, ...);

Returns true if call did not receive provided arguments.

spyCall.notCalledWithMatch(arg1, arg2, ...);

Returns true if call did not receive matching arguments. This behaves the same as spyCall.notCalledWith(sinon.match(arg1), sinon.match(arg2), ...).

spyCall.threw();

Returns true if call threw an exception.

spyCall.threw("TypeError");

Returns true if call threw exception of provided type.

spyCall.threw(obj);

Returns true if call threw provided exception object.

spyCall.thisValue

The call's this value.

spyCall.args

Array of received arguments.

spyCall.exception

Exception thrown, if any.

spyCall.returnValue

Return value.

Test stubs API reference

What are stubs?

        Test stubs are functions (spies) with pre-programmed behavior. They
        support the full test spy API in addition to
        methods which can be used to alter the stub's behavior.

        As spies, stubs can be either anonymous, or wrap existing
        functions. When wrapping an existing function with a stub, the original
        function is not called.

When to use stubs?

        Use a stub when you want to:

          Control a method's behavior from a test to force the code down a
          specific path. Examples include forcing a method to throw an error in
          order to test error handling.

          When you want to prevent a specific method from being called directly
          (possibly because it triggers undesired behavior, such as a
          XMLHttpRequest or similar).

        The following example is yet another test from Morgan Roderick's
        PubSubJS which shows how to create an anonymous stub that throws an
        exception when called.

"test should call all subscribers, even if there are exceptions" : function(){
    var message = 'an example message';
    var error = 'an example error message';
    var stub = sinon.stub().throws();
    var spy1 = sinon.spy();
    var spy2 = sinon.spy();

    PubSub.subscribe(message, stub);
    PubSub.subscribe(message, spy1);
    PubSub.subscribe(message, spy2);

    PubSub.publishSync(message, undefined);

    assert(spy1.called);
    assert(spy2.called);
    assert(stub.calledBefore(spy1));
}

        Note how the stub also implements the spy interface. The test verifies
        that all callbacks where called, and also that the exception throwing
        stub was called before one of the other callbacks.

Stub API

var stub = sinon.stub();

Creates an anonymous stub function.

var stub = sinon.stub(object, "method");

          Replaces object.method with a stub function. The original
          function can be restored by calling object.method.restore();
          (or stub.restore();). An exception is thrown if the property
          is not already a function, to help avoid typos when stubbing methods.

var stub = sinon.stub(object, "method", func);

          Replaces object.method with a func, wrapped
          in a spy. As usual, object.method.restore();
          can be used to restore the original method.

var stub = sinon.stub(obj);

Stubs all the object's methods.

stub.withArgs(arg1[, arg2, ...]);

          Stubs the method only for the provided arguments. This is useful to be
          more expressive in your assertions, where you can access the spy with
          the same call. It is also useful to create a stub that can act
          differently in response to different arguments:

"test should stub method differently based on arguments": function () {
    var callback = sinon.stub();
    callback.withArgs(42).returns(1);
    callback.withArgs(1).throws("TypeError");

    callback(); // No return value, no exception
    callback(42); // Returns 1
    callback(1); // Throws TypeError
}

stub.returns(obj);

Makes the stub return the provided value.

stub.returnsArg(index);

          Causes the stub to return the argument at the provided index.
          stub.returnsArg(0); causes the stub to return the first argument.

stub.throws();

Causes the stub to throw an exception (Error).

stub.throws("TypeError");

Causes the stub to throw an exception of the provided type.

stub.throws(obj);

Causes the stub to throw the provided exception object.

stub.callsArg(index);

          Causes the stub to call the argument at the provided index as a callback
          function. stub.callsArg(0); causes the stub to call the
          first argument as a callback.

stub.callsArgOn(index, context);

          Like above but with an additional parameter to pass the this context.

stub.callsArgWith(index, arg1, arg2, ...);

Like callsArg, but with arguments to pass to the callback.

stub.callsArgOnWith(index, context, arg1, arg2, ...);

          Like above but with an additional parameter to pass the this context.

stub.yields([arg1, arg2, ...])

          Almost like callsArg. Causes the stub to call the first
          callback it receives with the provided arguments (if any). If a method
          accepts more than one callback, you need to use callsArg
          to have the stub invoke other callbacks than the first one.

stub.yieldsOn(context, [arg1, arg2, ...])

          Like above but with an additional parameter to pass the this context.

stub.yieldsTo(property, [arg1, arg2, ...])

          Causes the spy to invoke a callback passed as a property of an object
          to the spy. Like yields, yieldsTo grabs the
          first matching argument, finds the callback and calls it with the
          (optional) arguments:

stub.yieldsToOn(property, context, [arg1, arg2, ...])

          Like above but with an additional parameter to pass the this context.

"test should fake successful ajax request": function () {
    sinon.stub(jQuery, "ajax").yieldsTo("success", [1, 2, 3]);

    jQuery.ajax({
        success: function (data) {
            assertEquals([1, 2, 3], data);
        }
    });
}

spy.yield([arg1, arg2, ...])

          Invoke callbacks passed to the spy with the given
          arguments. If the spy was never called with a function argument,
          yield throws an error. Also aliased as
          invokeCallback.

spy.yieldTo(callback, [arg1, arg2, ...])

          Invokes callbacks passed as a property of an object to the
          spy. Like yield, yieldTo grabs the first
          matching argument, finds the callback and calls it with the (optional)
          arguments:

"calling callbacks": function () {
    var callback = sinon.stub();
    callback({
        "success": function () {
            console.log("Success!");
        },
        "failure": function () {
            console.log("Oh noes!");
        }
    });

    callback.yieldTo("failure"); // Logs "Oh noes!"
}

spy.callArg(argNum)

          Like yield, but with an explicit argument number
          specifying which callback to call. Useful if a function is called with
          more than one callback, and simply calling the first callback is not
          desired.

"calling the last callback": function () {
    var callback = sinon.stub();
    callback(function () {
        console.log("Success!");
    },
    function () {
        console.log("Oh noes!");
    });

    callback.callArg(1); // Logs "Oh noes!"
}

spy.callArgWith(argNum, [arg1, arg2, ...])

          Like callArg, but with arguments.

Mocks API reference

What are mocks?

        Mocks (and mock expectations) are fake methods (like spies) with
        pre-programmed behavior (like stubs) as well as pre-programmed
        expectations. A mock will fail your test if it is not used as
        expected.

When to use mocks?

        Mocks should only be used for the method under test. In every
        unit test, there should be one unit under test. If you want to control
        how your unit is being used and like stating expectations upfront (as
        opposed to asserting after the fact), use a mock.

When to not use mocks?

        Mocks come with built-in expectations that may fail your test. Thus,
        they enforce implementation details. The rule of thumb is: if you
        wouldn't add an assertion for some call specific, don't mock it. Use a
        stub instead. In general you should never have more
        than one mock (possibly with several expectations) in a
        single test.

        Expectations implement both
        the spies and stubs APIs.

        To see how mocks look like in Sinon.JS, here's one of the PubSubJS tests
        again, this time using a method as callback and using mocks to verify
        its behavior:

"test should call all subscribers when exceptions": function () {
    var myAPI = { method: function () {} };

    var spy = sinon.spy();
    var mock = sinon.mock(myAPI);
    mock.expects("method").once().throws();

    PubSub.subscribe("message", myAPI.method);
    PubSub.subscribe("message", spy);
    PubSub.publishSync("message", undefined);

    mock.verify();
    assert(spy.calledOnce);
}

Mock API

var mock = sinon.mock(obj);

          Creates a mock for the provided object. Does not change the object, but returns
          a mock object to set expectations on the object's methods.

var expectation = mock.expects("method");

          Overrides obj.method with a mock function and returns it.
          See expectations below.

mock.restore();

Restores all mocked methods.

mock.verify();

          Verifies all expectations on the mock. If any expectation is not
          satiesfied, an exception is thrown. Also restores the mocked methods.

Expectations

        All the expectation methods returns the expectation, meaning you can chain them.
        Typical usage:

sinon.mock(jQuery).expects("ajax").atLeast(2).atMost(5);
jQuery.ajax.verify();

var expectation = sinon.expectation.create([methodName]);

          Creates an expectation without a mock object, basically an anonymous
          mock function. Method name is optional and is used in exception
          messages to make them more readable.

var expectation = sinon.mock();

The same as the above.

expectation.atLeast(number);

Specify the minimum amount of calls expected.

expectation.atMost(number);

Specify the maximum amount of calls expected.

expectation.never();

Expect the method to never be called.

expectation.once();

Expect the method to be called exactly once.

expectation.twice();

Expect the method to be called exactly twice.

expectation.thrice();

Expect the method to be called exactly thrice.

expectation.exactly(number);

Expect the method to be called exactly number times.

expectation.withArgs(arg1, arg2, ...);

Expect the method to be called with the provided arguments and possibly others.

expectation.withExactArgs(arg1, arg2, ...);

Expect the method to be called with the provided arguments and no others.

expectation.on(obj);

Expect the method to be called with obj as this.

expectation.verify();

Verifies the expectation and throws an exception if it's not met.

Fake timers API reference

        Fake timers is a synchronous implementation of setTimeout
        and friends that Sinon.JS can overwrite the global functions with to
        allow you to more easily test code using them. Fake timers provide
        a clock object to pass time, which can also be used to
        control Date objects created through either new
        Date(); or Date.now(); (if supported by the
        browser).

        When faking timers with IE you also need
        sinon-ie-1.5.0, which should be
        loaded after sinon-1.5.0.js.

        The fake timers can be used completely stand-alone by downloading
        sinon-timers-1.5.0. When
        using the fake timers in IE you also need
        sinon-timers-ie-1.5.0.
        Load it after the first file.

{
    setUp: function () {
        this.clock = sinon.useFakeTimers();
    },

    tearDown: function () {
        this.clock.restore();
    },

    "test should animate element over 500ms" : function(){
        var el = jQuery("<div></div>");
        el.appendTo(document.body);

        el.animate({ height: "200px", width: "200px" });
        this.clock.tick(510);

        assertEquals("200px", el.css("height"));
        assertEquals("200px", el.css("width"));
    }
}

Fake timers API

var clock = sinon.useFakeTimers();

            Causes Sinon to replace the global setTimeout,
            clearTimeout, setInterval,
            clearInterval and Date with a custom
            implementation which is bound to the returned clock
            object.

var clock = sinon.useFakeTimers(now);

          As above, but rather than starting the clock at the current timestamp,
          start at the provided timestamp.

var clock = sinon.useFakeTimers([now, ]prop1, prop2, ...);

          Sets the clock start timestamp and names functions to fake. Possible
          functions are setTimeout, clearTimeout, setInterval, clearInterval,
          and Date. Can also be called without the timestamp.

clock.tick(ms);

          Tick the clock ahead ms milliseconds. Causes all timers
          scheduled within the affected time range to be called.

clock.restore();

Restore the faked methods. Call in e.g. tearDown.

Fake XMLHttpRequest API reference

sinon.useFakeXMLHttpRequest

FakeXMLHttpRequest

Simulating responses

Fake server

        Provides a fake implementation of XMLHttpRequest and
        provides several interfaces for manipulating objects created by it. Also
        fakes the native XMLHttpRequest
        and ActiveXObject (if available, and only
        for XMLHTTP progids).  Helps with testing requests made
        with XHR.

        When faking XHR with IE you also need
        sinon-ie-1.5.0, which should be
        loaded after sinon-1.5.0.js.

        The fake server and XHR can be used completely stand-alone by
        downloading sinon-server-1.5.0.
        When using the fake server in IE you also need
        sinon-ie-1.5.0. Load it after
        the first file.

{
    setUp: function () {
        this.xhr = sinon.useFakeXMLHttpRequest();
        var requests = this.requests = [];

        this.xhr.onCreate = function (xhr) {
            requests.push(xhr);
        };
    },

    tearDown: function () {
        this.xhr.restore();
    },

    "test should fetch comments from server" : function () {
        var callback = sinon.spy();
        myLib.getCommentsFor("/some/article", callback);
        assertEquals(1, this.requests.length);

        this.requests[0].respond(200, { "Content-Type": "application/json" },
                                 '[{ "id": 12, "comment": "Hey there" }]');
        assert(callback.calledWith([{ id: 12, comment: "Hey there" }]));
    }
}

sinon.useFakeXMLHttpRequest

var xhr = sinon.useFakeXMLHttpRequest();

          Causes Sinon to replace the native XMLHttpRequest object
          in browsers that support it with a custom implementation which does
          not send actual requests. In browsers that support
          ActiveXObject, this constructor is replaced, and fake
          objects are returned for XMLHTTP progIds. Other progIds,
          such as XMLDOM are left untouched.

xhr.onCreate = function (xhr) {};

          By assigning a function to the onCreate property of the
          returned object from useFakeXMLHttpRequest() you can
          subscribe to newly created FakeXMLHttpRequest
          objects. See below for the fake xhr object API. Using this observer
          means you can still reach objects created by
          e.g. jQuery.ajax (or other abstractions/frameworks).

xhr.restore();

Restore original function(s).

FakeXMLHttpRequest interface

String request.url

          The URL set on the request object.

String request.method

          The request method as a string.

Object request.requestHeaders

            An object of all request headers, i.e.:

{
    "Accept": "text/html, */*",
    "Connection": "keep-alive"
}

String request.requestBody

The request body

int request.status

          The request's status code. Undefined if the request has not been
          handled (see respond below).

String request.statusText

          Only populated if the respond
          method is called (see below).

boolean request.async

          Whether or not the request is asynchronous.

String request.username

          Username, if any.

String request.password

          Password, if any.

Document request.responseXML

          When using respond, this property is
          populated with a parsed document if response headers indicate as much
          (see the spec).

String request.getResponseHeader(header);

          The value of the given response header, if the request has been
          responded to (see respond).

Object request.getAllResponseHeaders();

          All response headers as an object.

Filtered requests

        When using Sinon.JS for mockups or partial integration/functional
        testing, you might want to fake some requests, while allowing others to
        go throught to the backend server. With
        filtered FakeXMLHttpRequests (new in Sinon 1.3.0), you can.

FakeXMLHttpRequest.useFilters (default false)

          When set to true, Sinon will check added filters if
          certain requests should be "unfaked".

FakeXMLHttpRequest.addFilter(fn)

          Add a filter that will decide whether or not to fake a request. The
          filter will be called when xhr.open is called, with the
          exact same arguments (method, url,
          async, username, password). If
          the filter returns truthy, the request will not be faked.

Simulating server responses

request.setResponseHeaders(object);

          Sets response headers (e.g. { "Content-Type": "text/html", /*
          ... */ }, updates the readyState property and
          fires onreadystatechange.

request.setResponseBody(body);

          Sets the respond body, updates the readyState property and
          fires onreadystatechange. Additionally,
          populates responseXML with a parsed document
          if response headers indicate as much.

request.respond(status, headers, body);

          Calls the above two methods and sets the status and
          statusText properties. Status should be a number, the
          status text is looked up from sinon.FakeXMLHttpRequest.statusCodes.

request.autoRespond(ms);

          Causes the server to automatically respond to incoming requests after
          a timeout. The default timeout is 10ms but you can control it through
          the ms argument. Note that this feature is intended to
          help during mockup development, and is not suitable for use in tests.

Fake server

        High-level API to manipulate FakeXMLHttpRequest instances.

{
    setUp: function () {
        this.server = sinon.fakeServer.create();
    },

    tearDown: function () {
        this.server.restore();
    },

    "test should fetch comments from server" : function () {
        this.server.respondWith("GET", "/some/article/comments.json",
                                [200, { "Content-Type": "application/json" },
                                 '[{ "id": 12, "comment": "Hey there" }]']);

        var callback = sinon.spy();
        myLib.getCommentsFor("/some/article", callback);
        this.server.respond();

        sinon.assert.calledWith(callback, [{ id: 12, comment: "Hey there" }]));
    }
}

var server = sinon.fakeServer.create();

          Creates a new server. This function also calls sinon.useFakeXMLHttpRequest().

var server = sinon.fakeServerWithClock.create();

          Creates a server that also manages fake timers. This is useful when
          testing XHR objects created with e.g. jQuery 1.3.x, which uses a timer
          to poll the object for completion, rather than the usual onreadystatechange.

server.respondWith(response);

            response is either a string - the response body, an array
            with status, headers and response body, e.g.
            [200, { "Content-Type": "text/html", "Content-Length": 2 },
            "OK"] or a function. Default status is 200 and default headers
            are none. Causes the server to respond to any request not matched by
            another response with the provided data. The default catch-all
            response is [404, {} ""].

            When the response is a function, it will be passed the request
            object. You must manually call respond on it
            to complete the request.

server.respondWith(url, response);

          Responds to all requests to given URL, e.g. /posts/1.

server.respondWith(method, url, response);

          Responds to all method requests to the given URL with the
          given response. method is an HTTP verb.

server.respondWith(urlRegExp, response);

          URL may be a regular expression, e.g. /\/post/\d+
          If the response is a function, it will be passed any capture groups
          from the regular expression along with the XMLHttpRequest object:

server.respondWith(/\/todo-items\/(\d+)/, function (xhr, id) {
    xhr.respond(200, { "Content-Type": "application/json" }, '[{ "id": ' + id + ' }]');
});

server.respondWith(method, urlRegExp, response);

          Responds to all method requests to URLs matching the
          regular expression.

server.respond();

          Causes all queued asynchronous requests to receive a response. If none
          of the responses added through respondWith match, the
          default response is [404, {}, ""]. Synchronous requests
          are responded to immediately, so make sure to call
          respondWith upfront. If called with arguments,
          respondWith will be called with those arguments before
          responding to requests.

server.autoRespond = true;

          If set, will call to srv.respondWith automatically after every request.

server.autoRespondAfter = ms;

          Causes the server to automatically respond to incoming requests after
          a timeout.

Boolean server.fakeHTTPMethods

          If set to true, server will find _method
          parameter in POST body and recognize that as the actual
          method. Supports a pattern common to Ruby on Rails applications. For
          custom HTTP method faking,
          override server.getHTTPMethod(request).

server.getHTTPMethod(request)

          Used internally to determine the HTTP method used with the provided
          request. By default this method simply
          returns request.method. When server.fakeHTTPMethods
          is true, the method will return the value of the _method
          parameter if the method is "POST". This method can be overrided to
          provide custom behavior.

server.restore();

          Restores the native XHR constructor.

Assertions API reference

        Sinon.JS ships with a set of assertions that mirror most behavior
        verification methods and properties on spies and stubs. The advantage of
        using the assertions is that failed expectations on stubs and spies can
        be expressed directly as assertion failures with detailed and helpful
        error messages.

        To make sure assertions integrate nicely with your test framework, you
        should customize either sinon.assert.fail or
        sinon.assert.failException and look into
        sinon.assert.expose and
        sinon.assert.pass.

        The assertions can be used with either spies or stubs.

"test should call subscribers with message as first argument" : function () {
    var message = 'an example message';
    var spy = sinon.spy();

    PubSub.subscribe(message, spy);
    PubSub.publishSync(message, "some payload");

    sinon.assert.calledOnce(spy);
    sinon.assert.calledWith(spy, message);
}

Assertions API

sinon.assert.fail(message)

          Every assertion fails by calling this method. By default it throws an
          error of type sinon.assert.failException. If your testing
          framework looks for assertion errors by checking for a specific
          exception, you can simply override the kind of exception thrown. If
          that does not fit with your testing framework of choice, override
          the fail method to do the right thing.

String sinon.assert.failException

          Defaults to "AssertError".

sinon.assert.pass(assertion)

          Called every time an assertion passes. Default implementation does
          nothing.

sinon.assert.notCalled(spy)

          Passes if spy was never called.

sinon.assert.called(spy)

          Passes if spy was called at least once.

sinon.assert.calledOnce(spy)

          Passes if spy was called once and only once.

sinon.assert.calledTwice()

          Passes if spy was called exactly twice.

sinon.assert.calledThrice()

          Passes if spy was called exactly three times.

sinon.assert.callCount(spy, num)

          Passes if the spy was called exactly num times.

sinon.assert.callOrder(spy1, spy2, ...)

          Passes if the provided spies where called in the specified order.

sinon.assert.calledOn(spy, obj)

          Passes if the spy was ever called with obj as
          its this value.

sinon.assert.alwaysCalledOn(spy, obj)

          Passes if the spy was always called with obj as
          its this value.

sinon.assert.calledWith(spy, arg1, arg2, ...)

          Passes if the spy was called with the provided arguments.

sinon.assert.alwaysCalledWith(spy, arg1, arg2, ...)

          Passes if the spy was always called with the provided arguments.

sinon.assert.neverCalledWith(spy, arg1, arg2, ...)

          Passes if the spy was never called with the provided arguments.

sinon.assert.calledWithExactly(spy, arg1, arg2, ...)

          Passes if the spy was called with the provided arguments and no others.

sinon.assert.alwaysCalledWithExactly(spy, arg1, arg2, ...)

          Passes if the spy was always called with the provided arguments and no
          others.

sinon.assert.calledWithMatch(spy, arg1, arg2, ...)

          Passes if the spy was called with matching arguments. This behaves
          the same as sinon.assert.calledWith(spy, sinon.match(arg1), sinon.match(arg2), ...).

sinon.assert.alwaysCalledWithMatch(spy, arg1, arg2, ...)

          Passes if the spy was always called with matching arguments. This behaves
          the same as sinon.assert.alwaysCalledWith(spy, sinon.match(arg1), sinon.match(arg2), ...).

sinon.assert.neverCalledWithMatch(spy, arg1, arg2, ...)

          Passes if the spy was never called with matching arguments. This behaves
          the same as sinon.assert.neverCalledWith(spy, sinon.match(arg1), sinon.match(arg2), ...).

sinon.assert.threw(spy, exception)

          Passes if the spy threw the given exception. The exception can be a
          string denoting its type, or an actual object. If only one argument is
          provided, the assertion passes if the spy ever threw any exception.

sinon.assert.alwaysThrew(spy, exception)

          Like above, only required for all calls to the spy.

sinon.assert.expose(object, options)

            Exposes assertions into another object, to better integrate with the
            test framework. For instance, JsTestDriver uses global assertions, and
            to make Sinon.JS assertions appear alongside them, you can do:

sinon.assert.expose(this);

            This will give you assertCalled(spy),
            assertCallOrder(spy1, spy2, ...) and so on.

            The method accepts an optional options object with two
            options. prefix is a prefix to give assertions. By
            default it is "assert", so sinon.assert.called becomes
            target.assertCalled. By passing a blank string, the
            exposed method will be target.called. The second
            option, includeFail is true by default, and copies
            over the fail and failException
            properties.

Matchers API reference

Matcher API

Combining matchers

Custom matchers

        Matchers can be passed as arguments to spy.calledWith,
        spy.returned and the corresponding
        sinon.assert functions as well as
        spy.withArgs. Matchers allow to be either
        more fuzzy or more specific about the expected value.

"test should assert fuzzy": function () {
    var book = {
        pages: 42,
        author: "cjno"
    };
    var spy = sinon.spy();

    spy(book);

    sinon.assert.calledWith(spy, sinon.match({ author: "cjno" }));
    sinon.assert.calledWith(spy, sinon.match.has("pages", 42));
}

"test should stub method differently based on argument types": function () {
    var callback = sinon.stub();
    callback.withArgs(sinon.match.string).returns(true);
    callback.withArgs(sinon.match.number).throws("TypeError");

    callback("abc"); // Returns true
    callback(123); // Throws TypeError
}

Matchers API

sinon.match(number)

Requires the value to be == to the given number.

sinon.match(string)

Requires the value to be a string and have the expectation as a substring.

sinon.match(regexp)

Requires the value to be a string and match the given regular expression.

sinon.match(object)

Requires the value to be not null or undefined and have at least the same properties as expectation. This supports nested matchers.

sinon.match(function)

See custom matchers.

sinon.match.any

Matches anything.

sinon.match.defined

Requires the value to be defined.

sinon.match.truthy

Requires the value to be truthy.

sinon.match.falsy

Requires the value to be falsy.

sinon.match.bool

Requires the value to be a boolean.

sinon.match.number

Requires the value to be a number.

sinon.match.string

Requires the value to be a string.

sinon.match.object

Requires the value to be an object.

sinon.match.func

Requires the value to be a function.

sinon.match.array

Requires the value to be an array.

sinon.match.regexp

Requires the value to be a regular expression.

sinon.match.date

Requires the value to be a date object.

sinon.match.same(ref)

Requires the value to strictly equal ref.

sinon.match.typeOf(type)

Requires the value to be of the given type, where type can be one of
          "undefined",
          "null",
          "boolean",
          "number",
          "string",
          "object",
          "function",
          "array",
          "regexp" or
          "date".

sinon.match.instanceOf(type)

Requires the value to be an instance of the given type.

sinon.match.has(property[, expectation])

Requires the value to define the given property. The
property might be inherited via the prototype chain. If the optional
expectation is given, the value of the property is deeply compared with
the expectation. The expectation can be another matcher.

sinon.match.hasOwn(property[, expectation])

Same as sinon.match.has but the property must be defined by the value itself. Inherited properties are ignored.

Combining matchers

        All matchers implement and and or. This
        allows to logically combine mutliple matchers. The result is a new
        matchers that requires both (and) or one of the matchers (or) to
        return true.

var stringOrNumber = sinon.match.string.or(sinon.match.number);

var bookWithPages = sinon.match.instanceOf(Book).and(sinon.match.has("pages"));

Custom matchers

        Custom matchers are created with the sinon.match factory
        which takes a test function and an optional message. The test function takes a
        value as the only argument, returns true if the
        value matches the expectation and false otherwise.
        The message string is used to generate the error message in case the
        value does not match the expectation.

var trueIsh = sinon.match(function (value) {
    return !!value;
}, "trueIsh");

Sandboxes API reference

sinon.sandbox

sinon.test

sinon.testCase

        Sandboxes simplify working with fakes that need to be restored and/or
        verified. If you're using fake timers, fake XHR, or you are
        stubbing/spying on globally accessible properties you should use a
        sandbox to ease cleanup. By default the spy, stub and mock properties of
        the sandbox is bound to whatever object the function is run on, so if you
        don't want to manually restore(), you have to use this.spy() instead of
        sinon.spy() (and stub, mock).

"test using sinon.test sandbox": sinon.test(function () {
    var myAPI = { method: function () {} };
    this.mock(myAPI).expects("method").once();

    PubSub.subscribe("message", myAPI.method);
    PubSub.publishSync("message", undefined);
})

var sandbox = sinon.sandbox.create();

Creates a sandbox object.

var sandbox = sinon.sandbox.create(config);

            The sinon.sandbox.create(config) method is mostly an
            integration feature, and as an end-user of Sinon.JS you will
            probably not need it.

            Creates a pre-configured sandbox object. The configuration can
            instruct the sandbox to include fake timers, fake server, and how to
            interact with these. The default configuration looks like:

sinon.defaultConfig = {
    // ...
    injectInto: null,
    properties: ["spy", "stub", "mock", "clock", "server", "requests"],
    useFakeTimers: true,
    useFakeServer: true
}

injectInto

              The sandbox's methods can be injected into another object for
              convenience. The injectInto configuration option can
              name an object to add properties to. Usually, this is set by
              sinon.test such that it is the this
              value in a given test function.

properties

              What properties to inject. Note that simply naming "server" here
              is not sufficient to have a server property show up
              in the target object, you also have to
              set useFakeServer to true.

useFakeTimers

              If true, the sandbox will have a clock
              property. Can also be an array of timer properties to fake.

useFakeServer

                If true, server and
                requests properties are added to the sandbox. Can
                also be an object to use for fake server. The default one
                is sinon.fakeServer, but if you're using jQuery 1.3.x
                or some other library that does not set the XHR's
                onreadystatechange handler, you might want to do:

sinon.config = {
    useFakeServer: sinon.fakeServerWithClock
};

sandbox.spy();

          Works exactly like sinon.spy, only also adds the returned
          spy to the internal collection of fakes for easy restoring
          through sandbox.restore().

sandbox.stub();

          Works almost exactly like sinon.stub, only also adds the
          returned stub to the internal collection of fakes for easy restoring
          through sandbox.restore(). The sandbox stub
          method can also be used to stub any kind of property. This is useful
          if you need to override an object's property for the duration of a
          test, and have it restored when the test completes.

sandbox.mock();

          Works exactly like sinon.mock, only also adds the returned
          mock to the internal collection of fakes for easy restoring
          through sandbox.restore().

sandbox.useFakeTimers();

          Fakes timers and binds the clock object to the sandbox
          such that it too is restored when
          calling sandbox.restore().
          Access through sandbox.clock.

sandbox.useFakeXMLHttpRequest();

          Fakes XHR and binds the resulting object to the sandbox such that it
          too is restored when calling sandbox.restore(). Access
          requests through sandbox.requests.

sandbox.useFakeServer();

          Fakes XHR and binds a server object to the sandbox such that it
          too is restored when calling sandbox.restore(). Access
          requests through sandbox.requests and server through
          sandbox.server.

sandbox.restore();

Restores all fakes created through sandbox.

Test methods

        Wrapping test methods in sinon.test allows Sinon.JS to
        automatically create and manage sandboxes for you. The function's
        behavior can be configured through sinon.config.

var wrappedFn = sinon.test(fn);

          The wrappedFn function works exactly like the original
          one in all respect - in addition a sandbox object is created and
          automatically restored when the function finishes a call. By default
          the spy, stub and mock properties of the sandbox is bound to whatever
          object the function is run on, so you can do this.spy()
          (and stub, mock) and it works exactly like sandbox.spy()
          (and stub, mock), except you don't need to manually restore().

sinon.config

        The configuration controls how Sinon binds properties when
        using sinon.test. The default configuration looks like:

{
    injectIntoThis: true,
    injectInto: null,
    properties: ["spy", "stub", "mock", "clock", "server", "requests"],
    useFakeTimers: true,
    useFakeServer: true
}

        Simply set sinon.config to override any or all of these,
        e.g.:

sinon.config = {
    useFakeTimers: false,
    useFakeServer: false
}

        In this case, defaults are used for the non-existent
        properties. Additionally, sandboxes and tests will not have automatic
        access to the fake timers and fake server when using this configuration.

Boolean injectIntoThis

          Causes properties to be injected into the this object of
          the test function. Default true.

Object injectInto

          Object to bind properties to. If this is null (default)
          and injectIntoThis is false (not default),
          the properties are passed as arguments to the test function instead.

Array properties

          Properties to expose. Default is all:
          ["spy", "stub", "mock", "clock", "server",
          "requests"]. However, the last three properties are only bound
          if the following two configuration options are true
          (which is the default).

Boolean useFakeTimers

          Causes timers to be faked and allows clock property to
          be exposed. Default is true.

Boolean useFakeServer

          Causes fake XHR and server to be created and allows
          server and requests properties to be
          exposed. Default is true.

Test cases

        If you need the behavior of sinon.test for more than one
        test method in a test case, you can use sinon.testCase,
        which behaves exactly like wrapping each test in sinon.test
        with one exception: setUp and tearDown can
        share fakes.

var obj = sinon.testCase({});

Sinon.JS utilities

        Sinon.JS has a few utilities used internally in lib/sinon.js. Unless the
        method in question is documented here, it should not be considered
        part of the public API, and thus is subject to change.

sinon.format(object)

          Formats an object for pretty printing in error messages. Sinon < 1.3.0
          defaulted to  coercing objects to strings. As of 1.3.0, Sinon uses
          buster-format
          by default, or
          Node's util
          module. Feel free to override this method with your own implementation
          if you prefer different visualization of e.g. objects. The method
          should return a string.

sinon.log(string)

          Logs internal errors, helpful for debugging. By default this property
          is a noop function, set it to something that prints warnings in your
          environment for more help, e.g. (if you are using JsTestDriver):

sinon.log = function (message) {
    jstestdriver.console.log(message);
};

Sinon uses Semantic versioning.

        Copyright 2010 - 2012,
        Christian Johansen. Released under the
        BSD license.


text:
/*	$NetBSD: bootxx.h,v 1.1 2000/12/04 18:44:51 scw Exp $	*/

/* This determines the largest boot program we can load. */
#define MAXBLOCKNUM	64

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Northern\Core\Common\Exception;

abstract class CoreException extends \RuntimeException {

	protected static $scope = 0;

}


text:
CASENUM=0
RUN=0
USERINPUT="N"
STOP=0;

RED='\033[0;91m'
GREEN='\033[0;92m'
YELLOW='\033[0;93m'
REG='\033[0m'

printf "${YELLOW}Please note any \"*****This Test Fails*****\"${REG}"; echo;

printf "${GREEN}Display all test results at once? (Enter Y for 'yes')${REG} \n"
echo
read USERINPUT
if [ $USERINPUT = "Y" ]
    then
        STOP=1;
fi

printf "${RED}Testing ouput using < , > , and >>:${REG} \n"
echo

((++CASENUM))
echo "Case $CASENUM"
USERINPUT="echo \"Output File 1\" > newOutputFile1 ; cat < newOutputFile1 && echo \" More stuff for Output file 1\" >> newOutputFile1 && cat < newOutputFile1; echo \"Finished task\""
echo "Input: $USERINPUT"
echo "Output:"
echo
bin/rshell <<< $USERINPUT
echo "Case $CASENUM Test Complete"
echo

if [ $STOP -eq 0 ]
    then
        printf "${GREEN}Press enter to continue${REG}"
        echo
        read RUN
fi

((++CASENUM))
echo "Case $CASENUM"
USERINPUT="sort < NE_1.txt && pwd >> newOutputFile1 ; cat < NE_1.txt || ls > NE_1.txt ; echo \"Finished task\""
echo "Input: $USERINPUT"
echo "Output:"
echo
bin/rshell <<< $USERINPUT
echo "Case $CASENUM Test Complete"
echo

if [ $STOP -eq 0 ]
    then
        printf "${GREEN}Press enter to continue${REG}"
        echo
        read RUN
fi

printf "${RED}Parentheses:${REG}"
echo

((++CASENUM))
echo "Case $CASENUM"
USERINPUT="(echo \"Dog\" > NE_1.txt && pwd >> NE_1.txt) > NE_2.txt && cat < NE_2.txt"
echo "Input: $USERINPUT"
echo "Output:"
echo
bin/rshell <<< $USERINPUT
echo "Case $CASENUM Test Complete"
echo

if [ $STOP -eq 0 ]
    then
        printf "${GREEN}Press enter to continue${REG}"
        echo
        read RUN
fi

((++CASENUM))
echo "Case $CASENUM"
USERINPUT="(ls ; cat < NE_3.txt && echo \"Dog\" > NE_1.txt && pwd >> NE_1.txt) > NE_2.txt"
echo "Input: $USERINPUT"
echo "Output:"
echo
bin/rshell <<< $USERINPUT
echo "Case $CASENUM Test Complete"
echo

if [ $STOP -eq 0 ]
    then
        printf "${GREEN}Press enter to continue${REG}"
        echo
        read RUN
fi


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>SourceDirectory (Gradle API 1.12)</title>
<meta name="date" content="2014-04-29">
<link rel="stylesheet" type="text/css" href="../../../../javadoc.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.gradle.tooling.model

Interface SourceDirectory

All Known Subinterfaces:

EclipseSourceDirectory, IdeaSourceDirectory

public interface SourceDirectory

Represents a source directory.

Method Summary

Methods

Modifier and Type
Method and Description

File
getDirectory()

Returns the source directory.

Method Detail

getDirectory

File getDirectory()

Returns the source directory.

Returns:

The source directory.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
require 'time'
require 'bunny'
require 'logger'
require "event_pub_sub/version"
require 'event_pub_sub/broker_handler'
require 'event_pub_sub/message_producer'
require 'event_pub_sub/message_consumer'
require 'event_pub_sub/listener'
require 'json'
require 'securerandom'

module EventPubSub

end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class ch.lambdaj.mock.Person (lambdaj 2.4-SNAPSHOT Test API)</title>
<meta name="date" content="2012-02-12">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
ch.lambdaj.mock.Person

Packages that use Person

Package
Description

ch.lambdaj

ch.lambdaj.collection

ch.lambdaj.mock

Uses of Person in ch.lambdaj

Subclasses of Person in ch.lambdaj

Modifier and Type
Class and Description

static class
LambdaTest.FinalPerson

static class
LambdaTest.NoEmptyConstructorPerson

Methods in ch.lambdaj with parameters of type Person

Modifier and Type
Method and Description

void
ClosureTest.setAgeOnPerson(Person person,
              int age)

Uses of Person in ch.lambdaj.collection

Subclasses of Person in ch.lambdaj.collection

Modifier and Type
Class and Description

static class
LambdaCollectionsTest.NoEmptyConstructorPerson

Methods in ch.lambdaj.collection that return Person

Modifier and Type
Method and Description

Person
LambdaIteratorTest.convert(Person from)

Methods in ch.lambdaj.collection with parameters of type Person

Modifier and Type
Method and Description

Person
LambdaIteratorTest.convert(Person from)

Uses of Person in ch.lambdaj.mock

Subclasses of Person in ch.lambdaj.mock

Modifier and Type
Class and Description

class
PersonThrowingException

Methods in ch.lambdaj.mock that return Person

Modifier and Type
Method and Description

Person
Person.getBestFriend()

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2012. All Rights Reserved.


text:
package cz.metacentrum.perun.wui.json.managers;

import com.google.gwt.http.client.Request;
import cz.metacentrum.perun.wui.json.JsonClient;
import cz.metacentrum.perun.wui.json.JsonEvents;

import java.util.ArrayList;

/**
 * Manager with standard callbacks to Perun's API (UsersManager).
 * <p/>
 * Each callback returns unique Request used to make call. Such call can be removed
 * while processing to prevent any further actions based on it's {@link cz.metacentrum.perun.wui.json.JsonEvents JsonEvents}.
 *
 * @author Pavel Zlámal <zlamal@cesnet.cz>
 */
public class UsersManager {

	private static final String USERS_MANAGER = "usersManager/";

	/**
	 * Check if provided login in selected namespace is available.
	 *
	 * @param namespace namespace to check in
	 * @param login login to check for
	 * @param events Events done on callback
	 *
	 * @return Request unique request
	 */
	public static Request isLoginAvailable(String namespace, String login, JsonEvents events) {

		JsonClient client = new JsonClient(events);
		client.put("login", login);
		client.put("loginNamespace", namespace);
		return client.call(USERS_MANAGER + "isLoginAvailable");

	}

	/**
	 * Search for RichUsers with attributes who matches the searchString by name, login or email.
	 *
	 * When list of attributes names is specified, only such attributes are returned. If null or empty,
	 * all user attributes with non-NULL value are returned.
	 *
	 * @param searchString searched string
	 * @param attrNames list of attributes name
	 * @param events Events done on callback
	 *
	 * @return Request unique request
	 */
	public static Request findRichUsersWithAttributes(String searchString, ArrayList<String> attrNames, JsonEvents events){

		if(searchString == null || searchString.trim().isEmpty()){
			return null;
		}

		JsonClient client = new JsonClient(events);
		client.put("searchString", searchString);
		client.put("attrsNames", attrNames);
		return client.call(USERS_MANAGER + "findRichUsersWithAttributes");
	}

	/**
	 * Search RichUsers without Vo.
	 *
	 * @param events Events done on callback
	 *
	 * @return Request unique request
	 */
	public static Request getRichUsersWithoutVoAssigned(JsonEvents events){

		JsonClient client = new JsonClient(events);
		return client.call(USERS_MANAGER + "getRichUsersWithoutVoAssigned");
	}

	/**
	 * Get RichUser by ID with all filled attributes
	 *
	 * @param id Users ID
	 * @param events Events done on callback
	 *
	 * @return Request unique request
	 */
	public static Request getRichUserWithAttributes(int id, JsonEvents events){

		JsonClient client = new JsonClient(events);
		if (id > 0) client.put("user", id);
		return client.call(USERS_MANAGER + "getRichUserWithAttributes");

	}

	/**
	 * Remove UserExtSource from User
	 *
	 * @param userId Users ID
	 * @param userExtSourceId ID of UserExtSource to remove
	 * @param events Events done on callback
	 *
	 * @return Request unique request
	 */
	public static Request removeUserExtSource(int userId, int userExtSourceId, JsonEvents events){

		JsonClient client = new JsonClient(events);
		if (userId > 0) client.put("user", userId);
		if (userExtSourceId > 0) client.put("userExtSource", userExtSourceId);
		return client.call(USERS_MANAGER + "removeUserExtSource");

	}

	/**
	 * Gets list of all external sources of the user.
	 *
	 * @param userId Users ID
	 * @param events Events done on callback
	 *
	 * @return Request unique request
	 */
	public static Request getUserExtSources(int userId, JsonEvents events){

		JsonClient client = new JsonClient(events);
		if (userId > 0) client.put("user", userId);
		return client.call(USERS_MANAGER + "getUserExtSources");

	}

	/**
	 * Return list of VOs where user is a member (independent of membership status)
	 *
	 * @param userId Users ID
	 * @param events Events done on callback
	 *
	 * @return Request unique request
	 */
	public static Request getVosWhereUserIsMember(int userId, JsonEvents events){

		JsonClient client = new JsonClient(events);
		if (userId > 0) client.put("user", userId);
		return client.call(USERS_MANAGER + "getVosWhereUserIsMember");

	}

	/**
	 * Request to change preferred email address of user. Validation mail is sent on new address.
	 * Change is not saved until user validate new email address by calling validatePreferredEmailChange()
	 * method with proper set of parameters (sent in validation mail).
	 *
	 * @param userId Users ID
	 * @param email  New email address to set
	 * @param events Events done on callback
	 *
	 * @return Request unique request
	 */
	public static Request requestPreferredEmailChange(int userId, String email, JsonEvents events) {

		JsonClient client = new JsonClient(events);
		if (userId > 0) client.put("user", userId);
		client.put("email", email);
		return client.call(USERS_MANAGER + "requestPreferredEmailChange");

	}

	/**
	 * Request to change preferred email address of user. Validation mail is sent on new address.
	 * Change is not saved until user validate new email address by calling validatePreferredEmailChange()
	 * method with proper set of parameters (sent in validation mail).
	 *
	 * @param userId Users ID
	 * @param events Events done on callback
	 *
	 * @return Request unique request
	 */
	public static Request getPendingPreferredEmailChanges(int userId, JsonEvents events) {

		JsonClient client = new JsonClient(events);
		if (userId > 0) client.put("user", userId);
		return client.call(USERS_MANAGER + "getPendingPreferredEmailChanges");

	}

	/**
	 * Change password in selected namespace
	 *
	 * @param userId Users ID
	 * @param loginNamespace Login namespace in a which user wants to change password
	 * @param oldPass Old password used by the user
	 * @param newPass New password set for the user
	 * @param events Events done on callback
	 *
	 * @return Request unique request
	 */
	public static Request changePassword(int userId, String loginNamespace, String oldPass, String newPass, JsonEvents events){

		JsonClient client = new JsonClient(events);
		if (userId > 0) client.put("user", userId);
		if (loginNamespace != null && !loginNamespace.isEmpty()) client.put("loginNamespace", loginNamespace);
		if (oldPass != null && !oldPass.isEmpty()) client.put("oldPassword", oldPass);
		if (newPass!= null && !newPass.isEmpty()) client.put("newPassword", newPass);
		client.put("checkOldPassword", 1);
		return client.call(USERS_MANAGER + "changePassword");

	}

	/**
	 * Reset users password in selected namespace
	 *
	 * @param userId Users ID
	 * @param loginNamespace Login namespace in a which user wants to reset password
	 * @param newPass New password set for the user
	 * @param events Events done on callback
	 *
	 * @return Request unique request
	 */
	public static Request resetPassword(int userId, String loginNamespace, String newPass, JsonEvents events){

		JsonClient client = new JsonClient(events);
		client.put("oldPassword", "");
		client.put("checkOldPassword", 0);

		if (userId > 0) client.put("user", userId);
		if (loginNamespace != null && !loginNamespace.isEmpty()) client.put("loginNamespace", loginNamespace);
		if (newPass!= null && !newPass.isEmpty()) client.put("newPassword", newPass);
		return client.call(USERS_MANAGER + "changePassword");

	}

	/**
	 * Reset users password in selected namespace by non-authz call using secret token
	 *
	 * @param i Token param i
	 * @param m Token param m
	 * @param newPass New password set for the user
	 * @param events Events done on callback
	 *
	 * @return Request unique request
	 */
	public static Request resetNonAuthzPassword(String i, String m, String newPass, JsonEvents events){

		JsonClient client = new JsonClient(events);
		if (i != null && !i.isEmpty()) client.put("i", i);
		if (m != null && !m.isEmpty()) client.put("m", m);
		if (newPass!= null && !newPass.isEmpty()) client.put("password", newPass);
		return client.call(USERS_MANAGER + "changeNonAuthzPassword");

	}

}


text:
<?php

require(__DIR__."/../vendor/autoload.php");

use PHPUnit\Framework\TestCase;

////////////////////
/// Setup Aliasing
////////////////////

use Simnang\LoanPro\LoanProSDK as LPSDK,
    Simnang\LoanPro\Constants\LOAN as LOAN,
    Simnang\LoanPro\Constants\DOC_SECTION as DOC_SECTION,
    Simnang\LoanPro\Constants\BASE_ENTITY as BASE_ENTITY
    ;

////////////////////
/// Done Setting Up Aliasing
////////////////////

class DocSectionTest extends TestCase
{
    public static function setUpBeforeClass(){
        \Simnang\LoanPro\BaseEntity::SetStrictMode(true);
    }
    /**
     * @group create_correctness
     * @group offline
     */
    public function testDocSectionInstantiate(){
        // DocSections aren't exposed via LoanProSDK since they are saved and operated on differently
        $doc = new \Simnang\LoanPro\Loans\DocSectionEntity();

        $rclass = new \ReflectionClass('Simnang\LoanPro\Constants\DOC_SECTION');
        $consts = $rclass->getConstants();

        // make sure every other field is null
        foreach($consts as $key=>$field){
            $this->assertNull(null,$doc->Get($field));
        }
    }

    /**
     * @group set_correctness
     * @group offline
     */
    public function testLoanCannotSetNull(){
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage("Value for 'active' is null. The 'Set' function Cannot unset items, please use 'Rem' instead for class Simnang\\LoanPro\\Loans\\DocSectionEntity");
        (new \Simnang\LoanPro\Loans\DocSectionEntity())
            /* should throw exception when setting LOAN_AMT to null */ ->Set(DOC_SECTION::ACTIVE, null);
    }

    /**
     * @group set_correctness
     * @group offline
     */
    public function testLoanCheckValidProp(){
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage('Invalid property \''.\Simnang\LoanPro\Constants\LOAN_SETUP::AMT_DOWN.'\'');
        $ls = (new \Simnang\LoanPro\Loans\DocSectionEntity());
        $ls->Set(BASE_ENTITY::ID, 120);

        /* should throw exception when setting AGENT to null */
        $ls->Set(\Simnang\LoanPro\Constants\LOAN_SETUP::AMT_DOWN, 1280.32);
    }

    /**
     * @group del_correctness
     * @group offline
     */
    public function testDocSectionDel(){
        $doc = (new \Simnang\LoanPro\Loans\DocSectionEntity())->Set([DOC_SECTION::ACTIVE=> 1]);
        $this->assertEquals(1, $doc->Get(DOC_SECTION::ACTIVE));
        /* deletions should have 'get' return 'null' */
        $this->assertNull($doc->Rem(DOC_SECTION::ACTIVE)->Get(DOC_SECTION::ACTIVE));
        /* deletions should also not affect the original object (just return a copy) */
        $this->assertEquals(1, $doc->Get(DOC_SECTION::ACTIVE));
    }
}


text:
title: activiti流程文件部署
tags: [activiti]
---

### 流程资源文件

1)流程文件

主要包括流程描述文件、流程图等。Activiti如果需要对这些资源进行操作(包括添加、删除和查询等),可以使用RepositoryService提供的API来实现。

2)ACT_GE_BYTEARRAY表的存储内容

流程文件数据将会被保存在ACT_GE_BYTEARRAY表中,对应的实体为ResourceEntity。

另外,该表还会保存用户的图片数据,对应的实体为ByteArrayEntity。

两者的区别?

ResourceEntity会设置ACT_GE_BYTEARRAY表的GENERATED_字段值,而ByteArrayEntity保存时,该值为null。

### Deployment对象

1)接口

Deployment是一个接口,表示ACT_RE_DEPLOYMENT表的数据。实现类为DeploymentEntity。

```
protected String id;//对应ACT_RE_DEPLOYMENT表的ID_列
protected String name;//对应ACT_RE_DEPLOYMENT表的NAME_列
protected Date deploymentTime;//对应ACT_RE_DEPLOYMENT表的DEPLOY_TIME_列
```

注:调用DeploymentBuilder的deploy方法返回Deployment对象。

### DeploymentEntity和ResourceEntity的关系

1)实体与表

ResourceEntity与DeploymentEntity均为持久化对象。一个ResourceEntity实例表示一条ACT_GE_BYTEARRAY表的数据,一个DeploymentEntity实例表示一条ACT_RE_DEPLOYMENT表的数据。

2)多对一的关系

ResourceEntity与DeploymentEntity为多对一的关系,级一个DeploymentEntity下可以有多个ResourceEntity。在DeploymentEntity中维护一个Map对象来保存该部署的全部资源文件。

3)addInputStream的操作过程

DeploymentBuilder中的addInputStream方法,会将参数InputStream对象设置到ResourceEntity对象中,最后保存到DeploymentEntity中。每个DeploymentBuilder实例中均会维护一个DeploymentEntity实例,调用多次addInputStream会生成多个ResourceEntity对象,而与这些对象相关的只有一个DeploymentEntity。

4)数据存储的对应关系

DeploymentBuilder调用deploy方法后会将DeploymentEntity及它的全部ResourceEntity(map集合中维护关系)写到数据库中。ACT_GE_BYTEARRAY表的DEPLOYMENT_ID_值与ACT_RE_DEPLOYMENT表的主键相关联。

### 流程资源的部署

1)DeploymentBuilder对象

对流程的部署可以使用DeploymentBuilder对象完成,该对象用于从指定资源中加载(addClasspathResource等方法),并部署到系统中(deploy方法)。

获取DeploymentBuilder对象

```
//创建流程引擎
ProcessEngine engine = ProcessEngines.getDefaultProcessEngine();
//得到流程存储服务对象
RepositoryService repositoryService = engine.getRepositoryService();
//创建DeploymentBuilder实例
DeploymentBuilder builder = repositoryService.createDeployment();
```

2)添加资源

内部的执行过程:会将添加的资源封装到ResourceEntity对象中,最后存到DeploymentEntity中。

方式一:添加输入流资源

DeploymentBuilder中提供了一个addInputStream方法,参数为InputStream对象。

```
// 资源输入流
InputStream is1 = new FileInputStream(new File(
    "resource/artifact/flow_inputstream1.png"));
builder.addInputStream("inputA", is1);
```

方式二:添加Classpath资源

addClasspathResource方法将classpath下的资源写入到数据库中,底层会得到当前的ClassLoader对象,调用getResourceAsStream方法将指定的classpath下的资源文件转换为InputStream,再调用addInputStream方法。

```
//添加classpath下的资源
builder.addClasspathResource("artifact/classpath.png");
```

方式三:添加字符串资源

将一些流程定义的属性或公用的变量保存起来时,可以使用addString方法。

```
//添加String资源
builder.addString("test", "this is string method");
```

```
+-----+-------+---------------------+
| ID_ | NAME_ | DEPLOY_TIME_        |
+-----+-------+---------------------+
| 1   | NULL  | 2017-08-13 22:49:55 |
+-----+-------+---------------------+

+-----+------+-------+----------------+-----------------------+------------+
| ID_ | REV_ | NAME_ | DEPLOYMENT_ID_ | BYTES_                | GENERATED_ |
+-----+------+-------+----------------+-----------------------+------------+
| 2   |    1 | test  | 1              | this is string method |          0 |
+-----+------+-------+----------------+-----------------------+------------+
```

方式四:添加压缩包资源

使用DeploymentBuilder提供的addZipInputStream方法直接部署压缩包,该方法会遍历压缩包内的全部文件,然后将这些文件转换为byte数组,写到资源表中。

```
//获取zip文件的输入流
FileInputStream fis = new FileInputStream(new File("resource/artifact/ZipInputStream.zip"));
//读取zip文件,创建ZipInputStream对象
ZipInputStream zi = new ZipInputStream(fis);
//添加Zip压缩包资源
builder.addZipInputStream(zi);
```

注:zipInputStream是jdk自带的java类

3)修改部署名称

DeploymentBuilder的name方法可以设置部署名称,会更新ACT_RE_DEPLOYMENT的NAME_字段值。

```
builder.name("crazyit");
```

4)过滤重复部署

多次调用同一个资源部署,会在数据库中生成多个Deployment记录(ACT_RE_DEPLOYMENT)。如果想避免这种情况,可以调用DeploymentBuilder的enableDuplicateFiltering方法。

```
builder.enableDuplicateFiltering();
```

该方法仅仅将DeploymentBuilder的isDuplicateFilterEnabled属性设置为true,在执行deploy方法时,如果发现该值为true,则根据部署对象(DeploymentEntity)的名称去查询最后部署的记录。如果发现最后一条部署的记录与当前部署的记录一致,则不会重复部署。

注:这里所说的一致,是指Deployment下的资源是否相同(ACT_GE_BYTEARRAY表),包括资源名称和资源内容。


text:
class CWallet;

namespace interfaces {
class Chain;
class Handler;
class Wallet;
}

class DummyWalletInit : public WalletInitInterface {
public:

    bool HasWalletSupport() const override {return false;}
    void AddWalletOptions(ArgsManager& argsman) const override;
    bool ParameterInteraction() const override {return true;}
    void Construct(NodeContext& node) const override {LogPrintf("No wallet support compiled in!\n");}
};

void DummyWalletInit::AddWalletOptions(ArgsManager& argsman) const
{
    argsman.AddHiddenArgs({
        "-addresstype",
        "-avoidpartialspends",
        "-changetype",
        "-disablewallet",
        "-discardfee=<amt>",
        "-fallbackfee=<amt>",
        "-keypool=<n>",
        "-maxapsfee=<n>",
        "-maxtxfee=<amt>",
        "-mintxfee=<amt>",
        "-paytxfee=<amt>",
        "-rescan",
        "-salvagewallet",
        "-signer=<cmd>",
        "-spendzeroconfchange",
        "-txconfirmtarget=<n>",
        "-wallet=<path>",
        "-walletbroadcast",
        "-walletdir=<dir>",
        "-walletnotify=<cmd>",
        "-walletrbf",
        "-dblogsize=<n>",
        "-flushwallet",
        "-privdb",
        "-walletrejectlongchains",
        "-unsafesqlitesync",
    });
}

const WalletInitInterface& g_wallet_init_interface = DummyWalletInit();

namespace interfaces {

std::unique_ptr<Wallet> MakeWallet(const std::shared_ptr<CWallet>& wallet)
{
    throw std::logic_error("Wallet function called in non-wallet build.");
}

} // namespace interfaces


text:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="test-to-html.xsl" type="text/xml"?>

<!--

Copyright (c) 2001 World Wide Web Consortium,
(Massachusetts Institute of Technology, Institut National de
Recherche en Informatique et en Automatique, Keio University).  All
Rights Reserved.  This program is distributed under the W3C's Software
Intellectual Property License.  This program is distributed in the
hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.

See W3C License http://www.w3.org/Consortium/Legal/ for more details.

-->
<!DOCTYPE test SYSTEM "dom1.dtd">
<test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-1" name="HTMLInputElement08">
<metadata>
<title>HTMLInputElement08</title>
<creator>NIST</creator>
<description>
    The checked attribute represents the current state of the corresponding
    form control when type has the value Radio or Checkbox.

    Retrieve the accept attribute of the 3rd INPUT element and examine
    its value.
</description>
<contributor>Mary Brady</contributor>
<date qualifier="created">2002-02-22</date>
<subject resource="http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-html#ID-30233917"/>
</metadata>
<var name="nodeList" type="NodeList"/>
<var name="testNode" type="Node"/>
<var name="vchecked" type="boolean" />
<var name="doc" type="Document"/>
<load var="doc" href="input" willBeModified="false"/>
<getElementsByTagName interface="Document" obj="doc" var="nodeList" tagname='"input"'/>
<assertSize collection="nodeList" size="9" id="Asize"/>
<item interface="NodeList" obj="nodeList" var="testNode" index="2"/>
<checked interface="HTMLInputElement" obj="testNode" var="vchecked"/>
<assertTrue actual="vchecked" id="checkedLink"/>
</test>


text:
package de.ks.strudel.util;

import com.google.inject.Guice;
import com.google.inject.Injector;
import de.ks.strudel.Strudel;
import de.ks.strudel.StrudelModule;
import io.restassured.RestAssured;
import io.restassured.parsing.Parser;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.Extension;
import org.junit.jupiter.api.extension.TestExtensionContext;
import org.junit.jupiter.api.function.Executable;

public class StrudelTestExtension implements Extension, BeforeEachCallback, AfterEachCallback {
  private Strudel strudel;
  public static int port = 7777;

  @Override
  public void afterEach(TestExtensionContext context) throws Exception {
    strudel.stop();
  }

  @Override
  public void beforeEach(TestExtensionContext context) throws Exception {
    Injector injector = Guice.createInjector(new StrudelModule());
    strudel = injector.getInstance(Strudel.class);
    strudel.options().port(port);
    RestAssured.port = port;
    RestAssured.defaultParser = Parser.HTML;

    injector.injectMembers(context.getTestInstance());
  }

  public static Executable wrap(Object test, Executable original) {
    Injector injector = Guice.createInjector(new StrudelModule());
    Strudel local = injector.getInstance(Strudel.class);
    local.options().port(StrudelTestExtension.port);
    RestAssured.port = StrudelTestExtension.port;
    RestAssured.defaultParser = Parser.HTML;

    injector.injectMembers(test);
    return () -> {
      try {
        original.execute();
      } finally {
        local.stop();
      }
    };
  }
}


text:
using System.IO;

namespace RoaringDB.Operations.Collection
{
    internal class AddManyOp<T> : IOperation
        where T : class, new ()
    {
        public RoaringCollection<T> Collection { get; }
        public uint[] Keys { get; }
        public uint[][] Values { get; }
        public int[] ValueCounts { get; }

        public byte Type => (byte)OpType.AddMany;

        public AddManyOp(RoaringCollection<T> collection, uint[] keys, uint[][] values, int[] valueCounts)
        {
            Collection = collection;
            Keys = keys;
            Values = values;
            ValueCounts = valueCounts;
        }

        public static AddManyOp<T> Deserialize(RoaringCollection<T> collection, BinaryReader reader)
        {
            var keyCount = reader.ReadInt32();
            var keys = new uint[keyCount];
            for (int i = 0; i < keyCount; i++)
                keys[i] = reader.ReadUInt32();

            var bitmapCount = reader.ReadInt32();
            var valueCounts = new int[bitmapCount];
            var values = new uint[bitmapCount][];
            for (int i = 0; i < bitmapCount; i++)
            {
                valueCounts[i] = reader.ReadInt32();
                var bitmapValues = new uint[valueCounts[i]];
                for (int j = 0; j < bitmapValues.Length; j++)
                    bitmapValues[j] = reader.ReadUInt32();
                values[i] = bitmapValues;
            }

            return new AddManyOp<T>(collection, keys, values, valueCounts);
        }

        public void Execute()
        {
            Collection.AddManyInternal(Keys, Values, ValueCounts);
        }
        public void Serialize(BinaryWriter writer)
        {
            writer.Write((uint)Keys.Length);
            for (int i = 0; i < Keys.Length; i++)
                writer.Write((uint)Keys[i]);

            writer.Write((uint)Values.Length);
            for (int i = 0; i < Values.Length; i++)
            {
                writer.Write((int)ValueCounts[i]);
                for (int j = 0; j < ValueCounts[i]; j++)
                    writer.Write((uint)Values[i][j]);
            }
        }

        public override string ToString() => $"Add {Keys.Length} rows";
    }
}


text:
using System.Diagnostics;

namespace SignalR.Client._20
{
	[DebuggerDisplay("{ConnectionId} {Url} -> {ProtocolVersion}")]
	public class NegotiationResponse
	{
		public string ConnectionId { get; set; }
		public string Url { get; set; }
        public string ProtocolVersion { get; set; }
        public string ConnectionToken { get; set; }
        public double DisconnectTimeout { get; set; }
        public bool TryWebSockets { get; set; }
        public double? KeepAliveTimeout { get; set; }
        public double TransportConnectTimeout { get; set; }
	}
}


text:
package core

import (
	"sync/atomic"
	"time"

	"github.com/pingcap/parser/ast"
	"github.com/pingcap/parser/mysql"
	"github.com/pingcap/tidb/sessionctx/variable"
	"github.com/pingcap/tidb/types"
	"github.com/pingcap/tidb/util/codec"
	"github.com/pingcap/tidb/util/hack"
	"github.com/pingcap/tidb/util/kvcache"
	atomic2 "go.uber.org/atomic"
)

var (
	// preparedPlanCacheEnabledValue stores the global config "prepared-plan-cache-enabled".
	// If the value of "prepared-plan-cache-enabled" is true, preparedPlanCacheEnabledValue's value is 1.
	// Otherwise, preparedPlanCacheEnabledValue's value is 0.
	preparedPlanCacheEnabledValue int32
	// PreparedPlanCacheCapacity stores the global config "prepared-plan-cache-capacity".
	PreparedPlanCacheCapacity uint
	// PreparedPlanCacheMemoryGuardRatio stores the global config "prepared-plan-cache-memory-guard-ratio".
	PreparedPlanCacheMemoryGuardRatio float64
	// PreparedPlanCacheMaxMemory stores the max memory size defined in the global config "performance-max-memory".
	PreparedPlanCacheMaxMemory atomic2.Uint64
)

const (
	preparedPlanCacheEnabled = 1
	preparedPlanCacheUnable  = 0
)

// SetPreparedPlanCache sets isEnabled to true, then prepared plan cache is enabled.
func SetPreparedPlanCache(isEnabled bool) {
	if isEnabled {
		atomic.StoreInt32(&preparedPlanCacheEnabledValue, preparedPlanCacheEnabled)
	} else {
		atomic.StoreInt32(&preparedPlanCacheEnabledValue, preparedPlanCacheUnable)
	}
}

// PreparedPlanCacheEnabled returns whether the prepared plan cache is enabled.
func PreparedPlanCacheEnabled() bool {
	isEnabled := atomic.LoadInt32(&preparedPlanCacheEnabledValue)
	return isEnabled == preparedPlanCacheEnabled
}

type pstmtPlanCacheKey struct {
	database       string
	connID         uint64
	pstmtID        uint32
	snapshot       uint64
	schemaVersion  int64
	sqlMode        mysql.SQLMode
	timezoneOffset int

	hash []byte
}

// Hash implements Key interface.
func (key *pstmtPlanCacheKey) Hash() []byte {
	if len(key.hash) == 0 {
		var (
			dbBytes    = hack.Slice(key.database)
			bufferSize = len(dbBytes) + 8*6
		)
		if key.hash == nil {
			key.hash = make([]byte, 0, bufferSize)
		}
		key.hash = append(key.hash, dbBytes...)
		key.hash = codec.EncodeInt(key.hash, int64(key.connID))
		key.hash = codec.EncodeInt(key.hash, int64(key.pstmtID))
		key.hash = codec.EncodeInt(key.hash, int64(key.snapshot))
		key.hash = codec.EncodeInt(key.hash, key.schemaVersion)
		key.hash = codec.EncodeInt(key.hash, int64(key.sqlMode))
		key.hash = codec.EncodeInt(key.hash, int64(key.timezoneOffset))
	}
	return key.hash
}

// SetPstmtIDSchemaVersion implements PstmtCacheKeyMutator interface to change pstmtID and schemaVersion of cacheKey.
// so we can reuse Key instead of new every time.
func SetPstmtIDSchemaVersion(key kvcache.Key, pstmtID uint32, schemaVersion int64) {
	psStmtKey, isPsStmtKey := key.(*pstmtPlanCacheKey)
	if !isPsStmtKey {
		return
	}
	psStmtKey.pstmtID = pstmtID
	psStmtKey.schemaVersion = schemaVersion
	psStmtKey.hash = psStmtKey.hash[:0]
}

// NewPSTMTPlanCacheKey creates a new pstmtPlanCacheKey object.
func NewPSTMTPlanCacheKey(sessionVars *variable.SessionVars, pstmtID uint32, schemaVersion int64) kvcache.Key {
	timezoneOffset := 0
	if sessionVars.TimeZone != nil {
		_, timezoneOffset = time.Now().In(sessionVars.TimeZone).Zone()
	}
	return &pstmtPlanCacheKey{
		database:       sessionVars.CurrentDB,
		connID:         sessionVars.ConnectionID,
		pstmtID:        pstmtID,
		snapshot:       sessionVars.SnapshotTS,
		schemaVersion:  schemaVersion,
		sqlMode:        sessionVars.SQLMode,
		timezoneOffset: timezoneOffset,
	}
}

// PSTMTPlanCacheValue stores the cached Statement and StmtNode.
type PSTMTPlanCacheValue struct {
	Plan        Plan
	OutPutNames []*types.FieldName
}

// NewPSTMTPlanCacheValue creates a SQLCacheValue.
func NewPSTMTPlanCacheValue(plan Plan, names []*types.FieldName) *PSTMTPlanCacheValue {
	return &PSTMTPlanCacheValue{
		Plan:        plan,
		OutPutNames: names,
	}
}

// CachedPrepareStmt store prepared ast from PrepareExec and other related fields
type CachedPrepareStmt struct {
	PreparedAst *ast.Prepared
	VisitInfos  []visitInfo
	ColumnInfos interface{}
}


text: Implementation of the Raft consensus protocol


text:
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;

// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108

namespace System.Windows.Controls.Primitives
{
  public partial class StatusBar : System.Windows.Controls.ItemsControl
  {
    #region Methods and constructors
    protected override System.Windows.DependencyObject GetContainerForItemOverride()
    {
      return default(System.Windows.DependencyObject);
    }

    protected override bool IsItemItsOwnContainerOverride(Object item)
    {
      return default(bool);
    }

    protected override System.Windows.Automation.Peers.AutomationPeer OnCreateAutomationPeer()
    {
      return default(System.Windows.Automation.Peers.AutomationPeer);
    }

    protected override void PrepareContainerForItemOverride(System.Windows.DependencyObject element, Object item)
    {
    }

    protected override bool ShouldApplyItemContainerStyle(System.Windows.DependencyObject container, Object item)
    {
      return default(bool);
    }

    public StatusBar()
    {
    }
    #endregion

    #region Properties and indexers
    public static System.Windows.ResourceKey SeparatorStyleKey
    {
      get
      {
        Contract.Ensures(Contract.Result<System.Windows.ResourceKey>() != null);

        return default(System.Windows.ResourceKey);
      }
    }
    #endregion
  }
}


text:
using GlyssenEngine;
using InMemoryTestPersistence;
using NUnit.Framework;

namespace GlyssenEngineTests
{
	/// <summary>
	/// Assembly-level one-time setup (https://github.com/nunit/nunit/issues/1577)
	/// </summary>
	[SetUpFixture]
	public class TestFixtureSetUp
	{
		[OneTimeSetUp]
		public void OneTimeSetUp()
		{
			var persistenceImpl = new PersistenceImplementation();
			ProjectBase.Reader = persistenceImpl;
			ReferenceTextProxy.Reader = persistenceImpl;
			Project.Writer = persistenceImpl;
		}
	}
}


text:
python-crowd
============

.. image:: https://img.shields.io/pypi/pyversions/crowd.svg
        :target: https://pypi.python.org/pypi/jira/

.. image:: https://img.shields.io/pypi/l/crowd.svg
        :target: https://pypi.python.org/pypi/crowd/

.. image:: https://img.shields.io/pypi/dm/crowd.svg
        :target: https://pypi.python.org/pypi/crowd/

------------

.. image:: https://api.travis-ci.org/pycontribs/python-crowd.svg?branch=master
        :target: https://travis-ci.org/pycontribs/python-crowd

.. image:: https://img.shields.io/pypi/status/crowd.svg
        :target: https://pypi.python.org/pypi/crowd/

.. image:: https://img.shields.io/coveralls/pycontribs/crowd.svg
        :target: https://coveralls.io/r/pycontribs/crowd

python-crowd is a python client library to the Atlassian Crowd REST API.

This library may be useful to you if you wish to create an application
that authenticates users against Crowd or integrate with Crowd's SSO.

This project has no official status within Atlassian and is provided as
a service to the programming community. I hope that you find it useful.

Documentation
=============

Docs are built automatically by sphinx. You can build them yourself
in the doc directory or access them at
http://python-crowd.readthedocs.io/en/latest/

Examples
========

Some example invocations are provided in the examples directory, and
are included in the built documentation.

The unit tests may also be instructive.

License
=======
*BSD 2-Clause License*

Copyright (c) 2012-2014, Alexander Else
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

* Redistributions of source code must retain the above copyright notice,
  this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.

Contributors License Agreement
==============================

By contributing you agree that these contributions are your own (or approved by your employer) and you grant a full, complete, irrevocable copyright license to all users and developers of the project, present and future, pursuant to the license of the project.

Contributors
============

This project has been enhanced through the work of a number of contributors.
If you contribute to this project you can add your name and/or github username
to the end of this list and include the change in your pull request.

* Alexander Else (@aelse) - Original author
* Luke Cyca (@lukecyca)
* Dan Hansen (@dansomething)
* Terin Stock (@terinjokes)
* Sorin Sbarnea (@ssbarnea)
* Christian Schläppi (@nevious)
* Yuichi Tokutomi (@Tommy1969)
* Attila Bogár (@attilabogar)
* Jascha Geerds (@jgeerds)
* John Christian (@potus98)
* Maiko Bossuyt (@maiko)
* Oleg Sinilo (@GoRoSfan)


text: ln -s ../tre/environment .


text:
bool doorOpening(void)
{
	return false;
}

bool doorClosing(void)
{
	return false;
}


text:
<?php
namespace Minsal\SiapsBundle\Service\JasperReportService;

class DIMERecord {

    public $version;
    public $first;
    public $last;
    public $chunked;
    public $type_format;
    public $options;
    public $id;
    public $type;
    public $data;

}

?>


text:
from .cardinal_directions import CARDINAL_DIRECTIONS
from .hex_vector import HexVector
from .neighbors import find_neighbors
from .range import range_around
from .ring import ring_around


text:
FROM php:7.0-apache

RUN apt-get update \
 && apt-get install -y git zlib1g-dev \
 && docker-php-ext-install zip \
 && a2enmod rewrite \
 && sed -i 's!/var/www/html!/var/www/public!g' /etc/apache2/apache2.conf \
 && mv /var/www/html /var/www/public \
 && curl -sS https://getcomposer.org/installer \
  | php -- --install-dir=/usr/local/bin --filename=composer

WORKDIR /var/www


text:
import { registerComponent } from 'nornj';
import ImagePicker from 'antd-mobile/lib/image-picker/index';

registerComponent({
  'antm-ImagePicker': ImagePicker
});

export default ImagePicker;


text:
(function() {

  var disqus_shortname = '<%= jekyllConfig.disqus_username %>',
    s = document.createElement('script');

  s.type = 'text/javascript';
  s.async = true;
  s.src = 'http://' + disqus_shortname + '.disqus.com/count.js';

  ( document.getElementsByTagName('HEAD')[ 0 ] || document.getElementsByTagName('BODY')[ 0 ] ).appendChild( s );
}());

// Disqus recent comments
(function() {

  var s = document.createElement('script'),
    owner = '<%= jekyllConfig.github_username %>',
    disqusApiUrl = 'https://disqus.com/api/3.0/forums/listPosts.jsonp?forum=',
    forum = '<%= jekyllConfig.disqus_username %>',
    apiKey = '<%= jekyllConfig.disqus_api_key %>';

  s.type = 'text/javascript';
  s.async = true;
  s.src = disqusApiUrl + forum + '&related=thread&api_key=' + apiKey + '&callback=' + owner + '.getRecentComments';

  window[ owner ] = window[ owner ] || {};
  window[ owner ].getRecentComments = function( data ) {

    if ( !isThereComment() ) {
      return;
    }

    var ulTag = document.createElement('ul'),
      liTag,
      aTag,
      spanTag,
      i = 0,
      numOfComments = data.response.length,
      recentCommentsToDisplay = '<%= jekyllConfig.disqus_recent_comments_to_display %>',
      authorName,
      threadTitle,
      threadLink;

    for ( ; i < numOfComments && i < recentCommentsToDisplay; i++ ) {

      authorName = data.response[ i ].author.name;
      threadTitle = data.response[ i ].thread.title;
      threadLink = data.response[ i ].url;

      aTag = document.createElement('a');
      aTag.setAttribute( 'href', threadLink );
      aTag.innerText = threadTitle;
      spanTag = document.createElement('span');
      spanTag.innerText = authorName + ' on ';
      spanTag.className = 'disqus-author';

      liTag = document.createElement('li');
      liTag.appendChild( spanTag );
      liTag.appendChild( aTag );
      ulTag.appendChild( liTag );
    }

    document.getElementById('recent-comments-section').appendChild( ulTag );
    document.getElementById('recent-comments-section').style.display = 'block';

    //////////

    function isThereComment() {
      return !!data.response.length;
    }
  };

  document.getElementsByTagName('HEAD')[ 0 ].appendChild( s );
}());


text:
from distutils.core import setup
setup(
  name = 'Raspberry_SDK',
  packages = ['Raspberry_SDK'],
  version = '0.1.4',
  description = 'Countly IoT Analytics SDK for Raspberry Pi devices',
  author = 'Countly',
  author_email = 'hello@count.ly',
  url = 'https://github.com/countly/countly-sdk-python',
  download_url = 'https://github.com/countly/countly-sdk-python/tarball/0.1.4',
  keywords = ['countly', 'iot', 'pyhon'],
  classifiers = [],
)


text:
.x-grid-cell-checkcolumn .x-grid-cell-inner {
    padding-top: 4px;
    padding-bottom: 2px;
    line-height: 14px;
}
.x-grid-with-row-lines .x-grid-cell-checkcolumn .x-grid-cell-inner {
    padding-top: 3px;
}
.x-grid-checkheader {
    height: 14px;
    background-image: url('images/unchecked.gif');
    background-position: 50% -2px;
    background-repeat: no-repeat;
    background-color: transparent;
}

.x-grid-checkheader-checked {
    background-image: url('images/checked.gif');
}

.x-grid-checkheader-editor .x-form-cb-wrap {
    text-align: center;
}


text:
from pandas import Index, NaT, Timedelta, TimedeltaIndex
import pandas._testing as tm

class TestFillNA:
    def test_fillna_timedelta(self):
        # GH#11343
        idx = TimedeltaIndex(["1 day", NaT, "3 day"])

        exp = TimedeltaIndex(["1 day", "2 day", "3 day"])
        tm.assert_index_equal(idx.fillna(Timedelta("2 day")), exp)

        exp = TimedeltaIndex(["1 day", "3 hour", "3 day"])
        idx.fillna(Timedelta("3 hour"))

        exp = Index([Timedelta("1 day"), "x", Timedelta("3 day")], dtype=object)
        tm.assert_index_equal(idx.fillna("x"), exp)


text:
namespace media {

// Parser for WebM Info element.
class MEDIA_EXPORT WebMInfoParser : public WebMParserClient {
 public:
  WebMInfoParser();

  WebMInfoParser(const WebMInfoParser&) = delete;
  WebMInfoParser& operator=(const WebMInfoParser&) = delete;

  ~WebMInfoParser() override;

  // Parses a WebM Info element in |buf|.
  //
  // Returns -1 if the parse fails.
  // Returns 0 if more data is needed.
  // Returns the number of bytes parsed on success.
  int Parse(const uint8_t* buf, int size);

  int64_t timecode_scale_ns() const { return timecode_scale_ns_; }
  double duration() const { return duration_; }
  base::Time date_utc() const { return date_utc_; }

 private:
  // WebMParserClient methods
  WebMParserClient* OnListStart(int id) override;
  bool OnListEnd(int id) override;
  bool OnUInt(int id, int64_t val) override;
  bool OnFloat(int id, double val) override;
  bool OnBinary(int id, const uint8_t* data, int size) override;
  bool OnString(int id, const std::string& str) override;

  int64_t timecode_scale_ns_;
  double duration_;
  base::Time date_utc_;
};

}  // namespace media

#endif  // MEDIA_FORMATS_WEBM_WEBM_INFO_PARSER_H_


text:
PHP OpenID Authentication Example

      This example consumer uses the PHP
      OpenID library. It just verifies that the URL that you enter
      is your identity URL.

	<?php if ($this->getError()) echo $this->getError()->getMessage(); ?>
	<?php if ($this->getError() && $this->getError()->getSuccess()) echo $this->getError()->getSuccess(); ?>

      <form method="get" action="<iz:insert:uri/>consumer/tryAuth/">
        Identity URL:
        <input type="hidden" name="action" value="verify" />
        <input type="text" name="openid_identifier" value="" />

Optionally, request these PAPE policies:

        <?php foreach ($this->getPapePolicyUri() as $i => $uri) {
          print "<input type=\"checkbox\" name=\"policies[]\" value=\"$uri\" />";
          print "$uri
";
        } ?>

        <input type="submit" value="Verify" />
      </form>


text:
package org.ideaexchange;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * This class launches the web application in an embedded Jetty container.
 * This is the entry point to your application. The Java command that is used for
 * launching should fire this main method.
 *
 */
public class Main {

	final static Logger logger = LoggerFactory.getLogger(Main.class);

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception{
        String webappDirLocation = "src/main/webapp/";

        // The port that we should run on can be set into an environment variable
        // Look for that variable and default to 8080 if it isn't there.
        String webPort = System.getenv("PORT");
        if (webPort == null || webPort.isEmpty()) {
            webPort = "8080";
        }

        logger.info("Starting up on port: " + webPort);

        Server server = new Server(Integer.valueOf(webPort));
        WebAppContext root = new WebAppContext();

        root.setContextPath("/");
        root.setDescriptor(webappDirLocation + "WEB-INF/web.xml");
        logger.info("web.xml assigned");
        root.setResourceBase(webappDirLocation);

        // Parent loader priority is a class loader setting that Jetty accepts.
        // By default Jetty will behave like most web containers in that it will
        // allow your application to replace non-server libraries that are part of the
        // container. Setting parent loader priority to true changes this behavior.
        // Read more here: http://wiki.eclipse.org/Jetty/Reference/Jetty_Classloading
        root.setParentLoaderPriority(true);

        server.setHandler(root);

        server.start();
        server.join();
    }
}