<commit_before>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')

var rules = require('./rules')

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

slapp.message('start', ['mention', 'direct_message'], (msg) => {
  msg.say(rules.start_text)
})

slapp.message('^read (.*)', ['mention', 'direct_message'], (msg, text, entry ) => {
  var resp = ''
  switch(entry) {
    case 'r1':
      resp = rules.r1_text
      break;
    case 'r2':
      resp = rules.r2_text
      break;
    default:
      resp = 'Entry ${entry} not found'
  }

  msg.say(resp)
})

// var HELP_TEXT = `
// I will respond to the following messages:
// \`help\` - to see this message.
// \`hi\` - to demonstrate a conversation that tracks state.
// \`thanks\` - to demonstrate a simple response.
// \`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:.
// \`attachment\` - to see a Slack attachment message.
// `

// //*********************************************
// // Setup different handlers for messages
// //*********************************************

// // response to the user typing "help"
// slapp.message('help', ['mention', 'direct_message'], (msg) => {
//   msg.say(HELP_TEXT)
// })

// // "Conversation" flow that tracks state - kicks off when user says hi, hello or hey
// slapp
//   .message('^(hi|hello|hey)$', ['direct_mention', 'direct_message'], (msg, text) => {
//     msg
//       .say(`${text}, how are you?`)
//       // sends next event from user to this route, passing along state
//       .route('how-are-you', { greeting: text })
//   })
//   .route('how-are-you', (msg, state) => {
//     var text = (msg.body.event && msg.body.event.text) || ''

//     // user may not have typed text as their next action, ask again and re-route
//     if (!text) {
//       return msg
//         .say("Whoops, I'm still waiting to hear how you're doing.")
//         .say('How are you?')
//         .route('how-are-you', state)
//     }

//     // add their response to state
//     state.status = text

//     msg
//       .say(`Ok then. What's your favorite color?`)
//       .route('color', state)
//   })
//   .route('color', (msg, state) => {
//     var text = (msg.body.event && msg.body.event.text) || ''

//     // user may not have typed text as their next action, ask again and re-route
//     if (!text) {
//       return msg
//         .say("I'm eagerly awaiting to hear your favorite color.")
//         .route('color', state)
//     }

//     // add their response to state
//     state.color = text

//     msg
//       .say('Thanks for sharing.')
//       .say(`Here's what you've told me so far: \`\`\`${JSON.stringify(state)}\`\`\``)
//     // At this point, since we don't route anywhere, the "conversation" is over
//   })

// // Can use a regex as well
// slapp.message(/^(thanks|thank you)/i, ['mention', 'direct_message'], (msg) => {
//   // You can provide a list of responses, and a random one will be chosen
//   // You can also include slack emoji in your responses
//   msg.say([
//     "You're welcome :smile:",
//     'You bet',
//     ':+1: Of course',
//     'Anytime :sun_with_face: :full_moon_with_face:'
//   ])
// })

// // demonstrate returning an attachment...
// slapp.message('attachment', ['mention', 'direct_message'], (msg) => {
//   msg.say({
//     text: 'Check out this amazing attachment! :confetti_ball: ',
//     attachments: [{
//       text: 'Slapp is a robust open source library that sits on top of the Slack APIs',
//       title: 'Slapp Library - Open Source',
//       image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
//       title_link: 'https://beepboophq.com/',
//       color: '#7CD197'
//     }]
//   })
// })

// // Catch-all for any other responses not handled above
// slapp.message('.*', ['direct_mention', 'direct_message'], (msg) => {
//   // respond only 40% of the time
//   if (Math.random() < 0.4) {
//     msg.say([':wave:', ':pray:', ':raised_hands:'])
//   }
// })

// slapp.command('/choose', '(.*)', (msg, choice) => {
//   // `respond` is used for actions or commands and uses the `response_url` provided by the
//   // incoming request from Slack
//   msg.respond(choice)
// })

// attach Slapp to express server
var server = slapp.attachToExpress(express())

// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})
<commit_msg>Trying double quotes.<commit_after>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')

var rules = require('./rules')

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

slapp.message('start', ['mention', 'direct_message'], (msg) => {
  msg.say(rules.start_text)
})

slapp.message('^read (.*)', ['mention', 'direct_message'], (msg, text, entry ) => {
  var resp = ''
  switch(entry) {
    case 'r1':
      resp = rules.r1_text
      break;
    case 'r2':
      resp = rules.r2_text
      break;
    default:
      resp = "Entry ${entry} not found"
  }

  msg.say(resp)
})

// var HELP_TEXT = `
// I will respond to the following messages:
// \`help\` - to see this message.
// \`hi\` - to demonstrate a conversation that tracks state.
// \`thanks\` - to demonstrate a simple response.
// \`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:.
// \`attachment\` - to see a Slack attachment message.
// `

// //*********************************************
// // Setup different handlers for messages
// //*********************************************

// // response to the user typing "help"
// slapp.message('help', ['mention', 'direct_message'], (msg) => {
//   msg.say(HELP_TEXT)
// })

// // "Conversation" flow that tracks state - kicks off when user says hi, hello or hey
// slapp
//   .message('^(hi|hello|hey)$', ['direct_mention', 'direct_message'], (msg, text) => {
//     msg
//       .say(`${text}, how are you?`)
//       // sends next event from user to this route, passing along state
//       .route('how-are-you', { greeting: text })
//   })
//   .route('how-are-you', (msg, state) => {
//     var text = (msg.body.event && msg.body.event.text) || ''

//     // user may not have typed text as their next action, ask again and re-route
//     if (!text) {
//       return msg
//         .say("Whoops, I'm still waiting to hear how you're doing.")
//         .say('How are you?')
//         .route('how-are-you', state)
//     }

//     // add their response to state
//     state.status = text

//     msg
//       .say(`Ok then. What's your favorite color?`)
//       .route('color', state)
//   })
//   .route('color', (msg, state) => {
//     var text = (msg.body.event && msg.body.event.text) || ''

//     // user may not have typed text as their next action, ask again and re-route
//     if (!text) {
//       return msg
//         .say("I'm eagerly awaiting to hear your favorite color.")
//         .route('color', state)
//     }

//     // add their response to state
//     state.color = text

//     msg
//       .say('Thanks for sharing.')
//       .say(`Here's what you've told me so far: \`\`\`${JSON.stringify(state)}\`\`\``)
//     // At this point, since we don't route anywhere, the "conversation" is over
//   })

// // Can use a regex as well
// slapp.message(/^(thanks|thank you)/i, ['mention', 'direct_message'], (msg) => {
//   // You can provide a list of responses, and a random one will be chosen
//   // You can also include slack emoji in your responses
//   msg.say([
//     "You're welcome :smile:",
//     'You bet',
//     ':+1: Of course',
//     'Anytime :sun_with_face: :full_moon_with_face:'
//   ])
// })

// // demonstrate returning an attachment...
// slapp.message('attachment', ['mention', 'direct_message'], (msg) => {
//   msg.say({
//     text: 'Check out this amazing attachment! :confetti_ball: ',
//     attachments: [{
//       text: 'Slapp is a robust open source library that sits on top of the Slack APIs',
//       title: 'Slapp Library - Open Source',
//       image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
//       title_link: 'https://beepboophq.com/',
//       color: '#7CD197'
//     }]
//   })
// })

// // Catch-all for any other responses not handled above
// slapp.message('.*', ['direct_mention', 'direct_message'], (msg) => {
//   // respond only 40% of the time
//   if (Math.random() < 0.4) {
//     msg.say([':wave:', ':pray:', ':raised_hands:'])
//   }
// })

// slapp.command('/choose', '(.*)', (msg, choice) => {
//   // `respond` is used for actions or commands and uses the `response_url` provided by the
//   // incoming request from Slack
//   msg.respond(choice)
// })

// attach Slapp to express server
var server = slapp.attachToExpress(express())

// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})
<|endoftext|>


<commit_before>"use strict";

var fs = require('fs');
var util = require('util');
var events = require('events');
var fork = require('child_process').fork;
var _ = require('underscore');
var pad = require('./pad');

function Runner (node, opts, done) {

  var self = this;

  events.EventEmitter.call(this);

  this.node = node;
  this.opts = opts;

  // create a fake logger if none provided
  if(!this.opts.logger){
    this.opts.logger = {
      log: console.log
    };
  }

  this.child = null;

  // indicates node should be running, not actual state
  this.started = false;

  this.restarting = false;
  this.quitting = false;

  this.watch = true;

  this.startCallback = null;
  this.stopCallback = null;
  this.quitCallback = null;
  this.killedCallback = null;

  /*
   * create child process and initialize node in it
   */
  this.initialize = function(done) {

    // called on INITIALIZED from child process
    self.initializedCallback = done;

    self.child = fork(
      __dirname + '/run.js', [
        JSON.stringify(self.node),
        JSON.stringify(self.opts)
      ], {silent: true}
    );

    // add event handlers to child

    // child process dies unexpectedly
    self.child.on('exit', self.onChildExit);

    // childcommunicates with us
    self.child.on('message', self.onMessage);

    // child output
    self.child.stdout.on('data', self.onStdout);
    self.child.stderr.on('data', self.onStderr);
  };

  // handle child process exiting
  this.onChildExit = function(code) {

    self.opts.logger.log(
      'info',
      pad.timestamp(),
      'EXITED  ',
      pad.space(self.node.id, 20),
      code
    );

    self.child.removeAllListeners();
    self.child = null;

    if (self.killedCallback) {
      console.log('KILLED');
      return self.killedCallback();
    }

    // reboot node -- it died!
    if (!self.quitting) {
      self.initialize();
    }

  };

  this.onStdout = function(data){

    var s = data.toString().trim();

    if ( s === '') {
      return;
    }

    var x = s.split("\n");

    if (x.length === 0) {
      return;
    }

    var t = pad.timestamp();
    var log = [];
    for (var i=0, ii=x.length; i<ii; i++) {
      self.opts.logger.log(
        'info',
        t,
        'STDOUT  ',
        pad.space(self.node.id, 20),
        x[i]
      );
    }
  };

  this.onStderr = function(data){
    self.opts.logger.log(
      'info',
      pad.timestamp(),
      'STDERR  ',
      pad.space(self.node.id, 20),
      data.toString().trim()
    );
  };

  /*
   * methods for controlling child process
   */

  this.start = function(done) {
    // done called when STARTED message received child
    self.startedCallback = done;
    self.quitting = false;
    self.started = true;
    // tell node to start
    self.child.send('START');
  };

  // stop self-managed execution in node
  this.stop = function(done) {
    if (!self.child) {
      return done();
    }
    self.started = false;
    self.stoppedCallback = done;
    self.child.send('STOP');
  };

  // terminate child process
  this.quit = function(done) {
    if (!self.child) {
      return done();
    }
    self.quitCallback = done;
    self.started = false;
    self.quitting = true;
    if(self.child){
      self.child.send('QUIT');
    }
  };

  // force terminate child process
  this.kill = function(done) {
    if (!self.child ) {
      return done();
    }
    self.stoppedCallback = done;
    self.child.kill();
  };

  // restart node (creating a fresh child process and reloading code)
  // and ensure that if the node was started it gets started again
  // once reloaded
  this.restart = function(done) {
    if(self.started){
      self.restarting = true;
    }
    self.quit(function(){
      self.initialize(function(){
        if(self.restarting){
          self.restarting = false;
          self.start();
        }
      });
    });
  };

  // message received from child
  this.onMessage = function(data){
    // control messages are not stringified json

    //console.log('FROM NODE TO RUNNER GOT', data);

    if (data === 'INITIALIZED') {
      self.opts.logger.log(
        'info',
        pad.timestamp(),
        'INIT    ',
        self.node.id,
        self.child.pid
      );

      if (typeof self.initializedCallback === 'function'){
        self.initializedCallback(
          false, {
            pid:self.child.pid
          });
        self.initializedCallback = null;
      }
    }

    if (data === 'STARTED') {
      self.opts.logger.log(
        'info',
        pad.timestamp(),
        'STARTED ',
        self.node.id
      );
      if (typeof self.startedCallback === 'function'){
        self.startedCallback();
        self.startedCallback = null;
      }
    }

    if (data === 'STOPPED') {
      if (typeof self.stoppedCallback === 'function'){
        self.stoppedCallback();
        self.stoppedCallback = null;
      }
    }

    if (data === 'QUIT') {
      self.child.removeAllListeners();
      self.child.kill('SIGKILL');
      self.child.disconnect();
      self.child = null;
      if(self.quitCallback){
        self.quitCallback();
      }
    }

    // anything else is data

    self.opts.logger.log(
      'info',
      pad.timestamp(),
      'MESSAGE ',
      pad.space(self.node.id, 20), data);

    //self.emit('message', data );

  };

  this.onDisconnect = function() {

    // lost connection to the child node

    // if we were terminating it, then no problem
    self.opts.logger.log('info', pad.timestamp(),  'DISCONNECTED - STOPPED ', self.node.id);
    if ( self.stoppedCallback) {
      return self.stoppedCallback();
    }

    // if it was unexpected, start another one
    if (self.restarting) {
      self.opts.logger.log('info', pad.timestamp(),  'DISCONNECTED - RESTART ', self.node.id);
      self.restarting = false;
      self.initialize();
    }
  };

  if (this.watch){
    // fs.watch reports multiple times, so debounce this
    this.fileChanged = _.debounce(function (event, filename) {

      self.opts.logger.log(
        'info',
        pad.timestamp(),
        'CHANGED ',
        self.node.id
      );

      self.restart(function(){
        if(self.started){
          self.start(done);
        }
      });
    }, 100);

    // disable persistent so process doesn't start after being killed
    fs.watch (
      self.node.node,
      {persistent: false},
      this.fileChanged
    );
  }

  this.initialize(done);

}

