<commit_before>/*===============
    #SLIDESHOW
===============*/
var slideshow = slideshow || {};
slideshow.namespace = function(ns_string) {
    var parts = ns_string.split('.'),
        parent = slideshow,
        i;
    if (parts[0] === "slideshow") {
        parts = parts.slice(1);
    }
    for (i = 0; i < parts.length; i += 1) {
        if (typeof parent[parts[i]] === "undefined") {
            parent[parts[i]] = {};
        }
        parent = parent[parts[i]];
    }
    return parent;
};

/*==========
    #INIT
==========*/

slideshow.namespace('init');
slideshow.init = function() {
    for (var module in this.modules) {
        console.log(module);
        if (this.modules[module].hasOwnProperty('init')) {
            this.modules[module].init();
        }
    }
};

/*================
    #MODULES
===============*/

/*================
    #Navigation
===============*/

slideshow.namespace('modules.navigation');
slideshow.modules.navigation = (function () {
    var public = {},
        currentSlideIndex = 0,
        getSlideArray, evtCbs,moveHelpers, showSlide, init;

    getSlideArray = function () {
       return  document.querySelectorAll('.slide');
    };
    function setupSlides () {
        var slides = getSlideArray();
        for (var i=0,panels, slide; i< slides.length; i++) {
            slide = slides[i];
            panels = slide.querySelectorAll('.slide__content');
            slide.querySelector('.js-slideNum').innerHTML = (i + 1) + ' of ' + slides.length;
            slide.id = 'js-slide--' + i;
            slide.classList.add('js-slide--' + i);
            slide.dataset.slideindex = i;
            slide.dataset.panelcount = panels.length;
            for (var n=0, panel; n < panels.length; n++) {
                panel = panels[n];
               // panel.id = slide.id + '-panel--' + n;
                panel.classList.add('js-panel--' + n);
                if (n === 0) {
                    panel.classList.add('ui-visible');
                }
            }
            if (i === 0) {
                slide.classList.add('ui-current');
                currentSlideIndex = i;
            }

        }
    };

    showSlide = {
        currentSlide: 0,
        gotoSlide : function (i) {
            var rootSlide = document.querySelector('.slides .slide'),
                articleWidth = rootSlide.offsetWidth + rootSlide.style.marginRight,
                currentSlide = document.getElementById('js-slide--' + i),
                currentPanel = currentSlide.querySelector('.slide__content');
            rootSlide.style.marginLeft = 0 - (articleWidth * i) + 'px';
            document.querySelector('.ui-current').classList.remove('ui-current');
            currentSlide.classList.add('ui-current');
            currentPanel.classList.add('ui-visible');
            history.pushState(currentSlide.dataset.title, "slide " + i, '#' + currentSlide.dataset.title.replace(' ', '-'))
        },
        next: function () {
            if (this.currentSlide < slideshow.modules.navigation.getSlideCount-1) this.currentSlide++;
            this.gotoSlide(this.currentSlide);
        },
        prev: function () {
            if (this.currentSlide > 0) this.currentSlide--;
            this.gotoSlide(this.currentSlide)
        }
    };
    showPanel = {
        currentPanel: 0,
        panelCount: function () {
            var currentSlide = document.querySelector('.ui-current');
            return parseInt(currentSlide.dataset.panelcount, 10);
        },
        gotoPanel: function (i) {
            var currentSlide = document.querySelector('.ui-current'),
                hiddenTopPaneli = i > 0 ? i-1 : 0,
                hiddenBottomPaneli = i < this.panelCount() ? i + 1 : this.panelCount(),
                currentPanel = currentSlide.querySelector('.js-panel--' + i),
                hiddenTopPanel = currentSlide.querySelector('.js-panel--' + hiddenTopPaneli);
            hiddenTopPanel.classList.add('ui-hiddenTop');
            hiddenTopPanel.classList.remove('ui-visible');
            currentPanel.classList.remove('ui-hiddenTop');
            currentPanel.classList.add('ui-visible');
        },
        next: function () {
            if (this.currentPanel < this.panelCount() - 1) this.currentPanel++;
            this.gotoPanel(this.currentPanel);

        },
        prev: function () {
            var currentSlide = document.querySelector('.ui-current');
            if (this.currentPanel > 0) {
                this.currentPanel--;
                currentSlide.querySelector('.ui-visible').classList.remove('ui-visible');
            };
            this.gotoPanel(this.currentPanel);

        }
    };
    evtCbs = {

        keyup: function (e) {
            e.preventDefault();
            switch (e.which) {
                case 37:
                //left
                slideshow.modules.navigation.navigate.next();
                break;
                case 39:
                //right
                slideshow.modules.navigation.navigate.prev();
                break;
                case 38:
                //up
                slideshow.modules.navigation.view.prev();
                break;
                case 40:
                //down
                slideshow.modules.navigation.view.next();
                break;
                default:
                break;
            }
        },
        navClick: function (e) {
            e.preventDefault();
            console.log(e);
            var slides = document.querySelector('.slides'),
                humanID = e.target.href.slice(e.target.href.indexOf('#')).replace('#',''),
                targetSlide = slides.querySelector('#'+humanID).parentNode,
                targetIndex = targetSlide.dataset.slideindex;

            slideshow.modules.navigation.navigate.gotoSlide(targetIndex);
            history.pushState(null,null,'#'+humanID);
            console.log(humanID, targetIndex);
        }
    };
    function bindUiEvts () {
        window.addEventListener('keyup', evtCbs.keyup);
        [].forEach.call(document.querySelectorAll('.slideNav .list__item__link'), function (navLink) {
            navLink.addEventListener('click', evtCbs.navClick);
        });
        var slides = document.querySelector('.slides'),
            hslides = new Hammer(slides);
        hslides.on('swipeleft', function (e) {
            slideshow.modules.navigation.navigate.next();
        });
        hslides.on('swiperight', function (e) {
            slideshow.modules.navigation.navigate.prev();
        });
        hslides.on('swipeup', function (e) {
            slideshow.modules.navigation.view.prev();
        });
        hslides.on('swipedown', function (e) {
            slideshow.modules.navigation.view.next();
        });

    };
    init = function( ) {
        setupSlides();
        bindUiEvts();
    };
    init();
    public = {
        evtCbs: evtCbs,
        slides: getSlideArray(),
        getSlideCount: getSlideArray().length,
        navigate: showSlide,
        view: showPanel,
        currentSlide : currentSlideIndex
    }
    return public;

})();

/*================
    #NavBuilder
===============*/
slideshow.namespace('modules.navBuilder');
slideshow.modules.navBuilder = (function () {
    var navContainer = document.querySelector('.slideNav'),
        getSlideArray, navItemArray,navItem, init, evtCbs;

    getSlideArray = function () {
       return  document.querySelectorAll('.slide');
    };
    evtCbs = {
        navItemClick: function (e) {
            e.preventDefault();

        }
    };

    navItem = function (slide) {
        var slideLink = document.createElement('a'),
            clonedSlide = slide.cloneNode(true);

        slideLink.href = "#"+ slide.id;
        slideLink.classList.add('slideNav__link');
        clonedSlide.id = '';
        slideLink.appendChild(clonedSlide);

        slideLink.addEventListener('click', evtCbs.navItemClick,false);
        return slideLink;
    };

    function bindUiEvts() {

    };
    function init() {
        //setupNavItems();
        bindUiEvts();
    };
    init();
    return {};
})();

/*================
    #UIControls
===============*/
slideshow.namespace('modules.ui');
slideshow.modules.ui = (function () {
    var public = {}, evtCbs = {};

    public.toggleSidebar = function () {
        var sidebar = document.querySelector('.slideNav');
        sidebar.classList.toggle('ui-collapsed');
    };
    public.toggleMain = function () {
        var sidebar = document.querySelector('.slideNav');
        sidebar.classList.toggle('ui-expandedfull');
    };
    public.toggleFullscreen= function () {
          if (!document.fullscreenElement &&    // alternative standard method
              !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement ) {  // current working methods
            if (document.documentElement.requestFullscreen) {
              document.documentElement.requestFullscreen();
            } else if (document.documentElement.msRequestFullscreen) {
              document.documentElement.msRequestFullscreen();
            } else if (document.documentElement.mozRequestFullScreen) {
              document.documentElement.mozRequestFullScreen();
            } else if (document.documentElement.webkitRequestFullscreen) {
              document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
            }
          } else {
            if (document.exitFullscreen) {
              document.exitFullscreen();
            } else if (document.msExitFullscreen) {
              document.msExitFullscreen();
            } else if (document.mozCancelFullScreen) {
              document.mozCancelFullScreen();
            } else if (document.webkitExitFullscreen) {
              document.webkitExitFullscreen();
            }
          }

    };
    evtCbs = {
        keydown: function (e) {
            if (e.ctrlKey) {
                console.log(e.which);
                switch (e.which) {
                    case 73:
                    //i
                    slideshow.modules.ui.toggleMain();
                    break;
                    case 70:
                    //f
                    slideshow.modules.ui.toggleFullscreen();
                    break;
                    case 83:
                    //s
                    slideshow.modules.ui.toggleSidebar();
                    break;
                    case 78:
                    slideshow.modules.ui.toggleSidebar();
                    //n
                    break;
                    default:
                    break;
                }
            }
        },
        pushHash: function (e) {
            console.log(e);

        }
    };

    function bindUiEvts() {
        var nav = document.querySelector('.slideNav'),
            hNav = new Hammer(nav);

        hNav.on('swipeleft', function (e) {
            console.log(e);
            slideshow.modules.ui.toggleSidebar();
        });
        hNav.on('swiperight', function (e) {
            console.log(e);
            slideshow.modules.ui.toggleSidebar();
        });
        hNav.add(new Hammer.Tap({event: 'doubletap', taps: 2}));
        hNav.on('doubletap', function (e) {
            slideshow.modules.ui.toggleSidebar();
            console.log('doubletapped')
        });
        window.addEventListener('keydown', evtCbs.keydown);
        window.addEventListener('hashchange', evtCbs.pushHash);
        //to do: add in the history API, Hash by titles or slide number
    };
    function init() {
        bindUiEvts();
    }
    init();
    return public;
})();

slideshow.init();<commit_msg>proper touch events<commit_after>/*===============
    #SLIDESHOW
===============*/
var slideshow = slideshow || {};
slideshow.namespace = function(ns_string) {
    var parts = ns_string.split('.'),
        parent = slideshow,
        i;
    if (parts[0] === "slideshow") {
        parts = parts.slice(1);
    }
    for (i = 0; i < parts.length; i += 1) {
        if (typeof parent[parts[i]] === "undefined") {
            parent[parts[i]] = {};
        }
        parent = parent[parts[i]];
    }
    return parent;
};

/*==========
    #INIT
==========*/

slideshow.namespace('init');
slideshow.init = function() {
    for (var module in this.modules) {
        console.log(module);
        if (this.modules[module].hasOwnProperty('init')) {
            this.modules[module].init();
        }
    }
};

/*================
    #MODULES
===============*/

/*================
    #Navigation
===============*/

