<commit_before>(function () {

less.env = location.hostname == '127.0.0.1' ||
           location.hostname == '0.0.0.0'   ||
           location.hostname == 'localhost' ||
           location.protocol == 'file:'     ||
           location.port.length > 0         ? 'development'
                                            : 'production';

// Load styles asynchronously (default: false)
//
// This is set to `false` by default, so that the body
// doesn't start loading before the stylesheets are parsed.
// Setting this to `true` can result in flickering.
//
less.async = false;

// Interval between watch polls
less.poll = location.protocol == 'file:' ? 1000 : 1500;

//
// Watch mode
//
less.watch   = function () { return this.watchMode = true };
less.unwatch = function () { return this.watchMode = false };

if (less.env === 'development') {
    less.optimization = 0;

    if (/!watch/.test(location.hash)) {
        less.watch();
    }
    less.watchTimer = setInterval(function () {
        if (less.watchMode) {
            loadStyleSheets(function (root, sheet, env) {
                if (root) {
                    createCSS(root.toCSS(), sheet, env.lastModified);
                }
            });
        }
    }, less.poll);
} else {
    less.optimization = 3;
}

//
// Select all links with the 'rel' attribute set to "less"
//
var sheets = select('link[rel="stylesheet/less"]');

less.refresh = function () {
    loadStyleSheets(function (root, sheet, env) {
        if (env.local) {
            log("less: loading " + sheet.href + " from local storage.");
        } else {
            createCSS(root.toCSS(), sheet, env.lastModified);
            log("less: parsed " + sheet.href + " successfully.");
        }
    });
};

less.refresh();

function select(str) {
    if (!document.querySelectorAll && typeof(jQuery) === "undefined") {
        log("No selector method found");
    } else {
        return (document.querySelectorAll || jQuery).call(document, str);
    }
}

function loadStyleSheets(callback, async) {
    for (var i = 0; i < sheets.length; i++) {
        loadStyleSheet(sheets[i], callback, async);
    }
}

function loadStyleSheet(sheet, callback, async) {
    var css = typeof(localStorage) !== "undefined" && localStorage.getItem(sheet.href);
    var timestamp = typeof(localStorage) !== "undefined" && localStorage.getItem(sheet.href + ':timestamp');
    var styles = { css: css, timestamp: timestamp };

    xhr(sheet.href, async, function (data, lastModified) {
        if (styles && (new(Date)(lastModified).valueOf() ===
                       new(Date)(styles.timestamp).valueOf())) {
            // Use local copy
            createCSS(styles.css, sheet);
            callback(null, sheet, { local: true });
        } else {
            // Use remote copy (re-parse)
            new(less.Parser)({
                optimization: less.optimization
            }).parse(data, function (e, root) {
                if (e) { return error(e, sheet.href) }
                try {
                    callback(root, sheet, { local: false, lastModified: lastModified });
                    removeNode(document.getElementById('less-error-message:' + sheet.href.replace(/[^a-z]+/gi, '-')));
                } catch (e) {
                    error(e, sheet.href);
                }
            });
        }
    }, function (status) {
        throw new(Error)("Couldn't load " + sheet.href + " (" + status + ")");
    });
}

function createCSS(styles, sheet, lastModified) {
    var css, title, id;

    // If there is no title set, use the filename, minus the extension
    title = sheet.title || sheet.href.match(/(?:^|\/)([-\w]+)\.[a-z]+$/i)[1];
    id = 'less:' + title;

    // If the stylesheet doesn't exist, create a new node
    if ((css = document.getElementById(id)) === null) {
        css = document.createElement('style');
        css.type = 'text/css';
        css.media = 'screen';
        css.title = title;
        css.id = id;
        document.getElementsByTagName('head')[0].appendChild(css);
    }

    if (css.styleSheet) { // IE
        try {
            css.styleSheet.cssText = styles;
        } catch (e) {
            throw new(Error)("Couldn't reassign styleSheet.cssText.");
        }
    } else {
        (function (node) {
            if (css.childNodes.length > 0) {
                css.replaceChild(node, css.firstChild);
            } else {
                css.appendChild(node);
            }
        })(document.createTextNode(styles));
    }

    // Don't update the local store if the file wasn't modified
    if (lastModified && typeof(localStorage) !== "undefined") {
        localStorage.setItem(sheet.href, styles);
        localStorage.setItem(sheet.href + ':timestamp', lastModified);
    }
}

function xhr(url, async, callback, errback) {
    var xhr = getXMLHttpRequest();

    if (window.location.protocol === "file:") {
        xhr.open('GET', url, false);
        xhr.send(null);
        if (xhr.status === 0) {
            callback(xhr.responseText);
        } else {
            errback(xhr.status);
        }
    } else {
        xhr.open('GET', url, async || less.async);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status >= 200 && xhr.status < 300) {
                    callback(xhr.responseText,
                             xhr.getResponseHeader("Last-Modified"));
                } else if (typeof(errback) === 'function') {
                    errback(xhr.status);
                }
            }
        };
        xhr.send(null);
    }
}

function getXMLHttpRequest() {
    if (window.XMLHttpRequest) {
        return new(XMLHttpRequest);
    } else {
        try {
            return new(ActiveXObject)("MSXML2.XMLHTTP.3.0");
        } catch (e) {
            log("less: browser doesn't support AJAX.");
            return null;
        }
    }
}

function removeNode(node) {
    return node && node.parentNode.removeChild(node);
}

function log(str) {
    if (less.env == 'development' && typeof(console) !== "undefined") { console.log(str) }
}

function error(e, href) {
    var id = 'less-error-message:' + href.replace(/[^a-z]+/ig, '-');

    if (document.getElementById(id)) { return }

    var template = ['
',
                        '
[-1]{0}
',
                        '
[0]{current}
',
                        '
[1]{2}
',
                    '
'].join('\n');

    var elem = document.createElement('div'), timer;
    elem.id = id;
    elem.className = "less-error-message";
    elem.innerHTML = '
' + (e.message || 'There is an error in your .less file') + '
' +
                     '
' + href + " "                +
                     'on line '     + e.line + ', column ' + (e.column + 1)         + ':
' +
                     template.replace(/\[(-?\d)\]/g, function (_, i) {
                         return (parseInt(e.line) + parseInt(i)) || '';
                     }).replace(/\{(\d)\}/g, function (_, i) {
                         return e.extract[parseInt(i)] || '';
                     }).replace(/\{current\}/, e.extract[1].slice(0, e.column)      +
                                               ''               +
                                               e.extract[1].slice(e.column)         +
                                               '');
    // CSS for error messages
    createCSS([
        '.less-error-message span {',
            'margin-right: 15px;',
        '}',
        '.less-error-message pre {',
            'color: #ee4444;',
            'padding: 4px 0;',
            'margin: 0;',
        '}',
        '.less-error-message pre.ctx {',
            'color: #dd7777;',
        '}',
        '.less-error-message h3 {',
            'padding: 15px 0 5px 0;',
            'margin: 0;',
        '}',
        '.less-error-message a {',
            'color: #10a',
        '}',
        '.less-error-message .error {',
            'color: red;',
            'font-weight: bold;',
            'padding-bottom: 2px;',
            'border-bottom: 1px dashed red;',
        '}'
    ].join('\n'), { title: 'error-message' });

    elem.style.cssText = [
        "font-family: Arial, sans-serif",
        "border: 1px solid #e00",
        "background-color: #eee",
        "border-radius: 5px",
        "-webkit-border-radius: 5px",
        "-moz-border-radius: 5px",
        "color: #e00",
        "padding: 15px",
        "margin-bottom: 15px"
    ].join(';');

    if (less.env == 'development') {
        timer = setInterval(function () {
            if (document.body) {
                document.body.insertBefore(elem, document.body.firstChild);
                clearInterval(timer);
            }
        }, 10);
    }
}

//
// Used by `@import` directives
//
less.Parser.importer = function (path, paths, callback) {
    loadStyleSheet({ href: path, title: path }, function (root) {
        callback(root);
    });
};

})();
<commit_msg>don't give style tags a 'title' attribute, it screws things up. [browser]<commit_after>(function () {

less.env = location.hostname == '127.0.0.1' ||
           location.hostname == '0.0.0.0'   ||
           location.hostname == 'localhost' ||
           location.protocol == 'file:'     ||
           location.port.length > 0         ? 'development'
                                            : 'production';

// Load styles asynchronously (default: false)
//
// This is set to `false` by default, so that the body
// doesn't start loading before the stylesheets are parsed.
// Setting this to `true` can result in flickering.
//
less.async = false;

// Interval between watch polls
less.poll = location.protocol == 'file:' ? 1000 : 1500;

//
// Watch mode
//
less.watch   = function () { return this.watchMode = true };
less.unwatch = function () { return this.watchMode = false };

if (less.env === 'development') {
    less.optimization = 0;

    if (/!watch/.test(location.hash)) {
        less.watch();
    }
    less.watchTimer = setInterval(function () {
        if (less.watchMode) {
            loadStyleSheets(function (root, sheet, env) {
                if (root) {
                    createCSS(root.toCSS(), sheet, env.lastModified);
                }
            });
        }
    }, less.poll);
} else {
    less.optimization = 3;
}

//
// Select all links with the 'rel' attribute set to "less"
//
var sheets = select('link[rel="stylesheet/less"]');

less.refresh = function () {
    loadStyleSheets(function (root, sheet, env) {
        if (env.local) {
            log("less: loading " + sheet.href + " from local storage.");
        } else {
            createCSS(root.toCSS(), sheet, env.lastModified);
            log("less: parsed " + sheet.href + " successfully.");
        }
    });
};

less.refresh();

function select(str) {
    if (!document.querySelectorAll && typeof(jQuery) === "undefined") {
        log("No selector method found");
    } else {
        return (document.querySelectorAll || jQuery).call(document, str);
    }
}

function loadStyleSheets(callback, async) {
    for (var i = 0; i < sheets.length; i++) {
        loadStyleSheet(sheets[i], callback, async);
    }
}

