<commit_before>/*
 * Copyright 2015 Anton Tananaev (anton.tananaev@gmail.com)
 *
 * 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.
 */

Ext.define('Traccar.controller.Root', {
    extend: 'Ext.app.Controller',

    requires: [
        'Traccar.LoginManager',
        'Traccar.view.login.Login',
        'Traccar.view.main.Main'
    ],

    onLaunch: function () {
        Traccar.LoginManager.server({
            scope: this,
            callback: 'onServer'
        });
    },

    onServer: function() {
        Traccar.LoginManager.session({
            scope: this,
            callback: 'onSession'
        });
    },

    onSession: function(success) {
        if (success) {
            this.loadApp();
        } else {
            this.login = Ext.create('Traccar.view.login.Login', {
                listeners: {
                    scope: this,
                    login: 'onLogin'
                }
            });
            this.login.show();
        }
    },

    onLogin: function() {
        this.login.close();
        this.loadApp();
    },

    loadApp: function() {
        Ext.getStore('Devices').load();
        Ext.create('Traccar.view.main.Main');
    }

});
<commit_msg>Empty body after login<commit_after>/*
 * Copyright 2015 Anton Tananaev (anton.tananaev@gmail.com)
 *
 * 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.
 */

Ext.define('Traccar.controller.Root', {
    extend: 'Ext.app.Controller',

    requires: [
        'Traccar.LoginManager',
        'Traccar.view.login.Login',
        'Traccar.view.main.Main'
    ],

    onLaunch: function () {
        Traccar.LoginManager.server({
            scope: this,
            callback: 'onServer'
        });
    },

    onServer: function() {
        Traccar.LoginManager.session({
            scope: this,
            callback: 'onSession'
        });
    },

    onSession: function(success) {
        if (success) {
            this.loadApp();
        } else {
            this.login = Ext.create('Traccar.view.login.Login', {
                listeners: {
                    scope: this,
                    login: 'onLogin'
                }
            });
            this.login.show();
        }
    },

    onLogin: function() {
        this.login.close();
        this.loadApp();
    },

    loadApp: function() {
        Ext.getStore('Devices').load();
        Ext.getBody().empty();
        Ext.create('Traccar.view.main.Main');
    }

});
<|endoftext|>


