text:
package net.canadensys.dataportal.occurrence;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

/**
 * Ensure Occurrence page can be rendered correctly
 * @author canadensys
 *
 */
public class OccurrencePageFunctionalTest extends AbstractFunctionalTest {
	//the footer div presence ensure the page was all rendered by Freemarker
	@FindBy(css = "div#footer")
	private WebElement footerDiv;

	@Test
	public void testOccurrencePage() {
		browser.get(TESTING_SERVER_URL+"resources/acad-specimens/occurrences/ACAD-1");

		//bind the WebElement to the current page
		PageFactory.initElements(browser, this);

		WebElement h1 = browser.findElement(By.cssSelector("h1"));
		assertEquals("Acer pseudoplatanus", h1.getText());

		//make sure data coming from the extension are included
		WebElement imageDiv =  browser.findElement(By.cssSelector("div#occpage_image"));
		WebElement attributionElement = imageDiv.findElement(By.cssSelector("div.attribution a"));
		assertEquals("http://creativecommons.org/licenses/by/4.0/", attributionElement.getAttribute("href"));

		//make sure footer is there
		assertEquals("div",footerDiv.getTagName().toLowerCase());
	}

	@Test
	public void testOccurrencePageWithSpaceChar() {
		browser.get(TESTING_SERVER_URL+"resources/acad-specimens/occurrences/ACAD%203");

		//bind the WebElement to the current page
		PageFactory.initElements(browser, this);

		WebElement h1 = browser.findElement(By.cssSelector("h1"));
		assertEquals("Myosotis arvensis", h1.getText());
		//make sure footer is there
		assertEquals("div",footerDiv.getTagName().toLowerCase());
	}

	@Test
	public void testOccurrencePageDwcView() {
		browser.get(TESTING_SERVER_URL+"resources/acad-specimens/occurrences/ACAD-1?view=dwc");

		//bind the WebElement to the current page
		PageFactory.initElements(browser, this);

		WebElement h1 = browser.findElement(By.cssSelector("h1"));
		assertEquals("Acer pseudoplatanus", h1.getText());
		//make sure footer is there
		assertEquals("div",footerDiv.getTagName().toLowerCase());
	}
}


text:
var ADMIN_LIST_ADMINS = 	(1<<0);

var ADMIN_ADD_ADMINS = 		(1<<1);

var ADMIN_EDIT_ADMINS = 	(1<<2);
var ADMIN_DELETE_ADMINS = 	(1<<3);

var ADMIN_LIST_SERVERS = 	(1<<4);
var ADMIN_ADD_SERVER = 		(1<<5);
var ADMIN_EDIT_SERVERS = 	(1<<6);
var ADMIN_DELETE_SERVERS = 	(1<<7);

var ADMIN_ADD_BAN = 		(1<<8);
var ADMIN_EDIT_OWN_BANS = 	(1<<10);
var ADMIN_EDIT_GROUP_BANS = (1<<11);
var ADMIN_EDIT_ALL_BANS = 	(1<<12);
var ADMIN_BAN_PROTESTS = 	(1<<13);
var ADMIN_BAN_SUBMISSIONS = (1<<14);
var ADMIN_DELETE_BAN = 		(1<<25);
var ADMIN_UNBAN = 			(1<<26);
var ADMIN_BAN_IMPORT =		(1<<27);
var ADMIN_UNBAN_OWN_BANS =	(1<<30);
var ADMIN_UNBAN_GROUP_BANS =(1<<31);

var ADMIN_NOTIFY_SUB =		(1<<28);
var ADMIN_NOTIFY_PROTEST =	(1<<29);

var ADMIN_LIST_GROUPS = 	(1<<15);
var ADMIN_ADD_GROUP = 		(1<<16);
var ADMIN_EDIT_GROUPS = 	(1<<17);
var ADMIN_DELETE_GROUPS = 	(1<<18);

var ADMIN_WEB_SETTINGS = 	(1<<19);

var ADMIN_LIST_MODS = 		(1<<20);
var ADMIN_ADD_MODS = 		(1<<21);
var ADMIN_EDIT_MODS = 		(1<<22);
var ADMIN_DELETE_MODS = 	(1<<23);

var ADMIN_OWNER = 			(1<<24);

var accordion;

function ProcessAdminTabs()
{
	var url = window.location.toString();
	var pos = url.indexOf('^')+1;
	var tabNo = url.charAt(pos);
	SwapPane(tabNo);

	var upos = url.indexOf('~')+1;
	var utabNo = url.charAt(upos+1);
	var utabType = url.charAt(upos)
	Swap2ndPane(utabNo, utabType);

	if(parseInt(pos) == 0)
	{
		return -1;
	}
	else
	{
		return tabNo;
	}
}

function Swap2ndPane(id, ttype)
{
	var i = 0;
	var i2 = 0;
	if(document.getElementById("utab-" + ttype + id))
	{
		while($(document.getElementById(ttype + i)))
		{
			$(document.getElementById(ttype + i)).setStyle('display', 'none');
			i++;
		}
		while(i2 < 50)
		{
			if($("utab-" + ttype + i2))
			{
				$("utab-" + ttype + i2).removeClass('active');
				$("utab-" + ttype + i2).addClass('nonactive');
			}
			i2++;
		}
		$(document.getElementById("utab-" + ttype + id)).addClass('active');
		$(document.getElementById(ttype + id)).setStyle('display', 'block');
	}
}

function SwapPane(id)
{
	var i = 0;
	var i2 = 0;
	if(document.getElementById("tab-" + id))
	{
		while($(document.getElementById(i)))
		{
			$(document.getElementById(i)).setStyle('display', 'none');
			i++;
		}
		while(i2 < 50)
		{
			if($("tab-" + i2))
			{
				$("tab-" + i2).removeClass('active');
			}
			i2++;
		}
		$(document.getElementById("tab-" + id)).addClass('active');
		$(document.getElementById(id)).setStyle('display', 'block');
	}
}

function InitAccordion(opener, element, container, num)
{
	// IE6 got no window.addEventListener
	if (window.addEventListener) {
		window.addEventListener("load", function () {
				InitAccordion(opener, element, container, num);
		}, false);
	} else {
		window.attachEvent('onload', function () {
				InitAccordion(opener, element, container, num);
		});
	}

	if(num == null)
		num = -1;
	var ExtendedAccordion = Accordion.extend({
	showAll: function() {
		var obj = {};
		 this.previous = -1;
		this.elements.each(function(el, i){
			obj[i] = {};
			this.fireEvent('onActive', [this.togglers[i], el]);
			for (var fx in this.effects) obj[i][fx] = el[this.effects[fx]];
		}, this);
		return this.start(obj);
	},
	hideAll: function() {
		var obj = {};
		 this.previous = -1;
		this.elements.each(function(el, i){
			obj[i] = {};
			this.fireEvent('onBackground', [this.togglers[i], el]);
			for (var fx in this.effects) obj[i][fx] = 0;
		}, this);
		return this.start(obj);
	}
  });

	accordion = new ExtendedAccordion(opener, element, {
		opacity: true,
		alwaysHide: true,
		display: num,
		transition:Fx.Transitions.Quart.easeOut,
		onActive: function(toggler, element){
			toggler.setStyle('cursor', 'pointer');
			toggler.setStyle('background-color', '');
		},

		onBackground: function(toggler, element){
			toggler.setStyle('cursor', 'pointer');
			toggler.setStyle('background-color', '');
		}
	}, $(container));
	accordion.hideAll();
}

function ScrollRcon()
{
	var objDiv = document.getElementById("rcon");
	objDiv.scrollTop = objDiv.scrollHeight;
	//alert(objDiv.scrollTop);
}

function Shrink(id, time, height)
{
	var myEffects = $(document.getElementById(id)).effects({duration: time, transition:Fx.Transitions.Bounce.easeOut});
	myEffects.start({'height': [height]});
}

function FadeElOut(id, time)
{
	var myEffects = $(id).effects({duration: time, transition:Fx.Transitions.Sine.easeOut});
	myEffects.start({'opacity': [0]});
	var d = id;
	setTimeout("$(document.getElementById('" + d + "')).setStyle('display', 'none');$(document.getElementById('" + d + "')).setOpacity(0);", time);

	return;
}
function FadeElIn(id, time)
{
	$(document.getElementById(id)).setStyle('display', 'block');
	var myEffects = $(id).effects({duration: time, transition:Fx.Transitions.Sine.easeIn});
	myEffects.start({'opacity': [1]});
	setTimeout("$(document.getElementById('" + id + "')).setOpacity(1);", time);
	return;
}
function FXShow(id)
{
	$(document.getElementById(id)).setStyle('display', 'block');
}
function FXHide(id)
{
	$(document.getElementById(id)).setStyle('display', 'none');
}
function DoLogin(redir)
{
	var err = 0;
	var nopw = 0;
	if(!$('loginUsername').value)
	{
		$('loginUsername.msg').setHTML('You must enter your loginname!');
		$('loginUsername.msg').setStyle('display', 'block');
		err++;
	}else
	{
		$('loginUsername.msg').setHTML('');
		$('loginUsername.msg').setStyle('display', 'none');
	}

	if(!$('loginPassword').value)
	{
		$('loginPassword.msg').setHTML('You must enter your password!');
		$('loginPassword.msg').setStyle('display', 'block');
		nopw = 1;
	}else
	{
		$('loginPassword.msg').setHTML('');
		$('loginPassword.msg').setStyle('display', 'none');
	}

	if(err)
		return 0;

	if(redir == "undefined")
		redir = "";
	xajax_Plogin(document.getElementById('loginUsername').value,
				document.getElementById('loginPassword').value,
				 document.getElementById('loginRememberMe').checked,
				 redir,
				 nopw);
}

function SlideUp(id)
{
	var slider = new Fx.Slide(id);
	slider.slideOut().chain(
						function(){
							$(id).remove();
						}
		);
}

function RemoveGroup(id, name, type)
{
	var noPerm = confirm("Are you sure you want to delete the group: '" + name +"'?");
	if(noPerm == false)
	{
		return;
	}
	xajax_RemoveGroup(id, type);
}

function RemoveAdmin(id, name)
{
	var noPerm = confirm("Are you sure you want to delete '" + name +"'?");
	if(noPerm == false)
	{
		return;
	}
	xajax_RemoveAdmin(id);
}

function RemoveSubmission(id, name, archiv)
{
	if(archiv == '2') {
		var noPerm = confirm("Are you sure you want to restore the ban submission for '" + name + "' from the archive?");
	}
	else if(archiv == '1') {
		var noPerm = confirm("Are you sure you want to move the ban submission for '" + name +"' to the archive?");
	}
	else {
		var noPerm = confirm("Are you sure you want to delete the ban submission for '" + name +"'?");
	}
	if(noPerm == false)
		return;

	xajax_RemoveSubmission(id, archiv);
}

function RemoveProtest(id, name, archiv)
{
	if(archiv == '2') {
		var noPerm = confirm("Are you sure you want to restore the ban protest for '" + name + "' from the archive?");
	}
	else if(archiv == '1') {
		var noPerm = confirm("Are you sure you want to move the ban protest for '" + name +"' to the archive?");
	}
	else {
		var noPerm = confirm("Are you sure you want to delete the ban protest for '" + name +"'?");
	}
	if(noPerm == false)
	{
		return;
	}
	xajax_RemoveProtest(id, archiv);
}

function RemoveServer(id, name)
{
	var noPerm = confirm("Are you sure you want to delete the server: '" + name +"'?");
	if(noPerm == false)
	{
		return;
	}
	xajax_RemoveServer(id);
}

function RemoveBan(id, key, page, name, confirm, bulk)
{
	if(confirm==0) {
		ShowBox('Delete Ban', 'Are you sure you want to delete the ban'+(bulk=="true"?"s":"")+' for '+(bulk=="true"?"those players":"\'"+ name +"\'")+'?', 'blue', '', true);
		$('dialog-control').setHTML('<input type="button" onclick="RemoveBan(\''+id+'\', \''+key+'\', \''+page+'\', \''+addslashes(name.replace(/\'/g,'\\\''))+'\', \'1\''+(bulk=="true"?", \'true\'":"")+');" name="rban" class="btn ok" onmouseover="ButtonOver(\'rban\')" onmouseout="ButtonOver(\'rban\')" id="rban" value="Remove Ban" /> <input type="button" onclick="closeMsg(\'\');$(\'bulk_action\').options[0].selected=true;" name="astop" class="btn cancel" onmouseover="ButtonOver(\'astop\')" onmouseout="ButtonOver(\'astop\')" id="astop" value="Cancel" />');
	} else if(confirm==1) {
		if(page != "")
			var pagelink = page;
		else
			var pagelink = "";
		window.location = "index.php?p=banlist" + pagelink + "&a=delete&id="+ id +"&key="+ key +(bulk=="true"?"&bulk=true":"");
	}
}

