<commit_before>/*
 * BreezeJS BreezeEvent class.
 * version: 1.0 Bete
 * Copyright © 2015 BreezeJS All rights reserved.
 * Released under the MIT license
 * https://github.com/51breeze/breezejs
 */
(function(window,undefined){

    /**
     * BreezeEvent Class
     * 事件对象,处理指定类型的事件分发。
     * @param src
     * @param props
     * @constructor
     */
    function BreezeEvent( src, props )
    {
        if ( !(this instanceof BreezeEvent) )
            return new BreezeEvent( src, props );
        this.type = src;
        if ( src && src.type )
        {
            this.originalEvent = src;
            this.type = src.type;
            this.isDefaultPrevented = src.defaultPrevented ||
                src.defaultPrevented === undefined && src.returnValue === false ?
                true : false;
        }
        if ( props )for(var i in props)
           this[i]=props[i];
    };

    BreezeEvent.prototype = {
        target:null,
        currentTarget:null,
        isDefaultPrevented: false,
        isPropagationStopped: false,
        isImmediatePropagationStopped:false,

        preventDefault: function()
        {
            var e = this.originalEvent;
            this.isDefaultPrevented = true;
            if ( e && e.preventDefault ) {
                e.preventDefault();
            } else {
                e.returnValue = false;
            }
        },

        stopPropagation: function()
        {
            var e = this.originalEvent;
            this.isPropagationStopped = true;
            if ( e && e.stopPropagation ) {
                // e.stopPropagation();
            }
        },

        stopImmediatePropagation: function()
        {
            var e = this.originalEvent;
            this.isImmediatePropagationStopped = true;
            this.isPropagationStopped = true;
            if ( e ) {
                !e.stopImmediatePropagation || e.stopImmediatePropagation();
                !e.stopPropagation ? e.cancelBubble=true : e.stopPropagation();
            }
        }
    };

    BreezeEvent.SUBMIT='submit';
    BreezeEvent.RESIZE='resize';
    BreezeEvent.SELECT='select';
    BreezeEvent.UNLOAD='unload';
    BreezeEvent.LOAD='load';
    BreezeEvent.READY_STATE_CHANGE='readystatechange';
    BreezeEvent.KEYPRESS='keypress';
    BreezeEvent.KEY_UP='keyup';
    BreezeEvent.KEY_DOWN='keydown';
    BreezeEvent.RESET='reset';
    BreezeEvent.FOCUS='focus';
    BreezeEvent.BLUR='blur';
    BreezeEvent.ERROR='error';
    BreezeEvent.COPY='copy';
    BreezeEvent.BEFORECOPY='beforecopy';
    BreezeEvent.CUT='cut';
    BreezeEvent.BEFORECUT='beforecut';
    BreezeEvent.PASTE='paste';
    BreezeEvent.BEFOREPASTE='beforepaste';
    BreezeEvent.SELECTSTART='selectstart';
    BreezeEvent.READY='ready';
    BreezeEvent.SCROLL='scroll';

    /**
     * ElementEvent
     * @param src
     * @param props
     * @constructor
     */
    function ElementEvent( src, props ){ BreezeEvent.call(this, src, props);}
    ElementEvent.prototype=new BreezeEvent();
    ElementEvent.prototype.parent=null;
    ElementEvent.prototype.constructor=ElementEvent;
    ElementEvent.ADDED='added';
    ElementEvent.REMOVED='removed';
    ElementEvent.BEFORE_ADD='beforeadd';
    ElementEvent.BEFORE_REMOVE='beforeremove';

    /**
     * PropertyEvent
     * @param src
     * @param props
     * @constructor
     */
    function PropertyEvent( src, props ){ BreezeEvent.call(this, src, props);}
    PropertyEvent.prototype=new BreezeEvent();
    PropertyEvent.prototype.property=null;
    PropertyEvent.prototype.newValue=null;
    PropertyEvent.prototype.oldValue=null;
    PropertyEvent.prototype.constructor=PropertyEvent;
    PropertyEvent.PROPERTY_CHANGE='propertychange';
    PropertyEvent.PROPERTY_COMMIT='propertycommit';
    PropertyEvent.PROPERTY_STYLE_CHANGE='propertystylechange';

    /**
     * MouseEvent
     * @param src
     * @param props
     * @constructor
     */
    function MouseEvent( src, props ){ BreezeEvent.call(this, src, props);}
    MouseEvent.prototype=new BreezeEvent();
    MouseEvent.prototype.constructor=MouseEvent;
    MouseEvent.prototype.pageX= NaN
    MouseEvent.prototype.pageY= NaN
    MouseEvent.prototype.offsetX=NaN
    MouseEvent.prototype.offsetY=NaN;
    MouseEvent.prototype.screenX= NaN;
    MouseEvent.prototype.screenY= NaN;
    MouseEvent.MOUSE_DOWN='mousedown';
    MouseEvent.MOUSE_UP='mouseup';
    MouseEvent.MOUSE_OVER='mouseover';
    MouseEvent.MOUSE_OUT='mouseout';
    MouseEvent.MOUSE_MOVE='mousemove';
    MouseEvent.CLICK='click';
    MouseEvent.DBLCLICK='dblclick';

    function HttpEvent( src, props ){ BreezeEvent.call(this, src, props);}
    HttpEvent.prototype=new BreezeEvent();
    HttpEvent.prototype.data=null;
    HttpEvent.SUCCESS = 'success';
    HttpEvent.ERROR   = 'error';
    HttpEvent.CANCEL  = 'cancel';
    HttpEvent.TIMEOUT = 'timeout';
    HttpEvent.OPEN    = 'open';

    //除了不分发 timeout 状态的事件，其它的状态都发。这个事件最先调度。
    HttpEvent.DONE    = 'done';

    window.HttpEvent=HttpEvent;
    window.BreezeEvent=BreezeEvent;
    window.ElementEvent=ElementEvent;
    window.PropertyEvent=PropertyEvent;
    window.MouseEvent=MouseEvent;

})(window)<commit_msg>BreezeEvent<commit_after>/*
 * BreezeJS BreezeEvent class.
 * version: 1.0 Beta
 * Copyright © 2015 BreezeJS All rights reserved.
 * Released under the MIT license
 * https://github.com/51breeze/breezejs
 */
(function(window,undefined){

    /**
     * BreezeEvent Class
     * 事件对象,处理指定类型的事件分发。
     * @param src
     * @param props
     * @constructor
     */
    function BreezeEvent( src, props )
    {
        if ( !(this instanceof BreezeEvent) )
            return new BreezeEvent( src, props );
        this.type = src;
        if ( src && src.type )
        {
            this.originalEvent = src;
            this.type = src.type;
            this.isDefaultPrevented = src.defaultPrevented ||
                src.defaultPrevented === undefined && src.returnValue === false ?
                true : false;
        }
        if ( props )for(var i in props)
           this[i]=props[i];
    };

    BreezeEvent.prototype = {
        target:null,
        currentTarget:null,
        isDefaultPrevented: false,
        isPropagationStopped: false,
        isImmediatePropagationStopped:false,

        preventDefault: function()
        {
            var e = this.originalEvent;
            this.isDefaultPrevented = true;
            if ( e && e.preventDefault ) {
                e.preventDefault();
            } else {
                e.returnValue = false;
            }
        },

        stopPropagation: function()
        {
            var e = this.originalEvent;
            this.isPropagationStopped = true;
            if ( e && e.stopPropagation ) {
                // e.stopPropagation();
            }
        },

        stopImmediatePropagation: function()
        {
            var e = this.originalEvent;
            this.isImmediatePropagationStopped = true;
            this.isPropagationStopped = true;
            if ( e ) {
                !e.stopImmediatePropagation || e.stopImmediatePropagation();
                !e.stopPropagation ? e.cancelBubble=true : e.stopPropagation();
            }
        }
    };

    BreezeEvent.SUBMIT='submit';
    BreezeEvent.RESIZE='resize';
    BreezeEvent.SELECT='select';
    BreezeEvent.UNLOAD='unload';
    BreezeEvent.LOAD='load';
    BreezeEvent.READY_STATE_CHANGE='readystatechange';
    BreezeEvent.KEYPRESS='keypress';
    BreezeEvent.KEY_UP='keyup';
    BreezeEvent.KEY_DOWN='keydown';
    BreezeEvent.RESET='reset';
    BreezeEvent.FOCUS='focus';
    BreezeEvent.BLUR='blur';
    BreezeEvent.ERROR='error';
    BreezeEvent.COPY='copy';
    BreezeEvent.BEFORECOPY='beforecopy';
    BreezeEvent.CUT='cut';
    BreezeEvent.BEFORECUT='beforecut';
    BreezeEvent.PASTE='paste';
    BreezeEvent.BEFOREPASTE='beforepaste';
    BreezeEvent.SELECTSTART='selectstart';
    BreezeEvent.READY='ready';
    BreezeEvent.SCROLL='scroll';

    /**
     * ElementEvent
     * @param src
     * @param props
     * @constructor
     */
    function ElementEvent( src, props ){ BreezeEvent.call(this, src, props);}
    ElementEvent.prototype=new BreezeEvent();
    ElementEvent.prototype.parent=null;
    ElementEvent.prototype.constructor=ElementEvent;
    ElementEvent.ADDED='added';
    ElementEvent.REMOVED='removed';
    ElementEvent.BEFORE_ADD='beforeadd';
    ElementEvent.BEFORE_REMOVE='beforeremove';

    /**
     * PropertyEvent
     * @param src
     * @param props
     * @constructor
     */
    function PropertyEvent( src, props ){ BreezeEvent.call(this, src, props);}
    PropertyEvent.prototype=new BreezeEvent();
    PropertyEvent.prototype.property=null;
    PropertyEvent.prototype.newValue=null;
    PropertyEvent.prototype.oldValue=null;
    PropertyEvent.prototype.constructor=PropertyEvent;
    PropertyEvent.PROPERTY_CHANGE='propertychange';
    PropertyEvent.PROPERTY_COMMIT='propertycommit';
    PropertyEvent.PROPERTY_STYLE_CHANGE='propertystylechange';

    /**
     * MouseEvent
     * @param src
     * @param props
     * @constructor
     */
    function MouseEvent( src, props ){ BreezeEvent.call(this, src, props);}
    MouseEvent.prototype=new BreezeEvent();
    MouseEvent.prototype.constructor=MouseEvent;
    MouseEvent.prototype.pageX= NaN
    MouseEvent.prototype.pageY= NaN
    MouseEvent.prototype.offsetX=NaN
    MouseEvent.prototype.offsetY=NaN;
    MouseEvent.prototype.screenX= NaN;
    MouseEvent.prototype.screenY= NaN;
    MouseEvent.MOUSE_DOWN='mousedown';
    MouseEvent.MOUSE_UP='mouseup';
    MouseEvent.MOUSE_OVER='mouseover';
    MouseEvent.MOUSE_OUT='mouseout';
    MouseEvent.MOUSE_MOVE='mousemove';
    MouseEvent.CLICK='click';
    MouseEvent.DBLCLICK='dblclick';

    function HttpEvent( src, props ){ BreezeEvent.call(this, src, props);}
    HttpEvent.prototype=new BreezeEvent();
    HttpEvent.prototype.data=null;
    HttpEvent.SUCCESS = 'success';
    HttpEvent.ERROR   = 'error';
    HttpEvent.CANCEL  = 'cancel';
    HttpEvent.TIMEOUT = 'timeout';
    HttpEvent.OPEN    = 'open';

    //除了不分发 timeout 状态的事件，其它的状态都发。这个事件最先调度。
    HttpEvent.DONE    = 'done';

    window.HttpEvent=HttpEvent;
    window.BreezeEvent=BreezeEvent;
    window.ElementEvent=ElementEvent;
    window.PropertyEvent=PropertyEvent;
    window.MouseEvent=MouseEvent;

})(window)<|endoftext|>