<commit_before>define(["sprd/manager/IBasketManager", "flow", "sprd/model/Basket", "xaml!sprd/data/SprdApiDataSource",
        "js/data/LocalStorage", "js/data/Entity", "rAppid", "underscore"],
    function (IBasketManager, flow, Basket, SprdApiDataSource, LocalStorage, Entity, rAppid, _) {

        /***
         * @summary A BasketManager to interact with the Spreadshirt Basket API
         *
         * @see http://developer.spreadshirt.net/display/API/Basket+Resources
         */
        return IBasketManager.inherit('sprd.manager.ApiBasketManager', {
            defaults: {
                /***
                 * the basket model
                 * @type {sprd.model.Basket}
                 */
                basket: null,

                /***
                 * the id of the api basket which should try to be loaded.
                 * If the id isn't set the id is retrieved from the local storage or generated by the api
                 * after the basket has been created successfully. The id is written back to this property.
                 */
                apiBasketId: null,

                /***
                 * the shop used for creating a new basket
                 * @type {sprd.model.Shop}
                 */
                shop: null,

                /***
                 * the origin id used for basked items
                 * @type {Number|String}
                 */
                originId: null,

                /***
                 * a flag that indicates if the basket is updating
                 */
                updating: false,

                initBasketWithNoCache: true,

                /**
                 * if set, the element which is added will be saved under this basket item
                 */
                basketItem: null,
                /**
                 * a flag to trigger opossum synchronisation
                 */
                syncToOpossum: false
            },

            events: [
            /***
             * the basketChanged event is dispatched after the basket has been modified e.g. added, removed or updated an
             * BasketItem
             */
                "on:basketChanged",
                "on:basketUpdated",
                "on:basketUpdating",
                "on:basketSaving",
                "on:basketInitialized",
                "on:couponApplied",
                "on:couponRemoved",
                "on:couponsLoaded"
            ],

            inject: {
                api: SprdApiDataSource,
                localStorage: LocalStorage
            },

            ctor: function () {
                this.callBase();

                this.bind("on:basketUpdated", function () {
                    this.set("updating", false);
                }, this);

                this.bind("on:basketUpdating", function () {
                    this.set("updating", true);
                }, this);

            },

            _commitBasket: function (basket) {

                if (basket) {
                    basket = basket.clone();
                }

                // remember a clone
                this.$originalBasket = basket;
            },

            /**
             * Adds an element to the basket without saving it
             * @param element
             * @param quantity
             * @param callback
             */
            addElementToBasket: function (element, quantity, callback) {
                if (this.$.basket) {

                    this.fixBasketCurrency();

                    var basketItem = this.$.basket.addElement(element, quantity);
                    element = basketItem.$.element;

                    var originId = this.$.originId;
                    if (originId) {
                        basketItem.set('origin', new Entity({
                            id: originId
                        }));
                    }

                    this.extendElementWithLinks(element);
                }

                callback && callback();
            },

            fixBasketCurrency: function() {
                var basket = this.$.basket,
                    shop = this.$.shop;

                if (shop && basket && basket.get("basketItems.$items.length") == 0) {
                    basket.set({
                        currency: shop.$.currency
                    });
                }
            },

            /**
             * Updates the given basket item
             *
             * @param {sprd.model.BasketItem} basketItem
             * @param {sprd.model.ConcreteElement} element
             * @param {Number} quantity
             * @param {Function} cb
             */
            updateBasketItem: function (basketItem, element, quantity, cb) {
                this.extendElementWithLinks(element);

                basketItem.set({
                    element: element,
                    quantity: quantity
                });

                basketItem.save(null, cb);
            },

            waitForCouponApply: function (callback) {
                function couponAppliedCallback() {
                    this.unbind('on:couponApplied', couponAppliedCallback, this);
                    callback && callback();
                }

                if (this.$applyingCoupon) {
                    this.bind('on:couponApplied', couponAppliedCallback, this);
                } else {
                    callback();
                }
            },
            applyCoupon: function (coupon, locale, cb) {
                if (!this.$applyingCoupon) {
                    this.$applyingCoupon = true;
                    coupon.set('currency', this.get('basket.currency'));
                    var self = this;
                    coupon.validate({
                        locale: locale
                    }, function (err) {
                        if (coupon.isValid()) {
                            self.reloadBasket();
                        }
                        self.trigger('on:couponApplied', coupon, self);
                        self.$applyingCoupon = false;
                        cb && cb(err, coupon);
                    })
                }
            },

            removeCoupon: function (coupon, cb) {
                var self = this;
                coupon.remove(null, function () {
                    self.reloadBasket();
                    cb && cb();
                });
            },

            _triggerBasketSaving: function () {
                this.trigger("on:basketSaving", this.$.basket, this);
            },

            _triggerBasketChanged: function () {
                this.trigger("on:basketChanged", this.$.basket, this);
            },

            _triggerBasketUpdated: function () {
                this.trigger("on:basketUpdated", this.$.basket, this);
            },

            _triggerBasketUpdating: function () {
                this.trigger("on:basketUpdating", this.$.basket, this);
            },

            _initBasket: function (options, callback) {

                var api = this.$.api,
                    localStorage = this.$.localStorage,
                    basketId = this.$.apiBasketId,
                    basket,
                    self = this;

                if (!callback && options instanceof Function) {
                    callback = options;
                }

                options = options || {};
                basketId = basketId || localStorage.getItem("basketId");

                basket = api.createEntity(Basket, basketId);

                this.set({
                    basket: basket,
                    apiBasketId: basketId
                });

                var basketSaveCallback = function (err) {
                    if (!err) {
                        self.set("apiBasketId", basketId);

                        // try to save basket id to local storage
                        // this will fail in private browsing mode, but we can ignore this

                        try {
                            self.$.localStorage.setItem("basketId", basket.$.id);
                        } catch (e) {
                            // ignore this
                        }

                        try {
                            self._triggerBasketChanged();
                            self.fetchBasketDiscounts(callback);
                        } catch (e) {
                            callback && callback(e);
                            return;
                        }

                        self.trigger("on:basketInitialized", basket, self);

                        callback && callback();

                    } else {
                        console.warn(err);
                        callback && callback(err);
                    }

                };

                if (basket.isNew()) {

                    basket.set({
                        shop: this.$.shop,
                        currency: this.get("shop.currency")
                    });

                    basket.save(null, basketSaveCallback);
                } else {
                    flow()
                        .seq(function (cb) {
                            basket.fetch({
                                noCache: self.$.initBasketWithNoCache,
                                fetchSubModels: ["currency"]
                            }, cb);
                        })
                        .seq(function (cb) {
                            self.fetchBasketDiscounts(cb);
                        })
                        .seq(function (cb) {

                            if (options.lazyLoad) {
                                self.fetchBasketCoupons();
                                cb();
                            } else {
                                self.fetchBasketCoupons(cb);
                            }
                        })
                        .exec(function (err) {
                            if (err) {
                                // something went wrong
                                basket.set('id', undefined);
                                basket.save(null, basketSaveCallback);
                                console.warn(err);
                            } else {

                                self.set("shop", basket.$.shop);

                                flow()
                                    .parEach(basket.$.basketItems.toArray(), function (item, cb) {
                                        flow()
                                            .seq(function (cb) {
                                                item.$.element.init(cb);
                                            })
                                            .seq("product", function (cb) {
                                                item.$.element.getProduct().fetch({
                                                    fetchSubModels: ["productType"]
                                                }, cb);
                                            })
                                            .exec(function (err) {
                                                if (err) {
                                                    basket.$.basketItems.remove(item);
                                                }

                                                cb();
                                            });
                                    })
                                    .exec(function (err) {
                                        if (!err) {
                                            self.$originalBasket = basket.clone();
                                            self.trigger("on:basketInitialized", basket, self);
                                        }

                                        callback && callback(err, basket);
                                    });
                            }
                        });
                }
            },

            fetchBasketDiscounts: function (cb) {
                var basket = this.$.basket;
                if (basket.$.discounts && basket.$.discounts.size()) {
                    var discount = basket.$.discounts.at(0);
                    if (discount && discount.$.discountScale) {
                        discount.$.discountScale.fetch(null, cb);
                    } else {
                        cb();
                    }
                } else {
                    cb();
                }
            },

            fetchBasketCoupons: function (cb) {
                var basket = this.$.basket,
                    self   = this;
                if (basket && basket.schema.coupons) {
                    var coupons = basket.getCollection("coupons");
                    coupons.invalidatePageCache();
                    coupons.fetch(function(err) {
                        self.trigger("on:couponsLoaded");
                        cb && cb(err)
                    });
                } else {
                    cb && cb();
                }
            },

            /**
             *
             * @param {sprd.model.BasketItem} basketItem
             */
            saveBasketItem: function (basketItem) {
                var self = this;
                this.$itemSaveTimeout && clearTimeout(this.$itemSaveTimeout);

                this.$itemSaveTimeout = setTimeout(function () {
                    basketItem.save(null, function () {
                        self.$.basket.fetch({noCache: true});
                    });
                    self._triggerBasketChanged();
                }, 300);
            },

            /**
             *
             * @param {sprd.model.BasketItem} basketItem
             */
            removeBasketItem: function (basketItem) {
                this.$.basket.$.basketItems.remove(basketItem);
                this.saveBasketDebounced();
            },

            saveBasketDebounced: function (cb) {

                var self = this;

                this._triggerBasketUpdating();
                this._debounceFunctionCall(function () {
                    cb && cb();
                    this.saveBasket(function (err) {
                        if (err) {
                            // couldn't save basket, restore clone
                            if (self.$originalBasket) {
                                self.$originalBasket.sync();
                            }
                        } else {
                            // success create a new copy of it
                            self.$originalBasket = self.$.basket.clone();
                        }
                    });

                }, "saveBasketCall", 700, this, [], "DELAY");
            },

            getBasketDiscountCount: function(basket) {

                if (basket.$.discounts) {
                    return _.filter(basket.$.discounts.$items, function(d) {
                        return d.$.type != "scale";
                    }).length;
                }

                return null;
            },

            saveBasket: function (callback) {
                if (!this.$savingBasket) {
                    this._triggerBasketUpdating();
                    this._triggerBasketSaving();
                    this.$savingBasket = true;
                    this.$callSaveBasketAgain = false;
                    this.$saveCallbacks = this.$saveCallbacks || [];
                    if (callback) {
                        this.$saveCallbacks.push(callback);
                    }
                    var self = this,
                        basket = this.$.basket;

                    function callCallbacks(err, basket) {
                        var cb;
                        while (self.$saveCallbacks && self.$saveCallbacks.length) {
                            cb = self.$saveCallbacks.shift();
                            cb && cb(err, basket);
                        }
                    }

                    var discountsBeforeRefresh = this.getBasketDiscountCount(basket);

                    flow()
                        .seq(function (cb) {
                            basket.save(null, cb);
                        })
                        .seq(function (cb) {
                            if (self.$.syncToOpossum) {
                                // TODO: remove this shit after new checkout is live everywhere
                                rAppid.ajax("/syncBasket", {
                                    "method": "GET",
                                    "queryParameter": {
                                        basketId: basket.$.id
                                    }
                                }, function () {
                                    cb();
                                });
                            } else {
                                cb();
                            }
                        })
                        .seq(function () {
                            self._triggerBasketChanged();
                        })
                        .seq(function (cb) {
                            self.fetchBasketDiscounts(cb);
                        })
                        .seq(function(cb) {
                            if (discountsBeforeRefresh != null && self.getBasketDiscountCount(basket) != discountsBeforeRefresh) {

                                var couponCount = basket.get("coupons.size()");

                                self.fetchBasketCoupons(function(err) {
                                    if (basket.get("coupons.size()") < couponCount) {
                                        self.trigger("on:couponRemoved");
                                    }

                                    cb(err);
                                });
                            } else {
                                cb();
                            }
                        })
                        .exec(function (err) {
                            if (self.$basketChanged) {
                                self.$basketChanged = false;
                                self.$savingBasket = false;
                                self.saveBasket();
                            } else {

                                self.fixBasketCurrency();

                                callCallbacks(err, basket);
                                self.$savingBasket = false;
                                self._triggerBasketUpdated();
                            }
                        });
                } else {
                    if (callback) {
                        this.$saveCallbacks.push(callback);
                    }

                    this.$basketChanged = true;
                }
            },
            reloadBasket: function (callback) {
                this._triggerBasketUpdating();
                var self = this,
                    basket = this.$.basket;
                var couponCount;

                flow()
                    .seq(function (cb) {
                        basket.fetch({noCache: true}, cb);
                    })
                    .seq(function (cb) {
                        couponCount = basket.get("coupons.size()");
                        self.fetchBasketCoupons(cb);
                    })
                    .seq(function(){
                        if (basket.get("coupons.size()") < couponCount) {
                            self.trigger("on:couponRemoved");
                        }
                    })
                    .exec(function (err, basket) {
                        self._triggerBasketUpdated();
                        callback && callback(err, basket)
                    })
            }
        });

    });<commit_msg>[DEV-131280] - Wrong wording when removing a coupon<commit_after>define(["sprd/manager/IBasketManager", "flow", "sprd/model/Basket", "xaml!sprd/data/SprdApiDataSource",
        "js/data/LocalStorage", "js/data/Entity", "rAppid", "underscore"],
    function (IBasketManager, flow, Basket, SprdApiDataSource, LocalStorage, Entity, rAppid, _) {

        /***
         * @summary A BasketManager to interact with the Spreadshirt Basket API
         *
         * @see http://developer.spreadshirt.net/display/API/Basket+Resources
         */
        return IBasketManager.inherit('sprd.manager.ApiBasketManager', {
            defaults: {
                /***
                 * the basket model
                 * @type {sprd.model.Basket}
                 */
                basket: null,

                /***
                 * the id of the api basket which should try to be loaded.
                 * If the id isn't set the id is retrieved from the local storage or generated by the api
                 * after the basket has been created successfully. The id is written back to this property.
                 */
                apiBasketId: null,

                /***
                 * the shop used for creating a new basket
                 * @type {sprd.model.Shop}
                 */
                shop: null,

                /***
                 * the origin id used for basked items
                 * @type {Number|String}
                 */
                originId: null,

                /***
                 * a flag that indicates if the basket is updating
                 */
                updating: false,

                initBasketWithNoCache: true,

                /**
                 * if set, the element which is added will be saved under this basket item
                 */
                basketItem: null,
                /**
                 * a flag to trigger opossum synchronisation
                 */
                syncToOpossum: false
            },

            events: [
            /***
             * the basketChanged event is dispatched after the basket has been modified e.g. added, removed or updated an
             * BasketItem
             */
                "on:basketChanged",
                "on:basketUpdated",
                "on:basketUpdating",
                "on:basketSaving",
                "on:basketInitialized",
                "on:couponApplied",
                "on:couponRemoved",
                "on:couponManualRemoved",
                "on:couponsLoaded"
            ],

            inject: {
                api: SprdApiDataSource,
                localStorage: LocalStorage
            },

            ctor: function () {
                this.callBase();

                this.bind("on:basketUpdated", function () {
                    this.set("updating", false);
                }, this);

                this.bind("on:basketUpdating", function () {
                    this.set("updating", true);
                }, this);

            },

            _commitBasket: function (basket) {

                if (basket) {
                    basket = basket.clone();
                }

                // remember a clone
                this.$originalBasket = basket;
            },

            /**
             * Adds an element to the basket without saving it
             * @param element
             * @param quantity
             * @param callback
             */
            addElementToBasket: function (element, quantity, callback) {
                if (this.$.basket) {

                    this.fixBasketCurrency();

                    var basketItem = this.$.basket.addElement(element, quantity);
                    element = basketItem.$.element;

                    var originId = this.$.originId;
                    if (originId) {
                        basketItem.set('origin', new Entity({
                            id: originId
                        }));
                    }

                    this.extendElementWithLinks(element);
                }

                callback && callback();
            },

            fixBasketCurrency: function() {
                var basket = this.$.basket,
                    shop = this.$.shop;

                if (shop && basket && basket.get("basketItems.$items.length") == 0) {
                    basket.set({
                        currency: shop.$.currency
                    });
                }
            },

            /**
             * Updates the given basket item
             *
             * @param {sprd.model.BasketItem} basketItem
             * @param {sprd.model.ConcreteElement} element
             * @param {Number} quantity
             * @param {Function} cb
             */
            updateBasketItem: function (basketItem, element, quantity, cb) {
                this.extendElementWithLinks(element);

                basketItem.set({
                    element: element,
                    quantity: quantity
                });

                basketItem.save(null, cb);
            },

            waitForCouponApply: function (callback) {
                function couponAppliedCallback() {
                    this.unbind('on:couponApplied', couponAppliedCallback, this);
                    callback && callback();
                }

                if (this.$applyingCoupon) {
                    this.bind('on:couponApplied', couponAppliedCallback, this);
                } else {
                    callback();
                }
            },
            applyCoupon: function (coupon, locale, cb) {
                if (!this.$applyingCoupon) {
                    this.$applyingCoupon = true;
                    coupon.set('currency', this.get('basket.currency'));
                    var self = this;
                    coupon.validate({
                        locale: locale
                    }, function (err) {
                        if (coupon.isValid()) {
                            self.reloadBasket();
                        }
                        self.trigger('on:couponApplied', coupon, self);
                        self.$applyingCoupon = false;
                        cb && cb(err, coupon);
                    })
                }
            },

            removeCoupon: function (coupon, cb) {
                var self = this;
                coupon.remove(null, function () {
                    self.reloadBasket({
                        couponRemovedEvent: "on:couponManualRemoved"
                    });
                    cb && cb();
                });
            },

            _triggerBasketSaving: function () {
                this.trigger("on:basketSaving", this.$.basket, this);
            },

            _triggerBasketChanged: function () {
                this.trigger("on:basketChanged", this.$.basket, this);
            },

            _triggerBasketUpdated: function () {
                this.trigger("on:basketUpdated", this.$.basket, this);
            },

            _triggerBasketUpdating: function () {
                this.trigger("on:basketUpdating", this.$.basket, this);
            },

            _initBasket: function (options, callback) {

                var api = this.$.api,
                    localStorage = this.$.localStorage,
                    basketId = this.$.apiBasketId,
                    basket,
                    self = this;

                if (!callback && options instanceof Function) {
                    callback = options;
                }

                options = options || {};
                basketId = basketId || localStorage.getItem("basketId");

                basket = api.createEntity(Basket, basketId);

                this.set({
                    basket: basket,
                    apiBasketId: basketId
                });

                var basketSaveCallback = function (err) {
                    if (!err) {
                        self.set("apiBasketId", basketId);

                        // try to save basket id to local storage
                        // this will fail in private browsing mode, but we can ignore this

                        try {
                            self.$.localStorage.setItem("basketId", basket.$.id);
                        } catch (e) {
                            // ignore this
                        }

                        try {
                            self._triggerBasketChanged();
                            self.fetchBasketDiscounts(callback);
                        } catch (e) {
                            callback && callback(e);
                            return;
                        }

                        self.trigger("on:basketInitialized", basket, self);

                        callback && callback();

                    } else {
                        console.warn(err);
                        callback && callback(err);
                    }

                };

                if (basket.isNew()) {

                    basket.set({
                        shop: this.$.shop,
                        currency: this.get("shop.currency")
                    });

                    basket.save(null, basketSaveCallback);
                } else {
                    flow()
                        .seq(function (cb) {
                            basket.fetch({
                                noCache: self.$.initBasketWithNoCache,
                                fetchSubModels: ["currency"]
                            }, cb);
                        })
                        .seq(function (cb) {
                            self.fetchBasketDiscounts(cb);
                        })
                        .seq(function (cb) {

                            if (options.lazyLoad) {
                                self.fetchBasketCoupons();
                                cb();
                            } else {
                                self.fetchBasketCoupons(cb);
                            }
                        })
                        .exec(function (err) {
                            if (err) {
                                // something went wrong
                                basket.set('id', undefined);
                                basket.save(null, basketSaveCallback);
                                console.warn(err);
                            } else {

                                self.set("shop", basket.$.shop);

                                flow()
                                    .parEach(basket.$.basketItems.toArray(), function (item, cb) {
                                        flow()
                                            .seq(function (cb) {
                                                item.$.element.init(cb);
                                            })
                                            .seq("product", function (cb) {
                                                item.$.element.getProduct().fetch({
                                                    fetchSubModels: ["productType"]
                                                }, cb);
                                            })
                                            .exec(function (err) {
                                                if (err) {
                                                    basket.$.basketItems.remove(item);
                                                }

                                                cb();
                                            });
                                    })
                                    .exec(function (err) {
                                        if (!err) {
                                            self.$originalBasket = basket.clone();
                                            self.trigger("on:basketInitialized", basket, self);
                                        }

                                        callback && callback(err, basket);
                                    });
                            }
                        });
                }
            },

            fetchBasketDiscounts: function (cb) {
                var basket = this.$.basket;
                if (basket.$.discounts && basket.$.discounts.size()) {
                    var discount = basket.$.discounts.at(0);
                    if (discount && discount.$.discountScale) {
                        discount.$.discountScale.fetch(null, cb);
                    } else {
                        cb();
                    }
                } else {
                    cb();
                }
            },

            fetchBasketCoupons: function (cb) {
                var basket = this.$.basket,
                    self   = this;
                if (basket && basket.schema.coupons) {
                    var coupons = basket.getCollection("coupons");
                    coupons.invalidatePageCache();
                    coupons.fetch(function(err) {
                        self.trigger("on:couponsLoaded");
                        cb && cb(err)
                    });
                } else {
                    cb && cb();
                }
            },

            /**
             *
             * @param {sprd.model.BasketItem} basketItem
             */
            saveBasketItem: function (basketItem) {
                var self = this;
                this.$itemSaveTimeout && clearTimeout(this.$itemSaveTimeout);

                this.$itemSaveTimeout = setTimeout(function () {
                    basketItem.save(null, function () {
                        self.$.basket.fetch({noCache: true});
                    });
                    self._triggerBasketChanged();
                }, 300);
            },

            /**
             *
             * @param {sprd.model.BasketItem} basketItem
             */
            removeBasketItem: function (basketItem) {
                this.$.basket.$.basketItems.remove(basketItem);
                this.saveBasketDebounced();
            },

            saveBasketDebounced: function (cb) {

                var self = this;

                this._triggerBasketUpdating();
                this._debounceFunctionCall(function () {
                    cb && cb();
                    this.saveBasket(function (err) {
                        if (err) {
                            // couldn't save basket, restore clone
                            if (self.$originalBasket) {
                                self.$originalBasket.sync();
                            }
                        } else {
                            // success create a new copy of it
                            self.$originalBasket = self.$.basket.clone();
                        }
                    });

                }, "saveBasketCall", 700, this, [], "DELAY");
            },

            getBasketDiscountCount: function(basket) {

                if (basket.$.discounts) {
                    return _.filter(basket.$.discounts.$items, function(d) {
                        return d.$.type != "scale";
                    }).length;
                }

                return null;
            },

            saveBasket: function (callback) {
                if (!this.$savingBasket) {
                    this._triggerBasketUpdating();
                    this._triggerBasketSaving();
                    this.$savingBasket = true;
                    this.$callSaveBasketAgain = false;
                    this.$saveCallbacks = this.$saveCallbacks || [];
                    if (callback) {
                        this.$saveCallbacks.push(callback);
                    }
                    var self = this,
                        basket = this.$.basket;

                    function callCallbacks(err, basket) {
                        var cb;
                        while (self.$saveCallbacks && self.$saveCallbacks.length) {
                            cb = self.$saveCallbacks.shift();
                            cb && cb(err, basket);
                        }
                    }

                    var discountsBeforeRefresh = this.getBasketDiscountCount(basket);

                    flow()
                        .seq(function (cb) {
                            basket.save(null, cb);
                        })
                        .seq(function (cb) {
                            if (self.$.syncToOpossum) {
                                // TODO: remove this shit after new checkout is live everywhere
                                rAppid.ajax("/syncBasket", {
                                    "method": "GET",
                                    "queryParameter": {
                                        basketId: basket.$.id
                                    }
                                }, function () {
                                    cb();
                                });
                            } else {
                                cb();
                            }
                        })
                        .seq(function () {
                            self._triggerBasketChanged();
                        })
                        .seq(function (cb) {
                            self.fetchBasketDiscounts(cb);
                        })
                        .seq(function(cb) {
                            if (discountsBeforeRefresh != null && self.getBasketDiscountCount(basket) != discountsBeforeRefresh) {

                                var couponCount = basket.get("coupons.size()");

                                self.fetchBasketCoupons(function(err) {
                                    if (basket.get("coupons.size()") < couponCount) {
                                        self.trigger("on:couponRemoved");
                                    }

                                    cb(err);
                                });
                            } else {
                                cb();
                            }
                        })
                        .exec(function (err) {
                            if (self.$basketChanged) {
                                self.$basketChanged = false;
                                self.$savingBasket = false;
                                self.saveBasket();
                            } else {

                                self.fixBasketCurrency();

                                callCallbacks(err, basket);
                                self.$savingBasket = false;
                                self._triggerBasketUpdated();
                            }
                        });
                } else {
                    if (callback) {
                        this.$saveCallbacks.push(callback);
                    }

                    this.$basketChanged = true;
                }
            },

            /***
             *
             * @param options
             * @param callback
             */
            reloadBasket: function(options, callback) {

                if (options instanceof Function) {
                    callback = options;
                    options = undefined;
                }

                options = options || {};
                _.defaults(options, {
                    couponRemovedEvent: "on:couponRemoved"
                });

                this._triggerBasketUpdating();
                var self = this,
                    basket = this.$.basket;
                var couponCount;

                flow()
                    .seq(function (cb) {
                        basket.fetch({noCache: true}, cb);
                    })
                    .seq(function (cb) {
                        couponCount = basket.get("coupons.size()");
                        self.fetchBasketCoupons(cb);
                    })
                    .seq(function(){
                        if (basket.get("coupons.size()") < couponCount) {
                            self.trigger(options.couponRemovedEvent);
                        }
                    })
                    .exec(function (err, basket) {
                        self._triggerBasketUpdated();
                        callback && callback(err, basket)
                    })
            }
        });

    });<|endoftext|>


