<commit_before>/*
 * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var URL = {};
(function() {
    URL.buildURL = function(url) {
        return new Url(url);
    };

    function Url(url) {
        this.url = url;
        this.urlBase = '';
        this.queryParams = [];
        init(this);
    }
    Url.prototype.compile = function() {
        return reconstructURL(this.urlBase, this.queryParams);
    };
    Url.prototype.toString = function() {
        return reconstructURL(this.urlBase, this.queryParams);
    }
    Url.prototype.queryParam = function() {
        if (arguments.length === 1) {
            return getQueryParam.apply(this, arguments);
        }
        if (arguments.length === 2) {
            addQueryParam.apply(this, arguments);
            return this;
        }
    };
    Url.prototype.removeQueryParam = function() {
        removeQuery.apply(this, arguments);
        return this;
    };

    function init(expression) {
        expression.urlBase = '';
        var components = expression.url.split('?');
        expression.urlBase = components[0];
        //If there are no other components
        if (components.length === 1) {
            return;
        }
        expression.queryParams = processQueryParams(components[1] || '');
    }

    function processQueryParams(queryParamsString) {
        var components = queryParamsString.split('&');
        var params = [];
        components.forEach(function(component) {
            if (component !== '') {
                params.push(new QueryParam(component));
            }
        });
        return params;
    }

    function reconstructURL(urlBase, queryParams) {
        var params = [];
        queryParams.forEach(function(queryParam) {
            params.push(queryParam.compile());
        });
        var queryParamComponent = params.join('&');
        queryParams = (queryParamComponent === '') ? [] : [queryParamComponent];
        return [urlBase].concat(queryParams).join('?');
    }

    function addQueryParam(key, value) {
        //Check if the query param exists
        var queryParam = this.queryParam(key);
        value = (typeof value === 'QueryParam') ? value : (new QueryParam(key, value));
        //New query parameter
        if (!queryParam) {
            this.queryParams.splice(0, 0, value);
            //this.queryParams.push(value);
            return;
        }
        var indexToReplace = getQueryParamIndex(key, this.queryParams);
        if (indexToReplace < 0) {
            throw 'Could not add the query parameter with key: ' + key;
        }
        this.queryParams.splice(indexToReplace, 1);
        this.queryParams = this.queryParams.slice(0, indexToReplace).concat([value]).concat(this.queryParams.slice(indexToReplace));
    }

    function getQueryParam(key) {
        var value = null;
        this.queryParams.forEach(function(queryParam) {
            if (queryParam.key === key) {
                value = queryParam;
            }
        });
        return value;
    }

    function getQueryParamIndex(key, queryParams) {
        var index = -1;
        queryParams.forEach(function(queryParam, indexOfQueryParam) {
            if (queryParam.key === key) {
                index = indexOfQueryParam;
            }
        });
        return index;
    }

    function removeQuery(key) {
        var indexToReplace = getQueryParamIndex(key, this.queryParams);
        if (indexToReplace < 0) {
            return;
        }
        this.queryParams.splice(indexToReplace, 1);
    }

    function QueryParam() {
        var value = arguments[0];
        if (arguments.length === 2) {
            value = arguments[0] + '=' + arguments[1];
        }
        this.queryParamString = value;
        this.key = '';
        this.value = '';
        //Break up the value into a map
        initQueryParam.apply(this);
    }
    QueryParam.prototype.set = function(key, newValue) {
        if (!this.value instanceof ValueMap) {
            throw 'Cannot locate key ' + key;
        }
        this.value.set(key, newValue);
        return this;
    };
    QueryParam.prototype.get = function(key) {
        if (!this.value instanceof ValueMap) {
            throw 'Cannot locate key ' + key;
        }
        return this.value.get(key);
    };
    QueryParam.prototype.remove = function(key) {
        if (!this.value instanceof ValueMap) {
            throw 'Cannot locate key ' + key;
        }
        this.value.remove(key);
        return this;
    };
    QueryParam.prototype.compile = function() {
        return this.toString();
    };
    QueryParam.prototype.toString = function() {
        return reconstructQueryParam.apply(this);
    };

    function initQueryParam() {
        var components = this.queryParamString.split('=');
        this.key = components[0];
        var valueComponents = (components[1] || '').split(',');
        if (valueComponents.length === 1) {
            this.value = components[1];
        } else {
            this.value = new ValueMap(valueComponents);
        }
    }

    function reconstructQueryParam() {
        var value = this.value;
        if (typeof value === 'ValueMap') {
            value = value.compile();
        }
        return [this.key].concat([value]).join('=');
    }

    function ValueMap(values) {
        this.map = {};
        that = this;
        values.forEach(function(kv) {
            var components = kv.split(':');
            that.map[components[0]] = components[1];
        });
    }
    ValueMap.prototype.get = function(key) {
        return this.map[key];
    };
    ValueMap.prototype.set = function(key, value) {
        this.map[key] = value;
        return this;
    };
    ValueMap.prototype.remove = function(key) {
        if (this.map.hasOwnProperty(key)) {
            delete this.map[key];
        }
        return this;
    };
    ValueMap.prototype.compile = function() {
        return this.toString();
    };
    ValueMap.prototype.toString = function() {
        var values = [];
        var that = this;
        Object.keys(this.map).forEach(function(key) {
            values.push(key + ':' + that.map[key]);
        })
        return values.join(',');
    };
}());<commit_msg>Updated the url api to handle an edge case where the query should be removed if there is no inner query<commit_after>var URL = {};
(function() {
    URL.buildURL = function(url) {
        return new Url(url);
    };

    function Url(url) {
        this.url = url;
        this.urlBase = '';
        this.queryParams = [];
        init(this);
    }
    Url.prototype.compile = function() {
        return reconstructURL(this.urlBase, this.queryParams);
    };
    Url.prototype.toString = function() {
        return reconstructURL(this.urlBase, this.queryParams);
    }
    Url.prototype.queryParam = function() {
        if (arguments.length === 1) {
            return getQueryParam.apply(this, arguments);
        }
        if (arguments.length === 2) {
            addQueryParam.apply(this, arguments);
            return this;
        }
    };
    Url.prototype.removeQueryParam = function() {
        removeQuery.apply(this, arguments);
        return this;
    };

    function init(expression) {
        expression.urlBase = '';
        var components = expression.url.split('?');
        expression.urlBase = components[0];
        //If there are no other components
        if (components.length === 1) {
            return;
        }
        expression.queryParams = processQueryParams(components[1] || '');
    }

    function processQueryParams(queryParamsString) {
        var components = queryParamsString.split('&');
        var params = [];
        components.forEach(function(component) {
            if (component !== '') {
                params.push(new QueryParam(component));
            }
        });
        return params;
    }

    function reconstructURL(urlBase, queryParams) {
        var params = [];
        queryParams.forEach(function(queryParam) {
            params.push(queryParam.compile());
        });
        var queryParamComponent = params.join('&');
        queryParams = (queryParamComponent === '') ? [] : [queryParamComponent];
        return [urlBase].concat(queryParams).join('?');
    }

    function addQueryParam(key, value) {
        //Check if the query param exists
        var queryParam = this.queryParam(key);
        value = (typeof value === 'QueryParam') ? value : (new QueryParam(key, value));
        //New query parameter
        if (!queryParam) {
            this.queryParams.splice(0, 0, value);
            //this.queryParams.push(value);
            return;
        }
        var indexToReplace = getQueryParamIndex(key, this.queryParams);
        if (indexToReplace < 0) {
            throw 'Could not add the query parameter with key: ' + key;
        }
        this.queryParams.splice(indexToReplace, 1);
        this.queryParams = this.queryParams.slice(0, indexToReplace).concat([value]).concat(this.queryParams.slice(indexToReplace));
    }

    function getQueryParam(key) {
        var value = null;
        this.queryParams.forEach(function(queryParam) {
            if (queryParam.key === key) {
                value = queryParam;
            }
        });
        return value;
    }

    function getQueryParamIndex(key, queryParams) {
        var index = -1;
        queryParams.forEach(function(queryParam, indexOfQueryParam) {
            if (queryParam.key === key) {
                index = indexOfQueryParam;
            }
        });
        return index;
    }

    function removeQuery(key) {
        var indexToReplace = getQueryParamIndex(key, this.queryParams);
        if (indexToReplace < 0) {
            return;
        }
        this.queryParams.splice(indexToReplace, 1);
    }

    function QueryParam() {
        var value = arguments[0];
        if (arguments.length === 2) {
            value = arguments[0] + '=' + arguments[1];
        }
        this.queryParamString = value;
        this.key = '';
        this.value = '';
        //Break up the value into a map
        initQueryParam.apply(this);
    }
    QueryParam.prototype.set = function(key, newValue) {
        if (!this.value instanceof ValueMap) {
            throw 'Cannot locate key ' + key;
        }
        this.value.set(key, newValue);
        return this;
    };
    QueryParam.prototype.get = function(key) {
        if (!this.value instanceof ValueMap) {
            throw 'Cannot locate key ' + key;
        }
        return this.value.get(key);
    };
    QueryParam.prototype.remove = function(key) {
        if (!this.value instanceof ValueMap) {
            throw 'Cannot locate key ' + key;
        }
        this.value.remove(key);
        return this;
    };
    QueryParam.prototype.compile = function() {
        return this.toString();
    };
    QueryParam.prototype.toString = function() {
        return reconstructQueryParam.apply(this);
    };

    function initQueryParam() {
        var components = this.queryParamString.split('=');
        this.key = components[0];
        var valueComponents = (components[1] || '').split(',');
        if ((valueComponents.length === 1) && ((components[1] || '').indexOf(':') < 0)) {
            this.value = components[1];
        } else {
            this.value = new ValueMap(valueComponents);
        }
    }

    function reconstructQueryParam() {
        var value = this.value;
        if (this.value instanceof ValueMap) {
            value = value.compile();
        }
        if (value === '') {
            return '';
        }
        return [this.key].concat([value]).join('=');
    }

    function ValueMap(values) {
        this.map = {};
        that = this;
        values.forEach(function(kv) {
            var components = kv.split(':');
            that.map[components[0]] = components[1];
        });
    }
    ValueMap.prototype.get = function(key) {
        return this.map[key];
    };
    ValueMap.prototype.set = function(key, value) {
        this.map[key] = value;
        return this;
    };
    ValueMap.prototype.remove = function(key) {
        if (this.map.hasOwnProperty(key)) {
            delete this.map[key];
        }
        return this;
    };
    ValueMap.prototype.compile = function() {
        return this.toString();
    };
    ValueMap.prototype.toString = function() {
        var values = [];
        var that = this;
        Object.keys(this.map).forEach(function(key) {
            values.push(key + ':' + that.map[key]);
        })
        return values.join(',');
    };
}());<|endoftext|>


<commit_before>'use strict';

crop.factory('cropAreaCircle', ['cropArea', function(CropArea) {
    var CropAreaCircle = function() {
        CropArea.apply(this, arguments);

        this._boxResizeBaseSize = 25;
        this._boxResizeNormalRatio = 1;
        this._boxResizeHoverRatio = 1.2;
        this._iconMoveNormalRatio = 0.9;
        this._iconMoveHoverRatio = 1.2;

        this._boxResizeNormalSize = this._boxResizeBaseSize * this._boxResizeNormalRatio;
        this._boxResizeHoverSize = this._boxResizeBaseSize * this._boxResizeHoverRatio;

        this._posDragStartX = 0;
        this._posDragStartY = 0;
        this._posResizeStartX = 0;
        this._posResizeStartY = 0;
        this._posResizeStartSize = 0;

        this._boxResizeIsHover = false;
        this._areaIsHover = false;
        this._boxResizeIsDragging = false;
        this._areaIsDragging = false;
    };

    CropAreaCircle.prototype = new CropArea();

    CropAreaCircle.prototype.getType = function() {
        return 'circle';
    }

    CropAreaCircle.prototype._calcCirclePerimeterCoords = function(angleDegrees) {
        var hSize = this._size.w / 2;
        var angleRadians = angleDegrees * (Math.PI / 180),
            circlePerimeterX = this.getCenterPoint().x + hSize * Math.cos(angleRadians),
            circlePerimeterY = this.getCenterPoint().y + hSize * Math.sin(angleRadians);
        return [circlePerimeterX, circlePerimeterY];
    };

    CropAreaCircle.prototype._calcResizeIconCenterCoords = function() {
        return this._calcCirclePerimeterCoords(-45);
    };

    CropAreaCircle.prototype._isCoordWithinArea = function(coord) {
        return Math.sqrt((coord[0] - this.getCenterPoint().x) * (coord[0] - this.getCenterPoint().x) + (coord[1] - this.getCenterPoint().y) * (coord[1] - this.getCenterPoint().y)) < this._size.w / 2;
    };
    CropAreaCircle.prototype._isCoordWithinBoxResize = function(coord) {
        var resizeIconCenterCoords = this._calcResizeIconCenterCoords();
        var hSize = this._boxResizeHoverSize / 2;
        return (coord[0] > resizeIconCenterCoords[0] - hSize && coord[0] < resizeIconCenterCoords[0] + hSize &&
            coord[1] > resizeIconCenterCoords[1] - hSize && coord[1] < resizeIconCenterCoords[1] + hSize);
    };

    CropAreaCircle.prototype._drawArea = function(ctx, centerCoords, size) {
        ctx.arc(centerCoords.x, centerCoords.y, size.w / 2, 0, 2 * Math.PI);
    };

    CropAreaCircle.prototype.draw = function() {
        CropArea.prototype.draw.apply(this, arguments);

        // draw move icon
        var center = this.getCenterPoint();
        this._cropCanvas.drawIconMove([center.x, center.y], this._areaIsHover ? this._iconMoveHoverRatio : this._iconMoveNormalRatio);

        // draw resize cubes
        this._cropCanvas.drawIconResizeBoxNESW(this._calcResizeIconCenterCoords(), this._boxResizeBaseSize, this._boxResizeIsHover ? this._boxResizeHoverRatio : this._boxResizeNormalRatio);
    };

    CropAreaCircle.prototype.processMouseMove = function(mouseCurX, mouseCurY) {
        var cursor = 'default';
        var res = false;

        this._boxResizeIsHover = false;
        this._areaIsHover = false;

        if (this._areaIsDragging) {
            this.setCenterPointOnMove({
                x: mouseCurX - this._posDragStartX,
                y: mouseCurY - this._posDragStartY
            });
            this._areaIsHover = true;
            cursor = 'move';
            res = true;
            this._events.trigger('area-move');
        } else if (this._boxResizeIsDragging) {
            cursor = 'nesw-resize';
            var iFR, iFX, iFY;
            iFX = mouseCurX - this._posResizeStartX;
            iFY = this._posResizeStartY - mouseCurY;
            if (iFX > iFY) {
                iFR = this._posResizeStartSize.w + iFY * 2;
            } else {
                iFR = this._posResizeStartSize.w + iFX * 2;
            }

            var center = this.getCenterPoint(),
                newNO = {},
                newSE = {};

            newNO.x = this.getCenterPoint().x - iFR * 0.5;
            newSE.x = this.getCenterPoint().x + iFR * 0.5;

            newNO.y = this.getCenterPoint().y - iFR * 0.5;
            newSE.y = this.getCenterPoint().y + iFR * 0.5;

            this.CircleOnMove(newNO, newSE);
            this._boxResizeIsHover = true;
            res = true;
            this._events.trigger('area-resize');
        } else if (this._isCoordWithinBoxResize([mouseCurX, mouseCurY])) {
            cursor = 'nesw-resize';
            this._areaIsHover = false;
            this._boxResizeIsHover = true;
            res = true;
        } else if (this._isCoordWithinArea([mouseCurX, mouseCurY])) {
            cursor = 'move';
            this._areaIsHover = true;
            res = true;
        }

        //this._dontDragOutside();
        angular.element(this._ctx.canvas).css({
            'cursor': cursor
        });

        return res;
    };

    CropAreaCircle.prototype.processMouseDown = function(mouseDownX, mouseDownY) {
        if (this._isCoordWithinBoxResize([mouseDownX, mouseDownY])) {
            this._areaIsDragging = false;
            this._areaIsHover = false;
            this._boxResizeIsDragging = true;
            this._boxResizeIsHover = true;
            this._posResizeStartX = mouseDownX;
            this._posResizeStartY = mouseDownY;
            this._posResizeStartSize = this._size;
            this._events.trigger('area-resize-start');
        } else if (this._isCoordWithinArea([mouseDownX, mouseDownY])) {
            this._areaIsDragging = true;
            this._areaIsHover = true;
            this._boxResizeIsDragging = false;
            this._boxResizeIsHover = false;
            var center = this.getCenterPoint();
            this._posDragStartX = mouseDownX - center.x;
            this._posDragStartY = mouseDownY - center.y;
            this._events.trigger('area-move-start');
        }
    };

    CropAreaCircle.prototype.processMouseUp = function( /*mouseUpX, mouseUpY*/ ) {
        if (this._areaIsDragging) {
            this._areaIsDragging = false;
            this._events.trigger('area-move-end');
        }
        if (this._boxResizeIsDragging) {
            this._boxResizeIsDragging = false;
            this._events.trigger('area-resize-end');
        }
        this._areaIsHover = false;
        this._boxResizeIsHover = false;

        this._posDragStartX = 0;
        this._posDragStartY = 0;
    };

    return CropAreaCircle;
}]);
<commit_msg>Passed jsHint on crop-circle<commit_after>'use strict';