<commit_before>(function() {
    /**
     * Navigation Controller
     * @param $scope
     * @param $location
     * @constructor
     */
    var NavController = function($scope, $location) {
        $scope.isActive = function (viewLocation) {
            return viewLocation === $location.path();
        };
    };
    angular.module('App').controller('NavController', ['$scope', '$location', NavController]);

    /**
     * Main Controller
     * @param $scope
     * @param $location
     * @constructor
     */
    var MainController = function($routeParams, mainFactory) {
        mainFactory.useTestData = $routeParams['debug'] === 'true';
    };
    angular.module('App').controller('MainController', ['$routeParams', 'mainFactory', MainController]);

    /**
     * Search Controller
     * @param $scope
     * @constructor
     */
    var SearchController = function($scope, $rootScope, searchFactory) {
        $scope.tabs = searchFactory.tabs;

        $scope.populate = function (tab_name) {
            switch (tab_name) {
                case $scope.tabs[0].name:
                    searchFactory.getDrugs()
                        .then(function (results) {
                            $scope.drug_list = results
                        }, function (error) {
                            // TODO show alert
                            console.log("got an error, ", error)
                        });
                    break;
                case $scope.tabs[1].name:
                    searchFactory.getStates()
                        .then(function (results) {
                            $scope.state_list = results
                            $scope.selected_state = results[0].name
                        }, function (error) {
                            // TODO show alert
                            console.log("got an error, ", error)
                        });
                    break;
                case $scope.tabs[2].name:
                    searchFactory.getManufacturers()
                        .then(function (results) {
                            $scope.maker_list = results
                        }, function (error) {
                            // TODO show alert
                            console.log("got an error, ", error)
                        });
                    break;
                default:
                    break;
            }
        };

        $scope.dropdown = {
            isopen : false
        };

        $scope.toggleDropdown = function() {
            $scope.dropdown.isopen = this.search.drug_name.length
        };

        $scope.toggleMakerDropdown = function() {
            $scope.dropdown.isopen = this.search.maker_name.length
        };

        $scope.reset = function() {
            $rootScope.$broadcast('reset-update', [])
        };

        $scope.getDrugData = function(drug) {
            this.search.drug_name = drug
            searchFactory.getDrugLabelInfo(drug)
                .then( function( data ) {
                    $scope.selected_drug = drug;
                    setLabelInfo( data.results[0] )
                }, function( error ) {
                    console.log("got an error: ", error);
                    $scope.selected_drug = null
                });
            searchFactory.getDrugRecallInfo(drug)
                .then( function( data ) {
                    setRecallInfo( data.results )
                }, function( error ) {
                    console.log("got an error: ", error);
                    $scope.selected_drug = null
                });
        };

        $scope.getManufacturerData = function(maker) {
            searchFactory.getManufacturerInfo(maker)
                .then( function( data ) {
                    $scope.selected_maker = maker;
                    setManufacturerInfo( data )
                }, function( error ) {
                    console.log("got an error: ", error);
                    $scope.selected_maker = null
                });
        };

        $scope.update = function(state){
            $rootScope.$broadcast('state-update', state)
        };

        function setLabelInfo( info ){
            if( info.purpose ){
                $scope.selected_drug_purpose = info.purpose[0].replace("PURPOSES ", "")
            }
            $scope.selected_drug_usage = info.indications_and_usage[0].replace("USES ", "")
            $scope.manufacturer_name = info.openfda.manufacturer_name[0]

            var length = info.openfda.substance_name.length;
            var active_ingredients= [];
            for(var i= 0; i<length; i++){
                active_ingredients.push({name: info.openfda.substance_name[i]})
            }
            $scope.active_ingredients = active_ingredients
        }

        function setRecallInfo( results ){
            var length = results.length
            // fix the dates
            var regions = []
            for(var i= 0; i<length; i++){
                var date = results[i].recall_initiation_date;
                results[i].recall_initiation_date = new Date(date.substring(0,4), date.substring(4,6), date.substring(6,8)).toDateString();
                // grab all recall areas
                for( var j=0; j< results[i].recall_area.length; j++ ) {
                    regions.push( results[i].recall_area[j])
                }
            }
            // helper method
            function contains(a, obj) {
                for (var i = 0; i < a.length; i++) {
                    if (a[i] === obj) { return true; }
                }
                return false;
            }
            console.log(regions)
            if( contains(regions, "Nationwide") ) {
                regions = ["Nationwide"]
            } else {
                // remove duplicates by sorting and checking repeated regions
                regions = regions.sort().filter(function(item, pos, ary) {
                    return !pos || item != ary[pos - 1];
                });
            }
            console.log(regions)
            $rootScope.$broadcast('drug-update', regions)
            $scope.recalls = results
        }

        function setManufacturerInfo( response ){
            $scope.manufacturer_city = response.city
            $scope.manufacturer_state = response.state
            var drug_length = response.brand_names.length;
            $scope.maker_drug_recalls = [];
            for(var i= 0; i<drug_length; i++){
                $scope.maker_drug_recalls.push({name: response.brand_names[i]})
            }
            $rootScope.$broadcast('length-update', ($scope.maker_drug_recalls).length)

            var state_length = response.results.length;
            var maker_state_recalls = [];
            $scope.manufacturer_count = 0;
            for(var j= 0; j<state_length; j++){
                maker_state_recalls.push(response.results[j].state)
                $scope.manufacturer_count = response.results[j].count + $scope.manufacturer_count
            }
            // helper method
            function contains(a, obj) {
                for (var i = 0; i < a.length; i++) {
                    if (a[i] === obj) { return true; }
                }
                return false;
            }
            if( contains(maker_state_recalls, "Nationwide") ) {
                maker_state_recalls = ["Nationwide"]
            } else {
                // remove duplicates by sorting and checking repeated regions
                maker_state_recalls = maker_state_recalls.sort().filter(function(item, pos, ary) {
                    return !pos || item != ary[pos - 1];
                });
            }

            $rootScope.$broadcast('manufacturer-update', maker_state_recalls)
            $scope.manufacturer_states = maker_state_recalls
        }

    };
    angular.module('App').controller('SearchController', ['$scope', '$rootScope', 'searchFactory', SearchController]);

    /**
     * Map Controller
     * @param $scope
     * @constructor
     */

    var MapController = function($scope, $http, $rootScope, mapFactory, mainFactory) {
        var type = false;

        angular.extend($scope, {
            center: {
                lat: 39,
                lng: -100,
                zoom: 4
            }
        });

        $scope.$on('drug-update', function(event, args) {
            var all_locations = [];
            $http.get("data/us-states.json").success(function(response, status) {
                state_location = response.features
                recall_location = args
                    angular.forEach(recall_location, function (recall_locale) {
                        angular.forEach(state_location, function (state_locale) {
                            if (recall_locale == state_locale.properties.name || recall_locale == "Nationwide") {
                                all_locations.push(state_locale);
                            }
                        });
                    });
            });
            angular.extend($scope, {
                geojson: {
                    data: all_locations,
                    style: {
                        fillColor: "orange",
                        weight: 1,
                        opacity: 1,
                        color: 'white',
                        dashArray: '3',
                        fillOpacity: 0.7
                    }
                }
            });
        });

        $scope.$on('manufacturer-update', function(event, args) {
            var maker_locations = [];
            $http.get("data/us-states.json").success(function(response, status) {
                state_location = response.features
                recall_location = args
                angular.forEach(recall_location, function (recall_locale) {
                    angular.forEach(state_location, function (state_locale) {
                        if (recall_locale == state_locale.properties.name || recall_locale == "Nationwide") {
                            maker_locations.push(state_locale);
                        }
                    });
                });
            });

            angular.extend($scope, {
                geojson: {
                    data: maker_locations,
                    style: {
                        fillColor: "purple",
                        weight: 1,
                        opacity: 1,
                        color: 'white',
                        dashArray: '3',
                        fillOpacity: 0.7
                    }
                }
            });

        });

        $scope.$on('reset-update', function(event, args) {
             angular.extend($scope, {
                geojson: {
                    data: args
                }
            });

        });

        $scope.$on('state-update', function(event, args) {
            selected_state = args;

            $rootScope.all_drugs = []

            mapFactory.getRecallsByState("Nationwide")
                .then(function (results) {
                    angular.forEach(results, function(drug_name){
                        $rootScope.all_drugs.push(drug_name);
                    });
                }, function (error) {
                    // TODO show alert
                    console.log("got an error, ", error)
                });

            mapFactory.getRecallsByState(selected_state)
                .then(function (results) {
                    angular.forEach(results, function(drug_name){
                        $rootScope.all_drugs.push(drug_name);
                    });
                    $rootScope.$broadcast('length-update', ($rootScope.all_drugs).length)
                }, function (error) {
                    // TODO show alert
                    console.log("got an error, ", error)
                });

            var one_location = []
            $http.get("data/us-states.json").success(function (response, status) {
                state_location = response.features
                angular.forEach(state_location, function (state_locale) {
                    if (state_locale.properties.name == selected_state) {
                        one_location.push(state_locale)
                    }
                });
            });

            angular.extend($scope, {
                geojson: {
                    data: one_location,
                    style: {
                        fillColor: "red",
                        weight: 1,
                        opacity: 1,
                        color: 'white',
                        dashArray: '3',
                        fillOpacity: 0.7
                    }
                }
            });
        });

    };
    angular.module('App').controller('MapController', ["$scope", "$http", "$rootScope", "mapFactory", "mainFactory", MapController]);

    angular.module('App').controller('PaginationCtrl', function ($scope, $rootScope, $log) {

        $scope.$on('length-update', function(event, args){
            $scope.totalItems = args
        });

        $scope.currentPage = 1
        $scope.itemsPerPage = 3
        $scope.maxSize = 5

        $scope.setPage = function (pageNo) {
            $scope.currentPage = pageNo
        };

        $scope.pageChanged = function() {
            $log.log('Page changed to: ' + $scope.currentPage)
        };

    });

}());<commit_msg>Set input name in manufacturer tab when selected. Fixed default select for state search.<commit_after>(function() {
    /**
     * Navigation Controller
     * @param $scope
     * @param $location
     * @constructor
     */
    var NavController = function($scope, $location) {
        $scope.isActive = function (viewLocation) {
            return viewLocation === $location.path();
        };
    };
    angular.module('App').controller('NavController', ['$scope', '$location', NavController]);

    /**
     * Main Controller
     * @param $scope
     * @param $location
     * @constructor
     */
    var MainController = function($routeParams, mainFactory) {
        mainFactory.useTestData = $routeParams['debug'] === 'true';
    };
    angular.module('App').controller('MainController', ['$routeParams', 'mainFactory', MainController]);

    /**
     * Search Controller
     * @param $scope
     * @constructor
     */
    var SearchController = function($scope, $rootScope, searchFactory) {
        $scope.tabs = searchFactory.tabs;

        $scope.populate = function (tab_name) {
            switch (tab_name) {
                case $scope.tabs[0].name:
                    searchFactory.getDrugs()
                        .then(function (results) {
                            $scope.drug_list = results
                        }, function (error) {
                            // TODO show alert
                            console.log("got an error, ", error)
                        });
                    break;
                case $scope.tabs[1].name:
                    searchFactory.getStates()
                        .then(function (results) {
                            $scope.state_list = results
                        }, function (error) {
                            // TODO show alert
                            console.log("got an error, ", error)
                        });
                    break;
                case $scope.tabs[2].name:
                    searchFactory.getManufacturers()
                        .then(function (results) {
                            $scope.maker_list = results
                        }, function (error) {
                            // TODO show alert
                            console.log("got an error, ", error)
                        });
                    break;
                default:
                    break;
            }
        };

        $scope.dropdown = {
            isopen : false
        };

        $scope.toggleDropdown = function() {
            $scope.dropdown.isopen = this.search.drug_name.length
        };

        $scope.toggleMakerDropdown = function() {
            $scope.dropdown.isopen = this.search.maker_name.length
        };

        $scope.reset = function() {
            $rootScope.$broadcast('reset-update', [])
        };

        $scope.getDrugData = function(drug) {
            this.search.drug_name = drug
            searchFactory.getDrugLabelInfo(drug)
                .then( function( data ) {
                    $scope.selected_drug = drug;
                    setLabelInfo( data.results[0] )
                }, function( error ) {
                    console.log("got an error: ", error);
                    $scope.selected_drug = null
                });
            searchFactory.getDrugRecallInfo(drug)
                .then( function( data ) {
                    setRecallInfo( data.results )
                }, function( error ) {
                    console.log("got an error: ", error);
                    $scope.selected_drug = null
                });
        };

        $scope.getManufacturerData = function(maker) {
            this.search.maker_name = maker
            searchFactory.getManufacturerInfo(maker)
                .then( function( data ) {
                    $scope.selected_maker = maker;
                    setManufacturerInfo( data )
                }, function( error ) {
                    console.log("got an error: ", error);
                    $scope.selected_maker = null
                });
        };

        $scope.update = function(state){
            $rootScope.$broadcast('state-update', state)
        };

        function setLabelInfo( info ){
            if( info.purpose ){
                $scope.selected_drug_purpose = info.purpose[0].replace("PURPOSES ", "")
            }
            $scope.selected_drug_usage = info.indications_and_usage[0].replace("USES ", "")
            $scope.manufacturer_name = info.openfda.manufacturer_name[0]

            var length = info.openfda.substance_name.length;
            var active_ingredients= [];
            for(var i= 0; i<length; i++){
                active_ingredients.push({name: info.openfda.substance_name[i]})
            }
            $scope.active_ingredients = active_ingredients
        }

        function setRecallInfo( results ){
            var length = results.length
            // fix the dates
            var regions = []
            for(var i= 0; i<length; i++){
                var date = results[i].recall_initiation_date;
                results[i].recall_initiation_date = new Date(date.substring(0,4), date.substring(4,6), date.substring(6,8)).toDateString();
                // grab all recall areas
                for( var j=0; j< results[i].recall_area.length; j++ ) {
                    regions.push( results[i].recall_area[j])
                }
            }
            // helper method
            function contains(a, obj) {
                for (var i = 0; i < a.length; i++) {
                    if (a[i] === obj) { return true; }
                }
                return false;
            }
            console.log(regions)
            if( contains(regions, "Nationwide") ) {
                regions = ["Nationwide"]
            } else {
                // remove duplicates by sorting and checking repeated regions
                regions = regions.sort().filter(function(item, pos, ary) {
                    return !pos || item != ary[pos - 1];
                });
            }
            console.log(regions)
            $rootScope.$broadcast('drug-update', regions)
            $scope.recalls = results
        }

        function setManufacturerInfo( response ){
            $scope.manufacturer_city = response.city
            $scope.manufacturer_state = response.state
            var drug_length = response.brand_names.length;
            $scope.maker_drug_recalls = [];
            for(var i= 0; i<drug_length; i++){
                $scope.maker_drug_recalls.push({name: response.brand_names[i]})
            }
            $rootScope.$broadcast('length-update', ($scope.maker_drug_recalls).length)

            var state_length = response.results.length;
            var maker_state_recalls = [];
            $scope.manufacturer_count = 0;
            for(var j= 0; j<state_length; j++){
                maker_state_recalls.push(response.results[j].state)
                $scope.manufacturer_count = response.results[j].count + $scope.manufacturer_count
            }
            // helper method
            function contains(a, obj) {
                for (var i = 0; i < a.length; i++) {
                    if (a[i] === obj) { return true; }
                }
                return false;
            }
            if( contains(maker_state_recalls, "Nationwide") ) {
                maker_state_recalls = ["Nationwide"]
            } else {
                // remove duplicates by sorting and checking repeated regions
                maker_state_recalls = maker_state_recalls.sort().filter(function(item, pos, ary) {
                    return !pos || item != ary[pos - 1];
                });
            }

            $rootScope.$broadcast('manufacturer-update', maker_state_recalls)
            $scope.manufacturer_states = maker_state_recalls
        }

    };
    angular.module('App').controller('SearchController', ['$scope', '$rootScope', 'searchFactory', SearchController]);

    /**
     * Map Controller
     * @param $scope
     * @constructor
     */

    var MapController = function($scope, $http, $rootScope, mapFactory) {
        var type = false;

        angular.extend($scope, {
            center: {
                lat: 39,
                lng: -100,
                zoom: 4
            }
        });

        $scope.$on('drug-update', function(event, args) {
            var all_locations = [];
            $http.get("data/us-states.json").success(function(response, status) {
                state_location = response.features
                recall_location = args
                    angular.forEach(recall_location, function (recall_locale) {
                        angular.forEach(state_location, function (state_locale) {
                            if (recall_locale == state_locale.properties.name || recall_locale == "Nationwide") {
                                all_locations.push(state_locale);
                            }
                        });
                    });
            });
            angular.extend($scope, {
                geojson: {
                    data: all_locations,
                    style: {
                        fillColor: "orange",
                        weight: 1,
                        opacity: 1,
                        color: 'white',
                        dashArray: '3',
                        fillOpacity: 0.7
                    }
                }
            });
        });

        $scope.$on('manufacturer-update', function(event, args) {
            var maker_locations = [];
            $http.get("data/us-states.json").success(function(response, status) {
                state_location = response.features
                recall_location = args
                angular.forEach(recall_location, function (recall_locale) {
                    angular.forEach(state_location, function (state_locale) {
                        if (recall_locale == state_locale.properties.name || recall_locale == "Nationwide") {
                            maker_locations.push(state_locale);
                        }
                    });
                });
            });

            angular.extend($scope, {
                geojson: {
                    data: maker_locations,
                    style: {
                        fillColor: "purple",
                        weight: 1,
                        opacity: 1,
                        color: 'white',
                        dashArray: '3',
                        fillOpacity: 0.7
                    }
                }
            });

        });

        $scope.$on('reset-update', function(event, args) {
             angular.extend($scope, {
                geojson: {
                    data: args
                }
            });

        });

        $scope.$on('state-update', function(event, args) {
            selected_state = args;

            $rootScope.all_drugs = []

            mapFactory.getRecallsByState("Nationwide")
                .then(function (results) {
                    angular.forEach(results, function(drug_name){
                        $rootScope.all_drugs.push(drug_name);
                    });
                }, function (error) {
                    // TODO show alert
                    console.log("got an error, ", error)
                });

            mapFactory.getRecallsByState(selected_state)
                .then(function (results) {
                    angular.forEach(results, function(drug_name){
                        $rootScope.all_drugs.push(drug_name);
                    });
                    $rootScope.$broadcast('length-update', ($rootScope.all_drugs).length)
                }, function (error) {
                    // TODO show alert
                    console.log("got an error, ", error)
                });

            var one_location = []
            $http.get("data/us-states.json").success(function (response, status) {
                state_location = response.features
                angular.forEach(state_location, function (state_locale) {
                    if (state_locale.properties.name == selected_state) {
                        one_location.push(state_locale)
                    }
                });
            });

            angular.extend($scope, {
                geojson: {
                    data: one_location,
                    style: {
                        fillColor: "red",
                        weight: 1,
                        opacity: 1,
                        color: 'white',
                        dashArray: '3',
                        fillOpacity: 0.7
                    }
                }
            });
        });

    };
    angular.module('App').controller('MapController', ["$scope", "$http", "$rootScope", "mapFactory", MapController]);

    angular.module('App').controller('PaginationCtrl', function ($scope, $rootScope, $log) {

        $scope.$on('length-update', function(event, args){
            $scope.totalItems = args
        });

        $scope.currentPage = 1
        $scope.itemsPerPage = 3
        $scope.maxSize = 5

        $scope.setPage = function (pageNo) {
            $scope.currentPage = pageNo
        };

        $scope.pageChanged = function() {
            $log.log('Page changed to: ' + $scope.currentPage)
        };

    });

}());<|endoftext|>


