<commit_before>/**
 * Created by ar on 3/8/17.
 */

var idRepo = require("./../blogic/IdReposition");;
var auxConcept=require("../model/auxConcept");
var auxDescription=require("../model/auxDescription");
var auxRelationship=require("../model/auxRelationship");

var db=require("../config/MysqlInit");

var conceptIdBulkCreation = function (namespace, partitionId, idsTotal, request, callback) {

    console.log("step conceptIdBulkCreation");

    testQuantity(auxConcept, namespace, partitionId, idsTotal, function (err) {

        var t2 = new Date().getTime();
        //console.log("Partial call to testing space ids took: " + (t2 - t1) + " milisecs");
        if (err) {
            callback(err,null);
        }else{

            db.getDB(function (err,connection)
            {
                var t3 = new Date().getTime();
                console.log("Partial call to get db connection took: " + (t3 - t2) + " milisecs");
                var now = new Date();
                var jsonDate = now.toJSON();
                var modified_at = new Date(jsonDate);

                console.log("modified_at:" + connection.escape(modified_at));
                var sql="UPDATE auxConcept SET modified_at=" + connection.escape(modified_at) + "  where modified_at is null limit " + idsTotal;
                connection.query(sql, function (error, result) {
                    //connection.release();
                    var t4 = new Date().getTime();
                    console.log("Partial call to update data took: " + (t4 - t3) + " milisecs");
                    if (error) {
                        callback (error,null);
                    }
                    else {
                        sql="SELECT sctid, systemId from auxConcept where modified_at=" + connection.escape(modified_at) + " limit " + idsTotal;
                        connection.query(sql, function (error, result) {
                            var t5 = new Date().getTime();
                            console.log("Partial call to select data took: " + (t5 - t4) + " milisecs");
                            if (error) {
                                callback(error, null);
                            }
                            else {

                                if (request) {

                                    callback(null, result);

                                    sql = "update sctId s inner join auxConcept c on c.sctid=s.sctId set s.author= " + connection.escape(request.author) +
                                        ",s.software= " + connection.escape(request.software) +
                                        ",s.comment= " + connection.escape(request.comment) +
                                        ",s.jobId= " + connection.escape(request.jobId) +
                                        " where c.modified_at=" + connection.escape(modified_at)  ;

                                    connection.query(sql, function (error, result) {

                                        sql = "Delete from auxConcept where modified_at=" + connection.escape(modified_at) + " limit " + idsTotal;
                                        connection.query(sql, function (error, result) {
                                            connection.release();
                                        });
                                    });

                                }else{
                                    sql = "Delete from auxConcept where modified_at=" + connection.escape(modified_at) + " limit " + idsTotal;
                                    connection.query(sql, function (error, result) {
                                        connection.release();
                                        idRepo.idBulkCreation(auxDescription, namespace, partitionId, idsTotal, function (err) {
                                            console.log("End of concept id generation");
                                            if (err) {
                                                var str = "[ERROR] " + (new Date()).getTime() + ": namespace=" + namespace + ", partition=" + partitionId + ". " + err;
                                                console.log(str);
                                            }
                                        });
                                    });
                                }
                            }
                        });
                    }
                });
            });

        }

    });
};

var descriptionIdBulkCreation = function (namespace, partitionId, idsTotal, request, callback) {

    console.log("step descriptionIdBulkCreation");

    testQuantity(auxDescription, namespace, partitionId, idsTotal, function (err) {

        var t2 = new Date().getTime();
        //console.log("Partial call to testing space ids took: " + (t2 - t1) + " milisecs");
        if (err) {
            callback(err,null);
        }else{

            db.getDB(function (err,connection)
            {
                var t3 = new Date().getTime();
                console.log("Partial call to get db connection took: " + (t3 - t2) + " milisecs");
                var now = new Date();
                var jsonDate = now.toJSON();
                var modified_at = new Date(jsonDate);

                console.log("modified_at:" + connection.escape(modified_at));
                var sql="UPDATE auxDescription SET modified_at=" + connection.escape(modified_at) + "  where modified_at is null limit " + idsTotal;
                connection.query(sql, function (error, result) {
                    //connection.release();
                    var t4 = new Date().getTime();
                    console.log("Partial call to update data took: " + (t4 - t3) + " milisecs");
                    if (error) {
                        callback (error,null);
                    }
                    else {
                        sql="SELECT sctid, systemId from auxDescription where modified_at=" + connection.escape(modified_at) + " limit " + idsTotal;
                        connection.query(sql, function (error, result) {
                            var t5 = new Date().getTime();
                            console.log("Partial call to select data took: " + (t5 - t4) + " milisecs");
                            if (error) {
                                callback(error, null);
                            }
                            else {

                                if (request) {

                                    callback(null, result);

                                    sql = "update sctId s inner join auxDescription c on c.sctid=s.sctId set s.author= " + connection.escape(request.author) +
                                        ",s.software= " + connection.escape(request.software) +
                                        ",s.comment= " + connection.escape(request.comment) +
                                        ",s.jobId= " + connection.escape(request.jobId) +
                                        " where c.modified_at=" + connection.escape(modified_at)  ;

                                    connection.query(sql, function (error, result) {

                                        sql = "Delete from auxDescription where modified_at=" + connection.escape(modified_at) + " limit " + idsTotal;
                                        connection.query(sql, function (error, result) {
                                            connection.release();
                                            idRepo.idBulkCreation(auxDescription, namespace, partitionId, idsTotal, function (err) {
                                                console.log("End of description id generation");
                                                if (err) {
                                                    var str = "[ERROR] " + (new Date()).getTime() + ": namespace=" + namespace + ", partition=" + partitionId + ". " + err;
                                                    console.log(str);
                                                }
                                            });
                                        });
                                    });

                                }else{
                                    sql = "Delete from auxDescription where modified_at=" + connection.escape(modified_at) + " limit " + idsTotal;
                                    connection.query(sql, function (error, result) {
                                        connection.release();
                                    });
                                }
                            }
                        });
                    }
                });
            });

        }

    });
};
var relationshipIdBulkCreation = function (namespace, partitionId, idsTotal, request, callback) {

    console.log("step relationshipIdBulkCreation");

    testQuantity(auxRelationship, namespace, partitionId, idsTotal, function (err) {

        var t2 = new Date().getTime();
        //console.log("Partial call to testing space ids took: " + (t2 - t1) + " milisecs");
        if (err) {
            callback(err,null);
        }else{

            db.getDB(function (err,connection)
            {
                var t3 = new Date().getTime();
                console.log("Partial call to get db connection took: " + (t3 - t2) + " milisecs");
                var now = new Date();
                var jsonDate = now.toJSON();
                var modified_at = new Date(jsonDate);

                console.log("modified_at:" + connection.escape(modified_at));
                var sql="UPDATE auxRelationship SET modified_at=" + connection.escape(modified_at) + "  where modified_at is null limit " + idsTotal;
                connection.query(sql, function (error, result) {
                    //connection.release();
                    var t4 = new Date().getTime();
                    console.log("Partial call to update data took: " + (t4 - t3) + " milisecs");
                    if (error) {
                        callback (error,null);
                    }
                    else {
                        sql="SELECT sctid, systemId from auxRelationship where modified_at=" + connection.escape(modified_at) + " limit " + idsTotal;
                        connection.query(sql, function (error, result) {
                            var t5 = new Date().getTime();
                            console.log("Partial call to select data took: " + (t5 - t4) + " milisecs");
                            if (error) {
                                callback(error, null);
                            }
                            else {

                                if (request) {

                                    callback(null, result);

                                    sql = "update sctId s inner join auxRelationship c on c.sctid=s.sctId set s.author= " + connection.escape(request.author) +
                                        ",s.software= " + connection.escape(request.software) +
                                        ",s.comment= " + connection.escape(request.comment) +
                                        ",s.jobId= " + connection.escape(request.jobId) +
                                        " where c.modified_at=" + connection.escape(modified_at)  ;

                                    connection.query(sql, function (error, result) {

                                        //sql = "Delete from auxRelationship where modified_at=" + connection.escape(modified_at) + " limit " + idsTotal;
                                        //connection.query(sql, function (error, result) {
                                            connection.release();
                                            idRepo.idBulkCreation(auxRelationship, namespace, partitionId, idsTotal, function (err) {
                                                console.log("End of relationship id generation");
                                                if (err) {
                                                    var str = "[ERROR] " + (new Date()).getTime() + ": namespace=" + namespace + ", partition=" + partitionId + ". " + err;
                                                    console.log(str);
                                                }
                                            });
                                        //});
                                    });

                                }else{
                                    sql = "Delete from auxRelationship where modified_at=" + connection.escape(modified_at) + " limit " + idsTotal;
                                    connection.query(sql, function (error, result) {
                                        connection.release();
                                    });
                                }
                            }
                        });
                    }
                });
            });

        }

    });
};

var testQuantity = function (auxTable, namespace, partitionId, idsTotal, callback) {
    var query = {partitionId: partitionId, namespace: namespace, modified_at: null};

    auxTable.availableCount(query, function (err, recs) {
        console.log("step 12");
        if (err == null) {
            var quant = idsTotal - recs;
            console.log("step testing quantity in aux table, required - existent: " + quant);
            if (quant > 0) {
                callback("It is necesary wait for ids reposition. Try again in few minutes");
                createIds(auxTable, namespace, partitionId, idsTotal,function(err) {
                    if (err){
                        console.log("Cannot create ids:" + err);
                    }
                });
            } else {
                callback(null);
            }

        }
    });
};
var createIds = function (auxTable, namespace, partitionId, idsTotal, callback) {
    var query = {partitionId: partitionId, namespace: namespace, modified_at: null};

    auxTable.availableCount(query, function (err, recs) {
        console.log("step 12");
        if (err == null) {
            var quant = idsTotal - recs;
            console.log("step create Ids, checking quantity" );
            if (quant > 0) {
                console.log("need to create " + quant + " ids, up to " + idsTotal);
                idRepo.idBulkCreation(auxTable, namespace, partitionId, idsTotal, function (err) {
                    console.log("End of id generation");
                    if (err) {
                        var str = "[ERROR] " + (new Date()).getTime() + ": namespace=" + namespace + ", partition=" + partitionId + ". " + err;
                        console.log(str);
                        callback(str);
                    } else {
                        callback(null);
                    }
                });

            } else {
                console.log("ids quantity in aux table is ok");
                callback(null);
            }

        }
    });
};

