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

angular.module('n52.core.selection')
    .component('swcTrajectoryMapSelector', {
        bindings: {
            mapId: '@',
            serviceUrl: '<',
            filter: '<',
            mapLayers: '<',
            markerSelected: '&onMarkerSelected'
        },
        templateUrl: 'n52.core.selection.platform-map-selector',
        controller: ['seriesApiInterface', '$scope', 'leafletData',
            function(seriesApiInterface, $scope, leafletData) {

                var defaultStyle = {
                    color: 'red',
                    weight: 5,
                    opacity: 0.65
                };

                var hightlightStyle = {
                    color: 'blue',
                    weight: 7,
                    opacity: 1
                };

                this.markers = {};
                var layer;

                this.$onInit = () => {
                    setTimeout(() => {
                        leafletData.getMap(this.mapId).then((map) => {
                            map.invalidateSize();
                        });
                    }, 10);
                };

                this.$onChanges = () => {
                    this.loading = true;
                    leafletData.getMap(this.mapId).then((map) => {
                        // clear layer
                        if (layer) map.removeLayer(layer);
                        // add marker to layer
                        seriesApiInterface.getDatasets(null, this.serviceUrl, this.filter)
                            .then((dataset) => {
                                if (dataset instanceof Array) {
                                    var timespan = {
                                        start: dataset[0].firstValue.timestamp,
                                        end: dataset[0].lastValue.timestamp
                                    };

                                    seriesApiInterface.getDatasetData(dataset[0].id, this.serviceUrl, timespan)
                                        .then(data => {
                                            if (data.values instanceof Array) {
                                                layer = L.markerClusterGroup({
                                                    animate: false
                                                });
                                                data.values.forEach(entry => {
                                                    var geojson = L.geoJson(entry.geometry);
                                                    geojson.setStyle(defaultStyle);
                                                    geojson.addTo(map);
                                                    geojson.on('click', () => {
                                                        this.markerSelected({
                                                            dataset: dataset[0],
                                                            selectedGeometry: entry
                                                        });
                                                    });
                                                    geojson.on('mouseover', () => {
                                                        geojson.setStyle(hightlightStyle);
                                                        geojson.bringToFront();
                                                    });
                                                    geojson.on('mouseout', () => {
                                                        geojson.setStyle(defaultStyle);
                                                    });
                                                    layer.addLayer(geojson);
                                                });
                                                layer.addTo(map);
                                                map.fitBounds(layer.getBounds());
                                            }
                                            map.invalidateSize();
                                            this.loading = false;
                                        });
                                }
                            });
                    });
                };
            }
        ]
    });
<commit_msg>update tracjetory map selector<commit_after>require('../selection');

angular.module('n52.core.selection')
    .component('swcTrajectoryMapSelector', {
        bindings: {
            mapId: '@',
            serviceUrl: '<',
            filter: '<',
            mapLayers: '<',
            geometrySelected: '&onGeometrySelected'
        },
        templateUrl: 'n52.core.selection.platform-map-selector',
        controller: ['seriesApiInterface', '$scope', 'leafletData',
            function(seriesApiInterface, $scope, leafletData) {

                var defaultStyle = {
                    color: 'red',
                    weight: 5,
                    opacity: 0.65
                };

                var hightlightStyle = {
                    color: 'blue',
                    weight: 7,
                    opacity: 1
                };

                var layer;
                var init = false;

                var initMap = (callback) => {
                    if (!init) {
                        setTimeout(() => {
                            leafletData.getMap(this.mapId).then((map) => {
                                map.invalidateSize();
                                if (callback) callback();
                            });
                        }, 10);
                    } else {
                        if (callback) callback();
                    }
                };

                this.$onInit = () => {
                    initMap();
                };

                this.$onChanges = () => {
                    initMap(() => {
                        this.loading = true;
                        leafletData.getMap(this.mapId).then((map) => {
                            // clear layer
                            if (layer) map.removeLayer(layer);
                            // add geometries to layer
                            seriesApiInterface.getDatasets(null, this.serviceUrl, this.filter)
                                .then((dataset) => {
                                    if (dataset instanceof Array) {
                                        var timespan = {
                                            start: dataset[0].firstValue.timestamp,
                                            end: dataset[0].lastValue.timestamp
                                        };
                                        seriesApiInterface.getDatasetData(dataset[0].id, this.serviceUrl, timespan)
                                            .then(data => {
                                                if (data.values instanceof Array) {
                                                    layer = L.markerClusterGroup({
                                                        animate: false
                                                    });
                                                    data.values.forEach(entry => {
                                                        var geojson = L.geoJson(entry.geometry);
                                                        geojson.setStyle(defaultStyle);
                                                        geojson.addTo(map);
                                                        geojson.on('click', () => {
                                                            this.geometrySelected({
                                                                dataset: dataset[0],
                                                                selectedGeometry: entry
                                                            });
                                                        });
                                                        geojson.on('mouseover', () => {
                                                            geojson.setStyle(hightlightStyle);
                                                            geojson.bringToFront();
                                                        });
                                                        geojson.on('mouseout', () => {
                                                            geojson.setStyle(defaultStyle);
                                                        });
                                                        layer.addLayer(geojson);
                                                    });
                                                    layer.addTo(map);
                                                    map.fitBounds(layer.getBounds());
                                                }
                                                this.loading = false;
                                            });
                                    }
                                });
                        });
                    });
                };
            }
        ]
    });
<|endoftext|>


<commit_before>'use strict';

angular.module("mopify.account.services", [
    'LocalStorageModule',
    'mopify.widgets.directive.service',
])

.config(function($routeProvider) {
    $routeProvider.when("/account/services", {
        templateUrl: "account/services/services.tmpl.html",
        controller: "AccountServicesController"
    });
})

.controller("AccountServicesController", function AccountServicesController($rootScope, $scope, localStorageService){

    // bind connectedServices with the $scope
    localStorageService.bind($scope, 'connectedServices');

    // Define the default connectedServices object and extend it with the connectedServices object from storage
    $scope.availableServices = [
        {
            name: "Spotify",
            description: "Search and manage playlists and get the latests charts",
            image: "http://icons.iconarchive.com/icons/danleech/simple/256/spotify-icon.png",
            connected: ($scope.connectedServices !== null) ? $scope.connectedServices.spotify : false
        },
        {
            name: "Facebook",
            description: "Get more music based on your Facebook likes.",
            image: "http://www.ednfoundation.org/wp-content/uploads/facebook-logo-square.png",
            connected: ($scope.connectedServices !== null) ? $scope.connectedServices.facebook : false
        }
    ];

    if($scope.connectedServices === null){
        $scope.connectedServices = {};

        for(var x = 0; x < $scope.availableServices.length; x++){
            var service = $scope.availableServices[x];
            $scope.connectedServices[service.name.replace(" ", "").toLowerCase()] = false;
        }
    }
});<commit_msg>Disabled facebook as a service<commit_after>'use strict';

angular.module("mopify.account.services", [
    'LocalStorageModule',
    'mopify.widgets.directive.service',
])

.config(function($routeProvider) {
    $routeProvider.when("/account/services", {
        templateUrl: "account/services/services.tmpl.html",
        controller: "AccountServicesController"
    });
})

.controller("AccountServicesController", function AccountServicesController($rootScope, $scope, localStorageService){

    // bind connectedServices with the $scope
    localStorageService.bind($scope, 'connectedServices');

    // Define the default connectedServices object and extend it with the connectedServices object from storage
    $scope.availableServices = [
        {
            name: "Spotify",
            description: "Search and manage playlists and get the latests charts",
            image: "http://icons.iconarchive.com/icons/danleech/simple/256/spotify-icon.png",
            connected: ($scope.connectedServices !== null) ? $scope.connectedServices.spotify : false
        },
        /*{
            name: "Facebook",
            description: "Get more music based on your Facebook likes.",
            image: "http://www.ednfoundation.org/wp-content/uploads/facebook-logo-square.png",
            connected: ($scope.connectedServices !== null) ? $scope.connectedServices.facebook : false
        }*/
    ];

    if($scope.connectedServices === null){
        $scope.connectedServices = {};

        for(var x = 0; x < $scope.availableServices.length; x++){
            var service = $scope.availableServices[x];
            $scope.connectedServices[service.name.replace(" ", "").toLowerCase()] = false;
        }
    }
});<|endoftext|>


<commit_before>import { SanityActions } from '../../../../app/js/store/sanity'

describe('Sanity Store: Sync Actions', () => {
  describe('coreIsNotRunning', () => {
    it('should return an action of type CORE_IS_NOT_RUNNING', () => {
      const expectedResult = {
        type: 'CORE_IS_NOT_RUNNING'
      }
      const actualResult = SanityActions.coreIsNotRunning()
      assert.deepEqual(actualResult, expectedResult)
    })
  })

  describe('coreIsRunning', () => {
    it('should return an action of type CORE_IS_RUNNING', () => {
      const expectedResult = {
        type: 'CORE_IS_RUNNING'
      }
      const actualResult = SanityActions.coreIsRunning()
      assert.deepEqual(actualResult, expectedResult)
    })
  })
})
<commit_msg>add verify core api password sync actions tests #417<commit_after>import { SanityActions } from '../../../../app/js/store/sanity'

describe('Sanity Store: Sync Actions', () => {
  describe('coreApiPasswordIsNotValid', () => {
    it('should return an action of type CORE_API_PASSWORD_NOT_VALID', () => {
      const expectedResult = {
        type: 'CORE_API_PASSWORD_NOT_VALID'
      }
      const actualResult = SanityActions.coreApiPasswordIsNotValid()
      assert.deepEqual(actualResult, expectedResult)
    })
  })

  describe('coreApiPasswordIsValid', () => {
    it('should return an action of type CORE_API_PASSWORD_VALID', () => {
      const expectedResult = {
        type: 'CORE_API_PASSWORD_VALID'
      }
      const actualResult = SanityActions.coreApiPasswordIsValid()
      assert.deepEqual(actualResult, expectedResult)
    })
  })

  describe('coreIsNotRunning', () => {
    it('should return an action of type CORE_IS_NOT_RUNNING', () => {
      const expectedResult = {
        type: 'CORE_IS_NOT_RUNNING'
      }
      const actualResult = SanityActions.coreIsNotRunning()
      assert.deepEqual(actualResult, expectedResult)
    })
  })

  describe('coreIsRunning', () => {
    it('should return an action of type CORE_IS_RUNNING', () => {
      const expectedResult = {
        type: 'CORE_IS_RUNNING'
      }
      const actualResult = SanityActions.coreIsRunning()
      assert.deepEqual(actualResult, expectedResult)
    })
  })
})
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, you can obtain one at http://mozilla.org/MPL/2.0/. */

'use strict';

/* jasmine specs for controllers go here */

