<commit_before>var canvas; //Will be linked to the canvas in our index.html page
var stage; //Is the equivalent of stage in AS3; we'll add "children" to it

// Graphics
//[Background]

var bg; //The background graphic

//[Title View]

var main; //The Main Background
var startB; //The Start button in the main menu
var creditsB; //The credits button in the main menu

//[Credits]

var credits; //The Credits screen

//[Game View]

var player; //The player paddle graphic
var ball; //The ball graphic
var cpu; //The CPU paddle
var win; //The winning popup
var lose; //The losing popup

//[Score]

var playerScore; //The main player score
var cpuScore; //The CPU score
var cpuSpeed=6; //The speed of the CPU paddle; the faster it is the harder the game is

// Variables

var xSpeed = 5;
var ySpeed = 5;

var tkr = new Object;

//preloader
var preloader;
var manifest;
var totalLoaded = 0;

var TitleView = new Container();

function Main()
{
    /* Link Canvas */

    canvas = document.getElementById('PongStage');
    stage = new Stage(canvas);

    stage.mouseEventsEnabled = true;

    /* Set The Flash Plugin for browsers that don't support SoundJS */
    SoundJS.FlashPlugin.BASE_PATH = "assets/";
    if (!SoundJS.checkPlugin(true)) {
      alert("Error!");
      return;
    }

    manifest = [
                {src:"bg.png", id:"bg"},
                {src:"main.png", id:"main"},
                {src:"startB.png", id:"startB"},
                {src:"creditsB.png", id:"creditsB"},
                {src:"credits.png", id:"credits"},
                {src:"paddle.png", id:"cpu"},
                {src:"paddle.png", id:"player"},
                {src:"ball.png", id:"ball"},
                {src:"win.png", id:"win"},
                {src:"lose.png", id:"lose"},
                {src:"playerScore.mp3|playerScore.ogg", id:"playerScore"},
                {src:"enemyScore.mp3|enemyScore.ogg", id:"enemyScore"},
                {src:"hit.mp3|hit.ogg", id:"hit"},
                {src:"wall.mp3|wall.ogg", id:"wall"}
            ];

    preloader = new PreloadJS();
    preloader.installPlugin(SoundJS);
    preloader.onProgress = handleProgress;
    preloader.onComplete = handleComplete;
    preloader.onFileLoad = handleFileLoad;
    preloader.loadManifest(manifest);

    /* Ticker */

    Ticker.setFPS(30);
    Ticker.addListener(stage);
}

function handleProgress(event)
{
    //use event.loaded to get the percentage of the loading
}

function handleComplete(event) {
         //triggered when all loading is complete
}

function handleFileLoad(event) {
         //triggered when an individual file completes loading

         switch(event.type)
         {
            case PreloadJS.IMAGE:
            //image loaded
             var img = new Image();
              img.src = event.src;
              img.onload = handleLoadComplete;
              window[event.id] = new Bitmap(img);
            break;

            case PreloadJS.SOUND:
            //sound loaded
            handleLoadComplete();
            break;
         }
}
<commit_msg>anudder funkton<commit_after>var canvas; //Will be linked to the canvas in our index.html page
var stage; //Is the equivalent of stage in AS3; we'll add "children" to it

// Graphics
//[Background]

var bg; //The background graphic

//[Title View]

var main; //The Main Background
var startB; //The Start button in the main menu
var creditsB; //The credits button in the main menu

//[Credits]

var credits; //The Credits screen

//[Game View]

var player; //The player paddle graphic
var ball; //The ball graphic
var cpu; //The CPU paddle
var win; //The winning popup
var lose; //The losing popup

//[Score]

var playerScore; //The main player score
var cpuScore; //The CPU score
var cpuSpeed=6; //The speed of the CPU paddle; the faster it is the harder the game is

// Variables

var xSpeed = 5;
var ySpeed = 5;

var tkr = new Object;

//preloader
var preloader;
var manifest;
var totalLoaded = 0;

var TitleView = new Container();

function Main()
{
    /* Link Canvas */

    canvas = document.getElementById('PongStage');
    stage = new Stage(canvas);

    stage.mouseEventsEnabled = true;

    /* Set The Flash Plugin for browsers that don't support SoundJS */
    SoundJS.FlashPlugin.BASE_PATH = "assets/";
    if (!SoundJS.checkPlugin(true)) {
      alert("Error!");
      return;
    }

    manifest = [
                {src:"bg.png", id:"bg"},
                {src:"main.png", id:"main"},
                {src:"startB.png", id:"startB"},
                {src:"creditsB.png", id:"creditsB"},
                {src:"credits.png", id:"credits"},
                {src:"paddle.png", id:"cpu"},
                {src:"paddle.png", id:"player"},
                {src:"ball.png", id:"ball"},
                {src:"win.png", id:"win"},
                {src:"lose.png", id:"lose"},
                {src:"playerScore.mp3|playerScore.ogg", id:"playerScore"},
                {src:"enemyScore.mp3|enemyScore.ogg", id:"enemyScore"},
                {src:"hit.mp3|hit.ogg", id:"hit"},
                {src:"wall.mp3|wall.ogg", id:"wall"}
            ];

    preloader = new PreloadJS();
    preloader.installPlugin(SoundJS);
    preloader.onProgress = handleProgress;
    preloader.onComplete = handleComplete;
    preloader.onFileLoad = handleFileLoad;
    preloader.loadManifest(manifest);

    /* Ticker */

    Ticker.setFPS(30);
    Ticker.addListener(stage);
}

function handleProgress(event)
{
    //use event.loaded to get the percentage of the loading
}

function handleComplete(event) {
         //triggered when all loading is complete
}

function handleFileLoad(event) {
         //triggered when an individual file completes loading

         switch(event.type)
         {
            case PreloadJS.IMAGE:
            //image loaded
             var img = new Image();
              img.src = event.src;
              img.onload = handleLoadComplete;
              window[event.id] = new Bitmap(img);
            break;

            case PreloadJS.SOUND:
            //sound loaded
            handleLoadComplete();
            break;
         }
}

function handleLoadComplete(event)
{

   totalLoaded++;

   if(manifest.length==totalLoaded)
   {
       addTitleView();
   }
}
<|endoftext|>


<commit_before>
/*
The MIT License (MIT)

Copyright (c) 2014 Rob Christian

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

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

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

/*

Semi-colons are just FUD. If your minifier can't handle this code, switch to one that is JS-compliant.

*/

;(function(){

  /*  Private Class Data  */

  var DEFINE = Object.defineProperty
  var OVERRIDE = function(object, method_name, method){
    DEFINE(object, method_name, { enumerable:false, configurable:false, value:method })
  }
  var _property_modifier_ = null
  var PROPERTY_MODIFIER = function(obj){
    if (! obj) return _property_modifier_
    else _property_modifier_ = obj
    return PROPERTY_MODIFIER
  }

  var _bindables = []
  var _events = new MicroEvent()
  function _setter_cb(id,val){ _events.trigger(id,val) }

  /*  Bindable Classes  */

  function Bindable(data){
    if (typeOf(data) === 'Array')
      return new BindableArray(data)
    else if (familyOf(data) === 'complex')
      return new BindableObject(data)
  }
  function bind(parent, property, setter_cb){
    parent[property] = PROPERTY_MODIFIER({
      send:function(id){ _events.bind(id,setter_cb) }
    })
    // parent[property] = PROPERTY_MODIFIER
  }
  function unbind(property, setter_cb){
    _events.unbind(setter_cb)
  }
  function recompute(data){
    if (familyOf(data) === 'complex')
      this.constructor(data)
    return this
  }

  function BindableObject(data){
    Object.keys(data).map(function(prop){
      this._new_property_ = [prop, data[prop]]
    }.bind(this))
  }
  DEFINE(BindableObject.prototype, 'bind', { enumerable:false, configurable:false, value:bind })
  DEFINE(BindableObject.prototype, 'unbind', { enumerable:false, configurable:false, value:unbind })
  DEFINE(BindableObject.prototype, 'recompute', { enumerable:false, configurable:false, value:recompute })
  DEFINE(BindableObject.prototype, '_new_property_', { enumerable:false, configurable:false,
    set:function(keyval){ addProperty.apply(this, keyval) }
  })

  function BindableArray(array){
    var self = []

    DEFINE(self, 'bind', { enumerable:false, configurable:false, value:bind })
    DEFINE(self, 'unbind', { enumerable:false, configurable:false, value:unbind })
    DEFINE(self, 'recompute', { enumerable:false, configurable:false, value:recompute })
    DEFINE(self, '_new_property_', { enumerable:false, configurable:false,
      set:function(keyval){ addProperty.apply(self, keyval) }
    })
    OVERRIDE(self, 'push', function(v){ self._new_property_ = [self.length, v] })
    OVERRIDE(self, 'pop', function(){ var r = self[self.length-1]; self.length = self.length-1; return r })
    OVERRIDE(self, 'shift', function(){
      var r = self[0]
      Object.keys(self).map(function(idx){
        self[+idx-1] = self[+idx]
      })
      self.length = self.length-1
      return r
    })
    OVERRIDE(self, 'unshift', function(obj){

      Object.keys(self).map(function(idx){
        console.log(+idx+1, +idx)
        self._new_property_ = [+idx+1, self[+idx]]
        self[+idx] = PROPERTY_MODIFIER({
          send:function(id){ self[+idx+1] = PROPERTY_MODIFIER({id:id}) }
        })
      })

      self._new_property_ = [0, obj]
    })
    OVERRIDE(self, 'concat', function(arr){
      if (arr && arr.length) {
        Object.keys(arr).map(function(key){
          self._new_property_ = [self.length, arr[key]]
        })
      }
    })
    Object.keys(array).map(function(key){
      self._new_property_ = [key, array[key]]
    })

    return self
  }

  function addProperty(key, val){
    var _val = undefined
    var _id = Math.random().toString().split('.')[1]
    console.log('addProperty', key, val)

    DEFINE(this, key, {
      enumerable: true
    , configurable: true
    , get: function(){ return _val }
    , set: function(value){
        if (value === PROPERTY_MODIFIER && PROPERTY_MODIFIER().send) {
          PROPERTY_MODIFIER().send(_id)
        }
        else if (value === PROPERTY_MODIFIER && PROPERTY_MODIFIER().id) {
          _id = PROPERTY_MODIFIER().id
        }
        else if (familyOf(value) === 'complex') {
          _val = new Bindable(value)
          _setter_cb(_id, _val)
        }
        else {
          _val = value
          _setter_cb(_id, _val)
        }
      }
    })
    this[key] = val
  }

  /* Takes a form DOM object and a Binding object, and does the rest for you. */

  function bindForm(form, container){
    var bindable = container.bindable

    ;[].forEach.call(form.querySelectorAll('input'), function(field){

      if (field.name in bindable) {
        CrossTalk.fieldManager(function(input_handler, output_handler){

          field.addEventListener('input', function(ev){
            var do_it = function(){ bindable[field.name] = ev.target.value }
            input_handler( do_it )
          })

          container.bind(bindable, field.name, function(val){
            var do_it = function(){ field.value = val }
            output_handler( do_it )
          })

        })

        field.value = bindable[field.name]
      }

    })
  }

  /* Inverts control: Prevents inputs from receiving updates while they are the sender. */

  function fieldManager(receive_handlers){
    var _sent_by_me = false

    function input_handler(do_it){
      _sent_by_me = true
      do_it()
    }
    function output_handler(do_it){
      _sent_by_me ? _sent_by_me = false : do_it()
    }
    receive_handlers( input_handler, output_handler )
  }

  /* Our entry point for creating bindable objects, keeps a reference to the object created. */

  function NewBindable(data){
    var bindable = new Bindable(data)
    _bindables.push(bindable)
    return bindable
  }

  /*  HELPERS  */

  function familyOf(thing){
    if (typeOf(thing)) {
      return {
        Date: 'simple'
      , String: 'simple'
      , Number: 'simple'
      , Boolean: 'simple'
      , Function: 'simple'
      , Array: 'complex'
      , Object: 'complex'
      }[typeOf(thing)] || 'complex'
    } else {
      return false
    }
  }

  function typeOf(thing){
    return (thing != null && !Number.isNaN(thing) && thing.constructor) ? thing.constructor.name : '' + thing
  }

  function each(obj, cb){
    // if (typeOf(obj) === 'BindableObject' || typeOf(obj) === 'BindableArray')
    //   obj = obj

    for (var prop in obj)
      cb(prop, obj[prop])
  }

  var CrossTalk = {
    Binding: NewBindable
  , fieldManager: fieldManager
  , bindForm: bindForm
  }
  DEFINE(CrossTalk, 'bindables', {get:function(){return _bindables}, enumerable: true})
  DEFINE(CrossTalk, 'PROPERTY_MODIFIER', {value:PROPERTY_MODIFIER, writeable:false})

  if (typeof module !== 'undefined' && module.hasOwnProperty('exports')) {
    module.exports = CrossTalk
  } else {
    window.CrossTalk = CrossTalk
    window.familyOf = familyOf
    window.typeOf = typeOf
    window.Bindable = Bindable
  }

})()
<commit_msg>Fix typeOf for falsey objects. Add support for binding using _new_property_. Reorganize.<commit_after>
/*
The MIT License (MIT)

Copyright (c) 2014 Rob Christian

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

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

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

/*

Semi-colons are just FUD. If your minifier can't handle this code, switch to one that is JS-compliant.

*/