var createAvailableIds = function (request, callback) {
    var t1 = new Date().getTime();
    var auxTable;
    if (request.partitionId.substr(1,1)=="0") {
        auxTable = auxConcept;
    }else if (request.partitionId.substr(1,1)=="1"){
        auxTable = auxDescription;
    }else if (request.partitionId.substr(1,1)=="2") {
        auxTable = auxRelationship;
    }
    createIds(auxTable, request.namespace, request.partitionId, request.quantity,function (err) {

        var t2 = new Date().getTime();
        console.log("Partial call to testing available ids took: " + (t2 - t1) + " milisecs");
        if (err) {
            callback(err);
        } else {
            callback(null);
        }
    });
};

var idsRetrieve = function (request, callback) {

    if (request.partitionId.substr(1,1)=="0") {
        conceptIdBulkCreation( request.namespace, request.partitionId, request.quantity, request, function(err, result){

            if (err) {
                callback(err,null);
            } else {
                callback(null,result);
            }
        });
    }else if (request.partitionId.substr(1,1)=="1") {
        descriptionIdBulkCreation(request.namespace, request.partitionId, request.quantity, request, function (err, result) {

            if (err) {
                callback(err, null);
            } else {
                callback(null, result);
            }
        });
    }else if (request.partitionId.substr(1,1)=="2") {
        relationshipIdBulkCreation( request.namespace, request.partitionId, request.quantity, request, function(err, result){

            if (err) {
                callback(err,null);
            } else {
                callback(null,result);
            }
        });
    }

};

module.exports.createAvailableIds=createAvailableIds;
module.exports.testQuantity=testQuantity;
module.exports.conceptIdBulkCreation=conceptIdBulkCreation;
module.exports.descriptionIdBulkCreation=descriptionIdBulkCreation;
module.exports.relationshipIdBulkCreation=relationshipIdBulkCreation;
module.exports.idsRetrieve=idsRetrieve;

//var t1 = new Date().getTime();
//
//conceptIdBulkCreation( 0, "00", 100000, function(err, result){
//    if (err){
//        console.log("error: " + err);
//    }else{
//
//        if (result){
//            if (result.length){
//
//                console.log("result length:" + result.length);
//            }else{
//                console.log("There is not an array");
//            }
//        }else{
//            console.log("Result is null");
//
//        }
//    }
//        var t2 = new Date().getTime();
//        console.log("Final call to retrieve ids took: " + (t2 - t1) + " milisecs");
//});<commit_msg>Added service to keep 100000 ids pre generated in available status<commit_after>/**
 * Created by ar on 3/8/17.
 */

var idRepo = require("./../blogic/IdReposition");;
var auxConcept=require("../model/auxConcept");
var auxDescription=require("../model/auxDescription");
var auxRelationship=require("../model/auxRelationship");

var db=require("../config/MysqlInit");

var conceptIdBulkCreation = function (namespace, partitionId, idsTotal, request, callback) {

    console.log("step conceptIdBulkCreation");

    testQuantity(auxConcept, namespace, partitionId, idsTotal, function (err) {

        var t2 = new Date().getTime();
        //console.log("Partial call to testing space ids took: " + (t2 - t1) + " milisecs");
        if (err) {
            callback(err,null);
        }else{

            db.getDB(function (err,connection)
            {
                var t3 = new Date().getTime();
                console.log("Partial call to get db connection took: " + (t3 - t2) + " milisecs");
                var now = new Date();
                var jsonDate = now.toJSON();
                var modified_at = new Date(jsonDate);

                console.log("modified_at:" + connection.escape(modified_at));
                var sql="UPDATE auxConcept SET modified_at=" + connection.escape(modified_at) + "  where modified_at is null limit " + idsTotal;
                connection.query(sql, function (error, result) {
                    //connection.release();
                    var t4 = new Date().getTime();
                    console.log("Partial call to update data took: " + (t4 - t3) + " milisecs");
                    if (error) {
                        callback (error,null);
                    }
                    else {
                        sql="SELECT sctid, systemId from auxConcept where modified_at=" + connection.escape(modified_at) + " limit " + idsTotal;
                        connection.query(sql, function (error, result) {
                            var t5 = new Date().getTime();
                            console.log("Partial call to select data took: " + (t5 - t4) + " milisecs");
                            if (error) {
                                callback(error, null);
                            }
                            else {

                                if (request) {

                                    callback(null, result);

                                    sql = "update sctId s inner join auxConcept c on c.sctid=s.sctId set s.author= " + connection.escape(request.author) +
                                        ",s.software= " + connection.escape(request.software) +
                                        ",s.comment= " + connection.escape(request.comment) +
                                        ",s.jobId= " + connection.escape(request.jobId) +
                                        " where c.modified_at=" + connection.escape(modified_at)  ;

                                    connection.query(sql, function (error, result) {

                                        sql = "Delete from auxConcept where modified_at=" + connection.escape(modified_at) + " limit " + idsTotal;
                                        connection.query(sql, function (error, result) {
                                            connection.release();
                                        });
                                    });

                                }else{
                                    sql = "Delete from auxConcept where modified_at=" + connection.escape(modified_at) + " limit " + idsTotal;
                                    connection.query(sql, function (error, result) {
                                        connection.release();
                                        idRepo.idBulkCreation(auxDescription, namespace, partitionId, idsTotal, function (err) {
                                            console.log("End of concept id generation");
                                            if (err) {
                                                var str = "[ERROR] " + (new Date()).getTime() + ": namespace=" + namespace + ", partition=" + partitionId + ". " + err;
                                                console.log(str);
                                            }
                                        });
                                    });
                                }
                            }
                        });
                    }
                });
            });

        }

    });
};

var descriptionIdBulkCreation = function (namespace, partitionId, idsTotal, request, callback) {

    console.log("step descriptionIdBulkCreation");

    testQuantity(auxDescription, namespace, partitionId, idsTotal, function (err) {

        var t2 = new Date().getTime();
        //console.log("Partial call to testing space ids took: " + (t2 - t1) + " milisecs");
        if (err) {
            callback(err,null);
        }else{

            db.getDB(function (err,connection)
            {
                var t3 = new Date().getTime();
                console.log("Partial call to get db connection took: " + (t3 - t2) + " milisecs");
                var now = new Date();
                var jsonDate = now.toJSON();
                var modified_at = new Date(jsonDate);

                console.log("modified_at:" + connection.escape(modified_at));
                var sql="UPDATE auxDescription SET modified_at=" + connection.escape(modified_at) + "  where modified_at is null limit " + idsTotal;
                connection.query(sql, function (error, result) {
                    //connection.release();
                    var t4 = new Date().getTime();
                    console.log("Partial call to update data took: " + (t4 - t3) + " milisecs");
                    if (error) {
                        callback (error,null);
                    }
                    else {
                        sql="SELECT sctid, systemId from auxDescription where modified_at=" + connection.escape(modified_at) + " limit " + idsTotal;
                        connection.query(sql, function (error, result) {
                            var t5 = new Date().getTime();
                            console.log("Partial call to select data took: " + (t5 - t4) + " milisecs");
                            if (error) {
                                callback(error, null);
                            }
                            else {

                                if (request) {

                                    callback(null, result);

                                    sql = "update sctId s inner join auxDescription c on c.sctid=s.sctId set s.author= " + connection.escape(request.author) +
                                        ",s.software= " + connection.escape(request.software) +
                                        ",s.comment= " + connection.escape(request.comment) +
                                        ",s.jobId= " + connection.escape(request.jobId) +
                                        " where c.modified_at=" + connection.escape(modified_at)  ;

                                    connection.query(sql, function (error, result) {

                                        sql = "Delete from auxDescription where modified_at=" + connection.escape(modified_at) + " limit " + idsTotal;
                                        connection.query(sql, function (error, result) {
                                            connection.release();
                                            idRepo.idBulkCreation(auxDescription, namespace, partitionId, idsTotal, function (err) {
                                                console.log("End of description id generation");
                                                if (err) {
                                                    var str = "[ERROR] " + (new Date()).getTime() + ": namespace=" + namespace + ", partition=" + partitionId + ". " + err;
                                                    console.log(str);
                                                }
                                            });
                                        });
                                    });

                                }else{
                                    sql = "Delete from auxDescription where modified_at=" + connection.escape(modified_at) + " limit " + idsTotal;
                                    connection.query(sql, function (error, result) {
                                        connection.release();
                                    });
                                }
                            }
                        });
                    }
                });
            });

        }

    });
};
var relationshipIdBulkCreation = function (namespace, partitionId, idsTotal, request, callback) {

    console.log("step relationshipIdBulkCreation");

    testQuantity(auxRelationship, namespace, partitionId, idsTotal, function (err) {

        var t2 = new Date().getTime();
        //console.log("Partial call to testing space ids took: " + (t2 - t1) + " milisecs");
        if (err) {
            callback(err,null);
        }else{

            db.getDB(function (err,connection)
            {
                var t3 = new Date().getTime();
                console.log("Partial call to get db connection took: " + (t3 - t2) + " milisecs");
                var now = new Date();
                var jsonDate = now.toJSON();
                var modified_at = new Date(jsonDate);

                console.log("modified_at:" + connection.escape(modified_at));
                var sql="UPDATE auxRelationship SET modified_at=" + connection.escape(modified_at) + "  where modified_at is null limit " + idsTotal;
                connection.query(sql, function (error, result) {
                    //connection.release();
                    var t4 = new Date().getTime();
                    console.log("Partial call to update data took: " + (t4 - t3) + " milisecs");
                    if (error) {
                        callback (error,null);
                    }
                    else {
                        sql="SELECT sctid, systemId from auxRelationship where modified_at=" + connection.escape(modified_at) + " limit " + idsTotal;
                        connection.query(sql, function (error, result) {
                            var t5 = new Date().getTime();
                            console.log("Partial call to select data took: " + (t5 - t4) + " milisecs");
                            if (error) {
                                callback(error, null);
                            }
                            else {

                                if (request) {

                                    callback(null, result);

                                    sql = "update sctId s inner join auxRelationship c on c.sctid=s.sctId set s.author= " + connection.escape(request.author) +
                                        ",s.software= " + connection.escape(request.software) +
                                        ",s.comment= " + connection.escape(request.comment) +
                                        ",s.jobId= " + connection.escape(request.jobId) +
                                        " where c.modified_at=" + connection.escape(modified_at)  ;

                                    connection.query(sql, function (error, result) {

                                        sql = "Delete from auxRelationship where modified_at=" + connection.escape(modified_at) + " limit " + idsTotal;
                                        connection.query(sql, function (error, result) {
                                            connection.release();
                                            idRepo.idBulkCreation(auxRelationship, namespace, partitionId, idsTotal, function (err) {
                                                console.log("End of relationship id generation");
                                                if (err) {
                                                    var str = "[ERROR] " + (new Date()).getTime() + ": namespace=" + namespace + ", partition=" + partitionId + ". " + err;
                                                    console.log(str);
                                                }
                                            });
                                        });
                                    });

                                }else{
                                    sql = "Delete from auxRelationship where modified_at=" + connection.escape(modified_at) + " limit " + idsTotal;
                                    connection.query(sql, function (error, result) {
                                        connection.release();
                                    });
                                }
                            }
                        });
                    }
                });
            });

        }

    });
};