<commit_before>var webpack = require('webpack');
var path = require('path');
var fs = require('fs');

var SaveAssetsJson = require('assets-webpack-plugin');

var addons = require('./addons.json');
var root = path.join(__dirname, 'website', 'static');
/** Return the absolute path given a path relative to ./website/static */
var staticPath = function(dir) {
    return path.join(root, dir);
};
var nodePath = function(dir) {
    return path.join(__dirname, 'node_modules', dir);
};
var addonsPath = function(dir) {
    return path.join(__dirname, 'website', 'addons', dir);
};

/**
 * Each JS module for a page on the OSF is webpack entry point. These are built
 * to website/static/public/
 */
var entry = {
    // JS
    'base-page': staticPath('js/pages/base-page.js'),
    'home-page': staticPath('js/pages/home-page.js'),
    'dashboard-page': staticPath('js/pages/dashboard-page.js'),
    'profile-page': staticPath('js/pages/profile-page.js'),
    'project-dashboard': staticPath('js/pages/project-dashboard-page.js'),
    'project-base-page': staticPath('js/pages/project-base-page.js'),
    'wiki-edit-page': staticPath('js/pages/wiki-edit-page.js'),
    'files-page': staticPath('js/pages/files-page.js'),
    'profile-settings-page': staticPath('js/pages/profile-settings-page.js'),
    'profile-account-settings-page': staticPath('js/pages/profile-account-settings-page.js'),
    'register_1-page': staticPath('js/pages/register_1-page.js'),
    'sharing-page': staticPath('js/pages/sharing-page.js'),
    'conference-page': staticPath('js/pages/conference-page.js'),
    'view-file-page': staticPath('js/pages/view-file-page.js'),
    'view-file-tree-page': staticPath('js/pages/view-file-tree-page.js'),
    'new-folder-page': staticPath('js/pages/new-folder-page.js'),
    'project-settings-page': staticPath('js/pages/project-settings-page.js'),
    'search-page': staticPath('js/pages/search-page.js'),
    'share-search-page': staticPath('js/pages/share-search-page.js'),
    'profile-settings-addons-page': staticPath('js/pages/profile-settings-addons-page.js'),
    'twofactor-page': staticPath('js/pages/twofactor-page.js'),
    'forgotpassword-page': staticPath('js/pages/forgotpassword-page.js'),
    'login-page': staticPath('js/pages/login-page.js'),
    'notifications-config-page': staticPath('js/pages/notifications-config-page.js'),
    'share-embed-page': staticPath('js/pages/share-embed-page.js'),
    // Commons chunk
    'vendor': [
        // Vendor libraries
        'knockout',
        'knockout.validation',
        'knockout.punches',
        'moment',
        'bootstrap',
        'bootbox',
        'bootstrap-editable',
        'select2',
        'dropzone',
        'knockout-sortable',
        'treebeard',
        'jquery.cookie',
        'URIjs',
        // Common internal modules
        'js/fangorn',
        'js/citations',
        'js/osfHelpers'
    ]
};

