<commit_before>/**
 * @file Tfoot component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';

// Components
import Tf from '../_Tf';

// Statics
import TableFragment from '../_statics/TableFragment';
import HorizontalAlign from '../_statics/HorizontalAlign';
import SelectMode from '../_statics/SelectMode';
import SelectAllMode from '../_statics/SelectAllMode';
import SortingType from '../_statics/SortingType';

// Vendors
import classNames from 'classnames';
import Util from '../_vendors/Util';
import TC from '../_vendors/TableCalculation';

class Tfoot extends Component {

    static Align = HorizontalAlign;
    static SelectMode = SelectMode;
    static SelectAllMode = SelectAllMode;
    static SortingType = SortingType;

    constructor(props, ...restArgs) {
        super(props, ...restArgs);
    }

    getColumnsSpan = () => {
        const {columns, data, onRequestColumnsSpan} = this.props;
        return onRequestColumnsSpan ?
            onRequestColumnsSpan(TableFragment.FOOT, columns, data)
            :
            TC.getColumnsSpan(TableFragment.FOOT, columns, data);
    };

    handleClick = e => {
        const {data, disabled, onFootClick} = this.props;
        !disabled && onFootClick && onFootClick(data, e);
    };

    render() {

        const {
                className, data, disabled, baseColIndex, ignoreColumnSpan, scrollEl,
                onCellClick
            } = this.props,
            columnsSpan = this.getColumnsSpan();

        return (

                    {
                        columnsSpan && columnsSpan.map(({column, span}, colIndex) =>
                            <Tf key={colIndex}
                                className={column.footClassName}
                                style={column.footStyle}
                                colIndex={baseColIndex + colIndex}
                                data={data}
                                renderer={column.footRenderer}
                                align={column.footAlign || column.align}
                                span={ignoreColumnSpan ? null : span}
                                noWrap={TC.handleNoWrap(column.footNoWrap, column.noWrap, {
                                    data,
                                    rowIndex: 0,
                                    colIndex: baseColIndex + colIndex,
                                    tableData: data
                                })}
                                disabled={disabled}
                                scrollEl={scrollEl}
                                onCellClick={onCellClick}/>
                        )
                    }

        );

    }
}

Tfoot.propTypes = {

    className: PropTypes.string,

    /**
     * Children passed into table header.
     */
    columns: PropTypes.arrayOf(PropTypes.shape({

        /**
         * fixed position of column ( 'left' / 'right' ).
         */
        fixed: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * width of column.
         */
        width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),

        /**
         * minimum width of column.
         */
        minWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),

        /**
         * align of current column.
         */
        align: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * no wrap of current column.
         */
        noWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * The class name of header.
         */
        headClassName: PropTypes.string,

        /**
         * Override the styles of header.
         */
        headStyle: PropTypes.object,

        /**
         * align of table header cell
         */
        headAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * The render content in table head.
         *  (1) callback:
         *      function (tableData, colIndex) {
         *          return colIndex;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        headRenderer: PropTypes.any,

        /**
         * column span of table header.
         *  (1) function callback:
         *      function (tableData, colIndex) {
         *          return null;
         *      }
         *
         *  (2) number:
         *      render whatever you pass
         */
        headSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * no wrap of table header.
         */
        headNoWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * The class name of td.
         */
        bodyClassName: PropTypes.string,

        /**
         * Override the styles of td.
         */
        bodyStyle: PropTypes.object,

        /**
         * align of table body cell.
         */
        bodyAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * The render content in table body.
         *  (1) callback:
         *      function (rowData, rowIndex, colIndex, parentData, tableData, collapsed, depth, path) {
         *          return rowData.id;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        bodyRenderer: PropTypes.any,

        /**
         * column span of table body.
         *  (1) function callback:
         *      function (rowData, colIndex, rowIndex) {
         *          return null;
         *      }
         *
         *  (2) number:
         *      render whatever you pass
         */
        bodySpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * no wrap of table body.
         */
        bodyNoWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * The class name of footer.
         */
        footClassName: PropTypes.string,

        /**
         * Override the styles of footer.
         */
        footStyle: PropTypes.object,

        /**
         * align of table footer cell
         */
        footAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * The render content in table foot.
         *  (1) callback:
         *      function (tableData, colIndex) {
         *          return colIndex;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        footRenderer: PropTypes.any,

        /**
         * column span of table foot.
         *  (1) function callback:
         *      function (tableData, colIndex) {
         *          return null;
         *      }
         *
         *  (2) number:
         *      render whatever you pass
         */
        footSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * no wrap of table foot.
         */
        footNoWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * If true,this column can be sorted.
         */
        sortable: PropTypes.bool,

        /**
         * Sorting property.
         */
        sortingProp: PropTypes.string,

        defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType))

    })).isRequired,

    data: PropTypes.array,
    disabled: PropTypes.bool,
    baseColIndex: PropTypes.number,
    ignoreColumnSpan: PropTypes.bool,
    scrollEl: PropTypes.object,

    onFootClick: PropTypes.func,
    onCellClick: PropTypes.func,
    onRequestColumnsSpan: PropTypes.func

};

Tfoot.defaultProps = {
    disabled: false,
    baseColIndex: 0,
    ignoreColumnSpan: false
};

export default Tfoot;
<commit_msg>update Tfoot<commit_after>/**
 * @file Tfoot component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';

// Components
import Tf from '../_Tf';

// Statics
import TableFragment from '../_statics/TableFragment';
import HorizontalAlign from '../_statics/HorizontalAlign';
import SelectMode from '../_statics/SelectMode';
import SelectAllMode from '../_statics/SelectAllMode';
import SortingType from '../_statics/SortingType';

// Vendors
import classNames from 'classnames';
import Util from '../_vendors/Util';
import TC from '../_vendors/TableCalculation';

class Tfoot extends Component {

    static Align = HorizontalAlign;
    static SelectMode = SelectMode;
    static SelectAllMode = SelectAllMode;
    static SortingType = SortingType;

    constructor(props, ...restArgs) {
        super(props, ...restArgs);
    }

    getColumnsSpan = () => {
        const {columns, data, onRequestColumnsSpan} = this.props;
        return onRequestColumnsSpan ?
            onRequestColumnsSpan(TableFragment.FOOT, columns, data)
            :
            TC.getColumnsSpan(TableFragment.FOOT, columns, data);
    };

    handleClick = e => {
        const {data, disabled, onFootClick} = this.props;
        !disabled && onFootClick && onFootClick(data, e);
    };

    render() {

        const {
                className, data, disabled, baseColIndex, ignoreColumnSpan, scrollEl,
                onCellClick
            } = this.props,
            columnsSpan = this.getColumnsSpan();

        return (

                    {
                        columnsSpan && columnsSpan.map(({column, span}, colIndex) =>
                            <Tf key={colIndex}
                                className={column.footClassName}
                                style={column.footStyle}
                                colIndex={baseColIndex + colIndex}
                                data={data}
                                title={column.footTitle}
                                renderer={column.footRenderer}
                                align={column.footAlign || column.align}
                                span={ignoreColumnSpan ? null : span}
                                noWrap={TC.handleNoWrap(column.footNoWrap, column.noWrap, {
                                    data,
                                    rowIndex: 0,
                                    colIndex: baseColIndex + colIndex,
                                    tableData: data
                                })}
                                disabled={disabled}
                                scrollEl={scrollEl}
                                onCellClick={onCellClick}/>
                        )
                    }

        );

    }
}

Tfoot.propTypes = {

    className: PropTypes.string,

    /**
     * Children passed into table header.
     */
    columns: PropTypes.arrayOf(PropTypes.shape({

        /**
         * fixed position of column ( 'left' / 'right' ).
         */
        fixed: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * width of column.
         */
        width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),

        /**
         * minimum width of column.
         */
        minWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),

        /**
         * align of current column.
         */
        align: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * no wrap of current column.
         */
        noWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * The class name of header.
         */
        headClassName: PropTypes.string,

        /**
         * Override the styles of header.
         */
        headStyle: PropTypes.object,

        /**
         * align of table header cell
         */
        headAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * The render content in table head.
         *  (1) callback:
         *      function (tableData, colIndex) {
         *          return colIndex;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        headRenderer: PropTypes.any,

        /**
         * The title in table head.
         *  (1) callback:
         *      function (tableData, colIndex) {
         *          return colIndex;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        headTitle: PropTypes.any,

        /**
         * column span of table header.
         *  (1) function callback:
         *      function (tableData, colIndex) {
         *          return null;
         *      }
         *
         *  (2) number:
         *      render whatever you pass
         */
        headSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * no wrap of table header.
         */
        headNoWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * The class name of td.
         */
        bodyClassName: PropTypes.string,

        /**
         * Override the styles of td.
         */
        bodyStyle: PropTypes.object,

        /**
         * align of table body cell.
         */
        bodyAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * The render content in table body.
         *  (1) callback:
         *      function (rowData, rowIndex, colIndex, parentData, tableData, collapsed, depth, path) {
         *          return rowData.id;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        bodyRenderer: PropTypes.any,

        /**
         * The title in table body.
         *  (1) callback:
         *      function (rowData, rowIndex, colIndex, parentData, tableData, collapsed, depth, path) {
         *          return rowData.id;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        bodyTitle: PropTypes.any,

        /**
         * column span of table body.
         *  (1) function callback:
         *      function (rowData, colIndex, rowIndex) {
         *          return null;
         *      }
         *
         *  (2) number:
         *      render whatever you pass
         */
        bodySpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * no wrap of table body.
         */
        bodyNoWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * The class name of footer.
         */
        footClassName: PropTypes.string,

        /**
         * Override the styles of footer.
         */
        footStyle: PropTypes.object,

        /**
         * align of table footer cell
         */
        footAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * The render content in table foot.
         *  (1) callback:
         *      function (tableData, colIndex) {
         *          return colIndex;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        footRenderer: PropTypes.any,

        /**
         * The title in table foot.
         *  (1) callback:
         *      function (tableData, colIndex) {
         *          return colIndex;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        footTitle: PropTypes.any,

        /**
         * column span of table foot.
         *  (1) function callback:
         *      function (tableData, colIndex) {
         *          return null;
         *      }
         *
         *  (2) number:
         *      render whatever you pass
         */
        footSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * no wrap of table foot.
         */
        footNoWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * If true,this column can be sorted.
         */
        sortable: PropTypes.bool,

        /**
         * Sorting property.
         */
        sortingProp: PropTypes.string,

        defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType))

    })).isRequired,

    data: PropTypes.array,
    disabled: PropTypes.bool,
    baseColIndex: PropTypes.number,
    ignoreColumnSpan: PropTypes.bool,
    scrollEl: PropTypes.object,

    onFootClick: PropTypes.func,
    onCellClick: PropTypes.func,
    onRequestColumnsSpan: PropTypes.func

};

Tfoot.defaultProps = {
    disabled: false,
    baseColIndex: 0,
    ignoreColumnSpan: false
};