var testQuantity = function (auxTable, namespace, partitionId, idsTotal, callback) {
    var query = {partitionId: partitionId, namespace: namespace, modified_at: null};

    auxTable.availableCount(query, function (err, recs) {
        console.log("step 12");
        if (err == null) {
            var quant = idsTotal - recs;
            console.log("step testing quantity in aux table, required - existent: " + quant);
            if (quant > 0) {
                callback("It is necesary wait for ids reposition. Try again in few minutes");
                createIds(auxTable, namespace, partitionId, idsTotal,function(err) {
                    if (err){
                        console.log("Cannot create ids:" + err);
                    }
                });
            } else {
                callback(null);
            }

        }
    });
};
var createIds = function (auxTable, namespace, partitionId, idsTotal, callback) {
    var query = {partitionId: partitionId, namespace: namespace, modified_at: null};

    auxTable.availableCount(query, function (err, recs) {
        console.log("step 12");
        if (err == null) {
            var quant = idsTotal - recs;
            console.log("step create Ids, checking quantity" );
            if (quant > 0) {
                console.log("need to create " + quant + " ids, up to " + idsTotal);
                idRepo.idBulkCreation(auxTable, namespace, partitionId, idsTotal, function (err) {
                    console.log("End of id generation");
                    if (err) {
                        var str = "[ERROR] " + (new Date()).getTime() + ": namespace=" + namespace + ", partition=" + partitionId + ". " + err;
                        console.log(str);
                        callback(str);
                    } else {
                        callback(null);
                    }
                });

            } else {
                console.log("ids quantity in aux table is ok");
                callback(null);
            }

        }
    });
};

var createAvailableIds = function (request, callback) {
    var t1 = new Date().getTime();
    var auxTable;
    if (request.partitionId.substr(1,1)=="0") {
        auxTable = auxConcept;
    }else if (request.partitionId.substr(1,1)=="1"){
        auxTable = auxDescription;
    }else if (request.partitionId.substr(1,1)=="2") {
        auxTable = auxRelationship;
    }
    createIds(auxTable, request.namespace, request.partitionId, request.quantity,function (err) {

        var t2 = new Date().getTime();
        console.log("Partial call to testing available ids took: " + (t2 - t1) + " milisecs");
        if (err) {
            callback(err);
        } else {
            callback(null);
        }
    });
};

var idsRetrieve = function (request, callback) {

    if (request.partitionId.substr(1,1)=="0") {
        conceptIdBulkCreation( request.namespace, request.partitionId, request.quantity, request, function(err, result){

            if (err) {
                callback(err,null);
            } else {
                callback(null,result);
            }
        });
    }else if (request.partitionId.substr(1,1)=="1") {
        descriptionIdBulkCreation(request.namespace, request.partitionId, request.quantity, request, function (err, result) {

            if (err) {
                callback(err, null);
            } else {
                callback(null, result);
            }
        });
    }else if (request.partitionId.substr(1,1)=="2") {
        relationshipIdBulkCreation( request.namespace, request.partitionId, request.quantity, request, function(err, result){

            if (err) {
                callback(err,null);
            } else {
                callback(null,result);
            }
        });
    }

};

module.exports.createAvailableIds=createAvailableIds;
module.exports.testQuantity=testQuantity;
module.exports.conceptIdBulkCreation=conceptIdBulkCreation;
module.exports.descriptionIdBulkCreation=descriptionIdBulkCreation;
module.exports.relationshipIdBulkCreation=relationshipIdBulkCreation;
module.exports.idsRetrieve=idsRetrieve;

//var t1 = new Date().getTime();
//
//conceptIdBulkCreation( 0, "00", 100000, function(err, result){
//    if (err){
//        console.log("error: " + err);
//    }else{
//
//        if (result){
//            if (result.length){
//
//                console.log("result length:" + result.length);
//            }else{
//                console.log("There is not an array");
//            }
//        }else{
//            console.log("Result is null");
//
//        }
//    }
//        var t2 = new Date().getTime();
//        console.log("Final call to retrieve ids took: " + (t2 - t1) + " milisecs");
//});<|endoftext|>


<commit_before>// Placeholder manifest file.
// the installer will append this file to the app vendored assets here: vendor/assets/javascripts/spree/frontend/all.js'

$(window).load(function() {
  function loop() {
    $("#showcase_inner_container").css("transform", "translateX("+$(this).index() * 663+"px)");
    setTimeout(loop, 1000);
  };
});
<commit_msg>Add images to showcase.<commit_after>// Placeholder manifest file.
// the installer will append this file to the app vendored assets here: vendor/assets/javascripts/spree/frontend/all.js'

$(window).load(function() {
  function loop() {
    $("#showcase_inner_container").css("transform", "translateX("+$(this).index() * 663+"px)");
    setTimeout(loop, 1000);
  };
  setTimeout(loop,1000);
});
<|endoftext|>


<commit_before>/*
The MIT Licence, for code from kryogenix.org

Code downloaded from the Browser Experiments section
of kryogenix.org is licenced under the so-called MIT
licence. The licence is below.

Copyright (c) 1997-date Stuart Langridge

Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the
Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
Usage
=====

Add the "sortable" CSS class to a table to make it sortable.
The first column must be always table header, and the rest must be table data.
(the script seems to support rows to be fixed at the bottom, but haven't figured out how to use it.)

If the table data is sorted to begin with, you can add 'initialSortDir="up|down"' to the
corresponding column in the header row to display the direction icon from the beginning.
This is recommended to provide a visual cue that the table can be sorted.

The script guesses the table data, and try to use the right sorting algorithm.
But you can override this behavior by having 'data="..."' attribute on each row,
in which case the sort will be done on that field.
*/