function loadStyleSheet(sheet, callback, async) {
    var css = typeof(localStorage) !== "undefined" && localStorage.getItem(sheet.href);
    var timestamp = typeof(localStorage) !== "undefined" && localStorage.getItem(sheet.href + ':timestamp');
    var styles = { css: css, timestamp: timestamp };

    xhr(sheet.href, async, function (data, lastModified) {
        if (styles && (new(Date)(lastModified).valueOf() ===
                       new(Date)(styles.timestamp).valueOf())) {
            // Use local copy
            createCSS(styles.css, sheet);
            callback(null, sheet, { local: true });
        } else {
            // Use remote copy (re-parse)
            new(less.Parser)({
                optimization: less.optimization
            }).parse(data, function (e, root) {
                if (e) { return error(e, sheet.href) }
                try {
                    callback(root, sheet, { local: false, lastModified: lastModified });
                    removeNode(document.getElementById('less-error-message:' + sheet.href.replace(/[^a-z]+/gi, '-')));
                } catch (e) {
                    error(e, sheet.href);
                }
            });
        }
    }, function (status) {
        throw new(Error)("Couldn't load " + sheet.href + " (" + status + ")");
    });
}

function createCSS(styles, sheet, lastModified) {
    var css;

    // If there is no title set, use the filename, minus the extension
    var id = 'less:' + (sheet.title || sheet.href.match(/(?:^|\/)([-\w]+)\.[a-z]+$/i)[1]);

    // If the stylesheet doesn't exist, create a new node
    if ((css = document.getElementById(id)) === null) {
        css = document.createElement('style');
        css.type = 'text/css';
        css.media = 'screen';
        css.id = id;
        document.getElementsByTagName('head')[0].appendChild(css);
    }

    if (css.styleSheet) { // IE
        try {
            css.styleSheet.cssText = styles;
        } catch (e) {
            throw new(Error)("Couldn't reassign styleSheet.cssText.");
        }
    } else {
        (function (node) {
            if (css.childNodes.length > 0) {
                css.replaceChild(node, css.firstChild);
            } else {
                css.appendChild(node);
            }
        })(document.createTextNode(styles));
    }

    // Don't update the local store if the file wasn't modified
    if (lastModified && typeof(localStorage) !== "undefined") {
        localStorage.setItem(sheet.href, styles);
        localStorage.setItem(sheet.href + ':timestamp', lastModified);
    }
}

function xhr(url, async, callback, errback) {
    var xhr = getXMLHttpRequest();

    if (window.location.protocol === "file:") {
        xhr.open('GET', url, false);
        xhr.send(null);
        if (xhr.status === 0) {
            callback(xhr.responseText);
        } else {
            errback(xhr.status);
        }
    } else {
        xhr.open('GET', url, async || less.async);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status >= 200 && xhr.status < 300) {
                    callback(xhr.responseText,
                             xhr.getResponseHeader("Last-Modified"));
                } else if (typeof(errback) === 'function') {
                    errback(xhr.status);
                }
            }
        };
        xhr.send(null);
    }
}

function getXMLHttpRequest() {
    if (window.XMLHttpRequest) {
        return new(XMLHttpRequest);
    } else {
        try {
            return new(ActiveXObject)("MSXML2.XMLHTTP.3.0");
        } catch (e) {
            log("less: browser doesn't support AJAX.");
            return null;
        }
    }
}

function removeNode(node) {
    return node && node.parentNode.removeChild(node);
}

function log(str) {
    if (less.env == 'development' && typeof(console) !== "undefined") { console.log(str) }
}

function error(e, href) {
    var id = 'less-error-message:' + href.replace(/[^a-z]+/ig, '-');

    if (document.getElementById(id)) { return }

    var template = ['
',
                        '
[-1]{0}
',
                        '
[0]{current}
',
                        '
[1]{2}
',
                    '
'].join('\n');

    var elem = document.createElement('div'), timer;
    elem.id = id;
    elem.className = "less-error-message";
    elem.innerHTML = '
' + (e.message || 'There is an error in your .less file') + '
' +
                     '
' + href + " "                +
                     'on line '     + e.line + ', column ' + (e.column + 1)         + ':
' +
                     template.replace(/\[(-?\d)\]/g, function (_, i) {
                         return (parseInt(e.line) + parseInt(i)) || '';
                     }).replace(/\{(\d)\}/g, function (_, i) {
                         return e.extract[parseInt(i)] || '';
                     }).replace(/\{current\}/, e.extract[1].slice(0, e.column)      +
                                               ''               +
                                               e.extract[1].slice(e.column)         +
                                               '');
    // CSS for error messages
    createCSS([
        '.less-error-message span {',
            'margin-right: 15px;',
        '}',
        '.less-error-message pre {',
            'color: #ee4444;',
            'padding: 4px 0;',
            'margin: 0;',
        '}',
        '.less-error-message pre.ctx {',
            'color: #dd7777;',
        '}',
        '.less-error-message h3 {',
            'padding: 15px 0 5px 0;',
            'margin: 0;',
        '}',
        '.less-error-message a {',
            'color: #10a',
        '}',
        '.less-error-message .error {',
            'color: red;',
            'font-weight: bold;',
            'padding-bottom: 2px;',
            'border-bottom: 1px dashed red;',
        '}'
    ].join('\n'), { title: 'error-message' });

    elem.style.cssText = [
        "font-family: Arial, sans-serif",
        "border: 1px solid #e00",
        "background-color: #eee",
        "border-radius: 5px",
        "-webkit-border-radius: 5px",
        "-moz-border-radius: 5px",
        "color: #e00",
        "padding: 15px",
        "margin-bottom: 15px"
    ].join(';');

    if (less.env == 'development') {
        timer = setInterval(function () {
            if (document.body) {
                document.body.insertBefore(elem, document.body.firstChild);
                clearInterval(timer);
            }
        }, 10);
    }
}

//
// Used by `@import` directives
//
less.Parser.importer = function (path, paths, callback) {
    loadStyleSheet({ href: path, title: path }, function (root) {
        callback(root);
    });
};

})();
<|endoftext|>


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

import React, {Component, createRef} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import eventsOn from 'dom-helpers/events/on';
import eventsOff from 'dom-helpers/events/off';

import ScrollableTable from '../_ScrollableTable';

import Theme from '../Theme';
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';
import Direction from '../_statics/Direction';

import Util from '../_vendors/Util';
import TableCalculation from '../_vendors/TableCalculation';
import ScrollBar from '../_vendors/ScrollBar';

class TableContent extends Component {

    static Fragment = TableFragment;
    static Align = HorizontalAlign;
    static Fixed = HorizontalAlign;
    static SelectMode = SelectMode;
    static SelectAllMode = SelectAllMode;
    static SortingType = SortingType;

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.horizontalScrollBarSize = ScrollBar.getSize(Direction.HORIZONTAL);
        this.verticalScrollBarSize = ScrollBar.getSize(Direction.VERTICAL);

        this.leftScroller = null;
        this.bodyScroller = null;
        this.headScroller = null;
        this.footScroller = null;
        this.rightScroller = null;

        this.lastScrollLeft = 0;
        this.lastScrollTop = 0;