// Collect adddons endpoints. If an addon's static folder has
// any of the following files, it will be added as an entry point
// and output to website/static/public/js/<addon-name>/files.js
var addonModules = ['files.js', 'node-cfg.js', 'user-cfg.js', 'file-detail.js', 'widget-cfg.js'];
addons.addons.forEach(function(addonName) {
    var baseDir = addonName + '/';
    addonModules.forEach(function(module) {
        var modulePath = path.join(__dirname, 'website', 'addons',
                                  addonName, 'static', module);
        if (fs.existsSync(modulePath)) {
            var entryPoint = baseDir + module.split('.')[0];
            entry[entryPoint] =  modulePath;
        }
    });
});

var resolve = {
    extensions: ['', '.es6.js', '.js'],
    root: root,
    // Look for required files in bower and npm directories
    modulesDirectories: ['./website/static/vendor/bower_components', 'node_modules'],
    // Need to alias libraries that aren't managed by bower or npm
    alias: {
        'knockout-sortable': staticPath('vendor/knockout-sortable/knockout-sortable.js'),
        'bootstrap-editable': staticPath('vendor/bootstrap-editable-custom/js/bootstrap-editable.js'),
        'jquery-blockui': staticPath('vendor/jquery-blockui/jquery.blockui.js'),
        'bootstrap': staticPath('vendor/bower_components/bootstrap/dist/js/bootstrap.min.js'),
        'jquery-tagsinput': staticPath('vendor/bower_components/jquery.tagsinput/jquery.tagsinput.js'),
        'zeroclipboard': staticPath('vendor/bower_components/zeroclipboard/dist/ZeroClipboard.js'),
        'history': nodePath('historyjs/scripts/bundled/html4+html5/jquery.history.js'),
        // Needed for knockout-sortable
        'jquery.ui.sortable': staticPath('vendor/bower_components/jquery-ui/ui/jquery.ui.sortable.js'),
        'truncate': staticPath('vendor/bower_components/truncate/jquery.truncate.js'),
        // Needed for ace code editor in wiki
        'ace-noconflict': staticPath('vendor/bower_components/ace-builds/src-noconflict/ace.js'),
        'ace-ext-language_tools': staticPath('vendor/bower_components/ace-builds/src-noconflict/ext-language_tools.js'),
        'ace-mode-markdown': staticPath('vendor/bower_components/ace-builds/src-noconflict/mode-markdown.js'),
        'pagedown-ace-converter': addonsPath('wiki/static/pagedown-ace/Markdown.Converter.js'),
        'pagedown-ace-sanitizer': addonsPath('wiki/static/pagedown-ace/Markdown.Sanitizer.js'),
        'pagedown-ace-editor': addonsPath('wiki/static/pagedown-ace/Markdown.Editor.js'),
        'wikiPage': addonsPath('wiki/static/wikiPage.js'),
        'highlight-css': nodePath('highlight.js/styles/default.css'),
        // Also alias some internal libraries for easy access
        'addons': path.join(__dirname, 'website', 'addons'),
        'tests': staticPath('js/tests')
    }
};

var externals = {
    // require("jquery") is external and available
    //  on the global var jQuery, which is loaded with CDN
    'jquery': 'jQuery',
    'jquery-ui': 'jQuery.ui',
    'raven-js': 'Raven',
    'MathJax': 'MathJax'
};

var plugins = [
    // Bundle common code between modules
    new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.js'),
    // Bower support
    new webpack.ResolverPlugin(
        new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin('bower.json', ['main'])
    ),
    // Make jQuery available in all modules without having to do require('jquery')
    new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery'
    }),
    // Slight hack to make sure that CommonJS is always used
    new webpack.DefinePlugin({
        'define.amd': false
    }),
];

var output = {
    path: './website/static/public/js/',
    // publicPath: '/static/', // used to generate urls to e.g. images
    filename: '[name].js',
    sourcePrefix: ''
};

