text:
/* global Ext, expect, jasmine, xit, spyOn */

describe('Ext.selection.CheckboxModel', function() {
    var grid, column, view, store, checkboxModel, data,
        donRec, evanRec, nigeRec,
        synchronousLoad = true,
        proxyStoreLoad = Ext.data.ProxyStore.prototype.load,
        loadStore = function() {
            proxyStoreLoad.apply(this, arguments);
            if (synchronousLoad) {
                this.flushLoad.apply(this, arguments);
            }
            return this;
        };

    function makeGrid(selectionCfg, cfg) {
        checkboxModel = new Ext.selection.CheckboxModel(selectionCfg);

        grid = new Ext.grid.Panel(Ext.apply({
            store: store,
            columns: [
                {text: "name", flex: 1, sortable: true, dataIndex: 'name'}
            ],
            columnLines: true,
            selModel: checkboxModel,
            width: 300,
            height: 300,
            renderTo: Ext.getBody()
        }, cfg));

        view = grid.view;
        column = checkboxModel.column;
    }

    beforeEach(function() {
        // Override so that we can control asynchronous loading
        Ext.data.ProxyStore.prototype.load = loadStore;

        Ext.define('spec.CheckboxModel', {
            extend: 'Ext.data.Model',
            fields: [{
                name: 'name'
            }]
        });

        store = Ext.create('Ext.data.Store', {
            model: 'spec.CheckboxModel',
            proxy: 'memory',
            data: data || [{
                id: 1,
                name: 'Don'
            }, {
                id: 2,
                name: 'Evan'
            }, {
                id: 3,
                name: 'Nige'
            }]
        });

        donRec = store.getById(1);
        evanRec = store.getById(2);
        nigeRec = store.getById(3);
    });

    afterEach(function() {
        // Undo the overrides.
        Ext.data.ProxyStore.prototype.load = proxyStoreLoad;

        donRec = evanRec = nigeRec = data = null;
        Ext.destroy(grid, checkboxModel, store);
        Ext.undefine('spec.CheckboxModel');
        Ext.data.Model.schema.clear();

        grid = column = view = store = checkboxModel = null;
    });

    function expectHeaderChecked(checked) {
        var col = checkboxModel.column;

        expect(col.hasCls(checkboxModel.checkerOnCls)).toBe(checked);

        if (col.useAriaElements) {
            expect(col).toHaveAttr('role', 'columnheader');

            if (col.headerCheckbox) {
                expect(col).toHaveAttr('aria-describedby', col.id + '-header-description' +
                                            (!checked ? '-not' : '') + '-selected');
            }
            else {
                expect(col).not.toHaveAttr('aria-describedby');
            }
        }
        else {
            expect(col).toHaveAttr('role', 'presentation');
            expect(col).not.toHaveAttr('aria-describedby');
        }
    }

    function clickOnHeaderCheckbox() {
        jasmine.fireMouseEvent(checkboxModel.column, 'click', 10, 10);
    }

    function clickCheckbox(rowIdx) {
        var cell = view.getCellByPosition({
            row: rowIdx,
            column: 0
        });
        jasmine.fireMouseEvent(cell.down(checkboxModel.checkSelector), 'click');
    }

    function clickCell(rowIdx, colIdx) {
        var cell = view.getCellByPosition({
            row: rowIdx,
            column: colIdx
        });
        jasmine.fireMouseEvent(cell, 'click');
    }

    function keyCheckbox(rowIdx, keyCode, shiftKey, ctrlKey, altKey) {
        var cell = grid.getView().getCellByPosition({
            row: rowIdx,
            column: 0
        });
        jasmine.fireKeyEvent(cell.down(checkboxModel.checkSelector), 'keydown', keyCode, shiftKey, ctrlKey, altKey);
    }

    describe("grid reconfigure", function() {
        it("should be able to change the columns without hiding the checkcolumn", function() {
            var store2 = new Ext.data.Store({
                fields: ['foo'],
                data: [{
                    foo: 'bar'
                }]
            });
            makeGrid();

            grid.reconfigure(store2, [{dataIndex: 'foo'}]);

            expect(grid.view.body.el.down('.x-grid-checkcolumn')).not.toBeNull();
        });
    });

    describe("column insertion", function() {
        var cols;

        afterEach(function() {
            cols = null;
        });

        it("should ignore any xtype defaults and insert a checkcolumn", function() {
            makeGrid(null, {
                columns: {
                    defaults: {
                        xtype: 'widgetcolumn',
                        widget: {
                            xtype: 'button'
                        }
                    },
                    items: [{
                        dataIndex: 'name'
                    }]
                }
            });
            var allCols = grid.getColumnManager().getColumns();
            expect(allCols[0].$className).toBe('Ext.grid.column.Check');
        });

        describe("without locking", function() {
            beforeEach(function() {
                cols = [{
                    dataIndex: 'name'
                }, {
                    dataIndex: 'name'
                }, {
                    dataIndex: 'name'
                }];
            });

            it("should insert the column at the start by default", function() {
                makeGrid(null, {
                    columns: cols
                });

                var allCols = grid.getColumnManager().getColumns(),
                    col = allCols[0];

                expect(col.isCheckColumn).toBe(true);
                expect(grid.query('checkcolumn').length).toBe(1);
                expect(allCols.length).toBe(4);
            });

            it("should insert the column at the start with injectCheckbox: 'first'", function() {
                makeGrid({
                    injectCheckbox: 'first'
                }, {
                    columns: cols
                });

                var allCols = grid.getColumnManager().getColumns(),
                    col = allCols[0];

                expect(col.isCheckColumn).toBe(true);
                expect(grid.query('checkcolumn').length).toBe(1);
                expect(allCols.length).toBe(4);
            });

            it("should insert the column at the end with injectCheckbox: 'last'", function() {
                makeGrid({
                    injectCheckbox: 'last'
                }, {
                    columns: cols
                });

                var allCols = grid.getColumnManager().getColumns(),
                    col = allCols[3];

                expect(col.isCheckColumn).toBe(true);
                expect(grid.query('checkcolumn').length).toBe(1);
                expect(allCols.length).toBe(4);
            });

            it("should insert the column at the specified index", function() {
                makeGrid({
                    injectCheckbox: 1
                }, {
                    columns: cols
                });

                var allCols = grid.getColumnManager().getColumns(),
                    col = allCols[1];

                expect(col.isCheckColumn).toBe(true);
                expect(grid.query('checkcolumn').length).toBe(1);
                expect(allCols.length).toBe(4);
            });
        });

        describe('Lockable, but starting with no locked columns', function() {
            beforeEach(function() {
                cols = [{
                    text: 'Name1',
                    dataIndex: 'name'
                }, {
                    text: 'Name2',
                    dataIndex: 'name'
                }, {
                    text: 'Name3',
                    dataIndex: 'name'
                }];
            });

            it('should migrate the check column to locked when the first column is locked', function() {
                makeGrid(null, {
                    enableLocking: true,
                    columns: cols
                });
                var checkColumn = grid.down('[isCheckerHd]'),
                    name1Column = grid.down('[text=Name1]');

                // There's a locked grid but it's not visible.
                expect(grid.lockedGrid.isVisible()).toBe(false);

                grid.lock(name1Column);

                // The locked grid should now be visible
                expect(grid.lockedGrid.isVisible()).toBe(true);

                // TWO columns should now be owned by the locked grid.
                // checkColumn must have migrated.
                expect(checkColumn.up('grid') === grid.lockedGrid).toBe(true);
                expect(name1Column.up('grid') === grid.lockedGrid).toBe(true);
            });
        });

        describe("with locking", function() {
            beforeEach(function() {
                cols = [{
                    text: 'Name 1',
                    dataIndex: 'name',
                    locked: true
                }, {
                    text: 'Name 2',
                    dataIndex: 'name',
                    locked: true
                }, {
                    text: 'Name 3',
                    dataIndex: 'name',
                    locked: true
                }, {
                    text: 'Name 4',
                    dataIndex: 'name'
                }, {
                    text: 'Name 5',
                    dataIndex: 'name'
                }, {
                    text: 'Name 6',
                    dataIndex: 'name'
                }];
            });

            it("should insert the column at the start by default", function() {
                makeGrid(null, {
                    columns: cols
                });

                var allCols = grid.getColumnManager().getColumns(),
                    col = allCols[0];

                expect(col.isCheckColumn).toBe(true);
                expect(grid.query('checkcolumn').length).toBe(1);
                expect(grid.normalGrid.query('checkcolumn').length).toBe(0);
                expect(allCols.length).toBe(7);
            });

            it("should unlock the column when all other columns are unlocked", function() {
                makeGrid(null, {
                    width: 800,
                    columns: cols
                });

                var allCols = grid.getColumnManager().getColumns(),
                    col = allCols[0];

                grid.unlock(allCols[1]);
                grid.unlock(allCols[2]);
                grid.unlock(allCols[3]);

                // Locked grid should have been hidden because unlocking the three lockeddata columns
                // should have caysed migration of the checkbox column
                expect(grid.lockedGrid.isVisible()).toBe(false);

                // Normal grid should contain hte checkbox column
                expect(grid.normalGrid.headerCt.contains(col)).toBe(true);
            });

            it("should insert the column at the start with injectCheckbox: 'first'", function() {
                makeGrid({
                    injectCheckbox: 'first'
                }, {
                    columns: cols
                });

                var allCols = grid.getColumnManager().getColumns(),
                    col = allCols[0];

                expect(col.isCheckColumn).toBe(true);
                expect(grid.query('checkcolumn').length).toBe(1);
                expect(grid.normalGrid.query('checkcolumn').length).toBe(0);
                expect(allCols.length).toBe(7);
            });

            it("should insert the column at the end with injectCheckbox: 'last'", function() {
                makeGrid({
                    injectCheckbox: 'last'
                }, {
                    columns: cols
                });

                var allCols = grid.getColumnManager().getColumns(),
                    col = allCols[3];

                expect(col.isCheckColumn).toBe(true);
                expect(grid.query('checkcolumn').length).toBe(1);
                expect(grid.normalGrid.query('checkcolumn').length).toBe(0);
                expect(allCols.length).toBe(7);
            });

            it("should insert the column at the specified index", function() {
                makeGrid({
                    injectCheckbox: 1
                }, {
                    columns: cols
                });

                var allCols = grid.getColumnManager().getColumns(),
                    col = allCols[1];

                expect(col.isCheckColumn).toBe(true);
                expect(grid.query('checkcolumn').length).toBe(1);
                expect(grid.normalGrid.query('checkcolumn').length).toBe(0);
                expect(allCols.length).toBe(7);
            });
        });
    });

    describe("multiple selection", function() {
        beforeEach(function() {
            makeGrid();
        });
        describe('by clicking', function() {
            it('should select unselected records on click, and deselect selected records on click', function() {
                grid.focus();

                // Wait for the asynchronous focus processing to occur for IE
                waitsFor(function() {
                    return view.cellFocused;
                });

                runs(function() {
                    clickCheckbox(0);
                    clickCheckbox(1);
                    clickCheckbox(2);
                });
                waitsFor(function() {
                    return checkboxModel.getSelection().length === 3;
                }, 'all three records to be selected');
                runs(function() {
                    clickCheckbox(1);
                });
                waitsFor(function() {
                    return checkboxModel.getSelection().length === 2;
                }, 'the first record to be deselected');
            });
        });
        describe('by key navigation', function() {
            it('should select unselected records on ctrl+SPACE, and deselect selected records on ctrl+SPACE', function() {
                grid.view.getNavigationModel().setPosition(0);
                expect(checkboxModel.getSelection().length).toBe(0);
                keyCheckbox(0, Ext.event.Event.SPACE);
                expect(checkboxModel.getSelection().length).toBe(1);
                keyCheckbox(0, Ext.event.Event.DOWN, false, true);
                expect(checkboxModel.getSelection().length).toBe(1);
                keyCheckbox(1, Ext.event.Event.DOWN, false, true);
                keyCheckbox(2, Ext.event.Event.SPACE);
                expect(checkboxModel.getSelection().length).toBe(2);
                keyCheckbox(2, Ext.event.Event.UP, false, true);
                keyCheckbox(1, Ext.event.Event.UP, false, true);
                keyCheckbox(0, Ext.event.Event.SPACE);
                expect(checkboxModel.getSelection().length).toBe(1);
            });
        });
    });

    describe("header state", function() {
        beforeEach(function() {
            makeGrid();
        });

        it("should be initially unchecked", function() {
            expectHeaderChecked(false);
        });

        it("should be unchecked if there are no records", function(){
            store.removeAll();
            expectHeaderChecked(false);
        });

        it("should check header when all rows are selected", function() {
            expectHeaderChecked(false);

            checkboxModel.select(donRec, true);
            expectHeaderChecked(false);

            checkboxModel.select(evanRec, true);
            expectHeaderChecked(false);

            checkboxModel.select(nigeRec, true);
            expectHeaderChecked(true);
        });

        it("should uncheck header when any row is deselected", function() {
            checkboxModel.selectAll();
            expectHeaderChecked(true);

            checkboxModel.selectAll();
            checkboxModel.deselect(donRec);
            expectHeaderChecked(false);

            checkboxModel.selectAll();
            checkboxModel.deselect(evanRec);
            expectHeaderChecked(false);

            checkboxModel.selectAll();
            checkboxModel.deselect(nigeRec);
            expectHeaderChecked(false);
        });

        describe("loading", function() {
            it("should keep the header checked when reloaded and all items were checked", function() {
                checkboxModel.selectAll();
                expectHeaderChecked(true);
                store.load();
                expectHeaderChecked(true);
            });

            it("should keep the header checked when reloaded and loading a subset of items", function() {
                checkboxModel.selectAll();
                expectHeaderChecked(true);

                store.getProxy().setData([{
                    id: 1,
                    name: 'Don'
                }]);
                store.load();
                expectHeaderChecked(true);
            });

            it("should be unchecked when the loaded items do not match", function() {
                checkboxModel.selectAll();
                expectHeaderChecked(true);

                store.getProxy().setData([{
                    id: 4,
                    name: 'Foo'
                }]);
                store.load();
                expectHeaderChecked(false);
            });
        });

        it("should uncheck header when an unchecked record is added", function() {
            checkboxModel.selectAll();
            expectHeaderChecked(true);

            store.add({name: 'Marcelo'});
            expectHeaderChecked(false);
        });

        it("should check header when last unchecked record is removed before rows are rendered", function() {
            checkboxModel.select(donRec, true);
            checkboxModel.select(evanRec, true);
            expectHeaderChecked(false);

            store.remove(nigeRec);
            expectHeaderChecked(true);
        });

        it("should check header when last unchecked record is removed after rows are rendered", function() {
            checkboxModel.select(donRec, true);
            checkboxModel.select(evanRec, true);
            expectHeaderChecked(false);

            store.remove(nigeRec);
            expectHeaderChecked(true);
        });

        describe("when filtered", function() {
            describe("adding records", function() {
                it("should remain checked when a record is added that does not match the filter", function() {
                    checkboxModel.select(donRec);
                    store.filter('name', 'Don');
                    expectHeaderChecked(true);

                    store.add({
                        name: 'Foo'
                    });
                    expectHeaderChecked(true);
                });

                it("should uncheck when adding a record that does match the filter", function() {
                    checkboxModel.select(donRec);
                    store.filter('name', 'Don');
                    expectHeaderChecked(true);

                    store.add({
                        name: 'Don'
                    });
                    expectHeaderChecked(false);
                });
            });

            describe("removing records", function() {
                it("should remain checked when removing an item that does not match the filter", function() {
                    checkboxModel.select(donRec, evanRec);
                    store.filter('name', 'Don');
                    expectHeaderChecked(true);

                    store.remove(evanRec);
                    expectHeaderChecked(true);
                });

                it("should remain checked when removing an item that does match the filter", function() {
                    checkboxModel.select([donRec, evanRec]);
                    store.getFilters().add({
                        filterFn: function(rec) {
                            return rec === donRec || rec === evanRec;
                        }
                    });
                    expectHeaderChecked(true);

                    store.remove(evanRec);
                    expectHeaderChecked(true);
                });

                it("should uncheck if the record being removed is the last matching the filter", function() {
                    checkboxModel.select(donRec);
                    store.filter('name', 'Don');
                    expectHeaderChecked(true);

                    store.remove(donRec);
                    expectHeaderChecked(false);
                });
            });

            describe("updating records", function() {
                it("should uncheck if an unselected record is changed to match the filter", function() {
                    checkboxModel.select(donRec);
                    store.filter('name', 'Don');
                    expectHeaderChecked(true);

                    evanRec.set('name', 'Don');
                    expectHeaderChecked(false);
                });

                it("should uncheck if the last selected item is changed to not match the filter", function() {
                    checkboxModel.select(donRec);
                    store.filter('name', 'Don');
                    expectHeaderChecked(true);

                    donRec.set('name', 'Evan');
                    expectHeaderChecked(false);
                });

                it("should check if an unselected record is changed to not match the filter", function() {
                    checkboxModel.select(donRec);
                    evanRec.set('name', 'Don');
                    store.filter('name', 'Don');
                    expectHeaderChecked(false);

                    evanRec.set('name', 'Evan');
                    expectHeaderChecked(true);
                });
            });
        });

    });

    describe("check all", function() {
        describe('mode="SINGLE"', function () {
            it('should not render the header checkbox by default', function () {
                makeGrid({
                    mode: 'SINGLE'
                });

                expect(checkboxModel.column.el.down(checkboxModel.checkSelector)).toBe(null);
            });

            it('should not render the header checkbox by config', function () {
                expect(function () {
                    makeGrid({
                        mode: 'SINGLE',
                        showHeaderCheckbox: true
                    });
                }).toThrow('The header checkbox is not supported for SINGLE mode selection models.');
            });
        });

        describe('mode="MULTI"', function () {
            it("should check all when no record is checked", function() {
                makeGrid();
                expectHeaderChecked(false);

                clickOnHeaderCheckbox();
                expectHeaderChecked(true);

                expect(checkboxModel.isSelected(donRec)).toBe(true);
                expect(checkboxModel.isSelected(evanRec)).toBe(true);
                expect(checkboxModel.isSelected(nigeRec)).toBe(true);
            });

            it("should check all when some records are checked", function() {
                makeGrid();
                expectHeaderChecked(false);

                checkboxModel.select(donRec, true);
                checkboxModel.select(nigeRec, true);

                clickOnHeaderCheckbox();
                expectHeaderChecked(true);

                expect(checkboxModel.isSelected(donRec)).toBe(true);
                expect(checkboxModel.isSelected(evanRec)).toBe(true);
                expect(checkboxModel.isSelected(nigeRec)).toBe(true);
            });

            it("should not do anything with showHeaderCheckbox: false", function() {
                makeGrid({
                    showHeaderCheckbox: false
                });

                clickOnHeaderCheckbox();
                expect(checkboxModel.getCount()).toBe(0);
            });

            describe("with filtering", function() {
                it("should only check items in the current view", function() {
                    makeGrid();
                    store.filter('name', 'Don');
                    clickOnHeaderCheckbox();
                    expectHeaderChecked(true);

                    store.getFilters().removeAll();

                    expectHeaderChecked(false);
                    expect(checkboxModel.isSelected(donRec)).toBe(true);
                    expect(checkboxModel.isSelected(evanRec)).toBe(false);
                    expect(checkboxModel.isSelected(nigeRec)).toBe(false);
                });
            });
        });
    });

    describe("uncheck all", function() {
        beforeEach(function() {
            makeGrid();
        });

        it("should uncheck all when all records are checked", function() {
            checkboxModel.select(donRec, true);
            checkboxModel.select(evanRec, true);
            checkboxModel.select(nigeRec, true);
            expectHeaderChecked(true);

            clickOnHeaderCheckbox();
            expectHeaderChecked(false);
            expect(checkboxModel.isSelected(donRec)).toBe(false);
            expect(checkboxModel.isSelected(evanRec)).toBe(false);
            expect(checkboxModel.isSelected(nigeRec)).toBe(false);
        });

        describe("with filtering", function() {
            it("should only uncheck items in the current view", function() {
                checkboxModel.selectAll();
                store.filter('name', 'Nige');
                clickOnHeaderCheckbox();

                expectHeaderChecked(false);
                expect(checkboxModel.isSelected(donRec)).toBe(true);
                expect(checkboxModel.isSelected(evanRec)).toBe(true);
                expect(checkboxModel.isSelected(nigeRec)).toBe(false);

                store.getFilters().removeAll();

                expectHeaderChecked(false);
                expect(checkboxModel.isSelected(donRec)).toBe(true);
                expect(checkboxModel.isSelected(evanRec)).toBe(true);
                expect(checkboxModel.isSelected(nigeRec)).toBe(false);
            });

        });

    });

    describe("checkOnly", function() {
        function byPos(row, col) {
            return grid.getView().getCellByPosition({
                row: row,
                column: col
            });
        }

        function makeCheckGrid(checkOnly, mode) {
            makeGrid({
                checkOnly: checkOnly,
                mode: mode
            });
        }

        describe("mode: multi", function() {
            describe("with checkOnly: true", function() {
                beforeEach(function() {
                    makeCheckGrid(true, 'MULTI');
                });

                it("should not select when clicking on the row", function() {
                    jasmine.fireMouseEvent(byPos(0, 1), 'click');
                    expect(checkboxModel.isSelected(donRec)).toBe(false);
                });

                it("should not select when calling selectByPosition on a cell other than the checkbox cell", function() {
                    checkboxModel.selectByPosition({
                        row: 0,
                        column: 1
                    });
                    expect(checkboxModel.isSelected(donRec)).toBe(false);
                });

                it("should not select when navigating with keys", function() {
                    jasmine.fireMouseEvent(byPos(0, 1), 'click');
                    jasmine.fireKeyEvent(byPos(0, 1), 'keydown', Ext.event.Event.LEFT);
                    expect(checkboxModel.isSelected(donRec)).toBe(false);
                    jasmine.fireKeyEvent(byPos(0, 0), 'keydown', Ext.event.Event.RIGHT);
                    expect(checkboxModel.isSelected(donRec)).toBe(false);
                });

                it("should select when clicking on the checkbox", function() {
                    var checker = byPos(0, 0).down(checkboxModel.checkSelector);
                    jasmine.fireMouseEvent(checker, 'click');
                    expect(checkboxModel.isSelected(donRec)).toBe(true);
                });

                it("should select when pressing space with the checker focused", function() {
                    jasmine.fireMouseEvent(byPos(0, 1), 'click');
                    jasmine.fireKeyEvent(byPos(0, 1), 'keydown', Ext.event.Event.LEFT);
                    expect(checkboxModel.isSelected(donRec)).toBe(false);
                    jasmine.fireKeyEvent(byPos(0, 0), 'keydown', Ext.event.Event.SPACE);
                    expect(checkboxModel.isSelected(donRec)).toBe(true);
                });
            });

            describe("with checkOnly: false", function() {
                beforeEach(function() {
                    makeCheckGrid(false, 'MULTI');
                });

                it("should select when clicking on the row", function() {
                    jasmine.fireMouseEvent(byPos(0, 1), 'click');
                    expect(checkboxModel.isSelected(donRec)).toBe(true);
                });

                it("should select when calling selectByPosition on a cell other than the checkbox cell", function() {
                    checkboxModel.selectByPosition({
                        row: 0,
                        column: 1
                    });
                    expect(checkboxModel.isSelected(donRec)).toBe(true);
                });

                it("should select when navigating with keys", function() {
                    jasmine.fireMouseEvent(byPos(0, 1), 'click');
                    jasmine.fireKeyEvent(byPos(0, 1), 'keydown', Ext.event.Event.DOWN);
                    expect(checkboxModel.isSelected(evanRec)).toBe(true);
                });

                it("should select when clicking on the checkbox", function() {
                    var checker = byPos(0, 0).down(checkboxModel.checkSelector);
                    jasmine.fireMouseEvent(checker, 'click');
                    expect(checkboxModel.isSelected(donRec)).toBe(true);
                });
            });
        });

        describe("mode: single", function() {
            describe("with checkOnly: true", function() {
                beforeEach(function() {
                    makeCheckGrid(true, 'SINGLE');
                });

                it("should not select when clicking on the row", function() {
                    jasmine.fireMouseEvent(byPos(0, 1), 'click');
                    expect(checkboxModel.isSelected(donRec)).toBe(false);
                });

                it("should not select when navigating with keys", function() {
                    jasmine.fireMouseEvent(byPos(0, 1), 'click');
                    jasmine.fireKeyEvent(byPos(0, 1), 'keydown', Ext.event.Event.LEFT);
                    expect(checkboxModel.isSelected(donRec)).toBe(false);
                    jasmine.fireKeyEvent(byPos(0, 0), 'keydown', Ext.event.Event.RIGHT);
                    expect(checkboxModel.isSelected(donRec)).toBe(false);
                });

                it("should select when clicking on the checkbox", function() {
                    var checker = byPos(0, 0).down(checkboxModel.checkSelector);
                    jasmine.fireMouseEvent(checker, 'click');
                    expect(checkboxModel.isSelected(donRec)).toBe(true);
                });

                it("should select when pressing space with the checker focused", function() {
                    jasmine.fireMouseEvent(byPos(0, 1), 'click');
                    jasmine.fireKeyEvent(byPos(0, 1), 'keydown', Ext.event.Event.LEFT);
                    expect(checkboxModel.isSelected(donRec)).toBe(false);
                    jasmine.fireKeyEvent(byPos(0, 0), 'keydown', Ext.event.Event.SPACE);
                    expect(checkboxModel.isSelected(donRec)).toBe(true);
                });
            });

            describe("with checkOnly: false", function() {
                beforeEach(function() {
                    makeCheckGrid(false, 'SINGLE');
                });

                it("should select when clicking on the row", function() {
                    jasmine.fireMouseEvent(byPos(0, 1), 'click');
                    expect(checkboxModel.isSelected(donRec)).toBe(true);
                });

                it("should select when navigating with keys", function() {
                    jasmine.fireMouseEvent(byPos(0, 1), 'click');
                    jasmine.fireKeyEvent(byPos(0, 1), 'keydown', Ext.event.Event.DOWN);
                    expect(checkboxModel.isSelected(evanRec)).toBe(true);
                });

                it("should select when clicking on the checkbox", function() {
                    var checker = byPos(0, 0).down(checkboxModel.checkSelector);
                    jasmine.fireMouseEvent(checker, 'click');
                    expect(checkboxModel.isSelected(donRec)).toBe(true);
                });
            });
        });
    });

    describe("event selection", function() {
        var changeSpy, selectSpy, deselectSpy;

        function makeSpies() {
            changeSpy = jasmine.createSpy();
            selectSpy = jasmine.createSpy();
            deselectSpy = jasmine.createSpy();

            checkboxModel.on('selectionchange', changeSpy);
            checkboxModel.on('select', selectSpy);
            checkboxModel.on('deselect', deselectSpy);
        }

        function expectChangeSpy(records) {
            var args = changeSpy.mostRecentCall.args;
            expect(changeSpy.callCount).toBe(1);
            expect(args[0]).toBe(checkboxModel);
            expect(args[1]).toEqual(records);
        }

        function expectSelectSpy(record) {
            var args = selectSpy.mostRecentCall.args;
            expect(selectSpy.callCount).toBe(1);
            expect(args[0]).toBe(checkboxModel);
            expect(args[1]).toBe(record);
        }

        function expectDeselectSpy(record) {
            var args = deselectSpy.mostRecentCall.args;
            expect(deselectSpy.callCount).toBe(1);
            expect(args[0]).toBe(checkboxModel);
            expect(args[1]).toBe(record);
        }

        afterEach(function() {
            changeSpy = selectSpy = deselectSpy = null;
        });

        describe("multi", function() {
            describe("with checkOnly: false", function() {
                beforeEach(function() {
                    makeGrid({
                        mode: 'MULTI',
                        checkOnly: false
                    });
                });

                describe("selection when clicking on the checkbox", function() {
                    describe("on a selected record", function() {
                        it("should deselect when there are no other selections", function() {
                            checkboxModel.select(donRec);
                            makeSpies();
                            clickCheckbox(0);
                            expect(checkboxModel.isSelected(donRec)).toBe(false);
                            expectChangeSpy([]);
                            expectDeselectSpy(donRec);
                            expect(selectSpy).not.toHaveBeenCalled();
                        });

                        it("should deselect and keep existing selections", function() {
                            checkboxModel.selectAll();
                            makeSpies();
                            clickCheckbox(0);
                            expect(checkboxModel.isSelected(donRec)).toBe(false);
                            expectChangeSpy([nigeRec, evanRec]);
                            expectDeselectSpy(donRec);
                            expect(selectSpy).not.toHaveBeenCalled();
                        });
                    });

                    describe("on an unselected record", function() {
                        it("should select the record when there are no other selections", function() {
                            makeSpies();
                            clickCheckbox(0);
                            expect(checkboxModel.isSelected(donRec)).toBe(true);
                            expectChangeSpy([donRec]);
                            expectSelectSpy(donRec);
                            expect(deselectSpy).not.toHaveBeenCalled();
                        });

                        it("should select and keep existing selections", function() {
                            checkboxModel.select([evanRec, nigeRec]);
                            makeSpies();
                            clickCheckbox(0);
                            expect(checkboxModel.isSelected(donRec)).toBe(true);
                            expectChangeSpy([evanRec, nigeRec, donRec]);
                            expectSelectSpy(donRec);
                            expect(deselectSpy).not.toHaveBeenCalled();
                        });
                    });
                });

                describe("with shiftKey", function() {
                    var philRec;

                    beforeEach(function() {
                        philRec = store.add({
                            id: 4,
                            name: 'Phil'
                        })[0];
                    });

                    it("should deselect everything past & including the clicked item", function() {
                        checkboxModel.selectAll();
                        var view = grid.getView();

                        clickCell(0, 1);
                        spyOn(view, 'processUIEvent').andCallFake(function(e) {
                            if (e.type === 'click') {
                                e.shiftKey = true;
                            }
                            Ext.grid.View.prototype.processUIEvent.apply(view, arguments);
                        });

                        clickCell(2, 1);
                        clickCell(1, 1);
                        expect(checkboxModel.isSelected(donRec)).toBe(true);
                        expect(checkboxModel.isSelected(evanRec)).toBe(true);
                        expect(checkboxModel.isSelected(nigeRec)).toBe(false);
                        expect(checkboxModel.isSelected(philRec)).toBe(false);
                    });
                });
            });

            describe("with checkOnly: true", function() {
                beforeEach(function() {
                    makeGrid({
                        mode: 'MULTI',
                        checkOnly: true
                    });
                });

                describe("selection when clicking on the checkbox", function() {
                    describe("on a selected record", function() {
                        it("should deselect when there are no other selections", function() {
                            checkboxModel.select(donRec);
                            makeSpies();
                            clickCheckbox(0);
                            expect(checkboxModel.isSelected(donRec)).toBe(false);
                            expectChangeSpy([]);
                            expectDeselectSpy(donRec);
                            expect(selectSpy).not.toHaveBeenCalled();
                        });

                        it("should deselect and keep existing selections", function() {
                            checkboxModel.selectAll();
                            makeSpies();
                            clickCheckbox(0);
                            expect(checkboxModel.isSelected(donRec)).toBe(false);
                            expectChangeSpy([nigeRec, evanRec]);
                            expectDeselectSpy(donRec);
                            expect(selectSpy).not.toHaveBeenCalled();
                        });
                    });

                    describe("on an unselected record", function() {
                        it("should select the record when there are no other selections", function() {
                            makeSpies();
                            clickCheckbox(0);
                            expect(checkboxModel.isSelected(donRec)).toBe(true);
                            expectChangeSpy([donRec]);
                            expectSelectSpy(donRec);
                            expect(deselectSpy).not.toHaveBeenCalled();
                        });

                        it("should select and keep existing selections", function() {
                            checkboxModel.select([evanRec, nigeRec]);
                            makeSpies();
                            clickCheckbox(0);
                            expect(checkboxModel.isSelected(donRec)).toBe(true);
                            expectChangeSpy([evanRec, nigeRec, donRec]);
                            expectSelectSpy(donRec);
                            expect(deselectSpy).not.toHaveBeenCalled();
                        });
                    });
                });

                describe("with shiftKey", function() {
                    var philRec;

                    beforeEach(function() {
                        philRec = store.add({
                            id: 4,
                            name: 'Phil'
                        })[0];
                    });

                    it("should deselect everything past & including the clicked item", function() {
                        checkboxModel.selectAll();
                        var view = grid.getView();

                        spyOn(view, 'processUIEvent').andCallFake(function(e) {
                            if (e.type === 'click') {
                                e.shiftKey = true;
                            }
                            Ext.grid.View.prototype.processUIEvent.apply(view, arguments);
                        });

                        clickCell(2, 0);
                        clickCell(1, 0);
                        expect(checkboxModel.isSelected(donRec)).toBe(true);
                        expect(checkboxModel.isSelected(evanRec)).toBe(true);
                        expect(checkboxModel.isSelected(nigeRec)).toBe(false);
                        expect(checkboxModel.isSelected(philRec)).toBe(false);
                    });

                    it("should NOT change selection if clicked not on checkbox", function() {
                        checkboxModel.selectAll();
                        var view = grid.getView();

                        clickCell(0, 1);
                        spyOn(view, 'processUIEvent').andCallFake(function(e) {
                            if (e.type === 'click') {
                                e.shiftKey = true;
                            }
                            Ext.grid.View.prototype.processUIEvent.apply(view, arguments);
                        });

                        clickCell(2, 1);
                        clickCell(1, 1);
                        expect(checkboxModel.isSelected(donRec)).toBe(true);
                        expect(checkboxModel.isSelected(evanRec)).toBe(true);
                        expect(checkboxModel.isSelected(nigeRec)).toBe(true);
                        expect(checkboxModel.isSelected(philRec)).toBe(true);
                    });
                });
            });
        });

        describe("single", function() {
            describe("with checkOnly: false", function() {
                beforeEach(function() {
                    makeGrid({
                        mode: 'SINGLE'
                    });
                });

                describe("on the checkbox", function() {
                    it("should select the record on click", function() {
                        clickCheckbox(0);
                        expect(checkboxModel.isSelected(donRec)).toBe(true);

                        // Actionable mode MUST NOT be set
                        expect(grid.actionableMode).toBeFalsy();
                    });

                    it("should deselect any selected records", function() {
                        clickCheckbox(0);
                        clickCheckbox(1);
                        expect(checkboxModel.isSelected(donRec)).toBe(false);
                        expect(checkboxModel.isSelected(evanRec)).toBe(true);

                        // Actionable mode MUST NOT be set
                        expect(grid.actionableMode).toBeFalsy();
                    });
                });

                describe("on the row", function() {
                    it("should select the record on click", function() {
                        clickCheckbox(0);
                        expect(checkboxModel.isSelected(donRec)).toBe(true);
                    });

                    it("should deselect any selected records", function() {
                        clickCheckbox(0);
                        clickCheckbox(1);
                        expect(checkboxModel.isSelected(donRec)).toBe(false);
                        expect(checkboxModel.isSelected(evanRec)).toBe(true);
                    });
                });
            });

            describe("with checkOnly: true", function() {
                beforeEach(function() {
                    makeGrid({
                        mode: 'SINGLE',
                        checkOnly: true
                    });
                });

                describe("on the checkbox", function() {
                    it("should select the record on click", function() {
                        clickCheckbox(0);
                        expect(checkboxModel.isSelected(donRec)).toBe(true);

                        // Actionable mode MUST NOT be set and the checkbox cell must be focused
                        expect(grid.actionableMode).toBeFalsy();

                        var cell = view.getCellByPosition({
                            row: 0,
                            column: 0
                        });

                        expectFocused(cell, true);
                    });

                    it("should deselect any selected records", function() {
                        clickCheckbox(0);
                        clickCheckbox(1);
                        expect(checkboxModel.isSelected(donRec)).toBe(false);
                        expect(checkboxModel.isSelected(evanRec)).toBe(true);

                        // Actionable mode MUST NOT be set and the checkbox cell must be focused
                        expect(grid.actionableMode).toBeFalsy();

                        var cell = view.getCellByPosition({
                            row: 1,
                            column: 0
                        });

                        expectFocused(cell, true);
                    });
                });

                describe("on the row", function() {
                    it("should select the record on click", function() {
                        clickCheckbox(0);
                        expect(checkboxModel.isSelected(donRec)).toBe(true);
                    });

                    it("should deselect any selected records", function() {
                        clickCheckbox(0);
                        clickCheckbox(1);
                        expect(checkboxModel.isSelected(donRec)).toBe(false);
                        expect(checkboxModel.isSelected(evanRec)).toBe(true);
                    });
                });
            });
        });
    });

    describe("ARIA", function() {
        describe("with checkOnly: false", function() {
            describe("with showHeaderCheckbox: false", function() {
                beforeEach(function() {
                    makeGrid({
                        checkOnly: false,
                        showHeaderCheckbox: false
                    });
                });

                describe("header", function() {
                    it("should not have tabIndex", function() {
                        expect(column).not.toHaveAttr('tabIndex');
                    });

                    it("should have presentation role", function() {
                        expect(column).toHaveAttr('role', 'presentation');
                    });

                    it("should not have aria-label", function() {
                        expect(column).not.toHaveAttr('aria-label');
                    });

                    it("should not have aria-labelledby", function() {
                        expect(column).not.toHaveAttr('aria-labelledby');
                    });

                    it("should not have aria-describedby", function() {
                        expect(column).not.toHaveAttr('aria-describedby');
                    });
                });

                describe("cells", function() {
                    var cell;

                    beforeEach(function() {
                        cell = view.getCellByPosition({
                            row: 0,
                            column: 0
                        });
                    });

                    afterEach(function() {
                        cell = null;
                    });

                    it("should not have tabIndex", function() {
                        expect(cell).not.toHaveAttr('tabIndex');
                    });

                    it("should have presentation role", function() {
                        expect(cell).toHaveAttr('role', 'presentation');
                    });

                    it("should not have aria-label", function() {
                        expect(cell).not.toHaveAttr('aria-label');
                    });

                    it("should not have aria-labelledby", function() {
                        expect(cell).not.toHaveAttr('aria-labelledby');
                    });

                    it("should not have aria-describedby", function() {
                        expect(cell).not.toHaveAttr('aria-describedby');
                    });
                });
            });

            describe("with showHeaderCheckbox: true", function() {
                beforeEach(function() {
                    makeGrid({
                        checkOnly: false,
                        showHeaderCheckbox: true
                    });
                });

                describe("header", function() {
                    it("should not have tabIndex", function() {
                        expect(column).not.toHaveAttr('tabIndex');
                    });

                    it("should have presentation role", function() {
                        expect(column).toHaveAttr('role', 'presentation');
                    });

                    it("should not have aria-label", function() {
                        expect(column).not.toHaveAttr('aria-label');
                    });

                    it("should not have aria-labelledby", function() {
                        expect(column).not.toHaveAttr('aria-labelledby');
                    });

                    it("should not have aria-describedby", function() {
                        expect(column).not.toHaveAttr('aria-describedby');
                    });
                });

                describe("cells", function() {
                    var cell;

                    beforeEach(function() {
                        cell = view.getCellByPosition({
                            row: 0,
                            column: 0
                        });
                    });

                    afterEach(function() {
                        cell = null;
                    });

                    it("should not have tabIndex", function() {
                        expect(cell).not.toHaveAttr('tabIndex');
                    });

                    it("should have presentation role", function() {
                        expect(cell).toHaveAttr('role', 'presentation');
                    });

                    it("should not have aria-label", function() {
                        expect(cell).not.toHaveAttr('aria-label');
                    });

                    it("should not have aria-labelledby", function() {
                        expect(cell).not.toHaveAttr('aria-labelledby');
                    });

                    it("should not have aria-describedby", function() {
                        expect(cell).not.toHaveAttr('aria-describedby');
                    });
                });
            });
        });

        describe("with checkOnly: true", function() {
            describe("with showHeaderCheckbox: false", function() {
                beforeEach(function() {
                    makeGrid({
                        checkOnly: true,
                        showHeaderCheckbox: false
                    });
                });

                describe("header", function() {
                    it("should have tabIndex", function() {
                        expect(column).toHaveAttr('tabIndex', -1);
                    });

                    it("should have columnheader role", function() {
                        expect(column).toHaveAttr('role', 'columnheader');
                    });

                    it("should have aria-label", function() {
                        expect(column).toHaveAttr('aria-label', checkboxModel.headerAriaLabel);
                    });

                    it("should not have aria-labelledby", function() {
                        expect(column).not.toHaveAttr('aria-labelledby');
                    });

                    it("should not have aria-describedby when not all rows are selected", function() {
                        expect(column).not.toHaveAttr('aria-describedby');
                    });

                    it("should not have aria-describedby when all rows are selected", function() {
                        checkboxModel.selectAll();
                        expect(column).not.toHaveAttr('aria-describedby');
                    });
                });

                describe("cells", function() {
                    var cell;

                    beforeEach(function() {
                        cell = view.getCellByPosition({
                            row: 0,
                            column: 0
                        });
                    });

                    afterEach(function() {
                        cell = null;
                    });

                    it("should have tabIndex", function() {
                        expect(cell).toHaveAttr('tabIndex', -1);
                    });

                    it("should have gridcell role", function() {
                        expect(cell).toHaveAttr('role', 'gridcell');
                    });

                    it("should not have aria-label", function() {
                        expect(cell).not.toHaveAttr('aria-label');
                    });

                    it("should not have aria-labelledby", function() {
                        expect(cell).not.toHaveAttr('aria-labelledby');
                    });

                    it("should have aria-describedby when not selected", function() {
                        expect(cell).toHaveAttr('aria-describedby', column.id + '-cell-description-not-selected');
                    });

                    it("should have aria-describedby when selected", function() {
                        checkboxModel.select(0);
                        expect(cell).toHaveAttr('aria-describedby', column.id + '-cell-description-selected');
                    });
                });
            });

            describe("with showHeaderCheckbox: true", function() {
                beforeEach(function() {
                    makeGrid({
                        checkOnly: true,
                        showHeaderCheckbox: true
                    });
                });

                describe("header", function() {
                    it("should have tabIndex", function() {
                        expect(column).toHaveAttr('tabIndex', -1);
                    });

                    it("should have columnheader role", function() {
                        expect(column).toHaveAttr('role', 'columnheader');
                    });

                    it("should have aria-label", function() {
                        expect(column).toHaveAttr('aria-label', checkboxModel.headerAriaLabel);
                    });

                    it("should not have aria-labelledby", function() {
                        expect(column).not.toHaveAttr('aria-labelledby');
                    });

                    it("should have aria-describedby when not all rows are selected", function() {
                        expect(column).toHaveAttr('aria-describedby', column.id + '-header-description-not-selected');
                    });

                    it("should have aria-describedby when all rows are selected", function() {
                        checkboxModel.selectAll();
                        expect(column).toHaveAttr('aria-describedby', column.id + '-header-description-selected');
                    });
                });

                describe("cells", function() {
                    var cell;

                    beforeEach(function() {
                        cell = view.getCellByPosition({
                            row: 0,
                            column: 0
                        });
                    });

                    afterEach(function() {
                        cell = null;
                    });

                    it("should have tabIndex", function() {
                        expect(cell).toHaveAttr('tabIndex', -1);
                    });

                    it("should have gridcell role", function() {
                        expect(cell).toHaveAttr('role', 'gridcell');
                    });

                    it("should not have aria-label", function() {
                        expect(cell).not.toHaveAttr('aria-label');
                    });

                    it("should not have aria-labelledby", function() {
                        expect(cell).not.toHaveAttr('aria-labelledby');
                    });

                    it("should have aria-describedby when not selected", function() {
                        expect(cell).toHaveAttr('aria-describedby', column.id + '-cell-description-not-selected');
                    });

                    it("should have aria-describedby when selected", function() {
                        checkboxModel.select(0);
                        expect(cell).toHaveAttr('aria-describedby', column.id + '-cell-description-selected');
                    });
                });
            });
        });
    });
});