        this.wrapper = createRef();
        this.wrapperEl = null;

    }

    getColumns = () => {

        const {columns} = this.props,
            result = {
                [HorizontalAlign.LEFT]: [],
                [HorizontalAlign.CENTER]: [],
                [HorizontalAlign.RIGHT]: []
            };

        columns.forEach(column => {
            if (column.fixed === true || column.fixed === HorizontalAlign.LEFT) {
                result[HorizontalAlign.LEFT].push(column);
            } else if (column.fixed === HorizontalAlign.RIGHT) {
                result[HorizontalAlign.RIGHT].push(column);
            } else {
                result[HorizontalAlign.CENTER].push(column);
            }
        });

        return result;

    };

    /**
     * sort data by sorting
     * @param data
     * @returns {*[]}
     */
    sortData = (data = this.props.data) => {
        const {sorting, sortingFunc} = this.props;
        return sorting ? TableCalculation.sortTableData(data, sorting, sortingFunc) : data;
    };

    /**
     * slice data by pagination
     * @param data
     * @returns {*[]}
     */
    paginateData = (data = this.props.data) => {

        const {pagination} = this.props;

        if (!pagination) {
            return data;
        }

        const {pageSize, page} = pagination,
            len = data.length;

        let start = page * pageSize,
            stop = start + pageSize;

        start = start < 0 ? 0 : start;
        stop = stop > len ? len : stop;

        return data.slice(start, stop);

    };

    fixLayout = () => {
        if ((this.props.isHeadFixed || this.props.isFootFixed) && this.wrapperEl) {
            TableCalculation.fixLayout(this.wrapperEl, this.props);
        }
    };

    handleGetScrollerEl = (el, type) => {
        this[`${type}Scroller`] = el;
    };

    handleHorizontalScroll = e => {

        if (!e || e.currentTarget !== e.target) {
            return;
        }

        const {isHeadFixed, isFootFixed, scroll = {}} = this.props,
            target = e.target,
            scrollLeft = target.scrollLeft;

        if (scrollLeft !== this.lastScrollLeft && scroll.width) {
            switch (target) {
                case this.bodyScroller: {
                    if (isHeadFixed && this.headScroller) {
                        this.headScroller.scrollLeft = scrollLeft;
                    }
                    if (isFootFixed && this.headScroller) {
                        this.footScroller.scrollLeft = scrollLeft;
                    }
                    break;
                }
                case this.headScroller: {
                    if (this.bodyScroller) {
                        this.bodyScroller.scrollLeft = scrollLeft;
                    }
                    if (isFootFixed && this.headScroller) {
                        this.footScroller.scrollLeft = scrollLeft;
                    }
                    break;
                }
                case this.footScroller: {
                    if (isHeadFixed && this.headScroller) {
                        this.headScroller.scrollLeft = scrollLeft;
                    }
                    if (this.bodyScroller) {
                        this.bodyScroller.scrollLeft = scrollLeft;
                    }
                    break;
                }
            }
        }

        this.lastScrollLeft = scrollLeft;

    };

    handleVerticalScroll = e => {

        if (!e || e.currentTarget !== e.target) {
            return;
        }

        const {scroll = {}} = this.props,
            target = e.target,
            scrollTop = target.scrollTop;

        if (scrollTop !== this.lastScrollTop && scroll.height
            && (target != this.headScroller || target != this.footScroller)) {

            if (this.leftScroller && this.leftScroller !== target) {
                this.leftScroller.scrollTop = scrollTop;
            }

            if (this.bodyScroller && this.bodyScroller !== target) {
                this.bodyScroller.scrollTop = scrollTop;
            }

            if (this.rightScroller && this.rightScroller !== target) {
                this.rightScroller.scrollTop = scrollTop;
            }

        }

        this.lastScrollTop = scrollTop;

    };

    handleScroll = e => {
        this.handleHorizontalScroll(e);
        this.handleVerticalScroll(e);
    };

    handleWheel = e => {

        const {scroll = {}} = this.props;

        if (!window.navigator.userAgent.match(/Trident\/7\./) || !scroll.height) {
            return;
        }

        e.preventDefault();

        const wd = e.deltaY,
            target = e.target;

        let scrollTop = 0;

        if (this.lastScrollTop) {
            scrollTop = this.lastScrollTop + wd;
        } else {
            scrollTop = wd;
        }

        if (this.leftScroller && this.leftScroller !== target) {
            this.leftScroller.scrollTop = scrollTop;
        }

        if (this.bodyScroller && this.bodyScroller !== target) {
            this.bodyScroller.scrollTop = scrollTop;
        }

        if (this.rightScroller && this.rightScroller !== target) {
            this.rightScroller.scrollTop = scrollTop;
        }

    };

    componentDidMount() {
        this.wrapperEl = this.wrapper && this.wrapper.current;
        eventsOn(window, 'resize', this.fixLayout);
    }

    componentDidUpdate(prevProps, prevState, snapshot) {
        this.fixLayout();
    }

    componentWillUnmount() {
        eventsOff(window, 'resize', this.fixLayout);
    }

    render() {

        const {
                className, style, data, scroll,
                ...restProps
            } = this.props,

            columns = this.getColumns();

        if (!columns) {
            return null;
        }

        const tableData = this.paginateData(this.sortData(data)),

            horizontalScrollerStyle = this.horizontalScrollBarSize && this.horizontalScrollBarSize > 0 ? {
                marginBottom: -this.horizontalScrollBarSize,
                paddingBottom: 0
            } : null,
            bodyScrollerStyle = scroll && scroll.height ? {
                maxHeight: scroll.height
            } : null,
            maskStyle = this.horizontalScrollBarSize > 0 ?
                {paddingBottom: this.horizontalScrollBarSize} : null,
            tableStyle = scroll && scroll.width ? {minWidth: scroll.width} : null,
            footStyle = this.horizontalScrollBarSize > 0 ? {marginTop: this.horizontalScrollBarSize} : null;

        return (
            <div ref={this.wrapper}
                 className={classNames('table-content', {
                     [className]: className
                 })}
                 style={style}>

                <ScrollableTable {...restProps}
                                 className="table-content-center"
                                 headScrollerStyle={horizontalScrollerStyle}
                                 bodyScrollerStyle={bodyScrollerStyle}
                                 footScrollerStyle={horizontalScrollerStyle}
                                 maskStyle={tableStyle}
                                 tableStyle={tableStyle}
                                 columns={[
                                     ...TableCalculation.handleFixedColumns(columns[HorizontalAlign.LEFT]),
                                     ...columns[HorizontalAlign.CENTER],
                                     ...TableCalculation.handleFixedColumns(columns[HorizontalAlign.RIGHT])
                                 ]}
                                 data={tableData}
                                 scroll={scroll}
                                 onScroll={this.handleScroll}
                                 onWheel={this.handleWheel}
                                 onGetBodyScrollerEl={el =>
                                     this.handleGetScrollerEl(el, TableFragment.BODY)}
                                 onGetHeadScrollerEl={el =>
                                     this.handleGetScrollerEl(el, TableFragment.HEAD)}
                                 onGetFootScrollerEl={el =>
                                     this.handleGetScrollerEl(el, TableFragment.FOOT)}/>

                {
                    columns[HorizontalAlign.LEFT] && columns[HorizontalAlign.LEFT].length > 0 ?
                        <ScrollableTable {...restProps}
                                         className="table-content-left"
                                         bodyScrollerStyle={{
                                             ...horizontalScrollerStyle,
                                             ...bodyScrollerStyle,
                                             marginRight: this.verticalScrollBarSize > 0 ?
                                                 -this.verticalScrollBarSize : -20
                                         }}
                                         maskStyle={maskStyle}
                                         footStyle={footStyle}
                                         fixed={HorizontalAlign.LEFT}
                                         columns={columns[HorizontalAlign.LEFT]}
                                         data={tableData}
                                         scroll={scroll}
                                         onScroll={this.handleScroll}
                                         onWheel={this.handleWheel}
                                         onGetBodyScrollerEl={el =>
                                             this.handleGetScrollerEl(el, HorizontalAlign.LEFT)}/>
                        :
                        null
                }

                {
                    columns[HorizontalAlign.RIGHT] && columns[HorizontalAlign.RIGHT].length > 0 ?
                        <ScrollableTable {...restProps}
                                         className="table-content-right"
                                         bodyScrollerStyle={{
                                             ...horizontalScrollerStyle,
                                             ...bodyScrollerStyle,
                                             marginRight: this.verticalScrollBarSize > 0 ?
                                                 0 : -20
                                         }}
                                         maskStyle={maskStyle}
                                         footStyle={footStyle}
                                         fixed={HorizontalAlign.RIGHT}
                                         columns={columns[HorizontalAlign.RIGHT]}
                                         data={tableData}
                                         scroll={scroll}
                                         onScroll={this.handleScroll}
                                         onWheel={this.handleWheel}
                                         onGetBodyScrollerEl={el =>
                                             this.handleGetScrollerEl(el, HorizontalAlign.RIGHT)}/>
                        :
                        null
                }

            </div>
        );

    }
}

TableContent.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The theme of the table select radio or checkbox.
     */
    selectTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The select mode of table.
     */
    selectMode: PropTypes.oneOf(Util.enumerateValue(SelectMode)),

    /**
     * The select all mode of table, all or current page.
     */
    selectAllMode: PropTypes.oneOf(Util.enumerateValue(SelectAllMode)),

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

        /**
         * fixed position of column ( true / 'left' / 'right' )
         */
        fixed: PropTypes.oneOfType([PropTypes.bool, PropTypes.oneOf(Util.enumerateValue(HorizontalAlign))]),

        /**
         * width of column
         */
        width: PropTypes.number,

        /**
         * minimum width of column
         */
        minWidth: PropTypes.number,

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

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

        /**
         * The render content in header.
         * (1) string，example： 'id'
         * (2) callback，example：function (colIndex) {return colIndex;}
         */
        headRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

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

        /**
         * column span of table header
         */
        headSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

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

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

        /**
         * The render content in table.
         * (1) data key，example： 'id'
         * (2) data key tamplate，example：'${id} - ${name}'
         * (3) callback，example：function (rowData, rowIndex, colIndex) {return rowData.id;}
         */
        bodyRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

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

        /**
         * column span of table body
         */
        bodySpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

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

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

        /**
         * The render content in footer.
         * (1) string，example： 'id'
         * (2) callback，example：function (colIndex) {return colIndex;}
         */
        footRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

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

        /**
         * column span of table foot
         */
        footSpan: PropTypes.oneOfType([PropTypes.number, 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,

    /**
     * sorting
     */
    sorting: PropTypes.shape({
        prop: PropTypes.string,
        type: PropTypes.oneOf(Util.enumerateValue(SortingType))
    }),
    defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType)),
    sortingAscIconCls: PropTypes.string,
    sortingDescIconCls: PropTypes.string,
    sortingFunc: PropTypes.func,

    /**
     * pagination
     */
    isPaginated: PropTypes.bool,
    pagination: PropTypes.shape({
        pageSize: PropTypes.number,
        page: PropTypes.number
    }),
    pageSizes: PropTypes.array,

    /**
     * fixed
     */
    isHeadFixed: PropTypes.bool,
    isFootFixed: PropTypes.bool,

    scroll: PropTypes.shape({
        width: PropTypes.number,
        height: PropTypes.number
    }),

    /**
     * callback
     */
    onSortChange: PropTypes.func

};

TableContent.defaultProps = {

    selectMode: SelectMode.SINGLE_SELECT,
    selectAllMode: SelectAllMode.CURRENT_PAGE,

    defaultSortingType: SortingType.ASC,
    sortingAscIconCls: 'fas fa-angle-up',
    sortingDescIconCls: 'fas fa-angle-down',

    isPaginated: true,
    pagination: {
        pageSize: 10,
        page: 0
    },
    pageSizes: [5, 10, 15, 20],

    isHeadFixed: false,
    isFootFixed: false

};

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

import React, {Component, createRef} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import eventsOn from 'dom-helpers/events/on';
import eventsOff from 'dom-helpers/events/off';

import ScrollableTable from '../_ScrollableTable';

import Theme from '../Theme';
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';
import Direction from '../_statics/Direction';

import Util from '../_vendors/Util';
import TableCalculation from '../_vendors/TableCalculation';
import ScrollBar from '../_vendors/ScrollBar';

class TableContent extends Component {

    static Fragment = TableFragment;
    static Align = HorizontalAlign;
    static Fixed = HorizontalAlign;
    static SelectMode = SelectMode;
    static SelectAllMode = SelectAllMode;
    static SortingType = SortingType;

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.horizontalScrollBarSize = ScrollBar.getSize(Direction.HORIZONTAL);
        this.verticalScrollBarSize = ScrollBar.getSize(Direction.VERTICAL);

        this.leftScroller = null;
        this.bodyScroller = null;
        this.headScroller = null;
        this.footScroller = null;
        this.rightScroller = null;

        this.lastScrollLeft = 0;
        this.lastScrollTop = 0;