export default Tfoot;
<|endoftext|>


<commit_before>/**
 * @file Dom vendor
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import contains from 'dom-helpers/query/contains';

function getOffset(el, parentEl = document.body) {

    if (!el) {
        return null;
    }

    let offset = {
        top: el.offsetTop,
        left: el.offsetLeft
    };

    // handle offset
    let offsetParent = el.offsetParent;
    while (offsetParent) {

        if (parentEl && offsetParent.contains(parentEl)) {
            break;
        }

        // append layout offset
        offset.top += offsetParent.offsetTop;
        offset.left += offsetParent.offsetLeft;

        // append transform offset
        const transform = window.getComputedStyle(offsetParent).transform,
            matched = transform.match(/^matrix\((.*)\)$/);
        if (matched && matched[1]) {
            const matrix = matched[1].split(/\s*,\s*/);
            offset.top += +matrix[5];
            offset.left += +matrix[4];
        }

        offsetParent = offsetParent.offsetParent;

    }

    // handle scroll
    let scrollParent = getClosestScrollable(el.parentElement);
    while (scrollParent) {

        if (parentEl && scrollParent.contains(parentEl)) {
            break;
        }

        // drop scroll offset
        offset.top -= scrollParent.scrollTop;
        offset.left -= scrollParent.scrollLeft;

        scrollParent = getClosestScrollable(scrollParent.parentElement);

    }

    return offset;

}

function getScrollHeight() {
    return document.body.scrollHeight || document.documentElement.scrollHeight;
}

function getScrollLeft(parentEl) {

    if (window.SCROLL_EL && window.SCROLL_EL.scrollLeft) {
        return SCROLL_EL.scrollLeft;
    }

    if (parentEl && parentEl !== document.body) {
        return parentEl.scrollLeft;
    }

    return document.body.scrollLeft || document.documentElement.scrollLeft;

}

function getScrollTop(parentEl) {

    if (window.SCROLL_EL && window.SCROLL_EL.scrollTop) {
        return SCROLL_EL.scrollTop;
    }

    if (parentEl && parentEl !== document.body) {
        return parentEl.scrollTop;
    }

    return document.body.scrollTop || document.documentElement.scrollTop;

}

function hasClass(el, className) {

    if (!el || !className) {
        return false;
    }

    const elClassName = el.className;

    if (!elClassName) {
        return false;
    }

    const elClass = elClassName.split(/\s+/);

    return elClass && elClass.findIndex(item => item === className) !== -1;

}

function addClass(el, className) {

    if (!el || !className) {
        return;
    }

    const elClassName = el.className;

    if (!elClassName) {
        el.className = className;
        return;
    }

    const elClass = elClassName.split(/\s+/),
        index = elClass ? elClass.findIndex(item => item === className) : -1;

    if (index !== -1) { // already has this className
        return;
    }

    elClass.push(className);
    el.className = elClass.join(' ');

}

function removeClass(el, className) {

    if (!el || !className) {
        return;
    }

    const elClassName = el.className;

    if (!elClassName) {
        return;
    }

    const elClass = elClassName.split(/\s+/),
        index = elClass ? elClass.findIndex(item => item === className) : -1;

    if (index === -1) { // no this className
        return;
    }

    elClass.splice(index, 1);
    el.className = elClass.join(' ');

}

function toggleClass(el, className, bool) {
    bool ?
        addClass(el, className)
        :
        removeClass(el, className);
}

function findParentByClassName(el, className) {

    if (!el || !className) {
        return;
    }

    while (el) {
        if (hasClass(el, className)) {
            return el;
        }
        el = el.parentNode;
    }

    return;

}

function isParent(el, parentEl) {

    if (!el || !parentEl) {
        return false;
    }

    do {

        el = el.parentNode;

        if (el == parentEl) {
            return true;
        }

    } while (el);

    return false;

}

function isScrollable(...values) {
    return values.some(value => value === 'auto' || value === 'scroll');
}

function isElementScrollable(el) {
    const style = window.getComputedStyle(el);
    return isScrollable(style.overflow, style.overflowY, style.overflowX);
};

function getClosestScrollable(el) {

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

    if (!isElementScrollable(el)) {
        return getClosestScrollable(el.parentElement);
    }

    return el;

}

function getTotalScrollOffset(el, scrollEl = document.body) {

    const result = {
        left: 0,
        top: 0
    };

    if (!el || !scrollEl) {
        return result;
    }

    while (el && contains(scrollEl, el)) {
        result.left += el.scrollLeft;
        result.top += el.scrollTop;
        el = el.parentElement;
    }

    return result;

}

export default {
    getOffset,
    getScrollHeight,
    getScrollLeft,
    getScrollTop,
    hasClass,
    addClass,
    removeClass,
    toggleClass,
    findParentByClassName,
    isParent,
    isScrollable,
    isElementScrollable,
    getClosestScrollable,
    getTotalScrollOffset
};
<commit_msg>update Dom<commit_after>/**
 * @file Dom vendor
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import contains from 'dom-helpers/query/contains';

function getOffset(el, parentEl = document.body) {

    if (!el) {
        return null;
    }

    let offset = {
        top: el.offsetTop,
        left: el.offsetLeft
    };

    // handle offset
    let offsetParent = el.offsetParent;
    while (offsetParent) {

        if (parentEl && offsetParent.contains(parentEl)) {
            break;
        }

        // append layout offset
        offset.top += offsetParent.offsetTop;
        offset.left += offsetParent.offsetLeft;

        // append transform offset
        const transform = window.getComputedStyle(offsetParent).transform,
            matched = transform.match(/^matrix\((.*)\)$/);
        if (matched && matched[1]) {
            const matrix = matched[1].split(/\s*,\s*/);
            offset.top += +matrix[5];
            offset.left += +matrix[4];
        }

        offsetParent = offsetParent.offsetParent;

    }

    // handle scroll
    let scrollParent = getClosestScrollable(el.parentElement);
    while (scrollParent) {

        if (parentEl && scrollParent.contains(parentEl)) {
            break;
        }

        // drop scroll offset
        offset.top -= scrollParent.scrollTop;
        offset.left -= scrollParent.scrollLeft;

        scrollParent = getClosestScrollable(scrollParent.parentElement);

    }

    return offset;

}

function getScrollHeight() {
    return document.body.scrollHeight || document.documentElement.scrollHeight;
}

function getScrollLeft(parentEl) {

    if (window.SCROLL_EL && window.SCROLL_EL.scrollLeft) {
        return SCROLL_EL.scrollLeft;
    }

    if (parentEl && parentEl !== document.body) {
        return parentEl.scrollLeft;
    }

    return document.body.scrollLeft || document.documentElement.scrollLeft;

}

function getScrollTop(parentEl) {

    if (window.SCROLL_EL && window.SCROLL_EL.scrollTop) {
        return SCROLL_EL.scrollTop;
    }

    if (parentEl && parentEl !== document.body) {
        return parentEl.scrollTop;
    }

    return document.body.scrollTop || document.documentElement.scrollTop;

}

function hasClass(el, className) {

    if (!el || !className) {
        return false;
    }

    const elClassName = el.className;

    if (!elClassName) {
        return false;
    }

    const elClass = elClassName.split(/\s+/);

    return elClass && elClass.findIndex(item => item === className) !== -1;

}

function addClass(el, className) {

    if (!el || !className) {
        return;
    }

    const elClassName = el.className;

    if (!elClassName) {
        el.className = className;
        return;
    }

    const elClass = elClassName.split(/\s+/),
        index = elClass ? elClass.findIndex(item => item === className) : -1;

    if (index !== -1) { // already has this className
        return;
    }

    elClass.push(className);
    el.className = elClass.join(' ');

}

function removeClass(el, className) {

    if (!el || !className) {
        return;
    }

    const elClassName = el.className;

    if (!elClassName) {
        return;
    }

    const elClass = elClassName.split(/\s+/),
        index = elClass ? elClass.findIndex(item => item === className) : -1;

    if (index === -1) { // no this className
        return;
    }

    elClass.splice(index, 1);
    el.className = elClass.join(' ');

}

function toggleClass(el, className, bool) {
    bool ?
        addClass(el, className)
        :
        removeClass(el, className);
}

function findParentByClassName(el, className) {

    if (!el || !className) {
        return;
    }

    while (el) {
        if (hasClass(el, className)) {
            return el;
        }
        el = el.parentNode;
    }

    return;

}

function isParent(el, parentEl) {

    if (!el || !parentEl) {
        return false;
    }

    do {

        el = el.parentNode;

        if (el == parentEl) {
            return true;
        }

    } while (el);

    return false;

}

function isScrollable(...values) {
    return values.some(value => value === 'auto' || value === 'scroll');
}

function isElementScrollable(el) {
    const style = window.getComputedStyle(el);
    return isScrollable(style.overflow, style.overflowY, style.overflowX);
};

function getClosestScrollable(el) {

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

    if (!isElementScrollable(el)) {
        return getClosestScrollable(el.parentElement);
    }

    return el;

}

function getTotalScrollOffset(el, scrollEl = document.body) {

    const result = {
        left: 0,
        top: 0
    };

    if (!el || !scrollEl) {
        return result;
    }

    while (el && contains(scrollEl, el)) {
        result.left += el.scrollLeft;
        result.top += el.scrollTop;
        el = el.parentElement;
    }

    return result;

}

function isElementFixed(el) {
    return window.getComputedStyle(el).position === 'fixed';
};

function getClosestFixed(el) {

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

    if (!isElementFixed(el)) {
        return getClosestFixed(el.parentElement);
    }

    return el;

}

export default {
    getOffset,
    getScrollHeight,
    getScrollLeft,
    getScrollTop,
    hasClass,
    addClass,
    removeClass,
    toggleClass,
    findParentByClassName,
    isParent,
    isScrollable,
    isElementScrollable,
    getClosestScrollable,
    getTotalScrollOffset,
    isElementFixed,
    getClosestFixed
};
<|endoftext|>


<commit_before>import Chess from 'chess.js';
import Crazyhouse from 'crazyhouse.js';
import FourChess from '../../common/fourchess';
import SChess from 'schess.js';
import {CLOSE_ANALYSIS} from './types';

export function sitDownBoard(details) {
    return {
        type: 'server/sit-down-board',
        payload: details
    }
}

