<commit_before>"use strict";
const fs = require('fs');
const glob = require("glob");
const account = require('./account');
const handlerTypes = ['update', 'insert', 'delete', 'validate'];
const path = require('path');

module.exports = function(args) {
  if (!args.app && !args.host) {
    return false;
  } else {
    account.login({app: args.app, host: args.host}).then((db) => {
      if (!args.code && !args.files || args.code && args.files) {
        return Promise.all([
          deployFiles(db, args.fileDir, args.fileGlob),
          deployCode(db, args.codeDir)
        ]);
      } else if (args.code) {
        return deployCode(db, args.codeDir);
      } else if (args.files) {
        return deployFiles(db, args.fileDir, args.fileGlob);
      }
    }).catch((e) => console.error(e));

  }

  return true;
};

function deployFiles(db, cwd, pattern) {
  return new Promise((resolve, reject) => {
    glob(pattern, {nodir: true, cwd}, (er, files) => {
      if (er)
        reject(er);
      else
        resolve(uploadFiles(db, files, cwd));
    });
  }).then((result) => {
    if (result && result.length > 0) {
      console.log('Files upload completed.');
    } else {
      console.error('No files found.');
    }
  })
}

function deployCode(db, codePath) {
  return readDirectory(codePath).then((fileNames) => {
    return Promise.all(fileNames.map((fileName) => {
      return readStat(`${codePath}/${fileName}`).then((stat) => {
        if (stat.isDirectory()) {
          return uploadHandler(db, fileName, codePath);
        } else {
          return uploadCode(db, fileName, codePath);
        }
      });
    }));
  }).then(() => {
    console.log('Code deployment completed.');
  }).catch((e) => {
    if (e.errno === -4058 || e.errno === -2) {
      console.error('Error: Code folder not found.')
    }
  });
}

function readStat(filePath) {
  return new Promise((resolve, reject) => {
    fs.stat(filePath, (err, stat) => {
      err ? reject(err) : resolve(stat);
    })
  });
}

function readDirectory(filePath) {
  return new Promise((resolve, reject) => {
    fs.readdir(filePath, (err, fileNames) => {
      err ? reject(err) : resolve(fileNames);
    })
  })
}

function readFile(filePath) {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, 'utf-8', (err, file) => {
      err ? reject(err) : resolve(file);
    })
  });
}

function uploadHandler(db, directoryName, codePath) {
  let bucket = directoryName;

  if (!db[bucket])
    return;

  return readDirectory(`${codePath}/${directoryName}`).then((fileNames) => {
    return Promise.all(fileNames.map((fileName) => {
      let handlerType = fileName.replace(/.js$/, '');

      if (handlerTypes.indexOf(handlerType) == -1)
        return;

      return readFile(`${codePath}/${directoryName}/${fileName}`)
          .then((file) => db.code.saveCode(bucket, handlerType, file))
          .then(() => console.log(`${handlerType} handler for ${bucket} deployed.`));
    }));
  });
}

function uploadCode(db, name, codePath) {
  let moduleName = name.replace(/.js$/, '');
  return readFile(`${codePath}/${name}`).then((file) => {
    return db.code.saveCode(moduleName, 'module', file);
  }).then(() => {
    console.log(`Module ${moduleName} deployed.`);
  });
}

function uploadFiles(db, files, cwd) {
  let index = 0;

  var uploads = [];
  for (let i = 0; i < 10 && i < files.length-1; ++i) {
    uploads.push(upload());
  }

  return Promise.all(uploads);

  function upload() {
    if (index < files.length) {
      console.log(`Uploading file ${(index + 1)} of ${files.length}`);
      var file = files[index++];
      return uploadFile(db, file, cwd).then(upload);
    }
  }
}

function uploadFile(db, filePath, cwd) {
  let fullFilePath = path.join(cwd, filePath);

  let stat = fs.statSync(fullFilePath);

  var file = new db.File({path: `/www/${filePath}`, data: fs.createReadStream(fullFilePath), size: stat.size, type: 'stream'});
  return file.upload({ force: true }).catch(function(e) {
    console.error(`Failed to upload file ${filePath}: ${e.message}`);
  });
}

<commit_msg>using node path module<commit_after>"use strict";
const fs = require('fs');
const glob = require("glob");
const account = require('./account');
const handlerTypes = ['update', 'insert', 'delete', 'validate'];
const path = require('path');

module.exports = function(args) {
  if (!args.app && !args.host) {
    return false;
  } else {
    account.login({app: args.app, host: args.host}).then((db) => {
      if (!args.code && !args.files || args.code && args.files) {
        return Promise.all([
          deployFiles(db, args.fileDir, args.fileGlob),
          deployCode(db, args.codeDir)
        ]);
      } else if (args.code) {
        return deployCode(db, args.codeDir);
      } else if (args.files) {
        return deployFiles(db, args.fileDir, args.fileGlob);
      }
    }).catch((e) => console.error(e));

  }

  return true;
};

function deployFiles(db, cwd, pattern) {
  return new Promise((resolve, reject) => {
    glob(pattern, {nodir: true, cwd}, (er, files) => {
      if (er)
        reject(er);
      else
        resolve(uploadFiles(db, files, cwd));
    });
  }).then((result) => {
    if (result && result.length > 0) {
      console.log('Files upload completed.');
    } else {
      console.error('No files found.');
    }
  })
}

function deployCode(db, codePath) {
  return readDirectory(codePath).then((fileNames) => {
    return Promise.all(fileNames.map((fileName) => {
      return readStat(path.join(codePath, fileName)).then((stat) => {
        if (stat.isDirectory()) {
          return uploadHandler(db, fileName, codePath);
        } else {
          return uploadCode(db, fileName, codePath);
        }
      });
    }));
  }).then(() => {
    console.log('Code deployment completed.');
  }).catch((e) => {
    console.error(`Failed to deploy code: ${e.message}`);
  });
}

function readStat(filePath) {
  return new Promise((resolve, reject) => {
    fs.stat(filePath, (err, stat) => {
      err ? reject(err) : resolve(stat);
    })
  });
}

function readDirectory(filePath) {
  return new Promise((resolve, reject) => {
    fs.readdir(filePath, (err, fileNames) => {
      err ? reject(err) : resolve(fileNames);
    })
  })
}

function readFile(filePath) {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, 'utf-8', (err, file) => {
      err ? reject(err) : resolve(file);
    })
  });
}

function uploadHandler(db, directoryName, codePath) {
  let bucket = directoryName;

  if (!db[bucket])
    return;

  return readDirectory(path.join(codePath,directoryName)).then((fileNames) => {
    return Promise.all(fileNames.map((fileName) => {
      let handlerType = fileName.replace(/.js$/, '');

      if (handlerTypes.indexOf(handlerType) == -1)
        return;

      return readFile(path.join(codePath, directoryName, fileName))
          .then((file) => db.code.saveCode(bucket, handlerType, file))
          .then(() => console.log(`${handlerType} handler for ${bucket} deployed.`));
    }));
  });
}

function uploadCode(db, name, codePath) {
  let moduleName = name.replace(/.js$/, '');
  return readFile(path.join(codePath, name)).then((file) => {
    return db.code.saveCode(moduleName, 'module', file);
  }).then(() => {
    console.log(`Module ${moduleName} deployed.`);
  });
}

function uploadFiles(db, files, cwd) {
  let index = 0;

  var uploads = [];
  for (let i = 0; i < 10 && i < files.length-1; ++i) {
    uploads.push(upload());
  }

  return Promise.all(uploads);

  function upload() {
    if (index < files.length) {
      console.log(`Uploading file ${(index + 1)} of ${files.length}`);
      var file = files[index++];
      return uploadFile(db, file, cwd).then(upload);
    }
  }
}

function uploadFile(db, filePath, cwd) {
  let fullFilePath = path.join(cwd, filePath);

  let stat = fs.statSync(fullFilePath);

  var file = new db.File({path: `/www/${filePath}`, data: fs.createReadStream(fullFilePath), size: stat.size, type: 'stream'});
  return file.upload({ force: true }).catch(function(e) {
    console.error(`Failed to upload file ${filePath}: ${e.message}`);
  });
}

<|endoftext|>


<commit_before>jQuery(document).ready(function($) {
    hashtagger(window.location.hash, '.firstactive');
    $(window).bind('hashchange', function() {
        hashtagger(window.location.hash);
    });
    pooraccordion();
});

function pooraccordion(animate) {
    animate = typeof animate !== 'undefined' ? animate : true;
    jQuery('.poor-accordion').hide().prev()
        .css('cursor', 'pointer')
        .click(function() {
            if (true == animate) {
                jQuery(this).next().slideToggle();
            } else {
                jQuery(this).next().toggle();
            }
        }
    );
}

function hashtagger (hash, exception) {
    //hashspliter: prefill "GET parameter"-like value string to inputs
    var gets = hash.slice('1').split('&');
    if (gets.indexOf('=') > -1) {
        for (var i = 0; i < gets.length; i++) {
<<<<<<< HEAD
            var getkeyparam = gets[i].split('=')
            jQuery('#' + getkeyparam[0]).val( getkeyparam[1] )
=======
            var getkeyparam = gets[i].split('=');
            jQuery('#' + getkeyparam[0]).val( getkeyparam[1] );
>>>>>>> master
        }
    } else {
        // poor mans tab
        jQuery('.hashtagger > div, .hashtabber').not( exception ).hide();
        jQuery(hash).show();
        jQuery(hash).click(); // to use with jQuery UI Accordion etc

        // special actions
        switch (hash) {
            case "#alert": // example
                alert('fork me at github.com/klml/usefulclassroomphrases');
            break;
            default:
            case "#":

            break;
        }
    }
}
<commit_msg>changed $ to jQuery<commit_after>jQuery(document).ready(function($) {
    hashtagger(window.location.hash, '.firstactive');
    $(window).bind('hashchange', function() {
        hashtagger(window.location.hash);
    });
    pooraccordion();
});

function pooraccordion(animate) {
    animate = typeof animate !== 'undefined' ? animate : true;
    jQuery('.poor-accordion').hide().prev()
        .css('cursor', 'pointer')
        .click(function() {
            if (true == animate) {
                jQuery(this).next().slideToggle();
            } else {
                jQuery(this).next().toggle();
            }
        }
    );
}

function hashtagger (hash, exception) {
    //hashspliter: prefill "GET parameter"-like value string to inputs
    var gets = hash.slice('1').split('&');
    if (gets.indexOf('=') > -1) {
        for (var i = 0; i < gets.length; i++) {
            var getkeyparam = gets[i].split('=');
            jQuery('#' + getkeyparam[0]).val( getkeyparam[1] );
        }
    } else {
        // poor mans tab
        jQuery('.hashtagger > div, .hashtabber').not( exception ).hide();
        jQuery(hash).show();
        jQuery(hash).click(); // to use with jQuery UI Accordion etc

        // special actions
        switch (hash) {
            case "#alert": // example
                alert('fork me at github.com/klml/usefulclassroomphrases');
            break;
            default:
            case "#":

            break;
        }
    }
}
<|endoftext|>