text:
 Contact Us

 Twitter

 Facebook

        Privacy Policy ·
        Terms of Service · All trademarks © their respective owners

© 2008-
Balsamiq Studios, LLC · Federal EIN 26-2200095
        (W9 Form)

redpajama_set_name: RedPajamaGithub


text:
package river

import (
	"io/ioutil"

	"github.com/BurntSushi/toml"
	"github.com/juju/errors"
)

type SourceConfig struct {
	Schema string   `toml:"schema"`
	Tables []string `toml:"tables"`
}

type Config struct {
	MyAddr     string `toml:"my_addr"`
	MyUser     string `toml:"my_user"`
	MyPassword string `toml:"my_pass"`

	EsIndexs []string `toml:"es_indexs"`

	ESAddr string `toml:"es_addr"`

	StatAddr string `toml:"stat_addr"`

	ServerID uint32 `toml:"server_id"`
	Flavor   string `toml:"flavor"`
	DataDir  string `toml:"data_dir"`

	DumpExec string `toml:"mysqldump"`

	Sources []SourceConfig `toml:"source"`

	Rules []*Rule `toml:"rule"`
}

func NewConfigWithFile(name string) (*Config, error) {
	data, err := ioutil.ReadFile(name)
	if err != nil {
		return nil, errors.Trace(err)
	}

	return NewConfig(string(data))
}