describe('JobsCtrl', function(){
    var $httpBackend, controller, jobsScope;

    beforeEach(module('treeherder.app'));

    beforeEach(inject(function ($injector, $rootScope, $controller) {
        var projectPrefix = '/api/project/mozilla-central/';

        $httpBackend = $injector.get('$httpBackend');
        jasmine.getJSONFixtures().fixturesPath='base/test/mock';

        $httpBackend.whenGET('/api/repository/').respond(
            getJSONFixture('repositories.json')
        );

        $httpBackend.whenGET(projectPrefix + 'resultset/?count=10&format=json&full=true&with_jobs=false').respond(
            getJSONFixture('resultset_list.json')
        );

        $httpBackend.whenGET(projectPrefix + 'jobs/?count=2000&result_set_id=1&return_type=list').respond(
            getJSONFixture('job_list/job_1.json')
        );

        $httpBackend.whenGET(projectPrefix + 'jobs/?count=2000&result_set_id=2&return_type=list').respond(
            getJSONFixture('job_list/job_2.json')
        );

        $httpBackend.whenGET('https://treestatus.mozilla.org/mozilla-central?format=json').respond(
            {
                "status": "closed",
                "message_of_the_day": "See the Inbound tree rules before pushing. Sheriff notes/current issues.",
                "tree": "mozilla-central",
                "reason": "Bustage"
            }
        );

        $httpBackend.whenGET('/api/project/mozilla-central/jobs/0/unclassified_failure_count/').respond(
            {
                "unclassified_failure_count": 1152,
                "repository": "mozilla-central"
            }
        );

        $httpBackend.whenGET('/api/jobtype/').respond(
            getJSONFixture('job_type_list.json')
        );

        $httpBackend.whenGET('/api/jobgroup/').respond(
            getJSONFixture('job_group_list.json')
        );

        jobsScope = $rootScope.$new();
        jobsScope.setRepoPanelShowing = function(tf) {
                // no op in the tests.
        };
        $controller('JobsCtrl', {'$scope': jobsScope});
    }));

    /*
        Tests JobsCtrl
     */
    it('should have 2 resultsets', function() {
        $httpBackend.flush();
        expect(jobsScope.result_sets).toBeDefined();
        expect(jobsScope.result_sets.length).toBe(2);
    });

    it('should have a job_map', function(){
        $httpBackend.flush();
        expect(jobsScope.job_map).toBeDefined();
    });

    it('should know when it\'s loading the initial data', function() {
        expect(jobsScope.isLoadingRsBatch).toEqual(
            {appending: true, prepending: false }
        );
        $httpBackend.flush();
        expect(jobsScope.isLoadingRsBatch).toEqual(
            {appending: false, prepending: false }
        );
    });

    it('should have 2 platforms in resultset 1', function() {
        $httpBackend.flush()
        expect(jobsScope.result_sets[0].platforms.length).toBe(2);
    });

    /*
        Tests ResultSetCtrl
     */
    describe('ResultSetCtrl', function(){
        var resultSetScopeList;

        beforeEach(inject(function ($rootScope, $controller) {
            /*
            * ResultSetCtrl is created insided a ng-repeat
            * so we should have a list of resultSetscope
            */
            $httpBackend.flush();
            resultSetScopeList = [];
            for(var i=0; i<jobsScope.result_sets.length; i++){
                var resultSetScope = jobsScope.$new();
                resultSetScope.resultset = jobsScope.result_sets[i];
                $controller('ResultSetCtrl', {'$scope': resultSetScope});
                resultSetScopeList.push(resultSetScope);
            }
        }));

        it('should set the selectedJob in scope when calling viewJob()', function() {
            var job = resultSetScopeList[0].resultset.platforms[0].groups[0].jobs[0];
            var resultSetScope = resultSetScopeList[0];
            resultSetScope.viewJob(job);
            expect(resultSetScope.selectedJob).toBe(job);
        });
    });

});
<commit_msg>Bug 1153361 - Tests should not depend on a certain default repo value<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, you can obtain one at http://mozilla.org/MPL/2.0/. */

'use strict';

/* jasmine specs for controllers go here */

describe('JobsCtrl', function(){
    var $httpBackend, controller, jobsScope;

    beforeEach(module('treeherder.app'));

    beforeEach(inject(function ($injector, $rootScope, $controller) {
        var activeRepo = 'mozilla-central';
        var projectPrefix = '/api/project/' + activeRepo + '/';

        $httpBackend = $injector.get('$httpBackend');
        jasmine.getJSONFixtures().fixturesPath='base/test/mock';

        $httpBackend.whenGET('/api/repository/').respond(
            getJSONFixture('repositories.json')
        );

        $httpBackend.whenGET(projectPrefix + 'resultset/?count=10&format=json&full=true&with_jobs=false').respond(
            getJSONFixture('resultset_list.json')
        );

        $httpBackend.whenGET(projectPrefix + 'jobs/?count=2000&result_set_id=1&return_type=list').respond(
            getJSONFixture('job_list/job_1.json')
        );

        $httpBackend.whenGET(projectPrefix + 'jobs/?count=2000&result_set_id=2&return_type=list').respond(
            getJSONFixture('job_list/job_2.json')
        );

        $httpBackend.whenGET('https://treestatus.mozilla.org/mozilla-central?format=json').respond(
            {
                "status": "closed",
                "message_of_the_day": "See the Inbound tree rules before pushing. Sheriff notes/current issues.",
                "tree": "mozilla-central",
                "reason": "Bustage"
            }
        );

        $httpBackend.whenGET('/api/project/mozilla-central/jobs/0/unclassified_failure_count/').respond(
            {
                "unclassified_failure_count": 1152,
                "repository": "mozilla-central"
            }
        );

        $httpBackend.whenGET('/api/jobtype/').respond(
            getJSONFixture('job_type_list.json')
        );

        $httpBackend.whenGET('/api/jobgroup/').respond(
            getJSONFixture('job_group_list.json')
        );

        jobsScope = $rootScope.$new();
        jobsScope.repoName = activeRepo;
        jobsScope.setRepoPanelShowing = function(tf) {
                // no op in the tests.
        };
        $controller('JobsCtrl', {'$scope': jobsScope});
    }));

    /*
        Tests JobsCtrl
     */
    it('should have 2 resultsets', function() {
        $httpBackend.flush();
        expect(jobsScope.result_sets).toBeDefined();
        expect(jobsScope.result_sets.length).toBe(2);
    });

    it('should have a job_map', function(){
        $httpBackend.flush();
        expect(jobsScope.job_map).toBeDefined();
    });

    it('should know when it\'s loading the initial data', function() {
        expect(jobsScope.isLoadingRsBatch).toEqual(
            {appending: true, prepending: false }
        );
        $httpBackend.flush();
        expect(jobsScope.isLoadingRsBatch).toEqual(
            {appending: false, prepending: false }
        );
    });

    it('should have 2 platforms in resultset 1', function() {
        $httpBackend.flush()
        expect(jobsScope.result_sets[0].platforms.length).toBe(2);
    });

    /*
        Tests ResultSetCtrl
     */
    describe('ResultSetCtrl', function(){
        var resultSetScopeList;

        beforeEach(inject(function ($rootScope, $controller) {
            /*
            * ResultSetCtrl is created insided a ng-repeat
            * so we should have a list of resultSetscope
            */
            $httpBackend.flush();
            resultSetScopeList = [];
            for(var i=0; i<jobsScope.result_sets.length; i++){
                var resultSetScope = jobsScope.$new();
                resultSetScope.resultset = jobsScope.result_sets[i];
                $controller('ResultSetCtrl', {'$scope': resultSetScope});
                resultSetScopeList.push(resultSetScope);
            }
        }));

        it('should set the selectedJob in scope when calling viewJob()', function() {
            var job = resultSetScopeList[0].resultset.platforms[0].groups[0].jobs[0];
            var resultSetScope = resultSetScopeList[0];
            resultSetScope.viewJob(job);
            expect(resultSetScope.selectedJob).toBe(job);
        });
    });

});
<|endoftext|>


<commit_before>import Ember from 'ember';
import { test, moduleFor, moduleForComponent } from 'ember-qunit';
import SlButton from 'sl-ember-components/components/sl-button';
import AjaxHelper from '../../helpers/ajax-helper';

moduleForComponent( 'sl-button', 'Component: Sl-Button' );

test( 'Label changes during associated AJAX activity', function() {
    var component = this.subject({
        ajaxEnabled: true,
        label: 'Static Text',
        activeLabelText: 'Active Text'
    });

    AjaxHelper.begin();
    equal( component.get( 'label' ), 'Active Text' );

    AjaxHelper.end();
    equal( component.get( 'label' ), 'Static Text' );
});

test( 'The element hides during associated AJAX activity', function() {
    var component = this.subject({
        ajaxEnabled: true,
        hideOnAjax: true
    });

    equal( this.$().css( 'visibility' ), 'visible' );

    AjaxHelper.begin();
    equal( this.$().css( 'visibility' ), 'hidden' );

    AjaxHelper.end();
    equal( this.$().css( 'visibility' ), 'visible' );
});

test( 'The element fires event when clicked', function() {
    expect( 1 );

    var component = this.subject();
    var $component = this.append();

    var targetObject = {
        externalAction: function() {
            ok( true, 'External action was called' );
        }
    };

    component.set( 'action', 'externalAction' );
    component.set( 'targetObject', targetObject );

    $component.click();
});

test( 'The element disables during associated AJAX activity', function() {
    var component = this.subject({
        ajaxEnabled: true,
        disableOnAjax: true
    });

    equal( this.$().is( ':disabled' ), false );

    AjaxHelper.begin();
    equal( this.$().is( ':disabled' ), true );

    AjaxHelper.end();
    equal( this.$().is( ':disabled' ), false );
});
<commit_msg>Rename test module<commit_after>import Ember from 'ember';
import { test, moduleFor, moduleForComponent } from 'ember-qunit';
import SlButton from 'sl-ember-components/components/sl-button';
import AjaxHelper from '../../helpers/ajax-helper';

moduleForComponent( 'sl-button', 'Unit - component:sl-button' );

test( 'Label changes during associated AJAX activity', function() {
    var component = this.subject({
        ajaxEnabled: true,
        label: 'Static Text',
        activeLabelText: 'Active Text'
    });

    AjaxHelper.begin();
    equal( component.get( 'label' ), 'Active Text' );

    AjaxHelper.end();
    equal( component.get( 'label' ), 'Static Text' );
});

test( 'The element hides during associated AJAX activity', function() {
    var component = this.subject({
        ajaxEnabled: true,
        hideOnAjax: true
    });

    equal( this.$().css( 'visibility' ), 'visible' );

    AjaxHelper.begin();
    equal( this.$().css( 'visibility' ), 'hidden' );

    AjaxHelper.end();
    equal( this.$().css( 'visibility' ), 'visible' );
});

test( 'The element fires event when clicked', function() {
    expect( 1 );

    var component = this.subject();
    var $component = this.append();

    var targetObject = {
        externalAction: function() {
            ok( true, 'External action was called' );
        }
    };

    component.set( 'action', 'externalAction' );
    component.set( 'targetObject', targetObject );

    $component.click();
});

