<commit_before>function initTerm(){
  var terminal = document.getElementById("terminal");
  terminal.onfocus = function(){
    document.getElementById('cursor').style.display = 'inline-block';
  };
  terminal.onblur = function(){
    document.getElementById('cursor').style.display = 'none';
  };
  var current = terminal.children[terminal.children.length-1];
  var buffer = "";
  var newLine = function(){
    current.innerHTML = "
" + buffer.replace(/  /g,'  ').replace(/  /g,'  ') + "
";
    current = document.createElement('div');
    current.class = 'line';
    buffer = '';
    writeBuffer();
    terminal.appendChild(current);
  };
  var writeBuffer = function(){
    current.innerHTML = "
" + buffer.replace(/  /g,'  ').replace(/  /g,'  ') + "

";
  };
  var writeLine = function(str,color){
    if(str.includes('\n')){
      let lines = str.split('\n');
      writeLine(lines.shift(),color);
      for(let line of lines) {
        newLine();
        writeLine(line,color);
      }
    }else{
      buffer += (!color)?str:("
"+str+"
");
      writeBuffer();
    }
  };
  return writeLine;
}
function initMem(){
  var inspector = document.getElementById("inspector");
  var table = inspector.children[0];
  var memory = [];
  memory.length = 16*table.rows.length; memory.fill(0); //fill memory with 16*20 0's
  var toHex = function(val){
    var map = '0123456789abcdef';
    return map[(val/16)|0]+map[val % 16];
  };
  for(let i = 0; i < table.rows.length;i++){
    table.rows[i].cells[0].innerHTML = "0x" + i.toString(16) + '0:';
    for(let k = 0; k < 8;k++){
      table.rows[i].cells[k+1].innerHTML = toHex(memory[i*16+k*2])+toHex(memory[i*16+k*2+1]);
    }
  }
  var setMem = function(ptr,val){
    if(memory[ptr] === val){
      animCell(ptr);
    }else{
      memory[ptr] = val;
      animCell(ptr,true);
    }
  };
  var animCell = function(ptr,write){
    var offset = ptr % 16;
    var row = (ptr - offset) / 16;
    offset = (offset/2)|0; //there are half as many cells as bytes because of 4 hex width cells
    var cell = table.rows[row].cells[offset+1]; //account for address column
    if(write){
      cell.innerHTML = toHex(memory[row*16+offset*2])+toHex(memory[row*16+offset*2+1]);
    }
    cell.style.animation='none';
    setTimeout(()=>cell.style.animation='blink .2s',0);
  };
  return function(ptr,val){
    if(val !== undefined){
      setMem(ptr,val);
    }else{
      animCell(ptr);
      return memory[ptr];
    }
  };
}
function initCPU(term,mem){
  var table = document.getElementById("inspector").children[0];
  var memory = [];
  memory.length = 16*table.rows.length; memory.fill(0); //fill memory with 16*20 0's
  var i = 0,stdin, buffer;
  var printStr = function(ptr,callback){
    var val = mem(ptr);
    if(val!==0){
      term(String.fromCharCode(val));
      wait(200).then(printStr.bind(null,ptr+1,callback));
    }else{
      callback();
    }
  };
  var cmpStr = function(ptr,ptr2,callback){
    console.log('comapring ', ptr, 'to',ptr2)
    var val = mem(ptr), val2 = mem(ptr2);
    if(val === val2){
      if(val === 0){
        wait(200).then(callback.bind(null,true));
      }else{
        wait(200).then(cmpStr.bind(null,ptr+1,ptr2+1,callback));
      }
    }else{
      wait(200).then(callback.bind(null,false));
    }
  };
  var loadStr = function(ptr,buffer,i,callback){
    if(buffer[i]){
      console.log('reading from const buffer',buffer[i]);
      if(buffer[i] == '\t'){
        console.log('should end')
        mem(ptr,0);
        i++;
        wait(200).then(callback);
      }else{
        mem(ptr,buffer.charCodeAt(i));
        i++;
        wait(200).then(loadStr.bind(null,ptr+1,buffer,i,callback));
      }
    }
  };
    var loadUser = function(ptr,callback){
    if(buffer[i]){
      console.log('reading from buffer',buffer[i],i);
      term(buffer[i]);
      if(buffer[i] == '\n'){
        mem(ptr,0);
        i++;
        wait(200).then(callback);
      }else{
        mem(ptr,buffer.charCodeAt(i));
        i++;
        wait(200).then(loadUser.bind(null,ptr+1,callback));
      }
    }else{
      console.log('setting up callback');
      status = 'waiting';
      stdin = function(k){
        console.log('received ',k)
        term(k);
        if(k == '\n'){
          mem(ptr,0);
          wait(200).then(callback);
        }else{
          mem(ptr,k.charCodeAt(0));
          wait(200).then(loadUser.bind(null,ptr+1,callback));
        }
      };
    }
  };
  var wait = time=>new Promise(resolve=>setTimeout(resolve,time));

  var init = function(){
    loop = function(){
            printStr(0,function(){
              buffer = ''; i = 0;
              loadUser(43,function(){
                  cmpStr(31,43,function(success){
                    if(success){
                      printStr(11,()=>false)
                    }else{
                      printStr(21,loop)
                    }
                  })
                });
              })
            };
    Promise.all([new Promise(resolve=>loadStr(0,'Password: \t',0,resolve)),
                 new Promise(resolve=>loadStr(11,'Success!\n\t',0,resolve)),
                 new Promise(resolve=>loadStr(21,'Failure!\n\t',0,resolve)),
                 new Promise(resolve=>loadStr(31,'Hello World\t',0,resolve))]).then(loop);
  };
  init();
  return function(val){
    console.log(status)
    if(status === 'waiting'){
      status = 'running';
      setTimeout(stdin.bind(null,val),0);
    }else{
      buffer += val;
    }
  };
}
function initInput(input){
  var keys = {};
  document.onkeydown = function(e){
    if(document.activeElement.id === "terminal"){
      if(!keys[e.key]){
        if(e.key === 'Enter'){
          input('\n');
        }else if(e.key === 'Tab'){
          input('\t');
        }else if(e.key.length === 1){
          //console.log(e.key)
          input(e.key);
        }
      }
      keys[e.key] = true;
    }
  };
  document.onkeyup = function(e){
    keys[e.key] = false;
  };
}

var term = initTerm();
var mem = initMem();
var input = initCPU(term,mem);
initInput(input);

<commit_msg>adds Q<commit_after>function initTerm(){
  var terminal = document.getElementById("terminal");
  terminal.onfocus = function(){
    document.getElementById('cursor').style.display = 'inline-block';
  };
  terminal.onblur = function(){
    document.getElementById('cursor').style.display = 'none';
  };
  var current = terminal.children[terminal.children.length-1];
  var buffer = "";
  var newLine = function(){
    current.innerHTML = "
" + buffer.replace(/  /g,'  ').replace(/  /g,'  ') + "
";
    current = document.createElement('div');
    current.class = 'line';
    buffer = '';
    writeBuffer();
    terminal.appendChild(current);
  };
  var writeBuffer = function(){
    current.innerHTML = "
" + buffer.replace(/  /g,'  ').replace(/  /g,'  ') + "

";
  };
  var writeLine = function(str,color){
    if(str.includes('\n')){
      let lines = str.split('\n');
      writeLine(lines.shift(),color);
      for(let line of lines) {
        newLine();
        writeLine(line,color);
      }
    }else{
      buffer += (!color)?str:("
"+str+"
");
      writeBuffer();
    }
  };
  return writeLine;
}
function initMem(){
  var inspector = document.getElementById("inspector");
  var table = inspector.children[0];
  var memory = [];
  memory.length = 16*table.rows.length; memory.fill(0); //fill memory with 16*20 0's
  var toHex = function(val){
    var map = '0123456789abcdef';
    return map[(val/16)|0]+map[val % 16];
  };
  for(let i = 0; i < table.rows.length;i++){
    table.rows[i].cells[0].innerHTML = "0x" + i.toString(16) + '0:';
    for(let k = 0; k < 8;k++){
      table.rows[i].cells[k+1].innerHTML = toHex(memory[i*16+k*2])+toHex(memory[i*16+k*2+1]);
    }
  }
  var setMem = function(ptr,val){
    if(memory[ptr] === val){
      animCell(ptr);
    }else{
      memory[ptr] = val;
      animCell(ptr,true);
    }
  };
  var animCell = function(ptr,write){
    var offset = ptr % 16;
    var row = (ptr - offset) / 16;
    offset = (offset/2)|0; //there are half as many cells as bytes because of 4 hex width cells
    var cell = table.rows[row].cells[offset+1]; //account for address column
    if(write){
      cell.innerHTML = toHex(memory[row*16+offset*2])+toHex(memory[row*16+offset*2+1]);
    }
    cell.style.animation='none';
    setTimeout(()=>cell.style.animation='blink .1s',0);
  };
  return function(ptr,val){
    if(val !== undefined){
      setMem(ptr,val);
    }else{
      animCell(ptr);
      return memory[ptr];
    }
  };
}
function initCPU(term,mem){
  var table = document.getElementById("inspector").children[0];
  var memory = [];
  memory.length = 16*table.rows.length; memory.fill(0); //fill memory with 16*20 0's
  var i = 0,stdin, buffer;
  var Q = function(f,...args){ //wraps and binds args
    return new Promise(res=>f(...args,res));
  };
  var printStr = function(ptr,callback){
    var val = mem(ptr);
    if(val!==0){
      term(String.fromCharCode(val));
      wait(200).then(printStr.bind(null,ptr+1,callback));
    }else{
      callback();
    }
  };
  var cmpStr = function(ptr,ptr2,callback){
    console.log('comapring ', ptr, 'to',ptr2);
    var val = mem(ptr), val2 = mem(ptr2);
    if(val === val2){
      if(val === 0){
        wait(200).then(callback.bind(null,true));
      }else{
        wait(200).then(cmpStr.bind(null,ptr+1,ptr2+1,callback));
      }
    }else{
      wait(200).then(callback.bind(null,false));
    }
  };
  var loadStr = function(ptr,buffer,i,callback){
    if(buffer[i]){
      console.log('reading from const buffer',buffer[i]);
      if(buffer[i] == '\t'){
        console.log('should end');
        mem(ptr,0);
        i++;
        wait(200).then(callback);
      }else{
        mem(ptr,buffer.charCodeAt(i));
        i++;
        wait(200).then(loadStr.bind(null,ptr+1,buffer,i,callback));
      }
    }
  };
    var loadUser = function(ptr,callback){
    if(buffer[i]){
      console.log('reading from buffer',buffer[i],i);
      term(buffer[i]);
      if(buffer[i] == '\n'){
        mem(ptr,0);
        i++;
        wait(200).then(callback);
      }else{
        mem(ptr,buffer.charCodeAt(i));
        i++;
        wait(200).then(loadUser.bind(null,ptr+1,callback));
      }
    }else{
      console.log('setting up callback');
      status = 'waiting';
      stdin = function(k){
        console.log('received ',k)
        term(k);
        if(k == '\n'){
          mem(ptr,0);
          wait(200).then(callback);
        }else{
          mem(ptr,k.charCodeAt(0));
          wait(200).then(loadUser.bind(null,ptr+1,callback));
        }
      };
    }
  };
  var wait = time=>new Promise(resolve=>setTimeout(resolve,time));

  var init = function(){
    loop = function(){
            Q(printStr,0).then(function(){
              buffer = ''; i = 0;
              Q(loadUser,43).then(()=>Q(cmpStr,31,43)).then(function(success){
                    if(success){
                      printStr(11,()=>0)
                    }else{
                      printStr(21,loop)
                    }
                  });
              });
            };
    Promise.all([Q(loadStr,0,'Password: \t',0),
                 Q(loadStr,11,'Success!\n\t',0),
                 Q(loadStr,21,'Failure!\n\t',0),
                 Q(loadStr,31,'Hello World\t',0)]).then(loop);
  };
  init();
  return function(val){
    console.log(status)
    if(status === 'waiting'){
      status = 'running';
      setTimeout(stdin.bind(null,val),0);
    }else{
      buffer += val;
    }
  };
}
function initInput(input){
  var keys = {};
  document.onkeydown = function(e){
    if(document.activeElement.id === "terminal"){
      if(!keys[e.key]){
        if(e.key === 'Enter'){
          input('\n');
        }else if(e.key === 'Tab'){
          input('\t');
        }else if(e.key.length === 1){
          //console.log(e.key)
          input(e.key);
        }
      }
      keys[e.key] = true;
    }
  };
  document.onkeyup = function(e){
    keys[e.key] = false;
  };
}

var term = initTerm();
var mem = initMem();
var input = initCPU(term,mem);
initInput(input);

<|endoftext|>


<commit_before>var http = require('http');
var url = require('url');
var fs = require('fs');
var i = 0;
var html = undefined;
var css = undefined;
var zepto = undefined;
var port = process.env.PORT || 3000;

var inc = function() {
	i++;
}

var server = http.createServer(function (req, res) {
    var info = url.parse(req.url, true);

    if (info.pathname == '/v') {
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end(i + "\n\n\n\nReload to increment.\nResets often\n" + '\n');
		inc();
    } else if (info.pathname == "/api/json") {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({"number":i}));
    } else if (info.pathname == "/api/plaintext") {
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end(i + "\n");
    } else if (info.pathname == '/h') {
        res.writeHead(200, {'Content-Type': 'text/html'});
		fs.readFile('template.html', 'utf8', function (err,data) {
            if (err) {
            return console.log(err);
        }
            html = data;
        });
        res.end(html);
		inc();
    } else if (info.pathname == '/style.css') {
		res.writeHead(200, {'Content-Type': 'text/css'});
		fs.readFile('style.css', 'utf8', function (err,data) {
			if (err) {
				return console.log(err);
			}
			css = data;
		});
		res.end(css);
	} else if (info.pathname == '/zepto.min.js') {
        res.writeHead(200, {'Content-Type': 'text/javascript'});
        fs.readFile('zepto.min.js', 'utf8', function (err,data) {
            if (err) {
                return console.log(err);
            }
            zepto = data;
        });
        res.end(zepto)
    } else {
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end(i + "\n");
		inc();
    }
})
server.listen(port);
<commit_msg>/h should be faster<commit_after>//requires
var http = require('http');
var url = require('url');
var fs = require('fs');
//making vars
var i = 0;
var port = process.env.PORT || 3000;
//reading files & making functions
fs.readFile('style.css', 'utf8', function (err,data) {
	console.log("fetching css");
    if (err) {
        return console.log("css err " + err);
    }
	css = data;
});
fs.readFile('zepto.min.js', 'utf8', function (err,data) {
	console.log("fetching js");
	if (err) {
		return console.log("js err " + err);
	}
	zepto = data;
});
fs.readFile('template.html', 'utf8', function (err,data) {
	console.log("fetching html");
	if (err) {
		return console.log("html err " + err);
	}
	html = data;
});
var inc = function() {
	i++;
}
//main stuff
var server = http.createServer(function (req, res) {
    var info = url.parse(req.url, true);

    if (info.pathname == '/v') {
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end(i + "\n\n\n\nReload to increment.\nResets often\n" + '\n');
		inc();
    } else if (info.pathname == "/api/json") {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({"number":i}));
    } else if (info.pathname == "/api/plaintext") {
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end(i + "\n");
    } else if (info.pathname == '/h') {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end(html);
		inc();
    } else if (info.pathname == '/style.css') {
		res.writeHead(200, {'Content-Type': 'text/css'});
		res.end(css);
	} else if (info.pathname == '/zepto.min.js') {
        res.writeHead(200, {'Content-Type': 'text/javascript'});
        res.end(zepto)
    } else {
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end(i + "\n");
		inc();
    }
})
server.listen(port);
<|endoftext|>


