<commit_before>/*

REM: Remedial Rest Interfaces

A library that simplifies and normalizes access to REST APIs.

Reference:
http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven

*/

// Namespace.
var rem = typeof exports == 'undefined' ? this.rem = {} : exports;
var remutil = typeof require == 'undefined' ? remutil : require('./remutil');

// Configuration.
rem.USER_AGENT = 'Mozilla/5.0 (compatible; REMbot/1.0; +http://rem.tcr.io/)';
rem.CONFIG_FILE = null;

/**
 * A hypermedia resource.
 */

var HyperMedia = (function () {

  function HyperMedia (api, res, data) {
    this.api = api;
    this.res = res;
    this.data = data;

    this.type = api.format;
    this.statusCode = Number(this.res.statusCode);
    this.err = this.statusCode > 400 ? this.statusCode : 0;

    // Parse body
    try {
      if (this.type === 'xml') {
        if (!libxmljs) {
          var libxmljs = require('libxmljs');
        }
        this.data = this.xml = libxmljs.parseXmlString(String(this.data));
      } else {
        this.data = this.json = JSON.parse(String(this.data));
      }
    } catch (e) {
      this.err = e;
      console.warn('Could not parse data for type ' + this.type + '.')
    }
  }

  return HyperMedia;

})();

/**
 * A route endpoint.
 */

var Route = (function () {

  function Route (req, defaultBodyMime, middleware) {
    this.req = req;
    this.defaultBodyMime = defaultBodyMime || 'json';
    this.middleware = middleware;
  }

  Route.prototype.get = function (query, next) {
    if (typeof query == 'function') {
      next = query;
      query = null;
    }
    return this.middleware(remutil.modify(remutil.request.url(this.req, {
      query: query || {}
    }), {
      method: 'GET'
    }), next);
  };

  Route.prototype.head = function (query, next) {
    if (typeof query == 'function') {
      next = query;
      query = null;
    }
    return this.middleware(remutil.modify(remutil.request.url(this.req, {
      query: query || {}
    }), {
      method: 'HEAD'
    }), next);
  };

  Route.prototype.post = function (mime, body, next) {
    if (typeof body == 'function') {
      next = body;
      body = mime;
      mime = this.defaultBodyMime;
    }
    return this.middleware(remutil.modify(remutil.request.body(this.req, mime, body), {
      method: 'POST'
    }), next);
  };

  Route.prototype.put = function (mime, body, next) {
    if (typeof body == 'function') {
      next = body;
      body = mime;
      mime = this.defaultBodyMime;
    }
    return this.middleware(remutil.modify(remutil.request.body(this.req, mime, body), {
      method: 'PUT'
    }), next);
  };

  Route.prototype.del = function (next) {
    return this.middleware(remutil.modify(this.req, {
      method: 'DELETE'
    }), next);
  };

  return Route;

})();

/**
 * Middleware.
 */

var Middleware = (function () {

  function Middleware () { }

  Middleware.prototype.pre = function (type, callback) {
    this._middleware || (this._middleware = {});
    (this._middleware[type] || (this._middleware[type] = [])).push(callback);
    return this;
  };

  Middleware.prototype.middleware = function (type) {
    var args = Array.prototype.slice.call(arguments, 1);
    (this._middleware && this._middleware[type] || []).forEach(function (callback) {
      callback.apply(this, args);
    }.bind(this));
    return this;
  };

  return Middleware;

})();

/**
 * API
 */

var API = (function () {

  remutil.inherits(API, Middleware);

  function API (manifest, opts) {
    this.manifest = manifest;
    this.opts = opts || {};

    // Load key, secret, format.
    this.key = this.opts.key;
    this.secret = this.opts.secret;
    this.format = this.opts.format || 'json';

    // Load format-specific options from the manifest.
    if (!this.manifest.formats) {
      this.manifest.formats = {json: {}};
    }
    if (!this.manifest.formats[this.format]) {
      throw new Error("Format \"" + this.format + "\" not available. Please specify an available format in the options parameter.");
    }
    this.manifest = remutil.modify(this.manifest, this.manifest.formats[this.format]);

    // User agent.
    this.pre('request', function (req) {
      req.headers['user-agent'] = req.headers['user-agent'] || rem.USER_AGENT;
    });
    // Route root pathname.
    if (this.manifest.basepath) {
      this.pre('request', function (req) {
        req.url.pathname = this.manifest.basepath + req.url.pathname;
      });
    }
    // Route suffix.
    if (this.manifest.suffix) {
      this.pre('request', function (req) {
        req.url.pathname += this.manifest.suffix;
      });
    }
    // Route configuration parameters.
    if (this.manifest.configParams) {
      this.pre('request', function (req) {
        var params = this.manifest.configParams;
        for (var key in params) {
          req.url.query[key] = this.opts[this.manifest.configParams[key]];
        }
      });
    }
    // Route static parameters.
    if (this.manifest.params) {
      this.pre('request', function (req) {
        var params = this.manifest.params;
        for (var key in params) {
          req.url.query[key] = params[key];
        }
      });
    }
  }

  // Configuration prompt.

  API.prototype.configure = function(cont) {
    return cont();
  };

  // Callable function.

  function invoke (api, segments, send) {
    var query = typeof segments[segments.length - 1] == 'object' ? segments.pop() : {};
    var pathname = remutil.path.join.apply(null, segments);

    return new Route(remutil.request.create({
      query: query, pathname: pathname
    }), api.manifest.uploadFormat, middleware);

    function middleware (req, next) {
      // Expand payload shorthand.
      api.configure(function () {
        // Determine base that matches the path name.
        var pathname = req.url.pathname.replace(/^(?!\/)/, '/')
        // Bases can be fixed or an array of (pattern, base) tuples.
        if (Array.isArray(api.manifest.base)) {
          var base = '';
          api.manifest.base.some(function (tuple) {
            if (typeof tuple == 'string') {
              // TODO this functionality should be removed
              base = tuple;
              return true;
            } else {
              if (pathname.match(new RegExp(tuple[0]))) {
                base = tuple[1];
                return true;
              }
            }
          });
        } else {
          var base = String(api.manifest.base);
        }
        // Update the request with base.
        req = remutil.request.url(req, remutil.url.parse(base))
        req = remutil.request.url(req, {
          pathname: remutil.path.join(req.url.pathname, pathname)
        });

        // Apply manifest filters.
        api.middleware('request', req);
        send(req, next);
      });

      return req;
    }
  }

  API.prototype.stream = function () {
    return invoke(this, Array.prototype.slice.call(arguments), function (req, next) {
      this.send(req, function (err, res) {
        next(req, res);
      });
    }.bind(this));
  };

  API.prototype.call = function () {
    return invoke(this, Array.prototype.slice.call(arguments), function (req, next) {
      this.send(req, function (err, res) {
        if (err) {
          next && next(err, null, res);
        } else {
          remutil.consumeStream(res, function (data) {
            var media = new HyperMedia(this, res, data);
            next && next(media.err, media.data, media);
          });
        }
      });
    }.bind(this));
  };

  API.prototype.send = function (req, next) {
    remutil.request.send(req, next);
  }

  // Root request shorthands.

  API.prototype.get = function () {
    var route = this('');
    return route.get.apply(route, arguments);
  };

  API.prototype.post = function () {
    var route = this('');
    return route.post.apply(route, arguments);
  };

  API.prototype.del = function () {
    var route = this('');
    return route.del.apply(route, arguments);
  };

  API.prototype.head = function () {
    var route = this('');
    return route.head.apply(route, arguments);
  };

  API.prototype.put = function () {
    var route = this('');
    return route.put.apply(route, arguments);
  };

  API.prototype.patch = function () {
    var route = this('');
    return route.patch.apply(route, arguments);
  };

  // Configuration/prompt

  if (typeof require !== 'undefined') {

    API.prototype._promptConfig = false;

    API.prototype._persistConfig = false;

    API.prototype.prompt = function (_persistConfig) {
      this._persistConfig = _persistConfig || _persistConfig == null;
      this._promptConfig = true;
      return this;
    };

    API.prototype.configure = function (cont) {
      //return cont();

      var nconf = require('nconf');
      var read = require('read');
      var clc = require('cli-color');
      var path = require('path');

      // Configuration.
      var configFile = rem.CONFIG_FILE || path.join(require('osenv').home(), '.rem.json');
      nconf.file(configFile);

      // Optionally prompt for API key/secret.
      var k, v, _ref, _ref1,
        _this = this;
      if (this.key || !(this._promptConfig && this.manifest.id)) {
        return cont();
      }
      if (this._persistConfig && nconf.get(this.manifest.id)) {
        _ref = nconf.get(this.manifest.id);
        for (k in _ref) {
          v = _ref[k];
          this.opts[k] = v;
        }
        _ref1 = this.opts, this.key = _ref1.key, this.secret = _ref1.secret;
        return cont();
      }
      console.log(clc.yellow('Initializing API keys for ' + this.manifest.id + ' on first use.'));
      if (this.manifest.control) {
        console.log(clc.yellow('Register for an API key here:'), this.manifest.control);
      }
      this.middleware('configure');

      read({
        prompt: clc.yellow(this.manifest.id + ' API key: ')
      }, function (err, key) {
        _this.key = key;
        _this.opts.key = key;
        if (!key) {
          console.error(clc.red('ERROR:'), 'No API key specified, aborting.');
          process.exit(1);
        }
        return read({
          prompt: clc.yellow(_this.manifest.id + ' API secret (if provided): ')
        }, function (err, secret) {
          _this.secret = secret;
          _this.opts.secret = secret;
          if (_this._persistConfig) {
            nconf.set(_this.manifest.id + ':key', key);
            nconf.set(_this.manifest.id + ':secret', secret);
            return nconf.save(function (err, json) {
              console.log(clc.yellow('Your credentials are saved to the configuration file ' + configFile));
              console.log(clc.yellow('Edit that file to update or change your credentials.\n'));
              return cont();
            });
          } else {
            console.log('');
            return cont();
          }
        });
      });
    };

  }

  // Return.

  return API;

})();

/**
 * Public API.
 */

rem.API = API;

rem.create = function (manifest, opts) {
  return remutil.callable(new API(manifest, opts));
};

// TODO Be able to load manifest files locally.
rem.load = function (name, version, opts) {
  version = version || '1';
  var manifest = remutil.lookup(name);
  if (!manifest || !manifest[version]) {
    if (version == '*' && manifest) {
      var version = Object.keys(manifest).sort().pop();
      if (!manifest[version]) {
        throw new Error('Unable to find API ' + JSON.stringify(name) + ' version ' + JSON.stringify(Number(version)) + '. For the latest API, use "*".');
      }
    } else {
      throw new Error('Unable to find API ' + JSON.stringify(name) + '.');
    }
  }
  manifest = manifest[version];
  manifest.id = name;
  manifest.version = version;
  return rem.create(manifest, opts);
};

rem.url = function () {
  var segments = Array.prototype.slice.call(arguments);
  var query = typeof segments[segments.length - 1] == 'object' ? segments.pop() : {};
  var url = remutil.url.parse(segments.shift());
  url.pathname = remutil.path.join.apply(null, [url.pathname].concat(segments));
  url.query = query;

  return new Route(remutil.request.create(url), 'form', function (req, next) {
    req.headers['user-agent'] = req.headers['user-agent'] || rem.USER_AGENT;
    remutil.request.send(req, next);
    return req;
  });
};

rem.consume = remutil.consumeStream;

if (typeof require != 'undefined') {
  // Authentication methods.
  require('./oauth');
  require('./aws');
  require('./session');

  // TODO more than Oauth.
  rem.console = rem.oauthConsole;
}
<commit_msg>Store values in .remconf in home folder.<commit_after>/*

REM: Remedial Rest Interfaces

A library that simplifies and normalizes access to REST APIs.

Reference:
http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven

*/

// Namespace.
var rem = typeof exports == 'undefined' ? this.rem = {} : exports;
var remutil = typeof require == 'undefined' ? remutil : require('./remutil');

// Configuration.
rem.USER_AGENT = 'Mozilla/5.0 (compatible; REMbot/1.0; +http://rem.tcr.io/)';
rem.CONFIG_FILE = null;

/**
 * A hypermedia resource.
 */

