<commit_before>var Slime = require('./slime');
var Ball = require('./ball');
var Net = require('./net');
var CollisionDetector = require('./collision-detector');
var netCollisionDetector = require('./net-collision-detector');
var Scoreboard = require('./scoreboard');

function Game(){
  this.setCanvasAndContext();

  this.resetPoint("left");
  this.scoreboard = new Scoreboard(this.canvas);

  this.canvas.addEventListener("ballHitLeftSideOfFloor", function(e) { this.setUpNewPoint("left"); }.bind(this), false);
  this.canvas.addEventListener("ballHitRightSideOfFloor", function(e) { this.setUpNewPoint("right"); }.bind(this), false);
  this.canvas.addEventListener("rightSlimeWins", function(e) { this.endGameWithWinner("right"); }.bind(this), false);
  this.canvas.addEventListener("leftSlimeWins", function(e) { this.endGameWithWinner("left"); }.bind(this), false);
};

Game.prototype = {
  start: function () {
    requestAnimationFrame(function gameLoop() {
      this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);

      this.move();
      this.draw();
      this.detectCollisions();

      if (this.gameOver) {
        this.endGame();
      } else {
        requestAnimationFrame(gameLoop.bind(this));
      }
    }.bind(this));
  },

  setCanvasAndContext: function () {
    this.canvas = document.getElementById("game");
    this.context = this.canvas.getContext("2d");
  },

  draw: function () {
    this.slimes.forEach(function(slime) {
      slime.draw();
    })

    this.ball.draw(this.context);
    this.net.draw(this.context);
    this.scoreboard.draw(this.context);
  },

  move: function () {
    this.slimes.forEach(function(slime) { slime.move(); })

    this.ball.move();
  },

  detectCollisions: function () {
    this.collisionDetectors.forEach(function(detector) {
      detector.detectCollision(this.canvas);
    }.bind(this))
  },

  createSlimes: function () {
    var slimes = [];

    slimes.push(new Slime(150, 375, "deeppink", "KeyA", "KeyD", this.context, this.canvas, true));
    slimes.push(new Slime(600, 375, "dodgerblue", "ArrowLeft", "ArrowRight", this.context, this.canvas, false));

    return slimes;
  },

  createCollisionDetectors: function () {
    var collisionDetectors = this.slimes.map(function(slime) {
      return new CollisionDetector(slime, this.ball);
    }.bind(this))

    collisionDetectors.push(new netCollisionDetector(this.net, this.ball));
    return collisionDetectors;
  },

  setUpNewPoint: function (side) {
    setTimeout(function() {
      this.resetPoint(side);
    }.bind(this), 1000);
  },

  resetPoint: function (side) {
    this.slimes = this.createSlimes(this.context, this.canvas);

    if (side == "left") { var ballX = this.slimes[1].x }
    else if (side == "right") { var ballX = this.slimes[0].x }

    this.ball = new Ball(ballX, 250, this.canvas);
    this.net  = new Net(this.canvas.width, this.canvas.height);
    this.collisionDetectors = this.createCollisionDetectors();
  },

  endGameWithWinner: function (side) {
    this.gameOver = true;

    if (side == "right") {
      this.winner = "Player 2";
    } else if (side == "left") {
      this.winner = "Player 1";
    }
  },

  endGame: function () {
    this.removeAllEventListeners();
    this.drawGameOverScreen();
  },

  removeAllEventListeners: function () {
    var oldCanvas = document.getElementById("game");
    var newCanvas = oldCanvas.cloneNode(true);

    oldCanvas.parentNode.replaceChild(newCanvas, oldCanvas);

    this.setCanvasAndContext();
  },

  drawGameOverScreen: function () {
    // draw screen
    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    this.context.font = "48px sans-serif";
    this.context.textAlign = "center";
    this.context.fillStyle = "lightgrey"
    this.context.fillText(this.winner + " wins!", this.canvas.width/2 , this.canvas.height / 2);

    // create event listner
      // - reset score and point on space being clicked
      // - remove itself (it is an event listener)
  }
}

module.exports = Game;
<commit_msg>Players can start a new game after it ends<commit_after>var Slime = require('./slime');
var Ball = require('./ball');
var Net = require('./net');
var CollisionDetector = require('./collision-detector');
var netCollisionDetector = require('./net-collision-detector');
var Scoreboard = require('./scoreboard');

function Game(){
  this.setCanvasAndContext();
  this.setUpNewGame();
};

Game.prototype = {
  start: function () {
    requestAnimationFrame(function gameLoop() {
      this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);

      this.move();
      this.draw();
      this.detectCollisions();

      if (this.gameOver) {
        this.endGame();
      } else {
        requestAnimationFrame(gameLoop.bind(this));
      }
    }.bind(this));
  },

  addEventListeners: function () {
    this.canvas.addEventListener("ballHitLeftSideOfFloor", function(e) { this.setUpNewPoint("left"); }.bind(this), false);
    this.canvas.addEventListener("ballHitRightSideOfFloor", function(e) { this.setUpNewPoint("right"); }.bind(this), false);
    this.canvas.addEventListener("rightSlimeWins", function(e) { this.endGameWithWinner("right"); }.bind(this), false);
    this.canvas.addEventListener("leftSlimeWins", function(e) { this.endGameWithWinner("left"); }.bind(this), false);
  },

  setCanvasAndContext: function () {
    this.canvas = document.getElementById("game");
    this.context = this.canvas.getContext("2d");
  },

  draw: function () {
    this.slimes.forEach(function(slime) {
      slime.draw();
    })

    this.ball.draw(this.context);
    this.net.draw(this.context);
    this.scoreboard.draw(this.context);
  },

  move: function () {
    this.slimes.forEach(function(slime) { slime.move(); })

    this.ball.move();
  },

  detectCollisions: function () {
    this.collisionDetectors.forEach(function(detector) {
      detector.detectCollision(this.canvas);
    }.bind(this))
  },

  createSlimes: function () {
    var slimes = [];

    slimes.push(new Slime(150, 375, "deeppink", "KeyA", "KeyD", this.context, this.canvas, true));
    slimes.push(new Slime(600, 375, "dodgerblue", "ArrowLeft", "ArrowRight", this.context, this.canvas, false));

    return slimes;
  },

  createCollisionDetectors: function () {
    var collisionDetectors = this.slimes.map(function(slime) {
      return new CollisionDetector(slime, this.ball);
    }.bind(this))

    collisionDetectors.push(new netCollisionDetector(this.net, this.ball));
    return collisionDetectors;
  },

  setUpNewPoint: function (side) {
    setTimeout(function() {
      this.resetPoint(side);
    }.bind(this), 1000);
  },

  resetPoint: function (side) {
    this.slimes = this.createSlimes(this.context, this.canvas);

    if (side == "left") { var ballX = this.slimes[1].x }
    else if (side == "right") { var ballX = this.slimes[0].x }

    this.ball = new Ball(ballX, 250, this.canvas);
    this.collisionDetectors = this.createCollisionDetectors();
  },

  setUpNewGame: function () {
    this.gameOver = false;
    this.slimes = this.createSlimes(this.context, this.canvas);

    this.ball = new Ball(this.slimes[0].x, 250, this.canvas);
    this.net  = new Net(this.canvas.width, this.canvas.height);
    this.scoreboard = new Scoreboard(this.canvas);
    this.collisionDetectors = this.createCollisionDetectors();

    this.addEventListeners();
  },

  endGameWithWinner: function (side) {
    this.gameOver = true;

    if (side == "right") {
      this.winner = "Player 2";
    } else if (side == "left") {
      this.winner = "Player 1";
    }
  },

  endGame: function () {
    this.removeAllEventListeners();
    this.drawGameOverScreen();
  },

  removeAllEventListeners: function () {
    var oldCanvas = document.getElementById("game");
    var newCanvas = oldCanvas.cloneNode(true);

    oldCanvas.parentNode.replaceChild(newCanvas, oldCanvas);

    this.setCanvasAndContext();
  },

  drawGameOverScreen: function () {
    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    this.context.font = "48px sans-serif";
    this.context.textAlign = "center";
    this.context.fillStyle = "lightgrey"
    this.context.fillText(this.winner + " wins!", this.canvas.width/2 , this.canvas.height / 2);

    this.context.font = "18px sans-serif";
    this.context.fillText("Press any key to play again", this.canvas.width/2 , this.canvas.height / 2 + 40);

    this.newGameHandler = function (e) { this.restartGame(e) }.bind(this)
    window.addEventListener("keydown", this.newGameHandler, false);
  },

  restartGame: function (e) {
    e.view.removeEventListener("keydown", this.newGameHandler, false);
    this.setUpNewGame();
    this.start();
  }
}

module.exports = Game;
<|endoftext|>


<commit_before>var fs = require('fs');
var request = require('superagent');
var async = require('async');

global.client_list = './peers-list.txt'

global.set0 = []; // set0 contains hosts have the complete file
global.set1 = []; // set1 contains hosts don't have it yet

function do_match_hosts = function() {
  if (set1.length === 0) {
    console.log('Complete file distribution, bye~');
    process.exit(0);
  }

  var hungry_host_arr = set1.filter(function(node){
    return node.status === 'hungry';
  });

  if (hungry_host_arr.length === 0) {
    console.log('No more hungry hosts, just wait');
    return ;
  }

  var satisfied_host_arr = set0.filter(function(node){
    return node.status === 'satisfied';
  });

  if (satisfied_host_arr.length === 0) {
    console.log('No more satisfied hosts, just wait');
    return ;
  }

  var hungry_host = hungry_host_arr[0];
  var satisfied_host = satisfied_host_arr[0];

  provoke_trasfer(satisfied_host, hungry_host);
}

exports.match_hosts = function() {
  do_match_hosts();
}

function change_transferred_host_status(cmd_obj) {
  var from_addr = cmd_obj.from;
  var to_addr = cmd_obj.to;

  var from_host = set0.filter(function(node){
    return node.host === from_addr;
  });
  from_host.status = 'satisfied';

  var to_host = set1.filter(function(node){
    return node.host === to_addr;
  });

  var to_host_index = set1.indexOf(to_host);
  set1.splice(to_host_index, 1);

  to_host.status = 'satisfied';
  set0.push(to_host);
}