util.inherits(Runner, events.EventEmitter);

module.exports = Runner;
<commit_msg>Ensure child is connected before telling it to quit<commit_after>"use strict";

var fs = require('fs');
var util = require('util');
var events = require('events');
var fork = require('child_process').fork;
var _ = require('underscore');
var pad = require('./pad');

function Runner (node, opts, done) {

  var self = this;

  events.EventEmitter.call(this);

  this.node = node;
  this.opts = opts;

  // create a fake logger if none provided
  if(!this.opts.logger){
    this.opts.logger = {
      log: console.log
    };
  }

  this.child = null;

  // indicates node should be running, not actual state
  this.started = false;

  this.restarting = false;
  this.quitting = false;

  this.watch = true;

  this.startCallback = null;
  this.stopCallback = null;
  this.quitCallback = null;
  this.killedCallback = null;

  /*
   * create child process and initialize node in it
   */
  this.initialize = function(done) {

    // called on INITIALIZED from child process
    self.initializedCallback = done;

    self.child = fork(
      __dirname + '/run.js', [
        JSON.stringify(self.node),
        JSON.stringify(self.opts)
      ], {silent: true}
    );

    // add event handlers to child

    // child process dies unexpectedly
    self.child.on('exit', self.onChildExit);

    // childcommunicates with us
    self.child.on('message', self.onMessage);

    // child output
    self.child.stdout.on('data', self.onStdout);
    self.child.stderr.on('data', self.onStderr);
  };

  // handle child process exiting
  this.onChildExit = function(code) {

    self.opts.logger.log(
      'info',
      pad.timestamp(),
      'EXITED  ',
      pad.space(self.node.id, 20),
      code
    );

    self.child.removeAllListeners();
    self.child = null;

    if (self.killedCallback) {
      console.log('KILLED');
      return self.killedCallback();
    }

    // reboot node -- it died!
    if (!self.quitting) {
      self.initialize();
    }

  };

  this.onStdout = function(data){

    var s = data.toString().trim();

    if ( s === '') {
      return;
    }

    var x = s.split("\n");

    if (x.length === 0) {
      return;
    }

    var t = pad.timestamp();
    var log = [];
    for (var i=0, ii=x.length; i<ii; i++) {
      self.opts.logger.log(
        'info',
        t,
        'STDOUT  ',
        pad.space(self.node.id, 20),
        x[i]
      );
    }
  };

  this.onStderr = function(data){
    self.opts.logger.log(
      'info',
      pad.timestamp(),
      'STDERR  ',
      pad.space(self.node.id, 20),
      data.toString().trim()
    );
  };

  /*
   * methods for controlling child process
   */

  this.start = function(done) {
    // done called when STARTED message received child
    self.startedCallback = done;
    self.quitting = false;
    self.started = true;
    // tell node to start
    self.child.send('START');
  };

  // stop self-managed execution in node
  this.stop = function(done) {
    if (!self.child) {
      return done();
    }
    self.started = false;
    self.stoppedCallback = done;
    self.child.send('STOP');
  };

  // terminate child process
  this.quit = function(done) {
    if (!self.child) {
      return done();
    }
    self.quitCallback = done;
    self.started = false;
    self.quitting = true;
    if(self.child && self.child.connected){
      self.child.send('QUIT');
    }
  };

  // force terminate child process
  this.kill = function(done) {
    if (!self.child ) {
      return done();
    }
    self.stoppedCallback = done;
    self.child.kill();
  };

  // restart node (creating a fresh child process and reloading code)
  // and ensure that if the node was started it gets started again
  // once reloaded
  this.restart = function(done) {
    if(self.started){
      self.restarting = true;
    }
    self.quit(function(){
      self.initialize(function(){
        if(self.restarting){
          self.restarting = false;
          self.start();
        }
      });
    });
  };

  // message received from child
  this.onMessage = function(data){
    // control messages are not stringified json

    //console.log('FROM NODE TO RUNNER GOT', data);

    if (data === 'INITIALIZED') {
      self.opts.logger.log(
        'info',
        pad.timestamp(),
        'INIT    ',
        self.node.id,
        self.child.pid
      );

      if (typeof self.initializedCallback === 'function'){
        self.initializedCallback(
          false, {
            pid:self.child.pid
          });
        self.initializedCallback = null;
      }
    }

    if (data === 'STARTED') {
      self.opts.logger.log(
        'info',
        pad.timestamp(),
        'STARTED ',
        self.node.id
      );
      if (typeof self.startedCallback === 'function'){
        self.startedCallback();
        self.startedCallback = null;
      }
    }

    if (data === 'STOPPED') {
      if (typeof self.stoppedCallback === 'function'){
        self.stoppedCallback();
        self.stoppedCallback = null;
      }
    }

    if (data === 'QUIT') {
      self.child.removeAllListeners();
      self.child.kill('SIGKILL');
      self.child.disconnect();
      self.child = null;
      if(self.quitCallback){
        self.quitCallback();
      }
    }

    // anything else is data

    self.opts.logger.log(
      'info',
      pad.timestamp(),
      'MESSAGE ',
      pad.space(self.node.id, 20), data);

    //self.emit('message', data );

  };

  this.onDisconnect = function() {

    // lost connection to the child node

    // if we were terminating it, then no problem
    self.opts.logger.log('info', pad.timestamp(),  'DISCONNECTED - STOPPED ', self.node.id);
    if ( self.stoppedCallback) {
      return self.stoppedCallback();
    }

    // if it was unexpected, start another one
    if (self.restarting) {
      self.opts.logger.log('info', pad.timestamp(),  'DISCONNECTED - RESTART ', self.node.id);
      self.restarting = false;
      self.initialize();
    }
  };

  if (this.watch){
    // fs.watch reports multiple times, so debounce this
    this.fileChanged = _.debounce(function (event, filename) {

      self.opts.logger.log(
        'info',
        pad.timestamp(),
        'CHANGED ',
        self.node.id
      );

      self.restart(function(){
        if(self.started){
          self.start(done);
        }
      });
    }, 100);

    // disable persistent so process doesn't start after being killed
    fs.watch (
      self.node.node,
      {persistent: false},
      this.fileChanged
    );
  }

  this.initialize(done);

}

util.inherits(Runner, events.EventEmitter);

module.exports = Runner;
<|endoftext|>