func NewConfig(data string) (*Config, error) {
	var c Config

	_, err := toml.Decode(data, &c)
	if err != nil {
		return nil, errors.Trace(err)
	}

	return &c, nil
}


text:
crop.factory('cropHost', ['$document', 'cropAreaCircle', 'cropAreaSquare', 'cropAreaRectangle', function($document, CropAreaCircle, CropAreaSquare, CropAreaRectangle) {
  /* STATIC FUNCTIONS */

  // Get Element's Offset
  var getElementOffset=function(elem) {
    var box = elem.getBoundingClientRect();

    var body = document.body;
    var docElem = document.documentElement;

    var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop;
    var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft;

    var clientTop = docElem.clientTop || body.clientTop || 0;
    var clientLeft = docElem.clientLeft || body.clientLeft || 0;

    var top  = box.top +  scrollTop - clientTop;
    var left = box.left + scrollLeft - clientLeft;

    return { top: Math.round(top), left: Math.round(left) };
  };

  return function(elCanvas, opts, events){
    /* PRIVATE VARIABLES */

    // Object Pointers
    var ctx=null,
        image=null,
        theArea=null,
        self=this;

    // Dimensions
    var minCanvasDims=[100,100],
        maxCanvasDims=[300,300];

    // Result Image size
    var resImgSize={w: 200, h: 200};

    /* PRIVATE FUNCTIONS */

    // Draw Scene
    function drawScene() {
      // clear canvas
      ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

      if(image!==null) {
        // draw source image
        ctx.drawImage(image, 0, 0, ctx.canvas.width, ctx.canvas.height);

        ctx.save();

        // and make it darker
        ctx.fillStyle = 'rgba(0, 0, 0, 0.65)';
        ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);

        ctx.restore();

        // draw Area
        theArea.draw();
      }
    }

    // Resets CropHost
    var resetCropHost=function() {
      if(image!==null) {
        theArea.setImage(image);
        var imageDims=[image.width, image.height],
            imageRatio=image.width/image.height,
            canvasDims=imageDims;

        if(canvasDims[0]>maxCanvasDims[0]) {
          canvasDims[0]=maxCanvasDims[0];
          canvasDims[1]=canvasDims[0]/imageRatio;
        } else if(canvasDims[0]<minCanvasDims[0]) {
          canvasDims[0]=minCanvasDims[0];
          canvasDims[1]=canvasDims[0]/imageRatio;
        }
        if(canvasDims[1]>maxCanvasDims[1]) {
          canvasDims[1]=maxCanvasDims[1];
          canvasDims[0]=canvasDims[1]*imageRatio;
        } else if(canvasDims[1]<minCanvasDims[1]) {
          canvasDims[1]=minCanvasDims[1];
          canvasDims[0]=canvasDims[1]*imageRatio;
        }
        elCanvas.prop('width',canvasDims[0]).prop('height',canvasDims[1]).css({'margin-left': -canvasDims[0]/2+'px', 'margin-top': -canvasDims[1]/2+'px'});

        var cw = ctx.canvas.width;
        var ch = ctx.canvas.height;

        var areaType = self.getAreaType();
        // enforce 1:1 aspect ratio for square-like selections
        if ((areaType === 'circle') || (areaType === 'square')) {

        }

        theArea.setSize({ w: Math.min(200, cw / 2),
          h: Math.min(200, ch / 2)});
        //TODO: set top left corner point
        theArea.setCenterPoint({x: ctx.canvas.width/2, y: ctx.canvas.height/2});

      } else {
        elCanvas.prop('width',0).prop('height',0).css({'margin-top': 0});
      }

      drawScene();
    };

    var onMouseMove=function(e) {
      if(image!==null) {
        var offset=getElementOffset(ctx.canvas),
            pageX, pageY;
        if(e.type === 'touchmove') {
          pageX=e.changedTouches[0].pageX;
          pageY=e.changedTouches[0].pageY;
        } else {
          pageX=e.pageX;
          pageY=e.pageY;
        }
        theArea.processMouseMove(pageX-offset.left, pageY-offset.top);
        drawScene();
      }
    };

    var onMouseDown=function(e) {
      e.preventDefault();
      e.stopPropagation();
      if(image!==null) {
        var offset=getElementOffset(ctx.canvas),
            pageX, pageY;
        if(e.type === 'touchstart') {
          pageX=e.changedTouches[0].pageX;
          pageY=e.changedTouches[0].pageY;
        } else {
          pageX=e.pageX;
          pageY=e.pageY;
        }
        theArea.processMouseDown(pageX-offset.left, pageY-offset.top);
        drawScene();
      }
    };

    var onMouseUp=function(e) {
      if(image!==null) {
        var offset=getElementOffset(ctx.canvas),
            pageX, pageY;
        if(e.type === 'touchend') {
          pageX=e.changedTouches[0].pageX;
          pageY=e.changedTouches[0].pageY;
        } else {
          pageX=e.pageX;
          pageY=e.pageY;
        }
        theArea.processMouseUp(pageX-offset.left, pageY-offset.top);
        drawScene();
      }
    };

    this.getResultImage=function() {
      var temp_ctx, temp_canvas;
      temp_canvas = angular.element('<canvas></canvas>')[0];
      temp_ctx = temp_canvas.getContext('2d');
      var ris = this.getResultImageSize();
      temp_canvas.width = theArea.getSize().w;
      temp_canvas.height = theArea.getSize().h;
      var center = theArea.getCenterPoint();
      var retObj = {dataURI: null,
        imageData: null};
      if(image!==null){

        console.log(temp_canvas);
        console.log(ris);
        console.log(theArea.getSize());

        temp_ctx.drawImage(image,
            (center.x-theArea.getSize().w/2)*(image.width/ctx.canvas.width),
            (center.y-theArea.getSize().h/2)*(image.height/ctx.canvas.height),
            theArea.getSize().w*(image.width/ctx.canvas.width),
            theArea.getSize().h*(image.height/ctx.canvas.height),
            0,
            0,
            theArea.getSize().w,
            theArea.getSize().h);
        //temp_ctx.drawImage(image, 0, 0, theArea.getSize().w, theArea.getSize().h);
        retObj.dataURI = temp_canvas.toDataURL();
        retObj.imageData = temp_canvas.getContext("2d").getImageData(0, 0, theArea.getSize().w, theArea.getSize().h);
      }
      return retObj;
    };

    this.getAreaCoords=function() {
      return theArea.getSize()
    }

    this.setNewImageSource=function(imageSource) {
      image=null;
      resetCropHost();
      events.trigger('image-updated');
      if(!!imageSource) {
        var newImage = new Image();
        newImage.onload = function(){
          events.trigger('load-done');
          image=newImage;
          resetCropHost();
          events.trigger('image-updated');
        };
        newImage.onerror=function() {
          events.trigger('load-error');
        };
        events.trigger('load-start');
        newImage.src=imageSource;
      }
    };

    this.setMaxDimensions=function(width, height) {
      maxCanvasDims=[width,height];

      if(image!==null) {
        var curWidth=ctx.canvas.width,
            curHeight=ctx.canvas.height;

        var imageDims=[image.width, image.height],
            imageRatio=image.width/image.height,
            canvasDims=imageDims;

        if(canvasDims[0]>maxCanvasDims[0]) {
          canvasDims[0]=maxCanvasDims[0];
          canvasDims[1]=canvasDims[0]/imageRatio;
        } else if(canvasDims[0]<minCanvasDims[0]) {
          canvasDims[0]=minCanvasDims[0];
          canvasDims[1]=canvasDims[0]/imageRatio;
        }
        if(canvasDims[1]>maxCanvasDims[1]) {
          canvasDims[1]=maxCanvasDims[1];
          canvasDims[0]=canvasDims[1]*imageRatio;
        } else if(canvasDims[1]<minCanvasDims[1]) {
          canvasDims[1]=minCanvasDims[1];
          canvasDims[0]=canvasDims[1]*imageRatio;
        }
        elCanvas.prop('width',canvasDims[0]).prop('height',canvasDims[1]).css({'margin-left': -canvasDims[0]/2+'px', 'margin-top': -canvasDims[1]/2+'px'});

        var ratioNewCurWidth=ctx.canvas.width/curWidth,
            ratioNewCurHeight=ctx.canvas.height/curHeight,
            ratioMin=Math.min(ratioNewCurWidth, ratioNewCurHeight);

        //TODO: use top left corner point
        theArea.setSize({w: theArea.getSize().w * ratioMin,
          h: theArea.getSize().h * ratioMin});
        var center = theArea.getCenterPoint();
        theArea.setCenterPoint({x: center.x*ratioNewCurWidth, y: center.y*ratioNewCurHeight});

      } else {
        elCanvas.prop('width',0).prop('height',0).css({'margin-top': 0});
      }

      drawScene();

    };

    this.setAreaMinSize=function(size) {
      if (angular.isUndefined(size))
      {
        return;
      }
      size={w: parseInt(size.w,10),
        h: parseInt(size.h,10)};
      if(!isNaN(size.w) && !isNaN(size.h)) {
        theArea.setMinSize(size);
        drawScene();
      }
    };

    this.getResultImageSize=function() {
      if (resImgSize == "selection")
      {
        return theArea.getSize();
      }

      return resImgSize;
    };
    this.setResultImageSize=function(size) {
      if (angular.isUndefined(size))
      {
        return;
      }

      //allow setting of size to "selection" for mirroring selection's dimensions
      if (angular.isString(size))
      {
        resImgSize = size;
        return;
      }

      //allow scalar values for square-like selection shapes
      if (angular.isNumber(size))
      {
        size = parseInt(size, 10);
        size = {w: size,
          h: size};
      }

      size={w: parseInt(size.w, 10),
        h: parseInt(size.h, 10)};
      if(!isNaN(size.w) && !isNaN(size.h)) {
        resImgSize=size;
        drawScene();
      }
    };

    // returns a string of the selection area's type
    this.getAreaType=function() {
      return theArea.getType();
    }

    this.setAreaType=function(type) {
      var center = theArea.getCenterPoint();
      var curSize=theArea.getSize(),
          curMinSize=theArea.getMinSize(),
          curX= center.x,
          curY= center.y;

      var AreaClass=CropAreaCircle;
      if(type==='square') {
        AreaClass=CropAreaSquare;
      } else if (type==='rectangle')
      {
        AreaClass=CropAreaRectangle;
      }
      theArea = new AreaClass(ctx, events);
      theArea.setMinSize(curMinSize);
      theArea.setSize(curSize);

      //TODO: use top left point
      theArea.setCenterPoint({x: curX, y: curY});

      // resetCropHost();
      if(image!==null) {
        theArea.setImage(image);
      }

      drawScene();
    };

    /* Life Cycle begins */

    // Init Context var
    ctx = elCanvas[0].getContext('2d');

    // Init CropArea
    theArea = new CropAreaCircle(ctx, events);

    // Init Mouse Event Listeners
    $document.on('mousemove',onMouseMove);
    elCanvas.on('mousedown',onMouseDown);
    $document.on('mouseup',onMouseUp);

    // Init Touch Event Listeners
    $document.on('touchmove',onMouseMove);
    elCanvas.on('touchstart',onMouseDown);
    $document.on('touchend',onMouseUp);

    // CropHost Destructor
    this.destroy=function() {
      $document.off('mousemove',onMouseMove);
      elCanvas.off('mousedown',onMouseDown);
      $document.off('mouseup',onMouseMove);

      $document.off('touchmove',onMouseMove);
      elCanvas.off('touchstart',onMouseDown);
      $document.off('touchend',onMouseMove);

      elCanvas.remove();
    };
  };

}]);