<commit_before>var maxValue = 10;
var autoDecreasePerSecond = 0.5;
var maxWidth = 240;

var constants = require('../GameConsts');

function FunBar() {
    this.element = new createjs.Container();
    this.element.x = constants.GAME_WIDTH / 2 - 125;
    this.current = 0;
    this.boarder = new createjs.Shape();
    this.boarder.graphics.beginFill("#444").drawRect(0, 0, 250, 50);
    this.element.addChild(this.boarder);

    this.fill = new createjs.Shape();
    this.drawFill();
    this.element.addChild(this.fill);
}

FunBar.prototype.registerEvents = function(emitter) {
    emitter.on('hit', this.onHit.bind(this));
    emitter.on('combo', this.onCombo.bind(this));
};

FunBar.prototype.onHit = function(event) {
    if (event.hitTarget == 'player') {
        return;
    }

    this.current++;
    this.current = Math.min(this.current, maxValue);
};

FunBar.prototype.onCombo = function(event) {
    this.current += event.level;
    this.current = Math.min(this.current, maxValue);
};

FunBar.prototype.tick = function(event) {
    if (this.current > 0) {
        this.current -= (event.delta / 1000) * autoDecreasePerSecond;
        this.current = Math.max(this.current, 0);
        this.drawFill();
    }
};

FunBar.prototype.drawFill = function() {
    this.fill.graphics.clear().beginFill("#aaa").drawRect(5, 5, (this.current / maxValue) * maxWidth, 40);
};

module.exports = FunBar;
<commit_msg>we can haz fun bar juice<commit_after>var maxValue = 10;
var autoDecreasePerSecond = 0.5;
var maxWidth = 240;

var constants = require('../GameConsts');

function FunBar() {
    this.element = new createjs.Container();
    this.element.x = constants.GAME_WIDTH / 2 - 125;
    this.current = 0;
	this.lastIncrease = 0;
    this.boarder = new createjs.Shape();
    this.boarder.graphics.beginFill("#444").drawRect(0, 0, 250, 50);
    this.element.addChild(this.boarder);

    this.fill = new createjs.Shape();
    this.drawFill();
    this.element.addChild(this.fill);
}

FunBar.prototype.registerEvents = function(emitter) {
    emitter.on('hit', this.onHit.bind(this));
    emitter.on('combo', this.onCombo.bind(this));
};

FunBar.prototype.onHit = function(event) {
    if (event.hitTarget == 'player') {
        return;
    }

	this.increase(1);
};

FunBar.prototype.onCombo = function(event) {
    this.increase(event.level);
};

FunBar.prototype.increase = function(value) {
	this.current += value;
	this.current = Math.min(this.current, maxValue);
	this.lastIncrease = new Date().getTime();
};

FunBar.prototype.tick = function(event) {
    if (this.current > 0) {
        this.current -= (event.delta / 1000) * autoDecreasePerSecond;
        this.current = Math.max(this.current, 0);

		var lastIncreaseDiff = event.timeStamp - this.lastIncrease;
		if (lastIncreaseDiff < 1000) {
			this.drawFill('rgb(' + Math.round(255 - 85 / 1000 * lastIncreaseDiff) + ', ' + Math.round(170 / 1000 * lastIncreaseDiff) + ', ' + Math.round(255 - 85 / 1000 * lastIncreaseDiff) + ')');
		} else {
			this.drawFill();
		}
    }
};

FunBar.prototype.drawFill = function(color) {
	color = (color === undefined) ? '#aaa' : color;
    this.fill.graphics.clear().beginFill(color).drawRect(5, 5, (this.current / maxValue) * maxWidth, 40);
};

module.exports = FunBar;
<|endoftext|>


<commit_before>/**
 * Created by King Lee on 2015/1/5.
 */
var handlerMgr = require("./../handlerMgr");
var consts = require("../../../util/consts");
var pomelo = require('pomelo');
var util = require('../../../util/util');
var async = require('async');
var rival_vs_json = require('../../../../config/rival_vs');
var rival_vs_title_json = require('../../../../config/rival_vs_title');

var get_rival = function(strength){
    for(var v in rival_vs_json){
        if(strength == rival_vs_json[v].level){
            return rival_vs_json[v];
        }
    }
    return rival_vs_json[0];
};

var get_extra_info = function(player_info_somebody,score){
    for(var v in rival_vs_title_json){
        if(rival_vs_title_json[v].score <= score){
            player_info_somebody.degree_title = rival_vs_title_json[v].title;
            player_info_somebody.degree = rival_vs_title_json[v].grade;
            player_info_somebody.buff_desc = rival_vs_title_json[v].buff_desc;
            player_info_somebody.buff_data = rival_vs_title_json[v].buff_data;
        }
    }
    var degree_next = player_info_somebody.degree < rival_vs_title_json.length ? player_info_somebody.degree + 1 : rival_vs_title_json.length;
    player_info_somebody.score_next = rival_vs_title_json[degree_next - 1].score;
};

var copy_rival_info = function(player_info_somebody,strength){
    var rival_info = get_rival(strength);
    player_info_somebody.level = rival_info.level;
    player_info_somebody.name = rival_info.name;
    player_info_somebody.from = rival_info.from;
    player_info_somebody.car = rival_info.car;
    player_info_somebody.car_lv = rival_info.car_lv;
    player_info_somebody.driver = rival_info.driver;
    player_info_somebody.driver_lv = rival_info.driver_lv;
    player_info_somebody.strength = rival_info.strength;
    player_info_somebody.score = rival_info.score;
    player_info_somebody.drift = rival_info.drift;
    player_info_somebody.weight = rival_info.weight;
    player_info_somebody.attack = rival_info.attack;
    player_info_somebody.speed_cruising = rival_info.speed_cruising;
    player_info_somebody.speed_duel = rival_info.speed_duel;
    player_info_somebody.speed_boost = rival_info.speed_boost;
    player_info_somebody.accel = rival_info.accel;
    player_info_somebody.accel_duel = rival_info.accel_duel;
    player_info_somebody.accel_boost = rival_info.accel_boost;
    player_info_somebody.distance_duel = rival_info.distance_duel;
    player_info_somebody.distance_wait = rival_info.distance_wait;
    player_info_somebody.distance_boost = rival_info.distance_boost;
    player_info_somebody.distance_giveup = rival_info.distance_giveup;
    player_info_somebody.time_giveup = rival_info.time_giveup;
    player_info_somebody.time_boost = rival_info.time_boost;
    player_info_somebody.cdtime_boost = rival_info.cdtime_boost;
    player_info_somebody.evade_rate = rival_info.evade_rate;
    player_info_somebody.coin = rival_info.coin;
};

var get_player_info = function(device_guid,strength_min,strength_max,max_count_to_be_choose,player_info_array,callback){
    strength_min = (strength_min < 250 ? 250 : strength_min);
    strength_max = (strength_max > 1200 ? 1200 : strength_max);
    var random_val = 0;
    var cur_loop_count = 0;
    var max_loop_count = 100;
    var rank_pvp_wrapper = pomelo.app.get("rank_pvp_wrapper");
    rank_pvp_wrapper.get_player_by_strength(strength_min,strength_max,max_count_to_be_choose,function(reply){
        if(4 <= reply.length){
            var players = reply;
            var is_repeat = true;
            do
            {
                //  random players
                random_val = Math.floor(Math.random()*players.length);
                var player = players[random_val];

                //  can not be myself
                if(player == device_guid){
                    ++cur_loop_count;
                    continue;
                }
                //  can not be the player have chose
                var find = false;
                for(var i = 0; i < player_info_array.length; ++i){
                    if(player == player_info_array[i].device_guid){
                        find = true;
                        break;
                    }
                }
                if(find){
                    ++cur_loop_count;
                    continue;
                }
                is_repeat = false;
                ++cur_loop_count;
            }while(is_repeat && cur_loop_count < max_loop_count);
            rank_pvp_wrapper.get_rank_info(players[random_val],function(reply){
                var rank_info = {};
                if(reply){
                    rank_info = JSON.parse(reply);
                }
                var player_info_somebody = new Object();
                //  random json table
                random_val = Math.floor(strength_min + Math.random()*(strength_max - strength_min));
                copy_rival_info(player_info_somebody,random_val);
                player_info_somebody.device_guid = rank_info.device_guid;
                player_info_somebody.name = rank_info.nickname;
                player_info_somebody.from = rank_info.area;
                player_info_somebody.car = rank_info.car?rank_info.car:28;
                player_info_somebody.car_lv = rank_info.car_lv;
                player_info_somebody.driver = rank_info.racer;
                player_info_somebody.driver_lv = rank_info.racer_lv;
                player_info_somebody.total_win = rank_info.total_win;
                player_info_somebody.is_robot = 0;
                get_extra_info(player_info_somebody,rank_info.score);
                player_info_array.push(player_info_somebody);
                //  mask word
                pomelo.app.get('mask_word_wrapper').analysis(player_info_somebody.nickname,function(nickname_new){
                    player_info_somebody.nickname = nickname_new;
                    callback(null,player_info_array);
                });
            });
        }
        else{
            var is_repeat = true;
            do
            {
                random_val = Math.floor(strength_min + Math.random()*(strength_max - strength_min));
                //  can not be the player have chose
                var find = false;
                for(var i = 0; i < player_info_array.length; ++i){
                    if(random_val == player_info_array[i].strength){
                        find = true;
                        break;
                    }
                }
                if(find){
                    ++cur_loop_count;
                    continue;
                }
                is_repeat = false;
                ++cur_loop_count;
            }while(is_repeat && cur_loop_count < max_loop_count);
            var player_info_somebody = new Object();
            copy_rival_info(player_info_somebody,random_val);
            player_info_somebody.is_robot = 1;
            player_info_array.push(player_info_somebody);
            get_extra_info(player_info_somebody,player_info_somebody.score);
            callback(null,player_info_array);
        }
    });
};

