<commit_before>'use strict';

(function (angular) {
    angular
        .module('fixedTimerPluginWidget')
        .controller('WidgetHomeCtrl', ['$scope', '$rootScope', 'Buildfire', 'DataStore', 'TAG_NAMES', 'STATUS_CODE', '$sce', '$timeout',
            function ($scope, $rootScope, Buildfire, DataStore, TAG_NAMES, STATUS_CODE, $sce, $timeout) {
                var WidgetHome = this;
                WidgetHome.data = null;
                WidgetHome.busy = false;
                WidgetHome.allItems = {};
                WidgetHome.isCounterNegative = false;
                WidgetHome.timerRunning = "stop";
                WidgetHome.counter = 5;
                WidgetHome.isPlay = false;
                WidgetHome.stopped = false;
                WidgetHome.stoppedPlus = false;
                WidgetHome.selectedTimerIndex =0;
                WidgetHome.timerObj = {'timerTime': 0, 'lastUpdatedTime': 0, 'isPause': false, 'itemId': 0, 'itemDescription': '', 'itemDefaultTimer': 5};
                WidgetHome.countdown = function () {
                    WidgetHome.timerRunning = "start";
                    if (!WidgetHome.isCounterNegative) {
                        WidgetHome.countdownNeg();
                    }
                    else {
                        WidgetHome.countdownPlus();
                    }
                };

                WidgetHome.countdownNeg = function () {
                    WidgetHome.stopped = $timeout(function () {
                        console.log($scope.counter);
                        var localStorageData = localStorage.getItem('timerObject');
                        localStorageData = localStorageData && JSON.parse(localStorageData);
                        var elapsedTimeInSec;
                        var actualTimerTime;
                        if (WidgetHome.counter <= 0) {
                            WidgetHome.isPlay = true;
                            WidgetHome.timerRunning = '';
                            WidgetHome.isCounterNegative = true;
                            WidgetHome.timerObj.timerTime = WidgetHome.counter - 1;
                            WidgetHome.timerObj.lastUpdatedTime = new Date().getTime();
                            WidgetHome.timerObj.isPause = false;
                            WidgetHome.timerObj.itemId = WidgetHome.selectedTimerIndex;
                            WidgetHome.timerObj.itemDescription = WidgetHome.description;
                            WidgetHome.timerObj.itemDefaultTimer = WidgetHome.counterSetTime;
                            localStorage.setItem('timerObject', JSON.stringify(WidgetHome.timerObj));
                            WidgetHome.counter = Math.abs(WidgetHome.counter - 1);
                            WidgetHome.countdownPlus();
                            return;
                        }
                        if(localStorageData && !localStorageData.isPause) {
                            elapsedTimeInSec = (new Date().getTime() - localStorageData.lastUpdatedTime)/1000;
                            actualTimerTime = Math.ceil(localStorageData.timerTime - elapsedTimeInSec);
                            WidgetHome.timerObj = {'timerTime': actualTimerTime, 'lastUpdatedTime': new Date().getTime(), 'isPause': false, 'itemId': WidgetHome.selectedTimerIndex, 'itemDescription': WidgetHome.description, 'itemDefaultTimer': WidgetHome.counterSetTime};
                            localStorage.setItem('timerObject', JSON.stringify(WidgetHome.timerObj));
                            WidgetHome.counter = Math.abs(actualTimerTime);
                            if(actualTimerTime <= 0) {
                                WidgetHome.isPlay = true;
                                WidgetHome.timerRunning = '';
                                WidgetHome.isCounterNegative = true;
                            }
                        } else {
                            WidgetHome.timerObj.timerTime = WidgetHome.counter - 1;
                            WidgetHome.timerObj.lastUpdatedTime = new Date().getTime();
                            WidgetHome.timerObj.isPause = false;
                            WidgetHome.timerObj.itemId = WidgetHome.selectedTimerIndex;
                            WidgetHome.timerObj.itemDescription = WidgetHome.description;
                            WidgetHome.timerObj.itemDefaultTimer = WidgetHome.counterSetTime;
                            localStorage.setItem('timerObject', JSON.stringify(WidgetHome.timerObj));
                            WidgetHome.counter = Math.abs(WidgetHome.counter - 1);
                        }
                        WidgetHome.countdownNeg();
                    }, 1000);
                };

                WidgetHome.countdownPlus = function () {
                    WidgetHome.stoppedPlus = $timeout(function () {
                        console.log(WidgetHome.counter);
                        var actualTimerTime;
                        var localStorageData = localStorage.getItem('timerObject');
                        localStorageData = localStorageData && JSON.parse(localStorageData);
                        var elapsedTimeInSec;
                        if(localStorageData) {
                            if(localStorageData.timerTime == 0 && localStorageData.isPause) {
                                WidgetHome.timerObj.timerTime = WidgetHome.counter - 1;
                                WidgetHome.timerObj.lastUpdatedTime = new Date().getTime();
                                WidgetHome.timerObj.isPause = false;
                                WidgetHome.timerObj.itemId = WidgetHome.selectedTimerIndex;
                                WidgetHome.timerObj.itemDescription = WidgetHome.description;
                                WidgetHome.timerObj.itemDefaultTimer = WidgetHome.counterSetTime;
                                localStorage.setItem('timerObject', JSON.stringify(WidgetHome.timerObj));
                                WidgetHome.counter = Math.abs(WidgetHome.counter - 1);
                            } else {
                                elapsedTimeInSec = (new Date().getTime() - localStorageData.lastUpdatedTime) / 1000;
                                actualTimerTime = localStorageData.timerTime - elapsedTimeInSec;
                                WidgetHome.timerObj = {'timerTime': actualTimerTime, 'lastUpdatedTime': new Date().getTime(), 'isPause': false, 'itemId': WidgetHome.selectedTimerIndex, 'itemDescription': WidgetHome.description, 'itemDefaultTimer': WidgetHome.counterSetTime};
                                localStorage.setItem('timerObject', JSON.stringify(WidgetHome.timerObj));
                                WidgetHome.counter = Math.abs(actualTimerTime);
                            }
                        }
//                        WidgetHome.counter++;
                        WidgetHome.countdownPlus();
                    }, 1000);
                };

                WidgetHome.silenceReset = function () {
                    WidgetHome.isPlay = false;
                    WidgetHome.stop();
                    WidgetHome.timerRunning = "stop";
                    WidgetHome.isCounterNegative = false;
                    var localStorageData = localStorage.getItem('timerObject');
                    localStorageData = localStorageData && JSON.parse(localStorageData);
                    if(localStorageData)
                        WidgetHome.counter = localStorageData.itemDefaultTimer;
                    else
                        WidgetHome.counter = WidgetHome.counterSetTime;
                    localStorage.removeItem('timerObject');
                };

                WidgetHome.stop = function () {
                    var localStorageData = localStorage.getItem('timerObject');
                    localStorageData = localStorageData && JSON.parse(localStorageData);
                    localStorageData.isPause = true;
                    localStorage.setItem('timerObject', JSON.stringify(localStorageData));
                    WidgetHome.timerRunning = "pause";
                    WidgetHome.isPlay = false;
                    if (WidgetHome.isCounterNegative)
                        $timeout.cancel(WidgetHome.stoppedPlus);
                    else
                        $timeout.cancel(WidgetHome.stopped);
                };

                WidgetHome.resetTimer = function () {
                    WidgetHome.stop();
                    WidgetHome.timerRunning = "stop";
                    WidgetHome.isCounterNegative = false;
                    var localStorageData = localStorage.getItem('timerObject');
                    localStorageData = localStorageData && JSON.parse(localStorageData);
                    if(localStorageData)
                        WidgetHome.counter = localStorageData.itemDefaultTimer;
                    else
                        WidgetHome.counter = WidgetHome.counterSetTime;
                    localStorage.removeItem('timerObject');
                };

                var getTimerItems = function () {
                    Buildfire.spinner.show();
                    var success = function (result) {
                            WidgetHome.allItems = result;
                            console.log("----------------", WidgetHome.allItems);
                            if(WidgetHome.allItems.length) {
                                WidgetHome.selectTimer(WidgetHome.allItems[0].data.data, 0);
                            }
                            Buildfire.spinner.hide();
                        },
                        error = function () {
                            Buildfire.spinner.hide();
                            console.log("Error fetching events");
                        };
                    DataStore.search({}, TAG_NAMES.TIMER_ITEMS).then(success, error);
                };

                WidgetHome.loadMore = function () {
                    if (WidgetHome.busy) return;
                    WidgetHome.busy = true;
                    getTimerItems();
                };

                WidgetHome.safeHtml = function (html) {
                    if (html)
                        return $sce.trustAsHtml(html);
                };

                /**
                 * init() function invocation to fetch previously saved user's data from datastore.
                 */
                var init = function () {

                    /*declare the device width heights*/
                    $rootScope.deviceHeight = window.innerHeight;
                    $rootScope.deviceWidth = window.innerWidth;
                    $rootScope.backgroundImage = "";

                    var success = function (result) {
                            WidgetHome.data = result.data;
                            if (!WidgetHome.data.content)
                                WidgetHome.data.content = {};
                            if (!WidgetHome.data.design)
                                WidgetHome.data.design = {};
                            $rootScope.backgroundImage = WidgetHome.data.design.backgroundImage ? WidgetHome.data.design.backgroundImage : "";
                            updateTimer();
                        }
                        , error = function (err) {
                            if (err && err.code !== STATUS_CODE.NOT_FOUND) {
                                console.error('Error while getting data', err);
                            }
                        };
                    getTimerItems();
                    DataStore.get(TAG_NAMES.TIMER_INFO).then(success, error);
                };

                function updateTimer() {
                    var elapsedTimeInSec;
                    var actualTimerTime;
                    var localStorageData = localStorage.getItem('timerObject');
                    localStorageData = localStorageData && JSON.parse(localStorageData);
                    if(localStorageData && !localStorageData.isPause) {
                        elapsedTimeInSec = (new Date().getTime() - localStorageData.lastUpdatedTime)/1000;
                        actualTimerTime = Math.ceil(localStorageData.timerTime - elapsedTimeInSec);
                        WidgetHome.timerObj = {'timerTime': actualTimerTime, 'lastUpdatedTime': new Date().getTime(), 'isPause': false, 'itemId': WidgetHome.selectedTimerIndex, 'itemDescription': WidgetHome.description, 'itemDefaultTimer': WidgetHome.counterSetTime};
                        localStorage.setItem('timerObject', JSON.stringify(WidgetHome.timerObj));
                        WidgetHome.counter = Math.abs(actualTimerTime);
                        WidgetHome.description = localStorageData.itemDescription;
                        WidgetHome.selectedTimerIndex = localStorageData.itemId;
                        if(actualTimerTime <= 0) {
                            WidgetHome.timerRunning = "";
                            WidgetHome.isPlay = true;
                        }
                        else
                            WidgetHome.timerRunning = "start";
                        WidgetHome.countdownNeg();
                    } else {
                        localStorage.removeItem('timerObject');
                    }
                }

                var onUpdateCallback = function (event) {

                    setTimeout(function () {
                        if (event) {
                            switch (event.tag) {
                                case TAG_NAMES.TIMER_INFO:
                                    WidgetHome.data = event.data;
                                    if (!WidgetHome.data.design)
                                        WidgetHome.data.design = {};
                                    if (!WidgetHome.data.content)
                                        WidgetHome.data.content = {};
                                    if (!event.data.design.backgroundImage) {
                                        $rootScope.backgroundImage = "";
                                    } else {
                                        $rootScope.backgroundImage = event.data.design.backgroundImage;
                                    }
                                    break;
                                case TAG_NAMES.TIMER_ITEMS:
                                    if (event.id && !event.data) {
                                        WidgetHome.allItems = $.grep(WidgetHome.allItems, function (e, i) {
                                            return e.id !== event.id;
                                        });
                                        WidgetHome.selectTimer(WidgetHome.allItems[0].data.data, 0);
                                    }
                                    console.log("---------------", event);
                                    //if(event.data) {
                                    //    WidgetHome.selectTimer(event.data.data);
                                    //}
                                    //else
                                    // if(WidgetHome.allItems.length){
                                    //   WidgetHome.selectTimer(WidgetHome.allItems.data);
                                    //}
                                    $scope.$apply();
                                    break;
                            }
                            $rootScope.$digest();
                        }
                    }, 0);
                };

                $rootScope.$on('TIMER_ADDED', function (e, item) {
                    console.log("============= inside timer added", WidgetHome.allItems, item);
                    WidgetHome.allItems.push(item);
                    WidgetHome.description = item.data && item.data.data && item.data.data.description;
                    WidgetHome.counterSetTime = item.data && item.data.data && item.data.data.timer && WidgetHome.covertToMS(item.data.data.timer);
                    WidgetHome.counter = item.data && item.data.data && item.data.data.timer && WidgetHome.covertToMS(item.data.data.timer);
                    console.log("=============", WidgetHome.allItems, item, WidgetHome.allItems.lastIndexOf(item));
                    WidgetHome.selectTimer (item.data.data, WidgetHome.allItems.lastIndexOf(item))
                    $scope.$digest();
                });
                $rootScope.$on('TIMER_UPDATED', function (e, item) {
                    console.log("============= inside timer updated", WidgetHome.allItems, item);
                    WidgetHome.allItems.forEach(function (itemData, index) {
                        if (itemData.id == item.id) {
                            WidgetHome.allItems[index] = item;
                            WidgetHome.description = item.data && item.data.data && item.data.data.description;
                            WidgetHome.counterSetTime = item.data && item.data.data && item.data.data.timer && WidgetHome.covertToMS(item.data.data.timer);
                            WidgetHome.counter = item.data && item.data.data && item.data.data.timer && WidgetHome.covertToMS(item.data.data.timer);
                            WidgetHome.selectTimer(item.data.data, index)
                            return false;
                        }
                    });
//              $rootScope.$digest();
                    console.log("=============", WidgetHome.allItems, item);
                });

                WidgetHome.covertToMS = function (data) {

                    if (!data.hrs) {
                        data.hrs = 0;
                    }
                    else {
                        data.hrs = Number(data.hrs);
                    }
                    if (!data.min) {
                        data.min = 0;
                    }
                    else {
                        data.min = Number(data.min);
                    }
                    if (!data.sec) {
                        data.sec = 0;
                    }
                    else {
                        data.sec = Number(data.sec);
                    }
                    console.log(data);
                    var timeInMS = data.hrs * 3600 + data.min * 60 + data.sec;
                    return timeInMS;
                };
                WidgetHome.selectTimer = function (data, elementId) {
                   if(WidgetHome.timerRunning!="start" && WidgetHome.timerRunning!="") {
                        WidgetHome.selectedTimerIndex = elementId;
                        console.log(WidgetHome.counter);
                        WidgetHome.description = data.description;
                        WidgetHome.counterSetTime = WidgetHome.covertToMS(data.timer);
                        WidgetHome.counter = WidgetHome.covertToMS(data.timer);
                    }
                };
                /**
                 * DataStore.onUpdate() is bound to listen any changes in datastore
                 */
                DataStore.onUpdate().then(null, null, onUpdateCallback);

                init();
            }]);
})(window.angular);<commit_msg>Switching app and returning back in timer app now shoes correct time if timer goes -ve<commit_after>'use strict';