<commit_before>window.onload = function () {

  var alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
        'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
        't', 'u', 'v', 'w', 'x', 'y', 'z'];

  var categories;         // Array of topics
  var chosenCategory;     // Selected catagory
  var getHint ;          // Word getHint
  var word ;              // Selected word
  var guess ;             // Geuss
  var geusses = [ ];      // Stored geusses
  var lives ;             // Lives
  var counter ;           // Count correct geusses
  var space;              // Number of spaces in word '-'

  // Get elements
  var showLives = document.getElementById("mylives");
  var showCatagory = document.getElementById("scatagory");
  var getHint = document.getElementById("hint");
  var showClue = document.getElementById("clue");
  var audio = new Audio("sound.mp3");

  // create alphabet ul
  var buttons = function () {
    myButtons = document.getElementById('buttons');
    letters = document.createElement('ul');

    for (var i = 0; i < alphabet.length; i++) {
      letters.id = 'alphabet';
      list = document.createElement('li');
      list.id = 'letter';
      list.innerHTML = alphabet[i];
      check();
      myButtons.appendChild(letters);
      letters.appendChild(list);
    }
  }

  // Select Category
  var selectCat = function () {
    if (chosenCategory === categories[0]) {
      catagoryName.innerHTML = "The Chosen Category Is Premier League Football Teams";
    } else if (chosenCategory === categories[1]) {
      catagoryName.innerHTML = "The Chosen Category Is Films";
    } else if (chosenCategory === categories[2]) {
      catagoryName.innerHTML = "The Chosen Category Is Cities";
    }
  }

  // Create geusses ul
   result = function () {
    wordHolder = document.getElementById('hold');
    correct = document.createElement('ul');

    for (var i = 0; i < word.length; i++) {
      correct.setAttribute('id', 'my-word');
      guess = document.createElement('li');
      guess.setAttribute('class', 'guess');
      if (word[i] === "-") {
        guess.innerHTML = "-";
        space = 1;
      } else {
        guess.innerHTML = "_";
      }

      geusses.push(guess);
      wordHolder.appendChild(correct);
      correct.appendChild(guess);
    }
  }

  // Show lives
   comments = function () {
    showLives.innerHTML = "You have " + lives + " lives";
    if (lives < 1) {
      showLives.innerHTML = "Game Over";
    }
    for (var i = 0; i < geusses.length; i++) {
      if (counter + space === geusses.length) {
        showLives.innerHTML = "You Win!";
      }
    }
  }

      // Animate man
  var animate = function () {
    var drawMe = lives ;
    drawArray[drawMe]();
  }

   // Hangman
  canvas =  function(){

    myStickman = document.getElementById("stickman");
    context = myStickman.getContext('2d');
    context.beginPath();
    context.strokeStyle = "#fff";
    context.lineWidth = 2;
  };

    head = function(){
      myStickman = document.getElementById("stickman");
      context = myStickman.getContext('2d');
      context.beginPath();
      context.arc(60, 25, 10, 0, Math.PI*2, true);
      context.stroke();
    }

  draw = function($pathFromx, $pathFromy, $pathTox, $pathToy) {

    context.moveTo($pathFromx, $pathFromy);
    context.lineTo($pathTox, $pathToy);
    context.stroke();
    audio.play();

}

   frame1 = function() {
     draw (0, 150, 150, 150);
   };

   frame2 = function() {
     draw (10, 0, 10, 600);
   };

   frame3 = function() {
     draw (0, 5, 70, 5);
   };

   frame4 = function() {
     draw (60, 5, 60, 15);
   };

   torso = function() {
     draw (60, 36, 60, 70);
   };

   rightArm = function() {
     draw (60, 46, 100, 50);
   };

   leftArm = function() {
     draw (60, 46, 20, 50);
   };

   rightLeg = function() {
     draw (60, 70, 100, 100);
   };

   leftLeg = function() {
     draw (60, 70, 20, 100);
   };

  drawArray = [rightLeg, leftLeg, rightArm, leftArm,  torso,  head, frame4, frame3, frame2, frame1];

  // OnClick Function
   check = function () {
    list.onclick = function () {
      var geuss = (this.innerHTML);
      this.setAttribute("class", "active");
      this.onclick = null;
      for (var i = 0; i < word.length; i++) {
        if (word[i] === geuss) {
          geusses[i].innerHTML = geuss;
          counter += 1;
        }
      }
      var j = (word.indexOf(geuss));
      if (j === -1) {
        lives -= 1;
        comments();
        animate();
      } else {
        comments();
      }
    },

    document.onkeypress = function () {

      var key;
      var char;
      if (window.event)
              key = window.event.keyCode;
          else if (e)
              key = e.which;
          else
              return true;
      char = String.fromCharCode(key);
      console.log(char);

      this.setAttribute("class", "active");
      this.onkeyup = null;
      for (var i = 0; i < word.length; i++) {
        if (word[i] === char) {
          geusses[i].innerHTML = char;
          counter += 1;
        }
      }
      var j = (word.indexOf(geuss));
      if (j === -1) {
        lives -= 1;
        comments();
        animate();
      } else {
        comments();
      }
    }
  }

  // Play
  play = function () {
    categories = [
        ["everton", "liverpool", "swansea", "chelsea", "hull", "manchester-city", "newcastle-united"],
        ["alien", "dirty-harry", "gladiator", "finding-nemo", "jaws"],
        ["manchester", "milan", "madrid", "amsterdam", "prague"]
    ];

    chosenCategory = categories[Math.floor(Math.random() * categories.length)];
    word = chosenCategory[Math.floor(Math.random() * chosenCategory.length)];
    word = word.replace(/\s/g, "-");
    //console.log(word);
    buttons();

    geusses = [ ];
    lives = 10;
    counter = 0;
    space = 0;
    result();
    comments();
    selectCat();
    canvas();
  }

  play();

  // Hint

    hint.onclick = function() {

      hints = [
        ["Based in Mersyside", "Based in Mersyside", "First Welsh team to reach the Premier Leauge", "Owned by A russian Billionaire", "Once managed by Phil Brown", "2013 FA Cup runners up", "Gazza's first club"],
        ["Science-Fiction horror film", "1971 American action film", "Historical drama", "Anamated Fish", "Giant great white shark"],
        ["Northern city in the UK", "Home of AC and Inter", "Spanish capital", "Netherlands capital", "Czech Republic capital"]
    ];

    var catagoryIndex = categories.indexOf(chosenCategory);
    var hintIndex = chosenCategory.indexOf(word);
    showClue.innerHTML = "Clue: - " +  hints [catagoryIndex][hintIndex];
  };

   // Reset

  document.getElementById('reset').onclick = function() {
    correct.parentNode.removeChild(correct);
    letters.parentNode.removeChild(letters);
    showClue.innerHTML = "";
    context.clearRect(0, 0, 400, 400);
    play();
  }
}
<commit_msg>bugfix<commit_after>window.onload = function () {

  var alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
        'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
        't', 'u', 'v', 'w', 'x', 'y', 'z'];

  var categories;         // Array of topics
  var chosenCategory;     // Selected catagory
  var getHint ;          // Word getHint
  var word ;              // Selected word
  var guess ;             // Geuss
  var geusses = [ ];      // Stored geusses
  var lives ;             // Lives
  var counter ;           // Count correct geusses
  var space;              // Number of spaces in word '-'

  // Get elements
  var showLives = document.getElementById("mylives");
  var showCatagory = document.getElementById("scatagory");
  var getHint = document.getElementById("hint");
  var showClue = document.getElementById("clue");
  var audio = new Audio("sound.mp3");

  // create alphabet ul
  var buttons = function () {
    myButtons = document.getElementById('buttons');
    letters = document.createElement('ul');

    for (var i = 0; i < alphabet.length; i++) {
      letters.id = 'alphabet';
      list = document.createElement('li');
      list.id = 'letter';
      list.innerHTML = alphabet[i];
      check();
      myButtons.appendChild(letters);
      letters.appendChild(list);
    }
  };

  // Select Category
  var selectCat = function () {
    if (chosenCategory === categories[0]) {
      catagoryName.innerHTML = "The Chosen Category Is Premier League Football Teams";
    } else if (chosenCategory === categories[1]) {
      catagoryName.innerHTML = "The Chosen Category Is Films";
    } else if (chosenCategory === categories[2]) {
      catagoryName.innerHTML = "The Chosen Category Is Cities";
    }
  };

  // Create geusses ul
   result = function () {
    wordHolder = document.getElementById('hold');
    correct = document.createElement('ul');

    for (var i = 0; i < word.length; i++) {
      correct.setAttribute('id', 'my-word');
      guess = document.createElement('li');
      guess.setAttribute('class', 'guess');
      if (word[i] === "-") {
        guess.innerHTML = "-";
        space = 1;
      } else {
        guess.innerHTML = "_";
      }

      geusses.push(guess);
      wordHolder.appendChild(correct);
      correct.appendChild(guess);
    }
  };

  // Show lives
   comments = function () {
    showLives.innerHTML = "You have " + lives + " lives";
    if (lives < 1) {
      showLives.innerHTML = "Game Over";
    }
    for (var i = 0; i < geusses.length; i++) {
      if (counter + space === geusses.length) {
        showLives.innerHTML = "You Win!";
      }
    }
  };

      // Animate man
  var animate = function () {
    var drawMe = lives ;
    drawArray[drawMe]();
  };

   // Hangman
  canvas =  function(){

    myStickman = document.getElementById("stickman");
    context = myStickman.getContext('2d');
    context.beginPath();
    context.strokeStyle = "#fff";
    context.lineWidth = 2;
  };

    head = function(){
      myStickman = document.getElementById("stickman");
      context = myStickman.getContext('2d');
      context.beginPath();
      context.arc(60, 25, 10, 0, Math.PI*2, true);
      context.stroke();
    };

  draw = function($pathFromx, $pathFromy, $pathTox, $pathToy) {

    context.moveTo($pathFromx, $pathFromy);
    context.lineTo($pathTox, $pathToy);
    context.stroke();
    audio.play();

};

   frame1 = function() {
     draw (0, 150, 150, 150);
   };

   frame2 = function() {
     draw (10, 0, 10, 600);
   };

   frame3 = function() {
     draw (0, 5, 70, 5);
   };

   frame4 = function() {
     draw (60, 5, 60, 15);
   };

   torso = function() {
     draw (60, 36, 60, 70);
   };

   rightArm = function() {
     draw (60, 46, 100, 50);
   };

   leftArm = function() {
     draw (60, 46, 20, 50);
   };

   rightLeg = function() {
     draw (60, 70, 100, 100);
   };

   leftLeg = function() {
     draw (60, 70, 20, 100);
   };

  drawArray = [rightLeg, leftLeg, rightArm, leftArm,  torso,  head, frame4, frame3, frame2, frame1];

  // OnClick Function
   check = function () {
    list.onclick = function () {
      var geuss = (this.innerHTML);
      this.setAttribute("class", "active");
      this.onclick = null;
      for (var i = 0; i < word.length; i++) {
        if (word[i] === geuss) {
          geusses[i].innerHTML = geuss;
          counter += 1;
        }
      }
      var j = (word.indexOf(geuss));
      if (j === -1) {
        lives -= 1;
        comments();
        animate();
      } else {
        comments();
      }
    },

    document.onkeypress = function () {
      var key;
      var char;
      if (window.event)
              key = window.event.keyCode;
          else if (e)
              key = e.which;
          else
              return true;
      char = String.fromCharCode(key);
      console.log(char);

      this.setAttribute("class", "active");
      this.onkeyup = null;
      for (var i = 0; i < word.length; i++) {
        if (word[i] === char) {
          geusses[i].innerHTML = char;
          counter += 1;
        }
      }
      var j = (word.indexOf(geuss));
      if (j === -1) {
        lives -= 1;
        comments();
        animate();
      } else {
        comments();
      }
    }
  };

  // Play
  play = function () {
    categories = [
        ["everton", "liverpool", "swansea", "chelsea", "hull", "manchester-city", "newcastle-united"],
        ["alien", "dirty-harry", "gladiator", "finding-nemo", "jaws"],
        ["manchester", "milan", "madrid", "amsterdam", "prague"]
    ];

    chosenCategory = categories[Math.floor(Math.random() * categories.length)];
    word = chosenCategory[Math.floor(Math.random() * chosenCategory.length)];
    word = word.replace(/\s/g, "-");
    //console.log(word);
    buttons();

    geusses = [ ];
    lives = 10;
    counter = 0;
    space = 0;
    result();
    comments();
    selectCat();
    canvas();
  };

  play();

  // Hint

    hint.onclick = function() {

      hints = [
        ["Based in Mersyside", "Based in Mersyside", "First Welsh team to reach the Premier Leauge", "Owned by A russian Billionaire", "Once managed by Phil Brown", "2013 FA Cup runners up", "Gazza's first club"],
        ["Science-Fiction horror film", "1971 American action film", "Historical drama", "Anamated Fish", "Giant great white shark"],
        ["Northern city in the UK", "Home of AC and Inter", "Spanish capital", "Netherlands capital", "Czech Republic capital"]
    ];

    var catagoryIndex = categories.indexOf(chosenCategory);
    var hintIndex = chosenCategory.indexOf(word);
    showClue.innerHTML = "Clue: - " +  hints [catagoryIndex][hintIndex];
  };

   // Reset

  document.getElementById('reset').onclick = function() {
    correct.parentNode.removeChild(correct);
    letters.parentNode.removeChild(letters);
    showClue.innerHTML = "";
    context.clearRect(0, 0, 400, 400);
    play();
  };
};
<|endoftext|>


<commit_before>(function main() {

    var fs         = require('fs'),
        gulp       = require('gulp'),
        karma      = require('gulp-karma'),
        browserify = require('browserify'),
        babelify   = require('babelify');

    var compile = function(destPath, entryFile) {

        return browserify({ debug: true })
            .transform(babelify)
            .require(entryFile, { entry: true })
            .bundle()
            .on('error', function (model) { console.error(['Error:', model.message].join(' ')); })
            .pipe(fs.createWriteStream(destPath));

    };

    gulp.task('compile', function() {
        return compile('example/js/bundle.js', 'example/js/app.js');
    });

    gulp.task('karma', function() {

        return gulp.src([].concat('src/funkel.js', 'tests/*.test.js'))
            .pipe(karma({
                configFile: 'karma.conf.js',
                action: 'run'
            }))
            .on('error', function(err) { throw err; });

    });

    gulp.task('test', ['karma']);
    gulp.task('build', ['compile']);
    gulp.task('default', ['test', 'build']);

})();
<commit_msg>Added 'watch' task to Gulp<commit_after>(function main() {

    var fs         = require('fs'),
        gulp       = require('gulp'),
        karma      = require('gulp-karma'),
        browserify = require('browserify'),
        babelify   = require('babelify');

    var compile = function(destPath, entryFile) {

        return browserify({ debug: true })
            .transform(babelify)
            .require(entryFile, { entry: true })
            .bundle()
            .on('error', function (model) { console.error(['Error:', model.message].join(' ')); })
            .pipe(fs.createWriteStream(destPath));

    };

    gulp.task('compile', function() {
        return compile('example/js/bundle.js', 'example/js/app.js');
    });

    gulp.task('karma', function() {

        return gulp.src([].concat('src/funkel.js', 'tests/*.test.js'))
            .pipe(karma({
                configFile: 'karma.conf.js',
                action: 'run'
            }))
            .on('error', function(err) { throw err; });

    });

    gulp.task('test', ['karma']);
    gulp.task('build', ['compile']);
    gulp.task('default', ['test', 'build']);

    gulp.task('watch', function watch() {
        return gulp.watch(['example/js/app.js', 'src/Keo.js'. 'tests/components/Gremlin.js'], ['build']);
    });

})();
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOMServer from 'react-dom/server';
import {Html} from '~/src/server/components/Html';