        this.wrapper = createRef();
        this.wrapperEl = null;

    }

    getColumns = () => {

        const {columns} = this.props,
            result = {
                [HorizontalAlign.LEFT]: [],
                [HorizontalAlign.CENTER]: [],
                [HorizontalAlign.RIGHT]: []
            };

        columns.forEach(column => {
            if (column.fixed === true || column.fixed === HorizontalAlign.LEFT) {
                result[HorizontalAlign.LEFT].push(column);
            } else if (column.fixed === HorizontalAlign.RIGHT) {
                result[HorizontalAlign.RIGHT].push(column);
            } else {
                result[HorizontalAlign.CENTER].push(column);
            }
        });

        return result;

    };

    /**
     * sort data by sorting
     * @param data
     * @returns {*[]}
     */
    sortData = (data = this.props.data) => {
        const {sorting, sortingFunc} = this.props;
        return sorting ? TableCalculation.sortTableData(data, sorting, sortingFunc) : data;
    };

    /**
     * slice data by pagination
     * @param data
     * @returns {*[]}
     */
    paginateData = (data = this.props.data) => {

        const {pagination} = this.props;

        if (!pagination) {
            return data;
        }

        const {pageSize, page} = pagination,
            len = data.length;

        let start = page * pageSize,
            stop = start + pageSize;

        start = start < 0 ? 0 : start;
        stop = stop > len ? len : stop;

        return data.slice(start, stop);

    };

    fixLayout = () => {
        if ((this.props.isHeadFixed || this.props.isFootFixed) && this.wrapperEl) {
            TableCalculation.fixLayout(this.wrapperEl, this.props);
        }
    };

    handleGetScrollerEl = (el, type) => {
        this[`${type}Scroller`] = el;
    };

    handleHorizontalScroll = e => {

        if (!e || e.currentTarget !== e.target) {
            return;
        }

        const {isHeadFixed, isFootFixed, scroll = {}} = this.props,
            target = e.target,
            scrollLeft = target.scrollLeft;

        if (scrollLeft !== this.lastScrollLeft && scroll.width) {
            switch (target) {
                case this.bodyScroller: {
                    if (isHeadFixed && this.headScroller) {
                        this.headScroller.scrollLeft = scrollLeft;
                    }
                    if (isFootFixed && this.headScroller) {
                        this.footScroller.scrollLeft = scrollLeft;
                    }
                    break;
                }
                case this.headScroller: {
                    if (this.bodyScroller) {
                        this.bodyScroller.scrollLeft = scrollLeft;
                    }
                    if (isFootFixed && this.headScroller) {
                        this.footScroller.scrollLeft = scrollLeft;
                    }
                    break;
                }
                case this.footScroller: {
                    if (isHeadFixed && this.headScroller) {
                        this.headScroller.scrollLeft = scrollLeft;
                    }
                    if (this.bodyScroller) {
                        this.bodyScroller.scrollLeft = scrollLeft;
                    }
                    break;
                }
            }
        }

        this.lastScrollLeft = scrollLeft;

    };

    handleVerticalScroll = e => {

        if (!e || e.currentTarget !== e.target) {
            return;
        }

        const {scroll = {}} = this.props,
            target = e.target,
            scrollTop = target.scrollTop;

        if (scrollTop !== this.lastScrollTop && scroll.height
            && (target != this.headScroller || target != this.footScroller)) {
            switch (target) {
                case this.bodyScroller: {
                    if (this.leftScroller) {
                        this.leftScroller.scrollTop = scrollTop;
                    }
                    if (this.rightScroller) {
                        this.rightScroller.scrollTop = scrollTop;
                    }
                    break;
                }
                case this.leftScroller: {
                    if (this.bodyScroller) {
                        this.bodyScroller.scrollTop = scrollTop;
                    }
                    if (this.rightScroller) {
                        this.rightScroller.scrollTop = scrollTop;
                    }
                    break;
                }
                case this.rightScroller: {
                    if (this.leftScroller) {
                        this.leftScroller.scrollTop = scrollTop;
                    }
                    if (this.bodyScroller) {
                        this.bodyScroller.scrollTop = scrollTop;
                    }
                    break;
                }
            }
        }

        this.lastScrollTop = scrollTop;

    };

    handleScroll = e => {
        this.handleHorizontalScroll(e);
        this.handleVerticalScroll(e);
    };

    handleWheel = e => {

        const {scroll = {}} = this.props;

        if (!window.navigator.userAgent.match(/Trident\/7\./) || !scroll.height) {
            return;
        }

        e.preventDefault();

        const wd = e.deltaY,
            target = e.target;

        let scrollTop = 0;

        if (this.lastScrollTop) {
            scrollTop = this.lastScrollTop + wd;
        } else {
            scrollTop = wd;
        }

        if (this.leftScroller && this.leftScroller !== target) {
            this.leftScroller.scrollTop = scrollTop;
        }

        if (this.bodyScroller && this.bodyScroller !== target) {
            this.bodyScroller.scrollTop = scrollTop;
        }

        if (this.rightScroller && this.rightScroller !== target) {
            this.rightScroller.scrollTop = scrollTop;
        }

    };

    componentDidMount() {
        this.wrapperEl = this.wrapper && this.wrapper.current;
        eventsOn(window, 'resize', this.fixLayout);
    }

    componentDidUpdate(prevProps, prevState, snapshot) {
        this.fixLayout();
    }

    componentWillUnmount() {
        eventsOff(window, 'resize', this.fixLayout);
    }

    render() {

        const {
                className, style, data, scroll,
                ...restProps
            } = this.props,

            columns = this.getColumns();

        if (!columns) {
            return null;
        }

        const tableData = this.paginateData(this.sortData(data)),

            horizontalScrollerStyle = this.horizontalScrollBarSize && this.horizontalScrollBarSize > 0 ? {
                marginBottom: -this.horizontalScrollBarSize,
                paddingBottom: 0
            } : null,
            bodyScrollerStyle = scroll && scroll.height ? {
                maxHeight: scroll.height
            } : null,
            maskStyle = this.horizontalScrollBarSize > 0 ?
                {paddingBottom: this.horizontalScrollBarSize} : null,
            tableStyle = scroll && scroll.width ? {minWidth: scroll.width} : null,
            footStyle = this.horizontalScrollBarSize > 0 ? {marginTop: this.horizontalScrollBarSize} : null;

        return (
            <div ref={this.wrapper}
                 className={classNames('table-content', {
                     [className]: className
                 })}
                 style={style}>

                <ScrollableTable {...restProps}
                                 className="table-content-center"
                                 headScrollerStyle={horizontalScrollerStyle}
                                 bodyScrollerStyle={bodyScrollerStyle}
                                 footScrollerStyle={horizontalScrollerStyle}
                                 maskStyle={tableStyle}
                                 tableStyle={tableStyle}
                                 columns={[
                                     ...TableCalculation.handleFixedColumns(columns[HorizontalAlign.LEFT]),
                                     ...columns[HorizontalAlign.CENTER],
                                     ...TableCalculation.handleFixedColumns(columns[HorizontalAlign.RIGHT])
                                 ]}
                                 data={tableData}
                                 scroll={scroll}
                                 onScroll={this.handleScroll}
                                 onWheel={this.handleWheel}
                                 onGetBodyScrollerEl={el =>
                                     this.handleGetScrollerEl(el, TableFragment.BODY)}
                                 onGetHeadScrollerEl={el =>
                                     this.handleGetScrollerEl(el, TableFragment.HEAD)}
                                 onGetFootScrollerEl={el =>
                                     this.handleGetScrollerEl(el, TableFragment.FOOT)}/>

                {
                    columns[HorizontalAlign.LEFT] && columns[HorizontalAlign.LEFT].length > 0 ?
                        <ScrollableTable {...restProps}
                                         className="table-content-left"
                                         bodyScrollerStyle={{
                                             ...horizontalScrollerStyle,
                                             ...bodyScrollerStyle,
                                             marginRight: this.verticalScrollBarSize > 0 ?
                                                 -this.verticalScrollBarSize : -20
                                         }}
                                         maskStyle={maskStyle}
                                         footStyle={footStyle}
                                         fixed={HorizontalAlign.LEFT}
                                         columns={columns[HorizontalAlign.LEFT]}
                                         data={tableData}
                                         scroll={scroll}
                                         onScroll={this.handleScroll}
                                         onWheel={this.handleWheel}
                                         onGetBodyScrollerEl={el =>
                                             this.handleGetScrollerEl(el, HorizontalAlign.LEFT)}/>
                        :
                        null
                }

                {
                    columns[HorizontalAlign.RIGHT] && columns[HorizontalAlign.RIGHT].length > 0 ?
                        <ScrollableTable {...restProps}
                                         className="table-content-right"
                                         bodyScrollerStyle={{
                                             ...horizontalScrollerStyle,
                                             ...bodyScrollerStyle,
                                             marginRight: this.verticalScrollBarSize > 0 ?
                                                 0 : -20
                                         }}
                                         maskStyle={maskStyle}
                                         footStyle={footStyle}
                                         fixed={HorizontalAlign.RIGHT}
                                         columns={columns[HorizontalAlign.RIGHT]}
                                         data={tableData}
                                         scroll={scroll}
                                         onScroll={this.handleScroll}
                                         onWheel={this.handleWheel}
                                         onGetBodyScrollerEl={el =>
                                             this.handleGetScrollerEl(el, HorizontalAlign.RIGHT)}/>
                        :
                        null
                }

            </div>
        );

    }
}

TableContent.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The theme of the table select radio or checkbox.
     */
    selectTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The select mode of table.
     */
    selectMode: PropTypes.oneOf(Util.enumerateValue(SelectMode)),

    /**
     * The select all mode of table, all or current page.
     */
    selectAllMode: PropTypes.oneOf(Util.enumerateValue(SelectAllMode)),

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

        /**
         * fixed position of column ( true / 'left' / 'right' )
         */
        fixed: PropTypes.oneOfType([PropTypes.bool, PropTypes.oneOf(Util.enumerateValue(HorizontalAlign))]),

        /**
         * width of column
         */
        width: PropTypes.number,

        /**
         * minimum width of column
         */
        minWidth: PropTypes.number,

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

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

        /**
         * The render content in header.
         * (1) string，example： 'id'
         * (2) callback，example：function (colIndex) {return colIndex;}
         */
        headRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

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

        /**
         * column span of table header
         */
        headSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

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

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

        /**
         * The render content in table.
         * (1) data key，example： 'id'
         * (2) data key tamplate，example：'${id} - ${name}'
         * (3) callback，example：function (rowData, rowIndex, colIndex) {return rowData.id;}
         */
        bodyRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

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

        /**
         * column span of table body
         */
        bodySpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

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

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

        /**
         * The render content in footer.
         * (1) string，example： 'id'
         * (2) callback，example：function (colIndex) {return colIndex;}
         */
        footRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

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

        /**
         * column span of table foot
         */
        footSpan: PropTypes.oneOfType([PropTypes.number, 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,

    /**
     * sorting
     */
    sorting: PropTypes.shape({
        prop: PropTypes.string,
        type: PropTypes.oneOf(Util.enumerateValue(SortingType))
    }),
    defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType)),
    sortingAscIconCls: PropTypes.string,
    sortingDescIconCls: PropTypes.string,
    sortingFunc: PropTypes.func,

    /**
     * pagination
     */
    isPaginated: PropTypes.bool,
    pagination: PropTypes.shape({
        pageSize: PropTypes.number,
        page: PropTypes.number
    }),
    pageSizes: PropTypes.array,

    /**
     * fixed
     */
    isHeadFixed: PropTypes.bool,
    isFootFixed: PropTypes.bool,

    scroll: PropTypes.shape({
        width: PropTypes.number,
        height: PropTypes.number
    }),

    /**
     * callback
     */
    onSortChange: PropTypes.func

};