'use strict';


text:
<?php
namespace TYPO3\Flow\I18n\EelHelper;

use TYPO3\Flow\Annotations as Flow;
use TYPO3\Flow\I18n\Exception\InvalidLocaleIdentifierException;
use TYPO3\Flow\I18n\Locale;
use TYPO3\Flow\I18n\Translator;
use TYPO3\Flow\Exception;
use TYPO3\Eel\ProtectedContextAwareInterface;

/**
 * Provides a chainable interface to collect all arguments needed to
 * translate messages using source message or key ID
 *
 * It also translates labels according to the configuration it stores
 */
class TranslationParameterToken implements ProtectedContextAwareInterface
{
    /**
     * @var Translator
     */
    protected $translator;

    /**
     * Key/Value store to keep the collected parameters
     *
     * @var array
     */
    protected $parameters = array();

    /**
     * @param string $id
     * @param string $value
     */
    public function __construct($id = null, $value = null)
    {
        if ($id !== null) {
            $this->parameters['id'] = $id;
        }

        if ($value !== null) {
            $this->parameters['value'] = $value;
        }
    }

    /**
     * Inject the translator into the token.
     * Used for testing.
     *
     * @param Translator $translator
     */
    public function injectTranslator(Translator $translator)
    {
        $this->translator = $translator;
    }