<commit_before>import React, { PropTypes as T } from "react";
import { Table, Grid, Icon } from "semantic-ui-react";

import NextLink from "next/link";

// Convert simple links to next style href + as
// TODO: Actually finish implementing this...
const Link = ({ to, children }) =>
  <NextLink href={to} as={to}>

      {children}

  </NextLink>;

const DirectoryListing = props => {
  const base = props.basepath || "/";
  return (
    <Grid>
      <Grid.Column>

            {props.contents.map((row, index) => {
              const fullPath = `${base}/${row.path}`;
              if (!row.type) {
                return null;
              }
              switch (row.type) {
                case "notebook":
                  return (

                        <Link to={fullPath}>
                          <Icon name="book" color="grey" />
                          {row.name}
                        </Link>

                  );
                case "directory":
                  return (

                        <Link to={fullPath}>
                          <Icon name="folder" color="blue" />
                          {row.name}
                        </Link>

                  );
                case "file":
                  return (

                        <Link to={fullPath}>
                          <Icon name="file" color="grey" />
                          {row.name}
                        </Link>

                  );
                default:
                  return null;
              }
            })}

      </Grid.Column>
    </Grid>
  );
};

DirectoryListing.propTypes = {
  contents: T.arrayOf(
    T.shape({ type: T.string, path: T.string, name: T.string })
  ),
  basepath: T.string
};