TableContent.defaultProps = {

    selectMode: SelectMode.SINGLE_SELECT,
    selectAllMode: SelectAllMode.CURRENT_PAGE,

    defaultSortingType: SortingType.ASC,
    sortingAscIconCls: 'fas fa-angle-up',
    sortingDescIconCls: 'fas fa-angle-down',

    isPaginated: true,
    pagination: {
        pageSize: 10,
        page: 0
    },
    pageSizes: [5, 10, 15, 20],

    isHeadFixed: false,
    isFootFixed: false

};

export default TableContent;
<|endoftext|>


<commit_before>/*
 * @copyright Copyright (c) Sematext Group, Inc. - All Rights Reserved
 *
 * @licence SPM for NodeJS is free-to-use, proprietary software.
 * THIS IS PROPRIETARY SOURCE CODE OF Sematext Group, Inc. (Sematext)
 * This source code may not be copied, reverse engineered, or altered for any purpose.
 * This source code is to be used exclusively by users and customers of Sematext.
 * Please see the full license (found in LICENSE in this distribution) for details on its license and the licenses of its dependencies.
 */
var which = require('which')
var vmstatCommand = which.sync('vmstat')
var exec = require('child_process').exec
function vmstatS (callback) {
  exec(vmstatCommand + ' -s', function (err, stout, sterr) {
    if (err) {
      callback(err)
      return
    }
    try {
      var lines = stout.split('\n')
      lines = lines.map(function (line) { return line.trim()})
      if (lines.length >= 21) {
        var swapMapping = {
          swapUsed: 8,
          swapIn: 20,
          swapOut: 21
        }
        var memoryMapping = {
          total: 0,
          used: 1,
          active: 2,
          inactive: 3,
          free: 4,
          buffer: 5
        }
        var cpuMapping = {
          user: 10,
          nice: 11,
          sys: 12,
          idle: 13,
          wait: 14,
          irq: 15,
          softirq: 16,
          stolen: 17
        }
        var mapValues = function (mapping) {
          var result = {}
          for (var property in mapping) {
            result [property] = parseInt(lines[mapping[property]].replace(/\s+/, ' ').split(' ')[0], 10)
          }
          return result
        }
        var rv = {
          swap: mapValues(swapMapping),
          cpu: mapValues(cpuMapping),
          memory: mapValues(memoryMapping)
        }
        callback(null, rv)
      }
    } catch (error) {
      callback(error)
    }
  })
}

function vmstat (callback) {
  exec(vmstatCommand, function (err, stout, sterr) {
    // console.log (values)
    function mapValues (mapping) {
      var result = {}
      for (var property in mapping) {
        result [property] = parseInt(values[mapping[property]], 10)
      }
      return result
    }
    try {
      if (err) {
        callback(err)
        return
      }
      var lines = stout.split('\n')
      // console.log(lines)
      // var headers = lines[1].trim().replace(/\s+/g, ' ').split(' ')
      var values = lines[2].trim().replace(/\s+/g, ' ').split(' ')
      var mapping = {
        swapd: 2,
        free: 3,
        buff: 4,
        cache: 5,
        si: 6,
        so: 7,
        bi: 8,
        bo: 9
      }
      var rv = mapValues(mapping)
      callback(null, rv)
    } catch (error) {
      callback(error, null)
    }
  })
}
module.exports.vmstatS = vmstatS
module.exports.vmstat = vmstat
<commit_msg>add df function<commit_after>/*
 * @copyright Copyright (c) Sematext Group, Inc. - All Rights Reserved
 *
 * @licence SPM for NodeJS is free-to-use, proprietary software.
 * THIS IS PROPRIETARY SOURCE CODE OF Sematext Group, Inc. (Sematext)
 * This source code may not be copied, reverse engineered, or altered for any purpose.
 * This source code is to be used exclusively by users and customers of Sematext.
 * Please see the full license (found in LICENSE in this distribution) for details on its license and the licenses of its dependencies.
 */
var which = require('which')
var vmstatCommand = which.sync('vmstat')
var exec = require('child_process').exec
function vmstatS (callback) {
  exec(vmstatCommand + ' -s', function (err, stout, sterr) {
    if (err) {
      callback(err)
      return
    }
    try {
      var lines = stout.split('\n')
      lines = lines.map(function (line) { return line.trim()})
      if (lines.length >= 21) {
        var swapMapping = {
          swapUsed: 8,
          swapIn: 20,
          swapOut: 21
        }
        var memoryMapping = {
          total: 0,
          used: 1,
          active: 2,
          inactive: 3,
          free: 4,
          buffer: 5
        }
        var cpuMapping = {
          user: 10,
          nice: 11,
          sys: 12,
          idle: 13,
          wait: 14,
          irq: 15,
          softirq: 16,
          stolen: 17
        }
        var mapValues = function (mapping) {
          var result = {}
          for (var property in mapping) {
            result [property] = parseInt(lines[mapping[property]].replace(/\s+/, ' ').split(' ')[0], 10)
          }
          return result
        }
        var rv = {
          swap: mapValues(swapMapping),
          cpu: mapValues(cpuMapping),
          memory: mapValues(memoryMapping)
        }
        callback(null, rv)
      }
    } catch (error) {
      callback(error)
    }
  })
}

function vmstat (callback) {
  exec(vmstatCommand, function (err, stout, sterr) {
    // console.log (values)
    function mapValues (mapping) {
      var result = {}
      for (var property in mapping) {
        result [property] = parseInt(values[mapping[property]], 10)
      }
      return result
    }
    try {
      if (err) {
        callback(err)
        return
      }
      var lines = stout.split('\n')
      // console.log(lines)
      // var headers = lines[1].trim().replace(/\s+/g, ' ').split(' ')
      var values = lines[2].trim().replace(/\s+/g, ' ').split(' ')
      var mapping = {
        swapd: 2,
        free: 3,
        buff: 4,
        cache: 5,
        si: 6,
        so: 7,
        bi: 8,
        bo: 9
      }
      var rv = mapValues(mapping)
      callback(null, rv)
    } catch (error) {
      callback(error, null)
    }
  })
}

function df (callback) {
  df(function dfCallback (error, response) {
    if (error) {
      return callback(error)
    }
    return callback(null, response)
  })
}

module.exports.vmstatS = vmstatS
module.exports.vmstat = vmstat
module.exports.df = df
<|endoftext|>