<commit_before>import { HttpClient } from 'aurelia-fetch-client';
import environment from './environment'

export class WebAPI {
  client = new HttpClient();
  isRequesting = false;

  constructor() {
    this.client.configure(config => {
  config
    .useStandardConfiguration()
    .withBaseUrl( environment.baseurl + '/api/v1')
    .withDefaults({
      credentials: 'no-cors',
      headers: {
        'X-Requested-With': 'Fetch'
      }
    })
    .withInterceptor({
      request(request) {
          if (localStorage.getItem('token') != null) {
            request.headers.append('Authorization', 'Basic ' + btoa(localStorage.getItem('token') + ':'));
          }
          return request;
      }
    });
});
  }

  getActivityList() {
    this.isRequesting = true;

    return new Promise((resolve, reject) => {
      this.client.fetch('/activities')
      .then(response => { response.json() })
      .then(data => {
        console.log(data);
        resolve(data);
      })
      .catch(error => reject(error));
      this.isRequesting = false;
    });
  }

  getActivityTypes() {
    this.isRequesting = true;

    return new Promise((resolve, reject)=> {
      this.client.fetch('/activityTypes')
      .then(response => { response.json() })
      .then(data => {
        console.log(data);
        resolve(data);
      })
      .catch(error => reject(error));
      this.isRequesting = false;
    });
  }

  addActivity(activity) {
    this.isRequesting = true;

    console.log("Will add:");
    console.log(activity);
    return new Promise((resolve, reject) => {
      this.client.fetch('/activities', {
        method: 'post',
        body: JSON.stringify(activity),
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      })
      .then(response => { return response.json() })
      .then(data => {
        console.log(data);
        resolve(data);
      })
      .catch(error => reject(error));
      this.isRequesting = false;
    });
  }

  getCode(mobile) {
    this.isRequesting = true;

    return new Promise((resolve, reject) => {
      let url = '/login/' + mobile;
      console.log("Fetching code: " + url);

      this.client.fetch(url)
      .then(response => {
        console.log("Fetched code!");
        resolve(true);
      })
      .catch(error => {
        console.log("Error: " + error.message);
        reject(error) });
      this.isRequesting = false;
    });
  }

  login(mobile, code) {
    this.isRequesting = true;

    let auth = {code: code}

    return new Promise((resolve, reject) => {
      this.client.fetch('/login/' + mobile, {
        method: 'post',
        body: JSON.stringify(auth),
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      })
      .then(response => { return response.json() })
      .then(data => {
        console.log(data);
        resolve(data["token"]);
      })
      .catch(error => reject(error));
      this.isRequesting = false;
    });
  }
}
<commit_msg>Fix fetch request and promises<commit_after>import { HttpClient } from 'aurelia-fetch-client';
import environment from './environment'

export class WebAPI {
  client = new HttpClient();
  isRequesting = false;

  constructor() {
    this.client.configure(config => {
  config
    .useStandardConfiguration()
    .withBaseUrl( environment.baseurl + '/api/v1')
    .withDefaults({
      headers: {
        'X-Requested-With': 'Fetch'
      }
    })
    .withInterceptor({
      request(request) {
          if (localStorage.getItem('token') != null) {
            request.headers.append('Authorization', 'Basic ' + btoa(localStorage.getItem('token') + ':'));
          }
          return request;
      }
    });
});
  }

  getActivityList() {
    this.isRequesting = true;

    return new Promise((resolve, reject) => {
      this.client.fetch('/activities')
      .then(response => { return response.json() })
      .then(data => {
        console.log(data);
        resolve(data);
      })
      .catch(error => reject(error));
      this.isRequesting = false;
    });
  }

  getActivityTypes() {
    this.isRequesting = true;

    return new Promise((resolve, reject)=> {
      this.client.fetch('/activityTypes')
      .then(response => { return response.json() })
      .then(data => {
        console.log(data);
        resolve(data);
      })
      .catch(error => reject(error));
      this.isRequesting = false;
    });
  }

  addActivity(activity) {
    this.isRequesting = true;

    console.log("Will add:");
    console.log(activity);
    return new Promise((resolve, reject) => {
      this.client.fetch('/activities', {
        method: 'post',
        body: JSON.stringify(activity),
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      })
      .then(response => { return response.json() })
      .then(data => {
        console.log(data);
        resolve(data);
      })
      .catch(error => reject(error));
      this.isRequesting = false;
    });
  }

  getCode(mobile) {
    this.isRequesting = true;

    return new Promise((resolve, reject) => {
      let url = '/login/' + mobile;
      console.log("Fetching code: " + url);

      this.client.fetch(url)
      .then(response => {
        console.log("Fetched code!");
        resolve(true);
      })
      .catch(error => {
        console.log("Error: " + error.message);
        reject(error) });
      this.isRequesting = false;
    });
  }

  login(mobile, code) {
    this.isRequesting = true;

    let auth = {code: code}

    return new Promise((resolve, reject) => {
      this.client.fetch('/login/' + mobile, {
        method: 'post',
        body: JSON.stringify(auth),
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      })
      .then(response => { return response.json() })
      .then(data => {
        console.log(data);
        resolve(data["token"]);
      })
      .catch(error => reject(error));
      this.isRequesting = false;
    });
  }
}
<|endoftext|>


<commit_before>var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));

var path = require('path');
var express = require('express');
var app = express();

var env = {
  baseUrl : process.env.COREOS_IPXE_SERVER_BASE_URL ? process.env.COREOS_IPXE_SERVER_BASE_URL : '',
  dataDirectory : process.env.COREOS_IPXE_SERVER_DATA_DIR ? process.env.COREOS_IPXE_SERVER_DATA_DIR : "/opt/coreos-ipxe-server",
  listenPort : process.env.COREOS_IPXE_SERVER_LISTEN_ADDR ? process.env.COREOS_IPXE_SERVER_LISTEN_ADDR : "4777"
}

var script = '#!ipxe\r\n' +
'set coreos-version {{.Version}}\r\n' +
'set base-url http://{{.BaseUrl}}/images/amd64-usr/${coreos-version}\r\n' +
'kernel ${base-url}/coreos_production_pxe.vmlinuz{{.Options}}\r\n' +
'initrd ${base-url}/coreos_production_pxe_image.cpio.gz\r\n' +
'boot\r\n';

var cloudConfigBase = path.join(env.dataDirectory,'/configs');

app.get('/', getScript);

var route = express.Router();
//App.use will prepend the baseUrl to all paths in the route
app.use(env.baseUrl, route);

route.use('/configs', express.static(path.join(env.dataDirectory,'/configs')));
route.use('/images', express.static(path.join(env.dataDirectory,'/images')));
route.use('/sshKeys', express.static(path.join(env.dataDirectory,'/sshKeys')));

app.listen(env.listenPort.split(':')[1]);

console.log('Listening on ' + env.listenPort)

function getScript(req, res){
  var profileId = req.query['profile'] || '';
  if(env.baseUrl === ''){
    env.baseUrl = req.hostname;
  }
  console.log('Request for profile ' + profileId)
  getProfile(profileId)
    .then(JSON.parse)
    .then(getOptions)
    .then(processScript)
    .then(function(script){
      req.set('content-type', 'text/plain');
      res.status(200).send(script);
    }).catch(function(err){
      res.status(500).send(err);
    })
}

function getProfile(profileId){
  if(profileId === ''){
    return Promise.resolve('{}');
  }
  var profilePath = path.join(env.dataDirectory, 'profiles', profileId + '.json');
  return fs.readfileAsync(profilePath, 'utf8');
}

function getOptions(profile){
  var options = {
    'cloud_config' : '',
    'console' : [],
    'coreos_autologin' : '',
    'root' : '',
    'rootfstype' : '',
    'sshkey' : '',
    'version' : '',
    toString : function(){
      var optString = "";

      optString += this.rootfstype ? ' rootfstype=' + this.rootfstype : '';
      for(var i in this.console){
        optString += ' console=' + this.console[i];
      }
      optString += this.cloud_config ? ' cloud-config-url=http://' + env.baseUrl + ':' + env.listenEnv + this.cloud_config : '';
      optString += this.coreos_autologin ? ' coreos.autologin=' + this.coreos_autologin : '';
      optString += this.sshkey ? ' sshkey=' + this.sshkey : '';
      optString += this.root ? ' root=' + this.root : '';

      return optString;
    }.bind(this)
  };

  for(var i in options){
    for(var j in profile){
      if(i === j){
        options[i] = profile[j];
      }
    }
  }

  return options;
}