slideshow.namespace('modules.navigation');
slideshow.modules.navigation = (function () {
    var public = {},
        currentSlideIndex = 0,
        getSlideArray, evtCbs,moveHelpers, showSlide, init;

    getSlideArray = function () {
       return  document.querySelectorAll('.slide');
    };
    function setupSlides () {
        var slides = getSlideArray();
        for (var i=0,panels, slide; i< slides.length; i++) {
            slide = slides[i];
            panels = slide.querySelectorAll('.slide__content');
            slide.querySelector('.js-slideNum').innerHTML = (i + 1) + ' of ' + slides.length;
            slide.id = 'js-slide--' + i;
            slide.classList.add('js-slide--' + i);
            slide.dataset.slideindex = i;
            slide.dataset.panelcount = panels.length;
            for (var n=0, panel; n < panels.length; n++) {
                panel = panels[n];
               // panel.id = slide.id + '-panel--' + n;
                panel.classList.add('js-panel--' + n);
                if (n === 0) {
                    panel.classList.add('ui-visible');
                }
            }
            if (i === 0) {
                slide.classList.add('ui-current');
                currentSlideIndex = i;
            }

        }
    };

    showSlide = {
        currentSlide: 0,
        gotoSlide : function (i) {
            var rootSlide = document.querySelector('.slides .slide'),
                articleWidth = rootSlide.offsetWidth + rootSlide.style.marginRight,
                currentSlide = document.getElementById('js-slide--' + i),
                currentPanel = currentSlide.querySelector('.slide__content');
            rootSlide.style.marginLeft = 0 - (articleWidth * i) + 'px';
            document.querySelector('.ui-current').classList.remove('ui-current');
            currentSlide.classList.add('ui-current');
            currentPanel.classList.add('ui-visible');
            history.pushState(currentSlide.dataset.title, "slide " + i, '#' + currentSlide.dataset.title.replace(' ', '-'))
        },
        next: function () {
            if (this.currentSlide < slideshow.modules.navigation.getSlideCount-1) this.currentSlide++;
            this.gotoSlide(this.currentSlide);
        },
        prev: function () {
            if (this.currentSlide > 0) this.currentSlide--;
            this.gotoSlide(this.currentSlide)
        }
    };
    showPanel = {
        currentPanel: 0,
        panelCount: function () {
            var currentSlide = document.querySelector('.ui-current');
            return parseInt(currentSlide.dataset.panelcount, 10);
        },
        gotoPanel: function (i) {
            var currentSlide = document.querySelector('.ui-current'),
                hiddenTopPaneli = i > 0 ? i-1 : 0,
                hiddenBottomPaneli = i < this.panelCount() ? i + 1 : this.panelCount(),
                currentPanel = currentSlide.querySelector('.js-panel--' + i),
                hiddenTopPanel = currentSlide.querySelector('.js-panel--' + hiddenTopPaneli);
            hiddenTopPanel.classList.add('ui-hiddenTop');
            hiddenTopPanel.classList.remove('ui-visible');
            currentPanel.classList.remove('ui-hiddenTop');
            currentPanel.classList.add('ui-visible');
        },
        next: function () {
            if (this.currentPanel < this.panelCount() - 1) this.currentPanel++;
            this.gotoPanel(this.currentPanel);

        },
        prev: function () {
            var currentSlide = document.querySelector('.ui-current');
            if (this.currentPanel > 0) {
                this.currentPanel--;
                currentSlide.querySelector('.ui-visible').classList.remove('ui-visible');
            };
            this.gotoPanel(this.currentPanel);

        }
    };
    evtCbs = {

        keyup: function (e) {
            e.preventDefault();
            switch (e.which) {
                case 37:
                //left
                slideshow.modules.navigation.navigate.next();
                break;
                case 39:
                //right
                slideshow.modules.navigation.navigate.prev();
                break;
                case 38:
                //up
                slideshow.modules.navigation.view.prev();
                break;
                case 40:
                //down
                slideshow.modules.navigation.view.next();
                break;
                default:
                break;
            }
        },
        navClick: function (e) {
            e.preventDefault();
            console.log(e);
            var slides = document.querySelector('.slides'),
                humanID = e.target.href.slice(e.target.href.indexOf('#')).replace('#',''),
                targetSlide = slides.querySelector('#'+humanID).parentNode,
                targetIndex = targetSlide.dataset.slideindex;

            slideshow.modules.navigation.navigate.gotoSlide(targetIndex);
            history.pushState(null,null,'#'+humanID);
            console.log(humanID, targetIndex);
        }
    };
    function bindUiEvts () {
        window.addEventListener('keyup', evtCbs.keyup);
        [].forEach.call(document.querySelectorAll('.slideNav .list__item__link'), function (navLink) {
            navLink.addEventListener('click', evtCbs.navClick);
        });
        var slides = document.querySelector('.slides'),
            body = document.querySelector('body'),
            hslides = new Hammer(slides),
            hbody = new Hammer(body);
        hslides.on('swipeleft', function (e) {
            slideshow.modules.navigation.navigate.next();
        });
        hslides.on('swiperight', function (e) {
            slideshow.modules.navigation.navigate.prev();
        });
        hslides.on('pandown', function (e) {
            slideshow.modules.navigation.view.prev();
        });
        hslides.on('panup', function (e) {
            slideshow.modules.navigation.view.next();
        });

    };
    init = function( ) {
        setupSlides();
        bindUiEvts();
    };
    init();
    public = {
        evtCbs: evtCbs,
        slides: getSlideArray(),
        getSlideCount: getSlideArray().length,
        navigate: showSlide,
        view: showPanel,
        currentSlide : currentSlideIndex
    }
    return public;

})();

/*================
    #NavBuilder
===============*/
slideshow.namespace('modules.navBuilder');
slideshow.modules.navBuilder = (function () {
    var navContainer = document.querySelector('.slideNav'),
        getSlideArray, navItemArray,navItem, init, evtCbs;

    getSlideArray = function () {
       return  document.querySelectorAll('.slide');
    };
    evtCbs = {
        navItemClick: function (e) {
            e.preventDefault();

        }
    };

    navItem = function (slide) {
        var slideLink = document.createElement('a'),
            clonedSlide = slide.cloneNode(true);

        slideLink.href = "#"+ slide.id;
        slideLink.classList.add('slideNav__link');
        clonedSlide.id = '';
        slideLink.appendChild(clonedSlide);

        slideLink.addEventListener('click', evtCbs.navItemClick,false);
        return slideLink;
    };

    function bindUiEvts() {

    };
    function init() {
        //setupNavItems();
        bindUiEvts();
    };
    init();
    return {};
})();

/*================
    #UIControls
===============*/
slideshow.namespace('modules.ui');
slideshow.modules.ui = (function () {
    var public = {}, evtCbs = {};

    public.toggleSidebar = function () {
        var sidebar = document.querySelector('.slideNav');
        sidebar.classList.toggle('ui-collapsed');
    };
    public.toggleMain = function () {
        var sidebar = document.querySelector('.slideNav');
        sidebar.classList.toggle('ui-expandedfull');
    };
    public.toggleFullscreen= function () {
          if (!document.fullscreenElement &&    // alternative standard method
              !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement ) {  // current working methods
            if (document.documentElement.requestFullscreen) {
              document.documentElement.requestFullscreen();
            } else if (document.documentElement.msRequestFullscreen) {
              document.documentElement.msRequestFullscreen();
            } else if (document.documentElement.mozRequestFullScreen) {
              document.documentElement.mozRequestFullScreen();
            } else if (document.documentElement.webkitRequestFullscreen) {
              document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
            }
          } else {
            if (document.exitFullscreen) {
              document.exitFullscreen();
            } else if (document.msExitFullscreen) {
              document.msExitFullscreen();
            } else if (document.mozCancelFullScreen) {
              document.mozCancelFullScreen();
            } else if (document.webkitExitFullscreen) {
              document.webkitExitFullscreen();
            }
          }

    };
    evtCbs = {
        keydown: function (e) {
            if (e.ctrlKey) {
                console.log(e.which);
                switch (e.which) {
                    case 73:
                    //i
                    slideshow.modules.ui.toggleMain();
                    break;
                    case 70:
                    //f
                    slideshow.modules.ui.toggleFullscreen();
                    break;
                    case 83:
                    //s
                    slideshow.modules.ui.toggleSidebar();
                    break;
                    case 78:
                    slideshow.modules.ui.toggleSidebar();
                    //n
                    break;
                    default:
                    break;
                }
            }
        },
        pushHash: function (e) {
            console.log(e);

        }
    };

    function bindUiEvts() {
        var nav = document.querySelector('.slideNav'),
            hNav = new Hammer(nav);

        hNav.on('swipeleft', function (e) {
            console.log(e);
            slideshow.modules.ui.toggleSidebar();
        });
        hNav.on('swiperight', function (e) {
            console.log(e);
            slideshow.modules.ui.toggleSidebar();
        });
        hNav.add(new Hammer.Tap({event: 'doubletap', taps: 2}));
        hNav.on('doubletap', function (e) {
            slideshow.modules.ui.toggleSidebar();
            console.log('doubletapped')
        });
        window.addEventListener('keydown', evtCbs.keydown);
        window.addEventListener('hashchange', evtCbs.pushHash);
        //to do: add in the history API, Hash by titles or slide number
    };
    function init() {
        bindUiEvts();
    }
    init();
    return public;
})();

slideshow.init();<|endoftext|>


<commit_before>import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
import { computed } from '@ember/object';
import { w } from '@ember/string';
import countryList from 'iso-3166-country-list';

// states and provinces use iso-3166-2 codes
const stateList = [
  { code: 'US-AL', name: 'Alabama' },
  { code: 'US-AK', name: 'Alaska' },
  { code: 'US-AZ', name: 'Arizona' },
  { code: 'US-AR', name: 'Arkansas' },
  { code: 'US-CA', name: 'California' },
  { code: 'US-CO', name: 'Colorado' },
  { code: 'US-CT', name: 'Connecticut' },
  { code: 'US-DE', name: 'Delaware' },
  { code: 'US-FL', name: 'Florida' },
  { code: 'US-GA', name: 'Georgia' },
  { code: 'US-HI', name: 'Hawaii' },
  { code: 'US-ID', name: 'Idaho' },
  { code: 'US-IL', name: 'Illinois' },
  { code: 'US-IN', name: 'Indiana' },
  { code: 'US-IA', name: 'Iowa' },
  { code: 'US-KS', name: 'Kansas' },
  { code: 'US-KY', name: 'Kentucky' },
  { code: 'US-LA', name: 'Louisiana' },
  { code: 'US-ME', name: 'Maine' },
  { code: 'US-MD', name: 'Maryland' },
  { code: 'US-MA', name: 'Massachusetts' },
  { code: 'US-MI', name: 'Michigan' },
  { code: 'US-MN', name: 'Minnesota' },
  { code: 'US-MS', name: 'Mississippi' },
  { code: 'US-MO', name: 'Missouri' },
  { code: 'US-MT', name: 'Montana' },
  { code: 'US-NE', name: 'Nebraska' },
  { code: 'US-NV', name: 'Nevada' },
  { code: 'US-NH', name: 'New Hampshire' },
  { code: 'US-NJ', name: 'New Jersey' },
  { code: 'US-NM', name: 'New Mexico' },
  { code: 'US-NY', name: 'New York' },
  { code: 'US-NC', name: 'North Carolina' },
  { code: 'US-ND', name: 'North Dakota' },
  { code: 'US-OH', name: 'Ohio' },
  { code: 'US-OK', name: 'Oklahoma' },
  { code: 'US-OR', name: 'Oregon' },
  { code: 'US-PA', name: 'Pennsylvania' },
  { code: 'US-RI', name: 'Rhode Island' },
  { code: 'US-SC', name: 'South Carolina' },
  { code: 'US-SD', name: 'South Dakota' },
  { code: 'US-TN', name: 'Tennessee' },
  { code: 'US-TX', name: 'Texas' },
  { code: 'US-UT', name: 'Utah' },
  { code: 'US-VT', name: 'Vermont' },
  { code: 'US-VA', name: 'Virginia' },
  { code: 'US-WA', name: 'Washington' },
  { code: 'US-WV', name: 'West Virginia' },
  { code: 'US-WI', name: 'Wisconsin' },
  { code: 'US-WY', name: 'Wyoming' },
  { code: 'US-DC', name: 'District of Columbia' },
  { code: 'US-AS', name: 'American Samoa' },
  { code: 'US-GU', name: 'Guam' },
  { code: 'US-MP', name: 'Northern Mariana Islands' },
  { code: 'US-PR', name: 'Puerto Rico' },
  { code: 'US-UM', name: 'United States Minor Outlying Islands' },
  { code: 'US-VI', name: 'Virgin Islands, U.S.' },
];

const provinceListCanada = [
  { code: 'CA-AB', name: 'Alberta' },
  { code: 'CA-BC', name: 'British Columbia (Colombie-Britannique)' },
  { code: 'CA-MB', name: 'Manitoba' },
  { code: 'CA-NB', name: 'New Brunswick (Nouveau-Brunswick)' },
  { code: 'CA-NL', name: 'Newfoundland and Labrador (Terre-Neuve)' },
  { code: 'CA-NS', name: 'Nova Scotia (Nouvelle-Écosse)' },
  { code: 'CA-ON', name: 'Ontario' },
  { code: 'CA-PE', name: 'Prince Edward Island (Île-du-Prince-Édouard)' },
  { code: 'CA-QC', name: 'Quebec (Québec)' },
  { code: 'CA-SK', name: 'Saskatchewan' },
  { code: 'CA-NT', name: 'Northwest Territories (Territoires du Nord-Ouest)' },
  { code: 'CA-NU', name: 'Nunavut' },
  { code: 'CA-YT', name: 'Yukon Territory (Teritoire du Yukon)' },
];

