<commit_before>define(['sprd/entity/DesignConfigurationBase', 'sprd/entity/Size', 'sprd/util/UnitUtil', 'sprd/model/Design', "sprd/entity/PrintTypeColor", "underscore",
        "sprd/model/PrintType", "sprd/util/ProductUtil", "js/core/List", "flow", "sprd/manager/IDesignConfigurationManager", "sprd/data/IImageUploadService"
        , "sprd/entity/BlobImage", "sprd/data/MaskService", "sprd/data/ImageService", "sprd/manager/ImageMeasurer", "designer/manager/FeatureManager"],
    function (DesignConfigurationBase, Size, UnitUtil, Design, PrintTypeColor, _, PrintType, ProductUtil, List, flow
        , IDesignConfigurationManager, IImageUploadService, BlobImage, MaskService, ImageService, ImageMeasurer, FeatureManager) {

        return DesignConfigurationBase.inherit('sprd.model.DesignConfiguration', {
            defaults: {
                _dpi: "{printType.dpi}",

                _designCommission: "{design.price}",
                _allowScale: "{design.restrictions.allowScale}",

                afterEffect: null,
                processedDesign: null,
                processedImage: null,
                processedSize: null,
                innerRect: null,
                defaultInnerRect: null
            },

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

                this.bind('change:processedImage', this._setProcessedSize, this);
                this.bind('afterEffect', "processingParametersChanged", function () {
                    this.trigger("configurationChanged");
                }, this);
                this.bind('change:processedDesign', function () {
                    this._setOriginalDesignProperties()
                }, this);
                this.bind('change:rotation', function () {
                    this._debounceFunctionCall(this.setInnerRect, "innerRect", 800, this)
                }, this);

                this.set('defaultInnerRect', {
                    x: 0,
                    y: 0,
                    width: 1,
                    height: 1
                });
            },

            inject: {
                imageUploadService: IImageUploadService,
                maskService: MaskService,
                imageService: ImageService,
                context: "context",
                featureManager: FeatureManager
            },

            type: "design",

            _commitPrintType: function (newPrintType, oldPrintType) {
                // print type changed -> convert colors

                if (!newPrintType) {
                    return;
                }

                var colors = [],
                    printColors = this.$.printColors;

                printColors.each(function (printColor) {
                    colors.push(newPrintType.getClosestPrintColor(printColor.color()));
                });

                if (newPrintType.$.id === PrintType.Mapping.SpecialFlex) {
                    // convert all colors to the first one
                    for (var i = 1; i < colors.length; i++) {
                        colors[i] = colors[0];
                    }
                }

                var original = this.get('originalPrintType');
                if (original && original !== oldPrintType) {
                    this.set('originalPrintType', null);
                }

                printColors.reset(colors);
                this.trigger('configurationChanged');
                this.trigger("priceChanged");
            },

            getDesignColors: function (transformer) {
                var design = this.$.design,
                    printType = this.$.printType,
                    printColors = this.$.printColors;

                if (!design || !printType || !printColors || !design.isVectorDesign()) {
                    return;
                }

                var designColors = design.$.colors;

                if (!designColors || !designColors.length) {
                    return;
                }

                var newPrintColors = [];
                designColors.each(function (designColor) {
                    var color = (designColor.$["default"] || designColor.$["origin"]).toRGB();
                    color = transformer instanceof Function ? transformer(color) : color;

                    var closestPrintColor = printType.getClosestPrintColor(color);
                    newPrintColors.push(closestPrintColor);
                });

                return newPrintColors;
            },

            getInvertedDesignColors: function () {
                return this.getDesignColors(function (color) {
                    return color.invert();
                })
            },

            _commitAfterEffect: function (afterEffect) {
                var self = this;

                if (!afterEffect) {
                    this.set('processedImage', null);
                } else {
                    this.$.maskService.applyAfterEffect(self.$.design, afterEffect, null, function (err, ctx) {
                        if (!err) {
                            self.setProcessedImage(ctx);
                        } else {
                            console.error(err);
                        }

                        afterEffect.callback && afterEffect.callback(err, ctx);
                    });
                }

                this.trigger('configurationChanged');
            },

            _validatePrintTypeSize: function (printType, width, height, scale) {
                var ret = this.callBase();
                var design = this.$.design;

                if (!printType || !scale || !_.isNumber(width) || !_.isNumber(height) || !design) {
                    return ret;
                }

                if (!design.isVectorDesign()) {
                    ret.dpiBound = scale.x > 1 || scale.y > 1;
                }

                return ret;
            },

            getMinScale: function () {
                var minScale = this.callBase() || Number.MIN_VALUE,
                    printType = this.$.printType;

                if (printType && !printType.isShrinkable()) {
                    minScale = Math.max(minScale, this.minimumScale());
                }

                return minScale;
            }.onChange("minimumScale()", "printType"),

            getMaxScale: function () {
                var maxScale = this.callBase(),
                    design = this.$.design;

                if (design && !design.isVectorDesign()) {
                    maxScale = Math.min(1, maxScale);
                }

                return maxScale;
            }.onChange("printType", "size()", "design"),

            _setProcessedSize: function () {
                var afterEffect = this.$.afterEffect;
                var design = this.$.design;

                if (afterEffect && this.$.processedImage) {
                    this.set('processedSize', this.$.maskService.getProcessedSize(afterEffect, design));
                } else {
                    this.set('processedSize', null);
                }

                this.trigger('sizeChanged');
            },

            applyAfterEffect: function (ctx) {
                this.setProcessedImage(ctx);
            },

            setProcessedImage: function (ctx) {
                var self = this;

                if (!self.$.design || !self.$.afterEffect) {
                    return;
                }

                var cacheId = [self.$.design.$.id, self.$.afterEffect.id()].join('#');
                self.synchronizeFunctionCall.call(self, function (cb) {
                    var img = self.$.maskService.trimAndExport(ctx, self.$.afterEffect, null);
                    cb(null, img);
                }, cacheId, function (err, result) {
                    self.set('processedImage', result);
                }, self);
            },

            getPrintColorsAsRGB: function () {
                var ret = [];

                if (this.$.design.$.colors.size() === this.$.printColors.size()) {
                    // go in the direction of the layers of the design
                    for (var i = 0; i < this.$.design.$.colors.$items.length; i++) {
                        var designColor = this.$.design.$.colors.$items[i];
                        var printColor = this.$.printColors.$items[i];
                        ret[designColor.$.layer] = printColor.color().toRGB().toHexString();
                    }
                }

                return ret;
            },

            setColor: function (layerIndex, color) {
                var printType = this.$.printType;

                if (!(color instanceof PrintTypeColor)) {
                    color = printType.getClosestPrintColor(color);
                }

                if (!printType.containsPrintTypeColor(color)) {
                    throw new Error("Color not contained in print type");
                }

                var printColors = this.$.printColors.$items;

                if (printColors[layerIndex] === color) {
                    return;
                }

                printColors.splice(layerIndex, 1, color);

                if (printType.$.id === PrintType.Mapping.SpecialFlex) {
                    // convert all other layers to the new color
                    for (var i = 0; i < printColors.length; i++) {
                        if (i !== layerIndex) {
                            printColors[i] = printColors[layerIndex];
                        }
                    }
                }

                this.$.printColors.reset(printColors);

                this.trigger('configurationChanged');
                this.trigger("priceChanged");
            },

            size: function () {
                return this.getSizeForPrintType(this.$.printType);
            }.onChange("_dpi", "design", "processedSize"),

            getSizeInPx: function (design, options) {
                options = options || {};
                design = design || this.$.design;
                return options.original ? design.$.size : this.$.processedSize || design.$.size;
            },

            getSizeForPrintType: function (printType, design, options) {
                options = options || {};
                design = design || this.$.design;
                printType = printType || this.$.printType;

                if (design && design.$.size && printType && printType.$.dpi) {
                    var dpi = printType.$.dpi;
                    var size = this.getSizeInPx(design, options);
                    return UnitUtil.convertSizeToMm(size, dpi);
                }

                return Size.empty;
            },

            isScalable: function () {
                return this.get("printType.isScalable()") && this.$._allowScale;
            }.onChange("printType", "_allowScale"),

            allowScale: function () {
                return this.$._allowScale;
            },

            getImageUrl: function () {
                var design = this.$.design,
                    imageService = this.$.imageService;

                if (!design || !imageService) {
                    return;
                }

                return this.$.processedImage || design.$.localImage || this.$.imageService.designImageFromCache(design.$.wtfMbsId, {
                    width: 100,
                    sameOrigin: true
                });
            },

            setInnerRect: function () {
                var self = this,
                    isMeasuringEnabled = this.isMeasuringEnabled();

                if (!isMeasuringEnabled) {
                    return;
                }

                this.getInnerRect(this.$.rotation, function (err, rect) {
                    if (!err) {
                        self.set("innerRect", rect);
                    }
                });
            },

            isMeasuringEnabled: function () {
                var featureEnabled = this.$.featureManager && this.$.featureManager.getFeatureState("calcInnerRects"),
                    design = this.$.design;

                if (!design) {
                    return false;
                }

                return featureEnabled && design.isVectorDesign();
            },

            getInnerRect: function (rotation, callback) {
                var url = this.getImageUrl();

                if (!url) {
                    callback && callback(new Error("Not able to get an image from current configuration."));
                    return;
                }

                flow()
                    .seq("image", function (cb) {
                        ImageMeasurer.toImage(url, cb)
                    })
                    .seq("rect", function () {
                        return ImageMeasurer.getRealDesignSize(this.vars.image, rotation);
                    })
                    .exec(function (err, results) {
                        callback && callback(err, results && results.rect)
                    })
            },

            price: function () {

                var usedPrintColors = [],
                    price = this.callBase();

                this.$.printColors.each(function (printColor) {
                    if (_.indexOf(usedPrintColors, printColor) === -1) {
                        usedPrintColors.push(printColor);
                    }
                });

                for (var i = 0; i < usedPrintColors.length; i++) {
                    if (usedPrintColors[i]) {
                        price.add((usedPrintColors[i]).get("price"));
                    }
                }

                price.add(this.get('_designCommission'));

                return price;

            }.on("priceChanged").onChange("_designCommission", "_printTypePrice"),

            getPossiblePrintTypes: function (appearance) {
                var ret = [],
                    printArea = this.$.printArea,
                    design = this.$.design;

                if (this.$context) {
                    appearance = appearance || this.$context.$contextModel.get('appearance');
                }

                if (printArea && appearance && design) {
                    ret = this.getPossiblePrintTypesForPrintArea(printArea, appearance)
                }

                return ret;
            }.onChange("printArea", "design"),

            _setAfterEffectProperties: function () {
                var afterEffect = this.get('afterEffect');
                var properties = this.get('properties');

                if (afterEffect) {
                    properties.afterEffect = _.extend(properties.afterEffect || {}, afterEffect.compose());
                    properties.type = 'afterEffect';
                } else if (properties.afterEffect || properties.type === "afterEffect") {
                    delete properties.afterEffect;
                    delete properties.type;
                }
            },

            _setOriginalDesignProperties: function (design) {
                var properties = this.get('properties'),
                    afterEffect = this.get('afterEffect');

                design = design || this.$.processedDesign;

                if (design && afterEffect) {
                    //Mask is already applied and processedImage uploaded
                    properties.afterEffect = properties.afterEffect || {};
                    properties.afterEffect.originalDesign = {
                        id: design.get('wtfMbsId'),
                        href: "/" + design.get("id")
                    };
                }
            },

            compose: function () {
                var processedDesign = this.get('processedDesign'),
                    originalDesign = this.get('design');

                if (processedDesign) {
                    this.set('design', processedDesign, {silent: true});
                }

                var ret = this.callBase();
                this._setAfterEffectProperties();
                this._setOriginalDesignProperties(originalDesign);
                ret.properties = this.$.properties;

                if (processedDesign && originalDesign) {
                    this.set('design', originalDesign);
                }

                return ret;
            },

            save: function (callback) {
                var self = this,
                    afterEffect = this.$.afterEffect;

                if (!afterEffect) {
                    callback && callback();
                } else {
                    flow()
                        .seq("design", function (cb) {
                            var afterEffect = self.$.afterEffect;
                            if (afterEffect) {
                                self.$.maskService.applyMask(afterEffect, self.$.design, self.$.context.$.id, cb);
                            }
                        })
                        .seq(function () {
                            if (this.vars.design) {
                                self.set('processedDesign', this.vars.design);
                            }
                        })
                        .exec(callback);
                }
            },

            parse: function (data) {
                data = this.callBase();

                if (data.designs) {
                    this.$$.design = data.designs[0];
                }

                data.designs = undefined;

                if (data.printArea) {
                    // remove printArea from payload since it is the wrong one
                    // it will be set within the initSchema methods
                    this.$$.printArea = data.printArea;
                    data.printArea = null;
                }

                if (data.content) {
                    this.$$.svg = data.content.svg;
                }

                return data;
            },

            saveTakesTime: function () {
                return this.get('afterEffect');
            },

            init: function (options, callback) {
                this.$.manager.initializeConfiguration(this, options, callback);
                this.setInnerRect();
            },

            isAllowedOnPrintArea: function (printArea) {
                return printArea && printArea.get("restrictions.designAllowed");
            },

            getPossiblePrintTypesForPrintArea: function (printArea, appearance) {
                return ProductUtil.getPossiblePrintTypesForDesignOnPrintArea(this.$.design, printArea, appearance);
            },

            minimumScale: function () {
                return (this.get("design.restrictions.minimumScale") || 100 ) / 100;
            }.onChange("design.restrictions.minimumScale"),

            clone: function () {
                var afterEffect = this.$.afterEffect,
                    clone = this.callBase();

                if (afterEffect) {
                    var afterEffectClone = afterEffect.clone();
                    clone.set('afterEffect', afterEffectClone);
                }

                return clone;
            }
        });
    })