var HyperMedia = (function () {

  function HyperMedia (api, res, data) {
    this.api = api;
    this.res = res;
    this.data = data;

    this.type = api.format;
    this.statusCode = Number(this.res.statusCode);
    this.err = this.statusCode > 400 ? this.statusCode : 0;

    // Parse body
    try {
      if (this.type === 'xml') {
        if (!libxmljs) {
          var libxmljs = require('libxmljs');
        }
        this.data = this.xml = libxmljs.parseXmlString(String(this.data));
      } else {
        this.data = this.json = JSON.parse(String(this.data));
      }
    } catch (e) {
      this.err = e;
      console.warn('Could not parse data for type ' + this.type + '.')
    }
  }

  return HyperMedia;

})();

/**
 * A route endpoint.
 */

var Route = (function () {

  function Route (req, defaultBodyMime, middleware) {
    this.req = req;
    this.defaultBodyMime = defaultBodyMime || 'json';
    this.middleware = middleware;
  }

  Route.prototype.get = function (query, next) {
    if (typeof query == 'function') {
      next = query;
      query = null;
    }
    return this.middleware(remutil.modify(remutil.request.url(this.req, {
      query: query || {}
    }), {
      method: 'GET'
    }), next);
  };

  Route.prototype.head = function (query, next) {
    if (typeof query == 'function') {
      next = query;
      query = null;
    }
    return this.middleware(remutil.modify(remutil.request.url(this.req, {
      query: query || {}
    }), {
      method: 'HEAD'
    }), next);
  };

  Route.prototype.post = function (mime, body, next) {
    if (typeof body == 'function') {
      next = body;
      body = mime;
      mime = this.defaultBodyMime;
    }
    return this.middleware(remutil.modify(remutil.request.body(this.req, mime, body), {
      method: 'POST'
    }), next);
  };

  Route.prototype.put = function (mime, body, next) {
    if (typeof body == 'function') {
      next = body;
      body = mime;
      mime = this.defaultBodyMime;
    }
    return this.middleware(remutil.modify(remutil.request.body(this.req, mime, body), {
      method: 'PUT'
    }), next);
  };

  Route.prototype.del = function (next) {
    return this.middleware(remutil.modify(this.req, {
      method: 'DELETE'
    }), next);
  };

  return Route;

})();

/**
 * Middleware.
 */

var Middleware = (function () {

  function Middleware () { }

  Middleware.prototype.pre = function (type, callback) {
    this._middleware || (this._middleware = {});
    (this._middleware[type] || (this._middleware[type] = [])).push(callback);
    return this;
  };

  Middleware.prototype.middleware = function (type) {
    var args = Array.prototype.slice.call(arguments, 1);
    (this._middleware && this._middleware[type] || []).forEach(function (callback) {
      callback.apply(this, args);
    }.bind(this));
    return this;
  };

  return Middleware;

})();

/**
 * API
 */

var API = (function () {

  remutil.inherits(API, Middleware);

  function API (manifest, opts) {
    this.manifest = manifest;
    this.opts = opts || {};

    // Load key, secret, format.
    this.key = this.opts.key;
    this.secret = this.opts.secret;
    this.format = this.opts.format || 'json';

    // Load format-specific options from the manifest.
    if (!this.manifest.formats) {
      this.manifest.formats = {json: {}};
    }
    if (!this.manifest.formats[this.format]) {
      throw new Error("Format \"" + this.format + "\" not available. Please specify an available format in the options parameter.");
    }
    this.manifest = remutil.modify(this.manifest, this.manifest.formats[this.format]);

    // User agent.
    this.pre('request', function (req) {
      req.headers['user-agent'] = req.headers['user-agent'] || rem.USER_AGENT;
    });
    // Route root pathname.
    if (this.manifest.basepath) {
      this.pre('request', function (req) {
        req.url.pathname = this.manifest.basepath + req.url.pathname;
      });
    }
    // Route suffix.
    if (this.manifest.suffix) {
      this.pre('request', function (req) {
        req.url.pathname += this.manifest.suffix;
      });
    }
    // Route configuration parameters.
    if (this.manifest.configParams) {
      this.pre('request', function (req) {
        var params = this.manifest.configParams;
        for (var key in params) {
          req.url.query[key] = this.opts[this.manifest.configParams[key]];
        }
      });
    }
    // Route static parameters.
    if (this.manifest.params) {
      this.pre('request', function (req) {
        var params = this.manifest.params;
        for (var key in params) {
          req.url.query[key] = params[key];
        }
      });
    }
  }

  // Configuration prompt.

  API.prototype.configure = function(cont) {
    return cont();
  };

  // Callable function.

  function invoke (api, segments, send) {
    var query = typeof segments[segments.length - 1] == 'object' ? segments.pop() : {};
    var pathname = remutil.path.join.apply(null, segments);

    return new Route(remutil.request.create({
      query: query, pathname: pathname
    }), api.manifest.uploadFormat, middleware);

    function middleware (req, next) {
      // Expand payload shorthand.
      api.configure(function () {
        // Determine base that matches the path name.
        var pathname = req.url.pathname.replace(/^(?!\/)/, '/')
        // Bases can be fixed or an array of (pattern, base) tuples.
        if (Array.isArray(api.manifest.base)) {
          var base = '';
          api.manifest.base.some(function (tuple) {
            if (typeof tuple == 'string') {
              // TODO this functionality should be removed
              base = tuple;
              return true;
            } else {
              if (pathname.match(new RegExp(tuple[0]))) {
                base = tuple[1];
                return true;
              }
            }
          });
        } else {
          var base = String(api.manifest.base);
        }
        // Update the request with base.
        req = remutil.request.url(req, remutil.url.parse(base))
        req = remutil.request.url(req, {
          pathname: remutil.path.join(req.url.pathname, pathname)
        });

        // Apply manifest filters.
        api.middleware('request', req);
        send(req, next);
      });

      return req;
    }
  }

  API.prototype.stream = function () {
    return invoke(this, Array.prototype.slice.call(arguments), function (req, next) {
      this.send(req, function (err, res) {
        next(req, res);
      });
    }.bind(this));
  };

  API.prototype.call = function () {
    return invoke(this, Array.prototype.slice.call(arguments), function (req, next) {
      this.send(req, function (err, res) {
        if (err) {
          next && next(err, null, res);
        } else {
          remutil.consumeStream(res, function (data) {
            var media = new HyperMedia(this, res, data);
            next && next(media.err, media.data, media);
          });
        }
      });
    }.bind(this));
  };

  API.prototype.send = function (req, next) {
    remutil.request.send(req, next);
  }

  // Root request shorthands.

  API.prototype.get = function () {
    var route = this('');
    return route.get.apply(route, arguments);
  };

  API.prototype.post = function () {
    var route = this('');
    return route.post.apply(route, arguments);
  };

  API.prototype.del = function () {
    var route = this('');
    return route.del.apply(route, arguments);
  };

  API.prototype.head = function () {
    var route = this('');
    return route.head.apply(route, arguments);
  };

  API.prototype.put = function () {
    var route = this('');
    return route.put.apply(route, arguments);
  };

  API.prototype.patch = function () {
    var route = this('');
    return route.patch.apply(route, arguments);
  };

  // Configuration/prompt

  if (typeof require !== 'undefined') {

    API.prototype._promptConfig = false;

    API.prototype._persistConfig = false;

    API.prototype.prompt = function (_persistConfig) {
      this._persistConfig = _persistConfig || _persistConfig == null;
      this._promptConfig = true;
      return this;
    };

    API.prototype.configure = function (cont) {
      //return cont();

      var nconf = require('nconf');
      var read = require('read');
      var clc = require('cli-color');
      var path = require('path');

      // Configuration.
      var configFile = rem.CONFIG_FILE || path.join(require('osenv').home(), '.apikeys');
      nconf.file(configFile);

      // Optionally prompt for API key/secret.
      var k, v, _ref, _ref1,
        _this = this;
      if (this.key || !(this._promptConfig && this.manifest.id)) {
        return cont();
      }
      if (this._persistConfig && nconf.get(this.manifest.id)) {
        _ref = nconf.get(this.manifest.id);
        for (k in _ref) {
          v = _ref[k];
          this.opts[k] = v;
        }
        _ref1 = this.opts, this.key = _ref1.key, this.secret = _ref1.secret;
        return cont();
      }
      console.log(clc.yellow('Initializing API keys for ' + this.manifest.id + ' on first use.'));
      if (this.manifest.control) {
        console.log(clc.yellow('Register for an API key here:'), this.manifest.control);
      }
      this.middleware('configure');

      read({
        prompt: clc.yellow(this.manifest.id + ' API key: ')
      }, function (err, key) {
        _this.key = key;
        _this.opts.key = key;
        if (!key) {
          console.error(clc.red('ERROR:'), 'No API key specified, aborting.');
          process.exit(1);
        }
        return read({
          prompt: clc.yellow(_this.manifest.id + ' API secret (if provided): ')
        }, function (err, secret) {
          _this.secret = secret;
          _this.opts.secret = secret;
          if (_this._persistConfig) {
            nconf.set(_this.manifest.id + ':key', key);
            nconf.set(_this.manifest.id + ':secret', secret);
            return nconf.save(function (err, json) {
              console.log(clc.yellow('Your credentials are saved to the configuration file ' + configFile));
              console.log(clc.yellow('Edit that file to update or change your credentials.\n'));
              return cont();
            });
          } else {
            console.log('');
            return cont();
          }
        });
      });
    };

  }

  // Return.

  return API;

})();

/**
 * Public API.
 */

rem.API = API;

rem.create = function (manifest, opts) {
  return remutil.callable(new API(manifest, opts));
};

// TODO Be able to load manifest files locally.
rem.load = function (name, version, opts) {
  version = version || '1';
  var manifest = remutil.lookup(name);
  if (!manifest || !manifest[version]) {
    if (version == '*' && manifest) {
      var version = Object.keys(manifest).sort().pop();
      if (!manifest[version]) {
        throw new Error('Unable to find API ' + JSON.stringify(name) + ' version ' + JSON.stringify(Number(version)) + '. For the latest API, use "*".');
      }
    } else {
      throw new Error('Unable to find API ' + JSON.stringify(name) + '.');
    }
  }
  manifest = manifest[version];
  manifest.id = name;
  manifest.version = version;
  return rem.create(manifest, opts);
};

rem.url = function () {
  var segments = Array.prototype.slice.call(arguments);
  var query = typeof segments[segments.length - 1] == 'object' ? segments.pop() : {};
  var url = remutil.url.parse(segments.shift());
  url.pathname = remutil.path.join.apply(null, [url.pathname].concat(segments));
  url.query = query;

  return new Route(remutil.request.create(url), 'form', function (req, next) {
    req.headers['user-agent'] = req.headers['user-agent'] || rem.USER_AGENT;
    remutil.request.send(req, next);
    return req;
  });
};

rem.consume = remutil.consumeStream;

if (typeof require != 'undefined') {
  // Authentication methods.
  require('./oauth');
  require('./aws');
  require('./session');

  // TODO more than Oauth.
  rem.console = rem.oauthConsole;
}
<|endoftext|>


<commit_before>var game,player,backgroundMap,mob,commands,mob2,spike,stair;
// 最初のマップ
var map_start;
var sumFPS=0;
var pause_scene,pause_text;
// キャラクター用配列
// var characterList=new CharactersList();
var paused=false;

function toggle_pause(){
 var message_list=
  ([
//   "HELP",
   "GAME PAUSED",
   /*
   "LOL U DIED",
   "DISCONNECTED",
   "DISCONNECTED".split("").reverse().join(""),
   "ACCESS DENIED",
   "YOU LOSE",
   "GAME OVER",
   "PAUSE AHEAD",
   "TYPE THE COMMAND",
   "$ SHUTDOWN",
   "TOO COLD",
   "PING",
   "QUEUE",
   "FORGIVE ME"
   */
  ]).filter(function(val,index,arr){
   return val.length<=(game.width/16);
  });

 if(paused){
  game.popScene();
  game.resume()
 }else{
  var text=message_list[Math.floor(Math.random()*message_list.length)];
  pause_text.setText(text);
  pause_text.x=game.width/2-text.length*16/2;
  game.pushScene(pause_scene);
  game.pause();
  window.parent.toggleConnect();
 }
 paused=!paused;
}