;(function(){

  /*  Private Class Data  */

  var DEFINE = Object.defineProperty
  var OVERRIDE = function(object, method_name, method){
    DEFINE(object, method_name, { enumerable:false, configurable:false, value:method })
  }
  var _property_manipulator_ = null
  var PROPERTY_MANIPULATOR = function(obj){
    if (! obj) return _property_manipulator_
    else _property_manipulator_ = obj
    return PROPERTY_MANIPULATOR
  }

  var _bindables = []
  var _events = new MicroEvent()

  /*  Bindable Classes  */

  function Bindable(data){
    if (typeOf(data) === 'Array')
      return new BindableArray(data)
    else if (familyOf(data) === 'complex')
      return new BindableObject(data)
  }
  function bind(opts, setter_cb){ console.log('BIND', opts)
    if (opts.length && opts.length === 2) {
      var parent = opts[0]
      var property = opts[1]
      parent[property] = PROPERTY_MANIPULATOR({
        send:function(id){ _events.bind(id,setter_cb) }
      })
    }
    else {
      opts._new_property_ = PROPERTY_MANIPULATOR({
        send:function(id){ _events.bind(id,setter_cb) }
      })
    }
  }
  function unbind(setter_cb){
    _events.unbind(setter_cb)
  }
  function recompute(data){
    if (familyOf(data) === 'complex')
      this.constructor(data)
    return this
  }

  function BindableObject(data){
    Object.keys(data).map(function(prop){
      this._new_property_ = [prop, data[prop]]
    }.bind(this))
  }
  DEFINE(BindableObject.prototype, 'bind', { enumerable:false, configurable:false, value:bind })
  DEFINE(BindableObject.prototype, 'unbind', { enumerable:false, configurable:false, value:unbind })
  DEFINE(BindableObject.prototype, 'recompute', { enumerable:false, configurable:false, value:recompute })
  DEFINE(BindableObject.prototype, '_new_property_', { enumerable:false, configurable:false,
    set:function(){ addProperty.apply(this, arguments) }
  })

  function BindableArray(array){
    var self = []

    DEFINE(self, '_id', { enumerable:false, configurable:false, value:Math.random().toString().split('.')[1] })
    DEFINE(self, 'bind', { enumerable:false, configurable:false, value:bind })
    DEFINE(self, 'unbind', { enumerable:false, configurable:false, value:unbind })
    DEFINE(self, 'recompute', { enumerable:false, configurable:false, value:recompute })
    DEFINE(self, '_new_property_', { enumerable:false, configurable:false,
      set:function(){ addProperty.apply(self, arguments) }
    })
    OVERRIDE(self, 'push', function(v){
      self._new_property_ = [self.length, v]
      _events.trigger(this._id, ['push', self.length-1, self[self.length-1]])
    })
    OVERRIDE(self, 'pop', function(){ var r = self[self.length-1]; self.length = self.length-1; return r })
    OVERRIDE(self, 'shift', function(){
      var r = self[0]
      Object.keys(self).map(function(idx){
        self[+idx-1] = self[+idx]
      })
      self.length = self.length-1
      return r
    })
    OVERRIDE(self, 'unshift', function(obj){

      Object.keys(self).map(function(idx){
        console.log(+idx+1, +idx)
        self._new_property_ = [+idx+1, self[+idx]]
        self[+idx] = PROPERTY_MANIPULATOR({
          send:function(id){ self[+idx+1] = PROPERTY_MANIPULATOR({id:id}) }
        })
      })

      self._new_property_ = [0, obj]
    })
    OVERRIDE(self, 'concat', function(arr){
      if (arr && arr.length) {
        Object.keys(arr).map(function(key){
          self._new_property_ = [self.length, arr[key]]
        })
      }
    })
    Object.keys(array).map(function(key){
      self._new_property_ = [key, array[key]]
    })

    return self
  }

  function addProperty(args){
    var _val = undefined
    var _id = Math.random().toString().split('.')[1]

    if (typeOf(args) === 'Array') {
      var key = args[0]
      var val = args[1]
    }
    else if (args === PROPERTY_MANIPULATOR && PROPERTY_MANIPULATOR().send) {
      PROPERTY_MANIPULATOR().send(this._id)
      return
    }
    else {
      console.log('Abort! Bad property assignment:',args)
      return
    }
    // console.log('addProperty', key, val)

    DEFINE(this, key, {
      enumerable: true
    , configurable: true
    , get: function(){ return _val }
    , set: function(value){
        if (value === PROPERTY_MANIPULATOR && PROPERTY_MANIPULATOR().send) {
          PROPERTY_MANIPULATOR().send(_id)
        }
        else if (value === PROPERTY_MANIPULATOR && PROPERTY_MANIPULATOR().id) {
          _id = PROPERTY_MANIPULATOR().id
        }
        else if (familyOf(value) === 'complex') {
          _val = new Bindable(value)
          _events.trigger(_id, _val)
        }
        else {
          _val = value
          _events.trigger(_id, _val)
        }
      }
    })
    this[key] = val
  }

  /* Takes a form DOM object and a Binding object, and does the rest for you. */

  function bindForm(form, container){
    var bindable = container.bindable

    ;[].forEach.call(form.querySelectorAll('input'), function(field){

      if (field.name in bindable) {
        CrossTalk.fieldManager(function(input_handler, output_handler){

          field.addEventListener('input', function(ev){
            var do_it = function(){ bindable[field.name] = ev.target.value }
            input_handler( do_it )
          })

          container.bind([bindable, field.name], function(val){
            var do_it = function(){ field.value = val }
            output_handler( do_it )
          })

        })

        field.value = bindable[field.name]
      }

    })
  }

  /* Inverts control: Prevents inputs from receiving updates while they are the sender. */

  function fieldManager(receive_handlers){
    var _sent_by_me = false

    function input_handler(do_it){
      _sent_by_me = true
      do_it()
    }
    function output_handler(do_it){
      _sent_by_me ? _sent_by_me = false : do_it()
    }
    receive_handlers( input_handler, output_handler )
  }

  /* Our entry point for creating bindable objects, keeps a reference to the object created. */

  function NewBindable(data){
    var bindable = new Bindable(data)
    _bindables.push(bindable)
    return bindable
  }

  /*  HELPERS  */

  function familyOf(thing){
    if (typeOf(thing)) {
      return {
        Date: 'simple'
      , String: 'simple'
      , Number: 'simple'
      , Boolean: 'simple'
      , Function: 'simple'
      , Array: 'complex'
      , Object: 'complex'
      , 'undefined': 'falsey'
      , 'null': 'falsey'
      }[typeOf(thing)] || 'complex'
    } else {
      return false
    }
  }

  function typeOf(thing){
    return (thing != null && !Number.isNaN(thing) && thing.constructor) ? thing.constructor.name : '' + thing
  }

  function each(obj, cb){
    // if (typeOf(obj) === 'BindableObject' || typeOf(obj) === 'BindableArray')
    //   obj = obj

    for (var prop in obj)
      cb(prop, obj[prop])
  }

  NewBindable.fieldManager = fieldManager
  NewBindable.bindForm = bindForm

  DEFINE(NewBindable, 'bindables', {get:function(){return _bindables}, enumerable:true})
  DEFINE(NewBindable, 'PROPERTY_MANIPULATOR', {value:PROPERTY_MANIPULATOR, writeable:false})

  if (typeof module !== 'undefined' && module.hasOwnProperty('exports')) {
    module.exports = CrossTalk
  } else {
    window.glue = NewBindable
    window.familyOf = familyOf
    window.typeOf = typeOf
    window.Bindable = Bindable
  }

})()
<|endoftext|>


<commit_before>var chess = require('chess'),
    twilio = require('twilio'),
    express = require('express'),
    qs = require('querystring'),
    uuid = require('node-uuid');

var renderBoard = require('./lib/chess-renderer.js').renderBoard;

twilioClient = twilio('AC7bb2f43a783c6c974a8571d786605fa2', process.env.AUTH_TOKEN);

var app = express();

// create a game client
var board = chess.create(),
    m = null,
    status = null;

// look at the valid moves
status = board.getStatus();

console.log(renderBoard(status));

// make a move
m = board.move('a4');

// look at the status again after the move to see
// the opposing side's available moves
status = board.getStatus();

/*
twilio.sendMessage({

  to:'+16515556677', // Any number Twilio can deliver to
  from: '+14506667788', // A number you bought from Twilio and can use for outbound communication
  body: 'word to your mother.' // body of the SMS message

}, function(err, responseData) { //this function is executed when a response is received from Twilio

  if (!err) { // "err" is an error received during the request, if any

    "responseData" is a JavaScript object containing data received from Twilio.
      // A sample response from sending an SMS message is here (click "JSON" to see how the data appears in JavaScript):
      // http://www.twilio.com/docs/api/rest/sending-sms#example-1

      console.log(responseData.from); // outputs "+14506667788"
    console.log(responseData.body); // outputs "word to your mother."

  }
});
*/
var phoneNumbers = {};