function change_transfer_failed_host_status(cmd_obj) {
  var from_addr = cmd_obj.from;
  var to_addr = cmd_obj.to;

  var from_host = set0.filter(function(node){
    return node.host === from_addr;
  });
  from_host.status = 'satisfied';

  var to_host = set1.filter(function(node){
    return node.host === to_addr;
  });

  to_host.status = 'hungry';
}

function change_transfering_host_status(from_host, to_host) {
  from_host.status = 'sending';
  to_host.status = 'receving';
}

function provoke_trasfer(from_host, to_host) {
  console.log('Provoke trasferation, from ' + from_host.host + ':' + from_host.file_path + ', to ' + to_host.host + ':' + to_host.file_path);
  request.post(from_host.host + ':' + port)
    .send(
      {'cmd' : 'transfer',
       'from' : from_host.host,
       'from_path' : from_host.file_path,
       'to' : to_host.host,
       'to_path' : to_host.file_path
      })
    .end(function(error, res){
      if (error) {
	console.error('Send transfer command to ' + from_host.host + ' error!' + error);
	return ;
      }
      change_transfering_host_status(from_host, to_host);

      console.log('After matching hosts:');
      console.log('==================================');
      console.log(set0);
      console.log(set1);
      console.log('==================================');

      match_hosts();
    });
}

exports.load_clients = function (cb) {
  var clients_arr = fs.readFileSync(client_list).toString().split("\n");
  clients_arr = clients_arr.filter(function(value){
    return value != '';
  });
  async.map(clients_arr, spike_client, function(err, results){
    if (err) {
      console.log(err);
      process.exit(1);
    }
    cb(clients_arr, results);
  });

}

function spike_client(hostname, cb) {
  if ( hostname === '')
      return ;

  request.post(hostname + ':' + port)
    .send({'cmd': 'spike'})
    .end(function(error, res){
      if (error) {
	console.error('Spike client host ' + hostname +' error!' + error);
	return ;
      }

      var body = "";  // Extract path from client respond
      res.on('data', function (chunk) {
	body += chunk;
      });
      res.on('end', function () {
	cb(null, body);
      });
    });
}
<commit_msg>Fix error<commit_after>var fs = require('fs');
var request = require('superagent');
var async = require('async');

global.client_list = './peers-list.txt'

global.set0 = []; // set0 contains hosts have the complete file
global.set1 = []; // set1 contains hosts don't have it yet

function do_match_hosts() {
  if (set1.length === 0) {
    console.log('Complete file distribution, bye~');
    process.exit(0);
  }

  var hungry_host_arr = set1.filter(function(node){
    return node.status === 'hungry';
  });

  if (hungry_host_arr.length === 0) {
    console.log('No more hungry hosts, just wait');
    return ;
  }

  var satisfied_host_arr = set0.filter(function(node){
    return node.status === 'satisfied';
  });

  if (satisfied_host_arr.length === 0) {
    console.log('No more satisfied hosts, just wait');
    return ;
  }

  var hungry_host = hungry_host_arr[0];
  var satisfied_host = satisfied_host_arr[0];

  provoke_trasfer(satisfied_host, hungry_host);
}

exports.match_hosts = function() {
  do_match_hosts();
}

function change_transferred_host_status(cmd_obj) {
  var from_addr = cmd_obj.from;
  var to_addr = cmd_obj.to;

  var from_host = set0.filter(function(node){
    return node.host === from_addr;
  });
  from_host.status = 'satisfied';

  var to_host = set1.filter(function(node){
    return node.host === to_addr;
  });

  var to_host_index = set1.indexOf(to_host);
  set1.splice(to_host_index, 1);

  to_host.status = 'satisfied';
  set0.push(to_host);
}

function change_transfer_failed_host_status(cmd_obj) {
  var from_addr = cmd_obj.from;
  var to_addr = cmd_obj.to;

  var from_host = set0.filter(function(node){
    return node.host === from_addr;
  });
  from_host.status = 'satisfied';

  var to_host = set1.filter(function(node){
    return node.host === to_addr;
  });

  to_host.status = 'hungry';
}

function change_transfering_host_status(from_host, to_host) {
  from_host.status = 'sending';
  to_host.status = 'receving';
}

function provoke_trasfer(from_host, to_host) {
  console.log('Provoke trasferation, from ' + from_host.host + ':' + from_host.file_path + ', to ' + to_host.host + ':' + to_host.file_path);
  request.post(from_host.host + ':' + port)
    .send(
      {'cmd' : 'transfer',
       'from' : from_host.host,
       'from_path' : from_host.file_path,
       'to' : to_host.host,
       'to_path' : to_host.file_path
      })
    .end(function(error, res){
      if (error) {
	console.error('Send transfer command to ' + from_host.host + ' error!' + error);
	return ;
      }
      change_transfering_host_status(from_host, to_host);

      console.log('After matching hosts:');
      console.log('==================================');
      console.log(set0);
      console.log(set1);
      console.log('==================================');

      match_hosts();
    });
}

exports.load_clients = function (cb) {
  var clients_arr = fs.readFileSync(client_list).toString().split("\n");
  clients_arr = clients_arr.filter(function(value){
    return value != '';
  });
  async.map(clients_arr, spike_client, function(err, results){
    if (err) {
      console.log(err);
      process.exit(1);
    }
    cb(clients_arr, results);
  });

}

function spike_client(hostname, cb) {
  if ( hostname === '')
      return ;

  request.post(hostname + ':' + port)
    .send({'cmd': 'spike'})
    .end(function(error, res){
      if (error) {
	console.error('Spike client host ' + hostname +' error!' + error);
	return ;
      }

      var body = "";  // Extract path from client respond
      res.on('data', function (chunk) {
	body += chunk;
      });
      res.on('end', function () {
	cb(null, body);
      });
    });
}
<|endoftext|>


<commit_before>'use strict';

/* This is a simple cache intended to reduce the amount of load
 * Nightscout puts on MongoDB. The cache is based on identifying
 * elements based on the MongoDB _id field and implements simple
 * semantics for adding data to the cache in the runtime, intended
 * to be accessed by the persistence layer as data is inserted, updated
 * or deleted, as well as the periodic dataloader, which polls Mongo
 * for new inserts.
 *
 * Longer term, the cache is planned to allow skipping the Mongo polls
 * altogether.
 */

const _ = require('lodash');
const constants = require('../constants');

function cache (env, ctx) {

  const data = {
    treatments: []
    , devicestatus: []
    , entries: []
  };

  const retentionPeriods = {
    treatments: constants.ONE_HOUR * 60
    , devicestatus: env.extendedSettings.devicestatus && env.extendedSettings.devicestatus.days && env.extendedSettings.devicestatus.days == 2 ? constants.TWO_DAYS : constants.ONE_DAY
    , entries: constants.TWO_DAYS
  };

  function mergeCacheArrays (oldData, newData, retentionPeriod) {

    const ageLimit = Date.now() - retentionPeriod;

    var filteredOld =  filterForAge(oldData, ageLimit);
    var filteredNew = filterForAge(newData, ageLimit);

    const merged = ctx.ddata.idMergePreferNew(filteredOld, filteredNew);

    return _.sortBy(merged, function(item) {
      return -item.mills;
    });

    function filterForAge(data, ageLimit) {
      return _.filter(data, function hasId(object) {
        const hasId = !_.isEmpty(object._id);
        const isFresh = object.mills >= ageLimit;
        return isFresh && hasId;
      });
    }

  }

  data.isEmpty = (datatype) => {
    return data[datatype].length == 0;
  }

  data.getData = (datatype) => {
    return _.cloneDeep(data[datatype]);
  }

  data.insertData = (datatype, newData) => {
    data[datatype] = mergeCacheArrays(data[datatype], newData, retentionPeriods[datatype]);
    return data.getData(datatype);
  }

  function dataChanged (operation) {
    if (!data[operation.type]) return;

    if (operation.op == 'remove') {
      // if multiple items were deleted, flush entire cache
      if (!operation.changes) {
        data.treatments = [];
        data.devicestatus = [];
        data.entries = [];
      } else {
        removeFromArray(data[operation.type], operation.changes);
      }
    }

    if (operation.op == 'update') {
      data[operation.type] = mergeCacheArrays(data[operation.type], operation.changes, retentionPeriods[operation.type]);
    }
  }

  ctx.bus.on('data-update', dataChanged);

  function removeFromArray (array, id) {
    for (let i = 0; i < array.length; i++) {
      const o = array[i];
      if (o._id == id) {
        //console.log('Deleting object from cache', id);
        array.splice(i, 1);
        break;
      }
    }
  }

  return data;
}

module.exports = cache;
<commit_msg>Make empty cache detection a bit more aggressive to account for cache flush and data insert happening concurrently<commit_after>'use strict';

/* This is a simple cache intended to reduce the amount of load
 * Nightscout puts on MongoDB. The cache is based on identifying
 * elements based on the MongoDB _id field and implements simple
 * semantics for adding data to the cache in the runtime, intended
 * to be accessed by the persistence layer as data is inserted, updated
 * or deleted, as well as the periodic dataloader, which polls Mongo
 * for new inserts.
 *
 * Longer term, the cache is planned to allow skipping the Mongo polls
 * altogether.
 */

const _ = require('lodash');
const constants = require('../constants');