$(function(){
 game=new Game(16*16,16*16);
 lbl=new MutableText(0,0,game.width);

 game.fps=60;
 game.preload('font0.png','images/chara0.png','images/map1.png');
 game.keybind(27,"pause");
 game.keybind(90,"Z"); // Z
 game.keybind(88,"X"); // X
 game.keybind(67,"C"); // C

 // onload
 // プリロード
 game.onload=function(){
  backgroundMap = new Map(16, 16);
  backgroundMap.image = game.assets['images/map1.png'];
  backgroundMap.loadData([
    [64,64,23,23,23,23,23,23,64,64],
    [64,64,64,64,64,64,64,64,64,64],
    [7,64,64,23,64,23,23,64,64,7],
    [7,64,7,64,64,64,64,23,64,7],
    [7,64,23,64,64,64,64,64,64,7],
    [7,64,64,64,64,64,64,7,64,7],
    [7,64,23,64,64,64,64,23,64,7],
    [23,64,64,23,23,64,23,64,64,23],
    [64,64,64,64,64,64,64,64,64,64],
    [64,64,23,23,23,23,23,23,64,64]
   ],[
    [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],
    [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],
    [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],
    [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],
    [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],
    [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],
    [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],
    [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],
    [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],
    [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1]
  ]);
  backgroundMap.collisionData = [
   [0,0,1,1,1,1,1,1,0,0],
   [0,0,0,0,0,0,0,0,0,0],
   [1,0,0,1,0,1,1,0,0,1],
   [1,0,1,0,0,0,0,1,0,1],
   [1,0,1,0,0,0,0,0,0,1],
   [1,0,0,0,0,0,0,1,0,1],
   [1,0,1,0,0,0,0,1,0,1],
   [1,0,0,1,1,0,1,0,0,1],
   [0,0,0,0,0,0,0,0,0,0],
   [0,0,1,1,1,1,1,1,0,0]
  ];

  player=new Player(1,1);
  // 8ずらすことでキャラをマップ座標に居るように見せている
  var image=new Surface(96,128);
  image.draw(game.assets['images/chara0.png'],0,0,96,128,0,0,96,128);
  // 線を引く
  // 衝突判定枠
  for(i=0;i<12;i++){
   var x,y;
   x=(i%3)*32;
   y=Math.floor(i/3)*32;
   image.context.beginPath();
   image.context.moveTo(x+player.offsetX,y+player.offsetY);
   image.context.lineTo(x+player.offsetX+16,y+player.offsetY);
   image.context.lineTo(x+player.offsetX+16,y+player.offsetY+16);
   image.context.lineTo(x+player.offsetX,y+player.offsetY+16);
   image.context.lineTo(x+player.offsetX,y+player.offsetY);
   image.context.strokeStyle="#ff0000";
   image.context.stroke();
  }
  player.image=image;
  // characterList.addChild(player);

  mob = new MoveBot(2,1);
  mob2= new MoveBot(0,1);
  mobImage=new Surface(96,128);
  for(i=0;i<12;i++){
   var x,y;
   x=(i%3)*32;
   y=Math.floor(i/3)*32;
   mobImage.context.beginPath();
   mobImage.context.moveTo(x+mob.offsetX,y+mob.offsetY);
   mobImage.context.lineTo(x+mob.offsetX+16,y+mob.offsetY);
   mobImage.context.lineTo(x+mob.offsetX+16,y+mob.offsetY+16);
   mobImage.context.lineTo(x+mob.offsetX,y+mob.offsetY+16);
   mobImage.context.lineTo(x+mob.offsetX,y+mob.offsetY);
   mobImage.context.strokeStyle="#ff0000";
   mobImage.context.stroke();
  }
  mobImage.draw(game.assets['images/chara0.png'],96,0,96,128,0,0,96,128);
  mob.image=mobImage;
  mob2.image=mobImage;

  // スパイク
  spike=new Spike(2,2);
  stair=new Stair(4,5);

  // マップシーン
  map_start=new MapScene(player,backgroundMap);
  map_start.addCharacters(mob);
  // map_start.addCharacters(mob2);
  map_start.addCharacters(spike);
  map_start.addCharacters(stair);
  /*
  map_start.addEventListener("enterframe",function(){
   console.log("map_start enter_frame");
  });
  player.addEventListener("enterframe",function(){
   console.log("player enter_frame");
  });
  stair.addEventListener("enterframe",function(){
   console.log("stair enter_frame");
  });
  */

  game.rootScene.backgroundColor="#000000";
  game.pushScene(map_start);
  /*
  game.rootScene.addEventListener('enterframe',function(e){
   // FPS計算
   sumFPS+=game.actualFps;
   if(game.frame%10==0){
    lbl.setText(""+Math.round(sumFPS/10));
    sumFPS=0;
   }
   characterList.sortY();
  });
  */

  // ポーズ設定
  pause_scene=new Scene();
  pause_text=new MutableText(0,game.height/2-16/2,game.width);
  pause_text.setText("GAME PAUSED");
  pause_scene.backgroundColor="rgba(0, 0, 0, 0.5)";
  pause_scene.addChild(pause_text);

  // 最初のメッセージ表示
  /*
  player.pushCommand(new player.waitMessage(player,{messages:[
     "[Zキーを押して次に進む]",
     "デモ版\"RPG\"にようこそ",
     "このゲームでは\n塔の頂上を目指すことです",
     "マップのどこかにある\n階段に乗ると、\n上に行くことが出来ます",
     "では、頑張ってください！",
     "カーソルキー(←↓↑→)で\n上下左右に移動します"]})
  );
  */
 }

 game.addEventListener('pausebuttondown',function(){
  toggle_pause();
 });
 // game.debug();
 game.start();
});

function getGameObj(){
 return game;
}

function termCommands(){
 var data={
  player: player,
  mob:mob,
  mob2: mob2,
  spike: spike
 };
 var termObj={
  objs: function(){
   for(i in data){
    this.echo(i);
   }
  },
  echo: function(){
   if(arguments.length==0){
    this.echo("echo [String]");
   }else{
    var term=this;
    Array.prototype.slice.call(arguments).forEach(function(i){
     term.echo(i);
    });
   }
  },
  where: function(){
   this.echo("(" + player.mapX + ", "+player.mapY+")");
  },
  commands: function(){
   for(i in commands){
    this.echo(i);
   }
  },
  help: function(){
   for(var i in termObj){
    this.echo(i);
   }
  },
  queue: function(){
   var self=this;
   player.queue.forEach(function(cmd,index){
    self.echo(index+" : "+cmd.toString());
   });
  },
  setTimeoutTest: (function(){
   var i;
   return function(self){
    if(typeof self==="undefined"){
     i=0;
     self=this;
    }
    i++;
    self.echo(i);
    if(i<5){
     setTimeout(arguments.callee,1000,self);
    }
   };
  })(),
  walk: function(){
   var directionStr=["down","left","right","up"];
   if(arguments.length<1 || arguments[0] == "help"){
    this.echo("walk *direction* [times]")
    this.echo("歩くコマンドを追加する");
    this.echo("引数");
    this.echo("direction down: 下 left: 左 right: 右 up: 上");
    this.echo("times: 回数\n\tデフォルト: 1\n\t0は1として扱われる");
   }else{
    var direction=arguments[0]-0;
    var times=arguments[1] || 1;
    if(isNaN(direction)){
     direction=directionStr.indexOf(arguments[0].toLowerCase());
    }

    if(direction < 0 || 3< direction){
     this.echo("方向の指定がおかしい");
    }else if(times<0){
     this.echo("回数に負の値は指定できない");
    }else{
     for(var i=0;i<times;i++){
      player.pushCommand('walk',{direction: direction});
     }
     this.echo("walk "+directionStr[direction]+"を"+(times > 1 ? times +"回": "") + "追加" );
    }
   }
  }
 };

 return termObj;
}

function mes_debug_array(){
 var message=[];
 for(var i=0;i<arguments.length;i++){
  message.push(arguments[i]);
 }
 return message;
}
<commit_msg>コメント追加/メッセージ変更<commit_after>var game,player,backgroundMap,mob,commands,mob2,spike,stair;
// 最初のマップ
var map_start;
var sumFPS=0;
var pause_scene,pause_text;
// キャラクター用配列
// var characterList=new CharactersList();
var paused=false;

function toggle_pause(){
 var message_list=
  ([
   "GAME PAUSED",
   /*
   "HELP",
   "LOL U DIED",
   "DISCONNECTED",
   "DISCONNECTED".split("").reverse().join(""),
   "ACCESS DENIED",
   "YOU LOSE",
   "GAME OVER",
   "PAUSE AHEAD",
   "TYPE THE COMMAND",
   "$ SHUTDOWN",
   "TOO COLD",
   "PING",
   "QUEUE",
   "FORGIVE ME"
   */
  ]).filter(function(val,index,arr){
   return val.length<=(game.width/16);
  });

 if(paused){
  game.popScene();
  game.resume()
 }else{
  var text=message_list[Math.floor(Math.random()*message_list.length)];
  pause_text.setText(text);
  pause_text.x=game.width/2-text.length*16/2;
  game.pushScene(pause_scene);
  game.pause();
  window.parent.toggleConnect();
 }
 paused=!paused;
}

$(function(){
 game=new Game(16*16,16*16);
 lbl=new MutableText(0,0,game.width);

 game.fps=60;
 game.preload('font0.png','images/chara0.png','images/map1.png');
 game.keybind(27,"pause");
 game.keybind(90,"Z"); // Z
 game.keybind(88,"X"); // X
 game.keybind(67,"C"); // C

 // onload
 // プリロード
 game.onload=function(){
  backgroundMap = new Map(16, 16);
  backgroundMap.image = game.assets['images/map1.png'];
  backgroundMap.loadData([
    [64,64,23,23,23,23,23,23,64,64],
    [64,64,64,64,64,64,64,64,64,64],
    [7,64,64,23,64,23,23,64,64,7],
    [7,64,7,64,64,64,64,23,64,7],
    [7,64,23,64,64,64,64,64,64,7],
    [7,64,64,64,64,64,64,7,64,7],
    [7,64,23,64,64,64,64,23,64,7],
    [23,64,64,23,23,64,23,64,64,23],
    [64,64,64,64,64,64,64,64,64,64],
    [64,64,23,23,23,23,23,23,64,64]
   ],[
    [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],
    [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],
    [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],
    [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],
    [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],
    [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],
    [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],
    [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],
    [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],
    [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1]
  ]);
  backgroundMap.collisionData = [
   [0,0,1,1,1,1,1,1,0,0],
   [0,0,0,0,0,0,0,0,0,0],
   [1,0,0,1,0,1,1,0,0,1],
   [1,0,1,0,0,0,0,1,0,1],
   [1,0,1,0,0,0,0,0,0,1],
   [1,0,0,0,0,0,0,1,0,1],
   [1,0,1,0,0,0,0,1,0,1],
   [1,0,0,1,1,0,1,0,0,1],
   [0,0,0,0,0,0,0,0,0,0],
   [0,0,1,1,1,1,1,1,0,0]
  ];

  player=new Player(1,1);
  // 8ずらすことでキャラをマップ座標に居るように見せている
  var image=new Surface(96,128);
  image.draw(game.assets['images/chara0.png'],0,0,96,128,0,0,96,128);
  // 線を引く
  // 衝突判定枠
  for(i=0;i<12;i++){
   var x,y;
   x=(i%3)*32;
   y=Math.floor(i/3)*32;
   image.context.beginPath();
   image.context.moveTo(x+player.offsetX,y+player.offsetY);
   image.context.lineTo(x+player.offsetX+16,y+player.offsetY);
   image.context.lineTo(x+player.offsetX+16,y+player.offsetY+16);
   image.context.lineTo(x+player.offsetX,y+player.offsetY+16);
   image.context.lineTo(x+player.offsetX,y+player.offsetY);
   image.context.strokeStyle="#ff0000";
   image.context.stroke();
  }
  player.image=image;
  // characterList.addChild(player);

  mob = new MoveBot(2,1);
  mob2= new MoveBot(0,1);
  mobImage=new Surface(96,128);
  for(i=0;i<12;i++){
   var x,y;
   x=(i%3)*32;
   y=Math.floor(i/3)*32;
   mobImage.context.beginPath();
   mobImage.context.moveTo(x+mob.offsetX,y+mob.offsetY);
   mobImage.context.lineTo(x+mob.offsetX+16,y+mob.offsetY);
   mobImage.context.lineTo(x+mob.offsetX+16,y+mob.offsetY+16);
   mobImage.context.lineTo(x+mob.offsetX,y+mob.offsetY+16);
   mobImage.context.lineTo(x+mob.offsetX,y+mob.offsetY);
   mobImage.context.strokeStyle="#ff0000";
   mobImage.context.stroke();
  }
  mobImage.draw(game.assets['images/chara0.png'],96,0,96,128,0,0,96,128);
  mob.image=mobImage;
  mob2.image=mobImage;

  // スパイク
  spike=new Spike(2,2);
  stair=new Stair(4,5);

  // マップシーン
  map_start=new MapScene(player,backgroundMap);
  map_start.addCharacters(mob);
  // map_start.addCharacters(mob2);
  map_start.addCharacters(spike);
  map_start.addCharacters(stair);
  /*
  map_start.addEventListener("enterframe",function(){
   console.log("map_start enter_frame");
  });
  player.addEventListener("enterframe",function(){
   console.log("player enter_frame");
  });
  stair.addEventListener("enterframe",function(){
   console.log("stair enter_frame");
  });
  */

  game.rootScene.backgroundColor="#000000";
  game.pushScene(map_start);
  /*
  game.rootScene.addEventListener('enterframe',function(e){
   // FPS計算
   sumFPS+=game.actualFps;
   if(game.frame%10==0){
    lbl.setText(""+Math.round(sumFPS/10));
    sumFPS=0;
   }
   characterList.sortY();
  });
  */

  // ポーズ設定
  pause_scene=new Scene();
  pause_text=new MutableText(0,game.height/2-16/2,game.width);
  pause_text.setText("GAME PAUSED");
  pause_scene.backgroundColor="rgba(0, 0, 0, 0.5)";
  pause_scene.addChild(pause_text);

  // 最初のメッセージ表示
  /*
  player.pushCommand(new player.waitMessage(player,{messages:[
     "[Zキーを押して次に進む]",
     "デモ版\"RPG\"にようこそ",
     "このゲームでは\n塔の頂上を目指すことです",
     "マップのどこかにある\n階段に乗ると、\n上に行くことが出来ます",
     "では、頑張ってください！",
     "カーソルキー(←↓↑→)で\n上下左右に移動します"]})
  );
  */
 }

 game.addEventListener('pausebuttondown',function(){
  toggle_pause();
 });
 // game.debug();
 game.start();
});

