<commit_before>import React from 'react';

//import Web3 from "web3"
import BLOCKCHAIN_INFO from "../../../../../env"

export default class CachedServerProvider extends React.Component {
    constructor(props) {
        super(props)
        this.rpcUrl = props.url
        this.maxRequestTime = 3000
    }

    getGasPrice() {
        return new Promise((resolve, rejected) => {
            this.timeout(this.maxRequestTime, fetch(this.rpcUrl + '/getGasPrice'))
            .then((response) => {
                return response.json()
            }).then((result) => {
                if (result.success) {
                    resolve(result.data)
                } else {
                    rejected(new Error("Cannot get gas price from server"))
                }
            })
                .catch((err) => {
                    console.log(err.message)
                    rejected(new Error("Cannot get gas price from server"))
                })
        })
    }

    // getGasFromEthgasstation() {
    //     return new Promise((resolve, rejected) => {
    //         fetch(BLOCKCHAIN_INFO.gasstation_endpoint)
    //             .then((response) => {
    //                 return response.json()
    //             })
    //             .then((data) => {
    //                 resolve(data)
    //             })
    //             .catch((err) => {
    //                 rejected(err)
    //             })
    //     })
    // }

    checkKyberEnable() {
        return new Promise((resolve, rejected) => {
            this.timeout(this.maxRequestTime, fetch(this.rpcUrl + '/getKyberEnabled'))
            .then((response) => {
                return response.json()
            }).then((result) => {
                if (result.success) {
                    resolve(result.data)
                } else {
                    rejected(new Error("Cannot check kyber enable from server"))
                }
            })
                .catch((err) => {
                    console.log(err.message)
                    rejected(new Error("Cannot check kyber enable from server"))
                })
        })
    }

    getMaxGasPrice() {
        return new Promise((resolve, rejected) => {
            this.timeout(this.maxRequestTime, fetch(this.rpcUrl + '/getMaxGasPrice'))
            .then((response) => {
                return response.json()
            }).then((result) => {
                if (result.success) {
                    resolve(result.data)
                } else {
                    rejected(new Error("Cannot get max gas price from server"))
                }
            })
                .catch((err) => {
                    console.log(err.message)
                    rejected(new Error("Cannot get max gas price from server"))
                })
        })
    }

    getLatestBlock() {
        return new Promise((resolve, rejected) => {
            this.timeout(this.maxRequestTime, fetch(this.rpcUrl + '/getLatestBlock'))
            .then((response) => {
                return response.json()
            }).then((result) => {
                if (result.success) {
                    resolve(result.data)
                } else {
                    rejected(new Error("Cannot get latest block from server"))
                }
            })
                .catch((err) => {
                    rejected(new Error("Cannot get latest block from server"))
                })
        })
    }

    getAllRates(tokensObj) {
        return new Promise((resolve, rejected) => {
            this.timeout(this.maxRequestTime, fetch(this.rpcUrl + '/getRate'))

                .then((response) => {
                    return response.json()
                })
                .then(result => {
                    if (result.success) {
                        resolve(result.data)
                    } else {
                        rejected(new Error("Rate server is not fetching"))
                    }
                })
                .catch((err) => {
                    rejected(err)
                })
        })
    }

    getAllRatesUSD() {
        return new Promise((resolve, rejected) => {
            this.timeout(this.maxRequestTime, fetch(this.rpcUrl + '/getRateUSD'))
            .then((response) => {
                return response.json()
            })
                .then((result) => {
                    if (result.success) {
                        resolve(result.data)
                    } else {
                        rejected(new Error("RateUSD server is not fetching"))
                    }
                })
                .catch((err) => {
                    rejected(err)
                })
        })
    }

    getRateETH() {
        return new Promise((resolve, rejected) => {
            this.timeout(this.maxRequestTime, fetch(this.rpcUrl + '/getRateETH'))
            .then((response) => {
                return response.json()
            })
                .then((result) => {
                    if (result.success) {
                        resolve(result.data)
                    } else {
                        rejected(new Error("RateETHs server is not fetching"))
                    }
                })
                .catch((err) => {
                    rejected(err)
                })
        })
    }

    getLanguagePack(lang) {
        return new Promise((resolve, rejected) => {
            rejected(new Error("This api /getLanguagePack will comming soon"))
        })
    }

    getInfo(infoObj) {
        console.log(infoObj)
        fetch('https://broadcast.kyber.network/broadcast/' + infoObj.hash, {
            method: 'GET',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
        })

        return new Promise((resolve, rejected) => {
            resolve("get_info_successfully")
        })
    }

    getExchangeEnable(address) {
        return new Promise((resolve, rejected) => {
            this.timeout(this.maxRequestTime, fetch(BLOCKCHAIN_INFO.statEndPoint + '/richguy/' + address))

                .then((response) => {
                    return response.json()
                })
                .then((result) => {
                    if (result.success) {
                        resolve(result.data)
                    } else {
                        resolve(false)
                    }
                })
                .catch((err) => {
                    console.log(err)
                    resolve(false)
                })
        })
    }

    getMarketData() {
        return new Promise((resolve, rejected) => {
            this.timeout(this.maxRequestTime, fetch(this.rpcUrl + '/getMarketData'))
            .then((response) => {
                return response.json()
            })
                .then((result) => {
                    if (result.success) {
                        resolve(result.data)
                    } else {
                        rejected(new Error("Market data is not fetching"))
                    }
                })
                .catch((err) => {
                    rejected(err)
                })
        })
    }

    getGeneralTokenInfo() {
        return new Promise((resolve, rejected) => {
            this.timeout(this.maxRequestTime, fetch(this.rpcUrl + '/getTokenInfo'))
            .then((response) => {
                return response.json()
            })
                .then((result) => {
                    if (result.success) {
                        resolve(result.data)
                    } else {
                        rejected(new Error("Market data is not fetching"))
                    }
                })
                .catch((err) => {
                    rejected(err)
                })
        })
    }

    getVolumnChart() {
        return new Promise((resolve, rejected) => {
            this.timeout(this.maxRequestTime, fetch(BLOCKCHAIN_INFO.tracker + '/api/tokens/rates'))
            //fetch(BLOCKCHAIN_INFO.tracker + '/api/tokens/rates', {
            .then((response) => {
                return response.json()
            })
                .then((result) => {
                    resolve(result)
                })
                .catch((err) => {
                    console.log(err)
                    rejected(err)
                })
        })
    }

    getMarketInfo(queryString) {
        return new Promise((resolve, rejected) => {
            this.timeout(this.maxRequestTime, fetch(this.rpcUrl + '/getMarketInfoByTokens' + '?listToken=' + queryString))
            //fetch(this.rpcUrl + '/getMarketInfoByTokens' + '?listToken=' + queryString, {
            .then((response) => {
                return response.json()
            })
                .then((result) => {
                    resolve(result)
                })
                .catch((err) => {
                    console.log(err)
                    rejected(err)
                })
        })
    }

    getRightMarketInfo() {
        return new Promise((resolve, rejected) => {
            this.timeout(this.maxRequestTime,  fetch(this.rpcUrl + '/getRightMarketInfo'))
            .then((response) => {
                return response.json()
            })
                .then((result) => {
                    resolve(result)
                })
                .catch((err) => {
                    console.log(err)
                    rejected(err)
                })
        })
    }

    getLast7D(queryString) {
        return new Promise((resolve, rejected) => {
            this.timeout(this.maxRequestTime, fetch(this.rpcUrl + '/getLast7D' + '?listToken=' + queryString))
            //fetch(this.rpcUrl + '/getLast7D' + '?listToken=' + queryString, {
            .then((response) => {
                return response.json()
            })
                .then((result) => {
                    resolve(result)
                })
                .catch((err) => {
                    console.log(err)
                    rejected(err)
                })
        })
    }

    getUserMaxCap(address) {
        return new Promise((resolve, rejected) => {
            this.timeout(this.maxRequestTime,  fetch(BLOCKCHAIN_INFO.statEndPoint + '/cap-by-address/' + address))
            .then((response) => {
                return response.json()
            })
                .then((result) => {
                    if (result.data) {
                        var val = parseFloat(result.data);
                        if (isNaN(val)) {
                            rejected(new Error("Cannot parse data user cap"))
                        } else {
                            resolve(result)
                        }
                    } else {
                        rejected(new Error("Cannot parse data user cap"))
                    }
                })
                .catch((err) => {
                    rejected(err)
                })
        })
    }

    timeout(ms, promise) {
        return new Promise(function (resolve, reject) {
            setTimeout(function () {
                reject(new Error("timeout"))
            }, ms)
            promise.then(resolve, reject)
        })
    }
}
<commit_msg>change for new api cache<commit_after>import React from 'react';

//import Web3 from "web3"
import BLOCKCHAIN_INFO from "../../../../../env"

export default class CachedServerProvider extends React.Component {
    constructor(props) {
        super(props)
        this.rpcUrl = props.url
        this.maxRequestTime = 3000
    }

    getGasPrice() {
        return new Promise((resolve, rejected) => {
            this.timeout(this.maxRequestTime, fetch(this.rpcUrl + '/gasPrice'))
            .then((response) => {
                return response.json()
            }).then((result) => {
                if (result.success) {
                    resolve(result.data)
                } else {
                    rejected(new Error("Cannot get gas price from server"))
                }
            })
                .catch((err) => {
                    console.log(err.message)
                    rejected(new Error("Cannot get gas price from server"))
                })
        })
    }

    // getGasFromEthgasstation() {
    //     return new Promise((resolve, rejected) => {
    //         fetch(BLOCKCHAIN_INFO.gasstation_endpoint)
    //             .then((response) => {
    //                 return response.json()
    //             })
    //             .then((data) => {
    //                 resolve(data)
    //             })
    //             .catch((err) => {
    //                 rejected(err)
    //             })
    //     })
    // }

    checkKyberEnable() {
        return new Promise((resolve, rejected) => {
            this.timeout(this.maxRequestTime, fetch(this.rpcUrl + '/kyberEnabled'))
            .then((response) => {
                return response.json()
            }).then((result) => {
                if (result.success) {
                    resolve(result.data)
                } else {
                    rejected(new Error("Cannot check kyber enable from server"))
                }
            })
                .catch((err) => {
                    console.log(err.message)
                    rejected(new Error("Cannot check kyber enable from server"))
                })
        })
    }

    getMaxGasPrice() {
        return new Promise((resolve, rejected) => {
            this.timeout(this.maxRequestTime, fetch(this.rpcUrl + '/maxGasPrice'))
            .then((response) => {
                return response.json()
            }).then((result) => {
                if (result.success) {
                    resolve(result.data)
                } else {
                    rejected(new Error("Cannot get max gas price from server"))
                }
            })
                .catch((err) => {
                    console.log(err.message)
                    rejected(new Error("Cannot get max gas price from server"))
                })
        })
    }

    getLatestBlock() {
        return new Promise((resolve, rejected) => {
            this.timeout(this.maxRequestTime, fetch(this.rpcUrl + '/latestBlock'))
            .then((response) => {
                return response.json()
            }).then((result) => {
                if (result.success) {
                    resolve(result.data)
                } else {
                    rejected(new Error("Cannot get latest block from server"))
                }
            })
                .catch((err) => {
                    rejected(new Error("Cannot get latest block from server"))
                })
        })
    }