function cache (env, ctx) {

  const data = {
    treatments: []
    , devicestatus: []
    , entries: []
  };

  const retentionPeriods = {
    treatments: constants.ONE_HOUR * 60
    , devicestatus: env.extendedSettings.devicestatus && env.extendedSettings.devicestatus.days && env.extendedSettings.devicestatus.days == 2 ? constants.TWO_DAYS : constants.ONE_DAY
    , entries: constants.TWO_DAYS
  };

  function mergeCacheArrays (oldData, newData, retentionPeriod) {

    const ageLimit = Date.now() - retentionPeriod;

    var filteredOld =  filterForAge(oldData, ageLimit);
    var filteredNew = filterForAge(newData, ageLimit);

    const merged = ctx.ddata.idMergePreferNew(filteredOld, filteredNew);

    return _.sortBy(merged, function(item) {
      return -item.mills;
    });

    function filterForAge(data, ageLimit) {
      return _.filter(data, function hasId(object) {
        const hasId = !_.isEmpty(object._id);
        const isFresh = object.mills >= ageLimit;
        return isFresh && hasId;
      });
    }

  }

  data.isEmpty = (datatype) => {
    return data[datatype].length < 20;
  }

  data.getData = (datatype) => {
    return _.cloneDeep(data[datatype]);
  }

  data.insertData = (datatype, newData) => {
    data[datatype] = mergeCacheArrays(data[datatype], newData, retentionPeriods[datatype]);
    return data.getData(datatype);
  }

  function dataChanged (operation) {
    if (!data[operation.type]) return;

    if (operation.op == 'remove') {
      // if multiple items were deleted, flush entire cache
      if (!operation.changes) {
        data.treatments = [];
        data.devicestatus = [];
        data.entries = [];
      } else {
        removeFromArray(data[operation.type], operation.changes);
      }
    }

    if (operation.op == 'update') {
      data[operation.type] = mergeCacheArrays(data[operation.type], operation.changes, retentionPeriods[operation.type]);
    }
  }

  ctx.bus.on('data-update', dataChanged);

  function removeFromArray (array, id) {
    for (let i = 0; i < array.length; i++) {
      const o = array[i];
      if (o._id == id) {
        //console.log('Deleting object from cache', id);
        array.splice(i, 1);
        break;
      }
    }
  }

  return data;
}

module.exports = cache;
<|endoftext|>


<commit_before>(function(object) {
    'use strict';

    if(!global.cloudcmd)
        return console.log(
            '# files.js'                                        + '\n'  +
            '# -----------'                                     + '\n'  +
            '# Module is part of Cloud Commander,'              + '\n'  +
            '# used for reading a couple files.'                + '\n'  +
            '# http://cloudcmd.io'                              + '\n');

    var main        = global.cloudcmd.main,
        fs          = main.fs,
        path        = main.path,
        pipe        = main.pipe,
        CloudFunc   = main.cloudfunc,
        Util        = main.util;

    object.read     = function(pFiles, pCallBack) {
        var lDone = [],
            lFiles,
            lErrors,
            i, n,
            lName,
            lReadedFiles = {},
            lDoneFunc = function (pParams) {
                var msg, status, p, lName,
                    lRet =  Util.checkObj(pParams, ['error', 'data', 'params']);

                if (lRet) {
                    lDone.pop();
                    p       = pParams,
                    lName   = p.params;

                    if (p.error) {
                        status = 'error';

                        if (!lErrors)
                            lErrors = {};

                        lErrors[lName] = p.error;
                    }
                    else {
                        status = 'ok';
                        lReadedFiles[lName] = p.data;
                    }

                    lName   = path.basename(lName);
                    msg     = CloudFunc.formatMsg('read', lName, status);

                    Util.log(msg);

                    if (!lDone.length)
                        Util.exec(pCallBack, lErrors, lReadedFiles);
                }
            };

        if (Util.isArray(pFiles))
            lFiles = pFiles;
        else
            lFiles = [pFiles];

        for(i = 0, n = lFiles.length; i < n; i++) {
            lName = lFiles.pop();
            lDone.push(lName);

            fs.readFile(lName, Util.call(lDoneFunc, lName));
        }
    };

    object.readPipe     = readPipe;

    function readPipe(files, writeStream, callback) {
        var name, length = files && files.length;

        if (!length)
            Util.exec(callback);
        else {
            name = files.pop();

            pipe.create({
                from    : name,
                write   : writeStream,
                callback: function(error) {
                    if (error)
                        Util.exec(callback, error);
                    else
                        if (!length)
                            Util.exec(callback);
                        else
                            readPipe(files, writeStream, callback);
                }
            });
        }
    }

})(this);
<commit_msg>feature(files) readPipe: add dir<commit_after>(function(object) {
    'use strict';

    if(!global.cloudcmd)
        return console.log(
            '# files.js'                                        + '\n'  +
            '# -----------'                                     + '\n'  +
            '# Module is part of Cloud Commander,'              + '\n'  +
            '# used for reading a couple files.'                + '\n'  +
            '# http://cloudcmd.io'                              + '\n');

    var main        = global.cloudcmd.main,
        fs          = main.fs,
        path        = main.path,
        pipe        = main.pipe,
        CloudFunc   = main.cloudfunc,
        Util        = main.util;

    object.read     = function(pFiles, pCallBack) {
        var lDone = [],
            lFiles,
            lErrors,
            i, n,
            lName,
            lReadedFiles = {},
            lDoneFunc = function (pParams) {
                var msg, status, p, lName,
                    lRet =  Util.checkObj(pParams, ['error', 'data', 'params']);

                if (lRet) {
                    lDone.pop();
                    p       = pParams,
                    lName   = p.params;

                    if (p.error) {
                        status = 'error';

                        if (!lErrors)
                            lErrors = {};

                        lErrors[lName] = p.error;
                    }
                    else {
                        status = 'ok';
                        lReadedFiles[lName] = p.data;
                    }

                    lName   = path.basename(lName);
                    msg     = CloudFunc.formatMsg('read', lName, status);

                    Util.log(msg);

                    if (!lDone.length)
                        Util.exec(pCallBack, lErrors, lReadedFiles);
                }
            };

        if (Util.isArray(pFiles))
            lFiles = pFiles;
        else
            lFiles = [pFiles];

        for(i = 0, n = lFiles.length; i < n; i++) {
            lName = lFiles.pop();
            lDone.push(lName);

            fs.readFile(lName, Util.call(lDoneFunc, lName));
        }
    };

    object.readPipe     = readPipe;

    function readPipe(files, dir, writeStream, callback) {
        var name, length = files && files.length;

        if (!length) {
            writeStream.end();
            Util.exec(callback);
        } else {
            name = dir + files.pop();

            pipe.create({
                from    : name,
                write   : writeStream,
                callback: function(error) {
                    if (error)
                        Util.exec(callback, error);
                    else
                        if (!length)
                            Util.exec(callback);
                        else
                            readPipe(files, dir, writeStream, callback);
                }
            });
        }
    }

})(this);
<|endoftext|>