crop.factory('cropAreaCircle', ['cropArea', function(CropArea) {
    var CropAreaCircle = function() {
        CropArea.apply(this, arguments);

        this._boxResizeBaseSize = 25;
        this._boxResizeNormalRatio = 1;
        this._boxResizeHoverRatio = 1.2;
        this._iconMoveNormalRatio = 0.9;
        this._iconMoveHoverRatio = 1.2;

        this._boxResizeNormalSize = this._boxResizeBaseSize * this._boxResizeNormalRatio;
        this._boxResizeHoverSize = this._boxResizeBaseSize * this._boxResizeHoverRatio;

        this._posDragStartX = 0;
        this._posDragStartY = 0;
        this._posResizeStartX = 0;
        this._posResizeStartY = 0;
        this._posResizeStartSize = 0;

        this._boxResizeIsHover = false;
        this._areaIsHover = false;
        this._boxResizeIsDragging = false;
        this._areaIsDragging = false;
    };

    CropAreaCircle.prototype = new CropArea();

    CropAreaCircle.prototype.getType = function() {
        return 'circle';
    };

    CropAreaCircle.prototype._calcCirclePerimeterCoords = function(angleDegrees) {
        var hSize = this._size.w / 2;
        var angleRadians = angleDegrees * (Math.PI / 180),
            circlePerimeterX = this.getCenterPoint().x + hSize * Math.cos(angleRadians),
            circlePerimeterY = this.getCenterPoint().y + hSize * Math.sin(angleRadians);
        return [circlePerimeterX, circlePerimeterY];
    };

    CropAreaCircle.prototype._calcResizeIconCenterCoords = function() {
        return this._calcCirclePerimeterCoords(-45);
    };

    CropAreaCircle.prototype._isCoordWithinArea = function(coord) {
        return Math.sqrt((coord[0] - this.getCenterPoint().x) * (coord[0] - this.getCenterPoint().x) + (coord[1] - this.getCenterPoint().y) * (coord[1] - this.getCenterPoint().y)) < this._size.w / 2;
    };
    CropAreaCircle.prototype._isCoordWithinBoxResize = function(coord) {
        var resizeIconCenterCoords = this._calcResizeIconCenterCoords();
        var hSize = this._boxResizeHoverSize / 2;
        return (coord[0] > resizeIconCenterCoords[0] - hSize && coord[0] < resizeIconCenterCoords[0] + hSize &&
            coord[1] > resizeIconCenterCoords[1] - hSize && coord[1] < resizeIconCenterCoords[1] + hSize);
    };

    CropAreaCircle.prototype._drawArea = function(ctx, centerCoords, size) {
        ctx.arc(centerCoords.x, centerCoords.y, size.w / 2, 0, 2 * Math.PI);
    };

    CropAreaCircle.prototype.draw = function() {
        CropArea.prototype.draw.apply(this, arguments);

        // draw move icon
        var center = this.getCenterPoint();
        this._cropCanvas.drawIconMove([center.x, center.y], this._areaIsHover ? this._iconMoveHoverRatio : this._iconMoveNormalRatio);

        // draw resize cubes
        this._cropCanvas.drawIconResizeBoxNESW(this._calcResizeIconCenterCoords(), this._boxResizeBaseSize, this._boxResizeIsHover ? this._boxResizeHoverRatio : this._boxResizeNormalRatio);
    };

    CropAreaCircle.prototype.processMouseMove = function(mouseCurX, mouseCurY) {
        var cursor = 'default';
        var res = false;

        this._boxResizeIsHover = false;
        this._areaIsHover = false;

        if (this._areaIsDragging) {
            this.setCenterPointOnMove({
                x: mouseCurX - this._posDragStartX,
                y: mouseCurY - this._posDragStartY
            });
            this._areaIsHover = true;
            cursor = 'move';
            res = true;
            this._events.trigger('area-move');
        } else if (this._boxResizeIsDragging) {
            cursor = 'nesw-resize';
            var iFR, iFX, iFY;
            iFX = mouseCurX - this._posResizeStartX;
            iFY = this._posResizeStartY - mouseCurY;
            if (iFX > iFY) {
                iFR = this._posResizeStartSize.w + iFY * 2;
            } else {
                iFR = this._posResizeStartSize.w + iFX * 2;
            }

            var center = this.getCenterPoint(),
                newNO = {},
                newSE = {};

            newNO.x = this.getCenterPoint().x - iFR * 0.5;
            newSE.x = this.getCenterPoint().x + iFR * 0.5;

            newNO.y = this.getCenterPoint().y - iFR * 0.5;
            newSE.y = this.getCenterPoint().y + iFR * 0.5;

            this.CircleOnMove(newNO, newSE);
            this._boxResizeIsHover = true;
            res = true;
            this._events.trigger('area-resize');
        } else if (this._isCoordWithinBoxResize([mouseCurX, mouseCurY])) {
            cursor = 'nesw-resize';
            this._areaIsHover = false;
            this._boxResizeIsHover = true;
            res = true;
        } else if (this._isCoordWithinArea([mouseCurX, mouseCurY])) {
            cursor = 'move';
            this._areaIsHover = true;
            res = true;
        }

        //this._dontDragOutside();
        angular.element(this._ctx.canvas).css({
            'cursor': cursor
        });

        return res;
    };

    CropAreaCircle.prototype.processMouseDown = function(mouseDownX, mouseDownY) {
        if (this._isCoordWithinBoxResize([mouseDownX, mouseDownY])) {
            this._areaIsDragging = false;
            this._areaIsHover = false;
            this._boxResizeIsDragging = true;
            this._boxResizeIsHover = true;
            this._posResizeStartX = mouseDownX;
            this._posResizeStartY = mouseDownY;
            this._posResizeStartSize = this._size;
            this._events.trigger('area-resize-start');
        } else if (this._isCoordWithinArea([mouseDownX, mouseDownY])) {
            this._areaIsDragging = true;
            this._areaIsHover = true;
            this._boxResizeIsDragging = false;
            this._boxResizeIsHover = false;
            var center = this.getCenterPoint();
            this._posDragStartX = mouseDownX - center.x;
            this._posDragStartY = mouseDownY - center.y;
            this._events.trigger('area-move-start');
        }
    };

    CropAreaCircle.prototype.processMouseUp = function( /*mouseUpX, mouseUpY*/ ) {
        if (this._areaIsDragging) {
            this._areaIsDragging = false;
            this._events.trigger('area-move-end');
        }
        if (this._boxResizeIsDragging) {
            this._boxResizeIsDragging = false;
            this._events.trigger('area-resize-end');
        }
        this._areaIsHover = false;
        this._boxResizeIsHover = false;

        this._posDragStartX = 0;
        this._posDragStartY = 0;
    };

    return CropAreaCircle;
}]);
<|endoftext|>