(function (angular) {
    angular
        .module('fixedTimerPluginWidget')
        .controller('WidgetHomeCtrl', ['$scope', '$rootScope', 'Buildfire', 'DataStore', 'TAG_NAMES', 'STATUS_CODE', '$sce', '$timeout',
            function ($scope, $rootScope, Buildfire, DataStore, TAG_NAMES, STATUS_CODE, $sce, $timeout) {
                var WidgetHome = this;
                WidgetHome.data = null;
                WidgetHome.busy = false;
                WidgetHome.allItems = {};
                WidgetHome.isCounterNegative = false;
                WidgetHome.timerRunning = "stop";
                WidgetHome.counter = 5;
                WidgetHome.isPlay = false;
                WidgetHome.stopped = false;
                WidgetHome.stoppedPlus = false;
                WidgetHome.selectedTimerIndex =0;
                WidgetHome.timerObj = {'timerTime': 0, 'lastUpdatedTime': 0, 'isPause': false, 'itemId': 0, 'itemDescription': '', 'itemDefaultTimer': 5};
                WidgetHome.countdown = function () {
                    WidgetHome.timerRunning = "start";
                    if (!WidgetHome.isCounterNegative) {
                        WidgetHome.countdownNeg();
                    }
                    else {
                        WidgetHome.countdownPlus();
                    }
                };

                WidgetHome.countdownNeg = function () {
                    WidgetHome.stopped = $timeout(function () {
                        console.log($scope.counter);
                        var localStorageData = localStorage.getItem('timerObject');
                        localStorageData = localStorageData && JSON.parse(localStorageData);
                        var elapsedTimeInSec;
                        var actualTimerTime;
                        if (WidgetHome.counter <= 0 || (localStorageData && localStorageData.timerTime <= 0)) {
                            WidgetHome.isPlay = true;
                            WidgetHome.timerRunning = '';
                            WidgetHome.isCounterNegative = true;
                            WidgetHome.timerObj.timerTime = WidgetHome.counter - 1;
                            WidgetHome.timerObj.lastUpdatedTime = new Date().getTime();
                            WidgetHome.timerObj.isPause = false;
                            WidgetHome.timerObj.itemId = WidgetHome.selectedTimerIndex || (localStorageData && localStorageData.itemId);
                            WidgetHome.timerObj.itemDescription = WidgetHome.description || (localStorageData && localStorageData.itemDescription);
                            WidgetHome.timerObj.itemDefaultTimer = WidgetHome.counterSetTime || (localStorageData && localStorageData.itemDefaultTimer);
                            localStorage.setItem('timerObject', JSON.stringify(WidgetHome.timerObj));
                            WidgetHome.counter = Math.abs(WidgetHome.counter - 1);
                            WidgetHome.countdownPlus();
                            return;
                        }
                        if(localStorageData && !localStorageData.isPause) {
                            elapsedTimeInSec = (new Date().getTime() - localStorageData.lastUpdatedTime)/1000;
                            actualTimerTime = Math.ceil(localStorageData.timerTime - elapsedTimeInSec);
                            WidgetHome.timerObj = {'timerTime': actualTimerTime, 'lastUpdatedTime': new Date().getTime(), 'isPause': false, 'itemId': localStorageData.itemId, 'itemDescription': localStorageData.itemDescription, 'itemDefaultTimer': localStorageData.itemDefaultTimer};
                            localStorage.setItem('timerObject', JSON.stringify(WidgetHome.timerObj));
                            WidgetHome.counter = Math.abs(actualTimerTime);
                            if(actualTimerTime <= 0) {
                                WidgetHome.isPlay = true;
                                WidgetHome.timerRunning = '';
                                WidgetHome.isCounterNegative = true;
                            }
                        } else {
                            WidgetHome.timerObj.timerTime = WidgetHome.counter - 1;
                            WidgetHome.timerObj.lastUpdatedTime = new Date().getTime();
                            WidgetHome.timerObj.isPause = false;
                            WidgetHome.timerObj.itemId = WidgetHome.selectedTimerIndex;
                            WidgetHome.timerObj.itemDescription = WidgetHome.description;
                            WidgetHome.timerObj.itemDefaultTimer = WidgetHome.counterSetTime;
                            localStorage.setItem('timerObject', JSON.stringify(WidgetHome.timerObj));
                            WidgetHome.counter = Math.abs(WidgetHome.counter - 1);
                        }
                        WidgetHome.countdownNeg();
                    }, 1000);
                };

                WidgetHome.countdownPlus = function () {
                    WidgetHome.stoppedPlus = $timeout(function () {
                        console.log(WidgetHome.counter);
                        var actualTimerTime;
                        var localStorageData = localStorage.getItem('timerObject');
                        localStorageData = localStorageData && JSON.parse(localStorageData);
                        var elapsedTimeInSec;
                        if(localStorageData) {
                            WidgetHome.isCounterNegative = true;
                            if(localStorageData.timerTime == 0 && localStorageData.isPause) {
                                WidgetHome.timerObj.timerTime = WidgetHome.counter - 1;
                                WidgetHome.timerObj.lastUpdatedTime = new Date().getTime();
                                WidgetHome.timerObj.isPause = false;
                                WidgetHome.timerObj.itemId = localStorageData.itemId;
                                WidgetHome.timerObj.itemDescription = localStorageData.itemDescription;
                                WidgetHome.timerObj.itemDefaultTimer = localStorageData.itemDefaultTimer;
                                localStorage.setItem('timerObject', JSON.stringify(WidgetHome.timerObj));
                                WidgetHome.counter = Math.abs(WidgetHome.counter - 1);
                            } else {
                                elapsedTimeInSec = (new Date().getTime() - localStorageData.lastUpdatedTime) / 1000;
                                actualTimerTime = localStorageData.timerTime - elapsedTimeInSec;
                                WidgetHome.timerObj = {'timerTime': actualTimerTime, 'lastUpdatedTime': new Date().getTime(), 'isPause': false, 'itemId': localStorageData.itemId, 'itemDescription': localStorageData.itemDescription, 'itemDefaultTimer': localStorageData.itemDefaultTimer};
                                localStorage.setItem('timerObject', JSON.stringify(WidgetHome.timerObj));
                                WidgetHome.counter = Math.abs(actualTimerTime);
                            }
                        }
//                        WidgetHome.counter++;
                        WidgetHome.countdownPlus();
                    }, 1000);
                };

                WidgetHome.silenceReset = function () {
                    WidgetHome.isPlay = false;
                    WidgetHome.stop();
                    WidgetHome.timerRunning = "stop";
                    WidgetHome.isCounterNegative = false;
                    var localStorageData = localStorage.getItem('timerObject');
                    localStorageData = localStorageData && JSON.parse(localStorageData);
                    if(localStorageData)
                        WidgetHome.counter = localStorageData.itemDefaultTimer;
                    else
                        WidgetHome.counter = WidgetHome.counterSetTime;
                    localStorage.removeItem('timerObject');
                };

                WidgetHome.stop = function () {
                    var localStorageData = localStorage.getItem('timerObject');
                    localStorageData = localStorageData && JSON.parse(localStorageData);
                    localStorageData.isPause = true;
                    localStorage.setItem('timerObject', JSON.stringify(localStorageData));
                    WidgetHome.timerRunning = "pause";
                    WidgetHome.isPlay = false;
                    if (WidgetHome.isCounterNegative)
                        $timeout.cancel(WidgetHome.stoppedPlus);
                    else
                        $timeout.cancel(WidgetHome.stopped);
                };

                WidgetHome.resetTimer = function () {
                    WidgetHome.stop();
                    WidgetHome.timerRunning = "stop";
                    WidgetHome.isCounterNegative = false;
                    var localStorageData = localStorage.getItem('timerObject');
                    localStorageData = localStorageData && JSON.parse(localStorageData);
                    if(localStorageData)
                        WidgetHome.counter = localStorageData.itemDefaultTimer;
                    else
                        WidgetHome.counter = WidgetHome.counterSetTime;
                    localStorage.removeItem('timerObject');
                };

                var getTimerItems = function () {
                    Buildfire.spinner.show();
                    var success = function (result) {
                            WidgetHome.allItems = result;
                            console.log("----------------", WidgetHome.allItems);
                            if(WidgetHome.allItems.length) {
                                WidgetHome.selectTimer(WidgetHome.allItems[0].data.data, 0);
                            }
                            Buildfire.spinner.hide();
                        },
                        error = function () {
                            Buildfire.spinner.hide();
                            console.log("Error fetching events");
                        };
                    DataStore.search({}, TAG_NAMES.TIMER_ITEMS).then(success, error);
                };

                WidgetHome.loadMore = function () {
                    if (WidgetHome.busy) return;
                    WidgetHome.busy = true;
                    getTimerItems();
                };

                WidgetHome.safeHtml = function (html) {
                    if (html)
                        return $sce.trustAsHtml(html);
                };

                /**
                 * init() function invocation to fetch previously saved user's data from datastore.
                 */
                var init = function () {

                    /*declare the device width heights*/
                    $rootScope.deviceHeight = window.innerHeight;
                    $rootScope.deviceWidth = window.innerWidth;
                    $rootScope.backgroundImage = "";

                    var success = function (result) {
                            WidgetHome.data = result.data;
                            if (!WidgetHome.data.content)
                                WidgetHome.data.content = {};
                            if (!WidgetHome.data.design)
                                WidgetHome.data.design = {};
                            $rootScope.backgroundImage = WidgetHome.data.design.backgroundImage ? WidgetHome.data.design.backgroundImage : "";
                            updateTimer();
                        }
                        , error = function (err) {
                            if (err && err.code !== STATUS_CODE.NOT_FOUND) {
                                console.error('Error while getting data', err);
                            }
                        };
                    getTimerItems();
                    DataStore.get(TAG_NAMES.TIMER_INFO).then(success, error);
                };

                function updateTimer() {
                    var elapsedTimeInSec;
                    var actualTimerTime;
                    var localStorageData = localStorage.getItem('timerObject');
                    localStorageData = localStorageData && JSON.parse(localStorageData);
                    if(localStorageData && !localStorageData.isPause) {
                        elapsedTimeInSec = (new Date().getTime() - localStorageData.lastUpdatedTime)/1000;
                        actualTimerTime = Math.ceil(localStorageData.timerTime - elapsedTimeInSec);
                        WidgetHome.timerObj = {'timerTime': actualTimerTime, 'lastUpdatedTime': new Date().getTime(), 'isPause': false, 'itemId': localStorageData.itemId, 'itemDescription': localStorageData.itemDescription, 'itemDefaultTimer': localStorageData.itemDefaultTimer};
                        localStorage.setItem('timerObject', JSON.stringify(WidgetHome.timerObj));
                        WidgetHome.counter = Math.abs(actualTimerTime);
                        WidgetHome.description = localStorageData.itemDescription;
                        WidgetHome.selectedTimerIndex = localStorageData.itemId;
                        if(actualTimerTime <= 0) {
                            WidgetHome.timerRunning = "";
                            WidgetHome.isPlay = true;
                            WidgetHome.countdownPlus();
                        }
                        else {
                            WidgetHome.timerRunning = "start";
                            WidgetHome.countdownNeg();
                        }
                    } else {
                        localStorage.removeItem('timerObject');
                    }
                }

                var onUpdateCallback = function (event) {

                    setTimeout(function () {
                        if (event) {
                            switch (event.tag) {
                                case TAG_NAMES.TIMER_INFO:
                                    WidgetHome.data = event.data;
                                    if (!WidgetHome.data.design)
                                        WidgetHome.data.design = {};
                                    if (!WidgetHome.data.content)
                                        WidgetHome.data.content = {};
                                    if (!event.data.design.backgroundImage) {
                                        $rootScope.backgroundImage = "";
                                    } else {
                                        $rootScope.backgroundImage = event.data.design.backgroundImage;
                                    }
                                    break;
                                case TAG_NAMES.TIMER_ITEMS:
                                    if (event.id && !event.data) {
                                        WidgetHome.allItems = $.grep(WidgetHome.allItems, function (e, i) {
                                            return e.id !== event.id;
                                        });
                                        WidgetHome.selectTimer(WidgetHome.allItems[0].data.data, 0);
                                    }
                                    console.log("---------------", event);
                                    //if(event.data) {
                                    //    WidgetHome.selectTimer(event.data.data);
                                    //}
                                    //else
                                    // if(WidgetHome.allItems.length){
                                    //   WidgetHome.selectTimer(WidgetHome.allItems.data);
                                    //}
                                    $scope.$apply();
                                    break;
                            }
                            $rootScope.$digest();
                        }
                    }, 0);
                };

                $rootScope.$on('TIMER_ADDED', function (e, item) {
                    console.log("============= inside timer added", WidgetHome.allItems, item);
                    WidgetHome.allItems.push(item);
                    WidgetHome.description = item.data && item.data.data && item.data.data.description;
                    WidgetHome.counterSetTime = item.data && item.data.data && item.data.data.timer && WidgetHome.covertToMS(item.data.data.timer);
                    WidgetHome.counter = item.data && item.data.data && item.data.data.timer && WidgetHome.covertToMS(item.data.data.timer);
                    console.log("=============", WidgetHome.allItems, item, WidgetHome.allItems.lastIndexOf(item));
                    WidgetHome.selectTimer (item.data.data, WidgetHome.allItems.lastIndexOf(item))
                    $scope.$digest();
                });
                $rootScope.$on('TIMER_UPDATED', function (e, item) {
                    console.log("============= inside timer updated", WidgetHome.allItems, item);
                    WidgetHome.allItems.forEach(function (itemData, index) {
                        if (itemData.id == item.id) {
                            WidgetHome.allItems[index] = item;
                            WidgetHome.description = item.data && item.data.data && item.data.data.description;
                            WidgetHome.counterSetTime = item.data && item.data.data && item.data.data.timer && WidgetHome.covertToMS(item.data.data.timer);
                            WidgetHome.counter = item.data && item.data.data && item.data.data.timer && WidgetHome.covertToMS(item.data.data.timer);
                            WidgetHome.selectTimer(item.data.data, index)
                            return false;
                        }
                    });
//              $rootScope.$digest();
                    console.log("=============", WidgetHome.allItems, item);
                });

                WidgetHome.covertToMS = function (data) {

                    if (!data.hrs) {
                        data.hrs = 0;
                    }
                    else {
                        data.hrs = Number(data.hrs);
                    }
                    if (!data.min) {
                        data.min = 0;
                    }
                    else {
                        data.min = Number(data.min);
                    }
                    if (!data.sec) {
                        data.sec = 0;
                    }
                    else {
                        data.sec = Number(data.sec);
                    }
                    console.log(data);
                    var timeInMS = data.hrs * 3600 + data.min * 60 + data.sec;
                    return timeInMS;
                };
                WidgetHome.selectTimer = function (data, elementId) {
                   if(WidgetHome.timerRunning!="start" && WidgetHome.timerRunning!="") {
                        WidgetHome.selectedTimerIndex = elementId;
                        console.log(WidgetHome.counter);
                        WidgetHome.description = data.description;
                        WidgetHome.counterSetTime = WidgetHome.covertToMS(data.timer);
                        WidgetHome.counter = WidgetHome.covertToMS(data.timer);
                    }
                };
                /**
                 * DataStore.onUpdate() is bound to listen any changes in datastore
                 */
                DataStore.onUpdate().then(null, null, onUpdateCallback);

                init();
            }]);
})(window.angular);<|endoftext|>