test( 'The element disables during associated AJAX activity', function() {
    var component = this.subject({
        ajaxEnabled: true,
        disableOnAjax: true
    });

    equal( this.$().is( ':disabled' ), false );

    AjaxHelper.begin();
    equal( this.$().is( ':disabled' ), true );

    AjaxHelper.end();
    equal( this.$().is( ':disabled' ), false );
});
<|endoftext|>


<commit_before>'use strict';

var RootComponent = require('../lib/root-component.jsx'),

    React = require('react'),
    ReactTestUtils = require('react/lib/ReactTestUtils'),

    expect = require('chai').expect;

function randomInt(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}

function generateDummyItems(number) {
    var items = [],
        index;

    for (index = 0; index < number; index += 1) {
        items.push({
            name: '' + randomInt(10, 50)
        });
    }

    return items;
}

describe('Root Component', function () {
    var rootElement;

    beforeEach(function () {
        rootElement = React.createElement(RootComponent, {
            users: []
        });
    });

    it('should be a unordered list', function () {
        var renderedRootElement = ReactTestUtils.renderIntoDocument(rootElement),
            renderedDOMNode = renderedRootElement.getDOMNode();

        expect(renderedDOMNode.tagName).to.equal('UL');
    });

    describe('when the list is rendered with a set of users', function () {
        var rootElementWithItems,
            renderedElementWithItems,
            listItems,
            expectedNumberOfItems,
            dummyUsers;

        beforeEach(function () {
            expectedNumberOfItems = randomInt(20, 30);
            dummyUsers = generateDummyItems(expectedNumberOfItems);

            rootElementWithItems = React.createElement(RootComponent, {
                users: dummyUsers
            });

            renderedElementWithItems = ReactTestUtils.renderIntoDocument(rootElementWithItems);
            listItems = ReactTestUtils.scryRenderedDOMComponentsWithTag(renderedElementWithItems, 'LI');
        });

        it('should render an LI for each of the items', function () {
            expect(listItems).to.have.length(expectedNumberOfItems);
        });

        it('should include the name of the user in each item', function () {
            listItems.forEach(function (listItemElement, index) {
                var listItemNode = listItemElement.getDOMNode(),
                    dummyUser = dummyUsers[index].name;

                expect(listItemNode.textContent).to.equal(dummyUser);
            });
        });
    });
});
<commit_msg>Refactor: Replace `getDOMNode` with `React.findDOMNode`. Thanks to  @dariocravero for pointing that out.<commit_after>'use strict';

var RootComponent = require('../lib/root-component.jsx'),

    React = require('react'),
    ReactTestUtils = require('react/lib/ReactTestUtils'),

    expect = require('chai').expect;

function randomInt(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}

function generateDummyItems(number) {
    var items = [],
        index;

    for (index = 0; index < number; index += 1) {
        items.push({
            name: '' + randomInt(10, 50)
        });
    }

    return items;
}

describe('Root Component', function () {
    var rootElement;

    beforeEach(function () {
        rootElement = React.createElement(RootComponent, {
            users: []
        });
    });

    it('should be a unordered list', function () {
        var renderedRootElement = ReactTestUtils.renderIntoDocument(rootElement),
            renderedDOMNode = React.findDOMNode(renderedRootElement);

        expect(renderedDOMNode.tagName).to.equal('UL');
    });

    describe('when the list is rendered with a set of users', function () {
        var rootElementWithItems,
            renderedElementWithItems,
            listItems,
            expectedNumberOfItems,
            dummyUsers;

        beforeEach(function () {
            expectedNumberOfItems = randomInt(20, 30);
            dummyUsers = generateDummyItems(expectedNumberOfItems);

            rootElementWithItems = React.createElement(RootComponent, {
                users: dummyUsers
            });

            renderedElementWithItems = ReactTestUtils.renderIntoDocument(rootElementWithItems);
            listItems = ReactTestUtils.scryRenderedDOMComponentsWithTag(renderedElementWithItems, 'LI');
        });

        it('should render an LI for each of the items', function () {
            expect(listItems).to.have.length(expectedNumberOfItems);
        });

        it('should include the name of the user in each item', function () {
            listItems.forEach(function (listItemElement, index) {
                var listItemNode = React.findDOMNode(listItemElement),
                    dummyUser = dummyUsers[index].name;

                expect(listItemNode.textContent).to.equal(dummyUser);
            });
        });
    });
});
<|endoftext|>


<commit_before>import expect from 'expect';
import conf from '../';

describe('conf function', () => {
  it('should return undefined if "conf" is not provided', () => {
    const props = {};
    expect(conf(props)).toBe(undefined);
  });

  it('should return the "conf" props unless its child "conf" key', () => {
    const props = {conf: {
      foo: 'bar',
      conf: 'shouldNotCopy'
    }};
    expect(conf(props)).toEqual({foo: 'bar'});
  });

  it('should return the "conf" computed props if callback', () => {
    const props = {conf: {
      foo: () => ('bar')
    }};
    expect(conf(props)).toEqual({foo: 'bar'});
  });

  it('should return undefined if child "conf" is not provided', () => {
    const props = {};
    expect(conf(1, props)).toBe(undefined);
    expect(conf('div', props)).toBe(undefined);
  });

  it('should return the indexed child "conf"', () => {
    const props = {conf: {
      conf: [{foo: 'bar'}, {bar: 'baz'}]
    }};
    expect(conf(0, props)).toEqual({foo: 'bar'});
    expect(conf(1, props)).toEqual({bar: 'baz'});
  });

  it('should return the named child "conf"', () => {
    const props = {conf: {
      conf: {
        div: {foo: 'bar'},
        SomeComponent: {bar: 'baz'}
      }
    }};
    expect(conf('div', props)).toEqual({foo: 'bar'});
    expect(conf('SomeComponent', props)).toEqual({bar: 'baz'});
  });
});
<commit_msg>add conf tests<commit_after>import expect from 'expect';
import conf from '../';

describe('conf function', () => {
  it('should return undefined if "conf" is not provided', () => {
    const props = {};
    expect(conf(props)).toBe(undefined);
  });

  it('should return the "conf" props unless its child "conf" key', () => {
    const props = {conf: {
      foo: 'bar',
      conf: 'shouldNotCopy'
    }};
    expect(conf(props)).toEqual({foo: 'bar'});
  });

  it('should return the "conf" computed props if callback', () => {
    const props = {conf: {
      foo: () => ('bar')
    }};
    expect(conf(props)).toEqual({foo: 'bar'});
  });

  it('should return undefined if child "conf" is not provided', () => {
    const props = {};
    expect(conf(1, props)).toBe(undefined);
    expect(conf('div', props)).toBe(undefined);
  });

  it('should return the indexed child "conf"', () => {
    const props = {conf: {
      conf: [{foo: 'bar'}, {bar: 'baz'}]
    }};
    expect(conf(0, props)).toEqual({foo: 'bar'});
    expect(conf(1, props)).toEqual({bar: 'baz'});
  });

  it('should return the named child "conf"', () => {
    const props = {conf: {
      conf: {
        div: {foo: 'bar'},
        SomeComponent: {bar: 'baz'}
      }
    }};
    expect(conf('div', props)).toEqual({foo: 'bar'});
    expect(conf('SomeComponent', props)).toEqual({bar: 'baz'});
  });

  it('should return the child "conf" computed props', () => {
    const iprops = {conf: {
      conf: [{
        foo: () => ('bar')
      }]
    }};
    expect(conf(0, iprops)).toEqual({foo: 'bar'});

    const nprops = {conf: {
      conf: {div: {
        foo: () => ('bar')
      }}
    }};
    expect(conf('div', nprops)).toEqual({foo: 'bar'});
  });
});
<|endoftext|>


<commit_before>import { Meteor } from 'meteor/meteor';
import { _ } from 'meteor/underscore';

import Courses from './courses.js';
import Events from '/imports/api/events/events.js';
import Groups from '/imports/api/groups/groups.js';
import Regions from '/imports/api/regions/regions.js';
import Roles from '/imports/api/roles/roles.js';
import UpdateMethods from '/imports/utils/update-methods.js';
import {
	HasRoleUser,
	MaySubscribe,
	MayUnsubscribe
} from '/imports/utils/course-role-utils.js';

import AsyncTools from '/imports/utils/async-tools.js';
import StringTools from '/imports/utils/string-tools.js';
import HtmlTools from '/imports/utils/html-tools.js';

import PleaseLogin from '/imports/ui/lib/please-login.js';

function addRole(course, role, user) {
	// Add the user as member if she's not listed yet
	Courses.update(
		{ _id: course._id, 'members.user': { $ne: user } },
		{ $addToSet: { 'members': { user: user, roles: [ role ]} }}
	);

	Courses.update(
		{ _id: course._id, 'members.user': user },
		{ '$addToSet': { 'members.$.roles': role }}
	);

	Courses.updateGroups(course._id);
}

function removeRole(course, role, user) {
	Courses.update(
		{ _id: course._id, 'members.user': user },
		{ '$pull': { 'members.$.roles': role }}
	);

	// Housekeeping: Remove members that have no role left
	Courses.update(
		{ _id: course._id },
		{ $pull: { members: { roles: { $size: 0 } }}}
	);

	Courses.updateGroups(course._id);
}