export function joinAnalysisRoom(game, gameType, roomName) {
    game.gameType = gameType;
    game.fen = game.final_fen;
    game.numPlayers = 2;
    if(gameType === 'standard') {
        let g = new Chess();
        g.load_pgn(game.pgn);
        game.pgn = g.history({ verbose: true});
        g.reset();
        game.pgn.map((move) => {
           g.move(move);
           move.fen = g.fen();
        });
    } else if(gameType === 'schess') {
        let g = new SChess();
        g.load_pgn(game.pgn);
        game.pgn = g.history({ verbose: true});
        g.reset();
        game.pgn.map((move) => {
           g.move(move);
           move.fen = g.fen();
        });
    } else if(gameType === 'crazyhouse')  {
        let g = new Crazyhouse();
        g.load_pgn(game.pgn);
        game.pgn = g.history({ verbose: true});
        g.reset();
        game.pgn.map((move) => {
           g.move(move);
           move.fen = g.fen();
        });
    } else if(gameType === 'crazyhouse960') {
        let g = new Crazyhouse({960: true});
        g.load_pgn(game.pgn);
        game.pgn = g.history({ verbose: true});
        game.pgn[0].fen = game.initial_fen;
        g.reset();
        g.load(game.initial_fen);
        game.pgn.map((move) => {
           g.move(move);
           move.fen = g.fen();
        });
    } else if(gameType === 'four-player') {
        let g = new FourChess();

        game.pgn = 'w:j1-i3 g:b8-c8 b:e14-f12 r:n10-l9 w:j2-j3 g:a10-c9 b:j14-i12 r:n5-l6 w:g2-g3 g:b7-c7 b:e13-e12 r:m4-l4 w:e1-g2 g:a6-b7 b:j13-j12 r:m11-l11 w:e2-e3 g:b4-c4 b:k13-k12 r:m10-l10 w:f1-e2 g:a8-b8 b:h13-h12 r:n9-m10 w:k2-k3 g:a7-a8 b:k12-l11 r:m10-l11 w:k3-k4 g:b7-g2 b:i14-g12 r:l11-j13 w:i3-g2 g:a5-c6 b:k14-k13 r:j13-i12 w:i1-j2 g:b11-d11 b:g12-h13 r:i12-h13 w:f2-f4 g:d11-e12 b:f12-h13 r:n8-n9 w:e2-f3 g:e12-f13 b:g14-f13 r:n11-a11 w:g1-f2 g:a4-a6 b:f14-e13 r:n9-n11 w:f2-e2 g:a8-b7 b:h14-i14 r:a11-m11 w:h1-g1 g:b7-a7 b:h13-f12 r:l6-m4 w:g1-f2 g:c4-d4 b:i14-h13 r:m11-j11 w:e3-e4 g:c6-b4 b:d14-k14 r:m4-k5 w:f2-f1 g:b6-c6 b:f12-e10 r:k5-l7 w:d2-d3 g:b8-a8 b:e13-f12 r:l7-k9 w:g2-i3 g:a9-b8 b:e10-f8 r:m7-l7 w:e2-g2 g:a8-b7 b:f13-g14 r:n4-n5 w:f1-e1 g:a7-b6 b:f8-h7 r:n6-l8 w:e1-e2 g:a6-a10 b:h7-i9 r:j11-m11 w:i3-g4 g:b10-d10 b:h13-i12 r:n7-m7 w:j2-i3 g:c9-e10 b:f12-e13 r:m6-l6 w:g4-f2 g:e10-d8 b:k13-k10 r:n11-m10 w:d1-i1 g:b6-a6 b:k10-h10 r:n5-n11 w:e2-d1 g:b5-d5 b:k14-k10 r:l8-k7 w:f3-e2 g:d5-e4 b:h10-h7 r:m10-i14 w:d3-e4 g:a6-a5 b:g14-f13 r:m11-f11 w:i3-d8 g:a5-m5 b:e13-f12 r:m7-n7 w:d8-j2 g:m5-n5 b:i12-j13 r:n7-m7 w:f2-d3 g:n5-m5 b:j13-i14 r:m7-n7 w:d3-b4 g:m5-n5 b:i14-f11 r:n7-m7 w:e4-e5 g:n5-m5 b:h7-h8 w:e5-e6 g:m5-i5 b:k10-e10 w:b4-c6 g:d4-e4 b:e10-e6 w:c6-e5 g:c7-d7 b:e6-e12 w:j2-h4 g:i5-m5 b:f11-h9 w:g2-e4 g:b7-a7 b:i13-i11 w:e2-f3 b:f12-h10 w:i1-e1 b:i9-h7 w:e1-e2 b:h7-f6 w:h4-f6 b:h8-h2 w:f3-g4 b:h2-h6 w:f6-g5 b:h6-d6 w:e2-d2 b:d6-j6 w:k1-e1 b:h10-i9 w:e4-f5 b:f13-g14 w:g4-l9 b:g14-h14 w:f5-f14 b:h14-i13 w:f14-g13 b:i13-j14 w:l9-i12 b:h9-h5 w:g3-g4 b:h5-g4 w:e5-g4 b:e12-e1 w:d1-e1 b:j6-e6 w:e1-f1 b:e6-e1 w:f1-g2 b:e1-g1 w:g2-g1 b:i9-d4 w:d2-d4 b:h12-h11 w:g13-j13 w:j13-j14';

        game.pgn = game.pgn.trim();
        let moves = game.pgn.split(' ');
        moves.map((move) => {
            console.log(move);
            if(move.length > 1) {
                let fromTo = move.split(':')[1];
                let from = fromTo.split('-')[0];
                let to = fromTo.split('-')[1];
                g.move({
                    from: from,
                    to: to,
                    promotion: 'q',
                    color: move.split(':')[0]
                });
            }

        });

        game.numPlayers = 4;
        game.pgn = g.history();
    }
    return {
        type: 'update-room',
        payload: {
            gameType,
            room: {
                private: true,
                voiceChat: false,
                maxPlayers: 10000,
                name: roomName,

            },
            times: {
                b: 2,
                w: 2,
                g: 2,
                r: 2,
            },
            activePly: 0,
            mode: 'analysis',
            time: game.time,
            game,

        }
    }
}

export function closeAnalysisRoom(roomName) {
    return {
        type: CLOSE_ANALYSIS,
        payload: roomName
    }
}

export function sitDownComputer(details) {
    return {
        type: 'server/sit-down-board',
        payload: details
    }
}

export function enableMic(thread) {
    return {
        type: 'voice/enable-voice',
        payload: thread
    }
}

export function disableMic(thread) {
    return {
        type: 'voice/disable-voice',
        payload: thread
    }
}

export function removeComputer(player, thread) {
    return {
        type: 'server/remove-ai-player',
        payload: {
            player,
            thread
        }
    }
}

export function updateTime(roomName, turn, time) {
    return {
        type: 'update-time',
        payload: {
            thread: roomName,
            turn: turn,
            time: time
        }
    };
}

export function fourNewMove(move, roomName, moveTime) {
    return {
        type: 'server/four-new-move',
        payload: {
            thread: roomName,
            move: move,
            moveTime: moveTime
        }
    }
}

export function newMove(move, roomName, moveTime) {
    return {
        type: 'server/new-move',
        payload: {
            thread: roomName,
            move: move,
            moveTime: moveTime
        }
    }

}

export function draw(roomName) {
    return {
        type: 'server/draw',
        payload: {
            roomName
        }
    }
}

export function resign(playerId, roomName) {
    return {
        type: 'server/resign',
        payload: {
            playerId,
            roomName
        }
    }
}

export function fourResign(roomName) {
    return {
        type: 'server/four-resign',
        payload: {
            roomName
        }
    }
}

export function acceptDraw(roomName) {
    return {
        type: 'server/accept-draw',
        payload: {
            roomName
        }
    }
}

export function killAIs(roomName) {
    return {
        type: 'server/kill-ais',
        payload: roomName
    }
}

export function abort(roomName) {
    return {
        type: 'server/abort',
        payload: roomName
    }
}

export function changeActivePly(roomName, activePly) {
    return {
        type: 'change-active-ply',
        payload: {
            roomName: roomName,
            activePly: activePly
        }
    }
}

export function openPromotionSelector(roomName, callback) {
    return {
        type: 'open-promotion-selector',
        payload: {
            roomName,
            callback
        }
    };
}

export function closePromotionSelector(roomName) {
    return {
        type: 'close-promotion-selector',
        payload: {
            roomName
        }
    };
}<commit_msg>Forgot to remove test pgn ... again<commit_after>import Chess from 'chess.js';
import Crazyhouse from 'crazyhouse.js';
import FourChess from '../../common/fourchess';
import SChess from 'schess.js';
import {CLOSE_ANALYSIS} from './types';

export function sitDownBoard(details) {
    return {
        type: 'server/sit-down-board',
        payload: details
    }
}

export function joinAnalysisRoom(game, gameType, roomName) {
    game.gameType = gameType;
    game.fen = game.final_fen;
    game.numPlayers = 2;
    if(gameType === 'standard') {
        let g = new Chess();
        g.load_pgn(game.pgn);
        game.pgn = g.history({ verbose: true});
        g.reset();
        game.pgn.map((move) => {
           g.move(move);
           move.fen = g.fen();
        });
    } else if(gameType === 'schess') {
        let g = new SChess();
        g.load_pgn(game.pgn);
        game.pgn = g.history({ verbose: true});
        g.reset();
        game.pgn.map((move) => {
           g.move(move);
           move.fen = g.fen();
        });
    } else if(gameType === 'crazyhouse')  {
        let g = new Crazyhouse();
        g.load_pgn(game.pgn);
        game.pgn = g.history({ verbose: true});
        g.reset();
        game.pgn.map((move) => {
           g.move(move);
           move.fen = g.fen();
        });
    } else if(gameType === 'crazyhouse960') {
        let g = new Crazyhouse({960: true});
        g.load_pgn(game.pgn);
        game.pgn = g.history({ verbose: true});
        game.pgn[0].fen = game.initial_fen;
        g.reset();
        g.load(game.initial_fen);
        game.pgn.map((move) => {
           g.move(move);
           move.fen = g.fen();
        });
    } else if(gameType === 'four-player') {
        let g = new FourChess();

        game.pgn = game.pgn.trim();
        let moves = game.pgn.split(' ');
        moves.map((move) => {
            console.log(move);
            if(move.length > 1) {
                let fromTo = move.split(':')[1];
                let from = fromTo.split('-')[0];
                let to = fromTo.split('-')[1];
                g.move({
                    from: from,
                    to: to,
                    promotion: 'q',
                    color: move.split(':')[0]
                });
            }

        });

        game.numPlayers = 4;
        game.pgn = g.history();
    }
    return {
        type: 'update-room',
        payload: {
            gameType,
            room: {
                private: true,
                voiceChat: false,
                maxPlayers: 10000,
                name: roomName,

            },
            times: {
                b: 2,
                w: 2,
                g: 2,
                r: 2,
            },
            activePly: 0,
            mode: 'analysis',
            time: game.time,
            game,

        }
    }
}

export function closeAnalysisRoom(roomName) {
    return {
        type: CLOSE_ANALYSIS,
        payload: roomName
    }
}

export function sitDownComputer(details) {
    return {
        type: 'server/sit-down-board',
        payload: details
    }
}

export function enableMic(thread) {
    return {
        type: 'voice/enable-voice',
        payload: thread
    }
}

export function disableMic(thread) {
    return {
        type: 'voice/disable-voice',
        payload: thread
    }
}

export function removeComputer(player, thread) {
    return {
        type: 'server/remove-ai-player',
        payload: {
            player,
            thread
        }
    }
}