<commit_before>export let database = {
  officialProducts: [
    {
      userName: 'aurelia',
      productName: 'binding',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'bootstrapper',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'dependency-injection',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'event-aggregator',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'framework',
      tutorials: [
        {
          "title": "What is Aurelia?",
          "href": "doc/article/en-US/what-is-aurelia.html",
          profiles: [ {name: 'architect', order: 1} ]
        },
        {
          "title": "Getting Started",
          "href": "doc/article/en-US/getting-started.html",
          profiles: [ {name: 'architect', order: 1} ]
        },
        {
          "title": "A Production Setup",
          "href": "doc/article/en-US/a-production-setup.html",
          profiles: [ {name: 'architect', order: 1} ]
        },
        {
          "title": "Creating Components",
          "href": "doc/article/en-US/creating-components.html",
          profiles: [ {name: 'architect', order: 1} ]
        },
        {
          "title": "Cheat Sheet",
          "href": "doc/article/en-US/cheat-sheet.html",
          profiles: [ {name: 'architect', order: 1} ]
        },
        {
          "title": "Getting Help",
          "href": "doc/article/en-US/getting-help.html",
          profiles: [ {name: 'architect', order: 1} ]
        },
        {
          "title": "Technical Benefits",
          "href": "doc/article/en-US/technical-benefits.html",
          profiles: [ {name: 'architect', order: 1} ]
        },
        {
          "title": "Business Advantages",
          "href": "doc/article/en-US/business-advantages.html",
          profiles: [ {name: 'architect', order: 1} ]
        }
      ]
    },
    {
      userName: 'aurelia',
      productName: 'history',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'history-browser',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'fetch-client',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'loader',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'loader-default',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'logging',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'logging-console',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'metadata',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'pal',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'pal-browser',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'path',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'router',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'task-queue',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'templating',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'templating-binding',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'templating-resources',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'templating-router',
      tutorials: []
    }
  ]
};
<commit_msg>chore(profiles): hookup articles filtering and ordering<commit_after>export let database = {
  officialProducts: [
    {
      userName: 'aurelia',
      productName: 'binding',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'bootstrapper',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'dependency-injection',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'event-aggregator',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'framework',
      tutorials: [
        {
          "title": "What is Aurelia?",
          "href": "doc/article/en-US/what-is-aurelia.html",
          profiles: [
            {name: 'developer', order: 1},
            {name: 'new-developer', order: 1},
            {name: 'architect', order: 1},
            {name: 'manager', order: 1}
          ]
        },
        {
          "title": "Getting Started",
          "href": "doc/article/en-US/getting-started.html",
          profiles: [
            {name: 'developer', order: 2},
            {name: 'new-developer', order: 2}
          ]
        },
        {
          "title": "A Production Setup",
          "href": "doc/article/en-US/a-production-setup.html",
          profiles: [ {name: 'developer', order: 3} ]
        },
        {
          "title": "Creating Components",
          "href": "doc/article/en-US/creating-components.html",
          profiles: [ {name: 'developer', order: 4} ]
        },
        {
          "title": "Cheat Sheet",
          "href": "doc/article/en-US/cheat-sheet.html",
          profiles: [
            {name: 'developer', order: 5},
            {name: 'new-developer', order: 3}
           ]
        },
        {
          "title": "Getting Help",
          "href": "doc/article/en-US/getting-help.html",
          profiles: [
            {name: 'developer', order: 6},
            {name: 'new-developer', order: 4}
          ]
        },
        {
          "title": "Technical Benefits",
          "href": "doc/article/en-US/technical-benefits.html",
          profiles: [
            {name: 'architect', order: 2},
            {name: 'manager', order: 2 }
          ]
        },
        {
          "title": "Business Advantages",
          "href": "doc/article/en-US/business-advantages.html",
          profiles: [
            {name: 'architect', order: 2},
            {name: 'manager', order: 2 }
          ]
        }
      ]
    },
    {
      userName: 'aurelia',
      productName: 'history',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'history-browser',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'fetch-client',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'loader',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'loader-default',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'logging',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'logging-console',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'metadata',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'pal',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'pal-browser',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'path',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'router',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'task-queue',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'templating',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'templating-binding',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'templating-resources',
      tutorials: []
    },
    {
      userName: 'aurelia',
      productName: 'templating-router',
      tutorials: []
    }
  ]
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import createReactClass from 'create-react-class';
import { FlatList, Modal, Picker, View, ViewPropTypes } from 'react-native';
import { connectStyle } from 'native-base-shoutem-theme';
import _ from 'lodash';

import computeProps from '../utils/computeProps';
import mapPropsToStyleNames from '../utils/mapPropsToStyleNames';

import { Text } from './Text';
import { Radio } from './Radio';
import { Container } from './Container';
import { ListItem } from './ListItem';
import { Button } from './Button';
import { Header } from './Header';
import { Title } from './Title';
import { Left } from './Left';
import { Right } from './Right';
import { Body } from './Body';

class PickerNB extends Component {
  static getDerivedStateFromProps(nextProps, prevState) {
    let nextDS;
    if (nextProps.children && !Array.isArray(nextProps.children)) {
      nextDS = [].concat(nextProps.children);
      // eslint-disable-next-line prefer-spread
    } else nextDS = [].concat.apply([], nextProps.children);

    const item = _.find(
      nextProps.children,
      child => child.props.value === nextProps.selectedValue
    );

    const currentLabel = prevState.currentLabel;
    const nextLabel = _.get(item, 'props.label');
    const currentDS = prevState.dataSource;

    if (currentLabel !== nextLabel) {
      return {
        currentLabel: nextLabel
      };
    }
    if (currentDS !== nextDS) {
      return {
        dataSource: nextDS
      };
    }
    return null;
  }

  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      currentLabel: this.getLabel(props),
      dataSource: this.getChildren(props.children)
    };
  }

  getInitialStyle = () => {
    return {
      picker: {
        // alignItems: 'flex-end'
      },
      pickerItem: {}
    };
  };

  getLabel(props) {
    const children = this.getChildren(props.children);
    const item = _.find(
      children,
      child => child.props.value === props.selectedValue
    );
    return _.get(item, 'props.label');
  }

  getSelectedItem() {
    return _.find(
      this.props.children,
      child => child.props.value === this.props.selectedValue
    );
  }

  getChildren = children => {
    if (children && !Array.isArray(children)) {
      return [].concat(children);
    }
    // eslint-disable-next-line prefer-spread
    const appliedChildren = [].concat.apply([], children);
    return appliedChildren;
  };

  prepareRootProps() {
    const defaultProps = {
      style: this.getInitialStyle().picker,
      itemStyle: this.getInitialStyle().pickerItem
    };

    return computeProps(this.props, defaultProps);
  }

  _setModalVisible(visible) {
    this.setState({ modalVisible: visible });
  }

  renderIcon() {
    return React.cloneElement(this.props.iosIcon, {
      style: [
        {
          fontSize: 22,
          lineHeight: 26
        },
        { ...this.props.iosIcon.props.style }
      ]
    });
  }

  renderButton() {
    const onPress = () => {
      if (this.props.enabled !== undefined && !this.props.enabled) return;
      this._setModalVisible(true);
    };
    const text = this.state.currentLabel
      ? this.state.currentLabel
      : this.props.placeholder;
    if (this.props.renderButton) {
      return this.props.renderButton({
        onPress,
        text,
        picker: this,
        selectedItem: this.getSelectedItem()
      });
    }
    return (
      <Button
        style={this.props.style}
        dark
        picker
        transparent
        onPress={onPress}
      >
        {this.state.currentLabel ? (
          <Text
            style={[this.props.textStyle]}
            note={this.props.note}
            numberOfLines={1}
            ellipsizeMode="tail"
          >
            {this.state.currentLabel}
          </Text>
        ) : (
          <Text
            style={[this.props.textStyle, this.props.placeholderStyle]}
            note={this.props.note !== false}
            numberOfLines={1}
            ellipsizeMode="tail"
          >
            {this.props.placeholder}
          </Text>
        )}
        {this.props.iosIcon === undefined ? null : this.renderIcon()}
      </Button>
    );
  }

  renderHeader() {
    return this.props.renderHeader ? (
      this.props.renderHeader(() => this._setModalVisible(false))
    ) : (
      <Header style={this.props.headerStyle}>
        <Left>
          <Button
            style={{
              shadowOffset: null,
              shadowColor: null,
              shadowRadius: null,
              shadowOpacity: null,
              marginLeft: 3,
              ...this.props.headerBackButtonStyle
            }}
            transparent
            onPress={() => {
              this._setModalVisible(false);
            }}
          >
            <Text style={this.props.headerBackButtonTextStyle}>
              {this.props.headerBackButtonText || 'Back'}
            </Text>
          </Button>
        </Left>
        <Body>
          <Title style={this.props.headerTitleStyle}>
            {this.props.iosHeader || 'Select One'}
          </Title>
        </Body>
        <Right />
      </Header>
    );
  }

  render() {
    return (
      <View ref={c => (this._root = c)}>
        {this.renderButton()}
        <Modal
          // supportedOrientations={this.props.supportedOrientations || null}
          supportedOrientations={['portrait', 'landscape']}
          animationType="slide"
          transparent={false}
          visible={this.state.modalVisible}
          onRequestClose={() => {
            this._setModalVisible(false);
          }}
        >
          <Container style={this.props.modalStyle}>
            {this.renderHeader()}
            <FlatList
              data={this.state.dataSource}
              keyExtractor={(item, index) => String(index)}
              renderItem={({ item }) => (
                <ListItem
                  selected={item.props.value === this.props.selectedValue}
                  button
                  style={this.props.itemStyle}
                  onPress={() => {
                    this._setModalVisible(false);
                    this.props.onValueChange(item.props.value);
                    this.setState({ current: item.props.label });
                  }}
                >
                  <Left>
                    <Text style={this.props.itemTextStyle}>
                      {item.props.label}
                    </Text>
                  </Left>
                  <Right>
                    {item.props.value === this.props.selectedValue ? (
                      <Radio selected />
                    ) : (
                      <Radio selected={false} />
                    )}
                  </Right>
                </ListItem>
              )}
            />
          </Container>
        </Modal>
      </View>
    );
  }
}