module.exports = {
    entry: entry,
    resolve: resolve,
    externals: externals,
    plugins: plugins,
    output: output,
    module: {
        loaders: [
            {test: /\.es6\.js$/, exclude: [/node_modules/, /bower_components/, /vendor/], loader: 'babel-loader'},
            {test: /\.css$/, loaders: ['style', 'css']},
            // url-loader uses DataUrls; files-loader emits files
            {test: /\.png$/, loader: 'url-loader?limit=100000&mimetype=image/ng'},
            {test: /\.gif$/, loader: 'url-loader?limit=10000&mimetype=image/gif'},
            {test: /\.jpg$/, loader: 'url-loader?limit=10000&mimetype=image/jpg'},
            {test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'url-loader?mimetype=application/font-woff'},
            {test: /\.svg/, loader: 'file-loader'},
            {test: /\.eot/, loader: 'file-loader'},
            {test: /\.ttf/, loader: 'file-loader'}
        ]
    }
};
<commit_msg>Add mithril to web pack vendor list [skip ci]<commit_after>var webpack = require('webpack');
var path = require('path');
var fs = require('fs');

var SaveAssetsJson = require('assets-webpack-plugin');

var addons = require('./addons.json');
var root = path.join(__dirname, 'website', 'static');
/** Return the absolute path given a path relative to ./website/static */
var staticPath = function(dir) {
    return path.join(root, dir);
};
var nodePath = function(dir) {
    return path.join(__dirname, 'node_modules', dir);
};
var addonsPath = function(dir) {
    return path.join(__dirname, 'website', 'addons', dir);
};

/**
 * Each JS module for a page on the OSF is webpack entry point. These are built
 * to website/static/public/
 */
var entry = {
    // JS
    'base-page': staticPath('js/pages/base-page.js'),
    'home-page': staticPath('js/pages/home-page.js'),
    'dashboard-page': staticPath('js/pages/dashboard-page.js'),
    'profile-page': staticPath('js/pages/profile-page.js'),
    'project-dashboard': staticPath('js/pages/project-dashboard-page.js'),
    'project-base-page': staticPath('js/pages/project-base-page.js'),
    'wiki-edit-page': staticPath('js/pages/wiki-edit-page.js'),
    'files-page': staticPath('js/pages/files-page.js'),
    'profile-settings-page': staticPath('js/pages/profile-settings-page.js'),
    'profile-account-settings-page': staticPath('js/pages/profile-account-settings-page.js'),
    'register_1-page': staticPath('js/pages/register_1-page.js'),
    'sharing-page': staticPath('js/pages/sharing-page.js'),
    'conference-page': staticPath('js/pages/conference-page.js'),
    'view-file-page': staticPath('js/pages/view-file-page.js'),
    'view-file-tree-page': staticPath('js/pages/view-file-tree-page.js'),
    'new-folder-page': staticPath('js/pages/new-folder-page.js'),
    'project-settings-page': staticPath('js/pages/project-settings-page.js'),
    'search-page': staticPath('js/pages/search-page.js'),
    'share-search-page': staticPath('js/pages/share-search-page.js'),
    'profile-settings-addons-page': staticPath('js/pages/profile-settings-addons-page.js'),
    'twofactor-page': staticPath('js/pages/twofactor-page.js'),
    'forgotpassword-page': staticPath('js/pages/forgotpassword-page.js'),
    'login-page': staticPath('js/pages/login-page.js'),
    'notifications-config-page': staticPath('js/pages/notifications-config-page.js'),
    'share-embed-page': staticPath('js/pages/share-embed-page.js'),
    // Commons chunk
    'vendor': [
        // Vendor libraries
        'knockout',
        'knockout.validation',
        'knockout.punches',
        'moment',
        'bootstrap',
        'bootbox',
        'bootstrap-editable',
        'select2',
        'dropzone',
        'knockout-sortable',
        'treebeard',
        'jquery.cookie',
        'URIjs',
        // Common internal modules
        'js/fangorn',
        'js/citations',
        'js/osfHelpers',
        'mithril'
    ]
};

// Collect adddons endpoints. If an addon's static folder has
// any of the following files, it will be added as an entry point
// and output to website/static/public/js/<addon-name>/files.js
var addonModules = ['files.js', 'node-cfg.js', 'user-cfg.js', 'file-detail.js', 'widget-cfg.js'];
addons.addons.forEach(function(addonName) {
    var baseDir = addonName + '/';
    addonModules.forEach(function(module) {
        var modulePath = path.join(__dirname, 'website', 'addons',
                                  addonName, 'static', module);
        if (fs.existsSync(modulePath)) {
            var entryPoint = baseDir + module.split('.')[0];
            entry[entryPoint] =  modulePath;
        }
    });
});

var resolve = {
    extensions: ['', '.es6.js', '.js'],
    root: root,
    // Look for required files in bower and npm directories
    modulesDirectories: ['./website/static/vendor/bower_components', 'node_modules'],
    // Need to alias libraries that aren't managed by bower or npm
    alias: {
        'knockout-sortable': staticPath('vendor/knockout-sortable/knockout-sortable.js'),
        'bootstrap-editable': staticPath('vendor/bootstrap-editable-custom/js/bootstrap-editable.js'),
        'jquery-blockui': staticPath('vendor/jquery-blockui/jquery.blockui.js'),
        'bootstrap': staticPath('vendor/bower_components/bootstrap/dist/js/bootstrap.min.js'),
        'jquery-tagsinput': staticPath('vendor/bower_components/jquery.tagsinput/jquery.tagsinput.js'),
        'zeroclipboard': staticPath('vendor/bower_components/zeroclipboard/dist/ZeroClipboard.js'),
        'history': nodePath('historyjs/scripts/bundled/html4+html5/jquery.history.js'),
        // Needed for knockout-sortable
        'jquery.ui.sortable': staticPath('vendor/bower_components/jquery-ui/ui/jquery.ui.sortable.js'),
        'truncate': staticPath('vendor/bower_components/truncate/jquery.truncate.js'),
        // Needed for ace code editor in wiki
        'ace-noconflict': staticPath('vendor/bower_components/ace-builds/src-noconflict/ace.js'),
        'ace-ext-language_tools': staticPath('vendor/bower_components/ace-builds/src-noconflict/ext-language_tools.js'),
        'ace-mode-markdown': staticPath('vendor/bower_components/ace-builds/src-noconflict/mode-markdown.js'),
        'pagedown-ace-converter': addonsPath('wiki/static/pagedown-ace/Markdown.Converter.js'),
        'pagedown-ace-sanitizer': addonsPath('wiki/static/pagedown-ace/Markdown.Sanitizer.js'),
        'pagedown-ace-editor': addonsPath('wiki/static/pagedown-ace/Markdown.Editor.js'),
        'wikiPage': addonsPath('wiki/static/wikiPage.js'),
        'highlight-css': nodePath('highlight.js/styles/default.css'),
        // Also alias some internal libraries for easy access
        'addons': path.join(__dirname, 'website', 'addons'),
        'tests': staticPath('js/tests')
    }
};

var externals = {
    // require("jquery") is external and available
    //  on the global var jQuery, which is loaded with CDN
    'jquery': 'jQuery',
    'jquery-ui': 'jQuery.ui',
    'raven-js': 'Raven',
    'MathJax': 'MathJax'
};

var plugins = [
    // Bundle common code between modules
    new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.js'),
    // Bower support
    new webpack.ResolverPlugin(
        new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin('bower.json', ['main'])
    ),
    // Make jQuery available in all modules without having to do require('jquery')
    new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery'
    }),
    // Slight hack to make sure that CommonJS is always used
    new webpack.DefinePlugin({
        'define.amd': false
    }),
];

var output = {
    path: './website/static/public/js/',
    // publicPath: '/static/', // used to generate urls to e.g. images
    filename: '[name].js',
    sourcePrefix: ''
};

module.exports = {
    entry: entry,
    resolve: resolve,
    externals: externals,
    plugins: plugins,
    output: output,
    module: {
        loaders: [
            {test: /\.es6\.js$/, exclude: [/node_modules/, /bower_components/, /vendor/], loader: 'babel-loader'},
            {test: /\.css$/, loaders: ['style', 'css']},
            // url-loader uses DataUrls; files-loader emits files
            {test: /\.png$/, loader: 'url-loader?limit=100000&mimetype=image/ng'},
            {test: /\.gif$/, loader: 'url-loader?limit=10000&mimetype=image/gif'},
            {test: /\.jpg$/, loader: 'url-loader?limit=10000&mimetype=image/jpg'},
            {test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'url-loader?mimetype=application/font-woff'},
            {test: /\.svg/, loader: 'file-loader'},
            {test: /\.eot/, loader: 'file-loader'},
            {test: /\.ttf/, loader: 'file-loader'}
        ]
    }
};
<|endoftext|>


<commit_before>var _ = require('lodash');
var webpack = require('webpack');
var path = require('path');
var config = require('../common.config');
var WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin');
var webpackIsomorphicToolsPlugin = new WebpackIsomorphicToolsPlugin(require('../isomorphic.config'));
var appPath = path.join(__dirname, '..', '..');

var devMode = process.env.NODE_ENV !== 'production';
var prodMode = process.env.NODE_ENV === 'production';

var plugins = [
  new webpack.DefinePlugin({
    __CLIENT__: true,
    __SERVER__: false,
    __PRODUCTION__: prodMode,
    __DEV__: devMode
  }),
  webpackIsomorphicToolsPlugin
];

var loaders = [
  {
    test: webpackIsomorphicToolsPlugin.regular_expression('fonts'),
    loader: 'file?name=fonts/[hash].[ext]'
  }
];