;<commit_msg>reworked dod-check check<commit_after>define(['sprd/entity/DesignConfigurationBase', 'sprd/entity/Size', 'sprd/util/UnitUtil', 'sprd/model/Design', "sprd/entity/PrintTypeColor", "underscore",
        "sprd/model/PrintType", "sprd/util/ProductUtil", "js/core/List", "flow", "sprd/manager/IDesignConfigurationManager", "sprd/data/IImageUploadService"
        , "sprd/entity/BlobImage", "sprd/data/MaskService", "sprd/data/ImageService", "sprd/manager/ImageMeasurer", "designer/manager/FeatureManager"],
    function (DesignConfigurationBase, Size, UnitUtil, Design, PrintTypeColor, _, PrintType, ProductUtil, List, flow
        , IDesignConfigurationManager, IImageUploadService, BlobImage, MaskService, ImageService, ImageMeasurer, FeatureManager) {

        return DesignConfigurationBase.inherit('sprd.model.DesignConfiguration', {
            defaults: {
                _dpi: "{printType.dpi}",

                _designCommission: "{design.price}",
                _allowScale: "{design.restrictions.allowScale}",

                afterEffect: null,
                processedDesign: null,
                processedImage: null,
                processedSize: null,
                innerRect: null,
                defaultInnerRect: null
            },

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

                this.bind('change:processedImage', this._setProcessedSize, this);
                this.bind('afterEffect', "processingParametersChanged", function () {
                    this.trigger("configurationChanged");
                }, this);
                this.bind('change:processedDesign', function () {
                    this._setOriginalDesignProperties()
                }, this);
                this.bind('change:rotation', function () {
                    this._debounceFunctionCall(this.setInnerRect, "innerRect", 800, this)
                }, this);

                this.set('defaultInnerRect', {
                    x: 0,
                    y: 0,
                    width: 1,
                    height: 1
                });
            },

            inject: {
                imageUploadService: IImageUploadService,
                maskService: MaskService,
                imageService: ImageService,
                context: "context",
                featureManager: FeatureManager
            },

            type: "design",

            _commitPrintType: function (newPrintType, oldPrintType) {
                // print type changed -> convert colors

                if (!newPrintType) {
                    return;
                }

                var colors = [],
                    printColors = this.$.printColors;

                printColors.each(function (printColor) {
                    colors.push(newPrintType.getClosestPrintColor(printColor.color()));
                });

                if (newPrintType.$.id === PrintType.Mapping.SpecialFlex) {
                    // convert all colors to the first one
                    for (var i = 1; i < colors.length; i++) {
                        colors[i] = colors[0];
                    }
                }

                var original = this.get('originalPrintType');
                if (original && original !== oldPrintType) {
                    this.set('originalPrintType', null);
                }

                printColors.reset(colors);
                this.trigger('configurationChanged');
                this.trigger("priceChanged");
            },

            getDesignColors: function (transformer) {
                var design = this.$.design,
                    printType = this.$.printType,
                    printColors = this.$.printColors;

                if (!design || !printType || !printColors || !design.isVectorDesign()) {
                    return;
                }

                var designColors = design.$.colors;

                if (!designColors || !designColors.length) {
                    return;
                }

                var newPrintColors = [];
                designColors.each(function (designColor) {
                    var color = (designColor.$["default"] || designColor.$["origin"]).toRGB();
                    color = transformer instanceof Function ? transformer(color) : color;

                    var closestPrintColor = printType.getClosestPrintColor(color);
                    newPrintColors.push(closestPrintColor);
                });

                return newPrintColors;
            },

            getInvertedDesignColors: function () {
                return this.getDesignColors(function (color) {
                    return color.invert();
                })
            },

            _commitAfterEffect: function (afterEffect) {
                var self = this;

                if (!afterEffect) {
                    this.set('processedImage', null);
                } else {
                    this.$.maskService.applyAfterEffect(self.$.design, afterEffect, null, function (err, ctx) {
                        if (!err) {
                            self.setProcessedImage(ctx);
                        } else {
                            console.error(err);
                        }

                        afterEffect.callback && afterEffect.callback(err, ctx);
                    });
                }

                this.trigger('configurationChanged');
            },

            _validatePrintTypeSize: function (printType, width, height, scale) {
                var ret = this.callBase();
                var design = this.$.design;

                if (!printType || !scale || !_.isNumber(width) || !_.isNumber(height) || !design) {
                    return ret;
                }

                if (!design.isVectorDesign()) {
                    ret.dpiBound = scale.x > 1 || scale.y > 1;
                }

                return ret;
            },

            getMinScale: function () {
                var minScale = this.callBase() || Number.MIN_VALUE,
                    printType = this.$.printType;

                if (printType && !printType.isShrinkable()) {
                    minScale = Math.max(minScale, this.minimumScale());
                }

                return minScale;
            }.onChange("minimumScale()", "printType"),

            getMaxScale: function () {
                var maxScale = this.callBase(),
                    design = this.$.design;

                if (design && !design.isVectorDesign()) {
                    maxScale = Math.min(1, maxScale);
                }

                return maxScale;
            }.onChange("printType", "size()", "design"),

            _setProcessedSize: function () {
                var afterEffect = this.$.afterEffect;
                var design = this.$.design;

                if (afterEffect && this.$.processedImage) {
                    this.set('processedSize', this.$.maskService.getProcessedSize(afterEffect, design));
                } else {
                    this.set('processedSize', null);
                }

                this.trigger('sizeChanged');
            },

            applyAfterEffect: function (ctx) {
                this.setProcessedImage(ctx);
            },

            setProcessedImage: function (ctx) {
                var self = this;

                if (!self.$.design || !self.$.afterEffect) {
                    return;
                }

                var cacheId = [self.$.design.$.id, self.$.afterEffect.id()].join('#');
                self.synchronizeFunctionCall.call(self, function (cb) {
                    var img = self.$.maskService.trimAndExport(ctx, self.$.afterEffect, null);
                    cb(null, img);
                }, cacheId, function (err, result) {
                    self.set('processedImage', result);
                }, self);
            },

            getPrintColorsAsRGB: function () {
                var ret = [];

                if (this.$.design.$.colors.size() === this.$.printColors.size()) {
                    // go in the direction of the layers of the design
                    for (var i = 0; i < this.$.design.$.colors.$items.length; i++) {
                        var designColor = this.$.design.$.colors.$items[i];
                        var printColor = this.$.printColors.$items[i];
                        ret[designColor.$.layer] = printColor.color().toRGB().toHexString();
                    }
                }

                return ret;
            },

            setColor: function (layerIndex, color) {
                var printType = this.$.printType;

                if (!(color instanceof PrintTypeColor)) {
                    color = printType.getClosestPrintColor(color);
                }

                if (!printType.containsPrintTypeColor(color)) {
                    throw new Error("Color not contained in print type");
                }

                var printColors = this.$.printColors.$items;

                if (printColors[layerIndex] === color) {
                    return;
                }

                printColors.splice(layerIndex, 1, color);

                if (printType.$.id === PrintType.Mapping.SpecialFlex) {
                    // convert all other layers to the new color
                    for (var i = 0; i < printColors.length; i++) {
                        if (i !== layerIndex) {
                            printColors[i] = printColors[layerIndex];
                        }
                    }
                }

                this.$.printColors.reset(printColors);

                this.trigger('configurationChanged');
                this.trigger("priceChanged");
            },

            size: function () {
                return this.getSizeForPrintType(this.$.printType);
            }.onChange("_dpi", "design", "processedSize"),

            getSizeInPx: function (design, options) {
                options = options || {};
                design = design || this.$.design;
                return options.original ? design.$.size : this.$.processedSize || design.$.size;
            },

            getSizeForPrintType: function (printType, design, options) {
                options = options || {};
                design = design || this.$.design;
                printType = printType || this.$.printType;

                if (design && design.$.size && printType && printType.$.dpi) {
                    var dpi = printType.$.dpi;
                    var size = this.getSizeInPx(design, options);
                    return UnitUtil.convertSizeToMm(size, dpi);
                }

                return Size.empty;
            },

            isScalable: function () {
                return this.get("printType.isScalable()") && this.$._allowScale;
            }.onChange("printType", "_allowScale"),

            allowScale: function () {
                return this.$._allowScale;
            },

            getImageUrl: function () {
                var design = this.$.design,
                    imageService = this.$.imageService;

                if (!design || !imageService) {
                    return;
                }

                return this.$.processedImage || design.$.localImage || this.$.imageService.designImageFromCache(design.$.wtfMbsId, {
                    width: 100,
                    sameOrigin: true
                });
            },

            setInnerRect: function () {
                var self = this,
                    isMeasuringEnabled = this.isMeasuringEnabled();

                if (!isMeasuringEnabled) {
                    return;
                }

                this.getInnerRect(this.$.rotation, function (err, rect) {
                    if (!err) {
                        self.set("innerRect", rect);
                    }
                });
            },

            isMeasuringEnabled: function () {
                var featureEnabled = this.$.featureManager && this.$.featureManager.getFeatureState("calcInnerRects"),
                    design = this.$.design;

                if (!design) {
                    return false;
                }

                return featureEnabled && design.isVectorDesign();
            },

            getInnerRect: function (rotation, callback) {
                var url = this.getImageUrl();

                if (!url) {
                    callback && callback(new Error("Not able to get an image from current configuration."));
                    return;
                }

                flow()
                    .seq("image", function (cb) {
                        ImageMeasurer.toImage(url, cb)
                    })
                    .seq("rect", function () {
                        return ImageMeasurer.getRealDesignSize(this.vars.image, rotation);
                    })
                    .exec(function (err, results) {
                        callback && callback(err, results && results.rect)
                    })
            },

            price: function () {

                var usedPrintColors = [],
                    price = this.callBase();

                this.$.printColors.each(function (printColor) {
                    if (_.indexOf(usedPrintColors, printColor) === -1) {
                        usedPrintColors.push(printColor);
                    }
                });

                for (var i = 0; i < usedPrintColors.length; i++) {
                    if (usedPrintColors[i]) {
                        price.add((usedPrintColors[i]).get("price"));
                    }
                }

                price.add(this.get('_designCommission'));

                return price;

            }.on("priceChanged").onChange("_designCommission", "_printTypePrice"),

            getPossiblePrintTypes: function (appearance) {
                var ret = [],
                    printArea = this.$.printArea,
                    design = this.$.design;

                if (this.$context) {
                    appearance = appearance || this.$context.$contextModel.get('appearance');
                }

                if (printArea && appearance && design) {
                    ret = this.getPossiblePrintTypesForPrintArea(printArea, appearance)
                }

                return ret;
            }.onChange("printArea", "design"),

            _setAfterEffectProperties: function () {
                var afterEffect = this.get('afterEffect');
                var properties = this.get('properties');

                if (afterEffect) {
                    properties.afterEffect = _.extend(properties.afterEffect || {}, afterEffect.compose());
                    properties.type = 'afterEffect';
                } else if (properties.afterEffect || properties.type === "afterEffect") {
                    delete properties.afterEffect;
                    delete properties.type;
                }
            },

            _setOriginalDesignProperties: function (design) {
                var properties = this.get('properties'),
                    afterEffect = this.get('afterEffect');

                design = design || this.$.processedDesign;

                if (design && afterEffect) {
                    //Mask is already applied and processedImage uploaded
                    properties.afterEffect = properties.afterEffect || {};
                    properties.afterEffect.originalDesign = {
                        id: design.get('wtfMbsId'),
                        href: "/" + design.get("id")
                    };
                }
            },

            compose: function () {
                var processedDesign = this.get('processedDesign'),
                    originalDesign = this.get('design');

                if (processedDesign) {
                    this.set('design', processedDesign, {silent: true});
                }

                var ret = this.callBase();
                this._setAfterEffectProperties();
                this._setOriginalDesignProperties(originalDesign);
                ret.properties = this.$.properties;

                if (processedDesign && originalDesign) {
                    this.set('design', originalDesign);
                }

                return ret;
            },

            save: function (callback) {
                var self = this,
                    afterEffect = this.$.afterEffect;

                if (!afterEffect) {
                    callback && callback();
                } else {
                    flow()
                        .seq("design", function (cb) {
                            var afterEffect = self.$.afterEffect;
                            if (afterEffect) {
                                self.$.maskService.applyMask(afterEffect, self.$.design, self.$.context.$.id, cb);
                            }
                        })
                        .seq(function () {
                            if (this.vars.design) {
                                self.set('processedDesign', this.vars.design);
                            }
                        })
                        .exec(callback);
                }
            },

            parse: function (data) {
                data = this.callBase();

                if (data.designs) {
                    this.$$.design = data.designs[0];
                }

                data.designs = undefined;

                if (data.printArea) {
                    // remove printArea from payload since it is the wrong one
                    // it will be set within the initSchema methods
                    this.$$.printArea = data.printArea;
                    data.printArea = null;
                }

                if (data.content) {
                    this.$$.svg = data.content.svg;
                }

                return data;
            },

            saveTakesTime: function () {
                var designColors = this.get("design.colors");
                return this.get('afterEffect') || !designColors || designColors.length != 1;
            },

            init: function (options, callback) {
                this.$.manager.initializeConfiguration(this, options, callback);
                this.setInnerRect();
            },

            isAllowedOnPrintArea: function (printArea) {
                return printArea && printArea.get("restrictions.designAllowed");
            },

            getPossiblePrintTypesForPrintArea: function (printArea, appearance) {
                return ProductUtil.getPossiblePrintTypesForDesignOnPrintArea(this.$.design, printArea, appearance);
            },

            minimumScale: function () {
                return (this.get("design.restrictions.minimumScale") || 100 ) / 100;
            }.onChange("design.restrictions.minimumScale"),

            clone: function () {
                var afterEffect = this.$.afterEffect,
                    clone = this.callBase();

                if (afterEffect) {
                    var afterEffectClone = afterEffect.clone();
                    clone.set('afterEffect', afterEffectClone);
                }

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


<commit_before>$(document).ready(function(){
    var locations = {
        1: "region",
        2: "state",
        4: "mesoregion",
        5: "microregion",
        7: "municipality"
    };

    var course = location.pathname.split('/')[3];
    var courseFilter;

    if (course.length == 2)
    	courseFilter = 'hedu_course_field=' + course;
    else if (course.length == 6)
    	courseFilter = 'hedu_course=' + course;

    var idIbge = $('#id_ibge').val();
    var locationFilter = ''
    if (idIbge != 'None')
    	locationFilter = idIbge ? locations[idIbge.length] + '=' + idIbge : '';

    filter = [courseFilter, locationFilter].join('&');

    BlueBox.add({
        url: 'http://api.staging.dataviva.info/hedu/year/university?order=enrolleds&year=2015&direction=desc&limit=1&' + filter,
        title: dictionary['main_university'],
        subtitle: dictionary['number_enrolled_students'],
        label: {
            metadata: true,
            value: 'university'
        },
        value: 'enrolleds',
        tab: 'enrollments'
    });

    BlueBox.add({
        url: 'http://api.staging.dataviva.info/hedu/year/municipality?order=enrolleds&year=2015&direction=desc&limit=1&' + filter,
        title: dictionary['main_municipality'],
        subtitle: dictionary['number_enrolled_students'],
        label: {
            metadata: true,
            value: 'municipality'
        },

        value: 'enrolleds',
        tab: 'enrollments'
    });

    BlueBox.add({
        url: 'http://api.staging.dataviva.info/hedu/year/university?order=entrants&year=2015&direction=desc&limit=1&' + filter,
        title: dictionary['main_university'],
        subtitle: dictionary['number_entrant_students'],
        label: {
            metadata: true,
            value: 'university'
        },
        value: 'entrants',
        tab: 'enrollments'
    });

    BlueBox.add({
        url: 'http://api.staging.dataviva.info/hedu/year/municipality?order=entrants&year=2015&direction=desc&limit=1&' + filter,
        title: dictionary['main_municipality'],
        subtitle: dictionary['number_entrant_students'],
        label: {
            metadata: true,
            value: 'municipality'
        },
        value: 'entrants',
        tab: 'enrollments'
    });

    BlueBox.add({
        url: 'http://api.staging.dataviva.info/hedu/year/university?order=graduates&year=2015&direction=desc&limit=1&' + filter,
        title: dictionary['main_university'],
        subtitle: dictionary['number_graduates_students'],
        label: {
            metadata: true,
            value: 'university'
        },
        value: 'graduates',
        tab: 'enrollments'
    });

    BlueBox.add({
        url: 'http://api.staging.dataviva.info/hedu/year/municipality?order=graduates&year=2015&direction=desc&limit=1&' + filter,
        title: dictionary['main_municipality'],
        subtitle: dictionary['number_graduates_students'],
        label: {
            metadata: true,
            value: 'municipality'
        },
        value: 'graduates',
        tab: 'enrollments'
    });
});<commit_msg>Fixes major blueboxes to dont show when municipality is selected<commit_after>$(document).ready(function(){
    var locations = {
        1: "region",
        2: "state",
        4: "mesoregion",
        5: "microregion",
        7: "municipality"
    };

    var course = location.pathname.split('/')[3];
    var courseFilter;

    if (course.length == 2)
    	courseFilter = 'hedu_course_field=' + course;
    else if (course.length == 6)
    	courseFilter = 'hedu_course=' + course;

    var idIbge = $('#id_ibge').val();
    var locationFilter = ''
    if (idIbge != 'None')
    	locationFilter = idIbge ? locations[idIbge.length] + '=' + idIbge : '';

    filter = [courseFilter, locationFilter].join('&');
    var isMunicipality = idIbge.length == 7;

    if(!isMunicipality) {
	    BlueBox.add({
	        url: 'http://api.staging.dataviva.info/hedu/year/municipality?order=enrolleds&year=2015&direction=desc&limit=1&' + filter,
	        title: dictionary['main_municipality'],
	        subtitle: dictionary['number_enrolled_students'],
	        label: {
	            metadata: true,
	            value: 'municipality'
	        },

	        value: 'enrolleds',
	        tab: 'enrollments'
	    });

	    BlueBox.add({
	        url: 'http://api.staging.dataviva.info/hedu/year/municipality?order=entrants&year=2015&direction=desc&limit=1&' + filter,
	        title: dictionary['main_municipality'],
	        subtitle: dictionary['number_entrant_students'],
	        label: {
	            metadata: true,
	            value: 'municipality'
	        },
	        value: 'entrants',
	        tab: 'enrollments'
	    });

	    BlueBox.add({
	        url: 'http://api.staging.dataviva.info/hedu/year/municipality?order=graduates&year=2015&direction=desc&limit=1&' + filter,
	        title: dictionary['main_municipality'],
	        subtitle: dictionary['number_graduates_students'],
	        label: {
	            metadata: true,
	            value: 'municipality'
	        },
	        value: 'graduates',
	        tab: 'enrollments'
	    });
	}

    BlueBox.add({
        url: 'http://api.staging.dataviva.info/hedu/year/university?order=enrolleds&year=2015&direction=desc&limit=1&' + filter,
        title: dictionary['main_university'],
        subtitle: dictionary['number_enrolled_students'],
        label: {
            metadata: true,
            value: 'university'
        },
        value: 'enrolleds',
        tab: 'enrollments'
    });

    BlueBox.add({
        url: 'http://api.staging.dataviva.info/hedu/year/university?order=entrants&year=2015&direction=desc&limit=1&' + filter,
        title: dictionary['main_university'],
        subtitle: dictionary['number_entrant_students'],
        label: {
            metadata: true,
            value: 'university'
        },
        value: 'entrants',
        tab: 'enrollments'
    });

    BlueBox.add({
        url: 'http://api.staging.dataviva.info/hedu/year/university?order=graduates&year=2015&direction=desc&limit=1&' + filter,
        title: dictionary['main_university'],
        subtitle: dictionary['number_graduates_students'],
        label: {
            metadata: true,
            value: 'university'
        },
        value: 'graduates',
        tab: 'enrollments'
    });

});<|endoftext|>


<commit_before>// Edit this file to add your cloud design!

// Just write a function with a unique name like:
// function perlinNoiseCloud() {}
// and then add a line of code that "registers" it:
// register(perlinNoiseCloud, "Perlin Noise Cloud", "Daniel Shiffman");
// Here's an example below!

// Example rounded rectangle cloud
function rectangle() {
  // Draw your cloud here
  rect(50, 50, width - 100, height - 100, 50);
  // Return an internal rectangle that it is safe to draw text within. Of the
  // form [top_left, top_right, width, height]
  return [100, 100, width - 200, height - 200];
}

// Register your function with register(function, style_name, author_name)
register(rectangle, "Example", "example");

/* ------  Add your custom cloud generators below! ------ */

function ellipseCloud() {
  const CIRC_RADIUS = width / 8;

  const cloudWidth = width - 100 - CIRC_RADIUS;
  const cloudHeight = height - 100 - CIRC_RADIUS;

  // Getting number of circles based on the width of the cloud and the cloud radius size.
  const NUM_CIRCS = cloudWidth / (CIRC_RADIUS * 0.5) * 2;

  push();
  translate(width / 2, height / 2);

  // Drawing outside circles (with stroke)
  for (let i = 0; i < NUM_CIRCS; i++) {
    drawOuterCirc(i);
  }

  // Drawing inner circles which hide the inner stroke of the outer circles
  for (let i = 0; i < NUM_CIRCS; i++) {
    drawInnerCirc(i);
  }

  // Filling the middle with white for name
  noStroke();
  ellipse(0, 0, cloudWidth, cloudHeight);
  pop();

  function drawOuterCirc(num) {
    const angle = TWO_PI / NUM_CIRCS * num;

    const randomX = cloudWidth / 2 * cos(angle);
    const randomY = cloudHeight / 2 * sin(angle);

    push();
    translate(randomX, randomY);
    ellipse(0, 0, CIRC_RADIUS, CIRC_RADIUS);
    pop();
  }

  function drawInnerCirc(num) {
    const angle = TWO_PI / NUM_CIRCS * num;

    // * 0.99 to still show the stroke of the outer circles
    const randomX = cloudWidth / 2 * cos(angle) * 0.99;
    const randomY = cloudHeight / 2 * sin(angle) * 0.99;

    push();
    noStroke();
    translate(randomX, randomY);
    ellipse(0, 0, CIRC_RADIUS, CIRC_RADIUS);
    pop();
  }

  return [100, 100, width - 200, height - 200];
}

register(ellipseCloud, "Ellipse Cloud", "Raqbit");

// Unicode Cloud by Sergio Fernández
function unicodeCloud() {
  var size = floor(min(width, height * 2));
  textSize(size);

  var widthOfCloud = size;
  var heightOfCloud = widthOfCloud * 0.37;
  var textX = (width - widthOfCloud) / 2;
  var textY = height - (height - heightOfCloud) / 2;
  textAlign(LEFT, BASELINE);
  text("☁", textX, textY);

  return [
    textX + (widthOfCloud * 0.25),
    textY - (heightOfCloud * 0.7),
    widthOfCloud * 0.6,
    heightOfCloud * 0.6
  ];
}
register(unicodeCloud, "Unicode", "Sergio Fernández");
<commit_msg>Ellipse cloud: fix variable names<commit_after>// Edit this file to add your cloud design!

// Just write a function with a unique name like:
// function perlinNoiseCloud() {}
// and then add a line of code that "registers" it:
// register(perlinNoiseCloud, "Perlin Noise Cloud", "Daniel Shiffman");
// Here's an example below!

// Example rounded rectangle cloud
function rectangle() {
  // Draw your cloud here
  rect(50, 50, width - 100, height - 100, 50);
  // Return an internal rectangle that it is safe to draw text within. Of the
  // form [top_left, top_right, width, height]
  return [100, 100, width - 200, height - 200];
}

// Register your function with register(function, style_name, author_name)
register(rectangle, "Example", "example");

/* ------  Add your custom cloud generators below! ------ */

function ellipseCloud() {
  const circleRadius = width / 8;

  const cloudWidth = width - 100 - circleRadius;
  const cloudHeight = height - 100 - circleRadius;

  // Getting number of circles based on the width of the cloud and the cloud radius size.
  const circleAmount = cloudWidth / (circleRadius * 0.5) * 2;

  push();
  translate(width / 2, height / 2);

  // Drawing outside circles (with stroke)
  for (let i = 0; i < circleAmount; i++) {
    drawOuterCirc(i);
  }

  // Drawing inner circles which hide the inner stroke of the outer circles
  for (let i = 0; i < circleAmount; i++) {
    drawInnerCirc(i);
  }

  // Filling the middle with white for name
  noStroke();
  ellipse(0, 0, cloudWidth, cloudHeight);
  pop();

  function drawOuterCirc(num) {
    const angle = TWO_PI / circleAmount * num;

    const circleX = cloudWidth / 2 * cos(angle);
    const circleY = cloudHeight / 2 * sin(angle);

    push();
    translate(circleX, circleY);
    ellipse(0, 0, circleRadius, circleRadius);
    pop();
  }

  function drawInnerCirc(num) {
    const angle = TWO_PI / circleAmount * num;

    // * 0.99 to still show the stroke of the outer circles
    const circleX = cloudWidth / 2 * cos(angle) * 0.99;
    const circleY = cloudHeight / 2 * sin(angle) * 0.99;

    push();
    noStroke();
    translate(circleX, circleY);
    ellipse(0, 0, circleRadius, circleRadius);
    pop();
  }

  return [100, 100, width - 200, height - 200];
}

register(ellipseCloud, "Ellipse Cloud", "Raqbit");

// Unicode Cloud by Sergio Fernández
function unicodeCloud() {
  var size = floor(min(width, height * 2));
  textSize(size);

  var widthOfCloud = size;
  var heightOfCloud = widthOfCloud * 0.37;
  var textX = (width - widthOfCloud) / 2;
  var textY = height - (height - heightOfCloud) / 2;
  textAlign(LEFT, BASELINE);
  text("☁", textX, textY);

  return [
    textX + (widthOfCloud * 0.25),
    textY - (heightOfCloud * 0.7),
    widthOfCloud * 0.6,
    heightOfCloud * 0.6
  ];
}
register(unicodeCloud, "Unicode", "Sergio Fernández");
<|endoftext|>


<commit_before>
module.exports = function(context){
	var path = context.requireCordovaModule('path'),
        fs = context.requireCordovaModule('fs'),
        projectRoot = context.opts.projectRoot,
        ConfigParser = context.requireCordovaModule('cordova-lib').configparser,
        config = new ConfigParser(path.join(projectRoot, 'config.xml'));

    console.log("removing android avos notification setting...");
    var packageNames = config.android_packageName() || config.packageName();
    var targetFile = path.join(projectRoot, 'platforms', 'android', 'src', packageNames.replace(/\./g, path.sep), 'MainActivity.java');

    if(content.indexOf('com.mobishift.plugin.AVOSAndroidPushPlugin') >= 0){
    	content = content.replace('import com.mobishift.plugin.AVOSAndroidPushPlugin;\n', '')
    		.replace('if(getIntent().hasExtra("notificationUrl")){AVOSAndroidPushPlugin.setUrl(getIntent().getStringExtra("notificationUrl"));}\n', '')
    		.replace('if(intent.hasExtra("notificationUrl")){AVOSAndroidPushPlugin.setUrl(intent.getStringExtra("notificationUrl"));}\n', '');

    	fs.writeFileSync(targetFile, content);
    }
};<commit_msg>fix android hook<commit_after>
module.exports = function(context){
	var path = context.requireCordovaModule('path'),
        fs = context.requireCordovaModule('fs'),
        projectRoot = context.opts.projectRoot,
        ConfigParser = context.requireCordovaModule('cordova-lib').configparser,
        config = new ConfigParser(path.join(projectRoot, 'config.xml'));

    console.log("removing android avos notification setting...");
    var packageNames = config.android_packageName() || config.packageName();
    var targetFile = path.join(projectRoot, 'platforms', 'android', 'src', packageNames.replace(/\./g, path.sep), 'MainActivity.java');

    var content = fs.readFileSync(targetFile, {encoding: 'utf8'});
    if(content.indexOf('com.mobishift.plugin.AVOSAndroidPushPlugin') >= 0){
    	content = content.replace('import com.mobishift.plugin.AVOSAndroidPushPlugin;\n', '')
    		.replace('if(getIntent().hasExtra("notificationUrl")){AVOSAndroidPushPlugin.setUrl(getIntent().getStringExtra("notificationUrl"));}\n', '')
    		.replace('if(intent.hasExtra("notificationUrl")){AVOSAndroidPushPlugin.setUrl(intent.getStringExtra("notificationUrl"));}\n', '');

    	fs.writeFileSync(targetFile, content);
    }
};<|endoftext|>


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

/**
 * This originated from this repo https://github.com/maciejzasada/gulp-gae.
 * We do not use it directly because supported actions are
 * dev_appserver.py and appcfg.py which will require every developer to install
 * google app_engine and export its path.
 *
 * @fileoverview module that start gae server in gulp.
 */

'use strict';

var gulpUtil = require('gulp-util');
var path = require('path');
var spawn = require('child_process').spawn;
var through = require('through2');

var File = gulpUtil.File;
var PluginError = gulpUtil.PluginError;

module.exports = function(action, args, params) {
  action = action;
  args = args || [];
  params = params || {};

  var proc;

  var parseParams = function(params) {
    var p = [];
    for (var key in params) {
      var value = params[key];
      if (value === undefined) {
        // Value-less parameters.
        p.push('--' + key);
      } else {
        p.push('--' + key + '=' + value);
      }
    }

    return p;
  };

  var runScript = function(file, args, params, cb) {
    var scriptArgs = args.concat(parseParams(params));
    proc = spawn(file, scriptArgs);
    proc.stdout.pipe(process.stdout);
    proc.stderr.pipe(process.stderr);
    cb && cb();
  };

  var stopScript = function() {
    gulpUtil.log('[gulp-gae]', 'stopping script');
    proc && proc.kill('SIGHUP');
    proc = null;
    process.exit();
  };

  var bufferContents = function(file, enc, cb) {
    var appYamlPath = path.dirname(file.path);
    var shouldWait = false;

    if (action) {
      args = [appYamlPath].concat(args);
    }

    runScript(action, args, params, cb);

    process.on('SIGINT', stopScript);
    process.on('exit', stopScript);
  };

  var endStream = function(cb) {
    cb();
    return;
  };

  return through.obj(bufferContents, endStream);
};
<commit_msg>增加支持win32 平台gulp运行。<commit_after>// Copyright 2015 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * This originated from this repo https://github.com/maciejzasada/gulp-gae.
 * We do not use it directly because supported actions are
 * dev_appserver.py and appcfg.py which will require every developer to install
 * google app_engine and export its path.
 *
 * @fileoverview module that start gae server in gulp.
 */

'use strict';

var gulpUtil = require('gulp-util');
var path = require('path');
var cprocess = require('child_process');
var spawn = cprocess.spawn;
var exec = cprocess.exec;
var through = require('through2');
var os = require('os');

var File = gulpUtil.File;
var PluginError = gulpUtil.PluginError;

module.exports = function(action, args, params) {
  action = action;
  args = args || [];
  params = params || {};

  var proc;

  var parseParams = function(params) {
    var p = [];
    for (var key in params) {
      var value = params[key];
      if (value === undefined) {
        // Value-less parameters.
        p.push('--' + key);
      } else {
        p.push('--' + key + '=' + value);
      }
    }

    return p;
  };

  var runScript = function(file, args, params, cb) {
    var scriptArgs = args.concat(parseParams(params));
    if (os.platform() == 'win32') {
      proc = exec(file + " " + scriptArgs.join("  "));
    } else {
      proc = spawn(file, scriptArgs);
    }
    proc.stdout.pipe(process.stdout);
    proc.stderr.pipe(process.stderr);
    cb && cb();
  };

  var stopScript = function() {
    gulpUtil.log('[gulp-gae]', 'stopping script');
    proc && proc.kill('SIGHUP');
    proc = null;
    process.exit();
  };

  var bufferContents = function(file, enc, cb) {
    var appYamlPath = path.dirname(file.path);
    var shouldWait = false;

    if (action) {
      args = [appYamlPath].concat(args);
    }

    runScript(action, args, params, cb);

    process.on('SIGINT', stopScript);
    process.on('exit', stopScript);
  };

  var endStream = function(cb) {
    cb();
    return;
  };

  return through.obj(bufferContents, endStream);
};
<|endoftext|>


<commit_before>import * as fdc3 from 'openfin-fdc3';

export const viewChart = async function(symbol, stockName) {
  const availableApps = await fdc3.findIntent(fdc3.Intents.VIEW_CHART);
  if (availableApps && availableApps.apps) {
    const chart = availableApps.apps.find(app => app.appId === 'chart');
    if (chart) {
      await fdc3.raiseIntent(
        fdc3.Intents.VIEW_CHART,
        {
          type: 'security',
          name: code,
          id: {
            default: name
          }
        },
        chart.name
      );
    }
  }
};
<commit_msg>Renamed params<commit_after>import * as fdc3 from 'openfin-fdc3';

export const viewChart = async function(symbol, stockName) {
  const availableApps = await fdc3.findIntent(fdc3.Intents.VIEW_CHART);
  if (availableApps && availableApps.apps) {
    const chart = availableApps.apps.find(app => app.appId === 'chart');
    if (chart) {
      await fdc3.raiseIntent(
        fdc3.Intents.VIEW_CHART,
        {
          type: 'security',
          name: symbol,
          id: {
            default: stockName
          }
        },
        chart.name
      );
    }
  }
};
<|endoftext|>


<commit_before>import React from 'react';
import {AgGridReact, reactCellRendererFactory} from 'ag-grid-react';
import {Button} from 'react-bootstrap';

var StrategyControl = React.createClass({
    post(url, data) {
	$.ajax({
	    type: 'post',
	    url: url,
	    data: JSON.stringify(data),
	    contentType: "application/json"
	});
    },
    start() {
	var data = this.props.params.data;
	this.post("/strategy/start", data);
    },
    pause() {
	var data = this.props.params.data;
	this.post("/strategy/pause", data);
    },
    stop() {
	var data = this.props.params.data;
	this.post("/strategy/stop", data);
    },
    render() {
	var status = this.props.params.data.status;
	var start_disabled = true;
	var pause_disabled = true;
	var stop_disabled = true;
	console.log(this.props.params);
	if (status == undefined || status == "stopped" || start == "error") {
	    start_disabled = false;
	} else if (status == "paused") {
	    start_disabled = false;
	} else if (status == "running") {
	    pause_disabled = false;
	    stop_disabled = false;
	}
	return (

		<Button onClick={this.start}
	    disabled={start_disabled}>Start</Button>
		<Button onClick={this.pause}
	    disabled={pause_disabled}>Pause</Button>
		<Button onClick={this.stop}
	    disabled={stop_disabled}>Stop</Button>

	);
    }
});

var SampleUi = React.createClass({
    getInitialState() {
	return {
	    counter:0,
	    columnDefs: [
		{headerName: "Id",
		 field: "id"},
		{headerName: "Status",
		 field: "status"},
		{headerName: "Product",
		 field: "product",
		 editable: true },
		{headerName: "Parameter",
		 field: "param1",
		 editable: true },
		{headerName: "Log",
		 field: "log",
		 cellRenderer: function(params) {
		     return "Log";
		 }},
		{headerName: "Actions",
		 field: "start",
		 cellRenderer: reactCellRendererFactory(StrategyControl)
		}],
	    rowData: []
	};
    },
    // in onGridReady, store the api for later use
    componentWillReceiveProps(newprops) {
	if (newprops.status['sample'] == undefined) {
	    return;
	}
	var r = this.state.rowData;
	console.log(r);
	console.log(newprops.status['sample']);
	for(var i=0; i < r.length; i++) {
	    if (newprops.status['sample'][r[i]['id']] != undefined) {
		r[i]['status'] = newprops.status['sample'][r[i]['id']];
	    }
	}
	this.setState({rowData: r});
    },
    onGridReady(params) {
	this.api = params.api;
	this.columnApi = params.columnApi;
    },
    addRow() {
	var r = this.state.rowData;
	var c = this.state.counter;
	c = c+1;
	r.push({id: c,
		status: "stopped",
		strategy: "sample"});
	this.setState({rowData: r,
		       counter: c});
	this.api.setRowData(r);
    },
    status() {
    },
    render() {
	return (

		<Button onClick={this.addRow}>Add Row</Button>
	<AgGridReact
	    // column definitions and row data are immutable, the grid
	    // will update when these lists change
	    columnDefs={this.state.columnDefs}
	    rowData={this.state.rowData}
	    onGridReady={this.onGridReady}
		/>

	)
    }
});

module.exports = SampleUi;
<commit_msg>fix typo<commit_after>import React from 'react';
import {AgGridReact, reactCellRendererFactory} from 'ag-grid-react';
import {Button} from 'react-bootstrap';

var StrategyControl = React.createClass({
    post(url, data) {
	$.ajax({
	    type: 'post',
	    url: url,
	    data: JSON.stringify(data),
	    contentType: "application/json"
	});
    },
    start() {
	var data = this.props.params.data;
	this.post("/strategy/start", data);
    },
    pause() {
	var data = this.props.params.data;
	this.post("/strategy/pause", data);
    },
    stop() {
	var data = this.props.params.data;
	this.post("/strategy/stop", data);
    },
    render() {
	var status = this.props.params.data.status;
	var start_disabled = true;
	var pause_disabled = true;
	var stop_disabled = true;
	console.log(this.props.params);
	if (status == undefined || status == "stopped" || status == "error") {
	    start_disabled = false;
	} else if (status == "paused") {
	    start_disabled = false;
	} else if (status == "running") {
	    pause_disabled = false;
	    stop_disabled = false;
	}
	return (

		<Button onClick={this.start}
	    disabled={start_disabled}>Start</Button>
		<Button onClick={this.pause}
	    disabled={pause_disabled}>Pause</Button>
		<Button onClick={this.stop}
	    disabled={stop_disabled}>Stop</Button>

	);
    }
});

var SampleUi = React.createClass({
    getInitialState() {
	return {
	    counter:0,
	    columnDefs: [
		{headerName: "Id",
		 field: "id"},
		{headerName: "Status",
		 field: "status"},
		{headerName: "Product",
		 field: "product",
		 editable: true },
		{headerName: "Parameter",
		 field: "param1",
		 editable: true },
		{headerName: "Log",
		 field: "log",
		 cellRenderer: function(params) {
		     return "Log";
		 }},
		{headerName: "Actions",
		 field: "start",
		 cellRenderer: reactCellRendererFactory(StrategyControl)
		}],
	    rowData: []
	};
    },
    // in onGridReady, store the api for later use
    componentWillReceiveProps(newprops) {
	if (newprops.status['sample'] == undefined) {
	    return;
	}
	var r = this.state.rowData;
	console.log(r);
	console.log(newprops.status['sample']);
	for(var i=0; i < r.length; i++) {
	    if (newprops.status['sample'][r[i]['id']] != undefined) {
		r[i]['status'] = newprops.status['sample'][r[i]['id']];
	    }
	}
	this.setState({rowData: r});
    },
    onGridReady(params) {
	this.api = params.api;
	this.columnApi = params.columnApi;
    },
    addRow() {
	var r = this.state.rowData;
	var c = this.state.counter;
	c = c+1;
	r.push({id: c,
		status: "stopped",
		strategy: "sample"});
	this.setState({rowData: r,
		       counter: c});
	this.api.setRowData(r);
    },
    status() {
    },
    render() {
	return (

		<Button onClick={this.addRow}>Add Row</Button>
	<AgGridReact
	    // column definitions and row data are immutable, the grid
	    // will update when these lists change
	    columnDefs={this.state.columnDefs}
	    rowData={this.state.rowData}
	    onGridReady={this.onGridReady}
		/>

	)
    }
});

module.exports = SampleUi;
<|endoftext|>


<commit_before>import React from 'react';

class MoonScene extends React.Component {
  constructor(props) {
    super(props);
  }

  render () {
    return (

    );
  }
};

module.exports = MoonScene;
<commit_msg>Add more contrast to lunar lighting<commit_after>import React from 'react';

class MoonScene extends React.Component {
  constructor(props) {
    super(props);
  }

  render () {
    return (

    );
  }
};

module.exports = MoonScene;
<|endoftext|>


<commit_before>console.log('basic statements');
var b = 7;
if (b === 5) {
	console.log('b is 5 in if');
} else if (b < 5) {
	console.log('b is less than 5');
} else {
	console.log('b is greater than 5');
}

switch (b) {
case 4:
	console.log('b is 4');
	break;
case 5:
	console.log('b is 5');
	break;
default:
	console.log('b is nothing I understand');
	break;
}

for (var i = 0; i < 10; i = i + 1) {
	console.log(i);
}

console.log(i);
i = 0;
while (i < 10) {
	console.log(i);
	i = i + 1;
}

var d = 5;
do {
	console.log(d);
	d = d + 1;
}while (d < 3);<commit_msg>Updated basic statement<commit_after>console.log('basic statements');
var b = 7;
if (b === 5) {
	console.log('b is 5 in if');
} else if (b < 5) {
	console.log('b is less than 5');
} else {
	console.log('b is greater than 5');
}

switch (b) {
case 4:
	console.log('b is 4');
	break;
case 5:
	console.log('b is 5');
	break;
default:
	console.log('b is nothing I understand');
	break;
}

for (var i = 0; i < 10; i = i + 1) {
	console.log(i);
}

console.log(i);
i = 0;

while (i < 10) {
	console.log(i);
	i = i + 1;
}

var d = 5;
do {
	console.log(d);
	d = d + 1;
} while (d < 3);<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { browserHistory } from 'react-router';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { notification } from 'antd';
import client from 'api/client';
import { OrganizationDetailsForm } from 'components';
import { actions } from '../reducers/organizations/actions';

class OrganizationPage extends Component {
  componentDidMount() {
    const { mode } = this.props;
    if(mode === 'edit' || mode === 'view'){
      if(!this.props.params.organizationKey) {
        notification.error('Organization key not found...');
        browserHistory('/organizations');
        return;
      }
      this.props.actions.getOrganization(this.props.params.organizationKey);
    }
  }

  save(organization) {
    client.createOrganization(organization).then(() => {
      browserHistory.push('/organizations');
    });
  }

  render() {
    return (
      <main class="container">
        <OrganizationDetailsForm onSave={this.save} organization={this.props.organization} />
      </main>
    );
  }
}

OrganizationPage.propTypes = {};
OrganizationPage.defaultProps = {};

const mapStateToProps = (state) => ({
  organization: state.organization,
});

const mapDispatchToProps = (dispatch) => ({
  actions: bindActionCreators(actions, dispatch)
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(OrganizationPage);
<commit_msg>Reset Organization form when creation an Org<commit_after>import React, { Component } from 'react';
import { browserHistory } from 'react-router';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { notification } from 'antd';
import client from 'api/client';
import { OrganizationDetailsForm } from 'components';
import { actions } from '../reducers/organizations/actions';

class OrganizationPage extends Component {
  componentDidMount() {
    const { mode } = this.props;
    if(mode === 'edit' || mode === 'view'){
      if(!this.props.params.organizationKey) {
        notification.error('Organization key not found...');
        browserHistory('/organizations');
        return;
      }
      this.props.actions.getOrganization(this.props.params.organizationKey);
    }

    if(mode === 'create') {
      this.props.actions.getOrganization(null);
    }
  }

  save(organization) {
    client.createOrganization(organization).then(() => {
      browserHistory.push('/organizations');
    });
  }

  render() {
    return (
      <main class="container">
        <OrganizationDetailsForm onSave={this.save} organization={this.props.organization} />
      </main>
    );
  }
}

OrganizationPage.propTypes = {};
OrganizationPage.defaultProps = {};

const mapStateToProps = (state) => ({
  organization: state.organization,
});

const mapDispatchToProps = (dispatch) => ({
  actions: bindActionCreators(actions, dispatch)
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(OrganizationPage);
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {withRouter} from 'react-router';
import {connect} from 'react-redux';
import AppBarMain from '../components/AppBarMain';
import Paper from 'material-ui/Paper';
import StarRating from '../components/starRating';
import RaisedButton from 'material-ui/RaisedButton';
import {indigo, white, red} from './apecConnectTheme';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
import Logo from '../common/assets/APEC-CONNECT-LOGO.svg';
import {Link} from 'react-router';
import actions from 'state/actions';
import TextField from 'material-ui/TextField';
import Background from '../common/assets/bg-bottom-alpha-60.png';
import FontIcon from 'material-ui/FontIcon';
import Immutable from 'immutable';
import EconomyFlag, {ApecEconomyCodes} from '../components/EconomyFlag';
import CircularProgress from 'material-ui/CircularProgress';

/***`

This is the basic elements for a main view in the app.

***/

const paperStyle = {
  padding: '5px',
  textAlign: 'center',
  height: '100vh',
  overflow: 'hidden',
};

const divStyle = {
  height: '100%',
  backgroundSize: 'cover',
  position: 'relative',
};

const textStyle = {
  width: '75%',
  margin: '0 auto',
  position: 'relative',
  fontWeight: 'bold',
  display: 'block',
};

const logoStyle = {
  width: '100%',
  maxHeight: '150px'
};

const btnStyle = {
  width: '100%',
  fontSize: '20px',
  verticalAlign: 'middle',
};

const signUpBtnStyle = {
  width: '100%',
  fontSize: '40px',
  height: '60px',
};

const signUpLblStyle = {
  verticalAlign: 'middle',
  textAlign: 'center',
  lineHeight: '50px',
  fontSize: '35px',
};

const textFieldStyle = {
  position: 'relative',
};

const textOrStyle = {
  marginBottom: '-22px',
};

const spinnerContainerStyle = {
  textAlign: 'center'
};

@withRouter
@connect((state) => {
  return {
    dispatch: state.dispatch,
    authentication: state.authentication,
    participant: state.participant
  };
})

/**
 * Responsible for the rendering and actions on Sign Up screen.
 */
export default class SignUpScreen extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      participant: {
        businessName: '',
        email: '',
        phone: '',
        economy: 'VN'
      },
      validationErrors: {}
    };
  }

  /**
   * On next props update, check the log in status.
   * TODO: handle sign up error message here and also determine participant sign-in status.
   */
  componentWillReceiveProps(nextProps) {
    if (!nextProps.participant.isFetching && nextProps.participant.accountStatus === 'Enabled') {
      nextProps.router.push('/home');
    } else if (!nextProps.participant.isFetching && !nextProps.participant.accountStatus !== 'Enabled') {
      this.setState({message: 'Please sign up later.'});
    }
  }

  onParticipantInfoChange = (participantInfo) => {
    let nextParticipant = Object.assign({}, this.state.participant, participantInfo);
    this.setState(Object.assign({}, this.state, {participant: nextParticipant}));
  }

  onEconomyChange = (event, key, payload) => {
    let nextParticipant = Object.assign({}, this.state.participant, {economy: payload});
    this.setState({
      participant: nextParticipant
    });
  }

  economies = () => Immutable.List(ApecEconomyCodes).map((code) =>
    <MenuItem key={code} value={code} primaryText={<EconomyFlag economyCode={code} /> {code}} />
  );

  handleSignUp = () => {
    let {participant, validationErrors} = this.state;
    let nextValidationErrors = {};

    if (participant.businessName === '') {
      nextValidationErrors.businessName = 'Please enter your business name.';
    }
    else {
      nextValidationErrors.businessName = null;
    }

    this.setState({
      validationErrors: nextValidationErrors
    });

    if (!Immutable.fromJS(nextValidationErrors).find((error) => error)) {
      this.props.dispatch(actions.signUp(this.state.participant));
    }
  }

  buttonOrSpinner = () => {
    if(this.props.authentication.loading) {
      return
 <CircularProgress />
;
    } else {
      return <RaisedButton labelStyle={signUpLblStyle} style={signUpBtnStyle} label='Sign Up Now' onTouchTap={() => this.handleSignUp()} backgroundColor={red} labelColor={white}/>;
    }
  }

  render() {
    let {participant, validationErrors} = this.state;

    return (

        <Paper zDepth={1} style={paperStyle}>

                <TextField
                  hintText='Business Name'
                  errorText={validationErrors.businessName}
                  floatingLabelText='Business Name'
                  onChange={(event) => this.onParticipantInfoChange({businessName: event.target.value})}
                  value={participant.businessName}
                  style={{flex: '1'}}
                />
                <SelectField
                  value={participant.economy}
                  onChange={this.onEconomyChange}
                  style={{width: '90px'}}
                >
                  {this.economies()}
                </SelectField>

                AND

              <TextField style={textFieldStyle} hintText="Email Address" floatingLabelText="Email Address" type="email" onChange={(event) => this.onParticipantInfoChange({email: event.target.value})} value={participant.email}/>

                OR

              <TextField style={textFieldStyle} hintText="Mobile Phone Number" floatingLabelText="Mobile Phone Number" type="tel" onChange={(event) => this.onParticipantInfoChange({phone: event.target.value})} value={participant.phone}/>

                OR

              <RaisedButton
                style={btnStyle}

                primary={true}
                icon={

                  <FontIcon className='fa fa-google-plus fa-fw' color={white}/>
                  <FontIcon className='fa fa-facebook-official fa-fw' color={white}/>
                  <FontIcon className='fa fa-twitter fa-fw' color={white}/>

                  }
                />

            {this.buttonOrSpinner()}

        </Paper>

    );
  }
}
<commit_msg>APEC-36 = align fonts in buttons<commit_after>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {withRouter} from 'react-router';
import {connect} from 'react-redux';
import AppBarMain from '../components/AppBarMain';
import Paper from 'material-ui/Paper';
import StarRating from '../components/starRating';
import RaisedButton from 'material-ui/RaisedButton';
import {indigo, white, red} from './apecConnectTheme';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
import Logo from '../common/assets/APEC-CONNECT-LOGO.svg';
import {Link} from 'react-router';
import actions from 'state/actions';
import TextField from 'material-ui/TextField';
import Background from '../common/assets/bg-bottom-alpha-60.png';
import FontIcon from 'material-ui/FontIcon';
import Immutable from 'immutable';
import EconomyFlag, {ApecEconomyCodes} from '../components/EconomyFlag';
import CircularProgress from 'material-ui/CircularProgress';

/***`

This is the basic elements for a main view in the app.

***/

const paperStyle = {
  padding: '5px',
  textAlign: 'center',
  height: '100vh',
  overflow: 'hidden',
};

const divStyle = {
  height: '100%',
  backgroundSize: 'cover',
  position: 'relative',
};

const textStyle = {
  width: '75%',
  margin: '0 auto',
  position: 'relative',
  fontWeight: 'bold',
  display: 'block',
};

const logoStyle = {
  width: '100%',
  maxHeight: '150px'
};

const btnStyle = {
  width: '100%',
  fontSize: '20px',
  verticalAlign: 'middle',
};

const signUpBtnStyle = {
  width: '100%',
  fontSize: '40px',
  height: '60px',
};

const signUpLblStyle = {
  verticalAlign: 'middle',
  textAlign: 'center',
  lineHeight: '60px',
  fontSize: '35px',
};

const textFieldStyle = {
  position: 'relative',
};

const textOrStyle = {
  marginBottom: '-22px',
};

const spinnerContainerStyle = {
  textAlign: 'center'
};

@withRouter
@connect((state) => {
  return {
    dispatch: state.dispatch,
    authentication: state.authentication,
    participant: state.participant
  };
})

/**
 * Responsible for the rendering and actions on Sign Up screen.
 */
export default class SignUpScreen extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      participant: {
        businessName: '',
        email: '',
        phone: '',
        economy: 'VN'
      },
      validationErrors: {}
    };
  }

  /**
   * On next props update, check the log in status.
   * TODO: handle sign up error message here and also determine participant sign-in status.
   */
  componentWillReceiveProps(nextProps) {
    if (!nextProps.participant.isFetching && nextProps.participant.accountStatus === 'Enabled') {
      nextProps.router.push('/home');
    } else if (!nextProps.participant.isFetching && !nextProps.participant.accountStatus !== 'Enabled') {
      this.setState({message: 'Please sign up later.'});
    }
  }

  onParticipantInfoChange = (participantInfo) => {
    let nextParticipant = Object.assign({}, this.state.participant, participantInfo);
    this.setState(Object.assign({}, this.state, {participant: nextParticipant}));
  }

  onEconomyChange = (event, key, payload) => {
    let nextParticipant = Object.assign({}, this.state.participant, {economy: payload});
    this.setState({
      participant: nextParticipant
    });
  }

  economies = () => Immutable.List(ApecEconomyCodes).map((code) =>
    <MenuItem key={code} value={code} primaryText={<EconomyFlag economyCode={code} /> {code}} />
  );

  handleSignUp = () => {
    let {participant, validationErrors} = this.state;
    let nextValidationErrors = {};

    if (participant.businessName === '') {
      nextValidationErrors.businessName = 'Please enter your business name.';
    }
    else {
      nextValidationErrors.businessName = null;
    }

    this.setState({
      validationErrors: nextValidationErrors
    });

    if (!Immutable.fromJS(nextValidationErrors).find((error) => error)) {
      this.props.dispatch(actions.signUp(this.state.participant));
    }
  }

  buttonOrSpinner = () => {
    if(this.props.authentication.loading) {
      return
 <CircularProgress />
;
    } else {
      return <RaisedButton labelStyle={signUpLblStyle} style={signUpBtnStyle} label='Sign Up Now' onTouchTap={() => this.handleSignUp()} backgroundColor={red} labelColor={white}/>;
    }
  }

  render() {
    let {participant, validationErrors} = this.state;

    return (

        <Paper zDepth={1} style={paperStyle}>

                <TextField
                  hintText='Business Name'
                  errorText={validationErrors.businessName}
                  floatingLabelText='Business Name'
                  onChange={(event) => this.onParticipantInfoChange({businessName: event.target.value})}
                  value={participant.businessName}
                  style={{flex: '1'}}
                />
                <SelectField
                  value={participant.economy}
                  onChange={this.onEconomyChange}
                  style={{width: '90px'}}
                >
                  {this.economies()}
                </SelectField>

                AND

              <TextField style={textFieldStyle} hintText="Email Address" floatingLabelText="Email Address" type="email" onChange={(event) => this.onParticipantInfoChange({email: event.target.value})} value={participant.email}/>

                OR

              <TextField style={textFieldStyle} hintText="Mobile Phone Number" floatingLabelText="Mobile Phone Number" type="tel" onChange={(event) => this.onParticipantInfoChange({phone: event.target.value})} value={participant.phone}/>

                OR

              <RaisedButton
                style={btnStyle}

                primary={true}
                icon={

                  <FontIcon className='fa fa-google-plus fa-fw' color={white}/>
                  <FontIcon className='fa fa-facebook-official fa-fw' color={white}/>
                  <FontIcon className='fa fa-twitter fa-fw' color={white}/>

                  }
                />

            {this.buttonOrSpinner()}

        </Paper>

    );
  }
}
<|endoftext|>


<commit_before>Template.frontFootage.onRendered(function () {
  videojs("front-footage-vid").ready(function(){
    frontFootagePlayer = this;

    Tracker.autorun(function fControlToggle() {
      var status = Meteor.user().profile.status.fStatus;
      if ( status ) { frontFootagePlayer.pause(); }
      else { frontFootagePlayer.play(); }
    });

    Tracker.autorun(function fControlGoto() {
      var goTo = Meteor.user().profile.status.fCurrentTime;
      frontFootagePlayer.currentTime(goTo);
    });

  });
});

Template.rearFootage.onRendered(function () {
  videojs("rear-footage-vid").ready(function(){
    rearFootagePlayer = this;

    Tracker.autorun(function fControlToggle() {
      var status = Meteor.user().profile.status.fStatus;
      if ( status ) { rearFootagePlayer.pause(); }
      else { rearFootagePlayer.play(); }
    });

    Tracker.autorun(function fControlGoto() {
      var goTo = Meteor.user().profile.status.fCurrentTime;
      rearFootagePlayer.currentTime(goTo);
    });

  });
});
Template.leftFootage.onRendered(function () {
  videojs("left-footage-vid").ready(function(){
    leftFootagePlayer = this;

    Tracker.autorun(function fControlToggle() {
      var status = Meteor.user().profile.status.fStatus;
      if ( status ) { leftFootagePlayer.pause(); }
      else { leftFootagePlayer.play(); }
    });

    Tracker.autorun(function fControlGoto() {
      var goTo = Meteor.user().profile.status.fCurrentTime;
      leftFootagePlayer.currentTime(goTo);
    });

  });
});
Template.rightFootage.onRendered(function () {
  videojs("right-footage-vid").ready(function(){
    rightFootagePlayer = this;

    Tracker.autorun(function fControlToggle() {
      var status = Meteor.user().profile.status.fStatus;
      if ( status ) { rightFootagePlayer.pause(); }
      else { rightFootagePlayer.play(); }
    });

    Tracker.autorun(function fControlGoto() {
      var goTo = Meteor.user().profile.status.fCurrentTime;
      rightFootagePlayer.currentTime(goTo);
    });

  });
});

Template.frontFootage.helpers({
  route: function(){
    return Router.current().route.getName();
  },
  footageScenario: function(){
    var scenario = Meteor.user().profile.status.fScenario;
    var srcRoot = Meteor.user().profile.status.srcRoot;
    var scenarioSource = '<video id="front-footage-vid" autoplay loop class="video-js" preload="auto"> <source src="' + srcRoot + '/video/Valeo_Footage_Front_View_0'+ fScenario +'.webm" type="video/webm" />Your browser does not support the video tag. I suggest you upgrade your browser. </video>'
    return scenarioSource;

  },
})

Template.rearFootage.helpers({
  footageScenario: function(){
    var scenario = Meteor.user().profile.status.fScenario;
    var srcRoot = Meteor.user().profile.status.srcRoot;
    var scenarioSource = '<video id="front-footage-vid" autoplay loop class="video-js" preload="auto"> <source src="' + srcRoot + '/video/Valeo_Footage_Rear_View_0'+ fScenario +'.webm" type="video/webm" />Your browser does not support the video tag. I suggest you upgrade your browser. </video>'
    return scenarioSource;
  },
})

Template.leftFootage.helpers({
  footageScenario: function(){
    var scenario = Meteor.user().profile.status.fScenario;
    var srcRoot = Meteor.user().profile.status.srcRoot;
    var scenarioSource = '<video id="front-footage-vid" autoplay loop class="video-js" preload="auto"> <source src="' + srcRoot + '/video/Valeo_Footage_Left_View_0'+ fScenario +'.webm" type="video/webm" />Your browser does not support the video tag. I suggest you upgrade your browser. </video>'
    return scenarioSource;
  },
})

Template.rightFootage.helpers({
  footageScenario: function(){
    var scenario = Meteor.user().profile.status.fScenario;
    var srcRoot = Meteor.user().profile.status.srcRoot;
    var scenarioSource = '<video id="front-footage-vid" autoplay loop class="video-js" preload="auto"> <source src="' + srcRoot + '/video/Valeo_Footage_Right_View_0'+ fScenario +'.webm" type="video/webm" />Your browser does not support the video tag. I suggest you upgrade your browser. </video>'
    return scenarioSource;
  },
})
<commit_msg>minor changes<commit_after>Template.frontFootage.onRendered(function () {
  videojs("front-footage-vid").ready(function(){
    frontFootagePlayer = this;

    Tracker.autorun(function fControlToggle() {
      var status = Meteor.user().profile.status.fStatus;
      if ( status ) { frontFootagePlayer.pause(); }
      else { frontFootagePlayer.play(); }
    });

    Tracker.autorun(function fControlGoto() {
      var goTo = Meteor.user().profile.status.fCurrentTime;
      frontFootagePlayer.currentTime(goTo);
    });

  });
});

Template.rearFootage.onRendered(function () {
  videojs("rear-footage-vid").ready(function(){
    rearFootagePlayer = this;

    Tracker.autorun(function fControlToggle() {
      var status = Meteor.user().profile.status.fStatus;
      if ( status ) { rearFootagePlayer.pause(); }
      else { rearFootagePlayer.play(); }
    });

    Tracker.autorun(function fControlGoto() {
      var goTo = Meteor.user().profile.status.fCurrentTime;
      rearFootagePlayer.currentTime(goTo);
    });

  });
});
Template.leftFootage.onRendered(function () {
  videojs("left-footage-vid").ready(function(){
    leftFootagePlayer = this;

    Tracker.autorun(function fControlToggle() {
      var status = Meteor.user().profile.status.fStatus;
      if ( status ) { leftFootagePlayer.pause(); }
      else { leftFootagePlayer.play(); }
    });

    Tracker.autorun(function fControlGoto() {
      var goTo = Meteor.user().profile.status.fCurrentTime;
      leftFootagePlayer.currentTime(goTo);
    });

  });
});
Template.rightFootage.onRendered(function () {
  videojs("right-footage-vid").ready(function(){
    rightFootagePlayer = this;

    Tracker.autorun(function fControlToggle() {
      var status = Meteor.user().profile.status.fStatus;
      if ( status ) { rightFootagePlayer.pause(); }
      else { rightFootagePlayer.play(); }
    });

    Tracker.autorun(function fControlGoto() {
      var goTo = Meteor.user().profile.status.fCurrentTime;
      rightFootagePlayer.currentTime(goTo);
    });

  });
});

Template.frontFootage.helpers({
  route: function(){
    return Router.current().route.getName();
  },
  footageScenario: function(){
    var scenario = Meteor.user().profile.status.fScenario;
    var srcRoot = Meteor.user().profile.status.srcRoot;
    var scenarioSource = '<video id="front-footage-vid" autoplay loop class="video-js" preload="auto"> <source src="' + srcRoot + '/video/Valeo_Footage_Front_View_0'+ scenario +'.webm" type="video/webm" />Your browser does not support the video tag. I suggest you upgrade your browser. </video>'
    return scenarioSource;

  },
})

Template.rearFootage.helpers({
  footageScenario: function(){
    var scenario = Meteor.user().profile.status.fScenario;
    var srcRoot = Meteor.user().profile.status.srcRoot;
    var scenarioSource = '<video id="front-footage-vid" autoplay loop class="video-js" preload="auto"> <source src="' + srcRoot + '/video/Valeo_Footage_Rear_View_0'+ scenario +'.webm" type="video/webm" />Your browser does not support the video tag. I suggest you upgrade your browser. </video>'
    return scenarioSource;
  },
})

Template.leftFootage.helpers({
  footageScenario: function(){
    var scenario = Meteor.user().profile.status.fScenario;
    var srcRoot = Meteor.user().profile.status.srcRoot;
    var scenarioSource = '<video id="front-footage-vid" autoplay loop class="video-js" preload="auto"> <source src="' + srcRoot + '/video/Valeo_Footage_Left_View_0'+ scenario +'.webm" type="video/webm" />Your browser does not support the video tag. I suggest you upgrade your browser. </video>'
    return scenarioSource;
  },
})

Template.rightFootage.helpers({
  footageScenario: function(){
    var scenario = Meteor.user().profile.status.fScenario;
    var srcRoot = Meteor.user().profile.status.srcRoot;
    var scenarioSource = '<video id="front-footage-vid" autoplay loop class="video-js" preload="auto"> <source src="' + srcRoot + '/video/Valeo_Footage_Right_View_0'+ scenario +'.webm" type="video/webm" />Your browser does not support the video tag. I suggest you upgrade your browser. </video>'
    return scenarioSource;
  },
})
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';

import {
  CertificationLayout,
  DefaultLayout,
  GuideLayout
} from '../../src/components/layouts';
// eslint-disable-next-line max-len
import GuideNavMenu from '../../src/components/layouts/components/guide/NavMenu';

export default function layoutSelector({ element, props }) {
  const {
    location: { pathname }
  } = props;
  if (pathname === '/') {
    return (
      <DefaultLayout landingPage={true} pathname={pathname}>
        {element}
      </DefaultLayout>
    );
  }
  if (/^\/certification(\/.*)*/.test(pathname)) {
    return <CertificationLayout>{element}</CertificationLayout>;
  }
  if (/^\/guide(\/.*)*/.test(pathname)) {
    return (
      <DefaultLayout navigationMenu={<GuideNavMenu />} pathname={pathname}>
        <GuideLayout>{element}</GuideLayout>
      </DefaultLayout>
    );
  }
  if (/^\/learn(\/.*)*/.test(pathname)) {
    return (
      <DefaultLayout pathname={pathname} showFooter={false}>
        {element}
      </DefaultLayout>
    );
  }
  return <DefaultLayout pathname={pathname}>{element}</DefaultLayout>;
}

layoutSelector.propTypes = {
  element: PropTypes.any,
  location: PropTypes.objectOf({ pathname: PropTypes.string }),
  props: PropTypes.any
};
<commit_msg>fix(client): always show footer on 404 page<commit_after>import React from 'react';
import PropTypes from 'prop-types';

import {
  CertificationLayout,
  DefaultLayout,
  GuideLayout
} from '../../src/components/layouts';
// eslint-disable-next-line max-len
import GuideNavMenu from '../../src/components/layouts/components/guide/NavMenu';
import FourOhFourPage from '../../src/pages/404';

export default function layoutSelector({ element, props }) {
  const {
    location: { pathname }
  } = props;
  if (pathname === '/') {
    return (
      <DefaultLayout landingPage={true} pathname={pathname}>
        {element}
      </DefaultLayout>
    );
  }
  if (element.type === FourOhFourPage) {
    return <DefaultLayout pathname={pathname}>{element}</DefaultLayout>;
  }
  if (/^\/certification(\/.*)*/.test(pathname)) {
    return <CertificationLayout>{element}</CertificationLayout>;
  }
  if (/^\/guide(\/.*)*/.test(pathname)) {
    return (
      <DefaultLayout navigationMenu={<GuideNavMenu />} pathname={pathname}>
        <GuideLayout>{element}</GuideLayout>
      </DefaultLayout>
    );
  }
  if (/^\/learn(\/.*)*/.test(pathname)) {
    return (
      <DefaultLayout pathname={pathname} showFooter={false}>
        {element}
      </DefaultLayout>
    );
  }
  return <DefaultLayout pathname={pathname}>{element}</DefaultLayout>;
}

layoutSelector.propTypes = {
  element: PropTypes.any,
  location: PropTypes.objectOf({ pathname: PropTypes.string }),
  props: PropTypes.any
};
<|endoftext|>