<commit_before>const dry = (function() {
    "use strict";
    const unsafeWindow = this.unsafeWindow || this.window;

    const unique = function(a, key) {
        if (key) {
            return a.filter(function(e) {
                e = key(e);
                return !!e && (!this.has(e) && !!this.add(e));
            }, new Set());
        }
        return a.filter(function(e) {
            return !!e && (!this.has(e) && !!this.add(e));
        }, new Set());
    };

    const EventKeys = Symbol();
    class EventEmitter {
        constructor() {
            this[EventKeys] = new Map();
        }
        on(event, cb) {
            let handlers = this[EventKeys].get(event);
            if (!handlers) {
                this[EventKeys].set(event, handlers = new Set());
            }
            handlers.add(cb);
        }
        off(event, cb) {
            const keys = this[EventKeys];
            const handlers = keys.get(event);
            if (!handlers) {
                return;
            }
            handlers.delete(cb);
            if (!handlers.size) {
               keys.delete(event);
            }
        }
        once(event, cb, ...args) {
            let wrapped = (...args) => {
                try {
                    return cb(...args);
                }
                finally {
                    this.off(event, wrapped);
                }
            };
            return this.on(event, wrapped, ...args);
        }
        emit(event, ...args) {
            const handlers = this[EventKeys].get(event);
            if (!handlers) {
                return;
            }
            for (let e of Array.from(handlers)) {
                try {
                    e(...args);
                }
                catch (ex) {
                    console.error(`Event handler ${e} for ${event} failed`, ex);
                }
            }
        }
        emitSoon(event, ...args) {
            setTimeout(() => this.emit(event, ...args));
        }
    }

    const bus = new EventEmitter();

    if (document.readyState === "interactive" || document.readyState === "complete" ) {
        bus.emitSoon("dom", null, false);
    }
    else {
        addEventListener("DOMContentLoaded", function dom(evt) {
            removeEventListener("DOMContentLoaded", dom, true);
            bus.emit("dom", evt, true);
        }, true);
    }

    if (document.readyState === "complete") {
        bus.emitSoon("load", null, false);
    }
    else {
        addEventListener("load", function load(evt) {
            removeEventListener("load", load, true);
            bus.emit("load", evt, true);
        }, true);
    }

    let exts = null;
    try {
        exts = (window.Room || unsafeWindow.Room).prototype._extensions.connection.prototype.room.extensions;
    }
    catch (ex) {
        bus.on("load", () => {
            exts = (window.Room || unsafeWindow.Room).prototype._extensions.connection.prototype.room.extensions;
        });
    }
    let exportObject = function(o) {
        return unsafeWindow.JSON.parse(JSON.stringify(o));
    };
    let exportFunction = this.exportFunction;

    if (!exportFunction) {
        exportFunction = (fn, o) => fn;
        exportObject = o => o;
    }

    const replace = function(proto, where, what, newfn) {
        let ext = this[where];
        if (!ext) {
            throw new Error("Binding not available");
        }
        if (proto) {
            if (ext.prototype && document.readyState !== "complete") {
                ext = ext.prototype;
            }
            else {
                console.warn("binding late, skipping prototype, this might not work", where, what);
                return replace.call(exts, false, where, what, newfn);
            }
            if (!ext) {
                throw new Error("Binding prototype not available");
            }
        }
        let origfn = ext[what];
        if (!origfn) {
            throw new Error("Target not available");
        }
        ext[what] = exportFunction(function(...args) {
            return newfn.call(this, origfn.bind(this), ...args);
        }, unsafeWindow);
        return ext[what].bind(ext);
    };

    const replaceEarly = (...args) => {
        return replace.call((window.Room || unsafeWindow.Room).prototype._extensions, true, ...args);
    };

    class Commands {
        constructor() {
            replaceEarly("chat", "onCommand", (orig, command, e, ...args) => {
                let fn = this[command];
                if (fn && fn.call(this, e, args) !== false) {
                    return;
                }
                args.unshift(e);
                args.unshift(command);
                return orig(...exportObject(args));
            });
        }
    }

    const appendMessage = (user, message, options) => {
        let o = {
            dontsave: true,
            staff: true,
            highlight: true
        };
        if (options) {
            Object.assign(o, options);
        }
        if (message.trim) {
            message = [{type: "text", value: message}];
        }
        return exts.chat.showMessage(user, exportObject(message), exportObject(o));
    };

    let config = window.config || unsafeWindow.config;
    if (!config) {
        bus.once("load", () => {
            config = window.config || unsafeWindow.config;
        });
    }

    return {
        on: bus.on.bind(bus),
        off: bus.off.bind(bus),
        once: bus.once.bind(bus),
        emit: bus.emit.bind(bus),
        get config() {
            return config;
        },
        get exts() {
            return exts;
        },
        unsafeWindow,
        replaceEarly,
        replaceLate(...args) {
            return replace.call(this.exts, false, ...args);
        },
        appendMessage,
        exportFunction,
        exportObject,
        unique,
        EventEmitter,
        Commands,
        version: "0.2",
    };
}).call(this);
<commit_msg>More fixes just because<commit_after>const dry = (function() {
    "use strict";
    const unsafeWindow = this.unsafeWindow || window;

    const unique = function(a, key) {
        if (key) {
            return a.filter(function(e) {
                e = key(e);
                return !!e && (!this.has(e) && !!this.add(e));
            }, new Set());
        }
        return a.filter(function(e) {
            return !!e && (!this.has(e) && !!this.add(e));
        }, new Set());
    };

    const EventKeys = Symbol();
    class EventEmitter {
        constructor() {
            this[EventKeys] = new Map();
        }
        on(event, cb) {
            let handlers = this[EventKeys].get(event);
            if (!handlers) {
                this[EventKeys].set(event, handlers = new Set());
            }
            handlers.add(cb);
        }
        off(event, cb) {
            const keys = this[EventKeys];
            const handlers = keys.get(event);
            if (!handlers) {
                return;
            }
            handlers.delete(cb);
            if (!handlers.size) {
               keys.delete(event);
            }
        }
        once(event, cb, ...args) {
            let wrapped = (...args) => {
                try {
                    return cb(...args);
                }
                finally {
                    this.off(event, wrapped);
                }
            };
            return this.on(event, wrapped, ...args);
        }
        emit(event, ...args) {
            const handlers = this[EventKeys].get(event);
            if (!handlers) {
                return;
            }
            for (let e of Array.from(handlers)) {
                try {
                    e(...args);
                }
                catch (ex) {
                    console.error(`Event handler ${e} for ${event} failed`, ex);
                }
            }
        }
        emitSoon(event, ...args) {
            setTimeout(() => this.emit(event, ...args));
        }
    }

    const bus = new EventEmitter();

    if (document.readyState === "interactive" || document.readyState === "complete" ) {
        bus.emitSoon("dom", null, false);
    }
    else {
        addEventListener("DOMContentLoaded", function dom(evt) {
            removeEventListener("DOMContentLoaded", dom, true);
            bus.emit("dom", evt, true);
        }, true);
    }

    if (document.readyState === "complete") {
        bus.emitSoon("load", null, false);
    }
    else {
        addEventListener("load", function load(evt) {
            removeEventListener("load", load, true);
            bus.emit("load", evt, true);
        }, true);
    }

    let exts = null;
    try {
        exts = (window.Room || unsafeWindow.Room).prototype._extensions.connection.prototype.room.extensions;
    }
    catch (ex) {
        bus.on("load", () => {
            exts = (window.Room || unsafeWindow.Room).prototype._extensions.connection.prototype.room.extensions;
        });
    }
    let exportObject = function(o) {
        return unsafeWindow.JSON.parse(JSON.stringify(o));
    };
    let exportFunction = this.exportFunction;

    if (!exportFunction) {
        exportFunction = (fn, o) => fn;
        exportObject = o => o;
    }

    const replace = function(proto, where, what, newfn) {
        let ext = this[where];
        if (!ext) {
            throw new Error("Binding not available");
        }
        if (proto) {
            if (ext.prototype && document.readyState !== "complete") {
                ext = ext.prototype;
            }
            else {
                console.warn("binding late, skipping prototype, this might not work", where, what);
                return replace.call(exts, false, where, what, newfn);
            }
            if (!ext) {
                throw new Error("Binding prototype not available");
            }
        }
        let origfn = ext[what];
        if (!origfn) {
            throw new Error("Target not available");
        }
        ext[what] = exportFunction(function(...args) {
            return newfn.call(this, origfn.bind(this), ...args);
        }, unsafeWindow);
        return ext[what].bind(ext);
    };

    const replaceEarly = (...args) => {
        return replace.call((window.Room || unsafeWindow.Room).prototype._extensions, true, ...args);
    };

    class Commands {
        constructor() {
            replaceEarly("chat", "onCommand", (orig, command, e, ...args) => {
                let fn = this[command];
                if (fn && fn.call(this, e, args) !== false) {
                    return;
                }
                args.unshift(e);
                args.unshift(command);
                return orig(...exportObject(args));
            });
        }
    }

    const appendMessage = (user, message, options) => {
        let o = {
            dontsave: true,
            staff: true,
            highlight: true
        };
        if (options) {
            Object.assign(o, options);
        }
        if (message.trim) {
            message = [{type: "text", value: message}];
        }
        return exts.chat.showMessage(user, exportObject(message), exportObject(o));
    };

    let config = window.config || unsafeWindow.config;
    if (!config) {
        bus.once("load", () => {
            config = window.config || unsafeWindow.config;
        });
    }

    return {
        on: bus.on.bind(bus),
        off: bus.off.bind(bus),
        once: bus.once.bind(bus),
        emit: bus.emit.bind(bus),
        get config() {
            return config;
        },
        get exts() {
            return exts;
        },
        unsafeWindow,
        replaceEarly,
        replaceLate(...args) {
            return replace.call(this.exts, false, ...args);
        },
        appendMessage,
        exportFunction,
        exportObject,
        unique,
        EventEmitter,
        Commands,
        version: "0.2",
    };
}).call(this);
<|endoftext|>


