<commit_before>//Gets developers personal config Information
var cas = require('byu-cas');
var db = require('./db');
var co = require ('co');
var uuid = require('node-uuid');
var redis = require('./redis');

check_id = co.wrap(function*(netid){
  var client = db();
  var is_user = yield client.query("SELECT CASE WHEN EXISTS (SELECT * FROM users WHERE netid = $1) THEN 'TRUE' ELSE 'FALSE' end;", [netid]);
  return yield Promise.resolve(is_user.rows[0].case == "TRUE");
});

check_admin = co.wrap(function*(user){
  var client = db();
  var is_user = yield client.query("SELECT CASE WHEN EXISTS (SELECT * FROM users WHERE netid = $1 AND admin = 't') THEN 'TRUE' ELSE 'FALSE' end;", [user]);
  console.warn("The function 'check_admin' is deprecated. Use 'isAdmin' instead.");
  return yield Promise.resolve(is_user.rows[0].case == "TRUE");
});

isAdmin = co.wrap(function*(user){
  var client = db();
  var is_user = yield client.query("SELECT CASE WHEN EXISTS (SELECT * FROM users WHERE netid = $1 AND admin = 't') THEN 'TRUE' ELSE 'FALSE' end;", [user]);
  return yield Promise.resolve(is_user.rows[0].case == "TRUE");
});

module.exports = {
  cas_login: function(ticket, service) {
    return cas.validate(ticket, service);
  },
  // tells us whether or not this host has access to CAS' attributes for BYU's
  // NetIDs. Checks if the port is 443 and the host is on BYU's domain.
  has_cas_access: function(host, port) {
    return (port == 443 && host.match(/\.byu\.edu$/) !== null);
  },

  login: function(ctx, obj) {
    var client = db();
    var redisClient = redis();
    var token = uuid.v4();
    ctx.session.user=obj.username;
    ctx.session.token=token;
    ctx.session.attributes=obj.attributes;

    /**
     * NB: cookie is set only for testing purposes.
     * Tokens should be taken either from session storage
     * (server side) or window.HLRDESK.token (client side).
     * Setting it here in the cookie is an easy way to extract
     * it when needing to test sockets server-side, because it
     * can be taken right from the cookie. Ideally, this line
     * wouldn't be necessary, and it may very well not be if
     * someone can get the tests to otherwise work.
     */
    ctx.cookies.set('token', token, {maxAge: 0});

    redisClient.sadd([token, obj.username]);
    redisClient.expire(token, 43200);
    client.query("INSERT INTO users(netid) VALUES ($1);", [obj.username] );
  },

  getUser: co.wrap(function* (token) {
    if(typeof token !== 'string') {
      return yield Promise.resolve(false);
    }
    return new Promise(function(resolve, reject) {
      redis().smembers(token, function(err, reply){
        if(err) {
          reject(err);
          return;
        }
        if(reply.length === 0) {
          resolve(false);
          return;
        }
        resolve(reply.toString());
      });
    });
  }),

  // retrieves a service for use when logging in through CAS
  service: function(host, port, endpoint, no_proxy) {
    if(!no_proxy && !this.has_cas_access(host, port)) {
      var redirect = (port === 443 ? 'https' : 'http') + '://' + host + ':' + port + endpoint;
      return "https://hlrdev.byu.edu/redirect/" + redirect;
    }
    // assume if not in development the host is an ssl-enabled .byu.edu domain
    // note that cas does not allow specified ports in service URLs, even if the port is 443
    return 'https://' + host + endpoint;
  },

  check_admin: check_admin,
  isAdmin: isAdmin,

  check_id: check_id,

  mkadmin: co.wrap(function*(user, netid) {
    var client = db();
    var is_user = yield check_id(netid);
    var user_is_admin = yield check_admin(user);
    if (is_user && user_is_admin){
      client.query("UPDATE users SET admin='TRUE' WHERE netid = $1", [netid]);
      return yield Promise.resolve(true);
    }
    else {
      return yield Promise.resolve(false);
    }
  })
};
<commit_msg>Emails are now added to the database! Not that if for whatever reason a person net_id already exists but a "new email" is associated with there net id it will update. I hope that this will preserver email-ability even if someone's email was changed. I guess the only true way to do that would be to querry byu's database for an email, but as that seems not to be an option this will work.<commit_after>//Gets developers personal config Information
var cas = require('byu-cas');
var db = require('./db');
var co = require ('co');
var uuid = require('node-uuid');
var redis = require('./redis');

check_id = co.wrap(function*(netid){
  var client = db();
  var is_user = yield client.query("SELECT CASE WHEN EXISTS (SELECT * FROM users WHERE netid = $1) THEN 'TRUE' ELSE 'FALSE' end;", [netid]);
  return yield Promise.resolve(is_user.rows[0].case == "TRUE");
});

check_admin = co.wrap(function*(user){
  var client = db();
  var is_user = yield client.query("SELECT CASE WHEN EXISTS (SELECT * FROM users WHERE netid = $1 AND admin = 't') THEN 'TRUE' ELSE 'FALSE' end;", [user]);
  console.warn("The function 'check_admin' is deprecated. Use 'isAdmin' instead.");
  return yield Promise.resolve(is_user.rows[0].case == "TRUE");
});

isAdmin = co.wrap(function*(user){
  var client = db();
  var is_user = yield client.query("SELECT CASE WHEN EXISTS (SELECT * FROM users WHERE netid = $1 AND admin = 't') THEN 'TRUE' ELSE 'FALSE' end;", [user]);
  return yield Promise.resolve(is_user.rows[0].case == "TRUE");
});

module.exports = {
  cas_login: function(ticket, service) {
    return cas.validate(ticket, service);
  },
  // tells us whether or not this host has access to CAS' attributes for BYU's
  // NetIDs. Checks if the port is 443 and the host is on BYU's domain.
  has_cas_access: function(host, port) {
    return (port == 443 && host.match(/\.byu\.edu$/) !== null);
  },

  login: co.wrap(function*(ctx, obj) {
    var client = db();
    var redisClient = redis();
    var token = uuid.v4();
    ctx.session.user=obj.username;
    ctx.session.token=token;
    ctx.session.attributes=obj.attributes;

    /**
     * NB: cookie is set only for testing purposes.
     * Tokens should be taken either from session storage
     * (server side) or window.HLRDESK.token (client side).
     * Setting it here in the cookie is an easy way to extract
     * it when needing to test sockets server-side, because it
     * can be taken right from the cookie. Ideally, this line
     * wouldn't be necessary, and it may very well not be if
     * someone can get the tests to otherwise work.
     */
    ctx.cookies.set('token', token, {maxAge: 0});

    redisClient.sadd([token, obj.username]);
    redisClient.expire(token, 43200);
    var is_user = yield check_id(obj.username);
    if (is_user){
      client.query("UPDATE users set email = $2 WHERE netid = $1;", [obj.username, obj.attributes.emailAddress]);
    }
    else{
      client.query("INSERT INTO users(netid, email) VALUES ($1, $2);", [obj.username, obj.attributes.emailAddress]);
    }
  }),

  getUser: co.wrap(function* (token) {
    if(typeof token !== 'string') {
      return yield Promise.resolve(false);
    }
    return new Promise(function(resolve, reject) {
      redis().smembers(token, function(err, reply){
        if(err) {
          reject(err);
          return;
        }
        if(reply.length === 0) {
          resolve(false);
          return;
        }
        resolve(reply.toString());
      });
    });
  }),

  // retrieves a service for use when logging in through CAS
  service: function(host, port, endpoint, no_proxy) {
    if(!no_proxy && !this.has_cas_access(host, port)) {
      var redirect = (port === 443 ? 'https' : 'http') + '://' + host + ':' + port + endpoint;
      return "https://hlrdev.byu.edu/redirect/" + redirect;
    }
    // assume if not in development the host is an ssl-enabled .byu.edu domain
    // note that cas does not allow specified ports in service URLs, even if the port is 443
    return 'https://' + host + endpoint;
  },

  check_admin: check_admin,
  isAdmin: isAdmin,

  check_id: check_id,

  mkadmin: co.wrap(function*(user, netid) {
    var client = db();
    var is_user = yield check_id(netid);
    var user_is_admin = yield check_admin(user);
    if (is_user && user_is_admin){
      client.query("UPDATE users SET admin='TRUE' WHERE netid = $1", [netid]);
      return yield Promise.resolve(true);
    }
    else {
      return yield Promise.resolve(false);
    }
  })
};
<|endoftext|>


<commit_before>var firstChecked = false;
var secondChecked = false;
var thirdChecked = false;

var firstAnswer = "sorsa";
var secondAnswer = "sorsa";
var thirdAnswer = "sorsa";

var words_raw = '{"words":[{"fi":"Lyödä, iskeä","eng1":"strike","eng2":"struck","eng3":"struck"},{"fi":"Lyödä, osua","eng1":"hit","eng2":"hit","eng3":"hit"},{"fi":"Lyödä Vetoa","eng1":"bet","eng2":"bet","eng3":"bet"},{"fi":"Lyödä, voittaa","eng1":"beat","eng2":"beat","eng3":"beaten"},{"fi":"Lähettää","eng1":"send","eng2":"sent","eng3":"sent"},{"fi":"Lähteä","eng1":"leave","eng2":"left","eng3":"left"},{"fi":"Löytää","eng1":"find","eng2":"found","eng3":"found"},{"fi":"Maata, olla","eng1":"lie","eng2":"lay","eng3":"lain"},{"fi":"Maksaa","eng1":"pay","eng2":"paid","eng3":"paid"},{"fi":"Maksaa, olla hintana","eng1":"cost","eng2":"cost","eng3":"cost"},{"fi":"Menettää","eng1":"lose","eng2":"lost","eng3":"lost"},{"fi":"Mennä","eng1":"go","eng2":"went","eng3":"gone"},{"fi":"Myydä","eng1":"sell","eng2":"sold","eng3":"sold"},{"fi":"Nousta","eng1":"rise","eng2":"rose","eng3":"risen"},{"fi":"Nukkua","eng1":"sleep","eng2":"slept","eng3":"slept"}]}'
var words;
var WordCount = 0;

//Word Checkers
	function CheckWord1() {
		var value = document.getElementById("1").value;
			if (value.toLowerCase() == firstAnswer.toLowerCase()) {
			$("#1").css('border-color', '#26A65B');
			firstChecked = true;
			document.getElementById("2").focus();
		} else if(value == "") {
			$("#1").css('border-color', '#1abc9c');
			firstChecked = false;
		}
		else{
			$("#1").css('border-color', '#c0392b');
			firstChecked = false;
		};
		CheckAnswers();
	}

	function CheckWord2() {
		var value = document.getElementById("2").value;
			if (value.toLowerCase() == secondAnswer.toLowerCase()) {
			$("#2").css('border-color', '#26A65B');
			secondChecked = true;
			document.getElementById("3").focus();
		} else if(value == "") {
			$("#2").css('border-color', '#1abc9c');
			secondChecked = false;
		}
		else{
			$("#2").css('border-color', '#c0392b');
			secondChecked = false;
		};
		CheckAnswers();
	}

	function CheckWord3() {
		var value = document.getElementById("3").value;
			if (value.toLowerCase() == thirdAnswer.toLowerCase()) {
			$("#3").css('border-color', '#26A65B');
			thirdChecked = true;
		} else if(value == "") {
			$("#3").css('border-color', '#1abc9c');
			thirdChecked = false;
		}
		else{
			$("#3").css('border-color', '#c0392b');
			thirdChecked = false;
		};
		CheckAnswers();
	}

//Retrieve a new word
function GetRandomInt() {
	num = Math.floor((Math.random() * words.words.length));
	WordCount++;
	return num;

}

//Self Explanatory
function CheckAnswers() {
	if (firstChecked == true && secondChecked == true && thirdChecked == true) {
		ProceedToNext()
	}
}

function ProceedToNext() {
	//Flash Background
	$("body").css('background-color', '#27ae60');

	//Clear Boxes
	document.getElementById("1").value = "";
	document.getElementById("2").value = "";
	document.getElementById("3").value = "";

	$("#1").css('border-color', '#1abc9c');
	$("#2").css('border-color', '#1abc9c');
	$("#3").css('border-color', '#1abc9c');

	//Reset Vars
	firstChecked = false;
	secondChecked = false;
	thirdChecked = false;

	if(WordCount != 14) {
		//Start Again
		onStart();
	}
	else
	{
		//redirect to winning site
		/*TODO: Make some fancy js thingy
		instead of loading a different site*/
		window.location.replace("win.html");
	}
}