<commit_before>module.exports = {
  activate: function() {
    atom.workspaceView.command('markdown-pdf:convert', this.convert);
  },

  convert: function() {
    var fs = require("fs");
    var mdpreview = atom.packages.activePackages["markdown-preview"];
    var editor = atom.workspace.getActiveTextEditor();
    var markdownPath = atom.workspaceView.getActivePaneItem().getPath();
    if (!isMd(markdownPath)){
      alert("Please save the file as a markdown (.markdown, .md, .mkd, .mkdown or .ron)");
      return;
    }
    var pdfPath = markdownPath.replace(getExtension(markdownPath), "pdf");

    htmlFromMd(function(html){
      html = getStyledHtml(html);
      makePdf(html, pdfPath);
    });

    function editorSelected(){
      if(atom.workspace.getActiveTextEditor() !== undefined) return true;
      return false;
    }

    function isMd(path){
      //check extension of current file
      var accepted = ["markdown", "md", "mkd", "mkdown", "ron"];
      var current = path.split(".").pop();
      if(accepted.indexOf(current) != -1) return true;
      return false;
    }

    function getExtension(path){
      var ex = path.split('.').pop();
      return ex;
    }

    //Above: may be able to combine isMd and getExtension into single function call.

    function htmlFromMd(callback){
      var marked = require('marked');
      //explicitly setting default options below, in case we want to further configure the renderer
      marked.setOptions({
        renderer: new marked.Renderer(),
        gfm: true,
        tables: true,
        breaks: false,
        pedantic: false,
        sanitize: true,
        smartLists: true,
        smartypants: false
      });)
      if(editorSelected()){
        fs.readFile(markdownPath, 'utf-8', function(err, data){
          var md = data;
          var html = marked(md);
          callback(html);
        });
      }
      else alert('Please select the editor containing the markdown you wish to convert.');
    }

    function getStyledHtml(input){
      return getStyles() + wrapHtml(input);
    }

    function wrapHtml(input){
      return '' + input + '';
    }

    function getStyles(){
      var user_styles = atom.styles.getStyleElements();
      user_styles = user_styles[user_styles.length - 1].innerHTML;

      var styles = {
        previewStyles: mdpreview.stylesheets[0][1],
        syntaxStyles: atom.themes.getActiveThemes()[0].stylesheets[0][1],
        userStyles: user_styles
      };
      var styleString = '';
      for(var s in styles){
        styleString += '';
      }
      return styleString;
    }

    function makePdf(inputHtml, outputPath){
      var pdf = require('html-pdf');
      pdf.create(inputHtml, { width: '210mm', height: '297mm', border: '10mm'}, function(err, buffer) {
        if (err) {
          alert("Error converting to pdf. Check console for more information.");
          console.log(err + "\nIf the error is a timeout, try running the command again.");
        }
        fs.writeFile(outputPath, buffer);
        console.log("Converted successfully. Output in " + outputPath);
      });
    }

  }
};
<commit_msg>Add config options.<commit_after>module.exports = {

  config: {
    "format": {
      "title": "Page Format",
      "type": "string",
      "default": "A4",
      "enum": ["A3", "A4", "A5", "Legal", "Letter", "Tabloid"]
    },
    "orientation": {
      "title": "Page Orientation",
      "type": "string",
      "default": "portrait",
      "enum": ["portrait", "landscape"]
    },
    "timeout": {
      "title": "Timeout",
      "description": "Time (ms) before PhantomJS gives up on rendering. You can set a larger value for very big files.",
      "type": "integer",
      "default": 10000
    },
    "border": {
      "title": "Border Size",
      "type": "string",
      "default": "10mm"
    },
    "type": {
      "title": "Exported Filetype",
      "type": "string",
      "default": "pdf",
      "enum": ["pdf", "png", "jpeg"]
    },
    "quality": {
      "title": "Image Quality",
      "description": "Only used for .png and .jpeg formats.",
      "type": "integer",
      "minimum": 1,
      "maximum": 100,
      "default": 100
    }
  },

  activate: function() {
    atom.workspaceView.command('markdown-pdf:convert', this.convert);
  },

  convert: function() {
    var fs = require("fs");
    var mdpreview = atom.packages.activePackages["markdown-preview"];
    var editor = atom.workspace.getActiveTextEditor();
    var markdownPath = atom.workspaceView.getActivePaneItem().getPath();
    if (!isMd(markdownPath)){
      alert("Please save the file as a markdown (.markdown, .md, .mkd, .mkdown or .ron)");
      return;
    }
    var outPath = markdownPath.replace(getExtension(markdownPath), atom.config.get('markdown-pdf.type'));

    htmlFromMd(function(html){
      html = getStyledHtml(html);
      makePdf(html, outPath);
    });

    function editorSelected(){
      if(atom.workspace.getActiveTextEditor() !== undefined) return true;
      return false;
    }

    function isMd(path){
      //check extension of current file
      var accepted = ["markdown", "md", "mkd", "mkdown", "ron"];
      var current = path.split(".").pop();
      if(accepted.indexOf(current) != -1) return true;
      return false;
    }

    function getExtension(path){
      var ex = path.split('.').pop();
      return ex;
    }

    //Above: may be able to combine isMd and getExtension into single function call.

    function htmlFromMd(callback){
      var marked = require('marked');
      //explicitly setting default options below, in case we want to further configure the renderer
      marked.setOptions({
        renderer: new marked.Renderer(),
        gfm: true,
        tables: true,
        breaks: false,
        pedantic: false,
        sanitize: true,
        smartLists: true,
        smartypants: false
      });)
      if(editorSelected()){
        fs.readFile(markdownPath, 'utf-8', function(err, data){
          var md = data;
          var html = marked(md);
          callback(html);
        });
      }
      else alert('Please select the editor containing the markdown you wish to convert.');
    }

    function getStyledHtml(input){
      return getStyles() + wrapHtml(input);
    }

    function wrapHtml(input){
      return '' + input + '';
    }

    function getStyles(){
      var user_styles = atom.styles.getStyleElements();
      user_styles = user_styles[user_styles.length - 1].innerHTML;

      var styles = {
        previewStyles: mdpreview.stylesheets[0][1],
        syntaxStyles: atom.themes.getActiveThemes()[0].stylesheets[0][1],
        userStyles: user_styles
      };
      var styleString = '';
      for(var s in styles){
        styleString += '';
      }
      return styleString;
    }

    function makePdf(inputHtml, outputPath){
      var pdf = require('html-pdf');
      pdf.create(inputHtml, getConfig(), function(err, buffer) {
        if (err) {
          alert("Error converting to image format. Check console for more information.");
          console.log(err + "\nIf the error is a timeout, try running the command again.");
        }
        fs.writeFile(outputPath, buffer);
        console.log("Converted successfully. Output in " + outputPath);
      });
    }

  }
}

function getConfig(){
  return atom.config.getSettings()['markdown-pdf'];
}
<|endoftext|>


<commit_before>'use strict'

var rawData = [
  {
    name: 'Salmon Cookies',
    image: 'styles/images/salmon.png',
    description: 'This was a school project which involved setting up a cookie store with several locations.  Each store tracked the number of cookies sold and tallied the totals in a table.',
    created: '2017-06-18',
  },
  {
    name: 'Bus Mall',
    image: 'styles/images/vault-tec.png',
    description: 'This was a school project which involved setting up a survey where you would click on one of three randomly generated images out of a pool.  The images tracked how many times they were shown and how many times they were clicked.  The results were displayed on a chart.',
    created: '2017-07-01',
  },
  {
    name: 'We Don\'t Know Jack',
    image: 'styles/images/questionMark.jpg',
    description: 'This was a group project for school which involved making a trivia game in the style of the popular game "You Don\'t Know Jack" from the 90\'s.  Two players would to try buzz in before the other player and answer a trivia question, gaining points for correct answers and losing points for incorrect.',
    created: '2017-07-15',
  },
]
<commit_msg>removed projects.js file<commit_after><|endoftext|>


<commit_before>// Start of parsing results
function getJsonFromUrl(hashBased) {
    'use strict'
    var query;
    if (hashBased) {
        var pos = location.href.indexOf("?");
        if (pos === -1) return [];
        query = location.href.substr(pos + 1);
    } else {
        query = location.search.substr(1);
    }
    var result = {};
    query.split("&").forEach(function(part) {
        if (!part) return;
        part = part.split("+").join(" "); // replace every + with space, regexp-free version
        var eq = part.indexOf("=");
        var key = eq > -1 ? part.substr(0, eq) : part;
        var val = eq > -1 ? decodeURIComponent(part.substr(eq + 1)) : "";
        var from = key.indexOf("[");
        if (from == -1) result[decodeURIComponent(key)] = val;
        else {
            var to = key.indexOf("]");
            var index = decodeURIComponent(key.substring(from + 1, to));
            key = decodeURIComponent(key.substring(0, from));
            if (!result[key]) result[key] = [];
            if (!index) result[key].push(val);
            else result[key][index] = val;
        }
    });
    return result;
}

var resultado = [];
resultado = JSON.parse(getJsonFromUrl().test);
//End of parsing results

//Variables

var textV1, textV2, textV3;
var textA1, textA2, textA3;
var textM1, textM2, textM3;
var textT1, textT2, textT3;

// Building variable texts

textV1 = "
 Como " + resultado.lambV + "≤ " + resultado.lambpV + ", " + "\\(λ\\) ≤ \\(λ_p\\)" + ", o esforço cortante resistente é dado por:
" + " \\(V_{Rd}=\\frac{V_{pl}}{{\\gamma }_{a1}}\\) = " + resultado.vrd + " KN " + "
 Sendo:
 \\(V_{pl}=0,5\\times A_w\\times f_y\\) = " + resultado.vpl + "KN
 \\(A_w\\) = área da alma = \\(d\\times t_w\\) = " + resultado.aw + "\\({cm}^2\\)
";
MathJax.Hub.Queue(["Typeset", MathJax.Hub, textV1]);

textV2 = "
 Como " + resultado.lampV + "<" + resultado.lambV + "≤ " + resultado.lambpV + ",  \\(λ_p\\) < \\(λ\\) ≤ \\(λ_r\\), o esforço cortante resistente é dado por:
" + " \\[V_{Rd}=\\frac{{\\lambda }_p}{\\lambda }\\times \\frac{V_{pl}}{{\\gamma }_{a1}}\\]  = " + resultado.vrd + " KN " + "
 Sendo:
 \\(V_{pl}=0,5\\times A_w\\times f_y\\) = " + resultado.vpl + "KN
 \\(A_w\\) = área da alma = \\(d\\times t_w\\) = " + resultado.aw + "\\({cm}^2\\)
";
MathJax.Hub.Queue(["Typeset", MathJax.Hub, textV2]);

textV3 = "
 Como " + resultado.lambV + "> " + resultado.lambrV + ", " + "\\(λ\\) > \\(λ_r\\)" + ", o esforço cortante resistente é dado por:
" + " \\(V_{Rd}=1,24\\ \\times \\ ({\\frac{{\\lambda }_p}{\\lambda })}^2\\times \\frac{V_{pl}}{{\\gamma }_{a1}}\\)  = " + resultado.vrd + " KN " + "
 Sendo:
 \\(V_{pl}=0,5\\times A_w\\times f_y\\) = " + resultado.vpl + "KN
 \\(A_w\\) = área da alma = \\(d\\times t_w\\) = " + resultado.aw + "\\({cm}^2\\)
";
MathJax.Hub.Queue(["Typeset", MathJax.Hub, textV3]);

var text1 = "Como " + resultado.lambA + " = " + '\\(c=\\frac{2}{3x}\\) ' + " = " + resultado.lambpA
MathJax.Hub.Queue(["Typeset", MathJax.Hub, text1]);

$(document).ready(function () {
    // Header
    $(".project").html(resultado.project);
    $(".beam").html(resultado.beam);
    $(".lbForm").html(resultado.lbForm);
    $(".steel").html(resultado.steel);
    $(".fyForm").html(resultado.fyForm);
    $(".fuForm").html(resultado.fuForm);
    $(".E").html(resultado.EForm);
    $(".vk").html(resultado.vk);
    $(".mk").html(resultado.mk);
    $(".gama").html(resultado.gama);
    $(".gama1").html(resultado.gama1);
    $(".cb").html(resultado.cb);
    $(".a").html(resultado.a);

    // Section
    $("#section").html(resultado.section);
    $("#ml").html(resultado.ml);
    $("#d").html(resultado.d);
    $("#bf").html(resultado.bf);
    $(".tw").html(resultado.tw);
    $("#tf").html(resultado.tf);
    $(".h").html(resultado.h);
    $("#dl").html(resultado.dl);
    $("#area").html(resultado.area);
    $("#ix").html(resultado.ix);
    $("#wx").html(resultado.wx);
    $("#rx").html(resultado.rx);
    $("#zx").html(resultado.zx);
    $("#iy").html(resultado.iy);
    $("#wy").html(resultado.wy);
    $("#ry").html(resultado.ry);
    $("#zy").html(resultado.zy);
    $("#rt").html(resultado.rt);
    $("#it").html(resultado.it);
    $("#aba").html(resultado.aba);
    $("#alma").html(resultado.alma);
    $("#cw").html(resultado.cw);
    $("#u").html(resultado.u);

    // Lambs V
    $("#lambV").html(resultado.lambV);
    $("#lambpV").html(resultado.lambpV);
    $("#kv").html(resultado.kv);
    $("#lambrV").html(resultado.lambrV);

    // Situation V
    switch (resultado.situationV) {
        case "Caso 1":
            $("#textV").html(textV1);
            break;
        case "Caso 2":
            $("#textV").html(textV2);
            break;
        case "Caso 3":
            $("#textV").html(textV3);
            break;
    }

    $("#text1").html(text1);

});
<commit_msg>Update reportCS.js<commit_after>// Start of parsing results
function getJsonFromUrl(hashBased) {
    'use strict'
    var query;
    if (hashBased) {
        var pos = location.href.indexOf("?");
        if (pos === -1) return [];
        query = location.href.substr(pos + 1);
    } else {
        query = location.search.substr(1);
    }
    var result = {};
    query.split("&").forEach(function(part) {
        if (!part) return;
        part = part.split("+").join(" "); // replace every + with space, regexp-free version
        var eq = part.indexOf("=");
        var key = eq > -1 ? part.substr(0, eq) : part;
        var val = eq > -1 ? decodeURIComponent(part.substr(eq + 1)) : "";
        var from = key.indexOf("[");
        if (from == -1) result[decodeURIComponent(key)] = val;
        else {
            var to = key.indexOf("]");
            var index = decodeURIComponent(key.substring(from + 1, to));
            key = decodeURIComponent(key.substring(0, from));
            if (!result[key]) result[key] = [];
            if (!index) result[key].push(val);
            else result[key][index] = val;
        }
    });
    return result;
}

