<commit_before>var CenterIcon = (function() {

   function CenterIcon(x, y, rad) {
      this.xPos = x;
      this.yPos = y;
      this.radius = rad;
   }

   CenterIcon.prototype.draw = function() {
      context.beginPath();
      context.arc(this.xPos, this.yPos, this.radius, 0, 2 * Math.PI, false);
      context.fillStyle = 'green';
      context.fill();
   }

   CenterIcon.prototype.getRadius = function() {
        return this.radius;
   };

   return CenterIcon;
})();

var VisualizerDot = (function() {

   function VisualizerDot(x, y, c, rad) {
      this.xPos = x; this.yPos = y;
      this.color = c; this.radius = rad;
      this.vel = 3;
   }

   VisualizerDot.prototype.setAngle = function(theta) {
      this.angle = theta;
   }

   VisualizerDot.prototype.updateX = function() {
      this.xPos += this.vel * Math.cos(this.angle);
      this.vel -= 0.2; //gravity
   }

   VisualizerDot.prototype.updateY = function() {
      this.yPos += this.vel * Math.sin(this.angle);
   }

   VisualizerDot.prototype.bounceBack = function(otherObjX, otherObjY, otherObjRad) {
      if( Math.sqrt(Math.pow(otherObjY - this.yPos, 2) + Math.pow(otherObjX - this.xPos,2)) < (otherObjRad+this.radius)) {
         this.vel = -1 * this.vel * ((13-this.radius) / 10);//bouncefactor
      }
   }

   VisualizerDot.prototype.setImpulse = function(size) {
      this.vel += size;
   }

   VisualizerDot.prototype.draw = function() {
      context.beginPath();
      this.bounceBack(artist.xPos, artist.yPos, artist.radius);
      this.updateY(); this.updateX();
      context.arc(this.xPos, this.yPos, this.radius, 0, 2 * Math.PI, false);
      context.fillStyle = this.color;
      context.fill();
   }

   return VisualizerDot;
})();