function showAnswers() {
	var button = document.getElementById("btn");
	if (button.innerHTML == "Nyt en kyllä tiedä")
	{
		document.getElementById("1").value = firstAnswer;
		document.getElementById("2").value = secondAnswer;
		document.getElementById("3").value = thirdAnswer;

		button.innerHTML = "Seuraava Kysymys";

	}
	else
	{

		button.innerHTML = "Nyt en kyllä tiedä";
		ProceedToNext();
	}

}

//Gets ran on startup
function onStart() {
	document.getElementById("1").focus();
	var index = GetRandomInt();
	$("#fi-txt").text(words.words[index].fi)
	$("#counter").text(WordCount + "/15 Suoritettu")
	firstAnswer = words.words[index].eng1
	secondAnswer = words.words[index].eng2
	thirdAnswer = words.words[index].eng3
	console.log(words.words.splice(index, 1));
}

//Wait for site to load
jQuery(document).ready(function($) {
	words = JSON.parse(words_raw);
	onStart();
	WordCount--;
	$("#counter").text(WordCount + "/15 Suoritettu")
});<commit_msg>Made a new feature that checks and removes spaces<commit_after>var firstChecked = false;
var secondChecked = false;
var thirdChecked = false;

var firstAnswer = "sorsa";
var secondAnswer = "sorsa";
var thirdAnswer = "sorsa";

var words_raw = '{"words":[{"fi":"Lyödä, iskeä","eng1":"strike","eng2":"struck","eng3":"struck"},{"fi":"Lyödä, osua","eng1":"hit","eng2":"hit","eng3":"hit"},{"fi":"Lyödä Vetoa","eng1":"bet","eng2":"bet","eng3":"bet"},{"fi":"Lyödä, voittaa","eng1":"beat","eng2":"beat","eng3":"beaten"},{"fi":"Lähettää","eng1":"send","eng2":"sent","eng3":"sent"},{"fi":"Lähteä","eng1":"leave","eng2":"left","eng3":"left"},{"fi":"Löytää","eng1":"find","eng2":"found","eng3":"found"},{"fi":"Maata, olla","eng1":"lie","eng2":"lay","eng3":"lain"},{"fi":"Maksaa","eng1":"pay","eng2":"paid","eng3":"paid"},{"fi":"Maksaa, olla hintana","eng1":"cost","eng2":"cost","eng3":"cost"},{"fi":"Menettää","eng1":"lose","eng2":"lost","eng3":"lost"},{"fi":"Mennä","eng1":"go","eng2":"went","eng3":"gone"},{"fi":"Myydä","eng1":"sell","eng2":"sold","eng3":"sold"},{"fi":"Nousta","eng1":"rise","eng2":"rose","eng3":"risen"},{"fi":"Nukkua","eng1":"sleep","eng2":"slept","eng3":"slept"}]}'
var words;
var WordCount = 0;

//Word Checkers
	function CheckWord1() {
		checkSpaces('1');
		var value = document.getElementById("1").value;
			if (value.toLowerCase() == firstAnswer.toLowerCase()) {
			$("#1").css('border-color', '#26A65B');
			firstChecked = true;
			document.getElementById("2").focus();
		} else if(value == "") {
			$("#1").css('border-color', '#1abc9c');
			firstChecked = false;
		}
		else{
			$("#1").css('border-color', '#c0392b');
			firstChecked = false;
		};
		CheckAnswers();
	}

	function CheckWord2() {
		checkSpaces('2');
		var value = document.getElementById("2").value;
			if (value.toLowerCase() == secondAnswer.toLowerCase()) {
			$("#2").css('border-color', '#26A65B');
			secondChecked = true;
			document.getElementById("3").focus();
		} else if(value == "") {
			$("#2").css('border-color', '#1abc9c');
			secondChecked = false;
		}
		else{
			$("#2").css('border-color', '#c0392b');
			secondChecked = false;
		};
		CheckAnswers();
	}

	function CheckWord3() {
		checkSpaces('3');
		var value = document.getElementById("3").value;
			if (value.toLowerCase() == thirdAnswer.toLowerCase()) {
			$("#3").css('border-color', '#26A65B');
			thirdChecked = true;
		} else if(value == "") {
			$("#3").css('border-color', '#1abc9c');
			thirdChecked = false;
		}
		else{
			$("#3").css('border-color', '#c0392b');
			thirdChecked = false;
		};
		CheckAnswers();
	}

function checkSpaces(i) {
	value = document.getElementById(i).value;
	if(value[value.length-1] == ' ') {
		document.getElementById(i).value = value.slice(0, value.length-1)
	}
}

//Retrieve a new word
function GetRandomInt() {
	num = Math.floor((Math.random() * words.words.length));
	WordCount++;
	return num;

}

//Self Explanatory
function CheckAnswers() {
	if (firstChecked == true && secondChecked == true && thirdChecked == true) {
		ProceedToNext()
	}
}

function ProceedToNext() {
	//Flash Background
	$("body").css('background-color', '#27ae60');

	//Clear Boxes
	document.getElementById("1").value = "";
	document.getElementById("2").value = "";
	document.getElementById("3").value = "";

	$("#1").css('border-color', '#1abc9c');
	$("#2").css('border-color', '#1abc9c');
	$("#3").css('border-color', '#1abc9c');

	//Reset Vars
	firstChecked = false;
	secondChecked = false;
	thirdChecked = false;

	if(WordCount != 14) {
		//Start Again
		onStart();
	}
	else
	{
		//redirect to winning site
		/*TODO: Make some fancy js thingy
		instead of loading a different site*/
		window.location.replace("win.html");
	}
}

function showAnswers() {
	var button = document.getElementById("btn");
	if (button.innerHTML == "Nyt en kyllä tiedä")
	{
		document.getElementById("1").value = firstAnswer;
		document.getElementById("2").value = secondAnswer;
		document.getElementById("3").value = thirdAnswer;

		button.innerHTML = "Seuraava Kysymys";

	}
	else
	{

		button.innerHTML = "Nyt en kyllä tiedä";
		ProceedToNext();
	}

}

//Gets ran on startup
function onStart() {
	document.getElementById("1").focus();
	var index = GetRandomInt();
	$("#fi-txt").text(words.words[index].fi)
	$("#counter").text(WordCount + "/15 Suoritettu")
	firstAnswer = words.words[index].eng1
	secondAnswer = words.words[index].eng2
	thirdAnswer = words.words[index].eng3
	console.log(words.words.splice(index, 1));
}

//Wait for site to load
jQuery(document).ready(function($) {
	words = JSON.parse(words_raw);
	onStart();
	WordCount--;
	$("#counter").text(WordCount + "/15 Suoritettu")
});<|endoftext|>


<commit_before>function title(channel, tit){
   if(channel.indexOf("#") !== 0){
     return;
   }

   send("TITLE "+channel+": "+tit, function(respons){
      if(respons.command() == "ERROR"){
         getChannel(channel).error(language(respons.message()));
      }else{
         getChannel(channel).setTitle(respons.message());
      }
   });
}

function join(channel, error){
	if(channel.indexOf("#") !== 0){
	  error(language("A channel name should alweys start width #"));
	  return;
	}
	send("JOIN: "+channel.trim(), function(respons){
		if(respons.command() == "ERROR"){
			//ohh no some thinks dont works :(
			if(typeof error !== "undefined"){
				error(respons);
			}
		}else if(respons.command() == "JOIN"){
			appendChannel(respons.message());
		}else if(respons.command() == "TITLE"){
			getChannel(respons.channel()).setTitle(respons.message());
		}
	});
}

function leave(name, success, error){
	if(name.indexOf("#") == -1){
		return;
	}

	send("LEAVE: "+name, function(respons){
		if(respons.command() == "ERROR"){
			if(typeof error != "undefined"){
				error(respons);
			}
		}else{
			if(typeof success != "undefined"){
				success(respons);
			}
		}
	});
}

function online(channel, callback, error){
   if(channel.index("#") !== 0){
      return;
   }

   send("ONLINE: "+channel, function(respons){
       if(respons.command() == "ERROR" && typeof error !== "undefined"){
          error(respons.message());
       }else{
          callback(respons.message().split(","));//the message is nick,nick,nick
       }
   });
}

function message(channel, message){
	send("MESSAGE "+channel+": "+cleanMessage(message));
}

function cleanMessage(message){
	message = message.replace(/\n/g, "[br]");
	return message;
}
<commit_msg>Update command.js<commit_after>function userInfo(channel, nick, callback, error){
   send("INFO "+channel+": "+nick, function(respons){
      if(respons.command() == "ERROR" && typeof error !== "undefined"){
         error(respons.message());
      }else{
         //it a single string as key=vale;key=value
         var values = {};
         var part = respons.message().split(";");
         for(var i=0;i<part.length;i++){
            var value = part[i].split("=");
            values[value[0]]= value[1];
         }
         callback(values);
      }
   });
}

function title(channel, tit){
   if(channel.indexOf("#") !== 0){
     return;
   }

   send("TITLE "+channel+": "+tit, function(respons){
      if(respons.command() == "ERROR"){
         getChannel(channel).error(language(respons.message()));
      }else{
         getChannel(channel).setTitle(respons.message());
      }
   });
}

function join(channel, error){
	if(channel.indexOf("#") !== 0){
	  error(language("A channel name should alweys start width #"));
	  return;
	}
	send("JOIN: "+channel.trim(), function(respons){
		if(respons.command() == "ERROR"){
			//ohh no some thinks dont works :(
			if(typeof error !== "undefined"){
				error(respons);
			}
		}else if(respons.command() == "JOIN"){
			appendChannel(respons.message());
		}else if(respons.command() == "TITLE"){
			getChannel(respons.channel()).setTitle(respons.message());
		}
	});
}

function leave(name, success, error){
	if(name.indexOf("#") == -1){
		return;
	}

	send("LEAVE: "+name, function(respons){
		if(respons.command() == "ERROR"){
			if(typeof error != "undefined"){
				error(respons);
			}
		}else{
			if(typeof success != "undefined"){
				success(respons);
			}
		}
	});
}

function online(channel, callback, error){
   if(channel.index("#") !== 0){
      return;
   }

   send("ONLINE: "+channel, function(respons){
       if(respons.command() == "ERROR" && typeof error !== "undefined"){
          error(respons.message());
       }else{
          callback(respons.message().split(","));//the message is nick,nick,nick
       }
   });
}

function message(channel, message){
	send("MESSAGE "+channel+": "+cleanMessage(message));
}

function cleanMessage(message){
	message = message.replace(/\n/g, "[br]");
	return message;
}
<|endoftext|>


<commit_before>$(document).ready(function() {
	$('form').submit(function() {
		form = $(this)
		$.ajax({
			type: 'POST',
			url: $(this).attr('action'),
			data: $(this).serialize(),
			success: function(data)
			{
				if(data.success == 1)
				{
					form[0].reset();
					form.find('i, label').removeClass('active');
					form.find('input').blur();
				}
				toast(data.message, data.message.length * 150);
			}
		});
		return false;
	});
});<commit_msg>SEMI COLON<commit_after>$(document).ready(function() {
	$('form').submit(function() {
		form = $(this);
		$.ajax({
			type: 'POST',
			url: $(this).attr('action'),
			data: $(this).serialize(),
			success: function(data)
			{
				if(data.success == 1)
				{
					form[0].reset();
					form.find('i, label').removeClass('active');
					form.find('input').blur();
				}
				toast(data.message, data.message.length * 150);
			}
		});
		return false;
	});
});<|endoftext|>


<commit_before>$(function() {
	var imgURL = chrome.extension.getURL('img/appIcon.png');
	var el = $('<div />').css({
		position: 'fixed',
		right: 0,
		bottom: '50px',
		width: '60px',
		height: '60px',
		background: 'url('+imgURL+') no-repeat #fff',
		'background-size': '50px',
		'background-position': 'center',
		'z-index': 12000,
		'border-radius': '12px 0 0 12px',
		'box-shadow': '0 0 30px #888',
		cursor: 'pointer'
	});
	el.click(function() {
		chrome.runtime.sendMessage({command: "addBookmark", url: window.location.href});
	});
	$('body').append(el);
});