var resultado = [];
resultado = JSON.parse(getJsonFromUrl().test);
//End of parsing results

//Variables
var textV1, textV2, textV3;
var textA1, textA2, textA3;
var textM1, textM2, textM3;
var textT1, textT2, textT3;

// Building variable texts
textV1 = "
 Como " + resultado.lambV + " ≤ " + resultado.lambpV + ", " + "\\(λ\\) ≤ \\(λ_p\\)" + ", o esforço cortante resistente é dado por:
" + " \\(V_{Rd}=\\frac{V_{pl}}{{\\gamma }_{a1}}\\) = " + resultado.vrd + " KN
" + "
 Sendo:
 \\(V_{pl}=0,5\\times A_w\\times f_y\\) = " + resultado.vpl + "KN
 \\(A_w\\) = área da alma = \\(d\\times t_w\\) = " + resultado.aw + "\\({cm}^2\\)
";
MathJax.Hub.Queue(["Typeset", MathJax.Hub, textV1]);

textV2 = "
 Como " + resultado.lampV + " < " + resultado.lambV + " ≤ " + resultado.lambpV + ",  \\(λ_p\\) < \\(λ\\) ≤ \\(λ_r\\), o esforço cortante resistente é dado por:
" + " \\[V_{Rd}=\\frac{{\\lambda }_p}{\\lambda }\\times \\frac{V_{pl}}{{\\gamma }_{a1}}\\]  = " + resultado.vrd + " KN
" + "
 Sendo:
 \\(V_{pl}=0,5\\times A_w\\times f_y\\) = " + resultado.vpl + "KN
 \\(A_w\\) = área da alma = \\(d\\times t_w\\) = " + resultado.aw + "\\({cm}^2\\)
";
MathJax.Hub.Queue(["Typeset", MathJax.Hub, textV2]);

textV3 = "
 Como " + resultado.lambV + " > " + resultado.lambrV + ", " + "\\(λ\\) > \\(λ_r\\)" + ", o esforço cortante resistente é dado por:
" + " \\(V_{Rd}=1,24\\ \\times \\ ({\\frac{{\\lambda }_p}{\\lambda })}^2\\times \\frac{V_{pl}}{{\\gamma }_{a1}}\\)  = " + resultado.vrd + " KN
" + "
 Sendo:
 \\(V_{pl}=0,5\\times A_w\\times f_y\\) = " + resultado.vpl + "KN
 \\(A_w\\) = área da alma = \\(d\\times t_w\\) = " + resultado.aw + "\\({cm}^2\\)
";
MathJax.Hub.Queue(["Typeset", MathJax.Hub, textV3]);

textA1 = "
 Como " + resultado.lambA + " ≤ " + resultado.lambpA + ", " + "\\(λ\\) ≤ \\(λ_p\\)" + ", o momento fletor resistente é dado por:
" + " \\(M_{Rd}=\\frac{M_{pl}}{{\\gamma }_{a1}}\\) = " + resultado.mrdA + " KN.cm
" + "
 Sendo:
 \\(M_{pl}\\) = momento fletor de plastificação da seção transversal, igual ao produto do módulo de resistência plástico (z) pela resistência ao escoamento do aço (\\(fy\\))
;  \\(M_{pl}=z_x\\ \\times f_y\\)  = " + resultado.mpl + " KN.cm
";
MathJax.Hub.Queue(["Typeset", MathJax.Hub, textA1]);