function processScript(options){
  var scriptVariables = {
    '{{.Version}}' :'',
    '{{.BaseUrl}}' : '',
    '{{.Options}}' : ''
  };

  scriptVariables['{{.Version}}'] = options.version;
  scriptVariables['{{.BaseUrl}}'] = env.baseUrl;
  scriptVariables['{{.Options}}'] = options.toString();
  var genScript = script + '';
  for(var i in scriptVariables){
    genScript = genScript.replace(i, scriptVariables[i]);
  }

  return genScript;
}
<commit_msg>Fix readFileAsync<commit_after>var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));

var path = require('path');
var express = require('express');
var app = express();

var env = {
  baseUrl : process.env.COREOS_IPXE_SERVER_BASE_URL ? process.env.COREOS_IPXE_SERVER_BASE_URL : '',
  dataDirectory : process.env.COREOS_IPXE_SERVER_DATA_DIR ? process.env.COREOS_IPXE_SERVER_DATA_DIR : "/opt/coreos-ipxe-server",
  listenPort : process.env.COREOS_IPXE_SERVER_LISTEN_ADDR ? process.env.COREOS_IPXE_SERVER_LISTEN_ADDR : "4777"
}

var script = '#!ipxe\r\n' +
'set coreos-version {{.Version}}\r\n' +
'set base-url http://{{.BaseUrl}}/images/amd64-usr/${coreos-version}\r\n' +
'kernel ${base-url}/coreos_production_pxe.vmlinuz{{.Options}}\r\n' +
'initrd ${base-url}/coreos_production_pxe_image.cpio.gz\r\n' +
'boot\r\n';

var cloudConfigBase = path.join(env.dataDirectory,'/configs');

app.get('/', getScript);

var route = express.Router();
//App.use will prepend the baseUrl to all paths in the route
app.use(env.baseUrl, route);

route.use('/configs', express.static(path.join(env.dataDirectory,'/configs')));
route.use('/images', express.static(path.join(env.dataDirectory,'/images')));
route.use('/sshKeys', express.static(path.join(env.dataDirectory,'/sshKeys')));

app.listen(env.listenPort.split(':')[1]);

console.log('Listening on ' + env.listenPort)

function getScript(req, res){
  var profileId = req.query['profile'] || '';
  if(env.baseUrl === ''){
    env.baseUrl = req.hostname;
  }
  console.log('Request for profile ' + profileId)
  getProfile(profileId)
    .then(JSON.parse)
    .then(getOptions)
    .then(processScript)
    .then(function(script){
      req.set('content-type', 'text/plain');
      res.status(200).send(script);
    }).catch(function(err){
      res.status(500).send(err);
    })
}

function getProfile(profileId){
  if(profileId === ''){
    return Promise.resolve('{}');
  }
  var profilePath = path.join(env.dataDirectory, 'profiles', profileId + '.json');
  return fs.readFileAsync(profilePath, 'utf8');
}

function getOptions(profile){
  var options = {
    'cloud_config' : '',
    'console' : [],
    'coreos_autologin' : '',
    'root' : '',
    'rootfstype' : '',
    'sshkey' : '',
    'version' : '',
    toString : function(){
      var optString = "";

      optString += this.rootfstype ? ' rootfstype=' + this.rootfstype : '';
      for(var i in this.console){
        optString += ' console=' + this.console[i];
      }
      optString += this.cloud_config ? ' cloud-config-url=http://' + env.baseUrl + ':' + env.listenEnv + this.cloud_config : '';
      optString += this.coreos_autologin ? ' coreos.autologin=' + this.coreos_autologin : '';
      optString += this.sshkey ? ' sshkey=' + this.sshkey : '';
      optString += this.root ? ' root=' + this.root : '';

      return optString;
    }.bind(this)
  };

  for(var i in options){
    for(var j in profile){
      if(i === j){
        options[i] = profile[j];
      }
    }
  }

  return options;
}

function processScript(options){
  var scriptVariables = {
    '{{.Version}}' :'',
    '{{.BaseUrl}}' : '',
    '{{.Options}}' : ''
  };

  scriptVariables['{{.Version}}'] = options.version;
  scriptVariables['{{.BaseUrl}}'] = env.baseUrl;
  scriptVariables['{{.Options}}'] = options.toString();
  var genScript = script + '';
  for(var i in scriptVariables){
    genScript = genScript.replace(i, scriptVariables[i]);
  }

  return genScript;
}
<|endoftext|>


<commit_before>'use strict'

var config = require('./config') //either js: 'module.exports = {}' or json: '{}'
var express = require('express')

var app = express()
app.use(express.static(__dirname + '/public/'))
app.get(/^(.*)$/, function(req, res, next) {
  return res.sendfile(__dirname + '/public/query.htm')
})

app.listen(config.port)
console.log('now listening to port', config.port)

//
<commit_msg>serve the page only on valid gist ids<commit_after>'use strict'

var config = require('./config') //either js: 'module.exports = {}' or json: '{}'
var express = require('express')

var validGistIdPathRegex = /^\/(\d+|[\da-f]{20})$/

var app = express()
app.use(express.static(__dirname + '/public/'))
app.get(validGistIdPathRegex, function(req, res, next) {
  return res.sendfile(__dirname + '/public/query.htm')
})

// Add error on invalid paths

app.listen(config.port)
console.log('now listening to port', config.port)

//
<|endoftext|>


<commit_before>'use strict'

var config = require('./config') //either js: 'module.exports = {}' or json: '{}'
var GitHubApi = require('github')
var marked = require('marked')
var express = require('express')

var github = new GitHubApi({
  version: '3.0.0',
  // optional
  // debug: true,
  protocol: 'https',
  // pathPrefix: '/api/v3', // for some GHEs
  timeout: 5000
})

github.authenticate({ type: 'oauth', token: config.token })

var app = express()

app.use(express.static(__dirname + '/public/'))