function UnbanBan(id, key, page, name, popup, bulk)
{
	if(popup==1) {
		ShowBox('Unban Reason', 'Please give a short comment, why you are going to unban '+(bulk=="true"?"those players":"\'"+ name +"\'")+'!
<textarea rows="3" cols="40" name="ureason" id="ureason" style="overflow:auto;"></textarea>

', 'blue', '', true);
		$('dialog-control').setHTML('<input type="button" onclick="UnbanBan(\''+id+'\', \''+key+'\', \''+page+'\', \''+addslashes(name.replace(/\'/g,'\\\''))+'\', \'0\''+(bulk=="true"?", \'true\'":"")+');" name="uban" class="btn ok" onmouseover="ButtonOver(\'uban\')" onmouseout="ButtonOver(\'uban\')" id="uban" value="Unban Ban" /> <input type="button" onclick="closeMsg(\'\');$(\'bulk_action\').options[0].selected=true;" name="astop" class="btn cancel" onmouseover="ButtonOver(\'astop\')" onmouseout="ButtonOver(\'astop\')" id="astop" value="Cancel" />');
	} else if(popup==0) {
		if(page != "")
			var pagelink = page;
		else
			var pagelink = "";
		reason = $('ureason').value;
		if(reason == "") {
			$('ureason.msg').setHTML("Please leave a comment.");
			$('ureason.msg').setStyle('display', 'block');
			return;
		} else {
			$('ureason.msg').setHTML('');
			$('ureason.msg').setStyle('display', 'none');
		}
		window.location = "index.php?p=banlist" + pagelink + "&a=unban&id="+ id +"&key="+ key +"&ureason="+ reason +(bulk=="true"?"&bulk=true":"");
	}
}

function BoxToSrvMask()
{
	var string = "";
	if(document.getElementById('s1'))
	{
		if(document.getElementById('s1').checked)
			string += "a";
		if(document.getElementById('s23').checked)
			string +=  "b";
		if(document.getElementById('s2').checked)
			string += "c";
		if(document.getElementById('s3').checked)
			string += "d";
		if(document.getElementById('s4').checked)
			string += "e";
		if(document.getElementById('s5').checked)
			string += "f";
		if(document.getElementById('s6').checked)
			string += "g";
		if(document.getElementById('s7').checked)
			string += "h";
		if(document.getElementById('s8').checked)
			string += "i";
		if(document.getElementById('s9').checked)
			string += "j";
		if(document.getElementById('s10').checked)
			string += "k";
		if(document.getElementById('s11').checked)
			string += "l";
		if(document.getElementById('s12').checked)
			string += "m";
		if(document.getElementById('s13').checked)
			string += "n";
		if(document.getElementById('s17').checked)
			string += "o";
		if(document.getElementById('s18').checked)
			string += "p";
		if(document.getElementById('s19').checked)
			string += "q";
		if(document.getElementById('s20').checked)
			string += "r";
		if(document.getElementById('s21').checked)
			string += "s";
		if(document.getElementById('s22').checked)
			string += "t";
		if(document.getElementById('s14').checked)
			string += "z";
		if(document.getElementById('immunity').value)
			string += "#" + $('immunity').value;
	}
	return string;
}

function BoxToMask()
{
	var Mask = 0;
	if(document.getElementById('p4'))
	{
		if(document.getElementById('p4').checked)
			Mask |= ADMIN_LIST_ADMINS;
		if(document.getElementById('p5').checked)
			Mask |= ADMIN_ADD_ADMINS;
		if(document.getElementById('p6').checked)
			Mask |= ADMIN_EDIT_ADMINS;
		if(document.getElementById('p7').checked)
			Mask |= ADMIN_DELETE_ADMINS;

		if(document.getElementById('p9').checked)
			Mask |= ADMIN_LIST_SERVERS;
		if(document.getElementById('p10').checked)
			Mask |= ADMIN_ADD_SERVER;
		if(document.getElementById('p11').checked)
			Mask |= ADMIN_EDIT_SERVERS;
		if(document.getElementById('p12').checked)
			Mask |= ADMIN_DELETE_SERVERS;

		if(document.getElementById('p14').checked)
			Mask |= ADMIN_ADD_BAN;
		if(document.getElementById('p16').checked)
			Mask |= ADMIN_EDIT_OWN_BANS;
		if(document.getElementById('p17').checked)
			Mask |= ADMIN_EDIT_GROUP_BANS;
		if(document.getElementById('p18').checked)
			Mask |= ADMIN_EDIT_ALL_BANS;
		if(document.getElementById('p19').checked)
			Mask |= ADMIN_BAN_PROTESTS;
		if(document.getElementById('p20').checked)
			Mask |= ADMIN_BAN_SUBMISSIONS;
		if(document.getElementById('p38').checked)
			Mask |= ADMIN_UNBAN_OWN_BANS;
		if(document.getElementById('p39').checked)
			Mask |= ADMIN_UNBAN_GROUP_BANS;
		if(document.getElementById('p32').checked)
			Mask |= ADMIN_UNBAN;
		if(document.getElementById('p33').checked)
			Mask |= ADMIN_DELETE_BAN;
		if(document.getElementById('p34').checked)
			Mask |= ADMIN_BAN_IMPORT;

		if(document.getElementById('p36').checked)
			Mask |= ADMIN_NOTIFY_SUB;
		if(document.getElementById('p37').checked)
			Mask |= ADMIN_NOTIFY_PROTEST;

		if(document.getElementById('p22').checked)
			Mask |= ADMIN_LIST_GROUPS;
		if(document.getElementById('p23').checked)
			Mask |= ADMIN_ADD_GROUP;
		if(document.getElementById('p24').checked)
			Mask |= ADMIN_EDIT_GROUPS;
		if(document.getElementById('p25').checked)
			Mask |= ADMIN_DELETE_GROUPS;

		if(document.getElementById('p26').checked)
			Mask |= ADMIN_WEB_SETTINGS;

		if(document.getElementById('p28').checked)
			Mask |= ADMIN_LIST_MODS;
		if(document.getElementById('p29').checked)
			Mask |= ADMIN_ADD_MODS;
		if(document.getElementById('p30').checked)
			Mask |= ADMIN_EDIT_MODS;
		if(document.getElementById('p31').checked)
			Mask |= ADMIN_DELETE_MODS;

		if(document.getElementById('p2').checked)
			Mask |= ADMIN_OWNER;
	}
	return Mask;
}

function UpdateCheckBox(tgl, start, stop)
{
	for(var i=start;i<=stop;i++)
	{
		if($('p' + i))
		{
			if($('p' + tgl).checked == true)
				$('p' + i).checked = true;
			else
				$('p' + i).checked = false;
		}
	}

	// Other Arguments is individual items not available in the range
	if (arguments.length > 3)
	{
		for(var lp = 4; lp <= arguments.length; lp++)
		{
			if ($('p' + arguments[lp - 1]))
			{
				$('p' + arguments[lp - 1]).checked = $('p' + tgl).checked;
			}
		}
	}
}

function ProcessGroup()
{
	var Mask = BoxToMask();
	var Smask = BoxToSrvMask();
	xajax_AddGroup(document.getElementById('groupname').value, document.getElementById('grouptype').value, Mask, Smask);
}

function update_web()
{
	$('webperm').setHTML('');

	if(document.getElementById('webg').value == "c" || document.getElementById('webg').value == "n") {
		$('web.msg').setHTML('Please Wait...');
		$('web.msg').setStyle('display', 'block');
	}

	if(document.getElementById('webg').value == "c")
		var height = 390;
	else if(document.getElementById('webg').value == "n")
		var height = 410;
	else
	{
		$('webperm').setHTML('');
		var height = 1;
	}
	Shrink('webperm', 1000, height);

	if(document.getElementById('webg').value == "c" || document.getElementById('webg').value == "n")
		setTimeout("xajax_UpdateAdminPermissions(1, document.getElementById('webg').value)",1000);
	else {
		$('web.msg').setHTML('');
		$('web.msg').setStyle('display', 'none');
	}
}

function update_server_groups()
{
	$('nsgroup').setHTML('');

	if(document.getElementById('serverg').value == "n")
	{
		$('group.msg').setHTML('Please Wait...');
		$('group.msg').setStyle('display', 'block');
		var height = 50;
		Shrink('nsgroup', 500, height);
		setTimeout("xajax_AddServerGroupName()",500);
	}
	else
	{
		height = 5;
		Shrink('nsgroup', 500, height);
		$('group.msg').setHTML('');
		$('group.msg').setStyle('display', 'none');
	}
}

function ProcessAddAdmin()
{
	var Mask = BoxToMask();
	var srvMask = BoxToSrvMask();
	var server_a_pass = "-1";

	var el = document.getElementsByName('group[]');
	var grp = "";
  	for(i=0;i<el.length;i++){
    	if(el[i].checked){
       		grp = grp + "," + el[i].value;
    	}
  	}

  	var el = document.getElementsByName('servers[]');
	var svr = "";
  	for(i=0;i<el.length;i++){
    	if(el[i].checked){
       		svr = svr + "," + el[i].value;
    	}
  	}

    var serverg = document.getElementById('serverg').value;
  	if(serverg == "-3")
  	{
  		//serverg = "c";
  		srvMask = "";
  	}
    var webg = document.getElementById('webg').value;
  	if(webg == "-3")
  	{
  		//webg = "c";
  		Mask = 0;
  	}

  	if(document.getElementById('a_useserverpass').checked)
  		server_a_pass = document.getElementById('a_serverpass').value;

	if(document.getElementById('webname') && !document.getElementById('servername'))
	xajax_AddAdmin(Mask,srvMask, document.getElementById('adminname').value, //Admin name
					document.getElementById('steam').value, //Admin Steam
					document.getElementById('email').value, // Email
					document.getElementById('password').value,//passwrds
					document.getElementById('password2').value,
					serverg, //servergroup
					webg,
					server_a_pass,
					document.getElementById('webname').value,
					0,
					grp,
					svr); //server / server group
	else if(!document.getElementById('webname') && document.getElementById('servername'))
	xajax_AddAdmin(Mask,srvMask, document.getElementById('adminname').value, //Admin name
					document.getElementById('steam').value, //Admin Steam
					document.getElementById('email').value, // Email
					document.getElementById('password').value,//passwrds
					document.getElementById('password2').value,
					serverg, //servergroup
					webg,
					server_a_pass,
					0,
					document.getElementById('servername').value,
					grp,
					svr);
	else if(document.getElementById('webname') && document.getElementById('servername'))
	xajax_AddAdmin(Mask,srvMask, document.getElementById('adminname').value, //Admin name
					document.getElementById('steam').value, //Admin Steam
					document.getElementById('email').value, // Email
					document.getElementById('password').value,//passwrds
					document.getElementById('password2').value,
					serverg, //servergroup
					webg,
					server_a_pass,
					document.getElementById('webname').value,
					document.getElementById('servername').value,
					grp,
					svr);
	else
	xajax_AddAdmin(Mask,srvMask, document.getElementById('adminname').value, //Admin name
					document.getElementById('steam').value, //Admin Steam
					document.getElementById('email').value, // Email
					document.getElementById('password').value,//passwrds
					document.getElementById('password2').value,
					serverg, //servergroup
					webg,
					server_a_pass,
					0,
					0,
					grp,
					svr);

}

function ProcessEditAdminPermissions()
{
	var Mask = BoxToMask();
	var srvMask = BoxToSrvMask();
	var aid = $('admin_id').value;

	if($('immunity'))
	{
	 	if(IsNumeric($('immunity').value))
			xajax_EditAdminPerms(aid, Mask, srvMask);
		else
			ShowBox("Error", "Immunity must be a numerical value (0-9)", "red", "", true);
	}else
		xajax_EditAdminPerms(aid, Mask, srvMask);
}

function ProcessEditGroup(type, name)
{

	var Mask = BoxToMask();
	var srvMask = BoxToSrvMask();
	var group = $('group_id').value;

	if(name == "")
	{
		ShowBox("Error", "You have to type a name for the group.", "red", "", true);
		$('groupname.msg').innerHTML = 'You have to type a name for the group.';
		$('groupname.msg').setStyle('display', 'block');
		return;
	}
	else
	{
		$('groupname.msg').innerHTML = '';
		$('groupname.msg').setStyle('display', 'none');
	}

	if($('immunity') && !IsNumeric($('immunity').value))
	{
		ShowBox("Error", "Immunity must be a numerical value (0-9)", "red", "", true);
		return;
	}

	var overrides = [];
	var new_override = {};

	// Handle group overrides
	if(type == "srv")
	{
		var override_id = document.group_overrides_form.elements["override_id[]"];
		// Are there any old overrides to change?
		if(override_id != null)
		{
			var override_type = document.group_overrides_form.elements["override_type[]"];
			var override_name = document.group_overrides_form.elements["override_name[]"];
			var override_access = document.group_overrides_form.elements["override_access[]"];

			// Make sure they're arrays!
			if($type(override_id) == "element")
				override_id = [override_id];
			if($type(override_type) == "element")
				override_type = [override_type];
			if($type(override_name) == "element")
				override_name = [override_name];
			if($type(override_access) == "element")
				override_access = [override_access];

			overrides = new Array(override_id.length);

			for(var i=0;i<override_id.length;i++)
			{
				overrides[i] = {'id': override_id[i].value, 'type': override_type[i][override_type[i].selectedIndex].value, 'name': override_name[i].value, 'access': override_access[i][override_access[i].selectedIndex].value};
			}
		}

		new_override = {'type': $('new_override_type')[$('new_override_type').selectedIndex].value, 'name': $('new_override_name').value, 'access': $('new_override_access')[$('new_override_access').selectedIndex].value};
	}

	xajax_EditGroup(group, Mask, srvMask, type, name, overrides, new_override);
}

function update_server()
{
	$('serverperm').setHTML('');

	if(document.getElementById('serverg').value == "c" || document.getElementById('serverg').value == "n") {
		$('server.msg').setHTML('Please Wait...');
		$('server.msg').setStyle('display', 'block');
	}

	if(document.getElementById('serverg').value == "c")
		var height = 580;
	else if(document.getElementById('serverg').value == "n")
		var height = 590;
	else
	{
		$('serverperm').setHTML('');
		var height = 1;
	}
	Shrink('serverperm', 1000, height);

	if(document.getElementById('serverg').value == "c" || document.getElementById('serverg').value == "n")
		setTimeout("xajax_UpdateAdminPermissions(2, document.getElementById('serverg').value)",1000);
	else {
		$('server.msg').setHTML('');
		$('server.msg').setStyle('display', 'none');
	}
}

function process_add_server()
{
	var el = document.getElementsByName('groups[]');
	var grp = "";
  	for(i=0;i<el.length;i++){
    	if(el[i].checked){
       		grp = grp + "," + el[i].value;
    	}
  	}
	xajax_AddServer(document.getElementById('address').value,
				document.getElementById('port').value,
				document.getElementById('rcon').value,
				document.getElementById('rcon2').value,
				document.getElementById('mod').value,
				document.getElementById('enabled').checked,
				grp,
				-1);

}

function process_edit_server()
{
    if($('rcon').value != $('rcon2').value)
    {
        $('rcon2.msg').innerHTML = 'Passwords don\'t match.';
        $('rcon2.msg').setStyle('display', 'block');
        return;
    }

    $('rcon2.msg').setStyle('display', 'none');
	document.forms.editserver.submit();
}

function search_bans()
{
	var type = "";
	var input = "";
	if($('name').checked)
	{
		type = "name";
		input = $('nick').value;
	}
	if($('steam_').checked)
	{
		type = (document.getElementById('steam_match').value == "1" ? "steam" : "steamid");
		input = $('steamid').value;
	}
	if($('ip_').checked)
	{
		type = "ip";
		input = $('ip').value;
	}
	if($('reason_').checked)
	{
		type = "reason";
		input = $('ban_reason').value;
	}
	if($('date').checked)
	{
		type = "date";
		input = $('day').value + "," + $('month').value + "," + $('year').value;
	}
	if($('length_').checked)
	{
		type = "length";
		if($('length').value=="other")
			var length = $('other_length').value;
		else
			var length = $('length').value
		input = $('length_type').value + "," + length;
	}
	if($('ban_type_').checked)
	{
		type = "btype";
		input = $('ban_type').value;
	}
	if($('bancount').checked)
	{
		type = "bancount";
		input = $('timesbanned').value;
	}
	if($('admin').checked)
	{
		type = "admin";
		input = $('ban_admin').value;
	}
	if($('where_banned').checked)
	{
		type = "where_banned";
		input = $('server').value;
	}
	if($('comment_').checked)
	{
		type = "comment";
		input = $('ban_comment').value;
	}
	if(type!="" && input!="")
		window.location = "index.php?p=banlist&advSearch=" + input + "&advType=" + type;
}
var webSelected = new Array();
var srvSelected = new Array();
function getMultiple(ob, type) {
	if(type==1) {
		while (ob.selectedIndex != -1)
		{
			webSelected.push(ob.options[ob.selectedIndex].value);
			ob.options[ob.selectedIndex].selected = false;
		}
	}
	if(type==2) {
		while (ob.selectedIndex != -1)
		{
			srvSelected.push(ob.options[ob.selectedIndex].value);
			ob.options[ob.selectedIndex].selected = false;
		}
	}
}
function search_admins()
{
	var type = "";
	var input = "";
	if($('name_').checked)
	{
		type = "name";
		input = $('nick').value;
	}
	if($('steam_').checked)
	{
		type = (document.getElementById('steam_match').value == "1" ? "steam" : "steamid");
		input = $('steamid').value;
	}
	if($('admemail_').checked)
	{
		type = "admemail";
		input = $('admemail').value;
	}
	if($('webgroup_').checked)
	{
		type = "webgroup";
		input = $('webgroup').value;
	}
	if($('srvadmgroup_').checked)
	{
		type = "srvadmgroup";
		input = $('srvadmgroup').value;
	}
	if($('srvgroup_').checked)
	{
		type = "srvgroup";
		input = $('srvgroup').value;
	}
	if($('admwebflags_').checked)
	{
		type = "admwebflag";
		input = webSelected.toString();
	}
	if($('admsrvflags_').checked)
	{
		type = "admsrvflag";
		input = srvSelected.toString();
	}
	if($('admin_on_').checked)
	{
		type = "server";
		input = $('server').value;
	}
	if(type!="" && input!="")
		window.location = "index.php?p=admin&c=admins&advSearch=" + input + "&advType=" + type;
}

function search_log()
{
	var type = "";
	var input = "";
	if($('admin_').checked)
	{
		type = "admin";
		input = $('admin').value;
	}
	if($('message_').checked)
	{
		type = "message";
		input = $('message').value;
	}
	if($('date_').checked)
	{
		type = "date";
		input = $('day').value + "," + $('month').value + "," + $('year').value + "," + $('fhour').value + "," + $('fminute').value + "," + $('thour').value + "," + $('tminute').value;
	}
	if($('type_').checked)
	{
		type = "type";
		input = $('type').value;
	}
	if(type!="" && input!="")
		window.location = "index.php?p=admin&c=settings&advSearch=" + input + "&advType=" + type + "#^2";
}
var icname = "";
function icon(name)
{
	$('icon.msg').setHTML("Uploaded: " + name + "");
	icname = name;
	if($('icon_hid'))
		$('icon_hid').value = name;
}
function ProcessMod()
{
	var err = 0;
	if(!$('name').value)
	{
		$('name.msg').setHTML('You must enter the name of the mod you are adding.');
		$('name.msg').setStyle('display', 'block');
		err++;
	}else
	{
		$('name.msg').setHTML('');
		$('name.msg').setStyle('display', 'none');
	}

	if(!$('folder').value)
	{
		$('folder.msg').setHTML('You must enter mod\'s folder name.');
		$('folder.msg').setStyle('display', 'block');
		err++;
	}else
	{
		$('folder.msg').setHTML('');
		$('folder.msg').setStyle('display', 'none');
	}

	if(err)
		return 0;

	xajax_AddMod($('name').value,
				 $('folder').value,
				 icname,
				 $('steam_universe').value,
				 $('enabled').checked);
}
function ShowBox(title, msg, color, redir, noclose)
{
	var type = "";

	if(color == "red")
		color = "error";
	else if(color == "blue")
		color = "info";
	else if(color == "green")
		color = "ok";

	$('dialog-title').setProperty("class", color);

	$('dialog-icon').setProperty("class", 'icon-'+color);

	$('dialog-title').setHTML(title);
	$('dialog-content-text').setHTML(msg);
	FadeElIn('dialog-placement', 750);

	var jsCde = "closeMsg('" + redir + "');";
	$('dialog-control').setHTML("<input name='dialog-close' onclick=\""+jsCde+"\" class='btn ok' onmouseover=\"ButtonOver('dialog-close')\" onmouseout='ButtonOver(\"dialog-close\")' id=\"dialog-close\" value=\"OK\" type=\"button\">");
	$('dialog-control').setStyle('display', 'block');

	if(!noclose)
	{
		if(redir)
			setTimeout("window.location='" + redir + "'",5000);
		else
		{
			setTimeout("FadeElOut('dialog-placement', 750);",5000);
		}
	}
}
function closeMsg(redir)
{
	if(redir.toString().length > 0 && redir != "undefined")
		window.location = redir;
	else
	{
		FadeElOut('dialog-placement', 750);
	}
}

function TabToReload()
{
	var url = window.location.toString();
	var nurl = "window.location = '" + url.replace("#^" + url[url.length-1],"") + "'";
	$('admin_tab_0').setProperty('onclick', nurl);
}

function toggleMCE(id) {
	var elm = document.getElementById(id);
	if (tinyMCE.getInstanceById(id) == null)
		tinyMCE.execCommand('mceAddControl', false, id);
	else
		tinyMCE.execCommand('mceRemoveControl', false, id);
}

function CheckEmail(type, id)
{
	var err = 0;
	if($('subject').value == "") {
		$('subject.msg').setHTML("You must type a subject for the email.");
		$('subject.msg').setStyle('display', 'block');
		err++;
	} else {
		$('subject.msg').setHTML('');
		$('subject.msg').setStyle('display', 'none');
	}

	if($('message').value == "") {
		$('message.msg').setHTML("You must type a message for the email.");
		$('message.msg').setStyle('display', 'block');
		err++;
	} else {
		$('message.msg').setHTML('');
		$('message.msg').setStyle('display', 'none');
	}

	if(err>0)
		return;
	xajax_SendMail($('subject').value, $('message').value, type, id);
}

function IsNumeric(sText)
{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

	for (i = 0; i < sText.length && IsNumber == true; i++)
	{
		Char = sText.charAt(i);
  		if (ValidChars.indexOf(Char) == -1)
		{
			IsNumber = false;
     	}
  	}
   	return IsNumber;
}

function ButtonOver(el)
{
	if($(el))
	{
		if($(el).hasClass('btn'))
		{
			$(el).removeClass('btn');
			$(el).addClass('btnhvr');
		}
		else
		{
			$(el).removeClass('btnhvr');
			$(el).addClass('btn');
		}
	}
}

function ClearLogs()
{
	var noPerm = confirm("Are you sure you want to delete all of the log entries?");
	if(noPerm == false)
	{
		return;
	}
	window.location = "index.php?p=admin&c=settings&log_clear=true#^2";
}

function RemoveMod(name, id)
{
	var noPerm = confirm("Are you sure you want to delete '" + name +"'?");
	if(noPerm == false)
		return;
	xajax_RemoveMod(id);
}

function UpdateGroupPermissionCheckBoxes()
{
	$('perms').setHTML('');
	if(document.getElementById('grouptype').value != 3 && document.getElementById('grouptype').value != 0) {
		$('type.msg').setHTML('Please Wait...');
		$('type.msg').setStyle('display', 'block');
	}
	if(document.getElementById('grouptype').value == 1)
	{
		var height = 285;
	}else if(document.getElementById('grouptype').value == 2)
	{
		var height = 435;
	}else
	{
		$('type.msg').setStyle('display', 'none');
		var height = 2;
	}
	Shrink('perms', 1000, height);
	if(document.getElementById('grouptype').value != 3 && document.getElementById('grouptype').value != 0)
		setTimeout("xajax_UpdateGroupPermissions(document.getElementById('grouptype').value)",1000);
}

function changePage(newPage, type, advSearch, advType)
{
	nextPage = newPage.options[newPage.selectedIndex].value
	if(advSearch!="" && advType !="") {
		var searchlink = "&advSearch="+advSearch+"&advType="+advType;
	} else {
		var searchlink ="";
	}
	 if (nextPage != 0)
	 {
		if(type == "A")
            window.location = "index.php?p=admin&c=admins"+searchlink+"&page="+nextPage;
		if(type == "B")
            window.location = "index.php?p=banlist"+searchlink+"&page="+nextPage;
		if(type == "C")
            window.location = "index.php?p=commslist"+searchlink+"&page="+nextPage;
		if(type == "L")
            window.location = "index.php?p=admin&c=settings"+searchlink+"&page="+nextPage+"#^2";
        if(type == "P")
            window.location = "index.php?p=admin&c=bans&ppage="+nextPage+"#^1";
        if(type == "PA")
            window.location = "index.php?p=admin&c=bans&papage="+nextPage+"#^1~p1";
        if(type == "S")
            window.location = "index.php?p=admin&c=bans&spage="+nextPage+"#^2";
        if(type == "SA")
            window.location = "index.php?p=admin&c=bans&sapage="+nextPage+"#^2~s1";
	 }
}

function ShowKickBox(check, type)
{
	ShowBox('Ban Added', 'The ban has been successfully added
', 'green', 'index.php?p=admin&c=bans', true);
}

function ShowRehashBox(servers, title, msg, color, redir)
{
	// Don't show anything sm_rehash related, if there are no servers to rcon.
	if(servers == '')
	{
		ShowBox(title, msg, color, redir, true);
		return;
	}
	msg = msg + '

Rehashing Admin and Group data on all related servers...

';
	ShowBox(title, msg, color, redir, true);
	$('dialog-control').setStyle('display', 'none');
	xajax_RehashAdmins(servers);
}

function ProcessComment()
{
	var err = 0;
	if($('commenttext').value == "")
	{
		$('commenttext.msg').setHTML('You have to type your comment');
		$('commenttext.msg').setStyle('display', 'block');
		err++;
	}else
	{
		$('commenttext.msg').setHTML('');
		$('commenttext.msg').setStyle('display', 'none');
		err = 0;
	}

	if(err)
		return 0;

	if($('cid').value == -1)
	{
		xajax_AddComment($('bid').value,
					 $('ctype').value,
					 $('commenttext').value,
					 $('page').value);
	}
	else
	{
		xajax_EditComment($('cid').value,
					 $('ctype').value,
					 $('commenttext').value,
					 $('page').value);
	}
}

function RemoveComment(cid, type, page)
{
	var checkUp = confirm("Are you sure you want to delete the comment?");
	if(checkUp == false)
		return;
	xajax_RemoveComment(cid, type, page);
}

// drag and drop function, make the dialog window movable!
var ns4=document.layers;
var ie4=document.all;
var ns6=document.getElementById&&!document.all;

//NS 4
var dragswitch=0;
var nsx;
var nsy;
var nstemp;
function drag_drop_ns(name)
{
	if(!ns4)
		return;
	temp=eval(name);
	temp.captureEvents(Event.MOUSEDOWN | Event.MOUSEUP);
	temp.onmousedown=gons;
	temp.onmousemove=dragns;
	temp.onmouseup=stopns;
}
function gons(e)
{
	temp.captureEvents(Event.MOUSEMOVE);
	nsx=e.x;
	nsy=e.y;
}
function dragns(e)
{
	if(dragswitch==1) {
		temp.moveBy(e.x-nsx,e.y-nsy);
		return false;
	}
}
function stopns()
{
	temp.releaseEvents(Event.MOUSEMOVE);
}

//IE4 || NS6
function drag_drop(e)
{
	if(ie4&&dragapproved) {
		crossobj.style.left=tempx+event.clientX-offsetx+'px';
		crossobj.style.top=tempy+event.clientY-offsety+'px';
		return false;
	}
	else if(ns6&&dragapproved) {
		crossobj.style.left=tempx+e.clientX-offsetx+'px';
		crossobj.style.top=tempy+e.clientY-offsety+'px';
		return false;
	}
}
function initializiere_drag(e)
{
	crossobj=ns6? document.getElementById("dialog-placement") : document.all["dialog-placement"];
	var firedobj=ns6? e.target : event.srcElement;
	var topelement=ns6? "HTML" : "BODY";

	while (firedobj!=null&&firedobj.tagName!=topelement&&firedobj.id!="dragbar") {
		firedobj=ns6? firedobj.parentNode : firedobj.parentElement;
	}
	if(firedobj!=null&&firedobj.id=="dragbar")
	{
		offsetx=ie4? event.clientX : e.clientX;
		offsety=ie4? event.clientY : e.clientY;
		tempx=parseInt(crossobj.style.left);
		tempy=parseInt(crossobj.style.top);
		dragapproved=true;
		document.onmousemove=drag_drop;
	}

}
document.onmousedown=initializiere_drag;
document.onmouseup=new Function("dragapproved=false");

function TickSelectAll()
{
	for(var i=0;$('chkb_' + i);i++)
	{
		if($('tickswitch').value==0)
			$('chkb_' + i).checked = true;
		else
			$('chkb_' + i).checked = false;
	}
	if($('tickswitch').value==0) {
		$('tickswitch').value=1;
		$('tickswitch').setProperty('title','Deselect All');
		$('tickswitchlink').setProperty('title','Deselect All');
		$('tickswitchlink').innerHTML = 'Deselect All';
	} else {
		$('tickswitch').value=0;
		$('tickswitch').setProperty('title','Select All');
		$('tickswitchlink').setProperty('title','Select All');
		$('tickswitchlink').innerHTML = 'Select All';
	}
}

function BulkEdit(action, bankey)
{
	option = action.options[action.selectedIndex].value
	ids = new Array();
	for(var i=0;$('chkb_' + i);i++)
	{
		if($('chkb_' + i).checked===true)
			ids.push($('chkb_' + i).value);
	}
	switch(option)
	{
		case "U":
			UnbanBan(ids, bankey, "", "Bulk Unban", "1", "true");
		break;
		case "D":
			RemoveBan(ids, bankey, "", "Bulk Delete", "0", "true");
		break;
	}
}

function BanFriendsProcess(fid, name)
{
	var checkUp = confirm("Are you sure you want to ban all steam community friends of '"+name+"'?");
	if(checkUp == false)
		return;
	ShowBox("Banning friends of "+name, "Banning all steam community friends of '"+name+"'.
Please wait...
This can last very long, depending on the amount of friends.", 'blue', '', true);
	$('dialog-control').setStyle('display', 'none');
	xajax_BanFriends(fid, name);
}

function OpenMessageBox(sid, name, popup)
{
	if(popup==1) {
		ShowBox('Send Message', 'Please type the message you want to send to
\''+name+'\'.
You need to have basechat.smx enabled as we use
<sm_psay>.
<textarea rows="3" cols="40" name="ingamemsg" id="ingamemsg" style="overflow:auto;"></textarea>

', 'blue', '', true);
		$('dialog-control').setHTML('<input type="button" name="ingmsg" class="btn ok" onmouseover="ButtonOver(\'ingmsg\')" onmouseout="ButtonOver(\'ingmsg\')" id="ingmsg" value="Send Message" /> <input type="button" onclick="closeMsg(\'\');" name="astop" class="btn cancel" onmouseover="ButtonOver(\'astop\')" onmouseout="ButtonOver(\'astop\')" id="astop" value="Cancel" />');
		$('ingmsg').addEvent('click', function(){OpenMessageBox(sid, name, 0);});
	} else if(popup==0) {
		message = $('ingamemsg').value;
		if(message == "") {
			$('ingamemsg.msg').setHTML("Please type your message.");
			$('ingamemsg.msg').setStyle('display', 'block');
			return;
		} else {
			$('ingamemsg.msg').setHTML('');
			$('ingamemsg.msg').setStyle('display', 'none');
		}
		$('dialog-control').setStyle('display', 'none');
		$('ingamemsg').readOnly = true;
		xajax_SendMessage(sid, name, message);
	}
}

function KickPlayerConfirm(sid, name, conf)
{
	if(conf==0)	{
		ShowBox('Kick Player', 'Are you sure you want to kick player
\''+name+'\'?', 'blue', '', true);
		$('dialog-control').setHTML('<input type="button" name="kbutton" class="btn ok" onmouseover="ButtonOver(\'kbutton\')" onmouseout="ButtonOver(\'kbutton\')" id="kbutton" value="Yes" /> <input type="button" onclick="closeMsg(\'\');" name="astop" class="btn cancel" onmouseover="ButtonOver(\'astop\')" onmouseout="ButtonOver(\'astop\')" id="astop" value="No" />');
		$('kbutton').addEvent('click', function(){KickPlayerConfirm(sid, name, 1);});
	} else if(conf==1) {
		$('dialog-control').setStyle('display', 'none');
		xajax_KickPlayer(sid, name);
	}
}

function mapimg(filename)
{
	$('mapimg.msg').setHTML("Uploaded: " + filename + "");
}

function selectLengthTypeReason(length, type, reason)
{
	for(var i=0; i<=$('banlength').length ; i++) {
		if($('banlength').options[i].value == (length / 60)) {
			$('banlength').options[i].selected=true;
			break;
		}
	}
	$('type').options[type].selected = true;
	for(var i=0;i<=$('listReason').length;i++)	{
		if($('listReason').options[i].innerHTML == reason) {
			$('listReason').options[i].selected=true;
			break;
		}
		if($('listReason').options[i].value == 'other') {
			$('txtReason').value = reason;
			$('dreason').style.display = 'block';
			$('listReason').options[i].selected=true;
			break;
		}
	}
}

function ViewCommunityProfile(sid, name)
{
    ShowBox('View Community Profile', 'Generating Community Profile link for "'+name+'", please wait...', 'blue', '', true);
    $('dialog-control').setStyle('display', 'none');
    xajax_ViewCommunityProfile(sid, name);
}

// Thanks to http://phpjs.org/functions/addslashes:303
function addslashes (str)
{
	return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}

function RemoveBlock(id, key, page, name, confirm)
{
	if(confirm==0) {
		ShowBox('Delete Block', 'Are you sure you want to delete the block for '+ name + '?', 'blue', '', true);
		$('dialog-control').setHTML('<input type="button" onclick="RemoveBlock(\''+id+'\', \''+key+'\', \''+page+'\', \''+addslashes(name.replace(/\'/g,'\\\''))+'\', \'1\''+');" name="rban" class="btn ok" onmouseover="ButtonOver(\'rban\')" onmouseout="ButtonOver(\'rban\')" id="rban" value="Remove Block" /> <input type="button" onclick="closeMsg(\'\');$(\'bulk_action\').options[0].selected=true;" name="astop" class="btn cancel" onmouseover="ButtonOver(\'astop\')" onmouseout="ButtonOver(\'astop\')" id="astop" value="Cancel" />');
	} else if(confirm==1) {
		if(page != "")
			var pagelink = page;
		else
			var pagelink = "";
		window.location = "index.php?p=commslist" + pagelink + "&a=delete&id="+ id +"&key="+ key;
	}
}

function UnGag(id, key, page, name, popup)
{
	if(popup==1) {
		ShowBox('UnGag Reason', 'Please give a short comment, why you are going to ungag '+"\'"+ name +"\'"+'!
<textarea rows="3" cols="40" name="ureason" id="ureason" style="overflow:auto;"></textarea>

', 'blue', '', true);
		$('dialog-control').setHTML('<input type="button" onclick="UnGag(\''+id+'\', \''+key+'\', \''+page+'\', \''+addslashes(name.replace(/\'/g,'\\\''))+'\', \'0\''+');" name="uban" class="btn ok" onmouseover="ButtonOver(\'uban\')" onmouseout="ButtonOver(\'uban\')" id="uban" value="UnGag Player" /> <input type="button" onclick="closeMsg(\'\');" name="astop" class="btn cancel" onmouseover="ButtonOver(\'astop\')" onmouseout="ButtonOver(\'astop\')" id="astop" value="Cancel" />');
	} else if(popup==0) {
		if(page != "")
			var pagelink = page;
		else
			var pagelink = "";
		reason = $('ureason').value;
		if(reason == "") {
			$('ureason.msg').setHTML("Please leave a comment.");
			$('ureason.msg').setStyle('display', 'block');
			return;
		} else {
			$('ureason.msg').setHTML('');
			$('ureason.msg').setStyle('display', 'none');
		}
		window.location = "index.php?p=commslist" + pagelink + "&a=ungag&id="+ id +"&key="+ key +"&ureason="+ reason;
	}
}

function UnMute(id, key, page, name, popup)
{
	if(popup==1) {
		ShowBox('UnMute Reason', 'Please give a short comment, why you are going to unmute '+"\'"+ name +"\'"+'!
<textarea rows="3" cols="40" name="ureason" id="ureason" style="overflow:auto;"></textarea>

', 'blue', '', true);
		$('dialog-control').setHTML('<input type="button" onclick="UnMute(\''+id+'\', \''+key+'\', \''+page+'\', \''+addslashes(name.replace(/\'/g,'\\\''))+'\', \'0\''+');" name="uban" class="btn ok" onmouseover="ButtonOver(\'uban\')" onmouseout="ButtonOver(\'uban\')" id="uban" value="UnMute Player" /> <input type="button" onclick="closeMsg(\'\');" name="astop" class="btn cancel" onmouseover="ButtonOver(\'astop\')" onmouseout="ButtonOver(\'astop\')" id="astop" value="Cancel" />');
	} else if(popup==0) {
		if(page != "")
			var pagelink = page;
		else
			var pagelink = "";
		reason = $('ureason').value;
		if(reason == "") {
			$('ureason.msg').setHTML("Please leave a comment.");
			$('ureason.msg').setStyle('display', 'block');
			return;
		} else {
			$('ureason.msg').setHTML('');
			$('ureason.msg').setStyle('display', 'none');
		}
		window.location = "index.php?p=commslist" + pagelink + "&a=unmute&id="+ id +"&key="+ key +"&ureason="+ reason;
	}
}

function search_blocks()
{
	var type = "";
	var input = "";
	if($('name').checked)
	{
		type = "name";
		input = $('nick').value;
	}
	if($('steam_').checked)
	{
		type = (document.getElementById('steam_match').value == "1" ? "steam" : "steamid");
		input = $('steamid').value;
	}
	if($('reason_').checked)
	{
		type = "reason";
		input = $('ban_reason').value;
	}
	if($('date').checked)
	{
		type = "date";
		input = $('day').value + "," + $('month').value + "," + $('year').value;
	}
	if($('length_').checked)
	{
		type = "length";
		if($('length').value=="other")
			var length = $('other_length').value;
		else
			var length = $('length').value
		input = $('length_type').value + "," + length;
	}
	if($('ban_type_').checked)
	{
		type = "btype";
		input = $('ban_type').value;
	}
	if($('bancount').checked)
	{
		type = "bancount";
		input = $('timesbanned').value;
	}
	if($('admin').checked)
	{
		type = "admin";
		input = $('ban_admin').value;
	}
	if($('where_banned').checked)
	{
		type = "where_banned";
		input = $('server').value;
	}
	if($('comment_').checked)
	{
		type = "comment";
		input = $('ban_comment').value;
	}
	if(type!="" && input!="")
		window.location = "index.php?p=commslist&advSearch=" + input + "&advType=" + type;
}

function ShowBlockBox(check, type, length)
{
	ShowBox('Block Added', 'The block has been successfully added
', 'green', 'index.php?p=admin&c=comms', true);
}

redpajama_set_name: RedPajamaGithub


text:
{% load i18n %}
{% trans "None" as none_choice %}

    {% if field.label %}
        {{ field.label }}
    {% endif %}
    {% if field.allow_null or field.allow_blank %}

                <input type="radio" name="{{ field.name }}" value="" {% if not field.value %}checked{% endif %}>
                {{ none_choice }}

    {% endif %}
    {% for key, text in field.choices.items %}

                <input type="radio" name="{{ field.name }}" value="{{ key }}" {% if key == field.value %}checked{% endif %}>
                {{ text }}

    {% endfor %}


text:
package org.stajistics.tracker.span;

import org.stajistics.StatsKey;
import org.stajistics.session.StatsSession;
import org.stajistics.session.StatsSessionManager;

/**
 *
 *
 *
 * @author The Stajistics Project
 */
public class ConcurrentAccessTracker extends AbstractSpanTracker {

    public static final Factory FACTORY = new Factory();

    public ConcurrentAccessTracker(final StatsSession statsSession) {
        super(statsSession);
    }

    @Override
    protected void stopImpl(final long now) {
        value = session.getHits() - session.getCommits();

        session.update(this, now);
    }

    public static class Factory extends AbstractSpanTrackerFactory {

        @Override
        public SpanTracker createTracker(final StatsKey key,
                                         final StatsSessionManager sessionManager) {
            return new ConcurrentAccessTracker(sessionManager.getOrCreateSession(key));
        }
    }
}


text:
// ----------------------------------------------------------------------
// HEP coherent system of Units
//
// This file has been provided to CLHEP by Geant4 (simulation toolkit for HEP).
//
// The basic units are :
// millimeter              (millimeter)
// nanosecond              (nanosecond)
// Mega electron Volt      (MeV)
// positron charge         (eplus)
// degree Kelvin           (kelvin)
// the amount of substance (mole)
// luminous intensity      (candela)
// radian                  (radian)
// steradian               (steradian)
//
// Below is a non exhaustive list of derived and pratical units
// (i.e. mostly the SI units).
// You can add your own units.
//
// The SI numerical value of the positron charge is defined here,
// as it is needed for conversion factor : positron charge = e_SI (coulomb)
//
// The others physical constants are defined in the header file :
//PhysicalConstants.h
//
// Authors: M.Maire, S.Giani
//
// History:
//
// 06.02.96   Created.
// 28.03.96   Added miscellaneous constants.
// 05.12.97   E.Tcherniaev: Redefined pascal (to avoid warnings on WinNT)
// 20.05.98   names: meter, second, gram, radian, degree
//            (from Brian.Lasiuk@yale.edu (STAR)). Added luminous units.
// 05.08.98   angstrom, picobarn, microsecond, picosecond, petaelectronvolt
// 01.03.01   parsec
// 31.01.06   kilogray, milligray, microgray
// 29.04.08   use PDG 2006 value of e_SI
// 03.11.08   use PDG 2008 value of e_SI
// 19.08.15   added liter and its sub units (mma)

#ifndef GASTPC_SYSTEM_OF_UNITS_H
#define GASTPC_SYSTEM_OF_UNITS_H

namespace gastpc {

  //
  //
  //
  static const double     pi  = 3.14159265358979323846;
  static const double  twopi  = 2*pi;
  static const double halfpi  = pi/2;
  static const double     pi2 = pi*pi;

  //
  // Length [L]
  //
  static const double millimeter  = 1.;
  static const double millimeter2 = millimeter*millimeter;
  static const double millimeter3 = millimeter*millimeter*millimeter;

  static const double centimeter  = 10.*millimeter;
  static const double centimeter2 = centimeter*centimeter;
  static const double centimeter3 = centimeter*centimeter*centimeter;

  static const double meter  = 1000.*millimeter;
  static const double meter2 = meter*meter;
  static const double meter3 = meter*meter*meter;

  static const double kilometer = 1000.*meter;
  static const double kilometer2 = kilometer*kilometer;
  static const double kilometer3 = kilometer*kilometer*kilometer;

  static const double parsec = 3.0856775807e+16*meter;

  static const double micrometer = 1.e-6 *meter;
  static const double  nanometer = 1.e-9 *meter;
  static const double  angstrom  = 1.e-10*meter;
  static const double  fermi     = 1.e-15*meter;

  static const double      barn = 1.e-28*meter2;
  static const double millibarn = 1.e-3 *barn;
  static const double microbarn = 1.e-6 *barn;
  static const double  nanobarn = 1.e-9 *barn;
  static const double  picobarn = 1.e-12*barn;

  // symbols
  static const double nm  = nanometer;
  static const double um  = micrometer;

  static const double mm  = millimeter;
  static const double mm2 = millimeter2;
  static const double mm3 = millimeter3;

  static const double cm  = centimeter;
  static const double cm2 = centimeter2;
  static const double cm3 = centimeter3;

  static const double liter = 1.e+3*cm3;
  static const double  L = liter;
  static const double dL = 1.e-1*liter;
  static const double cL = 1.e-2*liter;
  static const double mL = 1.e-3*liter;

  static const double m  = meter;
  static const double m2 = meter2;
  static const double m3 = meter3;

  static const double km  = kilometer;
  static const double km2 = kilometer2;
  static const double km3 = kilometer3;

  static const double pc = parsec;

  //
  // Angle
  //
  static const double radian      = 1.;
  static const double milliradian = 1.e-3*radian;
  static const double degree = (pi/180.0)*radian;

  static const double   steradian = 1.;

  // symbols
  static const double rad  = radian;
  static const double mrad = milliradian;
  static const double sr   = steradian;
  static const double deg  = degree;

  //
  // Time [T]
  //
  static const double nanosecond  = 1.;
  static const double second      = 1.e+9 *nanosecond;
  static const double millisecond = 1.e-3 *second;
  static const double microsecond = 1.e-6 *second;
  static const double  picosecond = 1.e-12*second;

  static const double hertz = 1./second;
  static const double kilohertz = 1.e+3*hertz;
  static const double megahertz = 1.e+6*hertz;

  // symbols
  static const double ns = nanosecond;
  static const double  s = second;
  static const double ms = millisecond;

  //
  // Electric charge [Q]
  //
  static const double eplus = 1. ;// positron charge
  static const double e_SI  = 1.602176487e-19;// positron charge in coulomb
  static const double coulomb = eplus/e_SI;// coulomb = 6.24150 e+18 * eplus

  //
  // Energy [E]
  //
  static const double megaelectronvolt = 1. ;
  static const double     electronvolt = 1.e-6*megaelectronvolt;
  static const double kiloelectronvolt = 1.e-3*megaelectronvolt;
  static const double gigaelectronvolt = 1.e+3*megaelectronvolt;
  static const double teraelectronvolt = 1.e+6*megaelectronvolt;
  static const double petaelectronvolt = 1.e+9*megaelectronvolt;

  static const double joule = electronvolt/e_SI;// joule = 6.24150 e+12 * MeV

  // symbols
  static const double MeV = megaelectronvolt;
  static const double  eV = electronvolt;
  static const double keV = kiloelectronvolt;
  static const double GeV = gigaelectronvolt;
  static const double TeV = teraelectronvolt;
  static const double PeV = petaelectronvolt;

  //
  // Mass [E][T^2][L^-2]
  //
  static const double  kilogram = joule*second*second/(meter*meter);
  static const double      gram = 1.e-3*kilogram;
  static const double milligram = 1.e-3*gram;

  // symbols
  static const double  kg = kilogram;
  static const double   g = gram;
  static const double  mg = milligram;

  //
  // Power [E][T^-1]
  //
  static const double watt = joule/second;// watt = 6.24150 e+3 * MeV/ns

  //
  // Force [E][L^-1]
  //
  static const double newton = joule/meter;// newton = 6.24150 e+9 * MeV/mm

  //
  // Pressure [E][L^-3]
  //
#define pascal hep_pascal                          // a trick to avoid warnings
  static const double hep_pascal = newton/m2;   // pascal = 6.24150 e+3 * MeV/mm3
  static const double bar        = 100000*pascal; // bar    = 6.24150 e+8 * MeV/mm3
  static const double atmosphere = 101325*pascal; // atm    = 6.32420 e+8 * MeV/mm3

  //
  // Electric current [Q][T^-1]
  //
  static const double      ampere = coulomb/second; // ampere = 6.24150 e+9 * eplus/ns
  static const double milliampere = 1.e-3*ampere;
  static const double microampere = 1.e-6*ampere;
  static const double  nanoampere = 1.e-9*ampere;

  //
  // Electric potential [E][Q^-1]
  //
  static const double megavolt = megaelectronvolt/eplus;
  static const double kilovolt = 1.e-3*megavolt;
  static const double     volt = 1.e-6*megavolt;

  //
  // Electric resistance [E][T][Q^-2]
  //
  static const double ohm = volt/ampere;// ohm = 1.60217e-16*(MeV/eplus)/(eplus/ns)

  //
  // Electric capacitance [Q^2][E^-1]
  //
  static const double farad = coulomb/volt;// farad = 6.24150e+24 * eplus/Megavolt
  static const double millifarad = 1.e-3*farad;
  static const double microfarad = 1.e-6*farad;
  static const double  nanofarad = 1.e-9*farad;
  static const double  picofarad = 1.e-12*farad;

  //
  // Magnetic Flux [T][E][Q^-1]
  //
  static const double weber = volt*second;// weber = 1000*megavolt*ns

  //
  // Magnetic Field [T][E][Q^-1][L^-2]
  //
  static const double tesla     = volt*second/meter2;// tesla =0.001*megavolt*ns/mm2

  static const double gauss     = 1.e-4*tesla;
  static const double kilogauss = 1.e-1*tesla;

  //
  // Inductance [T^2][E][Q^-2]
  //
  static const double henry = weber/ampere;// henry = 1.60217e-7*MeV*(ns/eplus)**2

  //
  // Temperature
  //
  static const double kelvin = 1.;

  //
  // Amount of substance
  //
  static const double mole = 1.;

  //
  // Activity [T^-1]
  //
  static const double becquerel = 1./second ;
  static const double curie = 3.7e+10 * becquerel;
  static const double kilobecquerel = 1.e+3*becquerel;
  static const double megabecquerel = 1.e+6*becquerel;
  static const double gigabecquerel = 1.e+9*becquerel;
  static const double millicurie = 1.e-3*curie;
  static const double microcurie = 1.e-6*curie;
  static const double Bq = becquerel;
  static const double kBq = kilobecquerel;
  static const double MBq = megabecquerel;
  static const double GBq = gigabecquerel;
  static const double Ci = curie;
  static const double mCi = millicurie;
  static const double uCi = microcurie;

  //
  // Absorbed dose [L^2][T^-2]
  //
  static const double      gray = joule/kilogram ;
  static const double  kilogray = 1.e+3*gray;
  static const double milligray = 1.e-3*gray;
  static const double microgray = 1.e-6*gray;

  //
  // Luminous intensity [I]
  //
  static const double candela = 1.;

  //
  // Luminous flux [I]
  //
  static const double lumen = candela*steradian;

  //
  // Illuminance [I][L^-2]
  //
  static const double lux = lumen/meter2;

  //
  // Miscellaneous
  //
  static const double perCent     = 0.01 ;
  static const double perThousand = 0.001;
  static const double perMillion  = 0.000001;

}  // namespace gastpc

#endif /* GASTPC_SYSTEM_OF_UNITS_H */


text:
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using OrchardCore.ContentManagement;
using OrchardCore.Deployment;

namespace OrchardCore.ContentTypes.Deployment
{
    public class ReplaceContentDefinitionDeploymentSource : IDeploymentSource
    {
        private readonly IContentDefinitionStore _contentDefinitionStore;

        public ReplaceContentDefinitionDeploymentSource(IContentDefinitionStore contentDefinitionStore)
        {
            _contentDefinitionStore = contentDefinitionStore;
        }

        public async Task ProcessDeploymentStepAsync(DeploymentStep step, DeploymentPlanResult result)
        {
            if (!(step is ReplaceContentDefinitionDeploymentStep replaceContentDefinitionStep))
            {
                return;
            }

            var contentTypeDefinitionRecord = await _contentDefinitionStore.LoadContentDefinitionAsync();

            var contentTypes = replaceContentDefinitionStep.IncludeAll
                ? contentTypeDefinitionRecord.ContentTypeDefinitionRecords
                : contentTypeDefinitionRecord.ContentTypeDefinitionRecords
                    .Where(x => replaceContentDefinitionStep.ContentTypes.Contains(x.Name));

            var contentParts = replaceContentDefinitionStep.IncludeAll
                ? contentTypeDefinitionRecord.ContentPartDefinitionRecords
                : contentTypeDefinitionRecord.ContentPartDefinitionRecords
                        .Where(x => replaceContentDefinitionStep.ContentParts.Contains(x.Name));

            result.Steps.Add(new JObject(
                new JProperty("name", "ReplaceContentDefinition"),
                new JProperty("ContentTypes", JArray.FromObject(contentTypes)),
                new JProperty("ContentParts", JArray.FromObject(contentParts))
            ));
        }
    }
}


text:
package rx.test;

import java.util.concurrent.TimeUnit;

import rx.Scheduler;
import rx.Subscription;
import rx.functions.Action1;

/**
 * Common utility functions for testing operator implementations.
 */
public class OperatorTester {
    /*
     * This is purposefully package-only so it does not leak into the public API outside of this package.
     *
     * This package is implementation details and not part of the Javadocs and thus can change without breaking backwards compatibility.
     *
     * benjchristensen => I'm procrastinating the decision of where and how these types of classes (see rx.subjects.UnsubscribeTester) should exist.
     * If they are only for internal implementations then I don't want them as part of the API.
     * If they are truly useful for everyone to use then an "rx.testing" package may make sense.
     */

    private OperatorTester() {
    }

    /**
     * Used for mocking of Schedulers since many Scheduler implementations are static/final.
     *
     * @param underlying
     * @return
     */
    public static Scheduler forwardingScheduler(Scheduler underlying) {
        return new ForwardingScheduler(underlying);
    }

    public static class ForwardingScheduler extends Scheduler {
        private final Scheduler underlying;

        public ForwardingScheduler(Scheduler underlying) {
            this.underlying = underlying;
        }

        @Override
        public Subscription schedule(Action1<Inner> action) {
            return underlying.schedule(action);
        }

        @Override
        public Subscription schedule(Action1<Inner> action, long delayTime, TimeUnit unit) {
            return underlying.schedule(action, delayTime, unit);
        }

    }
}


text:
import { applyMiddleware, compose, createStore } from 'redux'
import thunk from 'redux-thunk'
import { browserHistory } from 'react-router'
import makeRootReducer from './reducers'
import { updateLocation } from './location'

export default (initialState = {}) => {
  // ======================================================
  // Middleware Configuration
  // ======================================================
  const middleware = [thunk]

  // ======================================================
  // Store Enhancers
  // ======================================================
  const enhancers = []
  // if (__DEV__) {
  //   const devToolsExtension = window.devToolsExtension
  //   if (typeof devToolsExtension === 'function') {
  //     enhancers.push(devToolsExtension())
  //   }
  // }

  // ======================================================
  // Store Instantiation and HMR Setup
  // ======================================================
  const store = createStore(
    makeRootReducer(),
    initialState,
    compose(
      applyMiddleware(...middleware),
      ...enhancers
    )
  )
  store.asyncReducers = {}

  // To unsubscribe, invoke `store.unsubscribeHistory()` anytime
  store.unsubscribeHistory = browserHistory.listen(updateLocation(store))

  if (module.hot) {
    module.hot.accept('./reducers', () => {
      const reducers = require('./reducers').default
      store.replaceReducer(reducers(store.asyncReducers))
    })
  }

  return store
}


text:
@implementation IVVServiceAssemblyImplementation

#pragma mark - Services

- (id<IVVStartUpManager>)startupService {
    return [TyphoonDefinition withClass:[IVVStartUpManagerImplementation class]
                          configuration:^(TyphoonDefinition *definition) {
                              definition.scope = TyphoonScopeLazySingleton;
                              [definition injectProperty:@selector(storyboardAssembly)
                                                    with:self.storyboardAssembly];
                          }];
}

- (id<IVVCurrencyRatesService>)currencyRatesService {
    return [TyphoonDefinition withClass:[IVVCurrencyRatesServiceImplementation class]
                          configuration:^(TyphoonDefinition *definition) {
                              definition.scope = TyphoonScopeLazySingleton;

                              [definition injectProperty:@selector(client)
                                                    with:[self.coreAssembly XMLCapableClient]];
                              [definition injectProperty:@selector(mapper)
                                                    with:[[IVVCurrencyRatesServiceMapperImplementation alloc] init]];
                              [definition injectProperty:@selector(configurator)
                                                    with:[[IVVCurrencyRatesServiceConfiguratorImplementation alloc] init]];
                          }];
}

- (id<IVVMoneyTransferService>)moneyTransferService {
    return [TyphoonDefinition withClass:[IVVMoneyTransferServiceImplementation class]
                          configuration:^(TyphoonDefinition *definition) {
                              definition.scope = TyphoonScopeLazySingleton;

                              [definition injectProperty:@selector(moneyStorage)
                                                    with:[self.helperAssembly moneyStorage]];
                              [definition injectProperty:@selector(currencyConverter)
                                                    with:[self.helperAssembly currencyConverter]];
                          }];
}

@end


text:
import * as React from "react";
import Comment from "./Comment";
import {ICommentListProps} from "../interfaces";

export default class CommentList extends React.Component<ICommentListProps, any> {
    render() {
        let commentNodes = this.props.data.map((comment) => {
            return (<Comment author={comment.author}>{comment.text}</Comment>);
        });
        return (
{commentNodes}
);
    }
}


text:
<?php
namespace AppBundle\Handler;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Form\FormFactoryInterface;
use AppBundle\Model\ParcelorderInterface;
use AppBundle\Form\ParcelorderType;
use AppBundle\Exception\InvalidFormException;
class ParcelorderFormHandler implements ParcelorderFormHandlerInterface
{
    private $entityClass;
    private $repository;
    private $formFactory;
    private $formType;
    public function __construct(ObjectManager $om, $entityClass,FormFactoryInterface $formFactory, $formType)
    {
        $this->entityClass = $entityClass;
        $this->repository = $om->getRepository($this->entityClass);
        $this->formFactory = $formFactory;
        $this->formType = $formType;
    }
    public function post(array $parameters)
    {
        $parcelorder = $this->createParcelorder();
        return $this->processForm($parcelorder, $parameters, 'POST');
    }
    private function processForm(ParcelorderInterface $parcelorder, array $parameters, $method = "PUT")
    {
        $form = $this->formFactory->create($this->formType, $parcelorder, array('method' => $method));
        $form->submit($parameters, 'PATCH' !== $method);
        if ($form->isValid()) {
            $note = $form->getData();
            $this->repository->save($parcelorder);
            return $parcelorder;
		}
        throw new InvalidFormException('Invalid submitted data', $form);
    }
    private function createParcelorder()
    {
        return new $this->entityClass();
    }
}


text:
import setFlexGrow from '../../src/node/setFlexGrow';

describe('node setFlexGrow', () => {
  const mock = jest.fn();
  const node = { yogaNode: { setFlexGrow: mock } };

  beforeEach(() => {
    mock.mockReset();
  });

  test('should return node if no yoga node available', () => {
    const emptyNode = { box: { width: 10, height: 20 } };
    const result = setFlexGrow(null)(emptyNode);

    expect(result).toBe(emptyNode);
  });

  test('Should set zero by default', () => {
    const result = setFlexGrow(null)(node);

    expect(mock.mock.calls).toHaveLength(1);
    expect(mock.mock.calls[0][0]).toBe(0);
    expect(result).toBe(node);
  });

  test('Should set provided value', () => {
    const result = setFlexGrow(2)(node);

    expect(mock.mock.calls).toHaveLength(1);
    expect(mock.mock.calls[0][0]).toBe(2);
    expect(result).toBe(node);
  });
});


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Figure.cs" company="OxyPlot">
//   Copyright (c) 2014 OxyPlot contributors
// </copyright>
// <summary>
//   Provides a base class for figures (drawings, images and plots).
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace OxyPlot.Reporting
{
    /// <summary>
    /// Provides a base class for figures (drawings, images and plots).
    /// </summary>
    public abstract class Figure : ReportItem
    {
        /// <summary>
        /// Gets or sets the figure number.
        /// </summary>
        public int FigureNumber { get; set; }

        /// <summary>
        /// Gets or sets the figure text.
        /// </summary>
        /// <remarks>No figure text will be shown if set to <c>null</c>.
        /// A figure number will be counted if the figure text is not <c>null</c>.</remarks>
        public string FigureText { get; set; }

        /// <summary>
        /// Gets the full caption for the figure.
        /// </summary>
        /// <param name="style">The style.</param>
        /// <returns>The caption string.</returns>
        public string GetFullCaption(ReportStyle style)
        {
            return string.Format(style.FigureTextFormatString, this.FigureNumber, this.FigureText);
        }
    }
}


text:
int main(int argc, const char **av)
{
  std::vector<const char *> args(av, av + argc);
  args.push_back("--osp:load-modules=mpi");
  args.push_back("--osp:device=mpiOffload");

  argc = args.size();
  ospInit(&argc, args.data());

  return 0;
}


text: [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "DateTimeNowAnalyzer:DateTime.Now should not be used.", Justification = "Ignore in tests")]


text:
// Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
//  This source code is licensed under both the GPLv2 (found in the
//  COPYING file in the root directory) and Apache 2.0 License
//  (found in the LICENSE.Apache file in the root directory).
//
// This file implements the "bridge" between Java and C++
// for ROCKSDB_NAMESPACE::OptimisticTransactionOptions.

#include <jni.h>

#include "include/org_rocksdb_OptimisticTransactionOptions.h"

#include "rocksdb/comparator.h"
#include "rocksdb/utilities/optimistic_transaction_db.h"

/*
 * Class:     org_rocksdb_OptimisticTransactionOptions
 * Method:    newOptimisticTransactionOptions
 * Signature: ()J
 */
jlong Java_org_rocksdb_OptimisticTransactionOptions_newOptimisticTransactionOptions(
    JNIEnv* /*env*/, jclass /*jcls*/) {
  ROCKSDB_NAMESPACE::OptimisticTransactionOptions* opts =
      new ROCKSDB_NAMESPACE::OptimisticTransactionOptions();
  return reinterpret_cast<jlong>(opts);
}

/*
 * Class:     org_rocksdb_OptimisticTransactionOptions
 * Method:    isSetSnapshot
 * Signature: (J)Z
 */
jboolean Java_org_rocksdb_OptimisticTransactionOptions_isSetSnapshot(
    JNIEnv* /*env*/, jobject /*jobj*/, jlong jhandle) {
  auto* opts =
      reinterpret_cast<ROCKSDB_NAMESPACE::OptimisticTransactionOptions*>(
          jhandle);
  return opts->set_snapshot;
}

/*
 * Class:     org_rocksdb_OptimisticTransactionOptions
 * Method:    setSetSnapshot
 * Signature: (JZ)V
 */
void Java_org_rocksdb_OptimisticTransactionOptions_setSetSnapshot(
    JNIEnv* /*env*/, jobject /*jobj*/, jlong jhandle, jboolean jset_snapshot) {
  auto* opts =
      reinterpret_cast<ROCKSDB_NAMESPACE::OptimisticTransactionOptions*>(
          jhandle);
  opts->set_snapshot = jset_snapshot;
}

/*
 * Class:     org_rocksdb_OptimisticTransactionOptions
 * Method:    setComparator
 * Signature: (JJ)V
 */
void Java_org_rocksdb_OptimisticTransactionOptions_setComparator(
    JNIEnv* /*env*/, jobject /*jobj*/, jlong jhandle,
    jlong jcomparator_handle) {
  auto* opts =
      reinterpret_cast<ROCKSDB_NAMESPACE::OptimisticTransactionOptions*>(
          jhandle);
  opts->cmp =
      reinterpret_cast<ROCKSDB_NAMESPACE::Comparator*>(jcomparator_handle);
}

/*
 * Class:     org_rocksdb_OptimisticTransactionOptions
 * Method:    disposeInternal
 * Signature: (J)V
 */
void Java_org_rocksdb_OptimisticTransactionOptions_disposeInternal(
    JNIEnv* /*env*/, jobject /*jobj*/, jlong jhandle) {
  delete reinterpret_cast<ROCKSDB_NAMESPACE::OptimisticTransactionOptions*>(
      jhandle);
}


text:
The List View
=============

.. note::

    This document is a stub representing a new work in progress. If you're reading
    this you can help contribute, **no matter what your experience level with Sonata
    is**. Check out the `issues on Github`_ for more information about how to get involved.

This document will cover the List view which you use to browse the objects in your
system. It will cover configuration of the list itself and the filters you can use
to control what's visible.

Basic configuration
-------------------

To do:

- global (yml) options that affect the list view
- a note about Routes and how disabling them disables the related action
- using configureListFields() to set which fields to display
- setting the identifier, and the available options
- options available when adding general fields, inc custom templates
- targeting submodel fields using dot-separated notation
- adding custom columns

Customising the query used to generate the list
-----------------------------------------------

You can customize the list query thanks to the ``createQuery`` method.

.. code-block:: php

    <?php

    public function createQuery($context = 'list')
    {
        $query = parent::createQuery($context);
        $query->andWhere(
            $query->expr()->eq($query->getRootAlias() . '.my_field', ':my_param')
        );
        $query->setParameter('my_param', 'my_value');
        return $query;
    }

Customising the sort order
--------------------------

Configure the default ordering in the list view
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Configuring the default ordering column can simply be achieved by overriding
the ``datagridValues`` array property. All three keys ``_page``, ``_sort_order`` and
``_sort_by`` can be omitted.

.. code-block:: php

    <?php

    use Sonata\AdminBundle\Admin\Admin;

    class PageAdmin extends Admin
    {
        // ...

        /**
         * Default Datagrid values
         *
         * @var array
         */
        protected $datagridValues = array(
            '_page' => 1,            // display the first page (default = 1)
            '_sort_order' => 'DESC', // reverse order (default = 'ASC')
            '_sort_by' => 'updated'  // name of the ordered field
                                     // (default = the model's id field, if any)

            // the '_sort_by' key can be of the form 'mySubModel.mySubSubModel.myField'.
        );

        // ...
    }

To do:

- how to sort by multiple fields (this might be a separate recipe?)

Filters
-------

To do:

- basic filter configuration and options
- how to set default filter values
- targeting submodel fields using dot-separated notation
- advanced filter options (global_search)

.. _`issues on Github`: https://github.com/sonata-project/SonataAdminBundle/issues/1519


text:
import unittest
import re
from passgen import passgen

class TestPassgen(unittest.TestCase):

    def test_errors(self):
        with self.assertRaises(ValueError):
            passgen(length=-2)

        with self.assertRaises(ValueError):
            passgen(case="spam")

        with self.assertRaises(ValueError):
            passgen(digits=False, letters=False)

    def test_case(self):
        password = passgen(case='upper')
        self.assertEqual(password, password.upper())

        password = passgen(case='lower')
        self.assertEqual(password, password.lower())

    def test_length(self):
        password = passgen(length=10)
        self.assertEqual(len(password), 10)

        password = passgen(length=15, case='upper', digits=False)
        self.assertEqual(len(password), 15)

    def test_limit_punctuation(self):
        pl = '.'
        password = passgen(letters=True, digits=False, length=6,
                           punctuation=True, limit_punctuation=pl)
        password = re.sub(r"[a-zA-Z.]", "", password)
        self.assertTrue(password == '')

    def test_only_letters(self):
        password = passgen(letters=True, digits=False)
        password = re.sub(r"[a-zA-Z]", "", password)
        self.assertTrue(password == '')

    def test_only_digits(self):
        password = passgen(letters=False, digits=True)
        password = re.sub(r"[0-9]", "", password)
        self.assertTrue(password == '')

    def test_class_always_occurs(self):
        # Generating 4-char password with all classes
        for i in range(1, 100):
            password = passgen(punctuation=True, case='both', length=4)
            password = re.sub(r"[0-9]", "", password)
            self.assertTrue(len(password) == 3)
            password = re.sub(r"[a-z]", "", password)
            self.assertTrue(len(password) == 2)
            password = re.sub(r"[A-Z]", "", password)
            self.assertTrue(len(password) == 1)

if __name__ == '__main__':
    unittest.main()


text:
Ext.define('Fixtures.ErrorStore', {
    extend: 'Fixtures.Store',
    autoLoad: false,

    proxy: {
        type: 'ajax',
        reader: {
            type: 'json',
            rootProperty: 'records'
        },
        api: {
            create: './spec/fixtures/error.json',
            read: './spec/fixtures/error.json',
            update: './spec/fixtures/error.json',
            destroy: './spec/fixtures/error.json'
        }
    }
});


text:
package org.eclipse.emf.cdo.eresource.util;

//import org.eclipse.emf.cdo.eresource.*;
import org.eclipse.emf.cdo.eresource.CDOBinaryResource;
import org.eclipse.emf.cdo.eresource.CDOFileResource;
import org.eclipse.emf.cdo.eresource.CDOResource;
import org.eclipse.emf.cdo.eresource.CDOResourceFolder;
import org.eclipse.emf.cdo.eresource.CDOResourceLeaf;
import org.eclipse.emf.cdo.eresource.CDOResourceNode;
import org.eclipse.emf.cdo.eresource.CDOTextResource;
import org.eclipse.emf.cdo.eresource.EresourcePackage;

import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.common.notify.impl.AdapterFactoryImpl;
import org.eclipse.emf.ecore.EObject;

/**
 *  The Adapter Factory for the model. It provides an adapter createXXX
 * method for each class of the model.
 *
 * @see org.eclipse.emf.cdo.eresource.EresourcePackage
 * @generated
 */
public class EresourceAdapterFactory extends AdapterFactoryImpl
{
  /**
   * The cached model package.
   *
   * @generated
   */
  protected static EresourcePackage modelPackage;

  /**
   * Creates an instance of the adapter factory.
   *
   * @generated
   */
  public EresourceAdapterFactory()
  {
    if (modelPackage == null)
    {
      modelPackage = EresourcePackage.eINSTANCE;
    }
  }

  /**
   * Returns whether this factory is applicable for the type of the object.  This implementation
   * returns true if the object is either the model's package or is an instance object of the model.
   *
   * @return whether this factory is applicable for the type of the object.
   * @generated
   */
  @Override
  public boolean isFactoryForType(Object object)
  {
    if (object == modelPackage)
    {
      return true;
    }
    if (object instanceof EObject)
    {
      return ((EObject)object).eClass().getEPackage() == modelPackage;
    }
    return false;
  }

  /**
   * The switch that delegates to the createXXX methods.
   *
   * @generated
   */
  protected EresourceSwitch<Adapter> modelSwitch = new EresourceSwitch<Adapter>()
  {
    @Override
    public Adapter caseCDOResourceNode(CDOResourceNode object)
    {
      return createCDOResourceNodeAdapter();
    }

    @Override
    public Adapter caseCDOResourceFolder(CDOResourceFolder object)
    {
      return createCDOResourceFolderAdapter();
    }

    @Override
    public Adapter caseCDOResource(CDOResource object)
    {
      return createCDOResourceAdapter();
    }

    @Override
    public Adapter caseCDOResourceLeaf(CDOResourceLeaf object)
    {
      return createCDOResourceLeafAdapter();
    }

    @Override
    public Adapter caseCDOFileResource(CDOFileResource<?> object)
    {
      return createCDOFileResourceAdapter();
    }

    @Override
    public Adapter caseCDOBinaryResource(CDOBinaryResource object)
    {
      return createCDOBinaryResourceAdapter();
    }

    @Override
    public Adapter caseCDOTextResource(CDOTextResource object)
    {
      return createCDOTextResourceAdapter();
    }

    @Override
    public Adapter defaultCase(EObject object)
    {
      return createEObjectAdapter();
    }
  };

  /**
   * Creates an adapter for the target.
   *
   * @param target
   *          the object to adapt.
   * @return the adapter for the target.
   * @generated
   */
  @Override
  public Adapter createAdapter(Notifier target)
  {
    return modelSwitch.doSwitch((EObject)target);
  }

  /**
   * Creates a new adapter for an object of class '{@link org.eclipse.emf.cdo.eresource.CDOResourceNode
   * CDO Resource Node}'.  This default implementation returns null so that we can
   * easily ignore cases; it's useful to ignore a case when inheritance will catch all the cases anyway.
   *
   * @since 2.0
   * @return the new adapter.
   * @see org.eclipse.emf.cdo.eresource.CDOResourceNode
   * @generated
   */
  public Adapter createCDOResourceNodeAdapter()
  {
    return null;
  }

  /**
   * Creates a new adapter for an object of class '{@link org.eclipse.emf.cdo.eresource.CDOResourceFolder
   * CDO Resource Folder}'.  This default implementation returns null so that we can
   * easily ignore cases; it's useful to ignore a case when inheritance will catch all the cases anyway.
   *
   * @since 2.0
   * @return the new adapter.
   * @see org.eclipse.emf.cdo.eresource.CDOResourceFolder
   * @generated
   */
  public Adapter createCDOResourceFolderAdapter()
  {
    return null;
  }

  /**
   * Creates a new adapter for an object of class '{@link org.eclipse.emf.cdo.eresource.CDOResource
   * CDO Resource}'.  This default implementation returns null so that we can easily
   * ignore cases; it's useful to ignore a case when inheritance will catch all the cases anyway.
   *
   * @return the new adapter.
   * @see org.eclipse.emf.cdo.eresource.CDOResource
   * @generated
   */
  public Adapter createCDOResourceAdapter()
  {
    return null;
  }

  /**
   * Creates a new adapter for an object of class '{@link org.eclipse.emf.cdo.eresource.CDOResourceLeaf
   * CDO Resource Leaf}'.  This default implementation returns null so that we can
   * easily ignore cases; it's useful to ignore a case when inheritance will catch all the cases anyway.
   *
   * @since 4.1
   * @return the new adapter.
   * @see org.eclipse.emf.cdo.eresource.CDOResourceLeaf
   * @generated
   */
  public Adapter createCDOResourceLeafAdapter()
  {
    return null;
  }

  /**
   * Creates a new adapter for an object of class '{@link org.eclipse.emf.cdo.eresource.CDOFileResource
   * CDO File Resource}'.  This default implementation returns null so that we can
   * easily ignore cases; it's useful to ignore a case when inheritance will catch all the cases anyway.
   *
   * @since 4.1
   * @return the new adapter.
   * @see org.eclipse.emf.cdo.eresource.CDOFileResource
   * @generated
   */
  public Adapter createCDOFileResourceAdapter()
  {
    return null;
  }

  /**
   * Creates a new adapter for an object of class '{@link org.eclipse.emf.cdo.eresource.CDOBinaryResource
   * CDO Binary Resource}'.  This default implementation returns null so that we can
   * easily ignore cases; it's useful to ignore a case when inheritance will catch all the cases anyway.
   *
   * @since 4.1
   * @return the new adapter.
   * @see org.eclipse.emf.cdo.eresource.CDOBinaryResource
   * @generated
   */
  public Adapter createCDOBinaryResourceAdapter()
  {
    return null;
  }

  /**
   * Creates a new adapter for an object of class '{@link org.eclipse.emf.cdo.eresource.CDOTextResource
   * CDO Text Resource}'.  This default implementation returns null so that we can
   * easily ignore cases; it's useful to ignore a case when inheritance will catch all the cases anyway.
   *
   * @since 4.1
   * @return the new adapter.
   * @see org.eclipse.emf.cdo.eresource.CDOTextResource
   * @generated
   */
  public Adapter createCDOTextResourceAdapter()
  {
    return null;
  }

  /**
   * Creates a new adapter for the default case.  This default implementation returns null.
   *
   * @return the new adapter.
   * @generated
   */
  public Adapter createEObjectAdapter()
  {
    return null;
  }

} // EresourceAdapterFactory


text:
package org.sakaiproject.content.impl.serialize.impl.test;

import java.util.GregorianCalendar;
import java.util.TimeZone;

import org.sakaiproject.time.api.Time;
import org.sakaiproject.time.api.TimeBreakdown;
import org.sakaiproject.time.api.TimeRange;
import org.sakaiproject.time.api.TimeService;

/**
 * @author ieb
 *
 */
public class MockTimeService implements TimeService
{

	/* (non-Javadoc)
	 * @see org.sakaiproject.time.api.TimeService#clearLocalTimeZone(java.lang.String)
	 */
	public boolean clearLocalTimeZone(String userId)
	{
		// TODO Auto-generated method stub
		return false;
	}

	/* (non-Javadoc)
	 * @see org.sakaiproject.time.api.TimeService#different(org.sakaiproject.time.api.Time, org.sakaiproject.time.api.Time)
	 */
	public boolean different(Time a, Time b)
	{
		// TODO Auto-generated method stub
		return false;
	}

	/* (non-Javadoc)
	 * @see org.sakaiproject.time.api.TimeService#getCalendar(java.util.TimeZone, int, int, int, int, int, int, int)
	 */
	public GregorianCalendar getCalendar(TimeZone zone, int year, int month, int day,
			int hour, int min, int sec, int ms)
	{
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see org.sakaiproject.time.api.TimeService#getLocalTimeZone()
	 */
	public TimeZone getLocalTimeZone()
	{
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see org.sakaiproject.time.api.TimeService#newTime()
	 */
	public Time newTime()
	{
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see org.sakaiproject.time.api.TimeService#newTime(long)
	 */
	public Time newTime(long value)
	{
		return new MockTime(value);
	}

	/* (non-Javadoc)
	 * @see org.sakaiproject.time.api.TimeService#newTime(java.util.GregorianCalendar)
	 */
	public Time newTime(GregorianCalendar cal)
	{
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see org.sakaiproject.time.api.TimeService#newTimeBreakdown(int, int, int, int, int, int, int)
	 */
	public TimeBreakdown newTimeBreakdown(int year, int month, int day, int hour,
			int minute, int second, int millisecond)
	{
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see org.sakaiproject.time.api.TimeService#newTimeGmt(java.lang.String)
	 */
	public Time newTimeGmt(String value)
	{
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see org.sakaiproject.time.api.TimeService#newTimeGmt(int, int, int, int, int, int, int)
	 */
	public Time newTimeGmt(int year, int month, int day, int hour, int minute,
			int second, int millisecond)
	{
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see org.sakaiproject.time.api.TimeService#newTimeGmt(org.sakaiproject.time.api.TimeBreakdown)
	 */
	public Time newTimeGmt(TimeBreakdown breakdown)
	{
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see org.sakaiproject.time.api.TimeService#newTimeLocal(int, int, int, int, int, int, int)
	 */
	public Time newTimeLocal(int year, int month, int day, int hour, int minute,
			int second, int millisecond)
	{
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see org.sakaiproject.time.api.TimeService#newTimeLocal(org.sakaiproject.time.api.TimeBreakdown)
	 */
	public Time newTimeLocal(TimeBreakdown breakdown)
	{
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see org.sakaiproject.time.api.TimeService#newTimeRange(org.sakaiproject.time.api.Time, org.sakaiproject.time.api.Time, boolean, boolean)
	 */
	public TimeRange newTimeRange(Time start, Time end, boolean startIncluded,
			boolean endIncluded)
	{
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see org.sakaiproject.time.api.TimeService#newTimeRange(java.lang.String)
	 */
	public TimeRange newTimeRange(String value)
	{
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see org.sakaiproject.time.api.TimeService#newTimeRange(org.sakaiproject.time.api.Time)
	 */
	public TimeRange newTimeRange(Time startAndEnd)
	{
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see org.sakaiproject.time.api.TimeService#newTimeRange(long, long)
	 */
	public TimeRange newTimeRange(long start, long duration)
	{
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see org.sakaiproject.time.api.TimeService#newTimeRange(org.sakaiproject.time.api.Time, org.sakaiproject.time.api.Time)
	 */
	public TimeRange newTimeRange(Time start, Time end)
	{
		// TODO Auto-generated method stub
		return null;
	}

}


text:
Linguagens de Programação 2 - Campus Engenho Novo II
=======

Esse é o repositório da Disciplina de Linguagens de Programação II.

  * **Campus:** Engenho Novo II
  * **Professor:** Francisco Vianna
  *  **Turma:** IN207
  *  **Ano Letivo**: 2015

Aqui vocês encontrarão todo o material da disciplina, de exercícios, desafios, gabaritos, e demais materias produzidos por nós durante as aulas.

Cada um de vocês terá um repositório próprio, como esse, para onde serão enviadas as soluções de vocês para os problemas propostos ao longo do ano. Sendo assim, nossa disciplina será pautada por algumas regras, a saber:

Regras
======

Regra Nº1: Primeiras coisas primeiro
-------------------------------------

Ninguém pode alegar o desconhecimento das regras que vão guiar a utilização dos repositórios.

Regra Nº2: O Respeito e a Honestidade
-------------------------------------

**Cada usuário só edita e envia código para a seu repositório.**. Não importa o que vocês façam, não é possível deletar nada que foi feito por ninguém. O histórico de **tudo** é mantido e nem eu mesmo posso mudar isso. Todas as ações realizadas no GitHub são gravadas com o nome do usuário que as realizou. Sendo assim, espero que ninguém tente. Caso isso aconteça, serei obrigado a tomar alguma atitude. Não me forcem a isso, por favor.

**É muito simples** pra mim saber quem faz o quê aqui. Se eu entrar no repositório de um aluno e vir que há algo feito por outro, vou procurar para saber o por quê. Mas ajudar seu colega não é algo ruim, então leia a *regra 3*.

Regra Nº 3: Colaboração é bom
-----------------------------

A alma do GitHub é a colaboração. Foi pra isso que ele foi criado. Vocês não só podem como devem se ajudar e trocar experiências. **Mas cópia de código é inaceitável**. Existem muitas formas de descobrir se vocês estão copiando código uns dos outros além da minha inspeção. Tenho algumas ferramentas que são capazes de detectar arquivos parecidos. Mais uma vez, **conto com vocês pra não termos problemas**.

Vocês vão perceber que podem acessar livremente tudo que seus colegas estão fazendo. Podem fazer isso se quiserem inspiração pra resolver um problema. **Mais uma vez, espero que vocês se esforcem pra realizar os exercícios.** Procurem seus colegas ou a mim para tirar dúvidas.

**Vocês não aprenderão a programar sem meter a mão na massa. Isso eu garanto a vocês.**

Regra Nº4: Siga as instruções
-----------------------------

Sempre que tivermos uma nova atividade, eu darei instruções dos **nomes dos diretórios** que quero que vocês criem. Isso vai ser importante pra nossa organização. Não deixem de fazer exatamente como eu pedir.

Regra Nº5: Prazos, prazos, prazos
---------------------------------

Como todo o resto, as datas do que vocês fazem também é guardada. Então se alguma atividade tiver prazo, não adianta mandar depois achando que eu não vou ver. Só pegarei o código do repositório até a data limite de entrega. **Exceções podem ser discutidas diretamente comigo**.

Regra Nº6:
----------

A Regra 2 é a mais importante.

Regra Nº7:
----------

Não tem Regra 7.


text:
=======  ============================================
SEP      1
Title    API for populating item fields (comparison)
Author   Ismael Carnales, Pablo Hoffman, Daniel Grana
Created  2009-07-19
Status   Obsoleted by :ref:`sep-008`
=======  ============================================

=====================================================
SEP-001 - API for populating item fields (comparison)
=====================================================

This page shows different usage scenarios for the two new proposed API for
populating item field values (which will replace the old deprecated !RobustItem
API)  and compares them. One of these will be chosen as the recommended (and
supported) mechanism in Scrapy 0.7.

Candidates and their API
========================

RobustItem (old, deprecated)
----------------------------

- ``attribute(field_name, selector_or_value, **modifiers_and_adaptor_args)``

.. note:: ``attribute()`` modifiers (like ``add=True``) are passed together
          with adaptor args as keyword arguments (this is ugly)

ItemForm
--------

- ``__init__(response, item=None, **adaptor_args)``
   - instantiate an ``ItemForm`` with a item instance with predefined adaptor arguments
- ``__setitem__(field_name, selector_or_value)``
   - set field value
- ``__getitem__(field_name)``
   - return the "computed" value of a field (the one that would be set to the item).
     returns ``None`` if not set.
- ``get_item()``
  - return the item populated with the data provided so far

ItemBuilder
-----------

- ``__init__(response, item=None, **adaptor_args)``
   - instantiate an ``ItemBuilder`` with predefined adaptor arguments
- ``add_value(field_name, selector_or_value, **adaptor_args)``
   - add value to field
- ``replace_value(field_name, selector_or_value, **adaptor_args)``
   - replace existing field value
- ``get_value(field_name)``
   - return the "computed" value of a field (the one that would be set to the
     item). returns ``None`` if not set.
- ``get_item()``
   - return the item populated with the data provided so far

Pros and cons of each candidate
===============================

ItemForm
--------

Pros:
- same API used for Items (see https://docs.scrapy.org/en/latest/topics/items.html)
- some people consider setitem API more elegant than methods API

Cons:
- doesn't allow passing run-time arguments to adaptors on assign, you have to
  override the adaptors for your spider if you need specific parameters, which
  can be an overhead. Example:

Neutral:
- solves the add=True problem using standard ``__add__`` and ``list.append()`` method

ItemBuilder
-----------

Pros:
- allows passing run-time arguments to adaptors on assigned

Cons:
- some people consider setitem API more elegant than methods API

Neutral:
- solves the "add=True" problem by implementing different methods per action
  (replacing or adding)

Usage Scenarios for each candidate
==================================

Defining adaptors
-----------------

ItemForm
~~~~~~~~

::

   #!python
   class NewsForm(ItemForm):
       item_class = NewsItem

       url = adaptor(extract, remove_tags(), unquote(), strip)
       headline = adaptor(extract, remove_tags(), unquote(), strip)

ItemBuilder
~~~~~~~~~~~

::

   #!python
   class NewsBuilder(ItemBuilder):
       item_class = NewsItem

       url = adaptor(extract, remove_tags(), unquote(), strip)
       headline = adaptor(extract, remove_tags(), unquote(), strip)

Creating an Item
----------------

ItemForm
~~~~~~~~

::

   #!python
   ia = NewsForm(response)
   ia['url'] = response.url
   ia['headline'] = x.x('//h1[@class="headline"]')

   # if we want to add another value to the same field
   ia['headline'] += x.x('//h1[@class="headline2"]')

   # if we want to replace the field value other value to the same field
   ia['headline'] = x.x('//h1[@class="headline3"]')

   return ia.get_item()

ItemBuilder
~~~~~~~~~~~

::

   #!python
   il = NewsBuilder(response)
   il.add_value('url', response.url)
   il.add_value('headline', x.x('//h1[@class="headline"]'))

   # if we want to add another value to the same field
   il.add_value('headline', x.x('//h1[@class="headline2"]'))

   # if we want to replace the field value other value to the same field
   il.replace_value('headline', x.x('//h1[@class="headline3"]'))

   return il.get_item()

Using different adaptors per Spider/Site
----------------------------------------

ItemForm
~~~~~~~~

::

   #!python
   class SiteNewsFrom(NewsForm):
       published = adaptor(HtmlNewsForm.published, to_date('%d.%m.%Y'))

ItemBuilder
~~~~~~~~~~~

::

   #!python
   class SiteNewsBuilder(NewsBuilder):
       published = adaptor(HtmlNewsBuilder.published, to_date('%d.%m.%Y'))

Check the value of an item being-extracted
------------------------------------------

ItemForm
~~~~~~~~

::

   #!python
   ia = NewsForm(response)
   ia['headline'] = x.x('//h1[@class="headline"]')
   if not ia['headline']:
       ia['headline'] = x.x('//h1[@class="title"]')

ItemBuilder
~~~~~~~~~~~

::

   #!python
   il = NewsBuilder(response)
   il.add_value('headline', x.x('//h1[@class="headline"]'))
   if not nf.get_value('headline'):
       il.add_value('headline', x.x('//h1[@class="title"]'))

Adding a value to a list attribute/field
----------------------------------------

ItemForm
~~~~~~~~

::

   #!python
   ia['headline'] += x.x('//h1[@class="headline"]')

ItemBuilder
~~~~~~~~~~~

::

   #!python
   il.add_value('headline', x.x('//h1[@class="headline"]'))

Passing run-time arguments to adaptors
--------------------------------------

ItemForm
~~~~~~~~

::

   #!python
   # Only approach is passing arguments when instantiating the form
   ia = NewsForm(response, default_unit='cm')
   ia['width'] = x.x('//p[@class="width"]')

ItemBuilder
~~~~~~~~~~~

::

   #!python
   il.add_value('width', x.x('//p[@class="width"]'), default_unit='cm')

   # an alternative approach (more efficient)
   il = NewsBuilder(response, default_unit='cm')
   il.add_value('width', x.x('//p[@class="width"]'))

Passing run-time arguments to adaptors (same argument name)
-----------------------------------------------------------

ItemForm
~~~~~~~~

::

   #!python
   class MySiteForm(ItemForm):
       witdth = adaptor(ItemForm.witdh, default_unit='cm')
       volume = adaptor(ItemForm.witdh, default_unit='lt')

   ia['width'] = x.x('//p[@class="width"]')
   ia['volume'] = x.x('//p[@class="volume"]')

   # another example passing parametes on instance
   ia = NewsForm(response, encoding='utf-8')
   ia['name'] = x.x('//p[@class="name"]')

ItemBuilder
~~~~~~~~~~~

::

   #!python
   il.add_value('width', x.x('//p[@class="width"]'), default_unit='cm')
   il.add_value('volume', x.x('//p[@class="volume"]'), default_unit='lt')