export function updateTime(roomName, turn, time) {
    return {
        type: 'update-time',
        payload: {
            thread: roomName,
            turn: turn,
            time: time
        }
    };
}

export function fourNewMove(move, roomName, moveTime) {
    return {
        type: 'server/four-new-move',
        payload: {
            thread: roomName,
            move: move,
            moveTime: moveTime
        }
    }
}

export function newMove(move, roomName, moveTime) {
    return {
        type: 'server/new-move',
        payload: {
            thread: roomName,
            move: move,
            moveTime: moveTime
        }
    }

}

export function draw(roomName) {
    return {
        type: 'server/draw',
        payload: {
            roomName
        }
    }
}

export function resign(playerId, roomName) {
    return {
        type: 'server/resign',
        payload: {
            playerId,
            roomName
        }
    }
}

export function fourResign(roomName) {
    return {
        type: 'server/four-resign',
        payload: {
            roomName
        }
    }
}

export function acceptDraw(roomName) {
    return {
        type: 'server/accept-draw',
        payload: {
            roomName
        }
    }
}

export function killAIs(roomName) {
    return {
        type: 'server/kill-ais',
        payload: roomName
    }
}

export function abort(roomName) {
    return {
        type: 'server/abort',
        payload: roomName
    }
}

export function changeActivePly(roomName, activePly) {
    return {
        type: 'change-active-ply',
        payload: {
            roomName: roomName,
            activePly: activePly
        }
    }
}

export function openPromotionSelector(roomName, callback) {
    return {
        type: 'open-promotion-selector',
        payload: {
            roomName,
            callback
        }
    };
}

export function closePromotionSelector(roomName) {
    return {
        type: 'close-promotion-selector',
        payload: {
            roomName
        }
    };
}<|endoftext|>