const provinceListChina = [
  { code: 'CN-34', name: 'Anhui' },
  { code: 'CN-11', name: 'Beijing' },
  { code: 'CN-50', name: 'Chongqing' },
  { code: 'CN-35', name: 'Fujian' },
  { code: 'CN-62', name: 'Gansu' },
  { code: 'CN-44', name: 'Guangdong' },
  { code: 'CN-45', name: 'Guangxi' },
  { code: 'CN-52', name: 'Guizhou' },
  { code: 'CN-46', name: 'Hainan' },
  { code: 'CN-13', name: 'Hebei' },
  { code: 'CN-23', name: 'Heilongjiang' },
  { code: 'CN-41', name: 'Henan' },
  { code: 'CN-91', name: 'Hong Kong' },
  { code: 'CN-42', name: 'Hubei' },
  { code: 'CN-43', name: 'Hunan' },
  { code: 'CN-32', name: 'Jiangsu' },
  { code: 'CN-36', name: 'Jiangxi' },
  { code: 'CN-22', name: 'Jilin' },
  { code: 'CN-21', name: 'Liaoning' },
  { code: 'CN-15', name: 'Nei Monggol' },
  { code: 'CN-64', name: 'Ningxia' },
  { code: 'CN-63', name: 'Qinghai' },
  { code: 'CN-61', name: 'Shaanxi' },
  { code: 'CN-37', name: 'Shandong' },
  { code: 'CN-31', name: 'Shanghai' },
  { code: 'CN-14', name: 'Shanxi' },
  { code: 'CN-51', name: 'Sichuan' },
  { code: 'CN-71', name: 'Taiwan' },
  { code: 'CN-12', name: 'Tianjin' },
  { code: 'CN-65', name: 'Xinjiang' },
  { code: 'CN-54', name: 'Xizang' },
  { code: 'CN-53', name: 'Yunnan' },
  { code: 'CN-33', name: 'Zhejiang' },
];

const stateListAustralia = [
  { code: 'AU-NSW', name: 'New South Wales' },
  { code: 'AU-QLD', name: 'Queensland' },
  { code: 'AU-SA', name: 'South Australia' },
  { code: 'AU-TAS', name: 'Tasmania' },
  { code: 'AU-VIC', name: 'Victoria' },
  { code: 'AU-WA', name: 'Western Australia' },
  { code: 'AU-ACT', name: 'Australian Capital Territory' },
  { code: 'AU-NT', name: 'Northern Territory' },
];

const organizationTypeList = [
  'researchInstitution',
  'academicInstitution',
  'governmentAgency',
  'nationalInstitution',
  'professionalSociety',
  'publisher',
  'serviceProvider',
  'other',
];
const memberTypeList = [
  'consortium',
  'consortium_organization',
  'contractual_member',
  'direct_member',
  'member_only',
  'registration_agency',
];
const focusAreaList = [
  'naturalSciences',
  'engineeringAndTechnology',
  'medicalAndHealthSciences',
  'agriculturalSciences',
  'socialSciences',
  'humanities',
  'general',
];

const nonProfitStatusList = [
  'non-profit',
  'for-profit',
];

export default Controller.extend({
  store: service(),
  features: service(),

  countryList,
  countries: null,
  stateList,
  provinceListCanada,
  provinceListChina,
  stateListAustralia,
  states: null,
  organizationTypeList,
  organizationTypes: organizationTypeList,
  memberTypeList,
  memberTypes: memberTypeList,
  focusAreaList,
  focusAreas: focusAreaList,
  nonProfitStatusList,
  nonProfitStatuses: nonProfitStatusList,
  organizations: [],
  consortia: [],
  // we are storing state/province information for US, CA, AU and CN
  showStateSearch: computed('model.billingInformation.country', function() {
    return this.model.get('billingInformation.country') && w('US CA AU CN').includes(this.model.get('billingInformation.country.code'));
  }),

  actions: {
    searchCountry(query) {
      let countries = countryList.filter(function(country) {
        return country.name.toLowerCase().startsWith(query.toLowerCase());
      });
      this.set('countries', countries);
    },
    selectCountry(country) {
      this.model.set('country', { code: country.code, name: countryList.name(country.code) });
      this.set('countries', countryList);
    },
    searchState(query) {
      let states = null;
      if (this.model.get('billingInformation.country.code') === 'US') {
        states = stateList.filter(function(state) {
          return state.name.toLowerCase().startsWith(query.toLowerCase());
        });
      } else if (this.model.get('billingInformation.country.code') === 'CA') {
        states = provinceListCanada.filter(function(state) {
          return state.name.toLowerCase().startsWith(query.toLowerCase());
        });
      } else if (this.model.get('billingInformation.country.code') === 'CN') {
        states = provinceListChina.filter(function(state) {
          return state.name.toLowerCase().startsWith(query.toLowerCase());
        });
      } else if (this.model.get('billingInformation.country.code') === 'AU') {
        states = stateListAustralia.filter(function(state) {
          return state.name.toLowerCase().startsWith(query.toLowerCase());
        });
      }
      this.set('states', states);
    },
    searchOrganizationType(query) {
      let organizationTypes = organizationTypeList.filter(function(organizationType) {
        return organizationType.startsWith(query.toLowerCase());
      });
      this.set('organizationTypes', organizationTypes);
    },
    selectOrganizationType(organizationType) {
      this.model.set('organizationType', organizationType);
      this.set('organizationTypes', organizationTypeList);
    },
    searchMemberType(query) {
      let memberTypes = memberTypeList.filter(function(memberType) {
        return memberType.startsWith(query.toLowerCase());
      });
      this.set('memberTypes', memberTypes);
    },
    selectMemberType(memberType) {
      this.model.set('memberType', memberType);
      this.set('memberTypes', memberTypeList);
    },
    searchFocusArea(query) {
      let focusAreas = focusAreaList.filter(function(focusArea) {
        return focusArea.startsWith(query.toLowerCase());
      });
      this.set('focusAreas', focusAreas);
    },
    selectFocusArea(focusArea) {
      this.model.set('focusArea', focusArea);
      this.set('focusAreas', focusAreaList);
    },
    searchNonProfitStatus(query) {
      let nonProfitStatuses = nonProfitStatusList.filter(function(nonProfitStatus) {
        return nonProfitStatus.startsWith(query.toLowerCase());
      });
      this.set('nonProfitStatuses', nonProfitStatuses);
    },
    selectNonProfitStatus(nonProfitStatus) {
      this.model.set('nonProfitStatus', nonProfitStatus);
      this.set('nonProfitStatuses', nonProfitStatusList);
    },
    searchConsortium(query) {
      this.set('consortia', this.store.query('provider', { query, 'member-type': 'consortium', sort: 'name', 'page[size]': 100 }));
    },
    selectConsortium(consortium) {
      this.model.set('consortium', consortium);
    },
    selectBillingCountry(billingCountry) {
      if (billingCountry) {
        this.model.set('billingInformation.country', { code: billingCountry.code, name: countryList.name(billingCountry.code) });
        this.model.set('billingInformation.state', null);
        this.set('countries', countryList);
      }
    },
    selectBillingState(billingState) {
      this.model.set('billingInformation.state', billingState);
    },
    searchRor(query) {
      let self = this;
      this.store.query('ror', { query }).then(function(organizations) {
        self.set('organizations', organizations);
      });
    },
    selectRor(ror) {
      if (ror) {
        this.model.set('rorId', ror.id);
        this.model.set('name', ror.name);
        this.model.set('displayName', ror.name);
      } else {
        this.model.set('rorId', null);
      }
      this.set('organizations', []);
    },
    didSelectFiles(file) {
      let reader = new FileReader();
      let self = this;

      reader.readAsDataURL(file.blob).then((logo) => {
        self.get('model').set('logo', logo);
      }, (err) => {
        console.error(err);
      });
    },
    submit() {
      let self = this;
      this.model.save().then(function(provider) {
        self.transitionToRoute('providers.show.settings', provider);
      }).catch(function(reason) {
        console.debug(reason);
      });
    },
    cancel() {
      this.model.rollbackAttributes();
      this.transitionToRoute('providers');
    },
  },
});
<commit_msg>add reminder for remaining countries that need state information<commit_after>import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
import { computed } from '@ember/object';
import { w } from '@ember/string';
import countryList from 'iso-3166-country-list';

// states and provinces use iso-3166-2 codes
// TODO add Brazil, India, Ireland, Italy, Mexico, all supported in Salesforce
const stateList = [
  { code: 'US-AL', name: 'Alabama' },
  { code: 'US-AK', name: 'Alaska' },
  { code: 'US-AZ', name: 'Arizona' },
  { code: 'US-AR', name: 'Arkansas' },
  { code: 'US-CA', name: 'California' },
  { code: 'US-CO', name: 'Colorado' },
  { code: 'US-CT', name: 'Connecticut' },
  { code: 'US-DE', name: 'Delaware' },
  { code: 'US-FL', name: 'Florida' },
  { code: 'US-GA', name: 'Georgia' },
  { code: 'US-HI', name: 'Hawaii' },
  { code: 'US-ID', name: 'Idaho' },
  { code: 'US-IL', name: 'Illinois' },
  { code: 'US-IN', name: 'Indiana' },
  { code: 'US-IA', name: 'Iowa' },
  { code: 'US-KS', name: 'Kansas' },
  { code: 'US-KY', name: 'Kentucky' },
  { code: 'US-LA', name: 'Louisiana' },
  { code: 'US-ME', name: 'Maine' },
  { code: 'US-MD', name: 'Maryland' },
  { code: 'US-MA', name: 'Massachusetts' },
  { code: 'US-MI', name: 'Michigan' },
  { code: 'US-MN', name: 'Minnesota' },
  { code: 'US-MS', name: 'Mississippi' },
  { code: 'US-MO', name: 'Missouri' },
  { code: 'US-MT', name: 'Montana' },
  { code: 'US-NE', name: 'Nebraska' },
  { code: 'US-NV', name: 'Nevada' },
  { code: 'US-NH', name: 'New Hampshire' },
  { code: 'US-NJ', name: 'New Jersey' },
  { code: 'US-NM', name: 'New Mexico' },
  { code: 'US-NY', name: 'New York' },
  { code: 'US-NC', name: 'North Carolina' },
  { code: 'US-ND', name: 'North Dakota' },
  { code: 'US-OH', name: 'Ohio' },
  { code: 'US-OK', name: 'Oklahoma' },
  { code: 'US-OR', name: 'Oregon' },
  { code: 'US-PA', name: 'Pennsylvania' },
  { code: 'US-RI', name: 'Rhode Island' },
  { code: 'US-SC', name: 'South Carolina' },
  { code: 'US-SD', name: 'South Dakota' },
  { code: 'US-TN', name: 'Tennessee' },
  { code: 'US-TX', name: 'Texas' },
  { code: 'US-UT', name: 'Utah' },
  { code: 'US-VT', name: 'Vermont' },
  { code: 'US-VA', name: 'Virginia' },
  { code: 'US-WA', name: 'Washington' },
  { code: 'US-WV', name: 'West Virginia' },
  { code: 'US-WI', name: 'Wisconsin' },
  { code: 'US-WY', name: 'Wyoming' },
  { code: 'US-DC', name: 'District of Columbia' },
  { code: 'US-AS', name: 'American Samoa' },
  { code: 'US-GU', name: 'Guam' },
  { code: 'US-MP', name: 'Northern Mariana Islands' },
  { code: 'US-PR', name: 'Puerto Rico' },
  { code: 'US-UM', name: 'United States Minor Outlying Islands' },
  { code: 'US-VI', name: 'Virgin Islands, U.S.' },
];

const provinceListCanada = [
  { code: 'CA-AB', name: 'Alberta' },
  { code: 'CA-BC', name: 'British Columbia (Colombie-Britannique)' },
  { code: 'CA-MB', name: 'Manitoba' },
  { code: 'CA-NB', name: 'New Brunswick (Nouveau-Brunswick)' },
  { code: 'CA-NL', name: 'Newfoundland and Labrador (Terre-Neuve)' },
  { code: 'CA-NS', name: 'Nova Scotia (Nouvelle-Écosse)' },
  { code: 'CA-ON', name: 'Ontario' },
  { code: 'CA-PE', name: 'Prince Edward Island (Île-du-Prince-Édouard)' },
  { code: 'CA-QC', name: 'Quebec (Québec)' },
  { code: 'CA-SK', name: 'Saskatchewan' },
  { code: 'CA-NT', name: 'Northwest Territories (Territoires du Nord-Ouest)' },
  { code: 'CA-NU', name: 'Nunavut' },
  { code: 'CA-YT', name: 'Yukon Territory (Teritoire du Yukon)' },
];