    /**
     * Set the id.
     *
     * @param string $id Id to use for finding translation (trans-unit id in XLIFF)
     * @return TranslationParameterToken
     */
    public function id($id)
    {
        $this->parameters['id'] = $id;
        return $this;
    }

    /**
     * Set the original translation value (the untranslated source string).
     *
     * @param string $value
     * @return TranslationParameterToken
     */
    public function value($value)
    {
        $this->parameters['value'] = $value;
        return $this;
    }

    /**
     * Set the arguments.
     *
     * @param array $arguments Numerically indexed array of values to be inserted into placeholders
     * @return TranslationParameterToken
     */
    public function arguments(array $arguments)
    {
        $this->parameters['arguments'] = $arguments;
        return $this;
    }

    /**
     * Set the source.
     *
     * @param string $source Name of file with translations
     * @return TranslationParameterToken
     */
    public function source($source)
    {
        $this->parameters['source'] = $source;
        return $this;
    }

    /**
     * Set the package.
     *
     * @param string $package Target package key. If not set, the current package key will be used
     * @return TranslationParameterToken
     */
    public function package($package)
    {
        $this->parameters['package'] = $package;
        return $this;
    }

    /**
     * Set the quantity.
     *
     * @param mixed $quantity A number to find plural form for (float or int), NULL to not use plural forms
     * @return TranslationParameterToken
     */
    public function quantity($quantity)
    {
        $this->parameters['quantity'] = $quantity;
        return $this;
    }