if (prodMode) {
  var ExtractTextPlugin = require("extract-text-webpack-plugin");

  plugins.push(new ExtractTextPlugin("styles.css"));
  plugins.push(new webpack.optimize.DedupePlugin());
  plugins.push(new webpack.optimize.OccurenceOrderPlugin());
  plugins.push(new webpack.optimize.UglifyJsPlugin({
    compress: {
      warnings: false
    }
  }));

  plugins.push(new webpack.DefinePlugin({
    process: {
      env: {
        NODE_ENV: JSON.stringify('production')
      }
    }
  }));

  loaders.push({
    test: webpackIsomorphicToolsPlugin.regular_expression('stylesCss'),
    loader: ExtractTextPlugin.extract('style', 'stylus')
  });

  loaders.push({
    test: webpackIsomorphicToolsPlugin.regular_expression('stylesStyl'),
    loader: ExtractTextPlugin.extract('style', 'css!stylus')
  });
} else {
  loaders.push({
    test: webpackIsomorphicToolsPlugin.regular_expression('stylesCss'),
    loader: 'style!css'
  });

  loaders.push({
    test: webpackIsomorphicToolsPlugin.regular_expression('stylesStyl'),
    loader: 'style!css!stylus'
  });
}

module.exports = _.mergeWith(config, {
  target: 'web',
  devtool: false,
  module: {
    loaders: loaders
  },
  entry: [
    path.resolve(path.join(appPath, 'src', 'client'))
  ],
  output: {
    path: path.resolve(path.join(appPath, 'static', 'assets')),
    filename: 'client.js',
    chunkFilename: '[name].[id].js'
  },
  plugins: plugins
}, function(objValue, srcValue) {
  if (_.isArray(objValue)) {
    return objValue.concat(srcValue);
  }
});
<commit_msg>Generate source map for development mode<commit_after>var _ = require('lodash');
var webpack = require('webpack');
var path = require('path');
var config = require('../common.config');
var WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin');
var webpackIsomorphicToolsPlugin = new WebpackIsomorphicToolsPlugin(require('../isomorphic.config'));
var appPath = path.join(__dirname, '..', '..');

var devMode = process.env.NODE_ENV !== 'production';
var prodMode = process.env.NODE_ENV === 'production';

var plugins = [
  new webpack.DefinePlugin({
    __CLIENT__: true,
    __SERVER__: false,
    __PRODUCTION__: prodMode,
    __DEV__: devMode
  }),
  webpackIsomorphicToolsPlugin
];

var loaders = [
  {
    test: webpackIsomorphicToolsPlugin.regular_expression('fonts'),
    loader: 'file?name=fonts/[hash].[ext]'
  }
];

if (prodMode) {
  var ExtractTextPlugin = require("extract-text-webpack-plugin");

  plugins.push(new ExtractTextPlugin("styles.css"));
  plugins.push(new webpack.optimize.DedupePlugin());
  plugins.push(new webpack.optimize.OccurenceOrderPlugin());
  plugins.push(new webpack.optimize.UglifyJsPlugin({
    compress: {
      warnings: false
    }
  }));

  plugins.push(new webpack.DefinePlugin({
    process: {
      env: {
        NODE_ENV: JSON.stringify('production')
      }
    }
  }));

  loaders.push({
    test: webpackIsomorphicToolsPlugin.regular_expression('stylesCss'),
    loader: ExtractTextPlugin.extract('style', 'stylus')
  });

  loaders.push({
    test: webpackIsomorphicToolsPlugin.regular_expression('stylesStyl'),
    loader: ExtractTextPlugin.extract('style', 'css!stylus')
  });
} else {
  loaders.push({
    test: webpackIsomorphicToolsPlugin.regular_expression('stylesCss'),
    loader: 'style!css'
  });

  loaders.push({
    test: webpackIsomorphicToolsPlugin.regular_expression('stylesStyl'),
    loader: 'style!css!stylus'
  });
}

module.exports = _.mergeWith(config, {
  target: 'web',
  devtool: devMode ? 'source-map' : null,
  module: {
    loaders: loaders
  },
  entry: [
    path.resolve(path.join(appPath, 'src', 'client'))
  ],
  output: {
    path: path.resolve(path.join(appPath, 'static', 'assets')),
    filename: 'client.js',
    chunkFilename: '[name].[id].js'
  },
  plugins: plugins
}, function(objValue, srcValue) {
  if (_.isArray(objValue)) {
    return objValue.concat(srcValue);
  }
});
<|endoftext|>


<commit_before>/*!
 * This file is part of me-cms.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright   Copyright (c) Mirko Pagliai
 * @link        https://github.com/mirko-pagliai/me-cms
 * @license     https://opensource.org/licenses/mit-license.php MIT License
 */