var Sortable = (function() {

    function Sortable(table) {
        this.table = table;
        this.arrows = [];

        var firstRow = this.getFirstRow();
        if (!firstRow) return;

        // We have a first row: assume it's the header, and make its contents clickable links
        firstRow.each(function (cell){
            cell.innerHTML = ''+this.getInnerText(cell)+'';
            this.arrows.push(cell.firstChild.lastChild);

            var self = this;
            cell.firstChild.onclick = function () {
                self.onClicked(this);
                return false;
            };
        }.bind(this));

        // figure out the initial sort preference
        this.pref = this.getStoredPreference();
        if (this.pref == null) {
            firstRow.each(function (cell,i){
                var initialSortDir = cell.getAttribute("initialSortDir");
                if (initialSortDir != null) {
                    this.pref = {column:i, direction:arrowTable[initialSortDir]};
                }
            }.bind(this));
        }

        this.refresh();
    }

    Sortable.prototype = {
        /**
         * SPAN tags that we use to render directional arrows, for each columns.
         */
        arrows : null /*Array*/,

        /**
         * Current sort preference.
         */
        pref : null /* { column:int, direction:arrow } */,

        getFirstRow : function() {
            if (this.table.rows && this.table.rows.length > 0) {
                return $A(this.table.rows[0].cells);
            }
            return null;
        },

        getDataRows : function() {
            var newRows = [];
            var rows = this.table.rows;
            for (var j = 1; j < rows.length; j++) {
                newRows.push($(rows[j]));
            }
            return newRows;
        },

        /**
         * If there's a persisted sort direction setting, retrieve it
         */
        getStoredPreference : function() {
            var key = this.getStorageKey();
            if(storage.hasKey(key)){
                var val = storage.getItem(key);
                if(val){
                    var vals = val.split(":");
                    if(vals.length == 2) {
                        return {column:parseInt(vals[0]), direction:arrowTable[vals[1]]};
                    }
                }
            }
            return null;
        },

        getStorageKey : function() {
            var uri = document.location;
            var tableIndex = this.getIndexOfSortableTable();
            return "ts_direction::" + uri + "::" + tableIndex;
        },

        savePreference : function() {
            var key = this.getStorageKey();
            storage.setItem(key, this.pref.column + ":" + this.pref.direction.id);
        },

        /**
         * Determine the sort function for the specified column
         */
        getSorter : function(column) {
            var rows = this.table.rows;
            if (rows.length <= 1)   return sorter.fallback;

            var itm = this.extractData(rows[1].cells[column]).trim();
            return sorter.determine(itm);
        },

        /**
         * Called when the column header gets clicked.
         */
        onClicked : function(lnk) {
            var arrow = lnk.lastChild;
            var th = lnk.parentNode;

            var column = th.cellIndex;
            if (column==(this.pref||{}).column) {
                // direction change on the same row
                this.pref.direction = this.pref.direction.next;
            } else {
                this.pref = {column:column, direction: arrow.sortdir||arrowTable.up};
            }

            arrow.sortdir = this.pref.direction; // remember the last sort direction on this column

            this.refresh();
            this.savePreference();
        },

        /**
         * Call when data has changed. Reapply the current sort setting to the existing data rows.
         * @since 1.484
         */
        refresh : function() {
            if (this.pref==null)     return; // not sorting

            var column = this.pref.column;
            var dir = this.pref.direction;

            var s = this.getSorter(column);
            if(dir === arrowTable.up) {// ascending
                s = sorter.reverse(s);
            }

            // we allow some rows to stick to the top and bottom, so that is our first sort criteria
            // regardless of the sort function
            function rowPos(r) {
                if (r.hasClassName("sorttop"))      return 0;
                if (r.hasClassName("sortbottom"))   return 2;
                return 1;
            }

            var rows = this.getDataRows();
            rows.sort(function(a,b) {
                var x = rowPos(a)-rowPos(b);
                if (x!=0)   return x;

                return s(
                    this.extractData(a.cells[column]),
                    this.extractData(b.cells[column]));
            }.bind(this));

            rows.each(function (e) {
                this.table.tBodies[0].appendChild(e);
            }.bind(this));

            // update arrow rendering
            this.arrows.each(function(e,i){
                e.innerHTML = ((i==column) ? dir : arrowTable.none).text;
            });
        },

        getIndexOfSortableTable : function(){
            return $(document.body).select("TABLE.sortable").indexOf(this.table);
        },

        getInnerText : function(el) {
        	if (typeof el == "string") return el;
        	if (typeof el == "undefined") { return el }
        	if (el.innerText) return el.innerText;	//Not needed but it is faster
        	var str = "";

        	var cs = el.childNodes;
        	var l = cs.length;
        	for (var i = 0; i < l; i++) {
        		switch (cs[i].nodeType) {
        			case 1: //ELEMENT_NODE
        				str += this.getInnerText(cs[i]);
        				break;
        			case 3:	//TEXT_NODE
        				str += cs[i].nodeValue;
        				break;
        		}
        	}
        	return str;
        },

        // extract data for sorting from a cell
        extractData : function(x) {
          if(x==null) return '';
          var data = x.getAttribute("data");
          if(data!=null)
            return data;
          return this.getInnerText(x);
        }
    };

    var arrowTable = {
        up: {
            id: "up",
            text: "  ↑"
        },
        down: {
            id: "down",
            text: "  ↓"
        },
        none: {
            id: "none",
            text: "   "
        },
        lnkRef: null
    };

    arrowTable.up.next = arrowTable.down;
    arrowTable.down.next = arrowTable.up;

    // available sort functions
    var sorter = {
        date : function(a,b) {
            function toDt(x) {
              // y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
              if (x.length == 10) {
                  return x.substr(6,4)+x.substr(3,2)+x.substr(0,2);
              } else {
                  var yr = x.substr(6,2);
                  if (parseInt(yr) < 50) { yr = '20'+yr; } else { yr = '19'+yr; }
                  return yr+x.substr(3,2)+x.substr(0,2);
              }
            }

            var dt1 = toDt(a);
            var dt2 = toDt(b);

            if (dt1==dt2) return 0;
            if (dt1<dt2) return -1;
            return 1;
        },

        currency : function(a,b) {
            a = a.replace(/[^0-9.]/g,'');
            b = b.replace(/[^0-9.]/g,'');
            return parseFloat(a) - parseFloat(b);
        },

        numeric : function(a,b) {
            a = parseFloat(a);
            if (isNaN(a)) a = 0;
            b = parseFloat(b);
            if (isNaN(b)) b = 0;
            return a-b;
        },

        caseInsensitive : function(a,b) {
            return sorter.fallback(a.toLowerCase(), b.toLowerCase());
        },

        fallback : function(a,b) {
            if (a==b) return 0;
            if (a<b) return -1;
            return 1;
        },

        /**
         * return the sorter to be used for the given value
         * @param {String} itm
         *      Text
         */
        determine : function(itm) {
            var sortfn = this.caseInsensitive;
            if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d\d\d$/)) sortfn = this.date;
            if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d$/)) sortfn = this.date;
            if (itm.match(/^[�$]/)) sortfn = this.currency;
            if (itm.match(/^-?[\d\.]+$/)) sortfn = this.numeric;
            return sortfn;
        },

        reverse : function(f) {
            return function (a, b) {
                return -f(a, b)
            };
        }
    };

    var storage;
    try {
        storage = YAHOO.util.StorageManager.get(
            YAHOO.util.StorageEngineHTML5.ENGINE_NAME,
            YAHOO.util.StorageManager.LOCATION_SESSION,
            {
                order: [
                    YAHOO.util.StorageEngineGears
                ]
            }
        );
    } catch(e) {
        // no storage available
        storage = {
            setItem : function() {},
            getItem : function() { return null; },
            hasKey : function() { return false; }
        };
    }

    return {
        Sortable : Sortable,
        sorter : sorter
    };
})();

function ts_makeSortable(table) { // backward compatibility
    return new Sortable.Sortable(table);
}

/** Calls table.sortable.refresh() in case the sortable has been initialized; otherwise does nothing. */
function ts_refresh(table) {
    var s = table.sortable;
    if (s != null) {
        s.refresh();
    }
}
<commit_msg>JENKINS-19634 Fix sorting percentages<commit_after>/*
The MIT Licence, for code from kryogenix.org

Code downloaded from the Browser Experiments section
of kryogenix.org is licenced under the so-called MIT
licence. The licence is below.

Copyright (c) 1997-date Stuart Langridge

Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the
Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
Usage
=====

Add the "sortable" CSS class to a table to make it sortable.
The first column must be always table header, and the rest must be table data.
(the script seems to support rows to be fixed at the bottom, but haven't figured out how to use it.)

If the table data is sorted to begin with, you can add 'initialSortDir="up|down"' to the
corresponding column in the header row to display the direction icon from the beginning.
This is recommended to provide a visual cue that the table can be sorted.

The script guesses the table data, and try to use the right sorting algorithm.
But you can override this behavior by having 'data="..."' attribute on each row,
in which case the sort will be done on that field.
*/