var showBookmarkMessage = function() {
	$.get(chrome.extension.getURL('notification.html'), function(d) {
		var el = $(d);
		$('body').append(el);
		setTimeout(function() {
			el.css({
				'visibility': 'visible',
				'transform': 'translate3d(0px, 0px, 0px)'
			});
		}, 100);
		setTimeout(function() {
			el.css({
				'transform': 'translate3d(0px, -100px, 0px)'
			});
		}, 4000);
		setTimeout(function() {
			el.fadeOut(function() {
				el.remove();
			});
		}, 5000);
	});
};<commit_msg>Have the icon transparent until the user hovers over it.<commit_after>$(function() {
	var imgURL = chrome.extension.getURL('img/appIcon.png');
	var el = $('<div />').css({
		position: 'fixed',
		right: 0,
		bottom: '50px',
		width: '60px',
		height: '60px',
		background: 'url('+imgURL+') no-repeat #fff',
		'background-size': '50px',
		'background-position': 'center',
		'z-index': 12000,
		'border-radius': '12px 0 0 12px',
		'box-shadow': '0 0 30px #888',
		cursor: 'pointer',
		opacity: '0.3'
	});
	el.click(function() {
		chrome.runtime.sendMessage({command: "addBookmark", url: window.location.href});
	});
	el.hover(function() {
		$(this).css('opacity', '1');
	}, function() {
		$(this).css('opacity', '0.3');
	});
	$('body').append(el);
});

var showBookmarkMessage = function() {
	$.get(chrome.extension.getURL('notification.html'), function(d) {
		var el = $(d);
		$('body').append(el);
		setTimeout(function() {
			el.css({
				'visibility': 'visible',
				'transform': 'translate3d(0px, 0px, 0px)'
			});
		}, 100);
		setTimeout(function() {
			el.css({
				'transform': 'translate3d(0px, -100px, 0px)'
			});
		}, 4000);
		setTimeout(function() {
			el.fadeOut(function() {
				el.remove();
			});
		}, 5000);
	});
};<|endoftext|>


<commit_before>
function removeChatWindow() {

	$('table:eq(3) td:eq(2) center:eq(0) *:lt(2)').remove();
	$('table:eq(3) td:eq(2) br').remove();
}

$(document).ready(function() {

	// FORUM.PHP
	if(window.location.href.match('forum.php')) {

		// Remove chat window
		if(dataStore['chat_hide']) {
			removeChatWindow();
		}

		if(dataStore['valami']) {
			// valami
		}
	}
});

var dataStore;
var port = chrome.extension.connect();

port.postMessage({ type : "getStorageData" });

port.onMessage.addListener(function(response) {

	if(response.type == 'setStorageData') {
		dataStore = response.data;
		extInit();
	}
});<commit_msg>fix chat hiding option<commit_after>
function removeChatWindow() {

	$('table:eq(3) td:eq(2) center:eq(0) *:lt(2)').remove();
	$('table:eq(3) td:eq(2) br').remove();
}

$(document).ready(function() {

	// FORUM.PHP
	if(window.location.href.match('forum.php')) {

		// Remove chat window
		if(dataStore['chat_hide'] == 'true') {
			removeChatWindow();
		}
	}
});

var dataStore;
var port = chrome.extension.connect();

port.postMessage({ type : "getStorageData" });

port.onMessage.addListener(function(response) {

	if(response.type == 'setStorageData') {
		dataStore = response.data;
		extInit();
	}
});<|endoftext|>


<commit_before>var fs = require('fs');
var glob = require('glob');
var linebyline = require('n-readlines');
var cmd = require('node-cmd');
var exec = require('child_process').exec;

function listFiles(path) {
    var filelist = [];
    var files =  glob.sync(path + '**').filter(isFile);

    for (var i = 0; i < files.length; i++) {
        if (getFilename(files[i]).split('.')[1] == 'elm') {
            if (hasView(files[i]) == true) {
                filelist.push(files[i].replace(path,''));
            }
        }
    }
    return filelist;
}

function generatePort(module_name) {
    var port_name = portName(module_name);
    return `
port ${port_name} : String
port ${port_name} =
    ${module_name}.view
        |> render`
}

function generateImport(module_name) {
    return `import ${module_name}`
}

function portName(module_name) {
    return module_name.replace('.','').toLowerCase();
}

function fileName(module_name, basedir, with_lower) {

    if (basedir === null) {
        basedir = './';
    }
    var with_basedir = basedir + module_name.replace('.','/');

    if (with_lower) {
        return with_basedir.toLowerCase();
    } return with_basedir;
}

function generateMapping(port, file) {
    return `echo "fs.writeFile('${file}.html', elm.ports['${port}']);" >> _main.js`
}

function generate_vdom(module_names, basedir) {

    var port_files = [];

    for (var i = 0; i < module_names.length; i++) {
        port_files.push({
            'port' : portName(module_names[i]),
            'filename' : fileName(module_names[i], basedir, false)
        });
    }

    var ports = module_names.map(generatePort).join('\n');
    var imports = module_names.map(generateImport).join('\n');
    var maps = [];

    var port_file_values = [];

    for (var i = port_files.length-1; i >= 0; i--) {

        var curr = port_files[i];

        maps.push(generateMapping(curr.port, curr.filename));

        port_file_values.push(curr.filename)

    }

    var mappings = maps.join('\n');

    makeFolders(port_file_values);

    var renderer_filename = '_Renderer.elm';
    var runner_filename = './runner.sh';

    var template = `
module Renderer where
import Html exposing (Html)
import Native.Renderer

${imports}

render : Html -> String
render = Native.Renderer.toHtml

${ports}`;

    fs.writeFile(renderer_filename, template);

    var executor = `
elm make ${renderer_filename} --output=_main.js
echo "var fs = require('fs');" >> _main.js
echo "var elm = Elm.worker(Elm.Renderer);" >> _main.js
${mappings}
node _main.js`;

    fs.writeFile(runner_filename, executor);

    // executeBash(runner_filename);

}

function makeFolders(filenames) {

    console.log(filenames);

    //for (var i = 0; i < filenames.length; i++) {
    filenames.forEach(function(filename) {
        if (filename.split('/').length > 1 || filename.startsWith('.') != -1) {
            var dir = filename.substring(0, filename.lastIndexOf('/'));
            try {
                fs.mkdir(dir);
            } catch (err) {
                console.log(err);
            }
    }
    });
}

function isFile(path) {
    return fs.lstatSync(path).isFile();
}

function getFilename(path) {
    var parts = path.split('/');
    return parts[parts.length - 1];
}

function hasView(filename) {
    var liner = new linebyline(filename);
    var line;

    while (line = liner.next()) {
        if (line.indexOf('view =') != -1) {
            return true;
        }
    }

    return false;

}

function cleanUp(name) {
    var new_name = name.replace(__dirname, '');
    return new_name.split('.')[0].replace('/','.');
}

function executeBash(filename) {
    fs.chmod(filename, 0755);
    exec(filename, (error, stdout, stderr) => {
        if (error !== null) {
            console.log(`exec error: ${error}`);
        }
    });
}

function main() {

    var files = listFiles('examples/').map(cleanUp);

    generate_vdom(files, 'output/');
}

main()
<commit_msg>refactored port_files loops<commit_after>var fs = require('fs');
var glob = require('glob');
var linebyline = require('n-readlines');
var cmd = require('node-cmd');
var exec = require('child_process').exec;

function listFiles(path) {
    var filelist = [];
    var files =  glob.sync(path + '**').filter(isFile);

    for (var i = 0; i < files.length; i++) {
        if (getFilename(files[i]).split('.')[1] == 'elm') {
            if (hasView(files[i]) == true) {
                filelist.push(files[i].replace(path,''));
            }
        }
    }
    console.log('for', filelist);

    var files = files.filter(function(file){
      return getFilename(file).split('.')[1] === 'elm';
    }).filter(hasView).map(function(file) {
        return file.replace(path,'');
    });

    // files.forEach(function(filename) {
    //     filename.replace(path, '');
    // })

    console.log('for2', files);
    return files
}

function generatePort(module_name) {
    var port_name = portName(module_name);
    return `
port ${port_name} : String
port ${port_name} =
    ${module_name}.view
        |> render`
}

function generateImport(module_name) {
    return `import ${module_name}`
}

function portName(module_name) {
    return module_name.replace('.','').toLowerCase();
}

function fileName(module_name, basedir, with_lower) {

    if (basedir === null) {
        basedir = './';
    }
    var with_basedir = basedir + module_name.replace('.','/');

    if (with_lower) {
        return with_basedir.toLowerCase();
    } return with_basedir;
}

function generateMapping(port, file) {
    return `echo "fs.writeFile('${file}.html', elm.ports['${port}']);" >> _main.js`
}

function generate_vdom(module_names, basedir) {

    var port_files = [];

    for (var i = module_names.length - 1; i >= 0; i--) {
        port_files.push({
            'port' : portName(module_names[i]),
            'filename' : fileName(module_names[i], basedir, false)
        });
    }

    var ports = module_names.map(generatePort).join('\n');
    var imports = module_names.map(generateImport).join('\n');
    // var maps = [];

     // var port_file_values = [];

    // for (var i = port_files.length-1; i >= 0; i--) {

    //     var curr = port_files[i];

    //     maps.push(generateMapping(curr.port, curr.filename));

    //      // port_file_values.push(curr.filename)

    // }

    var port_file_values = port_files.map(function(curr) {
        return curr.filename;
    })

    var maps = port_files.map(function(curr) {
        return generateMapping(curr.port, curr.filename);
    })

    var mappings = maps.join('\n');

    makeFolders(port_file_values);

    var renderer_filename = '_Renderer.elm';
    var runner_filename = './runner.sh';

    var template = `
module Renderer where
import Html exposing (Html)
import Native.Renderer

${imports}

render : Html -> String
render = Native.Renderer.toHtml

${ports}`;

    fs.writeFile(renderer_filename, template);

    var executor = `
elm make ${renderer_filename} --output=_main.js
echo "var fs = require('fs');" >> _main.js
echo "var elm = Elm.worker(Elm.Renderer);" >> _main.js
${mappings}
node _main.js`;

    fs.writeFile(runner_filename, executor);

    // executeBash(runner_filename);

}

function makeFolders(filenames) {

    //for (var i = 0; i < filenames.length; i++) {
    filenames.forEach(function(filename) {
        if (filename.split('/').length > 1 || filename.startsWith('.') != -1) {
            var dir = filename.substring(0, filename.lastIndexOf('/'));
            try {
                fs.mkdir(dir);
            } catch (err) {
                console.log(err);
            }
    }
    });
}

function isFile(path) {
    return fs.lstatSync(path).isFile();
}

function getFilename(path) {
    var parts = path.split('/');
    return parts[parts.length - 1];
}

function hasView(filename) {
    var liner = new linebyline(filename);
    var line;

    while (line = liner.next()) {
        if (line.indexOf('view =') != -1) {
            return true;
        }
    }

    return false;

}

function cleanUp(name) {
    var new_name = name.replace(__dirname, '');
    return new_name.split('.')[0].replace('/','.');
}

function executeBash(filename) {
    fs.chmod(filename, 0755);
    exec(filename, (error, stdout, stderr) => {
        if (error !== null) {
            console.log(`exec error: ${error}`);
        }
    });
}

function main() {
    var files = listFiles('examples/').map(cleanUp);

    generate_vdom(files, 'output/');
}

main()
<|endoftext|>


<commit_before>/**
 * OpenEyes
 *
 * (C) Moorfields Eye Hospital NHS Foundation Trust, 2008-2011
 * (C) OpenEyes Foundation, 2011-2013
 * This file is part of OpenEyes.
 * OpenEyes is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 * OpenEyes is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License along with OpenEyes in a file titled COPYING. If not, see <http://www.gnu.org/licenses/>.
 *
 * @package OpenEyes
 * @link http://www.openeyes.org.uk
 * @author OpenEyes <info@openeyes.org.uk>
 * @copyright Copyright (c) 2008-2011, Moorfields Eye Hospital NHS Foundation Trust
 * @copyright Copyright (c) 2011-2013, OpenEyes Foundation
 * @license http://www.gnu.org/licenses/gpl-3.0.html The GNU General Public License V3.0
 */