var games = {};
app.post('/sms/reply/', function (req, res) {
  var body = '';

  req.on('data', function (data) {
    body += data;
  });

  req.on('end', function () {

    var POST = qs.parse(body);

    console.log('text body', POST);

    //validate incoming request is from twilio using your auth token and the header from Twilio
    var token = process.env.AUTH_TOKEN,
    header = req.headers['x-twilio-signature'];

    //validateRequest returns true if the request originated from Twilio
    if (twilio.validateRequest(token, header, 'http://nicki.fn.lc:8183/sms/reply/', POST)) {

        //generate a TwiML response
        var resp = new twilio.TwimlResponse();
        var respMessage = '';

        if(!phoneNumbers.hasOwnProperty(POST.To)){
          phoneNumbers[POST.To] = {
            gameId: uuid.v1(),
          };

          var currGameId = phoneNumbers[POST.To].gameId;

          //create new game
          games[currGameId] = {
            board: chess.create(),
            players: [],
          };
          games[currGameId].players.push(POST.To);

          respMessage = 'Add your friends phone # to start a game';

        }

        else{
          var currGame = games[phoneNumbers[POST.To].gameId];
          var smsBody = POST.Body.replace(/^\s+|\s+$/g, '');

          //Check if we should add opponent or not
          if(currGame.players.length === 1){

            //Add person
            if(smsBody.length === 10){
              currGame.players.push(smsBody);
              respMessage = 'Opponent with # '+smsBody+' successfully added';
            }else {
              respMessage = 'incorrect number. Try adding a correct friends #';
            }
          }
          //Play Chess Game
          else{
            //If we lose or stalemate
            if(currGame.board.isCheckmate || currGame.board.isStalemate){
              //remove game
              delete game[phoneNumbers[POST.To].gameId];

              if(currGame.board.isCheckmate){
                respMessage = 'Checkmate. Game Over'
              }else {
                respMessage = 'Stalemate. Gameover'
              }
            }
            //If we aren't losing
            else{

              //if we have a valid message
              //TODO: need to do proper validation
              if(smsBody.length > 4){

                console.log(smsBody.slice(2,3));
                //If we have a move command
                if(smsBody.slice(2,3) === 'to'){
                  var piece_pos = smsBody.slice(0,1);

                  var move_pos = smsBody.reverse().slice(0,1);

                    //Error message
                    try{
                      currGame.board.move(piece_pos, move_pos);
                    }catch(err){
                      resp.message('Error'+err.message);
                      res.writeHead(200, { 'Content-Type':'text/xml' });
                      res.end(resp.toString());
                      return;
                    }
                    resp.message('Piece moved from '+piece_pos+' to '+move_pos);

                }else if(smsBody.slice(0,3) === 'undo'){
                  currGame.board.undo();
                  resp.message('Move successfully undo');
                }
              }else{

                respMessage = 'Board\n' + renderBoard(currGame.board.getStatus());
              }
            }
          }

        }

      resp.message(respMessage);
      //Write headers
      res.writeHead(200, { 'Content-Type':'text/xml' });
      res.end(resp.toString());
    }else {
      res.writeHead(403, { 'Content-Type':'text/plain' });
      res.end('you are not twilio - take a hike.');
    }
  });
});

var server = app.listen(8183, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('CheSMS listening at http://%s:%s', host, port);
});
<commit_msg>added console.log for smsBody<commit_after>var chess = require('chess'),
    twilio = require('twilio'),
    express = require('express'),
    qs = require('querystring'),
    uuid = require('node-uuid');

var renderBoard = require('./lib/chess-renderer.js').renderBoard;

twilioClient = twilio('AC7bb2f43a783c6c974a8571d786605fa2', process.env.AUTH_TOKEN);

var app = express();

// create a game client
var board = chess.create(),
    m = null,
    status = null;

// look at the valid moves
status = board.getStatus();

console.log(renderBoard(status));

// make a move
m = board.move('a4');

// look at the status again after the move to see
// the opposing side's available moves
status = board.getStatus();

/*
twilio.sendMessage({

  to:'+16515556677', // Any number Twilio can deliver to
  from: '+14506667788', // A number you bought from Twilio and can use for outbound communication
  body: 'word to your mother.' // body of the SMS message

}, function(err, responseData) { //this function is executed when a response is received from Twilio

  if (!err) { // "err" is an error received during the request, if any

    "responseData" is a JavaScript object containing data received from Twilio.
      // A sample response from sending an SMS message is here (click "JSON" to see how the data appears in JavaScript):
      // http://www.twilio.com/docs/api/rest/sending-sms#example-1

      console.log(responseData.from); // outputs "+14506667788"
    console.log(responseData.body); // outputs "word to your mother."

  }
});
*/
var phoneNumbers = {};

var games = {};
app.post('/sms/reply/', function (req, res) {
  var body = '';

  req.on('data', function (data) {
    body += data;
  });

  req.on('end', function () {

    var POST = qs.parse(body);

    console.log('text body', POST);

    //validate incoming request is from twilio using your auth token and the header from Twilio
    var token = process.env.AUTH_TOKEN,
    header = req.headers['x-twilio-signature'];

    //validateRequest returns true if the request originated from Twilio
    if (twilio.validateRequest(token, header, 'http://nicki.fn.lc:8183/sms/reply/', POST)) {

        //generate a TwiML response
        var resp = new twilio.TwimlResponse();
        var respMessage = '';

        if(!phoneNumbers.hasOwnProperty(POST.To)){
          phoneNumbers[POST.To] = {
            gameId: uuid.v1(),
          };

          var currGameId = phoneNumbers[POST.To].gameId;

          //create new game
          games[currGameId] = {
            board: chess.create(),
            players: [],
          };
          games[currGameId].players.push(POST.To);

          respMessage = 'Add your friends phone # to start a game';

        }

        else{
          var currGame = games[phoneNumbers[POST.To].gameId];
          var smsBody = POST.Body.replace(/^\s+|\s+$/g, '');

          //Check if we should add opponent or not
          if(currGame.players.length === 1){

            //Add person
            if(smsBody.length === 10){
              currGame.players.push(smsBody);
              respMessage = 'Opponent with # '+smsBody+' successfully added';
            }else {
              respMessage = 'incorrect number. Try adding a correct friends #';
            }
          }
          //Play Chess Game
          else{
            //If we lose or stalemate
            if(currGame.board.isCheckmate || currGame.board.isStalemate){
              //remove game
              delete game[phoneNumbers[POST.To].gameId];

              if(currGame.board.isCheckmate){
                respMessage = 'Checkmate. Game Over'
              }else {
                respMessage = 'Stalemate. Gameover'
              }
            }
            //If we aren't losing
            else{

              //if we have a valid message
              //TODO: need to do proper validation
              if(smsBody.length > 4){

                console.log(smsBody);
                //If we have a move command
                if(smsBody.slice(2,3) === 'to'){
                  var piece_pos = smsBody.slice(0,1);

                  var move_pos = smsBody.reverse().slice(0,1);

                    //Error message
                    try{
                      currGame.board.move(piece_pos, move_pos);
                    }catch(err){
                      resp.message('Error'+err.message);
                      res.writeHead(200, { 'Content-Type':'text/xml' });
                      res.end(resp.toString());
                      return;
                    }
                    resp.message('Piece moved from '+piece_pos+' to '+move_pos);
                }else if(smsBody.slice(0,3) === 'undo'){
                  currGame.board.undo();
                  resp.message('Move successfully undo');
                }
              }else{

                respMessage = 'Board\n' + renderBoard(currGame.board.getStatus());
              }
            }
          }

        }

      resp.message(respMessage);
      //Write headers
      res.writeHead(200, { 'Content-Type':'text/xml' });
      res.end(resp.toString());
    }else {
      res.writeHead(403, { 'Content-Type':'text/plain' });
      res.end('you are not twilio - take a hike.');
    }
  });
});

var server = app.listen(8183, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('CheSMS listening at http://%s:%s', host, port);
});
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 Massachusetts Institute of Technology, Adobe Systems
 * Incorporated, and other contributors. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $, brackets, Mustache */

/**
 * provides events:
 *
 *  - enable & disable, when the extension should operate
 */