handlerMgr.handler(consts.TYPE_MSG.TYPE_GET_RIVAL_FOR_PVP, function(msg, session, next) {
    var channel = msg.channel;
    var version = msg.version;
    var device_guid = msg.deviceid;
    var strength = parseInt(msg.strength);
    var random_val = Math.floor(Math.random()*100);
    var max_count_to_be_choose = 100;
    var strength_min = strength;
    var strength_max = strength;
    var player_info_array = [];
    var pvp_switch = 1;
    var activity = {};
    var activity_wrapper = pomelo.app.get('activity_wrapper');
    activity_wrapper.get(channel,version,function(activity_json) {
        for (var v in activity_json) {
            if (consts.TYPE_ACTIVITY.TYPE_PVP == parseInt(activity_json[v].type)) {
                activity = activity_json[v];
            }
        }
        //  calc stage
        var stage_array = activity.stage;
        pvp_switch = activity.switch;
        random_val = Math.floor(Math.random()* stage_array.length);
        async.waterfall([
                function (callback) {
                    //  player 1
                    if(random_val <= 80){
                        strength_min = strength - 100;
                        strength_max = strength + 30;
                    }else{
                        strength_min = strength + 50;
                        strength_max = strength + 150;
                    }
                    get_player_info(device_guid,strength_min,strength_max,max_count_to_be_choose,player_info_array,callback);
                },
                function (player_info_array,callback) {
                    strength_min = strength - 100;
                    strength_max = strength + 30;
                    get_player_info(device_guid,strength_min,strength_max,max_count_to_be_choose,player_info_array,callback);
                },
                function (player_info_array,callback) {
                    strength_min = strength - 100;
                    strength_max = strength + 30;
                    get_player_info(device_guid,strength_min,strength_max,max_count_to_be_choose,player_info_array,callback);
                }
            ],
            function (err, player_info_array) {
                //  get stage distance
                var max_strength = 0;
                for(var i = 0; i < player_info_array.length; ++i){
                    if(max_strength < player_info_array[i].strength){
                        max_strength = player_info_array[i].strength;
                    }
                }
                var stage_distance = Math.floor(max_strength / 6 * 100);
                next(null, {
                    code: 0,
                    msg_id : msg.msg_id,
                    flowid : msg.flowid,
                    time:Math.floor(Date.now()/1000),
                    stage:stage_array[random_val],
                    stage_distance:stage_distance,
                    player_info_array:player_info_array,
                    pvp_switch:pvp_switch
                });
            });
    });
});<commit_msg>fix the bug that the rank info is null<commit_after>/**
 * Created by King Lee on 2015/1/5.
 */
var handlerMgr = require("./../handlerMgr");
var consts = require("../../../util/consts");
var pomelo = require('pomelo');
var util = require('../../../util/util');
var async = require('async');
var rival_vs_json = require('../../../../config/rival_vs');
var rival_vs_title_json = require('../../../../config/rival_vs_title');

var get_rival = function(strength){
    for(var v in rival_vs_json){
        if(strength == rival_vs_json[v].level){
            return rival_vs_json[v];
        }
    }
    return rival_vs_json[0];
};

var get_extra_info = function(player_info_somebody,score){
    for(var v in rival_vs_title_json){
        if(rival_vs_title_json[v].score <= score){
            player_info_somebody.degree_title = rival_vs_title_json[v].title;
            player_info_somebody.degree = rival_vs_title_json[v].grade;
            player_info_somebody.buff_desc = rival_vs_title_json[v].buff_desc;
            player_info_somebody.buff_data = rival_vs_title_json[v].buff_data;
        }
    }
    var degree_next = player_info_somebody.degree < rival_vs_title_json.length ? player_info_somebody.degree + 1 : rival_vs_title_json.length;
    player_info_somebody.score_next = rival_vs_title_json[degree_next - 1].score;
};

var copy_rival_info = function(player_info_somebody,strength){
    var rival_info = get_rival(strength);
    player_info_somebody.level = rival_info.level;
    player_info_somebody.name = rival_info.name;
    player_info_somebody.from = rival_info.from;
    player_info_somebody.car = rival_info.car;
    player_info_somebody.car_lv = rival_info.car_lv;
    player_info_somebody.driver = rival_info.driver;
    player_info_somebody.driver_lv = rival_info.driver_lv;
    player_info_somebody.strength = rival_info.strength;
    player_info_somebody.score = rival_info.score;
    player_info_somebody.drift = rival_info.drift;
    player_info_somebody.weight = rival_info.weight;
    player_info_somebody.attack = rival_info.attack;
    player_info_somebody.speed_cruising = rival_info.speed_cruising;
    player_info_somebody.speed_duel = rival_info.speed_duel;
    player_info_somebody.speed_boost = rival_info.speed_boost;
    player_info_somebody.accel = rival_info.accel;
    player_info_somebody.accel_duel = rival_info.accel_duel;
    player_info_somebody.accel_boost = rival_info.accel_boost;
    player_info_somebody.distance_duel = rival_info.distance_duel;
    player_info_somebody.distance_wait = rival_info.distance_wait;
    player_info_somebody.distance_boost = rival_info.distance_boost;
    player_info_somebody.distance_giveup = rival_info.distance_giveup;
    player_info_somebody.time_giveup = rival_info.time_giveup;
    player_info_somebody.time_boost = rival_info.time_boost;
    player_info_somebody.cdtime_boost = rival_info.cdtime_boost;
    player_info_somebody.evade_rate = rival_info.evade_rate;
    player_info_somebody.coin = rival_info.coin;
};

var get_player_info = function(device_guid,strength_min,strength_max,max_count_to_be_choose,player_info_array,callback){
    strength_min = (strength_min < 250 ? 250 : strength_min);
    strength_max = (strength_max > 1200 ? 1200 : strength_max);
    var random_val = 0;
    var cur_loop_count = 0;
    var max_loop_count = 100;
    var rank_pvp_wrapper = pomelo.app.get("rank_pvp_wrapper");
    rank_pvp_wrapper.get_player_by_strength(strength_min,strength_max,max_count_to_be_choose,function(reply){
        if(4 <= reply.length){
            var players = reply;
            var is_repeat = true;
            do
            {
                //  random players
                random_val = Math.floor(Math.random()*players.length);
                var player = players[random_val];

                //  can not be myself
                if(player == device_guid){
                    ++cur_loop_count;
                    continue;
                }
                //  can not be the player have chose
                var find = false;
                for(var i = 0; i < player_info_array.length; ++i){
                    if(player == player_info_array[i].device_guid){
                        find = true;
                        break;
                    }
                }
                if(find){
                    ++cur_loop_count;
                    continue;
                }
                is_repeat = false;
                ++cur_loop_count;
            }while(is_repeat && cur_loop_count < max_loop_count);
            rank_pvp_wrapper.get_rank_info(players[random_val],function(reply){
                var rank_info = {};
                if(reply){
                    rank_info = JSON.parse(reply);
                    var player_info_somebody = new Object();
                    //  random json table
                    random_val = Math.floor(strength_min + Math.random()*(strength_max - strength_min));
                    copy_rival_info(player_info_somebody,random_val);
                    player_info_somebody.device_guid = rank_info.device_guid;
                    player_info_somebody.name = rank_info.nickname;
                    player_info_somebody.from = rank_info.area;
                    player_info_somebody.car = rank_info.car?rank_info.car:28;
                    player_info_somebody.car_lv = rank_info.car_lv;
                    player_info_somebody.driver = rank_info.racer;
                    player_info_somebody.driver_lv = rank_info.racer_lv;
                    player_info_somebody.total_win = rank_info.total_win;
                    player_info_somebody.is_robot = 0;
                    get_extra_info(player_info_somebody,rank_info.score);
                    player_info_array.push(player_info_somebody);
                    //  mask word
                    pomelo.app.get('mask_word_wrapper').analysis(player_info_somebody.nickname,function(nickname_new){
                        player_info_somebody.nickname = nickname_new;
                        callback(null,player_info_array);
                    });
                }
                else{
                    //  if rank_info is null,random from robot,usually it is impossible! just in case
                    var is_repeat = true;
                    do
                    {
                        random_val = Math.floor(strength_min + Math.random()*(strength_max - strength_min));
                        //  can not be the player have chose
                        var find = false;
                        for(var i = 0; i < player_info_array.length; ++i){
                            if(random_val == player_info_array[i].strength){
                                find = true;
                                break;
                            }
                        }
                        if(find){
                            ++cur_loop_count;
                            continue;
                        }
                        is_repeat = false;
                        ++cur_loop_count;
                    }while(is_repeat && cur_loop_count < max_loop_count);
                    var player_info_somebody = new Object();
                    copy_rival_info(player_info_somebody,random_val);
                    player_info_somebody.is_robot = 1;
                    player_info_array.push(player_info_somebody);
                    get_extra_info(player_info_somebody,player_info_somebody.score);
                    callback(null,player_info_array);
                }
            });
        }
        else{
            var is_repeat = true;
            do
            {
                random_val = Math.floor(strength_min + Math.random()*(strength_max - strength_min));
                //  can not be the player have chose
                var find = false;
                for(var i = 0; i < player_info_array.length; ++i){
                    if(random_val == player_info_array[i].strength){
                        find = true;
                        break;
                    }
                }
                if(find){
                    ++cur_loop_count;
                    continue;
                }
                is_repeat = false;
                ++cur_loop_count;
            }while(is_repeat && cur_loop_count < max_loop_count);
            var player_info_somebody = new Object();
            copy_rival_info(player_info_somebody,random_val);
            player_info_somebody.is_robot = 1;
            player_info_array.push(player_info_somebody);
            get_extra_info(player_info_somebody,player_info_somebody.score);
            callback(null,player_info_array);
        }
    });
};

handlerMgr.handler(consts.TYPE_MSG.TYPE_GET_RIVAL_FOR_PVP, function(msg, session, next) {
    var channel = msg.channel;
    var version = msg.version;
    var device_guid = msg.deviceid;
    var strength = parseInt(msg.strength);
    var random_val = Math.floor(Math.random()*100);
    var max_count_to_be_choose = 100;
    var strength_min = strength;
    var strength_max = strength;
    var player_info_array = [];
    var pvp_switch = 1;
    var activity = {};
    var activity_wrapper = pomelo.app.get('activity_wrapper');
    activity_wrapper.get(channel,version,function(activity_json) {
        for (var v in activity_json) {
            if (consts.TYPE_ACTIVITY.TYPE_PVP == parseInt(activity_json[v].type)) {
                activity = activity_json[v];
            }
        }
        //  calc stage
        var stage_array = activity.stage;
        pvp_switch = activity.switch;
        async.waterfall([
                function (callback) {
                    //  player 1
                    if(random_val <= 80){
                        strength_min = strength - 100;
                        strength_max = strength + 30;
                    }else{
                        strength_min = strength + 50;
                        strength_max = strength + 150;
                    }
                    get_player_info(device_guid,strength_min,strength_max,max_count_to_be_choose,player_info_array,callback);
                },
                function (player_info_array,callback) {
                    strength_min = strength - 100;
                    strength_max = strength + 30;
                    get_player_info(device_guid,strength_min,strength_max,max_count_to_be_choose,player_info_array,callback);
                },
                function (player_info_array,callback) {
                    strength_min = strength - 100;
                    strength_max = strength + 30;
                    get_player_info(device_guid,strength_min,strength_max,max_count_to_be_choose,player_info_array,callback);
                }
            ],
            function (err, player_info_array) {
                //  get stage distance
                var max_strength = 0;
                for(var i = 0; i < player_info_array.length; ++i){
                    if(max_strength < player_info_array[i].strength){
                        max_strength = player_info_array[i].strength;
                    }
                }
                var stage_distance = Math.floor(max_strength / 6 * 100);
                random_val = Math.floor(Math.random()* stage_array.length);
                next(null, {
                    code: 0,
                    msg_id : msg.msg_id,
                    flowid : msg.flowid,
                    time:Math.floor(Date.now()/1000),
                    stage:stage_array[random_val],
                    stage_distance:stage_distance,
                    player_info_array:player_info_array,
                    pvp_switch:pvp_switch
                });
            });
    });
});<|endoftext|>


<commit_before>/*

AWS Lambda function to get top ranking equations. Corresponds to /equations/top

Add the following environment variables to your Lambda function:
  neo4jBoltIp: The accessibile IP address of your bolt instance
  neo4jUser: The username of the neo4j instance to log in
  neo4jPassword: The password for the neo4j user

*/