<commit_before>
;(function() {

var root = this;

root.cartodb = root.cartodb || {};

var ramps = {
  bool: ['#229A00', '#F84F40', '#DDDDDD'],
  green:  ['#EDF8FB', '#D7FAF4', '#CCECE6', '#66C2A4', '#41AE76', '#238B45', '#005824'],
  blue:  ['#FFFFCC', '#C7E9B4', '#7FCDBB', '#41B6C4', '#1D91C0', '#225EA8', '#0C2C84'],
  pink: ['#F1EEF6', '#D4B9DA', '#C994C7', '#DF65B0', '#E7298A', '#CE1256', '#91003F'],
  black:  ['#F7F7F7', '#D9D9D9', '#BDBDBD', '#969696', '#737373', '#525252', '#252525'],
  red:  ['#FFFFB2', '#FED976', '#FEB24C', '#FD8D3C', '#FC4E2A', '#E31A1C', '#B10026'],
  category: ['#A6CEE3', '#1F78B4', '#B2DF8A', '#33A02C', '#FB9A99', '#E31A1C', '#FDBF6F', '#FF7F00', '#CAB2D6', '#6A3D9A', '#DDDDDD'],
  divergent: ['#0080FF', '#40A0FF', '#7FBFFF', '#FFF2CC', '#FFA6A6', '#FF7A7A', '#FF4D4D']
};

function geoAttr(geometryType) {
  return {
    "line": 'line-color',
    'polygon': "polygon-fill",
    'point': "marker-fill"
  }[geometryType]
}

function getDefaultCSSForGeometryType(geometryType) {
  if (geometryType === "polygon") {
    return [
      "polygon-opacity: 0.7;",
      "line-color: #FFF;",
      "line-width: 0.5;",
      "line-opacity: 1;"
    ];
  }
  if (geometryType === "line") {
    return  [
      "line-width: 2;",
      "line-opacity: 0.7;"
    ];
  }
  return [
    "line-color: #0C2C84;",
    "line-opacity: 1;",
    "marker-fill-opacity: 0.9;",
    "marker-line-color: #FFF;",
    "marker-line-width: 1;",
    "marker-line-opacity: 1;",
    "marker-placement: point;",
    "marker-type: ellipse;",
    "marker-width: 10;",
    "marker-allow-overlap: true;"
  ];
}

var CSS = {
  choropleth: function(quartiles, tableName, prop, geometryType, ramp) {
    var attr = geoAttr(geometryType);
    var tableID = "#" + tableName;

    var defaultCSS = getDefaultCSSForGeometryType(geometryType);
    var css = "/** choropleth visualization */\n\n" + tableID + " {\n  " + attr + ": " + ramp[0] + ";\n" + defaultCSS.join("\n") + "\n}\n";

    for (var i = quartiles.length - 1; i >= 0; --i) {
      if (quartiles[i] !== undefined && quartiles[i] != null) {
        css += "\n" + tableID + "[" + prop + " <= " + quartiles[i] + "] {\n";
        css += "  " + attr  + ":" + ramp[i] + ";\n}"
      }
    }
    return css;
  },

  categoryMetadata: function(cats, options) {
    var metadata = [];

    var ramp = (options && options.ramp) ? options.ramp : ramps.category;
    var type = options && options.type ? options.type : "string";

    for (var i = 0; i < cats.length; i++) {
      var cat = cats[i];
      if (i < 10 && cat !== undefined && ((type === 'string' && cat != null) || (type !== 'string'))) {
        metadata.push({ title: cat, title_type: type, value_type: 'color', color: ramp[i] });
      }
    }

    if (cats.length > 10) {
      metadata.push({ title: "Others", value_type: 'color', default: true, color: ramp[ramp.length - 1] });
    }

    return metadata;
  },

  category: function(cats, tableName, prop, geometryType, options) {
    var attr = geoAttr(geometryType);
    var tableID = "#" + tableName;
    var ramp = ramps.category;
    var name, value;

    var type = options && options.type ? options.type : "string";
    var ramp = (options && options.ramp) ? options.ramp : ramps.category;

    var defaultCSS = getDefaultCSSForGeometryType(geometryType);

    var css = "/** category visualization */\n\n" + tableID + " {\n  " + attr + ": " + ramp[0] + ";\n" + defaultCSS.join("\n") + "\n}\n";

    for (var i = 0; i < cats.length; i++) {

      var cat = cats[i];

      if (type === 'string') {
        name = cat.replace(/\n/g,'\\n').replace(/\"/g, "\\\"");
        value = "\"" + name + "\"";
      } else {
        value = cat;
      }

      if (i < 10 && cat !== undefined && ((type === 'string' && cat != null) || (type !== 'string'))) {
        css += "\n" + tableID + "[" + prop + "=" + value + "] {\n";
        css += "  " + attr  + ":" + ramp[i] + ";\n}"
      }
    }

    if (cats.length > 10) {
      css += "\n" + tableID + "{\n";
      css += "  " + attr  + ": " + ramp[ramp.length - 1]+ ";\n}"
    }

    return css;
  },

  torque: function(stats, tableName, options){
    var tableID = "#" + tableName;
    var aggFunction = "count(cartodb_id)";
    var css = [
        '/** torque visualization */',
        'Map {',
        '  -torque-time-attribute: ' + stats.column + ';',
        '  -torque-aggregation-function: "count(cartodb_id)";',
        '  -torque-frame-count: ' + stats.steps + ';',
        '  -torque-animation-duration: 10;',
        '  -torque-resolution: 2;',
        '}',
        tableID + " {",
        '  marker-width: 3;',
        '  marker-fill-opacity: 0.8;',
        '  marker-fill: #0F3B82; ',
        '  comp-op: "lighten"; ',
        '  [frame-offset = 1] { marker-width: 10; marker-fill-opacity: 0.05;}',
        '  [frame-offset = 2] { marker-width: 15; marker-fill-opacity: 0.02;}',
        '}'
    ];
    css = css.join('\n');

    return css;

  },

  bubble: function(quartiles, tableName, prop) {
    var tableID = "#" + tableName;
    var css = "/** bubble visualization */\n\n" + tableID + " {\n";
    css += getDefaultCSSForGeometryType("point").join('\n');
    css += "\nmarker-fill: #FF5C00;";
    css += "\n}\n\n";

    var min = 10;
    var max = 30;

    var values = [];

    var NPOINS = 10;
    for(var i = 0; i < NPOINS; ++i) {
      var t = i/(NPOINS-1);
      values.push(min + t*(max - min));
    }

    // generate carto
    for(var i = NPOINS - 1; i >= 0; --i) {
      if(quartiles[i] !== undefined && quartiles[i] != null) {
        css += "\n#" + tableName +" [ " + prop + " <= " + quartiles[i] + "] {\n"
        css += "   marker-width: " + values[i].toFixed(1) + ";\n}"
      }
    }
    return css;
  },

  heatmap: function(stats, tableName, options){
    var tableID = "#" + tableName;
    var css = [
        '/** heatmap visualization */',
        'Map {',
        '  -torque-time-attribute: "cartodb_id";',
        '  -torque-aggregation-function: "count(cartodb_id)";',
        '  -torque-frame-count: 1;',
        '  -torque-animation-duration: 10;',
        '  -torque-resolution: 2;',
        '}',
        tableID + " {",
        '  marker-width: 10;',
        '  marker-fill-opacity: 0.4;',
        '  marker-fill: #0F3B82; ',
        '  comp-op: "lighten"; ',
        '  image-filters: colorize-alpha(blue, cyan, lightgreen, yellow , orange, red);',
        '  marker-file: url(http://s3.amazonaws.com/com.cartodb.assets.static/alphamarker.png);',
        '}'
    ];
    css = css.join('\n');
    return css;
  }
}

function guessCss(sql, geometryType, column, stats) {
  var css = null
  if (stats.type === 'number') {
    css =  CSS.choropleth(stats.quantiles, column, geometryType, ramps.red);
  } else if(stats.type === 'string') {
    css = CSS.category(stats.hist.slice(0, ramps.cat.length).map(function(r) { return r[0]; }), column, geometryType)
  }
  return css;
}

function guess(o, callback) {
  if (!callback) throw new Error("no callback");
  var s = cartodb.SQL({ user: o.user });
  s.describe(o.sql, 'the_geom', function(data) {
    var geometryType = data.simplified_geometry_type;
    s.describe(o.sql, o.column, function(data) {
      callback(
        null,
        guessCss(o.sql, geometryType, data.column, data)
      )
    });
  })
}

function getWeightFromShape(dist_type){
  return {
    U: 0.9,
    A: 0.9,
    L: 0.7,
    J: 0.7,
    S: 0.5,
    F: 0.3
  }[dist_type];
}

function getMethodProperties(stats) { // TODO: only require the necessary params

  var method;
  var ramp = ramps.pink;
  var name = "pink";

  if (['A','U'].indexOf(stats.dist_type) != -1) { // apply divergent scheme
    method = stats.jenks;

    if (stats.min < 0 && stats.max > 0){
      ramp = ramps.divergent;
      name = "spectrum2";
    }

  } else if (stats.dist_type === 'F') {
    method = stats.equalint;
    ramp = ramps.red;
    name = "red";
  } else {
    if (stats.dist_type === 'J') {
      method = stats.headtails;
      ramp = ramps.blue;
      name = "blue";
    } else {
      //ramp = (_.clone(ramps.red)).reverse();
      method = stats.headtails;
      ramp = ramps.red;
      name = "red";
    }
  }

  return { name: name, ramp: ramp, method: method };

}

function guessMap(sql, tableName, column, stats) {
  var geometryType = column.get("geometry_type");
  var columnName = column.get("column");
  var visualizationType = "choropleth";
  var css = null
  var type = stats.type;
  var metadata = []
  var distinctPercentage = (stats.distinct / stats.count) * 100;

  if (type === 'number') {

    var calc_weight = (stats.weight + getWeightFromShape(stats.dist_type)) / 2;

    if (calc_weight >= 0.5) {

      var visFunction = CSS.choropleth;
      var properties = getMethodProperties(stats);

      if (stats.count < 200 && geometryType === 'point'){
        visualizationType = "bubble";
        visFunction = CSS.bubble;
      }

      css = visFunction(properties.method, tableName, columnName, geometryType, properties.ramp);

    } else if (stats.weight > 0.5 || distinctPercentage < 25) {

      if (distinctPercentage < 1) {
        visualizationType   = "category";

        var cats = stats.cat_hist;
        cats = _.sortBy(cats, function(cat) { return cat[1]; }).reverse().slice(0, ramps.category.length);
        cats = _.sortBy(cats, function(cat) { return cat[0]; });
        cats = cats.map(function(r) { return r[0]; });

        css      = CSS.category(cats, tableName, columnName, geometryType, { type: type });
        metadata = CSS.categoryMetadata(cats, { type: type });

      } else if (distinctPercentage >=1) {

        var visFunction = CSS.choropleth;

        if (geometryType === 'point'){
          visualizationType = "bubble";
          visFunction = CSS.bubble;
        }

        var properties = getMethodProperties(stats);
        css = visFunction(properties.method, tableName, columnName, geometryType, properties.ramp);
      }
    }

  } else if (type === 'string') {

    visualizationType   = "category";

    var cats = stats.hist;
    cats = _.sortBy(cats, function(cat) { return cat[1]; }).reverse().slice(0, ramps.category.length);
    cats = _.sortBy(cats, function(cat) { return cat[0]; });
    cats = cats.map(function(r) { return r[0]; });

    css      = CSS.category(cats, tableName, columnName, geometryType);
    metadata = CSS.categoryMetadata(cats);

  } else if (type === 'date') {
    visualizationType = "torque";
    css = CSS.torque(stats, tableName);

  } else if (type === 'boolean') {
    visualizationType  = "category";
    var ramp = ramps.bool;
    var cats = ['true', 'false', null];
    var options = { type: type, ramp: ramp };
    css      = CSS.category(cats, tableName, columnName, geometryType, options);
    metadata = CSS.categoryMetadata(cats, options);
  } else if (stats.type === 'geom') {
    visualizationType = "heatmap";
    css = CSS.heatmap(stats, tableName, options);
  }

  var properties = {
    sql: sql,
    geometryType: geometryType,
    column: columnName,
    bbox: column.get("bbox"),
    type: type,
    visualizationType: visualizationType
  };

  if (css) {
    properties.css = css;
  } else {
    properties.css = null;
    properties.weight = -100;
  }

  if (stats) {
    properties.stats = stats;
  }

  if (metadata) {
    properties.metadata = metadata;
  }

  return properties;
}

/*
CartoCSS.guess({
  user: '  '
  sql: '...'
  column:
})
*/

CSS.guess = guess;
CSS.guessCss = guessCss;
CSS.guessMap = guessMap;
CSS.getWeightFromShape = getWeightFromShape;
CSS.getMethodProperties = getMethodProperties;

root.cartodb.CartoCSS = CSS;

})();
<commit_msg>Changes the default basemap ramp to blue to avoid problems with the positron basemap<commit_after>
;(function() {

var root = this;

root.cartodb = root.cartodb || {};

var ramps = {
  bool: ['#229A00', '#F84F40', '#DDDDDD'],
  green:  ['#EDF8FB', '#D7FAF4', '#CCECE6', '#66C2A4', '#41AE76', '#238B45', '#005824'],
  blue:  ['#FFFFCC', '#C7E9B4', '#7FCDBB', '#41B6C4', '#1D91C0', '#225EA8', '#0C2C84'],
  pink: ['#F1EEF6', '#D4B9DA', '#C994C7', '#DF65B0', '#E7298A', '#CE1256', '#91003F'],
  black:  ['#F7F7F7', '#D9D9D9', '#BDBDBD', '#969696', '#737373', '#525252', '#252525'],
  red:  ['#FFFFB2', '#FED976', '#FEB24C', '#FD8D3C', '#FC4E2A', '#E31A1C', '#B10026'],
  category: ['#A6CEE3', '#1F78B4', '#B2DF8A', '#33A02C', '#FB9A99', '#E31A1C', '#FDBF6F', '#FF7F00', '#CAB2D6', '#6A3D9A', '#DDDDDD'],
  divergent: ['#0080FF', '#40A0FF', '#7FBFFF', '#FFF2CC', '#FFA6A6', '#FF7A7A', '#FF4D4D']
};

function geoAttr(geometryType) {
  return {
    "line": 'line-color',
    'polygon': "polygon-fill",
    'point': "marker-fill"
  }[geometryType]
}

function getDefaultCSSForGeometryType(geometryType) {
  if (geometryType === "polygon") {
    return [
      "polygon-opacity: 0.7;",
      "line-color: #FFF;",
      "line-width: 0.5;",
      "line-opacity: 1;"
    ];
  }
  if (geometryType === "line") {
    return  [
      "line-width: 2;",
      "line-opacity: 0.7;"
    ];
  }
  return [
    "line-color: #0C2C84;",
    "line-opacity: 1;",
    "marker-fill-opacity: 0.9;",
    "marker-line-color: #FFF;",
    "marker-line-width: 1;",
    "marker-line-opacity: 1;",
    "marker-placement: point;",
    "marker-type: ellipse;",
    "marker-width: 10;",
    "marker-allow-overlap: true;"
  ];
}

var CSS = {
  choropleth: function(quartiles, tableName, prop, geometryType, ramp) {
    var attr = geoAttr(geometryType);
    var tableID = "#" + tableName;

    var defaultCSS = getDefaultCSSForGeometryType(geometryType);
    var css = "/** choropleth visualization */\n\n" + tableID + " {\n  " + attr + ": " + ramp[0] + ";\n" + defaultCSS.join("\n") + "\n}\n";

    for (var i = quartiles.length - 1; i >= 0; --i) {
      if (quartiles[i] !== undefined && quartiles[i] != null) {
        css += "\n" + tableID + "[" + prop + " <= " + quartiles[i] + "] {\n";
        css += "  " + attr  + ":" + ramp[i] + ";\n}"
      }
    }
    return css;
  },

  categoryMetadata: function(cats, options) {
    var metadata = [];

    var ramp = (options && options.ramp) ? options.ramp : ramps.category;
    var type = options && options.type ? options.type : "string";

    for (var i = 0; i < cats.length; i++) {
      var cat = cats[i];
      if (i < 10 && cat !== undefined && ((type === 'string' && cat != null) || (type !== 'string'))) {
        metadata.push({ title: cat, title_type: type, value_type: 'color', color: ramp[i] });
      }
    }

    if (cats.length > 10) {
      metadata.push({ title: "Others", value_type: 'color', default: true, color: ramp[ramp.length - 1] });
    }

    return metadata;
  },

  category: function(cats, tableName, prop, geometryType, options) {
    var attr = geoAttr(geometryType);
    var tableID = "#" + tableName;
    var ramp = ramps.category;
    var name, value;

    var type = options && options.type ? options.type : "string";
    var ramp = (options && options.ramp) ? options.ramp : ramps.category;

    var defaultCSS = getDefaultCSSForGeometryType(geometryType);

    var css = "/** category visualization */\n\n" + tableID + " {\n  " + attr + ": " + ramp[0] + ";\n" + defaultCSS.join("\n") + "\n}\n";

    for (var i = 0; i < cats.length; i++) {

      var cat = cats[i];

      if (type === 'string') {
        name = cat.replace(/\n/g,'\\n').replace(/\"/g, "\\\"");
        value = "\"" + name + "\"";
      } else {
        value = cat;
      }

      if (i < 10 && cat !== undefined && ((type === 'string' && cat != null) || (type !== 'string'))) {
        css += "\n" + tableID + "[" + prop + "=" + value + "] {\n";
        css += "  " + attr  + ":" + ramp[i] + ";\n}"
      }
    }

    if (cats.length > 10) {
      css += "\n" + tableID + "{\n";
      css += "  " + attr  + ": " + ramp[ramp.length - 1]+ ";\n}"
    }

    return css;
  },

  torque: function(stats, tableName, options){
    var tableID = "#" + tableName;
    var aggFunction = "count(cartodb_id)";
    var css = [
        '/** torque visualization */',
        'Map {',
        '  -torque-time-attribute: ' + stats.column + ';',
        '  -torque-aggregation-function: "count(cartodb_id)";',
        '  -torque-frame-count: ' + stats.steps + ';',
        '  -torque-animation-duration: 10;',
        '  -torque-resolution: 2;',
        '}',
        tableID + " {",
        '  marker-width: 3;',
        '  marker-fill-opacity: 0.8;',
        '  marker-fill: #0F3B82; ',
        '  comp-op: "lighten"; ',
        '  [frame-offset = 1] { marker-width: 10; marker-fill-opacity: 0.05;}',
        '  [frame-offset = 2] { marker-width: 15; marker-fill-opacity: 0.02;}',
        '}'
    ];
    css = css.join('\n');

    return css;

  },

  bubble: function(quartiles, tableName, prop) {
    var tableID = "#" + tableName;
    var css = "/** bubble visualization */\n\n" + tableID + " {\n";
    css += getDefaultCSSForGeometryType("point").join('\n');
    css += "\nmarker-fill: #FF5C00;";
    css += "\n}\n\n";

    var min = 10;
    var max = 30;

    var values = [];

    var NPOINS = 10;
    for(var i = 0; i < NPOINS; ++i) {
      var t = i/(NPOINS-1);
      values.push(min + t*(max - min));
    }

    // generate carto
    for(var i = NPOINS - 1; i >= 0; --i) {
      if(quartiles[i] !== undefined && quartiles[i] != null) {
        css += "\n#" + tableName +" [ " + prop + " <= " + quartiles[i] + "] {\n"
        css += "   marker-width: " + values[i].toFixed(1) + ";\n}"
      }
    }
    return css;
  },

  heatmap: function(stats, tableName, options){
    var tableID = "#" + tableName;
    var css = [
        '/** heatmap visualization */',
        'Map {',
        '  -torque-time-attribute: "cartodb_id";',
        '  -torque-aggregation-function: "count(cartodb_id)";',
        '  -torque-frame-count: 1;',
        '  -torque-animation-duration: 10;',
        '  -torque-resolution: 2;',
        '}',
        tableID + " {",
        '  marker-width: 10;',
        '  marker-fill-opacity: 0.4;',
        '  marker-fill: #0F3B82; ',
        '  comp-op: "lighten"; ',
        '  image-filters: colorize-alpha(blue, cyan, lightgreen, yellow , orange, red);',
        '  marker-file: url(http://s3.amazonaws.com/com.cartodb.assets.static/alphamarker.png);',
        '}'
    ];
    css = css.join('\n');
    return css;
  }
}

function guessCss(sql, geometryType, column, stats) {
  var css = null
  if (stats.type === 'number') {
    css =  CSS.choropleth(stats.quantiles, column, geometryType, ramps.red);
  } else if(stats.type === 'string') {
    css = CSS.category(stats.hist.slice(0, ramps.cat.length).map(function(r) { return r[0]; }), column, geometryType)
  }
  return css;
}

function guess(o, callback) {
  if (!callback) throw new Error("no callback");
  var s = cartodb.SQL({ user: o.user });
  s.describe(o.sql, 'the_geom', function(data) {
    var geometryType = data.simplified_geometry_type;
    s.describe(o.sql, o.column, function(data) {
      callback(
        null,
        guessCss(o.sql, geometryType, data.column, data)
      )
    });
  })
}

function getWeightFromShape(dist_type){
  return {
    U: 0.9,
    A: 0.9,
    L: 0.7,
    J: 0.7,
    S: 0.5,
    F: 0.3
  }[dist_type];
}

function getMethodProperties(stats) { // TODO: only require the necessary params

  var method;
  var ramp = ramps.blue;
  var name = "blue";

  if (['A','U'].indexOf(stats.dist_type) != -1) { // apply divergent scheme
    method = stats.jenks;

    if (stats.min < 0 && stats.max > 0){
      ramp = ramps.divergent;
      name = "spectrum2";
    }

  } else if (stats.dist_type === 'F') {
    method = stats.equalint;
    ramp = ramps.red;
    name = "red";
  } else {
    if (stats.dist_type === 'J') {
      method = stats.headtails;
      ramp = ramps.blue;
      name = "blue";
    } else {
      //ramp = (_.clone(ramps.red)).reverse();
      method = stats.headtails;
      ramp = ramps.red;
      name = "red";
    }
  }

  return { name: name, ramp: ramp, method: method };

}

function guessMap(sql, tableName, column, stats) {
  var geometryType = column.get("geometry_type");
  var columnName = column.get("column");
  var visualizationType = "choropleth";
  var css = null
  var type = stats.type;
  var metadata = []
  var distinctPercentage = (stats.distinct / stats.count) * 100;

  if (type === 'number') {

    var calc_weight = (stats.weight + getWeightFromShape(stats.dist_type)) / 2;

    if (calc_weight >= 0.5) {

      var visFunction = CSS.choropleth;
      var properties = getMethodProperties(stats);

      if (stats.count < 200 && geometryType === 'point'){
        visualizationType = "bubble";
        visFunction = CSS.bubble;
      }

      css = visFunction(properties.method, tableName, columnName, geometryType, properties.ramp);

    } else if (stats.weight > 0.5 || distinctPercentage < 25) {

      if (distinctPercentage < 1) {
        visualizationType   = "category";

        var cats = stats.cat_hist;
        cats = _.sortBy(cats, function(cat) { return cat[1]; }).reverse().slice(0, ramps.category.length);
        cats = _.sortBy(cats, function(cat) { return cat[0]; });
        cats = cats.map(function(r) { return r[0]; });

        css      = CSS.category(cats, tableName, columnName, geometryType, { type: type });
        metadata = CSS.categoryMetadata(cats, { type: type });

      } else if (distinctPercentage >=1) {

        var visFunction = CSS.choropleth;

        if (geometryType === 'point'){
          visualizationType = "bubble";
          visFunction = CSS.bubble;
        }

        var properties = getMethodProperties(stats);
        css = visFunction(properties.method, tableName, columnName, geometryType, properties.ramp);
      }
    }

  } else if (type === 'string') {

    visualizationType   = "category";

    var cats = stats.hist;
    cats = _.sortBy(cats, function(cat) { return cat[1]; }).reverse().slice(0, ramps.category.length);
    cats = _.sortBy(cats, function(cat) { return cat[0]; });
    cats = cats.map(function(r) { return r[0]; });

    css      = CSS.category(cats, tableName, columnName, geometryType);
    metadata = CSS.categoryMetadata(cats);

  } else if (type === 'date') {
    visualizationType = "torque";
    css = CSS.torque(stats, tableName);

  } else if (type === 'boolean') {
    visualizationType  = "category";
    var ramp = ramps.bool;
    var cats = ['true', 'false', null];
    var options = { type: type, ramp: ramp };
    css      = CSS.category(cats, tableName, columnName, geometryType, options);
    metadata = CSS.categoryMetadata(cats, options);
  } else if (stats.type === 'geom') {
    visualizationType = "heatmap";
    css = CSS.heatmap(stats, tableName, options);
  }

  var properties = {
    sql: sql,
    geometryType: geometryType,
    column: columnName,
    bbox: column.get("bbox"),
    type: type,
    visualizationType: visualizationType
  };

  if (css) {
    properties.css = css;
  } else {
    properties.css = null;
    properties.weight = -100;
  }

  if (stats) {
    properties.stats = stats;
  }

  if (metadata) {
    properties.metadata = metadata;
  }

  return properties;
}

/*
CartoCSS.guess({
  user: '  '
  sql: '...'
  column:
})
*/

CSS.guess = guess;
CSS.guessCss = guessCss;
CSS.guessMap = guessMap;
CSS.getWeightFromShape = getWeightFromShape;
CSS.getMethodProperties = getMethodProperties;

root.cartodb.CartoCSS = CSS;

})();
<|endoftext|>