define(function (require, exports, module) {
    "use strict";

    var Agent              = require("Agent");
    var AgentManager       = require("AgentManager");
    var AppInit            = brackets.getModule("utils/AppInit");
    var CommandManager     = brackets.getModule("command/CommandManager");
    var Commands           = brackets.getModule("command/Commands");
    var Dialogs            = brackets.getModule("widgets/Dialogs");
    var EpochPanel         = require("EpochPanel");
    var FileCallGraphPanel = require("FileCallGraphPanel");
    var EditorInterface    = require("EditorInterface");
    var ExtensionUtils     = brackets.getModule("utils/ExtensionUtils");
    var Invitation         = require("Invitation");
    var Inspector          = brackets.getModule("LiveDevelopment/Inspector/Inspector");
    var LiveDevelopment    = brackets.getModule("LiveDevelopment/LiveDevelopment");
    var Menus              = brackets.getModule("command/Menus");
    var NativeApp          = brackets.getModule("utils/NativeApp");
    var NativeFileSystem   = brackets.getModule("file/NativeFileSystem").NativeFileSystem;
    var Panel              = require("Panel");
    var PreferencesManager = brackets.getModule("preferences/PreferencesManager");
    var ProxyProvider      = require("ProxyProvider");
    var Strings            = require("strings");
    var UI                 = require("UI");
    var Usage              = require("Usage");

    var $exports = $(exports);

    var THESEUS_VERSION = JSON.parse(require("text!package.json")).version;

    // check that node_modules is there and alert the user if it isn't
    var corruptInstallationDialogHTML = require("text!InstallationCorrupt.html");
    var corruptInstallationDialogTemplate = Mustache.render(corruptInstallationDialogHTML, {Strings : Strings});
    var nodeModulesPath = ExtensionUtils.getModulePath(module, "node_modules");
    NativeFileSystem.resolveNativeFileSystemPath(nodeModulesPath, function() {}, function() {
        var dialog = Dialogs.showModalDialogUsingTemplate(corruptInstallationDialogTemplate);
        var $dialog = dialog.getElement();
        $dialog.find(".close").on("click", dialog.close.bind(dialog));
    });

    // set up the menus

    var _modes = {
        "static" : { name: "static", displayName: "Serve files from disk" },
        "proxy" : { name: "proxy", displayName: "Proxy to localhost:3000 (experimental)" },
    };
    var _orderedModes = [_modes["static"], _modes["proxy"]];
    var DEFAULT_MODE = _modes["static"];

    var ID_THESEUS_SEND_FEEDBACK   = "brackets.theseus.sendFeedback";
    var NAME_THESEUS_SEND_FEEDBACK = "Send Theseus Feedback...";

    var ID_THESEUS_WELCOME_SCREEN   = "brackets.theseus.welcome";
    var NAME_THESEUS_WELCOME_SCREEN = "Theseus Welcome Screen...";

    var ID_THESEUS_ENABLE = "brackets.theseus.enable";
    var NAME_THESEUS_ENABLE = "Enable Theseus";

    var ID_THESEUS_DEBUG_BRACKETS = "brackets.theseus.debug-brackets";
    var NAME_THESEUS_DEBUG_BRACKETS = "Debug Brackets with Theseus";

    var ID_THESEUS_RESET_TRACE = "brackets.theseus.reset-trace";
    var NAME_THESEUS_RESET_TRACE = "Reset Theseus Trace Data (experimental)";

    var ID_THESEUS_MODES = _orderedModes.map(function (mode) { return "brackets.theseus.mode." + mode.name; });
    var NAME_THESEUS_MODES = _orderedModes.map(function (mode) { return "   Mode: " + mode.displayName; });

    // module variables

    var _enabled = false;
    var _mode = DEFAULT_MODE;
    var _prefs;

    function _enable() {
        $exports.triggerHandler("enable");
    }

    function _disable() {
        $exports.triggerHandler("disable");
    }

    function _toggleEnabled() {
        // TODO: disable or enable immediately
        _enabled = !_enabled;
        _prefs.setValue("enabled", _enabled);
        _updateMenuStates();

        if (_enabled) {
            _enable();
        } else {
            _disable();
        }
    }

    function _setMode(modeName) {
        // TODO: warn user that connection will need to be restarted
        _mode = _modes[modeName] || DEFAULT_MODE;
        _prefs.setValue("mode", _mode.name);
        _updateMenuStates();
    }

    function _setModeHandler(modeName) {
        return function () {
            _setMode(modeName);
            $exports.triggerHandler("modeChange", modeName);
        };
    }

    function _sendFeedback() {
        var params = "?";
        params += "brackets_version=" + brackets.metadata.version;
        params += "&theseus_version=" + THESEUS_VERSION;
        NativeApp.openURLInDefaultBrowser("file://" + ExtensionUtils.getModuleUrl(module, "feedback.html") + params);
    }

    function _showWelcomeScreen() {
        Invitation.showInvitation();
    }

    function _debugBrackets() {
        var _proxy;
        CommandManager.execute("debug.newBracketsWindow").then(function () {
            return ProxyProvider.getServer("/", "static");
        }).then(function (proxy) {
            _proxy = proxy;
            return Inspector.getDebuggableWindows("127.0.0.1", 9234);
        }).then(function (response) {
            var keys = Object.keys(response).sort(function (a, b) { return parseInt(a, 10) - parseInt(b, 10); });
            if (keys.length > 0) {
                // pick the last page
                var page = response[keys[keys.length - 1]];

                var redirect = function () {
                    Inspector.off("connect", redirect);
                    var redirectTo = _proxy.proxyRootURL + (window.location.pathname[0] === "/" ? window.location.pathname.slice(1) : window.location.pathname)
                    Inspector.Runtime.evaluate("window.location = " + JSON.stringify(redirectTo), function () {});
                };
                Inspector.on("connect", redirect);

                Inspector.connect(page.webSocketDebuggerUrl);
            }
        }).fail(function onFail(err) {
            console.log("debugging brackets failed: " + err);
        });
    }

    function _resetTrace() {
        AgentManager.resetTrace();
    }

    function _loadPreferences() {
        _prefs = PreferencesManager.getPreferenceStorage("com.adobe.theseus", { enabled: true, mode: "static" });
        _enabled = _prefs.getValue("enabled");
        _mode = _modes[_prefs.getValue("mode")] || DEFAULT_MODE;
    }

    function _setupMenu() {
        CommandManager.register(
            NAME_THESEUS_SEND_FEEDBACK,
            ID_THESEUS_SEND_FEEDBACK,
            _sendFeedback
        );

        CommandManager.register(
            NAME_THESEUS_WELCOME_SCREEN,
            ID_THESEUS_WELCOME_SCREEN,
            _showWelcomeScreen
        );

        CommandManager.register(
            NAME_THESEUS_ENABLE,
            ID_THESEUS_ENABLE,
            _toggleEnabled
        );

        CommandManager.register(
            NAME_THESEUS_DEBUG_BRACKETS,
            ID_THESEUS_DEBUG_BRACKETS,
            _debugBrackets
        );

        CommandManager.register(
            NAME_THESEUS_RESET_TRACE,
            ID_THESEUS_RESET_TRACE,
            _resetTrace
        );

        _orderedModes.forEach(function (mode, i) {
            CommandManager.register(
                NAME_THESEUS_MODES[i],
                ID_THESEUS_MODES[i],
                _setModeHandler(mode.name)
            );
        });

        var menu = Menus.getMenu(Menus.AppMenuBar.HELP_MENU);
        menu.addMenuDivider(Menus.LAST, null);
        menu.addMenuItem(ID_THESEUS_SEND_FEEDBACK, null, Menus.LAST, null);
        menu.addMenuItem(ID_THESEUS_WELCOME_SCREEN, null, Menus.LAST, null);

        var fileMenu = Menus.getMenu(Menus.AppMenuBar.FILE_MENU);
        fileMenu.addMenuDivider(Menus.LAST, null);
        fileMenu.addMenuItem(ID_THESEUS_ENABLE, null, Menus.LAST, null);
        _orderedModes.forEach(function (mode, i) {
            var prev = (i == 0) ? ID_THESEUS_ENABLE : ID_THESEUS_MODES[i - 1];
            fileMenu.addMenuItem(ID_THESEUS_MODES[i], null, Menus.AFTER, prev);
        });
        fileMenu.addMenuItem(ID_THESEUS_RESET_TRACE, null, Menus.AFTER, ID_THESEUS_MODES[ID_THESEUS_MODES.length - 1]);

        var debugMenu = Menus.getMenu("debug-menu");
        debugMenu.addMenuDivider(Menus.LAST, null);
        debugMenu.addMenuItem(ID_THESEUS_DEBUG_BRACKETS, [{ "key": "F10" }, { "key": "Cmd-Opt-T", "platform": "mac" }], Menus.LAST, null);

        _updateMenuStates();
    }

    function _updateMenuStates() {
        CommandManager.get(ID_THESEUS_ENABLE).setChecked(_enabled);
        _orderedModes.forEach(function (mode, i) {
            var cmd = CommandManager.get(ID_THESEUS_MODES[i]);
            cmd.setChecked(_mode.name === mode.name);
            cmd.setEnabled(_enabled);
        });
    }

    function isEnabled() {
        return _enabled;
    }

    function getModeName() {
        return _mode.name;
    }

    function _init() {
        _loadPreferences();
        _setupMenu();

        ExtensionUtils.loadStyleSheet(module, "main.less");

        Usage.init();
        ProxyProvider.init();
        Agent.init();
        AgentManager.init();
        EditorInterface.init();
        UI.init();
        Panel.init();
        EpochPanel.init();
        // FileCallGraphPanel.init();

        // after a short delay, show 'Thank you!' popup if they haven't seen it
        setTimeout(function () {
            Invitation.showInvitationIfNecessary();
        }, 1000);

        $(LiveDevelopment).on("statusChange", function (e, status) {
            if (status === 1) { // "Connecting to the remote debugger"
                setTimeout(function () {
                    var $btnGoLive = $("#toolbar-go-live");

                    $btnGoLive.twipsy("hide").removeData("twipsy");
                    $btnGoLive.twipsy({
                        placement: "left",
                        trigger: "manual",
                        autoHideDelay: 5000,
                        title: function () { return "Live development has been started with Theseus in " + _mode.name.toUpperCase() + " mode." },
                    }).twipsy("show");
                }, 1000);
            }
        });

        if (_enabled) { // enable now if enabled in preferences
            _enable();
        }
    }

    // exports

    exports.isEnabled = isEnabled;
    exports.getModeName = getModeName;
    exports.version = THESEUS_VERSION;

    // initialize the extension

    AppInit.htmlReady(_init);
});
<commit_msg>disable the 'reset trace' menu item<commit_after>/*
 * Copyright (c) 2012 Massachusetts Institute of Technology, Adobe Systems
 * Incorporated, and other contributors. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $, brackets, Mustache */

/**
 * provides events:
 *
 *  - enable & disable, when the extension should operate
 */