Meteor.methods({
	'course.addRole': function(courseId, userId, role) {
		check(courseId, String);
		check(userId, String);
		check(role, String);

		var user = Meteor.users.findOne(userId);
		if (!user) throw new Meteor.Error(404, "User not found");

		var operator = Meteor.user();
		if (!operator) throw new Meteor.Error(401, "please log in");

		var course = Courses.findOne({_id: courseId});
		if (!course) throw new Meteor.Error(404, "Course not found");

		if (course.roles.indexOf(role) == -1) throw new Meteor.Error(404, "No role "+role);

		// do nothing if user is already subscribed with this role
		if (HasRoleUser(course.members, role, userId)) return true;

		// Check permissions
		if (!MaySubscribe(operator._id, course, user._id, role)) {
			throw new Meteor.Error(401, "not permitted");
		}

		addRole(course, role, user._id);

		// Update the modification date
		Courses.update(courseId, { $set: {time_lastedit: new Date()} });

		// Send notifications
		Notification.Join.record(course._id, user._id, role);
	},

	'course.removeRole': function(courseId, userId, role) {
		check(role, String);
		check(userId, String);
		check(courseId, String);

		var user = Meteor.users.findOne(userId);
		if (!user) throw new Meteor.Error(404, "User not found");

		var operator = Meteor.user();
		if (!operator) throw new Meteor.Error(401, "please log in");

		var course = Courses.findOne({_id: courseId});
		if (!course) throw new Meteor.Error(404, "Course not found");

		// do nothing if user is not subscribed with this role
		if (!HasRoleUser(course.members, role, userId)) return true;

		// Check permissions
		 if (!MayUnsubscribe(operator._id, course, user._id, role)) {
			throw new Meteor.Error(401, "not permitted");
		}

		removeRole(course, role, user._id);
	},

	'course.changeComment': function(courseId, comment) {
		check(courseId, String);
		check(comment, String);
		var course = Courses.findOne({_id: courseId});
		if (!course) throw new Meteor.Error(404, "Course not found");

		Courses.update(
			{ _id: course._id, 'members.user': Meteor.userId() },
			{ $set: { 'members.$.comment': comment } }
		);
	},

	'course.save': function(courseId, changes) {
		check(courseId, String);
		check(changes, {
			description: Match.Optional(String),
			categories:  Match.Optional([String]),
			name:        Match.Optional(String),
			region:      Match.Optional(String),
			roles:       Match.Optional(Object),
			groups:      Match.Optional([String]),
			internal:    Match.Optional(Boolean),
		});

		var user = Meteor.user();
		if (!user) {
			if (Meteor.is_client) {
				PleaseLogin();
				return;
			} else {
				throw new Meteor.Error(401, "please log in");
			}
		}

		var course;
		var isNew = courseId.length === 0;
		if (isNew) {
			course = new Course();
		} else {
			course = Courses.findOne({_id: courseId});
			if (!course) throw new Meteor.Error(404, "Course not found");
		}

		if (!course.editableBy(user)) throw new Meteor.Error(401, "edit not permitted");

		/* Changes we want to perform */
		var set = {};

		if (changes.roles) {
			_.each(Roles, function(roletype) {
				var type = roletype.type;
				var should_have = roletype.preset || changes.roles && changes.roles[type];
				var have = course.roles.indexOf(type) !== -1;

				if (have && !should_have) {
					Courses.update(
						{ _id: courseId },
						{ $pull: { roles: type }},
						AsyncTools.checkUpdateOne
					);

					// HACK
					// due to a mongo limitation we can't { $pull { 'members.roles': type } }
					// so we keep removing one by one until there are none left
					while(Courses.update(
						{ _id: courseId, "members.roles": type },
						{ $pull: { 'members.$.roles': type }}
					));
				}
				if (!have && should_have) {
					if (isNew) {
						set.roles = set.roles || [];
						set.roles.push(type);
					} else {
						Courses.update(
							{ _id: courseId },
							{ $addToSet: { roles: type }},
							AsyncTools.checkUpdateOne
						);
					}
				}
			});
		}

		if (changes.description) {
			set.description = changes.description.substring(0, 640*1024); /* 640 k ought to be enough for everybody  -- Mao */
			if (Meteor.isServer) {
				set.description = HtmlTools.saneHtml(set.description);
			}
		}

		if (changes.categories) set.categories = changes.categories.slice(0, 20);
		if (changes.name) {
			set.name = StringTools.saneTitle(changes.name).substring(0, 1000);
			set.slug = StringTools.slug(set.name);
		}
		if (changes.internal !== undefined) {
			set.internal = changes.internal;
		}

		set.time_lastedit = new Date();
		if (isNew) {
			// You can add newly created courses to any group
			var tested_groups = [];
			if (changes.groups) {
				tested_groups = _.map(changes.groups, function(groupId) {
					var group = Groups.findOne(groupId);
					if (!group) throw new Meteor.Error(404, "no group with id "+groupId);
					return group._id;
				});
			}
			set.groups = tested_groups;
			set.groupOrganizers = tested_groups;

			/* region cannot be changed */
			var region = Regions.findOne({_id: changes.region});
			if (!region) throw new Meteor.Error(404, 'region missing');
			set.region = region._id;

			/* When a course is created, the creator is automatically added as sole member of the team */
			set.members = [{
				user: user._id,
				roles: ['participant', 'team'],
				comment: mf('courses.creator.defaultMessage', '(has proposed this course)')}
			];
			set.editors = [user._id];
			set.createdby = user._id;
			set.time_created = new Date();
			courseId = Courses.insert(set);

			Meteor.call('course.updateNextEvent', courseId);
		} else {
			Courses.update({ _id: courseId }, { $set: set }, AsyncTools.checkUpdateOne);
		}

		return courseId;
	},

	'course.remove': function(courseId) {
		var course = Courses.findOne({_id: courseId});
		if (!course) throw new Meteor.Error(404, "no such course");
		if (!course.editableBy(Meteor.user())) throw new Meteor.Error(401, "edit not permitted");
		Events.remove({ courseId: courseId });
		Courses.remove(courseId);
	},

	// Update the nextEvent field for the courses matching the selector
	'course.updateNextEvent': function(selector) {
		Courses.find(selector).forEach(function(course) {
			var futureEvents = Events.find(
				{courseId: course._id, start: {$gt: new Date()}}
			).count();

			var nextEvent = Events.findOne(
				{ courseId: course._id, start: {$gt: new Date()} },
				{ sort: {start: 1}, fields: {startLocal: 1, start: 1, _id: 1, venue: 1} }
			);

			var lastEvent = Events.findOne(
				{ courseId: course._id, start: {$lt: new Date()} },
				{ sort: {start: -1}, fields: {startLocal: 1, start: 1, _id: 1, venue: 1} }
			);

			Courses.update(course._id, { $set: {
				futureEvents: futureEvents,
				nextEvent: nextEvent,
				lastEvent: lastEvent,
			} });
		});
	},

	/** Add or remove a group from the groups list
	  *
	  * @param {String} courseId - The course to update
	  * @param {String} groupId - The group to add or remove
	  * @param {Boolean} add - Whether to add or remove the group
	  *
	  */
	'course.promote': UpdateMethods.Promote(Courses),

	/** Add or remove a group from the groupOrganizers list
	  *
	  * @param {String} courseId - The course to update
	  * @param {String} groupId - The group to add or remove
	  * @param {Boolean} add - Whether to add or remove the group
	  *
	  */
	'course.editing': UpdateMethods.Editing(Courses),

	// Recalculate the editors field
	'course.updateGroups': function(selector) {
		Courses.find(selector).forEach(function(course) {
			Courses.updateGroups(course._id);
		});
	},
});
<commit_msg>explicitly set fields to null<commit_after>import { Meteor } from 'meteor/meteor';
import { _ } from 'meteor/underscore';

import Courses from './courses.js';
import Events from '/imports/api/events/events.js';
import Groups from '/imports/api/groups/groups.js';
import Regions from '/imports/api/regions/regions.js';
import Roles from '/imports/api/roles/roles.js';
import UpdateMethods from '/imports/utils/update-methods.js';
import {
	HasRoleUser,
	MaySubscribe,
	MayUnsubscribe
} from '/imports/utils/course-role-utils.js';

import AsyncTools from '/imports/utils/async-tools.js';
import StringTools from '/imports/utils/string-tools.js';
import HtmlTools from '/imports/utils/html-tools.js';

import PleaseLogin from '/imports/ui/lib/please-login.js';

function addRole(course, role, user) {
	// Add the user as member if she's not listed yet
	Courses.update(
		{ _id: course._id, 'members.user': { $ne: user } },
		{ $addToSet: { 'members': { user: user, roles: [ role ]} }}
	);

	Courses.update(
		{ _id: course._id, 'members.user': user },
		{ '$addToSet': { 'members.$.roles': role }}
	);

	Courses.updateGroups(course._id);
}

function removeRole(course, role, user) {
	Courses.update(
		{ _id: course._id, 'members.user': user },
		{ '$pull': { 'members.$.roles': role }}
	);

	// Housekeeping: Remove members that have no role left
	Courses.update(
		{ _id: course._id },
		{ $pull: { members: { roles: { $size: 0 } }}}
	);

	Courses.updateGroups(course._id);
}