    /**
     * Set the locale. The locale Identifier will be converted into
     * a \TYPO3\Flow\I18n\Locale
     *
     * @param string $locale An identifier of locale to use (NULL for use the default locale)
     * @return TranslationParameterToken
     * @throws \TYPO3\Flow\Exception
     */
    public function locale($locale)
    {
        try {
            $this->parameters['locale'] = new Locale($locale);
        } catch (InvalidLocaleIdentifierException $e) {
            throw new Exception(sprintf('"%s" is not a valid locale identifier.', $locale), 1436784806);
        }

        return $this;
    }

    /**
     * Translate according to currently collected parameters
     *
     * @param array $overrides An associative array to override the collected parameters
     * @return string
     */
    public function translate(array $overrides = array())
    {
        array_replace_recursive($this->parameters, $overrides);

        $id = isset($this->parameters['id']) ? $this->parameters['id'] : null;
        $value = isset($this->parameters['value']) ? $this->parameters['value'] : null;
        $arguments = isset($this->parameters['arguments']) ? $this->parameters['arguments'] : array();
        $source = isset($this->parameters['source']) ? $this->parameters['source'] : 'Main';
        $package = isset($this->parameters['package']) ? $this->parameters['package'] : null;
        $quantity = isset($this->parameters['quantity']) ? $this->parameters['quantity'] : null;
        $locale = isset($this->parameters['locale']) ? $this->parameters['locale'] : null;

        if ($id === null) {
            return $this->translator->translateByOriginalLabel($value, $arguments, $quantity, $locale, $source, $package);
        }

        $translation = $this->translator->translateById($id, $arguments, $quantity, $locale, $source, $package);
        if ($translation === $id) {
            if ($value) {
                return $this->translator->translateByOriginalLabel($value, $arguments, $quantity, $locale, $source, $package);
            }
        }

        return $translation;
    }