var Sortable = (function() {

    function Sortable(table) {
        this.table = table;
        this.arrows = [];

        var firstRow = this.getFirstRow();
        if (!firstRow) return;

        // We have a first row: assume it's the header, and make its contents clickable links
        firstRow.each(function (cell){
            cell.innerHTML = ''+this.getInnerText(cell)+'';
            this.arrows.push(cell.firstChild.lastChild);

            var self = this;
            cell.firstChild.onclick = function () {
                self.onClicked(this);
                return false;
            };
        }.bind(this));

        // figure out the initial sort preference
        this.pref = this.getStoredPreference();
        if (this.pref == null) {
            firstRow.each(function (cell,i){
                var initialSortDir = cell.getAttribute("initialSortDir");
                if (initialSortDir != null) {
                    this.pref = {column:i, direction:arrowTable[initialSortDir]};
                }
            }.bind(this));
        }

        this.refresh();
    }

    Sortable.prototype = {
        /**
         * SPAN tags that we use to render directional arrows, for each columns.
         */
        arrows : null /*Array*/,

        /**
         * Current sort preference.
         */
        pref : null /* { column:int, direction:arrow } */,

        getFirstRow : function() {
            if (this.table.rows && this.table.rows.length > 0) {
                return $A(this.table.rows[0].cells);
            }
            return null;
        },

        getDataRows : function() {
            var newRows = [];
            var rows = this.table.rows;
            for (var j = 1; j < rows.length; j++) {
                newRows.push($(rows[j]));
            }
            return newRows;
        },

        /**
         * If there's a persisted sort direction setting, retrieve it
         */
        getStoredPreference : function() {
            var key = this.getStorageKey();
            if(storage.hasKey(key)){
                var val = storage.getItem(key);
                if(val){
                    var vals = val.split(":");
                    if(vals.length == 2) {
                        return {column:parseInt(vals[0]), direction:arrowTable[vals[1]]};
                    }
                }
            }
            return null;
        },

        getStorageKey : function() {
            var uri = document.location;
            var tableIndex = this.getIndexOfSortableTable();
            return "ts_direction::" + uri + "::" + tableIndex;
        },

        savePreference : function() {
            var key = this.getStorageKey();
            storage.setItem(key, this.pref.column + ":" + this.pref.direction.id);
        },

        /**
         * Determine the sort function for the specified column
         */
        getSorter : function(column) {
            var rows = this.table.rows;
            if (rows.length <= 1)   return sorter.fallback;

            var itm = this.extractData(rows[1].cells[column]).trim();
            return sorter.determine(itm);
        },

        /**
         * Called when the column header gets clicked.
         */
        onClicked : function(lnk) {
            var arrow = lnk.lastChild;
            var th = lnk.parentNode;

            var column = th.cellIndex;
            if (column==(this.pref||{}).column) {
                // direction change on the same row
                this.pref.direction = this.pref.direction.next;
            } else {
                this.pref = {column:column, direction: arrow.sortdir||arrowTable.up};
            }

            arrow.sortdir = this.pref.direction; // remember the last sort direction on this column

            this.refresh();
            this.savePreference();
        },

        /**
         * Call when data has changed. Reapply the current sort setting to the existing data rows.
         * @since 1.484
         */
        refresh : function() {
            if (this.pref==null)     return; // not sorting

            var column = this.pref.column;
            var dir = this.pref.direction;

            var s = this.getSorter(column);
            if(dir === arrowTable.up) {// ascending
                s = sorter.reverse(s);
            }

            // we allow some rows to stick to the top and bottom, so that is our first sort criteria
            // regardless of the sort function
            function rowPos(r) {
                if (r.hasClassName("sorttop"))      return 0;
                if (r.hasClassName("sortbottom"))   return 2;
                return 1;
            }

            var rows = this.getDataRows();
            rows.sort(function(a,b) {
                var x = rowPos(a)-rowPos(b);
                if (x!=0)   return x;

                return s(
                    this.extractData(a.cells[column]),
                    this.extractData(b.cells[column]));
            }.bind(this));

            rows.each(function (e) {
                this.table.tBodies[0].appendChild(e);
            }.bind(this));

            // update arrow rendering
            this.arrows.each(function(e,i){
                e.innerHTML = ((i==column) ? dir : arrowTable.none).text;
            });
        },

        getIndexOfSortableTable : function(){
            return $(document.body).select("TABLE.sortable").indexOf(this.table);
        },

        getInnerText : function(el) {
        	if (typeof el == "string") return el;
        	if (typeof el == "undefined") { return el }
        	if (el.innerText) return el.innerText;	//Not needed but it is faster
        	var str = "";

        	var cs = el.childNodes;
        	var l = cs.length;
        	for (var i = 0; i < l; i++) {
        		switch (cs[i].nodeType) {
        			case 1: //ELEMENT_NODE
        				str += this.getInnerText(cs[i]);
        				break;
        			case 3:	//TEXT_NODE
        				str += cs[i].nodeValue;
        				break;
        		}
        	}
        	return str;
        },

        // extract data for sorting from a cell
        extractData : function(x) {
          if(x==null) return '';
          var data = x.getAttribute("data");
          if(data!=null)
            return data;
          return this.getInnerText(x);
        }
    };

    var arrowTable = {
        up: {
            id: "up",
            text: "  ↑"
        },
        down: {
            id: "down",
            text: "  ↓"
        },
        none: {
            id: "none",
            text: "   "
        },
        lnkRef: null
    };

    arrowTable.up.next = arrowTable.down;
    arrowTable.down.next = arrowTable.up;

    // available sort functions
    var sorter = {
        date : function(a,b) {
            function toDt(x) {
              // y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
              if (x.length == 10) {
                  return x.substr(6,4)+x.substr(3,2)+x.substr(0,2);
              } else {
                  var yr = x.substr(6,2);
                  if (parseInt(yr) < 50) { yr = '20'+yr; } else { yr = '19'+yr; }
                  return yr+x.substr(3,2)+x.substr(0,2);
              }
            }

            var dt1 = toDt(a);
            var dt2 = toDt(b);

            if (dt1==dt2) return 0;
            if (dt1<dt2) return -1;
            return 1;
        },

        currency : function(a,b) {
            a = a.replace(/[^0-9.]/g,'');
            b = b.replace(/[^0-9.]/g,'');
            return parseFloat(a) - parseFloat(b);
        },

        numeric : function(a,b) {
            a = parseFloat(a);
            if (isNaN(a)) a = 0;
            b = parseFloat(b);
            if (isNaN(b)) b = 0;
            return a-b;
        },

        caseInsensitive : function(a,b) {
            return sorter.fallback(a.toLowerCase(), b.toLowerCase());
        },

        fallback : function(a,b) {
            if (a==b) return 0;
            if (a<b) return -1;
            return 1;
        },

        /**
         * return the sorter to be used for the given value
         * @param {String} itm
         *      Text
         */
        determine : function(itm) {
            var sortfn = this.caseInsensitive;
            if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d\d\d$/)) sortfn = this.date;
            if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d$/)) sortfn = this.date;
            if (itm.match(/^[�$]/)) sortfn = this.currency;
            if (itm.match(/\%$/)) sortfn = this.currency;
            if (itm.match(/^-?[\d\.]+$/)) sortfn = this.numeric;
            return sortfn;
        },

        reverse : function(f) {
            return function (a, b) {
                return -f(a, b)
            };
        }
    };

    var storage;
    try {
        storage = YAHOO.util.StorageManager.get(
            YAHOO.util.StorageEngineHTML5.ENGINE_NAME,
            YAHOO.util.StorageManager.LOCATION_SESSION,
            {
                order: [
                    YAHOO.util.StorageEngineGears
                ]
            }
        );
    } catch(e) {
        // no storage available
        storage = {
            setItem : function() {},
            getItem : function() { return null; },
            hasKey : function() { return false; }
        };
    }

    return {
        Sortable : Sortable,
        sorter : sorter
    };
})();

function ts_makeSortable(table) { // backward compatibility
    return new Sortable.Sortable(table);
}

/** Calls table.sortable.refresh() in case the sortable has been initialized; otherwise does nothing. */
function ts_refresh(table) {
    var s = table.sortable;
    if (s != null) {
        s.refresh();
    }
}
<|endoftext|>