Meteor.methods({
	'course.addRole': function(courseId, userId, role) {
		check(courseId, String);
		check(userId, String);
		check(role, String);

		var user = Meteor.users.findOne(userId);
		if (!user) throw new Meteor.Error(404, "User not found");

		var operator = Meteor.user();
		if (!operator) throw new Meteor.Error(401, "please log in");

		var course = Courses.findOne({_id: courseId});
		if (!course) throw new Meteor.Error(404, "Course not found");

		if (course.roles.indexOf(role) == -1) throw new Meteor.Error(404, "No role "+role);

		// do nothing if user is already subscribed with this role
		if (HasRoleUser(course.members, role, userId)) return true;

		// Check permissions
		if (!MaySubscribe(operator._id, course, user._id, role)) {
			throw new Meteor.Error(401, "not permitted");
		}

		addRole(course, role, user._id);

		// Update the modification date
		Courses.update(courseId, { $set: {time_lastedit: new Date()} });

		// Send notifications
		Notification.Join.record(course._id, user._id, role);
	},

	'course.removeRole': function(courseId, userId, role) {
		check(role, String);
		check(userId, String);
		check(courseId, String);

		var user = Meteor.users.findOne(userId);
		if (!user) throw new Meteor.Error(404, "User not found");

		var operator = Meteor.user();
		if (!operator) throw new Meteor.Error(401, "please log in");

		var course = Courses.findOne({_id: courseId});
		if (!course) throw new Meteor.Error(404, "Course not found");

		// do nothing if user is not subscribed with this role
		if (!HasRoleUser(course.members, role, userId)) return true;

		// Check permissions
		 if (!MayUnsubscribe(operator._id, course, user._id, role)) {
			throw new Meteor.Error(401, "not permitted");
		}

		removeRole(course, role, user._id);
	},

	'course.changeComment': function(courseId, comment) {
		check(courseId, String);
		check(comment, String);
		var course = Courses.findOne({_id: courseId});
		if (!course) throw new Meteor.Error(404, "Course not found");

		Courses.update(
			{ _id: course._id, 'members.user': Meteor.userId() },
			{ $set: { 'members.$.comment': comment } }
		);
	},

	'course.save': function(courseId, changes) {
		check(courseId, String);
		check(changes, {
			description: Match.Optional(String),
			categories:  Match.Optional([String]),
			name:        Match.Optional(String),
			region:      Match.Optional(String),
			roles:       Match.Optional(Object),
			groups:      Match.Optional([String]),
			internal:    Match.Optional(Boolean),
		});

		var user = Meteor.user();
		if (!user) {
			if (Meteor.is_client) {
				PleaseLogin();
				return;
			} else {
				throw new Meteor.Error(401, "please log in");
			}
		}

		var course;
		var isNew = courseId.length === 0;
		if (isNew) {
			course = new Course();
		} else {
			course = Courses.findOne({_id: courseId});
			if (!course) throw new Meteor.Error(404, "Course not found");
		}

		if (!course.editableBy(user)) throw new Meteor.Error(401, "edit not permitted");

		/* Changes we want to perform */
		var set = {};

		if (changes.roles) {
			_.each(Roles, function(roletype) {
				var type = roletype.type;
				var should_have = roletype.preset || changes.roles && changes.roles[type];
				var have = course.roles.indexOf(type) !== -1;

				if (have && !should_have) {
					Courses.update(
						{ _id: courseId },
						{ $pull: { roles: type }},
						AsyncTools.checkUpdateOne
					);

					// HACK
					// due to a mongo limitation we can't { $pull { 'members.roles': type } }
					// so we keep removing one by one until there are none left
					while(Courses.update(
						{ _id: courseId, "members.roles": type },
						{ $pull: { 'members.$.roles': type }}
					));
				}
				if (!have && should_have) {
					if (isNew) {
						set.roles = set.roles || [];
						set.roles.push(type);
					} else {
						Courses.update(
							{ _id: courseId },
							{ $addToSet: { roles: type }},
							AsyncTools.checkUpdateOne
						);
					}
				}
			});
		}

		if (changes.description) {
			set.description = changes.description.substring(0, 640*1024); /* 640 k ought to be enough for everybody  -- Mao */
			if (Meteor.isServer) {
				set.description = HtmlTools.saneHtml(set.description);
			}
		}

		if (changes.categories) set.categories = changes.categories.slice(0, 20);
		if (changes.name) {
			set.name = StringTools.saneTitle(changes.name).substring(0, 1000);
			set.slug = StringTools.slug(set.name);
		}
		if (changes.internal !== undefined) {
			set.internal = changes.internal;
		}

		set.time_lastedit = new Date();
		if (isNew) {
			// You can add newly created courses to any group
			var tested_groups = [];
			if (changes.groups) {
				tested_groups = _.map(changes.groups, function(groupId) {
					var group = Groups.findOne(groupId);
					if (!group) throw new Meteor.Error(404, "no group with id "+groupId);
					return group._id;
				});
			}
			set.groups = tested_groups;
			set.groupOrganizers = tested_groups;

			/* region cannot be changed */
			var region = Regions.findOne({_id: changes.region});
			if (!region) throw new Meteor.Error(404, 'region missing');
			set.region = region._id;

			/* When a course is created, the creator is automatically added as sole member of the team */
			set.members = [{
				user: user._id,
				roles: ['participant', 'team'],
				comment: mf('courses.creator.defaultMessage', '(has proposed this course)')}
			];
			set.editors = [user._id];
			set.createdby = user._id;
			set.time_created = new Date();
			courseId = Courses.insert(set);

			Meteor.call('course.updateNextEvent', courseId);
		} else {
			Courses.update({ _id: courseId }, { $set: set }, AsyncTools.checkUpdateOne);
		}

		return courseId;
	},

	'course.remove': function(courseId) {
		var course = Courses.findOne({_id: courseId});
		if (!course) throw new Meteor.Error(404, "no such course");
		if (!course.editableBy(Meteor.user())) throw new Meteor.Error(401, "edit not permitted");
		Events.remove({ courseId: courseId });
		Courses.remove(courseId);
	},

	// Update the nextEvent field for the courses matching the selector
	'course.updateNextEvent': function(selector) {
		Courses.find(selector).forEach(function(course) {
			var futureEvents = Events.find(
				{courseId: course._id, start: {$gt: new Date()}}
			).count();

			var nextEvent = Events.findOne(
				{ courseId: course._id, start: {$gt: new Date()} },
				{ sort: {start: 1}, fields: {startLocal: 1, start: 1, _id: 1, venue: 1} }
			);

			var lastEvent = Events.findOne(
				{ courseId: course._id, start: {$lt: new Date()} },
				{ sort: {start: -1}, fields: {startLocal: 1, start: 1, _id: 1, venue: 1} }
			);

			Courses.update(course._id, { $set: {
				futureEvents: futureEvents,
				nextEvent: nextEvent || null,
				lastEvent: lastEvent || null,
			} });
		});
	},

	/** Add or remove a group from the groups list
	  *
	  * @param {String} courseId - The course to update
	  * @param {String} groupId - The group to add or remove
	  * @param {Boolean} add - Whether to add or remove the group
	  *
	  */
	'course.promote': UpdateMethods.Promote(Courses),

	/** Add or remove a group from the groupOrganizers list
	  *
	  * @param {String} courseId - The course to update
	  * @param {String} groupId - The group to add or remove
	  * @param {Boolean} add - Whether to add or remove the group
	  *
	  */
	'course.editing': UpdateMethods.Editing(Courses),

	// Recalculate the editors field
	'course.updateGroups': function(selector) {
		Courses.find(selector).forEach(function(course) {
			Courses.updateGroups(course._id);
		});
	},
});
<|endoftext|>


<commit_before>import assert from 'assert'
import chai from 'chai'
import {getRandomString} from '../helpers'

const expect = chai.expect

describe('RSI - Save and restore test', function() {
  before('Progress from the developer page for 1_0102', function() {
    const userId = '.qa-user-id'
    const collectionSID = '.qa-collection-sid'
    const selectSchema = '.qa-select-schema'
    browser.url('/dev')
    browser.windowHandleMaximize()
    browser.deleteCookie()
    browser.waitForExist(userId)
    browser.setValue(userId, 'yoganandkunche')
    browser.waitForExist(collectionSID)
    browser.setValue(collectionSID, '7890102')
    browser.waitForExist(selectSchema)
    browser.selectByValue(selectSchema, '1_0102.json')
    browser.click('.qa-btn-submit-dev')
  })

  it('The landing page has been reached for 0102', function(done) {
    const getStartedBtn = browser.element('.qa-btn-get-started')
    getStartedBtn.waitForExist(10000)
    const url = browser.url().value
    expect(url).to.contain('introduction')
    getStartedBtn.click()
  })

  it('The questionnaire page for 0102 has been reached', function(done) {
    const questionnaireElementExists = browser.isExisting('.qa-questionnaire-form')
    expect(questionnaireElementExists).to.equal(true)
  })

  it('Enter Data in to 0102 questionnaire', function(done) {
    const questionnaireElementExists = browser.isExisting('.qa-questionnaire-form')
    expect(questionnaireElementExists).to.equal(true)
    const submitBtn = browser.element('.qa-btn-submit')
    submitBtn.waitForExist(10000)
    browser.setValue('[id="94f368e4-7c6c-4272-a780-8c46328626a2-day"]', '01')
    browser.setValue('[id="94f368e4-7c6c-4272-a780-8c46328626a2-year"]', '2016')
    browser.setValue('[id="dc156715-3d48-4af3-afed-7a0a6bb65583-day"]', '01')
    browser.setValue('[id="dc156715-3d48-4af3-afed-7a0a6bb65583-year"]', '2016')
    const saveandcontinueBtn2 = browser.element('.qa-btn-submit')
    saveandcontinueBtn2.click();
    const erroralert = browser.element('.alert__body')
    const Q1text = erroralert.getText()
    const experror = 'The \'to\' date must be different to the \'from\' date.'
    if(Q1text.indexOf(experror) > -1) {
      console.log('Expected Text is present: ' + experror );
    } else {
      console.log(Q1text.indexOf(experror) !== -1);
      assert.equal(Q1text, experror);
    }
  })

  it('Progress from the developer page for 1_0112', function() {
    const userId = '.qa-user-id'
    const collectionSID = '.qa-collection-sid'
    const selectSchema = '.qa-select-schema'
    browser.url('/dev')
    browser.waitForExist(userId)
    browser.setValue(userId, 'yoganandkunche')
    browser.waitForExist(collectionSID)
    browser.setValue(collectionSID, '7890112')
    browser.waitForExist(selectSchema)
    browser.selectByValue(selectSchema, '1_0112.json')
    browser.click('.qa-btn-submit-dev')
  })

  it('The landing page has been reached for 0112', function(done) {
    const getStartedBtn = browser.element('.qa-btn-get-started')
    getStartedBtn.waitForExist(10000)
    const url = browser.url().value
    expect(url).to.contain('introduction')
    getStartedBtn.click()
  })

  it('The questionnaire page for 0112 has been reached', function(done) {
    const questionnaireElementExists = browser.isExisting('.qa-questionnaire-form')
    expect(questionnaireElementExists).to.equal(true)
  })

  it('Enter Data in to 0112 questionnaire', function(done) {
    const questionnaireElementExists = browser.isExisting('.qa-questionnaire-form')
    expect(questionnaireElementExists).to.equal(true)
    const submitBtn = browser.element('.qa-btn-submit')
    submitBtn.waitForExist(10000)
    browser.setValue('#fad63234-1083-4f6a-826a-20b5df6e4baa-day', '01')
    browser.setValue('#fad63234-1083-4f6a-826a-20b5df6e4baa-year', '2016')
    browser.setValue('#c8c4bd92-fd45-4fd1-83b6-18c813de2df2-day', '01')
    browser.setValue('#c8c4bd92-fd45-4fd1-83b6-18c813de2df2-year', '2017')
    const saveandcontinueBtn2 = browser.element('.qa-btn-submit')
    saveandcontinueBtn2.click();
    submitBtn.waitForExist(10000)
    browser.setValue('.input--currency', 'Test')
    const saveandcontinueBtn3 = browser.element('.qa-btn-submit')
    saveandcontinueBtn3.click();
    const erroralert2 = browser.element('.alert__body')
    const Q2text = erroralert2.getText()
    const experror2 = 'Please only enter whole numbers into the field.'
    if(Q2text.indexOf(experror2) > -1) {
      console.log('Expected Text is present: ' + experror2 );
    } else {
      console.log(Q2text.indexOf(experror2) !== -1);
      assert.equal(Q2text, experror2);
    }
  })
  // Revisiting 0102
  it('Progress from the developer page for 1_0102', function() {
    const userId = '.qa-user-id'
    const collectionSID = '.qa-collection-sid'
    const selectSchema = '.qa-select-schema'
    browser.url('/dev')
    browser.waitForExist(userId)
    browser.setValue(userId, 'yoganandkunche')
    browser.waitForExist(collectionSID)
    browser.setValue(collectionSID, '7890102')
    browser.waitForExist(selectSchema)
    browser.selectByValue(selectSchema, '1_0102.json')
    browser.click('.qa-btn-submit-dev')
  })

  it('To make sure the error page has been reached for 0102 revisit', function(done) {
    const saveandcontinueBtn4 = browser.element('.qa-btn-submit')
    saveandcontinueBtn4.waitForExist(10000)
    const erroralert = browser.element('.alert__body')
    const Q1text = erroralert.getText()
    const experror = 'The \'to\' date must be different to the \'from\' date.'
    if(Q1text.indexOf(experror) > -1) {
      console.log('Expected Text is present: ' + experror );
    } else {
      console.log(Q1text.indexOf(experror) !== -1);
      assert.equal(Q1text, experror);
    }
  })

  it('Correcting the error and submitting the 0102 form', function(done) {
    const questionnaireElementExists = browser.isExisting('.qa-questionnaire-form')
    expect(questionnaireElementExists).to.equal(true)
    const submitBtn = browser.element('.qa-btn-submit')
    submitBtn.waitForExist(10000)
    browser.setValue('[id="94f368e4-7c6c-4272-a780-8c46328626a2-day"]', '01')
    browser.setValue('[id="94f368e4-7c6c-4272-a780-8c46328626a2-year"]', '2016')
    browser.setValue('#dc156715-3d48-4af3-afed-7a0a6bb65583-day', '01')
    browser.setValue('#dc156715-3d48-4af3-afed-7a0a6bb65583-year', '2017')
    const saveandcontinueBtn2 = browser.element('.qa-btn-submit')
    saveandcontinueBtn2.click();
    browser.setValue('.input--currency', '12345')
    const saveandcontinueBtn3 = browser.element('.qa-btn-submit')
    saveandcontinueBtn3.click();
    browser.setValue('.input--currency', '1234')
    const saveandcontinueBtn4 = browser.element('.qa-btn-submit')
    saveandcontinueBtn4.click();
    browser.setValue('.input--textarea', 'This is for RSI 0102 Save and restore testing')
    const saveandcontinueBtn5 = browser.element('.qa-btn-submit')
    saveandcontinueBtn5.click();
  })
  it('The survey can be completed with "thankyou page" reached', function(done) {
    const finalsubmitBtn = browser.element('.qa-btn-submit-answers')
    finalsubmitBtn.waitForExist(10000)
    finalsubmitBtn.click();
    const url = browser.url().value
    expect(url).to.contain('thank-you')
  })

  // Revisiting 0112
  it('Progress from the developer page for 1_0112', function() {
    const userId = '.qa-user-id'
    const collectionSID = '.qa-collection-sid'
    const selectSchema = '.qa-select-schema'
    browser.url('/dev')
    browser.waitForExist(userId)
    browser.setValue(userId, 'yoganandkunche')
    browser.waitForExist(collectionSID)
    browser.setValue(collectionSID, '7890112')
    browser.waitForExist(selectSchema)
    browser.selectByValue(selectSchema, '1_0112.json')
    browser.click('.qa-btn-submit-dev')
  })
  it('To make sure the error page has been reached for 0112 on revisit', function(done) {
    const saveandcontinueBtn4 = browser.element('.qa-btn-submit')
    saveandcontinueBtn4.waitForExist(10000)
    const erroralert = browser.element('.alert__body')
    const Q2text = erroralert.getText()
    const experror2 = 'Please only enter whole numbers into the field.'
    if(Q2text.indexOf(experror2) > -1) {
      console.log('Expected Text is present: ' + experror2 );
    } else {
      console.log(Q2text.indexOf(experror2) !== -1);
      assert.equal(Q2text, experror2);
    }
  })

  it('Correcting the error and submitting the 0112 form', function(done) {
    const questionnaireElementExists = browser.isExisting('.qa-questionnaire-form')
    expect(questionnaireElementExists).to.equal(true)
    const submitBtn = browser.element('.qa-btn-submit')
    submitBtn.waitForExist(10000)
    browser.setValue('.input--currency', '12345')
    browser.element('.qa-btn-submit').click();
    browser.setValue('.input--currency', '1234')
    browser.element('.qa-btn-submit').click();
    browser.setValue('.input--textarea', 'This is for RSI 0112 Save and restore testing')
    browser.element('.qa-btn-submit').click();
    browser.setValue('[name = "c6881970-98ff-4005-af4a-60bfd9b6179f"]', '13')
    browser.element('.qa-btn-submit').click();
    browser.setValue('.input--textarea', 'Changes in employee figures')
    browser.element('.qa-btn-submit').click();
  })

  it('The survey can be completed with "thankyou page" reached', function(done) {
    const finalsubmitBtn = browser.element('.qa-btn-submit-answers')
    finalsubmitBtn.waitForExist(10000)
    finalsubmitBtn.click();
    const url = browser.url().value
    expect(url).to.contain('thank-you')
  })
})
<commit_msg>Fix automated tests to work with new date labels<commit_after>import assert from 'assert'
import chai from 'chai'
import {getRandomString} from '../helpers'