<commit_before>
var gulp = require('gulp');

var template = require('lucify-commons/src/js/lucify-page-def-template.js');

var opts = {

  pageDef: template.apply({
    title: "Hello World Title",
    description: 'Hello World description',
    ogType: 'article',
    twitterImage: '50euro.jpg',
    openGraphImage: '100euro.jpg',
    schemaImage: '200euro.jpg'
  }),

  iFrameResize: false,
  paths: ['node_modules/lucify-commons', 'test_modules/module1'],
  publishFromFolder: 'dist',
  defaultBucket: 'lucify-dev',
  maxAge: 3600,
  assetContext: 'hello-world/',
  baseUrl: 'http://dev.lucify.com/',
}

var builder = require('../../index.js'); // lucify-component-builder
builder(gulp, opts);
<commit_msg>Add project name in metadata to support local also local deploys<commit_after>
var gulp = require('gulp');

var template = require('lucify-commons/src/js/lucify-page-def-template.js');

var opts = {
  project: 'single-page-test-project',

  pageDef: template.apply({
    title: "Hello World Title",
    description: 'Hello World description',
    ogType: 'article',
    twitterImage: '50euro.jpg',
    openGraphImage: '100euro.jpg',
    schemaImage: '200euro.jpg'
  }),

  iFrameResize: false,
  paths: ['node_modules/lucify-commons', 'test_modules/module1'],
  publishFromFolder: 'dist',
  defaultBucket: 'lucify-dev',
  maxAge: 3600,
  assetContext: 'hello-world/',
  baseUrl: 'http://dev.lucify.com/',
}