<commit_before>Ext.define('Datanium.controller.Homepage', {
	extend : 'Ext.app.Controller',
	views : [ 'Toolbar', 'ReportTemplate', 'LeftPanel', 'CubeCombo', 'IndicatorSearchCombo', 'Accordion',
			'DimensionTree', 'MeasureTree', 'ElementPanel', 'DataPanel', 'InnerToolbar' ],
	models : [ 'CubeName', 'Indicator' ],
	stores : [ 'CubeNames', 'Indicators' ],
	init : function() {
		this.control({
			'viewport reporttemplate' : {},
			'leftpanel > cubecombo' : {
				select : this.loadTrees
			},
			'leftpanel > searchcombo' : {
				select : this.addIndicator
			},
			'inner-toolbar > button[action=grid-mode]' : {
				click : function(btn) {
					if (Datanium.GlobalData.rptMode != 'grid') {
						Datanium.GlobalData.rptMode = 'grid';
						Datanium.util.CommonUtils.getCmpInActiveTab('datapanel').getLayout().setActiveItem(0);
					}
				}
			},
			'inner-toolbar > button[action=chart-mode]' : {
				click : function(btn) {
					if (Datanium.GlobalData.rptMode != 'chart') {
						Datanium.GlobalData.rptMode = 'chart';
						Datanium.util.CommonUtils.getCmpInActiveTab('datapanel').getLayout().setActiveItem(1);
					}
				}
			},
			'inner-toolbar > button[action=clear]' : {
				click : function(btn) {
					Datanium.GlobalData.queryParam = {
						dimensions : [],
						measures : [],
						groups : []
					};
					Datanium.GlobalData.QueryResult = null;
					Datanium.util.CommonUtils.getCmpInActiveTab('elementPanel').fireEvent('refreshElementPanel');
				}
			},
			'inner-toolbar > button[action=auto-run]' : {
				click : function(btn) {
					if (btn.pressed) {
						Datanium.GlobalData.autoRun = true;
					} else {
						Datanium.GlobalData.autoRun = false;
					}
				}
			},
			'inner-toolbar > button[action=manual-run]' : {
				click : function(btn) {
					this.getController('GridController').generateRpt(true);
				}
			}
		});
	},

	loadTrees : function(combobox, newValue, oldValue, eOpts) {
		var cubeInfoStore = this.getStore('CubeInfos');
		var leftpanel = Datanium.util.CommonUtils.getCmpInActiveTab('leftpanel');
		var mask = new Ext.LoadMask(leftpanel, {
			msg : "Loading..."
		});
		mask.show();
		cubeInfoStore.load({
			scope : this,
			params : {
				cubeName : combobox.getValue()
			},
			callback : function(records, operation, success) {
				if (success) {
					var tmpstore = records[0];
					var dimensionTree = Datanium.util.CommonUtils.getCmpInActiveTab('dimensionTree');
					var measureTree = Datanium.util.CommonUtils.getCmpInActiveTab('measureTree');
					var dimensionData = {};
					var measureData = {};
					dimensionData.children = tmpstore.data.dimensions;
					dimensionTree.store.setRootNode(dimensionData);
					measureData.children = tmpstore.data.measures;
					measureTree.store.setRootNode(measureData);
					Datanium.GlobalData.qubeInfo.dimensions = tmpstore.data.dimensions;
					Datanium.GlobalData.qubeInfo.measures = tmpstore.data.measures;
					Datanium.util.CommonUtils.getCmpInActiveTab('elementPanel').fireEvent('refreshElementPanel');
					mask.destroy();
				} else {
					console.log('cube loading failed');
					mask.destroy();
				}
			}
		});
	},
	addIndicator : function(combobox, newValue, oldValue, eOpts) {
		var leftpanel = Datanium.util.CommonUtils.getCmpInActiveTab('leftpanel');
		var mask = new Ext.LoadMask(leftpanel, {
			msg : "Loading..."
		});
		mask.show();
		var requestConfig = {
			url : '/rest/indicator/map?idc=' + combobox.getValue(),
			timeout : 300000,
			success : function(response) {
				mask.destroy();
				var result = Ext.JSON.decode(response.responseText, true);
				Datanium.GlobalData.qubeInfo.dimensions = Datanium.util.CommonUtils.pushElements2Array(
						result.dimensions, Datanium.GlobalData.qubeInfo.dimensions);
				Datanium.GlobalData.qubeInfo.measures = Datanium.util.CommonUtils.pushElements2Array(result.measures,
						Datanium.GlobalData.qubeInfo.measures);
				Datanium.util.CommonUtils.getCmpInActiveTab('elementPanel').fireEvent('refreshElementPanel');
			},
			failure : function() {
				mask.destroy();
			}
		};
		Ext.Ajax.request(requestConfig);

	}
});<commit_msg>add measure count validation<commit_after>Ext.define('Datanium.controller.Homepage', {
	extend : 'Ext.app.Controller',
	views : [ 'Toolbar', 'ReportTemplate', 'LeftPanel', 'CubeCombo', 'IndicatorSearchCombo', 'Accordion',
			'DimensionTree', 'MeasureTree', 'ElementPanel', 'DataPanel', 'InnerToolbar' ],
	models : [ 'CubeName', 'Indicator' ],
	stores : [ 'CubeNames', 'Indicators' ],
	init : function() {
		this.control({
			'viewport reporttemplate' : {},
			'leftpanel > cubecombo' : {
				select : this.loadTrees
			},
			'leftpanel > searchcombo' : {
				select : this.addIndicator
			},
			'inner-toolbar > button[action=grid-mode]' : {
				click : function(btn) {
					if (Datanium.GlobalData.rptMode != 'grid') {
						Datanium.GlobalData.rptMode = 'grid';
						Datanium.util.CommonUtils.getCmpInActiveTab('datapanel').getLayout().setActiveItem(0);
					}
				}
			},
			'inner-toolbar > button[action=chart-mode]' : {
				click : function(btn) {
					if (Datanium.GlobalData.rptMode != 'chart') {
						Datanium.GlobalData.rptMode = 'chart';
						Datanium.util.CommonUtils.getCmpInActiveTab('datapanel').getLayout().setActiveItem(1);
					}
				}
			},
			'inner-toolbar > button[action=clear]' : {
				click : function(btn) {
					Datanium.GlobalData.queryParam = {
						dimensions : [],
						measures : [],
						groups : []
					};
					Datanium.GlobalData.QueryResult = null;
					Datanium.util.CommonUtils.getCmpInActiveTab('elementPanel').fireEvent('refreshElementPanel');
				}
			},
			'inner-toolbar > button[action=auto-run]' : {
				click : function(btn) {
					if (btn.pressed) {
						Datanium.GlobalData.autoRun = true;
					} else {
						Datanium.GlobalData.autoRun = false;
					}
				}
			},
			'inner-toolbar > button[action=manual-run]' : {
				click : function(btn) {
					this.getController('GridController').generateRpt(true);
				}
			}
		});
	},

	loadTrees : function(combobox, newValue, oldValue, eOpts) {
		var cubeInfoStore = this.getStore('CubeInfos');
		var leftpanel = Datanium.util.CommonUtils.getCmpInActiveTab('leftpanel');
		var mask = new Ext.LoadMask(leftpanel, {
			msg : "Loading..."
		});
		mask.show();
		cubeInfoStore.load({
			scope : this,
			params : {
				cubeName : combobox.getValue()
			},
			callback : function(records, operation, success) {
				if (success) {
					var tmpstore = records[0];
					var dimensionTree = Datanium.util.CommonUtils.getCmpInActiveTab('dimensionTree');
					var measureTree = Datanium.util.CommonUtils.getCmpInActiveTab('measureTree');
					var dimensionData = {};
					var measureData = {};
					dimensionData.children = tmpstore.data.dimensions;
					dimensionTree.store.setRootNode(dimensionData);
					measureData.children = tmpstore.data.measures;
					measureTree.store.setRootNode(measureData);
					Datanium.GlobalData.qubeInfo.dimensions = tmpstore.data.dimensions;
					Datanium.GlobalData.qubeInfo.measures = tmpstore.data.measures;
					Datanium.util.CommonUtils.getCmpInActiveTab('elementPanel').fireEvent('refreshElementPanel');
					mask.destroy();
				} else {
					console.log('cube loading failed');
					mask.destroy();
				}
			}
		});
	},
	addIndicator : function(combobox, newValue, oldValue, eOpts) {
		var leftpanel = Datanium.util.CommonUtils.getCmpInActiveTab('leftpanel');
		var mask = new Ext.LoadMask(leftpanel, {
			msg : "Loading..."
		});
		mask.show();
		var requestConfig = {
			url : '/rest/indicator/map?idc=' + combobox.getValue(),
			timeout : 300000,
			success : function(response) {
				mask.destroy();
				var result = Ext.JSON.decode(response.responseText, true);
				Datanium.GlobalData.qubeInfo.dimensions = Datanium.util.CommonUtils.pushElements2Array(
						result.dimensions, Datanium.GlobalData.qubeInfo.dimensions);
				Datanium.GlobalData.qubeInfo.measures = Datanium.util.CommonUtils.pushElements2Array(result.measures,
						Datanium.GlobalData.qubeInfo.measures);
				Datanium.util.CommonUtils.getCmpInActiveTab('elementPanel').fireEvent('refreshElementPanel');
			},
			failure : function() {
				mask.destroy();
			}
		};
		if(this.isValidMeasures()){
		Ext.Ajax.request(requestConfig);
		}else{
			Ext.MessageBox.alert("Alert","Sorry, you cannot add more than 10 measures!");
			mask.destroy();
		}

	},
	isValidMeasures : function() {
		var measures = Datanium.GlobalData.qubeInfo.measures;
		if(measures.length>=10){
			return false;
		}else{
			return true;
		}
	}

});<|endoftext|>


<commit_before>'use strict';
import React, { PropTypes as T } from 'react';
import { render } from 'react-dom';
import { Bar as BarChart } from 'react-chartjs-2';
import _ from 'lodash';

import makeTooltip from '../../utils/tooltip';

var SectionLicencas = React.createClass({
  displayName: 'SectionLicencas',

  propTypes: {
    data: T.object
  },

  render: function () {
    let data = this.props.data;
    let distritos = _.sortBy(this.props.data.distritos, 'data.licencas2016').reverse();

    let tooltipFn = makeTooltip(entryIndex => {
      let distrito = distritos[entryIndex];
      return (

{distrito.name}

geral {distrito.data.licencas2016}

max {distrito.data.max2016}

Vagas {distrito.data.max2016 - distrito.data.licencas2016}

      );
    });

    let chartData = {
      labels: distritos.map(o => o.name),
      datasets: [
        {
          data: distritos.map(o => o.data.licencas2016),
          backgroundColor: '#ccc'
        },
        {
          data: distritos.map(o => o.data.max2016 - o.data.licencas2016),
          backgroundColor: '#444'
        }
      ]
    };

    let chartOptions = {
      legend: {
        display: false
      },
      scales: {
        xAxes: [{
          gridLines: {
            display: false
          }
        }],
        yAxes: [{
          stacked: true,
          type: 'logarithmic',
          gridLines: {
            display: false
          },
          ticks: {
            callback: (tick, index, ticks) => {
              var remain = tick / (Math.pow(10, Math.floor(Math.log10(tick))));

              if (tick === 0) {
                return '0';
              } else if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === ticks.length - 1) {
                return tick;
              }
              return '';
            }
          }
        }]
      },
      tooltips: {
        enabled: false,
        mode: 'index',
        position: 'nearest',
        custom: tooltipFn
      }
    };

    return (

Portugal

Licenças e Contingentes

A prestação de serviços de transporte em táxi implica que o prestador detenha um alvará emitido pelo IMT (acesso à actividade) e, simultaneamente, possua uma licença atribuída pelo município (acesso ao mercado).

                {data.licencas2016}
                Total de táxis licenciados em Agosto de 2016.

                {data.max2016}
                Total dos contingentes em Agosto de 2016.

                {Math.round(data.licencasHab * 10) / 10}
                Licenças activas por 1000 Habitantes

            <BarChart data={chartData} options={chartOptions} />

Notas: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi interdum eros rhoncus metus ultricies

    );
  }
});

module.exports = SectionLicencas;
<commit_msg>Move chart render to function<commit_after>'use strict';
import React, { PropTypes as T } from 'react';
import { Bar as BarChart } from 'react-chartjs-2';
import _ from 'lodash';

import makeTooltip from '../../utils/tooltip';

var SectionLicencas = React.createClass({
  displayName: 'SectionLicencas',

  propTypes: {
    data: T.object
  },

  renderChart: function () {
    let distritos = _.sortBy(this.props.data.distritos, 'data.licencas2016').reverse();

    let tooltipFn = makeTooltip(entryIndex => {
      let distrito = distritos[entryIndex];
      return (

{distrito.name}

geral {distrito.data.licencas2016}

max {distrito.data.max2016}

Vagas {distrito.data.max2016 - distrito.data.licencas2016}

      );
    });

    let chartData = {
      labels: distritos.map(o => o.name),
      datasets: [
        {
          data: distritos.map(o => o.data.licencas2016),
          backgroundColor: '#ccc'
        },
        {
          data: distritos.map(o => o.data.max2016 - o.data.licencas2016),
          backgroundColor: '#444'
        }
      ]
    };

    let chartOptions = {
      legend: {
        display: false
      },
      scales: {
        xAxes: [{
          gridLines: {
            display: false
          }
        }],
        yAxes: [{
          stacked: true,
          type: 'logarithmic',
          gridLines: {
            display: false
          },
          ticks: {
            callback: (tick, index, ticks) => {
              var remain = tick / (Math.pow(10, Math.floor(Math.log10(tick))));

              if (tick === 0) {
                return '0';
              } else if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === ticks.length - 1) {
                return tick;
              }
              return '';
            }
          }
        }]
      },
      tooltips: {
        enabled: false,
        mode: 'index',
        position: 'nearest',
        custom: tooltipFn
      }
    };

    return <BarChart data={chartData} options={chartOptions} />;
  },

  render: function () {
    let data = this.props.data;

    return (

Portugal

Licenças e Contingentes

A prestação de serviços de transporte em táxi implica que o prestador detenha um alvará emitido pelo IMT (acesso à actividade) e, simultaneamente, possua uma licença atribuída pelo município (acesso ao mercado).

                {data.licencas2016}
                Total de táxis licenciados em Agosto de 2016.

                {data.max2016}
                Total dos contingentes em Agosto de 2016.

                {Math.round(data.licencasHab * 10) / 10}
                Licenças activas por 1000 Habitantes

            {this.renderChart()}

Notas: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi interdum eros rhoncus metus ultricies

    );
  }
});