function makeHtml(initialState, content){
  return ReactDOMServer.renderToString(
    <Html
      title={'Evaluation App'}
      initialState={initialState}
      headScripts={['/head.js']}
      bodyScripts={['/body.js']}
    >
      {content}
    </Html>
  );
}

export default function(){
  return function *(next){
    const { routeContext } = this;
    const html = makeHtml(
      {},
      routeContext
    )
    this.response.body = `<!doctype html>${html}`;
  }
}
<commit_msg>fixed title of html doc<commit_after>import React from 'react';
import ReactDOMServer from 'react-dom/server';
import {Html} from '~/src/server/components/Html';

function makeHtml(initialState, content){
  return ReactDOMServer.renderToString(
    <Html
      title={'Breko Hub'}
      initialState={initialState}
      headScripts={['/head.js']}
      bodyScripts={['/body.js']}
    >
      {content}
    </Html>
  );
}

export default function(){
  return function *(next){
    const { routeContext } = this;
    const html = makeHtml(
      {},
      routeContext
    )
    this.response.body = `<!doctype html>${html}`;
  }
}
<|endoftext|>


<commit_before>/**
 * This leverages Express to create and run the http server.
 * A Fluxible context is created and executes the navigateAction
 * based on the URL. Once completed, the store state is dehydrated
 * and the application is rendered via React.
 */
import express from 'express';
import favicon from 'serve-favicon';
import serialize from 'serialize-javascript';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import csrf from 'csurf';
import compression from 'compression';
import debugLib from 'debug';
import path from 'path';
import {navigateAction} from 'fluxible-router';
import React from 'react';
import ReactDOM from 'react-dom/server';
import app from './app';
import HTMLComponent from './components/DefaultHTMLLayout';
import { createElementWithContext } from 'fluxible-addons-react';
import logger from './configs/log';

const env = process.env.NODE_ENV;
// So we can check whether we are in the browser or not.  Required for webpack-load-css
//otherwise it will try and transpile CSS into JavaScript.
process.env.BROWSER = false;

const debug = debugLib('slidewiki-platform');

const server = express();
server.use(cookieParser());
server.use(bodyParser.json({limit: '50mb'}));
server.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
server.use(compression());
server.use(favicon(path.join(__dirname, '/favicon.ico')));
server.use('/public', express.static (path.join(__dirname, '/build')));
server.use('/custom_modules', express.static (path.join(__dirname, '/custom_modules')));
server.use('/assets', express.static (path.join(__dirname, '/assets')));
//server.use('/bower_components', express.static (path.join(__dirname, '/bower_components')));
//add external dependencies to be loaded on frontend here:
server.use('/json3', express.static(path.join(__dirname, '/node_modules/json3')));
server.use('/es5-shim', express.static(path.join(__dirname, '/node_modules/es5-shim')));
server.use('/es6-shim', express.static(path.join(__dirname, '/node_modules/es6-shim')));
server.use('/jquery', express.static(path.join(__dirname, '/node_modules/jquery')));
server.use('/sweetalert2', express.static(path.join(__dirname, '/node_modules/sweetalert2')));
server.use('/headjs', express.static(path.join(__dirname, '/node_modules/headjs')));

//server.use(csrf({cookie: true}));
// Get access to the fetchr plugin instance
let fetchrPlugin = app.getPlugin('FetchrPlugin');

// Set up the fetchr middleware
server.use(fetchrPlugin.getXhrPath(), fetchrPlugin.getMiddleware());

// Register our services
fetchrPlugin.registerService(require('./services/contributors'));
fetchrPlugin.registerService(require('./services/deck'));
fetchrPlugin.registerService(require('./services/slide'));
fetchrPlugin.registerService(require('./services/datasource'));
fetchrPlugin.registerService(require('./services/activities'));
fetchrPlugin.registerService(require('./services/decktree'));
fetchrPlugin.registerService(require('./services/translation'));
fetchrPlugin.registerService(require('./services/history'));
fetchrPlugin.registerService(require('./services/usage'));
fetchrPlugin.registerService(require('./services/questions'));
fetchrPlugin.registerService(require('./services/discussion'));
fetchrPlugin.registerService(require('./services/similarcontent'));
fetchrPlugin.registerService(require('./services/import'));
fetchrPlugin.registerService(require('./services/presentation'));
fetchrPlugin.registerService(require('./services/notifications'));
fetchrPlugin.registerService(require('./services/user'));
fetchrPlugin.registerService(require('./services/searchresults'));
fetchrPlugin.registerService(require('./services/userProfile'));
fetchrPlugin.registerService(require('./services/suggester'));

server.use((req, res, next) => {

    const context =  app.createContext({
        req: req,
        res: res  //for userStoragePlugin
        //, // The fetchr plugin depends on this
        //xhrContext: {
        //    _csrf: req.csrfToken() // Make sure all XHR requests have the CSRF token
        //}
    });
    logger.debug('hello world from server.js');
    debug('Executing navigate action');
    context.getActionContext().executeAction(navigateAction, {
        url: req.url
    }, (err) => {
        if (err) {
            //console.log(req.url, err);//, err);
            if (err.statusCode && err.statusCode === 404) {
                // TODO refector the code in this if-else block
                const exposed = 'window.App=' + serialize(app.dehydrate(context)) + ';';
                debug('Rendering Application component into html');
                const markup = ReactDOM.renderToString(createElementWithContext(context));
                //todo: for future, we can choose to not include specific scripts in some predefined layouts
                const htmlElement = React.createElement(HTMLComponent, {
                    clientFile: 'main.js',
                    addAssets: (env === 'production'),
                    context: context.getComponentContext(),
                    state: exposed,
                    markup: markup
                });
                const html = ReactDOM.renderToStaticMarkup(htmlElement);
                debug('Sending markup');
                res.type('html');
                res.status(err.statusCode).send('<!DOCTYPE html>' + html);
                // Pass through to next middleware
                //next();
            } else {
                const exposed = 'window.App=' + serialize(app.dehydrate(context)) + ';';
                debug('Rendering Application component into html');
                const markup = ReactDOM.renderToString(createElementWithContext(context));
                //todo: for future, we can choose to not include specific scripts in some predefined layouts
                const htmlElement = React.createElement(HTMLComponent, {
                    clientFile: 'main.js',
                    addAssets: (env === 'production'),
                    context: context.getComponentContext(),
                    state: exposed,
                    markup: markup
                });
                const html = ReactDOM.renderToStaticMarkup(htmlElement);
                debug('Sending markup');
                res.type('html');
                res.status(err.statusCode).send('<!DOCTYPE html>' + html);
                //next(err);
            }
            return;
        }

        debug('Exposing context state');
        const exposed = 'window.App=' + serialize(app.dehydrate(context)) + ';';

        debug('Rendering Application component into html');
        const markup = ReactDOM.renderToString(createElementWithContext(context));
        //todo: for future, we can choose to not include specific scripts in some predefined layouts
        const htmlElement = React.createElement(HTMLComponent, {
            //clientFile: env === 'production' ? 'main.min.js' : 'main.js',
            clientFile: 'main.js',
            addAssets: (env === 'production'),
            context: context.getComponentContext(),
            state: exposed,
            markup: markup
        });
        const html = ReactDOM.renderToStaticMarkup(htmlElement);

        debug('Sending markup');
        res.type('html');
        res.write('<!DOCTYPE html>' + html);
        res.end();
    });
});

const port = process.env.PORT || 3000;
server.listen(port);
console.log('SlideWiki Platform is now Listening on port ' + port);

export default server;
<commit_msg>Adding support for reqId for distributed log tracking<commit_after>/**
 * This leverages Express to create and run the http server.
 * A Fluxible context is created and executes the navigateAction
 * based on the URL. Once completed, the store state is dehydrated
 * and the application is rendered via React.
 */
import express from 'express';
import favicon from 'serve-favicon';
import serialize from 'serialize-javascript';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import csrf from 'csurf';
import compression from 'compression';
import debugLib from 'debug';
import path from 'path';
import {navigateAction} from 'fluxible-router';
import React from 'react';
import ReactDOM from 'react-dom/server';
import app from './app';
import HTMLComponent from './components/DefaultHTMLLayout';
import { createElementWithContext } from 'fluxible-addons-react';
import { logger } from './configs/log';
const uuid = require('node-uuid');

const env = process.env.NODE_ENV;
// So we can check whether we are in the browser or not.  Required for webpack-load-css
//otherwise it will try and transpile CSS into JavaScript.
process.env.BROWSER = false;

const debug = debugLib('slidewiki-platform');

const server = express();
server.use(cookieParser());
server.use(bodyParser.json({limit: '50mb'}));
server.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
server.use(compression());
server.use(favicon(path.join(__dirname, '/favicon.ico')));
server.use('/public', express.static (path.join(__dirname, '/build')));
server.use('/custom_modules', express.static (path.join(__dirname, '/custom_modules')));
server.use('/assets', express.static (path.join(__dirname, '/assets')));
//server.use('/bower_components', express.static (path.join(__dirname, '/bower_components')));
//add external dependencies to be loaded on frontend here:
server.use('/json3', express.static(path.join(__dirname, '/node_modules/json3')));
server.use('/es5-shim', express.static(path.join(__dirname, '/node_modules/es5-shim')));
server.use('/es6-shim', express.static(path.join(__dirname, '/node_modules/es6-shim')));
server.use('/jquery', express.static(path.join(__dirname, '/node_modules/jquery')));
server.use('/sweetalert2', express.static(path.join(__dirname, '/node_modules/sweetalert2')));
server.use('/headjs', express.static(path.join(__dirname, '/node_modules/headjs')));

//server.use(csrf({cookie: true}));
// Get access to the fetchr plugin instance
let fetchrPlugin = app.getPlugin('FetchrPlugin');

// Set up the fetchr middleware
server.use(fetchrPlugin.getXhrPath(), fetchrPlugin.getMiddleware());

// Register our services
fetchrPlugin.registerService(require('./services/contributors'));
fetchrPlugin.registerService(require('./services/deck'));
fetchrPlugin.registerService(require('./services/slide'));
fetchrPlugin.registerService(require('./services/datasource'));
fetchrPlugin.registerService(require('./services/activities'));
fetchrPlugin.registerService(require('./services/decktree'));
fetchrPlugin.registerService(require('./services/translation'));
fetchrPlugin.registerService(require('./services/history'));
fetchrPlugin.registerService(require('./services/usage'));
fetchrPlugin.registerService(require('./services/questions'));
fetchrPlugin.registerService(require('./services/discussion'));
fetchrPlugin.registerService(require('./services/similarcontent'));
fetchrPlugin.registerService(require('./services/import'));
fetchrPlugin.registerService(require('./services/presentation'));
fetchrPlugin.registerService(require('./services/notifications'));
fetchrPlugin.registerService(require('./services/user'));
fetchrPlugin.registerService(require('./services/searchresults'));
fetchrPlugin.registerService(require('./services/userProfile'));
fetchrPlugin.registerService(require('./services/suggester'));