const provinceListChina = [
  { code: 'CN-34', name: 'Anhui' },
  { code: 'CN-11', name: 'Beijing' },
  { code: 'CN-50', name: 'Chongqing' },
  { code: 'CN-35', name: 'Fujian' },
  { code: 'CN-62', name: 'Gansu' },
  { code: 'CN-44', name: 'Guangdong' },
  { code: 'CN-45', name: 'Guangxi' },
  { code: 'CN-52', name: 'Guizhou' },
  { code: 'CN-46', name: 'Hainan' },
  { code: 'CN-13', name: 'Hebei' },
  { code: 'CN-23', name: 'Heilongjiang' },
  { code: 'CN-41', name: 'Henan' },
  { code: 'CN-91', name: 'Hong Kong' },
  { code: 'CN-42', name: 'Hubei' },
  { code: 'CN-43', name: 'Hunan' },
  { code: 'CN-32', name: 'Jiangsu' },
  { code: 'CN-36', name: 'Jiangxi' },
  { code: 'CN-22', name: 'Jilin' },
  { code: 'CN-21', name: 'Liaoning' },
  { code: 'CN-15', name: 'Nei Monggol' },
  { code: 'CN-64', name: 'Ningxia' },
  { code: 'CN-63', name: 'Qinghai' },
  { code: 'CN-61', name: 'Shaanxi' },
  { code: 'CN-37', name: 'Shandong' },
  { code: 'CN-31', name: 'Shanghai' },
  { code: 'CN-14', name: 'Shanxi' },
  { code: 'CN-51', name: 'Sichuan' },
  { code: 'CN-71', name: 'Taiwan' },
  { code: 'CN-12', name: 'Tianjin' },
  { code: 'CN-65', name: 'Xinjiang' },
  { code: 'CN-54', name: 'Xizang' },
  { code: 'CN-53', name: 'Yunnan' },
  { code: 'CN-33', name: 'Zhejiang' },
];

const stateListAustralia = [
  { code: 'AU-NSW', name: 'New South Wales' },
  { code: 'AU-QLD', name: 'Queensland' },
  { code: 'AU-SA', name: 'South Australia' },
  { code: 'AU-TAS', name: 'Tasmania' },
  { code: 'AU-VIC', name: 'Victoria' },
  { code: 'AU-WA', name: 'Western Australia' },
  { code: 'AU-ACT', name: 'Australian Capital Territory' },
  { code: 'AU-NT', name: 'Northern Territory' },
];

const organizationTypeList = [
  'researchInstitution',
  'academicInstitution',
  'governmentAgency',
  'nationalInstitution',
  'professionalSociety',
  'publisher',
  'serviceProvider',
  'other',
];
const memberTypeList = [
  'consortium',
  'consortium_organization',
  'contractual_member',
  'direct_member',
  'member_only',
  'registration_agency',
];
const focusAreaList = [
  'naturalSciences',
  'engineeringAndTechnology',
  'medicalAndHealthSciences',
  'agriculturalSciences',
  'socialSciences',
  'humanities',
  'general',
];

const nonProfitStatusList = [
  'non-profit',
  'for-profit',
];

export default Controller.extend({
  store: service(),
  features: service(),

  countryList,
  countries: null,
  stateList,
  provinceListCanada,
  provinceListChina,
  stateListAustralia,
  states: null,
  organizationTypeList,
  organizationTypes: organizationTypeList,
  memberTypeList,
  memberTypes: memberTypeList,
  focusAreaList,
  focusAreas: focusAreaList,
  nonProfitStatusList,
  nonProfitStatuses: nonProfitStatusList,
  organizations: [],
  consortia: [],
  // we are storing state/province information for US, CA, AU and CN
  showStateSearch: computed('model.billingInformation.country', function() {
    return this.model.get('billingInformation.country') && w('US CA AU CN').includes(this.model.get('billingInformation.country.code'));
  }),

  actions: {
    searchCountry(query) {
      let countries = countryList.filter(function(country) {
        return country.name.toLowerCase().startsWith(query.toLowerCase());
      });
      this.set('countries', countries);
    },
    selectCountry(country) {
      this.model.set('country', { code: country.code, name: countryList.name(country.code) });
      this.set('countries', countryList);
    },
    searchState(query) {
      let states = null;
      if (this.model.get('billingInformation.country.code') === 'US') {
        states = stateList.filter(function(state) {
          return state.name.toLowerCase().startsWith(query.toLowerCase());
        });
      } else if (this.model.get('billingInformation.country.code') === 'CA') {
        states = provinceListCanada.filter(function(state) {
          return state.name.toLowerCase().startsWith(query.toLowerCase());
        });
      } else if (this.model.get('billingInformation.country.code') === 'CN') {
        states = provinceListChina.filter(function(state) {
          return state.name.toLowerCase().startsWith(query.toLowerCase());
        });
      } else if (this.model.get('billingInformation.country.code') === 'AU') {
        states = stateListAustralia.filter(function(state) {
          return state.name.toLowerCase().startsWith(query.toLowerCase());
        });
      }
      this.set('states', states);
    },
    searchOrganizationType(query) {
      let organizationTypes = organizationTypeList.filter(function(organizationType) {
        return organizationType.startsWith(query.toLowerCase());
      });
      this.set('organizationTypes', organizationTypes);
    },
    selectOrganizationType(organizationType) {
      this.model.set('organizationType', organizationType);
      this.set('organizationTypes', organizationTypeList);
    },
    searchMemberType(query) {
      let memberTypes = memberTypeList.filter(function(memberType) {
        return memberType.startsWith(query.toLowerCase());
      });
      this.set('memberTypes', memberTypes);
    },
    selectMemberType(memberType) {
      this.model.set('memberType', memberType);
      this.set('memberTypes', memberTypeList);
    },
    searchFocusArea(query) {
      let focusAreas = focusAreaList.filter(function(focusArea) {
        return focusArea.startsWith(query.toLowerCase());
      });
      this.set('focusAreas', focusAreas);
    },
    selectFocusArea(focusArea) {
      this.model.set('focusArea', focusArea);
      this.set('focusAreas', focusAreaList);
    },
    searchNonProfitStatus(query) {
      let nonProfitStatuses = nonProfitStatusList.filter(function(nonProfitStatus) {
        return nonProfitStatus.startsWith(query.toLowerCase());
      });
      this.set('nonProfitStatuses', nonProfitStatuses);
    },
    selectNonProfitStatus(nonProfitStatus) {
      this.model.set('nonProfitStatus', nonProfitStatus);
      this.set('nonProfitStatuses', nonProfitStatusList);
    },
    searchConsortium(query) {
      this.set('consortia', this.store.query('provider', { query, 'member-type': 'consortium', sort: 'name', 'page[size]': 100 }));
    },
    selectConsortium(consortium) {
      this.model.set('consortium', consortium);
    },
    selectBillingCountry(billingCountry) {
      if (billingCountry) {
        this.model.set('billingInformation.country', { code: billingCountry.code, name: countryList.name(billingCountry.code) });
        this.model.set('billingInformation.state', null);
        this.set('countries', countryList);
      }
    },
    selectBillingState(billingState) {
      this.model.set('billingInformation.state', billingState);
    },
    searchRor(query) {
      let self = this;
      this.store.query('ror', { query }).then(function(organizations) {
        self.set('organizations', organizations);
      });
    },
    selectRor(ror) {
      if (ror) {
        this.model.set('rorId', ror.id);
        this.model.set('name', ror.name);
        this.model.set('displayName', ror.name);
      } else {
        this.model.set('rorId', null);
      }
      this.set('organizations', []);
    },
    didSelectFiles(file) {
      let reader = new FileReader();
      let self = this;

      reader.readAsDataURL(file.blob).then((logo) => {
        self.get('model').set('logo', logo);
      }, (err) => {
        console.error(err);
      });
    },
    submit() {
      let self = this;
      this.model.save().then(function(provider) {
        self.transitionToRoute('providers.show.settings', provider);
      }).catch(function(reason) {
        console.debug(reason);
      });
    },
    cancel() {
      this.model.rollbackAttributes();
      this.transitionToRoute('providers');
    },
  },
});
<|endoftext|>


<commit_before>// Recomputes all computed indexes and reduced records

'use strict';

var aFrom              = require('es5-ext/array/from')
  , findIndex          = require('es5-ext/array/#/find-index')
  , flatten            = require('es5-ext/array/#/flatten')
  , ensureIterable     = require('es5-ext/iterable/validate-object')
  , ensureString       = require('es5-ext/object/validate-stringifiable-value')
  , startsWith         = require('es5-ext/string/#/starts-with')
  , Map                = require('es6-map')
  , deferred           = require('deferred')
  , debug              = require('debug-ext')('setup', 4)
  , ensureDriver       = require('dbjs-persistence/ensure-driver')
  , recompute          = require('dbjs-persistence/recompute')
  , isOfficialRoleName = require('../../../utils/is-official-role-name');

module.exports = function (driver, slavePath/*, options*/) {
	var userStorage = ensureDriver(driver).getStorage('user')
	  , anyIdToStorage = require('../../utils/any-id-to-storage')
	  , businessProcessStorages = require('../../utils/business-process-storages')
	  , options = Object(arguments[2]), userManagers = new Map()
	  , officialPropertyNames;

	if (options.officialPropertyNames) {
		officialPropertyNames = aFrom(ensureIterable(officialPropertyNames));
	} else {
		officialPropertyNames = ['firstName', 'lastName'];
	}

	var getBusinessProcessData = function (bpId) {
		return anyIdToStorage(bpId)(function (storage) {
			if (!storage) return [];
			return storage.getObject(bpId)(function (bpData) {
				var id = bpId + '/derivedBusinessProcess';
				return deferred.map(bpData, function (data) {
					if (data.id !== id) return data;
					if (data.data.value[0] !== '7') return data;
					return getBusinessProcessData(data.data.value.slice(1))(function (result) {
						result.push(data);
						return result;
					});
				});
			});
		});
	};

	var getUserData = function (userId) {
		return userStorage.getObject(userId)(function (userData) {
			var prefix = userId + '/initialBusinessProcesses*7';
			return deferred.map(userData, function (data) {
				if (!startsWith.call(data.id, prefix)) return data;
				if (data.data.value !== '11') return data;
				return getBusinessProcessData(data.id.slice(prefix.length))(function (result) {
					result.push(data);
					return result;
				});
			});
		});
	};

	return deferred(
		userStorage.search({ keyPath: 'manager' }, function (id, data) {
			var managerId;
			if (data.value[0] !== '7') return;
			managerId = data.value.slice(1);
			if (!userManagers.has(managerId)) userManagers.set(managerId, []);
			userManagers.get(managerId).push(id.split('/', 1)[0]);
		}),
		businessProcessStorages.map(function (storage) {
			var businessProcessManagers = new Map();
			return storage.search({ keyPath: 'manager' }, function (id, data) {
				var managerId;
				if (data.value[0] !== '7') return;
				managerId = data.value.slice(1);
				businessProcessManagers.set(id.split('/', 1)[0], managerId);
			})(function () {
				return userStorage.search({ keyPath: 'initialBusinessProcesses' }, function (id, data) {
					var managerId;
					if (data.value !== '11') return;
					managerId = businessProcessManagers.get(id.slice(id.lastIndexOf('*') + 2));
					if (!managerId) return;
					if (!userManagers.has(managerId)) userManagers.set(managerId, []);
					userManagers.get(managerId).push(id.split('/', 1)[0]);
				});
			});
		})
	)(function () {

		var getManagerData = function (managerId) {
			if (!userManagers.has(managerId)) return [];
			return deferred.map(userManagers.get(managerId), getUserData);
		};

		var initialData = userStorage.search(function (id, data) {
			var userId = id.split('/', 1)[0];
			return userStorage.getObjectKeyPath(userId + '/roles')(function (records) {
				var isOfficial = records.some(function (record) {
					var roleName;
					if (record.data.value !== '11') return;
					roleName = record.id.slice((userId + '/roles*').length);
					if (isOfficialRoleName(roleName)) return true;
				});
				if (!isOfficial) return;
				return userStorage.getObject(userId, { keyPaths: officialPropertyNames });
			});
		})(function (data) {
			data = flatten.call(data).filter(Boolean);
			if (!options.initialData) return data;
			return deferred(options.initialData)(function (optionalData) {
				return data.concat(flatten.call(optionalData).filter(Boolean))
					.filter(function (record, index, all) {
						// Filter duplicate records
						return findIndex.call(all, function (item) { return record.id === item.id; }) === index;
					});
			});
		});
		debug.open("db-recompute");
		return recompute(driver, {
			slaveScriptPath: ensureString(slavePath),
			ids: userStorage.getAllObjectIds(),
			getData: function (userId) {
				return deferred(
					getUserData(userId),
					getManagerData(userId)
				).invoke(flatten);
			},
			initialData: initialData
		}).on('progress', function (event) {
			if (event.type === 'nextObject') debug.progress();
			if (event.type === 'nextPool') debug.progress('↻');
		});
	})(function () {
		debug.progress('|');
		return driver.recalculateAllSizes();
	})(function (stats) {
		debug.progress(' masters: ' + stats.mastersCount + ', records: ' + stats.recordCount +
			' maxRecords: ' + stats.maxRecordsPerMasterCount);
		debug.close();
	});
};
<commit_msg>Fix stats output<commit_after>// Recomputes all computed indexes and reduced records