PickerNB.Item = createReactClass({
  render() {
    return <Picker.Item {...this.props()} />;
  }
});

PickerNB.propTypes = {
  ...ViewPropTypes,
  renderButton: PropTypes.func
};

const StyledPickerNB = connectStyle(
  'NativeBase.PickerNB',
  {},
  mapPropsToStyleNames
)(PickerNB);

export { StyledPickerNB as PickerNB };
<commit_msg>Fix #2856 (#2873)<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import createReactClass from 'create-react-class';
import { FlatList, Modal, Picker, View, ViewPropTypes } from 'react-native';
import { connectStyle } from 'native-base-shoutem-theme';
import { find, flatten, get, isArray } from 'lodash';

import computeProps from '../utils/computeProps';
import mapPropsToStyleNames from '../utils/mapPropsToStyleNames';

import { Text } from './Text';
import { Radio } from './Radio';
import { Container } from './Container';
import { ListItem } from './ListItem';
import { Button } from './Button';
import { Header } from './Header';
import { Title } from './Title';
import { Left } from './Left';
import { Right } from './Right';
import { Body } from './Body';

class PickerNB extends Component {
  static getDerivedStateFromProps(nextProps, prevState) {
    let nextDS;

    if (nextProps.children && !Array.isArray(nextProps.children)) {
      nextDS = [].concat(nextProps.children);
      // eslint-disable-next-line prefer-spread
    } else nextDS = [].concat.apply([], nextProps.children);

    let item;

    if (isArray(nextProps.children)) {
      item = find(
        flatten(nextProps.children),
        child => child.props.value === nextProps.selectedValue
      );
    } else {
      item = nextProps.children;
    }

    const currentLabel = prevState.currentLabel;
    const nextLabel = get(item, 'props.label');
    const currentDS = prevState.dataSource;

    if (currentLabel !== nextLabel) {
      return {
        currentLabel: nextLabel
      };
    }
    if (currentDS !== nextDS) {
      return {
        dataSource: nextDS
      };
    }
    return null;
  }

  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      currentLabel: this.getLabel(props),
      dataSource: this.getChildren(props.children)
    };
  }

  getInitialStyle = () => {
    return {
      picker: {
        // alignItems: 'flex-end'
      },
      pickerItem: {}
    };
  };

  getLabel(props) {
    const children = this.getChildren(props.children);
    const item = find(
      children,
      child => child.props.value === props.selectedValue
    );
    return get(item, 'props.label');
  }

  getSelectedItem() {
    return find(
      this.props.children,
      child => child.props.value === this.props.selectedValue
    );
  }

  getChildren = children => {
    if (children && !Array.isArray(children)) {
      return [].concat(children);
    }
    // eslint-disable-next-line prefer-spread
    const appliedChildren = [].concat.apply([], children);
    return appliedChildren;
  };

  prepareRootProps() {
    const defaultProps = {
      style: this.getInitialStyle().picker,
      itemStyle: this.getInitialStyle().pickerItem
    };

    return computeProps(this.props, defaultProps);
  }

  _setModalVisible(visible) {
    this.setState({ modalVisible: visible });
  }

  renderIcon() {
    return React.cloneElement(this.props.iosIcon, {
      style: [
        {
          fontSize: 22,
          lineHeight: 26
        },
        { ...this.props.iosIcon.props.style }
      ]
    });
  }

  renderButton() {
    const onPress = () => {
      if (this.props.enabled !== undefined && !this.props.enabled) return;
      this._setModalVisible(true);
    };
    const text = this.state.currentLabel
      ? this.state.currentLabel
      : this.props.placeholder;
    if (this.props.renderButton) {
      return this.props.renderButton({
        onPress,
        text,
        picker: this,
        selectedItem: this.getSelectedItem()
      });
    }
    return (
      <Button
        style={this.props.style}
        dark
        picker
        transparent
        onPress={onPress}
      >
        {this.state.currentLabel ? (
          <Text
            style={[this.props.textStyle]}
            note={this.props.note}
            numberOfLines={1}
            ellipsizeMode="tail"
          >
            {this.state.currentLabel}
          </Text>
        ) : (
          <Text
            style={[this.props.textStyle, this.props.placeholderStyle]}
            note={this.props.note !== false}
            numberOfLines={1}
            ellipsizeMode="tail"
          >
            {this.props.placeholder}
          </Text>
        )}
        {this.props.iosIcon === undefined ? null : this.renderIcon()}
      </Button>
    );
  }

  renderHeader() {
    return this.props.renderHeader ? (
      this.props.renderHeader(() => this._setModalVisible(false))
    ) : (
      <Header style={this.props.headerStyle}>
        <Left>
          <Button
            style={{
              shadowOffset: null,
              shadowColor: null,
              shadowRadius: null,
              shadowOpacity: null,
              marginLeft: 3,
              ...this.props.headerBackButtonStyle
            }}
            transparent
            onPress={() => {
              this._setModalVisible(false);
            }}
          >
            <Text style={this.props.headerBackButtonTextStyle}>
              {this.props.headerBackButtonText || 'Back'}
            </Text>
          </Button>
        </Left>
        <Body>
          <Title style={this.props.headerTitleStyle}>
            {this.props.iosHeader || 'Select One'}
          </Title>
        </Body>
        <Right />
      </Header>
    );
  }

  render() {
    return (
      <View ref={c => (this._root = c)}>
        {this.renderButton()}
        <Modal
          // supportedOrientations={this.props.supportedOrientations || null}
          supportedOrientations={['portrait', 'landscape']}
          animationType="slide"
          transparent={false}
          visible={this.state.modalVisible}
          onRequestClose={() => {
            this._setModalVisible(false);
          }}
        >
          <Container style={this.props.modalStyle}>
            {this.renderHeader()}
            <FlatList
              data={this.state.dataSource}
              keyExtractor={(item, index) => String(index)}
              renderItem={({ item }) => (
                <ListItem
                  selected={item.props.value === this.props.selectedValue}
                  button
                  style={this.props.itemStyle}
                  onPress={() => {
                    this._setModalVisible(false);
                    this.props.onValueChange(item.props.value);
                    this.setState({ current: item.props.label });
                  }}
                >
                  <Left>
                    <Text style={this.props.itemTextStyle}>
                      {item.props.label}
                    </Text>
                  </Left>
                  <Right>
                    {item.props.value === this.props.selectedValue ? (
                      <Radio selected />
                    ) : (
                      <Radio selected={false} />
                    )}
                  </Right>
                </ListItem>
              )}
            />
          </Container>
        </Modal>
      </View>
    );
  }
}

PickerNB.Item = createReactClass({
  render() {
    return <Picker.Item {...this.props()} />;
  }
});

PickerNB.propTypes = {
  ...ViewPropTypes,
  renderButton: PropTypes.func
};

const StyledPickerNB = connectStyle(
  'NativeBase.PickerNB',
  {},
  mapPropsToStyleNames
)(PickerNB);

export { StyledPickerNB as PickerNB };
<|endoftext|>


<commit_before>/**
 * LaTeX book processor. Should implement methods present in
 * gpub.book.processor.
 */