    getAllRates(tokensObj) {
        return new Promise((resolve, rejected) => {
            this.timeout(this.maxRequestTime, fetch(this.rpcUrl + '/rate'))

                .then((response) => {
                    return response.json()
                })
                .then(result => {
                    if (result.success) {
                        resolve(result.data)
                    } else {
                        rejected(new Error("Rate server is not fetching"))
                    }
                })
                .catch((err) => {
                    rejected(err)
                })
        })
    }

    getAllRatesUSD() {
        return new Promise((resolve, rejected) => {
            this.timeout(this.maxRequestTime, fetch(this.rpcUrl + '/rateUSD'))
            .then((response) => {
                return response.json()
            })
                .then((result) => {
                    if (result.success) {
                        resolve(result.data)
                    } else {
                        rejected(new Error("RateUSD server is not fetching"))
                    }
                })
                .catch((err) => {
                    rejected(err)
                })
        })
    }

    getRateETH() {
        return new Promise((resolve, rejected) => {
            this.timeout(this.maxRequestTime, fetch(this.rpcUrl + '/rateETH'))
            .then((response) => {
                return response.json()
            })
                .then((result) => {
                    if (result.success) {
                        resolve(result.data)
                    } else {
                        rejected(new Error("RateETHs server is not fetching"))
                    }
                })
                .catch((err) => {
                    rejected(err)
                })
        })
    }

    getLanguagePack(lang) {
        return new Promise((resolve, rejected) => {
            rejected(new Error("This api /getLanguagePack will comming soon"))
        })
    }

    getInfo(infoObj) {
        console.log(infoObj)
        fetch('https://broadcast.kyber.network/broadcast/' + infoObj.hash, {
            method: 'GET',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
        })

        return new Promise((resolve, rejected) => {
            resolve("get_info_successfully")
        })
    }

    getExchangeEnable(address) {
        return new Promise((resolve, rejected) => {
            this.timeout(this.maxRequestTime, fetch(BLOCKCHAIN_INFO.statEndPoint + '/richguy/' + address))

                .then((response) => {
                    return response.json()
                })
                .then((result) => {
                    if (result.success) {
                        resolve(result.data)
                    } else {
                        resolve(false)
                    }
                })
                .catch((err) => {
                    console.log(err)
                    resolve(false)
                })
        })
    }

    getMarketData() {
        return new Promise((resolve, rejected) => {
            this.timeout(this.maxRequestTime, fetch(this.rpcUrl + '/getMarketData'))
            .then((response) => {
                return response.json()
            })
                .then((result) => {
                    if (result.success) {
                        resolve(result.data)
                    } else {
                        rejected(new Error("Market data is not fetching"))
                    }
                })
                .catch((err) => {
                    rejected(err)
                })
        })
    }

    getGeneralTokenInfo() {
        return new Promise((resolve, rejected) => {
            this.timeout(this.maxRequestTime, fetch(this.rpcUrl + '/getTokenInfo'))
            .then((response) => {
                return response.json()
            })
                .then((result) => {
                    if (result.success) {
                        resolve(result.data)
                    } else {
                        rejected(new Error("Market data is not fetching"))
                    }
                })
                .catch((err) => {
                    rejected(err)
                })
        })
    }

    getVolumnChart() {
        return new Promise((resolve, rejected) => {
            this.timeout(this.maxRequestTime, fetch(BLOCKCHAIN_INFO.tracker + '/api/tokens/rates'))
            //fetch(BLOCKCHAIN_INFO.tracker + '/api/tokens/rates', {
            .then((response) => {
                return response.json()
            })
                .then((result) => {
                    resolve(result)
                })
                .catch((err) => {
                    console.log(err)
                    rejected(err)
                })
        })
    }

    getMarketInfo(queryString) {
        return new Promise((resolve, rejected) => {
            this.timeout(this.maxRequestTime, fetch(this.rpcUrl + '/getMarketInfoByTokens' + '?listToken=' + queryString))
            //fetch(this.rpcUrl + '/getMarketInfoByTokens' + '?listToken=' + queryString, {
            .then((response) => {
                return response.json()
            })
                .then((result) => {
                    resolve(result)
                })
                .catch((err) => {
                    console.log(err)
                    rejected(err)
                })
        })
    }

    getRightMarketInfo() {
        return new Promise((resolve, rejected) => {
            this.timeout(this.maxRequestTime,  fetch(this.rpcUrl + '/marketInfo'))
            .then((response) => {
                return response.json()
            })
                .then((result) => {
                    resolve(result)
                })
                .catch((err) => {
                    console.log(err)
                    rejected(err)
                })
        })
    }

    getLast7D(queryString) {
        return new Promise((resolve, rejected) => {
            this.timeout(this.maxRequestTime, fetch(this.rpcUrl + '/last7D' + '?listToken=' + queryString))
            //fetch(this.rpcUrl + '/getLast7D' + '?listToken=' + queryString, {
            .then((response) => {
                return response.json()
            })
                .then((result) => {
                    resolve(result)
                })
                .catch((err) => {
                    console.log(err)
                    rejected(err)
                })
        })
    }

    getUserMaxCap(address) {
        return new Promise((resolve, rejected) => {
            this.timeout(this.maxRequestTime,  fetch(BLOCKCHAIN_INFO.statEndPoint + '/cap-by-address/' + address))
            .then((response) => {
                return response.json()
            })
                .then((result) => {
                    if (result.data) {
                        var val = parseFloat(result.data);
                        if (isNaN(val)) {
                            rejected(new Error("Cannot parse data user cap"))
                        } else {
                            resolve(result)
                        }
                    } else {
                        rejected(new Error("Cannot parse data user cap"))
                    }
                })
                .catch((err) => {
                    rejected(err)
                })
        })
    }

    timeout(ms, promise) {
        return new Promise(function (resolve, reject) {
            setTimeout(function () {
                reject(new Error("timeout"))
            }, ms)
            promise.then(resolve, reject)
        })
    }
}
<|endoftext|>


<commit_before>var FastMath = require('./fastMath');
var factory = {};
var _ = require('underscore');

/**
 * Polynomial of max 3rd degree
 * @param {Array} coeffArray [description]
 * @param {double} startPoint Point on the X-axis where to start evaluating
 * @param {double} endPoint where on x-axis does the evaluation stop
 */
var Polynomial = function(coeffArray, startPoint, endPoint) {

    this.A = coeffArray[3];
    this.B = coeffArray[2];
    this.C = coeffArray[1];
    this.D = coeffArray[0];
    this.startPoint = startPoint;
    this.endPoint = endPoint;

};

Polynomial.prototype.evaluateAt = function(x) {
    if (FastMath.lt(x, this.startPoint))
        throw new Error('Trying to evalute polynomial with x value less than the start point');
    if (FastMath.gt(x, this.endPoint))
        throw new Error('Trying to evaluate polynomial with x value greater than the end point');
    return this.A * Math.pow(x - this.startPoint, 3) + this.B * Math.pow(x - this.startPoint, 2) + this.C * (x - this.startPoint) + this.D;
};

/**
 * Takes derivative of this polynomial and returns a new polynomial
 * @returns {Polynomial} a new polynomial
 */
Polynomial.prototype.derivative = function() {
    var b = 3 * this.A;
    var c = 2 * this.B;
    var d = this.C;

    return new Polynomial([d, c, b, 0], this.startPoint, this.endPoint);
};

/**
 * Calculate cubic roots - props to http://stackoverflow.com/a/27176424/1579778
 */
Polynomial.prototype.roots = function() {

    var that = this;
    var roots = calculateCubicRoots(this.A, this.B, this.C, this.D);
    return roots.filter(function(value) {
        if (FastMath.geq(value, that.startPoint) && FastMath.leq(value, that.endPoint))
            return true;
    });
};

/**
 * gets all of the extreme values
 * @return {Array} an array of MotionPoints corresponding to the extremum
 */
Polynomial.prototype.getExtremeValues = function () {
    var that = this;
    var firstD = this.derivative();
    var x = calculateCubicRoots(firstD.A, firstD.B, firstD.C, firstD.D);
    x = x.map(function (xxx) {
        return xxx + that.startPoint;
    });
    x = x.filter(function (r) {
        return typeof r == 'number' && !isNaN(r) && isFinite(r) && FastMath.gt(r, that.startPoint) && FastMath.lt(r, that.endPoint);
    });

    // x = [].concat(y, this.startPoint, this.endPoint);
    x = _.uniq([].concat(x, this.startPoint, this.endPoint)).sort(function (curr, next) {
        return curr-next;
    });

    var y = x.map(function (r) {
        return that.evaluateAt(r);
    });

    var minY = _.min(y);
    var maxY = _.max(y);

    var indexes = [];

    // var indexes = y.reduce(function (acc, curr, i, arr) {
    //     return curr == minY || cur == maxY;
    // });

    for (i = 0; i < y.length; i++) {
        if (FastMath.equal(y[i], minY) || FastMath.equal(y[i], maxY)) {
            indexes.push(i);
        }
    }

    var xx = [];
    var yy = [];

    indexes.forEach(function (ind) {
        xx.push(x[ind]);
        yy.push(y[ind]);
    });

    return {x: xx, y: yy};
}

Polynomial.prototype.toPrettyString = function() {
    return this.this.A + '(x-' + this.startPoint + ')^3 + ' + this.B + '(x-' + this.startPoint + ')^2 + ' + this.C + '(x-' + this.startPoint + ')' + this.D;
};

var cuberoot = function cuberoot(x) {
    var y = Math.pow(Math.abs(x), 1 / 3);
    return x < 0 ? -y : y;
};

var calculateCubicRoots = function(a, b, c, d) {
    var D;
    var u;

    if (Math.abs(a) < 1e-8) { // Quadratic case, ax^2+bx+c=0
        a = b;
        b = c;
        c = d;
        if (Math.abs(a) < 1e-8) { // Linear case, ax+b=0
            a = b;
            b = c;
            if (Math.abs(a) < 1e-8) // Degenerate case
                return [];
            return [-b / a];
        }

        D = b * b - 4 * a * c;
        if (Math.abs(D) < 1e-8)
            return [-b / (2 * a)];
        else if (D > 0)
            return [(-b + Math.sqrt(D)) / (2 * a), (-b - Math.sqrt(D)) / (2 * a)];
        return [];
    }

    // Convert to depressed cubic t^3+pt+q = 0 (subst x = t - b/3a)
    var p = (3 * a * c - b * b) / (3 * a * a);
    var q = (2 * b * b * b - 9 * a * b * c + 27 * a * a * d) / (27 * a * a * a);
    var roots;

    if (Math.abs(p) < 1e-8) { // p = 0 -> t^3 = -q -> t = -q^1/3
        roots = [cuberoot(-q)];
    } else if (Math.abs(q) < 1e-8) { // q = 0 -> t^3 + pt = 0 -> t(t^2+p)=0
        roots = [0].concat(p < 0 ? [Math.sqrt(-p), -Math.sqrt(-p)] : []);
    } else {
        D = q * q / 4 + p * p * p / 27;
        if (Math.abs(D) < 1e-8) { // D = 0 -> two roots
            roots = [-1.5 * q / p, 3 * q / p];
        } else if (D > 0) { // Only one real root
            u = cuberoot(-q / 2 - Math.sqrt(D));
            roots = [u - p / (3 * u)];
        } else { // D < 0, three roots, but needs to use complex numbers/trigonometric solution
            u = 2 * Math.sqrt(-p / 3);
            var t = Math.acos(3 * q / p / u) / 3; // D < 0 implies p < 0 and acos argument in [-1..1]
            var k = 2 * Math.PI / 3;
            roots = [u * Math.cos(t), u * Math.cos(t - k), u * Math.cos(t - 2 * k)];
        }
    }

    // Convert back from depressed cubic
    for (var i = 0; i < roots.length; i++)
        roots[i] -= b / (3 * a);

    return roots;
};