<commit_before>"use strict";
apingApp.service('apingModels', [function () {
    this.getNew = function(_model, _platform) {
        var model = {};
        switch(_model) {
            case "social":
                model = {
                    platform : _platform, //NAME of platform ( "youtube" / "facebook", "instagram" , ...)
                    blog_name : false, //NAME of blog (channel / youtube uploader / facebook page, instagram account, ..)
                    blog_id : false, //ID of channel / page / account, ...
                    blog_link : false, //link to channel / uploader / page / account, ...
                    type : false, //"video", "image", "post", "audio", "link", "event", ...
                    timestamp : false,
                    date_time: false,
                    post_url : false, //URL to the post / video / tweet ...
                    intern_id : false, // INTERN ID of post / video / tweet / ... (facebook id, youtube id, ...)
                    text : false,
                    caption : false,
                    img_url : false,
                    source : false, //
                    likes: false,
                    shares: false,
                    comments: false,
                    position: false,
                };
                break;

            case "video":
                model = {
                    platform : _platform, //NAME of platform ( "youtube" / "facebook", "instagram" , ...)
                    blog_name : false, //NAME of blog (channel / youtube uploader / facebook page, instagram account, ..)
                    blog_id : false, //ID of channel / page / account, ...
                    blog_link : false, //link to channel / uploader / page / account, ...
                    timestamp : false,
                    date_time: false,
                    post_url : false, //URL to the post / video / tweet ...
                    intern_id : false, // INTERN ID of video (facebook id, youtube id, ...)
                    text : false,
                    caption : false,
                    img_url : false,
                    source : false, //
                    markup: false,
                    likes: false,
                    shares: false,
                    comments: false,
                    position: false,
                };
                break;

            case "image":
                model = {
                    platform : _platform, //NAME of platform ( "youtube" / "facebook", "instagram" , ...)
                    blog_name : false, //NAME of blog (channel / youtube uploader / facebook page, instagram account, ..)
                    blog_id : false, //ID of channel / page / account, ...
                    blog_link : false, //link to channel / uploader / page / account, ...
                    timestamp : false,
                    date_time: false,
                    post_url : false, //URL to the post / video / tweet ...
                    intern_id : false, // INTERN ID of image (facebook id, instagram id, ...)
                    text : false,
                    caption : false,
                    img_url : false,
                    source : false, //
                    likes: false,
                    shares: false,
                    comments: false,
                    position: false,
                };
                break;

            case "event":
                model = {
                    platform : _platform, //NAME of platform ( "youtube" / "facebook", "instagram" , ...)
                    blog_name : false, //NAME of blog (channel / facebook page, instagram account, ..)
                    blog_id : false, //ID of channel / page / account, ...
                    blog_link : false, //link to channel / uploader / page / account, ...
                    start_timestamp : false,
                    start_date_time: false,
                    end_timestamp: false,
                    end_date_time: false,
                    event_url : false, //URL to the event
                    ticket_url : false, //URL to the ticket
                    intern_id : false, // INTERN ID of event (facebook id, instagram id, ...)
                    text : false,
                    caption : false,
                    img_url : false,
                    place_name : false,
                    city: false,
                    country: false,
                    latitude: false,
                    longitude : false,
                    street: false,
                    zip : false,
                    source : false,
                };
                break;

            case "repo":
                model = {
                    platform : _platform, //NAME of platform ( "youtube" / "facebook", "instagram" , ...)
                    owner_name : false,
                    owner_id : false,
                    owner_link : false,
                    owner_img_url : false,
                    name : false,
                    id: false,
                    fullname: false,
                    description : false,
                    url : false,
                    homepage : false,
                    language : false,
                    clone_url : false,
                    git_url : false,
                    ssh_url : false,
                    svn_url : false,
                    isFork : false,
                    openIssues : false,
                    watchers : false,
                    stargazers : false,
                    forks : false,
                    created_timestamp : false,
                    created_date_time: false,
                    updated_timestamp: false,
                    updated_date_time: false,
                    pushed_timestamp: false,
                    pushed_date_time: false,
                };
                break;

            case "activity":
                model = {
                    platform : _platform, //NAME of platform ( "youtube" / "facebook", "instagram" , ...)

                    body : false,

                    actor_name : false, //who?
                    actor_id : false,
                    actor_url : false,
                    actor_img_url : false,
                    actor_type: false,

                    action_message : false, //what?
                    action_id : false,
                    action_url : false,
                    action_img : false,
                    action_type: false,

                    object_name : false,
                    object_id : false,
                    object_img : false,
                    object_url : false,
                    object_type: false,

                    context : false,
                    timestamp : false,
                    date_time: false,

                };
                break;

            default:
                break;
        }
        return model;
    }
}]);<commit_msg>impr: re-added attribute to model "activity"<commit_after>"use strict";
apingApp.service('apingModels', [function () {
    this.getNew = function(_model, _platform) {
        var model = {};
        switch(_model) {
            case "social":
                model = {
                    platform : _platform, //NAME of platform ( "youtube" / "facebook", "instagram" , ...)
                    blog_name : false, //NAME of blog (channel / youtube uploader / facebook page, instagram account, ..)
                    blog_id : false, //ID of channel / page / account, ...
                    blog_link : false, //link to channel / uploader / page / account, ...
                    type : false, //"video", "image", "post", "audio", "link", "event", ...
                    timestamp : false,
                    date_time: false,
                    post_url : false, //URL to the post / video / tweet ...
                    intern_id : false, // INTERN ID of post / video / tweet / ... (facebook id, youtube id, ...)
                    text : false,
                    caption : false,
                    img_url : false,
                    source : false, //
                    likes: false,
                    shares: false,
                    comments: false,
                    position: false,
                };
                break;

            case "video":
                model = {
                    platform : _platform, //NAME of platform ( "youtube" / "facebook", "instagram" , ...)
                    blog_name : false, //NAME of blog (channel / youtube uploader / facebook page, instagram account, ..)
                    blog_id : false, //ID of channel / page / account, ...
                    blog_link : false, //link to channel / uploader / page / account, ...
                    timestamp : false,
                    date_time: false,
                    post_url : false, //URL to the post / video / tweet ...
                    intern_id : false, // INTERN ID of video (facebook id, youtube id, ...)
                    text : false,
                    caption : false,
                    img_url : false,
                    source : false, //
                    markup: false,
                    likes: false,
                    shares: false,
                    comments: false,
                    position: false,
                };
                break;

            case "image":
                model = {
                    platform : _platform, //NAME of platform ( "youtube" / "facebook", "instagram" , ...)
                    blog_name : false, //NAME of blog (channel / youtube uploader / facebook page, instagram account, ..)
                    blog_id : false, //ID of channel / page / account, ...
                    blog_link : false, //link to channel / uploader / page / account, ...
                    timestamp : false,
                    date_time: false,
                    post_url : false, //URL to the post / video / tweet ...
                    intern_id : false, // INTERN ID of image (facebook id, instagram id, ...)
                    text : false,
                    caption : false,
                    img_url : false,
                    source : false, //
                    likes: false,
                    shares: false,
                    comments: false,
                    position: false,
                };
                break;

            case "event":
                model = {
                    platform : _platform, //NAME of platform ( "youtube" / "facebook", "instagram" , ...)
                    blog_name : false, //NAME of blog (channel / facebook page, instagram account, ..)
                    blog_id : false, //ID of channel / page / account, ...
                    blog_link : false, //link to channel / uploader / page / account, ...
                    start_timestamp : false,
                    start_date_time: false,
                    end_timestamp: false,
                    end_date_time: false,
                    event_url : false, //URL to the event
                    ticket_url : false, //URL to the ticket
                    intern_id : false, // INTERN ID of event (facebook id, instagram id, ...)
                    text : false,
                    caption : false,
                    img_url : false,
                    place_name : false,
                    city: false,
                    country: false,
                    latitude: false,
                    longitude : false,
                    street: false,
                    zip : false,
                    source : false,
                };
                break;

            case "repo":
                model = {
                    platform : _platform, //NAME of platform ( "youtube" / "facebook", "instagram" , ...)
                    owner_name : false,
                    owner_id : false,
                    owner_link : false,
                    owner_img_url : false,
                    name : false,
                    id: false,
                    fullname: false,
                    description : false,
                    url : false,
                    homepage : false,
                    language : false,
                    clone_url : false,
                    git_url : false,
                    ssh_url : false,
                    svn_url : false,
                    isFork : false,
                    openIssues : false,
                    watchers : false,
                    stargazers : false,
                    forks : false,
                    created_timestamp : false,
                    created_date_time: false,
                    updated_timestamp: false,
                    updated_date_time: false,
                    pushed_timestamp: false,
                    pushed_date_time: false,
                };
                break;

            case "activity":
                model = {
                    platform : _platform, //NAME of platform ( "youtube" / "facebook", "instagram" , ...)

                    body : false,

                    actor_name : false, //who?
                    actor_id : false,
                    actor_url : false,
                    actor_img_url : false,
                    actor_type: false,

                    action_name: false,
                    action_message : false, //what?
                    action_id : false,
                    action_url : false,
                    action_img : false,
                    action_type: false,

                    object_name : false,
                    object_id : false,
                    object_img : false,
                    object_url : false,
                    object_type: false,

                    context : false,
                    timestamp : false,
                    date_time: false,

                };
                break;

            default:
                break;
        }
        return model;
    }
}]);<|endoftext|>