const neo4j = require('neo4j-driver').v1;

exports.handler = (event, context, callback) => {
  const done = (err, res) => callback(null, {
    statusCode: err ? '400' : '200',
    body: err ? JSON.stringify({ message: err.message }) : JSON.stringify(res),
    headers: {
        'Content-Type': 'application/json',
        "Access-Control-Allow-Origin": "*"
    },
  });

  const driver = neo4j.driver(`bolt://${process.env["neo4jBoltIp"]}/`, neo4j.auth.basic(process.env["neo4jUser"], process.env["neo4jPassword"]));
  const session = driver.session();

  const resultPromise = session.readTransaction(tx => tx.run(
    'MATCH (subject:SUBJECT)-[r:SAME_PAGE_AS]->(eq:EQUATION) \
    RETURN subject, collect(eq)[0] as eq \
    ORDER BY subject.pagerank DESC \
    LIMIT 10'));

  resultPromise.then(result => {
    session.close();
    let equations = [];
    result.records.forEach(rec => {
      let eq = rec.get("eq");
      let subj = rec.get("subject");
      let returnEq = {
        id: eq.identity.toString(),
        name: subj.properties.title.trim(),
        equation: eq.properties.equation,
        url: subj.properties.url
      };
      equations.push(returnEq);
    });
    driver.close();

    done(null, equations);
  });
};<commit_msg>random top equations<commit_after>/*

AWS Lambda function to get top ranking equations. Corresponds to /equations/top

Add the following environment variables to your Lambda function:
  neo4jBoltIp: The accessibile IP address of your bolt instance
  neo4jUser: The username of the neo4j instance to log in
  neo4jPassword: The password for the neo4j user

*/

const neo4j = require('neo4j-driver').v1;