gpub.book.latex = {
  /**
   * Generate a LaTeX book!
   *
   * We assume that the options have already been generated.
   *
   * spec: A bookSpec -- i.e., a set of glift options.
   * templateString: the book template to use for the book
   * diagramType: The diagram format.
   * options: optional parameters. Including:
   *    Title: The title of the book
   *    Subtitle: Optional Subtitle
   *    Authors: Array of author names
   *    Publisher: Publisher Name
   *
   * Note: these parameters can also be specified in the spec metadata.
   */
  generate: function(spec, templateString, diagramType, options) {
    if (!spec) {
      throw new Error('Options must be defined. Was: ' + spec);
    }

    var diagramsPerPage = 2;

    var templateString = templateString || gpub.templates.latexBase;
    var diagramType = diagramType || gpub.diagrams.diagramType.GOOE

    var mgr = glift.widgets.createNoDraw(spec);
    var template = gpub.templates.parseLatexTemplate(templateString);
    var diagramTypePkg = gpub.diagrams[glift.enums.toCamelCase(diagramType)];
    var diagramTypeHeaders = diagramTypePkg.latexHeaders;

    var latexDefs = gpub.diagrams.latex;

    template.setExtraPackages(diagramTypeHeaders.packageDef())
        .setDiagramTypeDefs(diagramTypeHeaders.extraDefs())
        .setDiagramWrapperDefs(latexDefs.diagramDefs())
        .setTitleDef(this.basicTitleDef(
            'Relentless',
            'Gu Li vs Lee Sedol',
            ['Younggil An', 'David Ormerod', 'Josh Hoak'],
            'Go Game Guru'));

    var content = [];
    var diagramBuffer = []
    var chapter = 1;
    var section = 1;
    var lastPurpose = null;
    var diagramPurpose = gpub.diagrams.diagramPurpose;
    for (var i = 0; i < mgr.sgfCollection.length; i++) {
      var sgfObj = mgr.loadSgfStringSync(mgr.getSgfObj(i));
      var mt = glift.rules.movetree.getFromSgf(
          sgfObj.sgfString, sgfObj.initialPosition);
      var flattened = glift.flattener.flatten(mt, {
          nextMovesTreepath: sgfObj.nextMovesPath,
          boardRegion: sgfObj.boardRegion
      });

      var nodeData = gpub.book.NodeData.fromContext(
          mt, flattened, sgfObj.metadata, sgfObj.nextMovesPath || []);
      section = nodeData.setSectionFromCtx(mt, lastPurpose, section);
      chapter = nodeData.setChapterFromCtx(mt, lastPurpose, chapter);

      var diagram = gpub.diagrams.forPurpose(
          flattened,
          diagramType,
          gpub.book.bookFormat.LATEX,
          nodeData.purpose,
          nodeData);

      if (nodeData.purpose === diagramPurpose.SECTION_INTRO ||
          nodeData.purpose === diagramPurpose.GAME_REVIEW_CHAPTER ||
          nodeData.purpose !== lastPurpose) {
        // Flush the previous buffer centent to the page.
        content.push(gpub.book.latex.renderPage(diagramBuffer));

        diagramBuffer = [];
        diagramBuffer.push(diagram);
        content.push(gpub.book.latex.renderPage(diagramBuffer));
        diagramBuffer = [];
      } else {
        diagramBuffer.push(diagram);
        if (diagramBuffer.length === diagramsPerPage) {
          content.push(gpub.book.latex.renderPage(diagramBuffer));
          diagramBuffer = [];
        }
      }
      lastPurpose = nodeData.purpose;
    }
    return template.setContent(content.join('\n')).compile();
  },

  /**
   * Generates a basic title.
   *
   * title: title of the book as string
   * author: array of one or several authors as array af string
   * subtitle: the subtitle as string
   * publisher: the publisher as string
   *
   * Note: The LaTeX template expects the command \mainBookTitle.
   *
   * returns: filled in string.
   */
  // TODO(kashomon): Perhaps there should be a 'titles' package. Or perhaps each
  // booktype should get its own sub-package?
  basicTitleDef: function(title, subtitle, authors, publisher) {
    var strbuff = [
      '\\definecolor{light-gray}{gray}{0.55}',
      '\\newcommand*{\\mainBookTitle}{\\begingroup',
      '  \\raggedleft'
    ];
    for (var i = 0; i < authors.length; i++) {
      strbuff.push('  {\\Large ' + authors[i] + '} \\\\')
      if (i === 0) {
        strbuff.push('  \\vspace*{0.5 em}');
      } else if (i < authors.length - 1) {
        strbuff.push('  \\vspace*{0.5 em}');
      }
    }
    return strbuff.concat([
      '  \\vspace*{5 em}',
      '  {\\textcolor{light-gray}{\\Huge ' + title + '}}\\\\',
      '  \\vspace*{\\baselineskip}',
      '  {\\small \\bfseries ' + subtitle + '}\\par',
      '  \\vfill',
      '  {\\Large ' + publisher + '}\\par',
      '  \\vspace*{2\\baselineskip}',
      '\\endgroup}'
      ]).join('\n');
  },

  renderPage: function(buffer) {
    buffer.push('\\newpage');
    return buffer.join('\n');
  }
};
<commit_msg>Delete the old title code for LaTeX.<commit_after>/**
 * LaTeX book processor. Should implement methods present in
 * gpub.book.processor.
 */
gpub.book.latex = {
  /**
   * Generate a LaTeX book!
   *
   * We assume that the options have already been generated.
   *
   * spec: A bookSpec -- i.e., a set of glift options.
   * templateString: the book template to use for the book
   * diagramType: The diagram format.
   * options: optional parameters. Including:
   *    Title: The title of the book
   *    Subtitle: Optional Subtitle
   *    Authors: Array of author names
   *    Publisher: Publisher Name
   *
   * Note: these parameters can also be specified in the spec metadata.
   */
  generate: function(spec, templateString, diagramType, options) {
    if (!spec) {
      throw new Error('Options must be defined. Was: ' + spec);
    }

    var diagramsPerPage = 2;

    var templateString = templateString || gpub.templates.latexBase;
    var diagramType = diagramType || gpub.diagrams.diagramType.GOOE

    var mgr = glift.widgets.createNoDraw(spec);
    var template = gpub.templates.parseLatexTemplate(templateString);
    var diagramTypePkg = gpub.diagrams[glift.enums.toCamelCase(diagramType)];
    var diagramTypeHeaders = diagramTypePkg.latexHeaders;

    var latexDefs = gpub.diagrams.latex;

    template.setExtraPackages(diagramTypeHeaders.packageDef())
        .setDiagramTypeDefs(diagramTypeHeaders.extraDefs())
        .setDiagramWrapperDefs(latexDefs.diagramDefs())
        .setTitleDef(this.basicTitleDef(
            'Relentless',
            'Gu Li vs Lee Sedol',
            ['Younggil An', 'David Ormerod', 'Josh Hoak'],
            'Go Game Guru'));

    var content = [];
    var diagramBuffer = []
    var chapter = 1;
    var section = 1;
    var lastPurpose = null;
    var diagramPurpose = gpub.diagrams.diagramPurpose;
    for (var i = 0; i < mgr.sgfCollection.length; i++) {
      var sgfObj = mgr.loadSgfStringSync(mgr.getSgfObj(i));
      var mt = glift.rules.movetree.getFromSgf(
          sgfObj.sgfString, sgfObj.initialPosition);
      var flattened = glift.flattener.flatten(mt, {
          nextMovesTreepath: sgfObj.nextMovesPath,
          boardRegion: sgfObj.boardRegion
      });

      var nodeData = gpub.book.NodeData.fromContext(
          mt, flattened, sgfObj.metadata, sgfObj.nextMovesPath || []);
      section = nodeData.setSectionFromCtx(mt, lastPurpose, section);
      chapter = nodeData.setChapterFromCtx(mt, lastPurpose, chapter);

      var diagram = gpub.diagrams.forPurpose(
          flattened,
          diagramType,
          gpub.book.bookFormat.LATEX,
          nodeData.purpose,
          nodeData);

      if (nodeData.purpose === diagramPurpose.SECTION_INTRO ||
          nodeData.purpose === diagramPurpose.GAME_REVIEW_CHAPTER ||
          nodeData.purpose !== lastPurpose) {
        // Flush the previous buffer centent to the page.
        content.push(gpub.book.latex.renderPage(diagramBuffer));

        diagramBuffer = [];
        diagramBuffer.push(diagram);
        content.push(gpub.book.latex.renderPage(diagramBuffer));
        diagramBuffer = [];
      } else {
        diagramBuffer.push(diagram);
        if (diagramBuffer.length === diagramsPerPage) {
          content.push(gpub.book.latex.renderPage(diagramBuffer));
          diagramBuffer = [];
        }
      }
      lastPurpose = nodeData.purpose;
    }
    return template.setContent(content.join('\n')).compile();
  },

  renderPage: function(buffer) {
    buffer.push('\\newpage');
    return buffer.join('\n');
  }
};
<|endoftext|>


<commit_before>import { getUserByPageScopedId } from '../../lib/postgres';

export const isAuthorized = async (page_scoped_id) => {
  const user = await getUserByPageScopedId(page_scoped_id);

  return !!user;
};

export const showLoginMenu = async (reply) => {
  await reply({
    attachment: {
      type: 'template',
      payload: {
        template_type: 'generic',
        image_aspect_ratio: 'square',
        elements: [{
          title: 'EBudgie needs to log you',
          image_url: `${process.env.API_URL}/public/login.png`,
          subtitle: 'To see what is going on with your account you need to login first.',
          buttons: [{
            type: 'account_link',
            url: `${process.env.API_URL}/login`
          }]
        }]
      }
    }
  });
};
<commit_msg>Add logout menu<commit_after>import { getUserByPageScopedId } from '../../lib/postgres';

export const isAuthorized = async (page_scoped_id) => {
  const user = await getUserByPageScopedId(page_scoped_id);

  return !!user;
};

export const showLoginMenu = async (reply) => {
  await reply({
    attachment: {
      type: 'template',
      payload: {
        template_type: 'generic',
        image_aspect_ratio: 'square',
        elements: [{
          title: 'EBudgie needs to log you',
          image_url: `${process.env.API_URL}/public/login.png`,
          subtitle: 'To see what is going on with your account you need to login first.',
          buttons: [{
            type: 'account_link',
            url: `${process.env.API_URL}/login`
          }]
        }]
      }
    }
  });
};

export const showLogoutMenu = async (reply) => {
  await reply({
    attachment: {
      type: 'template',
      payload: {
        template_type: 'generic',
        image_aspect_ratio: 'square',
        elements: [{
          title: 'Account logout',
          image_url: `${process.env.API_URL}/public/login.png`,
          subtitle: 'Logout from EBudgie\'s account',
          buttons: [{
            type: 'account_unlink'
          }]
        }]
      }
    }
  });
};
<|endoftext|>


<commit_before>/* @flow */
import App from './App';
import BrowserHistory from 'react-history/BrowserHistory';
import React from 'react';
import { Provider as Redux, connect } from 'react-redux';
import { StaticRouter } from 'react-router';
import { setLocation } from '../../common/app/actions';

type RouterProps = {
  dispatch: () => void,
  pathname: ?string,
};

// TODO: Use ControlledRouter once it will be released.
const Router = ({ dispatch, pathname }: RouterProps) => (
  <BrowserHistory>
    {({ history, action, location }) => {
      if (location.pathname !== pathname) {
        setImmediate(() => {
          dispatch(setLocation(location));
        });
      }
      return (
        <StaticRouter
          action={action}
          blockTransitions={history.block}
          key={pathname} // github.com/yahoo/react-intl/issues/234#issuecomment-163366518
          location={location}
          onPush={history.push}
          onReplace={history.replace}
        >
          <App />
        </StaticRouter>
      );
    }}
  </BrowserHistory>
);

const ConnectedRouter = connect(state => ({
  pathname: state.app.location && state.app.location.pathname,
}))(Router);

type RootProps = {
  store: Object,
};

// We needs such Root for vanilla hot reloading.
const Root = ({ store }: RootProps) => (
  <Redux store={store}>
    <ConnectedRouter />
  </Redux>
);