server.use((req, res, next) => {
    req.reqId = uuid.v4();
    logger.info({reqId: req.reqId, requested: req.url, from: req.ip, hostname: req.hostname});
    const context =  app.createContext({
        req: req,
        res: res  //for userStoragePlugin
        //, // The fetchr plugin depends on this
        //xhrContext: {
        //    _csrf: req.csrfToken() // Make sure all XHR requests have the CSRF token
        //}
    });
    debug('Executing navigate action');
    context.getActionContext().executeAction(navigateAction, {url: req.url, reqId: req.reqId}, (err) => {
        if (err) {
            logger.error({reqId: req.reqId, err: err});
            if (err.statusCode && err.statusCode === 404) {
                // TODO refector the code in this if-else block
                const exposed = 'window.App=' + serialize(app.dehydrate(context)) + ';';
                debug('Rendering Application component into html');
                const markup = ReactDOM.renderToString(createElementWithContext(context));
                //todo: for future, we can choose to not include specific scripts in some predefined layouts
                const htmlElement = React.createElement(HTMLComponent, {
                    clientFile: 'main.js',
                    addAssets: (env === 'production'),
                    context: context.getComponentContext(),
                    state: exposed,
                    markup: markup
                });
                const html = ReactDOM.renderToStaticMarkup(htmlElement);
                debug('Sending markup');
                res.type('html');
                res.status(err.statusCode);
                logger.info({reqId: req.reqId, responded: req.url, statusCode: res.statusCode});
                res.write('<!DOCTYPE html>' + html);
                res.end();
            } else {
                const exposed = 'window.App=' + serialize(app.dehydrate(context)) + ';';
                debug('Rendering Application component into html');
                const markup = ReactDOM.renderToString(createElementWithContext(context));
                //todo: for future, we can choose to not include specific scripts in some predefined layouts
                const htmlElement = React.createElement(HTMLComponent, {
                    clientFile: 'main.js',
                    addAssets: (env === 'production'),
                    context: context.getComponentContext(),
                    state: exposed,
                    markup: markup
                });
                const html = ReactDOM.renderToStaticMarkup(htmlElement);
                debug('Sending markup');
                res.type('html');
                res.status(err.statusCode);
                logger.info({reqId: req.reqId, responded: req.url, statusCode: res.statusCode});
                res.write('<!DOCTYPE html>' + html);
                res.end();
            }
            return;
        }

        debug('Exposing context state');
        const exposed = 'window.App=' + serialize(app.dehydrate(context)) + ';';

        debug('Rendering Application component into html');
        const markup = ReactDOM.renderToString(createElementWithContext(context));
        //todo: for future, we can choose to not include specific scripts in some predefined layouts
        const htmlElement = React.createElement(HTMLComponent, {
            //clientFile: env === 'production' ? 'main.min.js' : 'main.js',
            clientFile: 'main.js',
            addAssets: (env === 'production'),
            context: context.getComponentContext(),
            state: exposed,
            markup: markup
        });
        const html = ReactDOM.renderToStaticMarkup(htmlElement);

        debug('Sending markup');
        res.type('html');
        res.write('<!DOCTYPE html>' + html);
        logger.info({reqId: req.reqId, responded: req.url, statusCode: res.statusCode});
        res.end();
    });
});

const port = process.env.PORT || 3000;
server.listen(port);
logger.info('SlideWiki Platform is now Listening on port ' + port);

export default server;
<|endoftext|>


<commit_before>'use strict';

const EventEmitter = require('events').EventEmitter;
const _ = require('lodash');
const debug = require('debug')('runner');
const debugPerf = require('debug')('perf');
const Measured = require('measured');
const Stats = require('./stats');
const JSCK = require('jsck');
const createPhaser = require('./phases');
const engineUtil = require('./engine_util');
const wl = require('./weighted-pick');

const Engines = {
  http: {},
  ws: {}
};

JSCK.Draft4 = JSCK.draft4;

const schema = new JSCK.Draft4(require('./schemas/minigun_test_script.json'));

module.exports = {
  runner: runner,
  validate: validate
};

// Only one runner can execute at a time when used as a library.

let pendingRequests = new Measured.Counter();
let pendingScenarios = new Measured.Counter();
let cancelledRequests = new Measured.Counter();

let compiledScenarios;
let scenarioEvents;
let picker;

let Report = {
  intermediate: [],
  aggregate: {}
};

let plugins = [];
let engines = [];

function validate(script) {
  let validation = schema.validate(script);
  return validation;
}

function runner(script, payload, options) {

  let opts = _.assign({
    periodicStats: script.config.statsInterval || 10,
    mode: script.config.mode || 'uniform'
  },
  options);

  _.each(script.config.phases, function(phaseSpec) {
    phaseSpec.mode = phaseSpec.mode || script.config.mode;
  });

  if (payload) {
    if (_.isArray(payload[0])) {
      script.config.payload = [
        {
          fields: script.config.payload.fields,
          data: payload
        }
      ];
    } else {
      script.config.payload = payload;
    }
  }

  let runnableScript = _.cloneDeep(script);

  if (opts.environment) {
    _.merge(
      runnableScript.config,
      script.config.environments[opts.environment]);
  }

  compiledScenarios = null;
  scenarioEvents = null;

  let ee = new EventEmitter();

  //
  // load engines:
  //
  engines = _.map(Object.assign({}, Engines, script.config.engines),
    function loadEngine(engineConfig, engineName) {
      let moduleName = 'minigun-engine-' + engineName;
      try {
        if (Engines[engineName]) {
          moduleName = './engine_' + engineName;
        }
        let Engine = require(moduleName);
        let engine = new Engine(script.config, ee);
        engine.__name = engineName;
        return engine;
      } catch (e) {
        console.log(
          'WARNING: engine %s specified but module %s could not be loaded',
          engineName,
          moduleName);
      }
    });

  //
  // load plugins:
  //
  plugins = _.map(script.config.plugins,
    function loadPlugin(pluginConfig, pluginName) {
      let moduleName = 'minigun-plugin-' + pluginName;
      try {
        let Plugin = require(moduleName);
        let plugin = new Plugin(script.config, ee);
        plugin.__name = pluginName;
        return plugin;
      } catch (e) {
        console.log(
          'WARNING: plugin %s specified but module %s could not be loaded',
          pluginName,
          moduleName);
      }
    });

  ee.run = function() {
    run(runnableScript, ee, opts);
  };
  return ee;
}

function run(script, ee, options) {
  let intermediate = Stats.create();
  let aggregate = Stats.create();

  let phaser = createPhaser(script.config.phases);
  phaser.on('arrival', function() {
    runScenario(script, intermediate, aggregate);
  });
  phaser.on('phaseStarted', function(spec) {
    ee.emit('phaseStarted', spec);
  });
  phaser.on('phaseCompleted', function(spec) {
    ee.emit('phaseCompleted', spec);
  });
  phaser.on('done', function() {
    debug('All phases launched');

    const doneYet = setInterval(function checkIfDone() {
      if (pendingScenarios.toJSON() === 0) {
        if (pendingRequests.toJSON() !== 0) {
          debug('DONE. Pending requests: %s', pendingRequests.toJSON());
        }

        Report.aggregate = aggregate.report();
        clearInterval(doneYet);
        clearInterval(periodicStatsTimer);
        intermediate.free();
        aggregate.free();

        //
        // Add plugin reports to the final report
        //
        _.each(plugins, function(plugin) {
          if (typeof plugin.report === 'function') {
            let report = plugin.report();
            if (report) {
              if (report.length) {
                _.each(report, function insertIntermediateReport(a) {
                  if (a.timestamp === 'aggregate') {
                    Report.aggregate[plugin.__name] = a.value;
                  } else {
                    let ir = _.findWhere(
                      Report.intermediate,
                      {timestamp: a.timestamp});
                    ir[plugin.__name] = a.value;
                  }
                });
              } else {
                Report.aggregate[plugin.__name] = report;
              }
            }
          }
        });

        return ee.emit('done', Report);
      } else {
        debug('Pending requests: %s', pendingRequests.toJSON());
        debug('Pending scenarios: %s', pendingScenarios.toJSON());
      }
    }, 500);
  });

  const periodicStatsTimer = setInterval(function() {
    const report = intermediate.report();
    Report.intermediate.push(report);
    intermediate.reset();
    ee.emit('stats', report);
  }, options.periodicStats * 1000);

  phaser.run();
}

function runScenario(script, intermediate, aggregate) {
  const start = process.hrtime();

  //
  // Compile scenarios if needed
  //
  if (!compiledScenarios) {
    _.each(script.scenarios, function(scenario) {
      if (!scenario.weight) {
        scenario.weight = 1;
      }
    });

    picker = wl(script.scenarios);

    scenarioEvents = new EventEmitter();
    scenarioEvents.on('started', function() {
      pendingScenarios.inc();
    });
    scenarioEvents.on('error', function(errCode) {
      intermediate.addError(errCode);
      aggregate.addError(errCode);
    });
    scenarioEvents.on('request', function() {
      intermediate.newRequest();
      aggregate.newRequest();

      pendingRequests.inc();
    });
    scenarioEvents.on('match', function() {
      intermediate.addMatch();
      aggregate.addMatch();
    });
    scenarioEvents.on('response', function(delta, code) {
      intermediate.completedRequest();
      intermediate.addLatency(delta);
      intermediate.addCode(code);

      aggregate.completedRequest();
      aggregate.addLatency(delta);
      aggregate.addCode(code);

      pendingRequests.dec();
    });

    compiledScenarios = _.map(script.scenarios, function(scenarioSpec) {
      const name = scenarioSpec.engine || 'http';
      const engine = engines.find((e) => e.__name === name);
      let tasks = _.map(scenarioSpec.flow, rs => {
        if (rs.think) {
          return engineUtil.createThink(rs);
        }
        return engine.step(rs, scenarioEvents);
      });
      return engine.compile(
        tasks,
        scenarioSpec.flow,
        scenarioEvents
        );
    });
  }

  intermediate.newScenario();
  aggregate.newScenario();

  let i = picker()[0];

  debug('picking scenario %s (%s) weight = %s',
        i,
        script.scenarios[i].name,
        script.scenarios[i].weight);

  const scenarioStartedAt = process.hrtime();
  const scenarioContext = createContext(script);
  const finish = process.hrtime(start);
  const runScenarioDelta = (finish[0] * 1e9) + finish[1];
  debugPerf('runScenarioDelta: %s', Math.round(runScenarioDelta / 1e6 * 100) / 100);
  compiledScenarios[i](scenarioContext, function(err, context) {
    pendingScenarios.dec();
    if (err) {
      debug(err);
      //debug('Scenario aborted due to error');
      cancelledRequests.inc(context._pendingRequests);
    } else {
      //debug('Scenario completed');
      //debug(context);
      const scenarioFinishedAt = process.hrtime(scenarioStartedAt);
      const delta = (scenarioFinishedAt[0] * 1e9) + scenarioFinishedAt[1];
      intermediate.addScenarioLatency(delta);
      aggregate.addScenarioLatency(delta);
      intermediate.completedScenario();
      aggregate.completedScenario();
    }
  });
}

/**
 * Create initial context for a scenario.
 */
function createContext(script) {
  const INITIAL_CONTEXT = {
    vars: {
      target: script.config.target
    },
    funcs: {
      $randomNumber: $randomNumber,
      $randomString: $randomString
    }
  };
  let result = _.cloneDeep(INITIAL_CONTEXT);

  //
  // variables from payloads
  //
  if (script.config.payload) {
    _.each(script.config.payload, function(el) {
      let i = _.random(0, el.data.length - 1);
      let row = el.data[i];
      _.each(el.fields, function(fieldName, j) {
        result.vars[fieldName] = row[j];
      });
    });
  }

  //
  // inline variables
  //
  if (script.config.variables) {
    _.each(script.config.variables, function(v, k) {
      let val;
      if (_.isArray(v)) {
        val = _.sample(v);
      } else {
        val = v;
      }
      result.vars[k] = val;
    });
  }
  return result;
}