define(function (require, exports, module) {
    "use strict";

    var Agent              = require("Agent");
    var AgentManager       = require("AgentManager");
    var AppInit            = brackets.getModule("utils/AppInit");
    var CommandManager     = brackets.getModule("command/CommandManager");
    var Commands           = brackets.getModule("command/Commands");
    var Dialogs            = brackets.getModule("widgets/Dialogs");
    var EpochPanel         = require("EpochPanel");
    var FileCallGraphPanel = require("FileCallGraphPanel");
    var EditorInterface    = require("EditorInterface");
    var ExtensionUtils     = brackets.getModule("utils/ExtensionUtils");
    var Invitation         = require("Invitation");
    var Inspector          = brackets.getModule("LiveDevelopment/Inspector/Inspector");
    var LiveDevelopment    = brackets.getModule("LiveDevelopment/LiveDevelopment");
    var Menus              = brackets.getModule("command/Menus");
    var NativeApp          = brackets.getModule("utils/NativeApp");
    var NativeFileSystem   = brackets.getModule("file/NativeFileSystem").NativeFileSystem;
    var Panel              = require("Panel");
    var PreferencesManager = brackets.getModule("preferences/PreferencesManager");
    var ProxyProvider      = require("ProxyProvider");
    var Strings            = require("strings");
    var UI                 = require("UI");
    var Usage              = require("Usage");

    var $exports = $(exports);

    var THESEUS_VERSION = JSON.parse(require("text!package.json")).version;

    // check that node_modules is there and alert the user if it isn't
    var corruptInstallationDialogHTML = require("text!InstallationCorrupt.html");
    var corruptInstallationDialogTemplate = Mustache.render(corruptInstallationDialogHTML, {Strings : Strings});
    var nodeModulesPath = ExtensionUtils.getModulePath(module, "node_modules");
    NativeFileSystem.resolveNativeFileSystemPath(nodeModulesPath, function() {}, function() {
        var dialog = Dialogs.showModalDialogUsingTemplate(corruptInstallationDialogTemplate);
        var $dialog = dialog.getElement();
        $dialog.find(".close").on("click", dialog.close.bind(dialog));
    });

    // set up the menus

    var _modes = {
        "static" : { name: "static", displayName: "Serve files from disk" },
        "proxy" : { name: "proxy", displayName: "Proxy to localhost:3000 (experimental)" },
    };
    var _orderedModes = [_modes["static"], _modes["proxy"]];
    var DEFAULT_MODE = _modes["static"];

    var ID_THESEUS_SEND_FEEDBACK   = "brackets.theseus.sendFeedback";
    var NAME_THESEUS_SEND_FEEDBACK = "Send Theseus Feedback...";

    var ID_THESEUS_WELCOME_SCREEN   = "brackets.theseus.welcome";
    var NAME_THESEUS_WELCOME_SCREEN = "Theseus Welcome Screen...";

    var ID_THESEUS_ENABLE = "brackets.theseus.enable";
    var NAME_THESEUS_ENABLE = "Enable Theseus";

    var ID_THESEUS_DEBUG_BRACKETS = "brackets.theseus.debug-brackets";
    var NAME_THESEUS_DEBUG_BRACKETS = "Debug Brackets with Theseus";

    var ID_THESEUS_RESET_TRACE = "brackets.theseus.reset-trace";
    var NAME_THESEUS_RESET_TRACE = "Reset Theseus Trace Data (experimental)";

    var ID_THESEUS_MODES = _orderedModes.map(function (mode) { return "brackets.theseus.mode." + mode.name; });
    var NAME_THESEUS_MODES = _orderedModes.map(function (mode) { return "   Mode: " + mode.displayName; });

    // module variables

    var _enabled = false;
    var _mode = DEFAULT_MODE;
    var _prefs;

    function _enable() {
        $exports.triggerHandler("enable");
    }

    function _disable() {
        $exports.triggerHandler("disable");
    }

    function _toggleEnabled() {
        // TODO: disable or enable immediately
        _enabled = !_enabled;
        _prefs.setValue("enabled", _enabled);
        _updateMenuStates();

        if (_enabled) {
            _enable();
        } else {
            _disable();
        }
    }

    function _setMode(modeName) {
        // TODO: warn user that connection will need to be restarted
        _mode = _modes[modeName] || DEFAULT_MODE;
        _prefs.setValue("mode", _mode.name);
        _updateMenuStates();
    }

    function _setModeHandler(modeName) {
        return function () {
            _setMode(modeName);
            $exports.triggerHandler("modeChange", modeName);
        };
    }

    function _sendFeedback() {
        var params = "?";
        params += "brackets_version=" + brackets.metadata.version;
        params += "&theseus_version=" + THESEUS_VERSION;
        NativeApp.openURLInDefaultBrowser("file://" + ExtensionUtils.getModuleUrl(module, "feedback.html") + params);
    }

    function _showWelcomeScreen() {
        Invitation.showInvitation();
    }

    function _debugBrackets() {
        var _proxy;
        CommandManager.execute("debug.newBracketsWindow").then(function () {
            return ProxyProvider.getServer("/", "static");
        }).then(function (proxy) {
            _proxy = proxy;
            return Inspector.getDebuggableWindows("127.0.0.1", 9234);
        }).then(function (response) {
            var keys = Object.keys(response).sort(function (a, b) { return parseInt(a, 10) - parseInt(b, 10); });
            if (keys.length > 0) {
                // pick the last page
                var page = response[keys[keys.length - 1]];

                var redirect = function () {
                    Inspector.off("connect", redirect);
                    var redirectTo = _proxy.proxyRootURL + (window.location.pathname[0] === "/" ? window.location.pathname.slice(1) : window.location.pathname)
                    Inspector.Runtime.evaluate("window.location = " + JSON.stringify(redirectTo), function () {});
                };
                Inspector.on("connect", redirect);

                Inspector.connect(page.webSocketDebuggerUrl);
            }
        }).fail(function onFail(err) {
            console.log("debugging brackets failed: " + err);
        });
    }

    function _resetTrace() {
        AgentManager.resetTrace();
    }

    function _loadPreferences() {
        _prefs = PreferencesManager.getPreferenceStorage("com.adobe.theseus", { enabled: true, mode: "static" });
        _enabled = _prefs.getValue("enabled");
        _mode = _modes[_prefs.getValue("mode")] || DEFAULT_MODE;
    }

    function _setupMenu() {
        CommandManager.register(
            NAME_THESEUS_SEND_FEEDBACK,
            ID_THESEUS_SEND_FEEDBACK,
            _sendFeedback
        );

        CommandManager.register(
            NAME_THESEUS_WELCOME_SCREEN,
            ID_THESEUS_WELCOME_SCREEN,
            _showWelcomeScreen
        );

        CommandManager.register(
            NAME_THESEUS_ENABLE,
            ID_THESEUS_ENABLE,
            _toggleEnabled
        );

        CommandManager.register(
            NAME_THESEUS_DEBUG_BRACKETS,
            ID_THESEUS_DEBUG_BRACKETS,
            _debugBrackets
        );

        CommandManager.register(
            NAME_THESEUS_RESET_TRACE,
            ID_THESEUS_RESET_TRACE,
            _resetTrace
        );

        _orderedModes.forEach(function (mode, i) {
            CommandManager.register(
                NAME_THESEUS_MODES[i],
                ID_THESEUS_MODES[i],
                _setModeHandler(mode.name)
            );
        });

        var menu = Menus.getMenu(Menus.AppMenuBar.HELP_MENU);
        menu.addMenuDivider(Menus.LAST, null);
        menu.addMenuItem(ID_THESEUS_SEND_FEEDBACK, null, Menus.LAST, null);
        menu.addMenuItem(ID_THESEUS_WELCOME_SCREEN, null, Menus.LAST, null);

        var fileMenu = Menus.getMenu(Menus.AppMenuBar.FILE_MENU);
        fileMenu.addMenuDivider(Menus.LAST, null);
        fileMenu.addMenuItem(ID_THESEUS_ENABLE, null, Menus.LAST, null);
        _orderedModes.forEach(function (mode, i) {
            var prev = (i == 0) ? ID_THESEUS_ENABLE : ID_THESEUS_MODES[i - 1];
            fileMenu.addMenuItem(ID_THESEUS_MODES[i], null, Menus.AFTER, prev);
        });
        // fileMenu.addMenuItem(ID_THESEUS_RESET_TRACE, null, Menus.AFTER, ID_THESEUS_MODES[ID_THESEUS_MODES.length - 1]);

        var debugMenu = Menus.getMenu("debug-menu");
        debugMenu.addMenuDivider(Menus.LAST, null);
        debugMenu.addMenuItem(ID_THESEUS_DEBUG_BRACKETS, [{ "key": "F10" }, { "key": "Cmd-Opt-T", "platform": "mac" }], Menus.LAST, null);

        _updateMenuStates();
    }

    function _updateMenuStates() {
        CommandManager.get(ID_THESEUS_ENABLE).setChecked(_enabled);
        _orderedModes.forEach(function (mode, i) {
            var cmd = CommandManager.get(ID_THESEUS_MODES[i]);
            cmd.setChecked(_mode.name === mode.name);
            cmd.setEnabled(_enabled);
        });
    }

    function isEnabled() {
        return _enabled;
    }

    function getModeName() {
        return _mode.name;
    }

    function _init() {
        _loadPreferences();
        _setupMenu();

        ExtensionUtils.loadStyleSheet(module, "main.less");

        Usage.init();
        ProxyProvider.init();
        Agent.init();
        AgentManager.init();
        EditorInterface.init();
        UI.init();
        Panel.init();
        EpochPanel.init();
        // FileCallGraphPanel.init();

        // after a short delay, show 'Thank you!' popup if they haven't seen it
        setTimeout(function () {
            Invitation.showInvitationIfNecessary();
        }, 1000);

        $(LiveDevelopment).on("statusChange", function (e, status) {
            if (status === 1) { // "Connecting to the remote debugger"
                setTimeout(function () {
                    var $btnGoLive = $("#toolbar-go-live");

                    $btnGoLive.twipsy("hide").removeData("twipsy");
                    $btnGoLive.twipsy({
                        placement: "left",
                        trigger: "manual",
                        autoHideDelay: 5000,
                        title: function () { return "Live development has been started with Theseus in " + _mode.name.toUpperCase() + " mode." },
                    }).twipsy("show");
                }, 1000);
            }
        });

        if (_enabled) { // enable now if enabled in preferences
            _enable();
        }
    }

    // exports

    exports.isEnabled = isEnabled;
    exports.getModeName = getModeName;
    exports.version = THESEUS_VERSION;

    // initialize the extension

    AppInit.htmlReady(_init);
});
<|endoftext|>


<commit_before>var express = require( "express" );
var Twitter = require( "twitter" );
var app = express();

var tokenList = [
  { name: "Consumer Key",        value: process.env.TWITTER_CONSUMER_KEY },
  { name: "Consumer Secret",     value: process.env.TWITTER_CONSUMER_SECRET },
  { name: "Access Token Key",    value: process.env.TWITTER_ACCESS_TOKEN_KEY },
  { name: "Access Token Secret", value: process.env.TWITTER_ACCESS_TOKEN_SECRET },
];

tokenList.forEach( function( item ) {
  if( item.value === void 0 /* undefined */ ) {
    console.log( "[ERROR] " + item.name + " is undefined. exit." );
    process.exit();
  }
} );

var client = new Twitter( {
  consumer_key:       process.env.TWITTER_CONSUMER_KEY,
  consumer_secret:    process.env.TWITTER_CONSUMER_SECRET,
  access_token_key:    process.env.TWITTER_ACCESS_TOKEN_KEY,
  access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
} );

var port = 3000;

if( process.env.NODE_PORT !== void 0 ) {
  port = parseInt( process.env.NODE_PORT, 10 );
  if( isNaN( port ) ) {
    console.log( "[ERROR] Unrecognized NODE_PORT: " + process.env.NODE_PORT );
    process.exit();
  }
}

app.use( '/', express.static( 'public' ) );

app.get( '/test', function( req, res ) {
  client.get('followers/ids', {screen_name: "@rmn_e"}, function(error, result, response){
    console.log( "Tweets:" + JSON.stringify( result ));
    console.log( "Error:" + JSON.stringify(error ));
  });
  res.send( "Hello, World!" );
} );

app.listen( port );
console.log( "server is running on http://localhost:" + port + "/" );

<commit_msg>とりあえず平均間隔を取得できるようになった<commit_after>var express = require( "express" );
var Twitter = require( "twitter" );
var app = express();

var tokenList = [
  { name: "Consumer Key",        value: process.env.TWITTER_CONSUMER_KEY },
  { name: "Consumer Secret",     value: process.env.TWITTER_CONSUMER_SECRET },
  { name: "Access Token Key",    value: process.env.TWITTER_ACCESS_TOKEN_KEY },
  { name: "Access Token Secret", value: process.env.TWITTER_ACCESS_TOKEN_SECRET },
];

tokenList.forEach( function( item ) {
  if( item.value === void 0 /* undefined */ ) {
    console.log( "[ERROR] " + item.name + " is undefined. exit." );
    process.exit();
  }
} );

var client = new Twitter( {
  consumer_key:       process.env.TWITTER_CONSUMER_KEY,
  consumer_secret:    process.env.TWITTER_CONSUMER_SECRET,
  access_token_key:    process.env.TWITTER_ACCESS_TOKEN_KEY,
  access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
} );

var port = 3000;

if( process.env.NODE_PORT !== void 0 ) {
  port = parseInt( process.env.NODE_PORT, 10 );
  if( isNaN( port ) ) {
    console.log( "[ERROR] Unrecognized NODE_PORT: " + process.env.NODE_PORT );
    process.exit();
  }
}

app.use( '/', express.static( 'public' ) );

app.get( '/friends', function( req, res ) {
  client.get('friends/ids', {screen_name: "@rmn_e", count: 100}, function(error, result, response){
    var userIdList = result.ids
    var allNum = userIdList.length;
    var finishedNum = 0;
    var avgTimeList = new Array( allNum );
    var stop = false;

    for( var i = 0; i < allNum; i++ ) {
      ( function ( i ) {
        getAverageIntervalByUser( userIdList[ i ], function( tStatus, avgDiff) {
          if( stop ) return;
          if( tStatus === "success" ) {
            avgTimeList[ i ] = avgDiff;
          } else if( tStatus === "ratelimit" || tStatus === "error" ) {
            console.log( "Rate Limit Exceeded!" );
            stop = true;
            return;
          }
          console.log( tStatus + " " + i + ": " + avgDiff );
          if( ++finishedNum === allNum ) {
            console.log( result );
            console.log( avgTimeList );
          }
        } );
      } ) ( i );
    }
    console.log( "Tweets:" + JSON.stringify( result ));
    console.log( "Error:" + JSON.stringify(error ));
  });
  res.send( "フォローしているユーザ一覧を取得中, しばらくお待ちください" );
} );

function getAverageIntervalByUser( userId, callBack ) {
  client.get('statuses/user_timeline', {user_id: userId }, function(error, result, response) {
    if( error === null ) {
      console.log( "ENTER with " + userId );

      var postedTimeDiffList = result.map( function( tweet ) {
        return new Date( tweet.created_at ).getTime() / 1000;
      } ).map( function( cur, idx, array ) {
        if( idx === array.length - 1 ) { return void 0; }
        return cur - array[ idx + 1 ];
      } );

      postedTimeDiffList.pop();

      var len = postedTimeDiffList.length;

      var avgDiff = postedTimeDiffList.reduce( function( prev, cur ) {
        return prev + cur;
      } ) / len;

      console.log( "average:" + avgDiff + "[sec]" );
      callBack( "success", avgDiff );
    } else {

      if( error[ 0 ].code === 88 ) {
        callBack( "ratelimit" );
      } else {
        callBack( "error" );
      }
    }
  } );
}

app.get( '/tweets', function( req, res ) {

   res.send( "指定ユーザの最新ツイートを取得中, しばらくお待ちください" );
} );

app.listen( port );
console.log( "server is running on http://localhost:" + port + "/" );

<|endoftext|>


<commit_before>'use strict';
var _ = require('lodash');
var fs = require('file-system');
var app = require('app');
var path = require('path');
var shell = require('shelljs');
var BrowserWindow = require('browser-window');

// ####################################################
// ####################################################

// Report crashes to our server.
require('crash-reporter').start();

var mainWindow = null;
var options = {
	"debug": true   ,
	"version": "1.0.0",
	"views_dir": "views",
	"root_view": "index.html"
};