const expect = chai.expect

describe('RSI - Save and restore test', function() {
  before('Progress from the developer page for 1_0102', function() {
    const userId = '.qa-user-id'
    const collectionSID = '.qa-collection-sid'
    const selectSchema = '.qa-select-schema'
    browser.url('/dev')
    browser.windowHandleMaximize()
    browser.deleteCookie()
    browser.waitForExist(userId)
    browser.setValue(userId, 'yoganandkunche')
    browser.waitForExist(collectionSID)
    browser.setValue(collectionSID, '7890102')
    browser.waitForExist(selectSchema)
    browser.selectByValue(selectSchema, '1_0102.json')
    browser.click('.qa-btn-submit-dev')
  })

  it('The landing page has been reached for 0102', function(done) {
    const getStartedBtn = browser.element('.qa-btn-get-started')
    getStartedBtn.waitForExist(10000)
    const url = browser.url().value
    expect(url).to.contain('introduction')
    getStartedBtn.click()
  })

  it('The questionnaire page for 0102 has been reached', function(done) {
    const questionnaireElementExists = browser.isExisting('.qa-questionnaire-form')
    expect(questionnaireElementExists).to.equal(true)
  })

  it('Enter Data in to 0102 questionnaire', function(done) {
    const questionnaireElementExists = browser.isExisting('.qa-questionnaire-form')
    expect(questionnaireElementExists).to.equal(true)
    const submitBtn = browser.element('.qa-btn-submit')
    submitBtn.waitForExist(10000)
    browser.setValue('[id="94f368e4-7c6c-4272-a780-8c46328626a2-day"]', '01')
    browser.setValue('[id="94f368e4-7c6c-4272-a780-8c46328626a2-year"]', '2016')
    browser.setValue('[id="dc156715-3d48-4af3-afed-7a0a6bb65583-day"]', '01')
    browser.setValue('[id="dc156715-3d48-4af3-afed-7a0a6bb65583-year"]', '2016')
    const saveandcontinueBtn2 = browser.element('.qa-btn-submit')
    saveandcontinueBtn2.click();
    const erroralert = browser.element('.alert__body')
    const Q1text = erroralert.getText()
    const experror = 'The \'period to\' date must be different to the \'period from\' date.'
    if(Q1text.indexOf(experror) > -1) {
      console.log('Expected Text is present: ' + experror );
    } else {
      console.log(Q1text.indexOf(experror) !== -1);
      assert.equal(Q1text, experror);
    }
  })

  it('Progress from the developer page for 1_0112', function() {
    const userId = '.qa-user-id'
    const collectionSID = '.qa-collection-sid'
    const selectSchema = '.qa-select-schema'
    browser.url('/dev')
    browser.waitForExist(userId)
    browser.setValue(userId, 'yoganandkunche')
    browser.waitForExist(collectionSID)
    browser.setValue(collectionSID, '7890112')
    browser.waitForExist(selectSchema)
    browser.selectByValue(selectSchema, '1_0112.json')
    browser.click('.qa-btn-submit-dev')
  })

  it('The landing page has been reached for 0112', function(done) {
    const getStartedBtn = browser.element('.qa-btn-get-started')
    getStartedBtn.waitForExist(10000)
    const url = browser.url().value
    expect(url).to.contain('introduction')
    getStartedBtn.click()
  })

  it('The questionnaire page for 0112 has been reached', function(done) {
    const questionnaireElementExists = browser.isExisting('.qa-questionnaire-form')
    expect(questionnaireElementExists).to.equal(true)
  })

  it('Enter Data in to 0112 questionnaire', function(done) {
    const questionnaireElementExists = browser.isExisting('.qa-questionnaire-form')
    expect(questionnaireElementExists).to.equal(true)
    const submitBtn = browser.element('.qa-btn-submit')
    submitBtn.waitForExist(10000)
    browser.setValue('#fad63234-1083-4f6a-826a-20b5df6e4baa-day', '01')
    browser.setValue('#fad63234-1083-4f6a-826a-20b5df6e4baa-year', '2016')
    browser.setValue('#c8c4bd92-fd45-4fd1-83b6-18c813de2df2-day', '01')
    browser.setValue('#c8c4bd92-fd45-4fd1-83b6-18c813de2df2-year', '2017')
    const saveandcontinueBtn2 = browser.element('.qa-btn-submit')
    saveandcontinueBtn2.click();
    submitBtn.waitForExist(10000)
    browser.setValue('.input--currency', 'Test')
    const saveandcontinueBtn3 = browser.element('.qa-btn-submit')
    saveandcontinueBtn3.click();
    const erroralert2 = browser.element('.alert__body')
    const Q2text = erroralert2.getText()
    const experror2 = 'Please only enter whole numbers into the field.'
    if(Q2text.indexOf(experror2) > -1) {
      console.log('Expected Text is present: ' + experror2 );
    } else {
      console.log(Q2text.indexOf(experror2) !== -1);
      assert.equal(Q2text, experror2);
    }
  })
  // Revisiting 0102
  it('Progress from the developer page for 1_0102', function() {
    const userId = '.qa-user-id'
    const collectionSID = '.qa-collection-sid'
    const selectSchema = '.qa-select-schema'
    browser.url('/dev')
    browser.waitForExist(userId)
    browser.setValue(userId, 'yoganandkunche')
    browser.waitForExist(collectionSID)
    browser.setValue(collectionSID, '7890102')
    browser.waitForExist(selectSchema)
    browser.selectByValue(selectSchema, '1_0102.json')
    browser.click('.qa-btn-submit-dev')
  })

  it('To make sure the error page has been reached for 0102 revisit', function(done) {
    const saveandcontinueBtn4 = browser.element('.qa-btn-submit')
    saveandcontinueBtn4.waitForExist(10000)
    const erroralert = browser.element('.alert__body')
    const Q1text = erroralert.getText()
    const experror = 'The \'period to\' date must be different to the \'period from\' date.'
    if(Q1text.indexOf(experror) > -1) {
      console.log('Expected Text is present: ' + experror );
    } else {
      console.log(Q1text.indexOf(experror) !== -1);
      assert.equal(Q1text, experror);
    }
  })

  it('Correcting the error and submitting the 0102 form', function(done) {
    const questionnaireElementExists = browser.isExisting('.qa-questionnaire-form')
    expect(questionnaireElementExists).to.equal(true)
    const submitBtn = browser.element('.qa-btn-submit')
    submitBtn.waitForExist(10000)
    browser.setValue('[id="94f368e4-7c6c-4272-a780-8c46328626a2-day"]', '01')
    browser.setValue('[id="94f368e4-7c6c-4272-a780-8c46328626a2-year"]', '2016')
    browser.setValue('#dc156715-3d48-4af3-afed-7a0a6bb65583-day', '01')
    browser.setValue('#dc156715-3d48-4af3-afed-7a0a6bb65583-year', '2017')
    const saveandcontinueBtn2 = browser.element('.qa-btn-submit')
    saveandcontinueBtn2.click();
    browser.setValue('.input--currency', '12345')
    const saveandcontinueBtn3 = browser.element('.qa-btn-submit')
    saveandcontinueBtn3.click();
    browser.setValue('.input--currency', '1234')
    const saveandcontinueBtn4 = browser.element('.qa-btn-submit')
    saveandcontinueBtn4.click();
    browser.setValue('.input--textarea', 'This is for RSI 0102 Save and restore testing')
    const saveandcontinueBtn5 = browser.element('.qa-btn-submit')
    saveandcontinueBtn5.click();
  })
  it('The survey can be completed with "thankyou page" reached', function(done) {
    const finalsubmitBtn = browser.element('.qa-btn-submit-answers')
    finalsubmitBtn.waitForExist(10000)
    finalsubmitBtn.click();
    const url = browser.url().value
    expect(url).to.contain('thank-you')
  })

  // Revisiting 0112
  it('Progress from the developer page for 1_0112', function() {
    const userId = '.qa-user-id'
    const collectionSID = '.qa-collection-sid'
    const selectSchema = '.qa-select-schema'
    browser.url('/dev')
    browser.waitForExist(userId)
    browser.setValue(userId, 'yoganandkunche')
    browser.waitForExist(collectionSID)
    browser.setValue(collectionSID, '7890112')
    browser.waitForExist(selectSchema)
    browser.selectByValue(selectSchema, '1_0112.json')
    browser.click('.qa-btn-submit-dev')
  })
  it('To make sure the error page has been reached for 0112 on revisit', function(done) {
    const saveandcontinueBtn4 = browser.element('.qa-btn-submit')
    saveandcontinueBtn4.waitForExist(10000)
    const erroralert = browser.element('.alert__body')
    const Q2text = erroralert.getText()
    const experror2 = 'Please only enter whole numbers into the field.'
    if(Q2text.indexOf(experror2) > -1) {
      console.log('Expected Text is present: ' + experror2 );
    } else {
      console.log(Q2text.indexOf(experror2) !== -1);
      assert.equal(Q2text, experror2);
    }
  })

  it('Correcting the error and submitting the 0112 form', function(done) {
    const questionnaireElementExists = browser.isExisting('.qa-questionnaire-form')
    expect(questionnaireElementExists).to.equal(true)
    const submitBtn = browser.element('.qa-btn-submit')
    submitBtn.waitForExist(10000)
    browser.setValue('.input--currency', '12345')
    browser.element('.qa-btn-submit').click();
    browser.setValue('.input--currency', '1234')
    browser.element('.qa-btn-submit').click();
    browser.setValue('.input--textarea', 'This is for RSI 0112 Save and restore testing')
    browser.element('.qa-btn-submit').click();
    browser.setValue('[name = "c6881970-98ff-4005-af4a-60bfd9b6179f"]', '13')
    browser.element('.qa-btn-submit').click();
    browser.setValue('.input--textarea', 'Changes in employee figures')
    browser.element('.qa-btn-submit').click();
  })

  it('The survey can be completed with "thankyou page" reached', function(done) {
    const finalsubmitBtn = browser.element('.qa-btn-submit-answers')
    finalsubmitBtn.waitForExist(10000)
    finalsubmitBtn.click();
    const url = browser.url().value
    expect(url).to.contain('thank-you')
  })
})
<|endoftext|>