//
// Generator functions for template strings:
//
function $randomNumber(min, max) {
  return _.random(min, max);
}

function $randomString(length) {
  return Math.random().toString(36).substr(2, length);
}
<commit_msg>Fix: error when no payload is passed in from the CLI<commit_after>'use strict';

const EventEmitter = require('events').EventEmitter;
const _ = require('lodash');
const debug = require('debug')('runner');
const debugPerf = require('debug')('perf');
const Measured = require('measured');
const Stats = require('./stats');
const JSCK = require('jsck');
const createPhaser = require('./phases');
const engineUtil = require('./engine_util');
const wl = require('./weighted-pick');

const Engines = {
  http: {},
  ws: {}
};

JSCK.Draft4 = JSCK.draft4;

const schema = new JSCK.Draft4(require('./schemas/minigun_test_script.json'));

module.exports = {
  runner: runner,
  validate: validate
};

// Only one runner can execute at a time when used as a library.

let pendingRequests = new Measured.Counter();
let pendingScenarios = new Measured.Counter();
let cancelledRequests = new Measured.Counter();

let compiledScenarios;
let scenarioEvents;
let picker;

let Report = {
  intermediate: [],
  aggregate: {}
};

let plugins = [];
let engines = [];

function validate(script) {
  let validation = schema.validate(script);
  return validation;
}

function runner(script, payload, options) {

  let opts = _.assign({
    periodicStats: script.config.statsInterval || 10,
    mode: script.config.mode || 'uniform'
  },
  options);

  _.each(script.config.phases, function(phaseSpec) {
    phaseSpec.mode = phaseSpec.mode || script.config.mode;
  });

  if (payload) {
    if (_.isArray(payload[0])) {
      script.config.payload = [
        {
          fields: script.config.payload.fields,
          data: payload
        }
      ];
    } else {
      script.config.payload = payload;
    }
  } else {
    script.config.payload = null;
  }

  let runnableScript = _.cloneDeep(script);

  if (opts.environment) {
    _.merge(
      runnableScript.config,
      script.config.environments[opts.environment]);
  }

  compiledScenarios = null;
  scenarioEvents = null;

  let ee = new EventEmitter();

  //
  // load engines:
  //
  engines = _.map(Object.assign({}, Engines, script.config.engines),
    function loadEngine(engineConfig, engineName) {
      let moduleName = 'minigun-engine-' + engineName;
      try {
        if (Engines[engineName]) {
          moduleName = './engine_' + engineName;
        }
        let Engine = require(moduleName);
        let engine = new Engine(script.config, ee);
        engine.__name = engineName;
        return engine;
      } catch (e) {
        console.log(
          'WARNING: engine %s specified but module %s could not be loaded',
          engineName,
          moduleName);
      }
    });

  //
  // load plugins:
  //
  plugins = _.map(script.config.plugins,
    function loadPlugin(pluginConfig, pluginName) {
      let moduleName = 'minigun-plugin-' + pluginName;
      try {
        let Plugin = require(moduleName);
        let plugin = new Plugin(script.config, ee);
        plugin.__name = pluginName;
        return plugin;
      } catch (e) {
        console.log(
          'WARNING: plugin %s specified but module %s could not be loaded',
          pluginName,
          moduleName);
      }
    });

  ee.run = function() {
    run(runnableScript, ee, opts);
  };
  return ee;
}

function run(script, ee, options) {
  let intermediate = Stats.create();
  let aggregate = Stats.create();

  let phaser = createPhaser(script.config.phases);
  phaser.on('arrival', function() {
    runScenario(script, intermediate, aggregate);
  });
  phaser.on('phaseStarted', function(spec) {
    ee.emit('phaseStarted', spec);
  });
  phaser.on('phaseCompleted', function(spec) {
    ee.emit('phaseCompleted', spec);
  });
  phaser.on('done', function() {
    debug('All phases launched');

    const doneYet = setInterval(function checkIfDone() {
      if (pendingScenarios.toJSON() === 0) {
        if (pendingRequests.toJSON() !== 0) {
          debug('DONE. Pending requests: %s', pendingRequests.toJSON());
        }

        Report.aggregate = aggregate.report();
        clearInterval(doneYet);
        clearInterval(periodicStatsTimer);
        intermediate.free();
        aggregate.free();

        //
        // Add plugin reports to the final report
        //
        _.each(plugins, function(plugin) {
          if (typeof plugin.report === 'function') {
            let report = plugin.report();
            if (report) {
              if (report.length) {
                _.each(report, function insertIntermediateReport(a) {
                  if (a.timestamp === 'aggregate') {
                    Report.aggregate[plugin.__name] = a.value;
                  } else {
                    let ir = _.findWhere(
                      Report.intermediate,
                      {timestamp: a.timestamp});
                    ir[plugin.__name] = a.value;
                  }
                });
              } else {
                Report.aggregate[plugin.__name] = report;
              }
            }
          }
        });

        return ee.emit('done', Report);
      } else {
        debug('Pending requests: %s', pendingRequests.toJSON());
        debug('Pending scenarios: %s', pendingScenarios.toJSON());
      }
    }, 500);
  });

  const periodicStatsTimer = setInterval(function() {
    const report = intermediate.report();
    Report.intermediate.push(report);
    intermediate.reset();
    ee.emit('stats', report);
  }, options.periodicStats * 1000);

  phaser.run();
}

function runScenario(script, intermediate, aggregate) {
  const start = process.hrtime();

  //
  // Compile scenarios if needed
  //
  if (!compiledScenarios) {
    _.each(script.scenarios, function(scenario) {
      if (!scenario.weight) {
        scenario.weight = 1;
      }
    });

    picker = wl(script.scenarios);

    scenarioEvents = new EventEmitter();
    scenarioEvents.on('started', function() {
      pendingScenarios.inc();
    });
    scenarioEvents.on('error', function(errCode) {
      intermediate.addError(errCode);
      aggregate.addError(errCode);
    });
    scenarioEvents.on('request', function() {
      intermediate.newRequest();
      aggregate.newRequest();

      pendingRequests.inc();
    });
    scenarioEvents.on('match', function() {
      intermediate.addMatch();
      aggregate.addMatch();
    });
    scenarioEvents.on('response', function(delta, code) {
      intermediate.completedRequest();
      intermediate.addLatency(delta);
      intermediate.addCode(code);

      aggregate.completedRequest();
      aggregate.addLatency(delta);
      aggregate.addCode(code);

      pendingRequests.dec();
    });

    compiledScenarios = _.map(script.scenarios, function(scenarioSpec) {
      const name = scenarioSpec.engine || 'http';
      const engine = engines.find((e) => e.__name === name);
      let tasks = _.map(scenarioSpec.flow, rs => {
        if (rs.think) {
          return engineUtil.createThink(rs);
        }
        return engine.step(rs, scenarioEvents);
      });
      return engine.compile(
        tasks,
        scenarioSpec.flow,
        scenarioEvents
        );
    });
  }

  intermediate.newScenario();
  aggregate.newScenario();

  let i = picker()[0];

  debug('picking scenario %s (%s) weight = %s',
        i,
        script.scenarios[i].name,
        script.scenarios[i].weight);

  const scenarioStartedAt = process.hrtime();
  const scenarioContext = createContext(script);
  const finish = process.hrtime(start);
  const runScenarioDelta = (finish[0] * 1e9) + finish[1];
  debugPerf('runScenarioDelta: %s', Math.round(runScenarioDelta / 1e6 * 100) / 100);
  compiledScenarios[i](scenarioContext, function(err, context) {
    pendingScenarios.dec();
    if (err) {
      debug(err);
      //debug('Scenario aborted due to error');
      cancelledRequests.inc(context._pendingRequests);
    } else {
      //debug('Scenario completed');
      //debug(context);
      const scenarioFinishedAt = process.hrtime(scenarioStartedAt);
      const delta = (scenarioFinishedAt[0] * 1e9) + scenarioFinishedAt[1];
      intermediate.addScenarioLatency(delta);
      aggregate.addScenarioLatency(delta);
      intermediate.completedScenario();
      aggregate.completedScenario();
    }
  });
}

/**
 * Create initial context for a scenario.
 */
function createContext(script) {
  const INITIAL_CONTEXT = {
    vars: {
      target: script.config.target
    },
    funcs: {
      $randomNumber: $randomNumber,
      $randomString: $randomString
    }
  };
  let result = _.cloneDeep(INITIAL_CONTEXT);

  //
  // variables from payloads
  //
  if (script.config.payload) {
    _.each(script.config.payload, function(el) {
      let i = _.random(0, el.data.length - 1);
      let row = el.data[i];
      _.each(el.fields, function(fieldName, j) {
        result.vars[fieldName] = row[j];
      });
    });
  }

  //
  // inline variables
  //
  if (script.config.variables) {
    _.each(script.config.variables, function(v, k) {
      let val;
      if (_.isArray(v)) {
        val = _.sample(v);
      } else {
        val = v;
      }
      result.vars[k] = val;
    });
  }
  return result;
}

//
// Generator functions for template strings:
//
function $randomNumber(min, max) {
  return _.random(min, max);
}

function $randomString(length) {
  return Math.random().toString(36).substr(2, length);
}
<|endoftext|>


<commit_before>const gulp = require('gulp');
const async = require('async');
const fs = require('fs');
const rimraf = require('rimraf');
const zip = require('gulp-zip');
const util = require('gulp-util');
const electron = require('gulp-atom-electron');
const symdest = require('gulp-symdest');
const git = require('gulp-git');
const exec = require('child_process').exec;
const grimraf = require('gulp-rimraf');
const debug = require('gulp-debug');
const vfs = require('vinyl-fs');
const imagemin = require ('gulp-imagemin');
const merge = require('merge2');

//CONFIG
const BUILD_DIR = 'build';
const PACKAGES = `${BUILD_DIR}/packages`;
const BOT = `${BUILD_DIR}/gofbot`;

gulp.task('python:install', callback => {
    async.waterfall([
        cb => rimraf(PACKAGES, cb),
        cb => async.concat(fs.readFileSync('build/gofbot/requirements.txt')
            .toString()
            .split('\n')
            .map(dep => dep.trim().replace('-e ', '')), (cmd, _) => exec(`pip install ${cmd} --target ${PACKAGES}`, _), err => cb(err)),
        cb => fs.open(`${PACKAGES}/google/__init__.py`, 'wx', cb),
        (file, cb) => fs.close(file, cb)
    ], callback);
});

gulp.task('python:package', ['python:install'], () => {
    return gulp.src(`${PACKAGES}/**/!(*.pyc|*.egg-info)`)
        .pipe(zip('packages.zip'))
        .pipe(grimraf())
        .pipe(gulp.dest('build'))
});

const PACKAGE_SRC = ['app/**', 'LICENSE', 'gofbot/**/*', 'package.json', 'main.js'];

gulp.task('electron:osx', ['python:package'], () => {
    return gulp.src(PACKAGE_SRC, {base: '.'})
        .pipe(electron({
            version: '1.3.3',
            platform: 'darwin',
            darwinIcon: 'src/assets/resources/image/icons/pokemon.icns',
            darwinBundleIdentifier: 'com.github.pokemongof'
        })).pipe(symdest('build'));
});

gulp.task('electron:windows', ['python:package'], () => {
    return gulp.src(PACKAGE_SRC.concat('pywin/**/*'), {base: '.'})
        .pipe(electron({
            version: '1.3.3',
            platform: 'win32',
            arch: 'ia32',
            winIcon: 'src/assets/resources/image/icons/pokemon.ico',
            companyName: 'PokemonGoF',
            copyright: '2016 PokemonGOF, All Rights Reserved.'
        }))
        .pipe(zip('app-windows.exe'))
        .pipe(gulp.dest('build/'));
});