'use strict';

var aFrom              = require('es5-ext/array/from')
  , findIndex          = require('es5-ext/array/#/find-index')
  , flatten            = require('es5-ext/array/#/flatten')
  , ensureIterable     = require('es5-ext/iterable/validate-object')
  , ensureString       = require('es5-ext/object/validate-stringifiable-value')
  , startsWith         = require('es5-ext/string/#/starts-with')
  , Map                = require('es6-map')
  , deferred           = require('deferred')
  , debug              = require('debug-ext')('setup', 4)
  , ensureDriver       = require('dbjs-persistence/ensure-driver')
  , recompute          = require('dbjs-persistence/recompute')
  , isOfficialRoleName = require('../../../utils/is-official-role-name');

module.exports = function (driver, slavePath/*, options*/) {
	var userStorage = ensureDriver(driver).getStorage('user')
	  , anyIdToStorage = require('../../utils/any-id-to-storage')
	  , businessProcessStorages = require('../../utils/business-process-storages')
	  , options = Object(arguments[2]), userManagers = new Map()
	  , officialPropertyNames;

	if (options.officialPropertyNames) {
		officialPropertyNames = aFrom(ensureIterable(officialPropertyNames));
	} else {
		officialPropertyNames = ['firstName', 'lastName'];
	}

	var getBusinessProcessData = function (bpId) {
		return anyIdToStorage(bpId)(function (storage) {
			if (!storage) return [];
			return storage.getObject(bpId)(function (bpData) {
				var id = bpId + '/derivedBusinessProcess';
				return deferred.map(bpData, function (data) {
					if (data.id !== id) return data;
					if (data.data.value[0] !== '7') return data;
					return getBusinessProcessData(data.data.value.slice(1))(function (result) {
						result.push(data);
						return result;
					});
				});
			});
		});
	};

	var getUserData = function (userId) {
		return userStorage.getObject(userId)(function (userData) {
			var prefix = userId + '/initialBusinessProcesses*7';
			return deferred.map(userData, function (data) {
				if (!startsWith.call(data.id, prefix)) return data;
				if (data.data.value !== '11') return data;
				return getBusinessProcessData(data.id.slice(prefix.length))(function (result) {
					result.push(data);
					return result;
				});
			});
		});
	};

	return deferred(
		userStorage.search({ keyPath: 'manager' }, function (id, data) {
			var managerId;
			if (data.value[0] !== '7') return;
			managerId = data.value.slice(1);
			if (!userManagers.has(managerId)) userManagers.set(managerId, []);
			userManagers.get(managerId).push(id.split('/', 1)[0]);
		}),
		businessProcessStorages.map(function (storage) {
			var businessProcessManagers = new Map();
			return storage.search({ keyPath: 'manager' }, function (id, data) {
				var managerId;
				if (data.value[0] !== '7') return;
				managerId = data.value.slice(1);
				businessProcessManagers.set(id.split('/', 1)[0], managerId);
			})(function () {
				return userStorage.search({ keyPath: 'initialBusinessProcesses' }, function (id, data) {
					var managerId;
					if (data.value !== '11') return;
					managerId = businessProcessManagers.get(id.slice(id.lastIndexOf('*') + 2));
					if (!managerId) return;
					if (!userManagers.has(managerId)) userManagers.set(managerId, []);
					userManagers.get(managerId).push(id.split('/', 1)[0]);
				});
			});
		})
	)(function () {

		var getManagerData = function (managerId) {
			if (!userManagers.has(managerId)) return [];
			return deferred.map(userManagers.get(managerId), getUserData);
		};

		var initialData = userStorage.search(function (id, data) {
			var userId = id.split('/', 1)[0];
			return userStorage.getObjectKeyPath(userId + '/roles')(function (records) {
				var isOfficial = records.some(function (record) {
					var roleName;
					if (record.data.value !== '11') return;
					roleName = record.id.slice((userId + '/roles*').length);
					if (isOfficialRoleName(roleName)) return true;
				});
				if (!isOfficial) return;
				return userStorage.getObject(userId, { keyPaths: officialPropertyNames });
			});
		})(function (data) {
			data = flatten.call(data).filter(Boolean);
			if (!options.initialData) return data;
			return deferred(options.initialData)(function (optionalData) {
				return data.concat(flatten.call(optionalData).filter(Boolean))
					.filter(function (record, index, all) {
						// Filter duplicate records
						return findIndex.call(all, function (item) { return record.id === item.id; }) === index;
					});
			});
		});
		debug.open("db-recompute");
		return recompute(driver, {
			slaveScriptPath: ensureString(slavePath),
			ids: userStorage.getAllObjectIds(),
			getData: function (userId) {
				return deferred(
					getUserData(userId),
					getManagerData(userId)
				).invoke(flatten);
			},
			initialData: initialData
		}).on('progress', function (event) {
			if (event.type === 'nextObject') debug.progress();
			if (event.type === 'nextPool') debug.progress('↻');
		});
	})(function (stats) {
		debug.progress('|');
		return driver.recalculateAllSizes()(stats);
	})(function (stats) {
		debug.progress(' records: ' + stats.recordsCount + ', masters: ' + stats.mastersCount +
			', maxMasterRecords: ' + stats.maxRecordsPerMasterCount);
		debug.close();
	});
};
<|endoftext|>


<commit_before>const express = require('express')
const React = require('react')
const ReactDOM = require('react-dom/server')
const History = require('history')
const Router = require('mobx-little-router')
const App = require('./src/App')
const routes = require('./src/routes')
const DataStore = require('./src/DataStore')

const app = express()

app.get('*', function(req, res) {
  const dataStore = new DataStore()
  const router = Router.install({
    createHistory: [History.createMemoryHistory, { initialEntries: [req.url] }],
    routes: routes,
    getContext: () => ({
      dataStore: dataStore
    })
  })

  router.start(() => {
    const html = ReactDOM.renderToString(
      React.createElement(App, { dataStore: dataStore, router: router })
    )

    res.send(html)
  })
})

app.listen(3000, function() {
  console.log('SSR example listening on port 3000!')
})
<commit_msg>Updates SSR example with history object instead of creator function.<commit_after>const express = require('express')
const React = require('react')
const ReactDOM = require('react-dom/server')
const History = require('history')
const Router = require('mobx-little-router')
const App = require('./src/App')
const routes = require('./src/routes')
const DataStore = require('./src/DataStore')

const app = express()

app.get('*', function(req, res) {
  const dataStore = new DataStore()
  const router = Router.install({
    history: History.createMemoryHistory({ initialEntries: [req.url] }),
    routes: routes,
    getContext: () => ({
      dataStore: dataStore
    })
  })

  router.start(() => {
    const html = ReactDOM.renderToString(
      React.createElement(App, { dataStore: dataStore, router: router })
    )

    res.send(html)
  })
})

app.listen(3000, function() {
  console.log('SSR example listening on port 3000!')
})
<|endoftext|>


<commit_before>'use strict';

var gulp       = require('gulp');
var plugins    = require('gulp-load-plugins')();
var browserify = require('browserify');
var source     = require('vinyl-source-stream');
var buffer     = require('vinyl-buffer');
var karma      = require('karma-as-promised').server;
var fs         = require('fs');
var argv       = require('yargs').argv;
var gutil      = require('gulp-util');
var path       = require('path');
var seq        = require('run-sequence');

function getBundle(pkg) {
  var fileName = 'fbutil' + (pkg? '.' + pkg : '') + '.js';
  return browserify({debug: false})
    .external('firebase', {expose: 'firebase'})
    .require('./src/' + fileName, {expose: 'firebase-util'})
    .add('./src/expose.js');
}

function copyTemplate(ext, isSpec) {
  if( !argv.t || !argv.d || !argv.n ) {
    gutil.log(gutil.colors.red('Usage: gulp scaffold -t type -d directory -n name'));
    return;
  }

  var baseDir = isSpec? 'test' : 'src';
  var subDir = argv.d;
  if( !isSpec ) { subDir = path.join(subDir, 'libs'); }
  var dest = path.join(baseDir, subDir, argv.n + ext);
  var src = path.join('gulp', argv.t + (isSpec? '.spec' : '') + '.tpl');
  var renameProps = {
    dirname: subDir,
    basename: argv.n,
    extname: ext
  };

  if( fs.existsSync(dest) ) {
    gutil.log(gutil.colors.red('File exists: '+dest));
    return;
  }

  gutil.log('Creating ', gutil.colors.magenta(dest));
  return gulp.src(src)
    .pipe(plugins.template({ name: argv.n }))
    .pipe(plugins.rename(renameProps))
    .pipe(gulp.dest(baseDir));
}

gulp.task('build', function(){
  return getBundle()
    .bundle()
    .pipe(source('./firebase-util.js'))
    .pipe(buffer())
    .pipe(plugins.header(fs.readFileSync('./gulp/header.tpl'), {
      pkg: require('./package.json')
    }))
    .pipe(gulp.dest('dist'))
    .pipe(plugins.livereload());
});

gulp.task('watch', function() {
  return karma.start({
    configFile: __dirname + '/karma.conf.js'
  });
});

gulp.task('test', function () {
  return karma.start({
    configFile: __dirname+'/karma.conf.js',
    singleRun: true
  });
});

//todo include the debug maps as external files
gulp.task('minify', function() {
  return seq('minify-paginate', 'minify-normalize', 'minify-all');
});

gulp.task('minify-paginate', function() {
  return getBundle('paginate')
    .bundle()
    .pipe(source('./firebase-util-paginate.min.js'))
    .pipe(buffer())
    .pipe(plugins.header(fs.readFileSync('./gulp/header.tpl'), {
      pkg: require('./package.json')
    }))
    .pipe(plugins.uglify({preserveComments: 'some'}))
    .pipe(plugins.size())
    .pipe(gulp.dest('dist'))
    .pipe(plugins.livereload());
});

gulp.task('minify-normalize', function() {
  return getBundle('normalize')
    .bundle()
    .pipe(source('./firebase-util-normalize.min.js'))
    .pipe(buffer())
    .pipe(plugins.header(fs.readFileSync('./gulp/header.tpl'), {
      pkg: require('./package.json')
    }))
    .pipe(plugins.uglify({preserveComments: 'some'}))
    .pipe(plugins.size())
    .pipe(gulp.dest('dist'))
    .pipe(plugins.livereload());
});

gulp.task('minify-all', function() {
  return getBundle()
    .bundle()
    .pipe(source('./firebase-util.min.js'))
    .pipe(buffer())
    .pipe(plugins.header(fs.readFileSync('./gulp/header.tpl'), {
      pkg: require('./package.json')
    }))
    .pipe(plugins.uglify({preserveComments: 'some'}))
    .pipe(plugins.size())
    .pipe(gulp.dest('dist'))
    .pipe(plugins.livereload());
});

gulp.task('lint', function () {
  return gulp.src(['./gulpfile.js', './src/**/*.js', './test/**/*.spec.js'])
    .pipe(plugins.jshint())
    .pipe(plugins.jshint.reporter('jshint-stylish'))
    .pipe(plugins.jshint.reporter('fail'));
});