$(function () {
    //Input button to add tags
    var inputButton = $("#tags-input-button");

    //Input text
    var inputText = $("#tags-input-text");

    //Output text
    var outputText = $("#tags-output-text");

    //Preview wrapper
    var preview = $("#tags-preview");

    //Sets the counter, index for tags
    var counter = 1;

    //List of tags
    var listOfTags = [];

    /**
     * Checks if a tag already exists
     * @param string tag Tag value
     * @returns bool
     */
    function tag_exist(tag)
    {
        var listOfTagsLength = listOfTags.length;

        for (var i = 0; i < listOfTagsLength; i++) {
            if (listOfTags[i].value === tag) {
                return true;
            }
        }

        return false;
    }

    /**
     * Adds tags
     * @param array tags Tags
     */
    function add_tags(tags)
    {
        $.each(tags, function (index, tag) {
            //Checks for length
            if (tag.length < 3) {
                return;
            }

            //Returns, if the tag already exists
            if (tag_exist(tag)) {
                return;
            }

            tag = tag.toLowerCase(); //Lowercase

            //Changes invalid chars
            var from = "àáäâèéëêìíïîıòóöôùúüûñç·/_,:;-";
            var to = "aaaaeeeeiiiiioooouuuunc       ";
            var fromLength = from.length;
            for (var i = 0; i < fromLength; i++) {
                tag = tag.replace(new RegExp(from.charAt(i), "g"), to.charAt(i));
            }

            //Removes invalid chars
            tag = tag.replace(/[^a-z0-9\s]/g, "")

            //Pushes the tag on the list of tags
            listOfTags.push({key:counter, value:tag});

            //Appends HTML
            var closeButton = "<button type=\"button\" data-tag=\"" + counter + "\" class=\"tag-remove\" href=\"#\">×</button>";
            preview.append("
" + tag + closeButton + "
");

            //Increments the counter
            counter++;
        });

        //At the end, updates the output text
        update_output_text();
    }

    /**
     * Removes a tag
     * @param string|int id Tag id
     */
    function remove_tag(id)
    {
        var listOfTagsLength = listOfTags.length;

        for (var i = 0; i < listOfTagsLength; i++) {
            if (listOfTags[i].key === parseInt(id)) {
                //Removes the tag from the list of tag
                listOfTags.splice(i, 1);

                //Removes HTML
                $("div[data-tag=" + id + "]", preview).remove();

                break;
            }
        }

        //At the end, updates the output text
        update_output_text();
    }

    /**
     * Updates the output text
     */
    function update_output_text()
    {
        //Creates a new empty array
        var newTags = [];

        $.each(listOfTags, function (index, tag) {
            //Pushes only the tag values the new array with
            newTags.push(tag['value']);
        });

        //Updats the output text
        outputText.val(newTags.join(", "));
    }

    //On start, gets and adds tags from the output text
    add_tags(outputText.val().split(", "));

    //On click on the input button
    inputButton.click(function () {
        //Gets and trims the input value
        var inputValue = inputText.val().replace(/^\s+|\s+$/g, "");

        //Checks for length
        if (!inputValue.length) {
            return false;
        }

        //Resets the input text
        inputText.val("");

        //Adds tags
        add_tags(inputValue.split(/\s*,+\s*/));
    });

    //On click on the remove link
    $(preview).on("click", ".tag-remove", function () {
        //Removes the tag
        remove_tag($(this).attr("data-tag"));
    });

    //On focus on the input text
    $(inputText).on("focusin", function () {
        $(this).off("keydown").keydown(function (event) {
            //On press the "enter" button
            if (event.keyCode === 13) {
                //Prevent default event
                event.preventDefault();

                //Clicks on input button
                inputButton.click();

                return false;
            }
        });
    });
});<commit_msg>fixed<commit_after>/*!
 * This file is part of me-cms.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright   Copyright (c) Mirko Pagliai
 * @link        https://github.com/mirko-pagliai/me-cms
 * @license     https://opensource.org/licenses/mit-license.php MIT License
 */
$(function () {
    //Input button to add tags
    var inputButton = $("#tags-input-button");

    //Input text
    var inputText = $("#tags-input-text");

    //Output text
    var outputText = $("#tags-output-text");

    //Preview wrapper
    var preview = $("#tags-preview");

    //Sets the counter, index for tags
    var counter = 1;

    //List of tags
    var listOfTags = [];

    /**
     * Checks if a tag already exists
     * @param string tag Tag value
     * @returns bool
     */
    function tag_exist(tag)
    {
        var listOfTagsLength = listOfTags.length;

        for (var i = 0; i < listOfTagsLength; i++) {
            if (listOfTags[i].value === tag) {
                return true;
            }
        }

        return false;
    }

    /**
     * Adds tags
     * @param array tags Tags
     */
    function add_tags(tags)
    {
        $.each(tags, function (index, tag) {
            //Checks for length
            if (tag.length < 3) {
                return;
            }

            //Returns, if the tag already exists
            if (tag_exist(tag)) {
                return;
            }

            tag = tag.toLowerCase(); //Lowercase

            //Changes invalid chars
            var from = "àáäâèéëêìíïîıòóöôùúüûñç·/_,:;-";
            var to = "aaaaeeeeiiiiioooouuuunc       ";
            var fromLength = from.length;
            for (var i = 0; i < fromLength; i++) {
                tag = tag.replace(new RegExp(from.charAt(i), "g"), to.charAt(i));
            }

            //Removes invalid chars
            tag = tag.replace(/[^a-z0-9\s]/g, "")

            //Pushes the tag on the list of tags
            listOfTags.push({key:counter, value:tag});

            //Appends HTML
            var closeButton = "<button type=\"button\" data-tag=\"" + counter + "\" class=\"tag-remove\" href=\"#\">×</button>";
            preview.append("
" + tag + closeButton + "
");

            //Increments the counter
            counter++;
        });

        //At the end, updates the output text
        update_output_text();
    }

    /**
     * Removes a tag
     * @param string|int id Tag id
     */
    function remove_tag(id)
    {
        var listOfTagsLength = listOfTags.length;

        for (var i = 0; i < listOfTagsLength; i++) {
            if (listOfTags[i].key === parseInt(id)) {
                //Removes the tag from the list of tag
                listOfTags.splice(i, 1);

                //Removes HTML
                $("div[data-tag=" + id + "]", preview).remove();

                break;
            }
        }

        //At the end, updates the output text
        update_output_text();
    }

    /**
     * Updates the output text
     */
    function update_output_text()
    {
        //Creates a new empty array
        var newTags = [];

        $.each(listOfTags, function (index, tag) {
            //Pushes only the tag values the new array with
            newTags.push(tag["value"]);
        });

        //Updats the output text
        outputText.val(newTags.join(", "));
    }

    //On start, gets and adds tags from the output text
    add_tags(outputText.val().split(", "));

    //On click on the input button
    inputButton.click(function () {
        //Gets and trims the input value
        var inputValue = inputText.val().replace(/^\s+|\s+$/g, "");

        //Checks for length
        if (!inputValue.length) {
            return false;
        }

        //Resets the input text
        inputText.val("");

        //Adds tags
        add_tags(inputValue.split(/\s*,+\s*/));
    });

    //On click on the remove link
    $(preview).on("click", ".tag-remove", function () {
        //Removes the tag
        remove_tag($(this).attr("data-tag"));
    });

    //On focus on the input text
    $(inputText).on("focusin", function () {
        $(this).off("keydown").keydown(function (event) {
            //On press the "enter" button
            if (event.keyCode === 13) {
                //Prevent default event
                event.preventDefault();

                //Clicks on input button
                inputButton.click();

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


<commit_before>/*global sap */

sap.ui.define([
    "sap/ui/core/message/Message",
    "sap/ui/core/MessageType",
    "sap/ui/core/ValueState"
], function (Message, MessageType, ValueState) {
    "use strict";

    /**
     * @name        nl.qualiture.plunk.demo.utils.Validator
     *
     * @class
     * @classdesc   Validator class.

     *
     * @version     Oktober 2015
     * @author      Robin van het Hof
     */
    var Validator = function () {
        this._isValid = true;
        this._isValidationPerformed = false;
    };

    /**
     * Returns true _only_ when the form validation has been performed, and no validation errors were found
     * @memberof nl.qualiture.plunk.demo.utils.Validator
     *
     * @returns {boolean}
     */
    Validator.prototype.isValid = function () {
        return this._isValidationPerformed && this._isValid;
    };

    /**
     * Recursively validates the given oControl and any aggregations (i.e. child controls) it may have
     * @memberof nl.qualiture.plunk.demo.utils.Validator
     *
     * @param {(sap.ui.core.Control|sap.ui.layout.form.FormContainer|sap.ui.layout.form.FormElement)} oControl - The control or element to be validated.
     * @return {boolean} whether the oControl is valid or not.
     */
    Validator.prototype.validate = function (oControl) {
        this._isValid = true;
        sap.ui.getCore().getMessageManager().removeAllMessages();
        this._validate(oControl);
        return this.isValid();
    };

    /**
     * Recursively validates the given oControl and any aggregations (i.e. child controls) it may have
     * @memberof nl.qualiture.plunk.demo.utils.Validator
     *
     * @param {(sap.ui.core.Control|sap.ui.layout.form.FormContainer|sap.ui.layout.form.FormElement)} oControl - The control or element to be validated.
     */
    Validator.prototype._validate = function (oControl) {
        var aPossibleAggregations = ["items", "content", "form", "formContainers", "formElements", "fields", "sections", "subSections", "_grid"],
            aControlAggregation   = null,
            oControlBinding       = null,
            aValidateProperties   = ["value", "selectedKey", "text"], // yes, I want to validate Select and Text controls too
            isValidatedControl    = false,
            oExternalValue, oInternalValue,
            i, j;

        // only validate controls and elements which have a 'visible' property
        if (oControl instanceof sap.ui.core.Control ||
            oControl instanceof sap.ui.layout.form.FormContainer ||
            oControl instanceof sap.ui.layout.form.FormElement) {

            // only check visible controls (invisible controls make no sense checking)
            if (oControl.getVisible()) {

                // check control for any properties worth validating
                for (i = 0; i < aValidateProperties.length; i += 1) {
                    if (oControl.getBinding(aValidateProperties[i])) {
                        // check if a data type exists (which may have validation constraints)
                        if (oControl.getBinding(aValidateProperties[i]).getType()) {
                            // try validating the bound value
                            try {
                                oControlBinding = oControl.getBinding(aValidateProperties[i]);
                                oExternalValue  = oControl.getProperty(aValidateProperties[i]);
                                oInternalValue  = oControlBinding.getType().parseValue(oExternalValue, oControlBinding.sInternalType);
                                oControlBinding.getType().validateValue(oInternalValue);
                            }
                            // catch any validation errors
                            catch (ex) {
                                this._isValid = false;
                                oControl.setValueState(ValueState.Error);

                                oControlBinding = oControl.getBinding(aValidateProperties[i]);
                                sap.ui.getCore().getMessageManager().addMessages(
                                    new Message({
                                        message  : ex.message,
                                        type     : MessageType.Error,
                                        target   : ( oControlBinding.getContext() ? oControlBinding.getContext().getPath() + "/" : "") +
                                                oControlBinding.getPath(),
                                        processor: oControl.getBinding(aValidateProperties[i]).getModel()
                                    })
                                );
                            }

                            isValidatedControl = true;
                        }
                    }
                }

                // if the control could not be validated, it may have aggregations
                if (!isValidatedControl) {
                    for (i = 0; i < aPossibleAggregations.length; i += 1) {
                        aControlAggregation = oControl.getAggregation(aPossibleAggregations[i]);

                        if (aControlAggregation) {
                            // generally, aggregations are of type Array
                            if (aControlAggregation instanceof Array) {
                                for (j = 0; j < aControlAggregation.length; j += 1) {
                                    this._validate(aControlAggregation[j]);
                                }
                            }
                            // ...however, with sap.ui.layout.form.Form, it is a single object *sigh*
                            else {
                                this._validate(aControlAggregation);
                            }
                        }
                    }
                }
            }
        }
        this._isValidationPerformed = true;
    };

    return Validator;
});
<commit_msg>Restructure to decrease depth of control structures<commit_after>/*global sap */

sap.ui.define([
    "sap/ui/core/message/Message",
    "sap/ui/core/MessageType",
    "sap/ui/core/ValueState"
], function (Message, MessageType, ValueState) {
    "use strict";

    /**
     * @name        nl.qualiture.plunk.demo.utils.Validator
     *
     * @class
     * @classdesc   Validator class.

     *
     * @version     Oktober 2015
     * @author      Robin van het Hof
     */
    var Validator = function () {
        this._isValid = true;
        this._isValidationPerformed = false;
    };

    /**
     * Returns true _only_ when the form validation has been performed, and no validation errors were found
     * @memberof nl.qualiture.plunk.demo.utils.Validator
     *
     * @returns {boolean}
     */
    Validator.prototype.isValid = function () {
        return this._isValidationPerformed && this._isValid;
    };

    /**
     * Recursively validates the given oControl and any aggregations (i.e. child controls) it may have
     * @memberof nl.qualiture.plunk.demo.utils.Validator
     *
     * @param {(sap.ui.core.Control|sap.ui.layout.form.FormContainer|sap.ui.layout.form.FormElement)} oControl - The control or element to be validated.
     * @return {boolean} whether the oControl is valid or not.
     */
    Validator.prototype.validate = function (oControl) {
        this._isValid = true;
        sap.ui.getCore().getMessageManager().removeAllMessages();
        this._validate(oControl);
        return this.isValid();
    };

    /**
     * Recursively validates the given oControl and any aggregations (i.e. child controls) it may have
     * @memberof nl.qualiture.plunk.demo.utils.Validator
     *
     * @param {(sap.ui.core.Control|sap.ui.layout.form.FormContainer|sap.ui.layout.form.FormElement)} oControl - The control or element to be validated.
     */
    Validator.prototype._validate = function (oControl) {
        var aPossibleAggregations = ["items", "content", "form", "formContainers", "formElements", "fields", "sections", "subSections", "_grid"],
            aControlAggregation   = null,
            oControlBinding       = null,
            aValidateProperties   = ["value", "selectedKey", "text"], // yes, I want to validate Select and Text controls too
            isValidatedControl    = false,
            oExternalValue, oInternalValue,
            i, j;

        // only validate controls and elements which have a 'visible' property
        // and are visible controls (invisible controls make no sense checking)
        if (( oControl instanceof sap.ui.core.Control
	          || oControl instanceof sap.ui.layout.form.FormContainer
	          || oControl instanceof sap.ui.layout.form.FormElement
            ) && oControl.getVisible() ) {

            // check control for any properties worth validating
            for (i = 0; i < aValidateProperties.length; i += 1) {
                if (oControl.getBinding(aValidateProperties[i])
                    	// check if a data type exists (which may have validation constraints)
                        && oControl.getBinding(aValidateProperties[i]).getType()
                        // but just if it's enabled
                        && oControl.getEnabled()) {

                    try { // try validating the bound value
                        oControlBinding = oControl.getBinding(aValidateProperties[i]);
                        oExternalValue  = oControl.getProperty(aValidateProperties[i]);
                        oInternalValue  = oControlBinding.getType().parseValue(oExternalValue, oControlBinding.sInternalType);
                        oControlBinding.getType().validateValue(oInternalValue);
                    }

                    catch (ex) { // catch any validation errors
                        this._isValid = false;
                        oControl.setValueState(ValueState.Error);

                        oControlBinding = oControl.getBinding(aValidateProperties[i]);
                        sap.ui.getCore().getMessageManager().addMessages(
                            new Message({
                                message  : ex.message,
                                type     : MessageType.Error,
                                target   : ( oControlBinding.getContext() ? oControlBinding.getContext().getPath() + "/" : "") +
                                        oControlBinding.getPath(),
                                processor: oControl.getBinding(aValidateProperties[i]).getModel()
                            })
                        );
                    }

                    isValidatedControl = true;
                }
            }

            // if the control could not be validated, it may have aggregations
            if (!isValidatedControl) {
                for (i = 0; i < aPossibleAggregations.length; i += 1) {
                    aControlAggregation = oControl.getAggregation(aPossibleAggregations[i]);

                    if (aControlAggregation) {
                        // generally, aggregations are of type Array
                        if (aControlAggregation instanceof Array) {
                            for (j = 0; j < aControlAggregation.length; j += 1) {
                                this._validate(aControlAggregation[j]);
                            }
                        }
                        // ...however, with sap.ui.layout.form.Form, it is a single object *sigh*
                        else {
                            this._validate(aControlAggregation);
                        }
                    }
                }
            }

        }
        this._isValidationPerformed = true;
    };

    return Validator;
});
<|endoftext|>


<commit_before>var BasketService       = require('services/BasketService');
var ApiService          = require('services/ApiService');
var NotificationService = require('services/NotificationService');
var ModalService        = require('services/ModalService');

Vue.component('add-to-basket', {

    template: '#vue-add-to-basket',

    props: [
        "basketItem",
        "baseUrl"
    ],

    data: function()
    {
        return {
            quantity: 1
        };
    },

    methods: {

        addToBasket: function(quantity)
        {
            var addItemModal = ModalService.findModal($(this.$el.parentElement));
            addItemModal.setTimeout(10000);

            $(".wrapper-bottom").append(addItemModal.getModalContainer());

            BasketService.addBasketItem({
                variationId: this.basketItem.variationBase.id,
                quantity   : this.quantity
            }).done(function()
            {
                addItemModal.show();
            })
                .fail(function()
                {
                    NotificationService.error(Translations.Callisto.basketItemNotAdded).closeAfter(10000);
                });
        },

        quantityPlus: function()
        {
            this.quantity++;
        },

        quantityMinus: function()
        {
            if (this.quantity > 1)
            {
                this.quantity--;
            }
        }
    }
});
<commit_msg>changed BasketService to ResourceService<commit_after>var ResourceService       = require('services/ResourceService');
var ApiService          = require('services/ApiService');
var NotificationService = require('services/NotificationService');
var ModalService        = require('services/ModalService');

Vue.component('add-to-basket', {

    template: '#vue-add-to-basket',

    props: [
        "basketItem",
        "baseUrl"
    ],

    data: function()
    {
        return {
            quantity: 1
        };
    },

    methods: {

        addToBasket: function(quantity)
        {
            var addItemModal = ModalService.findModal($(this.$el.parentElement));
            addItemModal.setTimeout(10000);

            $(".wrapper-bottom").append(addItemModal.getModalContainer());

            ResourceService
              .getResource( 'basketItems' )
              .push({'variationId': this.basketItem.variationBase.id, 'quantity': this.quantity})
              .done(function()
            {
              addItemModal.show();
            })
              .fail(function()
              {
                  NotificationService.error(Translations.Callisto.basketItemNotAdded).closeAfter(10000);
              });
        },

        quantityPlus: function()
        {
            this.quantity++;
        },

        quantityMinus: function()
        {
            if (this.quantity > 1)
            {
                this.quantity--;
            }
        }
    }
});
<|endoftext|>


<commit_before>var ResourceService = require("services/ResourceService");

Vue.component("add-to-basket", {

    props: [
        "item",
        "showQuantity",
        "itemUrl",
        "template"
    ],

    data: function()
    {
        return {
            quantity: 1
        };
    },

    created: function()
    {
        this.$options.template = this.template;
    },

    computed:
    {
        /**
         * returns item.variation.id
         */
        variationId: function()
        {
            return this.item.variation.id;
        }
    },

    methods:
    {
        /**
         * add an item to basket-resource
         */
        addToBasket: function()
        {
            var basketObject =
                {
                    variationId: this.variationId,
                    quantity   : this.quantity
                };

            ResourceService
                .getResource("basketItems")
                .push(basketObject);

            this.openAddToBasketOverlay();
        },

        // directToItem: function()
        // {
        //     window.location.assign(this.itemUrl);
        // },

        /**
         * open the AddItemToBasketOverlay
         */
        openAddToBasketOverlay: function()
        {
            var currentBasketObject =
                {
                    currentBasketItem: this.item,
                    quantity         : this.quantity
                };

            ResourceService
                .getResource("basketItem")
                .set(currentBasketObject);
        },

        /**
         * update the property quantity of the current instance
         * @param value
         */
        updateQuantity: function(value)
        {
            this.quantity = value;
        }
    }
});
<commit_msg>add directToItem back<commit_after>var ResourceService = require("services/ResourceService");

Vue.component("add-to-basket", {

    props: [
        "item",
        "showQuantity",
        "itemUrl",
        "template"
    ],

    data: function()
    {
        return {
            quantity: 1
        };
    },

    created: function()
    {
        this.$options.template = this.template;
    },

    computed:
    {
        /**
         * returns item.variation.id
         */
        variationId: function()
        {
            return this.item.variation.id;
        }
    },

    methods:
    {
        /**
         * add an item to basket-resource
         */
        addToBasket: function()
        {
            var basketObject =
                {
                    variationId: this.variationId,
                    quantity   : this.quantity
                };

            ResourceService
                .getResource("basketItems")
                .push(basketObject);

            this.openAddToBasketOverlay();
        },

        directToItem: function()
        {
            window.location.assign(this.itemUrl);
        },

        /**
         * open the AddItemToBasketOverlay
         */
        openAddToBasketOverlay: function()
        {
            var currentBasketObject =
                {
                    currentBasketItem: this.item,
                    quantity         : this.quantity
                };

            ResourceService
                .getResource("basketItem")
                .set(currentBasketObject);
        },

        /**
         * update the property quantity of the current instance
         * @param value
         */
        updateQuantity: function(value)
        {
            this.quantity = value;
        }
    }
});
<|endoftext|>


<commit_before>/*
 *  Bug noticed while doing underscore shimming, case fallthrough does not
 *  work correctly (it used to work but has broken at some point).
 */

/*===
matches 3
matches [object Date]
===*/

function test1() {
    var v = 2;
    switch (v) {
        case 1:
            print('matches 1');
            break;
        case 2:
        case 3:
            print('matches 3');
            break;
        default:
            print('matches default');
    }
}

function test2() {
    var date = new Date(2014, 1, 2);
    switch (Object.prototype.toString.call(date)) {
        case '[object String]':
            print('matches [object String]');
            break;
        case '[object Date]':
        case '[object Boolean]':
            print('matches [object Date]');
            break;
        default:
            print('matches default');
    }
}

try {
    test1();
} catch (e) {
    print(e);
}

try {
    test2();
} catch (e) {
    print(e);
}

<commit_msg>refine case fallthrough testcase<commit_after>/*
 *  Bug noticed while doing underscore shimming, case fallthrough does not
 *  work correctly (it used to work but has broken at some point).
 *
 *  The critical thing is that there are two case statements and the first
 *  case matches and falls through to the second (non-matching).
 */

/*===
matches 3
matches 3
matches 3
matches [object Date]
===*/

function test1a() {
    var v = 2;
    switch (v) {
        case 1:
            print('matches 1');
            break;
        case 2:
        case 3:
            print('matches 3');
            break;
        default:
            print('matches default');
    }
}

function test1b() {
    var v = 2;
    switch (v) {
        case 1:
            print('matches 1');
            break;
        case 3:
        case 2:
            print('matches 3');
            break;
        default:
            print('matches default');
    }
}

function test1c() {
    var v = 2;
    switch (v) {
        case 1:
            print('matches 1');
            break;
        case 2:
            ;  // this is enough to stop triggering the bug
        case 3:
            print('matches 3');
            break;
        default:
            print('matches default');
    }
}

// Check also with strings (originally found with this)
function test2a() {
    var date = new Date(2014, 1, 2);
    switch (Object.prototype.toString.call(date)) {
        case '[object String]':
            print('matches [object String]');
            break;
        case '[object Date]':
        case '[object Boolean]':
            print('matches [object Date]');
            break;
        default:
            print('matches default');
    }
}

try {
    test1a();
} catch (e) {
    print(e);
}

try {
    test1b();
} catch (e) {
    print(e);
}

try {
    test1c();
} catch (e) {
    print(e);
}

try {
    test2a();
} catch (e) {
    print(e);
}

<|endoftext|>


<commit_before>import $ from 'jquery'

$(() => {
  console.log('jQuery version is: ' + $().jquery)
})<commit_msg>[js] added missing newline<commit_after>import $ from 'jquery'

$(() => {
  console.log('jQuery version is: ' + $().jquery)
})
<|endoftext|>