module.exports = SectionLicencas;
<|endoftext|>


<commit_before>/**
Gather from the nearest source.
@param {Creep} creep
*/
function gatherFromClosestSource(creep) {
  var sources = creep.room.find(FIND_SOURCES);
  if (creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) {
    creep.moveTo(sources[0], {
      visualizePathStyle: {
        stroke: '#ffaa00'
      }
    });
  }
}

/**
Drop off energy at the closest structure that is not full of energy.
@param {Creep} creep
*/
function dropOffEnergyAtClosestStructure(creep) {
  var targets = creep.room.find(FIND_STRUCTURES, {
    filter: (structure) => {
      return (structure.structureType == STRUCTURE_EXTENSION ||
          structure.structureType == STRUCTURE_SPAWN ||
          structure.structureType == STRUCTURE_TOWER) &&
        structure.energy < structure.energyCapacity;
    }
  });
  if (targets.length > 0) {
    if (creep.transfer(targets[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
      creep.moveTo(targets[0], {
        visualizePathStyle: {
          stroke: '#ffffff'
        }
      });
    }
  }
}

/**
Find the biggest dropped pile of energy in the room and pick it up.
@param {Creep} creep
*/
function pickupBiggestEnergyPile(creep) {
  let droppedResources = creep.room.find(FIND_DROPPED_RESOURCES, {
    filter: {
      resourceType: RESOURCE_ENERGY
    }
  });
  if (droppedResources.length) {
    //determine which pile of resources is biggest
    let biggestResource = droppedResources[0];
    if (droppedResources.length > 1) {
      for (let i = 1; i < droppedResources.length; i++) {
        if (droppedResources[i].amount > biggestResource.amount) {
          biggestResource = droppedResources[i];
        }
      }
    }
    if (creep.pickup(biggestResource) == ERR_NOT_IN_RANGE) {
      creep.moveTo(biggestResource, {
        visualizePathStyle: {
          stroke: '#ffaa00'
        }
      });
    }
  }
}

/**
Upgrade this rooms controller.
@param {Creep} creep
*/
function upgradeRoomController(creep) {
  if (creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
    creep.moveTo(creep.room.controller, {
      visualizePathStyle: {
        stroke: '#ffffff'
      }
    });
  }
}

module.exports = {
  gatherFromClosestSource,
  dropOffEnergyAtClosestStructure,
  pickupBiggestEnergyPile,
  upgradeRoomController
};
<commit_msg>Upgrade logic now causes creeps to approach the room controller as they upgrade, until they are adjacent to it.<commit_after>/**
Gather from the nearest source.
@param {Creep} creep
*/
function gatherFromClosestSource(creep) {
  var sources = creep.room.find(FIND_SOURCES);
  if (creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) {
    creep.moveTo(sources[0], {
      visualizePathStyle: {
        stroke: '#ffaa00'
      }
    });
  }
}

/**
Drop off energy at the closest structure that is not full of energy.
@param {Creep} creep
*/
function dropOffEnergyAtClosestStructure(creep) {
  var targets = creep.room.find(FIND_STRUCTURES, {
    filter: (structure) => {
      return (structure.structureType == STRUCTURE_EXTENSION ||
          structure.structureType == STRUCTURE_SPAWN ||
          structure.structureType == STRUCTURE_TOWER) &&
        structure.energy < structure.energyCapacity;
    }
  });
  if (targets.length > 0) {
    if (creep.transfer(targets[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
      creep.moveTo(targets[0], {
        visualizePathStyle: {
          stroke: '#ffffff'
        }
      });
    }
  }
}

/**
Find the biggest dropped pile of energy in the room and pick it up.
@param {Creep} creep
*/
function pickupBiggestEnergyPile(creep) {
  let droppedResources = creep.room.find(FIND_DROPPED_RESOURCES, {
    filter: {
      resourceType: RESOURCE_ENERGY
    }
  });
  if (droppedResources.length) {
    //determine which pile of resources is biggest
    let biggestResource = droppedResources[0];
    if (droppedResources.length > 1) {
      for (let i = 1; i < droppedResources.length; i++) {
        if (droppedResources[i].amount > biggestResource.amount) {
          biggestResource = droppedResources[i];
        }
      }
    }
    if (creep.pickup(biggestResource) == ERR_NOT_IN_RANGE) {
      creep.moveTo(biggestResource, {
        visualizePathStyle: {
          stroke: '#ffaa00'
        }
      });
    }
  }
}

/**
Upgrade this rooms controller.
@param {Creep} creep
*/
function upgradeRoomController(creep) {
  creep.upgradeController(creep.room.controller);
  if (!creep.pos.isNearTo(creep.room.controller)) {
    creep.moveTo(creep.room.controller, {
      visualizePathStyle: {
        stroke: '#ffffff'
      }
    });
  }
}

module.exports = {
  gatherFromClosestSource,
  dropOffEnergyAtClosestStructure,
  pickupBiggestEnergyPile,
  upgradeRoomController
};
<|endoftext|>


<commit_before>import Component from '@glimmer/component';
import {
    ICON_EXTENSIONS,
    ICON_MIME_TYPES,
    IMAGE_EXTENSIONS,
    IMAGE_MIME_TYPES
} from 'ghost-admin/components/gh-image-uploader';
import {action} from '@ember/object';
import {htmlSafe} from '@ember/template';
import {inject as service} from '@ember/service';
import {task} from 'ember-concurrency-decorators';
import {timeout} from 'ember-concurrency';

export default class DesignTabGeneralSettingsComponent extends Component {
    @service config;
    @service ghostPaths;
    @service settings;

    iconExtensions = ICON_EXTENSIONS;
    iconMimeTypes = ICON_MIME_TYPES;
    imageExtensions = IMAGE_EXTENSIONS;
    imageMimeTypes = IMAGE_MIME_TYPES;

    get accentColor() {
        const color = this.settings.get('accentColor');
        if (color && color[0] === '#') {
            return color.slice(1);
        }
        return color;
    }

    get accentColorPickerValue() {
        return this.settings.get('accentColor') || '#ffffff';
    }

    get accentColorBgStyle() {
        return htmlSafe(`background-color: ${this.accentColorPickerValue}`);
    }

    get previewData() {
        const params = new URLSearchParams();

        params.append('c', this.accentColorPickerValue);
        params.append('icon', this.settings.get('icon'));
        params.append('logo', this.settings.get('logo'));
        params.append('cover', this.settings.get('coverImage'));

        return params.toString();
    }

    willDestroy() {
        super.willDestroy?.(...arguments);
        this.settings.errors.remove('accentColor');
        this.settings.rollbackAttributes();
    }

    @action
    triggerFileDialog({target}) {
        target.closest('.gh-setting-action')?.querySelector('input[type="file"]')?.click();
    }

    @action
    async imageUploaded(property, results) {
        if (results[0]) {
            this.settings.set(property, results[0].url);
            this.args.updatePreview();
        }
    }

    @action
    blurElement(event) {
        event.preventDefault();
        event.target.blur();
    }

    @action
    async updateSetting(setting, value) {
        this.settings.set(setting, value);
        await this.settings.validate({property: setting});
        this.args.updatePreview();
    }

    @action
    async updateAccentColor(event) {
        let newColor = event.target.value;
        const oldColor = this.settings.get('accentColor');

        // reset errors and validation
        this.settings.errors.remove('accentColor');
        this.settings.hasValidated.removeObject('accentColor');

        if (newColor === '') {
            if (newColor === oldColor) {
                return;
            }

            // Don't allow empty accent color
            this.settings.errors.add('accentColor', 'Please select an accent color');
            this.settings.hasValidated.pushObject('accentColor');
            return;
        }

        // accentColor will be null unless the user has input something
        if (!newColor) {
            newColor = oldColor;
        }

        if (newColor[0] !== '#') {
            newColor = `#${newColor}`;
        }

        if (newColor.match(/#[0-9A-Fa-f]{6}$/)) {
            if (newColor === oldColor) {
                return;
            }

            this.settings.set('accentColor', newColor);
            this.args.updatePreview();
        } else {
            this.settings.errors.add('accentColor', 'Please enter a color in hex format');
            this.settings.hasValidated.pushObject('accentColor');
        }
    }

    @task({restartable: true})
    *debounceUpdateAccentColor(event) {
        yield timeout(500);
        this.updateAccentColor(event);
    }
}
<commit_msg>Fixed unsaved general settings being lost when switching to theme tab<commit_after>import Component from '@glimmer/component';
import {
    ICON_EXTENSIONS,
    ICON_MIME_TYPES,
    IMAGE_EXTENSIONS,
    IMAGE_MIME_TYPES
} from 'ghost-admin/components/gh-image-uploader';
import {action} from '@ember/object';
import {htmlSafe} from '@ember/template';
import {inject as service} from '@ember/service';
import {task} from 'ember-concurrency-decorators';
import {timeout} from 'ember-concurrency';

export default class DesignTabGeneralSettingsComponent extends Component {
    @service config;
    @service ghostPaths;
    @service settings;

    iconExtensions = ICON_EXTENSIONS;
    iconMimeTypes = ICON_MIME_TYPES;
    imageExtensions = IMAGE_EXTENSIONS;
    imageMimeTypes = IMAGE_MIME_TYPES;

    get accentColor() {
        const color = this.settings.get('accentColor');
        if (color && color[0] === '#') {
            return color.slice(1);
        }
        return color;
    }

    get accentColorPickerValue() {
        return this.settings.get('accentColor') || '#ffffff';
    }

    get accentColorBgStyle() {
        return htmlSafe(`background-color: ${this.accentColorPickerValue}`);
    }

    get previewData() {
        const params = new URLSearchParams();

        params.append('c', this.accentColorPickerValue);
        params.append('icon', this.settings.get('icon'));
        params.append('logo', this.settings.get('logo'));
        params.append('cover', this.settings.get('coverImage'));

        return params.toString();
    }

    willDestroy() {
        super.willDestroy?.(...arguments);
        this.settings.errors.remove('accentColor');
    }

    @action
    triggerFileDialog({target}) {
        target.closest('.gh-setting-action')?.querySelector('input[type="file"]')?.click();
    }

    @action
    async imageUploaded(property, results) {
        if (results[0]) {
            this.settings.set(property, results[0].url);
            this.args.updatePreview();
        }
    }

    @action
    blurElement(event) {
        event.preventDefault();
        event.target.blur();
    }

    @action
    async updateSetting(setting, value) {
        this.settings.set(setting, value);
        await this.settings.validate({property: setting});
        this.args.updatePreview();
    }

    @action
    async updateAccentColor(event) {
        let newColor = event.target.value;
        const oldColor = this.settings.get('accentColor');

        // reset errors and validation
        this.settings.errors.remove('accentColor');
        this.settings.hasValidated.removeObject('accentColor');

        if (newColor === '') {
            if (newColor === oldColor) {
                return;
            }

            // Don't allow empty accent color
            this.settings.errors.add('accentColor', 'Please select an accent color');
            this.settings.hasValidated.pushObject('accentColor');
            return;
        }

        // accentColor will be null unless the user has input something
        if (!newColor) {
            newColor = oldColor;
        }

        if (newColor[0] !== '#') {
            newColor = `#${newColor}`;
        }

        if (newColor.match(/#[0-9A-Fa-f]{6}$/)) {
            if (newColor === oldColor) {
                return;
            }

            this.settings.set('accentColor', newColor);
            this.args.updatePreview();
        } else {
            this.settings.errors.add('accentColor', 'Please enter a color in hex format');
            this.settings.hasValidated.pushObject('accentColor');
        }
    }

    @task({restartable: true})
    *debounceUpdateAccentColor(event) {
        yield timeout(500);
        this.updateAccentColor(event);
    }
}
<|endoftext|>


<commit_before>'use strict';

var bench = require('./bench');
var co = require('../lib/utils/co');
var crypto = require('../lib/crypto/crypto');
var WalletDB = require('../lib/wallet/walletdb');
var MTX = require('../lib/primitives/mtx');
var Outpoint = require('../lib/primitives/outpoint');
var walletdb, runBench;

function dummy() {
  var hash = crypto.randomBytes(32).toString('hex');
  return new Outpoint(hash, 0);
}

walletdb = new WalletDB({
  name: 'wallet-test',
  db: 'memory',
  resolution: false,
  verify: false
});

runBench = co(function* runBench() {
  var i, j, wallet, addrs, jobs, end;
  var result, tx, options;

  // Open and Create
  yield walletdb.open();
  wallet = yield walletdb.create();
  addrs = [];

  // Accounts
  jobs = [];
  for (i = 0; i < 1000; i++)
    jobs.push(wallet.createAccount({}));

  end = bench('accounts');
  result = yield Promise.all(jobs);
  end(1000);

  for (i = 0; i < result.length; i++)
    addrs.push(result[i].receive.getAddress());

  // Addresses
  jobs = [];
  for (i = 0; i < 1000; i++) {
    for (j = 0; j < 10; j++)
      jobs.push(wallet.createReceive(i));
  }

  end = bench('addrs');
  result = yield Promise.all(jobs);
  end(1000 * 10);

  for (i = 0; i < result.length; i++)
    addrs.push(result[i].getAddress());

  // TX deposit
  jobs = [];
  for (i = 0; i < 10000; i++) {
    tx = new MTX();
    tx.addOutpoint(dummy());
    tx.addOutput(addrs[(i + 0) % addrs.length], 50460);
    tx.addOutput(addrs[(i + 1) % addrs.length], 50460);
    tx.addOutput(addrs[(i + 2) % addrs.length], 50460);
    tx.addOutput(addrs[(i + 3) % addrs.length], 50460);
    tx = tx.toTX();

    jobs.push(walletdb.addTX(tx));
  }

  end = bench('deposit');
  result = yield Promise.all(jobs);
  end(10000);

  // TX redemption
  jobs = [];
  for (i = 0; i < 10000; i++) {
    tx = new MTX();
    tx.addTX(tx, 0);
    tx.addTX(tx, 1);
    tx.addTX(tx, 2);
    tx.addTX(tx, 3);
    tx.addOutput(addrs[(i + 0) % addrs.length], 50460);
    tx.addOutput(addrs[(i + 1) % addrs.length], 50460);
    tx.addOutput(addrs[(i + 2) % addrs.length], 50460);
    tx.addOutput(addrs[(i + 3) % addrs.length], 50460);
    tx = tx.toTX();

    jobs.push(walletdb.addTX(tx));
  }

  end = bench('redemption');
  result = yield Promise.all(jobs);
  end(10000);

  // Balance
  end = bench('balance');
  result = yield wallet.getBalance();
  end(1);

  // Coins
  end = bench('coins');
  result = yield wallet.getCoins();
  end(1);

  // Create
  end = bench('create');
  options = {
    rate: 10000,
    outputs: [{
      value: 50460,
      address: addrs[0]
    }]
  };
  yield wallet.createTX(options);
  end(1);
});

runBench().then(process.exit);
<commit_msg>bench: fix walletdb benchmarks.<commit_after>'use strict';

var bench = require('./bench');
var co = require('../lib/utils/co');
var crypto = require('../lib/crypto/crypto');
var WalletDB = require('../lib/wallet/walletdb');
var MTX = require('../lib/primitives/mtx');
var Outpoint = require('../lib/primitives/outpoint');
var walletdb, runBench;

function dummy() {
  var hash = crypto.randomBytes(32).toString('hex');
  return new Outpoint(hash, 0);
}

walletdb = new WalletDB({
  name: 'wallet-test',
  db: 'memory',
  resolution: false,
  verify: false
});

runBench = co(function* runBench() {
  var i, j, wallet, addrs, jobs, end;
  var result, tx, mtx, options;

  // Open and Create
  yield walletdb.open();
  wallet = yield walletdb.create();
  addrs = [];

  // Accounts
  jobs = [];
  for (i = 0; i < 1000; i++)
    jobs.push(wallet.createAccount({}));

  end = bench('accounts');
  result = yield Promise.all(jobs);
  end(1000);

  for (i = 0; i < result.length; i++)
    addrs.push(result[i].receive.getAddress());

  // Keys
  jobs = [];
  for (i = 0; i < 1000; i++) {
    for (j = 0; j < 10; j++)
      jobs.push(wallet.createReceive(i));
  }

  end = bench('keys');
  result = yield Promise.all(jobs);
  end(1000 * 10);

  for (i = 0; i < result.length; i++)
    addrs.push(result[i].getAddress());

  // TX deposit
  jobs = [];
  for (i = 0; i < 10000; i++) {
    mtx = new MTX();
    mtx.addOutpoint(dummy());
    mtx.addOutput(addrs[(i + 0) % addrs.length], 50460);
    mtx.addOutput(addrs[(i + 1) % addrs.length], 50460);
    mtx.addOutput(addrs[(i + 2) % addrs.length], 50460);
    mtx.addOutput(addrs[(i + 3) % addrs.length], 50460);
    tx = mtx.toTX();

    jobs.push(walletdb.addTX(tx));
  }

  end = bench('deposit');
  result = yield Promise.all(jobs);
  end(10000);

  // TX redemption
  jobs = [];
  for (i = 0; i < 10000; i++) {
    mtx = new MTX();
    mtx.addTX(tx, 0);
    mtx.addTX(tx, 1);
    mtx.addTX(tx, 2);
    mtx.addTX(tx, 3);
    mtx.addOutput(addrs[(i + 0) % addrs.length], 50460);
    mtx.addOutput(addrs[(i + 1) % addrs.length], 50460);
    mtx.addOutput(addrs[(i + 2) % addrs.length], 50460);
    mtx.addOutput(addrs[(i + 3) % addrs.length], 50460);
    tx = mtx.toTX();

    jobs.push(walletdb.addTX(tx));
  }

  end = bench('redemption');
  result = yield Promise.all(jobs);
  end(10000);

  // Balance
  end = bench('balance');
  result = yield wallet.getBalance();
  end(1);

  // Coins
  end = bench('coins');
  result = yield wallet.getCoins();
  end(1);

  // Create
  end = bench('create');
  options = {
    rate: 10000,
    outputs: [{
      value: 50460,
      address: addrs[0]
    }]
  };
  yield wallet.createTX(options);
  end(1);
});

runBench().then(process.exit);
<|endoftext|>