options = _.extend({
	// ADDITIONAL CUSTOM SETTINGS
}, options);

// ############################################################################################
// ############################################################################################

// Quit when all windows are closed.
app.on('window-all-closed', function() {
  if(process.platform !== 'darwin') { app.quit(); }
});

app.on('ready', function() {

  shell.mkdir('-p','/home/richard/Desktop','/home/richard/Desktop/Me');

  //get os home path and create folder there with the permission read,write

  // mainWindow = new BrowserWindow({width: 600, height: 600});
  // mainWindow.loadUrl(path.join('file://', __dirname, options.views_dir, options.root_view));
  // if(options.debug) { mainWindow.openDevTools(); }
  // mainWindow.on('closed', function() { mainWindow = null; });
});

// ############################################################################################
// ############################################################################################
<commit_msg>Auto-commit<commit_after>'use strict';
var _ = require('lodash');
var fs = require('file-system');
var app = require('app');
var path = require('path');
var shell = require('shelljs');
var BrowserWindow = require('browser-window');

// ####################################################
// ####################################################

// Report crashes to our server.
require('crash-reporter').start();

var mainWindow = null;
var options = {
	"debug": true   ,
	"version": "1.0.0",
	"views_dir": "views",
	"root_view": "index.html"
};

options = _.extend({
	// ADDITIONAL CUSTOM SETTINGS
}, options);

// ############################################################################################
// ############################################################################################

// Quit when all windows are closed.
app.on('window-all-closed', function() {
  if(process.platform !== 'darwin') { app.quit(); }
});

app.on('ready', function() {

  // shell.mkdir('-p','/home/$USER/Desktop','/home/echo $USER/Desktop/Me');

	// var child = shell.exec('cd bash && ./dir.sh', {async:true});
	// shell.echo(child);
  if (shell.exec('git commit -am "Auto-commit"').code !== 0) {
  shell.echo('Error: Git commit failed');
  exit(1);
}

  //get os home path and create folder there with the permission read,write

  // mainWindow = new BrowserWindow({width: 600, height: 600});
  // mainWindow.loadUrl(path.join('file://', __dirname, options.views_dir, options.root_view));
  // if(options.debug) { mainWindow.openDevTools(); }
  // mainWindow.on('closed', function() { mainWindow = null; });
});

// ############################################################################################
// ############################################################################################
<|endoftext|>


<commit_before>// Init the app after page loaded.
window.onload = initPage;

var debug = true;

var config = {
  text: {
    "message": "Guest The Letter From a (lowser) to z (higher)",
    "guess": "Guesses:",
    "hint": "Higher Or Lower:",
    "guessed": "Letters Guessed:",
    "export": "Export Canvas Image"
  }
};

// The entry function.
function initPage() {
  if (!canvasSupport()) { // If Canvas is not supported on the browser, do nothing but tell the user.
    alert("Sorry, your browser does not support HTML5 Canvas");
    return false;
  }
  canvasApp();
}

function canvasApp() {
  var canvas = document.getElementById("theCanvas"),
      ctx = canvas.getContext("2d"),
      guessedCount = 0,
      guessedChars = [],
      allowedChars = range("a", "z"),
      userInputChar,
      correctChar = getRandomChar();

  addEventListeners();

  initGame();

  function initGame() {
    // Background color
    ctx.fillStyle = "rgb(255, 255, 170)";
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // box border
    ctx.strokeStyle = "#000000";
    ctx.strokeRect(5, 5, canvas.width - 10, canvas.height - 10);

    // Message
    ctx.fillStyle = "red";
    ctx.font = "14px Sans-Serif";
    ctx.fillText(t("message"), 100, 50);

    // Guesses
    ctx.fillStyle = "green";
    ctx.font = "16px Sans-Serif";
    ctx.fillText(t("guess") + guessedCount, 210, 70);

    // Higher Or Lower
    ctx.fillStyle = "black";
    ctx.font = "16px Sans-Serif";
    ctx.fillText(t("hint"), 170, 170);

    // Letters Guessed
    ctx.fillStyle = "red";
    ctx.font = "16px Sans-Serif";
    ctx.fillText(t("guessed"), 10, 370);
  }

  function addEventListeners() {
  }

  function getRandomChar() {
    var random = rand(0, allowedChars.length - 1);
    return allowedChars[random];
  }

  function t(text) {
    return typeof config["text"][text] !== "undefined" ? config["text"][text] : "";
  }

}

// Does the browser support HTML5 Canvas ?
function canvasSupport() {
  var canvas = document.createElement("canvas");
  return !!(canvas.getContext && canvas.getContext("2d"));
}

// A simple debugging tool.
function log() {
  if (!debug) return ;
  var args = Array.prototype.slice.call(arguments);
  if (window.console && window.console.log) {
    console.log.apply(console, args);
  } else {
    alert(args.join("\n"));
  }
}

//http://phpjs.org/functions/range/
function range(low, high, step) {

  var matrix = [];
  var inival, endval, plus;
  var walker = step || 1;
  var chars = false;

  if (!isNaN(low) && !isNaN(high)) {
    inival = low;
    endval = high;
  } else if (isNaN(low) && isNaN(high)) {
    chars = true;
    inival = low.charCodeAt(0);
    endval = high.charCodeAt(0);
  } else {
    inival = (isNaN(low) ? 0 : low);
    endval = (isNaN(high) ? 0 : high);
  }

  plus = ((inival > endval) ? false : true);
  if (plus) {
    while (inival <= endval) {
      matrix.push(((chars) ? String.fromCharCode(inival) : inival));
      inival += walker;
    }
  } else {
    while (inival >= endval) {
      matrix.push(((chars) ? String.fromCharCode(inival) : inival));
      inival -= walker;
    }
  }

  return matrix;
}
//http://phpjs.org/functions/rand/
function rand(min, max) {
  var argc = arguments.length;
  if (argc === 0) {
    min = 0;
    max = 2147483647;
  } else if (argc === 1) {
    throw new Error('Warning: rand() expects exactly 2 parameters, 1 given');
  }
  return Math.floor(Math.random() * (max - min + 1)) + min;
}<commit_msg>Add event listener<commit_after>// Init the app after page loaded.
window.onload = initPage;

var debug = true;

var config = {
  text: {
    "message": "Guest The Letter From a (lowser) to z (higher)",
    "guess": "Guesses:",
    "hint": "Higher Or Lower:",
    "guessed": "Letters Guessed:",
    "export": "Export Canvas Image",
    "inValidChar": "That is not a letter",
    "higher": "Higher",
    "lower": "Lower",
    "gameover": "You got it!"
  }
};

// The entry function.
function initPage() {
  if (!canvasSupport()) { // If Canvas is not supported on the browser, do nothing but tell the user.
    alert("Sorry, your browser does not support HTML5 Canvas");
    return false;
  }
  canvasApp();
}

function canvasApp() {
  var canvas = document.getElementById("theCanvas"),
      ctx = canvas.getContext("2d"),
      gameOver = false,
      higherOrLower = "",
      guessedCount = 0,
      guessedChars = [],
      allowedChars = range("a", "z"),
      userInputChar,
      correctCharIndex,
      correctChar = getRandomChar();

  addEventListeners();

  drawScreen();

  function drawScreen() {
    // Background color
    ctx.fillStyle = "rgb(255, 255, 170)";
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // box border
    ctx.strokeStyle = "#000000";
    ctx.strokeRect(5, 5, canvas.width - 10, canvas.height - 10);

    // Message
    ctx.fillStyle = "red";
    ctx.font = "14px Sans-Serif";
    ctx.fillText(t("message"), 100, 50);

    // Guesses
    ctx.fillStyle = "green";
    ctx.font = "16px Sans-Serif";
    ctx.fillText(t("guess") + guessedCount, 210, 70);

    // Higher Or Lower
    ctx.fillStyle = "black";
    ctx.font = "16px Sans-Serif";
    ctx.fillText(t("hint") + higherOrLower, 170, 170);

    // Letters Guessed
    ctx.fillStyle = "red";
    ctx.font = "16px Sans-Serif";
    ctx.fillText(t("guessed") + guessedChars.join(','), 10, 370);

    if (gameOver) {
      ctx.fillStyle = "red";
      ctx.font = "40px Sans-Serif";
      ctx.fillText(t("gameover"), 150, 180);
    }
  }

  function addEventListeners() {
    document.addEventListener("keydown", function(event) {
      if (gameOver) return;
      var userInputChar = String.fromCharCode(event.keyCode).toLowerCase();
      guessedCount++;
      guessedChars.push(userInputChar);

      if (userInputChar === correctChar) {
        gameOver = true;
      } else {
        // Is it a allowed char ?
        var letterIndex = allowedChars.indexOf(userInputChar);
        if (letterIndex === -1) {
          higherOrLower = t("inValidChar");
        } else if (letterIndex > correctCharIndex) {
          higherOrLower = t("lower");
        } else {
          higherOrLower = t("higher");
        }
      }
      drawScreen();
    }, false);
  }

  function getRandomChar() {
    var random = rand(0, allowedChars.length - 1);
    correctCharIndex = random;
    return allowedChars[random];
  }

  function t(text) {
    return typeof config["text"][text] !== "undefined" ? config["text"][text] : "";
  }

}

// Does the browser support HTML5 Canvas ?
function canvasSupport() {
  var canvas = document.createElement("canvas");
  return !!(canvas.getContext && canvas.getContext("2d"));
}

// A simple debugging tool.
function log() {
  if (!debug) return ;
  var args = Array.prototype.slice.call(arguments);
  if (window.console && window.console.log) {
    console.log.apply(console, args);
  } else {
    alert(args.join("\n"));
  }
}