gulp.task('gofbot:update', (callback) => {
    async.series([
        _ => git.exec({args: `submodule deinit -f ${BOT}`}, _),
        _ => git.updateSubmodule({ args: '--init' }, _)
    ], callback);
});

gulp.task('gofbot:prune', ['gofbot:update'], (callback) => {
    async.parallel([
        _ => rimraf(`${BOT}/docs`, _),
        _ => rimraf(`${BOT}/web`, _),
        _ => rimraf(`${BOT}/.github`, _),
        _ => rimraf(`${BOT}/tests`, _),
        _ => async.concat(['ws_server.py', 'run.sh', 'setup.sh', 'README.md', 'pylint-recursive.py', 'run.bat',
            'LICENSE', 'Dockerfile', 'install.sh', 'CONTRIBUTORS.md', 'docker-compose.yml', '.travis.yml', '.styles.yapf',
            '.pylintrc', '.mention-bot', '.pullapprove.yml', '.gitmodules', '.dockerignore', '.gitignore'].map(x => `${BOT}/${x}`), fs.unlink, _)
    ], callback);
});

gulp.task('clean', () => vfs.src([`${BUILD_DIR}/*`, `!${BUILD_DIR}/{gofbot,gofbot/*,pywin,pywin/*}`]).pipe(grimraf()));

gulp.task('build:node', ['clean'], () => {
    const getNodeModules = () => Object.keys(JSON.parse(fs.readFileSync('package.json').toString()).dependencies)
        .map(_ => `./node_modules/${_}/**/*`);
    return merge(
        vfs.src(getNodeModules(),  {base: '.'})
            .pipe(gulp.dest(BUILD_DIR)),
        gulp.src('package.json')
            .pipe(gulp.dest(BUILD_DIR))
    );
});

gulp.task('build:src', ['clean'], () => gulp.src('src/**/*').pipe(gulp.dest(BUILD_DIR)));

gulp.task('build', ['gofbot:prune', 'build:node', 'build:src']);
gulp.task('release', ['build', 'python:package', 'electron:osx', 'electron:windows']);<commit_msg>Fixed Gulp<commit_after>const gulp = require('gulp');
const async = require('async');
const fs = require('fs');
const rimraf = require('rimraf');
const zip = require('gulp-zip');
const util = require('gulp-util');
const electron = require('gulp-atom-electron');
const symdest = require('gulp-symdest');
const git = require('gulp-git');
const exec = require('child_process').exec;
const grimraf = require('gulp-rimraf');
const debug = require('gulp-debug');
const vfs = require('vinyl-fs');
const imagemin = require ('gulp-imagemin');
const merge = require('merge2');

//CONFIG
const BUILD_DIR = 'build';
const PACKAGES = `${BUILD_DIR}/packages`;
const BOT = `${BUILD_DIR}/gofbot`;

gulp.task('python:install', callback => {
    async.waterfall([
        cb => rimraf(PACKAGES, cb),
        cb => async.concat(fs.readFileSync('build/gofbot/requirements.txt')
            .toString()
            .split('\n')
            .map(dep => dep.trim().replace('-e ', '')), (cmd, _) => exec(`pip install ${cmd} --target ${PACKAGES}`, _), err => cb(err)),
        cb => fs.open(`${PACKAGES}/google/__init__.py`, 'wx', cb),
        (file, cb) => fs.close(file, cb)
    ], callback);
});

gulp.task('python:package', ['python:install'], () => {
    return gulp.src(`${PACKAGES}/**/!(*.pyc|*.egg-info)`)
        .pipe(zip('packages.zip'))
        .pipe(grimraf())
        .pipe(gulp.dest('build'))
});

const PACKAGE_SRC = ['app/**', 'LICENSE', 'gofbot/**/*', 'package.json', 'main.js'];

gulp.task('electron:osx', ['python:package'], () => {
    return gulp.src(PACKAGE_SRC, {base: '.'})
        .pipe(electron({
            version: '1.3.3',
            platform: 'darwin',
            darwinIcon: 'src/assets/resources/image/icons/pokemon.icns',
            darwinBundleIdentifier: 'com.github.pokemongof'
        })).pipe(symdest('build'));
});

gulp.task('electron:windows', ['python:package'], () => {
    return gulp.src(PACKAGE_SRC.concat('pywin/**/*'), {base: '.'})
        .pipe(electron({
            version: '1.3.3',
            platform: 'win32',
            arch: 'ia32',
            winIcon: 'src/assets/resources/image/icons/pokemon.ico',
            companyName: 'PokemonGoF',
            copyright: '2016 PokemonGOF, All Rights Reserved.'
        }))
        .pipe(zip('app-windows.exe'))
        .pipe(gulp.dest('build/'));
});

gulp.task('gofbot:update', (callback) => {
    async.series([
        _ => git.exec({args: `submodule deinit -f ${BOT}`}, _),
        _ => git.updateSubmodule({ args: '--init' }, _)
    ], callback);
});

gulp.task('gofbot:prune', ['gofbot:update'], (callback) => {
    //TODO - Switch to grimraf
    async.parallel([
        _ => rimraf(`${BOT}/docs`, _),
        _ => rimraf(`${BOT}/web`, _),
        _ => rimraf(`${BOT}/.github`, _),
        _ => rimraf(`${BOT}/tests`, _),
        _ => async.concat(['ws_server.py', 'run.sh', 'setup.sh', 'README.md', 'pylint-recursive.py', 'run.bat',
            'LICENSE', 'Dockerfile', 'install.sh', 'CONTRIBUTORS.md', 'docker-compose.yml', '.travis.yml', '.styles.yapf',
            '.pylintrc', '.mention-bot', '.pullapprove.yml', '.gitmodules', '.dockerignore', '.gitignore'].map(x => `${BOT}/${x}`), fs.unlink, _)
    ], callback);
});

gulp.task('clean', () => vfs.src([`${BUILD_DIR}/*`, `!${BUILD_DIR}/{gofbot,gofbot/*,pywin,pywin/*}`]).pipe(grimraf()));

gulp.task('build:node', ['clean'], () => {
    const getNodeModules = () => Object.keys(JSON.parse(fs.readFileSync('package.json').toString()).dependencies).map(_ => `node_modules/${_}/**/*`);
    return merge(
        vfs.src(getNodeModules(),  {base: '.'})
            .pipe(gulp.dest(BUILD_DIR)),
        gulp.src('package.json')
            .pipe(gulp.dest(BUILD_DIR))
    );
});

gulp.task('build:src', ['clean'], () => gulp.src('src/**/*').pipe(gulp.dest(BUILD_DIR)));

gulp.task('build', ['gofbot:prune', 'build:node', 'build:src']);
gulp.task('release', ['build', 'python:package', 'electron:osx', 'electron:windows']);<|endoftext|>