<commit_before>(function() {
    'use strict';

    var DIR         = __dirname + '/../../',
        DIR_TMPL    = DIR       + 'tmpl/',
        DIR_HTML    = DIR       + 'html/',
        DIR_LIB     = DIR       + 'lib/',
        DIR_JSON    = DIR       + 'json/',
        DIR_SERVER  = __dirname + '/',
        DIR_FS      = DIR_TMPL  + 'fs/',

        fs          = require('fs'),

        flop        = require('flop'),
        ponse       = require('ponse'),
        files       = require('files-io'),
        rendy       = require('rendy'),
        exec        = require('execon'),

        minify      = require('minify'),
        format      = require('format-io'),
        squad       = require('squad'),
        apart       = require('apart'),

        config      = require(DIR_SERVER + 'config'),
        root        = require(DIR_SERVER + 'root'),
        prefixer    = require(DIR_SERVER + 'prefixer'),
        prefix      = squad(prefixer, apart(config, 'prefix')),

        CloudFunc   = require(DIR_LIB + 'cloudfunc'),

        PATH_INDEX  = DIR_HTML   + 'index.html',

        TMPL_PATH   = [
            'file',
            'panel',
            'path',
            'pathLink',
            'link'
        ],

        Template    = {},

        FS          = CloudFunc.FS,

        CSS_URL   = require(DIR_JSON + 'css.json')
            .map(function(name) {
                return 'css/' + name + '.css';
            }).join(':');

    module.exports = function (req, res, next) {
        readFiles(function() {
            route(req, res, next);
        });
    };

    /**
     * additional processing of index file
     */
    function indexProcessing(options) {
        var left, right, from, to,
            keysPanel   = '<div id="js-keyspanel" class="{{ className }}',
            data        = options.data,
            panel       = options.panel;

        if (!config('showKeysPanel')) {
            from        = rendy(keysPanel, {
                className: 'keyspanel'
            });

            to          = rendy(keysPanel, {
                className: 'keyspanel hidden'
            });

            data        = data.replace(from, to);
        }

        left = rendy(Template.panel, {
            side    : 'left',
            content : panel
        });

        right = rendy(Template.panel, {
            side    : 'right',
            content : panel
        });

        data = rendy(data, {
            title   : CloudFunc.getTitle(),
            fm      : left + right,
            prefix  : prefix(),
            css     : CSS_URL
        });

        return data;
    }

    function readFiles(callback) {
        var filesList,
            paths       = {},

            lengthTmpl  = Object.keys(Template).length,
            lenthPath   = TMPL_PATH.length,
            isRead      = lengthTmpl === lenthPath;

        if (typeof callback !== 'function')
            throw Error('callback should be function!');

        if (isRead) {
            callback();
        } else {
            filesList   = TMPL_PATH.map(function(name) {
                var path = DIR_FS + name + '.hbs';

                paths[path] = name;

                return path;
            });

            files.read(filesList, 'utf8', function(error, files) {
                if (error)
                    throw error;
                else
                    Object.keys(files).forEach(function(path) {
                        var name = paths[path];

                        Template[name] = files[path];
                    });

                callback();
            });
        }
    }

    /**
     * routing of server queries
     */
    function route(request, response, callback) {
        var name, p, isAuth, isFS, fullPath;

        if (!request)
            throw Error('request could not be empty!');

        if (!response)
            throw Error('response could not be empty!');

        if (typeof callback !== 'function')
            throw Error('callback should be function!');

        name    = ponse.getPathName(request);

        isAuth  = RegExp('^(/auth|/auth/github)$').test(name);
        isFS    = RegExp('^/$|^' + FS).test(name);

        p       = {
            request     : request,
            response    : response,
            gzip        : true,
            name        : name
        };

        if (!isAuth && !isFS)
            callback();
        else if (isAuth) {
            p.name = DIR_HTML + name + '.html';
            ponse.sendFile(p);
        } else if (isFS) {
            name        = name.replace(CloudFunc.FS, '') || '/';
            fullPath    = root(name);

            flop.read(fullPath, function(error, dir) {
                if (dir)
                    dir.path = format.addSlashToEnd(name);

                if (!error)
                    buildIndex(dir, function(error, data) {
                        p.name = PATH_INDEX;

                        if (error)
                            ponse.sendError(error, p);
                        else
                            ponse.send(data, p);
                    });
                else if (error.code !== 'ENOTDIR')
                    ponse.sendError(error, p);
                else
                    fs.realpath(fullPath, function(error, pathReal) {
                        if (!error)
                            p.name = pathReal;
                        else
                            p.name = name;

                        p.gzip = false;
                        ponse.sendFile(p);
                    });
            });
        }
    }

    function buildIndex(json, callback) {
        var isMinify = config('minify');

        exec.if(!isMinify, function(error, name) {
            fs.readFile(name || PATH_INDEX, 'utf8', function(error, template) {
                var panel, data;

                if (!error) {
                    panel   = CloudFunc.buildFromJSON({
                        data        : json,
                        prefix      : prefix(),
                        template    : Template
                    }),

                    data    = indexProcessing({
                        panel   : panel,
                        data    : template
                    });
                }

                callback(error, data);
            });
        },  function(callback) {
                minify(PATH_INDEX, 'name', callback);
        });
    }
})();
<commit_msg>chore(route) rm "\n"<commit_after>(function() {
    'use strict';

    var DIR         = __dirname + '/../../',
        DIR_TMPL    = DIR       + 'tmpl/',
        DIR_HTML    = DIR       + 'html/',
        DIR_LIB     = DIR       + 'lib/',
        DIR_JSON    = DIR       + 'json/',
        DIR_SERVER  = __dirname + '/',
        DIR_FS      = DIR_TMPL  + 'fs/',

        fs          = require('fs'),

        flop        = require('flop'),
        ponse       = require('ponse'),
        files       = require('files-io'),
        rendy       = require('rendy'),
        exec        = require('execon'),

        minify      = require('minify'),
        format      = require('format-io'),
        squad       = require('squad'),
        apart       = require('apart'),

        config      = require(DIR_SERVER + 'config'),
        root        = require(DIR_SERVER + 'root'),
        prefixer    = require(DIR_SERVER + 'prefixer'),
        prefix      = squad(prefixer, apart(config, 'prefix')),

        CloudFunc   = require(DIR_LIB + 'cloudfunc'),

        PATH_INDEX  = DIR_HTML   + 'index.html',

        TMPL_PATH   = [
            'file',
            'panel',
            'path',
            'pathLink',
            'link'
        ],

        Template    = {},

        FS          = CloudFunc.FS,

        CSS_URL   = require(DIR_JSON + 'css.json')
            .map(function(name) {
                return 'css/' + name + '.css';
            }).join(':');

    module.exports = function(req, res, next) {
        readFiles(function() {
            route(req, res, next);
        });
    };

    /**
     * additional processing of index file
     */
    function indexProcessing(options) {
        var left, right, from, to,
            keysPanel   = '<div id="js-keyspanel" class="{{ className }}',
            data        = options.data,
            panel       = options.panel;

        if (!config('showKeysPanel')) {
            from        = rendy(keysPanel, {
                className: 'keyspanel'
            });

            to          = rendy(keysPanel, {
                className: 'keyspanel hidden'
            });

            data        = data.replace(from, to);
        }

        left = rendy(Template.panel, {
            side    : 'left',
            content : panel
        });

        right = rendy(Template.panel, {
            side    : 'right',
            content : panel
        });

        data = rendy(data, {
            title   : CloudFunc.getTitle(),
            fm      : left + right,
            prefix  : prefix(),
            css     : CSS_URL
        });

        return data;
    }

    function readFiles(callback) {
        var filesList,
            paths       = {},

            lengthTmpl  = Object.keys(Template).length,
            lenthPath   = TMPL_PATH.length,
            isRead      = lengthTmpl === lenthPath;

        if (typeof callback !== 'function')
            throw Error('callback should be function!');

        if (isRead) {
            callback();
        } else {
            filesList   = TMPL_PATH.map(function(name) {
                var path = DIR_FS + name + '.hbs';

                paths[path] = name;

                return path;
            });

            files.read(filesList, 'utf8', function(error, files) {
                if (error)
                    throw error;
                else
                    Object.keys(files).forEach(function(path) {
                        var name = paths[path];

                        Template[name] = files[path];
                    });

                callback();
            });
        }
    }

    /**
     * routing of server queries
     */
    function route(request, response, callback) {
        var name, p, isAuth, isFS, fullPath;

        if (!request)
            throw Error('request could not be empty!');

        if (!response)
            throw Error('response could not be empty!');

        if (typeof callback !== 'function')
            throw Error('callback should be function!');

        name    = ponse.getPathName(request);

        isAuth  = RegExp('^(/auth|/auth/github)$').test(name);
        isFS    = RegExp('^/$|^' + FS).test(name);

        p       = {
            request     : request,
            response    : response,
            gzip        : true,
            name        : name
        };

        if (!isAuth && !isFS)
            callback();
        else if (isAuth) {
            p.name = DIR_HTML + name + '.html';
            ponse.sendFile(p);
        } else if (isFS) {
            name        = name.replace(CloudFunc.FS, '') || '/';
            fullPath    = root(name);

            flop.read(fullPath, function(error, dir) {
                if (dir)
                    dir.path = format.addSlashToEnd(name);

                if (!error)
                    buildIndex(dir, function(error, data) {
                        p.name = PATH_INDEX;

                        if (error)
                            ponse.sendError(error, p);
                        else
                            ponse.send(data, p);
                    });
                else if (error.code !== 'ENOTDIR')
                    ponse.sendError(error, p);
                else
                    fs.realpath(fullPath, function(error, pathReal) {
                        if (!error)
                            p.name = pathReal;
                        else
                            p.name = name;

                        p.gzip = false;
                        ponse.sendFile(p);
                    });
            });
        }
    }

    function buildIndex(json, callback) {
        var isMinify = config('minify');

        exec.if(!isMinify, function(error, name) {
            fs.readFile(name || PATH_INDEX, 'utf8', function(error, template) {
                var panel, data;

                if (!error) {
                    panel   = CloudFunc.buildFromJSON({
                        data        : json,
                        prefix      : prefix(),
                        template    : Template
                    }),

                    data    = indexProcessing({
                        panel   : panel,
                        data    : template
                    });
                }

                callback(error, data);
            });
        },  function(callback) {
                minify(PATH_INDEX, 'name', callback);
        });
    }
})();
<|endoftext|>


<commit_before>"use strict";

var fs          = require("fs");
var filePath    = require("path");
var connect     = require("connect");
var Immutable   = require("immutable");
var http        = require("http");
var https       = require("https");
var Map         = require("immutable").Map;
var snippet     = require("./../snippet").utils;
var _           = require("./../../lodash.custom");
var serveStatic = require("serve-static");

var utils = {
    /**
     * @param options
     * @returns {{key, cert}}
     */
    getKeyAndCert: function (options) {
        return {
            key:  fs.readFileSync(options.getIn(["https", "key"])  || filePath.join(__dirname, "certs/server.key")),
            cert: fs.readFileSync(options.getIn(["https", "cert"]) || filePath.join(__dirname, "certs/server.crt"))
        };
    },
    /**
     * @param filePath
     * @returns {{pfx}}
     */
    getPFX: function (filePath) {
        return {
            pfx: fs.readFileSync(filePath)
        };
    },
    /**
     * Get either an http or https server
     */
    getServer: function (app, options) {
        return {
            server: (function () {
                if (options.get("scheme") === "https") {
                    var pfxPath = options.getIn(["https", "pfx"]);
                    return pfxPath ?
                        https.createServer(utils.getPFX(pfxPath), app) :
                        https.createServer(utils.getKeyAndCert(options), app);
                }
                return http.createServer(app);
            })(),
            app: app
        };
    },
    getBaseApp: function (bs, options, scripts) {

        var app  = connect();
        var defaultMiddlewares = [
            {
                id: "Browsersync IE8 Support",
                route: "",
                handle: snippet.isOldIe(options.get("excludedFileTypes").toJS())
            },
            {
                id: "Browsersync Response Modifier",
                route: "",
                handle: utils.getSnippetMiddleware(bs)
            },
            {
                id: "Browsersync Client - versioned",
                route: bs.options.getIn(["scriptPaths", "versioned"]),
                handle: scripts
            },
            {
                id: "Browsersync Client",
                route: bs.options.getIn(["scriptPaths", "path"]),
                handle: scripts
            }
        ];

        if (options.get("cors")) {
            defaultMiddlewares.unshift({
                id: "Browsersync CORS support",
                route: "",
                handle: utils.getCorsMiddlewware()
            })
        }

        if (options.get('serveStatic')) {
            options
                .get("serveStatic")
                .forEach(function (dir, i) {
                    if (Immutable.Map.isMap(dir)) {
                        var ssOptions = (function () {
                            if (dir.get('options')) {
                                return dir.get('options').toJS();
                            }
                            return {}
                        })();
                        defaultMiddlewares.push({
                            id: "Serve static " + i,
                            route: dir.get("route"),
                            handle: serveStatic(dir.get("dir"), ssOptions)
                        });
                    } else if (_.isString(dir)) {
                        defaultMiddlewares.push({
                            id: "Serve static " + i,
                            route: "",
                            handle: serveStatic(dir, options.get('serveStaticOptions').toJS())
                        });
                    }
                });
        }

        /**
         * Add the proxy Middleware to the end of the stack
         */

        app.stack.push.apply(app.stack, defaultMiddlewares);

        /**
         * Add user-provided middlewares
         */
        options.get("middleware")
            .map(function (item) {
                /**
                 * Object given in options, which
                 * ended up being a Map
                 */
                if (Map.isMap(item)) {
                    return item.toJS();
                }
                /**
                 * Single function
                 */
                if (typeof item === "function") {
                    return {
                        route: "",
                        handle: item
                    }
                }
                /**
                 * Plain obj
                 */
                if ((item.route !== undefined) && item.handle) {
                    return item;
                }
            })
            .forEach(function (item) {
                /**
                 * Add each middleware
                 */
                app.stack.push(item);
            });

        return app;
    },
    getSnippetMiddleware: function (bs) {
        if (bs.options.get("proxy")) {
            var rule = require("./proxy-utils").rewriteLinks(bs.options.getIn(["proxy", "url"]).toJS());
            bs.snippetMw.opts.rules.push(rule);
        }
        return bs.snippetMw.middleware;
    },
    getCorsMiddlewware: function () {

        return function (req, res, next) {
            // Website you wish to allow to connect
            res.setHeader("Access-Control-Allow-Origin", "*");

            // Request methods you wish to allow
            res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE");

            // Request headers you wish to allow
            res.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type");

            // Set to true if you need the website to include cookies in the requests sent
            // to the API (e.g. in case you use sessions)
            res.setHeader("Access-Control-Allow-Credentials", true);
            next();
        }
    }
};