export default DirectoryListing;
<commit_msg>complete the internal implementation of Link<commit_after>import React, { PropTypes as T } from "react";
import { Table, Grid, Icon } from "semantic-ui-react";

import NextLink from "next/link";

// Convert simple links to next style href + as
// TODO: Actually finish implementing this...
const Link = ({ to, children, basepath }) =>
  <NextLink
    href={{ pathname: "/view", query: { viewPath: to } }}
    as={basepath + "/" + to}
  >

      {children}

  </NextLink>;

const DirectoryListing = props => {
  const base = props.basepath || "/";
  return (
    <Grid>
      <Grid.Column>

            {props.contents.map((row, index) => {
              if (!row.type) {
                return null;
              }
              switch (row.type) {
                case "notebook":
                  return (

                        <Link to={row.path} basepath={base}>
                          <Icon name="book" color="grey" />
                          {row.name}
                        </Link>

                  );
                case "directory":
                  return (

                        <Link to={row.path} basepath={base}>
                          <Icon name="folder" color="blue" />
                          {row.name}
                        </Link>

                  );
                case "file":
                  return (

                        <Link to={row.path} basepath={base}>
                          <Icon name="file" color="grey" />
                          {row.name}
                        </Link>

                  );
                default:
                  return null;
              }
            })}

      </Grid.Column>
    </Grid>
  );
};

DirectoryListing.propTypes = {
  contents: T.arrayOf(
    T.shape({ type: T.string, path: T.string, name: T.string })
  ),
  basepath: T.string
};

export default DirectoryListing;
<|endoftext|>


<commit_before>import Boom from 'boom';
import {
  dbGetTeacherLectures,
  dbGetExpertLectures,
  dbGetLectures,
  dbGetLecture,
  dbCreateLecture,
  dbUpdateLecture,
  dbDelLecture,
} from '../models/lectures';

export const getTeacherLectures = (request, reply) => dbGetTeacherLectures(request.pre.user.id).then(reply);
export const getExpertLectures = (request, reply) => dbGetExpertLectures(request.pre.user.id).then(reply);
export const getLectures = (request, reply) => dbGetLectures().then(reply);

export const getLecture = (request, reply) => dbGetLecture(request.params.lectureId).then(reply);
export const createLecture = async (request, reply) => {
  try {
    const lecture = await dbCreateLecture(
      request.pre.user.id,
      request.payload,
    );

    dbGetLecture(lecture.id).then(reply);
  } catch (e) {
    reply(Boom.badImplementation(e));
  }
};

export const updateLecture = async (request, reply) => {
  try {
    const lecture = await dbUpdateLecture(
      request.pre.user.id,
      request.params.lectureId,
      request.payload,
    );

    dbGetLecture(lecture.id).then(reply);
  } catch (e) {
    reply(Boom.badImplementation(e));
  }
};

export const delLecture = (request, reply) => dbDelLecture(request.pre.user.id, request.params.lectureId).then(reply);
<commit_msg>Admin check added when fetching all lecture data<commit_after>import Boom from 'boom';
import {
  dbGetTeacherLectures,
  dbGetExpertLectures,
  dbGetLectures,
  dbGetLecture,
  dbCreateLecture,
  dbUpdateLecture,
  dbDelLecture,
} from '../models/lectures';

export const getTeacherLectures = (request, reply) => dbGetTeacherLectures(request.pre.user.id).then(reply);
export const getExpertLectures = (request, reply) => dbGetExpertLectures(request.pre.user.id).then(reply);

export const getLectures = (request, reply) => {
  if (request.pre.user.scope !== 'admin') {
    return reply(Boom.unauthorized('Unprivileged user!'));
  }
  dbGetLectures().then(reply);
};

export const getLecture = (request, reply) => dbGetLecture(request.params.lectureId).then(reply);
export const createLecture = async (request, reply) => {
  try {
    const lecture = await dbCreateLecture(
      request.pre.user.id,
      request.payload,
    );

    dbGetLecture(lecture.id).then(reply);
  } catch (e) {
    reply(Boom.badImplementation(e));
  }
};

export const updateLecture = async (request, reply) => {
  try {
    const lecture = await dbUpdateLecture(
      request.pre.user.id,
      request.params.lectureId,
      request.payload,
    );

    dbGetLecture(lecture.id).then(reply);
  } catch (e) {
    reply(Boom.badImplementation(e));
  }
};

export const delLecture = (request, reply) => dbDelLecture(request.pre.user.id, request.params.lectureId).then(reply);
<|endoftext|>


<commit_before>module.exports = {
  normalizeEntityName: function() {}, // no-op since we're just adding dependencies

  afterInstall: function() {
    return this.addPackagesToProject([
      // TODO: remove this because it forces the consuming user to use app.scss
      { name: 'broccoli-sass' }

    ]).then(function() {
      return this.addBowerPackagesToProject([
        { name: 'moment' },
        { name: 'twix'}
      ])

    }.bind(this)).then(function() {
      return this.addAddonToProject('ember-cli-velocity')

    }.bind(this)).then(function() {
      return this.addAddonToProject('ember-cli-list-view')

    }.bind(this))
  }
};
<commit_msg>update package name of list-view in blueprint<commit_after>module.exports = {
  normalizeEntityName: function() {}, // no-op since we're just adding dependencies

  afterInstall: function() {
    return this.addPackagesToProject([
      // TODO: remove this because it forces the consuming user to use app.scss
      { name: 'broccoli-sass' }

    ]).then(function() {
      return this.addBowerPackagesToProject([
        { name: 'moment' },
        { name: 'twix'}
      ])

    }.bind(this)).then(function() {
      return this.addAddonToProject('ember-cli-velocity')

    }.bind(this)).then(function() {
      return this.addAddonToProject('ember-list-view')

    }.bind(this))
  }
};
<|endoftext|>


<commit_before>global.self = global

var WebSocketClient = require('websocket').client
var Paho = require('paho-mqtt')
require('dotenv').config()

global.WebSocket = function(wsurl, protocol) {
  var ws = new WebSocketClient()
  var connection
  var obj = {
    send: function(msg) {
      var nodeBuf = new Buffer(new Uint8Array(msg))
      connection.send(nodeBuf)
    },
    get readyState() {
      return ws.readyState;
    }
  };

  ws.binaryType = 'arraybuffer';

  ws.on("connect", function(conn) {
    connection = conn;
    conn.on("error", function(error) {
      console.log("socket error ", error);
      if (obj.onerror) {
        obj.onerror();
      }
    });

    conn.on("close", function(reasonCode, description) {
      console.log("socket closed ", description);
    })

    conn.on("message", function(message) {
      if (message.type === "binary") {
        if (obj.onmessage) {
          obj.onmessage({
            data: message.binaryData
          });
        }
      }
    });
    if (obj.onopen) {
      obj.onopen();
    }
  });
  ws.on('connectFailed', function(error) {
    console.log('Connect Error: ' + error.toString());
    if (obj.onerror) {
      obj.onerror(error);
    }
  });
  ws.connect(wsurl, protocol);
  return obj;
}

var LocalStorage = require('node-localstorage').LocalStorage
global.localStorage = new LocalStorage('./persistence')

var Paho = require('paho-mqtt')
global.Paho = Paho

function ensureValue(prop, value) {
  if (prop === null || prop === '') { // || prop[0] === '$') {
    return value
  }
  return prop
}

function guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1)
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
    s4() + '-' + s4() + s4() + s4()
}

function printConfig(settings) {
  console.log(' - Eclipse Paho Javascript Client Test Harness Settings - ')
  console.log('Server URI: ' + settings.server + ':' + settings.port + settings.path)
  console.log('MQTT Version: ' + settings.mqttVersion)
  console.log('Interop Server URI: ' + settings.interopServer + ':' + settings.interopPort + settings.interopPath)
}