<commit_before>(function(global, undefined) {
  'use strict';

  global.ados_results = global.ados_results || null;

  var PLACEMENT_TYPES_FRIENDLY_NAMES = {
    '5': '300x250',
    '8': '300x100',
  };
  var RATE_TYPE_FRIENDLY_NAMES = {
    '1': 'Flat',
    '2': 'CPM',
    '3': 'CPC',
  }
  var NETWORK = global.ADS_GLOBALS.network;
  var SITE = global.ADS_GLOBALS.site;
  var PRIORITIES = global.ADS_GLOBALS.priorities;
  var PRIORITY_FRIEND_NAMES = Object.keys(PRIORITIES).reduce(function(r, key) {
    r[PRIORITIES[key]] = key
    return r;
  }, {});
  var PLACEMENT_TYPES = {
    main: 5,
    sponsorship: 8,
  };

  function asc(a, b) {
    return a > b ? 1 : -1
  }

  function lower(s) {
    return s.toLowerCase();
  }

  function getPriorityName(id) {
    return PRIORITY_FRIEND_NAMES[id] || 'unknown (' + id + ')';
  }

  function getConfig() {
    // Accessing `location.hash` directly does different
    // things in different browsers:
    //    > location.hash = "#%30";
    //    > location.hash === "#0"; // This is wrong, it should be "#%30"
    //    > true
    // see http://stackoverflow.com/a/1704842/704286
    var hash = location.href.split('#')[1] || '';

    // Firefox automatically encodes thing the fragment, but not other browsers.
    if (/^\{%22/.test(hash)) {
      hash = decodeURIComponent((hash));
    }

    try {
      return $.parseJSON(hash);
    } catch (e) {
      return {};
    }
  }

  var config = getConfig();
  var properties = config.properties || {};
  // If double sidebar experiment, have the top ad not call Adzerk
  if (properties.double_sidebar && properties.frame_id == 'ad_main_top') {
    var PLACEMENT = 'top';
    // Change the id of the ad so ados knows what div to insert to
    $('#main').attr('id', 'top');
    global.onload = function() {
      var adContent = global.parent.frames.ad_main.ados_results;
      global.name = 'ad-' + PLACEMENT;
      // Grabs data from the main frame and `eval`s it. Unfortunately
      // there isn't a great way to pass this data across frames
      // as it's more complicated than json and would normally be
      // loaded as a script tag, hence the `eval`
      eval(adContent[PLACEMENT]);
    };

    ados.run.push(function() {
      ados_loadDiv(PLACEMENT);
    });
    return;
  }

  // Allows the yield manager to target a percentage of users
  // with specific SSPs.
  if (!properties.hasOwnProperty('percentage')) {
    properties.percentage = Math.round(Math.random() * 100);
  }

  // Ensure all property values are URI encoded since
  // ados doesn't handle this properly.
  for (var key in properties) {
    properties[key] = encodeURIComponent(properties[key]);
  }

  // Display a random image in lieu of an ad for certain keywords.
  // This reduces the number of ad requests for low-fill targets.
  if (global.SKIP_AD_PROBABILITY && Math.random() <= global.SKIP_AD_PROBABILITY) {
    var keywords = config.keywords ? config.keywords : [];
    var skipAd = false;

    if (global.SKIP_AD_KEYWORDS && keywords) {
      for (var i = 0; i < keywords.length; i++) {
        if ($.inArray(keywords[i], global.SKIP_AD_KEYWORDS) !== -1) {
          skipAd = true;
          break;
        }
      }
    }

    if (skipAd) {
      var adframe = document.getElementById('main');
      var img = document.createElement('img');
      var randomImgIndex = Math.floor(Math.random() * global.SKIP_AD_IMAGES.length);
      img.height = 250;
      img.width = 300;
      img.src = global.SKIP_AD_IMAGES[randomImgIndex];

      adframe.appendChild(img);

      return;
    }
  }

  // Reconfigure placements if it's the double sidebar experiment
  if (properties.double_sidebar) {
    PLACEMENT_TYPES = {
      main: 5,
      top: 5,
    };
  }

  ados.run.push(function() {
    ados.isAsync = true;
    var placement = null;
    var instrumentedProperties = {
      age_hours: properties.age_hours,
      percentage: properties.percentage,
    };

    var requestPayload = {
      keywords: config.keywords.map(lower).sort(asc),
      placements: [],
      properties: instrumentedProperties,
    };

    if (config.placements) {
      var placements = config.placements.split(',');

      for (var i = 0; i < placements.length; i++) {
        var kvp = placements[i].split(':');
        var type = kvp[0];
        var creative = kvp[1];

        placement = ados_add_placement(NETWORK, SITE, type, PLACEMENT_TYPES[type]);
        placement.setFlightCreativeId(creative);
        placement.setProperties(properties);

        requestPayload.placements.push({
          name: 'sidebar_' + type,
          types: [
            PLACEMENT_TYPES_FRIENDLY_NAMES[PLACEMENT_TYPES[type]],
          ],
        })
      }
    } else {
      for (var type in PLACEMENT_TYPES) {
        placement = ados_add_placement(NETWORK, SITE, type, PLACEMENT_TYPES[type]);
        if(properties.double_sidebar && type === 'top'){
          properties.frame_id = 'ad_main_top';
        } else {
          properties.frame_id = 'ad_main';
        }
        placement.setProperties(properties);

        requestPayload.placements.push({
          name: 'sidebar_' + type,
          types: [
            PLACEMENT_TYPES_FRIENDLY_NAMES[PLACEMENT_TYPES[type]],
          ],
        })
      }
    }

    ados_setWriteResults(true);

    if (config.keywords) {
      ados_setKeywords(config.keywords);
    }

    r.frames.postMessage(global.parent, 'request.adzerk', requestPayload);

    ados_load();

    var load = setInterval(function() {
      if (global.ados_results) {
        clearInterval(load);

        // Load top ad if exists
        if (global.ados_results.top && global.postMessage) {
          global.parent.postMessage('ados.createAdFrame:top', config.origin);
        }

        for (var key in global.ados_ads) {
          if (!global.ados_ads.hasOwnProperty(key)) {
            continue;
          }

          var adResult = global.ados_ads[key];
          var impressionMatcher = global.ados_results[key].match(new RegExp(
            '.*https?:\/\/' +
            ados.domain +
            '\/e.gif\?e=([^&]+).*'
          ));
          var responsePayload = {
            keywords: config.keywords.map(lower).sort(asc),
            placement_type: PLACEMENT_TYPES_FRIENDLY_NAMES[adResult.creative.adType],
            placement_name: 'sidebar_' + key,
            adserver_campaign_id: adResult.flight.campaign.id,
            adserver_flight_id: adResult.flight.id,
            adserver_creative_id: adResult.creative.id,
            adserver_ad_id: adResult.id,
            priority: getPriorityName(adResult.flight.priorityId),
            rate_type: RATE_TYPE_FRIENDLY_NAMES[adResult.flight.rateType],
            ecpm: adResult.ecpm,
            companions: (adResult.companions || []).map(function(c) {
              return {
                adserver_ad_id: c.id,
                placement_type: PLACEMENT_TYPES_FRIENDLY_NAMES[c.adType],
              }
            }),
            properties: instrumentedProperties,
          };

          if (impressionMatcher) {
            var impressionb64data = impressionMatcher[1];

            // this is url safe base64, need to fix the padding and replace escape characters
            impressionb64data = impressionb64data + Array((impressionb64data.length % 4) + 1).join('=')
            impressionb64data = impressionb64data
                                  .replace(/\-/g, '+')
                                  .replace(/_/g, '\/');

            try {
              var impressionData = JSON.parse(global.atob(impressionb64data));

              responsePayload.matched_keywords = impressionData.mk.map(lower).sort(asc);
              responsePayload.interana_excluded = responsePayload.interana_excluded || {};
              responsePayload.interana_excluded.impression_id = impressionData.di;
            } catch (e) {
              // pass
            }
          }

          r.frames.postMessage(global.parent, 'response.adzerk', responsePayload);
        }

        // Load companion
        if (global.ados_results.sponsorship) {
          if (global.postMessage) {
            global.parent.postMessage('ados.createAdFrame:sponsorship', config.origin);
          } else {
            iframe = document.createElement('iframe');
            iframe.src = '/static/createadframe.html';
            iframe.style.display = 'none';
            document.documentElement.appendChild(iframe);
          }
        }
      }
    }, 50);
  });
})(this);
<commit_msg>Encode properties only for sending them to ados<commit_after>(function(global, undefined) {
  'use strict';

  global.ados_results = global.ados_results || null;

  var PLACEMENT_TYPES_FRIENDLY_NAMES = {
    '5': '300x250',
    '8': '300x100',
  };
  var RATE_TYPE_FRIENDLY_NAMES = {
    '1': 'Flat',
    '2': 'CPM',
    '3': 'CPC',
  }
  var NETWORK = global.ADS_GLOBALS.network;
  var SITE = global.ADS_GLOBALS.site;
  var PRIORITIES = global.ADS_GLOBALS.priorities;
  var PRIORITY_FRIEND_NAMES = Object.keys(PRIORITIES).reduce(function(r, key) {
    r[PRIORITIES[key]] = key
    return r;
  }, {});
  var PLACEMENT_TYPES = {
    main: 5,
    sponsorship: 8,
  };

  function asc(a, b) {
    return a > b ? 1 : -1
  }

  function lower(s) {
    return s.toLowerCase();
  }

  function getPriorityName(id) {
    return PRIORITY_FRIEND_NAMES[id] || 'unknown (' + id + ')';
  }

  function getConfig() {
    // Accessing `location.hash` directly does different
    // things in different browsers:
    //    > location.hash = "#%30";
    //    > location.hash === "#0"; // This is wrong, it should be "#%30"
    //    > true
    // see http://stackoverflow.com/a/1704842/704286
    var hash = location.href.split('#')[1] || '';

    // Firefox automatically encodes thing the fragment, but not other browsers.
    if (/^\{%22/.test(hash)) {
      hash = decodeURIComponent((hash));
    }

    try {
      return $.parseJSON(hash);
    } catch (e) {
      return {};
    }
  }

  var config = getConfig();
  var properties = config.properties || {};
  // If double sidebar experiment, have the top ad not call Adzerk
  if (properties.double_sidebar && properties.frame_id == 'ad_main_top') {
    var PLACEMENT = 'top';
    // Change the id of the ad so ados knows what div to insert to
    $('#main').attr('id', 'top');
    global.onload = function() {
      var adContent = global.parent.frames.ad_main.ados_results;
      global.name = 'ad-' + PLACEMENT;
      // Grabs data from the main frame and `eval`s it. Unfortunately
      // there isn't a great way to pass this data across frames
      // as it's more complicated than json and would normally be
      // loaded as a script tag, hence the `eval`
      eval(adContent[PLACEMENT]);
    };

    ados.run.push(function() {
      ados_loadDiv(PLACEMENT);
    });
    return;
  }

  // Allows the yield manager to target a percentage of users
  // with specific SSPs.
  if (!properties.hasOwnProperty('percentage')) {
    properties.percentage = Math.round(Math.random() * 100);
  }

  function encodeProperties(props) {
    // Ensure all property values are URI encoded since
    // ados doesn't handle this properly.
    var encoded = {};
    for (var key in properties) {
      encoded[key] = encodeURIComponent(properties[key]);
    }

    return encoded;
  }

  // Display a random image in lieu of an ad for certain keywords.
  // This reduces the number of ad requests for low-fill targets.
  if (global.SKIP_AD_PROBABILITY && Math.random() <= global.SKIP_AD_PROBABILITY) {
    var keywords = config.keywords ? config.keywords : [];
    var skipAd = false;

    if (global.SKIP_AD_KEYWORDS && keywords) {
      for (var i = 0; i < keywords.length; i++) {
        if ($.inArray(keywords[i], global.SKIP_AD_KEYWORDS) !== -1) {
          skipAd = true;
          break;
        }
      }
    }

    if (skipAd) {
      var adframe = document.getElementById('main');
      var img = document.createElement('img');
      var randomImgIndex = Math.floor(Math.random() * global.SKIP_AD_IMAGES.length);
      img.height = 250;
      img.width = 300;
      img.src = global.SKIP_AD_IMAGES[randomImgIndex];

      adframe.appendChild(img);

      return;
    }
  }

  // Reconfigure placements if it's the double sidebar experiment
  if (properties.double_sidebar) {
    PLACEMENT_TYPES = {
      main: 5,
      top: 5,
    };
  }

  ados.run.push(function() {
    ados.isAsync = true;
    var placement = null;
    var instrumentedProperties = {
      age_hours: properties.age_hours,
      percentage: properties.percentage,
    };

    var requestPayload = {
      keywords: config.keywords.map(lower).sort(asc),
      placements: [],
      properties: instrumentedProperties,
    };

    if (config.placements) {
      var placements = config.placements.split(',');

      for (var i = 0; i < placements.length; i++) {
        var kvp = placements[i].split(':');
        var type = kvp[0];
        var creative = kvp[1];

        placement = ados_add_placement(NETWORK, SITE, type, PLACEMENT_TYPES[type]);
        placement.setFlightCreativeId(creative);
        placement.setProperties(encodeProperties(properties));

        requestPayload.placements.push({
          name: 'sidebar_' + type,
          types: [
            PLACEMENT_TYPES_FRIENDLY_NAMES[PLACEMENT_TYPES[type]],
          ],
        })
      }
    } else {
      for (var type in PLACEMENT_TYPES) {
        placement = ados_add_placement(NETWORK, SITE, type, PLACEMENT_TYPES[type]);
        if(properties.double_sidebar && type === 'top'){
          properties.frame_id = 'ad_main_top';
        } else {
          properties.frame_id = 'ad_main';
        }
        placement.setProperties(encodeProperties(properties));

        requestPayload.placements.push({
          name: 'sidebar_' + type,
          types: [
            PLACEMENT_TYPES_FRIENDLY_NAMES[PLACEMENT_TYPES[type]],
          ],
        })
      }
    }

    ados_setWriteResults(true);

    if (config.keywords) {
      ados_setKeywords(config.keywords);
    }

    r.frames.postMessage(global.parent, 'request.adzerk', requestPayload);

    ados_load();

    var load = setInterval(function() {
      if (global.ados_results) {
        clearInterval(load);

        // Load top ad if exists
        if (global.ados_results.top && global.postMessage) {
          global.parent.postMessage('ados.createAdFrame:top', config.origin);
        }

        for (var key in global.ados_ads) {
          if (!global.ados_ads.hasOwnProperty(key)) {
            continue;
          }

          var adResult = global.ados_ads[key];
          var impressionMatcher = global.ados_results[key].match(new RegExp(
            '.*https?:\/\/' +
            ados.domain +
            '\/e.gif\?e=([^&]+).*'
          ));
          var responsePayload = {
            keywords: config.keywords.map(lower).sort(asc),
            placement_type: PLACEMENT_TYPES_FRIENDLY_NAMES[adResult.creative.adType],
            placement_name: 'sidebar_' + key,
            adserver_campaign_id: adResult.flight.campaign.id,
            adserver_flight_id: adResult.flight.id,
            adserver_creative_id: adResult.creative.id,
            adserver_ad_id: adResult.id,
            priority: getPriorityName(adResult.flight.priorityId),
            rate_type: RATE_TYPE_FRIENDLY_NAMES[adResult.flight.rateType],
            ecpm: adResult.ecpm,
            companions: (adResult.companions || []).map(function(c) {
              return {
                adserver_ad_id: c.id,
                placement_type: PLACEMENT_TYPES_FRIENDLY_NAMES[c.adType],
              }
            }),
            properties: instrumentedProperties,
          };

          if (impressionMatcher) {
            var impressionb64data = impressionMatcher[1];

            // this is url safe base64, need to fix the padding and replace escape characters
            impressionb64data = impressionb64data + Array((impressionb64data.length % 4) + 1).join('=')
            impressionb64data = impressionb64data
                                  .replace(/\-/g, '+')
                                  .replace(/_/g, '\/');

            try {
              var impressionData = JSON.parse(global.atob(impressionb64data));

              responsePayload.matched_keywords = impressionData.mk.map(lower).sort(asc);
              responsePayload.interana_excluded = responsePayload.interana_excluded || {};
              responsePayload.interana_excluded.impression_id = impressionData.di;
            } catch (e) {
              // pass
            }
          }

          r.frames.postMessage(global.parent, 'response.adzerk', responsePayload);
        }

        // Load companion
        if (global.ados_results.sponsorship) {
          if (global.postMessage) {
            global.parent.postMessage('ados.createAdFrame:sponsorship', config.origin);
          } else {
            iframe = document.createElement('iframe');
            iframe.src = '/static/createadframe.html';
            iframe.style.display = 'none';
            document.documentElement.appendChild(iframe);
          }
        }
      }
    }, 50);
  });
})(this);
<|endoftext|>