var builder = require('../../index.js'); // lucify-component-builder
builder(gulp, opts);
<|endoftext|>


<commit_before>/**
* Copyright (c) Microsoft.  All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

var fs = require('fs');
if (!fs.existsSync) {
  fs.existsSync = require('path').existsSync;
}

var azure;
if (fs.existsSync('./../../lib/azure.js')) {
  azure = require('./../../lib/azure');
} else {
  azure = require('azure');
}

var express = require('express');
var formidable = require('formidable');
var helpers = require('./helpers.js');

var app = module.exports = express.createServer();
// Global request options, set the retryPolicy
var blobClient = azure.createBlobService('UseDevelopmentStorage=true').withFilter(new azure.ExponentialRetryPolicyFilter());
var containerName = 'webpi';

//Configuration
app.configure(function () {
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.methodOverride());
  // app.use(express.logger());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function () {
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function () {
  app.use(express.errorHandler());
});

app.param(':id', function (req, res, next) {
  next();
});

//Routes
app.get('/', function (req, res) {
  res.render('index.ejs', { locals: {
    title: 'Welcome'
  }
  });
});

app.get('/Upload', function (req, res) {
  res.render('upload.ejs', { locals: {
    title: 'Upload File'
  }
  });
});

app.get('/Display', function (req, res) {
  blobClient.listBlobs(containerName, function (error, blobs) {
    res.render('display.ejs', { locals: {
      title: 'List of Blobs',
      serverBlobs: blobs
    }
    });
  });
});

app.get('/Download/:id', function (req, res) {
  blobClient.getBlobProperties(containerName, req.params.id, function (err, blobInfo) {
    if (err === null) {
      res.header('content-type', blobInfo.contentType);
      res.header('content-disposition', 'attachment; filename=' + blobInfo.metadata.filename);
      blobClient.getBlobToStream(containerName, req.params.id, res, function () { });
    } else {
      helpers.renderError(res);
    }
  });
});

app.post('/uploadhandler', function (req, res) {
  var form = new formidable.IncomingForm();

  form.parse(req, function (err, fields, files) {
    var formValid = true;
    if (fields.itemName === '') {
      helpers.renderError(res);
      formValid = false;
    }

    if (formValid) {
      var extension = files.uploadedFile.name.split('.').pop();
      var newName = fields.itemName + '.' + extension;

      var options = {
        contentType: files.uploadedFile.type,
        metadata: { fileName: newName }
      };

      blobClient.createBlockBlobFromFile(containerName, fields.itemName, files.uploadedFile.path, options, function (error) {
        if (error != null) {
          helpers.renderError(res);
        } else {
          res.redirect('/Display');
        }
      });
    } else {
      helpers.renderError(res);
    }
  });
});

app.post('/Delete/:id', function (req, res) {
  blobClient.deleteBlob(containerName, req.params.id, function (error) {
    if (error != null) {
      helpers.renderError(res);
    } else {
      res.redirect('/Display');
    }
  });
});

blobClient.createContainerIfNotExists(containerName, function (error) {
  if (error) {
    console.log(error);
  } else {
    setPermissions();
  }
});

function setPermissions() {
  blobClient.setContainerAcl(containerName, azure.Constants.BlobConstants.BlobContainerPublicAccessType.BLOB, function (error) {
    if (error) {
      console.log(error);
    } else {
      app.listen(process.env.port || 1337);
      console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
    }
  });
}<commit_msg>test it<commit_after>/**
* Copyright (c) Microsoft.  All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

var fs = require('fs');
if (!fs.existsSync) {
  fs.existsSync = require('path').existsSync;
}

var azure;
if (fs.existsSync('./../../lib/azure.js')) {
  azure = require('./../../lib/azure');
} else {
  azure = require('azure');
}

var express = require('express');
var formidable = require('formidable');
var helpers = require('./helpers.js');

var app = module.exports = express.createServer();
// Global request options, set the retryPolicy
var blobClient = azure.createBlobService('UseDevelopmentStorage=true').withFilter(new azure.ExponentialRetryPolicyFilter());
var containerName = 'webpi';

//Configuration
app.configure(function () {
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.methodOverride());
  // app.use(express.logger());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function () {
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function () {
  app.use(express.errorHandler());
});

app.param(':id', function (req, res, next) {
  next();
});

//Routes
app.get('/', function (req, res) {
  res.render('index.ejs', { locals: {
    title: 'Welcome'
  }
  });
});

app.get('/Upload', function (req, res) {
  res.render('upload.ejs', { locals: {
    title: 'Upload File'
  }
  });
});

app.get('/Display', function (req, res) {
  blobClient.listBlobs(containerName, function (error, blobs) {
    res.render('display.ejs', { locals: {
      title: 'List of Blobs',
      serverBlobs: blobs
    }
    });
  });
});

app.get('/Download/:id', function (req, res) {
  blobClient.getBlobProperties(containerName, req.params.id, function (err, blobInfo) {
    if (err === null) {
      res.header('content-type', blobInfo.contentType);
      res.header('content-disposition', 'attachment; filename=' + blobInfo.metadata.filename);
      blobClient.getBlobToStream(containerName, req.params.id, res, function () { });
    } else {
      helpers.renderError(res);
    }
  });
});

app.post('/uploadhandler', function (req, res) {
  var form = new formidable.IncomingForm();

  form.parse(req, function (err, fields, files) {
    var formValid = true;
    if (fields.itemName === '') {
      helpers.renderError(res);
      formValid = false;
    }

    if (formValid) {
      var extension = files.uploadedFile.name.split('.').pop();
      var newName = fields.itemName + '.' + extension;

      var options = {
        contentType: files.uploadedFile.type,
        metadata: { fileName: newName }
      };

      blobClient.createBlockBlobFromFile(containerName, fields.itemName, files.uploadedFile.path, options, function (error) {
        if (error != null) {
          helpers.renderError(res);
        } else {
            setSAS(containerName, fields.itemName);
          res.redirect('/Display');
        }
      });
    } else {
      helpers.renderError(res);
    }
  });
});

app.post('/Delete/:id', function (req, res) {
  blobClient.deleteBlob(containerName, req.params.id, function (error) {
    if (error != null) {
      helpers.renderError(res);
    } else {
      res.redirect('/Display');
    }
  });
});

blobClient.createContainerIfNotExists(containerName, function (error) {
  if (error) {
    console.log(error);
  } else {
    setPermissions();
  }
});

function setSAS(containerName, blobName) {
    var sharedAccessPolicy = {
        AccessPolicy: {
            Expiry: azure.date.minutesFromNow(5)
        }
    };

    var blobUrl = blobClient.getBlobUrl(containerName, blobName, sharedAccessPolicy);
    console.log("access the blob at ", blobUrl);
}

function setPermissions() {
  blobClient.setContainerAcl(containerName, azure.Constants.BlobConstants.BlobContainerPublicAccessType.BLOB, function (error) {
    if (error) {
      console.log(error);
    } else {
      app.listen(process.env.port || 1337);
      console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
    }
  });
}<|endoftext|>


<commit_before>// https://www.bloomberg.com/quote/USDGBP:CUR
const EXCHANGE_RATE_USD_TO_GBP = 0.7189
const EXCHANGE_RATE_GBP_TO_USD = parseFloat(
  Number(1 / EXCHANGE_RATE_USD_TO_GBP).toFixed(4)
)

const DATE_LONG_FORMAT = 'd MMMM yyyy'
const DATE_DAY_LONG_FORMAT = 'E, dd MMM yyyy'
const DATE_MEDIUM_FORMAT = 'd mmm yyyy'
const DATE_TIME_MEDIUM_FORMAT = 'd MMM yyyy, h:mmaaa'

module.exports = {
  EXCHANGE_RATE_USD_TO_GBP,
  EXCHANGE_RATE_GBP_TO_USD,
  DATE_DAY_LONG_FORMAT,
  DATE_LONG_FORMAT,
  DATE_MEDIUM_FORMAT,
  DATE_TIME_MEDIUM_FORMAT,
}
<commit_msg>Update the USDGBP exchange rate<commit_after>// https://www.bloomberg.com/quote/USDGBP:CUR
const EXCHANGE_RATE_USD_TO_GBP = 0.7062
const EXCHANGE_RATE_GBP_TO_USD = parseFloat(
  Number(1 / EXCHANGE_RATE_USD_TO_GBP).toFixed(4)
)

const DATE_LONG_FORMAT = 'd MMMM yyyy'
const DATE_DAY_LONG_FORMAT = 'E, dd MMM yyyy'
const DATE_MEDIUM_FORMAT = 'd mmm yyyy'
const DATE_TIME_MEDIUM_FORMAT = 'd MMM yyyy, h:mmaaa'

module.exports = {
  EXCHANGE_RATE_USD_TO_GBP,
  EXCHANGE_RATE_GBP_TO_USD,
  DATE_DAY_LONG_FORMAT,
  DATE_LONG_FORMAT,
  DATE_MEDIUM_FORMAT,
  DATE_TIME_MEDIUM_FORMAT,
}
<|endoftext|>


<commit_before>/*!
 * array-keys
 *   version 1.2.2
 *   http://github.com/silverbucket/array-keys
 *
 * Developed and Maintained by:
 *   Nick Jennings <nick@silverbucket.net> copyright 2014
 *
 * array-keys is released under the LGPL (see LICENSE).
 *
 * You don't have to do anything special to choose one license or the other
 * and you don't have to notify anyone which license you are using.
 * Please see the corresponding license file for details of these licenses.
 * You are free to use, modify and distribute this software, but all copyright
 * information must remain.
 *
 */