module.exports = {
  server: ensureValue(process.env.TEST_SERVER, 'localhost'),
  port: parseInt(ensureValue(process.env.TEST_SERVER_PORT, '443')),
  path: ensureValue(process.env.TEST_SERVER_PATH, '/ws'),
  mqttVersion: parseInt(ensureValue(process.env.TEST_SERVER_MQTTVER, '3')),
  interopServer: ensureValue(process.env.TEST_INTEROPSERVER, 'localhost'),
  interopPort: parseInt(ensureValue(process.env.TEST_INTEROPPORT, '443')),
  interopPath: ensureValue(process.env.TEST_INTEROPPATH, '/ws'),
  useSSL: ensureValue((process.env.TEST_USE_SSL === 'true'), true),
  topicPrefix: 'paho-mqtt-test-' + guid(),
  Paho: Paho,
  printConfig: printConfig
}<commit_msg>More javascript and tests.<commit_after>global.self = global

var WebSocketClient = require('websocket').client
var Paho = require('paho-mqtt')
require('dotenv').config()

global.WebSocket = function(wsurl, protocol) {
  var ws = new WebSocketClient({tlsOptions: { rejectUnauthorized: false }})
  var connection
  var obj = {
    send: function(msg) {
      var nodeBuf = new Buffer(new Uint8Array(msg))
      connection.send(nodeBuf)
    },
    get readyState() {
      return ws.readyState;
    }
  };

  ws.binaryType = 'arraybuffer';

  ws.on("connect", function(conn) {
    connection = conn;
    conn.on("error", function(error) {
      console.log("socket error ", error);
      if (obj.onerror) {
        obj.onerror();
      }
    });

    conn.on("close", function(reasonCode, description) {
      console.log("socket closed ", description);
    })

    conn.on("message", function(message) {
      if (message.type === "binary") {
        if (obj.onmessage) {
          obj.onmessage({
            data: message.binaryData
          });
        }
      }
    });
    if (obj.onopen) {
      obj.onopen();
    }
  });
  ws.on('connectFailed', function(error) {
    console.log('Connect Error: ' + error.toString());
    if (obj.onerror) {
      obj.onerror(error);
    }
  });
  ws.connect(wsurl, protocol);
  return obj;
}

var LocalStorage = require('node-localstorage').LocalStorage
global.localStorage = new LocalStorage('./persistence')

var Paho = require('paho-mqtt')
global.Paho = Paho

function ensureValue(prop, value) {
  if (prop === null || prop === '') { // || prop[0] === '$') {
    return value
  }
  return prop
}

function guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1)
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
    s4() + '-' + s4() + s4() + s4()
}

function printConfig(settings) {
  console.log(' - Eclipse Paho Javascript Client Test Harness Settings - ')
  console.log('Server URI: ' + settings.server + ':' + settings.port + settings.path)
  console.log('MQTT Version: ' + settings.mqttVersion)
  console.log('Interop Server URI: ' + settings.interopServer + ':' + settings.interopPort + settings.interopPath)
}

module.exports = {
  server: ensureValue(process.env.TEST_SERVER, 'localhost'),
  port: parseInt(ensureValue(process.env.TEST_SERVER_PORT, '443')),
  path: ensureValue(process.env.TEST_SERVER_PATH, '/ws'),
  mqttVersion: parseInt(ensureValue(process.env.TEST_SERVER_MQTTVER, '3')),
  interopServer: ensureValue(process.env.TEST_INTEROPSERVER, 'localhost'),
  interopPort: parseInt(ensureValue(process.env.TEST_INTEROPPORT, '443')),
  interopPath: ensureValue(process.env.TEST_INTEROPPATH, '/ws'),
  useSSL: ensureValue((process.env.TEST_USE_SSL === 'true'), true),
  topicPrefix: 'paho-mqtt-test-' + guid(),
  Paho: Paho,
  printConfig: printConfig
}<|endoftext|>


<commit_before>import classNames from "classnames";
import mixin from "reactjs-mixin";
import { Tooltip } from "reactjs-components";
import { routerShape } from "react-router";
import PropTypes from "prop-types";
import React from "react";
import { withI18n } from "@lingui/react";
import { Trans, t } from "@lingui/macro";
import { Badge, Icon } from "@dcos/ui-kit";
import { SystemIcons } from "@dcos/ui-kit/dist/packages/icons/dist/system-icons-enum";
import { iconSizeXs } from "@dcos/ui-kit/dist/packages/design-tokens/build/js/designTokens";

import DCOSStore from "#SRC/js/stores/DCOSStore";
import DSLFilterField from "#SRC/js/components/DSLFilterField";

import FilterBar from "#SRC/js/components/FilterBar";
import FilterHeadline from "#SRC/js/components/FilterHeadline";
import SaveStateMixin from "#SRC/js/mixins/SaveStateMixin";
import StringUtil from "#SRC/js/utils/StringUtil";
import { isSDKService } from "#PLUGINS/services/src/js/utils/ServiceUtil";

import TaskStatusDSLSection from "../../components/dsl/TaskStatusDSLSection";
import TaskZoneDSLSection from "../../components/dsl/TaskZoneDSLSection";
import TaskRegionDSLSection from "../../components/dsl/TaskRegionDSLSection";
import FuzzyTextDSLSection from "../../components/dsl/FuzzyTextDSLSection";

import * as ServiceStatus from "../../constants/ServiceStatus";
import TaskMergeDataUtil from "../../utils/TaskMergeDataUtil";

import TaskTable from "./TaskTable";

const METHODS_TO_BIND = ["handleItemCheck"];
const DSL_FORM_SECTIONS = [
  TaskStatusDSLSection,
  TaskZoneDSLSection,
  TaskRegionDSLSection,
  FuzzyTextDSLSection
];

class TasksView extends mixin(SaveStateMixin) {
  constructor() {
    super();

    this.state = {
      checkedItems: {}
    };

    METHODS_TO_BIND.forEach(function(method) {
      this[method] = this[method].bind(this);
    }, this);
  }

  componentWillMount() {
    this.saveState_key = `tasksView#${this.props.itemID}`;
    super.componentWillMount();
  }

  componentWillReceiveProps(nextProps) {
    const prevCheckedItems = this.state.checkedItems;
    const checkedItems = {};

    nextProps.tasks.forEach(function(task) {
      if (prevCheckedItems[task.id]) {
        checkedItems[task.id] = true;
      }
    });

    this.setState({ checkedItems });
  }

  handleItemCheck(idsChecked) {
    const checkedItems = {};
    idsChecked.forEach(function(id) {
      checkedItems[id] = true;
    });

    this.setState({ checkedItems });
  }

  handleActionClick(killAction) {
    const { checkedItems } = this.state;

    if (!Object.keys(checkedItems).length) {
      return;
    }

    this.context.modalHandlers.killTasks({
      action: killAction,
      selectedItems: Object.keys(checkedItems)
    });
  }

  getTaskTable(tasks, checkedItems) {
    const { inverseStyle, params } = this.props;

    const classSet = classNames({
      "table table-flush table-borderless-outer table-borderless-inner-columns": true,
      "flush-bottom": true,
      inverse: inverseStyle
    });

    console.log(tasks);

    return (
      <TaskTable
        checkedItemsMap={checkedItems}
        className={classSet}
        params={params}
        onCheckboxChange={this.handleItemCheck}
        tasks={tasks}
        i18n={this.props.i18n}
      />
    );
  }

  getButtonContent(filterName, count) {
    return (

          {StringUtil.capitalize(filterName)}

        <Badge>{count || 0}</Badge>

    );
  }

  getStopButtons() {
    const { tasks } = this.props;
    const { checkedItems } = this.state;

    if (!Object.keys(checkedItems).length) {
      return null;
    }

    // Only allow restarting the task if the service isn't deploying.
    const isDeploying = Object.keys(checkedItems).some(function(taskId) {
      const service = DCOSStore.serviceTree.getServiceFromTaskID(taskId);

      return service && service.getServiceStatus() === ServiceStatus.DEPLOYING;
    });

    const isSDK = Object.keys(checkedItems).some(function(taskId) {
      const service = DCOSStore.serviceTree.getServiceFromTaskID(taskId);

      return service && isSDKService(service);
    });

    // Only show Stop if a scheduler task isn't selected
    const hasSchedulerTask = tasks.some(
      task => task.id in checkedItems && task.isSchedulerTask
    );

    // Using Button's native "disabled" prop prevents onMouseLeave from
    // being correctly called, preventing correct dismissal of the Tooltip.
    //
    // So we overwrite the click handlers manually.
    let handleRestartClick = function() {};
    let handleStopClick = function() {};

    if (!isDeploying && !isSDK) {
      handleRestartClick = this.handleActionClick.bind(this, "restart");
    }

    if (!hasSchedulerTask) {
      handleStopClick = this.handleActionClick.bind(this, "stop");
    }

    const restartButtonClasses = classNames("button button-primary-link", {
      disabled: isDeploying || isSDK
    });
    const stopButtonClasses = classNames("button button-primary-link", {
      disabled: hasSchedulerTask
    });

    return (

        <Tooltip
          content={
            <Trans render="span">
              Restarting tasks is not supported while the service is deploying.
            </Trans>
          }
          suppress={!isDeploying || isSDK}
          width={200}
          wrapperClassName="button-group"
          wrapText={true}
        >
          <button className={restartButtonClasses} onClick={handleRestartClick}>
            <Icon shape={SystemIcons.Repeat} size={iconSizeXs} />
            <Trans render="span">Restart</Trans>
          </button>
        </Tooltip>
        <Tooltip
          content={
            <Trans render="span">
              Stopping a scheduler task is not supported.
            </Trans>
          }
          suppress={!hasSchedulerTask}
          width={200}
          wrapText={true}
          wrapperClassName="button-group"
        >
          <button className={stopButtonClasses} onClick={handleStopClick}>
            <Icon shape={SystemIcons.CircleClose} size={iconSizeXs} />
            <Trans render="span">Stop</Trans>
          </button>
        </Tooltip>

    );
  }