<commit_before>import React from 'react'
import { NavLink } from 'react-router-dom'
import { themeSettings, text } from '../lib/settings'

class AttributeValue extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      checked: props.checked
    }
  }

  onChange = (event) => {
    const {attributeName, valueName, setFilterAttribute, unsetFilterAttribute} = this.props;
    const checked = event.target.checked;

    this.setState({ checked: checked });

    if(checked){
      setFilterAttribute(attributeName, valueName);
    } else {
      unsetFilterAttribute(attributeName, valueName);
    }
  }

  render() {
    const { valueName, count } = this.props;
    const isDisabled = count === 0;
    const classChecked = this.state.checked ? "attribute-checked" : "";
    const classDisabled = isDisabled ? "attribute-disabled" : "";

    return (

        <input type="checkbox" disabled={isDisabled} onChange={this.onChange} checked={this.state.checked} />{valueName}

    )
  }
}

const AttributeSet = ({ attribute, setFilterAttribute, unsetFilterAttribute }) => {
  const values = attribute.values.map((value, index) => (
    <AttributeValue
      key={index}
      attributeName={attribute.name}
      valueName={value.name}
      checked={value.checked}
      count={value.count}
      setFilterAttribute={setFilterAttribute}
      unsetFilterAttribute={unsetFilterAttribute}
    />
  ))

  return (

{attribute.name}

      {values}

  )
}

const AttributeFilter = ({ attributes, setFilterAttribute, unsetFilterAttribute }) => {
  const attributeSets = attributes.map((attribute, index) => (
    <AttributeSet
      key={index}
      attribute={attribute}
      setFilterAttribute={setFilterAttribute}
      unsetFilterAttribute={unsetFilterAttribute}
    />
  ))

  return (

      {attributeSets}

  )
}

export default AttributeFilter;
<commit_msg>Fixed products filter update<commit_after>import React from 'react'
import { NavLink } from 'react-router-dom'
import { themeSettings, text } from '../lib/settings'

class AttributeValue extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      checked: props.checked
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.checked !== this.props.checked) {
      this.setState({ checked: nextProps.checked });
    }
  }

  onChange = (event) => {
    const {attributeName, valueName, setFilterAttribute, unsetFilterAttribute} = this.props;
    const checked = event.target.checked;

    this.setState({ checked: checked });

    if(checked){
      setFilterAttribute(attributeName, valueName);
    } else {
      unsetFilterAttribute(attributeName, valueName);
    }
  }

  render() {
    const { valueName, count } = this.props;
    const isDisabled = count === 0;
    const classChecked = this.state.checked ? "attribute-checked" : "";
    const classDisabled = isDisabled ? "attribute-disabled" : "";

    return (

        <input type="checkbox" disabled={isDisabled} onChange={this.onChange} checked={this.state.checked} />{valueName}

    )
  }
}

const AttributeSet = ({ attribute, setFilterAttribute, unsetFilterAttribute }) => {
  const values = attribute.values.map((value, index) => (
    <AttributeValue
      key={index}
      attributeName={attribute.name}
      valueName={value.name}
      checked={value.checked}
      count={value.count}
      setFilterAttribute={setFilterAttribute}
      unsetFilterAttribute={unsetFilterAttribute}
    />
  ))

  return (

{attribute.name}

      {values}

  )
}

const AttributeFilter = ({ attributes, setFilterAttribute, unsetFilterAttribute }) => {
  const attributeSets = attributes.map((attribute, index) => (
    <AttributeSet
      key={index}
      attribute={attribute}
      setFilterAttribute={setFilterAttribute}
      unsetFilterAttribute={unsetFilterAttribute}
    />
  ))

  return (

      {attributeSets}

  )
}

export default AttributeFilter;
<|endoftext|>


<commit_before>c3_chart_fn.load = function (args) {
    var $$ = this.internal, config = $$.config;
    // update xs if specified
    if (args.xs) {
        $$.addXs(args.xs);
    }
    // update classes if exists
    if ('classes' in args) {
        Object.keys(args.classes).forEach(function (id) {
            config.data_classes[id] = args.classes[id];
        });
    }
    // update categories if exists
    if ('categories' in args && $$.isCategorized()) {
        config.axis_x_categories = args.categories;
    }
    // update axes if exists
    if ('axes' in args) {
        Object.keys(args.axes).forEach(function (id) {
            config.data_axes[id] = args.axes[id];
        });
    }
    // use cache if exists
    if ('cacheIds' in args && $$.hasCaches(args.cacheIds)) {
        $$.load($$.getCaches(args.cacheIds), args.done);
        return;
    }
    // unload if needed
    if ('unload' in args) {
        // TODO: do not unload if target will load (included in url/rows/columns)
        $$.unload($$.mapToTargetIds((typeof args.unload === 'boolean' && args.unload) ? null : args.unload), function () {
            $$.loadFromArgs(args);
        });
    } else {
        $$.loadFromArgs(args);
    }
};

c3_chart_fn.unload = function (args) {
    var $$ = this.internal;
    args = args || {};
    if (args instanceof Array) {
        args = {ids: args};
    } else if (typeof args === 'string') {
        args = {ids: [args]};
    }
    $$.unload($$.mapToTargetIds(args.ids), function () {
        $$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true, withLegend: true});
        if (args.done) { args.done(); }
    });
};
<commit_msg>Add the ability to load data with colors<commit_after>c3_chart_fn.load = function (args) {
    var $$ = this.internal, config = $$.config;
    // update xs if specified
    if (args.xs) {
        $$.addXs(args.xs);
    }
    // update classes if exists
    if ('classes' in args) {
        Object.keys(args.classes).forEach(function (id) {
            config.data_classes[id] = args.classes[id];
        });
    }
    // update categories if exists
    if ('categories' in args && $$.isCategorized()) {
        config.axis_x_categories = args.categories;
    }
    // update axes if exists
    if ('axes' in args) {
        Object.keys(args.axes).forEach(function (id) {
            config.data_axes[id] = args.axes[id];
        });
    }
    // update colors if exists
    if ('colors' in args) {
        Object.keys(args.colors).forEach(function (id) {
            config.data_colors[id] = args.colors[id];
        });
    }
    // use cache if exists
    if ('cacheIds' in args && $$.hasCaches(args.cacheIds)) {
        $$.load($$.getCaches(args.cacheIds), args.done);
        return;
    }
    // unload if needed
    if ('unload' in args) {
        // TODO: do not unload if target will load (included in url/rows/columns)
        $$.unload($$.mapToTargetIds((typeof args.unload === 'boolean' && args.unload) ? null : args.unload), function () {
            $$.loadFromArgs(args);
        });
    } else {
        $$.loadFromArgs(args);
    }
};

c3_chart_fn.unload = function (args) {
    var $$ = this.internal;
    args = args || {};
    if (args instanceof Array) {
        args = {ids: args};
    } else if (typeof args === 'string') {
        args = {ids: [args]};
    }
    $$.unload($$.mapToTargetIds(args.ids), function () {
        $$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true, withLegend: true});
        if (args.done) { args.done(); }
    });
};
<|endoftext|>


<commit_before>import utilElementContains from '../util/element-contains';

var CustomEvent = (function (CustomEvent) {
  if (CustomEvent) {
    try {
      new CustomEvent();
    } catch (e) {
      return undefined;
    }
  }
  return CustomEvent;
}(window.CustomEvent));

var hasBubbleOnDetachedElements = (function () {
  var parent = document.createElement('div');
  var child = document.createElement('div');
  var hasBubbleOnDetachedElements = false;
  parent.appendChild(child);
  parent.addEventListener('test', () => hasBubbleOnDetachedElements = true);
  child.dispatchEvent(createCustomEvent('test', { bubbles: true }));
  return hasBubbleOnDetachedElements;
}());