/**
 * Creates a new  polynomial with coefficients A,B,C,D
 * Ax^3 + Bx^2 + Cx +D
 * @param {Array} coeffs [array of coefficients]
 * @param {double} startPoint where on x-axis does this poly start
 * @param {double} endPoint where on a x-axis does this poly end
 */
factory.createPolyAbCd = function(coeffs, startPoint, endPoint) {
    if (!Array.isArray(coeffs) || coeffs.length != 4)
        throw new Error('expecting parameter of type array and length 4');

    if (!FastMath.isNumeric(startPoint) || startPoint < 0)
        throw new Error('expecting a valid startpoint');

    if (!FastMath.isNumeric(endPoint) || endPoint <= startPoint)
        throw new Error('expecting valid endpoint');

    var poly = new Polynomial(coeffs.reverse(), startPoint, endPoint);

    return poly;
};

module.exports = factory;<commit_msg>forgot a semiclon<commit_after>var FastMath = require('./fastMath');
var factory = {};
var _ = require('underscore');

/**
 * Polynomial of max 3rd degree
 * @param {Array} coeffArray [description]
 * @param {double} startPoint Point on the X-axis where to start evaluating
 * @param {double} endPoint where on x-axis does the evaluation stop
 */
var Polynomial = function(coeffArray, startPoint, endPoint) {

    this.A = coeffArray[3];
    this.B = coeffArray[2];
    this.C = coeffArray[1];
    this.D = coeffArray[0];
    this.startPoint = startPoint;
    this.endPoint = endPoint;

};

Polynomial.prototype.evaluateAt = function(x) {
    if (FastMath.lt(x, this.startPoint))
        throw new Error('Trying to evalute polynomial with x value less than the start point');
    if (FastMath.gt(x, this.endPoint))
        throw new Error('Trying to evaluate polynomial with x value greater than the end point');
    return this.A * Math.pow(x - this.startPoint, 3) + this.B * Math.pow(x - this.startPoint, 2) + this.C * (x - this.startPoint) + this.D;
};

/**
 * Takes derivative of this polynomial and returns a new polynomial
 * @returns {Polynomial} a new polynomial
 */
Polynomial.prototype.derivative = function() {
    var b = 3 * this.A;
    var c = 2 * this.B;
    var d = this.C;

    return new Polynomial([d, c, b, 0], this.startPoint, this.endPoint);
};

/**
 * Calculate cubic roots - props to http://stackoverflow.com/a/27176424/1579778
 */
Polynomial.prototype.roots = function() {

    var that = this;
    var roots = calculateCubicRoots(this.A, this.B, this.C, this.D);
    return roots.filter(function(value) {
        if (FastMath.geq(value, that.startPoint) && FastMath.leq(value, that.endPoint))
            return true;
    });
};

/**
 * gets all of the extreme values
 * @return {Array} an array of MotionPoints corresponding to the extremum
 */
Polynomial.prototype.getExtremeValues = function () {
    var that = this;
    var firstD = this.derivative();
    var x = calculateCubicRoots(firstD.A, firstD.B, firstD.C, firstD.D);
    x = x.map(function (xxx) {
        return xxx + that.startPoint;
    });
    x = x.filter(function (r) {
        return typeof r == 'number' && !isNaN(r) && isFinite(r) && FastMath.gt(r, that.startPoint) && FastMath.lt(r, that.endPoint);
    });

    // x = [].concat(y, this.startPoint, this.endPoint);
    x = _.uniq([].concat(x, this.startPoint, this.endPoint)).sort(function (curr, next) {
        return curr-next;
    });

    var y = x.map(function (r) {
        return that.evaluateAt(r);
    });

    var minY = _.min(y);
    var maxY = _.max(y);

    var indexes = [];

    // var indexes = y.reduce(function (acc, curr, i, arr) {
    //     return curr == minY || cur == maxY;
    // });

    for (i = 0; i < y.length; i++) {
        if (FastMath.equal(y[i], minY) || FastMath.equal(y[i], maxY)) {
            indexes.push(i);
        }
    }

    var xx = [];
    var yy = [];

    indexes.forEach(function (ind) {
        xx.push(x[ind]);
        yy.push(y[ind]);
    });

    return {x: xx, y: yy};
};

Polynomial.prototype.toPrettyString = function() {
    return this.this.A + '(x-' + this.startPoint + ')^3 + ' + this.B + '(x-' + this.startPoint + ')^2 + ' + this.C + '(x-' + this.startPoint + ')' + this.D;
};

var cuberoot = function cuberoot(x) {
    var y = Math.pow(Math.abs(x), 1 / 3);
    return x < 0 ? -y : y;
};

var calculateCubicRoots = function(a, b, c, d) {
    var D;
    var u;

    if (Math.abs(a) < 1e-8) { // Quadratic case, ax^2+bx+c=0
        a = b;
        b = c;
        c = d;
        if (Math.abs(a) < 1e-8) { // Linear case, ax+b=0
            a = b;
            b = c;
            if (Math.abs(a) < 1e-8) // Degenerate case
                return [];
            return [-b / a];
        }

        D = b * b - 4 * a * c;
        if (Math.abs(D) < 1e-8)
            return [-b / (2 * a)];
        else if (D > 0)
            return [(-b + Math.sqrt(D)) / (2 * a), (-b - Math.sqrt(D)) / (2 * a)];
        return [];
    }

    // Convert to depressed cubic t^3+pt+q = 0 (subst x = t - b/3a)
    var p = (3 * a * c - b * b) / (3 * a * a);
    var q = (2 * b * b * b - 9 * a * b * c + 27 * a * a * d) / (27 * a * a * a);
    var roots;

    if (Math.abs(p) < 1e-8) { // p = 0 -> t^3 = -q -> t = -q^1/3
        roots = [cuberoot(-q)];
    } else if (Math.abs(q) < 1e-8) { // q = 0 -> t^3 + pt = 0 -> t(t^2+p)=0
        roots = [0].concat(p < 0 ? [Math.sqrt(-p), -Math.sqrt(-p)] : []);
    } else {
        D = q * q / 4 + p * p * p / 27;
        if (Math.abs(D) < 1e-8) { // D = 0 -> two roots
            roots = [-1.5 * q / p, 3 * q / p];
        } else if (D > 0) { // Only one real root
            u = cuberoot(-q / 2 - Math.sqrt(D));
            roots = [u - p / (3 * u)];
        } else { // D < 0, three roots, but needs to use complex numbers/trigonometric solution
            u = 2 * Math.sqrt(-p / 3);
            var t = Math.acos(3 * q / p / u) / 3; // D < 0 implies p < 0 and acos argument in [-1..1]
            var k = 2 * Math.PI / 3;
            roots = [u * Math.cos(t), u * Math.cos(t - k), u * Math.cos(t - 2 * k)];
        }
    }

    // Convert back from depressed cubic
    for (var i = 0; i < roots.length; i++)
        roots[i] -= b / (3 * a);

    return roots;
};

/**
 * Creates a new  polynomial with coefficients A,B,C,D
 * Ax^3 + Bx^2 + Cx +D
 * @param {Array} coeffs [array of coefficients]
 * @param {double} startPoint where on x-axis does this poly start
 * @param {double} endPoint where on a x-axis does this poly end
 */
factory.createPolyAbCd = function(coeffs, startPoint, endPoint) {
    if (!Array.isArray(coeffs) || coeffs.length != 4)
        throw new Error('expecting parameter of type array and length 4');

    if (!FastMath.isNumeric(startPoint) || startPoint < 0)
        throw new Error('expecting a valid startpoint');

    if (!FastMath.isNumeric(endPoint) || endPoint <= startPoint)
        throw new Error('expecting valid endpoint');

    var poly = new Polynomial(coeffs.reverse(), startPoint, endPoint);

    return poly;
};

module.exports = factory;<|endoftext|>


<commit_before>module.exports = inject

function inject (bot) {
  bot.isAlive = false

  bot._client.on('respawn', (packet) => {
    bot.isAlive = false
    bot.emit('respawn')
  })

  bot._client.on('update_health', (packet) => {
    bot.health = packet.health
    bot.food = packet.food
    bot.foodSaturation = packet.foodSaturation
    bot.emit('health')
    if (bot.health <= 0) {
      bot.isAlive = false
      bot.emit('death')
      bot._client.write('client_command', { payload: 0 })
    } else if (bot.health > 0 && !bot.isAlive) {
      bot.isAlive = true
      bot.emit('spawn')
    }
  })
}
<commit_msg>Start the bot alive<commit_after>module.exports = inject

function inject (bot) {
  bot.isAlive = true

  bot._client.on('respawn', (packet) => {
    bot.isAlive = false
    bot.emit('respawn')
  })

  bot._client.on('update_health', (packet) => {
    bot.health = packet.health
    bot.food = packet.food
    bot.foodSaturation = packet.foodSaturation
    bot.emit('health')
    if (bot.health <= 0) {
      bot.isAlive = false
      bot.emit('death')
      bot._client.write('client_command', { payload: 0 })
    } else if (bot.health > 0 && !bot.isAlive) {
      bot.isAlive = true
      bot.emit('spawn')
    }
  })
}
<|endoftext|>


<commit_before>/**
 * Define Global Namespace
 */
var Capitan = function (out) {
	out = out || {};

	for (var i = 1; i < arguments.length; i++) {
		if (!arguments[i]) {
			continue;
		}

		for (var key in arguments[i]) {
			if (arguments[i].hasOwnProperty(key)) {
				out[key] = arguments[i][key];
			}
		}
	}

	return out;
}({}, (Capitan || {}), {
	Vars: {
		// path to assets folder
		folderPath: '%%public%%/',
		// standard breakpoints
		breakpoints: {},
		// mobile first (xs, sm, md, lg, xl)
		currentBreakpoint: 'xs',
		// portrait first (portrait, landscape)
		currentOrientation: 'portrait',
		isIE: window.navigator.userAgent.indexOf("MSIE ") > -1 || // IE <= 10
			!(window.ActiveXObject) && "ActiveXObject" in window || // IE 11
			/x64|x32/ig.test(window.navigator.userAgent) // IE 12
	},
	// CSS components script namespace
	Component: {},
	// functions must return something
	Function: {},
	// everything that has to do with event handling
	Handle: {},
	// Should be used for scripts that have nothing to do with components, e.g. placeholder polyfills, plugins, etc.
	Util: {}
});