export default Root;
<commit_msg>using location.pathname as key to be consistant with true location changes (#1191)<commit_after>/* @flow */
import App from './App';
import BrowserHistory from 'react-history/BrowserHistory';
import React from 'react';
import { Provider as Redux, connect } from 'react-redux';
import { StaticRouter } from 'react-router';
import { setLocation } from '../../common/app/actions';

type RouterProps = {
  dispatch: () => void,
  pathname: ?string,
};

// TODO: Use ControlledRouter once it will be released.
const Router = ({ dispatch, pathname }: RouterProps) => (
  <BrowserHistory>
    {({ history, action, location }) => {
      if (location.pathname !== pathname) {
        setImmediate(() => {
          dispatch(setLocation(location));
        });
      }
      return (
        <StaticRouter
          action={action}
          blockTransitions={history.block}
          key={location.pathname} // github.com/yahoo/react-intl/issues/234#issuecomment-163366518
          location={location}
          onPush={history.push}
          onReplace={history.replace}
        >
          <App />
        </StaticRouter>
      );
    }}
  </BrowserHistory>
);

const ConnectedRouter = connect(state => ({
  pathname: state.app.location && state.app.location.pathname,
}))(Router);

type RootProps = {
  store: Object,
};

// We needs such Root for vanilla hot reloading.
const Root = ({ store }: RootProps) => (
  <Redux store={store}>
    <ConnectedRouter />
  </Redux>
);

export default Root;
<|endoftext|>


<commit_before>(function(){
	$(".modal .spinner").css("marginTop",($(window).height()-$(".navbar").outerHeight())/2);
	loading();
	$("#map-canvas").height($(window).height()-$(".navbar").outerHeight());
	var mapOptions = {
		center: new google.maps.LatLng(-34.397, 150.644),
 		zoom: 8,
 		mapTypeControl: false
	};
	map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
	markers = [];
	schools = [];
	setInitialLocation();
	$.getJSON("//indianalearns.info/api/v1/schools?limit=999999",function(data){
		schools = data;
		setControlEvents();
	});
	function setControlEvents(){
		var control = $(".map-controls");
		control.on("change","select,input",function(){
			updateMap();
		}).on("click",".input-group-btn-vertical",function(){
			updateMap();
		}).find("[name='grade']").trigger("change")
		control.on("click",".minimize",function(e){
			var v = $(e.target).closest(".map-control");
			v.find(".minimizable").slideToggle();
			v.find(".glyphicon").toggleClass("glyphicon-plus").toggleClass("glyphicon-minus")
		});
	}
	function updateMap(){
		loading();
		clearMarkers();
		var year = $("[name=year] :selected").val(),
			grade = $("[name=grade] :selected").val(),
			score = Number($("[name=score]").val().replace("%",""))*.01,
			subject	= $("[name=subject] :selected").val();
			$.getJSON("//indianalearns.info/api/v1/reports/istep_schools_public?group=" + grade + "&year=" + year + "&limit=999999",function(data){
				var params = {
					"grade"	: grade,
				 "score"	: score,
				 "subject"	: subject
				}
				mapSchoolArray(schools,data,params);
				notLoading();
			});
	}
	function buildSchoolInfoWindow(school,test){
		return new google.maps.InfoWindow({
			content : "
" + school.name + "
"+
			"

Principal: " + school.principal_name + "
"+
			"
School Type: "+school.category + "
" +
			"
Grade " + test.group + " English / Language Arts Passing: "+Number(test.ela_percent_pass*100).toPrecision(4)+ "%
" +
			"
Grade " + test.group + " Mathematics Passing: "+Number(test.math_percent_pass*100).toPrecision(4) + "%
" +
			"
Grade " + test.group + " Combined Passing: "+Number(test.pass_both_percent*100).toPrecision(4)+ "%
" +
			"
Grades: "+school.grade_span + "

"
		});
	}
	function schoolHasGrade(school,grade){
		if(school.grade_span){
			var grades = school.grade_span.split("-");
			for(var i = 0; i < grades.length; i++){
				grades[i] = grades[i]=="KG" ? 0 : grades[i]; //map letter grades to numeric values
				grades[i] = grades[i]=="PK" ? -1 : grades[i];
				grades[i] = grades[i]=="SP" || grades[i]=="ED" ? -2 : grades[i];
				grades[i] = parseInt(grades[i]);
			}
			if(grade>=grades[0]&&grade<=grades[1]){
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}
	function clearMarkers(){
		for(var i = 0; i< markers.length; i++){
			markers[i].setMap(null);
		}
		markers = [];
	}
	function loading(){
		$("#loading-overlay").fadeIn();
	}
	function notLoading(){
		$("#loading-overlay").fadeOut();
	}
	function setInitialLocation(){
		if (navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(function(loc){
				var lat = loc.coords.latitude;
				var lng = loc.coords.longitude;
				gloc = new google.maps.LatLng(lat, lng);
				map.setCenter(gloc);
			},function(){
				showDefaultMap();
			}
			);
		} else {
			showDefaultMap();
		}
	}
	function showDefaultMap(){
		gloc = new google.maps.LatLng("39.768403", "-86.158068");
		map.setCenter(gloc);
	}
	function mapSchoolArray(schools,tests,params){
		for(var i = 0; i < schools.length; i++){ //iterate over every school
			var school = schools[i];

			if(schoolHasGrade(school,params.grade)){ // if the school has the grade level we're interested
				var schoolTest, icon;
				for(var count=0; count<tests.length; count++){ // iterate through the tests
					var test = tests[count];
					if(test["school_id"] == school.id){ // found the correct report item
						schoolTest = test;
						break;
					}
				}
				if(schoolTest){
					if(schoolTest[params.subject] > params.score){
						icon = "http://maps.google.com/mapfiles/marker_green.png";
					}else if(schoolTest[params.subject] < params.score){
						icon = "http://maps.google.com/mapfiles/marker.png";
					}else{
						icon = "http://maps.google.com/mapfiles/marker_grey.png";
					}
				}else{
					icon = "http://maps.google.com/mapfiles/marker_grey.png";
				}
				addSchoolToMap(school,icon,test);
			};
		}
	}

	function addSchoolToMap(school,icon,test){
		var loc = new google.maps.LatLng(school.lat,school.lon);
		var mark = new google.maps.Marker({
			map: map,
			position: loc,
			title: school.name,
			icon: icon
		});
		mark['infowindow'] = buildSchoolInfoWindow(school,test);
		google.maps.event.addListener(mark, 'click', function() {
			this['infowindow'].open(map,this);
		});
		markers.push(mark);
	}
}());
(function ($) {
	$('.spinner .btn:first-of-type').on('click', function() {
		$('.spinner input').val( parseInt($('.spinner input').val().replace("%",""), 10) + 5 +"%");
	});
	$('.spinner .btn:last-of-type').on('click', function() {
		$('.spinner input').val( parseInt($('.spinner input').val().replace("%",""), 10) - 5 +"%");
	});
})(jQuery);<commit_msg>fix issue if school doesn't have test results<commit_after>(function(){
	$(".modal .spinner").css("marginTop",($(window).height()-$(".navbar").outerHeight())/2);
	loading();
	$("#map-canvas").height($(window).height()-$(".navbar").outerHeight());
	var mapOptions = {
		center: new google.maps.LatLng(-34.397, 150.644),
 		zoom: 8,
 		mapTypeControl: false
	};
	map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
	markers = [];
	schools = [];
	setInitialLocation();
	$.getJSON("//indianalearns.info/api/v1/schools?limit=999999",function(data){
		schools = data;
		setControlEvents();
	});
	function setControlEvents(){
		var control = $(".map-controls");
		control.on("change","select,input",function(){
			updateMap();
		}).on("click",".input-group-btn-vertical",function(){
			updateMap();
		}).find("[name='grade']").trigger("change")
		control.on("click",".minimize",function(e){
			var v = $(e.target).closest(".map-control");
			v.find(".minimizable").slideToggle();
			v.find(".glyphicon").toggleClass("glyphicon-plus").toggleClass("glyphicon-minus")
		});
	}
	function updateMap(){
		loading();
		clearMarkers();
		var year = $("[name=year] :selected").val(),
			grade = $("[name=grade] :selected").val(),
			score = Number($("[name=score]").val().replace("%",""))*.01,
			subject	= $("[name=subject] :selected").val();
			$.getJSON("//indianalearns.info/api/v1/reports/istep_schools_public?group=" + grade + "&year=" + year + "&limit=999999",function(data){
				var params = {
					"grade"	: grade,
				 "score"	: score,
				 "subject"	: subject
				}
				mapSchoolArray(schools,data,params);
				notLoading();
			});
	}
	function buildSchoolInfoWindow(school,test){
		var testResults = test ? "
Grade " + test.group + " English / Language Arts Passing: "+Number(test.ela_percent_pass*100).toPrecision(4)+ "%
" +
			"
Grade " + test.group + " Mathematics Passing: "+Number(test.math_percent_pass*100).toPrecision(4) + "%
" +
			"
Grade " + test.group + " Combined Passing: "+Number(test.pass_both_percent*100).toPrecision(4)+ "%
" : "";
		return new google.maps.InfoWindow({
			content : "
" + school.name + "
"+
			"

Principal: " + school.principal_name + "
"+
			"
School Type: "+school.category + "
" +
			"
Grades: "+school.grade_span + "

" + testResults
		});
	}
	function schoolHasGrade(school,grade){
		if(school.grade_span){
			var grades = school.grade_span.split("-");
			for(var i = 0; i < grades.length; i++){
				grades[i] = grades[i]=="KG" ? 0 : grades[i]; //map letter grades to numeric values
				grades[i] = grades[i]=="PK" ? -1 : grades[i];
				grades[i] = grades[i]=="SP" || grades[i]=="ED" ? -2 : grades[i];
				grades[i] = parseInt(grades[i]);
			}
			if(grade>=grades[0]&&grade<=grades[1]){
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}
	function clearMarkers(){
		for(var i = 0; i< markers.length; i++){
			markers[i].setMap(null);
		}
		markers = [];
	}
	function loading(){
		$("#loading-overlay").fadeIn();
	}
	function notLoading(){
		$("#loading-overlay").fadeOut();
	}
	function setInitialLocation(){
		if (navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(function(loc){
				var lat = loc.coords.latitude;
				var lng = loc.coords.longitude;
				gloc = new google.maps.LatLng(lat, lng);
				map.setCenter(gloc);
			},function(){
				showDefaultMap();
			}
			);
		} else {
			showDefaultMap();
		}
	}
	function showDefaultMap(){
		gloc = new google.maps.LatLng("39.768403", "-86.158068");
		map.setCenter(gloc);
	}
	function mapSchoolArray(schools,tests,params){
		for(var i = 0; i < schools.length; i++){ //iterate over every school
			var school = schools[i];

			if(schoolHasGrade(school,params.grade)){ // if the school has the grade level we're interested
				var schoolTest, icon;
				for(var count=0; count<tests.length; count++){ // iterate through the tests
					var test = tests[count];
					if(test["school_id"] == school.id){ // found the correct report item
						schoolTest = test;
						break;
					}
				}
				if(schoolTest){
					if(schoolTest[params.subject] > params.score){
						icon = "http://maps.google.com/mapfiles/marker_green.png";
					}else if(schoolTest[params.subject] < params.score){
						icon = "http://maps.google.com/mapfiles/marker.png";
					}else{
						icon = "http://maps.google.com/mapfiles/marker_grey.png";
					}
				}else{
					icon = "http://maps.google.com/mapfiles/marker_grey.png";
				}
				addSchoolToMap(school,icon,test);
			};
		}
	}

	function addSchoolToMap(school,icon,test){
		var loc = new google.maps.LatLng(school.lat,school.lon);
		var mark = new google.maps.Marker({
			map: map,
			position: loc,
			title: school.name,
			icon: icon
		});
		mark['infowindow'] = buildSchoolInfoWindow(school,test);
		google.maps.event.addListener(mark, 'click', function() {
			this['infowindow'].open(map,this);
		});
		markers.push(mark);
	}
}());
(function ($) {
	$('.spinner .btn:first-of-type').on('click', function() {
		$('.spinner input').val( parseInt($('.spinner input').val().replace("%",""), 10) + 5 +"%");
	});
	$('.spinner .btn:last-of-type').on('click', function() {
		$('.spinner input').val( parseInt($('.spinner input').val().replace("%",""), 10) - 5 +"%");
	});
})(jQuery);<|endoftext|>


<commit_before>
(function ($) {
  var FavoriteWorks = null;
  var DOMElements = [];
  var selectedFavoriteWorks = [];
  var Effectsplay = [
    'uk-animation-scale-up',
    'uk-animation-slide-top-small',
    'uk-animation-slide-bottom-small',
    'uk-animation-slide-top-medium',
    'uk-animation-slide-bottom-medium',
  ];
  var HoverSelectedContentID = null;
  var HoverSelectedContentNAME = null;
  var HoverSelectedContentPOST = null;
  var Effectreverse = "uk-animation-reverse";
  var AnimationInterval = null;

  /*
  ** Initialize animation
  ** first call to animate block
  */

  var Initialize = function Initialize() {
    var ElementsHTML = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
    var FavoriteContents = arguments[1];

    FavoriteWorks = FavoriteContents;
    DOMElements = ElementsHTML;
    /*
    ** Animate the DOM element content
    ** after time out 400 ms
    */
    window.setTimeout(function(){
      ShowAnimation();

      $( '.fw-background-container' )
      .css('cursor', 'pointer')
      .mouseenter(function(){
        HoverSelectedContentID = $( this ).attr( 'id' );
        HoverSelectedContentNAME = $( this ).data( 'name' );
      })
      .mouseleave(function(){
        HoverSelectedContentID = null;
        HoverSelectedContentNAME = null;
      })
      .find('.uk-label')
      .fadeOut('fast');

    }, 400);

    /*
    ** Animate the DOM element content to infinie
    ** after 20 000 ms
    */
    AnimationInterval = window.setInterval(function () {
      ShowAnimation();
    }, 20000);
  };

  var LoadingStatus = function(){
    var element = arguments.length > 0 && arguments[ 0 ] !== undefined ? arguments[ 0 ] : null;
    var status = arguments[ 1 ];
    if (element === null) return;
    $( element )
    .find( '.loading' )
      .css({
        visibility: status
      });
  };

  /*
  ** Request thumbnail url (img or gif) with AJAX
  ** @params:
     - $key : DOM element index (int)
     - post : Post selected (object)
     - element : current DOM element for this post (DOMElement)
     - fw_background : DOM element class fw_background for this element (DOMElement)
     - callback : function callback
  ** @function: xhjq
  ** @return: callback( [post] )
  */
  var xhjq = function xhjq( $key, post, element, fw_background, callback ){
    var key = $key;
    $.ajax({
      url : post.thumbnail_url,
      method : 'GET'
    })
    .done(function(){
      window.setTimeout(function(){
        selectedEffect = Effectsplay[ Math.floor(Math.random() * Effectsplay.length) ];
        $( fw_background )
          .removeClass(Effectsplay.join(' '))
          .addClass(selectedEffect + ' ' + Effectreverse);

        $( '#name_' + key)
          .removeClass(Effectsplay.join(' '))
          .addClass(selectedEffect + ' ' + Effectreverse);

        window.setTimeout(function() {
          selectedEffect = Effectsplay[ Math.floor( Math.random() * Effectsplay.length ) ];
          $( fw_background )
          .css({
            'background-image' : "url(" + post.thumbnail_url + ")"
          })
          .removeClass(Effectsplay.join(' ') + ' ' + Effectreverse)
          .addClass( selectedEffect )
          .css('display', 'block');

          //LoadingStatus(element, "hidden");
          var animationEffect = Effectsplay[ Math.floor(Math.random() * Effectsplay.length) ];
          $( '#name_' + key )
            .removeClass(Effectsplay.join(' ') + ' ' + Effectreverse)
            .addClass(animationEffect)
            .css('display', 'block')
            .find( 'a' )
              .text( post.title )
              .attr('href', post.link);

          element.data('name', post.name);
          element.data('validate', 1);
          callback( post );

        }, 500);
      }, Math.floor(Math.random() * (3000 - 1000 + 1)) + 1000);
    });
  };

  /*
  ** Animate content in block
  ** @function ShowAnimation
  ** @params void
  ** @return void
  */
  var ShowAnimation = function Animation() {
    var currentSelected = [];
    var pull = _.concat( FavoriteWorks );
    var selected = null;
    var step = 0;

    /*
    ** Select post in random mode at currentSelected variable
    */
    _.forEach(pull, function(){
      _.pullAllWith(pull, currentSelected, _.isEqual);
      selected = pull[ Math.floor(Math.random() * pull.length) ];
      currentSelected = currentSelected.concat( selected );
    });

    /*
    ** Remove post content if a hover DOM element
    */
    _.remove(currentSelected, function( el ){
      return el.name == HoverSelectedContentNAME;
    });

    /*
    ** Loop DOM element and check if is validate for new post
    ** remove the post content in currentSelected if DOM elements validate equal 0, name post equal DOM element name
    */
    _.forEach(DOMElements, function( el ){
      var V = parseInt($( el ).data( 'validate' ));
      var Name = $( el ).data( 'name' );
      if (V == 0) {
        _.remove(currentSelected, function( element ){
          return element.name == Name;
        });
        return;
      }
    });

    /*
    ** Loop DOM elements for set new post content
    ** xhjq, Ajax function to load img or gif
    */

    _.forEach(DOMElements, function( $element, $key ){
      var thisElement = $( $element );
      var selectedEffect = '';
      var thisElementID = thisElement.attr( 'id' );
      var currentPostName = thisElement.data( 'name' );
      var keys = step;
      var fw_background = thisElement.find( '.fw-background' );
      var validation = parseInt(thisElement.data( 'validate' ));
      if (validation == 0) {
        step += 1;
        return;
      }
      if ((HoverSelectedContentID != null && currentPostName == HoverSelectedContentNAME) ||
        thisElementID == HoverSelectedContentID) {
        return;
      }
      var post = currentSelected[ keys ];
      if (typeof post == "undefined") return;
      if (post.thumbnail_url != false) {
        thisElement.data('validate', 0);
        xhjq( $key, post, thisElement, fw_background, function( post ){

        });
      } else {
        thisElement
        .find( '.fw-background' )
          .css({
            'background-image': 'none',
            'background-color': "#ffffff"
          })
        .end()
        .find( '.loading' )
          .css('visibility', 'hidden');
      }
      step += 1;
    });
  };

  $( document ).ready(function () {
    var self = this;
    var Elements = [];
    $( '.fw-background-container' ).each(function () {
      var type = $( this ).data( 'post' );
      Elements = Elements.concat( this );
    });
    if (typeof FavoriteContents === "undefined") {
      console.warn('variable: undefined variable Favorite Contents in this document');
      return;
    }
    Initialize(Elements, FavoriteContents);
  });
})(jQuery);<commit_msg>Animate bloc after 10s<commit_after>
(function ($) {
  var FavoriteWorks = null;
  var DOMElements = [];
  var selectedFavoriteWorks = [];
  var Effectsplay = [
    'uk-animation-scale-up',
    'uk-animation-slide-top-small',
    'uk-animation-slide-bottom-small',
    'uk-animation-slide-top-medium',
    'uk-animation-slide-bottom-medium',
  ];
  var HoverSelectedContentID = null;
  var HoverSelectedContentNAME = null;
  var HoverSelectedContentPOST = null;
  var Effectreverse = "uk-animation-reverse";
  var AnimationInterval = null;

  /*
  ** Initialize animation
  ** first call to animate block
  */

  var Initialize = function Initialize() {
    var ElementsHTML = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
    var FavoriteContents = arguments[1];

    FavoriteWorks = FavoriteContents;
    DOMElements = ElementsHTML;
    /*
    ** Animate the DOM element content
    ** after time out 400 ms
    */
    window.setTimeout(function(){
      ShowAnimation();

      $( '.fw-background-container' )
      .css('cursor', 'pointer')
      .mouseenter(function(){
        HoverSelectedContentID = $( this ).attr( 'id' );
        HoverSelectedContentNAME = $( this ).data( 'name' );
      })
      .mouseleave(function(){
        HoverSelectedContentID = null;
        HoverSelectedContentNAME = null;
      })
      .find('.uk-label')
      .fadeOut('fast');

    }, 400);

    /*
    ** Animate the DOM element content to infinie
    ** after 10 000 ms
    */
    AnimationInterval = window.setInterval(function () {
      ShowAnimation();
    }, 10000);
  };

  var LoadingStatus = function(){
    var element = arguments.length > 0 && arguments[ 0 ] !== undefined ? arguments[ 0 ] : null;
    var status = arguments[ 1 ];
    if (element === null) return;
    $( element )
    .find( '.loading' )
      .css({
        visibility: status
      });
  };

  /*
  ** Request thumbnail url (img or gif) with AJAX
  ** @params:
     - $key : DOM element index (int)
     - post : Post selected (object)
     - element : current DOM element for this post (DOMElement)
     - fw_background : DOM element class fw_background for this element (DOMElement)
     - callback : function callback
  ** @function: xhjq
  ** @return: callback( [post] )
  */
  var xhjq = function xhjq( $key, post, element, fw_background, callback ){
    var key = $key;
    $.ajax({
      url : post.thumbnail_url,
      method : 'GET'
    })
    .done(function(){
      window.setTimeout(function(){
        selectedEffect = Effectsplay[ Math.floor(Math.random() * Effectsplay.length) ];
        $( fw_background )
          .removeClass(Effectsplay.join(' '))
          .addClass(selectedEffect + ' ' + Effectreverse);

        $( '#name_' + key)
          .removeClass(Effectsplay.join(' '))
          .addClass(selectedEffect + ' ' + Effectreverse);

        window.setTimeout(function() {
          selectedEffect = Effectsplay[ Math.floor( Math.random() * Effectsplay.length ) ];
          $( fw_background )
          .css({
            'background-image' : "url(" + post.thumbnail_url + ")"
          })
          .removeClass(Effectsplay.join(' ') + ' ' + Effectreverse)
          .addClass( selectedEffect )
          .css('display', 'block');

          //LoadingStatus(element, "hidden");
          var animationEffect = Effectsplay[ Math.floor(Math.random() * Effectsplay.length) ];
          $( '#name_' + key )
            .removeClass(Effectsplay.join(' ') + ' ' + Effectreverse)
            .addClass(animationEffect)
            .css('display', 'block')
            .find( 'a' )
              .text( post.title )
              .attr('href', post.link);

          element.data('name', post.name);
          element.data('validate', 1);
          callback( post );

        }, 500);
      }, Math.floor(Math.random() * (3000 - 1000 + 1)) + 1000);
    });
  };

  /*
  ** Animate content in block
  ** @function ShowAnimation
  ** @params void
  ** @return void
  */
  var ShowAnimation = function Animation() {
    var currentSelected = [];
    var pull = _.concat( FavoriteWorks );
    var selected = null;
    var step = 0;

    /*
    ** Select post in random mode at currentSelected variable
    */
    _.forEach(pull, function(){
      _.pullAllWith(pull, currentSelected, _.isEqual);
      selected = pull[ Math.floor(Math.random() * pull.length) ];
      currentSelected = currentSelected.concat( selected );
    });

    /*
    ** Remove post content if a hover DOM element
    */
    _.remove(currentSelected, function( el ){
      return el.name == HoverSelectedContentNAME;
    });

    /*
    ** Loop DOM element and check if is validate for new post
    ** remove the post content in currentSelected if DOM elements validate equal 0, name post equal DOM element name
    */
    _.forEach(DOMElements, function( el ){
      var V = parseInt($( el ).data( 'validate' ));
      var Name = $( el ).data( 'name' );
      if (V == 0) {
        _.remove(currentSelected, function( element ){
          return element.name == Name;
        });
        return;
      }
    });

    /*
    ** Loop DOM elements for set new post content
    ** xhjq, Ajax function to load img or gif
    */

    _.forEach(DOMElements, function( $element, $key ){
      var thisElement = $( $element );
      var selectedEffect = '';
      var thisElementID = thisElement.attr( 'id' );
      var currentPostName = thisElement.data( 'name' );
      var keys = step;
      var fw_background = thisElement.find( '.fw-background' );
      var validation = parseInt(thisElement.data( 'validate' ));
      if (validation == 0) {
        step += 1;
        return;
      }
      if ((HoverSelectedContentID != null && currentPostName == HoverSelectedContentNAME) ||
        thisElementID == HoverSelectedContentID) {
        return;
      }
      var post = currentSelected[ keys ];
      if (typeof post == "undefined") return;
      if (post.thumbnail_url != false) {
        thisElement.data('validate', 0);
        xhjq( $key, post, thisElement, fw_background, function( post ){

        });
      } else {
        thisElement
        .find( '.fw-background' )
          .css({
            'background-image': 'none',
            'background-color': "#ffffff"
          })
        .end()
        .find( '.loading' )
          .css('visibility', 'hidden');
      }
      step += 1;
    });
  };

  $( document ).ready(function () {
    var self = this;
    var Elements = [];
    $( '.fw-background-container' ).each(function () {
      var type = $( this ).data( 'post' );
      Elements = Elements.concat( this );
    });
    if (typeof FavoriteContents === "undefined") {
      console.warn('variable: undefined variable Favorite Contents in this document');
      return;
    }
    Initialize(Elements, FavoriteContents);
  });
})(jQuery);<|endoftext|>


<commit_before>jQuery(function($){
	var edit_ta = $('div.translation');
	edit_ta.find('textarea.resizable:not(.processed)').TextAreaResizer();

	var votes = $('div.translation ul');
	votes.find('>li').mouseover(showVote);
	votes.find('>li').mouseleave(hideVote);

	function showVote(){
		$(this).addClass('voteOver');
		$(this).children('span.btn_vote').show();
		};
	function hideVote(){
		$(this).removeClass('voteOver');
	votes.find('span.btn_vote').hide();
	}

	var tBlock = $('div#t_list>div.t_item');
	var tItem = tBlock.children('div.item');

	//init
	tBlock.children('div.item:lt(1)').hide();
	tBlock.children('div.edit:gt(0)').hide();
	tBlock.children('div.item:gt(0)').show();

	// click item
	tItem.click(function(){
		var idx = tItem.index(this);
		tBlock.children('div.item').show();
		tBlock.children('div.edit').hide();
		$(this).hide();
		tBlock.eq(idx).children('div.edit').show();
	});

	var btns = tBlock.find('div.btns button');
	btns.click(function(){
		var t = $(this).parents('div.t_item');
		var idx = tBlock.index(t);
		var btn_att = btns.hasClass('btn_prev');
		//var bIdx = tItem.index(t);
		if($(this).hasClass('btn_prev')){
			acc(idx,'prev');
			return false;
		}else{
			acc(idx,'next');
			return false;
		}

	});

	btns.first().toggleClass('btn_hidden');
	btns.last().toggleClass('btn_hidden');

	var voteBts = votes.find('span.btn_vote');
	voteBts.each(function(ind, btEl){
		btEl.onclick = function(eventObj){
			var btObj = $(btEl);
			var params = [];

		    params['translation_content_srl'] = btObj.attr('data');
		    var callBack = function(){
				var recomCountObj = $(btEl).parent().find('.recomCount');
				var refreshNum = parseInt(recomCountObj.html()) + 1;
				recomCountObj.html(refreshNum);
		    };
		    exec_xml('translation','procVoteItem', params, callBack);
		}

	});

	var textAreaObj = edit_ta.find('textarea');
	var srlArr = [];
	var i = 0;
	textAreaObj.each(function(ind, taObj){
		srlArr[i] = $(taObj).attr('name');
		srlArr[i] = srlArr[i].slice(8,srlArr[i].length - 1);
		i++;
	});

	var findDicTable = function(srl){
		srl = srl || srlArr[0];
		var callBack = function(ret_obj){
			var htmlStr = ret_obj['html'];
			var dicObj = $('.dic_content_' + srl);
			if(htmlStr != ''){
				dicObj.toggleClass("glossary");
				dicObj.html(htmlStr);
			}
		};
		var params = [];
		params['translation_content_srl'] = srl;
		exec_xml('translation','procGetDicInfo', params, callBack, new Array('error','message','html'));
	}
	findDicTable();

	function acc(idx,dir){
	var tBlock = jQuery('div#t_list>div.t_item');
	var length = tBlock.length;

	switch (dir)
	{
		case 'prev':
			idx = (idx == 0)?idx=0:idx-=1;
			tBlock.children('div.item').show();
			tBlock.children('div.edit').hide();
			tBlock.eq(idx).find('div.item').hide();
			tBlock.eq(idx).find('div.edit').show();
			findDicTable(srlArr[idx]);
			return;
		case 'next':
			idx = (idx == length - 1)?idx=length - 1:idx+=1;
			tBlock.children('div.item').show();
			tBlock.children('div.edit').hide();
			tBlock.eq(idx).find('div.item').hide();
			tBlock.eq(idx).find('div.edit').show();
			findDicTable(srlArr[idx]);
			return;
		default:
	}
	return false;
}
})<commit_msg><commit_after>jQuery(function($){
	var edit_ta = $('div.translation');
	edit_ta.find('textarea.resizable:not(.processed)').TextAreaResizer();

	var votes = $('div.translation ul');
	votes.find('>li').mouseover(showVote);
	votes.find('>li').mouseleave(hideVote);

	function showVote(){
		$(this).addClass('voteOver');
		$(this).children('span.btn_vote').show();
		};
	function hideVote(){
		$(this).removeClass('voteOver');
	votes.find('span.btn_vote').hide();
	}

	var tBlock = $('div#t_list>div.t_item');
	var tItem = tBlock.children('div.item');

	//init
	tBlock.children('div.item:lt(1)').hide();
	tBlock.children('div.edit:gt(0)').hide();
	tBlock.children('div.item:gt(0)').show();

	// click item
	tItem.click(function(){
		var idx = tItem.index(this);
		tBlock.children('div.item').show();
		tBlock.children('div.edit').hide();
		$(this).hide();
		tBlock.eq(idx).children('div.edit').show();
	});

	var btns = tBlock.find('div.btns button');
	btns.click(function(){
		var t = $(this).parents('div.t_item');
		var idx = tBlock.index(t);
		var btn_att = btns.hasClass('btn_prev');
		//var bIdx = tItem.index(t);
		if($(this).hasClass('btn_prev')){
			acc(idx,'prev');
			return false;
		}else{
			acc(idx,'next');
			return false;
		}

	});

	btns.first().toggleClass('btn_hidden');
	btns.last().toggleClass('btn_hidden');

	var voteBts = votes.find('span.btn_vote');
	voteBts.each(function(ind, btEl){
		btEl.onclick = function(eventObj){
			var btObj = $(btEl);
			var params = [];

		    params['translation_content_srl'] = btObj.attr('data');
		    var callBack = function(){
		    	var recomCountObj = $(btEl).parent().find('.recomCount');
				var recomCountHtml = recomCountObj.html();
				var reg = /\D*/g;
				var countNum = recomCountHtml.replace(reg, '');
				var refreshNum = parseInt(countNum) + 1;
				var reg = /(\D*)(\d+)(\D*)/;
				refreshStr = recomCountHtml.replace(reg, '$1' + refreshNum + '$3');
				recomCountObj.html(refreshStr);
		    };
		    exec_xml('translation','procVoteItem', params, callBack);
		}

	});

	var textAreaObj = edit_ta.find('textarea');
	var srlArr = [];
	var i = 0;
	textAreaObj.each(function(ind, taObj){
		srlArr[i] = $(taObj).attr('name');
		srlArr[i] = srlArr[i].slice(8,srlArr[i].length - 1);
		i++;
	});

	var findDicTable = function(srl){
		srl = srl || srlArr[0];
		var callBack = function(ret_obj){
			var htmlStr = ret_obj['html'];
			var dicObj = $('.dic_content_' + srl);
			if(htmlStr != ''){
				dicObj.toggleClass("glossary");
				dicObj.html(htmlStr);
			}
		};
		var params = [];
		params['translation_content_srl'] = srl;
		exec_xml('translation','procGetDicInfo', params, callBack, new Array('error','message','html'));
	}
	findDicTable();

	function acc(idx,dir){
	var tBlock = jQuery('div#t_list>div.t_item');
	var length = tBlock.length;

	switch (dir)
	{
		case 'prev':
			idx = (idx == 0)?idx=0:idx-=1;
			tBlock.children('div.item').show();
			tBlock.children('div.edit').hide();
			tBlock.eq(idx).find('div.item').hide();
			tBlock.eq(idx).find('div.edit').show();
			findDicTable(srlArr[idx]);
			return;
		case 'next':
			idx = (idx == length - 1)?idx=length - 1:idx+=1;
			tBlock.children('div.item').show();
			tBlock.children('div.edit').hide();
			tBlock.eq(idx).find('div.item').hide();
			tBlock.eq(idx).find('div.edit').show();
			findDicTable(srlArr[idx]);
			return;
		default:
	}
	return false;
}
})<|endoftext|>