function getGameObj(){
 return game;
}

// コマンドオブジェクト生成
function termCommands(){
 var data={
  player: player,
  mob:mob,
  mob2: mob2,
  spike: spike
 };
 var termObj={
  objs: function(){
   for(i in data){
    this.echo(i);
   }
  },
  echo: function(){
   if(arguments.length==0){
    this.echo("echo [String]");
   }else{
    var term=this;
    Array.prototype.slice.call(arguments).forEach(function(i){
     term.echo(i);
    });
   }
  },
  where: function(){
   this.echo("(" + player.mapX + ", "+player.mapY+")");
  },
  commands: function(){
   for(i in commands){
    this.echo(i);
   }
  },
  help: function(){
   for(var i in termObj){
    this.echo(i);
   }
  },
  queue: function(){
   var self=this;
   player.queue.forEach(function(cmd,index){
    self.echo(index+" : "+cmd.toString());
   });
  },
  setTimeoutTest: (function(){
   var i;
   return function(self){
    if(typeof self==="undefined"){
     i=0;
     self=this;
    }
    i++;
    self.echo(i);
    if(i<5){
     setTimeout(arguments.callee,1000,self);
    }
   };
  })(),
  walk: function(){
   var directionStr=["down","left","right","up"];
   if(arguments.length<1 || arguments[0] == "help"){
    this.echo("walk *direction* [times]")
    this.echo("歩くコマンドを追加する");
    this.echo("引数");
    this.echo("direction down: 下 left: 左 right: 右 up: 上");
    this.echo("times: 回数\n\tデフォルト: 1\n\t0は1として扱われる");
   }else{
    var direction=arguments[0]-0;
    var times=arguments[1] || 1;
    if(isNaN(direction)){
     direction=directionStr.indexOf(arguments[0].toLowerCase());
    }

    if(direction < 0 || 3< direction){
     this.echo("方向の指定がおかしい");
    }else if(times<0){
     this.echo("回数に負の値は指定できない");
    }else{
     for(var i=0;i<times;i++){
      player.pushCommand('walk',{direction: direction});
     }
     this.echo("walk "+directionStr[direction]+"を"+(times > 1 ? times +"回": "") + "追加" );
    }
   }
  }
 };

 return termObj;
}

function mes_debug_array(){
 var message=[];
 for(var i=0;i<arguments.length;i++){
  message.push(arguments[i]);
 }
 return message;
}
<|endoftext|>


<commit_before>import Ember from 'ember';
import C from 'ui/utils/constants';
import EditLabels from 'ui/mixins/edit-labels';