// <@delete
// clear basket in develop mode
basket.clear();
// delete@>

// abortion timeout for asset fetching, default 5000ms
basket.timeout = 60000;

/**
 * Load main plugins via basket.js
 */
basket.require(
	{
		url: Capitan.Vars.folderPath + 'js/libs/vendor/jquery/jquery.min.js',
		unique: 0
	},
	{
		url: Capitan.Vars.folderPath + 'js/libs/vendor/modernizr/modernizr.custom.min.js',
		unique: 0
	},
	{
		url: Capitan.Vars.folderPath + 'js/libs/vendor/import/jquery.import.min.js',
		unique: 0
	}
).then(function () {
	(function ($) {
		// store commonly used jQuery objects to Vars object
		Capitan.Vars = $.extend(Capitan.Vars, {
			$html: $('html'),
			$body: $('body'),
			$window: $(window),
			$doc: $(document)
		});

		// Assets that are necessary globally and on every page, can and will be loaded here (DOM not ready)
		Capitan.Util.fetchBeforeRender = function () {
			return $.import([
				{
					condition: true,
					order: 0,
					fetch: [
						// <@bundle#before-render
						Capitan.Vars.folderPath + 'js/util/console-polyfill.js',
						Capitan.Vars.folderPath + 'js/util/inject-smartresize.js',
						Capitan.Vars.folderPath + 'js/function/assert-breakpoint.js',
						Capitan.Vars.folderPath + 'js/function/get-breakpoint.js',
						Capitan.Vars.folderPath + 'js/function/get-orientation.js',
						Capitan.Vars.folderPath + 'js/function/get-computed-style.js',
						Capitan.Vars.folderPath + 'js/util/set-breakpoints.js',
						Capitan.Vars.folderPath + 'js/handle/set-event-class.js',
						Capitan.Vars.folderPath + 'js/handle/resize-handler.js'
						// bundle@>
					],
					callback: [
						{ method: Capitan.Util.loadComponents }
					],
					unique: '<@unique@>'
				}
			], false);
		};

		// Component loader (DOM is ready)
		Capitan.Util.loadComponents = function () {
			$.import([
				{
					condition: $('[data-role="sg"]'),
					fetch: [
						Capitan.Vars.folderPath + 'js/libs/bra/bra_styleguide-widget/bra_styleguide-widget.js',
						Capitan.Vars.folderPath + 'js/libs/bra/bra_styleguide-widget/bra_styleguide-widget.css'
					],
					unique: '<@unique@>'
				},
				{
					condition: Capitan.Function.assertBreakpoint('lt', 'md'),
					fetch: [
						// <@bundle#h5bp-helper
						Capitan.Vars.folderPath + 'js/libs/vendor/h5bp/helper.js',
						Capitan.Vars.folderPath + 'js/util/h5bp-helper.js'
						// bundle@>
					],
					unique: '<@unique@>'
				},
				{
					// load always and always from server
					condition: true,
					fetch: [
						Capitan.Vars.folderPath + 'js/hotfix.js',
						Capitan.Vars.folderPath + 'css/hotfix.css'
					],
					unique: new Date().getTime()
				},
				{
					condition: $('.alert'),
					fetch: [
						Capitan.Vars.folderPath + 'component/alert/alert.css'
					],
					unique: '<@unique@>'
				},
				{
					condition: $('form'),
					fetch: [
						Capitan.Vars.folderPath + 'component/forms/forms.css'
					],
					unique: '<@unique@>'
				},
				{
					condition: $('.btn'),
					fetch: [
						Capitan.Vars.folderPath + 'component/buttons/buttons.css'
					],
					unique: '<@unique@>'
				}// <@newComponent@>
			], true);
		};

		// snippets placeholder
		// --- start|bra-pb: js ---
		// --- end|bra-pb: js ---

		// load before-render bundle before DOM ready
		Capitan.Util.fetchBeforeRender();

		/**
		 * document ready call
		 */
		$(function () {
			// ...
		});

	})(jQuery);
}, function () {
	// <@delete
	console.error('main.js: fetching of scripts and initialization failed');
	// delete@>
});
<commit_msg>load components when DOM is ready<commit_after>/**
 * Define Global Namespace
 */
var Capitan = function (out) {
	out = out || {};

	for (var i = 1; i < arguments.length; i++) {
		if (!arguments[i]) {
			continue;
		}

		for (var key in arguments[i]) {
			if (arguments[i].hasOwnProperty(key)) {
				out[key] = arguments[i][key];
			}
		}
	}

	return out;
}({}, (Capitan || {}), {
	Vars: {
		// path to assets folder
		folderPath: '%%public%%/',
		// standard breakpoints
		breakpoints: {},
		// mobile first (xs, sm, md, lg, xl)
		currentBreakpoint: 'xs',
		// portrait first (portrait, landscape)
		currentOrientation: 'portrait',
		isIE: window.navigator.userAgent.indexOf("MSIE ") > -1 || // IE <= 10
			!(window.ActiveXObject) && "ActiveXObject" in window || // IE 11
			/x64|x32/ig.test(window.navigator.userAgent) // IE 12
	},
	// CSS components script namespace
	Component: {},
	// functions must return something
	Function: {},
	// everything that has to do with event handling
	Handle: {},
	// Should be used for scripts that have nothing to do with components, e.g. placeholder polyfills, plugins, etc.
	Util: {}
});

// <@delete
// clear basket in develop mode
basket.clear();
// delete@>

// abortion timeout for asset fetching, default 5000ms
basket.timeout = 60000;

/**
 * Load main plugins via basket.js
 */
basket.require(
	{
		url: Capitan.Vars.folderPath + 'js/libs/vendor/jquery/jquery.min.js',
		unique: 0
	},
	{
		url: Capitan.Vars.folderPath + 'js/libs/vendor/modernizr/modernizr.custom.min.js',
		unique: 0
	},
	{
		url: Capitan.Vars.folderPath + 'js/libs/vendor/import/jquery.import.min.js',
		unique: 0
	}
).then(function () {
	(function ($) {
		// store commonly used jQuery objects to Vars object
		Capitan.Vars = $.extend(Capitan.Vars, {
			$html: $('html'),
			$body: $('body'),
			$window: $(window),
			$doc: $(document)
		});

		// Assets that are necessary globally and on every page, can and will be loaded here (DOM not ready)
		Capitan.Util.fetchBeforeRender = function () {
			return $.import([
				{
					condition: true,
					order: 0,
					fetch: [
						// <@bundle#before-render
						Capitan.Vars.folderPath + 'js/util/console-polyfill.js',
						Capitan.Vars.folderPath + 'js/util/inject-smartresize.js',
						Capitan.Vars.folderPath + 'js/function/assert-breakpoint.js',
						Capitan.Vars.folderPath + 'js/function/get-breakpoint.js',
						Capitan.Vars.folderPath + 'js/function/get-orientation.js',
						Capitan.Vars.folderPath + 'js/function/get-computed-style.js',
						Capitan.Vars.folderPath + 'js/util/set-breakpoints.js',
						Capitan.Vars.folderPath + 'js/handle/set-event-class.js',
						Capitan.Vars.folderPath + 'js/handle/resize-handler.js'
						// bundle@>
					],
					callback: [
						{
							method: function () {
								// load components when DOM is ready
								$(function(){
									Capitan.Util.loadComponents();
								})
							}
						}
					],
					unique: '<@unique@>'
				}
			], false);
		};

		// Component loader (DOM is ready)
		Capitan.Util.loadComponents = function () {
			$.import([
				{
					condition: $('[data-role="sg"]'),
					fetch: [
						Capitan.Vars.folderPath + 'js/libs/bra/bra_styleguide-widget/bra_styleguide-widget.js',
						Capitan.Vars.folderPath + 'js/libs/bra/bra_styleguide-widget/bra_styleguide-widget.css'
					],
					unique: '<@unique@>'
				},
				{
					condition: Capitan.Function.assertBreakpoint('lt', 'md'),
					fetch: [
						// <@bundle#h5bp-helper
						Capitan.Vars.folderPath + 'js/libs/vendor/h5bp/helper.js',
						Capitan.Vars.folderPath + 'js/util/h5bp-helper.js'
						// bundle@>
					],
					unique: '<@unique@>'
				},
				{
					// load always and always from server
					condition: true,
					fetch: [
						Capitan.Vars.folderPath + 'js/hotfix.js',
						Capitan.Vars.folderPath + 'css/hotfix.css'
					],
					unique: new Date().getTime()
				},
				{
					condition: $('.alert'),
					fetch: [
						Capitan.Vars.folderPath + 'component/alert/alert.css'
					],
					unique: '<@unique@>'
				},
				{
					condition: $('form'),
					fetch: [
						Capitan.Vars.folderPath + 'component/forms/forms.css'
					],
					unique: '<@unique@>'
				},
				{
					condition: $('.btn'),
					fetch: [
						Capitan.Vars.folderPath + 'component/buttons/buttons.css'
					],
					unique: '<@unique@>'
				}// <@newComponent@>
			], true);
		};

		// snippets placeholder
		// --- start|bra-pb: js ---
		// --- end|bra-pb: js ---

		// load before-render bundle before DOM ready
		Capitan.Util.fetchBeforeRender();

		/**
		 * document ready call
		 */
		$(function () {
			// ...
		});

	})(jQuery);
}, function () {
	// <@delete
	console.error('main.js: fetching of scripts and initialization failed');
	// delete@>
});
<|endoftext|>


<commit_before><commit_msg>no message<commit_after> /* 描画エリアのサイズ */
 var width = 1200;
 var height = 600;

 /* 表示領域の用意 */
 var svgContainer = d3.select("#mainBlock").append("svg")
.attr("width", width).attr("height", height);
 var mapContainer = svgContainer.append("g").attr("class", "mapBlock");
 var dataContainer = svgContainer.append("g").attr("class", "dataBlock");
 var legendContainer = svgContainer.append("g").attr("id", "legendBlock")