function createCustomEvent (name, opts = {}) {
  if (CustomEvent) {
    return new CustomEvent(name, opts);
  }

  var e = document.createEvent('CustomEvent');
  e.initCustomEvent(name, opts.bubbles, opts.cancelable, opts.detail);
  return e;
}

function createReadableStopPropagation (oldStopPropagation) {
  return function () {
    this.isPropagationStopped = true;
    oldStopPropagation.call(this);
  };
}

function simulateBubbling (elem, cEvent) {
  var didPreventDefault;
  cEvent.stopPropagation = createReadableStopPropagation(cEvent.stopPropagation);
  while (elem && !cEvent.isPropagationStopped) {
    cEvent.currentTarget = elem;
    if (elem.dispatchEvent(cEvent) === false) {
      didPreventDefault = false;
    }
    elem = elem.parentNode;
  }
  return didPreventDefault;
}

function emitOne (elem, name, opts) {
  var cEvent, shouldSimulateBubbling;

  /* jshint expr: true */
  opts.bubbles === undefined && (opts.bubbles = true);
  opts.cancelable === undefined && (opts.cancelable = true);
  cEvent = createCustomEvent(name, opts);
  shouldSimulateBubbling = opts.bubbles &&
    !hasBubbleOnDetachedElements &&
    !utilElementContains(document, elem);

  return shouldSimulateBubbling ?
    simulateBubbling(elem, cEvent) :
    elem.dispatchEvent(cEvent);
}

export default function (elem, name, opts = {}) {
  var names = (typeof name === 'string' ? name.split(' ') : name);
  return names.reduce(function (prev, curr) {
    if (emitOne(elem, curr, opts) === false) {
      prev.push(curr);
    }
    return prev;
  }, []);
}
<commit_msg>When using skate.fragment() and not using the fixture in the events test, it caused simulated bubbling to happen which broke in Safari. Updating the simulation to always set the target to the original element fixes this.<commit_after>import utilElementContains from '../util/element-contains';

var CustomEvent = (function (CustomEvent) {
  if (CustomEvent) {
    try {
      new CustomEvent();
    } catch (e) {
      return undefined;
    }
  }
  return CustomEvent;
}(window.CustomEvent));

var hasBubbleOnDetachedElements = (function () {
  var parent = document.createElement('div');
  var child = document.createElement('div');
  var hasBubbleOnDetachedElements = false;
  parent.appendChild(child);
  parent.addEventListener('test', () => hasBubbleOnDetachedElements = true);
  child.dispatchEvent(createCustomEvent('test', { bubbles: true }));
  return hasBubbleOnDetachedElements;
}());

function createCustomEvent (name, opts = {}) {
  if (CustomEvent) {
    return new CustomEvent(name, opts);
  }

  var e = document.createEvent('CustomEvent');
  e.initCustomEvent(name, opts.bubbles, opts.cancelable, opts.detail);
  return e;
}

function createReadableStopPropagation (oldStopPropagation) {
  return function () {
    this.isPropagationStopped = true;
    oldStopPropagation.call(this);
  };
}

function simulateBubbling (elem, cEvent) {
  let didPreventDefault;
  let currentElem = elem;
  cEvent.stopPropagation = createReadableStopPropagation(cEvent.stopPropagation);
  Object.defineProperty(cEvent, 'target', { value: elem });
  while (currentElem && !cEvent.isPropagationStopped) {
    cEvent.currentTarget = currentElem;
    if (currentElem.dispatchEvent(cEvent) === false) {
      didPreventDefault = false;
    }
    currentElem = currentElem.parentNode;
  }
  return didPreventDefault;
}

function emitOne (elem, name, opts) {
  var cEvent, shouldSimulateBubbling;

  /* jshint expr: true */
  opts.bubbles === undefined && (opts.bubbles = true);
  opts.cancelable === undefined && (opts.cancelable = true);
  cEvent = createCustomEvent(name, opts);
  shouldSimulateBubbling = opts.bubbles &&
    !hasBubbleOnDetachedElements &&
    !utilElementContains(document, elem);

  return shouldSimulateBubbling ?
    simulateBubbling(elem, cEvent) :
    elem.dispatchEvent(cEvent);
}

export default function (elem, name, opts = {}) {
  var names = (typeof name === 'string' ? name.split(' ') : name);
  return names.reduce(function (prev, curr) {
    if (emitOne(elem, curr, opts) === false) {
      prev.push(curr);
    }
    return prev;
  }, []);
}
<|endoftext|>


<commit_before>
// This converts a HTTP/1 Request to HTTP/2 headers object
module.exports = function(request) {
	// Assume anything that doesn't look like an IncomingMessage is already
	// an HTTP/2 headers object
	if(!isIncomingMessage(request)) {
		return request;
	}

	var headers = Object.create(null);
	Object.assign(headers, request.headers);
	headers[":method"] = request.method;
	headers[":path"] = request.url || "";
	headers[":scheme"] = request.protocol;

	if(request.get) {
		headers[":authority"] = request.get("host");
	} else {
		headers[":authority"] = request.headers.host;
	}

	// Override one more time.
	Object.assign(headers, request.headers);

	return headers;
};

// An IncomingMessage always has a `.headers` property.
function isIncomingMessage(request) {
	return !!request.headers;
}
<commit_msg>Default to http for the protocol<commit_after>
// This converts a HTTP/1 Request to HTTP/2 headers object
module.exports = function(request) {
	// Assume anything that doesn't look like an IncomingMessage is already
	// an HTTP/2 headers object
	if(!isIncomingMessage(request)) {
		return request;
	}

	var headers = Object.create(null);
	Object.assign(headers, request.headers);
	headers[":method"] = request.method;
	headers[":path"] = request.url || "";
	headers[":scheme"] = request.protocol || "http";

	if(request.get) {
		headers[":authority"] = request.get("host");
	} else {
		headers[":authority"] = request.headers.host;
	}

	// Override one more time.
	Object.assign(headers, request.headers);

	return headers;
};

// An IncomingMessage always has a `.headers` property.
function isIncomingMessage(request) {
	return !!request.headers;
}
<|endoftext|>


<commit_before>const promiseQueue = require('./promise-queue');
const curryOptions = require('./curry-options');

const promiseLense = ({parallelism, progress}) => {
  const getChannel = promiseQueue({
    parallelism: Math.max(1, parallelism || 8)
  });

  const factory = (labels = []) => {
    const enqueue = getChannel(labels.join('|'));

    let self = {};
    let total = 0;
    let completed = 0;

    const toString = () =>
      `(${completed}/${total}) ${labels.join(' / ')}`;

    const info = () => ({
      labels: labels.concat(),
      completed,
      total,
      toString
    });

    const create = (label = '*') => {
      total++;
      if (labels.length && progress) {
        progress(info());
      }

      const onComplete = (v) => {
        completed++;
        if (labels.length && progress) {
          progress(info());
        }
        return v;
      };

      const child = (label === '*') ? self : factory(labels.concat(label));

      return {onComplete, child};
    };

    const lens = curryOptions(({from = '*', to = from, label = to}) => {
      const isSelector = (value) =>
        ((typeof value === 'string') && (value !== '*'));

      const getter = (hash) =>
        (isSelector(from) ? hash[from] : hash);

      const setter = (existing) => (value) =>
        ((typeof value === 'undefined') ?
          existing :
          Object.assign({}, existing, isSelector(to) ? {[to]: value} : value));

      return (fn) => (args, context = self) => {
        const {onComplete, child} = context.create(label);

        return Promise.resolve(getter(args))
          .then((v) => fn(v, child))
          .then(setter(args))
          .then(onComplete);
      };
    });

    const all = (list, fn) =>
      Promise.all(list.map((v) =>
        enqueue(() => fn(v))
          .then(create().onComplete)
      ));

    const map = (fn) => (list, context = self) =>
      context.all(list, (v) => fn(v, context));

    const merge = (...fns) => (args, context = self) => {
      const reduceObject = (reduced1, obj = {}, i) => Object.keys(obj)
        .filter((k) => (i === 0) || ((obj[k] !== args[k]) && (obj[k] !== reduced1[k])))
        .reduce((reduced2, k) => Object.assign(reduced2, {[k]: obj[k]}), reduced1);

      return context.all(fns, (fn) => fn(args, context))
        .then((results) => [args].concat(results).reduce(reduceObject, {}));
    };

    self = {create, lens, merge, map, all, toString, info};
    return self;
  };

  return factory();
};

module.exports = promiseLense;
<commit_msg>fix merge of arrays<commit_after>const promiseQueue = require('./promise-queue');
const curryOptions = require('./curry-options');

const promiseLense = ({parallelism, progress}) => {
  const getChannel = promiseQueue({
    parallelism: Math.max(1, parallelism || 8)
  });

  const factory = (labels = []) => {
    const enqueue = getChannel(labels.join('|'));

    let self = {};
    let total = 0;
    let completed = 0;

    const toString = () =>
      `(${completed}/${total}) ${labels.join(' / ')}`;

    const info = () => ({
      labels: labels.concat(),
      completed,
      total,
      toString
    });

    const create = (label = '*') => {
      total++;
      if (labels.length && progress) {
        progress(info());
      }

      const onComplete = (v) => {
        completed++;
        if (labels.length && progress) {
          progress(info());
        }
        return v;
      };

      const child = (label === '*') ? self : factory(labels.concat(label));

      return {onComplete, child};
    };

    const lens = curryOptions(({from = '*', to = from, label = to}) => {
      const isSelector = (value) =>
        ((typeof value === 'string') && (value !== '*'));

      const getter = (hash) =>
        (isSelector(from) ? hash[from] : hash);

      const setter = (existing) => (value) =>
        ((typeof value === 'undefined') ?
          existing :
          Object.assign({}, existing, isSelector(to) ? {[to]: value} : value));

      return (fn) => (args, context = self) => {
        const {onComplete, child} = context.create(label);

        return Promise.resolve(getter(args))
          .then((v) => fn(v, child))
          .then(setter(args))
          .then(onComplete);
      };
    });

    const all = (list, fn) =>
      Promise.all(list.map((v) =>
        enqueue(() => fn(v))
          .then(create().onComplete)
      ));

    const map = (fn) => (list, context = self) =>
      context.all(list, (v) => fn(v, context));

    const merge = (...fns) => (args, context = self) => {
      const mergeObjects = (reduced1, obj = {}) =>
        Object.keys(obj)
          .filter((k) => (obj[k] !== args[k]) && (obj[k] !== reduced1[k]))
          .reduce((reduced2, k) => Object.assign(reduced2, {
            [k]: [reduced2[k], obj[k]].every(Array.isArray) ? reduced2[k].concat(obj[k]) : obj[k]
          }), reduced1);

      return context.all(fns, (fn) => fn(args, context))
        .then((results) => results.reduce(mergeObjects, {}))
        .then((merged) => Object.assign({}, args, merged));
    };

    self = {create, lens, merge, map, all, toString, info};
    return self;
  };

  return factory();
};

module.exports = promiseLense;
<|endoftext|>