app.get(/^(.*)$/, function(req, res, next) {
  var requestPath = req.params[0].replace(/^\//,'')
  if (requestPath === '') requestPath = config.defaultGist
  //varify requestPath against a regex
  res.write('
loading...
')
  github.gists.get({ id: requestPath }, function(error, gist) {
    if (error) return res.end('error!')
    var firstFile = gist.files[Object.keys(gist.files)[0]]
    if (firstFile.language === 'Markdown') res.end('' + marked(firstFile.content) + '')
    else res.end('not a markdown file')
  })
});

app.use(function(err, req, res, next){
  console.error(err.stack);
  res.status(500).send('Something broke!')
});

app.listen(config.port)
console.log('now listening to port', config.port)

//
<commit_msg>rendering all md files in gist<commit_after>'use strict'

var config = require('./config') //either js: 'module.exports = {}' or json: '{}'
var GitHubApi = require('github')
var marked = require('marked')
var express = require('express')

var github = new GitHubApi({
  version: '3.0.0',
  // optional
  // debug: true,
  protocol: 'https',
  // pathPrefix: '/api/v3', // for some GHEs
  timeout: 5000
})

github.authenticate({ type: 'oauth', token: config.token })

var app = express()

app.use(express.static(__dirname + '/public/'))

app.get(/^(.*)$/, function(req, res, next) {
  var requestPath = req.params[0].replace(/^\//,'')
  if (requestPath === '') requestPath = config.defaultGist
  //varify requestPath against a regex
  res.write('
loading...
')
  github.gists.get({ id: requestPath }, function(error, gist) {
    if (error) return res.end('error!')
    var files = Object.keys(gist.files).map(function(filename){return gist.files[filename]})
    var mdFiles = files.filter(function(file){return file.language === 'Markdown'})
    var html = mdFiles.map(function(file){return marked(file.content)}).join('
')
    res.end('' + html + '')
  })
});

app.use(function(err, req, res, next){
  console.error(err.stack);
  res.status(500).send('Something broke!')
});

app.listen(config.port)
console.log('now listening to port', config.port)

//
<|endoftext|>


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

	var AppInit             = staruml.getModule("utils/AppInit"),
		Repository          = staruml.getModule("engine/Repository"),
		Engine              = staruml.getModule("engine/Engine"),
		Commands            = staruml.getModule("command/Commands"),
		CommandManager      = staruml.getModule("command/CommandManager"),
		MenuManager         = staruml.getModule("menu/MenuManager"),
		Dialogs             = staruml.getModule("dialogs/Dialogs"),
		ElementPickerDialog = staruml.getModule("dialogs/ElementPickerDialog"),
		FileSystem          = staruml.getModule("filesystem/FileSystem"),
		FileSystemError     = staruml.getModule("filesystem/FileSystemError"),
		ExtensionUtils      = staruml.getModule("utils/ExtensionUtils"),
		UML                 = staruml.getModule("uml/UML");

	var CodeGenUtils        = require("CodeGenUtils"),
		CppPreferences		= require("CppPreferences"),
		CppCodeGenerator	= require("CppCodeGenerator");

	/**
	 * Command IDs
	 */
	var CMD_CPP            = 'cpp',
		CMD_CPP_GENERATE   = 'cpp.generate',
		CMD_CPP_REVERSE    = 'cpp.reverse',
		CMD_CPP_CONFIGURE  = 'cpp.configure';

	function _handleGenerate(base, path, options) {
		var result = new $.Deferred();

		// If options is not passed, get from preference
		options = options || CppPreferences.getGenOptions();

		// If base is not assigned, popup ElementPicker
		if (!base) {
			ElementPickerDialog.showDialog("Select a base model to generate codes", null, type.UMLPackage)
				.done(function (buttonId, selected) {
					if (buttonId === Dialogs.DIALOG_BTN_OK && selected) {
						base = selected;

						// If path is not assigned, popup Open Dialog to select a folder
						if (!path) {
							FileSystem.showOpenDialog(false, true, "Select a folder where generated codes to be located", null, null, function (err, files) {
								if (!err) {
									if (files.length > 0) {
										path = files[0];
										CppCodeGenerator.generate(base, path, options).then(result.resolve, result.reject);
									} else {
										result.reject(FileSystem.USER_CANCELED);
									}
								} else {
									result.reject(err);
								}
							});
						} else {
							CppCodeGenerator.generate(base, path, options).then(result.resolve, result.reject);
						}
					} else {
						result.reject();
					}
				});
		} else {
			// If path is not assigned, popup Open Dialog to select a folder
			if (!path) {
				FileSystem.showOpenDialog(false, true, "Select a folder where generated codes to be located", null, null, function (err, files) {
					if (!err) {
						if (files.length > 0) {
							path = files[0];
							CppCodeGenerator.generate(base, path, options).then(result.resolve, result.reject);
						} else {
							result.reject(FileSystem.USER_CANCELED);
						}
					} else {
						result.reject(err);
					}
				});
			} else {
				CppCodeGenerator.generate(base, path, options).then(result.resolve, result.reject);
			}
		}
		return result.promise();
	}

	function _handleConfigure() {
		CommandManager.execute(Commands.FILE_PREFERENCES, CppPreferences.getId());
	}

	CommandManager.register("Cpp",             CMD_CPP,           function(){console.log("Cpp");});
	CommandManager.register("Generate Code...", CMD_CPP_GENERATE,  _handleGenerate);
	CommandManager.register("Reverse Code...",  CMD_CPP_REVERSE,   function(){console.log("Reverse code...");});
	CommandManager.register("Configure...",     CMD_CPP_CONFIGURE, _handleConfigure);

	var menu, menuItem;
	menu = MenuManager.getMenu(Commands.TOOLS);
	menuItem = menu.addMenuItem(CMD_CPP);
	menuItem.addMenuItem(CMD_CPP_GENERATE);
	menuItem.addMenuItem(CMD_CPP_REVERSE);
	menuItem.addMenuDivider();
	menuItem.addMenuItem(CMD_CPP_CONFIGURE);
});<commit_msg>add logging versions, and last sync time.<commit_after>define(function (require, exports, module) {
	"use strict";

	var AppInit             = staruml.getModule("utils/AppInit"),
		Repository          = staruml.getModule("engine/Repository"),
		Engine              = staruml.getModule("engine/Engine"),
		Commands            = staruml.getModule("command/Commands"),
		CommandManager      = staruml.getModule("command/CommandManager"),
		MenuManager         = staruml.getModule("menu/MenuManager"),
		Dialogs             = staruml.getModule("dialogs/Dialogs"),
		ElementPickerDialog = staruml.getModule("dialogs/ElementPickerDialog"),
		FileSystem          = staruml.getModule("filesystem/FileSystem"),
		FileSystemError     = staruml.getModule("filesystem/FileSystemError"),
		ExtensionUtils      = staruml.getModule("utils/ExtensionUtils"),
		UML                 = staruml.getModule("uml/UML");

	var CodeGenUtils        = require("CodeGenUtils"),
		CppPreferences		= require("CppPreferences"),
		CppCodeGenerator	= require("CppCodeGenerator");

	/**
	 * Command IDs
	 */
	var CMD_CPP            = 'cpp',
		CMD_CPP_GENERATE   = 'cpp.generate',
		CMD_CPP_REVERSE    = 'cpp.reverse',
		CMD_CPP_CONFIGURE  = 'cpp.configure';

	function _handleGenerate(base, path, options) {
		var result = new $.Deferred();

		// If options is not passed, get from preference
		options = options || CppPreferences.getGenOptions();

		// If base is not assigned, popup ElementPicker
		if (!base) {
			ElementPickerDialog.showDialog("Select a base model to generate codes", null, type.UMLPackage)
				.done(function (buttonId, selected) {
					if (buttonId === Dialogs.DIALOG_BTN_OK && selected) {
						base = selected;

						// If path is not assigned, popup Open Dialog to select a folder
						if (!path) {
							FileSystem.showOpenDialog(false, true, "Select a folder where generated codes to be located", null, null, function (err, files) {
								if (!err) {
									if (files.length > 0) {
										path = files[0];
										CppCodeGenerator.generate(base, path, options).then(result.resolve, result.reject);
									} else {
										result.reject(FileSystem.USER_CANCELED);
									}
								} else {
									result.reject(err);
								}
							});
						} else {
							CppCodeGenerator.generate(base, path, options).then(result.resolve, result.reject);
						}
					} else {
						result.reject();
					}
				});
		} else {
			// If path is not assigned, popup Open Dialog to select a folder
			if (!path) {
				FileSystem.showOpenDialog(false, true, "Select a folder where generated codes to be located", null, null, function (err, files) {
					if (!err) {
						if (files.length > 0) {
							path = files[0];
							CppCodeGenerator.generate(base, path, options).then(result.resolve, result.reject);
						} else {
							result.reject(FileSystem.USER_CANCELED);
						}
					} else {
						result.reject(err);
					}
				});
			} else {
				CppCodeGenerator.generate(base, path, options).then(result.resolve, result.reject);
			}
		}
		return result.promise();
	}

	function _handleConfigure() {
		CommandManager.execute(Commands.FILE_PREFERENCES, CppPreferences.getId());
	}

	CommandManager.register("Cpp",             CMD_CPP,           function(){console.log("Cpp");});
	CommandManager.register("Generate Code...", CMD_CPP_GENERATE,  _handleGenerate);
	CommandManager.register("Reverse Code...",  CMD_CPP_REVERSE,   function(){console.log("Reverse code...");});
	CommandManager.register("Configure...",     CMD_CPP_CONFIGURE, _handleConfigure);

	var menu, menuItem;
	menu = MenuManager.getMenu(Commands.TOOLS);
	menuItem = menu.addMenuItem(CMD_CPP);
	menuItem.addMenuItem(CMD_CPP_GENERATE);
	menuItem.addMenuItem(CMD_CPP_REVERSE);
	menuItem.addMenuDivider();
	menuItem.addMenuItem(CMD_CPP_CONFIGURE);

    // for debug

    var getCurrentTime = function () {
        var currentdate = new Date();
        var datetime = "Last Sync: " + currentdate.getDate() + "/"
                + (currentdate.getMonth()+1)  + "/"
                + currentdate.getFullYear() + " @ "
                + currentdate.getHours() + ":"
                + currentdate.getMinutes() + ":"
                + currentdate.getSeconds();
        return datetime;
    }
    console.log("================================================");
    console.log("Java Code Generator Plugin.");
    console.log("Version time - " + CppCodeGenerator.getVersion() );
    console.log(getCurrentTime());
    console.log("================================================");
});<|endoftext|>


<commit_before>/* Copyright (c) 2013-present The TagSpaces Authors.
 * Use of this source code is governed by the MIT license which can be found in the LICENSE.txt file. */

/* globals marked, CodeMirror, $, getParameterByName, sendMessageToHost, initI18N */

sendMessageToHost({ command: 'loadDefaultTextContent' });

let cmEditor;
let viewMode = true;
const locale = getParameterByName('locale');
const filePath = getParameterByName('file');
const filetype = [];
filetype.h = 'clike';
filetype.c = 'clike';
filetype.clj = 'clojure';
filetype.coffee = 'coffeescript';
filetype.cpp = 'clike';
filetype.cs = 'clike';
filetype.css = 'css';
filetype.groovy = 'groovy';
filetype.haxe = 'haxe';
filetype.htm = 'xml';
filetype.html = 'xml';
filetype.java = 'clike';
filetype.js = 'javascript';
filetype.ts = 'javascript';
filetype.jsm = 'javascript';
filetype.json = 'javascript';
filetype.less = 'less';
filetype.lua = 'lua';
filetype.markdown = 'markdown';
filetype.md = 'markdown';
filetype.mdown = 'markdown';
filetype.mdwn = 'markdown';
filetype.mkd = 'markdown';
filetype.ml = 'ocaml';
filetype.mli = 'ocaml';
filetype.pl = 'perl';
filetype.php = 'php';
filetype.py = 'python';
filetype.rb = 'ruby';
filetype.sh = 'shell';
filetype.sql = 'sql';
filetype.svg = 'xml';
filetype.xml = 'xml';
filetype.txt = 'txt';

$(document).ready(() => {
  initI18N(locale, 'ns.editorText.json');

  if (viewMode) {
    $(document).dblclick(() => {
      sendMessageToHost({ command: 'editDocument' });
    });
  }

  let extSettings;
  loadExtSettings();

  if (marked) {
    marked.setOptions({
      renderer: new marked.Renderer(),
      gfm: true,
      tables: true,
      breaks: true,
      pedantic: false,
      smartLists: true,
      smartypants: false
    });
  }

  // Init Markdown Preview functionality
  $('#markdownPreviewModal').on('show.bs.modal', () => {
    if (marked) {
      const modalBody = $('#markdownPreviewModal .modal-body');
      modalBody.html(marked(cmEditor.getValue(), { sanitize: true }));
    } else {
      console.log('markdown to html transformer not found');
    }
  });

  $('#markdownPreview').on('click', () => {
    $('#markdownPreviewModal').modal({ show: true });
  });

  $('#mdHelpButton').on('click', () => {
    $('#markdownHelpModal').modal({ show: true });
  });

  function loadExtSettings() {
    extSettings = JSON.parse(localStorage.getItem('editorTextSettings'));
  }
});

function viewerMode(isViewerMode) {
  viewMode = isViewerMode;
  if (!viewMode) {
    cmEditor.focus();
  }

  // cmEditor.options.lineNumbers = isViewerMode;
  cmEditor.options.cursorBlinkRate = isViewerMode ? -1 : 530;
  cmEditor.options.readOnly = isViewerMode;
  cmEditor.options.foldGutter = isViewerMode;
  cmEditor.options.styleActiveLine = isViewerMode;
  cmEditor.options.matchBrackets = isViewerMode;
  cmEditor.options.showCursorWhenSelecting = isViewerMode;
  cmEditor.options.autofocus = !isViewerMode;
  cmEditor.refresh();
}

function getContent() {
  return cmEditor.getValue();
}

function setContent(content, fileDirectory, isViewMode) {
  const $editorText = $('#editorText');
  $editorText.append(
    "
"
  );

  let fileExt = '';
  let cleanedPath = filePath;
  const lastindexQuestionMark = filePath.lastIndexOf('?');
  if (lastindexQuestionMark > 0) { // Removing everything after ? in URLs .png?queryParam1=2342
    cleanedPath = filePath.substring(0, lastindexQuestionMark);
  }
  fileExt = cleanedPath
    .substring(cleanedPath.lastIndexOf('.') + 1, cleanedPath.length)
    .toLowerCase();
  const mode = filetype[fileExt];

  if (
    mode !== filetype.markdown ||
    mode !== filetype.md ||
    mode !== filetype.mdown ||
    mode !== filetype.mdwn
  ) {
    $('#markdownPreview').hide();
    $('#mdHelpButton').hide();
  } else {
    $('#markdownPreview').show();
    $('#mdHelpButton').show();
  }

  const place = document.getElementById('code');
  cmEditor = new CodeMirror(place, {
    mode,
    lineNumbers: true,
    foldGutter: true,
    gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
    lineWrapping: true,
    tabSize: 2,
    // lineSeparator: isWin ? '\n\r' : null, // TODO check under windows if content contains \n\r -> set
    styleSelectedText: true,
    showCursorWhenSelecting: true,
    autofocus: !viewMode
    // theme: 'lesser-dark',
    // extraKeys: keys // workarrounded with bindGlobal plugin for mousetrap
  });

  CodeMirror.modeURL = 'libs/codemirror/mode/%N/%N.js';
  if (mode) {
    cmEditor.setOption('mode', mode);
    CodeMirror.autoLoadMode(cmEditor, mode);
  } else {
    console.warn('Invalid mode !' + mode);
  }

  viewerMode(isViewMode);

  cmEditor.setSize('100%', '100%');

  const UTF8_BOM = '\ufeff';
  if (content.indexOf(UTF8_BOM) === 0) {
    content = content.substring(1, content.length);
  }

  cmEditor.setValue(content);
  cmEditor.clearHistory();
  cmEditor.refresh();
  cmEditor.addKeyMap({ 'Ctrl-S': () => {
    if (!viewMode) {
      sendMessageToHost({ command: 'saveDocument', filepath: filePath });
    }
  } });

  CodeMirror.on(cmEditor, 'change', () => {
    if (!viewMode) {
      sendMessageToHost({
        command: 'contentChangedInEditor',
        filepath: filePath
      });
      $('.CodeMirror-cursor').show();
    } else {
      $('.CodeMirror-cursor').hide();
    }
  });
}
<commit_msg>fix: click-event unbinding<commit_after>/* Copyright (c) 2013-present The TagSpaces Authors.
 * Use of this source code is governed by the MIT license which can be found in the LICENSE.txt file. */

/* globals marked, CodeMirror, $, getParameterByName, sendMessageToHost, initI18N */

sendMessageToHost({ command: 'loadDefaultTextContent' });

let cmEditor;
let viewMode = true;
const locale = getParameterByName('locale');
const filePath = getParameterByName('file');
const filetype = [];
filetype.h = 'clike';
filetype.c = 'clike';
filetype.clj = 'clojure';
filetype.coffee = 'coffeescript';
filetype.cpp = 'clike';
filetype.cs = 'clike';
filetype.css = 'css';
filetype.groovy = 'groovy';
filetype.haxe = 'haxe';
filetype.htm = 'xml';
filetype.html = 'xml';
filetype.java = 'clike';
filetype.js = 'javascript';
filetype.ts = 'javascript';
filetype.jsm = 'javascript';
filetype.json = 'javascript';
filetype.less = 'less';
filetype.lua = 'lua';
filetype.markdown = 'markdown';
filetype.md = 'markdown';
filetype.mdown = 'markdown';
filetype.mdwn = 'markdown';
filetype.mkd = 'markdown';
filetype.ml = 'ocaml';
filetype.mli = 'ocaml';
filetype.pl = 'perl';
filetype.php = 'php';
filetype.py = 'python';
filetype.rb = 'ruby';
filetype.sh = 'shell';
filetype.sql = 'sql';
filetype.svg = 'xml';
filetype.xml = 'xml';
filetype.txt = 'txt';

$(document).ready(() => {
  initI18N(locale, 'ns.editorText.json');

  if (viewMode) {
    $(document).dblclick(() => {
      sendMessageToHost({ command: 'editDocument' });
    });
  }

  let extSettings;
  loadExtSettings();

  if (marked) {
    marked.setOptions({
      renderer: new marked.Renderer(),
      gfm: true,
      tables: true,
      breaks: true,
      pedantic: false,
      smartLists: true,
      smartypants: false
    });
  }

  // Init Markdown Preview functionality
  $('#markdownPreviewModal').off();
  $('#markdownPreviewModal').on('show.bs.modal', () => {
    if (marked) {
      const modalBody = $('#markdownPreviewModal .modal-body');
      modalBody.html(marked(cmEditor.getValue(), { sanitize: true }));
    } else {
      console.log('markdown to html transformer not found');
    }
  });

  $('#markdownPreview').off();
  $('#markdownPreview').on('click', () => {
    $('#markdownPreviewModal').modal({ show: true });
  });

  $('#mdHelpButton').off();
  $('#mdHelpButton').on('click', () => {
    $('#markdownHelpModal').modal({ show: true });
  });

  function loadExtSettings() {
    extSettings = JSON.parse(localStorage.getItem('editorTextSettings'));
  }
});

function viewerMode(isViewerMode) {
  viewMode = isViewerMode;
  if (!viewMode) {
    cmEditor.focus();
  }

  // cmEditor.options.lineNumbers = isViewerMode;
  cmEditor.options.cursorBlinkRate = isViewerMode ? -1 : 530;
  cmEditor.options.readOnly = isViewerMode;
  cmEditor.options.foldGutter = isViewerMode;
  cmEditor.options.styleActiveLine = isViewerMode;
  cmEditor.options.matchBrackets = isViewerMode;
  cmEditor.options.showCursorWhenSelecting = isViewerMode;
  cmEditor.options.autofocus = !isViewerMode;
  cmEditor.refresh();
}

function getContent() {
  return cmEditor.getValue();
}

function setContent(content, fileDirectory, isViewMode) {
  const $editorText = $('#editorText');
  $editorText.append(
    "
"
  );

  let fileExt = '';
  let cleanedPath = filePath;
  const lastindexQuestionMark = filePath.lastIndexOf('?');
  if (lastindexQuestionMark > 0) {
    // Removing everything after ? in URLs .png?queryParam1=2342
    cleanedPath = filePath.substring(0, lastindexQuestionMark);
  }
  fileExt = cleanedPath
    .substring(cleanedPath.lastIndexOf('.') + 1, cleanedPath.length)
    .toLowerCase();
  const mode = filetype[fileExt];

  if (
    mode !== filetype.markdown ||
    mode !== filetype.md ||
    mode !== filetype.mdown ||
    mode !== filetype.mdwn
  ) {
    $('#markdownPreview').hide();
    $('#mdHelpButton').hide();
  } else {
    $('#markdownPreview').show();
    $('#mdHelpButton').show();
  }

  const place = document.getElementById('code');
  cmEditor = new CodeMirror(place, {
    mode,
    lineNumbers: true,
    foldGutter: true,
    gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
    lineWrapping: true,
    tabSize: 2,
    // lineSeparator: isWin ? '\n\r' : null, // TODO check under windows if content contains \n\r -> set
    styleSelectedText: true,
    showCursorWhenSelecting: true,
    autofocus: !viewMode
    // theme: 'lesser-dark',
    // extraKeys: keys // workarrounded with bindGlobal plugin for mousetrap
  });

  CodeMirror.modeURL = 'libs/codemirror/mode/%N/%N.js';
  if (mode) {
    cmEditor.setOption('mode', mode);
    CodeMirror.autoLoadMode(cmEditor, mode);
  } else {
    console.warn('Invalid mode !' + mode);
  }

  viewerMode(isViewMode);

  cmEditor.setSize('100%', '100%');

  const UTF8_BOM = '\ufeff';
  if (content.indexOf(UTF8_BOM) === 0) {
    content = content.substring(1, content.length);
  }

  cmEditor.setValue(content);
  cmEditor.clearHistory();
  cmEditor.refresh();
  cmEditor.addKeyMap({
    'Ctrl-S': () => {
      if (!viewMode) {
        sendMessageToHost({ command: 'saveDocument', filepath: filePath });
      }
    }
  });

  CodeMirror.on(cmEditor, 'change', () => {
    if (!viewMode) {
      sendMessageToHost({
        command: 'contentChangedInEditor',
        filepath: filePath
      });
      $('.CodeMirror-cursor').show();
    } else {
      $('.CodeMirror-cursor').hide();
    }
  });
}
<|endoftext|>


<commit_before>const electron = require('electron');
const { app, BrowserWindow } = require('electron');
const path = require('path');
const url = require('url');
const Configstore = require('configstore');

const configStore = new Configstore('YouWatch');

app.on('ready', () => {
  const screen = electron.screen;

  const pageUrl = url.format({
    protocol: 'file',
    slashes: true,
    pathname: path.join(__dirname, 'client', 'index.html'),
  });

  const isMac = process.platform === 'darwin';
  const MAIN_WINDOW = 'main';
  const ICON = path.join(__dirname, '..', 'static', 'icon.png');

  const windows = {};

  let isPlayerMaximized = false;
  let isChangingMode = false;
  let primaryDisplay;
  let sortedDisplaysIds;

  onNumberOfDisplaysChange();

  function openMainWindow() {
    if (!windows[MAIN_WINDOW])
      windows[MAIN_WINDOW] = createMainWindow();
  }

  function createMainWindow() {
    const _window = new BrowserWindow({
      title: app.getName(),
      x: configStore.get(getConfigStoreWindow('classic.x')),
      y: configStore.get(getConfigStoreWindow('classic.y')),
      width: configStore.get(getConfigStoreWindow('classic.width')),
      height: configStore.get(getConfigStoreWindow('classic.height')),
      icon: ICON,
      autoHideMenuBar: true,
      minWidth: 880,
      minHeight: 370,
      frame: isMac,
      titleBarStyle: 'hidden-inset',
      alwaysOnTop: false,
      hasShadow: true,
      enableLargerThanScreen: true,
    });

    if (isMac)
      app.dock.setIcon(ICON);

    if (require('electron-is-dev'))
      _window.openDevTools();

    _window.loadURL(pageUrl);
    _window.on('resize', onResize.bind(null, MAIN_WINDOW));
    _window.on('move', onResize.bind(null, MAIN_WINDOW));

    _window.on('closed', onClosed.bind(null, MAIN_WINDOW));

    screen.on('display-added', onNumberOfDisplaysChange);
    screen.on('display-removed', onNumberOfDisplaysChange);

    return _window;
  }

  function togglePlayerState(_isPlayerMaximized) {
    const bounds = configStore.get(getConfigStoreWindow(_isPlayerMaximized ? 'floatOnTop' : 'classic'));

    isChangingMode = true;
    windows[MAIN_WINDOW].setBounds(bounds, true);
    isChangingMode = false;

    isPlayerMaximized = _isPlayerMaximized;
  }

  module.exports.openMainWindow = openMainWindow;
  module.exports.togglePlayerState = togglePlayerState;

  function onResize(windowName) {
    if (isChangingMode || primaryDisplay.id !== screen.getPrimaryDisplay().id)
      return;

    const bounds = windows[windowName].getBounds();
    const key = getConfigStoreWindow(isPlayerMaximized ? 'floatOnTop' : 'classic');
    configStore.set(key, bounds);
  }

  function onClosed(windowName) {
    // dereference the window
    windows[windowName] = null;
  }

  function onNumberOfDisplaysChange() {
    sortedDisplaysIds = screen.getAllDisplays().map((display) => display.id).sort().join('-');
    primaryDisplay = screen.getPrimaryDisplay();

    if (!windows[MAIN_WINDOW] || !configStore.get(getConfigStoreWindowKey())) {
      const { width: screenWidth, height: screenHeight } = primaryDisplay.size;
      const appWidth = 0.75 * screenWidth;
      const appHeight = 0.75 * screenHeight;

      const defaultConfig = {
        classic: {
          x: (screenWidth / 2.0) - (appWidth / 2.0),
          y: (screenHeight / 2.0) - (appHeight / 2.0),
          width: appWidth,
          height: appHeight,
        },
        floatOnTop: {
          x: screenWidth - 640,
          y: screenHeight - 360,
          width: 640,
          height: 360,
        },
      };

      configStore.set(getConfigStoreWindowKey(), defaultConfig);
    }

    if (windows[MAIN_WINDOW]) {
      const bounds = configStore.get(getConfigStoreWindow(isPlayerMaximized ? 'floatOnTop' : 'classic'));
      windows[MAIN_WINDOW].setBounds(bounds, true);
    }
  }

  function getConfigStoreWindowKey() {
    return 'window.' + sortedDisplaysIds;
  }

  function getConfigStoreWindow(param) {
    return getConfigStoreWindowKey() + '.' + param;
  }
});
<commit_msg>Improve position save<commit_after>const electron = require('electron');
const { app, BrowserWindow } = require('electron');
const path = require('path');
const url = require('url');
const Configstore = require('configstore');

const configStore = new Configstore('YouWatch');

app.on('ready', () => {
  const screen = electron.screen;

  const pageUrl = url.format({
    protocol: 'file',
    slashes: true,
    pathname: path.join(__dirname, 'client', 'index.html'),
  });

  const isMac = process.platform === 'darwin';
  const MAIN_WINDOW = 'main';
  const ICON = path.join(__dirname, '..', 'static', 'icon.png');

  const windows = {};

  let isPlayerMaximized = false;
  let isChangingMode = false;
  let primaryDisplay;
  let sortedDisplaysIds;

  function openMainWindow() {
    if (!windows[MAIN_WINDOW])
      windows[MAIN_WINDOW] = createMainWindow();
  }

  function createMainWindow() {
    onNumberOfDisplaysChange();

    const _window = new BrowserWindow({
      title: app.getName(),
      x: configStore.get(getConfigStoreWindow('classic.x')),
      y: configStore.get(getConfigStoreWindow('classic.y')),
      width: configStore.get(getConfigStoreWindow('classic.width')),
      height: configStore.get(getConfigStoreWindow('classic.height')),
      icon: ICON,
      autoHideMenuBar: true,
      minWidth: 880,
      minHeight: 370,
      frame: isMac,
      titleBarStyle: 'hidden-inset',
      alwaysOnTop: false,
      hasShadow: true,
      enableLargerThanScreen: true,
    });

    if (isMac)
      app.dock.setIcon(ICON);

    if (require('electron-is-dev'))
      _window.openDevTools();

    _window.loadURL(pageUrl);
    _window.on('resize', onResize.bind(null, MAIN_WINDOW));
    _window.on('move', onResize.bind(null, MAIN_WINDOW));

    _window.on('closed', onClosed.bind(null, MAIN_WINDOW));

    screen.on('display-added', onNumberOfDisplaysChange);
    screen.on('display-removed', onNumberOfDisplaysChange);

    return _window;
  }

  function togglePlayerState(_isPlayerMaximized) {
    const bounds = configStore.get(getConfigStoreWindow(_isPlayerMaximized ? 'floatOnTop' : 'classic'));

    isChangingMode = true;
    windows[MAIN_WINDOW].setBounds(bounds, true);
    isChangingMode = false;

    isPlayerMaximized = _isPlayerMaximized;
  }

  module.exports.openMainWindow = openMainWindow;
  module.exports.togglePlayerState = togglePlayerState;

  function onResize(windowName) {
    if (isChangingMode || primaryDisplay.id !== screen.getPrimaryDisplay().id)
      return;

    const bounds = windows[windowName].getBounds();
    const key = getConfigStoreWindow(isPlayerMaximized ? 'floatOnTop' : 'classic');
    configStore.set(key, bounds);
  }

  function onClosed(windowName) {
    // dereference the window
    windows[windowName] = null;
  }

  function onNumberOfDisplaysChange() {
    sortedDisplaysIds = screen.getAllDisplays().map((display) => display.id).sort().join('-');
    primaryDisplay = screen.getPrimaryDisplay();

    if (!configStore.get(getConfigStoreWindowKey())) {
      const { width: screenWidth, height: screenHeight } = primaryDisplay.size;
      const appWidth = 0.75 * screenWidth;
      const appHeight = 0.75 * screenHeight;

      const defaultConfig = {
        classic: {
          x: (screenWidth / 2.0) - (appWidth / 2.0),
          y: (screenHeight / 2.0) - (appHeight / 2.0),
          width: appWidth,
          height: appHeight,
        },
        floatOnTop: {
          x: screenWidth - 640,
          y: screenHeight - 360,
          width: 640,
          height: 360,
        },
      };

      configStore.set(getConfigStoreWindowKey(), defaultConfig);
    }

    if (windows[MAIN_WINDOW]) {
      const bounds = configStore.get(getConfigStoreWindow(isPlayerMaximized ? 'floatOnTop' : 'classic'));
      windows[MAIN_WINDOW].setBounds(bounds, true);
    }
  }

  function getConfigStoreWindowKey() {
    return 'window.' + sortedDisplaysIds;
  }

  function getConfigStoreWindow(param) {
    return getConfigStoreWindowKey() + '.' + param;
  }
});
<|endoftext|>


<commit_before>import React from "react";

// Predefined size options from Youtube.
const videoSizes = new Map([
  [
    "small", {
      width: 560,
      height: 315
    }
  ], [
    "medium", {
      width: 640,
      height: 360
    }
  ], [
    "large", {
      width: 853,
      height: 480
    }
  ], [
    "largest", {
      width: 1280,
      height: 720
    }
  ]
]);

function YoutubeEmbedVideo(props) {
  const {
    videoId,
    width,
    height,
    size,
    autoplay,
    enhancedPrivacy,
    suggestions,
    controls,
    showInfo,
    ...rest
  } = props;
  let url = getFullVideoUrl(props),
    { calculatedWidth, calculatedHeight } = getVideoSize(width, height, size);

  return (
    <iframe
      width={calculatedWidth}
      height={calculatedHeight}
      src={url}
      frameBorder="0"
      allowFullScreen={true}
      {...rest}
    />
  );
}

function getFullVideoUrl(props) {
  let params = [];

  if (props.enhancedPrivacy)
    params.push("https://www.youtube-nocookie.com/embed/");
  else
    params.push("https://www.youtube.com/embed/");

  params.push(props.videoId);
  params.push(props.autoplay ? "?autoplay=1" : "?autoplay=0");

  if (!props.suggestions)
    params.push("&rel=0");

  if (!props.controls)
    params.push("&controls=0");

  if (!props.showInfo)
    params.push("&showinfo=0");

  return params.join("");
}

function getVideoSize(width, height, size) {
  if (size && videoSizes.has(size.toLowerCase()))
    return videoSizes.get(size.toLowerCase());
  else
    return {
      width,
      height
    }
}

YoutubeEmbedVideo.propTypes = {
  videoId: React.PropTypes.string.isRequired,
  width: React.PropTypes.number,
  height: React.PropTypes.number,
  size: React.PropTypes.string,
  autoplay: React.PropTypes.bool,
  enhancedPrivacy: React.PropTypes.bool,
  suggestions: React.PropTypes.bool,
  controls: React.PropTypes.bool,
  showInfo: React.PropTypes.bool
};

YoutubeEmbedVideo.defaultProps = {
  width: 560,
  height: 315,
  size: "",
  autoplay: false,
  enhancedPrivacy: false,
  suggestions: true,
  controls: true,
  showInfo: true
};

export default YoutubeEmbedVideo;
<commit_msg>Fix size calculation bug after adding class and style props<commit_after>import React from "react";

// Predefined size options from Youtube.
const videoSizes = new Map([
  [
    "small", {
      width: 560,
      height: 315
    }
  ], [
    "medium", {
      width: 640,
      height: 360
    }
  ], [
    "large", {
      width: 853,
      height: 480
    }
  ], [
    "largest", {
      width: 1280,
      height: 720
    }
  ]
]);

function YoutubeEmbedVideo(props) {
  let {
    videoId,
    autoplay,
    suggestions,
    controls,
    showInfo,
    enhancedPrivacy,
    width,
    height,
    size,
    ...rest
  } = props;

  let url = getFullVideoUrl(props);
  let calculatedSize = getVideoSize(width, height, size);

  return (
    <iframe
      width={calculatedSize.width}
      height={calculatedSize.height}
      src={url}
      frameBorder="0"
      allowFullScreen={true}
      {...rest}
    />
  );
}

function getFullVideoUrl(props) {
  let params = [];

  if (props.enhancedPrivacy)
    params.push("https://www.youtube-nocookie.com/embed/");
  else
    params.push("https://www.youtube.com/embed/");

  params.push(props.videoId);
  params.push(props.autoplay ? "?autoplay=1" : "?autoplay=0");

  if (!props.suggestions)
    params.push("&rel=0");

  if (!props.controls)
    params.push("&controls=0");

  if (!props.showInfo)
    params.push("&showinfo=0");

  return params.join("");
}

function getVideoSize(width, height, size) {
  if (size && videoSizes.has(size.toLowerCase()))
    return videoSizes.get(size.toLowerCase());

  return {
    width,
    height
  }
}

YoutubeEmbedVideo.propTypes = {
  videoId: React.PropTypes.string.isRequired,
  width: React.PropTypes.number,
  height: React.PropTypes.number,
  size: React.PropTypes.string,
  autoplay: React.PropTypes.bool,
  enhancedPrivacy: React.PropTypes.bool,
  suggestions: React.PropTypes.bool,
  controls: React.PropTypes.bool,
  showInfo: React.PropTypes.bool
};

YoutubeEmbedVideo.defaultProps = {
  width: 560,
  height: 315,
  size: "",
  autoplay: false,
  enhancedPrivacy: false,
  suggestions: true,
  controls: true,
  showInfo: true
};

export default YoutubeEmbedVideo;
<|endoftext|>


<commit_before>angular.module('chatApp', []).controller('ChatController', function($scope) {
    // When we're using HTTPS, use WSS too.
    var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
    var chatsock = new ReconnectingWebSocket(ws_scheme + '://' + window.location.host + "/chat" + window.location.pathname);

    chatsock.onmessage = function(message) {
        var data = JSON.parse(message.data);
        chatform.messages.push({timestamp:data.timestamp, handle:data.handle, message:data.message});
    };

    $scope.submitMessage = function() {
        var message = {
            handle: $scope.handle,
            message: $scope.message,
        }
        chatsock.send(JSON.stringify(message));
        $scope.message = '';
        return false;
    });
});
<commit_msg>Update chat.js<commit_after>angular.module('chatApp', []).controller('ChatController', function($scope) {
    // When we're using HTTPS, use WSS too.
    var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
    var chatsock = new ReconnectingWebSocket(ws_scheme + '://' + window.location.host + "/chat" + window.location.pathname);

    chatsock.onmessage = function(message) {
        var data = JSON.parse(message.data);
        $scope.messages.push({timestamp:data.timestamp, handle:data.handle, message:data.message});
    };

    $scope.submitMessage = function() {
        var message = {
            handle: $scope.handle,
            message: $scope.message,
        }
        chatsock.send(JSON.stringify(message));
        $scope.message = '';
        return false;
    });
});
<|endoftext|>


<commit_before>var land;
var hero;
var map;
var layer;
var layerObstacles;
var socket;
var blueTeam = {};
var redTeam = {};
var blueTeamData = [];
var redTeamData = [];
var spellsData = [];
var redTower;
var blueTower;
var gameParams;
var chatKey;
var chatting = false;

function parseUrlParams() {
    var params = location.pathname.substring(1).split('/');

    var errorMessage = null;
    var example = '\nExample: /darwinbattle/jon/blue/warrior';

    if (!/^[a-zA-Z]+$/.test(params[0])) {
        errorMessage = 'The room name must be letters only.';
    } else if (!/^[a-zA-Z]+$/.test(params[1])) {
        errorMessage = 'The username must be letters only.';
    } else if (params.length !== 4) {
        errorMessage = 'Not the right number of parameters.';
    } else if (params[2] !== 'red' && params[2] !== 'blue') {
        errorMessage = "Team parameter must be 'red' or 'blue'.";
    } else if (params[3] !== 'warrior' && params[3] !== 'mage' && params[3] !== 'healer') {
        errorMessage = "Class parameter must be 'warrior', 'mage', or 'healer'.";
    }

    if (errorMessage) {
        alert(errorMessage + example);
        return null;
    }

    return {
        'room': params[0],
        'username': params[1],
        'team': params[2],
        'characterClass': params[3]
    }
}

function preload() {
    // Sets up map stuff
    game.load.tilemap('desertMap', '/static/desert.json', null, Phaser.Tilemap.TILED_JSON);
    game.load.image('tiles', '/static/map.png');

    game.load.image('tower_red', '/static/sprites/tower_red.png');
    game.load.image('tower_blue', '/static/sprites/tower_blue.png');

    game.load.atlasJSONHash('ranger', '/static/sprites/ranger/ranger.png', '/static/sprites/ranger/ranger.json');
    game.load.atlasJSONHash('healer', '/static/sprites/healer/healer.png', '/static/sprites/healer/healer.json');
    game.load.atlasJSONHash('ninja', '/static/sprites/ninja/ninja.png', '/static/sprites/ninja/ninja.json');

    game.load.atlasJSONHash('blood', '/static/sprites/blood/blood.png', '/static/sprites/blood/blood.json');

    game.load.audio('railgun', '/static/sounds/railgun.mp3');
    game.load.audio('heal', '/static/sounds/heal.mp3');
    game.load.audio('spell', '/static/sounds/spell.wav');
    game.load.audio('simple_spell', '/static/sounds/simple_spell.wav');
    game.load.audio('punch', '/static/sounds/punch.wav');
    game.load.audio('fatality', '/static/sounds/fatality.mp3');

}

function create() {
    var websocketURL = 'http://' + window.location.host + '/websocket';
    socket = new SockJS(websocketURL);

    //  Resize our game world to be a 2000 x 2000 square
    game.world.setBounds(0, 0, 1008, 608);

    map = game.add.tilemap('desertMap');

    map.addTilesetImage('map', 'tiles');
    map.fixedToCamera = true;

    layer = map.createLayer('Base');
    layer.resizeWorld();

    layerObstacles = map.createLayer('obstacles');
    layerObstacles.resizeWorld();

    //  The base of our hero
    hero = createHero(gameParams['characterClass'], gameParams['username'], gameParams['team'], true);
    if (hero.team === 'blue') {
        blueTeam[hero.characterName] = hero;
    } else {
        redTeam[hero.characterName] = hero;
    }

    game.camera.follow(hero);
    game.camera.deadzone = new Phaser.Rectangle(150, 150, 500, 300);
    game.camera.focusOnXY(0, 0);

    setSocketListeners();

    chatKey = game.input.keyboard.addKey(Phaser.Keyboard.ENTER);
    chatKey.onDown.add(function(event) {
        if (!$('#chat-input').val()) {
            toggleChat();
        } else {
            sendChatMessage();
            toggleChat();
        }
    }.bind(this));

    $('#chat-input').focus(function() {
        hero.disableKeys();
    });

    $('#chat-input').blur(function() {
        hero.enableKeys();
    });

    // BLOOD
    // var blood = game.add.sprite(60, 60, 'blood');
    // blood.animations.add('blood');
    // blood.animations.play('blood', 10, true);
}

function update() {
    hero.updateTo();

    // map.tilePosition.x = -game.camera.x;
    // map.tilePosition.y = -game.camera.y;

    if (spellsData.length > 0) {
        updateSpells();
    }
    blueTeamData = [];
    redTeamData = [];

    // Update all heroes to flash when hit
    for (var key in blueTeam) {
        blueTeam[key].updateHitFlash();
    }
    for (var key in redTeam) {
        redTeam[key].updateHitFlash();
    }
}

function updateTeam(team, teamData, teamName) {
    var activeUsers = Object.keys(team);
    var processedUsers = {};
    for (var i = 0; i < teamData.length; i++) {
        var player = teamData[i];
        if (!team[player['username']]) {
            team[player['username']] = createHero(player['character_class'], player['username'], teamName, false)
        }
        team[player['username']].receiveMessage(player);
        processedUsers[player['username']] = true;
    }
    for (var i = 0; i < activeUsers.length; i++) {
        if (!processedUsers[activeUsers[i]]) {
            team[activeUsers[i]].destroyHero();
            delete team[activeUsers[i]];
        }
    }
    return team;
}

function updateKills(blueKills, redKills) {
    $('.js-kills-blue').html(blueKills);
    $('.js-kills-red').html(redKills);
}

function updateSpells() {
    var tmpSpells = [];
    for (var i = 0; i < spellsData.length; i++) {
        var spellData = spellsData[i];
        tmpSpells.push(new Spell(game, spellData));
        hero.bringToTop();
        spellsData.splice(i, 1);
        i--;
    }
    setTimeout(function(){
        for (var i = 0; i < tmpSpells.length; i++) {
            tmpSpells[i].destroy();
        }
        tmpSpells = null;
    }, 120);
}

function render() {
    game.debug.text('', 32, 32);
}

function setSocketListeners() {
    socket.onopen = function() {
        var enterRoomMessage = JSON.stringify({
            type: 'FE_JOIN_ROOM',
            content: gameParams
        });
        this.send(enterRoomMessage);
    };

    socket.onmessage = function(evt) {
        var data = JSON.parse(evt.data);
        if (data['type'] == 'BE_ALL_MAIN_BROADCAST') {
            blueTeamData = data['content']['teams']['blue']['players'];
            redTeamData = data['content']['teams']['red']['players'];
            updateTeam(blueTeam, blueTeamData, 'blue');
            updateTeam(redTeam, redTeamData, 'red');
            spellsData.push.apply(spellsData, data['content']['spells']);
            updateKills(
                data['content']['teams']['blue']['kills'],
                data['content']['teams']['red']['kills']
            );
            if(!redTower) {
                redTower = new Tower(
                    game,
                    data['content']['teams']['red']['building_position']['x'],
                    data['content']['teams']['red']['building_position']['y'],
                    'red'
                );
            }
            if(!blueTower) {
                blueTower = new Tower(
                    game,
                    data['content']['teams']['blue']['building_position']['x'],
                    data['content']['teams']['blue']['building_position']['y'],
                    'blue'
                );
            }
            redTower.updateTower(
                data['content']['teams']['red']['building_hp'],
                data['content']['teams']['red']['building_max_hp']
            );
            blueTower.updateTower(
                data['content']['teams']['blue']['building_hp'],
                data['content']['teams']['blue']['building_max_hp']
            );
        } else if (data['type'] == 'BE_SEND_CHAT') {
            addChatMessage(data['content']);
        }
    };

    socket.onclose = function() {
        console.log('Connection closed.');
    };

}

function createHero(characterClass, username, team, isLocalPlayer) {
    var pom = null;
    switch (characterClass) {
        case 'warrior':
            pom = new Warrior(game, username, team, isLocalPlayer, 0, 0);
            break;
        case 'healer':
            pom = new Healer(game, username, team, isLocalPlayer, 10, 10);
            break;
        case 'mage':
            pom = new Mage(game, username, team, isLocalPlayer, 20, 20);
            break;
    }
    return pom;
}

function sendChatMessage() {
    var message = $('#chat-input').val();
    socket.send(JSON.stringify({
        type: 'FE_SEND_CHAT',
        content: {
            'message': message
        }
    }));
    $('#chat-input').val('')
}

function addChatMessage(data) {
    var sender = data['username'];
    var message = data['message'];
    var timestamp = data['timestamp'];
    var color = '#555555';
    if(data['team']) {
        if(data['team'] === 'red') {
            color = '#DD0000';
        } else if (data['team'] === 'blue') {
            color = '#0000DD';
        }
    }
    var li = $('<li>');
    li.append($('<strong>').text('[' + timestamp + '] '));
    li.append($('<strong>').css({'color':color}).text(sender + ': '));
    li.append($('<span>').text(message));
    $('.chat-messages').prepend(li);
}

function toggleChat() {
    chatting = !chatting;
    if(chatting) {
        $('#chat-input').focus();
    } else {
        $('#chat-input').blur();
    }
}

$('.js-form').submit(function(event){
    event.preventDefault();
    window.location = $('#popup-room').val() + '/' + $('#popup-user').val()
        + '/' + $('#popup-team').val() + '/' + $('#popup-class').val();
});

if (location.pathname == '/') {
    $('.js-popup').show();
}
else
{
    gameParams = parseUrlParams();
    if (!gameParams)
        window.location = '/';
    $('.ui').show();
    $('.chat-container').show();
    var game = new Phaser.Game(1008, 608, Phaser.AUTO, 'canvas', {
        preload: preload,
        create: create,
        update: update,
        render: render
    });
}

<commit_msg>Initial game.js manual linting<commit_after>var land;
var hero;
var map;
var layer;
var layerObstacles;
var socket;
var blueTeam = {};
var redTeam = {};
var blueTeamData = [];
var redTeamData = [];
var spellsData = [];
var redTower;
var blueTower;
var gameParams;
var chatKey;
var chatting = false;

function parseUrlParams() {
    var params = location.pathname.substring(1).split('/');

    var errorMessage = null;
    var example = '\nExample: /darwinbattle/jon/blue/warrior';

    if (!/^[a-zA-Z]+$/.test(params[0])) {
        errorMessage = 'The room name must be letters only.';
    } else if (!/^[a-zA-Z]+$/.test(params[1])) {
        errorMessage = 'The username must be letters only.';
    } else if (params.length !== 4) {
        errorMessage = 'Not the right number of parameters.';
    } else if (params[2] !== 'red' && params[2] !== 'blue') {
        errorMessage = "Team parameter must be 'red' or 'blue'.";
    } else if (params[3] !== 'warrior' && params[3] !== 'mage' && params[3] !== 'healer') {
        errorMessage = "Class parameter must be 'warrior', 'mage', or 'healer'.";
    }

    if (errorMessage) {
        alert(errorMessage + example);
        return null;
    }

    return {
        'room': params[0],
        'username': params[1],
        'team': params[2],
        'characterClass': params[3]
    };
}

function preload() {
    // Sets up map stuff
    game.load.tilemap('desertMap', '/static/desert.json', null, Phaser.Tilemap.TILED_JSON);
    game.load.image('tiles', '/static/map.png');

    game.load.image('tower_red', '/static/sprites/tower_red.png');
    game.load.image('tower_blue', '/static/sprites/tower_blue.png');

    game.load.atlasJSONHash('ranger', '/static/sprites/ranger/ranger.png', '/static/sprites/ranger/ranger.json');
    game.load.atlasJSONHash('healer', '/static/sprites/healer/healer.png', '/static/sprites/healer/healer.json');
    game.load.atlasJSONHash('ninja', '/static/sprites/ninja/ninja.png', '/static/sprites/ninja/ninja.json');

    game.load.atlasJSONHash('blood', '/static/sprites/blood/blood.png', '/static/sprites/blood/blood.json');

    game.load.audio('railgun', '/static/sounds/railgun.mp3');
    game.load.audio('heal', '/static/sounds/heal.mp3');
    game.load.audio('spell', '/static/sounds/spell.wav');
    game.load.audio('simple_spell', '/static/sounds/simple_spell.wav');
    game.load.audio('punch', '/static/sounds/punch.wav');
    game.load.audio('fatality', '/static/sounds/fatality.mp3');

}

function create() {
    var websocketURL = 'http://' + window.location.host + '/websocket';
    socket = new SockJS(websocketURL);

    //  Resize our game world to be a 2000 x 2000 square
    game.world.setBounds(0, 0, 1008, 608);

    map = game.add.tilemap('desertMap');

    map.addTilesetImage('map', 'tiles');
    map.fixedToCamera = true;

    layer = map.createLayer('Base');
    layer.resizeWorld();

    layerObstacles = map.createLayer('obstacles');
    layerObstacles.resizeWorld();

    //  The base of our hero
    hero = createHero(gameParams.characterClass, gameParams.username, gameParams.team, true);
    if (hero.team === 'blue') {
        blueTeam[hero.characterName] = hero;
    } else {
        redTeam[hero.characterName] = hero;
    }

    game.camera.follow(hero);
    game.camera.deadzone = new Phaser.Rectangle(150, 150, 500, 300);
    game.camera.focusOnXY(0, 0);

    setSocketListeners();

    chatKey = game.input.keyboard.addKey(Phaser.Keyboard.ENTER);
    chatKey.onDown.add(function(event) {
        if (!$('#chat-input').val()) {
            toggleChat();
        } else {
            sendChatMessage();
            toggleChat();
        }
    }.bind(this));

    $('#chat-input').focus(function() {
        hero.disableKeys();
    });

    $('#chat-input').blur(function() {
        hero.enableKeys();
    });

    // BLOOD
    // var blood = game.add.sprite(60, 60, 'blood');
    // blood.animations.add('blood');
    // blood.animations.play('blood', 10, true);
}

function update() {
    hero.updateTo();

    // map.tilePosition.x = -game.camera.x;
    // map.tilePosition.y = -game.camera.y;

    if (spellsData.length > 0) {
        updateSpells();
    }
    blueTeamData = [];
    redTeamData = [];

    // Update all heroes to flash when hit
    for (var key in blueTeam) {
        blueTeam[key].updateHitFlash();
    }
    for (var key in redTeam) {
        redTeam[key].updateHitFlash();
    }
}

function updateTeam(team, teamData, teamName) {
    var activeUsers = Object.keys(team);
    var processedUsers = {};
    for (var i = 0; i < teamData.length; i++) {
        var player = teamData[i];
        if (!team[player.username]) {
            team[player.username] = createHero(player.character_class, player.username, teamName, false);
        }
        team[player.username].receiveMessage(player);
        processedUsers[player.username] = true;
    }
    for (var i = 0; i < activeUsers.length; i++) {
        if (!processedUsers[activeUsers[i]]) {
            team[activeUsers[i]].destroyHero();
            delete team[activeUsers[i]];
        }
    }
    return team;
}

function updateKills(blueKills, redKills) {
    $('.js-kills-blue').html(blueKills);
    $('.js-kills-red').html(redKills);
}

function updateSpells() {
    var tmpSpells = [];
    for (var i = 0; i < spellsData.length; i++) {
        var spellData = spellsData[i];
        tmpSpells.push(new Spell(game, spellData));
        hero.bringToTop();
        spellsData.splice(i, 1);
        i--;
    }
    setTimeout(function(){
        for (var i = 0; i < tmpSpells.length; i++) {
            tmpSpells[i].destroy();
        }
        tmpSpells = null;
    }, 120);
}

function render() {
    game.debug.text('', 32, 32);
}

function setSocketListeners() {
    socket.onopen = function() {
        var enterRoomMessage = JSON.stringify({
            type: 'FE_JOIN_ROOM',
            content: gameParams
        });
        this.send(enterRoomMessage);
    };

    socket.onmessage = function(evt) {
        var data = JSON.parse(evt.data);
        if (data.type == 'BE_ALL_MAIN_BROADCAST') {
            blueTeamData = data.content.teams.blue.players;
            redTeamData = data.content.teams.red.players;
            updateTeam(blueTeam, blueTeamData, 'blue');
            updateTeam(redTeam, redTeamData, 'red');
            spellsData.push.apply(spellsData, data.content.spells);
            updateKills(
                data.content.teams.blue.kills,
                data.content.teams.red.kills
            );
            if(!redTower) {
                redTower = new Tower(
                    game,
                    data.content.teams.red.building_position.x,
                    data.content.teams.red.building_position.y,
                    'red'
                );
            }
            if(!blueTower) {
                blueTower = new Tower(
                    game,
                    data.content.teams.blue.building_position.x,
                    data.content.teams.blue.building_position.y,
                    'blue'
                );
            }
            redTower.updateTower(
                data.content.teams.red.building_hp,
                data.content.teams.red.building_max_hp
            );
            blueTower.updateTower(
                data.content.teams.blue.building_hp,
                data.content.teams.blue.building_max_hp
            );
        } else if (data.type == 'BE_SEND_CHAT') {
            addChatMessage(data.content);
        }
    };

    socket.onclose = function() {
        console.log('Connection closed.');
    };

}

function createHero(characterClass, username, team, isLocalPlayer) {
    var pom = null;
    switch (characterClass) {
        case 'warrior':
            pom = new Warrior(game, username, team, isLocalPlayer, 0, 0);
            break;
        case 'healer':
            pom = new Healer(game, username, team, isLocalPlayer, 10, 10);
            break;
        case 'mage':
            pom = new Mage(game, username, team, isLocalPlayer, 20, 20);
            break;
    }
    return pom;
}

function sendChatMessage() {
    var message = $('#chat-input').val();
    socket.send(JSON.stringify({
        type: 'FE_SEND_CHAT',
        content: {
            'message': message
        }
    }));
    $('#chat-input').val('');
}

function addChatMessage(data) {
    var sender = data.username;
    var message = data.message;
    var timestamp = data.timestamp;
    var color = '#555555';
    if(data.team) {
        if(data.team === 'red') {
            color = '#DD0000';
        } else if (data.team === 'blue') {
            color = '#0000DD';
        }
    }
    var li = $('<li>');
    li.append($('<strong>').text('[' + timestamp + '] '));
    li.append($('<strong>').css({'color':color}).text(sender + ': '));
    li.append($('<span>').text(message));
    $('.chat-messages').prepend(li);
}

function toggleChat() {
    chatting = !chatting;
    if(chatting) {
        $('#chat-input').focus();
    } else {
        $('#chat-input').blur();
    }
}

$('.js-form').submit(function(event){
    event.preventDefault();
    window.location = $('#popup-room').val() + '/' + $('#popup-user').val() +
        '/' + $('#popup-team').val() + '/' + $('#popup-class').val();
});

if (location.pathname == '/') {
    $('.js-popup').show();
}
else
{
    gameParams = parseUrlParams();
    if (!gameParams)
        window.location = '/';
    $('.ui').show();
    $('.chat-container').show();
    var game = new Phaser.Game(1008, 608, Phaser.AUTO, 'canvas', {
        preload: preload,
        create: create,
        update: update,
        render: render
    });
}
<|endoftext|>


<commit_before>$(function() {

  var highlighter = new Sunlight.Highlighter();

  function sendToServer(content, callback) {
    $.ajax({
      type: 'POST',
      url: "/ghci",
      data: {'data' : content},
      success: callback
    });
  }

  function startsWith(bigger, smaller) {
    if (smaller.length > bigger) { return false; }
    return bigger.slice(0, smaller.length) === smaller;
  }

  function htmlDecode(input){
    var e = document.createElement('div');
    e.innerHTML = input;
    return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
  }

  function decodeResponse(odata, cn) {
    content = $.parseJSON(odata);
    var out;

    if (content['type'] == "error") {
      out = [{
        msg: htmlDecode(content['msg'][2]),
        className: "output-error"
      }];
    } else if (content['type'] == "doc") {
      out = [{
        msg: htmlDecode(content['msg']),
        className: "output-doc"
      }];
    } else if (content['type'] == "value") {
      var context;
      try {
        context = highlighter.highlight(content['msg'], "haskell");
      } catch (e) {
        contet = undefined;
      }
      if (context == undefined || context.getNodes() == undefined) {
        out = $("");
        out.text(content['msg']);
        out.html(out.html().replace(/\n/g,'
'));
      } else {
        out = document.createElement("div");
        var nodes = context.getNodes();
        for (var i = 0; i < nodes.length; i++) {
          out.appendChild(nodes[i]);
        }
      }
      if (content['prompt'] && content['prompt'].length > 0) {
        cn.promptLabel = content['prompt'] + ' ';
      }
    } else {
      out = [{
        msg: htmlDecode(odata),
        className: "output-doc"
      }];
    }

    return out;
  }

  /* ************************************ */
  /* Timers... */
  /* ************************************ */

  // Keep-Alive (once every 10 seconds)
  setInterval(function () {
    $.post('/ghci');
  }, 10 * 1000);

  /* ************************************ */
  /* JQuery Console... */
  /* ************************************ */

  var cn = $("#console").console({
    welcomeMessage:'Welcome to GHC.IO!',
    promptLabel: 'Prelude> ',
    autofocus: true,
    animateScroll: true,
    promptHistory: true,

    commandValidate:function(line) {
      if (line == "") return false;
      else return true;
    },

    commandHandle: function(line, report) {
      sendToServer(line, function(data){
        report(decodeResponse(data, cn));
        // prettyPrint(); // prettyPrintOne may be better here...
        // Sunlight.highlightAll();
        window.scrollTo(0, document.body.scrollHeight);
      });
    },

    charInsertTrigger: function(keycode,line) {
      window.scrollTo(0, document.body.scrollHeight);
      return true;
    }
  });

});
<commit_msg>fix line breaks<commit_after>$(function() {

  var highlighter = new Sunlight.Highlighter();

  function sendToServer(content, callback) {
    $.ajax({
      type: 'POST',
      url: "/ghci",
      data: {'data' : content},
      success: callback
    });
  }

  function startsWith(bigger, smaller) {
    if (smaller.length > bigger) { return false; }
    return bigger.slice(0, smaller.length) === smaller;
  }

  function htmlDecode(input){
    var e = document.createElement('div');
    e.innerHTML = input;
    return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
  }

  function decodeResponse(odata, cn) {
    content = $.parseJSON(odata);
    var out;

    if (content['type'] == "error") {
      out = [{
        msg: htmlDecode(content['msg'][2]),
        className: "output-error"
      }];
    } else if (content['type'] == "doc") {
      out = [{
        msg: htmlDecode(content['msg']),
        className: "output-doc"
      }];
    } else if (content['type'] == "value") {
      var context;
      try {
        context = highlighter.highlight(content['msg'], "haskell");
      } catch (e) {
        contet = undefined;
      }
      if (context == undefined || context.getNodes() == undefined) {
        out = $("");
        out.text(content['msg']);
        out.html(out.html().replace(/\n/g,'
'));
      } else {
        out = document.createElement("div");
        var nodes = context.getNodes();
        for (var i = 0; i < nodes.length; i++) {
          var n = $(nodes[i]);
          n.html(n.html().replace(/\n/g, '
'));
          out.appendChild(nodes[i]);
        }
      }
      if (content['prompt'] && content['prompt'].length > 0) {
        cn.promptLabel = content['prompt'] + ' ';
      }
    } else {
      out = [{
        msg: htmlDecode(odata),
        className: "output-doc"
      }];
    }

    return out;
  }

  /* ************************************ */
  /* Timers... */
  /* ************************************ */

  // Keep-Alive (once every 10 seconds)
  setInterval(function () {
    $.post('/ghci');
  }, 10 * 1000);

  /* ************************************ */
  /* JQuery Console... */
  /* ************************************ */

  var cn = $("#console").console({
    welcomeMessage:'Welcome to GHC.IO!',
    promptLabel: 'Prelude> ',
    autofocus: true,
    animateScroll: true,
    promptHistory: true,

    commandValidate:function(line) {
      if (line == "") return false;
      else return true;
    },

    commandHandle: function(line, report) {
      sendToServer(line, function(data){
        report(decodeResponse(data, cn));
        // prettyPrint(); // prettyPrintOne may be better here...
        // Sunlight.highlightAll();
        window.scrollTo(0, document.body.scrollHeight);
      });
    },

    charInsertTrigger: function(keycode,line) {
      window.scrollTo(0, document.body.scrollHeight);
      return true;
    }
  });

});
<|endoftext|>


<commit_before>$(function() {
  function fadeOut(element) {
    element.animate({ margin: 'hide', padding: 'hide', height: 'hide' }, 'fast', 'swing', function() {
        $(this).remove()
    });
  }

  // inspired by http://stackoverflow.com/questions/22636819/confirm-delete-using-bootstrap-3-modal-box
  $('button[name="removePost"]').on('click', function(e) {
    var $form = $(this).closest('form');
    e.preventDefault();
    $('#confirm-delete').modal({ keyboard: false })
      .one('click', '#delete', function() {
        $form.trigger('submit');
      });
  });

  var alertSuccess = $(".alert-success");
  window.setTimeout(function() {
    fadeOut(alertSuccess)
  }, 4000);
  $('button[class="close"]').on('click', function(e) {
    fadeOut(alertSuccess);
  });
});
<commit_msg>lower timeout<commit_after>$(function() {
  function fadeOut(element) {
    element.animate({ margin: 'hide', padding: 'hide', height: 'hide' }, 'fast', 'swing', function() {
        $(this).remove()
    });
  }

  // inspired by http://stackoverflow.com/questions/22636819/confirm-delete-using-bootstrap-3-modal-box
  $('button[name="removePost"]').on('click', function(e) {
    var $form = $(this).closest('form');
    e.preventDefault();
    $('#confirm-delete').modal({ keyboard: false })
      .one('click', '#delete', function() {
        $form.trigger('submit');
      });
  });

  var alertSuccess = $(".alert-success");
  window.setTimeout(function() {
    fadeOut(alertSuccess)
  }, 2000);
  $('button[class="close"]').on('click', function(e) {
    fadeOut(alertSuccess);
  });
});
<|endoftext|>


<commit_before>/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/* Copyright 2012 Mozilla Foundation
 *
 * 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.
 */
/* jshint node:true */
/* globals cat, cd, cp, echo, env, exec, exit, find, ls, mkdir, mv, process, rm,
           sed, target, test */

'use strict';

require('./external/shelljs/make');
var crlfchecker = require('./external/crlfchecker/crlfchecker.js');
var path = require('path');
var staticServer = require('node-static');

var ROOT_DIR = __dirname + '/'; // absolute path to project's root

//
// make all
//
target.all = function() {
  // Don't do anything by default
  echo('Please specify a target. Available targets:');
  for (var t in target)
    if (t !== 'all') echo('  ' + t);
};

//
// make lint
//
target.lint = function() {
  cd(ROOT_DIR);
  echo();
  echo('### Linting JS files');

  var LINT_FILES = ['make.js',
                    'external/crlfchecker/',
                    'src/'
                    ];

  var jshintPath = path.normalize('./node_modules/.bin/jshint');
  if (!test('-f', jshintPath)) {
    echo('jshint is not installed -- installing...');
    exec('npm install jshint');
  }

  exit(exec('"' + jshintPath + '" --reporter test/reporter.js ' +
            LINT_FILES.join(' ')).code);

  crlfchecker.checkIfCrlfIsPresent(LINT_FILES);
};

target.server = function() {
  var file = new staticServer.Server();

  require('http').createServer(function (request, response) {
      request.addListener('end', function () {
          //
          // Serve files!
          //
          file.serve(request, response);
      });
  }).listen(8888);

  echo('### Running local server')
  echo('');
  echo('Running server at localhost:8888')
};

//
// make makefile
//
target.makefile = function() {
  var makefileContent = 'help:\n\tnode make\n\n';
  var targetsNames = [];
  for (var i in target) {
    makefileContent += i + ':\n\tnode make ' + i + '\n\n';
    targetsNames.push(i);
  }
  makefileContent += '.PHONY: ' + targetsNames.join(' ') + '\n';
  makefileContent.to('Makefile');
};
<commit_msg>Remove not yet existing src/ directory<commit_after>/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/* Copyright 2012 Mozilla Foundation
 *
 * 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.
 */
/* jshint node:true */
/* globals cat, cd, cp, echo, env, exec, exit, find, ls, mkdir, mv, process, rm,
           sed, target, test */

'use strict';

require('./external/shelljs/make');
var crlfchecker = require('./external/crlfchecker/crlfchecker.js');
var path = require('path');
var staticServer = require('node-static');

var ROOT_DIR = __dirname + '/'; // absolute path to project's root

//
// make all
//
target.all = function() {
  // Don't do anything by default
  echo('Please specify a target. Available targets:');
  for (var t in target)
    if (t !== 'all') echo('  ' + t);
};

//
// make lint
//
target.lint = function() {
  cd(ROOT_DIR);
  echo();
  echo('### Linting JS files');

  var LINT_FILES = ['make.js',
                    'external/crlfchecker/'
                    ];

  var jshintPath = path.normalize('./node_modules/.bin/jshint');
  if (!test('-f', jshintPath)) {
    echo('jshint is not installed -- installing...');
    exec('npm install jshint');
  }

  exit(exec('"' + jshintPath + '" --reporter test/reporter.js ' +
            LINT_FILES.join(' ')).code);

  crlfchecker.checkIfCrlfIsPresent(LINT_FILES);
};

target.server = function() {
  var file = new staticServer.Server();

  require('http').createServer(function (request, response) {
      request.addListener('end', function () {
          //
          // Serve files!
          //
          file.serve(request, response);
      });
  }).listen(8888);

  echo('### Running local server')
  echo('');
  echo('Running server at localhost:8888')
};

//
// make makefile
//
target.makefile = function() {
  var makefileContent = 'help:\n\tnode make\n\n';
  var targetsNames = [];
  for (var i in target) {
    makefileContent += i + ':\n\tnode make ' + i + '\n\n';
    targetsNames.push(i);
  }
  makefileContent += '.PHONY: ' + targetsNames.join(' ') + '\n';
  makefileContent.to('Makefile');
};
<|endoftext|>