module.exports = utils;
<commit_msg>feat(serveStatic): allow mapping single or multiple routes to a directory<commit_after>"use strict";

var fs          = require("fs");
var filePath    = require("path");
var connect     = require("connect");
var Immutable   = require("immutable");
var http        = require("http");
var https       = require("https");
var Map         = require("immutable").Map;
var snippet     = require("./../snippet").utils;
var _           = require("./../../lodash.custom");
var serveStatic = require("serve-static");
var logger      = require("../logger");

var utils = {
    /**
     * @param options
     * @returns {{key, cert}}
     */
    getKeyAndCert: function (options) {
        return {
            key:  fs.readFileSync(options.getIn(["https", "key"])  || filePath.join(__dirname, "certs/server.key")),
            cert: fs.readFileSync(options.getIn(["https", "cert"]) || filePath.join(__dirname, "certs/server.crt"))
        };
    },
    /**
     * @param filePath
     * @returns {{pfx}}
     */
    getPFX: function (filePath) {
        return {
            pfx: fs.readFileSync(filePath)
        };
    },
    /**
     * Get either an http or https server
     */
    getServer: function (app, options) {
        return {
            server: (function () {
                if (options.get("scheme") === "https") {
                    var pfxPath = options.getIn(["https", "pfx"]);
                    return pfxPath ?
                        https.createServer(utils.getPFX(pfxPath), app) :
                        https.createServer(utils.getKeyAndCert(options), app);
                }
                return http.createServer(app);
            })(),
            app: app
        };
    },
    getBaseApp: function (bs, options, scripts) {

        var app  = connect();
        var defaultMiddlewares = [
            {
                id: "Browsersync IE8 Support",
                route: "",
                handle: snippet.isOldIe(options.get("excludedFileTypes").toJS())
            },
            {
                id: "Browsersync Response Modifier",
                route: "",
                handle: utils.getSnippetMiddleware(bs)
            },
            {
                id: "Browsersync Client - versioned",
                route: bs.options.getIn(["scriptPaths", "versioned"]),
                handle: scripts
            },
            {
                id: "Browsersync Client",
                route: bs.options.getIn(["scriptPaths", "path"]),
                handle: scripts
            }
        ];

        if (options.get("cors")) {
            defaultMiddlewares.unshift({
                id: "Browsersync CORS support",
                route: "",
                handle: utils.getCorsMiddlewware()
            })
        }

        if (options.get("serveStatic")) {

            var ssMiddlewares = utils.getServeStaticMiddlewares(options.get("serveStatic"), options.get("serveStaticOptions", Immutable.Map({})).toJS());
            var withErrors    = ssMiddlewares.filter(function(x) { return x.errors.length > 0 });
            var withoutErrors = ssMiddlewares.filter(function(x) { return x.errors.length === 0 });

            if (withErrors.size) {
                withErrors.forEach(function (item) {
                    logger.logger.error("{red:Warning!} %s", item.errors[0].data.message);
                });
            }

            if (withoutErrors.size) {
                withoutErrors.forEach(function (item) {
                    defaultMiddlewares.push.apply(defaultMiddlewares, item.items);
                });
            }
        }

        /**
         * Add the proxy Middleware to the end of the stack
         */

        app.stack.push.apply(app.stack, defaultMiddlewares);

        /**
         * Add user-provided middlewares
         */
        options.get("middleware")
            .map(function (item) {
                /**
                 * Object given in options, which
                 * ended up being a Map
                 */
                if (Map.isMap(item)) {
                    return item.toJS();
                }
                /**
                 * Single function
                 */
                if (typeof item === "function") {
                    return {
                        route: "",
                        handle: item
                    }
                }
                /**
                 * Plain obj
                 */
                if ((item.route !== undefined) && item.handle) {
                    return item;
                }
            })
            .forEach(function (item) {
                /**
                 * Add each middleware
                 */
                app.stack.push(item);
            });

        return app;
    },
    getSnippetMiddleware: function (bs) {
        if (bs.options.get("proxy")) {
            var rule = require("./proxy-utils").rewriteLinks(bs.options.getIn(["proxy", "url"]).toJS());
            bs.snippetMw.opts.rules.push(rule);
        }
        return bs.snippetMw.middleware;
    },
    getCorsMiddlewware: function () {

        return function (req, res, next) {
            // Website you wish to allow to connect
            res.setHeader("Access-Control-Allow-Origin", "*");

            // Request methods you wish to allow
            res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE");

            // Request headers you wish to allow
            res.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type");

            // Set to true if you need the website to include cookies in the requests sent
            // to the API (e.g. in case you use sessions)
            res.setHeader("Access-Control-Allow-Credentials", true);
            next();
        }
    },
    getServeStaticMiddlewares: function (ssOption, serveStaticOptions) {

        return ssOption.map(function (dir, i) {

            if (Immutable.Map.isMap(dir)) {

                var ssOptions = (function () {
                    if (dir.get("options")) {
                        return dir.get("options").toJS();
                    }
                    return {}
                })();

                var route = dir.get("route");
                var _dir  = dir.get("dir");

                if (!isValidOption(route) || !isValidOption(_dir)) {
                    return {
                        items: [],
                        errors: [{
                            type: "Invalid Object",
                            data: {
                                message: "Serve Static requires both 'route' and 'dir' options when using an Object"
                            }
                        }]
                    }
                }
                var ssItems = (function () {
                    if (_.isString(route)) {
                        return [{
                            id: "Serve static " + i,
                            route: getRoute(route),
                            handle: serveStatic(_dir, ssOptions)
                        }]
                    }
                    return route.map(function (item, j) {
                        return {
                            id: "Serve static " + i + "." + j,
                            route: getRoute(item),
                            handle: serveStatic(_dir, ssOptions)
                        }
                    }).toJS()
                })();
                return {
                    items: ssItems,
                    errors: []
                };
            }

            if (_.isString(dir)) {
                return {
                    items: [
                        {
                            id: "Serve static " + i,
                            route: "",
                            handle: serveStatic(dir, serveStaticOptions)
                        }
                    ],
                    errors: []
                }
            }

            return {
                items: [],
                errors: [{
                    type: "Invalid Type",
                    data: {
                        message: "Only strings and Objects (with route+dir) are supported for the ServeStatic option"
                    }
                }]
            }
        });
        function isValidOption (x) {
            return _.isString(x) || (_.isArray(x) && x.length > 0) || (Immutable.List.isList(x) && x.size > 0);
        }
        function getRoute (x) {
            return x[0] === "/" ? x : "/" + x;
        }
    }
};

module.exports = utils;
<|endoftext|>


<commit_before>import './CalendarMonthNavigator.js'
import './SeamlessButton.js';
import { getSuperProperty } from './workarounds.js';
import { merge } from './updates.js';
import { stateChanged } from './utilities.js';
import * as symbols from './symbols.js';
import * as template from './template.js';
import CalendarElementMixin from './CalendarElementMixin.js';
import ComboBox from './ComboBox.js';
import { calendar } from './elix.js';

const previousStateKey = Symbol('previousState');

const Base =
  CalendarElementMixin(
    ComboBox
  );

class DateComboBox extends Base {

  componentDidUpdate(previousState) {
    if (super.componentDidUpdate) { super.componentDidUpdate(previousState); }
    this.$.todayButton.addEventListener('mousedown', event => {
      this.date = calendar.today();
    });
    this.$.calendar.addEventListener('date-changed', event => {
      /** @type {any} */
      const cast = event;
      const date = cast.detail.date;
      this.setState({
        date
      });
    });
  }

  refineState(state) {
    let result = super.refineState ? super.refineState(state) : true;
    state[previousStateKey] = state[previousStateKey] || {
      date: null,
      value: null
    };
    const changed = stateChanged(state, state[previousStateKey]);
    const { date, value } = state;
    if (changed.date) {
      // Update value from date.
      const formattedDate = date.toDateString();
      if (state.value !== formattedDate) {
        state.value = date.toDateString();
        result = false;
      }
    } else if (changed.value) {
      // Update date from value.
      const parsedDate = new Date(value);
      const time = parsedDate.getTime();
      if (!isNaN(time) && time !== date.getTime()) {
        state.date = parsedDate;
        result = false;
      }
    }
    return result;
  }

  get [symbols.template]() {
    // Next line is same as: const result = super[symbols.template]
    const result = getSuperProperty(this, DateComboBox, symbols.template);

    // Replace default slot with calendar.
    const calendarTemplate = template.html`
      <style>
        #calendar {
          /* flex: 1; */
          width: 100%;
        }

        #todayButton {
          padding: 0.5em;
        }
      </style>
      <elix-calendar-month-navigator id="calendar"></elix-calendar-month-navigator>
      <elix-seamless-button id="todayButton">Today</elix-seamless-button>
    `;
    const defaultSlot = template.defaultSlot(result.content);
    if (defaultSlot) {
      template.transmute(defaultSlot, calendarTemplate);
    }

    return result;
  }

  get updates() {
    const { date, locale, value } = this.state;
    return merge(super.updates, {
      $: {
        calendar: {
          date,
          locale
        },
        input: {
          value
        }
      }
    });
  }

}