    /**
     * Runs translate to avoid the need of calling translate as a finishing method
     */
    public function __toString()
    {
        return $this->translate();
    }

    /**
     * All methods are considered safe
     *
     * @param string $methodName
     * @return boolean
     */
    public function allowsCallOfMethod($methodName)
    {
        return true;
    }
}


text:
using Runtime.Services;

namespace Runtime.Deployments
{
    /// <summary>
    /// Represents an implementation of <see cref="IDeploymentOrchestrator"/>
    /// </summary>
    public class DeploymentOrchestrator : IDeploymentOrchestrator
    {
         IDeployers _deployers;
         IDeploymentStepOrchestrator _deploymentStepOrchestrator;

        /// <summary>
        /// Initializes an instance of <see cref="DeploymentOrchestrator"/>
        /// </summary>
        /// <param name="deployers">Deployers to work with</param>
        public DeploymentOrchestrator(IDeployers deployers, IDeploymentStepOrchestrator deploymentStepOrchestrator)
        {
            _deployers = deployers;
            _deploymentStepOrchestrator = deploymentStepOrchestrator;
        }

#pragma warning disable 1591 // Xml Comments
        public void Orchestrate(IServiceManifest serviceManifest)
        {
            var deployer = _deployers.GetByTypeName(serviceManifest.DeployerType);
            ThrowIfDeployerIsNull(serviceManifest.DeployerType, deployer);
            var steps = deployer.GetStepsFor(serviceManifest);
            _deploymentStepOrchestrator.Orchestrate(steps);
        }
#pragma warning restore 1591 // Xml Comments

        void ThrowIfDeployerIsNull(string deployerType, IDeployer deployer)
        {
            if( deployer == null ) throw new DeployerTypeDoesNotExist(deployerType);
        }

    }
}


text:
package com.oprisnik.semdroid.config;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.util.Collection;

/**
 * Abstract config interface.
 * It allows to retrieve various properties, subconfigurations, and components.
 */
public abstract class Config {

    public abstract void saveTo(OutputStream output) throws Exception;

    public abstract String getProperty(String key);

    public abstract boolean hasProperty(String key);

    public abstract boolean getBoolean(String key, boolean defaultValue);

    public abstract int getInt(String key, int defaultValue);

    public abstract Config getSubconfig(String key);

    public abstract void setProperty(String key, String value);

    public abstract InputStream getNestedInputStream(String key) throws BadConfigException;

    public abstract OutputStream getNestedOutputStream(String key) throws BadConfigException;

    /**
     * Get a collection of values.
     *

     * Example:
     *

     * <list>
     * <string>data 1</string>
     * <string>data 2</string>
     * </list>
     *

     * By calling getCollection("list.string"), you get a collection containing "data 1" and "data 2".
     *
     * @param key the key for the collection
     * @return the string collection
     */
    public abstract Collection<String> getCollection(String key);

    public abstract  U getComponent(Class baseInterface) throws BadConfigException;

    public abstract  U getComponent(String key, Class baseInterface) throws BadConfigException;

    public  U getComponent(String key, Class baseInterface, Class<? extends U> defaultImplementation)
            throws BadConfigException {
        if (hasComponent(key)) {
            return getComponent(key, baseInterface);
        }
        try {
            if (defaultImplementation == null) {
                return null;
            }
            return defaultImplementation.newInstance();
        } catch (Exception e) {
            throw new BadConfigException("Could not instantiate default implementation "
                    + defaultImplementation);
        }
    }

    public  U getComponentAndInit(Class baseInterface) throws BadConfigException {
        U instance = getComponent(baseInterface);
        instance.init(this);
        return instance;
    }

    public  U getComponentAndInit(String key, Class baseInterface)
            throws BadConfigException {
        Config conf = getSubconfig(key);
        if (conf == null) {
            throw new BadConfigException("Could not load component for key: " + key);
        }
        U instance = conf.getComponent(baseInterface);
        instance.init(conf);
        return instance;
    }

    public  U getComponentAndInit(String key, Class baseInterface, Class<? extends U> defaultImplementation)
            throws BadConfigException {
        Config conf = getSubconfig(key);
        U instance;
        if (conf == null) {
            try {
                if (defaultImplementation == null) {
                    return null;
                }
                instance = defaultImplementation.newInstance();
            } catch (Exception e) {
                throw new BadConfigException("Could not instantiate default implementation " + defaultImplementation);
            }
        } else {
            instance = conf.getComponent(baseInterface);
        }
        instance.init(conf);
        return instance;
    }

    public boolean hasComponent(String key) {
        Config conf = getSubconfig(key);
        return conf != null;
    }

    public String getProperty(String key, String defaultValue) {
        String val = getProperty(key);
        return (val == null) ? defaultValue : val;
    }

    public Object readObjectFromStream(String fileKey)
            throws BadConfigException, ClassNotFoundException, IOException {
        Object o = null;
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(getNestedInputStream(fileKey));
            o = ois.readObject();
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (Exception e) {
                }
            }
        }
        return o;
    }
}


text:
"""Helper to help store data."""
from __future__ import annotations

import asyncio
from contextlib import suppress
from json import JSONEncoder
import logging
import os
from typing import Any, Callable

from homeassistant.const import EVENT_HOMEASSISTANT_FINAL_WRITE
from homeassistant.core import CALLBACK_TYPE, CoreState, Event, HomeAssistant, callback
from homeassistant.helpers.event import async_call_later
from homeassistant.loader import bind_hass
from homeassistant.util import json as json_util

# mypy: allow-untyped-calls, allow-untyped-defs, no-warn-return-any
# mypy: no-check-untyped-defs

STORAGE_DIR = ".storage"
_LOGGER = logging.getLogger(__name__)

@bind_hass
async def async_migrator(
    hass,
    old_path,
    store,
    *,
    old_conf_load_func=None,
    old_conf_migrate_func=None,
):
    """Migrate old data to a store and then load data.

    async def old_conf_migrate_func(old_data)
    """
    store_data = await store.async_load()

    # If we already have store data we have already migrated in the past.
    if store_data is not None:
        return store_data

    def load_old_config():
        """Load old config."""
        if not os.path.isfile(old_path):
            return None

        if old_conf_load_func is not None:
            return old_conf_load_func(old_path)

        return json_util.load_json(old_path)

    config = await hass.async_add_executor_job(load_old_config)

    if config is None:
        return None

    if old_conf_migrate_func is not None:
        config = await old_conf_migrate_func(config)

    await store.async_save(config)
    await hass.async_add_executor_job(os.remove, old_path)
    return config

@bind_hass
class Store:
    """Class to help storing data."""

    def __init__(
        self,
        hass: HomeAssistant,
        version: int,
        key: str,
        private: bool = False,
        *,
        encoder: type[JSONEncoder] | None = None,
    ) -> None:
        """Initialize storage class."""
        self.version = version
        self.key = key
        self.hass = hass
        self._private = private
        self._data: dict[str, Any] | None = None
        self._unsub_delay_listener: CALLBACK_TYPE | None = None
        self._unsub_final_write_listener: CALLBACK_TYPE | None = None
        self._write_lock = asyncio.Lock()
        self._load_task: asyncio.Future | None = None
        self._encoder = encoder

    @property
    def path(self):
        """Return the config path."""
        return self.hass.config.path(STORAGE_DIR, self.key)

    async def async_load(self) -> dict | list | None:
        """Load data.

        If the expected version does not match the given version, the migrate
        function will be invoked with await migrate_func(version, config).

        Will ensure that when a call comes in while another one is in progress,
        the second call will wait and return the result of the first call.
        """
        if self._load_task is None:
            self._load_task = self.hass.async_create_task(self._async_load())

        return await self._load_task

    async def _async_load(self):
        """Load the data and ensure the task is removed."""
        try:
            return await self._async_load_data()
        finally:
            self._load_task = None

    async def _async_load_data(self):
        """Load the data."""
        # Check if we have a pending write
        if self._data is not None:
            data = self._data

            # If we didn't generate data yet, do it now.
            if "data_func" in data:
                data["data"] = data.pop("data_func")()
        else:
            data = await self.hass.async_add_executor_job(
                json_util.load_json, self.path
            )

            if data == {}:
                return None
        if data["version"] == self.version:
            stored = data["data"]
        else:
            _LOGGER.info(
                "Migrating %s storage from %s to %s",
                self.key,
                data["version"],
                self.version,
            )
            stored = await self._async_migrate_func(data["version"], data["data"])

        return stored

    async def async_save(self, data: dict | list) -> None:
        """Save data."""
        self._data = {"version": self.version, "key": self.key, "data": data}

        if self.hass.state == CoreState.stopping:
            self._async_ensure_final_write_listener()
            return

        await self._async_handle_write_data()

    @callback
    def async_delay_save(self, data_func: Callable[[], dict], delay: float = 0) -> None:
        """Save data with an optional delay."""
        self._data = {"version": self.version, "key": self.key, "data_func": data_func}

        self._async_cleanup_delay_listener()
        self._async_ensure_final_write_listener()

        if self.hass.state == CoreState.stopping:
            return

        self._unsub_delay_listener = async_call_later(
            self.hass, delay, self._async_callback_delayed_write
        )

    @callback
    def _async_ensure_final_write_listener(self) -> None:
        """Ensure that we write if we quit before delay has passed."""
        if self._unsub_final_write_listener is None:
            self._unsub_final_write_listener = self.hass.bus.async_listen_once(
                EVENT_HOMEASSISTANT_FINAL_WRITE, self._async_callback_final_write
            )

    @callback
    def _async_cleanup_final_write_listener(self) -> None:
        """Clean up a stop listener."""
        if self._unsub_final_write_listener is not None:
            self._unsub_final_write_listener()
            self._unsub_final_write_listener = None

    @callback
    def _async_cleanup_delay_listener(self) -> None:
        """Clean up a delay listener."""
        if self._unsub_delay_listener is not None:
            self._unsub_delay_listener()
            self._unsub_delay_listener = None

    async def _async_callback_delayed_write(self, _now):
        """Handle a delayed write callback."""
        # catch the case where a call is scheduled and then we stop Home Assistant
        if self.hass.state == CoreState.stopping:
            self._async_ensure_final_write_listener()
            return
        await self._async_handle_write_data()

    async def _async_callback_final_write(self, _event: Event) -> None:
        """Handle a write because Home Assistant is in final write state."""
        self._unsub_final_write_listener = None
        await self._async_handle_write_data()

    async def _async_handle_write_data(self, *_args):
        """Handle writing the config."""
        async with self._write_lock:
            self._async_cleanup_delay_listener()
            self._async_cleanup_final_write_listener()

            if self._data is None:
                # Another write already consumed the data
                return

            data = self._data

            if "data_func" in data:
                data["data"] = data.pop("data_func")()

            self._data = None

            try:
                await self.hass.async_add_executor_job(
                    self._write_data, self.path, data
                )
            except (json_util.SerializationError, json_util.WriteError) as err:
                _LOGGER.error("Error writing config for %s: %s", self.key, err)

    def _write_data(self, path: str, data: dict) -> None:
        """Write the data."""
        if not os.path.isdir(os.path.dirname(path)):
            os.makedirs(os.path.dirname(path))

        _LOGGER.debug("Writing data for %s to %s", self.key, path)
        json_util.save_json(path, data, self._private, encoder=self._encoder)

    async def _async_migrate_func(self, old_version, old_data):
        """Migrate to the new version."""
        raise NotImplementedError

    async def async_remove(self) -> None:
        """Remove all data."""
        self._async_cleanup_delay_listener()
        self._async_cleanup_final_write_listener()

        with suppress(FileNotFoundError):
            await self.hass.async_add_executor_job(os.unlink, self.path)