  getFilterBar() {
    const {
      filters,
      filterExpression,
      handleExpressionChange,
      defaultFilterData
    } = this.props;

    const filterExpressionValue = filterExpression.value;

    const hostClasses = classNames("flush-left", {
      "column-medium-5": !filterExpressionValue,
      "column-medium-12": filterExpressionValue
    });

    return (

        <DSLFilterField
          filters={filters}
          formSections={DSL_FORM_SECTIONS}
          defaultData={defaultFilterData}
          expression={filterExpression}
          onChange={handleExpressionChange}
        />

    );
  }

  render() {
    const {
      inverseStyle,
      tasks,
      totalTasks,
      handleExpressionChange,
      i18n
    } = this.props;

    const { checkedItems } = this.state;

    let rightAlignLastNChildren = 0;
    const hasCheckedTasks = Object.keys(checkedItems).length !== 0;

    if (hasCheckedTasks) {
      rightAlignLastNChildren = 1;
    }

    const mergedTasks = TaskMergeDataUtil.mergeTaskData(tasks);

    // L10NTODO: Pluralize
    // We should pluralize FilterHeadline name here using lingui macro instead of
    // doing it manually in FilterHeadline
    return (

        <FilterHeadline
          currentLength={mergedTasks.length}
          inverseStyle={inverseStyle}
          name={i18n._(t`task`)}
          totalLength={totalTasks}
          onReset={() => handleExpressionChange({ value: "" })}
        />

          <FilterBar rightAlignLastNChildren={rightAlignLastNChildren}>
            {this.getFilterBar()}
            {this.getStopButtons()}
          </FilterBar>

        {this.getTaskTable(mergedTasks, checkedItems)}

    );
  }
}

TasksView.contextTypes = {
  modalHandlers: PropTypes.shape({
    killTasks: PropTypes.func.isRequired
  }).isRequired
};

TasksView.defaultProps = {
  inverseStyle: false,
  itemID: "",
  tasks: []
};

TasksView.propTypes = {
  params: PropTypes.object.isRequired,
  inverseStyle: PropTypes.bool,
  itemID: PropTypes.string,
  tasks: PropTypes.array
};

TasksView.contextTypes = {
  modalHandlers: PropTypes.shape({
    createGroup: PropTypes.func
  }).isRequired,
  router: routerShape
};

module.exports = withI18n()(TasksView);
<commit_msg>chore: remove debug helper<commit_after>import classNames from "classnames";
import mixin from "reactjs-mixin";
import { Tooltip } from "reactjs-components";
import { routerShape } from "react-router";
import PropTypes from "prop-types";
import React from "react";
import { withI18n } from "@lingui/react";
import { Trans, t } from "@lingui/macro";
import { Badge, Icon } from "@dcos/ui-kit";
import { SystemIcons } from "@dcos/ui-kit/dist/packages/icons/dist/system-icons-enum";
import { iconSizeXs } from "@dcos/ui-kit/dist/packages/design-tokens/build/js/designTokens";

import DCOSStore from "#SRC/js/stores/DCOSStore";
import DSLFilterField from "#SRC/js/components/DSLFilterField";

import FilterBar from "#SRC/js/components/FilterBar";
import FilterHeadline from "#SRC/js/components/FilterHeadline";
import SaveStateMixin from "#SRC/js/mixins/SaveStateMixin";
import StringUtil from "#SRC/js/utils/StringUtil";
import { isSDKService } from "#PLUGINS/services/src/js/utils/ServiceUtil";

import TaskStatusDSLSection from "../../components/dsl/TaskStatusDSLSection";
import TaskZoneDSLSection from "../../components/dsl/TaskZoneDSLSection";
import TaskRegionDSLSection from "../../components/dsl/TaskRegionDSLSection";
import FuzzyTextDSLSection from "../../components/dsl/FuzzyTextDSLSection";

import * as ServiceStatus from "../../constants/ServiceStatus";
import TaskMergeDataUtil from "../../utils/TaskMergeDataUtil";

import TaskTable from "./TaskTable";

const METHODS_TO_BIND = ["handleItemCheck"];
const DSL_FORM_SECTIONS = [
  TaskStatusDSLSection,
  TaskZoneDSLSection,
  TaskRegionDSLSection,
  FuzzyTextDSLSection
];

class TasksView extends mixin(SaveStateMixin) {
  constructor() {
    super();

    this.state = {
      checkedItems: {}
    };

    METHODS_TO_BIND.forEach(function(method) {
      this[method] = this[method].bind(this);
    }, this);
  }

  componentWillMount() {
    this.saveState_key = `tasksView#${this.props.itemID}`;
    super.componentWillMount();
  }

  componentWillReceiveProps(nextProps) {
    const prevCheckedItems = this.state.checkedItems;
    const checkedItems = {};

    nextProps.tasks.forEach(function(task) {
      if (prevCheckedItems[task.id]) {
        checkedItems[task.id] = true;
      }
    });

    this.setState({ checkedItems });
  }

  handleItemCheck(idsChecked) {
    const checkedItems = {};
    idsChecked.forEach(function(id) {
      checkedItems[id] = true;
    });

    this.setState({ checkedItems });
  }

  handleActionClick(killAction) {
    const { checkedItems } = this.state;

    if (!Object.keys(checkedItems).length) {
      return;
    }

    this.context.modalHandlers.killTasks({
      action: killAction,
      selectedItems: Object.keys(checkedItems)
    });
  }

  getTaskTable(tasks, checkedItems) {
    const { inverseStyle, params } = this.props;

    const classSet = classNames({
      "table table-flush table-borderless-outer table-borderless-inner-columns": true,
      "flush-bottom": true,
      inverse: inverseStyle
    });

    return (
      <TaskTable
        checkedItemsMap={checkedItems}
        className={classSet}
        params={params}
        onCheckboxChange={this.handleItemCheck}
        tasks={tasks}
        i18n={this.props.i18n}
      />
    );
  }

  getButtonContent(filterName, count) {
    return (

          {StringUtil.capitalize(filterName)}

        <Badge>{count || 0}</Badge>

    );
  }

  getStopButtons() {
    const { tasks } = this.props;
    const { checkedItems } = this.state;

    if (!Object.keys(checkedItems).length) {
      return null;
    }

    // Only allow restarting the task if the service isn't deploying.
    const isDeploying = Object.keys(checkedItems).some(function(taskId) {
      const service = DCOSStore.serviceTree.getServiceFromTaskID(taskId);

      return service && service.getServiceStatus() === ServiceStatus.DEPLOYING;
    });

    const isSDK = Object.keys(checkedItems).some(function(taskId) {
      const service = DCOSStore.serviceTree.getServiceFromTaskID(taskId);

      return service && isSDKService(service);
    });

    // Only show Stop if a scheduler task isn't selected
    const hasSchedulerTask = tasks.some(
      task => task.id in checkedItems && task.isSchedulerTask
    );

    // Using Button's native "disabled" prop prevents onMouseLeave from
    // being correctly called, preventing correct dismissal of the Tooltip.
    //
    // So we overwrite the click handlers manually.
    let handleRestartClick = function() {};
    let handleStopClick = function() {};

    if (!isDeploying && !isSDK) {
      handleRestartClick = this.handleActionClick.bind(this, "restart");
    }

    if (!hasSchedulerTask) {
      handleStopClick = this.handleActionClick.bind(this, "stop");
    }

    const restartButtonClasses = classNames("button button-primary-link", {
      disabled: isDeploying || isSDK
    });
    const stopButtonClasses = classNames("button button-primary-link", {
      disabled: hasSchedulerTask
    });

    return (

        <Tooltip
          content={
            <Trans render="span">
              Restarting tasks is not supported while the service is deploying.
            </Trans>
          }
          suppress={!isDeploying || isSDK}
          width={200}
          wrapperClassName="button-group"
          wrapText={true}
        >
          <button className={restartButtonClasses} onClick={handleRestartClick}>
            <Icon shape={SystemIcons.Repeat} size={iconSizeXs} />
            <Trans render="span">Restart</Trans>
          </button>
        </Tooltip>
        <Tooltip
          content={
            <Trans render="span">
              Stopping a scheduler task is not supported.
            </Trans>
          }
          suppress={!hasSchedulerTask}
          width={200}
          wrapText={true}
          wrapperClassName="button-group"
        >
          <button className={stopButtonClasses} onClick={handleStopClick}>
            <Icon shape={SystemIcons.CircleClose} size={iconSizeXs} />
            <Trans render="span">Stop</Trans>
          </button>
        </Tooltip>

    );
  }

  getFilterBar() {
    const {
      filters,
      filterExpression,
      handleExpressionChange,
      defaultFilterData
    } = this.props;

    const filterExpressionValue = filterExpression.value;

    const hostClasses = classNames("flush-left", {
      "column-medium-5": !filterExpressionValue,
      "column-medium-12": filterExpressionValue
    });

    return (

        <DSLFilterField
          filters={filters}
          formSections={DSL_FORM_SECTIONS}
          defaultData={defaultFilterData}
          expression={filterExpression}
          onChange={handleExpressionChange}
        />

    );
  }