function ArrayKeys(p) {
  if (typeof p !== 'object') { p = {}; }
  this.identifier = p.identifier || 'id';
  this.store = [];
  this.idx = []; // array of identifier strings for quick lookup
}

ArrayKeys.prototype.getIdentifiers = function () {
  var ids = [];
  for (var i = this.store.length - 1; i >= 0; i = i - 1) {
    ids[ids.length] = this.store[i][this.identifier];
  }
  return ids;
};

ArrayKeys.prototype.getRecord = function (id) {
  for (var i = this.store.length - 1; i >= 0; i = i - 1) {
    if (this.store[i][this.identifier] === id) {
      return this.store[i];
    }
  }
  return undefined;
};

ArrayKeys.prototype.exists = function (id) {
  if (this.getIndex(id) >= 0) {
    return true;
  } else {
    return false;
  }
};

// faster than using indexOf
ArrayKeys.prototype.getIndex = function (id) {
  for (i = this.idx.length - 1; i >= 0; i = i - 1) {
    if (this.idx[i] === id) {
      return i;
    }
  }
  return -1;
};

ArrayKeys.prototype.addRecord = function (record) {
  if (typeof record !== 'object') {
    throw new Error('cannot add non-object records.');
  } else if (!record[this.identifier]) {
    throw new Error('cannot add a record with no `' + this.identifier +
                    '` property specified.');
  }

  this.removeRecord(record[this.identifier]);
  this.idx[this.idx.length] = record[this.identifier];
  this.store[this.store.length] = record;
  return true;
};

ArrayKeys.prototype.removeRecord = function (id) {
  var idx  = this.getIndex(id);
  if (idx < 0) {
    return false;
  }

  var i;
  // start looking for the record at the same point as the idx entry
  for (i = idx; i !== 0; i = i - 1) {
    if (this.store[i][this.identifier] === id) {
      this.store.splice(i, 1);
      this.idx.splice(idx, 1);
      return true;
    }
  }

  // if it was not found, start at the end and break at the idx number
  for (i = this.store.length - 1; i !== idx; i = i - 1) {
    if (this.store[i][this.identifier] === id) {
      this.store.splice(i, 1);
      this.idx.splice(idx, 1);
      return true;
    }
  }
  return false;
};

ArrayKeys.prototype.forEachRecord = function (cb) {
  var count = 0;
  var self = this;
  var finished = function () {};

  setTimeout(function () {
    for (var i = self.store.length - 1; i >= 0; i = i - 1) {
      count += 1;
      cb(self.store[i]);
    }
    finished(count);
  }, 0);

  return {
    finally: function (func) {
      finished = func;
    }
  };
};

ArrayKeys.prototype.getCount = function () {
  return this.store.length;
};

module.exports = ArrayKeys;
<commit_msg>undefined counter var i<commit_after>/*!
 * array-keys
 *   version 1.2.2
 *   http://github.com/silverbucket/array-keys
 *
 * Developed and Maintained by:
 *   Nick Jennings <nick@silverbucket.net> copyright 2014
 *
 * array-keys is released under the LGPL (see LICENSE).
 *
 * You don't have to do anything special to choose one license or the other
 * and you don't have to notify anyone which license you are using.
 * Please see the corresponding license file for details of these licenses.
 * You are free to use, modify and distribute this software, but all copyright
 * information must remain.
 *
 */

function ArrayKeys(p) {
  if (typeof p !== 'object') { p = {}; }
  this.identifier = p.identifier || 'id';
  this.store = [];
  this.idx = []; // array of identifier strings for quick lookup
}

ArrayKeys.prototype.getIdentifiers = function () {
  var ids = [];
  for (var i = this.store.length - 1; i >= 0; i = i - 1) {
    ids[ids.length] = this.store[i][this.identifier];
  }
  return ids;
};

ArrayKeys.prototype.getRecord = function (id) {
  for (var i = this.store.length - 1; i >= 0; i = i - 1) {
    if (this.store[i][this.identifier] === id) {
      return this.store[i];
    }
  }
  return undefined;
};

ArrayKeys.prototype.exists = function (id) {
  if (this.getIndex(id) >= 0) {
    return true;
  } else {
    return false;
  }
};

// faster than using indexOf
ArrayKeys.prototype.getIndex = function (id) {
  for (var i = this.idx.length - 1; i >= 0; i = i - 1) {
    if (this.idx[i] === id) {
      return i;
    }
  }
  return -1;
};