<commit_before>define([
    'app/config',
    'app/_GPMixin',
    'app/_ResultsQueryMixin',

    'dijit/_TemplatedMixin',
    'dijit/_WidgetBase',

    'dojo/dom-attr',
    'dojo/dom-class',
    'dojo/text!app/templates/Download.html',
    'dojo/_base/declare',
    'dojo/_base/lang',

    'ladda'
], function (
    config,
    _GPMixin,
    _ResultsQueryMixin,

    _TemplatedMixin,
    _WidgetBase,

    domAttr,
    domClass,
    template,
    declare,
    lang,

    Ladda
) {
    return declare([_WidgetBase, _TemplatedMixin, _ResultsQueryMixin, _GPMixin], {
        // description:
        //      Download the currently filtered data.
        templateString: template,
        baseClass: 'download',

        // Properties to be sent into constructor

        initSpinner: function () {
            // summary:
            //      set up the ladda spinner
            console.log('app.Download:initSpinner', arguments);

            if (!this.spinner) {
                this.spinner = Ladda.create(this.btn);
            }
        },
        onClick: function () {
            // summary:
            //      submit form
            console.log('app.Download::onClick', arguments);

            this.initSpinner();

            if (!this.checkForCurrentQuery()) {
                return;
            }

            this.reset();
            this.spinner.start();

            this.submitJob({
                format: this.formatSelect.value,
                query: this.convertToResultsQuery(this.currentQuery)
            });
        },
        onFormatChange: function () {
            // summary:
            //      type changed
            console.log('app.Download:onFormatChange');

            this.btn.disabled = this.formatSelect.value === '-1';
        },
        switchToSecure: function () {
            // summary:
            //      description
            console.log('app.Download:switchToSecure', arguments);

            this.initGP(config.urls.secureDownload);
        },
        reset: function () {
            // summary:
            //      description
            console.log('app.Download:reset', arguments);

            domClass.add(this.linkContainer, 'hidden');
            this.spinner.stop();
        },
        onDownloadGPComplete: function (result) {
            // summary:
            //      callback for gp task
            // result: esri/tasks/ParameterValue
            console.log('app.Download:onDownloadGPComplete', arguments);

            this.link.href = result.value.url;

            domClass.remove(this.linkContainer, 'hidden');
            this.spinner.stop();
        },
        onJobComplete: function (results) {
            // summary:
            //      description
            // results: Event Object
            console.log('app.Download:onJobComplete', arguments);

            this.gp.getResultData(results.jobInfo.jobId, 'zipfile', lang.hitch(this, 'onDownloadGPComplete'));
        }
    });
});
<commit_msg>reset download on error<commit_after>define([
    'app/config',
    'app/_GPMixin',
    'app/_ResultsQueryMixin',

    'dijit/_TemplatedMixin',
    'dijit/_WidgetBase',

    'dojo/dom-attr',
    'dojo/dom-class',
    'dojo/text!app/templates/Download.html',
    'dojo/_base/declare',
    'dojo/_base/lang',

    'ladda'
], function (
    config,
    _GPMixin,
    _ResultsQueryMixin,

    _TemplatedMixin,
    _WidgetBase,

    domAttr,
    domClass,
    template,
    declare,
    lang,

    Ladda
) {
    return declare([_WidgetBase, _TemplatedMixin, _ResultsQueryMixin, _GPMixin], {
        // description:
        //      Download the currently filtered data.
        templateString: template,
        baseClass: 'download',

        // Properties to be sent into constructor

        initSpinner: function () {
            // summary:
            //      set up the ladda spinner
            console.log('app.Download:initSpinner', arguments);

            if (!this.spinner) {
                this.spinner = Ladda.create(this.btn);
            }
        },
        onClick: function () {
            // summary:
            //      submit form
            console.log('app.Download::onClick', arguments);

            this.initSpinner();

            if (!this.checkForCurrentQuery()) {
                return;
            }

            this.reset();
            this.spinner.start();

            this.submitJob({
                format: this.formatSelect.value,
                query: this.convertToResultsQuery(this.currentQuery)
            });
        },
        initGP: function () {
            console.log('app.Download:initGP', arguments);

            this.inherited(arguments);

            this.gp.on('error', this.reset.bind(this));
        },
        onFormatChange: function () {
            // summary:
            //      type changed
            console.log('app.Download:onFormatChange');

            this.btn.disabled = this.formatSelect.value === '-1';
        },
        switchToSecure: function () {
            // summary:
            //      description
            console.log('app.Download:switchToSecure', arguments);

            this.initGP(config.urls.secureDownload);
        },
        reset: function () {
            // summary:
            //      description
            console.log('app.Download:reset', arguments);

            domClass.add(this.linkContainer, 'hidden');
            this.spinner.stop();
        },
        onDownloadGPComplete: function (result) {
            // summary:
            //      callback for gp task
            // result: esri/tasks/ParameterValue
            console.log('app.Download:onDownloadGPComplete', arguments);

            this.link.href = result.value.url;

            domClass.remove(this.linkContainer, 'hidden');
            this.spinner.stop();
        },
        onJobComplete: function (results) {
            // summary:
            //      description
            // results: Event Object
            console.log('app.Download:onJobComplete', arguments);

            this.gp.getResultData(results.jobInfo.jobId, 'zipfile', lang.hitch(this, 'onDownloadGPComplete'));
        }
    });
});
<|endoftext|>


<commit_before>'use strict'

var remix = require('ethereum-remix')

/**
 * Manage remix and source highlighting
 */