export default DateComboBox;
customElements.define('elix-date-combo-box', DateComboBox);
<commit_msg>DateComboBox uses DateInput.<commit_after>import './CalendarMonthNavigator.js'
import './SeamlessButton.js';
import { calendar } from './elix.js';
import { getSuperProperty } from './workarounds.js';
import { merge } from './updates.js';
import { stateChanged } from './utilities.js';
import * as symbols from './symbols.js';
import * as template from './template.js';
import CalendarElementMixin from './CalendarElementMixin.js';
import ComboBox from './ComboBox.js';
import DateInput from './DateInput.js';

const previousStateKey = Symbol('previousState');

const Base =
  CalendarElementMixin(
    ComboBox
  );

class DateComboBox extends Base {

  componentDidUpdate(previousState) {
    if (super.componentDidUpdate) { super.componentDidUpdate(previousState); }
    this.$.input.addEventListener('date-changed', event => {
      this[symbols.raiseChangeEvents] = true;
      /** @type {any} */
      const cast = event;
      const date = cast.detail.date;
      this.setState({
        date
      });
      this[symbols.raiseChangeEvents] = false;
    });
    this.$.calendar.addEventListener('date-changed', event => {
      this[symbols.raiseChangeEvents] = true;
      /** @type {any} */
      const cast = event;
      const date = cast.detail.date;
      this.setState({
        date
      });
      this[symbols.raiseChangeEvents] = false;
    });
    this.$.todayButton.addEventListener('mousedown', event => {
      this[symbols.raiseChangeEvents] = true;
      this.date = calendar.today();
      this[symbols.raiseChangeEvents] = false;
    });
  }

  get defaultState() {
    return Object.assign({}, super.defaultState, {
      date: null,
      inputRole: DateInput
    });
  }

  refineState(state) {
    let result = super.refineState ? super.refineState(state) : true;
    state[previousStateKey] = state[previousStateKey] || {
      date: null,
      opened: false,
      value: null
    };
    const changed = stateChanged(state, state[previousStateKey]);
    const { date, opened, value } = state;
    if (changed.date) {
      // Update value from date.
      const dateTimeFormat = new Intl.DateTimeFormat(state.locale, {
        day: 'numeric',
        month: 'numeric',
        year: 'numeric'
      });
      const formattedDate = dateTimeFormat.format(date);
      if (state.value !== formattedDate) {
        state.value = formattedDate;
        result = false;
      }
    } else if (changed.value && !opened) {
      // Update date from value.
      const parsedDate = new Date(value);
      const time = parsedDate.getTime();
      if (!isNaN(time) && time !== date.getTime()) {
        state.date = parsedDate;
        result = false;
      }
    }
    return result;
  }

  get [symbols.template]() {
    // Next line is same as: const result = super[symbols.template]
    const result = getSuperProperty(this, DateComboBox, symbols.template);

    // Replace default slot with calendar.
    const calendarTemplate = template.html`
      <style>
        #calendar {
          /* flex: 1; */
          width: 100%;
        }

        #todayButton {
          padding: 0.5em;
        }
      </style>
      <elix-calendar-month-navigator id="calendar"></elix-calendar-month-navigator>
      <elix-seamless-button id="todayButton">Today</elix-seamless-button>
    `;
    const defaultSlot = template.defaultSlot(result.content);
    if (defaultSlot) {
      template.transmute(defaultSlot, calendarTemplate);
    }

    return result;
  }

  get updates() {
    const { date, locale, value } = this.state;
    return merge(super.updates, {
      $: {
        calendar: Object.assign(
          {
            locale
          },
          date && {
            date
          }
        ),
        input: {
          value
        }
      }
    });
  }

}

export default DateComboBox;
customElements.define('elix-date-combo-box', DateComboBox);
<|endoftext|>


<commit_before>/*
 *  DeviceEvents.js
 *  2014/07/15
 *  @auther minimo
 *  This Program is MIT license.
 */

//実行ＯＳ種別
DEVICE_IOS = false;
DEVICE_ANDROID = false;

//定数
//PhoneGap使用可能フラグ
ENABLE_PHONEGAP = false;
DEBUG_PHONEGAP = false;

//GAMECENTER(GooglePlay)使用可能フラグ
ENABLE_GAMECENTER = false;
DEBUG_GAMECENTER = false;

//AdMob使用可能フラグ
ENABLE_ADMOB = false;
DEBUG_ADMOB = false;
TEST_ADMOB = false;

//Social Message
ENABLE_SOCIAL = false;

//PhoneGap Device Events
var onDeviceReady = function () {

    //使用ＯＳの判別
    DEVICE_IOS = ( /(android)/i.test(navigator.userAgent) )? false: true;
    if (!DEVICE_IOS) DEVICE_ANDROID = true;

    if (DEBUG_PHONEGAP) {
        AdvanceAlert('devicereadyイベントが発火しました');
        AdvanceAlert('Device:'+device.name+" "+device.platform);
    }

    ENABLE_PHONEGAP = true;

    //AdMob plugin
    if (AdMob) {
        var defaultOptions = {
            bannerId: admobid.banner,
            interstitialId: admobid.interstitial,
            position: AdMob.AD_POSITION.BOTTOM_CENTER,
            bgColor: 'black',
            isTesting: TEST_ADMOB,
            autoShow: true
        };
        AdMob.setOptions(defaultOptions);
        ENABLE_ADMOB = true;
    }

    //Game Center Plugin
    if (DEVICE_IOS) {
        gamecenter.auth(onGamecenterSuccess, onGamecenterFailure);
    }
    if (DEVICE_ANDROID) {
        googleplaygame.auth(onGamecenterSuccess, onGamecenterFailure);
    }

    //Social Message
    ENABLE_SOCIAL = true;
}

var onPause = function() {
    if (DEBUG_PHONEGAP) AdvanceAlert('pauseイベントが発火しました');

    //ゲーム中の場合ポーズシーンに移行
    var scene = appMain.currentScene;
    if (scene instanceof shotgun.MainScene && !scene.gameend) {
        appMain.pushScene(shotgun.PauseScene(scene));
    }
}

var onResume = function() {
    if (DEBUG_PHONEGAP) AdvanceAlert('resumeイベントが発火しました');

    //GAME CENTERに再度接続を行う
    if (DEVICE_IOS) {
        if (!ENABLE_GAMECENTER) {
            gamecenter.auth(onGamecenterSuccess, onGamecenterFailure);
        }
        return;
    }
    if (DEVICE_ANDROID) {
        if (!ENABLE_GAMECENTER) {
            googleplaygame.auth(onGamecenterSuccess, onGamecenterFailure);
        }
    }
}

var onOnline = function() {
    if (DEBUG_PHONEGAP) AdvanceAlert('onlineイベントが発火しました');
}

var onOffline = function() {
    if (DEBUG_PHONEGAP) AdvanceAlert('offlineイベントが発火しました');
}

//Phonegap Event listener
document.addEventListener("deviceready", onDeviceReady, false);
document.addEventListener('pause', onPause, false);
document.addEventListener('resume', onResume, false);
document.addEventListener('online', onOnline, false);
document.addEventListener('offline', onOffline, false);

/*
 *
 * iOS GameCenter
 * Android Google Play
 *
 */

// GAMECENTER CallBack
var onGamecenterSuccess = function() {
    if (DEBUG_GAMECENTER) AdvanceAlert('GameCenter connect success');
    ENABLE_GAMECENTER = true;
}

var onGamecenterFailure = function(result) {
    if (DEBUG_GAMECENTER) AdvanceAlert('GameCenterに接続できませんでした\n'+result);
    ENABLE_GAMECENTER = false;
}

//リーダーズボード参照
var showLeadersBoard = function(id) {
    id = id || "";

    if (DEVICE_IOS) {
        if (!ENABLE_PHONEGAP) {
            appMain.pushScene(shotgun.AlertDialog({
                height: SC_H*0.2,
                text1: "GameCenterに接続できませんでした",
                fontSize: 32,
                button: "OK"
            }));
            return false;
        }
        //GAMECENTERに接続してない場合は再接続
        if (!ENABLE_GAMECENTER) {
            gamecenter.auth(onGamecenterSuccess, onGamecenterFailure);

            //再接続失敗
            if (!ENABLE_GAMECENTER) {
                appMain.pushScene(shotgun.AlertDialog({
                    height: SC_H*0.2,
                    text1: "GameCenterに接続できませんでした",
                    fontSize: 32,
                    button: "OK"
                }));
                return false;
            }
        }

        gamecenter.showLeaderboard(function(){}, function(){}, {
            leaderboardId: id,
        });
        return true;
    }
    if (DEVICE_ANDROID) {
        if (id == "") {
            googleplaygame.showAllLeaderboards();
        } else {
            googleplaygame.showLeaderboard({
                leaderboardId: id,
            });
        }
        return true;
    }
}

//GameCenterにスコアを登録
var submitScore = function(mode, returnJoker, score) {
    if (!ENABLE_GAMECENTER) return false;
    if (DEVICE_IOS) {
        var id = "Normal_";
        if (mode == GAMEMODE_HARD) id = "Hard_";
        if (returnJoker) id += "RJ";
        gamecenter.submitScore(
            function() {
                if (DEBUG_GAMECENTER) AdvanceAlert('スコア登録に成功しました');
            },
            function() {
                if (DEBUG_GAMECENTER) AdvanceAlert('スコア登録に失敗しました');
            }, {
                score: score,
                leaderboardId: id,
            });
    }
    if (DEVICE_ANDROID) {
        var id = "";
        if (mode == GAMEMODE_NORMAL && !returnJoker) id = "CgkI-I-vk7YTEAIQAA";
        if (mode == GAMEMODE_NORMAL && returnJoker)  id = "CgkI-I-vk7YTEAIQAQ";
        if (mode == GAMEMODE_HARD   && !returnJoker) id = "CgkI-I-vk7YTEAIQAg";
        if (mode == GAMEMODE_HARD   && returnJoker)  id = "CgkI-I-vk7YTEAIQAw";
        googleplaygame.submitScore({
                score: score,
                leaderboardId: id,
            },
            function() {
                if (DEBUG_GAMECENTER) AdvanceAlert('スコア登録に成功しました');
            },
            function() {
                if (DEBUG_GAMECENTER) AdvanceAlert('スコア登録に失敗しました');
            });
    }
}