ArrayKeys.prototype.addRecord = function (record) {
  if (typeof record !== 'object') {
    throw new Error('cannot add non-object records.');
  } else if (!record[this.identifier]) {
    throw new Error('cannot add a record with no `' + this.identifier +
                    '` property specified.');
  }

  this.removeRecord(record[this.identifier]);
  this.idx[this.idx.length] = record[this.identifier];
  this.store[this.store.length] = record;
  return true;
};

ArrayKeys.prototype.removeRecord = function (id) {
  var idx  = this.getIndex(id);
  if (idx < 0) {
    return false;
  }

  var i;
  // start looking for the record at the same point as the idx entry
  for (i = idx; i !== 0; i = i - 1) {
    if (this.store[i][this.identifier] === id) {
      this.store.splice(i, 1);
      this.idx.splice(idx, 1);
      return true;
    }
  }

  // if it was not found, start at the end and break at the idx number
  for (i = this.store.length - 1; i !== idx; i = i - 1) {
    if (this.store[i][this.identifier] === id) {
      this.store.splice(i, 1);
      this.idx.splice(idx, 1);
      return true;
    }
  }
  return false;
};

ArrayKeys.prototype.forEachRecord = function (cb) {
  var count = 0;
  var self = this;
  var finished = function () {};

  setTimeout(function () {
    for (var i = self.store.length - 1; i >= 0; i = i - 1) {
      count += 1;
      cb(self.store[i]);
    }
    finished(count);
  }, 0);

  return {
    finally: function (func) {
      finished = func;
    }
  };
};

ArrayKeys.prototype.getCount = function () {
  return this.store.length;
};

module.exports = ArrayKeys;
<|endoftext|>


<commit_before>//todo write angular scripts for developer page.