textA2 = "
 Como " + resultado.lampA + " < " + resultado.lambA + " ≤ " + resultado.lambpA + ", \\(λ_p\\) < \\(λ\\) ≤ \\(λ_r\\), o momento fletor resistente é dado por:
  \\(M_{Rd}=\\frac{Cb}{{\\gamma }_{a1}}\\times (M_{pl}-(M_{pl}-\\ M_r)(\\frac{\\lambda -{\\lambda }_p}{{\\lambda }_r-{\\lambda }_p})\\)  = " + resultado.mrdA + " KN.cm
" + "
 Sendo:
 \\(C_b)\\ = coeficiente para majorar momento DESCREVER = " + resultado.cb + ";
 \\(M_{pl}\\) = momento fletor de plastificação da seção transversal, igual ao produto do módulo de resistência plástico (z) pela resistência ao escoamento do aço (\\(fy\\))
;  \\(M_{pl}=z_x\\ \\times f_y\\)  = " + resultado.mpl + " KN.cm
 \\(M_r\\) = momento fletor correspondente ao início do escoamento, incluindo a influência das tensões residuais em alguns casos;
  \\(M_r=0,7f_yW_x\\)   = " + resultado.mrA + " KN.cm
";
MathJax.Hub.Queue(["Typeset", MathJax.Hub, textA2]);

textA3 = "
 Como " + resultado.lambA + " > " + resultado.lambrA + ", " + "\\(λ\\) > \\(λ_r\\), tem-se uma viga de alma esbelta conforme Anexo H da NBR 8800:2008. Não é indicado o uso, sugere-se a escolha de outro perfil ao projeto."
MathJax.Hub.Queue(["Typeset", MathJax.Hub, textA3]);

textM1 = "
 Como " + resultado.lambM + " ≤ " + resultado.lambpM + ", \\(λ\\) ≤ \\(λ_p\\) , o momento fletor resistente é dado por:
" + " \\(M_{Rd}=\\frac{M_{pl}}{{\\gamma }_{a1}}\\) = " + resultado.mrdM + " KN.cm
" + "
 Sendo:
 \\(M_{pl}\\) = momento fletor de plastificação da seção transversal, igual ao produto do módulo de resistência plástico (z) pela resistência ao escoamento do aço (\\(fy\\))
;  \\(M_{pl}=z_x\\ \\times f_y\\)  = " + resultado.mpl + " KN.cm
";
MathJax.Hub.Queue(["Typeset", MathJax.Hub, textM1]);

textM2 = "
 Como " + resultado.lampM + " < " + resultado.lambM + " ≤ " + resultado.lambpM + ", \\(λ_p\\) < \\(λ\\) ≤ \\(λ_r\\), o momento fletor resistente é dado por:
  \\(M_{Rd}=\\frac{Cb}{{\\gamma }_{a1}}\\times (M_{pl}-(M_{pl}-\\ M_r)(\\frac{\\lambda -{\\lambda }_p}{{\\lambda }_r-{\\lambda }_p})\\)  = " + resultado.mrdM + " KN.cm
" + "
 Sendo:
 \\(C_b)\\ = coeficiente para majorar momento DESCREVER = " + resultado.cb + " ;
 \\(M_{pl}\\) = momento fletor de plastificação da seção transversal, igual ao produto do módulo de resistência plástico (z) pela resistência ao escoamento do aço (\\(fy\\))
;  \\(M_{pl}=z_x\\ \\times f_y\\)  = " + resultado.mpl + " KN.cm
 \\(M_r\\) = momento fletor correspondente ao início do escoamento, incluindo a influência das tensões residuais em alguns casos;
  \\(M_r=0,7f_yW_x\\)   = " + resultado.mrM + " KN.cm
";
MathJax.Hub.Queue(["Typeset", MathJax.Hub, textM2]);

textM3 = "
 Como " + resultado.lambM + " > " + resultado.lambrM + ", \\(λ\\) > \\(λ_r\\), o momento fletor resistente é dado por:
" + " \\(M_{Rd}=\\frac{M_{cr}}{{\\gamma }_{a1}}\\)  = " + resultado.mrdM + " KN.cm
" + "
 Sendo:
 \\(M_{cr}\\) = momento fletor de flambagem elástica. Para perfis laminados:
;  \\(M_{cr}=\\frac{0,69\\times E}{{\\lambda }^2}W_c\\)  = " + resultado.mcrM + " KN.cm
" + "
 Onde:
 \\(W_c\\) = módulo de resistência elástico do lado comprimido da seção, relativo ao eixo de flexão, neste caso, o eixo x; valor retirado das especificações do perfil = " + resultado.wx + "\\({cm}^3\\).
";
MathJax.Hub.Queue(["Typeset", MathJax.Hub, textM3]);

textT1 = "
 Como " + resultado.lambT + " ≤ " + resultado.lambpT + ", \\(λ\\) ≤ \\(λ_p\\) , o momento fletor resistente é dado por:
" + " \\(M_{Rd}=\\frac{M_{pl}}{{\\gamma }_{a1}}\\) = " + resultado.mrdT + " KN.cm
" + "
 Sendo:
 \\(M_{pl}\\) = momento fletor de plastificação da seção transversal, igual ao produto do módulo de resistência plástico (z) pela resistência ao escoamento do aço (\\(fy\\))
;  \\(M_{pl}=z_x\\ \\times f_y\\)  = " + resultado.mpl + " KN.cm
";
MathJax.Hub.Queue(["Typeset", MathJax.Hub, textT1]);

textT2 = "
 Como " + resultado.lampT + " < " + resultado.lambT + " ≤ " + resultado.lambpT + ", \\(λ_p\\) < \\(λ\\) ≤ \\(λ_r\\), o momento fletor resistente é dado por:
  \\(M_{Rd}=\\frac{Cb}{{\\gamma }_{a1}}\\times (M_{pl}-(M_{pl}-\\ M_r)(\\frac{\\lambda -{\\lambda }_p}{{\\lambda }_r-{\\lambda }_p})\\)  = " + resultado.mrdT + " KN.cm
" + "
 Sendo:
 \\(C_b)\\ = coeficiente para majorar momento DESCREVER = " + resultado.cb + " ;
 \\(M_{pl}\\) = momento fletor de plastificação da seção transversal, igual ao produto do módulo de resistência plástico (z) pela resistência ao escoamento do aço (\\(fy\\))
;  \\(M_{pl}=z_x\\ \\times f_y\\)  = " + resultado.mpl + " KN.cm
 \\(M_r\\) = momento fletor correspondente ao início do escoamento, incluindo a influência das tensões residuais em alguns casos;
  \\(M_r=0,7f_yW_x\\)   = " + resultado.mrT + " KN.cm
";
MathJax.Hub.Queue(["Typeset", MathJax.Hub, textT2]);

textT3 = "
 Como " + resultado.lambT + " > " + resultado.lambrT + ", \\(λ\\) > \\(λ_r\\), o momento fletor resistente é dado por:
" + " \\(M_{Rd}=\\frac{M_{cr}}{{\\gamma }_{a1}}\\)  = " + resultado.mrdT + " KN.cm
" + "
 Sendo:
 \\(M_{cr}\\) = momento fletor de flambagem elástica. Para perfis laminados:
;  \\(M_{cr}=\\ \\frac{C_b\times \\ {\pi }^2}{L_b}\\ \\times E\\ \\times \\ I_y\\ \\ \\times \\ \\sqrt{\\frac{C_w}{I_y}\\ \\times \\ \\left(1+0,039\\ \\times \\ \\frac{J\\times {L_b}^2}{C_w}\\right)}\\)  = " + resultado.mcrT + " KN.cm
" + "
 Onde:
 \\(C_b)\\ = coeficiente para majorar momento DESCREVER = " + resultado.cb + ";

";
MathJax.Hub.Queue(["Typeset", MathJax.Hub, textT3]);

var text1 = "Como " + resultado.lambA + " = " + '\\(c=\\frac{2}{3x}\\) ' + " = " + resultado.lambpA
MathJax.Hub.Queue(["Typeset", MathJax.Hub, text1]);

$(document).ready(function() {
    // Header
    $(".project").html(resultado.project);
    $(".beam").html(resultado.beam);
    $(".lbForm").html(resultado.lbForm);
    $(".steel").html(resultado.steel);
    $(".fyForm").html(resultado.fyForm);
    $(".fuForm").html(resultado.fuForm);
    $(".E").html(resultado.EForm);
    $(".vk").html(resultado.vk);
    $(".mk").html(resultado.mk);
    $(".gama").html(resultado.gama);
    $(".gama1").html(resultado.gama1);
    $(".cb").html(resultado.cb);
    $(".a").html(resultado.a);

    // Section
    $("#section").html(resultado.section);
    $("#ml").html(resultado.ml);
    $("#d").html(resultado.d);
    $(".bf").html(resultado.bf);
    $(".tw").html(resultado.tw);
    $(".tf").html(resultado.tf);
    $(".h").html(resultado.h);
    $(".dl").html(resultado.dl);
    $("#area").html(resultado.area);
    $("#ix").html(resultado.ix);
    $(".wx").html(resultado.wx);
    $("#rx").html(resultado.rx);
    $("#zx").html(resultado.zx);
    $(".iy").html(resultado.iy);
    $("#wy").html(resultado.wy);
    $(".ry").html(resultado.ry);
    $("#zy").html(resultado.zy);
    $("#rt").html(resultado.rt);
    $(".it").html(resultado.it);
    $("#aba").html(resultado.aba);
    $("#alma").html(resultado.alma);
    $(".cw").html(resultado.cw);
    $("#u").html(resultado.u);

    // Lambs V
    $("#lambV").html(resultado.lambV);
    $("#lambpV").html(resultado.lambpV);
    $("#kv").html(resultado.kv);
    $("#lambrV").html(resultado.lambrV);

    // Situation V
    switch (resultado.situationV) {
        case "Caso 1":
            $("#textV").html(textV1);
            break;
        case "Caso 2":
            $("#textV").html(textV2);
            break;
        case "Caso 3":
            $("#textV").html(textV3);
            break;
    }

    // Lambs A
    $("#lambA").html(resultado.lambA);
    $("#lambpA").html(resultado.lambpA);
    $("#lambrA").html(resultado.lambrA);

    // Situation A
    switch (resultado.situationA) {
        case "Caso 1":
            $("#textA").html(textA1);
            break;
        case "Caso 2":
            $("#textA").html(textA2);
            break;
        case "Caso 3":
            $("#textA").html(textA3);
            break;
    }

    // Lambs M
    $("#lambM").html(resultado.lambM);
    $("#lambpM").html(resultado.lambpM);
    $("#lambrM").html(resultado.lambrM);
    $("#tr").html(resultado.tr);

    // Situation M
    switch (resultado.situationM) {
        case "Caso 1":
            $("#textM").html(textM1);
            break;
        case "Caso 2":
            $("#textM").html(textM2);
            break;
        case "Caso 3":
            $("#textM").html(textM3);
            break;
    }

    // Lambs T
    $("#lambT").html(resultado.lambT);
    $("#lambpT").html(resultado.lambpT);
    $("#lambrT").html(resultado.lambrT);
    $("#beta1").html(resultado.beta1);

    // Situation T
    switch (resultado.situationT) {
        case "Caso 1":
            $("#textT").html(textT1);
            break;
        case "Caso 2":
            $("#textT").html(textT2);
            break;
        case "Caso 3":
            $("#textT").html(textT3);
            break;
    }

    // Results

    // Sd
    $(".vsd").html(resultado.vsd);
    $(".msd").html(resultado.msd);

    // Rd
    $(".vrd").html(resultado.vrd);
    $(".mrd").html(resultado.mrdOut);

    // Conclusion

    $("#text1").html(text1);

});
<|endoftext|>


<commit_before>const Promise = require('bluebird');

const db = {
    registerDsn: (dsns) => {
        if (dsns && dsns.hasOwnProperty('forEach')) {
            dsns.forEach((dsn) => {
                db.conn(dsn);
            })
        }
    },
    _conn: {},
    conn: (dsn) => {
        var key;

        if (typeof(dsn) == 'string') {
            key = dsn;
        }
        else if (dsn.key) {
            key = dsn.key;
        }
        else {
            key = dsn.client + '|' + dsn.connection.database + '|' + dsn.connection.host + '|' + dsn.connection.user;
        }

        if (db._conn[key]) {
            return db._conn[key];
        }

        db._conn[key] = require('knex')(dsn);
        return db._conn[key];
    },
    knex: (dsn) => {
        return db.conn(dsn);
    },
    tran: (blocks, dsn) => {
        return db.conn(dsn).transaction((tran) => {
            var results = [];

            return await(new Promise((resolve, reject) => {
                Promise.each(blocks, (block) => {
                    var payload = block.apply(this, results)

                    if (payload) {
                        return tran.raw(payload[0], payload[1]).then((result) => {
                            results.push(result[0])
                        });
                    }
                }).then(() => {
                    resolve.apply(this, results);
                }).catch((error) => {
                    reject(error)
                })
            }))
        })
    },
    execute: (query, params, dsn) => {
        if (dsn == undefined && params) {
            dsn = params;
            params = undefined;
        }

        return await(new Promise((resolve, reject) => {
            db.conn(dsn).raw(query, params).then((result) => {
                resolve(result[0] ? result[0] : {})
            }).catch((error) => {
                reject(error)
            })
        }))
    },
    rows: (query, params, dsn) => {
        var result = db.execute(query, params, dsn);
        return result;
    },
    row: (query, params, dsn) => {
        var result = db.rows(query, params, dsn);
        return result && result.length >= 1 ? result[0] : null;
    }
};

module.exports = db;
<commit_msg>remove hasOwnProperty check.<commit_after>const Promise = require('bluebird');

const db = {
    registerDsn: (dsns) => {
        if (dsns) {
            dsns.forEach((dsn) => {
                db.conn(dsn);
            })
        }
    },
    _conn: {},
    conn: (dsn) => {
        var key;

        if (typeof(dsn) == 'string') {
            key = dsn;
        }
        else if (dsn.key) {
            key = dsn.key;
        }
        else {
            key = dsn.client + '|' + dsn.connection.database + '|' + dsn.connection.host + '|' + dsn.connection.user;
        }

        if (db._conn[key]) {
            return db._conn[key];
        }

        db._conn[key] = require('knex')(dsn);
        return db._conn[key];
    },
    knex: (dsn) => {
        return db.conn(dsn);
    },
    tran: (blocks, dsn) => {
        return db.conn(dsn).transaction((tran) => {
            var results = [];

            return await(new Promise((resolve, reject) => {
                Promise.each(blocks, (block) => {
                    var payload = block.apply(this, results)

                    if (payload) {
                        return tran.raw(payload[0], payload[1]).then((result) => {
                            results.push(result[0])
                        });
                    }
                }).then(() => {
                    resolve.apply(this, results);
                }).catch((error) => {
                    reject(error)
                })
            }))
        })
    },
    execute: (query, params, dsn) => {
        if (dsn == undefined && params) {
            dsn = params;
            params = undefined;
        }

        return await(new Promise((resolve, reject) => {
            db.conn(dsn).raw(query, params).then((result) => {
                resolve(result[0] ? result[0] : {})
            }).catch((error) => {
                reject(error)
            })
        }))
    },
    rows: (query, params, dsn) => {
        var result = db.execute(query, params, dsn);
        return result;
    },
    row: (query, params, dsn) => {
        var result = db.rows(query, params, dsn);
        return result && result.length >= 1 ? result[0] : null;
    }
};

module.exports = db;
<|endoftext|>