gulp.task('scaffold-file', function() {
  return copyTemplate('.js');
});

gulp.task('scaffold-test', function() {
  return copyTemplate('.spec.js', true);
});

gulp.task('serve', function() {
  gulp.src('.')
    .pipe(plugins.webserver({
      livereload: true,
      directoryListing: true,
      open: 'test/e2e/e2etest.html'
    }));
});

gulp.task('e2e', ['bundle', 'serve'], function() {
  return gulp.watch(['./src/**/*.js', './test/e2e/**/*'], ['bundle']);
});

gulp.task('scaffold', ['scaffold-file', 'scaffold-test']);

gulp.task('bundle', function() {
  return seq('lint', 'build', 'minify');
});

gulp.task('default', function() {
  return seq('bundle', 'test');
});
<commit_msg>Update the gulpfile with some docs, make e2e tests not reload in the middle of the initial test run.<commit_after>'use strict';

/**
 * USEFUL COMMANDS:
 *   gulp           bundle and run tests
 *   gulp e2e       bundle, start a server, open e2e tests in browser, watch for changes, livereload
 *   gulp bundle    lint src code, bundle content, and minify
 *   gulp scaffold  create a new class and test unit for that class
 */

var gulp       = require('gulp');
var plugins    = require('gulp-load-plugins')();
var browserify = require('browserify');
var source     = require('vinyl-source-stream');
var buffer     = require('vinyl-buffer');
var karma      = require('karma-as-promised').server;
var fs         = require('fs');
var argv       = require('yargs').argv;
var gutil      = require('gulp-util');
var path       = require('path');
var seq        = require('run-sequence');

function getBundle(pkg) {
  var fileName = 'fbutil' + (pkg? '.' + pkg : '') + '.js';
  return browserify({debug: false})
    .external('firebase', {expose: 'firebase'})
    .require('./src/' + fileName, {expose: 'firebase-util'})
    .add('./src/expose.js');
}

function copyTemplate(ext, isSpec) {
  if( !argv.t || !argv.d || !argv.n ) {
    gutil.log(gutil.colors.red('Usage: gulp scaffold -t type -d directory -n name'));
    return;
  }

  var baseDir = isSpec? 'test' : 'src';
  var subDir = argv.d;
  if( !isSpec ) { subDir = path.join(subDir, 'libs'); }
  var dest = path.join(baseDir, subDir, argv.n + ext);
  var src = path.join('gulp', argv.t + (isSpec? '.spec' : '') + '.tpl');
  var renameProps = {
    dirname: subDir,
    basename: argv.n,
    extname: ext
  };

  if( fs.existsSync(dest) ) {
    gutil.log(gutil.colors.red('File exists: '+dest));
    return;
  }

  gutil.log('Creating ', gutil.colors.magenta(dest));
  return gulp.src(src)
    .pipe(plugins.template({ name: argv.n }))
    .pipe(plugins.rename(renameProps))
    .pipe(gulp.dest(baseDir));
}

gulp.task('build', function(){
  return getBundle()
    .bundle()
    .pipe(source('./firebase-util.js'))
    .pipe(buffer())
    .pipe(plugins.header(fs.readFileSync('./gulp/header.tpl'), {
      pkg: require('./package.json')
    }))
    .pipe(gulp.dest('dist'))
    .pipe(plugins.livereload());
});

gulp.task('watch', function() {
  return karma.start({
    configFile: __dirname + '/karma.conf.js'
  });
});

gulp.task('test', function () {
  return karma.start({
    configFile: __dirname+'/karma.conf.js',
    singleRun: true
  });
});

//todo include the debug maps as external files
gulp.task('minify', function() {
  return seq('minify-paginate', 'minify-normalize', 'minify-all');
});

gulp.task('minify-paginate', function() {
  return getBundle('paginate')
    .bundle()
    .pipe(source('./firebase-util-paginate.min.js'))
    .pipe(buffer())
    .pipe(plugins.header(fs.readFileSync('./gulp/header.tpl'), {
      pkg: require('./package.json')
    }))
    .pipe(plugins.uglify({preserveComments: 'some'}))
    .pipe(plugins.size())
    .pipe(gulp.dest('dist'))
    .pipe(plugins.livereload());
});

gulp.task('minify-normalize', function() {
  return getBundle('normalize')
    .bundle()
    .pipe(source('./firebase-util-normalize.min.js'))
    .pipe(buffer())
    .pipe(plugins.header(fs.readFileSync('./gulp/header.tpl'), {
      pkg: require('./package.json')
    }))
    .pipe(plugins.uglify({preserveComments: 'some'}))
    .pipe(plugins.size())
    .pipe(gulp.dest('dist'))
    .pipe(plugins.livereload());
});

gulp.task('minify-all', function() {
  return getBundle()
    .bundle()
    .pipe(source('./firebase-util.min.js'))
    .pipe(buffer())
    .pipe(plugins.header(fs.readFileSync('./gulp/header.tpl'), {
      pkg: require('./package.json')
    }))
    .pipe(plugins.uglify({preserveComments: 'some'}))
    .pipe(plugins.size())
    .pipe(gulp.dest('dist'))
    .pipe(plugins.livereload());
});

gulp.task('lint', function () {
  return gulp.src(['./gulpfile.js', './src/**/*.js', './test/**/*.spec.js'])
    .pipe(plugins.jshint())
    .pipe(plugins.jshint.reporter('jshint-stylish'))
    .pipe(plugins.jshint.reporter('fail'));
});

gulp.task('scaffold-file', function() {
  return copyTemplate('.js');
});

gulp.task('scaffold-test', function() {
  return copyTemplate('.spec.js', true);
});

gulp.task('serve', function() {
  gulp.src('.')
    .pipe(plugins.webserver({
      livereload: true,
      directoryListing: true,
      open: 'test/e2e/e2etest.html'
    }));
});

gulp.task('e2e', function() {
  return seq('bundle', 'serve', 'watch');
});

gulp.task('watch', function() {
  return gulp.watch(['./src/**/*.js', './test/e2e/**/*'], ['bundle']);
});

gulp.task('scaffold', ['scaffold-file', 'scaffold-test']);

gulp.task('bundle', function() {
  return seq('lint', 'build', 'minify');
});

gulp.task('default', function() {
  return seq('bundle', 'test');
});
<|endoftext|>


<commit_before>/* eslint max-nested-callbacks: [2, 5] max-len:0*/
"use strict";

import RssParser from "../../src/rss/RssParser";
import HttpResponseHandler from "../../../common/src/HttpResponseHandler.js";
import CryptUtil from "../../src/util/CryptUtil.js";
import LogTestHelper from "../helpers/LogTestHelper";
import Logger from "../../src/logging/Logger";
import { expect } from "chai";
import nock from "nock";
import restRequest from "request";
import sinon from "sinon";

describe("RssParser", () => {
    let sandbox = null;
    before("RssParser", () => {
        sinon.stub(Logger, "instance").returns(LogTestHelper.instance());
    });

    after("RssParser", () => {
        Logger.instance.restore();
    });

    beforeEach("RssParser", () => {
        sandbox = sinon.sandbox.create();
    });

    afterEach("RssParser", () => {
        sandbox.restore();
    });

    it("should reject if the url is not a feed", (done) => {
        let data = `<meta http-equiv="content-type" content="text/html;charset=utf-8">
        <TITLE>302 Moved</TITLE>

302 Moved

        The document has moved
        here.
        `;

        nock("http://www.google.com")
            .get("/users")
            .reply(HttpResponseHandler.codes.OK, data);
        let url = "http://www.google.com/users";

        restRequest(url).on("response", function(res) {
            let rssParser = new RssParser(res);
            rssParser.parse().catch((error) => {
                expect(error).to.eq("Not a feed");
                done();
            });
        });
    });

    it("should resolve with parsed items for proper url", (done) => {
        let data = `<?xml version="1.0" encoding="utf-8" ?>
                     <rss version="2.0" xml:base="http://www.nasa.gov/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:media="http://search.yahoo.com/mrss/"> <channel>
                    <item>
                     <title>NASA Administrator Remembers Apollo-Era Astronaut Edgar Mitchell</title>
                     <link>http://www.nasa.gov/press-release/nasa-administrator-remembers-apollo-era-astronaut-edgar-mitchell</link>
                     <description>The following is a statement from NASA Administrator Charles Bolden on the passing of NASA astronaut Edgar Mitchell:</description>
                    </item>

                    <item>
                     <title>NASA Television to Air Russian Spacewalk</title>
                     <link>http://www.nasa.gov/press-release/nasa-television-to-air-russian-spacewalk</link>
                     <description>NASA Television will broadcast live coverage of a 5.5-hour spacewalk by two Russian cosmonauts aboard the International Space Station beginning at 7:30 a.m. EST Wednesday, Feb. 3.</description>
                    </item>
                    </channel>
                    </rss>`;
        let url = "http://www.nasa.com/images/?service=rss";

        nock("http://www.nasa.com/images")
            .get("/?service=rss")
            .reply(HttpResponseHandler.codes.OK, data);

        let hmacStub = sandbox.stub(CryptUtil, "hmac");
        hmacStub.withArgs("sha256", "appSecretKey", "hex", "http://www.nasa.gov/press-release/nasa-administrator-remembers-apollo-era-astronaut-edgar-mitchell").returns("test-guid-1");
        hmacStub.withArgs("sha256", "appSecretKey", "hex", "http://www.nasa.gov/press-release/nasa-television-to-air-russian-spacewalk").returns("test-guid-2");

        let expectedFeeds = {
            "items":
                [{
                    "guid": "test-guid-1",
                    "title": "NASA Administrator Remembers Apollo-Era Astronaut Edgar Mitchell",
                    "link": "http://www.nasa.gov/press-release/nasa-administrator-remembers-apollo-era-astronaut-edgar-mitchell",
                    "description": "The following is a statement from NASA Administrator Charles Bolden on the passing of NASA astronaut Edgar Mitchell:",
                    "pubDate": null,
                    "enclosures": [],
                    "image": {}
                },
                    {
                        "guid": "test-guid-2",
                        "title": "NASA Television to Air Russian Spacewalk",
                        "link": "http://www.nasa.gov/press-release/nasa-television-to-air-russian-spacewalk",
                        "description": "NASA Television will broadcast live coverage of a 5.5-hour spacewalk by two Russian cosmonauts aboard the International Space Station beginning at 7:30 a.m. EST Wednesday, Feb. 3.",
                        "pubDate": null,
                        "enclosures": [],
                        "image": {}
                    }]
        };

        restRequest(url).on("response", function(res) {
            let rssParser = new RssParser(res);
            rssParser.parse().then((feedJson) => {
                expect(feedJson.items).deep.equal(expectedFeeds.items);
                done();
            }).catch(error => {
                console.log(error);
            });
        });
    });
});
<commit_msg>[Vik] fixed eslint<commit_after>/* eslint max-nested-callbacks: [2, 5] max-len:0*/
"use strict";

import RssParser from "../../src/rss/RssParser";
import HttpResponseHandler from "../../../common/src/HttpResponseHandler.js";
import CryptUtil from "../../src/util/CryptUtil.js";
import LogTestHelper from "../helpers/LogTestHelper";
import Logger from "../../src/logging/Logger";
import { expect } from "chai";
import nock from "nock";
import restRequest from "request";
import sinon from "sinon";