var developerKingdomModule = angular.module('app', []).
	controller("forumCtrl", function forumCtrl($scope, $window, $http){

		$scope.forum = {
			threads: [{subject: "blah blah blah", id: "1",  posts: []},
				{subject: "how to add your own functions", posts: []}
			]
		};

		var getThreadIndexFromID = function(id){
			for(var i = 0; i < $scope.forum.threads.length; i++){
				if($scope.forum.threads[i].id == id){
					return i;
				}
			}
		}

		$scope.fetch = function(){
			var additionalThreads = [];

			$http({method: "GET", url: "http://localhost:3000/threads"}).success(function(data, status){

				additionalThreads = data;
				for(var i = 0; i < additionalThreads; i++){
					$scope.forum.threads.push(additionalThreads[i]);
				}

				$scope.$apply();

				var additionalPosts = [];
				$http({method: "GET", url: "http://localhost:3000/posts"})
					.success(function(data, status){
						additionalPosts = data;
						console.log(additionalPosts);

					for(var i = 0; i < additionalPosts.length; i++){
						var relevantThreadIndex = getThreadIndexFromID(additionalPosts[i].threadID);
						$scope.forum.threads[relevantThreadIndex].posts.push(additionalPosts[i]);
					}
				})
				.error(function(data, status){
					additionalPosts = data || "Request failed";
					console.log(additionalPosts);
				});
			});

		};

		$scope.fetch();

		$scope.currentThread = {};
		$scope.currentThreadOn = false;

		$scope.setThread = function(thread){
			$scope.currentThread = thread;
			$scope.currentThreadOn = true;
		}

		$scope.backToForum = function(){
			$scope.currentThreadOn = false;
		}

		$scope.addPost = function(thread){
			if($scope.currentUser == "" || $scope.currentUser == null){
				$scope.currentUser = "Guest";
			}

			var postObject = {user: $scope.currentUser, message: $scope.newPost, time: new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')};

			$scope.currentThread.posts.push(postObject);

			var stringifiedPost = JSON.stringify(postObject);
			$http({method: "POST", url: "http://localhost:3000/posts", data: stringifiedPost})

			$scope.newPost = "";
		}

		$scope.addThread = function(){
			if($scope.currentUser == "" || $scope.currentUser == null){
				$scope.currentUser = "Guest";
			}
			$scope.forum.threads.push({
				subject: $scope.newSubject,
				posts: [{user: $scope.currentUser, message: $scope.newPost, time: new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')}]
			});

			$scope.newSubject = "";
			$scope.newPost = "";
		}

		$scope.currentUser = "";
		$scope.newPost = "";
		$scope.newSubject = "";
		$scope.predicate = '';
	});
<commit_msg>Update forum.js<commit_after>//todo write angular scripts for developer page.

var developerKingdomModule = angular.module('app', []).
	controller("forumCtrl", function forumCtrl($scope, $window, $http){

		$scope.forum = {
			threads: [{subject: "blah blah blah", id: "1",  posts: []},
				{subject: "how to add your own functions", posts: []}
			]
		};

		var getThreadIndexFromID = function(id){
			for(var i = 0; i < $scope.forum.threads.length; i++){
				if($scope.forum.threads[i].id == id){
					return i;
				}
			}
		}

		$scope.fetch = function(){
			var additionalThreads = [];

			$http({method: "GET", url: "http://localhost:3000/threads"}).success(function(data, status){

				$scope.$apply(
					additionalThreads = data;
					for(var i = 0; i < additionalThreads; i++){
						$scope.forum.threads.push(additionalThreads[i]);
					}
				);

				var additionalPosts = [];
				$http({method: "GET", url: "http://localhost:3000/posts"})
					.success(function(data, status){
						additionalPosts = data;
						console.log(additionalPosts);

					for(var i = 0; i < additionalPosts.length; i++){
						var relevantThreadIndex = getThreadIndexFromID(additionalPosts[i].threadID);
						$scope.forum.threads[relevantThreadIndex].posts.push(additionalPosts[i]);
					}
				})
				.error(function(data, status){
					additionalPosts = data || "Request failed";
					console.log(additionalPosts);
				});
			});

		};

		$scope.fetch();

		$scope.currentThread = {};
		$scope.currentThreadOn = false;

		$scope.setThread = function(thread){
			$scope.currentThread = thread;
			$scope.currentThreadOn = true;
		}

		$scope.backToForum = function(){
			$scope.currentThreadOn = false;
		}

		$scope.addPost = function(thread){
			if($scope.currentUser == "" || $scope.currentUser == null){
				$scope.currentUser = "Guest";
			}

			var postObject = {user: $scope.currentUser, message: $scope.newPost, time: new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')};

			$scope.currentThread.posts.push(postObject);

			var stringifiedPost = JSON.stringify(postObject);
			$http({method: "POST", url: "http://localhost:3000/posts", data: stringifiedPost})

			$scope.newPost = "";
		}

		$scope.addThread = function(){
			if($scope.currentUser == "" || $scope.currentUser == null){
				$scope.currentUser = "Guest";
			}
			$scope.forum.threads.push({
				subject: $scope.newSubject,
				posts: [{user: $scope.currentUser, message: $scope.newPost, time: new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')}]
			});

			$scope.newSubject = "";
			$scope.newPost = "";
		}

		$scope.currentUser = "";
		$scope.newPost = "";
		$scope.newSubject = "";
		$scope.predicate = '';
	});
<|endoftext|>


<commit_before>/**
 * @author sarkiroka on 2016.05.08.
 */
var acnsy = require('../../index_v2');
var addToResultFactory = require('./helper/add-to-result-factory');
describe('simple serial functionality', function () {
	it('can add two number in async', function (done) {
		var params = {a: 1, b: 2, result: 0};
		var timeA = 100;
		var timeB = 150;
		var addA = addToResultFactory(timeA, 'a');
		var addB = addToResultFactory(timeB, 'b');
		var tasks = [addA, addB];
		var startTime = Date.now();

		acnsy(params, tasks, function (err, givenParams) {
			var endTime = Date.now();
			expect(err).toBeFalsy('shouldn\'t pass any error');
			expect(givenParams.result).toEqual(params.a + params.b, 'should calculate correctly');
			var timeDiff = endTime - startTime;
			expect(timeDiff).not.toBeLessThan(timeA + timeB, 'when the exectution is serial, the all time should not be less than sum of each task times');
			done();
		})
	});
});
<commit_msg>idődilettáció beépítése a tesztbe<commit_after>/**
 * @author sarkiroka on 2016.05.08.
 */
var acnsy = require('../../index_v2');
var addToResultFactory = require('./helper/add-to-result-factory');
describe('simple serial functionality', function () {
	it('can add two number in async', function (done) {
		var params = {a: 1, b: 2, result: 0};
		var timeA = 100;
		var timeB = 150;
		var addA = addToResultFactory(timeA, 'a');
		var addB = addToResultFactory(timeB, 'b');
		var tasks = [addA, addB];
		var startTime = Date.now();

		acnsy(params, tasks, function (err, givenParams) {
			var endTime = Date.now();
			expect(err).toBeFalsy('shouldn\'t pass any error');
			expect(givenParams.result).toEqual(params.a + params.b, 'should calculate correctly');
			var timeDiff = endTime - startTime + 1;
			expect(timeDiff).not.toBeLessThan(timeA + timeB, 'when the exectution is serial, the all time should not be less than sum of each task times');
			done();
		})
	});
});
<|endoftext|>


<commit_before>'use strict';

(function (angular) {
    angular
        .module('geoFenceWidget')
        .controller('WidgetHomeCtrl', ['$scope', '$timeout', 'COLLECTIONS', 'DB', 'Buildfire',
            function ($scope, $timeout, COLLECTIONS, DB, Buildfire) {
                var WidgetHome = this;
                var _skip = 0, _limit = 50, searchOptions, GeoActions, GeoItems = [], GeoInfo, info;
                GeoActions = new DB(COLLECTIONS.GeoActions);

                console.log('WidgetHomeCtrl loaded');

                searchOptions = {
                    filter: {"$json.title": {"$regex": '/*'}},
                    skip: _skip,
                    limit: _limit + 1 // the plus one is to check if there are any more
                };

                GeoInfo = new DB(COLLECTIONS.GeoInfo);
                GeoInfo.get().then(function (data) {
                    console.log('Got Info in Widget------------', data);
                    info = data;
                }, function (err) {
                    info = null;
                    console.error('Got Error while getting geoInfo------', err);
                });

                GeoActions.find(searchOptions).then(function (result) {
                    console.log('Item got based on the search------------------Widget Section-------', result);
                    GeoItems = result;
                    watcherFun();
                }, function (err) {
                    watcherFun();
                    console.error('Error while getting searched items---------------', err);
                });

                function distance(lat1, lon1, lat2, lon2, unit) {
                    var radlat1 = Math.PI * lat1 / 180;
                    var radlat2 = Math.PI * lat2 / 180;
                    var theta = lon1 - lon2;
                    var radtheta = Math.PI * theta / 180;
                    var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
                    dist = Math.acos(dist);
                    dist = dist * 180 / Math.PI;
                    dist = dist * 60 * 1.1515;
                    if (unit == "K") {
                        dist = dist * 1.609344
                    }
                    if (unit == "N") {
                        dist = dist * 0.8684
                    }
                    return dist;
                }

                function trigerAction(lat, lng) {
                    GeoItems.forEach(function (item) {
                        var dis;
                        if (item.data && item.data.epicenter && item.data.epicenter.coordinates && item.data.epicenter.coordinates.lng && item.data.epicenter.coordinates.lat) {
                            dis = distance(lat, lng, item.data.epicenter.coordinates.lat, item.data.epicenter.coordinates.lng, 'N');
                            console.log('Distance---------------------', dis, 'Item-------------------------------', item);
                            if (dis < item.data.radius && !item.actionPerformed) {
                                item.actionPerformed = true;
                                Buildfire.actionItems.execute(item.data.actionToPerform);
                            }
                        }
                    })
                }

                function watcherFun() {
                    Buildfire.geo.watchPosition(
                        //{timeout:3000},
                        {enableHighAccuracy: (info && info.data && info.data.highAccuracy) || false, timeout: 30000},
                        function (position, err) {
                            //clearWatcher(position.watchId);
                            if (err)
                                alert("GEO ERROR------------------->"err);
                            else {
                                //alert('Watcher Called-----------' + position.watchId + ' location----' + position.coords.latitude + ',' + position.coords.longitude + ' accuracy:' + info.data.highAccuracy);
                                console.info('Watching Position------watchId:::', position.watchId, position,' accuracy:' + info.data.highAccuracy ,info);
                                if (position && position.coords && position.coords.latitude && position.coords.longitude) {
                                    trigerAction(position.coords.latitude, position.coords.longitude);
                                }
                            }
                        });
                }

                function clearWatcher(watchId) {
                    Buildfire.geo.clearWatch(watchId, function (err, data) {
                        if(err)
                            alert(err);
                        console.info('Watcher has been cleared-----GEO ERROR , DATA', err, data);
                        watcherFun();
                    })
                }

               /* Buildfire.datastore.onUpdate(function (event) {
                    console.log('OnUpdate Called----------------', event);
                    switch (event.tag) {
                        case COLLECTIONS.GeoInfo:
                            info=event;
                            break;
                        case COLLECTIONS.GeoActions:
                    }
                });
*/
            }]);
})(window.angular);<commit_msg>alert applied to see if geo error issue of braces<commit_after>'use strict';

(function (angular) {
    angular
        .module('geoFenceWidget')
        .controller('WidgetHomeCtrl', ['$scope', '$timeout', 'COLLECTIONS', 'DB', 'Buildfire',
            function ($scope, $timeout, COLLECTIONS, DB, Buildfire) {
                var WidgetHome = this;
                var _skip = 0, _limit = 50, searchOptions, GeoActions, GeoItems = [], GeoInfo, info;
                GeoActions = new DB(COLLECTIONS.GeoActions);

                console.log('WidgetHomeCtrl loaded');

                searchOptions = {
                    filter: {"$json.title": {"$regex": '/*'}},
                    skip: _skip,
                    limit: _limit + 1 // the plus one is to check if there are any more
                };

                GeoInfo = new DB(COLLECTIONS.GeoInfo);
                GeoInfo.get().then(function (data) {
                    console.log('Got Info in Widget------------', data);
                    info = data;
                }, function (err) {
                    info = null;
                    console.error('Got Error while getting geoInfo------', err);
                });

                GeoActions.find(searchOptions).then(function (result) {
                    console.log('Item got based on the search------------------Widget Section-------', result);
                    GeoItems = result;
                    watcherFun();
                }, function (err) {
                    watcherFun();
                    console.error('Error while getting searched items---------------', err);
                });

                function distance(lat1, lon1, lat2, lon2, unit) {
                    var radlat1 = Math.PI * lat1 / 180;
                    var radlat2 = Math.PI * lat2 / 180;
                    var theta = lon1 - lon2;
                    var radtheta = Math.PI * theta / 180;
                    var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
                    dist = Math.acos(dist);
                    dist = dist * 180 / Math.PI;
                    dist = dist * 60 * 1.1515;
                    if (unit == "K") {
                        dist = dist * 1.609344
                    }
                    if (unit == "N") {
                        dist = dist * 0.8684
                    }
                    return dist;
                }

                function trigerAction(lat, lng) {
                    GeoItems.forEach(function (item) {
                        var dis;
                        if (item.data && item.data.epicenter && item.data.epicenter.coordinates && item.data.epicenter.coordinates.lng && item.data.epicenter.coordinates.lat) {
                            dis = distance(lat, lng, item.data.epicenter.coordinates.lat, item.data.epicenter.coordinates.lng, 'N');
                            console.log('Distance---------------------', dis, 'Item-------------------------------', item);
                            if (dis < item.data.radius && !item.actionPerformed) {
                                item.actionPerformed = true;
                                Buildfire.actionItems.execute(item.data.actionToPerform);
                            }
                        }
                    })
                }

                function watcherFun() {
                    Buildfire.geo.watchPosition(
                        //{timeout:3000},
                        {enableHighAccuracy: (info && info.data && info.data.highAccuracy) || false, timeout: 30000},
                        function (position, err) {
                            //clearWatcher(position.watchId);
                            if (err)
                                alert("GEO ERROR------------------->",err);
                            else {
                                //alert('Watcher Called-----------' + position.watchId + ' location----' + position.coords.latitude + ',' + position.coords.longitude + ' accuracy:' + info.data.highAccuracy);
                                console.info('Watching Position------watchId:::', position.watchId, position,' accuracy:' + info.data.highAccuracy ,info);
                                if (position && position.coords && position.coords.latitude && position.coords.longitude) {
                                    trigerAction(position.coords.latitude, position.coords.longitude);
                                }
                            }
                        });
                }

                function clearWatcher(watchId) {
                    Buildfire.geo.clearWatch(watchId, function (err, data) {
                        if(err)
                            alert(err);
                        console.info('Watcher has been cleared-----GEO ERROR , DATA', err, data);
                        watcherFun();
                    })
                }

               /* Buildfire.datastore.onUpdate(function (event) {
                    console.log('OnUpdate Called----------------', event);
                    switch (event.tag) {
                        case COLLECTIONS.GeoInfo:
                            info=event;
                            break;
                        case COLLECTIONS.GeoActions:
                    }
                });
*/
            }]);
})(window.angular);<|endoftext|>


<commit_before>'use strict';

var Drone = require('../');
var noble = require('noble');
var knownDevices = [];

if (this.ble.state === 'poweredOn') {
  start()
} else {
  noble.on('stateChange', start);
}

function start () {
  noble.startScanning();

  noble.on('discover', function(peripheral) {
    if (!Drone.isDronePeripheral(peripheral)) {
      return; // not a rolling spider
    }

    var details = {
      name: peripheral.advertisement.localName,
      uuid: peripheral.uuid,
      rssi: peripheral.rssi
    };

    knownDevices.push(details);
    console.log(knownDevices.length + ': ' + details.name + ' (' + details.uuid + '), RSSI ' + details.rssi);
  });
}
<commit_msg>Modify to make this file work as is<commit_after>'use strict';

var Drone = require('rolling-spider');
var noble = require('noble');
var knownDevices = [];

if (noble.state === 'poweredOn') {
  start()
} else {
  noble.on('stateChange', start);
}

function start () {
  noble.startScanning();

  noble.on('discover', function(peripheral) {
    if (!Drone.isDronePeripheral(peripheral)) {
      return; // not a rolling spider
    }

    var details = {
      name: peripheral.advertisement.localName,
      uuid: peripheral.uuid,
      rssi: peripheral.rssi
    };

    knownDevices.push(details);
    console.log(knownDevices.length + ': ' + details.name + ' (' + details.uuid + '), RSSI ' + details.rssi);
  });
}
<|endoftext|>