//GameCenterに実績登録
var reportAchievements = function(id, percent) {
    if (!ENABLE_GAMECENTER) return false;
    if (DEVICE_IOS) {
        gamecenter.reportAchievement(
            function(){
                if (DEBUG_GAMECENTER) AdvanceAlert('実績登録に成功しました');
            },
            function(){
                if (DEBUG_GAMECENTER) AdvanceAlert('実績登録に失敗しました');
            }, {
                achievementId: id,
                percent: "100",
            });
    }
    if (DEVICE_ANDROID) {
        googleplaygame.unlockAchievement({
                achievementId: id,
            },
            function(){
                if (DEBUG_GAMECENTER) AdvanceAlert('実績登録に成功しました');
            },
            function(){
                if (DEBUG_GAMECENTER) AdvanceAlert('実績登録に失敗しました');
            });
    }
    return true;
}

//GameCenterの実績をリセット
var resetAchievements = function() {
    if (!ENABLE_GAMECENTER) return false;
    if (DEVICE_IOS) {
        gamecenter.resetAchievements(
            function(){
                if (DEBUG_GAMECENTER) AdvanceAlert('実績リセットに成功しました');
            },
            function(){
            if (DEBUG_GAMECENTER) AdvanceAlert('実績リセットに失敗しました');
            });
    }
    if (DEVICE_ANDROID) {
    }
}

/*
 *
 * AdMob
 *
 */

var ad_units = {
    ios : {
        banner:       'ca-app-pub-4753786498901311/3019381180', // or DFP format "/6253334/dfp_example_ad"
        interstitial: 'ca-app-pub-4753786498901311/7270571985'
//        banner: '/6253334/dfp_example_ad', // or DFP format "/6253334/dfp_example_ad"
//        interstitial: 'ca-app-pub-3940256099942544/4411468910'
    },
    android : {
        banner:       'ca-app-pub-4753786498901311/3019381180', // or DFP format "/6253334/dfp_example_ad"
        interstitial: 'ca-app-pub-4753786498901311/7270571985'
    }
};
// select the right Ad Id according to platform
var admobid = ( /(android)/i.test(navigator.userAgent) ) ? ad_units.android : ad_units.ios;

// AdMob CallBack
var onBannerLeaveApp = function(result) {
    if (DEBUG_ADMOB) AdvanceAlert('OnBannerLeaveApp\n'+result);
}

var onBannerDismiss = function(result) {
    if (DEBUG_ADMOB) AdvanceAlert('OnBannerDismiss\n'+result);
}

var onInterstitialPresent = function(result) {
    if (DEBUG_ADMOB) AdvanceAlert('onInterstitialPresent\n'+result);
}

var onInterstitialLeaveApp = function(result) {
    if (DEBUG_ADMOB) AdvanceAlert('onInterstitialLeaveApp\n'+result);
}

var onInterstitialDissmiss = function(result) {
    if (DEBUG_ADMOB) AdvanceAlert('onInterstitialDissmiss\n'+result);
}

//AdMob Event listener
document.addEventListener('onBannerLeaveApp', onBannerLeaveApp, false);
document.addEventListener('onBannerDismiss', onBannerDismiss, false);
document.addEventListener('onInterstitialPresent', onInterstitialPresent, false);
document.addEventListener('onInterstitialLeaveApp', onInterstitialLeaveApp, false);
document.addEventListener('onInterstitialDissmiss', onInterstitialDissmiss, false);

/*
 *
 * Social Message
 *
 */

//SNSにメッセージを送（ゲームオーバー時）
var sendSocialMessage = function(mode, returnJoker, score) {
    if (!ENABLE_SOCIAL) return false;

    //メッセージテキストの作成
    var lb = "Normal";
    if (mode == GAMEMODE_HARD) lb = "Hard";
    if (returnJoker) lb += "_RJ";

    var url = "https://itunes.apple.com/jp/app/shottoganpoka/id951249463";
    var text = "ShotgunPoker Score:"+score+"pts("+lb+")【"+url+"】 #ShotgunPoker #SGP_"+lb;
    var message = {
        text: text,
//        activityTypes: ["PostToTwitter"],
    };
    window.socialmessage.send(message);
}

//SNSにメッセージを送る（総合情報）
var sendSocialMessageGlobal = function() {
    if (!ENABLE_SOCIAL) return false;

    var score = 0;
    var mode = GAMEMODE_NORMAL;
    var returnJoker = false;

    //ベストスコアはどれか
    var sc1 = appMain.highScore[GAMEMODE_NORMAL];
    var sc2 = appMain.highScore[GAMEMODE_NORMAL+10];
    var sc3 = appMain.highScore[GAMEMODE_HARD];
    var sc4 = appMain.highScore[GAMEMODE_HARD+10];
    var sc = [sc1, sc2, sc3, sc4];
    score = sc[0];
    for (var i = 1; i < sc.length; i++) {
        if (score < sc[i]) score = sc[i];
    }
    if (score == sc[0]) {mode = GAMEMODE_NORMAL; returnJoker = false;}
    if (score == sc[1]) {mode = GAMEMODE_NORMAL; returnJoker = true;}
    if (score == sc[2]) {mode = GAMEMODE_HARD;   returnJoker = false;}
    if (score == sc[3]) {mode = GAMEMODE_HARD;   returnJoker = true;}

    //メッセージテキストの作成
    var lb = "Normal";
    if (mode == GAMEMODE_HARD) lb = "Hard";
    if (returnJoker) lb += "-RJ";

    var url = "https://itunes.apple.com/jp/app/shottoganpoka/id951249463";
    var text = "ShotgunPoker MyBestScore:"+score+"pts("+lb+")【"+url+"】 #ShotgunPoker #SGP_Best";
    var message = {
        text: text,
//        activityTypes: ["PostToTwitter"],
    };
    window.socialmessage.send(message);
}
<commit_msg>GooglePlay実績登録対応<commit_after>/*
 *  DeviceEvents.js
 *  2014/07/15
 *  @auther minimo
 *  This Program is MIT license.
 */

//実行ＯＳ種別
DEVICE_IOS = false;
DEVICE_ANDROID = false;

//定数
//PhoneGap使用可能フラグ
ENABLE_PHONEGAP = false;
DEBUG_PHONEGAP = false;

//GAMECENTER(GooglePlay)使用可能フラグ
ENABLE_GAMECENTER = false;
DEBUG_GAMECENTER = false;

//AdMob使用可能フラグ
ENABLE_ADMOB = false;
DEBUG_ADMOB = false;
TEST_ADMOB = false;

//Social Message
ENABLE_SOCIAL = false;

//PhoneGap Device Events
var onDeviceReady = function () {

    //使用ＯＳの判別
    DEVICE_IOS = ( /(android)/i.test(navigator.userAgent) )? false: true;
    if (!DEVICE_IOS) DEVICE_ANDROID = true;

    if (DEBUG_PHONEGAP) {
        AdvanceAlert('devicereadyイベントが発火しました');
        AdvanceAlert('Device:'+device.name+" "+device.platform);
    }

    ENABLE_PHONEGAP = true;

    //AdMob plugin
    if (AdMob) {
        var defaultOptions = {
            bannerId: admobid.banner,
            interstitialId: admobid.interstitial,
            position: AdMob.AD_POSITION.BOTTOM_CENTER,
            bgColor: 'black',
            isTesting: TEST_ADMOB,
            autoShow: true
        };
        AdMob.setOptions(defaultOptions);
        ENABLE_ADMOB = true;
    }

    //Game Center Plugin
    if (DEVICE_IOS) {
        gamecenter.auth(onGamecenterSuccess, onGamecenterFailure);
    }
    if (DEVICE_ANDROID) {
        googleplaygame.auth(onGamecenterSuccess, onGamecenterFailure);
    }

    //Social Message
    ENABLE_SOCIAL = true;
}

var onPause = function() {
    if (DEBUG_PHONEGAP) AdvanceAlert('pauseイベントが発火しました');

    //ゲーム中の場合ポーズシーンに移行
    var scene = appMain.currentScene;
    if (scene instanceof shotgun.MainScene && !scene.gameend) {
        appMain.pushScene(shotgun.PauseScene(scene));
    }
}

var onResume = function() {
    if (DEBUG_PHONEGAP) AdvanceAlert('resumeイベントが発火しました');

    //GAME CENTERに再度接続を行う
    if (DEVICE_IOS) {
        if (!ENABLE_GAMECENTER) {
            gamecenter.auth(onGamecenterSuccess, onGamecenterFailure);
        }
        return;
    }
    if (DEVICE_ANDROID) {
        if (!ENABLE_GAMECENTER) {
            googleplaygame.auth(onGamecenterSuccess, onGamecenterFailure);
        }
    }
}

var onOnline = function() {
    if (DEBUG_PHONEGAP) AdvanceAlert('onlineイベントが発火しました');
}

var onOffline = function() {
    if (DEBUG_PHONEGAP) AdvanceAlert('offlineイベントが発火しました');
}

//Phonegap Event listener
document.addEventListener("deviceready", onDeviceReady, false);
document.addEventListener('pause', onPause, false);
document.addEventListener('resume', onResume, false);
document.addEventListener('online', onOnline, false);
document.addEventListener('offline', onOffline, false);

/*
 *
 * iOS GameCenter
 * Android Google Play
 *
 */

// GAMECENTER CallBack
var onGamecenterSuccess = function() {
    if (DEBUG_GAMECENTER) AdvanceAlert('GameCenter connect success');
    ENABLE_GAMECENTER = true;
}

var onGamecenterFailure = function(result) {
    if (DEBUG_GAMECENTER) AdvanceAlert('GameCenterに接続できませんでした\n'+result);
    ENABLE_GAMECENTER = false;
}