.attr(“transform”, “translate(“ + 800 + "," + 60 + “)") .attr("width", 300).attr("height", 60);<|endoftext|>


<commit_before>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import theme from './theme.css';

class Cell extends PureComponent {
  static propTypes = {
    align: PropTypes.oneOf(['left', 'center', 'right']),
    backgroundColor: PropTypes.oneOf(['white', 'neutral']),
    border: PropTypes.oneOf(['none', 'around', 'left', 'right']),
    bordered: PropTypes.bool,
    children: PropTypes.any,
    className: PropTypes.string,
    flex: PropTypes.oneOf(['min-width', '1', '2', '3', '4']),
    soft: PropTypes.bool,
    strong: PropTypes.bool,
  };

  static defaultProps = {
    align: 'left',
    backgroundColor: 'transparent',
    border: 'none',
    flex: '1',
    soft: false,
    strong: false,
  };

  render() {
    const { align, backgroundColor, border, children, className, flex, soft, strong, ...others } = this.props;

    const classNames = cx(
      theme['cell'],
      theme[`align-${align}`],
      theme[`flex-${flex}`],
      theme[`has-background-${backgroundColor}`],
      theme[`has-border-${border}`],
      {
        [theme['is-soft']]: soft,
        [theme['is-strong']]: strong,
      },
      className,
    );

    return (

        {children}

    );
  }
}

export default Cell;
<commit_msg>Added extra wrapper so we could prevent the cell overflow<commit_after>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import theme from './theme.css';

class Cell extends PureComponent {
  static propTypes = {
    align: PropTypes.oneOf(['left', 'center', 'right']),
    backgroundColor: PropTypes.oneOf(['white', 'neutral']),
    border: PropTypes.oneOf(['none', 'around', 'left', 'right']),
    bordered: PropTypes.bool,
    children: PropTypes.any,
    className: PropTypes.string,
    flex: PropTypes.oneOf(['min-width', '1', '2', '3', '4']),
    soft: PropTypes.bool,
    strong: PropTypes.bool,
  };

  static defaultProps = {
    align: 'left',
    backgroundColor: 'transparent',
    border: 'none',
    flex: '1',
    soft: false,
    strong: false,
  };

  render() {
    const { align, backgroundColor, border, children, className, flex, soft, strong, ...others } = this.props;

    const classNames = cx(
      theme['cell'],
      theme[`align-${align}`],
      theme[`flex-${flex}`],
      theme[`has-background-${backgroundColor}`],
      theme[`has-border-${border}`],
      {
        [theme['is-soft']]: soft,
        [theme['is-strong']]: strong,
      },
      className,
    );

    return (

{children}

    );
  }
}

export default Cell;
<|endoftext|>


<commit_before>[
{"id": "align_relative_to", "title": "Aligner par rapport à ..."},
{"id": "bkgnd_color", "title": "Changer la couleur d'arrière-plan / l'opacité"},
{"id": "circle_cx", "title": "Changer la position horizontale cx du cercle"},
{"id": "circle_cy", "title": "Changer la position verticale cy du cercle"},
{"id": "circle_r", "title": "Changer le rayon du cercle"},
{"id": "connector_no_arrow", "textContent": "No arrow"},
{"id": "copyrightLabel", "textContent": "Powered by"},
{"id": "cornerRadiusLabel", "title": "Changer le rayon des coins du rectangle"},
{"id": "curve_segments", "textContent": "Courbe"},
{"id": "ellipse_cx", "title": "Changer la position horizontale cx de l'ellipse"},
{"id": "ellipse_cy", "title": "Changer la position verticale cy de l'ellipse"},
{"id": "ellipse_rx", "title": "Changer le rayon horizontal x de l'ellipse"},
{"id": "ellipse_ry", "title": "Changer le rayon vertical y de l'ellipse"},
{"id": "fill_color", "title": "Changer la couleur de remplissage"},
{"id": "fitToContent", "textContent": "Ajuster au contenu"},
{"id": "fit_to_all", "textContent": "Ajuster au contenu de tous les calques"},
{"id": "fit_to_canvas", "textContent": "Ajuster au canevas"},
{"id": "fit_to_layer_content", "textContent": "Ajuster au contenu du calque"},
{"id": "fit_to_sel", "textContent": "Ajuster à la sélection"},
{"id": "font_family", "title": "Changer la famille de police"},
{"id": "icon_large", "textContent": "Grande"},
{"id": "icon_medium", "textContent": "Moyenne"},
{"id": "icon_small", "textContent": "Petite"},
{"id": "icon_xlarge", "textContent": "Super-Grande"},
{"id": "image_height", "title": "Changer la hauteur de l'image"},
{"id": "image_opt_embed", "textContent": "Incorporer les images en tant que données (fichiers locaux)"},
{"id": "image_opt_ref", "textContent": "Utiliser la référence des images "},
{"id": "image_url", "title": "Modifier l'URL"},
{"id": "image_width", "title": "Changer la largeur de l'image"},
{"id": "includedImages", "textContent": "Images incorporées"},
{"id": "largest_object", "textContent": "Plus gros objet"},
{"id": "layer_delete", "title": "Supprimer le calque"},
{"id": "layer_down", "title": "Descendre le calque"},
{"id": "layer_new", "title": "Nouveau calque"},
{"id": "layer_rename", "title": "Renommer le calque"},
{"id": "layer_up", "title": "Monter le calque"},
{"id": "layersLabel", "textContent": "Calques :"},
{"id": "line_x1", "title": "Changer la position horizontale x de début de la ligne"},
{"id": "line_x2", "title": "Changer la position horizontale x de fin de la ligne"},
{"id": "line_y1", "title": "Changer la position verticale y de début de la ligne"},
{"id": "line_y2", "title": "Changer la position verticale y de fin de la ligne"},
{"id": "linecap_butt", "title": "Linecap: Butt"},
{"id": "linecap_round", "title": "Linecap: Round"},
{"id": "linecap_square", "title": "Linecap: Square"},
{"id": "linejoin_bevel", "title": "Linejoin: Bevel"},
{"id": "linejoin_miter", "title": "Linejoin: Miter"},
{"id": "linejoin_round", "title": "Linejoin: Round"},
{"id": "main_icon", "title": "Main Menu"},
{"id": "mode_connect", "title": "Connect two objects"},
{"id": "page", "textContent": "Page"},
{"id": "palette", "title": "Cliquer pour changer la couleur de remplissage, Shift-Clic pour changer la couleur de contour"},
{"id": "path_node_x", "title": "Changer la positon horizontale x du nœud"},
{"id": "path_node_y", "title": "Changer la position verticale y du nœud"},
{"id": "rect_height_tool", "title": "Changer la hauteur du rectangle"},
{"id": "rect_width_tool", "title": "Changer la largeur du rectangle"},
{"id": "relativeToLabel", "textContent": "Relativement à:"},
{"id": "seg_type", "title": "Changer le type du Segment"},
{"id": "selLayerLabel", "textContent": "Déplacer éléments vers:"},
{"id": "selLayerNames", "title": "Déplacer les éléments sélectionnés vers un autre calque"},
{"id": "selectedPredefined", "textContent": "Sélectionner prédéfinis:"},
{"id": "selected_objects", "textContent": "Objets sélectionnés"},
{"id": "selected_x", "title": "Changer la position horizontale X"},
{"id": "selected_y", "title": "Changer la position verticale Y"},
{"id": "smallest_object", "textContent": "Plus petit objet"},
{"id": "straight_segments", "textContent": "Droit"},
{"id": "stroke_color", "title": "Changer la couleur du contour"},
{"id": "stroke_style", "title": "Changer le style du contour"},
{"id": "stroke_width", "title": "Changer la largeur du contour"},
{"id": "svginfo_bg_note", "textContent": "Note: La toile de fond n'est pas sauvegardée avec l'image."},
{"id": "svginfo_change_background", "textContent": "Toile de fond de l'Éditeur"},
{"id": "svginfo_dim", "textContent": "Dimensions du canevas"},
{"id": "svginfo_editor_prefs", "textContent": "Préférences de l'Éditeur"},
{"id": "svginfo_height", "textContent": "Hauteur:"},
{"id": "svginfo_icons", "textContent": "Taille des icônes"},
{"id": "svginfo_image_props", "textContent": "Propriétés de l'Image"},
{"id": "svginfo_lang", "textContent": "Langue"},
{"id": "svginfo_title", "textContent": "Titre"},
{"id": "svginfo_width", "textContent": "Largeur:"},
{"id": "text", "title": "Changer le contenu du texte"},
{"id": "toggle_stroke_tools", "title": "Show/hide more stroke tools"},
{"id": "tool_add_subpath", "title": "Add sub-path"},
{"id": "tool_alignbottom", "title": "Aligner le bas des objets"},
{"id": "tool_aligncenter", "title": "Centrer verticalement"},
{"id": "tool_alignleft", "title": "Aligner les côtés gauches"},
{"id": "tool_alignmiddle", "title": "Centrer horizontalement"},
{"id": "tool_alignright", "title": "Aligner les côtés droits"},
{"id": "tool_aligntop", "title": "Aligner le haut des objets"},
{"id": "tool_angle", "title": "Changer l'angle de rotation"},
{"id": "tool_blur", "title": "Change gaussian blur value"},
{"id": "tool_bold", "title": "Texte en gras"},
{"id": "tool_circle", "title": "Cercle"},
{"id": "tool_clear", "textContent": "Nouvelle image"},
{"id": "tool_clone", "title": "Cloner l'élément"},
{"id": "tool_clone_multi", "title": "Cloner les éléments"},
{"id": "tool_delete", "title": "Supprimer l'élément"},
{"id": "tool_delete_multi", "title": "Supprimer les éléments sélectionnés"},
{"id": "tool_docprops", "textContent": "Propriétés du document"},
{"id": "tool_docprops_cancel", "textContent": "Annuler"},
{"id": "tool_docprops_save", "textContent": "OK"},
{"id": "tool_ellipse", "title": "Ellipse"},
{"id": "tool_export", "textContent": "Export as PNG"},
{"id": "tool_eyedropper", "title": "Eye Dropper Tool"},
{"id": "tool_fhellipse", "title": "Ellipse main levée"},
{"id": "tool_fhpath", "title": "Crayon à main levée"},
{"id": "tool_fhrect", "title": "Rectangle main levée"},
{"id": "tool_font_size", "title": "Taille de la police"},
{"id": "tool_group", "title": "Grouper les éléments"},
{"id": "tool_image", "title": "Outil Image"},
{"id": "tool_import", "textContent": "Import SVG"},
{"id": "tool_italic", "title": "Texte en italique"},
{"id": "tool_line", "title": "Tracer des lignes"},
{"id": "tool_move_bottom", "title": "Déplacer vers le bas"},
{"id": "tool_move_top", "title": "Déplacer vers le haut"},
{"id": "tool_node_clone", "title": "Cloner le nœud"},
{"id": "tool_node_delete", "title": "Supprimer le nœud"},
{"id": "tool_node_link", "title": "Rendre les points de contrôle solidaires"},
{"id": "tool_opacity", "title": "Changer l'opacité de l'élément"},
{"id": "tool_open", "textContent": "Ouvrir une image"},
{"id": "tool_path", "title": "Outil Chemin"},
{"id": "tool_rect", "title": "Rectangle"},
{"id": "tool_redo", "title": "Refaire l'action"},
{"id": "tool_reorient", "title": "Réorienter le chemin"},
{"id": "tool_save", "textContent": "Enregistrer l'image"},
{"id": "tool_select", "title": "Outil de sélection"},
{"id": "tool_source", "title": "Modifier la source"},
{"id": "tool_source_cancel", "textContent": "Annuler"},
{"id": "tool_source_save", "textContent": "Appliquer Modifications"},
{"id": "tool_square", "title": "Carré"},
{"id": "tool_text", "title": "Outil Texte"},
{"id": "tool_topath", "title": "Convertir en chemin"},
{"id": "tool_undo", "title": "Annuler l'action"},
{"id": "tool_ungroup", "title": "Dégrouper les éléments"},
{"id": "tool_wireframe", "title": "Mode Fil de Fer"},
{"id": "tool_zoom", "title": "Zoom"},
{"id": "url_notice", "title": "NOTE: This image cannot be embedded. It will depend on this path to be displayed"},
{"id": "zoom_panel", "title": "Changer le niveau de zoom"},
{"id": "sidepanel_handle", "textContent": "C A L Q U E S", "title": "Tirer vers la gauche/droite pour redimensionner le panneau"},
{
 "js_strings": {
  "QerrorsRevertToSource": "Il y a des erreurs d'analyse syntaxique dans votre code-source SVG.\nRevenir au code-source SVG avant modifications ?",
  "QignoreSourceChanges": "Ignorer les modifications faites à la source SVG ?",
  "QmoveElemsToLayer": "Déplacer les éléments sélectionnés vers le calque '%s' ?",
  "QwantToClear": "Voulez-vous effacer le dessin ?\nL'historique de vos actions sera également effacé !",
  "cancel": "Annuler",
  "defsFailOnSave": "NOTE: Due to a bug in your browser, this image may appear wrong (missing gradients or elements). It will however appear correct once actually saved.",
  "dupeLayerName": "Il existe déjà un calque de ce nom !",
  "enterNewImgURL": "Entrer la nouvelle URL de l'image",
  "enterNewLayerName": "Veuillez entrer le nouveau nom du calque",
  "enterUniqueLayerName": "Veuillez entrer un nom (unique) pour le calque",
  "exportNoBlur": "Blurred elements will appear as un-blurred",
  "exportNoDashArray": "Strokes will appear filled",
  "exportNoImage": "Image elements will not appear",
  "exportNoText": "Text may not appear as expected",
  "exportNoforeignObject": "foreignObject elements will not appear",
  "featNotSupported": "Fonction non supportée",
  "invalidAttrValGiven": "Valeur fournie invalide",
  "key_backspace": "Suppr.",
  "key_del": "Retour Arr.",
  "key_down": "Bas",
  "key_up": "Haut",
  "layer": "Calque",
  "layerHasThatName": "Le calque porte déjà ce nom",
  "loadingImage": "Loading image, please wait...",
  "noContentToFitTo": "Il n'y a pas de contenu auquel ajuster",
  "noteTheseIssues": "Also note the following issues: ",
  "ok": "OK",
  "pathCtrlPtTooltip": "Glisser-déposer le point de contrôle pour ajuster les propriétés de la courbe",
  "pathNodeTooltip": "Glisser-déposer le nœud pour le déplacer. Double-cliquer le nœud pour changer de type de segment",
  "saveFromBrowser": "Select \"Save As...\" in your browser to save this image as a %s file."
 }
}
]<commit_msg>Update French translation file.<commit_after>[
{"id": "align_relative_to", "title": "Aligner par rapport à ..."},
{"id": "bkgnd_color", "title": "Changer la couleur d'arrière-plan / l'opacité"},
{"id": "circle_cx", "title": "Changer la position horizontale cx du cercle"},
{"id": "circle_cy", "title": "Changer la position verticale cy du cercle"},
{"id": "circle_r", "title": "Changer le rayon du cercle"},
{"id": "connector_no_arrow", "textContent": "Sans flèches"},
{"id": "copyrightLabel", "textContent": "Powered by"},
{"id": "cornerRadiusLabel", "title": "Changer le rayon des coins du rectangle"},
{"id": "curve_segments", "textContent": "Courbe"},
{"id": "ellipse_cx", "title": "Changer la position horizontale cx de l'ellipse"},
{"id": "ellipse_cy", "title": "Changer la position verticale cy de l'ellipse"},
{"id": "ellipse_rx", "title": "Changer le rayon horizontal x de l'ellipse"},
{"id": "ellipse_ry", "title": "Changer le rayon vertical y de l'ellipse"},
{"id": "fill_color", "title": "Changer la couleur de remplissage"},
{"id": "fitToContent", "textContent": "Ajuster au contenu"},
{"id": "fit_to_all", "textContent": "Ajuster au contenu de tous les calques"},
{"id": "fit_to_canvas", "textContent": "Ajuster au canevas"},
{"id": "fit_to_layer_content", "textContent": "Ajuster au contenu du calque"},
{"id": "fit_to_sel", "textContent": "Ajuster à la sélection"},
{"id": "font_family", "title": "Changer la famille de police"},
{"id": "icon_large", "textContent": "Grande"},
{"id": "icon_medium", "textContent": "Moyenne"},
{"id": "icon_small", "textContent": "Petite"},
{"id": "icon_xlarge", "textContent": "Super-Grande"},
{"id": "idLabel", "title": "Identifier l'élément"},
{"id": "image_height", "title": "Changer la hauteur de l'image"},
{"id": "image_opt_embed", "textContent": "Incorporer les images en tant que données (fichiers locaux)"},
{"id": "image_opt_ref", "textContent": "Utiliser la référence des images "},
{"id": "image_url", "title": "Modifier l'URL"},
{"id": "image_width", "title": "Changer la largeur de l'image"},
{"id": "includedImages", "textContent": "Images incorporées"},
{"id": "largest_object", "textContent": "Plus gros objet"},
{"id": "layer_delete", "title": "Supprimer le calque"},
{"id": "layer_down", "title": "Descendre le calque"},
{"id": "layer_new", "title": "Nouveau calque"},
{"id": "layer_rename", "title": "Renommer le calque"},
{"id": "layer_up", "title": "Monter le calque"},
{"id": "layersLabel", "textContent": "Calques :"},
{"id": "line_x1", "title": "Changer la position horizontale x de début de la ligne"},
{"id": "line_x2", "title": "Changer la position horizontale x de fin de la ligne"},
{"id": "line_y1", "title": "Changer la position verticale y de début de la ligne"},
{"id": "line_y2", "title": "Changer la position verticale y de fin de la ligne"},
{"id": "linecap_butt", "title": "Terminaison : Sur le nœud"},
{"id": "linecap_round", "title": "Terminaison : Arrondie"},
{"id": "linecap_square", "title": "Terminaison : Carrée"},
{"id": "linejoin_bevel", "title": "Raccord : Biseauté"},
{"id": "linejoin_miter", "title": "Raccord : Droit"},
{"id": "linejoin_round", "title": "Raccord : Arrondi"},
{"id": "main_icon", "title": "Menu principal"},
{"id": "mode_connect", "title": "Connecter deux objets"},
{"id": "page", "textContent": "Page"},
{"id": "palette", "title": "Cliquer pour changer la couleur de remplissage, Shift-Clic pour changer la couleur de contour"},
{"id": "path_node_x", "title": "Changer la positon horizontale x du nœud"},
{"id": "path_node_y", "title": "Changer la position verticale y du nœud"},
{"id": "rect_height_tool", "title": "Changer la hauteur du rectangle"},
{"id": "rect_width_tool", "title": "Changer la largeur du rectangle"},
{"id": "relativeToLabel", "textContent": "Relativement à:"},
{"id": "seg_type", "title": "Changer le type du Segment"},
{"id": "selLayerLabel", "textContent": "Déplacer éléments vers:"},
{"id": "selLayerNames", "title": "Déplacer les éléments sélectionnés vers un autre calque"},
{"id": "selectedPredefined", "textContent": "Sélectionner prédéfinis:"},
{"id": "selected_objects", "textContent": "Objets sélectionnés"},
{"id": "selected_x", "title": "Changer la position horizontale X"},
{"id": "selected_y", "title": "Changer la position verticale Y"},
{"id": "smallest_object", "textContent": "Plus petit objet"},
{"id": "straight_segments", "textContent": "Droit"},
{"id": "stroke_color", "title": "Changer la couleur du contour"},
{"id": "stroke_style", "title": "Changer le style du contour"},
{"id": "stroke_width", "title": "Changer la largeur du contour de 1, Shift-Click pour changer la largeur de 0.1"},
{"id": "svginfo_bg_note", "textContent": "Note: La toile de fond n'est pas sauvegardée avec l'image."},
{"id": "svginfo_change_background", "textContent": "Toile de fond de l'Éditeur"},
{"id": "svginfo_dim", "textContent": "Dimensions du canevas"},
{"id": "svginfo_editor_prefs", "textContent": "Préférences de l'Éditeur"},
{"id": "svginfo_height", "textContent": "Hauteur:"},
{"id": "svginfo_icons", "textContent": "Taille des icônes"},
{"id": "svginfo_image_props", "textContent": "Propriétés de l'Image"},
{"id": "svginfo_lang", "textContent": "Langue"},
{"id": "svginfo_title", "textContent": "Titre"},
{"id": "svginfo_width", "textContent": "Largeur:"},
{"id": "text", "title": "Changer le contenu du texte"},
{"id": "toggle_stroke_tools", "title": "Montrer/Cacher plus d'outils de Contour"},
{"id": "tool_add_subpath", "title": "Ajouter un sous-chemin"},
{"id": "tool_alignbottom", "title": "Aligner le bas des objets"},
{"id": "tool_aligncenter", "title": "Centrer verticalement"},
{"id": "tool_alignleft", "title": "Aligner les côtés gauches"},
{"id": "tool_alignmiddle", "title": "Centrer horizontalement"},
{"id": "tool_alignright", "title": "Aligner les côtés droits"},
{"id": "tool_aligntop", "title": "Aligner le haut des objets"},
{"id": "tool_angle", "title": "Changer l'angle de rotation"},
{"id": "tool_blur", "title": "Changer la valeur du flou gaussien"},
{"id": "tool_bold", "title": "Texte en gras"},
{"id": "tool_circle", "title": "Cercle"},
{"id": "tool_clear", "textContent": "Nouvelle image"},
{"id": "tool_clone", "title": "Cloner l'élément"},
{"id": "tool_clone_multi", "title": "Cloner les éléments"},
{"id": "tool_delete", "title": "Supprimer l'élément"},
{"id": "tool_delete_multi", "title": "Supprimer les éléments sélectionnés"},
{"id": "tool_docprops", "textContent": "Propriétés du document"},
{"id": "tool_docprops_cancel", "textContent": "Annuler"},
{"id": "tool_docprops_save", "textContent": "OK"},
{"id": "tool_ellipse", "title": "Ellipse"},
{"id": "tool_export", "textContent": "Exporter au format PNG"},
{"id": "tool_eyedropper", "title": "Outil Pipette"},
{"id": "tool_fhellipse", "title": "Ellipse main levée"},
{"id": "tool_fhpath", "title": "Crayon à main levée"},
{"id": "tool_fhrect", "title": "Rectangle main levée"},
{"id": "tool_font_size", "title": "Changer la taille de la police"},
{"id": "tool_group", "title": "Grouper les éléments"},
{"id": "tool_image", "title": "Outil Image"},
{"id": "tool_import", "textContent": "Importer un objet SVG"},
{"id": "tool_italic", "title": "Texte en italique"},
{"id": "tool_line", "title": "Tracer des lignes"},
{"id": "tool_move_bottom", "title": "Déplacer vers le bas"},
{"id": "tool_move_top", "title": "Déplacer vers le haut"},
{"id": "tool_node_clone", "title": "Cloner le nœud"},
{"id": "tool_node_delete", "title": "Supprimer le nœud"},
{"id": "tool_node_link", "title": "Rendre les points de contrôle solidaires"},
{"id": "tool_opacity", "title": "Changer l'opacité de l'élément sélectionné"},
{"id": "tool_open", "textContent": "Ouvrir une image"},
{"id": "tool_openclose_path", "title": "Ouvrir/Fermer sous-chemin"},
{"id": "tool_path", "title": "Outil Chemin"},
{"id": "tool_position", "title": "Aligner l'élément relativement à la Page"},
{"id": "tool_rect", "title": "Rectangle"},
{"id": "tool_redo", "title": "Refaire l'action"},
{"id": "tool_reorient", "title": "Réorienter le chemin"},
{"id": "tool_save", "textContent": "Enregistrer l'image"},
{"id": "tool_select", "title": "Outil de sélection"},
{"id": "tool_source", "title": "Modifier la source"},
{"id": "tool_source_cancel", "textContent": "Annuler"},
{"id": "tool_source_save", "textContent": "Appliquer Modifications"},
{"id": "tool_square", "title": "Carré"},
{"id": "tool_text", "title": "Outil Texte"},
{"id": "tool_topath", "title": "Convertir en chemin"},
{"id": "tool_undo", "title": "Annuler l'action"},
{"id": "tool_ungroup", "title": "Dégrouper les éléments"},
{"id": "tool_wireframe", "title": "Mode Fil de Fer"},
{"id": "tool_zoom", "title": "Zoom"},
{"id": "url_notice", "title": "NOTE: Cette image ne peut être incorporée en tant que données. Le contenu affiché sera celui de l'image située à cette adresse"},
{"id": "zoom_panel", "title": "Changer le niveau de zoom"},
{"id": "sidepanel_handle", "textContent": "C A L Q U E S", "title": "Tirer vers la gauche/droite pour redimensionner le panneau"},
{
 "js_strings": {
  "QerrorsRevertToSource": "Il y a des erreurs d'analyse syntaxique dans votre code-source SVG.\nRevenir au code-source SVG avant modifications ?",
  "QignoreSourceChanges": "Ignorer les modifications faites à la source SVG ?",
  "QmoveElemsToLayer": "Déplacer les éléments sélectionnés vers le calque '%s' ?",
  "QwantToClear": "Voulez-vous effacer le dessin ?\nL'historique de vos actions sera également effacé !",
  "cancel": "Annuler",
  "defsFailOnSave": "NOTE : À cause d'un bug de votre navigateur, cette image peut être affichée de façon incorrecte (dégradés ou éléments manquants). Cependant, une fois enregistrée, elle sera correcte.",
  "dupeLayerName": "Il existe déjà un calque de ce nom !",
  "enterNewImgURL": "Entrer la nouvelle URL de l'image",
  "enterNewLayerName": "Veuillez entrer le nouveau nom du calque",
  "enterUniqueLayerName": "Veuillez entrer un nom (unique) pour le calque",
  "exportNoBlur": "Les éléments ayant du flou gaussien seront affichés sans flou",
  "exportNoDashArray": "Les contours seront affichés remplis",
  "exportNoImage": "Les éléments Image ne seront pas affichés",
  "exportNoText": "Le texte peut être affiché de façon incorrecte",
  "exportNoforeignObject": "Les éléments foreignObject se seront pas affichés",
  "featNotSupported": "Fonction non supportée",
  "invalidAttrValGiven": "Valeur fournie invalide",
  "key_backspace": "Suppr.",
  "key_del": "Retour Arr.",
  "key_down": "Bas",
  "key_up": "Haut",
  "layer": "Calque",
  "layerHasThatName": "Le calque porte déjà ce nom",
  "loadingImage": "Chargement de l'image, veuillez patienter...",
  "noContentToFitTo": "Il n'y a pas de contenu auquel ajuster",
  "noteTheseIssues": "Notez également les problèmes suivants : ",
  "ok": "OK",
  "pathCtrlPtTooltip": "Glisser-déposer le point de contrôle pour ajuster les propriétés de la courbe",
  "pathNodeTooltip": "Glisser-déposer le nœud pour le déplacer. Double-cliquer le nœud pour changer de type de segment",
  "saveFromBrowser": "Selectionner \"Enregistrer sous...\" dans votre navigateur pour sauvegarder l'image en tant que fichier %s."
 }
}
]<|endoftext|>


<commit_before>(function (angular) {

  'use strict';

  var actividadPerfil = angular.module('actividadPerfil');

  // Service para comentarios. Cargar y guardar datos principales de la embarcacion
  actividadPerfil.service('pimcActividadService', ['$http', '$q', 'pimcService', 'pimcBarraEstadoService', function($http, $q, pimcService, pimcBarraEstadoService, ) {
    var actividadServiceCtrl = this;

    // Funcion para cargar datos principales de la embarcacion
    actividadServiceCtrl.cargarDatosPrincipales = function(actividadID) {
      var consultaActividadDatosPrincipales = pimcService.crearURLOperacion('Consulta', 'Actividades');
      var config = {
        params: {
          actividadID: actividadID
        }
      }
      // Cargamos los datos principales
      return $http.get(consultaActividadDatosPrincipales, config).then( function(data) {
        //Obtener los datos JSON
        var actividadDatosPrincipales = data.data;
        var datosPrincipales = {
          contenido: {},
          estado: pimcService.datosEstados.LIMPIO
        };
        // Revisamos si se recibio algo
        if (Object.keys(actividadDatosPrincipales).length != 0) {
          try {
            // Contenido, datos de embarcacion en la base de datos
            datosPrincipales.contenido = actividadDatosPrincipales[0];
          }
          catch(err) {
            console.log("Problema cargando los valores de datos principales de la actividad " + err.message);
          }
        }

      });
    }; //Fin de cargar datos principales

    actividadServiceCtrl.guardarDatosPrincipales = function(datosPrincipales) {

      // Si los datos fueron cambiados, entonces actualizamos todas las bases de datos
      if (datosPrincipales.estado != pimcService.datosEstados.LIMPIO) {
        pimcBarraEstadoService.registrarAccion("Actualizando BD Actividad");
        var modificarActividadesURL = pimcService.crearURLOperacion('Modificar', 'Actividades');
        var parametros = datosPrincipales.contenido;
        parametros.idUnico = 'actividadID';
        var config = {
          params: parametros
        }
        return $http.get(modificarActividadesURL, config).then(
          // funcion conexion exitosa
          function (data) {
            if (data.data[0] != 0) {
              return true;

            } else {
              pimcService.debug("ERROR no se modificó la base de datos guardando datos principales de actividades", data);
              return false;
            }
          }, function (dataError) {
            // funcion error de conexion
            pimcService.debug("ERROR guardando actividades", dataError);
            return $q.resolve(false);
          }
        );
      }
    }; // Fin de guardar datos principales

    actividadServiceCtrl.crearActividad = function(actividadNueva) {
      pimcBarraEstadoService.registrarAccion("Actualizando BD Actividad");
        var crearActividadesURL = pimcService.crearURLOperacion('Insertar', 'Actividades');
        var parametros = actividadNueva;
        var config = {
          params: parametros
        }
        return $http.get(crearActividadesURL, config).then(
          // funcion conexion exitosa
          function (data) {
            if (data.data[0] != 0) {
              return true;
            } else {
              pimcService.debug("ERROR no se modificó la base de datos guardando datos principales de actividades", data);
              return false;
            }
          }, function (dataError) {
            // funcion error de conexion
            pimcService.debug("ERROR guardando actividades", dataError);
            return $q.resolve(false);
          }
        );
      }
    }

})(window.angular);
<commit_msg>Agregando punto y coma<commit_after>(function (angular) {

  'use strict';

  var actividadPerfil = angular.module('actividadPerfil');

  // Service para comentarios. Cargar y guardar datos principales de la embarcacion
  actividadPerfil.service('pimcActividadService', ['$http', '$q', 'pimcService', 'pimcBarraEstadoService', function($http, $q, pimcService, pimcBarraEstadoService, ) {
    var actividadServiceCtrl = this;

    // Funcion para cargar datos principales de la embarcacion
    actividadServiceCtrl.cargarDatosPrincipales = function(actividadID) {
      var consultaActividadDatosPrincipales = pimcService.crearURLOperacion('Consulta', 'Actividades');
      var config = {
        params: {
          actividadID: actividadID
        }
      }
      // Cargamos los datos principales
      return $http.get(consultaActividadDatosPrincipales, config).then( function(data) {
        //Obtener los datos JSON
        var actividadDatosPrincipales = data.data;
        var datosPrincipales = {
          contenido: {},
          estado: pimcService.datosEstados.LIMPIO
        };
        // Revisamos si se recibio algo
        if (Object.keys(actividadDatosPrincipales).length != 0) {
          try {
            // Contenido, datos de embarcacion en la base de datos
            datosPrincipales.contenido = actividadDatosPrincipales[0];
          }
          catch(err) {
            console.log("Problema cargando los valores de datos principales de la actividad " + err.message);
          }
        }

      });
    }; //Fin de cargar datos principales

    actividadServiceCtrl.guardarDatosPrincipales = function(datosPrincipales) {

      // Si los datos fueron cambiados, entonces actualizamos todas las bases de datos
      if (datosPrincipales.estado != pimcService.datosEstados.LIMPIO) {
        pimcBarraEstadoService.registrarAccion("Actualizando BD Actividad");
        var modificarActividadesURL = pimcService.crearURLOperacion('Modificar', 'Actividades');
        var parametros = datosPrincipales.contenido;
        parametros.idUnico = 'actividadID';
        var config = {
          params: parametros
        }
        return $http.get(modificarActividadesURL, config).then(
          // funcion conexion exitosa
          function (data) {
            if (data.data[0] != 0) {
              return true;

            } else {
              pimcService.debug("ERROR no se modificó la base de datos guardando datos principales de actividades", data);
              return false;
            }
          }, function (dataError) {
            // funcion error de conexion
            pimcService.debug("ERROR guardando actividades", dataError);
            return $q.resolve(false);
          }
        );
      }
    }; // Fin de guardar datos principales

    actividadServiceCtrl.crearActividad = function(actividadNueva) {
      pimcBarraEstadoService.registrarAccion("Actualizando BD Actividad");
        var crearActividadesURL = pimcService.crearURLOperacion('Insertar', 'Actividades');
        var parametros = actividadNueva;
        var config = {
          params: parametros
        }
        return $http.get(crearActividadesURL, config).then(
          // funcion conexion exitosa
          function (data) {
            if (data.data[0] != 0) {
              return true;
            } else {
              pimcService.debug("ERROR no se modificó la base de datos guardando datos principales de actividades", data);
              return false;
            }
          }, function (dataError) {
            // funcion error de conexion
            pimcService.debug("ERROR guardando actividades", dataError);
            return $q.resolve(false);
          }
        );
      }
    }
  ]);

})(window.angular);
<|endoftext|>


<commit_before>'use strict';

var Sparkline = Class.extend({
  init: function(divId, json, trend, freq) {
    this.container = divId;
    this.timeParse = freq === 'daily' ? d3.timeParse('%Y-%m-%d') : freq === 'monthly' ? d3.timeParse('%Y-%m') : d3.timeParse('%Y');
    this.isMobile = window.innerWidth <= 768;
    this.trend = trend;
    this.data = json;

    // Chart dimensions
    this.margin = {top: 5, right: 5, bottom: 5, left: 5};
    this.width = this._width() - this.margin.left - this.margin.right;
    this.height = this._height() - this.margin.top - this.margin.bottom;

    // Scales & Ranges
    this.xScale = d3.scaleTime();
    this.yScale = d3.scaleLinear();
    this.color = d3.scaleOrdinal();

    // Create main elements
    this.svg = d3.select(this.container)
      .append('svg')
      .attr('width', this.width + this.margin.left + this.margin.right)
      .attr('height', this.height + this.margin.top + this.margin.bottom)
      .append('g')
      .attr('class', 'chart-container')
      .attr('transform', 'translate(' + this.margin.left + ',' + this.margin.top + ')');

    d3.select(window).on('resize.' + this.container, this._resize.bind(this));
  },
  render: function() {
    this._type();
    this.updateRender();
    this._renderLines();
  },
  updateRender: function(callback) {
    this.xScale
      .rangeRound([0, this.width])
      .domain(d3.extent(this.data, function(d) { return d.date; }.bind(this)));

    this.yScale
      .rangeRound([this.height, 0])
      .domain(d3.extent(this.data, function(d) { return d.value; }.bind(this)));
  },
  _renderLines: function() {
    this.line = d3.line()
      .x(function(d) { return this.xScale(d.date); }.bind(this))
      .y(function(d) { return this.yScale(d.value); }.bind(this));

    this.isPositive = this.data[0].value - this.data.slice(-1)[0].value > 0 ? true : false;

    this.svg.append('path')
      .datum(this.data)
      .attr('stroke', this._getColor())
      .attr('d', this.line);

    this.svg.append('circle')
      .attr('cx', function(d) { return this.xScale(this.data[0].date); }.bind(this))
      .attr('cy', function(d) { return this.yScale(this.data[0].value); }.bind(this))
      .attr('r', 2.5)
      .attr('fill', this._getColor());
  },
  _getColor: function() {
    if (this.isPositive && this.trend === 'up' || !this.isPositive && this.trend === 'down') {
      return '#AAC44B';
    } else {
      return '#981F2E';
    }
  },
  _type: function() {
    this.data.forEach(function(d) {
      d.date = this.timeParse(d.date)
    }.bind(this));
  },
  _width: function() {
    return parseInt(d3.select(this.container).style('width'));
  },
  _height: function() {
    return this._width() * 0.2;
  },
  _resize: function() {
    this.width = this._width() - this.margin.left - this.margin.right;
    this.height = this._height() - this.margin.top - this.margin.bottom;

    this.updateRender();

    d3.select(this.container + ' svg')
      .attr('width', this.width + this.margin.left + this.margin.right)
      .attr('height', this.height + this.margin.top + this.margin.bottom)

    this.svg.select('.chart-container')
      .attr('transform', 'translate(' + this.margin.left + ',' + this.margin.top + ')');

    this.svg.select('path')
      .attr('d', this.line);

    this.svg.select('circle')
      .attr('cx', function(d) { return this.xScale(this.data[0].date); }.bind(this))
      .attr('cy', function(d) { return this.yScale(this.data[0].value); }.bind(this))
  }
});
<commit_msg>Deal with card width when the element is null<commit_after>'use strict';

var Sparkline = Class.extend({
  init: function(divId, json, trend, freq) {
    this.container = divId;
    this.timeParse = freq === 'daily' ? d3.timeParse('%Y-%m-%d') : freq === 'monthly' ? d3.timeParse('%Y-%m') : d3.timeParse('%Y');
    this.isMobile = window.innerWidth <= 768;
    this.trend = trend;
    this.data = json;

    // Chart dimensions
    this.margin = {top: 5, right: 5, bottom: 5, left: 5};
    this.width = this._width() - this.margin.left - this.margin.right;
    this.height = this._height() - this.margin.top - this.margin.bottom;

    // Scales & Ranges
    this.xScale = d3.scaleTime();
    this.yScale = d3.scaleLinear();
    this.color = d3.scaleOrdinal();

    // Create main elements
    this.svg = d3.select(this.container)
      .append('svg')
      .attr('width', this.width + this.margin.left + this.margin.right)
      .attr('height', this.height + this.margin.top + this.margin.bottom)
      .append('g')
      .attr('class', 'chart-container')
      .attr('transform', 'translate(' + this.margin.left + ',' + this.margin.top + ')');

    d3.select(window).on('resize.' + this.container, this._resize.bind(this));
  },
  render: function() {
    this._type();
    this.updateRender();
    this._renderLines();
  },
  updateRender: function(callback) {
    this.xScale
      .rangeRound([0, this.width])
      .domain(d3.extent(this.data, function(d) { return d.date; }.bind(this)));

    this.yScale
      .rangeRound([this.height, 0])
      .domain(d3.extent(this.data, function(d) { return d.value; }.bind(this)));
  },
  _renderLines: function() {
    this.line = d3.line()
      .x(function(d) { return this.xScale(d.date); }.bind(this))
      .y(function(d) { return this.yScale(d.value); }.bind(this));

    this.isPositive = this.data[0].value - this.data.slice(-1)[0].value > 0 ? true : false;

    this.svg.append('path')
      .datum(this.data)
      .attr('stroke', this._getColor())
      .attr('d', this.line);

    this.svg.append('circle')
      .attr('cx', function(d) { return this.xScale(this.data[0].date); }.bind(this))
      .attr('cy', function(d) { return this.yScale(this.data[0].value); }.bind(this))
      .attr('r', 2.5)
      .attr('fill', this._getColor());
  },
  _getColor: function() {
    if (this.isPositive && this.trend === 'up' || !this.isPositive && this.trend === 'down') {
      return '#AAC44B';
    } else {
      return '#981F2E';
    }
  },
  _type: function() {
    this.data.forEach(function(d) {
      d.date = this.timeParse(d.date)
    }.bind(this));
  },
  _width: function() {
    var cont = d3.select(this.container);
    try {
      return parseInt(cont.style('width'));
    } catch(e) {
      return 0;
    }
  },
  _height: function() {
    return this._width() * 0.2;
  },
  _resize: function() {
    this.width = this._width() - this.margin.left - this.margin.right;
    this.height = this._height() - this.margin.top - this.margin.bottom;

    this.updateRender();

    d3.select(this.container + ' svg')
      .attr('width', this.width + this.margin.left + this.margin.right)
      .attr('height', this.height + this.margin.top + this.margin.bottom)

    this.svg.select('.chart-container')
      .attr('transform', 'translate(' + this.margin.left + ',' + this.margin.top + ')');

    this.svg.select('path')
      .attr('d', this.line);

    this.svg.select('circle')
      .attr('cx', function(d) { return this.xScale(this.data[0].date); }.bind(this))
      .attr('cy', function(d) { return this.yScale(this.data[0].value); }.bind(this))
  }
});
<|endoftext|>


<commit_before>/*global angular*/
angular.module('app', [
        'ui.bootstrap',
        'app.includes',
        'blog',
        'enterprise',
        'home',
        'session',
        'translation',
        'modalExample',
        'diagrams',
        'hljs'
    ])
    .constant('USE_SOCKET', false)
    .config(['$routeProvider', '$locationProvider', '$translateProvider',
        function ($routeProvider, $locationProvider, $translateProvider) {
            $locationProvider.html5Mode(true);
            $routeProvider.otherwise({redirectTo: '/'});

            $translateProvider.useStaticFilesLoader({
                prefix: '/locale/locale-',
                suffix: '.json'
            });
            $translateProvider.preferredLanguage('en');
            $translateProvider.fallbackLanguage('en');
        }])
    .run(['$rootScope', 'lxSession', '$log', '$translate', '$window', 'lxModal', 'lxAlert',
        function ($rootScope, lxSession, $log, $translate, $window, lxModal, lxAlert) {

            // bind lxAlert service to $rootScope
            $rootScope.lxAlert = lxAlert;
            $rootScope.lxModal = lxModal;

            $rootScope.$on('$routeChangeStart', function () {
                lxSession.setActivity(function (err) {
                    if (err) {
                        lxModal.msgBox('sessionExpired', true, '', 'Session is expired! Please log in.', 'Warning', function () {
                            window.location.assign('/');
                        });
                    }
                });

            });

            // get users preferred language from session
            lxSession.getData('language', function (error, result) {
                if (error) {
                    $log.error(error);
                }

                // use language
                if (result && result.language) {
                    $translate.uses(result.language);
                } else {
                    // detect language of browser
                    var browserLanguage = $window.navigator.language || $window.navigator.userLanguage;
                    $translate.uses(browserLanguage.substring(0, 2));
                }
            });

            $rootScope.modal = lxModal.modal;

            $rootScope.changeLanguage = function (langKey) {
                // tell angular-translate to use the new language
                $translate.uses(langKey);

                // save selected language in session
                lxSession.setData('language', langKey, function (err) {
                    if (err) {
                        $log.error(err);
                    }
                });
            };
        }]);<commit_msg>socket true<commit_after>/*global angular*/
angular.module('app', [
        'ui.bootstrap',
        'app.includes',
        'blog',
        'enterprise',
        'home',
        'session',
        'translation',
        'modalExample',
        'diagrams',
        'hljs'
    ])
    .constant('USE_SOCKET', true)
    .config(['$routeProvider', '$locationProvider', '$translateProvider',
        function ($routeProvider, $locationProvider, $translateProvider) {
            $locationProvider.html5Mode(true);
            $routeProvider.otherwise({redirectTo: '/'});

            $translateProvider.useStaticFilesLoader({
                prefix: '/locale/locale-',
                suffix: '.json'
            });
            $translateProvider.preferredLanguage('en');
            $translateProvider.fallbackLanguage('en');
        }])
    .run(['$rootScope', 'lxSession', '$log', '$translate', '$window', 'lxModal', 'lxAlert',
        function ($rootScope, lxSession, $log, $translate, $window, lxModal, lxAlert) {

            // bind lxAlert service to $rootScope
            $rootScope.lxAlert = lxAlert;
            $rootScope.lxModal = lxModal;

            $rootScope.$on('$routeChangeStart', function () {
                lxSession.setActivity(function (err) {
                    if (err) {
                        lxModal.msgBox('sessionExpired', true, '', 'Session is expired! Please log in.', 'Warning', function () {
                            window.location.assign('/');
                        });
                    }
                });

            });

            // get users preferred language from session
            lxSession.getData('language', function (error, result) {
                if (error) {
                    $log.error(error);
                }

                // use language
                if (result && result.language) {
                    $translate.uses(result.language);
                } else {
                    // detect language of browser
                    var browserLanguage = $window.navigator.language || $window.navigator.userLanguage;
                    $translate.uses(browserLanguage.substring(0, 2));
                }
            });

            $rootScope.modal = lxModal.modal;

            $rootScope.changeLanguage = function (langKey) {
                // tell angular-translate to use the new language
                $translate.uses(langKey);

                // save selected language in session
                lxSession.setData('language', langKey, function (err) {
                    if (err) {
                        $log.error(err);
                    }
                });
            };
        }]);<|endoftext|>