var OpenEyes = window.OpenEyes || {};
OpenEyes.Dialog = OpenEyes.Dialog || {};

(function() {

  // Set the jQuery UI Dialog default options.
  $.extend($.ui.dialog.prototype.options, {
    dialogClass: 'dialog',
    show: 'fade'
  });

  var EventEmitter = OpenEyes.Util.EventEmitter;

  /**
   * Dialog constructor.
   * @name Dialog
   * @constructor
   * @extends Emitter
   * @property {object} options    - The collection of dialog options, merged
   *  with the default options
   * @example
   * var dialog = new OpenEyes.Dialog({
   *   title: 'Title here',
   *   content: 'Here is some content.'
   * });
   * dialog.on('open', function() {
   *   console.log('The dialog is now open');
   * });
   * dialog.on('close', function() {
   *   console.log('The dialog is now closed.');
   * });
   * dialog.on('destroy', function() {
   *   console.log('The dialog has been destroyed.');
   * });
   * dialog.open();
   */
  function Dialog(options) {

    EventEmitter.call(this);

    this.options = $.extend(true, {}, Dialog.defaultOptions, options);

    this.create();
    this.bindEvents();

    if (this.options.url) {
      this.loadContent();
    }
  }

  Dialog.inherits(EventEmitter);

  /**
   * The default dialog options. Custom options will be merged with these.
   * @name Dialog#defaultOptions
   * @static
   */
  Dialog.defaultOptions = {
    content: '',
    destroyOnClose: true,
    url: null,
    data: null,
    id: null,
    autoOpen: false,
    title: '',
    modal: true,
    dialogClass: 'dialog',
    resizable: false,
    draggable: false,
    width: 400,
    height: 'auto',
    minHeight: 'auto',
    show: 'fade'
  };

  /**
   * Creates and stores the dialog container, and creates a new jQuery UI
   * instance on the container.
   * @name Dialog#create
   * @method
   * @private
   */
  Dialog.prototype.create = function() {

    // Create the dialog content div.
    this.content = $('
', { id: this.options.id });

    // Add default content (if any exists)
    this.setContent(this.options.content);

    // Create the jQuery UI dialog.
    this.content.dialog(this.options);

    // Store a reference to the jQuery UI dialog instance.
    this.instance = this.content.data('ui-dialog');
  };

  /**
   * Add content to the dialog.
   * @name Dialog#setContent
   * @method
   * @public
   */
  Dialog.prototype.setContent = function(content) {
    this.content.html(content);
  };

  /**
   * Binds common dialog event handlers.
   * @name Dialog#create
   * @method
   * @private
   */
  Dialog.prototype.bindEvents = function() {
    this.content.on({
      dialogclose: this.onDialogClose.bind(this),
      dialogopen: this.onDialogOpen.bind(this)
    });
  };

  /**
   * Gets a script template from the DOM, compiles it using Mustache, and
   * returns the HTML.
   * @name Dialog#compileTemplate
   * @method
   * @private
   * @param {object} options - An options object container the template selector and data.
   * @returns {string}
   */
  Dialog.prototype.compileTemplate = function(options) {

    var template = $(options.selector).html();

    if (!template) {
      throw new Error('Unable to compile dialog template. Template not found: ' + options.selector);
    }

    return Mustache.render(template, options.data || {});
  };

  /**
   * Sets a 'loading' message and retrieves the dialog content via AJAX.
   * @name Dialog#loadContent
   * @method
   * @private
   */
  Dialog.prototype.loadContent = function() {

    this.content.addClass('loading');
    this.setTitle('Loading...');

    var xhr = $.ajax({
      url: this.options.url,
      data: this.options.data
    });

    xhr.done(this.onContentLoadSuccess.bind(this));
    xhr.fail(this.onContentLoadFail.bind(this));
    xhr.always(this.onContentLoad.bind(this));
  };

  /**
   * Sets the dialog title.
   * @name Dialog#setTitle
   * @method
   * @public
   */
  Dialog.prototype.setTitle = function(title) {
    this.instance._setOption('title', title);
  };

  /**
   * Repositions the dialog in the center of the page.
   * @name Dialog#reposition
   * @method
   * @pubic
   */
  Dialog.prototype.reposition = function() {
    this.instance._position(this.instance._position());
  };

  /**
   * Opens (shows) the dialog.
   * @name Dialog#open
   * @method
   * @pubic
   */
  Dialog.prototype.open = function() {
    this.instance.open();
  };

  /**
   * Closes (hides) the dialog.
   * @name Dialog#close
   * @method
   * @pubic
   */
  Dialog.prototype.close = function() {
    this.instance.close();
  };

  /**
   * Destroys the dialog. Removes all elements from the DOM and detaches all
   * event handlers.
   * @name Dialog#destroy
   * @method
   * @fires Dialog#destroy
   * @pubic
   */
  Dialog.prototype.destroy = function() {
    this.instance.destroy();
    this.content.remove();

    /**
     * Destroy event.
     *
     * @event Dialog#destroy
     */
    this.emit('destroy');
  };

  /** Event handlers */

  /**
   * Emit the 'open' event after the dialog has opened.
   * @name Dialog#onDialogOpen
   * @method
   * @fires Dialog#open
   * @private
   */
  Dialog.prototype.onDialogOpen = function() {
    /**
     * Open event.
     * @event Dialog#open
     */
    this.emit('open');
  };

  /**
   * Emit the 'close' event after the dialog has closed, and optionally destroy
   * the dialog.
   * @name Dialog#onDialogClose
   * @method
   * @fires Dialog#close
   * @private
   */
  Dialog.prototype.onDialogClose = function() {
    /**
     * Close event.
     * @event Dialog#close
     */
    this.emit('close');
    if (this.options.destroyOnClose) {
      this.destroy();
    }
  };

  /**
   * Content load handler. This method is always executed after the content
   * request completes (whether there was an error or not), and is executed after
   * any success or fail handlers. This method removes the loading state of the
   * dialog, and repositions it in the center of the screen.
   * @name Dialog#onContentLoad
   * @method
   * @private
   */
  Dialog.prototype.onContentLoad = function() {
    // Remove loading state.
    this.content.removeClass('loading');
    // Reposition the dialog in the center of the screen.
    this.reposition();
  };

  /**
   * Content load success handler. Sets the dialog content to be the response of
   * the content request.
   * @name Dialog#onContentLoadSuccess
   * @method
   * @private
   */
  Dialog.prototype.onContentLoadSuccess = function(response) {
    // Set the dialog content.
    this.setTitle(this.options.title);
    this.setContent(response);
  };

  /**
   * Content load fail handler. This method is executed if the content request
   * fails, and shows an error message.
   * @name Dialog#onContentLoadFail
   * @method
   * @private
   */
  Dialog.prototype.onContentLoadFail = function() {
    // Show the error.
    this.setTitle('Error');
    this.setContent('Sorry, there was an error retrieving the content. Please try again.');
  };

  OpenEyes.Dialog = Dialog;

}());

(function() {

  var Dialog = OpenEyes.Dialog;

  /**
   * AlertDialog constructor. The AlertDialog extends the base Dialog and provides
   * an 'Ok' button for the user to click on.
   * @name AlertDialog
   * @constructor
   * @extends Dialog
   * @example
   * var alert = new OpenEyes.Dialog.Alert({
   *   content: 'Here is some content.'
   * });
   * alert.open();
   */
  function AlertDialog(options) {

    options = $.extend(true, options, AlertDialog.defaultOptions);
    options.content = this.getContent(options.content);

    Dialog.call(this, options);
  }

  AlertDialog.inherits(Dialog);

  /**
   * The default alert dialog options. These options will be merged into the
   * default dialog options.
   * @name AlertDialog#defaultOptions
   * @static
   */
  AlertDialog.defaultOptions = {
    modal: true,
    width: 400,
    minHeight: 'auto',
    title: 'Alert',
    dialogClass: 'dialog alert'
  };

  /**
   * Get the dialog content. Do some basic content formatting, then compile
   * and return the alert dialog template.
   * @name AlertDialog#getContent
   * @method
   * @private
   * @param {string} content - The main alert dialog content to display.
   * @returns {string}
   */
  AlertDialog.prototype.getContent = function(content) {

    // Replace new line characters with html breaks
    content = (content || '').replace(/\n/g, '
');

    // Compile the template, get the HTML
    return this.compileTemplate({
      selector: '#dialog-alert-template',
      data: {
        content: content
      }
    });
  };

  /**
   * Bind events
   * @name AlertDialog#bindEvents
   * @method
   * @private
   */
  AlertDialog.prototype.bindEvents = function() {
    Dialog.prototype.bindEvents.apply(this, arguments);
    this.content.on('click', '.ok', this.onButtonClick.bind(this));
  };

  /** Event handlers */

  /**
   * 'OK' button click handler. Simply close the dialog on click.
   * @name AlertDialog#onButtonClick
   * @method
   * @private
   */
  AlertDialog.prototype.onButtonClick = function() {
    this.close();
  };

  OpenEyes.Dialog.Alert = AlertDialog;
}());<commit_msg>Alert dialog: fixed passing in custom options<commit_after>/**
 * OpenEyes
 *
 * (C) Moorfields Eye Hospital NHS Foundation Trust, 2008-2011
 * (C) OpenEyes Foundation, 2011-2013
 * This file is part of OpenEyes.
 * OpenEyes is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 * OpenEyes is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License along with OpenEyes in a file titled COPYING. If not, see <http://www.gnu.org/licenses/>.
 *
 * @package OpenEyes
 * @link http://www.openeyes.org.uk
 * @author OpenEyes <info@openeyes.org.uk>
 * @copyright Copyright (c) 2008-2011, Moorfields Eye Hospital NHS Foundation Trust
 * @copyright Copyright (c) 2011-2013, OpenEyes Foundation
 * @license http://www.gnu.org/licenses/gpl-3.0.html The GNU General Public License V3.0
 */

var OpenEyes = window.OpenEyes || {};
OpenEyes.Dialog = OpenEyes.Dialog || {};

(function() {

  // Set the jQuery UI Dialog default options.
  $.extend($.ui.dialog.prototype.options, {
    dialogClass: 'dialog',
    show: 'fade'
  });

  var EventEmitter = OpenEyes.Util.EventEmitter;

  /**
   * Dialog constructor.
   * @name Dialog
   * @constructor
   * @extends Emitter
   * @property {object} options    - The collection of dialog options, merged
   *  with the default options
   * @example
   * var dialog = new OpenEyes.Dialog({
   *   title: 'Title here',
   *   content: 'Here is some content.'
   * });
   * dialog.on('open', function() {
   *   console.log('The dialog is now open');
   * });
   * dialog.on('close', function() {
   *   console.log('The dialog is now closed.');
   * });
   * dialog.on('destroy', function() {
   *   console.log('The dialog has been destroyed.');
   * });
   * dialog.open();
   */
  function Dialog(options) {

    EventEmitter.call(this);

    this.options = $.extend(true, {}, Dialog.defaultOptions, options);

    this.create();
    this.bindEvents();

    if (this.options.url) {
      this.loadContent();
    }
  }

  Dialog.inherits(EventEmitter);

  /**
   * The default dialog options. Custom options will be merged with these.
   * @name Dialog#defaultOptions
   * @static
   */
  Dialog.defaultOptions = {
    content: '',
    destroyOnClose: true,
    url: null,
    data: null,
    id: null,
    autoOpen: false,
    title: '',
    modal: true,
    dialogClass: 'dialog',
    resizable: false,
    draggable: false,
    width: 400,
    height: 'auto',
    minHeight: 'auto',
    show: 'fade'
  };

  /**
   * Creates and stores the dialog container, and creates a new jQuery UI
   * instance on the container.
   * @name Dialog#create
   * @method
   * @private
   */
  Dialog.prototype.create = function() {

    // Create the dialog content div.
    this.content = $('
', { id: this.options.id });

    // Add default content (if any exists)
    this.setContent(this.options.content);

    // Create the jQuery UI dialog.
    this.content.dialog(this.options);

    // Store a reference to the jQuery UI dialog instance.
    this.instance = this.content.data('ui-dialog');
  };

  /**
   * Add content to the dialog.
   * @name Dialog#setContent
   * @method
   * @public
   */
  Dialog.prototype.setContent = function(content) {
    this.content.html(content);
  };

  /**
   * Binds common dialog event handlers.
   * @name Dialog#create
   * @method
   * @private
   */
  Dialog.prototype.bindEvents = function() {
    this.content.on({
      dialogclose: this.onDialogClose.bind(this),
      dialogopen: this.onDialogOpen.bind(this)
    });
  };

  /**
   * Gets a script template from the DOM, compiles it using Mustache, and
   * returns the HTML.
   * @name Dialog#compileTemplate
   * @method
   * @private
   * @param {object} options - An options object container the template selector and data.
   * @returns {string}
   */
  Dialog.prototype.compileTemplate = function(options) {

    var template = $(options.selector).html();

    if (!template) {
      throw new Error('Unable to compile dialog template. Template not found: ' + options.selector);
    }

    return Mustache.render(template, options.data || {});
  };

  /**
   * Sets a 'loading' message and retrieves the dialog content via AJAX.
   * @name Dialog#loadContent
   * @method
   * @private
   */
  Dialog.prototype.loadContent = function() {

    this.content.addClass('loading');
    this.setTitle('Loading...');

    var xhr = $.ajax({
      url: this.options.url,
      data: this.options.data
    });

    xhr.done(this.onContentLoadSuccess.bind(this));
    xhr.fail(this.onContentLoadFail.bind(this));
    xhr.always(this.onContentLoad.bind(this));
  };

  /**
   * Sets the dialog title.
   * @name Dialog#setTitle
   * @method
   * @public
   */
  Dialog.prototype.setTitle = function(title) {
    this.instance._setOption('title', title);
  };

  /**
   * Repositions the dialog in the center of the page.
   * @name Dialog#reposition
   * @method
   * @pubic
   */
  Dialog.prototype.reposition = function() {
    this.instance._position(this.instance._position());
  };

  /**
   * Opens (shows) the dialog.
   * @name Dialog#open
   * @method
   * @pubic
   */
  Dialog.prototype.open = function() {
    this.instance.open();
  };

  /**
   * Closes (hides) the dialog.
   * @name Dialog#close
   * @method
   * @pubic
   */
  Dialog.prototype.close = function() {
    this.instance.close();
  };

  /**
   * Destroys the dialog. Removes all elements from the DOM and detaches all
   * event handlers.
   * @name Dialog#destroy
   * @method
   * @fires Dialog#destroy
   * @pubic
   */
  Dialog.prototype.destroy = function() {
    this.instance.destroy();
    this.content.remove();

    /**
     * Destroy event.
     *
     * @event Dialog#destroy
     */
    this.emit('destroy');
  };

  /** Event handlers */

  /**
   * Emit the 'open' event after the dialog has opened.
   * @name Dialog#onDialogOpen
   * @method
   * @fires Dialog#open
   * @private
   */
  Dialog.prototype.onDialogOpen = function() {
    /**
     * Open event.
     * @event Dialog#open
     */
    this.emit('open');
  };

  /**
   * Emit the 'close' event after the dialog has closed, and optionally destroy
   * the dialog.
   * @name Dialog#onDialogClose
   * @method
   * @fires Dialog#close
   * @private
   */
  Dialog.prototype.onDialogClose = function() {
    /**
     * Close event.
     * @event Dialog#close
     */
    this.emit('close');
    if (this.options.destroyOnClose) {
      this.destroy();
    }
  };

  /**
   * Content load handler. This method is always executed after the content
   * request completes (whether there was an error or not), and is executed after
   * any success or fail handlers. This method removes the loading state of the
   * dialog, and repositions it in the center of the screen.
   * @name Dialog#onContentLoad
   * @method
   * @private
   */
  Dialog.prototype.onContentLoad = function() {
    // Remove loading state.
    this.content.removeClass('loading');
    // Reposition the dialog in the center of the screen.
    this.reposition();
  };

  /**
   * Content load success handler. Sets the dialog content to be the response of
   * the content request.
   * @name Dialog#onContentLoadSuccess
   * @method
   * @private
   */
  Dialog.prototype.onContentLoadSuccess = function(response) {
    // Set the dialog content.
    this.setTitle(this.options.title);
    this.setContent(response);
  };

  /**
   * Content load fail handler. This method is executed if the content request
   * fails, and shows an error message.
   * @name Dialog#onContentLoadFail
   * @method
   * @private
   */
  Dialog.prototype.onContentLoadFail = function() {
    // Show the error.
    this.setTitle('Error');
    this.setContent('Sorry, there was an error retrieving the content. Please try again.');
  };

  OpenEyes.Dialog = Dialog;

}());

(function() {

  var Dialog = OpenEyes.Dialog;

  /**
   * AlertDialog constructor. The AlertDialog extends the base Dialog and provides
   * an 'Ok' button for the user to click on.
   * @name AlertDialog
   * @constructor
   * @extends Dialog
   * @example
   * var alert = new OpenEyes.Dialog.Alert({
   *   content: 'Here is some content.'
   * });
   * alert.open();
   */
  function AlertDialog(options) {

    options = $.extend(true, {}, AlertDialog.defaultOptions, options);
    options.content = this.getContent(options.content);

    Dialog.call(this, options);
  }

  AlertDialog.inherits(Dialog);

  /**
   * The default alert dialog options. These options will be merged into the
   * default dialog options.
   * @name AlertDialog#defaultOptions
   * @static
   */
  AlertDialog.defaultOptions = {
    modal: true,
    width: 400,
    minHeight: 'auto',
    title: 'Alert',
    dialogClass: 'dialog alert'
  };

  /**
   * Get the dialog content. Do some basic content formatting, then compile
   * and return the alert dialog template.
   * @name AlertDialog#getContent
   * @method
   * @private
   * @param {string} content - The main alert dialog content to display.
   * @returns {string}
   */
  AlertDialog.prototype.getContent = function(content) {

    // Replace new line characters with html breaks
    content = (content || '').replace(/\n/g, '
');

    // Compile the template, get the HTML
    return this.compileTemplate({
      selector: '#dialog-alert-template',
      data: {
        content: content
      }
    });
  };

  /**
   * Bind events
   * @name AlertDialog#bindEvents
   * @method
   * @private
   */
  AlertDialog.prototype.bindEvents = function() {
    Dialog.prototype.bindEvents.apply(this, arguments);
    this.content.on('click', '.ok', this.onButtonClick.bind(this));
  };

  /** Event handlers */

  /**
   * 'OK' button click handler. Simply close the dialog on click.
   * @name AlertDialog#onButtonClick
   * @method
   * @private
   */
  AlertDialog.prototype.onButtonClick = function() {
    this.close();
  };

  OpenEyes.Dialog.Alert = AlertDialog;
}());<|endoftext|>


<commit_before>import { $$ } from 'util/dom';
import settings from 'settings';
import preloader from 'util/loader';
import loadedImages from 'images';

var boardElement;
var boardDimensions;

var canvas = document.createElement('canvas');
export var ctx = canvas.getContext('2d');
var rows = settings.rows;
var cols = settings.cols;
// size changes based on screen size
var jewelSize;
// holds filename to get access to jewels sprite image from the loadedImages object
var jewelSpritesFilename;
// holds a copy of the board received from the board module
var jewels;
// the cursor position as sent from the game-screen module
var cursor;
// flag to only run setup once
var firstRun = true;

function createBackground () {
    var bg = document.createElement('canvas');
    var bgCtx = bg.getContext('2d');
    var x, y;

    bg.classList.add('board-bg');
    bg.width = boardDimensions.width;
    bg.height = boardDimensions.height;

    bgCtx.fillStyle = 'rgba(255,235,255,0.15)';

    for (x = 0; x < cols; ++x) {
        for (y = 0; y < cols; ++y) {
            if ((x+y) % 2) {
                bgCtx.fillRect(
                    x * jewelSize, y * jewelSize,
                    jewelSize, jewelSize
                );
            }
        }
    }

    return bg;
}

function clearJewel (x, y) {
    ctx.clearRect(x, y, 1, 1);
}

function drawJewel (type, x, y) {
    var image = loadedImages[jewelSpritesFilename];

    ctx.drawImage(image,
                  type * jewelSize, 0, jewelSize, jewelSize,
                  x, y, 1, 1
                 );
}

export function moveJewels (movedJewels, callback) {
    for (let mover of movedJewels) {
        clearJewel(mover.fromX, mover.fromY);
        drawJewel(mover.type, mover.toX, mover.toY);
    }

    callback();
}

export function removeJewels (removedJewels, callback) {
    for (let removed of removedJewels) {
        clearJewel(removed.x, removed.y);
    }

    callback();
}

export function refill (...args) {
    redraw(...args);
}

function clearCursor () {
    if (!cursor) {
        return;
    }

    var { x, y } = cursor;
    clearJewel(x, y);
    drawJewel(jewels[x][y], x, y);
}

function renderCursor () {
    if (!cursor) {
        return;
    }

    var { x, y } = cursor;
    var lineWidthPercent = 0.05;

    clearCursor();

    // draw the jewel lighter
    if (cursor.selected) {
        ctx.save();
        ctx.globalCompositeOperation = 'lighter';
        ctx.globalAlpha = 0.8;
        drawJewel(jewels[x][y], x, y);
        ctx.restore();
    }

    // draw the cursor
    ctx.save();
    ctx.lineWidth = lineWidthPercent;
    ctx.strokeStyle = 'rgba(250,250,150,0.8)';
    ctx.strokeRect(
        x + lineWidthPercent, y + lineWidthPercent,
        1 - 2 * lineWidthPercent, 1 - 2 * lineWidthPercent
    );
    ctx.restore();
}

export function setCursor ({ x, y, selected }) {
    clearCursor();

    if (arguments.length > 0) {
        cursor = { x, y, selected };
    } else {
        cursor = null;
    }

    renderCursor();
}

export function redraw (newJewels, callback) {
    var x, y;
    var { cols, rows } = settings;
    jewels = newJewels;

    preloader.one(jewelSpritesFilename, () => {
        ctx.clearRect(0, 0, cols, rows);

        for (x = 0; x < cols; ++x) {
            for (y = 0; y < rows; ++y) {
                drawJewel(jewels[x][y], x, y);
            }
        }

        renderCursor();
        callback();
    });
}

function setup () {
    boardElement = $$('#game-screen .game-board')[0];
    boardDimensions = boardElement.getBoundingClientRect();

    // jewel size changes based on screen size
    jewelSize = settings.jewelSize = boardDimensions.width / settings.cols;
    jewelSpritesFilename = 'images/jewels' + jewelSize + '.png';
    preloader.load(jewelSpritesFilename, loadedImages);

    canvas.classList.add('board');
    canvas.width = boardDimensions.width;
    canvas.height = boardDimensions.height;

    // scale canvas coordinates to the size of one jewel.
    // makes it easier to manipulate jewels in drawing and animations.
    ctx.scale(jewelSize, jewelSize);

    boardElement.appendChild(createBackground());
    boardElement.appendChild(canvas);
}

export function initialize (callback) {
    if (firstRun) {
        setup();
        firstRun = false;
    }

    callback();
}
<commit_msg>Normalize columns and rows variables in display.js<commit_after>import { $$ } from 'util/dom';
import settings from 'settings';
import preloader from 'util/loader';
import loadedImages from 'images';

var boardElement;
var boardDimensions;

var canvas = document.createElement('canvas');
export var ctx = canvas.getContext('2d');
var { cols, rows } = settings;
// size changes based on screen size
var jewelSize;
// holds filename to get access to jewels sprite image from the loadedImages object
var jewelSpritesFilename;
// holds a copy of the board received from the board module
var jewels;
// the cursor position as sent from the game-screen module
var cursor;
// flag to only run setup once
var firstRun = true;

function createBackground () {
    var bg = document.createElement('canvas');
    var bgCtx = bg.getContext('2d');
    var x, y;

    bg.classList.add('board-bg');
    bg.width = boardDimensions.width;
    bg.height = boardDimensions.height;

    bgCtx.fillStyle = 'rgba(255,235,255,0.15)';

    for (x = 0; x < cols; ++x) {
        for (y = 0; y < rows; ++y) {
            if ((x+y) % 2) {
                bgCtx.fillRect(
                    x * jewelSize, y * jewelSize,
                    jewelSize, jewelSize
                );
            }
        }
    }

    return bg;
}

function clearJewel (x, y) {
    ctx.clearRect(x, y, 1, 1);
}

function drawJewel (type, x, y) {
    var image = loadedImages[jewelSpritesFilename];

    ctx.drawImage(image,
                  type * jewelSize, 0, jewelSize, jewelSize,
                  x, y, 1, 1
                 );
}

export function moveJewels (movedJewels, callback) {
    for (let mover of movedJewels) {
        clearJewel(mover.fromX, mover.fromY);
        drawJewel(mover.type, mover.toX, mover.toY);
    }

    callback();
}

export function removeJewels (removedJewels, callback) {
    for (let removed of removedJewels) {
        clearJewel(removed.x, removed.y);
    }

    callback();
}

export function refill (...args) {
    redraw(...args);
}

function clearCursor () {
    if (!cursor) {
        return;
    }

    var { x, y } = cursor;
    clearJewel(x, y);
    drawJewel(jewels[x][y], x, y);
}

function renderCursor () {
    if (!cursor) {
        return;
    }

    var { x, y } = cursor;
    var lineWidthPercent = 0.05;

    clearCursor();

    // draw the jewel lighter
    if (cursor.selected) {
        ctx.save();
        ctx.globalCompositeOperation = 'lighter';
        ctx.globalAlpha = 0.8;
        drawJewel(jewels[x][y], x, y);
        ctx.restore();
    }

    // draw the cursor
    ctx.save();
    ctx.lineWidth = lineWidthPercent;
    ctx.strokeStyle = 'rgba(250,250,150,0.8)';
    ctx.strokeRect(
        x + lineWidthPercent, y + lineWidthPercent,
        1 - 2 * lineWidthPercent, 1 - 2 * lineWidthPercent
    );
    ctx.restore();
}

export function setCursor ({ x, y, selected }) {
    clearCursor();

    if (arguments.length > 0) {
        cursor = { x, y, selected };
    } else {
        cursor = null;
    }

    renderCursor();
}

export function redraw (newJewels, callback) {
    var x, y;
    jewels = newJewels;

    preloader.one(jewelSpritesFilename, () => {
        ctx.clearRect(0, 0, cols, rows);

        for (x = 0; x < cols; ++x) {
            for (y = 0; y < rows; ++y) {
                drawJewel(jewels[x][y], x, y);
            }
        }

        renderCursor();
        callback();
    });
}

function setup () {
    boardElement = $$('#game-screen .game-board')[0];
    boardDimensions = boardElement.getBoundingClientRect();

    // jewel size changes based on screen size
    jewelSize = settings.jewelSize = boardDimensions.width / settings.cols;
    jewelSpritesFilename = 'images/jewels' + jewelSize + '.png';
    preloader.load(jewelSpritesFilename, loadedImages);

    canvas.classList.add('board');
    canvas.width = boardDimensions.width;
    canvas.height = boardDimensions.height;

    // scale canvas coordinates to the size of one jewel.
    // makes it easier to manipulate jewels in drawing and animations.
    ctx.scale(jewelSize, jewelSize);

    boardElement.appendChild(createBackground());
    boardElement.appendChild(canvas);
}

export function initialize (callback) {
    if (firstRun) {
        setup();
        firstRun = false;
    }

    callback();
}
<|endoftext|>


<commit_before>/**
 * Clears the draw table
 * @param drawTable The draw table SVG DOM element
 */
function clearDrawTable(drawTable) {
    while (drawTable.firstChild) {
        drawTable.removeChild(drawTable.firstChild);
    }
}

/**
 * Draw a line to the draw table
 * @param drawTable The draw table SVG DOM element
 * @param x1 X coordinate of the start point
 * @param y1 Y coordinate of the start point
 * @param x2 X coordinate of the end point
 * @param y2 Y coordinate of the end point
 */
function drawLine(drawTable, x1, y1, x2, y2) {
    var path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
    path.setAttribute("d", "M " + x1 + " " + y1 + " l " + x2 + " " + y2);
    path.style.stroke = "#F00";
    path.style.strokeWidth = "1px";

    drawTable.appendChild(path);
}

/**
 * Koch-curve description
 *
 * syntax: [x,y,l,r]
 * Draw from (x,y) in r radian angle l lenght
 *
 * @type {*[]}
 */
var koch_spec = [ // (0px,0px); 1px, 0 rad) -> ??
// x              y    l  r
    [0, 0, 1 / 3, 0],
    [1 / 3, 0, 1 / 3, Math.PI / 3],
    [1 / 2, Math.sqrt(3) / 6, 1 / 3, -Math.PI / 3],
    [2 / 3, 0, 1 / 3, 0]
];

/**
 * Specify a fractal
 * TODO comment it right
 * @type {*[]}
 */
var fractalSpec = koch_spec;

// x,y,l,r a fenti negyes leirasaval egyezik
/**
 * Draw the fractal recursively to the draw table
 * TODO comment it right
 * @param drawTable The draw table SVG DOM element
 * @param d
 * @param x
 * @param y
 * @param l
 * @param r
 */
function draw(drawTable, d, x, y, l, r) {
    var c = Math.cos(r);
    var s = Math.sin(r);

    if (d === 0) {
        var x1 = x;
        var y1 = y;
        var x2 = c * l;
        var y2 = s * l;
        drawLine(drawTable, x1, y1, x2, y2);
        return;
    }

    for (var i = 0; i < fractalSpec.length; i++) {
        var sp = fractalSpec[i];
        var x2 = sp[0], y2 = sp[1], l2 = sp[2], r2 = sp[3];
        // (x;y) -> (x*c+y*s; -x*s+y*x)
        var x3 = l * (x2 * c - y2 * s) + x;
        var y3 = l * (y2 * c + x2 * s) + y;
        var l3 = l2 * l;
        var r3 = r2 + r;
        draw(drawTable, d - 1, x3, y3, l3, r3);
    }
}

/**
 * Drow the fractal to the draw table
 * @param drawTable The draw table SVG DOM element
 */
function drawFractal(drawTable) {
    drawTable = document.querySelector(selector);

    clearDrawTable(drawTable);
    // TODO connect this function with the GUI
    // 5 szintu gorbe (20;20) ponttol, 729 hosszu vonal helyett
    draw(drawTable, 5, 20, 20, 729, 0);
}

<commit_msg>bugfix<commit_after>/**
 * Clears the draw table
 * @param drawTable The draw table SVG DOM element
 */
function clearDrawTable(drawTable) {
    while (drawTable.firstChild) {
        drawTable.removeChild(drawTable.firstChild);
    }
}

/**
 * Draw a line to the draw table
 * @param drawTable The draw table SVG DOM element
 * @param x1 X coordinate of the start point
 * @param y1 Y coordinate of the start point
 * @param x2 X coordinate of the end point
 * @param y2 Y coordinate of the end point
 */
function drawLine(drawTable, x1, y1, x2, y2) {
    var path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
    path.setAttribute("d", "M " + x1 + " " + y1 + " l " + x2 + " " + y2);
    path.style.stroke = "#F00";
    path.style.strokeWidth = "1px";

    drawTable.appendChild(path);
}

/**
 * Koch-curve description
 *
 * syntax: [x,y,l,r]
 * Draw from (x,y) in r radian angle l lenght
 *
 * @type {*[]}
 */
var koch_spec = [ // (0px,0px); 1px, 0 rad) -> ??
// x              y    l  r
    [0, 0, 1 / 3, 0],
    [1 / 3, 0, 1 / 3, Math.PI / 3],
    [1 / 2, Math.sqrt(3) / 6, 1 / 3, -Math.PI / 3],
    [2 / 3, 0, 1 / 3, 0]
];

/**
 * Specify a fractal
 * TODO comment it right
 * @type {*[]}
 */
var fractalSpec = koch_spec;

// x,y,l,r a fenti negyes leirasaval egyezik
/**
 * Draw the fractal recursively to the draw table
 * TODO comment it right
 * @param drawTable The draw table SVG DOM element
 * @param d
 * @param x
 * @param y
 * @param l
 * @param r
 */
function draw(drawTable, d, x, y, l, r) {
    var c = Math.cos(r);
    var s = Math.sin(r);

    if (d === 0) {
        var x1 = x;
        var y1 = y;
        var x2 = c * l;
        var y2 = s * l;
        drawLine(drawTable, x1, y1, x2, y2);
        return;
    }

    for (var i = 0; i < fractalSpec.length; i++) {
        var sp = fractalSpec[i];
        var x2 = sp[0], y2 = sp[1], l2 = sp[2], r2 = sp[3];
        // (x;y) -> (x*c+y*s; -x*s+y*x)
        var x3 = l * (x2 * c - y2 * s) + x;
        var y3 = l * (y2 * c + x2 * s) + y;
        var l3 = l2 * l;
        var r3 = r2 + r;
        draw(drawTable, d - 1, x3, y3, l3, r3);
    }
}

/**
 * Drow the fractal to the draw table
 * @param selector The draw table SVG DOM element
 */
function drawFractal(selector) {
    drawTable = document.querySelector(selector);

    clearDrawTable(drawTable);
    // TODO connect this function with the GUI
    // 5 szintu gorbe (20;20) ponttol, 729 hosszu vonal helyett
    draw(drawTable, 5, 20, 20, 729, 0);
}

<|endoftext|>


<commit_before>// FIXME rk 2013-06-10
// we need the right order of libs to be loaded, this should eventually be
// supported by lively.Module>>requireLib
var allDependenciesLoaded = false;
var dependencies = [
    {url: Config.codeBase + 'lib/acorn/acorn.js', loadTest: function() { return typeof acorn !== 'undefined'; }},
    {url: Config.codeBase + 'lib/acorn/acorn-loose.js', loadTest: function() { return typeof acorn !== 'undefined' && typeof acorn.parse_dammit !== 'undefined'; }},
    {url: Config.codeBase + 'lib/acorn/acorn-walk.js', loadTest: function() { return typeof acorn !== 'undefined' && typeof acorn.walk !== 'undefined'; }}
];

dependencies.doAndContinue(function(next, lib) {
    JSLoader.loadJs(lib.url);
    var interval = Global.setInterval(function() {
        if (!lib.loadTest()) return;
        Global.clearInterval(interval);
        next();
    }, 50);
}, function() { allDependenciesLoaded = true; });

module("lively.ast.acorn").requires("lively.ide.SourceDatabase").requiresLib({loadTest: function() { return !!allDependenciesLoaded; }}).toRun(function() {

(function extendAcorn() {

    acorn.walk.all = function walkASTNode(astNode, iterator, state) {
        // walks the tree that's defined by astNode and its referenced objects.
        // will maintain depth and path information of the current astNode. this
        // walker will follow all properties of astNode and every value that has a
        // "type" property will be interpreted as ast node. Note that astNode my
        // refere to intermediate objects (such as arrays) that are not nodes but
        // contain nodes.
        // Example:
        // all = []; acorn.walk.all(acorn.parse("1+2"), function(node, state) {
        //     all.push(Strings.indent(
        //         node.type + ' ' + state.referencedAs.join('.'),
        //         ' ', state.depth));
        // }); all.join('\n');
        //   result:
        //     Program
        //      ExpressionStatement body.0
        //       BinaryExpression expression
        //       Literal left
        //       Literal right
        function makeScope(parentScope) {
            var scope = {id: Strings.newUUID(), parentScope: parentScope, containingScopes: []};
            parentScope && parentScope.containingScopes.push(scope);
            return scope;
        }
        if (!state) state = {depth: 0, path: [], referencedAs: [], scope: makeScope()};
        if (state.depth > 100) throw new Error('Endless recursion?');
        var isASTNode = !!astNode.type;
        if (isASTNode && astNode.type === 'FunctionExpression') state.scope = makeScope(state.scope);
        if (isASTNode) iterator(astNode, state);
        var excludedKeys = ['start', 'end', 'raw', 'source'];

        Object.getOwnPropertyNames(astNode).forEach(function(key) {
            if (excludedKeys.indexOf(key) !== -1) return;
            var val = astNode[key];
            if (val && typeof val === 'object') {
                walkASTNode(val, iterator, {
                    depth: isASTNode ? state.depth + 1 : state.depth,
                    scope: state.scope,
                    path: state.path.concat([Object.isNumber ? 'number:'+  key : key]),
                    parentNode: isASTNode ? astNode : state.parentNode,
                    referencedAs: isASTNode ? [key] : state.referencedAs.concat([key])
                });
            }
        });
    }

    acorn.walk.forEachNode = function(ast, func, state, options) {
        // note: func can get called with the same node for different
        // visitor callbacks!
        // func args: node, state, depth, type
        options = options || {};
        var traversal = options.traversal || 'preorder'; // also: postorder
        var visitors = options.visitors ? Object.extend({}, options.visitors) : acorn.walk.make({
            MemberExpression: function(node, st, c) {
                c(node.object, st, "Expression");
                c(node.property, st, "Expression");
            }
        });
        var iterator = traversal === 'preorder' ?
            function(orig, type, node, depth, cont) { func(node, state, depth, type); return orig(node, depth+1, cont); } :
            function(orig, type, node, depth, cont) { var result = orig(node, depth+1, cont); func(node, state, depth, type); return result; };
        Object.keys(visitors).forEach(function(type) {
            var orig = visitors[type];
            visitors[type] = function(node, depth, cont) { return iterator(orig, type, node, depth, cont); };
        });
        acorn.walk.recursive(ast, 0, null, visitors);
        return ast;
    }

    acorn.walk.matchNodes = function(ast, visitor, state, options) {
        function visit(node, state, depth, type) {
            if (visitor[node.type]) visitor[node.type](node, state, depth, type);
        }
        return acorn.walk.forEachNode(ast, visit, state, options);
    }

    acorn.walk.findNodesIncluding = function(ast, pos, test, base) {
        var nodes = [];
        base = base || acorn.walk.make({
            MemberExpression: function(node, st, c) {
                c(node.object, st, "Expression");
                c(node.property, st, "Expression");
            }
        });
        Object.keys(base).forEach(function(name) {
            var orig = base[name];
            base[name] = function(node, state, cont) {
                nodes.pushIfNotIncluded(node);
                return orig(node, state, cont);
            }
        });
        acorn.walk.findNodeAround(ast, pos, test, base);
        return nodes;
    }

    acorn.walk.addSource = function(ast, source) {
        source = Object.isString(ast) ? ast : source;
        ast = Object.isString(ast) ? acorn.parse(ast) : ast;
        return acorn.walk.forEachNode(ast, function(node) {
            node.source || (node.source = source.slice(node.start, node.end));
        });
    }

    acorn.walk.inspect = function(ast, source) {
        source = Object.isString(ast) ? ast : null;
        ast = Object.isString(ast) ? acorn.parse(ast) : ast;
        source && acorn.walk.addSource(ast, source);
        return Objects.inspect(ast);
    }

    acorn.walk.withParentInfo = function(ast, iterator, options) {
        // options = {visitAllNodes: BOOL}
        options = options || {};
        function makeScope(parentScope) {
            var scope = {id: Strings.newUUID(), parentScope: parentScope, containingScopes: []};
            parentScope && parentScope.containingScopes.push(scope);
            return scope;
        }
        var visitors = acorn.walk.make({
            Function: function(node, st, c) {
                if (st && st.scope) st.scope = makeScope(st.scope);
                c(node.body, st, "ScopeBody");
            },
            VariableDeclarator: function(node, st, c) {
                // node.id && c(node.id, st, 'Identifier');
                node.init && c(node.init, st, 'Expression');
            },
            VariableDeclaration: function(node, st, c) {
                for (var i = 0; i < node.declarations.length; ++i) {
                    var decl = node.declarations[i];
                    if (decl) c(decl, st, "VariableDeclarator");
                }
            },
            ObjectExpression: function(node, st, c) {
                for (var i = 0; i < node.properties.length; ++i) {
                    var prop = node.properties[i];
                    c(prop.key, st, "Expression");
                    c(prop.value, st, "Expression");
                }
            },
            MemberExpression: function(node, st, c) {
                c(node.object, st, "Expression");
                c(node.property, st, "Expression");
            }
        });
        var lastActiveProp, getters = [];
        acorn.walk.forEachNode(ast, function(node) {
            Object.keys(node).without('end', 'start', 'type', 'source', 'raw').forEach(function(propName) {
                if (node.__lookupGetter__(propName)) return; // already defined
                var val = node[propName];
                node.__defineGetter__(propName, function() { lastActiveProp = propName; return val; });
                getters.push([node, propName, node[propName]]);
            });
        }, null, {visitors: visitors});
        var result = [];
        Object.keys(visitors).forEach(function(type) {
            var orig = visitors[type];
            visitors[type] = function(node, state, cont) {
                if (type === node.type || options.visitAllNodes) {
                    result.push(iterator.call(null, node, {scope: state.scope, depth: state.depth, parent: state.parent, type: type, propertyInParent: lastActiveProp}));
                    return orig(node, {scope: state.scope, parent: node, depth: state.depth+1}, cont);
                } else {
                    return orig(node, state, cont);
                }
            }
        });
        acorn.walk.recursive(ast, {scope: makeScope(), parent: null, propertyInParent: '', depth: 0}, null, visitors);
        getters.forEach(function(nodeNameVal) {
            delete nodeNameVal[0][nodeNameVal[1]];
            nodeNameVal[0][nodeNameVal[1]] = nodeNameVal[2];
        });
        return result;
    }

    acorn.walk.print = function(ast, source) {
        // acorn.walk.print('12+3')
        source = Object.isString(ast) ? ast : source;
        ast = Object.isString(ast) ? acorn.parse(ast) : ast;
        var result = [];
        acorn.walk.all(ast, function(node, state) {
            var nodeSrc = source ? ',' + Strings.print(source.slice(node.start, node.end).replace(/\n|\r/g, '').truncate(20)) : '';
            var indent = Strings.indent('', '  ', state.depth);
            result.push(Strings.format('%s%s:%s<%s-%s%s>',
                                    indent, state.referencedAs.length ? state.referencedAs.join('.') : 'root',
                                    node.type, node.start, node.end, nodeSrc));
        });
        return result.join('\n');
    }
})();

lively.ide.ModuleWrapper.addMethods(
'acorn lib', {
    acornParse: function() {
        return acorn.parse(this.getSource());
    },

    acornGetSource: function(node) {
        return this.getSourceFragment(node.start, node.end);
    }
});

Object.extend(lively.ast.acorn, {

    parse: function(source) {
        return acorn.parse(source);
    },

    fuzzyParse: function(source, options) {
        // options: verbose, addSource, type
        options = options || {};
        var ast, safeSource, err;
        if (options.type === 'LabeledStatement') { safeSource = '$={' + source + '}'; }
        try {
            // we only parse to find errors
            ast = acorn.parse(safeSource || source);
            if (safeSource) ast = null; // we parsed only for finding errors
            else if (options.addSource) acorn.walk.addSource(ast, source);
        } catch (e) { err = e; }
        if (err && err.raisedAt !== undefined) {
            if (safeSource) { // fix error pos
                err.pos -= 3; err.raisedAt -= 3; err.loc.column -= 3; }
            var parseErrorSource = '';
            parseErrorSource += source.slice(err.raisedAt - 20, err.raisedAt);
            parseErrorSource += '<-error->';
            parseErrorSource += source.slice(err.raisedAt, err.raisedAt + 20);
            options.verbose && show('parse error: ' + parseErrorSource);
            err.parseErrorSource = parseErrorSource;
        } else if (err && options.verbose) {
            show('' + err + err.stack);
        }
        if (!ast) {
            ast = acorn.parse_dammit(source);
            if (options.addSource) acorn.walk.addSource(ast, source);
            ast.isFuzzy = true;
            ast.parseError = err;
        }
        return ast;
    },

    nodesAt: function(pos, ast) {
        ast = Object.isString(ast) ? this.parse(ast) : ast;
        return acorn.walk.findNodesIncluding(ast, pos);
    },

    nodeSource: function(source, node) {
        return source.slice(node.start, node.end);
    },

    transformReturnLastStatement: function(source) {
        // lively.ast.acorn.transformReturnLastStatement('foo + 3;\n this.baz(99 * 3) + 4;')
        // source = that.getTextRange()
        var ast = lively.ast.acorn.parse(source),
            last = ast.body.pop(),
            newLastsource = 'return ' + lively.ast.acorn.nodeSource(source, last),
            newLast = lively.ast.acorn.fuzzyParse(newLastsource).body.last(),
            newSource = source.slice(0, last.start) + 'return ' + source.slice(last.start)
        ast.body.push(newLast);
        ast.end += 'return '.length
        return lively.ast.acorn.nodeSource(newSource, ast);
    },
    simpleWalk: function(aNode, arg) {
        acorn.walk.simple(aNode, arg);
    }

});

}); // end of module
<commit_msg>get tokens from acorn<commit_after>// FIXME rk 2013-06-10
// we need the right order of libs to be loaded, this should eventually be
// supported by lively.Module>>requireLib
var allDependenciesLoaded = false;
var dependencies = [
    {url: Config.codeBase + 'lib/acorn/acorn.js', loadTest: function() { return typeof acorn !== 'undefined'; }},
    {url: Config.codeBase + 'lib/acorn/acorn-loose.js', loadTest: function() { return typeof acorn !== 'undefined' && typeof acorn.parse_dammit !== 'undefined'; }},
    {url: Config.codeBase + 'lib/acorn/acorn-walk.js', loadTest: function() { return typeof acorn !== 'undefined' && typeof acorn.walk !== 'undefined'; }}
];

dependencies.doAndContinue(function(next, lib) {
    JSLoader.loadJs(lib.url);
    var interval = Global.setInterval(function() {
        if (!lib.loadTest()) return;
        Global.clearInterval(interval);
        next();
    }, 50);
}, function() { allDependenciesLoaded = true; });

module("lively.ast.acorn").requires("lively.ide.SourceDatabase").requiresLib({loadTest: function() { return !!allDependenciesLoaded; }}).toRun(function() {

(function extendAcorn() {

    acorn.walk.all = function walkASTNode(astNode, iterator, state) {
        // walks the tree that's defined by astNode and its referenced objects.
        // will maintain depth and path information of the current astNode. this
        // walker will follow all properties of astNode and every value that has a
        // "type" property will be interpreted as ast node. Note that astNode my
        // refere to intermediate objects (such as arrays) that are not nodes but
        // contain nodes.
        // Example:
        // all = []; acorn.walk.all(acorn.parse("1+2"), function(node, state) {
        //     all.push(Strings.indent(
        //         node.type + ' ' + state.referencedAs.join('.'),
        //         ' ', state.depth));
        // }); all.join('\n');
        //   result:
        //     Program
        //      ExpressionStatement body.0
        //       BinaryExpression expression
        //       Literal left
        //       Literal right
        function makeScope(parentScope) {
            var scope = {id: Strings.newUUID(), parentScope: parentScope, containingScopes: []};
            parentScope && parentScope.containingScopes.push(scope);
            return scope;
        }
        if (!state) state = {depth: 0, path: [], referencedAs: [], scope: makeScope()};
        if (state.depth > 100) throw new Error('Endless recursion?');
        var isASTNode = !!astNode.type;
        if (isASTNode && astNode.type === 'FunctionExpression') state.scope = makeScope(state.scope);
        if (isASTNode) iterator(astNode, state);
        var excludedKeys = ['start', 'end', 'raw', 'source'];

        Object.getOwnPropertyNames(astNode).forEach(function(key) {
            if (excludedKeys.indexOf(key) !== -1) return;
            var val = astNode[key];
            if (val && typeof val === 'object') {
                walkASTNode(val, iterator, {
                    depth: isASTNode ? state.depth + 1 : state.depth,
                    scope: state.scope,
                    path: state.path.concat([Object.isNumber ? 'number:'+  key : key]),
                    parentNode: isASTNode ? astNode : state.parentNode,
                    referencedAs: isASTNode ? [key] : state.referencedAs.concat([key])
                });
            }
        });
    }

    acorn.walk.forEachNode = function(ast, func, state, options) {
        // note: func can get called with the same node for different
        // visitor callbacks!
        // func args: node, state, depth, type
        options = options || {};
        var traversal = options.traversal || 'preorder'; // also: postorder
        var visitors = options.visitors ? Object.extend({}, options.visitors) : acorn.walk.make({
            MemberExpression: function(node, st, c) {
                c(node.object, st, "Expression");
                c(node.property, st, "Expression");
            }
        });
        var iterator = traversal === 'preorder' ?
            function(orig, type, node, depth, cont) { func(node, state, depth, type); return orig(node, depth+1, cont); } :
            function(orig, type, node, depth, cont) { var result = orig(node, depth+1, cont); func(node, state, depth, type); return result; };
        Object.keys(visitors).forEach(function(type) {
            var orig = visitors[type];
            visitors[type] = function(node, depth, cont) { return iterator(orig, type, node, depth, cont); };
        });
        acorn.walk.recursive(ast, 0, null, visitors);
        return ast;
    }

    acorn.walk.matchNodes = function(ast, visitor, state, options) {
        function visit(node, state, depth, type) {
            if (visitor[node.type]) visitor[node.type](node, state, depth, type);
        }
        return acorn.walk.forEachNode(ast, visit, state, options);
    }

    acorn.walk.findNodesIncluding = function(ast, pos, test, base) {
        var nodes = [];
        base = base || acorn.walk.make({
            MemberExpression: function(node, st, c) {
                c(node.object, st, "Expression");
                c(node.property, st, "Expression");
            }
        });
        Object.keys(base).forEach(function(name) {
            var orig = base[name];
            base[name] = function(node, state, cont) {
                nodes.pushIfNotIncluded(node);
                return orig(node, state, cont);
            }
        });
        acorn.walk.findNodeAround(ast, pos, test, base);
        return nodes;
    }

    acorn.walk.addSource = function(ast, source) {
        source = Object.isString(ast) ? ast : source;
        ast = Object.isString(ast) ? acorn.parse(ast) : ast;
        return acorn.walk.forEachNode(ast, function(node) {
            node.source || (node.source = source.slice(node.start, node.end));
        });
    }

    acorn.walk.inspect = function(ast, source) {
        source = Object.isString(ast) ? ast : null;
        ast = Object.isString(ast) ? acorn.parse(ast) : ast;
        source && acorn.walk.addSource(ast, source);
        return Objects.inspect(ast);
    }

    acorn.walk.withParentInfo = function(ast, iterator, options) {
        // options = {visitAllNodes: BOOL}
        options = options || {};
        function makeScope(parentScope) {
            var scope = {id: Strings.newUUID(), parentScope: parentScope, containingScopes: []};
            parentScope && parentScope.containingScopes.push(scope);
            return scope;
        }
        var visitors = acorn.walk.make({
            Function: function(node, st, c) {
                if (st && st.scope) st.scope = makeScope(st.scope);
                c(node.body, st, "ScopeBody");
            },
            VariableDeclarator: function(node, st, c) {
                // node.id && c(node.id, st, 'Identifier');
                node.init && c(node.init, st, 'Expression');
            },
            VariableDeclaration: function(node, st, c) {
                for (var i = 0; i < node.declarations.length; ++i) {
                    var decl = node.declarations[i];
                    if (decl) c(decl, st, "VariableDeclarator");
                }
            },
            ObjectExpression: function(node, st, c) {
                for (var i = 0; i < node.properties.length; ++i) {
                    var prop = node.properties[i];
                    c(prop.key, st, "Expression");
                    c(prop.value, st, "Expression");
                }
            },
            MemberExpression: function(node, st, c) {
                c(node.object, st, "Expression");
                c(node.property, st, "Expression");
            }
        });
        var lastActiveProp, getters = [];
        acorn.walk.forEachNode(ast, function(node) {
            Object.keys(node).without('end', 'start', 'type', 'source', 'raw').forEach(function(propName) {
                if (node.__lookupGetter__(propName)) return; // already defined
                var val = node[propName];
                node.__defineGetter__(propName, function() { lastActiveProp = propName; return val; });
                getters.push([node, propName, node[propName]]);
            });
        }, null, {visitors: visitors});
        var result = [];
        Object.keys(visitors).forEach(function(type) {
            var orig = visitors[type];
            visitors[type] = function(node, state, cont) {
                if (type === node.type || options.visitAllNodes) {
                    result.push(iterator.call(null, node, {scope: state.scope, depth: state.depth, parent: state.parent, type: type, propertyInParent: lastActiveProp}));
                    return orig(node, {scope: state.scope, parent: node, depth: state.depth+1}, cont);
                } else {
                    return orig(node, state, cont);
                }
            }
        });
        acorn.walk.recursive(ast, {scope: makeScope(), parent: null, propertyInParent: '', depth: 0}, null, visitors);
        getters.forEach(function(nodeNameVal) {
            delete nodeNameVal[0][nodeNameVal[1]];
            nodeNameVal[0][nodeNameVal[1]] = nodeNameVal[2];
        });
        return result;
    }

    acorn.walk.print = function(ast, source) {
        // acorn.walk.print('12+3')
        source = Object.isString(ast) ? ast : source;
        ast = Object.isString(ast) ? acorn.parse(ast) : ast;
        var result = [];
        acorn.walk.all(ast, function(node, state) {
            var nodeSrc = source ? ',' + Strings.print(source.slice(node.start, node.end).replace(/\n|\r/g, '').truncate(20)) : '';
            var indent = Strings.indent('', '  ', state.depth);
            result.push(Strings.format('%s%s:%s<%s-%s%s>',
                                    indent, state.referencedAs.length ? state.referencedAs.join('.') : 'root',
                                    node.type, node.start, node.end, nodeSrc));
        });
        return result.join('\n');
    }
})();

lively.ide.ModuleWrapper.addMethods(
'acorn lib', {
    acornParse: function() {
        return acorn.parse(this.getSource());
    },

    acornGetSource: function(node) {
        return this.getSourceFragment(node.start, node.end);
    }
});

Object.extend(lively.ast.acorn, {

    parse: function(source) {
        return acorn.parse(source);
    },
    tokenize: function(input) {
        return acorn.tokenize(input);
    },

    fuzzyParse: function(source, options) {
        // options: verbose, addSource, type
        options = options || {};
        var ast, safeSource, err;
        if (options.type === 'LabeledStatement') { safeSource = '$={' + source + '}'; }
        try {
            // we only parse to find errors
            ast = acorn.parse(safeSource || source);
            if (safeSource) ast = null; // we parsed only for finding errors
            else if (options.addSource) acorn.walk.addSource(ast, source);
        } catch (e) { err = e; }
        if (err && err.raisedAt !== undefined) {
            if (safeSource) { // fix error pos
                err.pos -= 3; err.raisedAt -= 3; err.loc.column -= 3; }
            var parseErrorSource = '';
            parseErrorSource += source.slice(err.raisedAt - 20, err.raisedAt);
            parseErrorSource += '<-error->';
            parseErrorSource += source.slice(err.raisedAt, err.raisedAt + 20);
            options.verbose && show('parse error: ' + parseErrorSource);
            err.parseErrorSource = parseErrorSource;
        } else if (err && options.verbose) {
            show('' + err + err.stack);
        }
        if (!ast) {
            ast = acorn.parse_dammit(source);
            if (options.addSource) acorn.walk.addSource(ast, source);
            ast.isFuzzy = true;
            ast.parseError = err;
        }
        return ast;
    },

    nodesAt: function(pos, ast) {
        ast = Object.isString(ast) ? this.parse(ast) : ast;
        return acorn.walk.findNodesIncluding(ast, pos);
    },

    nodeSource: function(source, node) {
        return source.slice(node.start, node.end);
    },

    transformReturnLastStatement: function(source) {
        // lively.ast.acorn.transformReturnLastStatement('foo + 3;\n this.baz(99 * 3) + 4;')
        // source = that.getTextRange()
        var ast = lively.ast.acorn.parse(source),
            last = ast.body.pop(),
            newLastsource = 'return ' + lively.ast.acorn.nodeSource(source, last),
            newLast = lively.ast.acorn.fuzzyParse(newLastsource).body.last(),
            newSource = source.slice(0, last.start) + 'return ' + source.slice(last.start)
        ast.body.push(newLast);
        ast.end += 'return '.length
        return lively.ast.acorn.nodeSource(newSource, ast);
    },
    tokens: function(input) {
        //this returns an array of all tokens, including recreating the skipped ones (comments and whitespace)
        var next = acorn.tokenize(input, {onComment: function(bool, text, start, end){
            tokens.push({value: text, start: start, end: end, type: "comment"});
        }});
        var tokens = [];
        var token = next();
        var previousEnd = token.end;
        var whitespace, prevValue, prevType, prevIndex;
        var _eof = acorn.tokTypes.eof;
        var _slash = acorn.tokTypes.slash;
        var _name = acorn.tokTypes.name;
        var _bracketR = acorn.tokTypes.bracketR;
        while(token.type !== _eof) {
            prevType = token.type;
            prevValue = token.value || prevType.type.valueOf();
            prevIndex = tokens.length;
            tokens.push({value: prevValue, start: token.start, end: token.end, type: prevType.type});
            token = next();
            if(token.start > previousEnd) {
                whitespace = input.substring(previousEnd, token.start);
                tokens.push({value: whitespace, start: previousEnd, end: token.start, type: "whitespace"});
            }
            if (token.type.type == "assign" && token.value == "/=" && prevType !== _name && prevType !== _bracketR) {
                debugger;
                token = next(true);
            }
            else if(token.type === _slash && prevValue === ")") {
                var count = 1;
                for(var i = prevIndex - 1; i > 0; i--) {
                    var value = tokens[i].value;
                    if(value == ")")
                        count++;
                    else if(value == "(")
                        count--;
                    if(count == 0)
                        break;
                }
                if(i > 0 && ["if", "while", "for", "with"].indexOf(tokens[i - 1].value.valueOf()) > -1 ) {
                    debugger;
                    token = next(true);
                }
            }
            previousEnd = token.end;
        }
        return tokens;
    },

    simpleWalk: function(aNode, arg) {
        acorn.walk.simple(aNode, arg);
    }

});

}); // end of module
<|endoftext|>


<commit_before>obtain(['./src/utils.js', 'child_process'], ({ copyConfigFile, call: Call }, { exec })=> {

  var mainDir = __dirname.substring(0, __dirname.indexOf('piFig/src'));
  var startup = 'sudo startx ' + mainDir + 'node_modules/electron/dist/electron ' + mainDir;

  console.log(startup);

  exports.remove = ()=> {
    var command = 'sed -i".bak" "/node_modules\/.bin\/electron/d" /home/pi/.bashrc > /home/pi/.bashrc';
    if (__dirname.indexOf('/home/pi') >= 0) exec(command);
    else console.error('System not a pi, preventing uninstall');
  };

  exports.configure = ()=> {
    exports.remove();
    var command = 'echo "' + startup + '" >> /home/pi/.bashrc';
    if (__dirname.indexOf('/home/pi') >= 0) exec(command);
    else console.error('System not a pi, preventing install');
  };
});
<commit_msg>moved pifig to template<commit_after>obtain(['./src/utils.js', 'child_process'], ({ copyConfigFile, call: Call }, { execSync })=> {

  var mainDir = __dirname.substring(0, __dirname.indexOf('piFig/src'));
  var startup = 'sudo startx ' + mainDir + 'node_modules/electron/dist/electron ' + mainDir;

  console.log(startup);

  exports.remove = ()=> {
    var command = 'sed -i".bak" "/node_modules\/.bin\/electron/d" /home/pi/.bashrc > /home/pi/.bashrc';
    if (__dirname.indexOf('/home/pi') >= 0) execSync(command);
    else console.error('System not a pi, preventing uninstall');
  };

  exports.configure = ()=> {
    exports.remove();
    var command = 'echo "' + startup + '" >> /home/pi/.bashrc';
    if (__dirname.indexOf('/home/pi') >= 0) execSync(command);
    else console.error('System not a pi, preventing install');
  };
});
<|endoftext|>