  render() {
    const {
      inverseStyle,
      tasks,
      totalTasks,
      handleExpressionChange,
      i18n
    } = this.props;

    const { checkedItems } = this.state;

    let rightAlignLastNChildren = 0;
    const hasCheckedTasks = Object.keys(checkedItems).length !== 0;

    if (hasCheckedTasks) {
      rightAlignLastNChildren = 1;
    }

    const mergedTasks = TaskMergeDataUtil.mergeTaskData(tasks);

    // L10NTODO: Pluralize
    // We should pluralize FilterHeadline name here using lingui macro instead of
    // doing it manually in FilterHeadline
    return (

        <FilterHeadline
          currentLength={mergedTasks.length}
          inverseStyle={inverseStyle}
          name={i18n._(t`task`)}
          totalLength={totalTasks}
          onReset={() => handleExpressionChange({ value: "" })}
        />

          <FilterBar rightAlignLastNChildren={rightAlignLastNChildren}>
            {this.getFilterBar()}
            {this.getStopButtons()}
          </FilterBar>

        {this.getTaskTable(mergedTasks, checkedItems)}

    );
  }
}

TasksView.contextTypes = {
  modalHandlers: PropTypes.shape({
    killTasks: PropTypes.func.isRequired
  }).isRequired
};

TasksView.defaultProps = {
  inverseStyle: false,
  itemID: "",
  tasks: []
};

TasksView.propTypes = {
  params: PropTypes.object.isRequired,
  inverseStyle: PropTypes.bool,
  itemID: PropTypes.string,
  tasks: PropTypes.array
};

TasksView.contextTypes = {
  modalHandlers: PropTypes.shape({
    createGroup: PropTypes.func
  }).isRequired,
  router: routerShape
};

module.exports = withI18n()(TasksView);
<|endoftext|>


<commit_before>import BaseScene from '../BaseScene/BaseScene';
import Player from '../../Three/Objects/Player/Player';
import PlayerService from '../../Manager/PlayerManager/PlayerManager';
import playerStats from '../../Tools/PlayerStats/PlayerStats';
import Helper from '../../Tools/Helper/Helper';
import musicService from '../../Tools/MusicService/MusicService';
import GameTableManager from '../../Manager/GameTableManager/GameTableManager';
import gameAudioManager from '../../Manager/GameAudioManager/GameAudioManager';
import textureLoader from '../../Manager/LoaderManager/LoaderManager';
import timeHandler from '../../Tools/TimeHandler/TimeHandler';
import {
  SNAPSHOT,
  REMOVE_PLAYER,
  END_GAME
} from '../../Constants/MultiPlayer';

export default class MultiPlayerScene extends BaseScene {
  constructor(keys, mouse, gameWebSocketManager, functionGo) {
    super(keys, mouse, functionGo);

    this._game = false;
    this._id = +localStorage.getItem('id');

    this._webSocketManager = gameWebSocketManager;
    this._gameTableManager = new GameTableManager();

    this._isInitLeaderboard = false;
    this._killed = false;

    this._stats.style.display = 'none';
    this._hurt = document.body.querySelector('.hurt');
    this._time = document.body.querySelector('.parent__inf__wrapper');
  }

  set game(value) {
    this._game = value;
  }

  get game() {
    return this._game;
  }

  _init() {
    this._webSocketManager.setOnMessage(this._setUpWebSockets());

    this._findConnectInformation();
    this._setMouseWebSocketHandler();
    this._initScenePreferences();

    this._makeScene();

    this._setUpRender();
  }

  _findConnectInformation() {
    this._connectionInfo = document.body.querySelector('.stats__position-leftDown');
    this._connectionInfoText = this._connectionInfo.getElementsByTagName('p')[0];

    this._hideConnectionInfo();
  }

  _hideConnectionInfo() {
    this._connectionInfo.style.display = 'none';
  }

  _showConnectionInfo(text) {
    this._connectionInfo.style.display = 'block';
    this._connectionInfoText.innerHTML = `${text} connected`;
  }

  _setMouseWebSocketHandler() {
    document.addEventListener('mousedown', (event) => {
      event.preventDefault();

      if (!this._killed && event.which === 1) {
        this._updateBackEnd(true);
      }
    });
  }

  _setUpWebSockets() {
    return (content, data) => {
      console.log(data);

      switch (content.type) {
        case SNAPSHOT:
          this._updateGame(data);
          break;
        case REMOVE_PLAYER:
          this._removePlayer(data);
          break;
        case END_GAME:
          this._endGame();
          break;
        default:
          break;
      }
    };
  }

  _updateGame(data) {
    if (!this._isInitLeaderboard) {
      this._updateTable(this._makeListPlayers(data.players), this._id);
      this._isInitLeaderboard = true;
    }

    if (data.shot) {
      this._showShoot(data.hp);
      this._changeStats(data.hp);
    }

    this._changeStats(data.hp);

    if (data.hp === 0) {
      const {x, y, z} = Helper.randomVector(50);

      this._camera.position.copy({x, y, z});
    }

    if (+data.timeLeft === 1) {
      this._isAnimate = false;
      this._animate();
      this._endGame();

      return;
    }

    this._updateTime(data.timeLeft);

    data.players.forEach(player => {
      if (player.victims.length > 0) {
        player.victims.forEach(victim => {
          this._setKills(player.login, victim.login);

          setTimeout(() => {
            this._stopStats();
          }, 3000);
        });
      }

      const playerId = player.id;

      if (playerId === this._id) {
        return;
      }

      const playerPosition = player.position;

      if (playerPosition === null) {
        return;
      }

      if (!this._playersService.getFullPlayer(`id${playerId}`)) {
        const playerObject = new Player().object;
        this._playersService.setFullPlayer(playerId, {
          playerObject,
          isAngry: false
        });
        this._playersService.getFullPlayer(`id${playerId}`)
          .playerObject
          .position.copy(playerPosition);

        this._playersService.add(new PlayerService(playerObject, 100));

        this._scene.add(playerObject);

        this._showConnectionInfo(player.login);

        setTimeout(() => {
          this._hideConnectionInfo();
        }, 5000);
      } else {
        const playerStats = this._playersService.getFullPlayer(`id${playerId}`);
        playerStats.playerObject.position.copy(playerPosition);

        const color = playerStats.playerObject.material.color;
        const percent = player.hp / 100;

        if (!playerStats.isAngry && percent < 1) {
          playerStats.playerObject.material.map = textureLoader.load('/static/gameSource/face_angry.png');
          playerStats.isAngry = true;
        } else if (playerStats.isAngry && percent === 1) {
          playerStats.playerObject.material.map = textureLoader.load('/static/gameSource/face_usual.png');
          playerStats.isAngry = false;
        }

        percent < 1 ? color.setRGB(1, percent, percent) : color.setRGB(1, 1, 1);
      }
    });

    this._updateTable(this._makeListPlayers(data.players), this._id);
  }

  _removePlayer(data) {
    data.forEach(id => {
      this._scene.remove(this._playersService.getFullPlayer(`id${id}`).playerObject);
      this._playersService.removeFullPlayer(id);
    });
  }

  _animate() {
    if (this._isAnimate) {
      requestAnimationFrame(this._animate.bind(this));
    }

    this._render();

    setTimeout(() => {
      this._updateBackEnd(false);
    }, 30);
  }

  _updateBackEnd(shooting) {
    this._webSocketManager.send({
      type: 'application.mechanics.base.UserSnap',
      data: {
        position: this._getCameraPosition(),
        id: this._player.id,
        camera: this._getCameraRotation(),
        shooting
      }
    });
  }

  _getCameraPosition() {
    return {
      x: this._camera.position.x,
      y: this._camera.position.y,
      z: this._camera.position.z
    };
  }

  _getCameraRotation() {
    return {
      phi: this._camera.rotation.y,
      theta: 0
    };
  }

  _render() {
    const delta = this._clock.getDelta();
    this._keys.update(this._camera, delta, Helper.checkWallCollision.bind(this));

    this._renderer.render(this._scene, this._camera);
  }

  _endGame() {
    this.stop();
    this._keys._deactivateTable();

    musicService.startEndGame();
    this._openEndGame();

    setTimeout(() => {
      localStorage.setItem('multiPlayerScore', playerStats.kills * 100);
      this._closeEndGame();
      this._goToFromGame();
      location.reload();
    }, 4000);
  }

  _updateTable(data, id, type) {
    this._gameTableManager.setData(data, id, type);
  }

  _makeListPlayers(list) {
    const players = [];

    for (let field of list) {
      players.push([field.login, field.kills, field.deaths, field.id]);
    }

    return players;
  }

  _showShoot(health) {
    let lowHealth = null;

    if (health < 30) {
      lowHealth = 1 - health / 100;

      this._hurt.style.opacity = `${lowHealth}`;
    }

    this._hurt.style.opacity = `0.9`;

    setTimeout(() => {
      this._hurt.style.opacity = `${lowHealth ? lowHealth : 0}`;
    }, 300);

    const sound = gameAudioManager.getSound('pain');

    if (sound) {
      sound.play();
    }
  }

  _changeStats(health) {
    if (+health === 100) {
      this._hurt.style.opacity = `0`;
    }

    this._healthText.innerHTML = `${health}  HP`;
    this._healthProgress.style.width = `${health}%`;
  }

  _setKills(hunt, soul) {
    this._stats.style.display = 'block';
    this._kills.innerHTML = `${this._changeUsername(hunt)} killed ${this._changeUsername(soul)}`;
  }

  _stopStats() {
    this._stats.style.display = 'none';
  }

  _changeUsername(name) {
    if (name.length > 7) {
      name = name.slice(0, 7) + '...';
    }

    return name.toUpperCase();
  }