// See http://stackoverflow.com/questions/1527803/generating-random-numbers-in-javascript-in-a-specific-range
function getRandomInt (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function initializeDotsAboutRadius(radius, offset, dots) {
   var numDots = 85;
   var possibleColors = new Array("#E6E6E6", "#EEEEEE", "#aaaaaa", "#F6F6F6")
   for(var i = 1; i <= numDots; i++) {
      angle = 2 * Math.PI * i/numDots;
      var rad = getRandomInt(5, 8);
      dots.push(new VisualizerDot(Math.cos(angle) * (radius + offset + rad) + centerX, Math.sin(angle) * (radius + offset + rad) + centerY, possibleColors[rad-5], rad));
      dots[i-1].setAngle(angle);
      dots[i-1].draw();
   }
}

function draw() {
   context.clearRect(0,0,canvas.width,canvas.height);
   artist.draw();
   for(var i = 0; i < dots.length; i++) {
      dots[i].draw();
   }
}

function impulse() {
   size = 4;
   for(var i = 0; i < dots.length; i++) {
      dots[i].setImpulse(size);
   }
}

var canvas = document.getElementById("visualizer");
var context = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 70;

var artist = new CenterIcon(centerX, centerY, radius);
artist.draw(context);

var dots = new Array();
initializeDotsAboutRadius(radius, 100, dots);

setInterval(draw,1000/60);
<commit_msg>Soundcloud streaming enabled<commit_after>var CenterIcon = (function() {

   function CenterIcon(x, y, rad) {
      this.xPos = x;
      this.yPos = y;
      this.radius = rad;
   }

   CenterIcon.prototype.draw = function() {
      context.beginPath();
      context.arc(this.xPos, this.yPos, this.radius, 0, 2 * Math.PI, false);
      context.fillStyle = 'green';
      context.fill();
   }

   CenterIcon.prototype.getRadius = function() {
        return this.radius;
   };

   return CenterIcon;
})();

var VisualizerDot = (function() {

   function VisualizerDot(x, y, c, rad) {
      this.xPos = x; this.yPos = y;
      this.color = c; this.radius = rad;
      this.vel = 3;
   }

   VisualizerDot.prototype.setAngle = function(theta) {
      this.angle = theta;
   }

   VisualizerDot.prototype.updateX = function() {
      this.xPos += this.vel * Math.cos(this.angle);
      this.vel -= 0.2; //gravity
   }

   VisualizerDot.prototype.updateY = function() {
      this.yPos += this.vel * Math.sin(this.angle);
   }

   VisualizerDot.prototype.bounceBack = function(otherObjX, otherObjY, otherObjRad) {
      if( Math.sqrt(Math.pow(otherObjY - this.yPos, 2) + Math.pow(otherObjX - this.xPos,2)) < (otherObjRad+this.radius)) {
         this.vel = -1 * this.vel * ((13-this.radius) / 10);//bouncefactor
      }
   }

   VisualizerDot.prototype.setImpulse = function(size) {
      this.vel += size;
   }

   VisualizerDot.prototype.draw = function() {
      context.beginPath();
      this.bounceBack(artist.xPos, artist.yPos, artist.radius);
      this.updateY(); this.updateX();
      context.arc(this.xPos, this.yPos, this.radius, 0, 2 * Math.PI, false);
      context.fillStyle = this.color;
      context.fill();
   }

   return VisualizerDot;
})();

// See http://stackoverflow.com/questions/1527803/generating-random-numbers-in-javascript-in-a-specific-range
function getRandomInt (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function initializeDotsAboutRadius(radius, offset, dots) {
   var numDots = 85;
   var possibleColors = new Array("#E6E6E6", "#EEEEEE", "#aaaaaa", "#F6F6F6")
   for(var i = 1; i <= numDots; i++) {
      angle = 2 * Math.PI * i/numDots;
      var rad = getRandomInt(5, 8);
      dots.push(new VisualizerDot(Math.cos(angle) * (radius + offset + rad) + centerX, Math.sin(angle) * (radius + offset + rad) + centerY, possibleColors[rad-5], rad));
      dots[i-1].setAngle(angle);
      dots[i-1].draw();
   }
}

function draw() {
   context.clearRect(0,0,canvas.width,canvas.height);
   artist.draw();
   for(var i = 0; i < dots.length; i++) {
      dots[i].draw();
   }
}

function impulse() {
   size = 4;
   for(var i = 0; i < dots.length; i++) {
      dots[i].setImpulse(size);
   }
}

var canvas = document.getElementById("visualizer");
var context = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 70;

var artist = new CenterIcon(centerX, centerY, radius);
artist.draw(context);

var dots = new Array();
initializeDotsAboutRadius(radius, 100, dots);

setInterval(draw,1000/60);

//http://stackoverflow.com/questions/13455956/setup-web-audio-api-source-node-from-soundcloud
var ctx = new webkitAudioContext(),
    audio = new Audio(),
    source,
    url = 'http://api.soundcloud.com/tracks/111453161/stream' +
          '?client_id=9dbc638d0d3dc69a9500c85a6097e786';

audio.src = url;
source = ctx.createMediaElementSource(audio);
source.connect(ctx.destination);
source.mediaElement.play();
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var path = require('path');
var moment = require('moment');
var casual = require('casual');
var yaml = require('js-yaml');
var glob = require('glob');

router.use('/images', express.static(path.join(__dirname, 'images')));

var prototypeVersion = path.basename(__dirname);

var countries = require('./country-records.json');
countries = countries.sort(function(a, b) {
  if(a.entry.name < b.entry.name) {
    return -1;
  }

  if(a.entry.name > b.entry.name) {
    return 1;
  }

  return 0;
});

/**
 * Sign in / out hack
 */
router.use(function (req, res, next) {
  // In order to quickly prototype sign in, if the GET or POST data sent to the
  // server contains either do_sign_in or do_sign_out values we will act
  // accordingly and sign the user in or out. No passwords are checked, no
  // accounts exist anywhere in any databases. This is a straight up hack
  // for prototyping purposes only. Move along now.

  // Default to not being logged in
  if(typeof req.session.isLoggedIn === 'undefined') {
    req.session.isLoggedIn = false;
  }

  // If we've been asked to sign in, reflect this in the session
  if(typeof req.query.do_sign_in !== 'undefined' || typeof req.body.do_sign_in !== 'undefined') {
    req.session.isLoggedIn = true;
    return next();
  }

  // If we've been asked to sign out, destroy the session
  else if(typeof req.query.do_sign_out !== 'undefined' || typeof req.body.do_sign_out !== 'undefined') {
    req.session.destroy(function(err) {
      next();
    });
  }

  else {
    next();
  }

});

/**
 * Sign in route
 */
router.get('/sign_in', function(req, res) {
  req.session.isLoggedIn = false;

  req.session.destroy(function() {
    res.render(path.join(__dirname, 'sign_in'));
  })
});

/**
 * Sign out route
 */
router.get('/sign_out', function(req, res) {
  req.session.isLoggedIn = false;

  req.session.destroy(function() {
    return res.render(path.join(__dirname, 'signed_out'));
  })
});

router.get('/sign_out', function(req, res) {
  req.session.isLoggedIn = false;

  req.session.destroy(function() {
    return res.render(path.join(__dirname, '/signed_out'));
  })
});

router.get('/', function(req, res) {
  res.render(path.join(__dirname, 'start'));
});

/**
 * Basic routes for templates
 */
glob(path.join(__dirname, '*.html'), function(err, files) {
  files.forEach(function(file) {
    router.get('/' + path.basename(file, '.html'), function(req, res) {
      res.render(prototypeVersion + '/' + path.basename(file, '.html'));
    })
  });
});

/**
 * Landing page form
 */
router.post('/landing_page', function (req, res) {

  // Route people to the appropriate places dependant on what they chose
  switch(req.body.information) {
    case 'title_summary':
      return res.redirect('search');

      break;

    case 'full_title_documents':
      return res.redirect('https://eservices.landregistry.gov.uk/wps/portal/Property_Search');

      break;

    case 'official_copy':
      return res.redirect('https://www.gov.uk/government/publications/official-copies-of-register-or-plan-registration-oc1');

      break;
  }

  // Otherwise just render the form again
  // Equivalent to the form failing validation, except we don't have any server side in the proto
  res.render(path.join(__dirname, 'landing_page'));

});

/**
 * Search results
 */
router.get('/search_results', function (req, res) {
  var rpp = 20;

  // Equivalent to the form failing validation, except we don't have any server side in the proto
  if(!req.query.search_term) {
    res.render(path.join(__dirname, 'search'));
    return;
  }

  var data = {
    display_page_number: req.query.page ? req.query.page : 1,
    search_term: req.query.search_term,
    results: {
    }
  };

  require('./data')(req.query.search_term, function(titles) {
    data.results.titles = titles;

    // Total result count
    data.results.number_results = data.results.titles.length;
    data.results.number_pages = Math.ceil(data.results.number_results / rpp);

    // Restrict results to this page
    data.results.titles = data.results.titles.slice((data.display_page_number - 1) * rpp, data.display_page_number * rpp);

    return res.render(path.join(__dirname, 'search_results'), data);

  });

});

/**
 * Display title route
 */
router.get('/display_title', function (req, res) {

  if(typeof req.query.title_number === 'undefined') {
    return res.sendStatus(404);
  }

  // VAT receipt data
  var receipt = {
    date: moment().format('D MMM YYYY'),
    trans_id: casual.integer(4000000000, 5000000000),
    title_number: req.query.title_number,
    net: '2.50',
    vat: '0.50',
    total: '3.00',
    address1: 'HM Land Registry',
    address2: 'Trafalgar house',
    address3: '1 Bedford Park',
    address4: 'Croydon',
    postcode: 'CR0 2AQ',
    reg_number: 'GB 8888 181 53'
  }

  res.render(path.join(__dirname, 'display_title'), {
    receipt: receipt
  });

});

/**
 * Account creation forms
 */
router.all('/create_account:variant?', function(req, res) {
  var variant = '';
  if(typeof req.params.variant !== 'undefined') {
    variant = req.params.variant;
  }

  res.render(path.join(__dirname, 'create_account' + variant), {
    countries: countries
  });
});

/**
 * Password reset forms
 */
router.all('*/reset/:item/:section', function(req, res) {

  res.render(path.join(__dirname, 'reset_' + req.params.section), {
    item: req.params.item,
  });

});

module.exports = router;

<commit_msg>temp add pe12re signout route, until refactor pe12re<commit_after>var express = require('express');
var router = express.Router();
var path = require('path');
var moment = require('moment');
var casual = require('casual');
var yaml = require('js-yaml');
var glob = require('glob');

router.use('/images', express.static(path.join(__dirname, 'images')));

var prototypeVersion = path.basename(__dirname);

var countries = require('./country-records.json');
countries = countries.sort(function(a, b) {
  if(a.entry.name < b.entry.name) {
    return -1;
  }

  if(a.entry.name > b.entry.name) {
    return 1;
  }

  return 0;
});

/**
 * Sign in / out hack
 */
router.use(function (req, res, next) {
  // In order to quickly prototype sign in, if the GET or POST data sent to the
  // server contains either do_sign_in or do_sign_out values we will act
  // accordingly and sign the user in or out. No passwords are checked, no
  // accounts exist anywhere in any databases. This is a straight up hack
  // for prototyping purposes only. Move along now.

  // Default to not being logged in
  if(typeof req.session.isLoggedIn === 'undefined') {
    req.session.isLoggedIn = false;
  }

  // If we've been asked to sign in, reflect this in the session
  if(typeof req.query.do_sign_in !== 'undefined' || typeof req.body.do_sign_in !== 'undefined') {
    req.session.isLoggedIn = true;
    return next();
  }

  // If we've been asked to sign out, destroy the session
  else if(typeof req.query.do_sign_out !== 'undefined' || typeof req.body.do_sign_out !== 'undefined') {
    req.session.destroy(function(err) {
      next();
    });
  }

  else {
    next();
  }

});

/**
 * Sign in route
 */
router.get('/sign_in', function(req, res) {
  req.session.isLoggedIn = false;

  req.session.destroy(function() {
    res.render(path.join(__dirname, 'sign_in'));
  })
});

/**
 * Sign out route
 */
router.get('/sign_out', function(req, res) {
  req.session.isLoggedIn = false;

  req.session.destroy(function() {
    return res.render(path.join(__dirname, 'signed_out'));
  })
});

router.get('/sign_out', function(req, res) {
  req.session.isLoggedIn = false;

  req.session.destroy(function() {
    return res.render(path.join(__dirname, '/signed_out'));
  })
});

router.get('/pe12re/sign_out', function(req, res) {
  req.session.isLoggedIn = false;

  req.session.destroy(function() {
    return res.render(path.join(__dirname, '/pe12re/signed_out'));
  })
});

router.get('/', function(req, res) {
  res.render(path.join(__dirname, 'start'));
});

/**
 * Basic routes for templates
 */
glob(path.join(__dirname, '*.html'), function(err, files) {
  files.forEach(function(file) {
    router.get('/' + path.basename(file, '.html'), function(req, res) {
      res.render(prototypeVersion + '/' + path.basename(file, '.html'));
    })
  });
});

/**
 * Landing page form
 */
router.post('/landing_page', function (req, res) {

  // Route people to the appropriate places dependant on what they chose
  switch(req.body.information) {
    case 'title_summary':
      return res.redirect('search');

      break;

    case 'full_title_documents':
      return res.redirect('https://eservices.landregistry.gov.uk/wps/portal/Property_Search');

      break;

    case 'official_copy':
      return res.redirect('https://www.gov.uk/government/publications/official-copies-of-register-or-plan-registration-oc1');

      break;
  }

  // Otherwise just render the form again
  // Equivalent to the form failing validation, except we don't have any server side in the proto
  res.render(path.join(__dirname, 'landing_page'));

});

/**
 * Search results
 */
router.get('/search_results', function (req, res) {
  var rpp = 20;

  // Equivalent to the form failing validation, except we don't have any server side in the proto
  if(!req.query.search_term) {
    res.render(path.join(__dirname, 'search'));
    return;
  }

  var data = {
    display_page_number: req.query.page ? req.query.page : 1,
    search_term: req.query.search_term,
    results: {
    }
  };

  require('./data')(req.query.search_term, function(titles) {
    data.results.titles = titles;

    // Total result count
    data.results.number_results = data.results.titles.length;
    data.results.number_pages = Math.ceil(data.results.number_results / rpp);

    // Restrict results to this page
    data.results.titles = data.results.titles.slice((data.display_page_number - 1) * rpp, data.display_page_number * rpp);

    return res.render(path.join(__dirname, 'search_results'), data);

  });

});

/**
 * Display title route
 */
router.get('/display_title', function (req, res) {

  if(typeof req.query.title_number === 'undefined') {
    return res.sendStatus(404);
  }

  // VAT receipt data
  var receipt = {
    date: moment().format('D MMM YYYY'),
    trans_id: casual.integer(4000000000, 5000000000),
    title_number: req.query.title_number,
    net: '2.50',
    vat: '0.50',
    total: '3.00',
    address1: 'HM Land Registry',
    address2: 'Trafalgar house',
    address3: '1 Bedford Park',
    address4: 'Croydon',
    postcode: 'CR0 2AQ',
    reg_number: 'GB 8888 181 53'
  }

  res.render(path.join(__dirname, 'display_title'), {
    receipt: receipt
  });

});

/**
 * Account creation forms
 */
router.all('/create_account:variant?', function(req, res) {
  var variant = '';
  if(typeof req.params.variant !== 'undefined') {
    variant = req.params.variant;
  }

  res.render(path.join(__dirname, 'create_account' + variant), {
    countries: countries
  });
});

/**
 * Password reset forms
 */
router.all('*/reset/:item/:section', function(req, res) {

  res.render(path.join(__dirname, 'reset_' + req.params.section), {
    item: req.params.item,
  });

});

module.exports = router;

<|endoftext|>


<commit_before>import af from './translations/af'
import ar from './translations/ar'
import bg from './translations/bg'
import bs from './translations/bs'
import ca from './translations/ca'
import cs from './translations/cs'
import da from './translations/da'
import de from './translations/de'
import ee from './translations/ee'
import el from './translations/el'
import en from './translations/en'
import es from './translations/es'
import fa from './translations/fa'
import fi from './translations/fi'
import fr from './translations/fr'
import ge from './translations/ge'
import he from './translations/he'
import hr from './translations/hr'
import hu from './translations/hu'
import id from './translations/id'
import is from './translations/is'
import it from './translations/it'
import ja from './translations/ja'
import ko from './translations/ko'
import lb from './translations/lb'
import lt from './translations/lt'
import lv from './translations/lv'
import mn from './translations/mn'
import nbNO from './translations/nb-NO'
import nl from './translations/nl'
import pl from './translations/pl'
import ptBR from './translations/pt-BR'
import ro from './translations/ro'
import ru from './translations/ru'
import sk from './translations/sk'
import slSI from './translations/sl-SI'
import srCYRL from './translations/sr-CYRL'
import sr from './translations/sr'
import sv from './translations/sv'
import th from './translations/th'
import tr from './translations/tr'
import uk from './translations/uk'
import ur from './translations/ur'
import vi from './translations/vi'
import zh from './translations/zh'

export {
  af,
  ar,
  bg,
  bs,
  ca,
  cs,
  da,
  de,
  ee,
  el,
  en,
  es,
  fa,
  fi,
  fr,
  ge,
  he,
  hr,
  hu,
  id,
  is,
  it,
  ja,
  ko,
  lb,
  lt,
  lv,
  mn,
  nbNO,
  nl,
  pl,
  ptBR,
  ro,
  ru,
  sk,
  slSI,
  srCYRL,
  sr,
  sv,
  th,
  tr,
  uk,
  ur,
  vi,
  zh
}
// eslint-disable-next-line
;
<commit_msg>Update index.js<commit_after>import af from './translations/af'
import ar from './translations/ar'
import bg from './translations/bg'
import bs from './translations/bs'
import ca from './translations/ca'
import cs from './translations/cs'
import da from './translations/da'
import de from './translations/de'
import ee from './translations/ee'
import el from './translations/el'
import en from './translations/en'
import es from './translations/es'
import fa from './translations/fa'
import fi from './translations/fi'
import fo from './translations/fo'
import fr from './translations/fr'
import ge from './translations/ge'
import he from './translations/he'
import hr from './translations/hr'
import hu from './translations/hu'
import id from './translations/id'
import is from './translations/is'
import it from './translations/it'
import ja from './translations/ja'
import ko from './translations/ko'
import lb from './translations/lb'
import lt from './translations/lt'
import lv from './translations/lv'
import mn from './translations/mn'
import nbNO from './translations/nb-NO'
import nl from './translations/nl'
import pl from './translations/pl'
import ptBR from './translations/pt-BR'
import ro from './translations/ro'
import ru from './translations/ru'
import sk from './translations/sk'
import slSI from './translations/sl-SI'
import srCYRL from './translations/sr-CYRL'
import sr from './translations/sr'
import sv from './translations/sv'
import th from './translations/th'
import tr from './translations/tr'
import uk from './translations/uk'
import ur from './translations/ur'
import vi from './translations/vi'
import zh from './translations/zh'

export {
  af,
  ar,
  bg,
  bs,
  ca,
  cs,
  da,
  de,
  ee,
  el,
  en,
  es,
  fa,
  fi,
  fo,
  fr,
  ge,
  he,
  hr,
  hu,
  id,
  is,
  it,
  ja,
  ko,
  lb,
  lt,
  lv,
  mn,
  nbNO,
  nl,
  pl,
  ptBR,
  ro,
  ru,
  sk,
  slSI,
  srCYRL,
  sr,
  sv,
  th,
  tr,
  uk,
  ur,
  vi,
  zh
}
// eslint-disable-next-line
;
<|endoftext|>


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

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

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

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

 // onload
 // プリロード
 game.onload=function(){
  register_maps();
  game.rootScene.backgroundColor="#000000";
  map_manager.map_list["F1"].set_assets(game);
  game.pushScene(map_manager.map_list["F1"]);

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

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

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

function getGameObj(){
 return game;
}

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

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

 return termObj;
}

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

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

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

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

 // onload
 // プリロード
 game.onload=function(){
  register_maps();
  game.rootScene.backgroundColor="#000000";
  map_manager.map_list["F1"].set_assets(game);
  game.pushScene(map_manager.map_list["F1"]);

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

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

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

function getGameObj(){
 return game;
}

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

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

 return termObj;
}

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


<commit_before>var bigInt = require("big-integer");
var util = require("./util.js");

var minPrimeNumber = bigInt(2).pow(64);
var maxPrimeNumber = bigInt(2).pow(128);

function encryptRSA(str, publicKey) {
	return "$";
}

function decryptRSA(str, privateKey) {
	return "^";
}

function generateRSAKeys() {

	var primeP = util.getRandomBigIntPrime(minPrimeNumber, maxPrimeNumber);
	var primeQ = util.getRandomBigIntPrime(minPrimeNumber, maxPrimeNumber);
	var N = primeP.times(primeQ);
	var F = primeQ.prev().times(primeP.prev());
	var E = bigInt(0);

	do {
		E = util.getRandomBigIntPrime(2, F.prev());

	} while(bigInt.gcd(E, F).notEquals(1));
	var D = E.modInv(N);

	var key = {};
	key.publicKey =  { N: N.toString(), E : E };
	key.privateKey = { N: N, E: E, D: D, P: primeP, Q: primeQ };
	return key;

}

exports.generateRSAKeys = generateRSAKeys;
exports.decryptRSA = decryptRSA;
exports.encryptRSA = encryptRSA;
<commit_msg>Simplifies object creation.<commit_after>var bigInt = require("big-integer");
var util = require("./util.js");

var minPrimeNumber = bigInt(2).pow(64);
var maxPrimeNumber = bigInt(2).pow(128);

function encryptRSA(str, publicKey) {
	return "$";
}

function decryptRSA(str, privateKey) {
	return "^";
}

function generateRSAKeys() {

	var primeP = util.getRandomBigIntPrime(minPrimeNumber, maxPrimeNumber);
	var primeQ = util.getRandomBigIntPrime(minPrimeNumber, maxPrimeNumber);
	var N = primeP.times(primeQ);
	var F = primeQ.prev().times(primeP.prev());
	var E = bigInt(0);

	do {
		E = util.getRandomBigIntPrime(2, F.prev());

	} while(bigInt.gcd(E, F).notEquals(1));
	var D = E.modInv(N);

	var key = {};
	key.publicKey =  { N, E };
	key.privateKey = { N, E, D, P: primeP, Q: primeQ };
	return key;

}

exports.generateRSAKeys = generateRSAKeys;
exports.decryptRSA = decryptRSA;
exports.encryptRSA = encryptRSA;
<|endoftext|>


<commit_before>export function LazySeq(iterable){
	this.iterable = iterable || [];
}

LazySeq.prototype.push = function (v) {
	return this.concat(v);
};

// TODO create seq containing iterator, partially iterated
// we need this for transducers, because LazySeq is immutable
LazySeq.prototype["@@append"] = LazySeq.prototype.push;

LazySeq.prototype.__is_Seq = true;

LazySeq.prototype.concat = function (...v) {
	return new LazySeq(this.iterable.concat(v));
};

LazySeq.prototype.toString = function(){
	return "["+this.iterable+"]";
};

LazySeq.prototype.count = function(){
	return this.iterable.length;
};

Object.defineProperty(LazySeq.prototype,"size",{
	get:function(){
		return this.count();
	}
});

function SeqIterator(iterable) {
    this.iter = iterable[Symbol.iterator]();
}

SeqIterator.prototype["@@append"] = LazySeq.prototype.push;

SeqIterator.prototype["@@empty"] = function(){
	return new LazySeq();
};

const DONE = {
    done: true
};

SeqIterator.prototype.next = function () {
    var v = this.iter.next();
    if (v.done) return DONE;
    return v;
};

SeqIterator.prototype[Symbol.iterator] = function () {
    return this;
};

LazySeq.prototype[Symbol.iterator] = function () {
    return new SeqIterator(this.iterable);
};

export function toSeq(a){
	return new LazySeq(a);
}

export function seq(...a){
	return new LazySeq(a);
}

export function isSeq(a){
	return !!a && a.__is_Seq;
}

export const Seq = LazySeq;
<commit_msg>added operations<commit_after>export function LazySeq(iterable){
	this.iterable = isSeq(iterable) ? iterable.toArray() : iterable || [];
}

LazySeq.prototype.push = function (v) {
	return this.concat(v);
};

// TODO create seq containing iterator, partially iterated
// we need this for transducers, because LazySeq is immutable
LazySeq.prototype["@@append"] = LazySeq.prototype.push;

LazySeq.prototype.__is_Seq = true;

LazySeq.prototype.concat = function (...v) {
	return new LazySeq(this.iterable.concat(v));
};

LazySeq.prototype.toString = function(){
	return "["+this.iterable+"]";
};

LazySeq.prototype.count = function(){
	return this.iterable.length;
};

LazySeq.prototype.toArray = function() {
	return this.iterable;
};

Object.defineProperty(LazySeq.prototype,"size",{
	get:function(){
		return this.count();
	}
});

function SeqIterator(iterable) {
    this.iter = iterable[Symbol.iterator]();
}

SeqIterator.prototype["@@append"] = LazySeq.prototype.push;

SeqIterator.prototype["@@empty"] = function(){
	return new LazySeq();
};

const DONE = {
    done: true
};

SeqIterator.prototype.next = function () {
    var v = this.iter.next();
    if (v.done) return DONE;
    return v;
};

SeqIterator.prototype[Symbol.iterator] = function () {
    return this;
};

LazySeq.prototype[Symbol.iterator] = function () {
    return new SeqIterator(this.iterable);
};

function _isArray(a){
	return !!a && a.constructor == Array;
}

export function seq(...a){
	var ret = [];
	for(var i = 0, l = a.length; i < l; i++){
		var x = a[i];
		if(_isArray(x)) {
			//  assume flat
			ret = ret.concat(x);
		} else if(isSeq(x)){
			ret = ret.concat(x.toArray());
		} else {
			ret.push(x);
		}
	}
	return new LazySeq(ret);
}

export function isSeq(a){
	return !!a && a.__is_Seq;
}

export const Seq = LazySeq;

export const isEmpty = s => isSeq(s) && !s.count();

export const first = s => isSeq(s) ? _isArray(s.iterable) ? s.iterable[0] : _first(s.iterable) : s;

const undef = s => s === undefined || s === null;

export function empty(s){
    return isSeq(s) ? !s.count() : undef(s);
}

export function exists($i){
    return isSeq(s) ? !!s.count() : !undef(s);
}

export function count(s){
	return empty(s) ? 0 : isSeq(s) ? s.count() : undef(s) ? 0 : 1;
}

export function insertBefore(s,pos,ins) {
    pos = first(pos);
    pos = pos === 0 ? 1 : pos - 1;
	var a = s.toArray();
	var n = a.slice(0,pos);
	if(isSeq(ins)) {
		n = n.concat(ins.toArray());
	} else {
		n.push(ins);
	}
    return seq(n.concat(a.slice(pos)));
}
<|endoftext|>


<commit_before>// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview The test runner is a singleton object that is used to execute
 * a goog.testing.TestCases, display the results, and expose the results to
 * Selenium for automation.  If a TestCase hasn't been registered with the
 * runner by the time window.onload occurs, the testRunner will try to auto-
 * discover JsUnit style test pages.
 *
 * The hooks for selenium are (see http://go/selenium-hook-setup):-
 *  - Boolean G_testRunner.isFinished()
 *  - Boolean G_testRunner.isSuccess()
 *  - String G_testRunner.getReport()
 *  - number G_testRunner.getRunTime()
 *  - Object<string, Array<string>> G_testRunner.getTestResults()
 *
 * Testing code should not have dependencies outside of goog.testing so as to
 * reduce the chance of masking missing dependencies.
 *
 */

goog.setTestOnly('goog.testing.TestRunner');
goog.provide('goog.testing.TestRunner');

goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.testing.TestCase');

/**
 * Construct a test runner.
 *
 * NOTE(user): This is currently pretty weird, I'm essentially trying to
 * create a wrapper that the Selenium test can hook into to query the state of
 * the running test case, while making goog.testing.TestCase general.
 *
 * @constructor
 */
goog.testing.TestRunner = function() {
  /**
   * Errors that occurred in the window.
   * @type {!Array<string>}
   */
  this.errors = [];

  /**
   * Reference to the active test case.
   * @type {?goog.testing.TestCase}
   */
  this.testCase = null;

  /**
   * Whether the test runner has been initialized yet.
   * @type {boolean}
   */
  this.initialized = false;

  /**
   * Element created in the document to add test results to.
   * @private {?Element}
   */
  this.logEl_ = null;

  /**
   * Function to use when filtering errors.
   * @private {(function(string))?}
   */
  this.errorFilter_ = null;

  /**
   * Whether an empty test case counts as an error.
   * @private {boolean}
   */
  this.strict_ = true;
};

/**
 * Initializes the test runner.
 * @param {goog.testing.TestCase} testCase The test case to initialize with.
 */
goog.testing.TestRunner.prototype.initialize = function(testCase) {
  if (this.testCase && this.testCase.running) {
    throw Error('The test runner is already waiting for a test to complete');
  }
  this.testCase = testCase;
  this.initialized = true;
};

/**
 * By default, the test runner is strict, and fails if it runs an empty
 * test case.
 * @param {boolean} strict Whether the test runner should fail on an empty
 *     test case.
 */
goog.testing.TestRunner.prototype.setStrict = function(strict) {
  this.strict_ = strict;
};

/**
 * @return {boolean} Whether the test runner should fail on an empty
 *     test case.
 */
goog.testing.TestRunner.prototype.isStrict = function() {
  return this.strict_;
};

/**
 * Returns true if the test runner is initialized.
 * Used by Selenium Hooks.
 * @return {boolean} Whether the test runner is active.
 */
goog.testing.TestRunner.prototype.isInitialized = function() {
  return this.initialized;
};

/**
 * Returns true if the test runner is finished.
 * Used by Selenium Hooks.
 * @return {boolean} Whether the test runner is active.
 */
goog.testing.TestRunner.prototype.isFinished = function() {
  return this.errors.length > 0 ||
      this.initialized && !!this.testCase && this.testCase.started &&
      !this.testCase.running;
};

/**
 * Returns true if the test case didn't fail.
 * Used by Selenium Hooks.
 * @return {boolean} Whether the current test returned successfully.
 */
goog.testing.TestRunner.prototype.isSuccess = function() {
  return !this.hasErrors() && !!this.testCase && this.testCase.isSuccess();
};

/**
 * Returns true if the test case runner has errors that were caught outside of
 * the test case.
 * @return {boolean} Whether there were JS errors.
 */
goog.testing.TestRunner.prototype.hasErrors = function() {
  return this.errors.length > 0;
};

/**
 * Logs an error that occurred.  Used in the case of environment setting up
 * an onerror handler.
 * @param {string} msg Error message.
 */
goog.testing.TestRunner.prototype.logError = function(msg) {
  if (!this.errorFilter_ || this.errorFilter_.call(null, msg)) {
    this.errors.push(msg);
  }
};

/**
 * Log failure in current running test.
 * @param {Error} ex Exception.
 */
goog.testing.TestRunner.prototype.logTestFailure = function(ex) {
  var testName = /** @type {string} */ (goog.testing.TestCase.currentTestName);
  if (this.testCase) {
    this.testCase.logError(testName, ex);
  } else {
    // NOTE: Do not forget to log the original exception raised.
    throw new Error(
        'Test runner not initialized with a test case. Original ' +
        'exception: ' + ex.message);
  }
};

/**
 * Sets a function to use as a filter for errors.
 * @param {function(string)} fn Filter function.
 */
goog.testing.TestRunner.prototype.setErrorFilter = function(fn) {
  this.errorFilter_ = fn;
};

/**
 * Returns a report of the test case that ran.
 * Used by Selenium Hooks.
 * @param {boolean=} opt_verbose If true results will include data about all
 *     tests, not just what failed.
 * @return {string} A report summary of the test.
 */
goog.testing.TestRunner.prototype.getReport = function(opt_verbose) {
  var report = [];
  if (this.testCase) {
    report.push(this.testCase.getReport(opt_verbose));
  }
  if (this.errors.length > 0) {
    report.push('JavaScript errors detected by test runner:');
    report.push.apply(report, this.errors);
    report.push('\n');
  }
  return report.join('\n');
};

/**
 * Returns the amount of time it took for the test to run.
 * Used by Selenium Hooks.
 * @return {number} The run time, in milliseconds.
 */
goog.testing.TestRunner.prototype.getRunTime = function() {
  return this.testCase ? this.testCase.getRunTime() : 0;
};

/**
 * Returns the number of script files that were loaded in order to run the test.
 * @return {number} The number of script files.
 */
goog.testing.TestRunner.prototype.getNumFilesLoaded = function() {
  return this.testCase ? this.testCase.getNumFilesLoaded() : 0;
};

/**
 * Executes a test case and prints the results to the window.
 */
goog.testing.TestRunner.prototype.execute = function() {
  if (!this.testCase) {
    throw Error(
        'The test runner must be initialized with a test case ' +
        'before execute can be called.');
  }

  if (this.strict_ && this.testCase.getCount() == 0) {
    throw Error(
        'No tests found in given test case: ' + this.testCase.getName() + '. ' +
        'By default, the test runner fails if a test case has no tests. ' +
        'To modify this behavior, see goog.testing.TestRunner\'s ' +
        'setStrict() method, or G_testRunner.setStrict()');
  }

  this.testCase.setCompletedCallback(goog.bind(this.onComplete_, this));
  if (goog.testing.TestRunner.shouldUsePromises_(this.testCase)) {
    this.testCase.runTestsReturningPromise();
  } else {
    this.testCase.runTests();
  }
};

/**
 * @param {!goog.testing.TestCase} testCase
 * @return {boolean}
 * @private
 */
goog.testing.TestRunner.shouldUsePromises_ = function(testCase) {
  return testCase.constructor === goog.testing.TestCase;
};

/**
 * Writes the results to the document when the test case completes.
 * @private
 */
goog.testing.TestRunner.prototype.onComplete_ = function() {
  var log = this.testCase.getReport(true);
  if (this.errors.length > 0) {
    log += '\n' + this.errors.join('\n');
  }

  if (!this.logEl_) {
    var el = document.getElementById('closureTestRunnerLog');
    if (el == null) {
      el = goog.dom.createElement(goog.dom.TagName.DIV);
      document.body.appendChild(el);
    }
    this.logEl_ = el;
  }

  // Highlight the page to indicate the overall outcome.
  this.writeLog(log);

  // TODO(chrishenry): Make this work with multiple test cases (b/8603638).
  var runAgainLink = goog.dom.createElement(goog.dom.TagName.A);
  runAgainLink.style.display = 'inline-block';
  runAgainLink.style.fontSize = 'small';
  runAgainLink.style.marginBottom = '16px';
  runAgainLink.href = '';
  runAgainLink.onclick = goog.bind(function() {
    this.execute();
    return false;
  }, this);
  runAgainLink.innerHTML = 'Run again without reloading';
  this.logEl_.appendChild(runAgainLink);
};

/**
 * Writes a nicely formatted log out to the document.
 * @param {string} log The string to write.
 */
goog.testing.TestRunner.prototype.writeLog = function(log) {
  var lines = log.split('\n');
  for (var i = 0; i < lines.length; i++) {
    var line = lines[i];
    var color;
    var isFailOrError = /FAILED/.test(line) || /ERROR/.test(line);
    if (/PASSED/.test(line)) {
      color = 'darkgreen';
    } else if (isFailOrError) {
      color = 'darkred';
    } else {
      color = '#333';
    }
    var div = goog.dom.createElement(goog.dom.TagName.DIV);
    if (line.substr(0, 2) == '> ') {
      // The stack trace may contain links so it has to be interpreted as HTML.
      div.innerHTML = line;
    } else {
      div.appendChild(document.createTextNode(line));
    }

    var testNameMatch = /(\S+) (\[[^\]]*] )?: (FAILED|ERROR|PASSED)/.exec(line);
    if (testNameMatch) {
      // Build a URL to run the test individually.  If this test was already
      // part of another subset test, we need to overwrite the old runTests
      // query parameter.  We also need to do this without bringing in any
      // extra dependencies, otherwise we could mask missing dependency bugs.
      var newSearch = 'runTests=' + testNameMatch[1];
      var search = window.location.search;
      if (search) {
        var oldTests = /runTests=([^&]*)/.exec(search);
        if (oldTests) {
          newSearch = search.substr(0, oldTests.index) + newSearch +
              search.substr(oldTests.index + oldTests[0].length);
        } else {
          newSearch = search + '&' + newSearch;
        }
      } else {
        newSearch = '?' + newSearch;
      }
      var href = window.location.href;
      var hash = window.location.hash;
      if (hash && hash.charAt(0) != '#') {
        hash = '#' + hash;
      }
      href = href.split('#')[0].split('?')[0] + newSearch + hash;

      // Add the link.
      var a = goog.dom.createElement(goog.dom.TagName.A);
      a.innerHTML = '(run individually)';
      a.style.fontSize = '0.8em';
      a.style.color = '#888';
      a.href = href;
      div.appendChild(document.createTextNode(' '));
      div.appendChild(a);
    }

    div.style.color = color;
    div.style.font = 'normal 100% monospace';
    div.style.wordWrap = 'break-word';
    if (i == 0) {
      // Highlight the first line as a header that indicates the test outcome.
      div.style.padding = '20px';
      div.style.marginBottom = '10px';
      if (isFailOrError) {
        div.style.border = '5px solid ' + color;
        div.style.backgroundColor = '#ffeeee';
      } else {
        div.style.border = '1px solid black';
        div.style.backgroundColor = '#eeffee';
      }
    }

    try {
      div.style.whiteSpace = 'pre-wrap';
    } catch (e) {
      // NOTE(brenneman): IE raises an exception when assigning to pre-wrap.
      // Thankfully, it doesn't collapse whitespace when using monospace fonts,
      // so it will display correctly if we ignore the exception.
    }

    if (i < 2) {
      div.style.fontWeight = 'bold';
    }
    this.logEl_.appendChild(div);
  }
};

/**
 * Logs a message to the current test case.
 * @param {string} s The text to output to the log.
 */
goog.testing.TestRunner.prototype.log = function(s) {
  if (this.testCase) {
    this.testCase.log(s);
  }
};

// TODO(nnaze): Properly handle serving test results when multiple test cases
// are run.
/**
 * @return {Object<string, !Array<string>>} A map of test names to a list of
 * test failures (if any) to provide formatted data for the test runner.
 */
goog.testing.TestRunner.prototype.getTestResults = function() {
  if (this.testCase) {
    return this.testCase.getTestResults();
  }
  return null;
};
<commit_msg>Set an ID on closureTestRunnerLog when creating it if it doesn't exist.<commit_after>// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview The test runner is a singleton object that is used to execute
 * a goog.testing.TestCases, display the results, and expose the results to
 * Selenium for automation.  If a TestCase hasn't been registered with the
 * runner by the time window.onload occurs, the testRunner will try to auto-
 * discover JsUnit style test pages.
 *
 * The hooks for selenium are (see http://go/selenium-hook-setup):-
 *  - Boolean G_testRunner.isFinished()
 *  - Boolean G_testRunner.isSuccess()
 *  - String G_testRunner.getReport()
 *  - number G_testRunner.getRunTime()
 *  - Object<string, Array<string>> G_testRunner.getTestResults()
 *
 * Testing code should not have dependencies outside of goog.testing so as to
 * reduce the chance of masking missing dependencies.
 *
 */

goog.setTestOnly('goog.testing.TestRunner');
goog.provide('goog.testing.TestRunner');

goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.testing.TestCase');

/**
 * Construct a test runner.
 *
 * NOTE(user): This is currently pretty weird, I'm essentially trying to
 * create a wrapper that the Selenium test can hook into to query the state of
 * the running test case, while making goog.testing.TestCase general.
 *
 * @constructor
 */
goog.testing.TestRunner = function() {
  /**
   * Errors that occurred in the window.
   * @type {!Array<string>}
   */
  this.errors = [];

  /**
   * Reference to the active test case.
   * @type {?goog.testing.TestCase}
   */
  this.testCase = null;

  /**
   * Whether the test runner has been initialized yet.
   * @type {boolean}
   */
  this.initialized = false;

  /**
   * Element created in the document to add test results to.
   * @private {?Element}
   */
  this.logEl_ = null;

  /**
   * Function to use when filtering errors.
   * @private {(function(string))?}
   */
  this.errorFilter_ = null;

  /**
   * Whether an empty test case counts as an error.
   * @private {boolean}
   */
  this.strict_ = true;
};

/**
 * Initializes the test runner.
 * @param {goog.testing.TestCase} testCase The test case to initialize with.
 */
goog.testing.TestRunner.prototype.initialize = function(testCase) {
  if (this.testCase && this.testCase.running) {
    throw Error('The test runner is already waiting for a test to complete');
  }
  this.testCase = testCase;
  this.initialized = true;
};

/**
 * By default, the test runner is strict, and fails if it runs an empty
 * test case.
 * @param {boolean} strict Whether the test runner should fail on an empty
 *     test case.
 */
goog.testing.TestRunner.prototype.setStrict = function(strict) {
  this.strict_ = strict;
};

/**
 * @return {boolean} Whether the test runner should fail on an empty
 *     test case.
 */
goog.testing.TestRunner.prototype.isStrict = function() {
  return this.strict_;
};

/**
 * Returns true if the test runner is initialized.
 * Used by Selenium Hooks.
 * @return {boolean} Whether the test runner is active.
 */
goog.testing.TestRunner.prototype.isInitialized = function() {
  return this.initialized;
};

/**
 * Returns true if the test runner is finished.
 * Used by Selenium Hooks.
 * @return {boolean} Whether the test runner is active.
 */
goog.testing.TestRunner.prototype.isFinished = function() {
  return this.errors.length > 0 ||
      this.initialized && !!this.testCase && this.testCase.started &&
      !this.testCase.running;
};

/**
 * Returns true if the test case didn't fail.
 * Used by Selenium Hooks.
 * @return {boolean} Whether the current test returned successfully.
 */
goog.testing.TestRunner.prototype.isSuccess = function() {
  return !this.hasErrors() && !!this.testCase && this.testCase.isSuccess();
};

/**
 * Returns true if the test case runner has errors that were caught outside of
 * the test case.
 * @return {boolean} Whether there were JS errors.
 */
goog.testing.TestRunner.prototype.hasErrors = function() {
  return this.errors.length > 0;
};

/**
 * Logs an error that occurred.  Used in the case of environment setting up
 * an onerror handler.
 * @param {string} msg Error message.
 */
goog.testing.TestRunner.prototype.logError = function(msg) {
  if (!this.errorFilter_ || this.errorFilter_.call(null, msg)) {
    this.errors.push(msg);
  }
};

/**
 * Log failure in current running test.
 * @param {Error} ex Exception.
 */
goog.testing.TestRunner.prototype.logTestFailure = function(ex) {
  var testName = /** @type {string} */ (goog.testing.TestCase.currentTestName);
  if (this.testCase) {
    this.testCase.logError(testName, ex);
  } else {
    // NOTE: Do not forget to log the original exception raised.
    throw new Error(
        'Test runner not initialized with a test case. Original ' +
        'exception: ' + ex.message);
  }
};

/**
 * Sets a function to use as a filter for errors.
 * @param {function(string)} fn Filter function.
 */
goog.testing.TestRunner.prototype.setErrorFilter = function(fn) {
  this.errorFilter_ = fn;
};

/**
 * Returns a report of the test case that ran.
 * Used by Selenium Hooks.
 * @param {boolean=} opt_verbose If true results will include data about all
 *     tests, not just what failed.
 * @return {string} A report summary of the test.
 */
goog.testing.TestRunner.prototype.getReport = function(opt_verbose) {
  var report = [];
  if (this.testCase) {
    report.push(this.testCase.getReport(opt_verbose));
  }
  if (this.errors.length > 0) {
    report.push('JavaScript errors detected by test runner:');
    report.push.apply(report, this.errors);
    report.push('\n');
  }
  return report.join('\n');
};

/**
 * Returns the amount of time it took for the test to run.
 * Used by Selenium Hooks.
 * @return {number} The run time, in milliseconds.
 */
goog.testing.TestRunner.prototype.getRunTime = function() {
  return this.testCase ? this.testCase.getRunTime() : 0;
};

/**
 * Returns the number of script files that were loaded in order to run the test.
 * @return {number} The number of script files.
 */
goog.testing.TestRunner.prototype.getNumFilesLoaded = function() {
  return this.testCase ? this.testCase.getNumFilesLoaded() : 0;
};

/**
 * Executes a test case and prints the results to the window.
 */
goog.testing.TestRunner.prototype.execute = function() {
  if (!this.testCase) {
    throw Error(
        'The test runner must be initialized with a test case ' +
        'before execute can be called.');
  }

  if (this.strict_ && this.testCase.getCount() == 0) {
    throw Error(
        'No tests found in given test case: ' + this.testCase.getName() + '. ' +
        'By default, the test runner fails if a test case has no tests. ' +
        'To modify this behavior, see goog.testing.TestRunner\'s ' +
        'setStrict() method, or G_testRunner.setStrict()');
  }

  this.testCase.setCompletedCallback(goog.bind(this.onComplete_, this));
  if (goog.testing.TestRunner.shouldUsePromises_(this.testCase)) {
    this.testCase.runTestsReturningPromise();
  } else {
    this.testCase.runTests();
  }
};

/**
 * @param {!goog.testing.TestCase} testCase
 * @return {boolean}
 * @private
 */
goog.testing.TestRunner.shouldUsePromises_ = function(testCase) {
  return testCase.constructor === goog.testing.TestCase;
};

/** @const {string} The ID of the element to log output to. */
goog.testing.TestRunner.TEST_LOG_ID = 'closureTestRunnerLog';

/**
 * Writes the results to the document when the test case completes.
 * @private
 */
goog.testing.TestRunner.prototype.onComplete_ = function() {
  var log = this.testCase.getReport(true);
  if (this.errors.length > 0) {
    log += '\n' + this.errors.join('\n');
  }

  if (!this.logEl_) {
    var el = document.getElementById(goog.testing.TestRunner.TEST_LOG_ID);
    if (el == null) {
      el = goog.dom.createDom(
          goog.dom.TagName.DIV, {id: goog.testing.TestRunner.TEST_LOG_ID});
      document.body.appendChild(el);
    }
    this.logEl_ = el;
  }

  // Highlight the page to indicate the overall outcome.
  this.writeLog(log);

  // TODO(chrishenry): Make this work with multiple test cases (b/8603638).
  var runAgainLink = goog.dom.createElement(goog.dom.TagName.A);
  runAgainLink.style.display = 'inline-block';
  runAgainLink.style.fontSize = 'small';
  runAgainLink.style.marginBottom = '16px';
  runAgainLink.href = '';
  runAgainLink.onclick = goog.bind(function() {
    this.execute();
    return false;
  }, this);
  runAgainLink.innerHTML = 'Run again without reloading';
  this.logEl_.appendChild(runAgainLink);
};

/**
 * Writes a nicely formatted log out to the document.
 * @param {string} log The string to write.
 */
goog.testing.TestRunner.prototype.writeLog = function(log) {
  var lines = log.split('\n');
  for (var i = 0; i < lines.length; i++) {
    var line = lines[i];
    var color;
    var isFailOrError = /FAILED/.test(line) || /ERROR/.test(line);
    if (/PASSED/.test(line)) {
      color = 'darkgreen';
    } else if (isFailOrError) {
      color = 'darkred';
    } else {
      color = '#333';
    }
    var div = goog.dom.createElement(goog.dom.TagName.DIV);
    if (line.substr(0, 2) == '> ') {
      // The stack trace may contain links so it has to be interpreted as HTML.
      div.innerHTML = line;
    } else {
      div.appendChild(document.createTextNode(line));
    }

    var testNameMatch = /(\S+) (\[[^\]]*] )?: (FAILED|ERROR|PASSED)/.exec(line);
    if (testNameMatch) {
      // Build a URL to run the test individually.  If this test was already
      // part of another subset test, we need to overwrite the old runTests
      // query parameter.  We also need to do this without bringing in any
      // extra dependencies, otherwise we could mask missing dependency bugs.
      var newSearch = 'runTests=' + testNameMatch[1];
      var search = window.location.search;
      if (search) {
        var oldTests = /runTests=([^&]*)/.exec(search);
        if (oldTests) {
          newSearch = search.substr(0, oldTests.index) + newSearch +
              search.substr(oldTests.index + oldTests[0].length);
        } else {
          newSearch = search + '&' + newSearch;
        }
      } else {
        newSearch = '?' + newSearch;
      }
      var href = window.location.href;
      var hash = window.location.hash;
      if (hash && hash.charAt(0) != '#') {
        hash = '#' + hash;
      }
      href = href.split('#')[0].split('?')[0] + newSearch + hash;

      // Add the link.
      var a = goog.dom.createElement(goog.dom.TagName.A);
      a.innerHTML = '(run individually)';
      a.style.fontSize = '0.8em';
      a.style.color = '#888';
      a.href = href;
      div.appendChild(document.createTextNode(' '));
      div.appendChild(a);
    }

    div.style.color = color;
    div.style.font = 'normal 100% monospace';
    div.style.wordWrap = 'break-word';
    if (i == 0) {
      // Highlight the first line as a header that indicates the test outcome.
      div.style.padding = '20px';
      div.style.marginBottom = '10px';
      if (isFailOrError) {
        div.style.border = '5px solid ' + color;
        div.style.backgroundColor = '#ffeeee';
      } else {
        div.style.border = '1px solid black';
        div.style.backgroundColor = '#eeffee';
      }
    }

    try {
      div.style.whiteSpace = 'pre-wrap';
    } catch (e) {
      // NOTE(brenneman): IE raises an exception when assigning to pre-wrap.
      // Thankfully, it doesn't collapse whitespace when using monospace fonts,
      // so it will display correctly if we ignore the exception.
    }

    if (i < 2) {
      div.style.fontWeight = 'bold';
    }
    this.logEl_.appendChild(div);
  }
};

/**
 * Logs a message to the current test case.
 * @param {string} s The text to output to the log.
 */
goog.testing.TestRunner.prototype.log = function(s) {
  if (this.testCase) {
    this.testCase.log(s);
  }
};

// TODO(nnaze): Properly handle serving test results when multiple test cases
// are run.
/**
 * @return {Object<string, !Array<string>>} A map of test names to a list of
 * test failures (if any) to provide formatted data for the test runner.
 */
goog.testing.TestRunner.prototype.getTestResults = function() {
  if (this.testCase) {
    return this.testCase.getTestResults();
  }
  return null;
};
<|endoftext|>


<commit_before>
const os = require('os')

const { logger } = require('./logs')

const networkInterfaces = Object.entries(os.networkInterfaces())
  .map(([name, interfaces]) => [name, interfaces.filter(i => i.family === 'IPv4')])
  .filter(([name, interfaces]) => interfaces.length)
  .map(([name, interfaces]) => ({ [name]: interfaces }))
  .reduce((obj, entry) => Object.assign(obj, entry), {})

exports.networkInterfaces = () => networkInterfaces

exports.getIp = networkInterface => {
  networkInterface = networkInterface || Object.keys(networkInterfaces)[0]

  logger.info(`Network interfaces: ${networkInterfaces} Active: ${networkInterfaces[networkInterface]}`)

  if (networkInterfaces[networkInterface]) {
    return networkInterfaces[networkInterface][0].address
  } else {
    logger.warn('Running in offline mode')
    return '127.0.0.1'
  }
}
<commit_msg>FIX ip logging again<commit_after>
const os = require('os')

const { logger } = require('./logs')

const networkInterfaces = Object.entries(os.networkInterfaces())
  .map(([name, interfaces]) => [name, interfaces.filter(i => i.family === 'IPv4')])
  .filter(([name, interfaces]) => interfaces.length)
  .map(([name, interfaces]) => ({ [name]: interfaces }))
  .reduce((obj, entry) => Object.assign(obj, entry), {})

exports.networkInterfaces = () => networkInterfaces

exports.getIp = networkInterface => {
  networkInterface = networkInterface || Object.keys(networkInterfaces)[0]

  logger.info(`Network interfaces: ${JSON.stringify(networkInterfaces)} Active: ${JSON.stringify(networkInterfaces[networkInterface])}`)

  if (networkInterfaces[networkInterface]) {
    return networkInterfaces[networkInterface][0].address
  } else {
    logger.warn('Running in offline mode')
    return '127.0.0.1'
  }
}
<|endoftext|>


<commit_before>/*!
    Copyright (C) 2014 Google Inc., authors, and contributors <see AUTHORS file>
    Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
    Created By: dan@reciprocitylabs.com
    Maintained By: dan@reciprocitylabs.com
*/

(function(can) {

  var _mustache_path,
      overdue_compute;

  overdue_compute = can.compute(function(val) {
    if (this.attr("status") === "Verified") {
      return "";
    }
    var date = moment(this.attr("next_due_date") || this.attr("end_date"));
    if(date && date.isBefore(new Date())){
      return "overdue";
    }
    return "";
  });

  function refresh_attr(instance, attr){
    if (instance.attr(attr).reify().selfLink) {
      instance.attr(attr).reify().refresh();
    }
  }

  function refresh_attr_wrap(attr){
    return function(ev, instance) {
      if (instance instanceof this) {
        refresh_attr(instance, attr);
      }
    };
  }

  _mustache_path = GGRC.mustache_path + "/cycles";
  can.Model.Cacheable("CMS.Models.Cycle", {
    root_object: "cycle",
    root_collection: "cycles",
    category: "workflow",
    findAll: "GET /api/cycles",
    findOne: "GET /api/cycles/{id}",
    create: "POST /api/cycles",
    update: "PUT /api/cycles/{id}",
    destroy: "DELETE /api/cycles/{id}",

    attributes: {
      workflow: "CMS.Models.Workflow.stub",
      cycle_task_groups: "CMS.Models.CycleTaskGroup.stubs",
      modified_by: "CMS.Models.Person.stub",
      context: "CMS.Models.Context.stub"
    },

    tree_view_options: {
      show_view: _mustache_path + "/tree.mustache",
      header_view : _mustache_path + "/tree_header.mustache",
      draw_children: true,
      child_options: [
        {
          model: "CycleTaskGroup",
          mapping: "cycle_task_groups",
          allow_creating: false
        }
      ]
    },
    init: function(){
      var that = this;
      this._super.apply(this, arguments);
      this.bind("created", refresh_attr_wrap('workflow').bind(this));
      this.bind("destroyed", function(ev, inst) {
        if(inst instanceof that) {
          can.each(inst.cycle_task_groups, function(cycle_task_group) {
            if (!cycle_task_group) {
              return;
            }
            cycle_task_group = cycle_task_group.reify();
            can.trigger(cycle_task_group, "destroyed");
            can.trigger(cycle_task_group.constructor, "destroyed", cycle_task_group);
          });
        }
      });
    }
  }, {
    init: function() {
      var that = this;
      this._super.apply(this, arguments);
      this.bind("status", function(ev, newVal) {
        if (newVal === 'Verified') {
          new RefreshQueue().enqueue(this.workflow.reify()).trigger().then(function(wfs) {
            return wfs[0].get_binding("owners").refresh_instances();
          }).then(function(wf_owner_bindings) {
            var current_user = CMS.Models.get_instance(GGRC.current_user);
            if(~can.inArray(
              current_user,
              can.map(wf_owner_bindings, function(wf_owner_binding) {
                return wf_owner_binding.instance;
              })
            )) {
              that.refresh().then(function() {
                if(that.attr("is_current")) {
                  that.attr("is_current", false);
                  that.save();
                }
              });
            }
          });
        }
      });
    },
    overdue: overdue_compute,
  });

  _mustache_path = GGRC.mustache_path + "/cycle_task_entries";
  can.Model.Cacheable("CMS.Models.CycleTaskEntry", {
    root_object: "cycle_task_entry",
    root_collection: "cycle_task_entries",
    category: "workflow",
    findAll: "GET /api/cycle_task_entries",
    findOne: "GET /api/cycle_task_entries/{id}",
    create: "POST /api/cycle_task_entries",
    update: "PUT /api/cycle_task_entries/{id}",
    destroy: "DELETE /api/cycle_task_entries/{id}",

    attributes: {
      cycle_task_group_object_task: "CMS.Models.CycleTaskGroupObjectTask.stub",
      modified_by: "CMS.Models.Person.stub",
      context: "CMS.Models.Context.stub",
      object_documents: "CMS.Models.ObjectDocument.stubs",
      documents: "CMS.Models.Document.stubs",
      cycle: "CMS.Models.Cycle.stub"
    },

    tree_view_options: {
      show_view: _mustache_path + "/tree.mustache",
      footer_view: _mustache_path + "/tree_footer.mustache",
      child_options: [{
        //0: Documents
        model: "Document",
        mapping: "documents",
        show_view: _mustache_path + "/documents.mustache",
        footer_view: _mustache_path + "/documents_footer.mustache"
      }],
    },
    init: function(){
      this._super.apply(this, arguments);
      this.bind("created",
        refresh_attr_wrap("cycle_task_group_object_task").bind(this));
      this.validateNonBlank("description");
    }
  }, {
    workflowFolder: function() {
      return this.refresh_all('cycle', 'workflow').then(function(workflow){
        if (workflow.has_binding('folders')) {
          return workflow.refresh_all('folders').then(function(folders){
            if (folders.length === 0) {
              return null;  // workflow folder has not been assigned
            }
            return folders[0].instance;
          }, function(result) {
            return result;
          });
        }
      });
    }
  });

  _mustache_path = GGRC.mustache_path + "/cycle_task_groups";
  can.Model.Cacheable("CMS.Models.CycleTaskGroup", {
    root_object: "cycle_task_group",
    root_collection: "cycle_task_groups",
    category: "workflow",
    findAll: "GET /api/cycle_task_groups",
    findOne: "GET /api/cycle_task_groups/{id}",
    create: "POST /api/cycle_task_groups",
    update: "PUT /api/cycle_task_groups/{id}",
    destroy: "DELETE /api/cycle_task_groups/{id}",

    attributes: {
      cycle: "CMS.Models.Cycle.stub",
      task_group: "CMS.Models.TaskGroup.stub",
      cycle_task_group_tasks: "CMS.Models.CycleTaskGroupObjectTask.stubs",
      modified_by: "CMS.Models.Person.stub",
      context: "CMS.Models.Context.stub"
    },

    tree_view_options: {
      sort_property: 'sort_index',
      show_view: _mustache_path + "/tree.mustache",
      //footer_view: _mustache_path + "/tree_footer.mustache",
      draw_children: true,
      child_options: [
        {
          title: 'Tasks',
          model: "CycleTaskGroupObjectTask",
          mapping: "cycle_task_group_tasks",
          allow_creating: false
        }
      ]
    },

    init: function() {
      var that = this;
      this._super.apply(this, arguments);

      this.validateNonBlank("contact");
      this.validateContact(["_transient.contact", "contact"]);
      this.bind("updated", function(ev, instance) {
        if (instance instanceof that) {
          var dfd = instance.refresh_all_force('cycle', 'workflow');
          dfd.then(function(){
            return $.when(
              instance.refresh_all_force('related_objects'),
              instance.refresh_all_force('cycle_task_group_tasks')
            );
          });
        }
      });
      this.bind("destroyed", function(ev, inst) {
        if(inst instanceof that) {
          can.each(inst.cycle_task_group_tasks, function(ctgt) {
            if (!ctgt) {
              return;
            }
            ctgt = ctgt.reify();
            can.trigger(ctgt, "destroyed");
            can.trigger(ctgt.constructor, "destroyed", ctgt);
          });
        }
      });
    }
  }, {
    overdue: overdue_compute
  });

  _mustache_path = GGRC.mustache_path + "/cycle_task_group_object_tasks";
  can.Model.Cacheable("CMS.Models.CycleTaskGroupObjectTask", {
    root_object: "cycle_task_group_object_task",
    root_collection: "cycle_task_group_object_tasks",
    category: "workflow",
    findAll: "GET /api/cycle_task_group_object_tasks",
    findOne: "GET /api/cycle_task_group_object_tasks/{id}",
    create: "POST /api/cycle_task_group_object_tasks",
    update: "PUT /api/cycle_task_group_object_tasks/{id}",
    destroy: "DELETE /api/cycle_task_group_object_tasks/{id}",
    title_singular: "Cycle Task",

    attributes: {
      cycle_task_group: "CMS.Models.CycleTaskGroup.stub",
      task_group_task: "CMS.Models.TaskGroupTask.stub",
      cycle_task_entries: "CMS.Models.CycleTaskEntry.stubs",
      modified_by: "CMS.Models.Person.stub",
      contact: "CMS.Models.Person.stub",
      context: "CMS.Models.Context.stub",
      cycle: "CMS.Models.Cycle.stub"
    },
    permalink_options: {
      url: "<%= base.viewLink %>#current_widget/cycle/<%= instance.cycle.id %>/cycle_task_group/<%= instance.cycle_task_group.id %>/cycle_task_group_object_task/<%= instance.id %>",
      base: "cycle:workflow"
    },
    info_pane_options: {
      mapped_objects: {
        model: can.Model.Cacheable,
        mapping: 'info_related_objects',
        show_view: GGRC.mustache_path + '/base_templates/subtree.mustache'
      }
    },
    tree_view_options: {
      sort_property: 'sort_index',
      show_view: _mustache_path + "/tree.mustache",
      attr_list: [
        {attr_title: 'Title', attr_name: 'title'},
        {attr_title: 'Workflow', attr_name: 'workflow', attr_sort_field: 'cycle.workflow.title'},
        {attr_title: 'State', attr_name: 'status'},
        {attr_title: 'Assignee', attr_name: 'assignee', attr_sort_field: 'contact.name|email'},
        {attr_title: 'Start Date', attr_name: 'start_date'},
        {attr_title: 'End Date', attr_name: 'end_date'},
        {attr_title: 'Last Updated', attr_name: 'updated_at'}
      ],
      display_attr_names: ['title', 'mapped_object', 'workflow'],
      mandatory_attr_name: ['title'],
      draw_children: true,
      child_options: [
        {
          model: "CycleTaskEntry",
          mapping: "cycle_task_entries",
          allow_creating: true
        },
        {
          model: can.Model.Cacheable,
          mapping: 'info_related_objects',
          allow_creating: true
        }
      ]
    },

    init: function() {
      var that = this;
      this._super.apply(this, arguments);
      this.validateNonBlank("title");
      this.validateNonBlank("contact");
      this.validateContact(["_transient.contact", "contact"]);

      this.validate(['start_date', 'end_date'], function (newVal, prop) {
        if (!(this.start_date && this.end_date)) {
          return "Start and/or end date is invalid";
        }
      });

      this.bind("updated", function (ev, instance) {
        if (instance instanceof that) {
          instance.refresh_all_force('related_objects').then(function (object) {
            return instance.refresh_all_force('cycle_task_group', 'cycle', 'workflow');
          });
        }
      });
    }
  }, {
    overdue: overdue_compute,
    workflow: function () {
      return this.refresh_all('cycle', 'workflow').then(function (workflow) {
        return workflow;
      });
    },
    object: function () {
      return this.refresh_all('task_group_object', 'object').then(function (object) {
        return object;
      });
    },
    response_options_csv: can.compute(function (val) {
      if(val != null) {
        this.attr("response_options", $.map(val.split(","), $.proxy("".trim.call, "".trim)));
      } else {
        return (this.attr("response_options") || []).join(", ");
      }
    }),

    selected_response_options_csv: can.compute(function(val) {
      if(val != null) {
        this.attr("selected_response_options", $.map(val.split(","), $.proxy("".trim.call, "".trim)));
      } else {
        return (this.attr("selected_response_options") || []).join(", ");
      }
    }),

    get_filter_vals: function () {
      var filter_vals = can.Model.Cacheable.prototype.get_filter_vals;
      var mappings = jQuery.extend({}, this.class.filter_mappings, {
        'task title': 'title'
      });

      var vals = filter_vals.apply(this, [this.class.filter_keys, mappings]);

      try {
        vals['workflows'] = this.cycle.reify().workflow.reify().title;
      } catch (e) {}

      return vals;
    }

  });

})(window.can);
<commit_msg>Add the callback and form setup on cycle task model<commit_after>/*!
    Copyright (C) 2014 Google Inc., authors, and contributors <see AUTHORS file>
    Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
    Created By: dan@reciprocitylabs.com
    Maintained By: dan@reciprocitylabs.com
*/

(function(can) {

  var _mustache_path,
      overdue_compute;

  overdue_compute = can.compute(function(val) {
    if (this.attr("status") === "Verified") {
      return "";
    }
    var date = moment(this.attr("next_due_date") || this.attr("end_date"));
    if(date && date.isBefore(new Date())){
      return "overdue";
    }
    return "";
  });

  function refresh_attr(instance, attr){
    if (instance.attr(attr).reify().selfLink) {
      instance.attr(attr).reify().refresh();
    }
  }

  function refresh_attr_wrap(attr){
    return function(ev, instance) {
      if (instance instanceof this) {
        refresh_attr(instance, attr);
      }
    };
  }

  function populateFromWorkflow(form, workflow) {
    if (!workflow || typeof workflow === 'string') {
      // We need to invalidate the form, so we remove workflow if it's not set
      form.removeAttr('workflow');
      return;
    }
    if (typeof workflow.cycles === undefined || !workflow.cycles) {
      $(document.body).trigger(
        "ajax:flash"
        , {warning: "No cycles in the workflow!"}
      );
      return;
    }
    console.log("stage 2 triggered");
    workflow.refresh_all('cycles').then(function (cycleList) {
      var activeCycleList = _.filter(cycleList, {is_current: true});
      var activeCycle;

      console.log(cycleList);
      if (!activeCycleList.length) {
        $(document.body).trigger(
          "ajax:flash"
          , {warning: "No active cycles in the workflow!"}
        );
        return;
      }
      activeCycleList = _.sortByOrder(
        activeCycleList, ['start_date'], ['desc']);
      activeCycle = activeCycleList[0];
      form.attr('workflow', {id: workflow.id, type: 'Workflow'});
      form.attr('context', {id: workflow.context.id, type: 'Context'});
      form.attr('cycle', {id: activeCycle.id, type: 'Cycle'});
      form.cycle_task_group = activeCycle.cycle_task_groups[0].id;

      console.log(form);
    });
  }

  _mustache_path = GGRC.mustache_path + "/cycles";
  can.Model.Cacheable("CMS.Models.Cycle", {
    root_object: "cycle",
    root_collection: "cycles",
    category: "workflow",
    findAll: "GET /api/cycles",
    findOne: "GET /api/cycles/{id}",
    create: "POST /api/cycles",
    update: "PUT /api/cycles/{id}",
    destroy: "DELETE /api/cycles/{id}",

    attributes: {
      workflow: "CMS.Models.Workflow.stub",
      cycle_task_groups: "CMS.Models.CycleTaskGroup.stubs",
      modified_by: "CMS.Models.Person.stub",
      context: "CMS.Models.Context.stub"
    },

    tree_view_options: {
      show_view: _mustache_path + "/tree.mustache",
      header_view : _mustache_path + "/tree_header.mustache",
      draw_children: true,
      child_options: [
        {
          model: "CycleTaskGroup",
          mapping: "cycle_task_groups",
          allow_creating: false
        }
      ]
    },
    init: function(){
      var that = this;
      this._super.apply(this, arguments);
      this.bind("created", refresh_attr_wrap('workflow').bind(this));
      this.bind("destroyed", function(ev, inst) {
        if(inst instanceof that) {
          can.each(inst.cycle_task_groups, function(cycle_task_group) {
            if (!cycle_task_group) {
              return;
            }
            cycle_task_group = cycle_task_group.reify();
            can.trigger(cycle_task_group, "destroyed");
            can.trigger(cycle_task_group.constructor, "destroyed", cycle_task_group);
          });
        }
      });
    }
  }, {
    init: function() {
      var that = this;
      this._super.apply(this, arguments);
      this.bind("status", function(ev, newVal) {
        if (newVal === 'Verified') {
          new RefreshQueue().enqueue(this.workflow.reify()).trigger().then(function(wfs) {
            return wfs[0].get_binding("owners").refresh_instances();
          }).then(function(wf_owner_bindings) {
            var current_user = CMS.Models.get_instance(GGRC.current_user);
            if(~can.inArray(
              current_user,
              can.map(wf_owner_bindings, function(wf_owner_binding) {
                return wf_owner_binding.instance;
              })
            )) {
              that.refresh().then(function() {
                if(that.attr("is_current")) {
                  that.attr("is_current", false);
                  that.save();
                }
              });
            }
          });
        }
      });
    },
    overdue: overdue_compute,
  });

  _mustache_path = GGRC.mustache_path + "/cycle_task_entries";
  can.Model.Cacheable("CMS.Models.CycleTaskEntry", {
    root_object: "cycle_task_entry",
    root_collection: "cycle_task_entries",
    category: "workflow",
    findAll: "GET /api/cycle_task_entries",
    findOne: "GET /api/cycle_task_entries/{id}",
    create: "POST /api/cycle_task_entries",
    update: "PUT /api/cycle_task_entries/{id}",
    destroy: "DELETE /api/cycle_task_entries/{id}",

    attributes: {
      cycle_task_group_object_task: "CMS.Models.CycleTaskGroupObjectTask.stub",
      modified_by: "CMS.Models.Person.stub",
      context: "CMS.Models.Context.stub",
      object_documents: "CMS.Models.ObjectDocument.stubs",
      documents: "CMS.Models.Document.stubs",
      cycle: "CMS.Models.Cycle.stub"
    },

    tree_view_options: {
      show_view: _mustache_path + "/tree.mustache",
      footer_view: _mustache_path + "/tree_footer.mustache",
      child_options: [{
        //0: Documents
        model: "Document",
        mapping: "documents",
        show_view: _mustache_path + "/documents.mustache",
        footer_view: _mustache_path + "/documents_footer.mustache"
      }],
    },
    init: function(){
      this._super.apply(this, arguments);
      this.bind("created",
        refresh_attr_wrap("cycle_task_group_object_task").bind(this));
      this.validateNonBlank("description");
    }
  }, {
    workflowFolder: function() {
      return this.refresh_all('cycle', 'workflow').then(function(workflow){
        if (workflow.has_binding('folders')) {
          return workflow.refresh_all('folders').then(function(folders){
            if (folders.length === 0) {
              return null;  // workflow folder has not been assigned
            }
            return folders[0].instance;
          }, function(result) {
            return result;
          });
        }
      });
    }
  });

  _mustache_path = GGRC.mustache_path + "/cycle_task_groups";
  can.Model.Cacheable("CMS.Models.CycleTaskGroup", {
    root_object: "cycle_task_group",
    root_collection: "cycle_task_groups",
    category: "workflow",
    findAll: "GET /api/cycle_task_groups",
    findOne: "GET /api/cycle_task_groups/{id}",
    create: "POST /api/cycle_task_groups",
    update: "PUT /api/cycle_task_groups/{id}",
    destroy: "DELETE /api/cycle_task_groups/{id}",

    attributes: {
      cycle: "CMS.Models.Cycle.stub",
      task_group: "CMS.Models.TaskGroup.stub",
      cycle_task_group_tasks: "CMS.Models.CycleTaskGroupObjectTask.stubs",
      modified_by: "CMS.Models.Person.stub",
      context: "CMS.Models.Context.stub"
    },

    tree_view_options: {
      sort_property: 'sort_index',
      show_view: _mustache_path + "/tree.mustache",
      //footer_view: _mustache_path + "/tree_footer.mustache",
      draw_children: true,
      child_options: [
        {
          title: 'Tasks',
          model: "CycleTaskGroupObjectTask",
          mapping: "cycle_task_group_tasks",
          allow_creating: false
        }
      ]
    },

    init: function() {
      var that = this;
      this._super.apply(this, arguments);

      this.validateNonBlank("contact");
      this.validateContact(["_transient.contact", "contact"]);
      this.bind("updated", function(ev, instance) {
        if (instance instanceof that) {
          var dfd = instance.refresh_all_force('cycle', 'workflow');
          dfd.then(function(){
            return $.when(
              instance.refresh_all_force('related_objects'),
              instance.refresh_all_force('cycle_task_group_tasks')
            );
          });
        }
      });
      this.bind("destroyed", function(ev, inst) {
        if(inst instanceof that) {
          can.each(inst.cycle_task_group_tasks, function(ctgt) {
            if (!ctgt) {
              return;
            }
            ctgt = ctgt.reify();
            can.trigger(ctgt, "destroyed");
            can.trigger(ctgt.constructor, "destroyed", ctgt);
          });
        }
      });
    }
  }, {
    overdue: overdue_compute
  });

  _mustache_path = GGRC.mustache_path + "/cycle_task_group_object_tasks";
  can.Model.Cacheable("CMS.Models.CycleTaskGroupObjectTask", {
    root_object: "cycle_task_group_object_task",
    root_collection: "cycle_task_group_object_tasks",
    category: "workflow",
    findAll: "GET /api/cycle_task_group_object_tasks",
    findOne: "GET /api/cycle_task_group_object_tasks/{id}",
    create: "POST /api/cycle_task_group_object_tasks",
    update: "PUT /api/cycle_task_group_object_tasks/{id}",
    destroy: "DELETE /api/cycle_task_group_object_tasks/{id}",
    title_singular: "Cycle Task",
    attributes: {
      cycle_task_group: "CMS.Models.CycleTaskGroup.stub",
      task_group_task: "CMS.Models.TaskGroupTask.stub",
      cycle_task_entries: "CMS.Models.CycleTaskEntry.stubs",
      modified_by: "CMS.Models.Person.stub",
      contact: "CMS.Models.Person.stub",
      context: "CMS.Models.Context.stub",
      cycle: "CMS.Models.Cycle.stub"
    },
    permalink_options: {
      url: "<%= base.viewLink %>#current_widget/cycle/<%= instance.cycle.id %>/cycle_task_group/<%= instance.cycle_task_group.id %>/cycle_task_group_object_task/<%= instance.id %>",
      base: "cycle:workflow"
    },
    info_pane_options: {
      mapped_objects: {
        model: can.Model.Cacheable,
        mapping: 'info_related_objects',
        show_view: GGRC.mustache_path + '/base_templates/subtree.mustache'
      }
    },
    tree_view_options: {
      sort_property: 'sort_index',
      show_view: _mustache_path + "/tree.mustache",
      attr_list: [
        {attr_title: 'Title', attr_name: 'title'},
        {attr_title: 'Workflow', attr_name: 'workflow', attr_sort_field: 'cycle.workflow.title'},
        {attr_title: 'State', attr_name: 'status'},
        {attr_title: 'Assignee', attr_name: 'assignee', attr_sort_field: 'contact.name|email'},
        {attr_title: 'Start Date', attr_name: 'start_date'},
        {attr_title: 'End Date', attr_name: 'end_date'},
        {attr_title: 'Last Updated', attr_name: 'updated_at'}
      ],
      display_attr_names: ['title', 'mapped_object', 'workflow'],
      mandatory_attr_name: ['title'],
      draw_children: true,
      child_options: [
        {
          model: "CycleTaskEntry",
          mapping: "cycle_task_entries",
          allow_creating: true
        },
        {
          model: can.Model.Cacheable,
          mapping: 'info_related_objects',
          allow_creating: true
        }
      ]
    },
    init: function() {
      var that = this;
      this._super.apply(this, arguments);
      this.validateNonBlank("title");
      this.validateNonBlank("contact");
      this.validateNonBlank("workflow");
      this.validateContact(["_transient.contact", "contact"]);

      this.validate(['start_date', 'end_date'], function (newVal, prop) {
        if (!(this.start_date && this.end_date)) {
          return "Start and/or end date is invalid";
        }
      });

      this.bind("updated", function (ev, instance) {
        if (instance instanceof that) {
          instance.refresh_all_force('related_objects').then(function (object) {
            return instance.refresh_all_force('cycle_task_group', 'cycle', 'workflow');
          });
        }
      });
    }
  }, {
    overdue: overdue_compute,
    _workflow: function () {
      return this.refresh_all('cycle', 'workflow').then(function (workflow) {
        return workflow;
      });
    },
    set_properties_from_workflow: function (workflow) {
      // The form sometimes returns plaintext instead of object, return in that case
      if (typeof workflow === 'string') {
        return;
      }
      populateFromWorkflow(this, workflow);
    },
    form_preload: function (newObjectForm) {
      var form = this;
      var workflows;
      var _workflow;
      var cycle;

      if (newObjectForm) {
        if (!form.contact) {
          form.attr("contact", {id: GGRC.current_user.id, type: "Person"});
        }

        workflows = CMS.Models.Workflow.findAll({
          __search: 'Backlog', status: 'Active'}); // TODO: INSTEAD OF hardcode BACKLOG USE A SETTING
        workflows.then(function (workflowList) {
          if (!workflowList.length) {
            $(document.body).trigger(
              "ajax:flash"
              , {error: "No active workflows found! You need to create and activate at least one"}
            );
            return;
          }
          _workflow = workflowList[0];
          populateFromWorkflow(form, _workflow);
        });
      } else {
        cycle = form.cycle.reify();
        if (cycle.workflow !== undefined) {
          form.attr('workflow', cycle.workflow.reify());
        }
      }
    },
    object: function () {
      return this.refresh_all('task_group_object', 'object').then(function (object) {
        return object;
      });
    },
    response_options_csv: can.compute(function (val) {
      if(val != null) {
        this.attr("response_options", $.map(val.split(","), $.proxy("".trim.call, "".trim)));
      } else {
        return (this.attr("response_options") || []).join(", ");
      }
    }),

    selected_response_options_csv: can.compute(function(val) {
      if(val != null) {
        this.attr("selected_response_options", $.map(val.split(","), $.proxy("".trim.call, "".trim)));
      } else {
        return (this.attr("selected_response_options") || []).join(", ");
      }
    }),

    get_filter_vals: function () {
      var filter_vals = can.Model.Cacheable.prototype.get_filter_vals;
      var mappings = jQuery.extend({}, this.class.filter_mappings, {
        'task title': 'title'
      });

      var vals = filter_vals.apply(this, [this.class.filter_keys, mappings]);

      try {
        vals['workflows'] = this.cycle.reify().workflow.reify().title;
      } catch (e) {}

      return vals;
    }

  });

})(window.can);
<|endoftext|>