export default Ember.Mixin.create(EditLabels, {
  primaryResource: Ember.computed.alias('model.service'),
  labelResource: Ember.computed.alias('model.service.launchConfig'),

  actions: {
    addServiceLink: function() {
      this.get('serviceLinksArray').pushObject(Ember.Object.create({serviceId: null, linkName: null}));
    },
    removeServiceLink: function(obj) {
      this.get('serviceLinksArray').removeObject(obj);
    },
  },

  initFields: function() {
    this._super();
    this.initServiceLinks();
    this.initScheduling();
  },

  // ----------------------------------
  // Services
  // ----------------------------------
  serviceChoices: function() {
    var env = this.get('selectedEnvironment');
    var group = 'Project: ' + (env.get('name') || '('+env.get('id')+')');

    var list = (env.get('services')||[]).map((service) => {
      var serviceLabel = (service.get('name') || '('+service.get('id')+')');
      if ( service.get('state') !== 'active' )
      {
        serviceLabel += ' (' + service.get('state') + ')';
      }

      return Ember.Object.create({
        group: group,
        id: service.get('id'),
        name: serviceLabel,
        obj: service,
      });
    });

    return list.sortBy('group','name','id');
  }.property('environment.services.@each.{id,name,state}'),

  serviceLinksArray: null,
  serviceLinksAsMap: null,
  initServiceLinks: function() {
    var out = [];
    var links;
    if ( this.get('service.id') )
    {
      // Edit
      links = this.get('service.consumedServicesWithNames')||[];
    }
    else
    {
      // New / Clone
      links = this.get('service.serviceLinks')||[];
    }

    links.forEach(function(obj) {
      var linkName = obj.get('name');
      var service = obj.get('service');

      out.push(Ember.Object.create({
        linkName: (linkName === service.get('name') ? '' : linkName),
        obj: service,
        serviceId: service.get('id'),
      }));
    });

    this.set('serviceLinksArray', out);
  },

  serviceLinksDidChange: function() {
    // Sync with the actual environment
    var out = {};
    this.get('serviceLinksArray').forEach((row) => {
      if ( row.serviceId )
      {
        var name = row.linkName;
        if ( !name )
        {
          // If no name is given, use the name of the service
          var service = this.get('serviceChoices').filterProperty('id', row.serviceId)[0];
          if ( service )
          {
            name = service.get('obj.name');
          }
        }

        if ( name )
        {
          out[name] = row.serviceId;
        }
      }
    });

    this.set('serviceLinksAsMap', out);
  }.observes('serviceLinksArray.@each.{linkName,serviceId}'),

  // ----------------------------------
  // Scheduling
  // ----------------------------------
  isGlobal: null,
  initScheduling: function() {
    var existing = this.getLabel(C.LABEL.SCHED_GLOBAL);
    this.set('isGlobal', !!existing);
    this._super();
    if ( this.get('isRequestedHost') )
    {
      this.set('isGlobal', false);
    }
  },

  globalDidChange: function() {
    if ( this.get('isGlobal') )
    {
      this.setLabel(C.LABEL.SCHED_GLOBAL,'true');
      this.set('isRequestedHost', false);
    }
    else
    {
      this.removeLabel(C.LABEL.SCHED_GLOBAL);
    }
  }.observes('isGlobal'),

  isRequestedHostDidChangeGlobal: function() {
    if ( this.get('isRequestedHost') )
    {
      this.set('isGlobal', false);
    }
  }.observes('isRequestedHost'),

  // ----------------------------------
  // Save
  // ----------------------------------
  didSave: function() {
    var service = this.get('model.service');
    if ( service.get('type').toLowerCase() !== 'externalservice')
    {
      return service.doAction('setservicelinks', {serviceLinks: this.get('serviceLinksAsMap')});
    }
  },

});
<commit_msg>Use serviceIds for dns and lb links instead of map (rancherio/rancher#1215)<commit_after>import Ember from 'ember';
import C from 'ui/utils/constants';
import EditLabels from 'ui/mixins/edit-labels';

export default Ember.Mixin.create(EditLabels, {
  primaryResource: Ember.computed.alias('model.service'),
  labelResource: Ember.computed.alias('model.service.launchConfig'),

  actions: {
    addServiceLink: function() {
      this.get('serviceLinksArray').pushObject(Ember.Object.create({serviceId: null, linkName: null}));
    },
    removeServiceLink: function(obj) {
      this.get('serviceLinksArray').removeObject(obj);
    },
  },

  initFields: function() {
    this._super();
    this.initServiceLinks();
    this.initScheduling();
  },

  // ----------------------------------
  // Services
  // ----------------------------------
  serviceChoices: function() {
    var env = this.get('selectedEnvironment');
    var group = 'Project: ' + (env.get('name') || '('+env.get('id')+')');

    var list = (env.get('services')||[]).map((service) => {
      var serviceLabel = (service.get('name') || '('+service.get('id')+')');
      if ( service.get('state') !== 'active' )
      {
        serviceLabel += ' (' + service.get('state') + ')';
      }

      return Ember.Object.create({
        group: group,
        id: service.get('id'),
        name: serviceLabel,
        obj: service,
      });
    });

    return list.sortBy('group','name','id');
  }.property('environment.services.@each.{id,name,state}'),

  serviceLinksArray: null,
  serviceLinksAsMap: null,
  initServiceLinks: function() {
    var out = [];
    var links;
    if ( this.get('service.id') )
    {
      // Edit
      links = this.get('service.consumedServicesWithNames')||[];
    }
    else
    {
      // New / Clone
      links = this.get('service.serviceLinks')||[];
    }

    links.forEach(function(obj) {
      var linkName = obj.get('name');
      var service = obj.get('service');

      out.push(Ember.Object.create({
        linkName: (linkName === service.get('name') ? '' : linkName),
        obj: service,
        serviceId: service.get('id'),
      }));
    });

    this.set('serviceLinksArray', out);
  },

  serviceLinksDidChange: function() {
    // Sync with the actual environment
    var out = {};
    this.get('serviceLinksArray').forEach((row) => {
      if ( row.serviceId )
      {
        var name = row.linkName;
        if ( !name )
        {
          // If no name is given, use the name of the service
          var service = this.get('serviceChoices').filterProperty('id', row.serviceId)[0];
          if ( service )
          {
            name = service.get('obj.name');
          }
        }

        if ( name )
        {
          out[name] = row.serviceId;
        }
      }
    });

    this.set('serviceLinksAsMap', out);
  }.observes('serviceLinksArray.@each.{linkName,serviceId}'),

  // ----------------------------------
  // Scheduling
  // ----------------------------------
  isGlobal: null,
  initScheduling: function() {
    var existing = this.getLabel(C.LABEL.SCHED_GLOBAL);
    this.set('isGlobal', !!existing);
    this._super();
    if ( this.get('isRequestedHost') )
    {
      this.set('isGlobal', false);
    }
  },

  globalDidChange: function() {
    if ( this.get('isGlobal') )
    {
      this.setLabel(C.LABEL.SCHED_GLOBAL,'true');
      this.set('isRequestedHost', false);
    }
    else
    {
      this.removeLabel(C.LABEL.SCHED_GLOBAL);
    }
  }.observes('isGlobal'),

  isRequestedHostDidChangeGlobal: function() {
    if ( this.get('isRequestedHost') )
    {
      this.set('isGlobal', false);
    }
  }.observes('isRequestedHost'),

  // ----------------------------------
  // Save
  // ----------------------------------
  didSave: function() {
    var service = this.get('model.service');
    var type = service.get('type').toLowerCase();
    if ( type === 'service' )
    {
      return service.doAction('setservicelinks', {serviceLinks: this.get('serviceLinksAsMap')});
    }
    else if ( ['dnsservice','loadbalancerservice'].indexOf(type) >= 0 )
    {
      var ids = this.get('serviceLinksArray').map((link) => { return link.serviceId; }).uniq();
      return service.doAction('setservicelinks', {serviceIds: ids});
    }
  },

});
<|endoftext|>


<commit_before>var game,player,backgroundMap,mob,commands,mob2,spike,stair;
var map_manager;
// 最初のマップ
var map_start;
var sumFPS=0;
var pause_scene,pause_text;
// キャラクター用配列
// var characterList=new CharactersList();
var paused=false;

function toggle_pause(){
 var message_list=
  ([
   "GAME PAUSED",
   /*
   "HELP",
   "LOL U DIED",
   "DISCONNECTED",
   "DISCONNECTED".split("").reverse().join(""),
   "ACCESS DENIED",
   "YOU LOSE",
   "GAME OVER",
   "PAUSE AHEAD",
   "TYPE THE COMMAND",
   "$ SHUTDOWN",
   "TOO COLD",
   "PING",
   "QUEUE",
   "FORGIVE ME"
   */
  ]).filter(function(val,index,arr){
   return val.length<=(game.width/16);
  });

 if(paused){
  game.popScene();
  game.resume()
 }else{
  var text=message_list[Math.floor(Math.random()*message_list.length)];
  pause_text.setText(text);
  pause_text.x=game.width/2-text.length*16/2;
  game.pushScene(pause_scene);
  game.pause();
  window.parent.toggleConnect();
 }
 paused=!paused;
}

$(function(){
 game=new Game(16*16,16*16);
 lbl=new MutableText(0,0,game.width);
 game.fps=60;
 game.preload('font0.png','images/chara0.png','images/chara5.png','images/map1.png','images/map0.png');
 game.keybind(27,"pause");
 game.keybind(90,"Z"); // Z
 game.keybind(88,"X"); // X
 game.keybind(67,"C"); // C

 map_manager.set_core(game);

 // onload
 // プリロード
 game.onload=function(){
  game.rootScene.backgroundColor="#000000";
  register_maps(game);
  map_manager.move_player(["F1"],1,1);
  player=game.currentScene.player;

  // ポーズ設定
  pause_scene=new Scene();
  pause_text=new MutableText(0,game.height/2-16/2,game.width);
  pause_text.setText("GAME PAUSED");
  pause_scene.backgroundColor="rgba(0, 0, 0, 0.5)";
  pause_scene.addChild(pause_text);

  // 最初のメッセージ表示
  /*
  player.pushCommand(new player.waitMessage(player,{messages:[
     "[Zキーを押して次に進む]",
     "デモ版\"RPG\"にようこそ",
     "このゲームでは\n塔の頂上を目指すことです",
     "マップのどこかにある\n階段に乗ると、\n上に行くことが出来ます",
     "では、頑張ってください！",
     "カーソルキー(←↓↑→)で\n上下左右に移動します"]})
  );
  */
 }

 game.addEventListener('pausebuttondown',function(){
  toggle_pause();
 });
 // game.debug();
 game.start();
});

function getGameObj(){
 return game;
}

function mes_debug_array(){
 var message=[];
 for(var i=0;i<arguments.length;i++){
  message.push(arguments[i]);
 }
 return message;
}
<commit_msg>不要な変数を削除<commit_after>var game,map_manager;

var player,backgroundMap,mob,commands,mob2,spike,stair;
// 最初のマップ
var pause_scene,pause_text;
// キャラクター用配列
// var characterList=new CharactersList();
var paused=false;

function toggle_pause(){
 var message_list=
  ([
   "GAME PAUSED",
   /*
   "HELP",
   "LOL U DIED",
   "DISCONNECTED",
   "DISCONNECTED".split("").reverse().join(""),
   "ACCESS DENIED",
   "YOU LOSE",
   "GAME OVER",
   "PAUSE AHEAD",
   "TYPE THE COMMAND",
   "$ SHUTDOWN",
   "TOO COLD",
   "PING",
   "QUEUE",
   "FORGIVE ME"
   */
  ]).filter(function(val,index,arr){
   return val.length<=(game.width/16);
  });

 if(paused){
  game.popScene();
  game.resume()
 }else{
  var text=message_list[Math.floor(Math.random()*message_list.length)];
  pause_text.setText(text);
  pause_text.x=game.width/2-text.length*16/2;
  game.pushScene(pause_scene);
  game.pause();
  window.parent.toggleConnect();
 }
 paused=!paused;
}

$(function(){
 game=new Game(16*16,16*16);
 lbl=new MutableText(0,0,game.width);
 game.fps=60;
 game.preload('font0.png','images/chara0.png','images/chara5.png','images/map1.png','images/map0.png');
 game.keybind(27,"pause");
 game.keybind(90,"Z"); // Z
 game.keybind(88,"X"); // X
 game.keybind(67,"C"); // C

 map_manager.set_core(game);

 // onload
 // プリロード
 game.onload=function(){
  game.rootScene.backgroundColor="#000000";
  register_maps(game);
  map_manager.move_player(["F1"],1,1);
  player=game.currentScene.player;

  // ポーズ設定
  pause_scene=new Scene();
  pause_text=new MutableText(0,game.height/2-16/2,game.width);
  pause_text.setText("GAME PAUSED");
  pause_scene.backgroundColor="rgba(0, 0, 0, 0.5)";
  pause_scene.addChild(pause_text);

  // 最初のメッセージ表示
  /*
  player.pushCommand(new player.waitMessage(player,{messages:[
     "[Zキーを押して次に進む]",
     "デモ版\"RPG\"にようこそ",
     "このゲームでは\n塔の頂上を目指すことです",
     "マップのどこかにある\n階段に乗ると、\n上に行くことが出来ます",
     "では、頑張ってください！",
     "カーソルキー(←↓↑→)で\n上下左右に移動します"]})
  );
  */
 }

 game.addEventListener('pausebuttondown',function(){
  toggle_pause();
 });
 // game.debug();
 game.start();
});

function getGameObj(){
 return game;
}

function mes_debug_array(){
 var message=[];
 for(var i=0;i<arguments.length;i++){
  message.push(arguments[i]);
 }
 return message;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2011-2014 YY Digital Pty Ltd. All Rights Reserved.
 * Please see the LICENSE file included with this distribution for details.
 */

var path   = require("path"),
    fs     = require("fs"),
    spawn  = require("./spawn"),
    async  = require("async"),
    fs_map = require("./fs_map"),
    api    = require("./api"),
    bundle = require("./bundle"),
    config = require("./config"),
    uglify = require("./uglify"),
    logger = require("../../server/logger.js"),
    jshint = require("./jshint_runner"),
    wrench = require("wrench"),
    _      = require("underscore");

require("./fs_extension");

// Copies all Resource files and prepares JS files
function prepare(src, dst, callback) {
  var app_name = config.app_name;
  if (src.match("js$")){
    try {
      var src_text = uglify.toString(fs.readFileSync(src).toString(),src);
      if (src.match("_spec.js$")) {
        if (config.specType === "jasmine") {
          src_text =  "var __jasmine = require('/lib/jasmine');var methods = ['spyOn','it','xit','expect','runs','waits','waitsFor','beforeEach','afterEach','describe','xdescribe','jasmine'];methods.forEach(function(method) {this[method] = __jasmine[method];});"
          +src_text;
        } else if (config.specType === "mocha-should") {
          src_text =  "var should = require('/lib/should');\n"
            + "var sinon = require('/lib/sinon');\n"
          +src_text;
        } else if (config.specType === "mocha-chai") {
          src_text =  "var chai = require('/lib/chai'); var expect = chai.expect; var assert = chai.assert;\n"
            + "var sinon = require('/lib/sinon');\n"
          +src_text;
        }
        if (config.isAlloy) {
          src_text =
          "var Alloy = __p.require(\"alloy\"), _ = Alloy._, Backbone = Alloy.Backbone;\n"
          +src_text;
        }
      }
      else if(config.runCoverage && !src.match("spec/")) { //Instrumenting the application code with istanbul for code coverage
		var instrumentedCode = require("./coverage").instrumentCode(src_text, src);
		src_text = instrumentedCode;

		config.instrumentedfiles[src] = dst;// storing all instrumented file
      }

      fs.writeFile(dst,src_text, callback);
    } catch (e) {
      logger.error(e.message + "\nFile   : " + src + "\nLine   : " + e.line + "\nColumn : " + e.col);
      config.isWatching || process.exit(1);
    }
  } else { // Non-JS file - just pump it
    var  is = fs.createReadStream(src);
    var  os = fs.createWriteStream(dst);
    is.on("end", callback).pipe(os);
  }
}

function copyI18n(file, callback) {
  var read = fs.createReadStream(path.join(config.i18n_path,file));
  var write = fs.createWriteStream(path.join(config.tishadow_src, file));
  write.on('close',callback);
  read.pipe(write);
};

function finalise(file_list,callback) {
  // Bundle up to go
  var total = file_list.files.length;
  bundle.pack(file_list.files,function(written) {
    logger.info(total+ " file(s) bundled.");
    fs_map.writeMap();
    fs.touch(config.last_updated_file);
    if (config.isBundle) {
      logger.info("Bundle Ready: " + config.bundle_file);
      if (callback) {
        callback();
      }
    } else {
      api.newBundle(config.isPatch?_.filter(file_list.files, function(f) { return f.match(".js$");}):null );
    }
  });
}

module.exports = function(env, callback) {
  config.buildPaths(env, function() {
    if (env.jshint) {
      logger.info("Running JSHint");
      jshint.checkPath(config.jshint_path);
    }

    logger.info("Beginning Build Process");
    // a js map of hashes must be built whether or not it is an update.
    if (config.isAlloy && !config.skipAlloyCompile) {
      if (config.platform === undefined) {
        logger.error("You need to use the --platform (android|ios) flag or have deployment-targets in tiapp.xml with an alloy project.");
        process.exit();
      }
      async.detectSeries(config.platform, function(platform, callback) {
        logger.info("Compiling Alloy for " + platform);
        var args = ['compile', '-b','-l', '2', '--platform', platform, '--config', 'sourcemap=false'];
        if (config.alloyCompileFile) {
          args[7] = "sourcemap=false,file="+config.alloyCompileFile;
        }
        var alloy_command;
        if (config.useAppcCLI) {
          alloy_command = spawn("appc", ['alloy'].concat(args), {stdio: "inherit"});
        } else {
          alloy_command = spawn('alloy', args, {stdio: "inherit"});
        }

        alloy_command.on("exit", function(code) {
          if (code !== 0) {
            logger.error("Alloy Compile Error\n");
            callback(true);
          }
          if (fs.existsSync(config.res_alloy_path)) {
            wrench.copyDirSyncRecursive(
              config.res_alloy_path,
              path.join(config.resources_path,(platform === 'ios' ? 'iphone' : platform),'alloy'),
              {preserve:true,preserveFiles:true}
            );
          }
          callback(false);
        });
        alloy_command.on("error", function() {
          logger.error("Alloy Compile Error\n");
          callback(true);
        });
      },function(failed){
        if (failed) return;
        if (fs.existsSync(config.res_alloy_path)) {
          fs.rm_rf(config.res_alloy_path);
        }
        fs.touch(path.join(config.resources_path,'app.js'));
        fs_map.buildMap();
        beginCompile(callback);
      });;
      //Remove non-specific
    } else {
      fs_map.buildMap();
      beginCompile(callback);
    }
  });
};

function beginCompile(callback) {
  var file_list,i18n_list,spec_list,assets_list;
  if( config.isUpdate) {
    var last_stat = fs.statSync(config.last_updated_file);
    file_list = fs_map.mapFiles();
    if (config.isModule)  {
      assets_list = fs.getList(config.assets_path,last_stat.mtime);
    }
    i18n_list = fs.getList(config.i18n_path,last_stat.mtime);
    spec_list = fs.getList(config.spec_path,last_stat.mtime);

    if (file_list.files.length === 0 && (!config.isModule || assets_list.files.length === 0) && i18n_list.files.length === 0 && spec_list.files.length === 0) {
      logger.warn("Nothing to update.");
      return;
    }
  } else {
    if (!fs.existsSync(config.build_path)){
      fs.mkdirSync(config.build_path, 0755);
    }
    //Clean Build Directory
    if (fs.existsSync(config.tishadow_build)) {
      fs.rm_rf(config.tishadow_build);
    }
    // Create the tishadow build paths
    fs.mkdirs([config.tishadow_build, config.tishadow_src, config.tishadow_dist]);
    file_list = fs.getList(config.resources_path);
    if (config.isModule) {
      assets_list = fs.getList(config.assets_path);
    }
    i18n_list = fs.getList(config.i18n_path);
    spec_list = fs.getList(config.spec_path);
  }

  // Build the required directory structure
  fs.mkdirs(file_list.dirs, config.tishadow_src);
  fs.mkdirs(i18n_list.dirs, config.tishadow_src);
  if(spec_list.files.length > 0) {
    if (!fs.existsSync(config.tishadow_spec)) {
      fs.mkdirSync(config.tishadow_spec, 0755);
    }
    fs.mkdirs(spec_list.dirs, config.tishadow_spec);
    spec_list.files = spec_list.files.map(function(file) { return "spec/" + file;});
    spec_list.dirs = ["spec"].concat(spec_list.dirs.map(function(dir) {return "spec/" + dir;}));
  }

  // prepare tasks to process files
  var process_tasks = file_list.files.map(function(file) {
    return _.bind(prepare, null, path.join(config.resources_path,file), path.join(config.tishadow_src,file));
  }).concat(spec_list.files.map(function(file) {
    return _.bind(prepare, null, path.join(config.base,file), path.join(config.tishadow_src,file));
  }));

  // if acting on a native module - see https://github.com/dbankier/TiShadow/commit/bec799b3d03660704ce6ab303f5e28110b86f051
  if (config.isModule && assets_list.files.length > 0) {
    // create paths
  	fs.mkdirs([config.module_name], config.tishadow_src);
  	fs.mkdirs(assets_list.dirs, config.module_path);
    // add files for processing
    process_tasks = process_tasks.concat(assets_list.files.map(function(file) {
      var fileName = file.slice(0,file.lastIndexOf('.'));
      if(fileName == config.module_name){
      	return _.bind(prepare, null, path.join(config.assets_path,file), path.join(config.tishadow_src, file));
      } else {
      	return _.bind(prepare, null, path.join(config.assets_path,file), path.join(config.tishadow_src, config.module_name, file));
      }
    }));
    console.log(process_tasks);
    // modify for bundling
    assets_list.files = assets_list.files.map(function(file) {
      var filePath = config.module_name + "/" + file;
      var fileName = file.slice(0,file.lastIndexOf('.'));
      if(fileName == config.module_name){
      	filePath = file;
      }
      return filePath;
    });
  }

  async.series([
    _.bind(async.eachLimit, null, i18n_list.files, 100, copyI18n), //localisation filed
    _.bind(async.parallelLimit, null, process_tasks, 100), // source, assets, specs
    function() {
      file_list.files = file_list.files.concat(i18n_list.files).concat(spec_list.files);
      if (config.isModule) {
        file_list.files = file_list.files.concat(assets_list.files);
      }
      finalise(file_list,callback);
    }
  ]);
};
<commit_msg>Fix alloy compile error with -l option<commit_after>/*
 * Copyright (c) 2011-2014 YY Digital Pty Ltd. All Rights Reserved.
 * Please see the LICENSE file included with this distribution for details.
 */

var path   = require("path"),
    fs     = require("fs"),
    spawn  = require("./spawn"),
    async  = require("async"),
    fs_map = require("./fs_map"),
    api    = require("./api"),
    bundle = require("./bundle"),
    config = require("./config"),
    uglify = require("./uglify"),
    logger = require("../../server/logger.js"),
    jshint = require("./jshint_runner"),
    wrench = require("wrench"),
    _      = require("underscore");

require("./fs_extension");

// Copies all Resource files and prepares JS files
function prepare(src, dst, callback) {
  var app_name = config.app_name;
  if (src.match("js$")){
    try {
      var src_text = uglify.toString(fs.readFileSync(src).toString(),src);
      if (src.match("_spec.js$")) {
        if (config.specType === "jasmine") {
          src_text =  "var __jasmine = require('/lib/jasmine');var methods = ['spyOn','it','xit','expect','runs','waits','waitsFor','beforeEach','afterEach','describe','xdescribe','jasmine'];methods.forEach(function(method) {this[method] = __jasmine[method];});"
          +src_text;
        } else if (config.specType === "mocha-should") {
          src_text =  "var should = require('/lib/should');\n"
            + "var sinon = require('/lib/sinon');\n"
          +src_text;
        } else if (config.specType === "mocha-chai") {
          src_text =  "var chai = require('/lib/chai'); var expect = chai.expect; var assert = chai.assert;\n"
            + "var sinon = require('/lib/sinon');\n"
          +src_text;
        }
        if (config.isAlloy) {
          src_text =
          "var Alloy = __p.require(\"alloy\"), _ = Alloy._, Backbone = Alloy.Backbone;\n"
          +src_text;
        }
      }
      else if(config.runCoverage && !src.match("spec/")) { //Instrumenting the application code with istanbul for code coverage
		var instrumentedCode = require("./coverage").instrumentCode(src_text, src);
		src_text = instrumentedCode;

		config.instrumentedfiles[src] = dst;// storing all instrumented file
      }

      fs.writeFile(dst,src_text, callback);
    } catch (e) {
      logger.error(e.message + "\nFile   : " + src + "\nLine   : " + e.line + "\nColumn : " + e.col);
      config.isWatching || process.exit(1);
    }
  } else { // Non-JS file - just pump it
    var  is = fs.createReadStream(src);
    var  os = fs.createWriteStream(dst);
    is.on("end", callback).pipe(os);
  }
}

function copyI18n(file, callback) {
  var read = fs.createReadStream(path.join(config.i18n_path,file));
  var write = fs.createWriteStream(path.join(config.tishadow_src, file));
  write.on('close',callback);
  read.pipe(write);
};

function finalise(file_list,callback) {
  // Bundle up to go
  var total = file_list.files.length;
  bundle.pack(file_list.files,function(written) {
    logger.info(total+ " file(s) bundled.");
    fs_map.writeMap();
    fs.touch(config.last_updated_file);
    if (config.isBundle) {
      logger.info("Bundle Ready: " + config.bundle_file);
      if (callback) {
        callback();
      }
    } else {
      api.newBundle(config.isPatch?_.filter(file_list.files, function(f) { return f.match(".js$");}):null );
    }
  });
}

module.exports = function(env, callback) {
  config.buildPaths(env, function() {
    if (env.jshint) {
      logger.info("Running JSHint");
      jshint.checkPath(config.jshint_path);
    }

    logger.info("Beginning Build Process");
    // a js map of hashes must be built whether or not it is an update.
    if (config.isAlloy && !config.skipAlloyCompile) {
      if (config.platform === undefined) {
        logger.error("You need to use the --platform (android|ios) flag or have deployment-targets in tiapp.xml with an alloy project.");
        process.exit();
      }
      async.detectSeries(config.platform, function(platform, callback) {
        logger.info("Compiling Alloy for " + platform);
        var args = ['compile', '-b','-l', 'info', '--platform', platform, '--config', 'sourcemap=false'];
        if (config.alloyCompileFile) {
          args[7] = "sourcemap=false,file="+config.alloyCompileFile;
        }
        var alloy_command;
        if (config.useAppcCLI) {
          alloy_command = spawn("appc", ['alloy'].concat(args), {stdio: "inherit"});
        } else {
          alloy_command = spawn('alloy', args, {stdio: "inherit"});
        }

        alloy_command.on("exit", function(code) {
          if (code !== 0) {
            logger.error("Alloy Compile Error\n");
            callback(true);
          }
          if (fs.existsSync(config.res_alloy_path)) {
            wrench.copyDirSyncRecursive(
              config.res_alloy_path,
              path.join(config.resources_path,(platform === 'ios' ? 'iphone' : platform),'alloy'),
              {preserve:true,preserveFiles:true}
            );
          }
          callback(false);
        });
        alloy_command.on("error", function() {
          logger.error("Alloy Compile Error\n");
          callback(true);
        });
      },function(failed){
        if (failed) return;
        if (fs.existsSync(config.res_alloy_path)) {
          fs.rm_rf(config.res_alloy_path);
        }
        fs.touch(path.join(config.resources_path,'app.js'));
        fs_map.buildMap();
        beginCompile(callback);
      });;
      //Remove non-specific
    } else {
      fs_map.buildMap();
      beginCompile(callback);
    }
  });
};

function beginCompile(callback) {
  var file_list,i18n_list,spec_list,assets_list;
  if( config.isUpdate) {
    var last_stat = fs.statSync(config.last_updated_file);
    file_list = fs_map.mapFiles();
    if (config.isModule)  {
      assets_list = fs.getList(config.assets_path,last_stat.mtime);
    }
    i18n_list = fs.getList(config.i18n_path,last_stat.mtime);
    spec_list = fs.getList(config.spec_path,last_stat.mtime);

    if (file_list.files.length === 0 && (!config.isModule || assets_list.files.length === 0) && i18n_list.files.length === 0 && spec_list.files.length === 0) {
      logger.warn("Nothing to update.");
      return;
    }
  } else {
    if (!fs.existsSync(config.build_path)){
      fs.mkdirSync(config.build_path, 0755);
    }
    //Clean Build Directory
    if (fs.existsSync(config.tishadow_build)) {
      fs.rm_rf(config.tishadow_build);
    }
    // Create the tishadow build paths
    fs.mkdirs([config.tishadow_build, config.tishadow_src, config.tishadow_dist]);
    file_list = fs.getList(config.resources_path);
    if (config.isModule) {
      assets_list = fs.getList(config.assets_path);
    }
    i18n_list = fs.getList(config.i18n_path);
    spec_list = fs.getList(config.spec_path);
  }

  // Build the required directory structure
  fs.mkdirs(file_list.dirs, config.tishadow_src);
  fs.mkdirs(i18n_list.dirs, config.tishadow_src);
  if(spec_list.files.length > 0) {
    if (!fs.existsSync(config.tishadow_spec)) {
      fs.mkdirSync(config.tishadow_spec, 0755);
    }
    fs.mkdirs(spec_list.dirs, config.tishadow_spec);
    spec_list.files = spec_list.files.map(function(file) { return "spec/" + file;});
    spec_list.dirs = ["spec"].concat(spec_list.dirs.map(function(dir) {return "spec/" + dir;}));
  }

  // prepare tasks to process files
  var process_tasks = file_list.files.map(function(file) {
    return _.bind(prepare, null, path.join(config.resources_path,file), path.join(config.tishadow_src,file));
  }).concat(spec_list.files.map(function(file) {
    return _.bind(prepare, null, path.join(config.base,file), path.join(config.tishadow_src,file));
  }));

  // if acting on a native module - see https://github.com/dbankier/TiShadow/commit/bec799b3d03660704ce6ab303f5e28110b86f051
  if (config.isModule && assets_list.files.length > 0) {
    // create paths
  	fs.mkdirs([config.module_name], config.tishadow_src);
  	fs.mkdirs(assets_list.dirs, config.module_path);
    // add files for processing
    process_tasks = process_tasks.concat(assets_list.files.map(function(file) {
      var fileName = file.slice(0,file.lastIndexOf('.'));
      if(fileName == config.module_name){
      	return _.bind(prepare, null, path.join(config.assets_path,file), path.join(config.tishadow_src, file));
      } else {
      	return _.bind(prepare, null, path.join(config.assets_path,file), path.join(config.tishadow_src, config.module_name, file));
      }
    }));
    console.log(process_tasks);
    // modify for bundling
    assets_list.files = assets_list.files.map(function(file) {
      var filePath = config.module_name + "/" + file;
      var fileName = file.slice(0,file.lastIndexOf('.'));
      if(fileName == config.module_name){
      	filePath = file;
      }
      return filePath;
    });
  }

  async.series([
    _.bind(async.eachLimit, null, i18n_list.files, 100, copyI18n), //localisation filed
    _.bind(async.parallelLimit, null, process_tasks, 100), // source, assets, specs
    function() {
      file_list.files = file_list.files.concat(i18n_list.files).concat(spec_list.files);
      if (config.isModule) {
        file_list.files = file_list.files.concat(assets_list.files);
      }
      finalise(file_list,callback);
    }
  ]);
};
<|endoftext|>


<commit_before>var auth = angular.module('beer-tab.auth', []);

auth.controller('AuthCtrl', function ($scope, $rootScope, $window, $location, AuthService, fbAuthService) {

  $scope.loginError = false;
  $scope.loginErrorMessage = '';

  $scope.user = {};
  $scope.logIn = function () {
    console.log("In legacy logIn");
    $window.username = $scope.user.username;
    AuthService.login($scope.user)
      .then(function (token) {
        $window.localStorage.setItem('com.beer-tab', token);
        $location.path('/main');
      })
      .catch(function (error) {
        console.log(error);
        $scope.loginError = true;
        $scope.loginErrorMessage = error.data;
      });
  };

  $scope.signUp = function () {
    AuthService.signup($scope.user)
      .then(function (token) {
        $window.localStorage.setItem('com.beer-tab', token);
        $location.path('/main');
      })
      .catch(function (error) {
        console.error(error);
      });
  };

  $scope.signout = function () {
    AuthService.signout();
  };

  $scope.redirect = function (path) {
    console.log(path);
    $location.path('/' + path);
  };

  //FACEBOOK AUTHENTICATION
  $scope.fbLogIn = function() {
    console.log("in FB login");
    FB.login(function(res){
      console.log(res);
    })
    fbAuthService.checkLoginStatus();
  };

  $scope.fbSignUp = function() {

  };

  $scope.fbLogOut = function(){
    fbAuthService.logout();
  };

})

.directive('checkRequired', function () {
  return {
    require: 'ngModel',
    restrict: 'A',
    link: function (scope, element, attrs, ngModel) {
      ngModel.$validators.checkRequired = function (modelValue, viewValue) {
        var value = modelValue || viewValue;
        var match = scope.$eval(attrs.ngTrueValue) || true;
        return value && match === value;
      };
    }
  };
})
.directive('passwordMatch', [function () {
    return {
        restrict: 'A',
        scope:true,
        require: 'ngModel',
        link: function (scope, elem , attrs,control) {
            var checker = function () {

                //get the value of the first password
                var e1 = scope.$eval(attrs.ngModel);

                //get the value of the other password
                var e2 = scope.$eval(attrs.passwordMatch);
                return e1 == e2;
            };
            scope.$watch(checker, function (n) {

                //set the form control to valid if both
                //passwords are the same, else invalid
                control.$setValidity("unique", n);
            });
        }
    };
}]);
<commit_msg>rebase 06<commit_after>var auth = angular.module('beer-tab.auth', []);

auth.controller('AuthCtrl', function ($scope, $rootScope, $window, $location, AuthService, fbAuthService) {

  $scope.loginError = false;
  $scope.loginErrorMessage = '';

  $scope.user = {};
  $scope.logIn = function () {
    console.log("In legacy logIn");
    $window.username = $scope.user.username;
    AuthService.login($scope.user)
      .then(function (token) {
        $window.localStorage.setItem('com.beer-tab', token);
        $location.path('/main');
      })
      .catch(function (error) {
        console.log(error);
        $scope.loginError = true;
        $scope.loginErrorMessage = error.data;
      });
  };

  $scope.signUp = function () {
    AuthService.signup($scope.user)
      .then(function (token) {
        $window.localStorage.setItem('com.beer-tab', token);
        $location.path('/main');
      })
      .catch(function (error) {
        console.error(error);
      });
  };

  $scope.signout = function () {
    AuthService.signout();
  };

  $scope.redirect = function (path) {
    console.log(path);
    $location.path('/' + path);
  };

  //FACEBOOK AUTHENTICATION
  $scope.fbLogIn = function() {
    console.log("in FB login");
    FB.login(function(res){
      console.log(res);
    })
    fbAuthService.checkLoginStatus();
  };

  $scope.fbSignUp = function() {

  };

  $scope.fbLogOut = function(){
    fbAuthService.logout();
  };

})

.directive('checkRequired', function () {
  return {
    require: 'ngModel',
    restrict: 'A',
    link: function (scope, element, attrs, ngModel) {
      ngModel.$validators.checkRequired = function (modelValue, viewValue) {
        var value = modelValue || viewValue;
        var match = scope.$eval(attrs.ngTrueValue) || true;
        return value && match === value;
      };
    }
  };
})
.directive('passwordMatch', [function () {
    return {
        restrict: 'A',
        scope:true,
        require: 'ngModel',
        link: function (scope, elem , attrs,control) {
            var checker = function () {

                //get the value of the first password
                var e1 = scope.$eval(attrs.ngModel);

                //get the value of the other password
                var e2 = scope.$eval(attrs.passwordMatch);
                return e1 == e2;
            };
            scope.$watch(checker, function (n) {

                //set the form control to valid if both
                //passwords are the same, else invalid
                control.$setValidity("unique", n);
            });
        }
    };
}]);
<|endoftext|>


<commit_before>;(function(context) {

    // Variables
    var AT = {};
    var listeners = {};
    AT.shareToken = null;
    AT.queryParamName = null;

    // Constants
    var scriptId = 'advocate-things-script';
    var storageName = 'advocate-things';
    var points = {
        Sharepoint: {
            name: 'Sharepoint',
            url: 'https://sharepoint-data-collector.herokuapp.com/sharepoint/data'
        },
        Touchpoint: {
            name: 'Touchpoint',
            url: 'https://touchpoint-data-collector.herokuapp.com/touchpoint/data'
        },
        Unknown: {
            name: 'Unknown'
        }
    };

    AT.Events = {
        SharepointSaved: 'SharepointSaved',
        TouchpointSaved: 'TouchpointSaved',
        ReferredPerson: 'ReferredPerson'
    };

    /**
     * Injection of polyfils and third-party libraries
     */

    AT._utils = {};
    (function () {
        /* inject */
        /* endinject */
    }).call(AT._utils);

    /**
     * Internal function definitions
     */

    AT._appendTokenToUrl = function (token, qpName) {
        if (!token || !qpName) {
            return null;
        }

        var url = window.location.href;

        var qpRe = new RegExp('([?&]' + qpName + '=)([^&#]*)', 'g');

        var hash = '';
        var split = '';

        if (url.indexOf('#') !== -1) {
            split = url.split('#');
            hash = split[1];
            url = split[0];
        }

        var params = '';
        if (url.indexOf('?') !== -1) {
            split = url.split('?');
            params = '?' + split[1];
            if (params[params.length - 1] === '/') {
                params = params.slice(0, -1);
            }
        }

        if (params.match(qpRe)) {
            // Replace
            params = params.replace(qpRe, '$1' + token);
        } else {
            // Append
            var separator = '?';
            if (params) {
                separator = '&';
            }
            params += separator + qpName + '=' + token;
        }

        // We can rebuild it, we have the technology
        var newParams = (hash)
            ? params + '#' + hash
            : params;

        // Rewrite the URL
        History.replaceState(null, null, newParams);
    };

    AT._getApiKey = function () {
        var elScript = document.getElementById(scriptId);

        if (!elScript) {
            return null;
        }

        var scriptUrl = elScript.src;
        if (scriptUrl.indexOf('?key') !== -1) {
            return scriptUrl.split('?').pop().split('=').pop();
        }

        return null;
    };

    AT._getSharepointTokens = function () {
        var tokens = [];

        if (!store.hasItem(storageName)) {
            return tokens;
        }

        var storeData = JSON.parse(store.getItem(storageName));
        var apiKey = AT._getApiKey();
        if (!storeData[apiKey]) {
            return tokens;
        }

        for (entry in storeData[apiKey]) {
            tokens.push(entry.token);
        }

        return tokens;
    };

    AT._getTokenOrAlias = function (sharepointData) {
        if (!sharepointData) {
            return null;
        }

        return sharepointData.alias || sharepointData.token || null;
    };

    AT._initEventListeners = function () {
        var listeners = {};

        for (evt in AT.Events) {
            listeners[AT.Events[evt]] = [];
        }

        return listeners;
    };

    AT._initStorage = function () {
        var store = null;

        store = AT._utils.cookieStorage; // by default

        if (typeof window.localStorage === 'object') {
            // Test localStorage to see if we can use it
            var test = 'test';
            try {
                AT._utils.lclStorage.setItem(test, test);
                AT._utils.lclStorage.removeItem(test);
                store = AT._utils.lclStorage;
            } catch (e) {
                AT._log('warn', 'Failed to initialise localStorage, falling back to cookies');
            }
        }

        return store;
    };

    AT._log = function (type, msg) {
        console[type](msg);
    }

    AT._prepareData = function (data) {
        var requiredProps = [ '_at', '_client' ];
        var tidy; // Will contain tidied data.

        // Ensure data is a real object. Initialise if not.
        if (!data || Object.prototype.toString.call(data) !== '[object Object]') {
            tidy = {};
        } else {
            tidy = JSON.parse(JSON.stringify(data || {})); // clone data
        }

        for (propId in requiredProps) {
            if (!tidy[requiredProps[propId]] || Object.prototype.toString.call(tidy[requiredProps[propId]]) !== '[object Object]') {
                tidy[requiredProps[propId]] = {};
            }
        }

        tidy._at.apiKey = AT._getApiKey();
        tidy._at.fingerprint = 'foo';
        tidy._at.url = window.location.href;

        for (key in tidy) {
            if (!(key === '_at' || key === '_client')) { // TODO: change to use requiredProps?
                tidy._client[key] = tidy[key];
                delete tidy[key];
            }
        }

        return tidy;
    };

    AT._storeTouchpointData = function (data) {
        // Structure:
        // storage
        //   -> advocate-things {}
        //      -> apiKey []
        //         -> data {}
        if (!data || Object.prototype.toString.call(data) !== '[object Object]' || !data.token) {
            return null;
        }

        if (!store.hasItem(storageName)) {
            store.setItem(storageName, JSON.stringify({}), Infinity);
        }

        var currentlyStoredData = JSON.parse(store.getItem(storageName)); // TODO: try/catch
        var apiKey = AT._getApiKey();

        if (!currentlyStoredData[apiKey]) {
            currentlyStoredData[apiKey] = [];
        }

        var duplicateData = false;

        for (var i=0,len=currentlyStoredData[apiKey].length; i<len; i++) {
            if (currentlyStoredData[apiKey][i].token === data.token) {
                duplcateData = true;
                break;
            }
        }

        if (!duplicateData) {
            currentlyStoredData[apiKey].push(data);
            store.setItem(storageName, JSON.stringify(currentlyStoredData), Infinity);
        }
    };

    AT._triggerEvent = function (eventType, data) {
        for (var l=0; l<listeners[eventType].length; l++) {
            listeners[eventType][l].call(data, data);
        }
    };

    /**
     * Public function definitions
     */

    AT.addEventListener = function (type, listener) {
        if (!AT._getApiKey()) {
            return null;
        }

        if (!listeners[type]) {
            return null;
        }

        listeners[type].push(listener);
    };

            AT.send = function (data, cb, isInit) {
        if (!AT._getApiKey()) {
            return null;
        }

        if (data && data._at) {
            if (data._at.sharepointName) {
                return sendSharepoint(null, data, cb, isInit);
            }
            if (data._at.touchpointName) {
                return sendTouchpoint(null, data, cb);
            }
        }

        return AT._log('warn', 'Neither sharepointName or touchpointName are specified');
    };

    AT.sendSharepoint = function (name, data, cb, isInit) {
        if (!AT._getApiKey()) {
            return null;
        }

        var dataPrep = AT._prepareData(data);

        if (name) {
            dataPrep._at.sharepointName = name;
        }

        var dataString = JSON.stringify(dataPrep);

        var xhr = new XMLHttpRequest();
        var isAsync = true;

        xhr.onload = function () {
            // Handle error responses.
            if (!/^20[0-9]{1}/.test(xhr.status)) {
                if (cb) {
                    return cb(new Error(xhr.statusText));
                }
            }

            // Handle good responses.
            var res = JSON.parse(xhr.responseText); // TODO: try/catch here

            // Make details available in AT
            var oldShareToken = AT.shareToken;
            AT.shareToken = AT._getTokenOrAlias(res[0]);
            AT.queryParamName = res[0].queryParamName;

            // Trigger saved event
            AT._triggerEvent(AT.Events.SharepointSaved, res);

            if ((oldShareToken !== AT.shareToken) || isInit) {
                AT._appendTokenToUrl(AT.shareToken, AT.queryParamName);
            } else {
                sendSharepoint(name, data, cb, true);
            }

            if (cb) {
                return cb(null, res);
            }
        };

        xhr.open('POST', points.Sharepoint.url, isAsync);
        xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
        xhr.send(dataString);
    };

    AT.sendTouchpoint = function (name, data, cb, isInit) {
        if (!AT._getApiKey()) {
            return null;
        }

        var dataPrep = AT._prepareData(data);

        if (name) {
            dataPrep._at.touchpointName = name;
        }

        dataPrep._at.shareTokens = AT._getSharepointTokens();

        var dataString = JSON.stringify(dataPrep);

        var xhr = new XMLHttpRequest();
        var isAsync = true;

        xhr.onload = function () {
            // Handle error responses.
            if (!/^20[0-9]{1}/.test(xhr.status)) {
                if (cb) {
                    return cb(new Error(xhr.statusText));
                }
            }
            // Handle good responses.
            var res = JSON.parse(xhr.responseText); // TODO: try/catch here

            AT._storeTouchpointData(res);

            var meta = res.meta;

            // Trigger saved event
            AT._triggerEvent(AT.Events.TouchpointSaved, meta);

            if (res.token && res.token !== '') {
                // TODO: consider triggering this event downstream as well
                triggerEvent(AT.Events.ReferredPerson, meta);
            }

            if (cb) {
                return cb(null, res);
            }
        };

        xhr.open('POST', points.Touchpoint.url, isAsync);
        xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
        xhr.send(dataString);
    };

    /**
     * Initialisation
     */
    AT._autoSend = function (cb) {
        var data = window.advocate_things_data;

        AT.send(data, cb, true);
    };

    AT._init = function (cb) {
        listeners = AT._initEventListeners();
        store = AT._initStorage();

        AT._autoSend(cb);

        if (cb) {
            cb(null);
        }
    };
    AT._init(); // Run immediately

    context.AT = AT;

})(this);
<commit_msg>refer to AT.sen...<commit_after>;(function(context) {
    console.log('sdk loading');

    // Variables
    var AT = {};
    var listeners = {};
    AT.shareToken = null;
    AT.queryParamName = null;

    // Constants
    var scriptId = 'advocate-things-script';
    var storageName = 'advocate-things';
    var points = {
        Sharepoint: {
            name: 'Sharepoint',
            url: 'https://sharepoint-data-collector.herokuapp.com/sharepoint/data'
        },
        Touchpoint: {
            name: 'Touchpoint',
            url: 'https://touchpoint-data-collector.herokuapp.com/touchpoint/data'
        },
        Unknown: {
            name: 'Unknown'
        }
    };

    AT.Events = {
        SharepointSaved: 'SharepointSaved',
        TouchpointSaved: 'TouchpointSaved',
        ReferredPerson: 'ReferredPerson'
    };

    /**
     * Injection of polyfils and third-party libraries
     */

    AT._utils = {};
    (function () {
        /* inject */
        /* endinject */
    }).call(AT._utils);

    /**
     * Internal function definitions
     */

    AT._appendTokenToUrl = function (token, qpName) {
        if (!token || !qpName) {
            return null;
        }

        var url = window.location.href;

        var qpRe = new RegExp('([?&]' + qpName + '=)([^&#]*)', 'g');

        var hash = '';
        var split = '';

        if (url.indexOf('#') !== -1) {
            split = url.split('#');
            hash = split[1];
            url = split[0];
        }

        var params = '';
        if (url.indexOf('?') !== -1) {
            split = url.split('?');
            params = '?' + split[1];
            if (params[params.length - 1] === '/') {
                params = params.slice(0, -1);
            }
        }

        if (params.match(qpRe)) {
            // Replace
            params = params.replace(qpRe, '$1' + token);
        } else {
            // Append
            var separator = '?';
            if (params) {
                separator = '&';
            }
            params += separator + qpName + '=' + token;
        }

        // We can rebuild it, we have the technology
        var newParams = (hash)
            ? params + '#' + hash
            : params;

        // Rewrite the URL
        History.replaceState(null, null, newParams);
    };

    AT._getApiKey = function () {
        var elScript = document.getElementById(scriptId);

        if (!elScript) {
            return null;
        }

        var scriptUrl = elScript.src;
        if (scriptUrl.indexOf('?key') !== -1) {
            return scriptUrl.split('?').pop().split('=').pop();
        }

        return null;
    };

    AT._getSharepointTokens = function () {
        var tokens = [];

        if (!store.hasItem(storageName)) {
            return tokens;
        }

        var storeData = JSON.parse(store.getItem(storageName));
        var apiKey = AT._getApiKey();
        if (!storeData[apiKey]) {
            return tokens;
        }

        for (entry in storeData[apiKey]) {
            tokens.push(entry.token);
        }

        return tokens;
    };

    AT._getTokenOrAlias = function (sharepointData) {
        if (!sharepointData) {
            return null;
        }

        return sharepointData.alias || sharepointData.token || null;
    };

    AT._initEventListeners = function () {
        var listeners = {};

        for (evt in AT.Events) {
            listeners[AT.Events[evt]] = [];
        }

        return listeners;
    };

    AT._initStorage = function () {
        var store = null;

        store = AT._utils.cookieStorage; // by default

        if (typeof window.localStorage === 'object') {
            // Test localStorage to see if we can use it
            var test = 'test';
            try {
                AT._utils.lclStorage.setItem(test, test);
                AT._utils.lclStorage.removeItem(test);
                store = AT._utils.lclStorage;
            } catch (e) {
                AT._log('warn', 'Failed to initialise localStorage, falling back to cookies');
            }
        }

        return store;
    };

    AT._log = function (type, msg) {
        console[type](msg);
    }

    AT._prepareData = function (data) {
        var requiredProps = [ '_at', '_client' ];
        var tidy; // Will contain tidied data.

        // Ensure data is a real object. Initialise if not.
        if (!data || Object.prototype.toString.call(data) !== '[object Object]') {
            tidy = {};
        } else {
            tidy = JSON.parse(JSON.stringify(data || {})); // clone data
        }

        for (propId in requiredProps) {
            if (!tidy[requiredProps[propId]] || Object.prototype.toString.call(tidy[requiredProps[propId]]) !== '[object Object]') {
                tidy[requiredProps[propId]] = {};
            }
        }

        tidy._at.apiKey = AT._getApiKey();
        tidy._at.fingerprint = 'foo';
        tidy._at.url = window.location.href;

        for (key in tidy) {
            if (!(key === '_at' || key === '_client')) { // TODO: change to use requiredProps?
                tidy._client[key] = tidy[key];
                delete tidy[key];
            }
        }

        return tidy;
    };

    AT._storeTouchpointData = function (data) {
        // Structure:
        // storage
        //   -> advocate-things {}
        //      -> apiKey []
        //         -> data {}
        if (!data || Object.prototype.toString.call(data) !== '[object Object]' || !data.token) {
            return null;
        }

        if (!store.hasItem(storageName)) {
            store.setItem(storageName, JSON.stringify({}), Infinity);
        }

        var currentlyStoredData = JSON.parse(store.getItem(storageName)); // TODO: try/catch
        var apiKey = AT._getApiKey();

        if (!currentlyStoredData[apiKey]) {
            currentlyStoredData[apiKey] = [];
        }

        var duplicateData = false;

        for (var i=0,len=currentlyStoredData[apiKey].length; i<len; i++) {
            if (currentlyStoredData[apiKey][i].token === data.token) {
                duplcateData = true;
                break;
            }
        }

        if (!duplicateData) {
            currentlyStoredData[apiKey].push(data);
            store.setItem(storageName, JSON.stringify(currentlyStoredData), Infinity);
        }
    };

    AT._triggerEvent = function (eventType, data) {
        for (var l=0; l<listeners[eventType].length; l++) {
            listeners[eventType][l].call(data, data);
        }
    };

    /**
     * Public function definitions
     */

    AT.addEventListener = function (type, listener) {
        if (!AT._getApiKey()) {
            return null;
        }

        if (!listeners[type]) {
            return null;
        }

        listeners[type].push(listener);
    };

    AT.send = function (data, cb, isInit) {
        if (!AT._getApiKey()) {
            return null;
        }

        if (data && data._at) {
            if (data._at.sharepointName) {
                return AT.sendSharepoint(null, data, cb, isInit);
            }
            if (data._at.touchpointName) {
                return AT.sendTouchpoint(null, data, cb);
            }
        }

        return AT._log('warn', 'Neither sharepointName or touchpointName are specified');
    };

    AT.sendSharepoint = function (name, data, cb, isInit) {
        if (!AT._getApiKey()) {
            return null;
        }

        var dataPrep = AT._prepareData(data);

        if (name) {
            dataPrep._at.sharepointName = name;
        }

        var dataString = JSON.stringify(dataPrep);

        var xhr = new XMLHttpRequest();
        var isAsync = true;

        xhr.onload = function () {
            // Handle error responses.
            if (!/^20[0-9]{1}/.test(xhr.status)) {
                if (cb) {
                    return cb(new Error(xhr.statusText));
                }
            }

            // Handle good responses.
            var res = JSON.parse(xhr.responseText); // TODO: try/catch here

            // Make details available in AT
            var oldShareToken = AT.shareToken;
            AT.shareToken = AT._getTokenOrAlias(res[0]);
            AT.queryParamName = res[0].queryParamName;

            // Trigger saved event
            AT._triggerEvent(AT.Events.SharepointSaved, res);

            if ((oldShareToken !== AT.shareToken) || isInit) {
                AT._appendTokenToUrl(AT.shareToken, AT.queryParamName);
            } else {
                sendSharepoint(name, data, cb, true);
            }

            if (cb) {
                return cb(null, res);
            }
        };

        xhr.open('POST', points.Sharepoint.url, isAsync);
        xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
        xhr.send(dataString);
    };

    AT.sendTouchpoint = function (name, data, cb, isInit) {
        if (!AT._getApiKey()) {
            return null;
        }

        var dataPrep = AT._prepareData(data);

        if (name) {
            dataPrep._at.touchpointName = name;
        }

        dataPrep._at.shareTokens = AT._getSharepointTokens();

        var dataString = JSON.stringify(dataPrep);

        var xhr = new XMLHttpRequest();
        var isAsync = true;

        xhr.onload = function () {
            // Handle error responses.
            if (!/^20[0-9]{1}/.test(xhr.status)) {
                if (cb) {
                    return cb(new Error(xhr.statusText));
                }
            }
            // Handle good responses.
            var res = JSON.parse(xhr.responseText); // TODO: try/catch here

            AT._storeTouchpointData(res);

            var meta = res.meta;

            // Trigger saved event
            AT._triggerEvent(AT.Events.TouchpointSaved, meta);

            if (res.token && res.token !== '') {
                // TODO: consider triggering this event downstream as well
                triggerEvent(AT.Events.ReferredPerson, meta);
            }

            if (cb) {
                return cb(null, res);
            }
        };

        xhr.open('POST', points.Touchpoint.url, isAsync);
        xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
        xhr.send(dataString);
    };

    /**
     * Initialisation
     */
    AT._autoSend = function (cb) {
        var data = window.advocate_things_data;

        AT.send(data, cb, true);
    };

    AT._init = function (cb) {
        listeners = AT._initEventListeners();
        store = AT._initStorage();

        AT._autoSend(cb);

        if (cb) {
            cb(null);
        }
    };
    AT._init(); // Run immediately

    context.AT = AT;

})(this);
<|endoftext|>