//http://phpjs.org/functions/range/
function range(low, high, step) {

  var matrix = [];
  var inival, endval, plus;
  var walker = step || 1;
  var chars = false;

  if (!isNaN(low) && !isNaN(high)) {
    inival = low;
    endval = high;
  } else if (isNaN(low) && isNaN(high)) {
    chars = true;
    inival = low.charCodeAt(0);
    endval = high.charCodeAt(0);
  } else {
    inival = (isNaN(low) ? 0 : low);
    endval = (isNaN(high) ? 0 : high);
  }

  plus = ((inival > endval) ? false : true);
  if (plus) {
    while (inival <= endval) {
      matrix.push(((chars) ? String.fromCharCode(inival) : inival));
      inival += walker;
    }
  } else {
    while (inival >= endval) {
      matrix.push(((chars) ? String.fromCharCode(inival) : inival));
      inival -= walker;
    }
  }

  return matrix;
}
//http://phpjs.org/functions/rand/
function rand(min, max) {
  var argc = arguments.length;
  if (argc === 0) {
    min = 0;
    max = 2147483647;
  } else if (argc === 1) {
    throw new Error('Warning: rand() expects exactly 2 parameters, 1 given');
  }
  return Math.floor(Math.random() * (max - min + 1)) + min;
}<|endoftext|>


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

    var name = prompt("What is your name?");

    function checkName(){
      if (name === "" || name === null) {
        alert("Please give a valid name!");
        name = prompt("What is your name?");
        checkName();
      }
    }
  // Check the entered name
  checkName();

  alert("Welcome to the game " + name + ", may the odds ever be in your favor!");

  alert("This is an Adventure Game, It goes as you please, as you desire. \nLET US START!");

  var myChoice = prompt("So, do you like scary stories, " + name + "?");

  if (myChoice.toLowerCase === "yes") {
      alert("So we depart on our journey...");
  } else if (myChoice.toLowerCase() === "no") {
      alert("This is gonna be FUN! Haha!");
  } else {
      checkMyChoice();
  }

  function checkMyChoice() {
    if (myChoice.toLowerCase != "yes" || myChoice.toLowerCase != "no"){
      alert("Please answer 'yes' or 'no'");
      var myChoice = prompt("So, do you like scary stories, " + name + "?");
      checkMyChoice();
    }
  }

 function checkAlone() {
   if (alone.toLowerCase() != "a" || alone.toLowerCase() != "b" || alone.toLowerCase() != "c"){
     alert("Please respond with 'a', 'b', or 'c'!");
     var alone = prompt(
         "You're at home, alone, watching the TV and hear a knock on the door. You hear more banging on the door. Your heatbeat speeds up and you're very scared. What do you do? \nA) Ignore the knocking nervously. \nB) Start screaming your head off. \nC) Couragously go and open the door. \nPlease choose A, B, or C "
     );
     checkAlone();
   }
  }

  var alone = prompt(
      "You're at home, alone, watching the TV and hear a knock on the door. You hear more banging on the door. Your heatbeat speeds up and you're very scared. What do you do? \nA) Ignore the knocking nervously. \nB) Start screaming your head off. \nC) Couragously go and open the door. \nPlease choose A, B, or C "
  );

  if (alone.toLowerCase() === "c") {
      alert( name + " , WOW! You are very couragous! Sadly your bravery comes to an end when you find that it was just your friends pranking you. You guys go take a walk.");
  } else if (alone.toLowerCase() === "b") {
      alert( name + " , too bad because they was your friends pulling a prank on you. You actually fell for it! You guys go take a walk.");
  } else if (alone.toLowerCase() === "a") {
      alert( name + " , too bad because it was your friends just pulling a prank on you. You actually fell for it! You guys decide take a walk.");
  } else if (alone.toLowerCase() === "" || alone === undefined) {
    checkAlone();
  } else {
    checkAlone();
  }

  var rumors = prompt(
      "Your friends tell you that rumors are circulating about 'Chain-Saw Billy' the new boogyman around town. He catches his victems and tortures them until death with his chainsaw. You and your buds hear a yell then a chainsaw starting up! \nYou look back and see 'Chain-Saw Billy' cutting off a mans head... He looks at you and comes sprinting after you. What do you do? \nA) Run away screaming your head off. \nB) Stand your ground and try to protect you and your friends. \nC) Go try to get help."
  );

  function checkRumors(){
    if (rumors.toLowerCase() != "a" || rumors.toLowerCase() != "b" || rumors.toLowerCase() != "c") {
      alert("Please respond with 'a', 'b', or 'c'!");
      var rumors = prompt(
          "Your friends tell you that rumors are circulating about 'Chain-Saw Billy' the new boogyman around town. He catches his victems and tortures them until death with his chainsaw. You and your buds hear a yell then a chainsaw starting up! \nYou look back and see 'Chain-Saw Billy' cutting off a mans head... He looks at you and comes sprinting after you. What do you do? \nA) Run away screaming your head off. \nB) Stand your ground and try to protect you and your friends. \nC) Go try to get help."
      );
      checkRumors();
    }
  }

  if (rumors.toLowerCase() === "b") {
      alert("Boy! You have the guts!");
  } else if(rumors.toLowerCase() === "a" || rumors.toLowerCase() === "c"){
      alert("Your cowardliness doesn't save you! He gets you! Sorry! \n \n BUT, you still manage to excape him!");
      done();
  } else {
    checkRumors();
  }

  function checkRunAfter() {
    if (runafter.toLowerCase() != "a" || runafter.toLowerCase() != "b" || runafter.toLowerCase() != "c"){
      alert("Please respond with 'a', 'b', or 'c'!");
      var runafter = prompt(
          "You run home sprint up the stairs, jump under the bed and hide. You hear 'Chain-Saw Billy' capture your friend. What do you do? \nA) Get tired of all this stuff and suicide out the window. \nB) Choke yourself. \nC) Try to protect yourself with anything you can find."
      );
      checkRunAfter();
    }
  }

  var runafter = prompt(
      "You run home sprint up the stairs, jump under the bed and hide. You hear 'Chain-Saw Billy' capture your friend. What do you do? \nA) Get tired of all this stuff and suicide out the window. \nB) Choke yourself. \nC) Try to protect yourself with anything you can find."
  );

  if (runafter.toLowerCase() === "c") {
      alert("Sorry, you get killed in inexplicable ways");
  } else if (runafter.toLowerCase() === "a" || runafter.toLowerCase() === "b"){
      alert("You'd kill yourself?! Wow must be depressed! Please call the local Suicide Hotline!");
  } else {
    checkRunAfter();
  }

  function done(){
    alert("Thanks for playing this Adventure Game!");
  }

}
<commit_msg>main.js: fix some more check bugs<commit_after>function game() {
    'use strict';

    var name = prompt("What is your name?");

    function checkName(){
      if (name === "" || name === null) {
        alert("Please give a valid name!");
        name = prompt("What is your name?");
        checkName();
      }
    }
  // Check the entered name
  checkName();

  alert("Welcome to the game " + name + ", may the odds ever be in your favor!");

  alert("This is an Adventure Game, It goes as you please, as you desire. \nLET US START!");

  function checkMyChoice() {
    if (myChoice.toLowerCase != "yes" || myChoice.toLowerCase != "no") {
      alert("Please answer 'yes' or 'no'");
      myChoice = prompt("So, do you like scary stories, " + name + "?");
    }
  }

  var myChoice = prompt("So, do you like scary stories, " + name + "?");

  if (myChoice.toLowerCase === "yes") {
      alert("So we depart on our journey...");
  } else if (myChoice.toLowerCase() === "no") {
      alert("This is gonna be FUN! Haha!");
  } else {
      checkMyChoice();
  }

 function checkAlone() {
     alert("Please respond with 'a', 'b', or 'c'!");
     alone = prompt(
         "You're at home, alone, watching the TV and hear a knock on the door. You hear more banging on the door. Your heatbeat speeds up and you're very scared. What do you do? \nA) Ignore the knocking nervously. \nB) Start screaming your head off. \nC) Couragously go and open the door. \nPlease choose A, B, or C "
     );
     checkAlone();
   }

  var alone = prompt(
      "You're at home, alone, watching the TV and hear a knock on the door. You hear more banging on the door. Your heatbeat speeds up and you're very scared. What do you do? \nA) Ignore the knocking nervously. \nB) Start screaming your head off. \nC) Couragously go and open the door. \nPlease choose A, B, or C "
  );

  if (alone.toLowerCase() === "c") {
      alert( name + " , WOW! You are very couragous! Sadly your bravery comes to an end when you find that it was just your friends pranking you. You guys go take a walk.");
  } else if (alone.toLowerCase() === "b") {
      alert( name + " , too bad because they was your friends pulling a prank on you. You actually fell for it! You guys go take a walk.");
  } else if (alone.toLowerCase() === "a") {
      alert( name + " , too bad because it was your friends just pulling a prank on you. You actually fell for it! You guys decide take a walk.");
  } else if (alone.toLowerCase() === "" || alone === undefined) {
    checkAlone();
  } else {
    checkAlone();
  }

  var rumors = prompt(
      "Your friends tell you that rumors are circulating about 'Chain-Saw Billy' the new boogyman around town. He catches his victems and tortures them until death with his chainsaw. You and your buds hear a yell then a chainsaw starting up! \nYou look back and see 'Chain-Saw Billy' cutting off a mans head... He looks at you and comes sprinting after you. What do you do? \nA) Run away screaming your head off. \nB) Stand your ground and try to protect you and your friends. \nC) Go try to get help."
  );

  function checkRumors() {
    if (rumors.toLowerCase() != "a" || rumors.toLowerCase() != "b" || rumors.toLowerCase() != "c") {
      alert("Please respond with 'a', 'b', or 'c'!");
      rumors = prompt(
          "Your friends tell you that rumors are circulating about 'Chain-Saw Billy' the new boogyman around town. He catches his victems and tortures them until death with his chainsaw. You and your buds hear a yell then a chainsaw starting up! \nYou look back and see 'Chain-Saw Billy' cutting off a mans head... He looks at you and comes sprinting after you. What do you do? \nA) Run away screaming your head off. \nB) Stand your ground and try to protect you and your friends. \nC) Go try to get help."
      );
    }
  }

  if (rumors.toLowerCase() === "b") {
      alert("Boy! You have the guts!");
  } else if(rumors.toLowerCase() === "a" || rumors.toLowerCase() === "c"){
      alert("Your cowardliness doesn't save you! He gets you! Sorry! \n \n BUT, you still manage to excape him!");
  } else {
    checkRumors();
  }

  function checkRunAfter() {
    if (runafter.toLowerCase() != "a" || runafter.toLowerCase() != "b" || runafter.toLowerCase() != "c") {
      alert("Please respond with 'a', 'b', or 'c'!");
      runafter = prompt(
          "You run home sprint up the stairs, jump under the bed and hide. You hear 'Chain-Saw Billy' capture your friend. What do you do? \nA) Get tired of all this stuff and suicide out the window. \nB) Choke yourself. \nC) Try to protect yourself with anything you can find."
      );
    }
  }

  var runafter = prompt(
      "You run home sprint up the stairs, jump under the bed and hide. You hear 'Chain-Saw Billy' capture your friend. What do you do? \nA) Get tired of all this stuff and suicide out the window. \nB) Choke yourself. \nC) Try to protect yourself with anything you can find."
  );

  if (runafter.toLowerCase() === "c") {
      alert("Sorry, you get killed in inexplicable ways");
  } else if (runafter.toLowerCase() === "a" || runafter.toLowerCase() === "b"){
      alert("You'd kill yourself?! Wow must be depressed! Please call the local Suicide Hotline!");
  } else {
    checkRunAfter();
  }

  function done(){
    alert("Thanks for playing this Adventure Game!");
  }

}
<|endoftext|>


<commit_before>//url from https://www.random.org which gives us random numbers through their APIs
//all parameters explained in http://api.jquery.com/jQuery.ajax/

var cells; //declare variable to be acessible everywhere
var player = 'pink';
var pink = 'pink';
var green = 'green';

//create a function to check if player won
function playerWon(events){

	var col = events.attr('x');
	var line = events.parent().attr('y');

	var win = true;

	for(i = 0; i < cells; i++){
		$('td[y=' + line + ']').hasClass(player);
		if( ! $('td[y=' + line + ']').hasClass(player) ){
			win = false;
		}

	}

	/*for(j = 0; j < cells; j++){
		var win = true;
		$('tr[x=' + col + ']').hasClass(player);
		if( ! $('td[x=' + col + ']').hasClass(player) ){
			win = false;
		}
	}*/

}