describe("RssParser", () => {
    let sandbox = null;
    before("RssParser", () => {
        sinon.stub(Logger, "instance").returns(LogTestHelper.instance());
    });

    after("RssParser", () => {
        Logger.instance.restore();
    });

    beforeEach("RssParser", () => {
        sandbox = sinon.sandbox.create();
    });

    afterEach("RssParser", () => {
        sandbox.restore();
    });

    it("should reject if the url is not a feed", (done) => {
        let data = `<meta http-equiv="content-type" content="text/html;charset=utf-8">
        <TITLE>302 Moved</TITLE>

302 Moved

        The document has moved
        here.
        `;

        nock("http://www.google.com")
            .get("/users")
            .reply(HttpResponseHandler.codes.OK, data);
        let url = "http://www.google.com/users";

        restRequest(url).on("response", function(res) {
            let rssParser = new RssParser(res);
            rssParser.parse().catch((error) => {
                expect(error).to.eq("Not a feed");
                done();
            });
        });
    });

    it("should resolve with parsed items for proper url", (done) => {
        let data = `<?xml version="1.0" encoding="utf-8" ?>
                     <rss version="2.0" xml:base="http://www.nasa.gov/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:media="http://search.yahoo.com/mrss/"> <channel>
                    <item>
                     <title>NASA Administrator Remembers Apollo-Era Astronaut Edgar Mitchell</title>
                     <link>http://www.nasa.gov/press-release/nasa-administrator-remembers-apollo-era-astronaut-edgar-mitchell</link>
                     <description>The following is a statement from NASA Administrator Charles Bolden on the passing of NASA astronaut Edgar Mitchell:</description>
                    </item>

                    <item>
                     <title>NASA Television to Air Russian Spacewalk</title>
                     <link>http://www.nasa.gov/press-release/nasa-television-to-air-russian-spacewalk</link>
                     <description>NASA Television will broadcast live coverage of a 5.5-hour spacewalk by two Russian cosmonauts aboard the International Space Station beginning at 7:30 a.m. EST Wednesday, Feb. 3.</description>
                    </item>
                    </channel>
                    </rss>`;
        let url = "http://www.nasa.com/images/?service=rss";

        nock("http://www.nasa.com/images")
            .get("/?service=rss")
            .reply(HttpResponseHandler.codes.OK, data);

        let hmacStub = sandbox.stub(CryptUtil, "hmac");
        hmacStub.withArgs("sha256", "appSecretKey", "hex", "http://www.nasa.gov/press-release/nasa-administrator-remembers-apollo-era-astronaut-edgar-mitchell").returns("test-guid-1");
        hmacStub.withArgs("sha256", "appSecretKey", "hex", "http://www.nasa.gov/press-release/nasa-television-to-air-russian-spacewalk").returns("test-guid-2");

        let expectedFeeds = {
            "items":
                [{
                    "guid": "test-guid-1",
                    "title": "NASA Administrator Remembers Apollo-Era Astronaut Edgar Mitchell",
                    "link": "http://www.nasa.gov/press-release/nasa-administrator-remembers-apollo-era-astronaut-edgar-mitchell",
                    "description": "The following is a statement from NASA Administrator Charles Bolden on the passing of NASA astronaut Edgar Mitchell:",
                    "pubDate": null,
                    "enclosures": [],
                    "image": {}
                },
                    {
                        "guid": "test-guid-2",
                        "title": "NASA Television to Air Russian Spacewalk",
                        "link": "http://www.nasa.gov/press-release/nasa-television-to-air-russian-spacewalk",
                        "description": "NASA Television will broadcast live coverage of a 5.5-hour spacewalk by two Russian cosmonauts aboard the International Space Station beginning at 7:30 a.m. EST Wednesday, Feb. 3.",
                        "pubDate": null,
                        "enclosures": [],
                        "image": {}
                    }]
        };

        restRequest(url).on("response", function(res) {
            let rssParser = new RssParser(res);
            rssParser.parse().then((feedJson) => {
                expect(feedJson.items).deep.equal(expectedFeeds.items);
                done();
            });
        });
    });
});
<|endoftext|>


<commit_before>const minimist = require('minimist'),
    fs = require('fs'),
    path = require('path'),
    gulp = require('gulp'),
    del = require('del'),
    zip = require('gulp-zip'),
    concat = require('gulp-concat'),
    cssnano = require('gulp-cssnano'),
    connect = require('gulp-connect'),
    uglify = require('uglify-js').minify,
    zlib = require('zlib'),
    Server = require('karma').Server,
    package = require('./package.json');

const knownOptions = {
    string: ['browsers', 'pattern'],
    boolean: 'coverage',
    alias: {
        'coverage': 'cov'
    },
    default: {
        browsers: null,
        coverage: false
    }
};

const options = minimist(process.argv.slice(2), knownOptions);

const browsers = [];

const configBrowsers = options.browsers || process.env['MAPTALKS_BROWSERS'] || '';
configBrowsers.split(',').forEach(name => {
    if (!name || name.length < 1) {
        return;
    }
    browsers.push(name);
});

const stylesPattern = './assets/css/**/*.css';

gulp.task('styles', ['images'], () => {
    return gulp.src(stylesPattern)
        .pipe(concat('maptalks.css'))
        .pipe(cssnano())
        .pipe(gulp.dest('./dist/'));
});

gulp.task('images', () => {
    return gulp.src('./assets/images/**/*')
        .pipe(gulp.dest('./dist/images'));
});

gulp.task('transform-proto', () => {
    //a silly work round as transform proto-to-assign is not working in babel 7
    const filename = __dirname + '/dist/maptalks.js';
    const code = fs.readFileSync(filename).toString('utf-8');
    const transformed = code.replace('subClass.__proto__ = superClass;',
        "if (typeof document !== 'undefined' && document.documentMode < 11) { _defaults(subClass, superClass); } else { subClass.__proto__ = superClass;}"
    );
    // fs.writeFileSync(__dirname + '/dist/compiled.js', transformed);
    fs.writeFileSync(filename, transformed);
});

gulp.task('minify', () => {
    const name = package.name;
    const dest = package.main;
    const code = fs.readFileSync(dest).toString('utf-8');
    const u = uglify(code, {
        'output': {
            'ascii_only': true
        }
    });
    const minified = this.banner + '\n' + u.code;
    fs.writeFileSync('dist/' + name + '.min.js', minified);
    const gzipped = zlib.gzipSync(minified);
    fs.writeFileSync('dist/' + name + '.min.js.gz', gzipped);
});

/**
 * Run test once and exit
 */
gulp.task('test', function (done) {
    // const karmaConfig = {
    //     configFile: path.join(__dirname, 'build/karma.test.config.js')
    // };
    let file = 'build/karma.test.config.js';
    if (options.coverage) {
        file = 'build/karma.cover.config.js';
    }
    const cfg = require('karma').config;
    const karmaConfig = cfg.parseConfig(path.join(__dirname, file));
    if (browsers.length > 0) {
        karmaConfig.browsers = browsers;
    }
    if (configBrowsers.indexOf('IE') >= 0) {
        let idx = -1;
        for (let i = 0; i < karmaConfig.files.length; i++) {
            if (karmaConfig.files[i].pattern.indexOf('test/core/ClassSpec.js') >= 0) {
                idx = i;
                break;
            }
        }
        if (idx >= 0) {
            karmaConfig.files.splice(idx, 1);
        }
    }
    if (configBrowsers === 'IE9') {
        //override IE9's pattern
        options.pattern = 'IE9.Specs';
    }
    if (options.pattern) {
        if (!karmaConfig.client) {
            karmaConfig.client = {
                mocha: {
                    grep: options.pattern
                }
            };
        } else {
            karmaConfig.client.mocha.grep = options.pattern;
        }
    }
    new Server(karmaConfig, done).start();
});

/**
 * Watch for file changes and re-run tests on each change
 */
gulp.task('tdd', function (done) {
    const karmaConfig = {
        configFile: path.join(__dirname, 'build/karma.tdd.config.js')
    };
    if (browsers.length > 0) {
        karmaConfig.browsers = browsers;
    }
    if (options.pattern) {
        karmaConfig.client = {
            mocha: {
                grep: options.pattern
            }
        };
    }
    if (options.pattern) {
        if (!karmaConfig.client) {
            karmaConfig.client = {
                mocha: {
                    grep: options.pattern
                }
            };
        } else {
            karmaConfig.client.mocha.grep = options.pattern;
        }
    }

    const karmaServer = new Server(karmaConfig, done);
    karmaServer.start();
    started = true;
});

gulp.task('connect', () => {
    connect.server({
        root: ['dist', 'debug'],
        livereload: true,
        port: 20000
    });
});

gulp.task('reload', ['scripts'], () => {
    gulp.src('./dist/*.js')
        .pipe(connect.reload());
});

gulp.task('doc', (done) => {
    const sources = require('./build/api-files.js');
    del([
        './docs/api/**/*'
    ], {
        force : true
    });
    const conf = require('./jsdoc.json');
    const cmd = 'jsdoc';
    const args = ['-c', 'jsdoc.json'].concat(['-P', 'package.json']).concat(sources);
    const exec = require('child_process').exec;
    exec([cmd].concat(args).join(' '), (error, stdout, stderr) => {
        if (error) {
            console.error('JSDoc returned with error: ' + stderr ? stderr : '');
            done(error);
            return;
        }
        if (stderr) {
            console.error(stderr);
        }
        if (stdout) { console.log(stdout); }
        console.log('Documented ' + sources.length + ' files in:');
        console.log(conf.opts.destination);
        done(stderr);
    });
});

gulp.task('editdoc', ['doc'], () => {
    gulp.watch(['src/**/*.js'], ['doc']);
});

gulp.task('beforeZip', () => {
    return gulp.src(['LICENSE', 'ACKNOWLEDGEMENT', 'docs/**/*'])
    .pipe(gulp.dest('dist'))
});

gulp.task('zip', ['beforeZip'], done => {
    gulp.src(['dist/*.js', 'dist/*.mjs', 'dist/images/**/*', 'dist/maptalks.css', 'dist/LICENSE', 'dist/ACKNOWLEDGEMENT', 'dist/api/**/*'], { base: 'dist/' })
        .pipe(zip('maptalks-' + package.version + '.zip'))
        .pipe(gulp.dest('dist'));
    setTimeout(function () {
        del([
            'dist/api/**/*', 'dist/LICENSE', 'dist/ACKNOWLEDGEMENT'
        ], {
            force : true
        });
        done();
    }, 2000);
});

gulp.task('default', ['connect']);

<commit_msg>[ci skip] fix minify task<commit_after>const minimist = require('minimist'),
    fs = require('fs'),
    path = require('path'),
    gulp = require('gulp'),
    del = require('del'),
    zip = require('gulp-zip'),
    concat = require('gulp-concat'),
    cssnano = require('gulp-cssnano'),
    connect = require('gulp-connect'),
    uglify = require('uglify-js').minify,
    zlib = require('zlib'),
    Server = require('karma').Server,
    package = require('./package.json');

const knownOptions = {
    string: ['browsers', 'pattern'],
    boolean: 'coverage',
    alias: {
        'coverage': 'cov'
    },
    default: {
        browsers: null,
        coverage: false
    }
};

const options = minimist(process.argv.slice(2), knownOptions);

const browsers = [];

const configBrowsers = options.browsers || process.env['MAPTALKS_BROWSERS'] || '';
configBrowsers.split(',').forEach(name => {
    if (!name || name.length < 1) {
        return;
    }
    browsers.push(name);
});

const stylesPattern = './assets/css/**/*.css';

gulp.task('styles', ['images'], () => {
    return gulp.src(stylesPattern)
        .pipe(concat('maptalks.css'))
        .pipe(cssnano())
        .pipe(gulp.dest('./dist/'));
});

gulp.task('images', () => {
    return gulp.src('./assets/images/**/*')
        .pipe(gulp.dest('./dist/images'));
});

gulp.task('transform-proto', () => {
    //a silly work round as transform proto-to-assign is not working in babel 7
    const filename = __dirname + '/dist/maptalks.js';
    const code = fs.readFileSync(filename).toString('utf-8');
    const transformed = code.replace('subClass.__proto__ = superClass;',
        "if (typeof document !== 'undefined' && document.documentMode < 11) { _defaults(subClass, superClass); } else { subClass.__proto__ = superClass;}"
    );
    // fs.writeFileSync(__dirname + '/dist/compiled.js', transformed);
    fs.writeFileSync(filename, transformed);
});

gulp.task('minify', () => {
    const name = package.name;
    const dest = package.main;
    const code = fs.readFileSync(dest).toString('utf-8');
    const u = uglify(code, {
        'output': {
            'ascii_only': true,
            'comments' : /^!/
        }
    });
    const minified = u.code;
    fs.writeFileSync('dist/' + name + '.min.js', minified);
    const gzipped = zlib.gzipSync(minified);
    fs.writeFileSync('dist/' + name + '.min.js.gz', gzipped);
});

/**
 * Run test once and exit
 */