  _updateTime(time) {
    const resultTime = timeHandler(time);
    this._time.innerHTML = `${resultTime.minutes}:${(resultTime.seconds + '').length === 1 ? `0${resultTime.seconds}` : resultTime.seconds}`;
  }
}
<commit_msg>delete consolelog<commit_after>import BaseScene from '../BaseScene/BaseScene';
import Player from '../../Three/Objects/Player/Player';
import PlayerService from '../../Manager/PlayerManager/PlayerManager';
import playerStats from '../../Tools/PlayerStats/PlayerStats';
import Helper from '../../Tools/Helper/Helper';
import musicService from '../../Tools/MusicService/MusicService';
import GameTableManager from '../../Manager/GameTableManager/GameTableManager';
import gameAudioManager from '../../Manager/GameAudioManager/GameAudioManager';
import textureLoader from '../../Manager/LoaderManager/LoaderManager';
import timeHandler from '../../Tools/TimeHandler/TimeHandler';
import {
  SNAPSHOT,
  REMOVE_PLAYER,
  END_GAME
} from '../../Constants/MultiPlayer';

export default class MultiPlayerScene extends BaseScene {
  constructor(keys, mouse, gameWebSocketManager, functionGo) {
    super(keys, mouse, functionGo);

    this._game = false;
    this._id = +localStorage.getItem('id');

    this._webSocketManager = gameWebSocketManager;
    this._gameTableManager = new GameTableManager();

    this._isInitLeaderboard = false;
    this._killed = false;

    this._stats.style.display = 'none';
    this._hurt = document.body.querySelector('.hurt');
    this._time = document.body.querySelector('.parent__inf__wrapper');
  }

  set game(value) {
    this._game = value;
  }

  get game() {
    return this._game;
  }

  _init() {
    this._webSocketManager.setOnMessage(this._setUpWebSockets());

    this._findConnectInformation();
    this._setMouseWebSocketHandler();
    this._initScenePreferences();

    this._makeScene();

    this._setUpRender();
  }

  _findConnectInformation() {
    this._connectionInfo = document.body.querySelector('.stats__position-leftDown');
    this._connectionInfoText = this._connectionInfo.getElementsByTagName('p')[0];

    this._hideConnectionInfo();
  }

  _hideConnectionInfo() {
    this._connectionInfo.style.display = 'none';
  }

  _showConnectionInfo(text) {
    this._connectionInfo.style.display = 'block';
    this._connectionInfoText.innerHTML = `${text} connected`;
  }

  _setMouseWebSocketHandler() {
    document.addEventListener('mousedown', (event) => {
      event.preventDefault();

      if (!this._killed && event.which === 1) {
        this._updateBackEnd(true);
      }
    });
  }

  _setUpWebSockets() {
    return (content, data) => {
      switch (content.type) {
        case SNAPSHOT:
          this._updateGame(data);
          break;
        case REMOVE_PLAYER:
          this._removePlayer(data);
          break;
        case END_GAME:
          this._endGame();
          break;
        default:
          break;
      }
    };
  }

  _updateGame(data) {
    if (!this._isInitLeaderboard) {
      this._updateTable(this._makeListPlayers(data.players), this._id);
      this._isInitLeaderboard = true;
    }

    if (data.shot) {
      this._showShoot(data.hp);
      this._changeStats(data.hp);
    }

    this._changeStats(data.hp);

    if (data.hp === 0) {
      const {x, y, z} = Helper.randomVector(50);

      this._camera.position.copy({x, y, z});
    }

    if (+data.timeLeft === 1) {
      this._isAnimate = false;
      this._animate();
      this._endGame();

      return;
    }

    this._updateTime(data.timeLeft);

    data.players.forEach(player => {
      if (player.victims.length > 0) {
        player.victims.forEach(victim => {
          this._setKills(player.login, victim.login);

          setTimeout(() => {
            this._stopStats();
          }, 3000);
        });
      }

      const playerId = player.id;

      if (playerId === this._id) {
        return;
      }

      const playerPosition = player.position;

      if (playerPosition === null) {
        return;
      }

      if (!this._playersService.getFullPlayer(`id${playerId}`)) {
        const playerObject = new Player().object;
        this._playersService.setFullPlayer(playerId, {
          playerObject,
          isAngry: false
        });
        this._playersService.getFullPlayer(`id${playerId}`)
          .playerObject
          .position.copy(playerPosition);

        this._playersService.add(new PlayerService(playerObject, 100));

        this._scene.add(playerObject);

        this._showConnectionInfo(player.login);

        setTimeout(() => {
          this._hideConnectionInfo();
        }, 5000);
      } else {
        const playerStats = this._playersService.getFullPlayer(`id${playerId}`);
        playerStats.playerObject.position.copy(playerPosition);

        const color = playerStats.playerObject.material.color;
        const percent = player.hp / 100;

        if (!playerStats.isAngry && percent < 1) {
          playerStats.playerObject.material.map = textureLoader.load('/static/gameSource/face_angry.png');
          playerStats.isAngry = true;
        } else if (playerStats.isAngry && percent === 1) {
          playerStats.playerObject.material.map = textureLoader.load('/static/gameSource/face_usual.png');
          playerStats.isAngry = false;
        }

        percent < 1 ? color.setRGB(1, percent, percent) : color.setRGB(1, 1, 1);
      }
    });

    this._updateTable(this._makeListPlayers(data.players), this._id);
  }

  _removePlayer(data) {
    data.forEach(id => {
      this._scene.remove(this._playersService.getFullPlayer(`id${id}`).playerObject);
      this._playersService.removeFullPlayer(id);
    });
  }

  _animate() {
    if (this._isAnimate) {
      requestAnimationFrame(this._animate.bind(this));
    }

    this._render();

    setTimeout(() => {
      this._updateBackEnd(false);
    }, 30);
  }

  _updateBackEnd(shooting) {
    this._webSocketManager.send({
      type: 'application.mechanics.base.UserSnap',
      data: {
        position: this._getCameraPosition(),
        id: this._player.id,
        camera: this._getCameraRotation(),
        shooting
      }
    });
  }

  _getCameraPosition() {
    return {
      x: this._camera.position.x,
      y: this._camera.position.y,
      z: this._camera.position.z
    };
  }

  _getCameraRotation() {
    return {
      phi: this._camera.rotation.y,
      theta: 0
    };
  }

  _render() {
    const delta = this._clock.getDelta();
    this._keys.update(this._camera, delta, Helper.checkWallCollision.bind(this));

    this._renderer.render(this._scene, this._camera);
  }

  _endGame() {
    this.stop();
    this._keys._deactivateTable();

    musicService.startEndGame();
    this._openEndGame();

    setTimeout(() => {
      localStorage.setItem('multiPlayerScore', playerStats.kills * 100);
      this._closeEndGame();
      this._goToFromGame();
      location.reload();
    }, 4000);
  }

  _updateTable(data, id, type) {
    this._gameTableManager.setData(data, id, type);
  }

  _makeListPlayers(list) {
    const players = [];

    for (let field of list) {
      players.push([field.login, field.kills, field.deaths, field.id]);
    }

    return players;
  }

  _showShoot(health) {
    let lowHealth = null;

    if (health < 30) {
      lowHealth = 1 - health / 100;

      this._hurt.style.opacity = `${lowHealth}`;
    }

    this._hurt.style.opacity = `0.9`;

    setTimeout(() => {
      this._hurt.style.opacity = `${lowHealth ? lowHealth : 0}`;
    }, 300);

    const sound = gameAudioManager.getSound('pain');

    if (sound) {
      sound.play();
    }
  }

  _changeStats(health) {
    if (+health === 100) {
      this._hurt.style.opacity = `0`;
    }

    this._healthText.innerHTML = `${health}  HP`;
    this._healthProgress.style.width = `${health}%`;
  }

  _setKills(hunt, soul) {
    this._stats.style.display = 'block';
    this._kills.innerHTML = `${this._changeUsername(hunt)} killed ${this._changeUsername(soul)}`;
  }

  _stopStats() {
    this._stats.style.display = 'none';
  }

  _changeUsername(name) {
    if (name.length > 7) {
      name = name.slice(0, 7) + '...';
    }

    return name.toUpperCase();
  }

  _updateTime(time) {
    const resultTime = timeHandler(time);
    this._time.innerHTML = `${resultTime.minutes}:${(resultTime.seconds + '').length === 1 ? `0${resultTime.seconds}` : resultTime.seconds}`;
  }
}
<|endoftext|>


<commit_before>// Copyright 2021 Google LLC
//
// 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.

'use strict';

const path = require('path');
const assert = require('assert');
const cp = require('child_process');
const {describe, it} = require('mocha');

const execSync = cmd => cp.execSync(cmd, {encoding: 'utf-8'});

const cwd = path.join(__dirname, '..');

const project = process.env.GCLOUD_PROJECT;
const location = 'us-central1-a';

describe('Quickstart', () => {
  it('should run quickstart', async () => {
    const out = execSync(`node ./quickstart.js ${project} ${location}`, {cwd});
    assert.strictEqual(out.includes('fileShares'), true);
  });
});
<commit_msg>update samples test<commit_after>// Copyright 2021 Google LLC
//
// 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.

'use strict';

const path = require('path');
const assert = require('assert');
const cp = require('child_process');
const {describe, it, before} = require('mocha');
const {CloudFilestoreManagerClient} = require('@google-cloud/filestore');
const client = new CloudFilestoreManagerClient();

const execSync = cmd => cp.execSync(cmd, {encoding: 'utf-8'});

const cwd = path.join(__dirname, '..');

const location = 'us-central1-a';

describe('Quickstart', () => {
  let project;
  before(async () => {
    project = await client.getProjectId();
  });
  it('should run quickstart', async () => {
    const out = execSync(`node ./quickstart.js ${project} ${location}`, {cwd});
    assert.strictEqual(out.includes('fileShares'), true);
  });
});
<|endoftext|>