//リーダーズボード参照
var showLeadersBoard = function(id) {
    id = id || "";

    if (DEVICE_IOS) {
        if (!ENABLE_PHONEGAP) {
            appMain.pushScene(shotgun.AlertDialog({
                height: SC_H*0.2,
                text1: "GameCenterに接続できませんでした",
                fontSize: 32,
                button: "OK"
            }));
            return false;
        }
        //GAMECENTERに接続してない場合は再接続
        if (!ENABLE_GAMECENTER) {
            gamecenter.auth(onGamecenterSuccess, onGamecenterFailure);

            //再接続失敗
            if (!ENABLE_GAMECENTER) {
                appMain.pushScene(shotgun.AlertDialog({
                    height: SC_H*0.2,
                    text1: "GameCenterに接続できませんでした",
                    fontSize: 32,
                    button: "OK"
                }));
                return false;
            }
        }

        gamecenter.showLeaderboard(function(){}, function(){}, {
            leaderboardId: id,
        });
        return true;
    }
    if (DEVICE_ANDROID) {
        if (id == "") {
            googleplaygame.showAllLeaderboards();
        } else {
            googleplaygame.showLeaderboard({
                leaderboardId: id,
            });
        }
        return true;
    }
}

//GameCenterにスコアを登録
var submitScore = function(mode, returnJoker, score) {
    if (!ENABLE_GAMECENTER) return false;
    if (DEVICE_IOS) {
        var id = "Normal_";
        if (mode == GAMEMODE_HARD) id = "Hard_";
        if (returnJoker) id += "RJ";
        gamecenter.submitScore(
            function() {
                if (DEBUG_GAMECENTER) AdvanceAlert('スコア登録に成功しました');
            },
            function() {
                if (DEBUG_GAMECENTER) AdvanceAlert('スコア登録に失敗しました');
            }, {
                score: score,
                leaderboardId: id,
            });
    }
    if (DEVICE_ANDROID) {
        var id = "";
        if (mode == GAMEMODE_NORMAL && !returnJoker) id = "CgkI-I-vk7YTEAIQAA";
        if (mode == GAMEMODE_NORMAL && returnJoker)  id = "CgkI-I-vk7YTEAIQAQ";
        if (mode == GAMEMODE_HARD   && !returnJoker) id = "CgkI-I-vk7YTEAIQAg";
        if (mode == GAMEMODE_HARD   && returnJoker)  id = "CgkI-I-vk7YTEAIQAw";
        googleplaygame.submitScore({
                score: score,
                leaderboardId: id,
            },
            function() {
                if (DEBUG_GAMECENTER) AdvanceAlert('スコア登録に成功しました');
            },
            function() {
                if (DEBUG_GAMECENTER) AdvanceAlert('スコア登録に失敗しました');
            });
    }
}

//GameCenterに実績登録
var reportAchievements = function(name, percent) {
    if (!ENABLE_GAMECENTER) return false;
    if (DEVICE_IOS) {
        gamecenter.reportAchievement(
            function(){
                if (DEBUG_GAMECENTER) AdvanceAlert('実績登録に成功しました');
            },
            function(){
                if (DEBUG_GAMECENTER) AdvanceAlert('実績登録に失敗しました');
            }, {
                achievementId: name,    //GameCenterは実績名とidが同一
                percent: "100"
            });
    }
    if (DEVICE_ANDROID) {
        if (shotgun.achievementList[name].id === undefined) return false;
        if (shotgun.achievementList[name].id == "") return false;
        googleplaygame.unlockAchievement({
                achievementId: shotgun.achievementList[name].id
            },
            function(){
                if (DEBUG_GAMECENTER) AdvanceAlert('実績登録に成功しました');
            },
            function(){
                if (DEBUG_GAMECENTER) AdvanceAlert('実績登録に失敗しました');
            });
    }
    return true;
}

//GameCenterの実績をリセット
var resetAchievements = function() {
    if (!ENABLE_GAMECENTER) return false;
    if (DEVICE_IOS) {
        gamecenter.resetAchievements(
            function(){
                if (DEBUG_GAMECENTER) AdvanceAlert('実績リセットに成功しました');
            },
            function(){
            if (DEBUG_GAMECENTER) AdvanceAlert('実績リセットに失敗しました');
            });
    }
    if (DEVICE_ANDROID) {
    }
}

/*
 *
 * AdMob
 *
 */

var ad_units = {
    ios : {
        banner:       'ca-app-pub-4753786498901311/3019381180', // or DFP format "/6253334/dfp_example_ad"
        interstitial: 'ca-app-pub-4753786498901311/7270571985'
//        banner: '/6253334/dfp_example_ad', // or DFP format "/6253334/dfp_example_ad"
//        interstitial: 'ca-app-pub-3940256099942544/4411468910'
    },
    android : {
        banner:       'ca-app-pub-4753786498901311/3019381180', // or DFP format "/6253334/dfp_example_ad"
        interstitial: 'ca-app-pub-4753786498901311/7270571985'
    }
};
// select the right Ad Id according to platform
var admobid = ( /(android)/i.test(navigator.userAgent) ) ? ad_units.android : ad_units.ios;

// AdMob CallBack
var onBannerLeaveApp = function(result) {
    if (DEBUG_ADMOB) AdvanceAlert('OnBannerLeaveApp\n'+result);
}

var onBannerDismiss = function(result) {
    if (DEBUG_ADMOB) AdvanceAlert('OnBannerDismiss\n'+result);
}

var onInterstitialPresent = function(result) {
    if (DEBUG_ADMOB) AdvanceAlert('onInterstitialPresent\n'+result);
}

var onInterstitialLeaveApp = function(result) {
    if (DEBUG_ADMOB) AdvanceAlert('onInterstitialLeaveApp\n'+result);
}

var onInterstitialDissmiss = function(result) {
    if (DEBUG_ADMOB) AdvanceAlert('onInterstitialDissmiss\n'+result);
}

//AdMob Event listener
document.addEventListener('onBannerLeaveApp', onBannerLeaveApp, false);
document.addEventListener('onBannerDismiss', onBannerDismiss, false);
document.addEventListener('onInterstitialPresent', onInterstitialPresent, false);
document.addEventListener('onInterstitialLeaveApp', onInterstitialLeaveApp, false);
document.addEventListener('onInterstitialDissmiss', onInterstitialDissmiss, false);

/*
 *
 * Social Message
 *
 */

//SNSにメッセージを送（ゲームオーバー時）
var sendSocialMessage = function(mode, returnJoker, score) {
    if (!ENABLE_SOCIAL) return false;

    //メッセージテキストの作成
    var lb = "Normal";
    if (mode == GAMEMODE_HARD) lb = "Hard";
    if (returnJoker) lb += "_RJ";

    var url = "https://itunes.apple.com/jp/app/shottoganpoka/id951249463";
    var text = "ShotgunPoker Score:"+score+"pts("+lb+")【"+url+"】 #ShotgunPoker #SGP_"+lb;
    var message = {
        text: text,
//        activityTypes: ["PostToTwitter"],
    };
    window.socialmessage.send(message);
}

//SNSにメッセージを送る（総合情報）
var sendSocialMessageGlobal = function() {
    if (!ENABLE_SOCIAL) return false;

    var score = 0;
    var mode = GAMEMODE_NORMAL;
    var returnJoker = false;

    //ベストスコアはどれか
    var sc1 = appMain.highScore[GAMEMODE_NORMAL];
    var sc2 = appMain.highScore[GAMEMODE_NORMAL+10];
    var sc3 = appMain.highScore[GAMEMODE_HARD];
    var sc4 = appMain.highScore[GAMEMODE_HARD+10];
    var sc = [sc1, sc2, sc3, sc4];
    score = sc[0];
    for (var i = 1; i < sc.length; i++) {
        if (score < sc[i]) score = sc[i];
    }
    if (score == sc[0]) {mode = GAMEMODE_NORMAL; returnJoker = false;}
    if (score == sc[1]) {mode = GAMEMODE_NORMAL; returnJoker = true;}
    if (score == sc[2]) {mode = GAMEMODE_HARD;   returnJoker = false;}
    if (score == sc[3]) {mode = GAMEMODE_HARD;   returnJoker = true;}

    //メッセージテキストの作成
    var lb = "Normal";
    if (mode == GAMEMODE_HARD) lb = "Hard";
    if (returnJoker) lb += "-RJ";

    var url = "https://itunes.apple.com/jp/app/shottoganpoka/id951249463";
    var text = "ShotgunPoker MyBestScore:"+score+"pts("+lb+")【"+url+"】 #ShotgunPoker #SGP_Best";
    var message = {
        text: text,
//        activityTypes: ["PostToTwitter"],
    };
    window.socialmessage.send(message);
}
<|endoftext|>


<commit_before>import React from "react";
import axios from "axios";
import {Line} from "react-chartjs-2";

class DynamicChart extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      chartData: {
        datasets: [ ]
      },
    }
  }

  componentDidMount() {
    this.fetchXml();
  }

  render() {
    const options = {
      spanGaps: false,
      scales: {
        xAxes: [{
          type: 'time',
          time: {
            displayFormats: {
              quarter: 'HH:mm'
            }
          }
        }]
      }
    };

    return

      <Line data={this.state.chartData} options={options}/>

  }

  fetchXml() {
    axios.get('http://localhost:11900/temperature.json')
        .then(response => {
          this.setState({
            loading: false,
            chartData: {
              datasets: response.data
            }
          });
        })
        .catch(error => {
          this.setState({
            loading: false
          })
        });
  }

}

export default DynamicChart;
<commit_msg>rename method<commit_after>import React from "react";
import axios from "axios";
import {Line} from "react-chartjs-2";

class DynamicChart extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      chartData: {
        datasets: [ ]
      },
    }
  }

  componentDidMount() {
    this.fetchJson();
  }

  render() {
    const options = {
      spanGaps: false,
      scales: {
        xAxes: [{
          type: 'time',
          time: {
            displayFormats: {
              quarter: 'HH:mm'
            }
          }
        }]
      }
    };

    return

      <Line data={this.state.chartData} options={options}/>

  }

  fetchJson() {
    axios.get('http://localhost:11900/temperature.json')
        .then(response => {
          this.setState({
            loading: false,
            chartData: {
              datasets: response.data
            }
          });
        })
        .catch(error => {
          this.setState({
            loading: false
          })
        });
  }

}

export default DynamicChart;
<|endoftext|>