$(document).ready(function(){
	$.ajax({
		type: 'GET',
		url: 'https://www.random.org/integers/',
		data: {
			num:1,
			min: 3,
			max: 5,
			base: 10,
			col:1,
			base:10,
			format: 'plain'
		},
		error: function(xhr, errorcode){

		},
		success: function(data, code, xhr){
			cells = data; //our variable is now defined
			//append table data dynamically depending on the random number we get from the request. First append

			for(i = 0; i < cells; i++){
				y = i;
				$('table').append('

');
			}

			//then append
			for(j = 0; j < cells; j++){
				x = j; //give ids for all  and get coordinates for all
				$('tr').append('	');
			}

			//get all the clicks on all  and alternate colors depending on player
			$('td').click(function(ev){

				//add css color class
				$(ev.currentTarget).addClass(player);

				playerWon($(ev.currentTarget));

				if(player === 'pink'){
					player = green;
				} else {
					player = pink;
				}

			});

		}
	});

});

//callback function
/*
$(document).ready(function(){
	getParameters();
}); */<commit_msg>playerWon function<commit_after>//url from https://www.random.org which gives us random numbers through their APIs
//all parameters explained in http://api.jquery.com/jQuery.ajax/

var cells; //declare variable to be acessible everywhere
var player = 'pink';
var pink = 'pink';
var green = 'green';

//create a function to check if player won
function playerWon(events){

	var win;

	//check horizontal lines
	for(line = 0; line <cells; line++){
		win = true;
		for(col = 0; col < cells; col++){
			if( ! $('tr[data-y=' + line + '] > td[data-x=' + col + ']').hasClass(player) ){
				win = false;
				break;
			}
		}
		if (win == true){
			break;
		}
	}

	if(win == true){
		setTimeout(function(){
			alert('Winner');
		}, 100);
	}

	//check vertical lines
	for(col = 0; col <cells; col++){
		win = true;
		for(line = 0; line < cells; line++){
			if( ! $('tr[data-y=' + line + '] > td[data-x=' + col + ']').hasClass(player) ){
				win = false;
				break;
			}
		}
		if (win == true){
			break;
		}
	}

	if(win == true){
		setTimeout(function(){
			alert('Winner');
		}, 100);
	}
}

$(document).ready(function(){
	$.ajax({
		type: 'GET',
		url: 'https://www.random.org/integers/',
		data: {
			num:1,
			min: 3,
			max: 5,
			base: 10,
			col:1,
			base:10,
			format: 'plain'
		},
		error: function(xhr, errorcode){

		},
		success: function(data, code, xhr){
			cells = data; //our variable is now defined
			//append table data dynamically depending on the random number we get from the request. First append

			for(i = 0; i < cells; i++){
				y = i;
				$('table').append('

');
			}

			//then append
			for(j = 0; j < cells; j++){
				x = j; //give ids for all  and get coordinates for all
				$('tr').append('	');
			}

			//get all the clicks on all  and alternate colors depending on player
			$('td').click(function(ev){

				//add css color class
				$(ev.currentTarget).addClass(player);

				playerWon($(ev.currentTarget));

				if(player === 'pink'){
					player = green;
				} else {
					player = pink;
				}

			});

		}
	});

});

//callback function
/*
$(document).ready(function(){
	getParameters();
}); */<|endoftext|>


<commit_before>let app;
let listing = null;
let isAutomated = false;
let block = false;
let wordLoop = null;
let minerLoop = null;
let minerStatus = [
	{
		name: "shop-basic-miner",
		value: 0
	},
	{
		name: "shop-advanced-miner",
		value: 0
	},
	{
		name: "shop-mining-drill",
		value: 0
	},
	{
		name: "shop-data-center",
		value: 0
	},
	{
		name: "shop-bot-net",
		value: 0
	},
	{
		name: "shop-quantum-server",
		value: 0
	}
];

const ocrApiKey = "e3b7e80ac588957";
const db = "https://raw.githubusercontent.com/snollygolly/sourceio-automation/master/db.json";
const message = "papa bless, one love /r/javascript";
const frequency = 1250;
const minerLevel = 20;

app = {
	downloadListing: () => {
		$.get("https://raw.githubusercontent.com/snollygolly/sourceio-automation/master/db.json").done((data) => {
			listing = JSON.parse(data);
		});
	},

	exportListing: () => {
		console.log(JSON.stringify(listing, null, 2));
	},

	automate: () => {
		// first check the windows are open, and open them if they aren't
		if ($("#player-list").is(":visible") === false) {
			console.error("! Target list must be open");
			$("#desktop-list").children("img").click();
		}
		if ($("#window-shop").is(":visible") === false) {
			console.error("! Black market must be open");
			$("#desktop-shop").children("img").click();
		}
		isAutomated = true;
		// start by getting the first target in the list
		const targetName = $("#player-list").children("tr").eq(0)[0].innerText;
		console.log(`* Now attacking ${targetName}`);
		// click it, and then hack, and then port b
		$("#player-list").children("tr").eq(0)[0].click();
		$("#window-other-button").click();
		// do a check for money
		const portStyle = $("#window-other-port2").attr("style");
		if (portStyle.indexOf("opacity: 1") === -1) {
			// this port costs too much, let's wait a bit
			console.log("* Hack too expensive, waiting");
			setTimeout(app.automate, frequency);
		}
		$("#window-other-port2").click();
		// start the loop that does the guessing
		wordLoop = setInterval(app.loops.word, frequency);
		// start the loop for btc monitoring
		minerLoop = setInterval(app.loops.miner, frequency);
	},

	loops: {
		word: () => {
			if (block === true) {
				return;
			}
			if ($("#targetmessage-input").is(":visible") === true) {
				// we're done!
				$("#targetmessage-input").val(message);
				$("#targetmessage-button-send").click();
				app.restart();
				return;
			}
			app.go();
		},
		miner: () => {
			// first, get the status of our miners
			for (const miner of minerStatus) {
				// set value
				miner.value = parseInt($(`#${miner.name}-amount`).text());
				// this is available to buy
				if ($(`#${miner.name}`).attr("style") === "opacity: 1;") {
					if (miner.value < minerLevel) {
						// we should buy this
						$(`#${miner.name}`).click();
					}
				}
			}
		}
	},

	restart: () => {
		app.stop();
		app.automate();
	},

	stop: () => {
		if (wordLoop === null && minerLoop === null) {
			console.log("! No loops to stop");
			return;
		}
		isAutomated = false;
		block = false;
		clearInterval(wordLoop);
		clearInterval(minerLoop);
		wordLoop = null;
		console.log("* Stopped loop");
	},

	exportListing: () => {
		console.log(JSON.stringify(listing, null, 2));
	},

	go: () => {
		console.log("* Running 'go'");
		const wordLink = $(".tool-type-img").prop("src");
		if (listing.hasOwnProperty(wordLink) === true) {
			const word = listing[wordLink];
			console.log(`* Found word: [${word}]`);
			app.submit(word);
			return;
		}
		console.log("* Not seen, trying OCR...");
		app.ocr(wordLink);
	},

	submit: (word) => {
		$("#tool-type-word").val(word);
		$("#tool-type-word").submit();
	},

	learn: (word) => {
		const wordLink = $(".tool-type-img").prop("src");
		listing[wordLink] = word;
		app.submit(word);
	},

	ocr: (url) => {
		block = true;
		$.post("http://api.ocr.space/parse/image", {
			apikey: ocrApiKey,
			language: "eng",
			url: url
		}).done((data) => {
			const word = String(data["ParsedResults"][0]["ParsedText"]).trim().toLowerCase();
			if (word.length > 3) {
				console.log(`* Got data: [${word}]`);
				$("#tool-type-word").val(word);
				if (isAutomated === true) {
					app.learn(word);
					block = false;
				}
			} else {
				console.log("! OCR failed");
				app.restart();
			}
		});
	}
};
<commit_msg>broke out frequency for different loops, fixed too expensive backoff<commit_after>let app;
let listing = null;
let isAutomated = false;
let block = false;
let wordLoop = null;
let minerLoop = null;
let minerStatus = [
	{
		name: "shop-basic-miner",
		value: 0
	},
	{
		name: "shop-advanced-miner",
		value: 0
	},
	{
		name: "shop-mining-drill",
		value: 0
	},
	{
		name: "shop-data-center",
		value: 0
	},
	{
		name: "shop-bot-net",
		value: 0
	},
	{
		name: "shop-quantum-server",
		value: 0
	}
];

const ocrApiKey = "e3b7e80ac588957";
const db = "https://raw.githubusercontent.com/snollygolly/sourceio-automation/master/db.json";
const message = "papa bless, one love /r/javascript";
const wordFreq = 1250;
const mineFreq = 2000;
const minerLevel = 20;

app = {
	downloadListing: () => {
		$.get("https://raw.githubusercontent.com/snollygolly/sourceio-automation/master/db.json").done((data) => {
			listing = JSON.parse(data);
		});
	},

	exportListing: () => {
		console.log(JSON.stringify(listing, null, 2));
	},

	automate: () => {
		// first check the windows are open, and open them if they aren't
		if ($("#player-list").is(":visible") === false) {
			console.error("! Target list must be open");
			$("#desktop-list").children("img").click();
		}
		if ($("#window-shop").is(":visible") === false) {
			console.error("! Black market must be open");
			$("#desktop-shop").children("img").click();
		}
		isAutomated = true;
		// start by getting the first target in the list
		const targetName = $("#player-list").children("tr").eq(0)[0].innerText;
		console.log(`* Now attacking ${targetName}`);
		// click it, and then hack, and then port b
		$("#player-list").children("tr").eq(0)[0].click();
		$("#window-other-button").click();
		// do a check for money
		const portStyle = $("#window-other-port2").attr("style");
		if (portStyle.indexOf("opacity: 1") === -1) {
			// this port costs too much, let's wait a bit
			console.log("* Hack too expensive, waiting");
			setTimeout(app.automate, 1000);
			return;
		}
		$("#window-other-port2").click();
		// start the loop that does the guessing
		wordLoop = setInterval(app.loops.word, wordFreq);
		// start the loop for btc monitoring
		minerLoop = setInterval(app.loops.miner, mineFreq
		);
	},

	loops: {
		word: () => {
			if (block === true) {
				return;
			}
			if ($("#targetmessage-input").is(":visible") === true) {
				// we're done!
				$("#targetmessage-input").val(message);
				$("#targetmessage-button-send").click();
				app.restart();
				return;
			}
			app.go();
		},
		miner: () => {
			// first, get the status of our miners
			for (const miner of minerStatus) {
				// set value
				miner.value = parseInt($(`#${miner.name}-amount`).text());
				// this is available to buy
				if ($(`#${miner.name}`).attr("style") === "opacity: 1;") {
					if (miner.value < minerLevel) {
						// we should buy this
						$(`#${miner.name}`).click();
					}
				}
			}
		}
	},

	restart: () => {
		app.stop();
		app.automate();
	},

	stop: () => {
		if (wordLoop === null && minerLoop === null) {
			console.log("! No loops to stop");
			return;
		}
		isAutomated = false;
		block = false;
		clearInterval(wordLoop);
		clearInterval(minerLoop);
		wordLoop = null;
		console.log("* Stopped loop");
	},

	exportListing: () => {
		console.log(JSON.stringify(listing, null, 2));
	},

	go: () => {
		console.log("* Running 'go'");
		const wordLink = $(".tool-type-img").prop("src");
		if (listing.hasOwnProperty(wordLink) === true) {
			const word = listing[wordLink];
			console.log(`* Found word: [${word}]`);
			app.submit(word);
			return;
		}
		console.log("* Not seen, trying OCR...");
		app.ocr(wordLink);
	},

	submit: (word) => {
		$("#tool-type-word").val(word);
		$("#tool-type-word").submit();
	},

	learn: (word) => {
		const wordLink = $(".tool-type-img").prop("src");
		listing[wordLink] = word;
		app.submit(word);
	},

	ocr: (url) => {
		block = true;
		$.post("http://api.ocr.space/parse/image", {
			apikey: ocrApiKey,
			language: "eng",
			url: url
		}).done((data) => {
			const word = String(data["ParsedResults"][0]["ParsedText"]).trim().toLowerCase();
			if (word.length > 3) {
				console.log(`* Got data: [${word}]`);
				$("#tool-type-word").val(word);
				if (isAutomated === true) {
					app.learn(word);
					block = false;
				}
			} else {
				console.log("! OCR failed");
				app.restart();
			}
		});
	}
};
<|endoftext|>