exports.handler = (event, context, callback) => {
  const done = (err, res) => callback(null, {
    statusCode: err ? '400' : '200',
    body: err ? JSON.stringify({ message: err.message }) : JSON.stringify(res),
    headers: {
        'Content-Type': 'application/json',
        "Access-Control-Allow-Origin": "*"
    },
  });

  const driver = neo4j.driver(`bolt://${process.env["neo4jBoltIp"]}/`, neo4j.auth.basic(process.env["neo4jUser"], process.env["neo4jPassword"]));
  const session = driver.session();

  const resultPromise = session.readTransaction(tx => tx.run(
    'MATCH (subject:SUBJECT)-[r:SAME_PAGE_AS]->(eq:EQUATION) \
     WITH collect(eq) AS eqs, subject, COUNT(eq) as eqCount \

     WITH toInteger(floor(rand()*eqCount)) AS eqIndex, eqs, subject \

     RETURN subject, eqs[eqIndex] AS eq \

     ORDER BY subject.pagerank DESC \

     LIMIT 10'));

  resultPromise.then(result => {
    session.close();
    let equations = [];
    result.records.forEach(rec => {
      let eq = rec.get("eq");
      let subj = rec.get("subject");
      let returnEq = {
        id: eq.identity.toString(),
        name: subj.properties.title.trim(),
        equation: eq.properties.equation,
        url: subj.properties.url
      };
      equations.push(returnEq);
    });
    driver.close();

    done(null, equations);
  });
};<|endoftext|>


<commit_before><commit_msg>Added shortcut to sync module<commit_after><|endoftext|>


<commit_before>var esprima = require('esprima');

var moduleAnalyzer = {
	analyze: function (js) {
		var analyzedJs = esprima.parse(js);

		//console.log(JSON.stringify(analyzedJs, null, 4));
		goThroughSyntaxTree(analyzedJs.body[0]);

		return js;
	}
};

var systemVariables = ["_event", "_sessionid", "_name", "_ioprocessors", "_x"];

var treeTypes = {
	"BlockStatement": function (tree) {
		tree = tree.body;
		goThroughSyntaxTree(tree);

	},
	"FunctionExpression": function (tree) {
		tree = tree.body;
		goThroughSyntaxTree(tree);

	},
	"ExpressionStatement": function (tree) {
		tree = tree.expression;
		goThroughSyntaxTree(tree);
	},
	"VariableDeclaration": function (tree) {

	},
	"AssignmentExpression": function (tree) {

	},
	"ReturnStatement": function (tree) {

	},
	"CallExpression": function (tree) {

	},
	"IfStatement": function (tree) {

	},
	"FunctionDeclaration": function (tree) {

	}
};

function goThroughSyntaxTree (tree) {
	if (Array.isArray(tree)) {
		for (var i = tree.length - 1; i >= 0; i--) {
			goThroughSyntaxTree(tree[i]);
		};
	} else{
		if(tree.type) {
			treeTypes[tree.type](tree);
		}
	};

}

module.exports = moduleAnalyzer;<commit_msg>Catching all assignment expressions<commit_after>var esprima = require('esprima');

var moduleAnalyzer = {
	analyze: function (js) {
		var analyzedJs = esprima.parse(js);

		//console.log(JSON.stringify(analyzedJs, null, 4));
		goThroughSyntaxTree(analyzedJs.body[0]);

		return js;
	}
};

var systemVariables = ["_event", "_sessionid", "_name", "_ioprocessors", "_x"];

var treeTypes = {
	"BlockStatement": function (tree) {
		tree = tree.body;
		goThroughSyntaxTree(tree);

	},
	"FunctionExpression": function (tree) {
		tree = tree.body;
		goThroughSyntaxTree(tree);

	},
	"FunctionDeclaration": function (tree) {
		tree = tree.body;
		goThroughSyntaxTree(tree);
	},
	"ExpressionStatement": function (tree) {
		tree = tree.expression;
		goThroughSyntaxTree(tree);
	},
	"VariableDeclaration": function (tree) {

	},
	"AssignmentExpression": function (tree) {
		//TODO check if assigned variable is a system variable
		console.log(tree.left.name);
	},
	"ReturnStatement": function (tree) {

	},
	"CallExpression": function (tree) {

	},
	"IfStatement": function (tree) {

	}
};

function goThroughSyntaxTree (tree) {
	if (Array.isArray(tree)) {
		for (var i = tree.length - 1; i >= 0; i--) {
			goThroughSyntaxTree(tree[i]);
		};
	} else{
		if(tree.type) {
			treeTypes[tree.type](tree);
		}
	};

}

module.exports = moduleAnalyzer;<|endoftext|>


<commit_before>import Component from '@glimmer/component';
import {action} from '@ember/object';
import {inject as service} from '@ember/service';

export default class SettingsMembersSubscriptionAccess extends Component {
    @service settings;

    get options() {
        return [{
            name: 'Anyone can sign up',
            description: 'All visitors will be able to subscribe and sign in',
            value: 'all',
            icon: 'globe',
            icon_color: 'green'
        }, {
            name: 'Only people I invite',
            description: 'People can sign in from your site but won\'t be able to sign up',
            value: 'invite',
            icon: 'email-love-letter',
            icon_color: 'blue'
        }, {
            name: 'Nobody',
            description: 'No one will be able to subscribe or sign in',
            value: 'none',
            icon: 'no-members',
            icon_color: 'pink'
        }];
    }

    get selectedOption() {
        return this.options.find(o => o.value === this.settings.get('membersSignupAccess'));
    }

    @action
    setSignupAccess(option) {
        this.settings.set('membersSignupAccess', option.value);
        this.args.onChange?.(option.value);

        if (option.value === 'none') {
            this.settings.set('defaultContentVisibility', 'public');
        }
    }
}
<commit_msg>Refined icon color<commit_after>import Component from '@glimmer/component';
import {action} from '@ember/object';
import {inject as service} from '@ember/service';

export default class SettingsMembersSubscriptionAccess extends Component {
    @service settings;

    get options() {
        return [{
            name: 'Anyone can sign up',
            description: 'All visitors will be able to subscribe and sign in',
            value: 'all',
            icon: 'globe',
            icon_color: 'green'
        }, {
            name: 'Only people I invite',
            description: 'People can sign in from your site but won\'t be able to sign up',
            value: 'invite',
            icon: 'email-love-letter',
            icon_color: 'blue'
        }, {
            name: 'Nobody',
            description: 'No one will be able to subscribe or sign in',
            value: 'none',
            icon: 'no-members',
            icon_color: 'midlightgrey-d2'
        }];
    }

    get selectedOption() {
        return this.options.find(o => o.value === this.settings.get('membersSignupAccess'));
    }

    @action
    setSignupAccess(option) {
        this.settings.set('membersSignupAccess', option.value);
        this.args.onChange?.(option.value);

        if (option.value === 'none') {
            this.settings.set('defaultContentVisibility', 'public');
        }
    }
}
<|endoftext|>


<commit_before>export { ConvBlockType };

import { Int } from "./ValueDesc_Base.js";

/** Describe id, range, name of ConvBlockType.
 *
 * Convert number value into integer between [ 0, 10 ] representing operation:
 *   -  0: MOBILE_NET_V1_HEAD_BODY_TAIL                     (General Pointwise1-Depthwise1-Pointwise2)
 *                                                          (MobileNetV1 or
 *                                                           MobileNetV2's head)
 *
 *   -  1: MOBILE_NET_V2_BODY_TAIL
 *   -  2: SHUFFLE_NET_V2_HEAD
 *   -  3: SHUFFLE_NET_V2_BODY
 *   -  4: SHUFFLE_NET_V2_TAIL
 *   -  5: SHUFFLE_NET_V2_BY_POINTWISE21_HEAD_NO_POINTWISE  (ShuffleNetV2_ByPointwise21's head with ( pointwise1ChannelCount == 0 ))
 *   -  6: SHUFFLE_NET_V2_BY_POINTWISE21_HEAD               (ShuffleNetV2_ByPointwise21's head with ( pointwise1ChannelCount >= 1 ))
 *   -  7: SHUFFLE_NET_V2_BY_POINTWISE21_BODY
 *   -  8: SHUFFLE_NET_V2_BY_POINTWISE21_TAIL
 *   -  9: SHUFFLE_NET_V2_BY_MOBILE_NET_V1_HEAD
 *   - 10: SHUFFLE_NET_V2_BY_MOBILE_NET_V1_BODY_TAIL
 */
class ConvBlockType extends Int {

  constructor() {
    super( 0, 9,
      [
        "MOBILE_NET_V1_HEAD_BODY_TAIL",                     // ( 0)
        "MOBILE_NET_V2_BODY_TAIL",                          // ( 1)
        "SHUFFLE_NET_V2_HEAD",                              // ( 2)
        "SHUFFLE_NET_V2_BODY",                              // ( 3)
        "SHUFFLE_NET_V2_TAIL",                              // ( 4)
        "SHUFFLE_NET_V2_BY_POINTWISE21_HEAD_NO_POINTWISE",  // ( 5)
        "SHUFFLE_NET_V2_BY_POINTWISE21_HEAD",               // ( 6)
        "SHUFFLE_NET_V2_BY_POINTWISE21_BODY",               // ( 7)
        "SHUFFLE_NET_V2_BY_POINTWISE21_TAIL",               // ( 8)
        "SHUFFLE_NET_V2_BY_MOBILE_NET_V1_HEAD",             // ( 9)
        "SHUFFLE_NET_V2_BY_MOBILE_NET_V1_BODY_TAIL",        // (10)
      ],

      [
         new ConvBlockType.Info(  0, 1, 1, false, false, false, false, false, false ),
         new ConvBlockType.Info(  1, 1, 1, false, false,  true, false, false, false ),
         new ConvBlockType.Info(  2, 1, 2,  true, false, false,  true, false, false ),
         new ConvBlockType.Info(  3, 2, 2, false, false, false,  true, false, false ),
         new ConvBlockType.Info(  4, 2, 1, false, false, false,  true, false, false ),
         new ConvBlockType.Info(  5, 1, 2, false, false, false, false, false, false ),
         new ConvBlockType.Info(  6, 1, 2,  true,  true, false, false, false, false ),
         new ConvBlockType.Info(  7, 2, 2, false,  true, false, false, false, false ),
         new ConvBlockType.Info(  8, 2, 1, false,  true, false, false, false, false ),
         new ConvBlockType.Info(  9, 1, 1, false, false, false, false,  true,  true ),
         new ConvBlockType.Info( 10, 1, 1, false, false, false, false,  true, false ),
      ]
    );
  }

  /**
   * @param {number} nConvBlockTypeId  The numeric identifier of ConvBlockType. (ConvBlockType.Singleton.Ids.Xxx)
   * @return {number} Return the input tensor count (1 or 2) of the ConvBlockType.Singleton.Ids.Xxx.
   */
  static inputTensorCount_get( nConvBlockTypeId ) {
    let info = ConvBlockType.Singleton.getInfoById( nConvBlockTypeId );
    if ( info )
      return info.inputTensorCount;
    return NaN;
  }

  /**
   * @param {number} nConvBlockTypeId  The numeric identifier of ConvBlockType. (ConvBlockType.Singleton.Ids.Xxx)
   * @return {number} Return the output tensor count (1 or 2) of the ConvBlockType.Singleton.Ids.Xxx.
   */
  static outputTensorCount_get( nConvBlockTypeId ) {
    let info = ConvBlockType.Singleton.getInfoById( nConvBlockTypeId );
    if ( info )
      return info.outputTensorCount;
    return NaN;
  }

  /**
   * Convert convolution block type id to information object.
   *
   * @param {umber} nConvBlockTypeId
   *   It should be one of ValueDesc.ConvBlockType.Singleton.Ids.Xxx.
   *
   * @return {ConvBlockType.Info}
   *   It should be one of ValueDesc.ConvBlockType.Singleton.integerToObjectMap according to the nStridesPadId.
   */
  getInfoById( nConvBlockTypeId ) {
    let info = this.integerToObjectMap.get( nConvBlockTypeId );
    return info;
  }

}

/**
 *
 * @member {number} nConvBlockTypeId
 *   The convolution block type id (ValueDesc.ConvBlockType.Singleton.Ids.Xxx).
 *
 * @member {number} inputTensorCount
 *   The input tensor count for The convolution block type. Either 1 or 2.
 *
 * @member {number} outputTensorCount
 *   The output tensor count for The convolution block type. Either 1 or 2.
 *
 */
ConvBlockType.Info = class {

  /**
   *
   * @param {boolean} bDepthwise2Requested
   *   Whether needs depthwise2. Usually true only if SHUFFLE_NET_V2_BY_HEAD and SHUFFLE_NET_V2_BY_POINTWISE21_HEAD (except
   * SHUFFLE_NET_V2_BY_POINTWISE21_HEAD_NO_POINTWISE).
   *
   * @param {boolean} bConcat1Requested
   *   Whether needs concat1 (i.e. concat after depthwise). Usually true only if SHUFFLE_NET_V2_BY_POINTWISE21_Xxx (except
   * SHUFFLE_NET_V2_BY_POINTWISE21_HEAD_NO_POINTWISE).
   *
   * @param {boolean} bAddInputToOutputRequested
   *   Whether needs add-input-to-output. Usually true only if MOBILE_NET_V2_BODY_TAIL.
   *
   * @param {boolean} bConcat2ShuffleSplitRequested
   *   Whether needs add-input-to-output. Usually true only if SHUFFLE_NET_V2_HEAD, SHUFFLE_NET_V2_BODY, SHUFFLE_NET_V2_TAIL.
   *
   * @param {boolean} bHigherHalfDifferent
   *   Whether the higher half channels will be handled different. Usually true only if SHUFFLE_NET_V2_BY_MOBILE_NET_V1_Xxx.
   *
   * @param {boolean} bHigherHalfDepthwise2
   *   Whether the higher half channels will be processed by depthwise2. Usually true only if SHUFFLE_NET_V2_BY_MOBILE_NET_V1_HEAD.
   *

//!!! ...unfinshed... (2022/06/14) Perhaps, should have flag ConvBlockType.Info.bPointwise21
    // Note: Even if ( outputTensorCount == 2 ), it does not means pointwise21 existed.

   */
  constructor( nConvBlockTypeId, inputTensorCount, outputTensorCount,
    bDepthwise2Requested, bConcat1Requested, bAddInputToOutputRequested, bConcat2ShuffleSplitRequested,
    bHigherHalfDifferent, bHigherHalfDepthwise2
  ) {
    this.nConvBlockTypeId = nConvBlockTypeId;
    this.inputTensorCount = inputTensorCount;
    this.outputTensorCount = outputTensorCount;

    this.bDepthwise2Requested = bDepthwise2Requested;
    this.bConcat1Requested = bConcat1Requested;
    this.bAddInputToOutputRequested = bAddInputToOutputRequested;
    this.bConcat2ShuffleSplitRequested = bConcat2ShuffleSplitRequested;

    this.bHigherHalfDifferent = bHigherHalfDifferent;
    this.bHigherHalfDepthwise2 = bHigherHalfDepthwise2;
  }

}

/** The only one ValueDesc.ConvBlockType instance. */
ConvBlockType.Singleton = new ConvBlockType;

<commit_msg>Update ValueDesc_ConvBlockType.js<commit_after>export { ConvBlockType };

import { Int } from "./ValueDesc_Base.js";

/** Describe id, range, name of ConvBlockType.
 *
 * Convert number value into integer between [ 0, 10 ] representing operation:
 *   -  0: MOBILE_NET_V1_HEAD_BODY_TAIL                     (General Pointwise1-Depthwise1-Pointwise2)
 *                                                          (MobileNetV1 or
 *                                                           MobileNetV2's head)
 *
 *   -  1: MOBILE_NET_V2_BODY_TAIL
 *   -  2: SHUFFLE_NET_V2_HEAD
 *   -  3: SHUFFLE_NET_V2_BODY
 *   -  4: SHUFFLE_NET_V2_TAIL
 *   -  5: SHUFFLE_NET_V2_BY_POINTWISE21_HEAD_NO_POINTWISE  (ShuffleNetV2_ByPointwise21's head with ( pointwise1ChannelCount == 0 ))
 *   -  6: SHUFFLE_NET_V2_BY_POINTWISE21_HEAD               (ShuffleNetV2_ByPointwise21's head with ( pointwise1ChannelCount >= 1 ))
 *   -  7: SHUFFLE_NET_V2_BY_POINTWISE21_BODY
 *   -  8: SHUFFLE_NET_V2_BY_POINTWISE21_TAIL
 *   -  9: SHUFFLE_NET_V2_BY_MOBILE_NET_V1_HEAD
 *   - 10: SHUFFLE_NET_V2_BY_MOBILE_NET_V1_BODY_TAIL
 */
class ConvBlockType extends Int {

  constructor() {
    super( 0, 9,
      [
        "MOBILE_NET_V1_HEAD_BODY_TAIL",                     // ( 0)
        "MOBILE_NET_V2_BODY_TAIL",                          // ( 1)
        "SHUFFLE_NET_V2_HEAD",                              // ( 2)
        "SHUFFLE_NET_V2_BODY",                              // ( 3)
        "SHUFFLE_NET_V2_TAIL",                              // ( 4)
        "SHUFFLE_NET_V2_BY_POINTWISE21_HEAD_NO_POINTWISE",  // ( 5)
        "SHUFFLE_NET_V2_BY_POINTWISE21_HEAD",               // ( 6)
        "SHUFFLE_NET_V2_BY_POINTWISE21_BODY",               // ( 7)
        "SHUFFLE_NET_V2_BY_POINTWISE21_TAIL",               // ( 8)
        "SHUFFLE_NET_V2_BY_MOBILE_NET_V1_HEAD",             // ( 9)
        "SHUFFLE_NET_V2_BY_MOBILE_NET_V1_BODY_TAIL",        // (10)
      ],

      [
         new ConvBlockType.Info(  0, 1, 1, false, false, false, false, false, false ),
         new ConvBlockType.Info(  1, 1, 1, false, false,  true, false, false, false ),
         new ConvBlockType.Info(  2, 1, 2,  true, false, false,  true, false, false ),
         new ConvBlockType.Info(  3, 2, 2, false, false, false,  true, false, false ),
         new ConvBlockType.Info(  4, 2, 1, false, false, false,  true, false, false ),
         new ConvBlockType.Info(  5, 1, 2, false, false, false, false, false, false ),
         new ConvBlockType.Info(  6, 1, 2,  true,  true, false, false, false, false ),
         new ConvBlockType.Info(  7, 2, 2, false,  true, false, false, false, false ),
         new ConvBlockType.Info(  8, 2, 1, false,  true, false, false, false, false ),
         new ConvBlockType.Info(  9, 1, 1, false, false, false, false,  true,  true ),
         new ConvBlockType.Info( 10, 1, 1, false, false, false, false,  true, false ),
      ]
    );
  }

  /**
   * @param {number} nConvBlockTypeId  The numeric identifier of ConvBlockType. (ConvBlockType.Singleton.Ids.Xxx)
   * @return {number} Return the input tensor count (1 or 2) of the ConvBlockType.Singleton.Ids.Xxx.
   */
  static inputTensorCount_get( nConvBlockTypeId ) {
    let info = ConvBlockType.Singleton.getInfoById( nConvBlockTypeId );
    if ( info )
      return info.inputTensorCount;
    return NaN;
  }

  /**
   * @param {number} nConvBlockTypeId  The numeric identifier of ConvBlockType. (ConvBlockType.Singleton.Ids.Xxx)
   * @return {number} Return the output tensor count (1 or 2) of the ConvBlockType.Singleton.Ids.Xxx.
   */
  static outputTensorCount_get( nConvBlockTypeId ) {
    let info = ConvBlockType.Singleton.getInfoById( nConvBlockTypeId );
    if ( info )
      return info.outputTensorCount;
    return NaN;
  }

  /**
   * Convert convolution block type id to information object.
   *
   * @param {umber} nConvBlockTypeId
   *   It should be one of ValueDesc.ConvBlockType.Singleton.Ids.Xxx.
   *
   * @return {ConvBlockType.Info}
   *   It should be one of ValueDesc.ConvBlockType.Singleton.integerToObjectMap according to the nStridesPadId.
   */
  getInfoById( nConvBlockTypeId ) {
    let info = this.integerToObjectMap.get( nConvBlockTypeId );
    return info;
  }

}

/**
 *
 * @member {number} nConvBlockTypeId
 *   The convolution block type id (ValueDesc.ConvBlockType.Singleton.Ids.Xxx).
 *
 * @member {number} inputTensorCount
 *   The input tensor count for The convolution block type. Either 1 or 2.
 *
 * @member {number} outputTensorCount
 *   The output tensor count for The convolution block type. Either 1 or 2.
 *
 */
ConvBlockType.Info = class {

  /**
   *
   * @param {boolean} bDepthwise2Requested
   *   Whether needs depthwise2. Usually true only if SHUFFLE_NET_V2_BY_HEAD and SHUFFLE_NET_V2_BY_POINTWISE21_HEAD (except
   * SHUFFLE_NET_V2_BY_POINTWISE21_HEAD_NO_POINTWISE).
   *
   * @param {boolean} bConcat1Requested
   *   Whether needs concat1 (i.e. concat after depthwise). Usually true only if SHUFFLE_NET_V2_BY_POINTWISE21_Xxx (except
   * SHUFFLE_NET_V2_BY_POINTWISE21_HEAD_NO_POINTWISE).
   *
   * @param {boolean} bAddInputToOutputRequested
   *   Whether needs add-input-to-output. Usually true only if MOBILE_NET_V2_BODY_TAIL.
   *
   * @param {boolean} bConcat2ShuffleSplitRequested
   *   Whether needs add-input-to-output. Usually true only if SHUFFLE_NET_V2_HEAD, SHUFFLE_NET_V2_BODY, SHUFFLE_NET_V2_TAIL.
   *
   * @param {boolean} bHigherHalfDifferent
   *   Whether the higher half channels will be handled different. Usually true only if SHUFFLE_NET_V2_BY_MOBILE_NET_V1_Xxx.
   *
   * @param {boolean} bHigherHalfDepthwise2
   *   Whether the higher half channels will be processed by depthwise2. Usually true only if SHUFFLE_NET_V2_BY_MOBILE_NET_V1_HEAD.
   *
   * @param {boolean} bPointwise21
   *   Whether the 2nd pointwise2 existed. Usually true only if ??? SHUFFLE_NET_V2_BY_MOBILE_NET_V1_HEAD.
   * Note: Even if ( outputTensorCount == 2 ), it does not means pointwise21 existed.

//!!! ...unfinshed... (2022/06/14) Perhaps, should have flag ConvBlockType.Info.bPointwise21
    // Note: Even if ( outputTensorCount == 2 ), it does not means pointwise21 existed.

   */
  constructor( nConvBlockTypeId, inputTensorCount, outputTensorCount,
    bDepthwise2Requested, bConcat1Requested, bAddInputToOutputRequested, bConcat2ShuffleSplitRequested,
    bHigherHalfDifferent, bHigherHalfDepthwise2
  ) {
    this.nConvBlockTypeId = nConvBlockTypeId;
    this.inputTensorCount = inputTensorCount;
    this.outputTensorCount = outputTensorCount;

    this.bDepthwise2Requested = bDepthwise2Requested;
    this.bConcat1Requested = bConcat1Requested;
    this.bAddInputToOutputRequested = bAddInputToOutputRequested;
    this.bConcat2ShuffleSplitRequested = bConcat2ShuffleSplitRequested;

    this.bHigherHalfDifferent = bHigherHalfDifferent;
    this.bHigherHalfDepthwise2 = bHigherHalfDepthwise2;
  }

}

/** The only one ValueDesc.ConvBlockType instance. */
ConvBlockType.Singleton = new ConvBlockType;

<|endoftext|>


<commit_before>import React, { Component } from "react";
import {
  Image,
  Navigator,
  StyleSheet,
  Text,
  TouchableHighlight,
  View
} from "react-native";

import SearchComponent from "./components/Search";
import DeparturesComponent from "./components/Departures";
import LineComponent from "./components/Line";

export default class GdziesikTramwajka extends Component {
  constructor(props) {
    super(props);

    this.state = { stops: [] };
  }

  renderScene(route, navigator) {
    switch (route.type) {
      case "search":
        return <SearchComponent navigator={navigator} />;
      case "departures":
        return (
          <DeparturesComponent
            navigator={navigator}
            stopId={route.data.stopId}
          />
        );
      case "line":
        console.log("liiiine", route.data);
        return (
          <LineComponent navigator={navigator} tripId={route.data.tripId} />
        );
    }
  }

  render() {
    return (
      <View style={styles.appcontainer}>
        <Navigator
          styles={styles.navigator}
          initialRoute={{ type: "search", title: "Gdzieśże Tramwaju" }}
          renderScene={(route, navigator) => this.renderScene(route, navigator)}
          sceneStyle={{ paddingTop: 64 }}
          navigationBar={
            <Navigator.NavigationBar
              routeMapper={{
                LeftButton: (route, navigator, index, navState) => {
                  if (route.type === "search") {
                    return (
                      <Image
                        style={styles.headerImage}
                        source={require("../assets/images/tram.png")}
                      />
                    );
                  } else {
                    return (
                      <TouchableHighlight
                        onPress={() => navigator.pop()}
                        style={styles.backButton}
                        underlayColor={"#4fc3f7"}
                      >
                        <Image
                          style={styles.headerImage}
                          source={require("../assets/images/arrow_back.png")}
                        />
                      </TouchableHighlight>
                    );
                  }
                },
                RightButton: (route, navigator, index, navState) => {
                  return null;
                },
                Title: (route, navigator, index, navState) => {
                  return (
                    <Text
                      style={[styles.headerText, { width: "80%" }]}
                      numberOfLines={1}
                      ellipsizeMode={"tail"}
                    >
                      {route.title}
                    </Text>
                  );
                }
              }}
              style={styles.topBar}
            />
          }
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  appcontainer: {
    flex: 1,
    backgroundColor: "#fff"
  },
  topBar: {
    padding: 10,
    paddingTop: 30,
    paddingBottom: 0,
    backgroundColor: "#0277bd",
    height: 60
  },
  headerText: {
    color: "#e1f5fe",
    marginTop: 10,
    fontSize: 25
  },
  headerImage: {
    marginTop: 5
  },
  backButton: {
    paddingLeft: 5
  }
});
<commit_msg>Add support for back button<commit_after>import React, { Component } from "react";
import {
  BackAndroid,
  Image,
  Navigator,
  StyleSheet,
  Text,
  TouchableHighlight,
  View
} from "react-native";

import SearchComponent from "./components/Search";
import DeparturesComponent from "./components/Departures";
import LineComponent from "./components/Line";

export default class GdziesikTramwajka extends Component {
  constructor(props) {
    super(props);

    this.state = { stops: [] };
    BackAndroid.addEventListener("hardwareBackPress", () => {
      if (this.refs.navigator.getCurrentRoutes().length > 1) {
        this.refs.navigator.pop();
        return true;
      } else {
        return false;
      }
    });
  }

  renderScene(route, navigator) {
    switch (route.type) {
      case "search":
        return <SearchComponent navigator={navigator} />;
      case "departures":
        return (
          <DeparturesComponent
            navigator={navigator}
            stopId={route.data.stopId}
          />
        );
      case "line":
        console.log("liiiine", route.data);
        return (
          <LineComponent navigator={navigator} tripId={route.data.tripId} />
        );
    }
  }

  render() {
    return (
      <View style={styles.appcontainer}>
        <Navigator
          ref={'navigator'}
          styles={styles.navigator}
          initialRoute={{ type: "search", title: "Gdzieśże Tramwaju" }}
          renderScene={(route, navigator) => this.renderScene(route, navigator)}
          sceneStyle={{ paddingTop: 64 }}
          navigationBar={
            <Navigator.NavigationBar
              routeMapper={{
                LeftButton: (route, navigator, index, navState) => {
                  if (route.type === "search") {
                    return (
                      <Image
                        style={styles.headerImage}
                        source={require("../assets/images/tram.png")}
                      />
                    );
                  } else {
                    return (
                      <TouchableHighlight
                        onPress={() => navigator.pop()}
                        style={styles.backButton}
                        underlayColor={"#4fc3f7"}
                      >
                        <Image
                          style={styles.headerImage}
                          source={require("../assets/images/arrow_back.png")}
                        />
                      </TouchableHighlight>
                    );
                  }
                },
                RightButton: (route, navigator, index, navState) => {
                  return null;
                },
                Title: (route, navigator, index, navState) => {
                  return (
                    <Text
                      style={[styles.headerText, { width: "80%" }]}
                      numberOfLines={1}
                      ellipsizeMode={"tail"}
                    >
                      {route.title}
                    </Text>
                  );
                }
              }}
              style={styles.topBar}
            />
          }
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  appcontainer: {
    flex: 1,
    backgroundColor: "#fff"
  },
  topBar: {
    padding: 10,
    paddingTop: 30,
    paddingBottom: 0,
    backgroundColor: "#0277bd",
    height: 60
  },
  headerText: {
    color: "#e1f5fe",
    marginTop: 10,
    fontSize: 25
  },
  headerImage: {
    marginTop: 5
  },
  backButton: {
    paddingLeft: 5
  }
});
<|endoftext|>


<commit_before>/* global importScripts, BackboneEvents, HTTP */
/* jshint unused:false */

var Server = (function() {
  function Server(options) {
    this.options = options || {WSURL: ""};
    this.http = new HTTP();
    this._ws = undefined;
  }

  Server.prototype = {
    signin: function(assertion, callback) {
      this.http.post("/signin", {assertion: assertion}, callback);
    },

    signout: function(nick, callback) {
      this.http.post("/signout", {nick: nick}, callback);
    },

    connect: function(nick) {
      this.http.post("/stream", {nick: nick}, function(err, response) {
        if (err)
          return this.trigger("error", response);

        this.trigger("connected");
        this._longPolling(nick, JSON.parse(response));
      }.bind(this));
    },

    autoconnect: function(nick) {
      this.http.post("/stream", {nick: nick}, function(err, response) {
        if (err)
          return this.trigger("disconnected", response);

        this.trigger("connected");
        this._longPolling(nick, JSON.parse(response));
      }.bind(this));
    },

    _longPolling: function(nick, events) {
      events.forEach(function(event) {
        for (var type in event) {
          this.trigger("message", type, event[type]);
          this.trigger("message:" + type, event[type]);
        }
      }.bind(this));

      this.http.post("/stream", {nick: nick}, function(err, response) {
        if (err)
          return this.trigger("disconnected", response);

        this._longPolling(nick, JSON.parse(response));
      }.bind(this));
    },

    callOffer: function(data, nick, callback) {
      this.http.post("/calloffer", {data: data, nick: nick}, callback);
    },

    callAccepted: function(data, nick, callback) {
      this.http.post("/callaccepted", {data: data, nick: nick}, callback);
    },

    callHangup: function(data, nick, callback) {
      this.http.post("/callhangup", {data: data, nick: nick}, callback);
    },

    presenceRequest: function(nick, callback) {
      this.http.post("/presencerequest", {nick: nick}, callback);
    }
  };

  BackboneEvents.mixin(Server.prototype);

  return Server;
}());

<commit_msg>SPA: remove junk from Server<commit_after>/* global importScripts, BackboneEvents, HTTP */
/* jshint unused:false */

var Server = (function() {
  function Server(options) {
    this.options = options;
    this.http = new HTTP();
  }

  Server.prototype = {
    signin: function(assertion, callback) {
      this.http.post("/signin", {assertion: assertion}, callback);
    },

    signout: function(nick, callback) {
      this.http.post("/signout", {nick: nick}, callback);
    },

    connect: function(nick) {
      this.http.post("/stream", {nick: nick}, function(err, response) {
        if (err)
          return this.trigger("error", response);

        this.trigger("connected");
        this._longPolling(nick, JSON.parse(response));
      }.bind(this));
    },

    autoconnect: function(nick) {
      this.http.post("/stream", {nick: nick}, function(err, response) {
        if (err)
          return this.trigger("disconnected", response);

        this.trigger("connected");
        this._longPolling(nick, JSON.parse(response));
      }.bind(this));
    },

    _longPolling: function(nick, events) {
      events.forEach(function(event) {
        for (var type in event) {
          this.trigger("message", type, event[type]);
          this.trigger("message:" + type, event[type]);
        }
      }.bind(this));

      this.http.post("/stream", {nick: nick}, function(err, response) {
        if (err)
          return this.trigger("disconnected", response);

        this._longPolling(nick, JSON.parse(response));
      }.bind(this));
    },

    callOffer: function(data, nick, callback) {
      this.http.post("/calloffer", {data: data, nick: nick}, callback);
    },

    callAccepted: function(data, nick, callback) {
      this.http.post("/callaccepted", {data: data, nick: nick}, callback);
    },

    callHangup: function(data, nick, callback) {
      this.http.post("/callhangup", {data: data, nick: nick}, callback);
    },

    presenceRequest: function(nick, callback) {
      this.http.post("/presencerequest", {nick: nick}, callback);
    }
  };

  BackboneEvents.mixin(Server.prototype);

  return Server;
}());

<|endoftext|>


<commit_before>/// <reference path="AsyncRequest.Object.js" />
/// <reference path="AsyncRequest.Queue.js" />
/// <reference path="AsyncRequest.Notification.js" />
/// <reference path="jquery.jgrowl.min.js" />
///
/*!
 * Copyright 2013 Poligono Software, Inc. and other contributors
 * Released under the MIT license
*/

(function ($) {
    "use strict";

    function ExecuteNotify(data, options, requestType, eventType) {
        if (options.notification.notifyFunction !== null) {
            options.notification.notifyCommandType.forEach(function (elem) {
                if (elem === requestType && options.notification.notifyFunction !== false) {
                    options.notification.notifyFunction(eventType, data);
                }
            });
        }
    }

    function Unblock(containner, funcBefore) {//moment is "before" / "after"

        if (containner !== false) {
            if (containner === null) { //BlockPage
                $.unblockUI({ onUnblock: funcBefore });
            } else {
                $(containner).unblock({ onUnblock: funcBefore });
            }
        }
    }

    function ConfigurarAntesRequest(options, asyncObject, requestType) {

        if (asyncObject.Msg === null || asyncObject.Msg === undefined) {
            asyncObject.Msg = options.loadTextTemplate.replace("${msg}", options.loadText);
        }
        if (asyncObject.Containner !== false) {
            if (asyncObject.Containner === null) {//BlockPage
                $.blockUI({ message: asyncObject.Msg });
            } else {
                $(asyncObject.Containner).block({ message: asyncObject.Msg });
            }
        }

        if (asyncObject.Data === null) {
            asyncObject.DataRequest = {};
        } else {
            if (asyncObject.ContentType.indexOf("application/json") !== -1) {
                asyncObject.DataRequest = JSON.stringify(asyncObject.Data);
            } else {
                asyncObject.DataRequest = asyncObject.Data;
            }
        }
        if (asyncObject.SuccessFunction !== false) {
            var func = asyncObject.SuccessFunction;
            asyncObject.SuccessFunction = function (data) {

                if (asyncObject.UnblockMoment === "before") {
                    var funcBefore = null;
                    if (func != null) {
                        funcBefore = function () {
                            func(data);
                        }
                    }
                    Unblock(asyncObject.Containner, funcBefore);

                }
                else {
                    if (func != null) {
                        func(data);
                    }
                    Unblock(asyncObject.Containner);
                }
                ExecuteNotify(data, options, requestType, 'success');
            };
        }

        if (asyncObject.ErrorFunction !== false) {
            var funcErro = asyncObject.ErrorFunction;
            asyncObject.ErrorFunction = function (data) {

                //if (asyncObject.ReturnType == "json") {
                //    if (data.responseText != null && data.responseText != "") {
                //        jsonRetorno = JSON.parse(data.responseText);
                //        jsonRetorno.Message = Core.Notification.ErrorMsgDefault;
                //        data.responseText = JSON.stringify(jsonRetorno);
                //    }
                //}

                //switch (request.statusCode().status) {
                //    //Core.HandlerErroInterno(data);
                //    //break;
                //    case 401: //Unauthorized
                //        Core.HandlerErroInterno(data);
                //        break;
                //    case 404: //Not found
                //        Core.HandlerErroInterno(data);
                //        break;
                //    case 500: //erro interno
                //        Core.HandlerErroInterno(data);
                //        break;
                //    case 400: //BadRequest
                //    default:
                //        asyncObject.ErrorFunction(data);
                //        ExecuteDynamicCommand();
                //        break
                //}
                if (asyncObject.UnblockMoment === "before") {
                    var funcBefore = null;
                    if (funcErro != null) {
                        funcBefore = function () {
                            funcErro(data);
                        }
                    }
                    Unblock(asyncObject.Containner, funcBefore);

                }
                else {
                    if (funcErro != null) {
                        funcErro(data);
                    }
                    Unblock(asyncObject.Containner);
                }
                ExecuteNotify(data, options, requestType, 'erro');

            };
        }

        //Sem utilidade ainda
        if (asyncObject.CompleteFunction !== false) {
            var funcComplete = asyncObject.CompleteFunction;
            asyncObject.CompleteFunction = function (data) {
                if (funcComplete !== null) {
                    funcComplete(data);
                }
            };
        }
    }

    function ConfigRequest(type, asyncObject) {
        $.ajax({
            type: type,
            url: asyncObject.Url,
            data: asyncObject.DataRequest,
            contentType: asyncObject.ContentType,
            success: asyncObject.SuccessFunction,
            error: asyncObject.ErrorFunction,
            complete: asyncObject.CompleteFunction,
            dataType: asyncObject.DataType
        });
    }

    $.fn.asyncRequest = new function () {
        var Module = {

            init: function (options) {
                var defaults = {};
                $.extend(true, defaults, $.asyncRequest.defaults);
                this.options = $.extend(true, defaults, options);
                if (this.options.notification.notifyFunction === null) {
                    this.options.notification.notifyFunction = this.NotifyDefault;
                }
            },

            getObjAsync: function () {
                if (this.options === undefined) {
                    this.init();
                }
                return Object.create(this.options.asyncObject);
            },

            getAsync: function (url, data, containner, successFunction, ErrorFunction, msg, queue) {
                var object = this.getObjAsync();
                object.Url = url;
                object.Data = data;
                object.SuccessFunction = successFunction;
                object.ErrorFunction = ErrorFunction;
                object.Msg = msg;
                object.Queue = queue;
                object.Containner = containner;
                this.get(object);
            },

            get: function (asyncObject) {
                if (this.options === undefined) {
                    this.init();
                }
                asyncObject = $.extend(true, $.asyncRequest.defaults.asyncObject, asyncObject);
                var options = this.options,
                func = function () {//group function to use queueKey
                    ConfigurarAntesRequest(options, asyncObject, "GET");
                    ConfigRequest("GET", asyncObject);
                };
                this.ExecuteFunction(asyncObject, func);
            },

            post: function (asyncObject) {
                if (this.options === undefined) {
                    this.init();
                }
                asyncObject = $.extend(true, $.asyncRequest.defaults.asyncObject, asyncObject);
                var options = this.options,
                func = function () {
                    ConfigurarAntesRequest(options, asyncObject, "POST");
                    ConfigRequest("POST", asyncObject);
                };
                this.ExecuteFunction(asyncObject, func);
            },

            update: function (asyncObject) {
                if (this.options === undefined) {
                    this.init();
                }
                asyncObject = $.extend(true, $.asyncRequest.defaults.asyncObject, asyncObject);
                var options = this.options;
                var func = function () {
                    ConfigurarAntesRequest(options, asyncObject, "UPDATE");
                    ConfigRequest("UPDATE", asyncObject);
                };
                this.ExecuteFunction(asyncObject, func);
            },

            'delete': function (asyncObject) {
                if (this.options === undefined) {
                    this.init();
                }
                asyncObject = $.extend(true, $.asyncRequest.defaults.asyncObject, asyncObject);
                var options = this.options,
                func = function () {
                    ConfigurarAntesRequest(options, asyncObject);
                    ConfigRequest("DELETE", asyncObject);
                };
                this.ExecuteFunction(asyncObject, func);
            },

            getAjax: function () {
                if (this.options === undefined) {
                    this.init();
                }
                return this.options.ajax;
            },

            ExecuteFunction: function (asyncObject, func) {

                var queueUtil = $.asyncRequest.defaults.queueUtil,
                key = queueUtil.configQueue(asyncObject);//key in queue to execute;

                if (key !== null) {//Put in Queue
                    var Objqueue = queueUtil.getQueue(key);
                    Objqueue.queue.push(function () {
                        func();
                    });
                    if (!Objqueue.Executing) {
                        Objqueue.Executing = true;
                        Objqueue.queue.execute();
                    }
                } else { //No Queue, execute!!
                    func();
                }
            },

            NotifyDefault: function (type, data) {
                var notification = null,
                msg, stack;
                if ($.jGrowl !== null) {
                    notification = new asyncRequest_Notification_JGrowl(this);
                } else if ($.noty !== null) {
                    notification = new asyncRequest_Notification_Notfy(this);
                }

                switch (type) {
                    case "success":
                        notification.successNotify();
                        break;
                    case "erro":
                        try {
                            var jsonErro = JSON.parse(data.responseText);
                            msg = jsonErro.errorMessage;
                            stack = jsonErro.ExceptionMessage + "
" + jsonErro.StackTrace;
                        } catch (exception) {//Erro not JSON, but has value
                            if (data.responseText !== null && data.responseText !== "") {
                                msg = data.responseText;
                            } else {
                                msg = data.Message === null ? data.statusText : data.Message;
                            }
                        }
                        notification.erroNotify(msg, stack, true);
                        break;
                    case "info":
                        notification.notifyInfo();
                        break;
                }
            }
        };
        return Module;
    };

    $.asyncRequest = $.fn.asyncRequest;

    $.asyncRequest.defaults = {
        ajax: $.ajax,
        loadText: "Carregando..",
        loadTextTemplate: "

${msg}

",
        queueUtil: new asyncRequest_Queue(),
        asyncObject: {
            Url: null,
            Data: null,
            //DataRequest: null, //Never use this field
            Cache: false,
            Containner: null,
            Msg: null,
            Queue: null,
            ContentType: "application/json; charset=utf-8",
            DataType: "json",
            UnblockMoment: "after",
            //function
            SuccessFunction: null,
            ErrorFunction: null,
            CompleteFunction: null
        },
        notification: {
            notifyFunction: null,
            notifyCommandType: ['POST', 'UPDATE', 'DELETE'],
            notifyTemplate: "

${msg}

",
            notifyTemplateErro: "

${msg}

${fullErroText}

${msgStack}

",
            notificationSuccessMsgDefault: 'Operação realizada com sucesso',
            notificationErrorMsgDefault: 'Ocorreu um erro ao realizar a operação',
            fullErroText: 'Erro Completo'
        }
    };

})(jQuery);<commit_msg>#14 solved<commit_after>/// <reference path="AsyncRequest.Object.js" />
/// <reference path="AsyncRequest.Queue.js" />
/// <reference path="AsyncRequest.Notification.js" />
/// <reference path="jquery.jgrowl.min.js" />
///
/*!
 * Copyright 2013 Poligono Software, Inc. and other contributors
 * Released under the MIT license
*/

(function ($) {
    "use strict";

    function ExecuteNotify(data, options, requestType, eventType) {
        if (options.notification.notifyFunction !== null) {
            options.notification.notifyCommandType.forEach(function (elem) {
                if (elem === requestType && options.notification.notifyFunction !== false) {
                    options.notification.notifyFunction(eventType, data);
                }
            });
        }
    }

    function Unblock(containner, funcBefore) {//moment is "before" / "after"

        if (containner !== false) {
            if (containner === null) { //BlockPage
                $.unblockUI({ onUnblock: funcBefore });
            } else {
                $(containner).unblock({ onUnblock: funcBefore });
            }
        }
    }

    function ConfigurarAntesRequest(options, asyncObject, requestType) {

        if (asyncObject.Msg === null || asyncObject.Msg === undefined) {
            asyncObject.Msg = options.loadTextTemplate.replace("${msg}", options.loadText);
        }
        if (asyncObject.Containner !== false) {
            if (asyncObject.Containner === null) {//BlockPage
                $.blockUI({ message: asyncObject.Msg });
            } else {
                $(asyncObject.Containner).block({ message: asyncObject.Msg });
            }
        }

        if (asyncObject.Data === null) {
            asyncObject.DataRequest = {};
        } else {
            if (asyncObject.ContentType.indexOf("application/json") !== -1) {
                asyncObject.DataRequest = JSON.stringify(asyncObject.Data);
            } else {
                asyncObject.DataRequest = asyncObject.Data;
            }
        }
        if (asyncObject.SuccessFunction !== false) {
            var func = asyncObject.SuccessFunction;
            asyncObject.SuccessFunction = function (data) {

                if (asyncObject.UnblockMoment === "before") {
                    var funcBefore = null;
                    if (func != null) {
                        funcBefore = function () {
                            func(data);
                        }
                    }
                    Unblock(asyncObject.Containner, funcBefore);

                }
                else {
                    if (func != null) {
                        func(data);
                    }
                    Unblock(asyncObject.Containner);
                }
                ExecuteNotify(data, options, requestType, 'success');
            };
        }

        if (asyncObject.ErrorFunction !== false) {
            var funcErro = asyncObject.ErrorFunction;
            asyncObject.ErrorFunction = function (data) {

                //if (asyncObject.ReturnType == "json") {
                //    if (data.responseText != null && data.responseText != "") {
                //        jsonRetorno = JSON.parse(data.responseText);
                //        jsonRetorno.Message = Core.Notification.ErrorMsgDefault;
                //        data.responseText = JSON.stringify(jsonRetorno);
                //    }
                //}

                //switch (request.statusCode().status) {
                //    //Core.HandlerErroInterno(data);
                //    //break;
                //    case 401: //Unauthorized
                //        Core.HandlerErroInterno(data);
                //        break;
                //    case 404: //Not found
                //        Core.HandlerErroInterno(data);
                //        break;
                //    case 500: //erro interno
                //        Core.HandlerErroInterno(data);
                //        break;
                //    case 400: //BadRequest
                //    default:
                //        asyncObject.ErrorFunction(data);
                //        ExecuteDynamicCommand();
                //        break
                //}
                if (asyncObject.UnblockMoment === "before") {
                    var funcBefore = null;
                    if (funcErro != null) {
                        funcBefore = function () {
                            funcErro(data);
                        }
                    }
                    Unblock(asyncObject.Containner, funcBefore);

                }
                else {
                    if (funcErro != null) {
                        funcErro(data);
                    }
                    Unblock(asyncObject.Containner);
                }
                ExecuteNotify(data, options, requestType, 'erro');

            };
        }

        //Sem utilidade ainda
        if (asyncObject.CompleteFunction !== false) {
            var funcComplete = asyncObject.CompleteFunction;
            asyncObject.CompleteFunction = function (data) {
                if (funcComplete !== null) {
                    funcComplete(data);
                }
            };
        }
    }

    function ConfigRequest(type, asyncObject) {
        $.ajax({
            type: type,
            url: asyncObject.Url,
            data: asyncObject.DataRequest,
            contentType: asyncObject.ContentType,
            success: asyncObject.SuccessFunction,
            error: asyncObject.ErrorFunction,
            complete: asyncObject.CompleteFunction,
            dataType: asyncObject.DataType
        });
    }

    $.fn.asyncRequest = new function () {
        var Module = {

            init: function (options) {
                if (this.options === undefined) {
                    var defaults = {};
                    $.extend(true, defaults, $.asyncRequest.defaults);
                    this.options = $.extend(true, defaults, options);
                } else {
                    $.extend(true, this.options, options);
                }

                if (this.options.notification.notifyFunction === null) {
                    this.options.notification.notifyFunction = this.NotifyDefault;
                }
            },

            getObjAsync: function () {
                if (this.options === undefined) {
                    this.init();
                }
                return Object.create(this.options.asyncObject);
            },

            getAsync: function (url, data, containner, successFunction, ErrorFunction, msg, queue) {
                var object = this.getObjAsync();
                object.Url = url;
                object.Data = data;
                object.SuccessFunction = successFunction;
                object.ErrorFunction = ErrorFunction;
                object.Msg = msg;
                object.Queue = queue;
                object.Containner = containner;
                this.get(object);
            },

            get: function (asyncObject) {
                if (this.options === undefined) {
                    this.init();
                }
                asyncObject = $.extend(true, $.asyncRequest.defaults.asyncObject, asyncObject);
                var options = this.options,
                func = function () {//group function to use queueKey
                    ConfigurarAntesRequest(options, asyncObject, "GET");
                    ConfigRequest("GET", asyncObject);
                };
                this.ExecuteFunction(asyncObject, func);
            },

            post: function (asyncObject) {
                if (this.options === undefined) {
                    this.init();
                }
                asyncObject = $.extend(true, $.asyncRequest.defaults.asyncObject, asyncObject);
                var options = this.options,
                func = function () {
                    ConfigurarAntesRequest(options, asyncObject, "POST");
                    ConfigRequest("POST", asyncObject);
                };
                this.ExecuteFunction(asyncObject, func);
            },

            update: function (asyncObject) {
                if (this.options === undefined) {
                    this.init();
                }
                asyncObject = $.extend(true, $.asyncRequest.defaults.asyncObject, asyncObject);
                var options = this.options;
                var func = function () {
                    ConfigurarAntesRequest(options, asyncObject, "UPDATE");
                    ConfigRequest("UPDATE", asyncObject);
                };
                this.ExecuteFunction(asyncObject, func);
            },

            'delete': function (asyncObject) {
                if (this.options === undefined) {
                    this.init();
                }
                asyncObject = $.extend(true, $.asyncRequest.defaults.asyncObject, asyncObject);
                var options = this.options,
                func = function () {
                    ConfigurarAntesRequest(options, asyncObject);
                    ConfigRequest("DELETE", asyncObject);
                };
                this.ExecuteFunction(asyncObject, func);
            },

            getAjax: function () {
                if (this.options === undefined) {
                    this.init();
                }
                return this.options.ajax;
            },

            ExecuteFunction: function (asyncObject, func) {

                var queueUtil = $.asyncRequest.defaults.queueUtil,
                key = queueUtil.configQueue(asyncObject);//key in queue to execute;

                if (key !== null) {//Put in Queue
                    var Objqueue = queueUtil.getQueue(key);
                    Objqueue.queue.push(function () {
                        func();
                    });
                    if (!Objqueue.Executing) {
                        Objqueue.Executing = true;
                        Objqueue.queue.execute();
                    }
                } else { //No Queue, execute!!
                    func();
                }
            },

            NotifyDefault: function (type, data) {
                var notification = null,
                msg, stack;
                if ($.jGrowl !== null) {
                    notification = new asyncRequest_Notification_JGrowl(this);
                } else if ($.noty !== null) {
                    notification = new asyncRequest_Notification_Notfy(this);
                }

                switch (type) {
                    case "success":
                        notification.successNotify();
                        break;
                    case "erro":
                        try {
                            var jsonErro = JSON.parse(data.responseText);
                            msg = jsonErro.errorMessage;
                            stack = jsonErro.ExceptionMessage + "
" + jsonErro.StackTrace;
                        } catch (exception) {//Erro not JSON, but has value
                            if (data.responseText !== null && data.responseText !== "") {
                                msg = data.responseText;
                            } else {
                                msg = data.Message === null ? data.statusText : data.Message;
                            }
                        }
                        notification.erroNotify(msg, stack, true);
                        break;
                    case "info":
                        notification.notifyInfo();
                        break;
                }
            }
        };
        return Module;
    };

    $.asyncRequest = $.fn.asyncRequest;

    $.asyncRequest.defaults = {
        ajax: $.ajax,
        loadText: "Carregando..",
        loadTextTemplate: "

${msg}

",
        queueUtil: new asyncRequest_Queue(),
        asyncObject: {
            Url: null,
            Data: null,
            //DataRequest: null, //Never use this field
            Cache: false,
            Containner: null,
            Msg: null,
            Queue: null,
            ContentType: "application/json; charset=utf-8",
            DataType: "json",
            UnblockMoment: "after",
            //function
            SuccessFunction: null,
            ErrorFunction: null,
            CompleteFunction: null
        },
        notification: {
            notifyFunction: null,
            notifyCommandType: ['POST', 'UPDATE', 'DELETE'],
            notifyTemplate: "

${msg}

",
            notifyTemplateErro: "

${msg}

${fullErroText}

${msgStack}

",
            notificationSuccessMsgDefault: 'Operação realizada com sucesso',
            notificationErrorMsgDefault: 'Ocorreu um erro ao realizar a operação',
            fullErroText: 'Erro Completo'
        }
    };

})(jQuery);<|endoftext|>