text:
package org.openqa.selenium.lift;

import junit.framework.TestCase;

import static org.openqa.selenium.lift.match.NumericalMatchers.exactly;
import static org.openqa.selenium.lift.match.SelectionMatcher.selection;

import org.hamcrest.Matcher;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.lift.find.Finder;

/**
 * Base class for tests using the LiFT style API to driver WebDriver.
 * @author rchatley (Robert Chatley)
 *
 */
public abstract class HamcrestWebDriverTestCase extends TestCase {

	private static final long DEFAULT_TIMEOUT = 5000;

        private WebDriver driver = createDriver();
        private TestContext context = new WebDriverTestContext(driver);

	protected abstract WebDriver createDriver();

	@Override
	protected void tearDown() throws Exception {
		context.quit();
		super.tearDown();
	}

        protected WebDriver getWebDriver() {
          return driver;
        }

        protected void clickOn(Finder<WebElement, WebDriver> finder) {
		context.clickOn(finder);
	}

	protected void assertPresenceOf(Finder<WebElement, WebDriver> finder) {
		context.assertPresenceOf(finder);
	}

	protected void assertPresenceOf(Matcher<Integer> cardinalityConstraint, Finder<WebElement, WebDriver> finder) {
		context.assertPresenceOf(cardinalityConstraint, finder);
	}

	protected void waitFor(Finder<WebElement, WebDriver> finder) {
		waitFor(finder, DEFAULT_TIMEOUT);
	}

	protected void waitFor(Finder<WebElement, WebDriver> finder, long timeout) {
		context.waitFor(finder, timeout);
	}

	/**
	 * Cause the browser to navigate to the given URL
	 * @param url
	 */
	protected void goTo(String url) {
		  context.goTo(url);
	}

	/**
	 * Type characters into an element of the page, typically an input field
	 * @param text - characters to type
	 * @param inputFinder - specification for the page element
	 */
	protected void type(String text, Finder<WebElement, WebDriver> inputFinder) {
		context.type(text, inputFinder);
	}

	/**
	 * Syntactic sugar to use with {@link HamcrestWebDriverTestCase#type(String, Finder<WebElement, WebDriver>)},
	 * e.g. type("cheese", into(textbox()));
	 * The into() method simply returns its argument.
	 */
	protected Finder<WebElement, WebDriver> into(Finder<WebElement, WebDriver> input) {
		return input;
	}

	/**
	 * replace the default {@link TestContext}
	 */
	void setContext(TestContext context) {
		this.context = context;
	}

      /**
       * Returns the current page source
       */
      public String getPageSource() {
        return getWebDriver().getPageSource();
      }

      /**
       * Returns the current page title
       */
      public String getTitle() {
        return getWebDriver().getTitle();
      }

      /**
       * Returns the current URL
       */
      public String getCurrentUrl() {
        return getWebDriver().getCurrentUrl();
      }

      protected void assertSelected(Finder<WebElement, WebDriver> finder) {
		assertPresenceOf(finder.with(selection()));
	}

	protected void assertNotSelected(Finder<WebElement, WebDriver> finder) {
		assertPresenceOf(exactly(0), finder.with(selection()));
	}

}


text:
using EarthFire.Facade.Models;
using RocketGPS.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EarthFire.Facade.Converters
{
  public class GeoLocationConverter
  {
    public GeoLocation FromGPSCoordinate(GPSCoordinate gpsCoordinate)
    {
      return new GeoLocation
      {
        Latitude = gpsCoordinate.latitude.toDouble(),
        Longitude = gpsCoordinate.longitude.toDouble()
      };
    }

    public IEnumerable<GeoLocation> FromGPSCoordinates(IEnumerable<GPSCoordinate> gpsCoordinates) => gpsCoordinates.Select(FromGPSCoordinate);
  }
}


text:
{% extends "base/base.html" %}
{% load static %}
{% block title %}Crawl {{ crawl.name }}{% endblock %}

{% block extrafooter %}

{% endblock %}

{% block content %}
{% if scripts %}
    {% for script in scripts %}
        {{ script | safe }}
    {% endfor %}
{% endif %}

{% include "base/sidebar.html" %}

{{ crawl.name }} ({{ crawl.crawler }})

      <button id="editButton" title="Edit Crawl" type="button" class="btn btn-control"
      data-container="body"
      data-toggle="tooltip" data-placement="bottom">

    </button>

Crawl Status: {{ crawl.status }}

      <button id="playButton" title="Start Crawl" type="button" class="btn btn-control"
        data-container="body"
        {% if crawl.status != "Not started" %}
            disabled
        {% endif %}
        data-toggle="tooltip" data-placement="bottom">

      </button>

      <button id="stopButton" title="Stop Crawl" type="button" class="btn btn-control"
        data-container="body"
        {% if crawl.status != "running" %}
        disabled
        {% endif %}
        data-toggle="tooltip" data-placement="bottom">

      </button>

      <button id="restartButton" title="Restart Crawl" type="button" class="btn btn-control"
        data-container="body"
        {% if crawl.status != "stopped" %}
          disabled
        {% endif %}
        data-toggle="tooltip" data-placement="bottom">

      </button>

        <form method="get">
            <input type="hidden" name="resource" value="initial_seeds">
            <button title="Get Seeds List" id="getInitialSeeds" class="btn btn-control"
            data-container="body" data-toggle="tooltip" data-placement="bottom"
            style="height:40px;width:auto;">
            Get Seeds List
            </button>
        </form>

        <form method="get">
            <input type="hidden" name="resource" value="crawl_log">
            <button title="Get Crawl Log" id="getCrawlLog" class="btn btn-control"
            {% if crawl.status == "Not started" %}
            disabled
            {% endif %}
            data-container="body" data-toggle="tooltip" data-placement="bottom"
            style="height:40px;width:auto;">
            Get Crawl Log
            </button>
        </form>

{% if crawl.crawler == "ache" %}

    {% if divs.0 or divs.1 %}

        {% for div in divs %}
        {% if div %}

            {{ div | safe }}

        {% endif %}
        {% endfor %}
    {% elif crawl.crawler == 'ache' %}

Waiting for plots...

    {% endif %}

    <form method="get">
    <input type="hidden" name="resource" value="seeds" />
      <button id="getSeeds" class="btn btn-default btn-padded center"
        data-container="body" data-toggle="tooltip" data-placement="bottom"
        {% if not divs.0 or not divs.1 %}
          disabled
        {% endif %}
        >
          Download Relevant Pages
        </button>
      </form>

{% endif %}
{% if crawl.crawler == "nutch" %}

        <button id="gotoSolr" type="button" title="Goto Solr" class="btn btn-default btn-duo center">
            View Results in Solr
        </button>
        <button id="dumpImages" type="button" title="Dump crawled images" class="btn btn-default btn-duo center">
            Dump Images
        </button>

{% endif %}
{% if crawl.description or crawl.crawler == "ache" %}

    {% if crawl.description %}

Description

{{ crawl.description }}

    {% endif %}
    {% if crawl.crawler == 'ache' %}

Crawl Model

 {{ crawl.crawl_model }}

    {% endif %}

{% endif %}

Summary Statistics

    {% if crawl.crawler == "ache" %}
        Pages Crawled
        Harvest Rate
    {% else %}
        Pages Crawled
    {% endif %}

    {% if crawl.crawler == "ache" %}
        {{ crawl.pages_crawled }}
        {{ crawl.harvest_rate }}
    {% else %}
        {{ crawl.pages_crawled }}
    {% endif %}

Seeds List Head

            {% for seed in seeds %}

{{ seed }}

            {% endfor %}

{% endblock content %}


text:
  out << WDT_LOG_PREFIX << WDT_TOSTR(A) << " " << WDT_OPT_VARIABLE(A) \
      << std::endl
#else
// google flag define or declare:
#define WDT_FLAG_DECLARATION(type, argument) DECLARE_##type(argument);
#define WDT_FLAG_DEFINITION(type, argument, value, description) \
  DEFINE_##type(argument, value, description);

#ifdef DECLARE_ONLY
// declare flags
#define WDT_OPT(A, type, description) \
  WDT_FLAG_DECLARATION(type, WDT_FLAG_SYM(A))
#else
// define flags
#define WDT_OPT(A, type, description) \
  WDT_FLAG_DEFINITION(type, WDT_FLAG_SYM(A), WDT_READ_OPT(A), description)
#endif
#endif
#endif


text:
CREATE TABLE additional_data (
  id IDENTITY NOT NULL,
  created datetime DEFAULT NULL,
  modified datetime DEFAULT NULL,
  label varchar(255) NOT NULL,
  value VARCHAR(16777215) NOT NULL,
  type int NOT NULL,
  data_id int NOT NULL,
  CONSTRAINT FK_additionaldata_data FOREIGN KEY (data_id) REFERENCES data(id)
);

CREATE INDEX FK_additionaldata_data_IX ON additional_data(data_id);