function Debugger (id, appAPI, executionContextEvent, editorEvent) {
  this.el = document.querySelector(id)
  this.debugger = new remix.ui.Debugger()
  this.sourceMappingDecoder = new remix.util.SourceMappingDecoder()
  this.el.appendChild(this.debugger.render())
  this.appAPI = appAPI
  this.markers = {}
  this.breakPointManager = new remix.code.BreakpointManager(this.debugger, (sourceLocation) => {
    return this.offsetToLineColumnConverter.offsetToLineColumn(sourceLocation, sourceLocation.file, this.editor, this.compiler.lastCompilationResult.data)
  })

  this.debugger.setBreakpointManager(this.breakPointManager)
  this.breakPointManager.event.register('breakpointHit', (sourceLocation) => {})

  function convertSourceLocation (self, fileName, row) {
    var source = {}
    for (let file in self.compiler.lastCompilationResult.data.sourceList) {
      if (self.compiler.lastCompilationResult.data.sourceList[file] === fileName) {
        source.file = file
        break
      }
    }
    source.row = row
    return source
  }

  editorEvent.register('breakpointCleared', (fileName, row) => {
    if (self.compiler.lastCompilationResult.data) {
      this.breakPointManager.remove(convertSourceLocation(this, fileName, row))
    }
  })

  editorEvent.register('breakpointAdded', (fileName, row) => {
    if (self.compiler.lastCompilationResult.data) {
      this.breakPointManager.add(convertSourceLocation(this, fileName, row))
    }
  })

  var self = this
  executionContextEvent.register('contextChanged', this, function (context) {
    self.switchProvider(context)
  })

  this.debugger.event.register('traceUnloaded', this, function () {
    self.appAPI.currentSourceLocation(null)
  })

  // unload if a file has changed (but not if tabs were switched)
  editorEvent.register('contentChanged', function () {
    self.debugger.unLoad()
    self.removeMarkers()
  })

  // register selected code item, highlight the corresponding source location
  this.debugger.codeManager.event.register('changed', this, function (code, address, index) {
    if (self.appAPI.lastCompilationResult()) {
      this.debugger.callTree.sourceLocationTracker.getSourceLocationFromInstructionIndex(address, index, self.appAPI.lastCompilationResult().data.contracts, function (error, rawLocation) {
        if (!error) {
          var lineColumnPos = self.appAPI.offsetToLineColumn(rawLocation, rawLocation.file)
          self.appAPI.currentSourceLocation(lineColumnPos, rawLocation)
        } else {
          self.appAPI.currentSourceLocation(null)
        }
      })
    }
  })
}

/**
 * Start debugging using Remix
 *
 * @param {String} txHash    - hash of the transaction
 */
Debugger.prototype.debug = function (txHash) {
  var self = this
  this.debugger.web3().eth.getTransaction(txHash, function (error, tx) {
    if (!error) {
      self.debugger.setCompilationResult(self.appAPI.lastCompilationResult().data)
      self.debugger.debug(tx)
    }
  })
}

Debugger.prototype.switchFile = function (rawLocation) {
  var name = this.editor.getCacheFile() // current opened tab
  var source = this.compiler.lastCompilationResult.data.sourceList[rawLocation.file] // auto switch to that tab
  if (name !== source) {
    this.switchToFile(source) // command the app to swicth to the next file
  }
}

/**
 * add a new web3 provider to remix
 *
 * @param {String} type - type/name of the provider to add
 * @param {Object} obj  - provider
 */
Debugger.prototype.addProvider = function (type, obj) {
  this.debugger.addProvider(type, obj)
}

/**
 * switch the provider
 *
 * @param {String} type - type/name of the provider to use
 */
Debugger.prototype.switchProvider = function (type) {
  this.debugger.switchProvider(type)
}

/**
 * get the current provider
 */
Debugger.prototype.web3 = function (type) {
  return this.debugger.web3()
}

module.exports = Debugger
<commit_msg>check if compilation available<commit_after>'use strict'

var remix = require('ethereum-remix')

/**
 * Manage remix and source highlighting
 */
function Debugger (id, appAPI, executionContextEvent, editorEvent) {
  this.el = document.querySelector(id)
  this.debugger = new remix.ui.Debugger()
  this.sourceMappingDecoder = new remix.util.SourceMappingDecoder()
  this.el.appendChild(this.debugger.render())
  this.appAPI = appAPI
  this.markers = {}
  this.breakPointManager = new remix.code.BreakpointManager(this.debugger, (sourceLocation) => {
    return this.offsetToLineColumnConverter.offsetToLineColumn(sourceLocation, sourceLocation.file, this.editor, this.compiler.lastCompilationResult.data)
  })

  this.debugger.setBreakpointManager(this.breakPointManager)
  this.breakPointManager.event.register('breakpointHit', (sourceLocation) => {
  })

  editorEvent.register('breakpointCleared', (fileName, row) => {
    if (self.compiler.lastCompilationResult.data) {
      this.breakPointManager.remove({fileName: fileName, row: row})
    }
  })

  editorEvent.register('breakpointAdded', (fileName, row) => {
    if (self.compiler.lastCompilationResult.data) {
      this.breakPointManager.add({fileName: fileName, row: row})
    }
  })

  var self = this
  executionContextEvent.register('contextChanged', this, function (context) {
    self.switchProvider(context)
  })

  this.debugger.event.register('traceUnloaded', this, function () {
    self.appAPI.currentSourceLocation(null)
  })

  // unload if a file has changed (but not if tabs were switched)
  editorEvent.register('contentChanged', function () {
    self.debugger.unLoad()
    self.removeMarkers()
  })

  // register selected code item, highlight the corresponding source location
  this.debugger.codeManager.event.register('changed', this, function (code, address, index) {
    if (self.appAPI.lastCompilationResult()) {
      this.debugger.callTree.sourceLocationTracker.getSourceLocationFromInstructionIndex(address, index, self.appAPI.lastCompilationResult().data.contracts, function (error, rawLocation) {
        if (!error) {
          var lineColumnPos = self.appAPI.offsetToLineColumn(rawLocation, rawLocation.file)
          self.appAPI.currentSourceLocation(lineColumnPos, rawLocation)
        } else {
          self.appAPI.currentSourceLocation(null)
        }
      })
    }
  })
}

/**
 * Start debugging using Remix
 *
 * @param {String} txHash    - hash of the transaction
 */
Debugger.prototype.debug = function (txHash) {
  var self = this
  this.debugger.web3().eth.getTransaction(txHash, function (error, tx) {
    if (!error) {
      self.debugger.setCompilationResult(self.appAPI.lastCompilationResult().data)
      self.debugger.debug(tx)
    }
  })
}

Debugger.prototype.switchFile = function (rawLocation) {
  var name = this.editor.getCacheFile() // current opened tab
  if (this.compiler.lastCompilationResult.data) {
    var source = this.compiler.lastCompilationResult.data.sourceList[rawLocation.file] // auto switch to that tab
    if (name !== source) {
      this.switchToFile(source) // command the app to swicth to the next file
    }
  }
}

/**
 * add a new web3 provider to remix
 *
 * @param {String} type - type/name of the provider to add
 * @param {Object} obj  - provider
 */
Debugger.prototype.addProvider = function (type, obj) {
  this.debugger.addProvider(type, obj)
}

/**
 * switch the provider
 *
 * @param {String} type - type/name of the provider to use
 */
Debugger.prototype.switchProvider = function (type) {
  this.debugger.switchProvider(type)
}

/**
 * get the current provider
 */
Debugger.prototype.web3 = function (type) {
  return this.debugger.web3()
}

module.exports = Debugger
<|endoftext|>


<commit_before>import { combineReducers } from 'redux';
import * as authReducers from './../auth/authReducers';
import * as messageReducers from './../message/messageReducers';

export default combineReducers({
  auth: authReducers.auth,
  userMessage: messageReducers.userMessage,
  messages: messageReducers.messages
});
<commit_msg>add users reducer to the main state<commit_after>import { combineReducers } from 'redux';
import * as authReducers from './../auth/authReducers';
import * as messageReducers from './../message/messageReducers';
import * as usersReducers from './../user/userReducers';

export default combineReducers({
  auth: authReducers.auth,
  userMessage: messageReducers.userMessage,
  messages: messageReducers.messages,
  users: usersReducers.users
});
<|endoftext|>


<commit_before>'use strict'

const _h = require('./_helpers')
const crypto = require('crypto')

exports.handler = async (event, context) => {
  if (event.source === 'aws.events') { return }

  try {
    const key = await _h.ssmParameter('entu-api-lhv-key')
    const next = _.get(event, 'queryStringParameters.next')

    const data = {
      VK_SERVICE: '4011',
      VK_VERSION: '008',
      VK_SND_ID: 'ENTUSIASTID',
      VK_REPLY: '3012',
      VK_RETURN: next ? 'https://api.entu.app/auth/lhv?next=' + next : 'https://api.entu.app/auth/lhv',
      VK_DATETIME: (new Date()).toISOString().substr(0, 19) + 'Z',
      VK_RID: '',
      VK_MAC: null,
      VK_ENCODING: 'UTF-8',
      VK_LANG: 'EST',
    }

    const macDataArray = [
      ('000' + data.VK_SERVICE.length).slice(-3),
      data.VK_SERVICE,
      ('000' + data.VK_VERSION.length).slice(-3),
      data.VK_VERSION,
      ('000' + data.VK_SND_ID.length).slice(-3),
      data.VK_SND_ID,
      ('000' + data.VK_REPLY.length).slice(-3),
      data.VK_REPLY,
      ('000' + data.VK_RETURN.length).slice(-3),
      data.VK_RETURN,
      ('000' + data.VK_DATETIME.length).slice(-3),
      data.VK_DATETIME,
      ('000' + data.VK_RID.length).slice(-3),
      data.VK_RID
    ]

    data.VK_MAC = crypto.createSign('SHA1').update(macDataArray.join('')).sign(key, 'base64')

    return _h.json({ url: 'https://www.lhv.ee/banklink', signedRequest: data })
  } catch (e) {
    return _h.error(e)
  }
}
<commit_msg>Get VK_SND_ID from SSM<commit_after>'use strict'

const _ = require('lodash')
const _h = require('./_helpers')
const crypto = require('crypto')

exports.handler = async (event, context) => {
  if (event.source === 'aws.events') { return }

  try {
    const lhvId = await _h.ssmParameter('entu-api-lhv-id')
    const lhvKey = await _h.ssmParameter('entu-api-lhv-key')
    const next = _.get(event, 'queryStringParameters.next')

    const data = {
      VK_SERVICE: '4011',
      VK_VERSION: '008',
      VK_SND_ID: lhvId,
      VK_REPLY: '3012',
      VK_RETURN: next ? 'https://api.entu.app/auth/lhv?next=' + next : 'https://api.entu.app/auth/lhv',
      VK_DATETIME: (new Date()).toISOString().substr(0, 19) + 'Z',
      VK_RID: '',
      VK_MAC: null,
      VK_ENCODING: 'UTF-8',
      VK_LANG: 'EST',
    }

    const macDataArray = [
      ('000' + data.VK_SERVICE.length).slice(-3),
      data.VK_SERVICE,
      ('000' + data.VK_VERSION.length).slice(-3),
      data.VK_VERSION,
      ('000' + data.VK_SND_ID.length).slice(-3),
      data.VK_SND_ID,
      ('000' + data.VK_REPLY.length).slice(-3),
      data.VK_REPLY,
      ('000' + data.VK_RETURN.length).slice(-3),
      data.VK_RETURN,
      ('000' + data.VK_DATETIME.length).slice(-3),
      data.VK_DATETIME,
      ('000' + data.VK_RID.length).slice(-3),
      data.VK_RID
    ]

    data.VK_MAC = crypto.createSign('SHA1').update(macDataArray.join('')).sign(lhvKey, 'base64')

    return _h.json({ url: 'https://www.lhv.ee/banklink', signedRequest: data })
  } catch (e) {
    return _h.error(e)
  }
}
<|endoftext|>