gulp.task('test', function (done) {
    // const karmaConfig = {
    //     configFile: path.join(__dirname, 'build/karma.test.config.js')
    // };
    let file = 'build/karma.test.config.js';
    if (options.coverage) {
        file = 'build/karma.cover.config.js';
    }
    const cfg = require('karma').config;
    const karmaConfig = cfg.parseConfig(path.join(__dirname, file));
    if (browsers.length > 0) {
        karmaConfig.browsers = browsers;
    }
    if (configBrowsers.indexOf('IE') >= 0) {
        let idx = -1;
        for (let i = 0; i < karmaConfig.files.length; i++) {
            if (karmaConfig.files[i].pattern.indexOf('test/core/ClassSpec.js') >= 0) {
                idx = i;
                break;
            }
        }
        if (idx >= 0) {
            karmaConfig.files.splice(idx, 1);
        }
    }
    if (configBrowsers === 'IE9') {
        //override IE9's pattern
        options.pattern = 'IE9.Specs';
    }
    if (options.pattern) {
        if (!karmaConfig.client) {
            karmaConfig.client = {
                mocha: {
                    grep: options.pattern
                }
            };
        } else {
            karmaConfig.client.mocha.grep = options.pattern;
        }
    }
    new Server(karmaConfig, done).start();
});

/**
 * Watch for file changes and re-run tests on each change
 */
gulp.task('tdd', function (done) {
    const karmaConfig = {
        configFile: path.join(__dirname, 'build/karma.tdd.config.js')
    };
    if (browsers.length > 0) {
        karmaConfig.browsers = browsers;
    }
    if (options.pattern) {
        karmaConfig.client = {
            mocha: {
                grep: options.pattern
            }
        };
    }
    if (options.pattern) {
        if (!karmaConfig.client) {
            karmaConfig.client = {
                mocha: {
                    grep: options.pattern
                }
            };
        } else {
            karmaConfig.client.mocha.grep = options.pattern;
        }
    }

    const karmaServer = new Server(karmaConfig, done);
    karmaServer.start();
    started = true;
});

gulp.task('connect', () => {
    connect.server({
        root: ['dist', 'debug'],
        livereload: true,
        port: 20000
    });
});

gulp.task('reload', ['scripts'], () => {
    gulp.src('./dist/*.js')
        .pipe(connect.reload());
});

gulp.task('doc', (done) => {
    const sources = require('./build/api-files.js');
    del([
        './docs/api/**/*'
    ], {
        force : true
    });
    const conf = require('./jsdoc.json');
    const cmd = 'jsdoc';
    const args = ['-c', 'jsdoc.json'].concat(['-P', 'package.json']).concat(sources);
    const exec = require('child_process').exec;
    exec([cmd].concat(args).join(' '), (error, stdout, stderr) => {
        if (error) {
            console.error('JSDoc returned with error: ' + stderr ? stderr : '');
            done(error);
            return;
        }
        if (stderr) {
            console.error(stderr);
        }
        if (stdout) { console.log(stdout); }
        console.log('Documented ' + sources.length + ' files in:');
        console.log(conf.opts.destination);
        done(stderr);
    });
});

gulp.task('editdoc', ['doc'], () => {
    gulp.watch(['src/**/*.js'], ['doc']);
});

gulp.task('beforeZip', () => {
    return gulp.src(['LICENSE', 'ACKNOWLEDGEMENT', 'docs/**/*'])
    .pipe(gulp.dest('dist'))
});

gulp.task('zip', ['beforeZip'], done => {
    gulp.src(['dist/*.js', 'dist/*.mjs', 'dist/images/**/*', 'dist/maptalks.css', 'dist/LICENSE', 'dist/ACKNOWLEDGEMENT', 'dist/api/**/*'], { base: 'dist/' })
        .pipe(zip('maptalks-' + package.version + '.zip'))
        .pipe(gulp.dest('dist'));
    setTimeout(function () {
        del([
            'dist/api/**/*', 'dist/LICENSE', 'dist/ACKNOWLEDGEMENT'
        ], {
            force : true
        });
        done();
    }, 2000);
});

gulp.task('default', ['connect']);

<|endoftext|>


<commit_before>var browserSync = require('browser-sync')
var gulp = require('gulp')
var gulpAutoprefixer = require('gulp-autoprefixer')
var gulpCleanCss = require('gulp-clean-css')
var gulpDest = require('gulp-dest')
var gulpPlumber = require('gulp-plumber')
var gulpRename = require('gulp-rename')
var gulpSass = require('gulp-sass')
var gulpSourcemaps = require('gulp-sourcemaps')
var gulpStylus = require('gulp-stylus')

gulp.task('browser-sync', function () {
  browserSync({
    server: {
      baseDir: './'
    }
  })
})

gulp.task('bs-reload', function () {
  browserSync.reload()
})

gulp.task('scss', function () {
  gulp.src(['scss/**/*.scss'])
    .pipe(gulpPlumber({
      errorHandler: function (error) {
        console.log(error.message)
        this.emit('end')
      }}))
    .pipe(gulpSourcemaps.init())
    .pipe(gulpSass())
    .pipe(gulpAutoprefixer())
    .pipe(gulp.dest('css/'))
    .pipe(gulpRename({suffix: '.min'}))
    .pipe(gulpCleanCss({compatibility: 'ie8'}))
    .pipe(gulpSourcemaps.write('.'))
    .pipe(gulp.dest('css/'))
    .pipe(browserSync.reload({stream: true}))
})

gulp.task('styl', function () {
  gulp.src(['./node_modules/sanitize.css/sanitize.css'])
    .pipe(gulpDest('tmp', {ext: '.styl'}))
    .pipe(gulp.dest('./'))
  gulp.src(['styl/**/[^_]*.styl'])
    .pipe(gulpPlumber({
      errorHandler: function (error) {
        console.log(error.message)
        this.emit('end')
      }}))
    .pipe(gulpSourcemaps.init())
    .pipe(gulpStylus())
    .pipe(gulpAutoprefixer())
    .pipe(gulpRename({suffix: '.styl'}))
    .pipe(gulp.dest('css/'))
    .pipe(gulpRename({suffix: '.min'}))
    .pipe(gulpCleanCss({compatibility: 'ie8'}))
    .pipe(gulpSourcemaps.write('.'))
    .pipe(gulp.dest('css/'))
    .pipe(browserSync.reload({stream: true}))
})

gulp.task('styles', ['scss', 'styl'])

gulp.task('default', ['browser-sync'], function () {
  gulp.watch('scss/**/*.scss', ['scss'])
  gulp.watch('styl/**/*.styl', ['styl'])
  gulp.watch('*.html', ['bs-reload'])
})
<commit_msg>move from var to const list<commit_after>const
  browserSync = require('browser-sync'),
  gulp = require('gulp'),
  gulpAutoprefixer = require('gulp-autoprefixer'),
  gulpCleanCss = require('gulp-clean-css'),
  gulpDest = require('gulp-dest'),
  gulpPlumber = require('gulp-plumber'),
  gulpRename = require('gulp-rename'),
  gulpSass = require('gulp-sass'),
  gulpSourcemaps = require('gulp-sourcemaps'),
  gulpStylus = require('gulp-stylus')

gulp.task('browser-sync', function () {
  browserSync({
    server: {
      baseDir: './'
    }
  })
})

gulp.task('bs-reload', function () {
  browserSync.reload()
})

gulp.task('scss', function () {
  gulp.src(['scss/**/*.scss'])
    .pipe(gulpPlumber({
      errorHandler: function (error) {
        console.log(error.message)
        this.emit('end')
      }}))
    .pipe(gulpSourcemaps.init())
    .pipe(gulpSass())
    .pipe(gulpAutoprefixer())
    .pipe(gulp.dest('css/'))
    .pipe(gulpRename({suffix: '.min'}))
    .pipe(gulpCleanCss({compatibility: 'ie8'}))
    .pipe(gulpSourcemaps.write('.'))
    .pipe(gulp.dest('css/'))
    .pipe(browserSync.reload({stream: true}))
})

gulp.task('styl', function () {
  gulp.src(['./node_modules/sanitize.css/sanitize.css'])
    .pipe(gulpDest('tmp', {ext: '.styl'}))
    .pipe(gulp.dest('./'))
  gulp.src(['styl/**/[^_]*.styl'])
    .pipe(gulpPlumber({
      errorHandler: function (error) {
        console.log(error.message)
        this.emit('end')
      }}))
    .pipe(gulpSourcemaps.init())
    .pipe(gulpStylus())
    .pipe(gulpAutoprefixer())
    .pipe(gulpRename({suffix: '.styl'}))
    .pipe(gulp.dest('css/'))
    .pipe(gulpRename({suffix: '.min'}))
    .pipe(gulpCleanCss({compatibility: 'ie8'}))
    .pipe(gulpSourcemaps.write('.'))
    .pipe(gulp.dest('css/'))
    .pipe(browserSync.reload({stream: true}))
})

gulp.task('styles', ['scss', 'styl'])

gulp.task('default', ['browser-sync'], function () {
  gulp.watch('scss/**/*.scss', ['scss'])
  gulp.watch('styl/**/*.styl', ['styl'])
  gulp.watch('*.html', ['bs-reload'])
})
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp'),
    gutil = require('gulp-util'),
    connect = require('gulp-connect'),
    sass = require('gulp-sass'),
    uglify = require('gulp-uglify'),
    concat = require('gulp-concat'),
    serve = require('gulp-serve'),
    ghPages = require('gulp-gh-pages'),
    clean = require('gulp-clean'),
    gih = require('gulp-include-html');

gulp.task('js', function() {
  gulp.src('./app/js/*.js')
    .pipe(uglify())
    .pipe(gulp.dest('dest/assets'))
    .pipe(connect.reload());
});

gulp.task('sass', function() {
  gulp.src('./app/sass/app.scss')
    .pipe(sass().on('error', gutil.log))
    .pipe(gulp.dest('dest/assets'))
    .pipe(connect.reload());
});

gulp.task('html', function() {
  gulp.src(['./*.html', './views/*.html'])
    .pipe(gih({
      baseDir:'./views/',
      ignore:'./views/',
    }))
    .pipe(gulp.dest('dest'))
    .pipe(connect.reload());
});

gulp.task('connect', function() {
  connect.server({
    root: ['dest'],
    port: 8080,
    livereload: true
  })
});

gulp.task('watch', function () {
  gulp.watch(['./*.html', './templates/*.html'], ['html']);
  gulp.watch(['./src/styles/*.scss'], ['sass']);
  gulp.watch(['./src/scripts/*.js'], ['js']);
});

gulp.task('build', ['html', 'sass', 'js']);

gulp.task('serve', ['build'], serve('dest'));

// gulp.task('deploy', ['build'], function () {
//   gulp.src('./build/**/*')
//     .pipe(ghPages({
//     branch: 'master'
//     }))
// });

gulp.task('default', ['connect', 'watch', 'build']);
<commit_msg>fixed js/sass loading bug, gulp-cli test passed<commit_after>'use strict';

var gulp = require('gulp'),
    gutil = require('gulp-util'),
    connect = require('gulp-connect'),
    sass = require('gulp-sass'),
    uglify = require('gulp-uglify'),
    concat = require('gulp-concat'),
    serve = require('gulp-serve'),
    ghPages = require('gulp-gh-pages'),
    clean = require('gulp-clean'),
    gih = require('gulp-include-html');

gulp.task('js', function() {
  gulp.src('./src/js/*.js')
    .pipe(uglify())
    .pipe(gulp.dest('dest/assets'))
    .pipe(connect.reload());
});

gulp.task('sass', function() {
  gulp.src('./src/sass/app.scss')
    .pipe(sass().on('error', gutil.log))
    .pipe(gulp.dest('dest/assets'))
    .pipe(connect.reload());
});

gulp.task('html', function() {
  gulp.src(['./*.html', './views/*.html'])
    .pipe(gih({
      baseDir:'./views/',
      ignore:'./views/',
    }))
    .pipe(gulp.dest('dest'))
    .pipe(connect.reload());
});

gulp.task('connect', function() {
  connect.server({
    root: ['dest'],
    port: 8080,
    livereload: true
  })
});

gulp.task('watch', function () {
  gulp.watch(['./*.html', './templates/*.html'], ['html']);
  gulp.watch(['./src/styles/*.scss'], ['sass']);
  gulp.watch(['./src/scripts/*.js'], ['js']);
});

gulp.task('build', ['html', 'sass', 'js']);

gulp.task('serve', ['build'], serve('dest'));

// gulp.task('deploy', ['build'], function () {
//   gulp.src('./build/**/*')
//     .pipe(ghPages({
//     branch: 'master'
//     }))
// });

gulp.task('default', ['connect', 'watch', 'build']);
<|endoftext|>