<commit_before>/* */ //
undefined null//{{{
Number String Boolean
Array Object Function
RegExp Date Math JSON
Infinity NaN "" '' true false
[,] {:,} function() {}
[] . ()
/ /gi
//}}}
++ --//{{{
+ -
~ & | ^ << >> >>>
! && ||
* / % + -
< <= > >= != == !== ===
?:
=
isNaN()
isFinite()
parseInt()
parseFloat()
encodeURI()
decodeURI()
encodeURIComponent()
decodeURIComponent()
new
delete
typeof
instanceof
//}}}
; {}//{{{
for (;;) {}
for (in) {}
while () {}
do {} while ();
if () {} else {}
switch () {case: default:}
break continue label:
with () {}
try{}catch(){}finally{}

var function() {return}
arguments this
	callee
	caller
	length
//}}}

Number//{{{
	EPSILON NaN
	MAX_VALUE MAX_SAFE_INTEGER
	MIN_VALUE MIN_SAFE_INTEGER
	NEGATIVE_INFINITY
	POSITIVE_INFINITY
	isNaN() isFinite()
	isInteger() isSafeInteger()
	parseInt() parseFloat()
	//}}}
number//{{{
	toFixed()
	toPrecision()
	toExponential()
//}}}
String//{{{
	fromCharCode()
//}}}
string//{{{
	length concat() trim()
	charAt() charCodeAt()
	indexOf() lastIndexOf()
	toUpperCase() toLowerCase()
	slice() substr() substring()
	search() match() replace() split()
	anchor() link()
	big() small()
	bold() italics()
	sub() sup()
//}}}
Boolean//{{{
//}}}
boolean//{{{
//}}}
Array//{{{
	isArray()
//}}}
array//{{{
	length
	join()
	push() pop()
	shift() unshift()
	reverse() sort()
	concat() slice()
	splice()
	indexOf() lastIndexOf()
	every() some()
	map() filter()
	forEach()
	reduce() reduceRight()
//}}}
Object//{{{
	defineProperty()
	defineProperties()
	getOwnPropertyNames()
	getOwnPropertySymbols()
	getOwnPropertyDescriptor()
	getPrototypeOf() setPrototypeOf()
	freeze() seal() preventExtensions()
	isFrozen() isSealed() isExtensible()
//}}}
object//{{{
	constructor isPrototypeOf()
	hasOwnPorperty() propertyIsEnumrable()
	toLocaleString() toString() valueOf()
//}}}
Function//{{{
//}}}
function//{{{
	name length arguments caller
	apply() call() bind()
	prototype
//}}}
RegExp//{{{
//}}}
regexp//{{{
	global ignorecase multiline
	source lastIndex
	test() exec() complie()
//}}}
Date//{{{
	now() parse() UTC()
//}}}
date//{{{
	getFullYear() getMonth() getDate() getDay()
	getHours() getMinutes() getSeconds() getMilliseconds()
	getTime() getTimezoneOffset()
//}}}
Math//{{{
	PI E LN10 LN2 LOG2E LOG10E SQRT1_2 SQRT2
	sin() asin() sinh() asinh()
	cos() acos() cosh() acosh()
	tan() atan() tanh() atanh()
	atan2()
	exp() expm1()
	log() log2() log10() log1p()
	pow() sqrt() cbrt()
	clz32() hypot()
	max() min() imul()
	abs() sign() fround()
	ceil() floor() round() trunc()
	random()
//}}}
JSON//{{{
	parse() stringify()
//}}}
Error//{{{
//}}}

window//{{{
	top parent self
	open() close() opener
	screenLeft(screenX)
	screenTop(screenY)
	moveTo() moveBy()
	innerWidth innerHeight
	outerWidth outerHeight
	resizeTo() resizeBy()
	setTimeout() clearTimeout()
	setInterval() clearInterval()
	alert() confirm() prompt()
	print() find()

	onload onunload
	onabort onerror
	onresize onscroll
	onselect

	location//{{{
		assign() replace() reload()
		href protocol host
		hostname port search hash
//}}}
	history//{{{
		length go() back() forward()
//}}}
	navigator//{{{
		appName appCodeName appVersion
		platform userAgent plugins[]
//}}}
	screen//{{{
		availWidth availHeight colorDepth width height
//}}}
	document//{{{
		URL domain referer
		documentElement title head body
		anchors[] links[] forms[] images[]

		createElement()
		createTextNode()
		createComment()
		createDocumentFragment()
		createAttribute()

		open() close()
		write() writeln()

		readyState
		compatMode
		hasFocus()
		activeElement
		implementation.hasFeature("Core", "1.0");
//}}}
	element//{{{
		id dir title
		tagName className
		classList
			add()
			remove()
			toggle()
			contains()
		dataset
		innerHTML outerHTML insertAdjacentHTML()
		attributes
			getNamedItem()
			removeNamedItem()
			setNamedItem()
			item()
		getAttribute()
		setAttribute()
		removeAttribute()

		setAttributeNode()
		getAttributeNode()

		getElementById()
		getElementByName()
		getElementsByTagName()
		getElementsByClassName()

		querySelector()
		querySelectorAll()

		children contains()
		childElementCount
		firstElementChild
		lastElementChild
		previousElementSibling
		nextElementSibling

		focus()
		scrollIntoView()

		addEventListener()/attachEvent()
		removeEventListener()/detachEvent()
		onclick
		onblur onfocus onfocusin onfocusout
		onmouseover
		onmousemove
		onmouseout
		onmousedown
		onmouseup
		onclick
		ondbclick
		onmouseenter
		onmouseleave
		onmousewheel

		onkeydown
		onkeypress
		onkeyup
		ontouchstart
		ontouchmove
		ontouchend

		canvas
			toDataURL()
			getContext()
				createLinearGradient().addColorStop()
				createRadialGradient().addColorStop()
				createPattern()

				strokeStyle fillStyle lineWidth lineCap lineJoin
				shadowColor shadowOffsetX shadowOffsetY shadowBlur
				rotate() scale() translate() transform() setTransform()
				save() restore()

				beginPath() closePath() stroke() fill() clip()
	 			moveTo() lineTo() bezieCurveTo() arcTo() arc() rect()

				strokeRect() fillRect() clearRect()
				strokeText() fillText()
				drawImage() toDataURL()
				getImageData()

//}}}
	event//{{{
		bubbles stopPropagation()/cancelBubble
		cancelable preventDefault()/returnValue defaultPrevented
		type target/srcElement currentTarget
		detail eventPhase view
		clientX
		clientY
		pageX
		pageY
		screenX
		screenY
		relatedTarget/toElement/fromElement
		button
		wheelDelta
		shiftKey
		ctrlKey
		altKey
		metaKey
//}}}
	HTMLCollection//{{{
		length [] item() namedItem()
//}}}
	NodeList//{{{
		length [] item()
//}}}
	Node//{{{
		nodeType nodeName nodeValue
		ownerDocument parentNode childNodes[] hasChildNodes()
		firstChild lastChild previousSibling nextSibling
		appendChild() removeChild() replaceChild() insertBefore()
		cloneNode()
//}}}
//}}}
jQuery

$(",")

$(">")
$(" ")
$("+")
$("~")

$("#")
$("div")
$(".")
$(":not")
$(":has")
$(":contains")
$(":lang")
$(":target")
$(":root")
$(":empty")
$(":parent")
$(":header")

$(":focus")
$(":input")
$(":button")
$(":enabled")
$(":disabled")
$(":checked")
$(":selected")

$(":text")

$(":first")
$(":last")
$(":lt")
$(":gt")
$(":eq")
$(":odd")
$(":even")
$(":nth-child")

$("[]")
$("[=]")
$("[!=]")
$("[^=]")
$("[$=]")
$("[*=]")
$("[|=]")
$("[~=]")

$().filter().find().not().is()
.parent().next().prev().children()
.end()

$(function(){}).ready()
$().on("", function(){}).off().one().trigger()
.load().focus().blur().click().hover()
event target stopPropagation() preventDefault() return false;
$().addClass().removeClass().toggleClass().hasClass()
$().css().show().hide().toggle()
	.fadeIn().fadeOut().fadeToggle()
	.slideDown().slideUp().slideToggle()
	.animate()
$().text()

global

1990
1991  ARM   Linux  HTTP
1994                        linux 1.0
1995  IE1   win95           linux 1.2
1995  IE2
1996  IE3                   linux 2.0
1997  IE4
1998        win98
1999  IE5          HTML4    linux 2.2
2001  IE6   winXP  MacOSX   linux 2.4
2003               Safari   linux 2.6
2004               FireFox
2006  IE7		   jQuery
2007               HTML5
2008               Chrome
2009  IE8   win7
2011  IE9          wechat   linux 3.0
2012  IE10  win8   go1.0
2013  IE11  win81
2015        win10           linux 4.0

2007               iOS1
2008  Andorid1.0   iOS2
2009  Andorid1.1   iOS3
2009  Andorid2.0
2009  Andorid2.1
2010  Andorid2.2   iOS4
2011  Andorid3.0   iOS5
2011  Andorid4.0
2012  Ahdorid4.1   iOS6
2012  Ahdorid4.2
2013  Ahdorid4.3   iOS7
2014  Ahdorid5.0   iOS8
2015  Ahdorid6.0   iOS9
2016  Ahdorid7.0   iOS10
<commit_msg>mac add mp<commit_after>/* */ //
undefined null//{{{
Number String Boolean
Array Object Function
RegExp Date Math JSON
Infinity NaN "" '' true false
[,] {:,} function() {}
[] . ()
/ /gi
//}}}
++ --//{{{
+ -
~ & | ^ << >> >>>
! && ||
* / % + -
< <= > >= != == !== ===
?:
=
isNaN()
isFinite()
parseInt()
parseFloat()
encodeURI()
decodeURI()
encodeURIComponent()
decodeURIComponent()
new
delete
typeof
instanceof
//}}}
; {}//{{{
for (;;) {}
for (in) {}
while () {}
do {} while ();
if () {} else {}
switch () {case: default:}
break continue label:
with () {}
try{}catch(){}finally{}

var function() {return}
arguments this
	callee
	caller
	length
//}}}

Number//{{{
	EPSILON NaN
	MAX_VALUE MAX_SAFE_INTEGER
	MIN_VALUE MIN_SAFE_INTEGER
	NEGATIVE_INFINITY
	POSITIVE_INFINITY
	isNaN() isFinite()
	isInteger() isSafeInteger()
	parseInt() parseFloat()
	//}}}
number//{{{
	toFixed()
	toPrecision()
	toExponential()
//}}}
String//{{{
	fromCharCode()
//}}}
string//{{{
	length concat() trim()
	charAt() charCodeAt()
	indexOf() lastIndexOf()
	toUpperCase() toLowerCase()
	slice() substr() substring()
	search() match() replace() split()
	anchor() link()
	big() small()
	bold() italics()
	sub() sup()
//}}}
Boolean//{{{
//}}}
boolean//{{{
//}}}
Array//{{{
	isArray()
//}}}
array//{{{
	length
	join()
	push() pop()
	shift() unshift()
	reverse() sort()
	concat() slice()
	splice()
	indexOf() lastIndexOf()
	every() some()
	map() filter()
	forEach()
	reduce() reduceRight()
//}}}
Object//{{{
	defineProperty()
	defineProperties()
	getOwnPropertyNames()
	getOwnPropertySymbols()
	getOwnPropertyDescriptor()
	getPrototypeOf() setPrototypeOf()
	freeze() seal() preventExtensions()
	isFrozen() isSealed() isExtensible()
//}}}
object//{{{
	constructor isPrototypeOf()
	hasOwnPorperty() propertyIsEnumrable()
	toLocaleString() toString() valueOf()
//}}}
Function//{{{
//}}}
function//{{{
	name length arguments caller
	apply() call() bind()
	prototype
//}}}
RegExp//{{{
//}}}
regexp//{{{
	global ignorecase multiline
	source lastIndex
	test() exec() complie()
//}}}
Date//{{{
	now() parse() UTC()
//}}}
date//{{{
	getFullYear() getMonth() getDate() getDay()
	getHours() getMinutes() getSeconds() getMilliseconds()
	getTime() getTimezoneOffset()
//}}}
Math//{{{
	PI E LN10 LN2 LOG2E LOG10E SQRT1_2 SQRT2
	sin() asin() sinh() asinh()
	cos() acos() cosh() acosh()
	tan() atan() tanh() atanh()
	atan2()
	exp() expm1()
	log() log2() log10() log1p()
	pow() sqrt() cbrt()
	clz32() hypot()
	max() min() imul()
	abs() sign() fround()
	ceil() floor() round() trunc()
	random()
//}}}
JSON//{{{
	parse() stringify()
//}}}
Error//{{{
//}}}

window//{{{
	top parent self
	open() close() opener
	screenLeft(screenX)
	screenTop(screenY)
	moveTo() moveBy()
	innerWidth innerHeight
	outerWidth outerHeight
	resizeTo() resizeBy()
	setTimeout() clearTimeout()
	setInterval() clearInterval()
	alert() confirm() prompt()
	print() find()

	onload onunload
	onabort onerror
	onresize onscroll
	onselect

	location//{{{
		assign() replace() reload()
		href protocol host
		hostname port search hash
//}}}
	history//{{{
		length go() back() forward()
//}}}
	navigator//{{{
		appName appCodeName appVersion
		platform userAgent plugins[]
//}}}
	screen//{{{
		availWidth availHeight colorDepth width height
//}}}
	document//{{{
		URL domain referer
		documentElement title head body
		anchors[] links[] forms[] images[]

		createElement()
		createTextNode()
		createComment()
		createDocumentFragment()
		createAttribute()

		open() close()
		write() writeln()

		readyState
		compatMode
		hasFocus()
		activeElement
		implementation.hasFeature("Core", "1.0");
//}}}
	element//{{{
		id dir title
		tagName className
		classList
			add()
			remove()
			toggle()
			contains()
		dataset
		innerHTML outerHTML insertAdjacentHTML()
		attributes
			getNamedItem()
			removeNamedItem()
			setNamedItem()
			item()
		getAttribute()
		setAttribute()
		removeAttribute()

		setAttributeNode()
		getAttributeNode()

		getElementById()
		getElementByName()
		getElementsByTagName()
		getElementsByClassName()

		querySelector()
		querySelectorAll()

		children contains()
		childElementCount
		firstElementChild
		lastElementChild
		previousElementSibling
		nextElementSibling

		focus()
		scrollIntoView()

		addEventListener()/attachEvent()
		removeEventListener()/detachEvent()
		onclick
		onblur onfocus onfocusin onfocusout
		onmouseover
		onmousemove
		onmouseout
		onmousedown
		onmouseup
		onclick
		ondbclick
		onmouseenter
		onmouseleave
		onmousewheel

		onkeydown
		onkeypress
		onkeyup
		ontouchstart
		ontouchmove
		ontouchend

		canvas
			toDataURL()
			getContext()
				createLinearGradient().addColorStop()
				createRadialGradient().addColorStop()
				createPattern()

				strokeStyle fillStyle lineWidth lineCap lineJoin
				shadowColor shadowOffsetX shadowOffsetY shadowBlur
				rotate() scale() translate() transform() setTransform()
				save() restore()

				beginPath() closePath() stroke() fill() clip()
	 			moveTo() lineTo() bezieCurveTo() arcTo() arc() rect()

				strokeRect() fillRect() clearRect()
				strokeText() fillText()
				drawImage() toDataURL()
				getImageData()

//}}}
	event//{{{
		bubbles stopPropagation()/cancelBubble
		cancelable preventDefault()/returnValue defaultPrevented
		type target/srcElement currentTarget
		detail eventPhase view
		clientX
		clientY
		pageX
		pageY
		screenX
		screenY
		relatedTarget/toElement/fromElement
		button
		wheelDelta
		shiftKey
		ctrlKey
		altKey
		metaKey
//}}}
	HTMLCollection//{{{
		length [] item() namedItem()
//}}}
	NodeList//{{{
		length [] item()
//}}}
	Node//{{{
		nodeType nodeName nodeValue
		ownerDocument parentNode childNodes[] hasChildNodes()
		firstChild lastChild previousSibling nextSibling
		appendChild() removeChild() replaceChild() insertBefore()
		cloneNode()
//}}}
//}}}

wechat
app.wxss
app.json//{{{
{
	"pages":["pages/index/index"],
	"window":{},
	"tabBar":{},
	"network":{},
	"debug":true,
}
//}}}
app.js//{{{
	App({onLaunch({path,query,scene,shareTicket,referrerInfo}),onShow({}),onHide,onError})
	getApp()

	wx.getSystemInfo()
	wx.getSystemInfoSync()
//}}}
pages/index/index.wxml//{{{
	<scroll-view></scroll-view>
	<swiper> <swiper-item> </swiper-item> </swiper>
	<movable-area> <movable-view> <movable-view> </movable-area>
	<icon/>
	<text></text>
	<progress/>
	<button></button>
	<checkbox/>
	<radio/>
	<slider/>
	<switch/>
	<textarea>
	<navigator> </navigator>
	<picker> </picker>
	<picker-view> </picker-view>
	<form> </form>
	<input/>
	<label> </label>

	<audio> </audio>
	<image> </image>
	<video> </video>
	<map> </map>
	<canvas></canvas>

	<view hover-class="" hover-start-time="" hover-stay-time=""></view>

	<view bindtap=""></view>
	<view catchtap=""></view>

	<view wx:for="{{}}" wx:for-index="" wx:for-item="" wx:key="*this">{{}}</view>

	<view wx:if="{{}}">{{}}</view>
	<view wx:elif="{{}}">{{}}</view>
	<view wx:else="{{}}">{{}}</view>

	<block></block>

	<template name=""></template>
	<template is="" data="{{...}}"></template>
	<import src="">
	<include src="">
//}}}
pages/index/index.wxss//{{{
{
	flex-direction:row;
	flex-direction:column;
}//}}}
pages/index/index.json//{{{
{
	"navigationBarTitleText":""
}
//}}}
pages/index/index.js//{{{
	Page({data,viewTap({}),onLoad(),onShow(),onReady,onHide,onUnload,onPullDownRefresh,onReachBottom,onShareAppMessage,route})
	getCurrentPages().setData()

	wx.navigateTo()
	wx.redirectTo()
	wx.navigateBack()
	wx.switchTab()
	wx.reLaunch()

	wx.request({url,data,header,method,dataType,success({data,statusCode,header}),fail,complete})
	wx.uploadFile({url,filePath,name,header,formData,success({data,statusCode}),fail,complete})
	wx.downloadFile({url,header,success({tempFilePath}),fail,complete})
	wx.connectSocket({url,data,header,method,success,fail,complete})
	wx.onSocketOpen(function(){})
	wx.onSocketError(function(){})
	wx.sendSocketMessage({data,success,fail,complete})
	wx.onSocketMessage(({data}))
	wx.closeSocket()
	wx.onSocketClose()

	wx.chooseImage({count,sizeType,sourceType,success({tempFilePaths,tempFiles}),fail,complete})
	wx.previewImage({count,urls,success({tempFilePaths,tempFiles}),fail,complete})
	wx.getImageInfo({src,success({width,height,path}),fail,complete})
	wx.saveImageToPhotoAlbum({filePath,success({errMsg}),fail,complete})

	wx.startRecord({success({tempFilePath}),fail,complete})
	wx.stopRecord()
	wx.playVoice({filePath,success,fail,complete})
	wx.stopVoice()
	wx.pauseVoice()

	wx.saveFile({tempFilePath,success({savedFilePath}),fail,complete})
	wx.getSavedFileList({success({errMsg,fileList:[{filePath,createTime,size}]}),fail,complete})
	wx.getSavedFileInfo({filePath,success({filePath,createTime,size}),fail,complete})
	wx.removeSavedFileInfo({filePath,success,fail,complete})
	wx.openDocument({filePath,success,fail,complete})

	wx.setStorage({key,data,success,fail,complete})
	wx.setStorageSync({key,data})
	wx.getStorage({key,success({data}),fail,complete})
	wx.getStorageSync({key})
	wx.getStorageInfo({success({keys,currentSize,limitSize}),fail,complete})
	wx.getStorageInfoSync()
	wx.removeStorage({key,success({data}),fail,complete})
	wx.removeStorageSync({key})
	wx.clearStorage()
	wx.clearStorageSync()

	wx.getLocation({type,success({latitude,longitude,speed,accuracy,altitude,verticalAccuracy,horizontalAccuracy}),fail,complete})
	wx.chooseLocation({success({name,address,latitude,longitude}),cancelfail,complete})
	wx.openLocation({latitude,longitude,scale,name,address,success,cancelfail,complete})

//}}}
utils/utils.js//{{{
	module.exports
	require("")
//}}}

wxml
wxss
json
	pages[]
	window{}
	tabBar{}
	networkTimeout
	debug
js
	getApp()
	Page({})

jQuery

$(",")

$(">")
$(" ")
$("+")
$("~")

$("#")
$("div")
$(".")
$(":not")
$(":has")
$(":contains")
$(":lang")
$(":target")
$(":root")
$(":empty")
$(":parent")
$(":header")

$(":focus")
$(":input")
$(":button")
$(":enabled")
$(":disabled")
$(":checked")
$(":selected")

$(":text")

$(":first")
$(":last")
$(":lt")
$(":gt")
$(":eq")
$(":odd")
$(":even")
$(":nth-child")

$("[]")
$("[=]")
$("[!=]")
$("[^=]")
$("[$=]")
$("[*=]")
$("[|=]")
$("[~=]")

$().filter().find().not().is()
.parent().next().prev().children()
.end()

$(function(){}).ready()
$().on("", function(){}).off().one().trigger()
.load().focus().blur().click().hover()
event target stopPropagation() preventDefault() return false;
$().addClass().removeClass().toggleClass().hasClass()
$().css().show().hide().toggle()
	.fadeIn().fadeOut().fadeToggle()
	.slideDown().slideUp().slideToggle()
	.animate()
$().text()

global

1990
1991  ARM   Linux  HTTP
1994                        linux 1.0
1995  IE1   win95           linux 1.2
1995  IE2
1996  IE3                   linux 2.0
1997  IE4
1998        win98
1999  IE5          HTML4    linux 2.2
2001  IE6   winXP  MacOSX   linux 2.4
2003               Safari   linux 2.6
2004               FireFox
2006  IE7		   jQuery
2007               HTML5
2008               Chrome
2009  IE8   win7
2011  IE9          wechat   linux 3.0
2012  IE10  win8   go1.0
2013  IE11  win81
2015        win10           linux 4.0

2007               iOS1
2008  Andorid1.0   iOS2
2009  Andorid1.1   iOS3
2009  Andorid2.0
2009  Andorid2.1
2010  Andorid2.2   iOS4
2011  Andorid3.0   iOS5
2011  Andorid4.0
2012  Ahdorid4.1   iOS6
2012  Ahdorid4.2
2013  Ahdorid4.3   iOS7
2014  Ahdorid5.0   iOS8
2015  Ahdorid6.0   iOS9
2016  Ahdorid7.0   iOS10
<|endoftext|>


<commit_before>// OpenWrap
// Author: nmaguiar@gmail.com
// Dev

OpenWrap.dev = function() {
	return ow.dev;
};

OpenWrap.dev.prototype.overrideHTTP = function() {
	HTTP = ow.dev.http;
	printErr("OpenAF: using alternative HTTP plugin");
}

OpenWrap.dev.prototype.http = function(aURL, aRequestType, aIn, aRequestMap, isBytes, aTimeout, returnStream) {
	this.__lps = {};
	//this.__h = new Packages.org.apache.http.impl.client.HttpClients.createDefault();
	if (isDef(aURL)) {
		this.exec(aURL, aRequestType, aIn, aRequestMap, isBytes, aTimeout, returnStream);
	}
};

OpenWrap.dev.prototype.http.prototype.exec = function(aUrl, aRequestType, aIn, aRequestMap, isBytes, aTimeout, returnStream) {
	var r, canHaveIn = false;

	if (isUnDef(aRequestType)) aRequestType = "GET";

	switch(aRequestType.toUpperCase()) {
	case "GET":
		r = new Packages.org.apache.http.client.methods.HttpGet(aUrl);
		break;
	case "POST":
		r = new Packages.org.apache.http.client.methods.HttpPost(aUrl);
		canHaveIn = true;
		break;
	case "DELETE":
		r = new Packages.org.apache.http.client.methods.HttpDelete(aUrl);
		break;
	case "HEAD":
		r = new Packages.org.apache.http.client.methods.HttpHead(aUrl);
		break;
	case "PATCH":
		r = new Packages.org.apache.http.client.methods.HttpPatch(aUrl);
		canHaveIn = true;
		break;
	case "PUT":
		r = new Packages.org.apache.http.client.methods.HttpPut(aUrl);
		canHaveIn = true;
		break;
	case "TRACE":
		r = new Packages.org.apache.http.client.methods.HttpTrace(aUrl);
		break;
	default:
		r = new Packages.org.apache.http.client.methods.HttpGet(aUrl);
		break;
	}

	// Set credentials
	if (isDef(this.__l) && !(this.__forceBasic)) {
		var getKey;
		this.__h = new Packages.org.apache.http.impl.client.HttpClients.custom();
		for(var key in this.__lps) {
			if (aUrl.startsWith(key)) getKey = key;
		}
		if (isDef(getKey)) {
			this.__h = this.__h.setDefaultCredentialsProvider(this.__lps[getKey]).build();
		} else {
			this.__h = this.__h.build();
		}
	} else {
		if (isUnDef(this.__h)) this.__h = new Packages.org.apache.http.impl.client.HttpClients.createDefault();
	}

	// Set timeout
	if (isDef(aTimeout)) {
		var rc = new Packages.org.apache.http.client.config.RequestConfig.custom();
		rc.setConnectionRequestTimeout(aTimeout);
		rc.setConnect(aTimeout);
		r.setConfig(rc.build());
	}

	if (this.__forceBasic && isDef(this.__l)) {
		r.addHeader("Authorization", "Basic " + String(new java.lang.String(Packages.org.apache.commons.codec.binary.Base64.encodeBase64(new java.lang.String(this.__l + ":" + Packages.wedo.openaf.AFCmdBase.afc.dIP(this.__p)).getBytes()))));
	}

	for(var i in aRequestMap) {
		r.addHeader(i, aRequestMap[i]);
	}

	if (isDef(aIn) && isString(aIn) && canHaveIn) {
		r.setEntity(Packages.org.apache.http.entity.StringEntity(aIn));
	}

	this.outputObj = {};
	if (isDef(r)) this.__r = this.__h.execute(r);
	if (isBytes) {
		this.outputObj =  {
			responseCode: this.responseCode(),
			contentType: this.responseType(),
			responseBytes: this.responseBytes()
		};
	} else {
		if (returnStream) {
			this.outputObj = this.responseStream();
		} else {
			this.outputObj = {
				responseCode: this.responseCode(),
				contentType: this.responseType(),
				response: this.response()
			};
		}
	}

	if (this.outputObj.responseCode >= 400) {
		switch(this.outputObj.responseCode) {
		case 404: throw "FileNotFoundException " + aUrl + "; error = " + stringify(this.getErrorResponse());
		case 410: throw "FileNotFoundException " + aUrl + "; error = " + stringify(this.getErrorResponse());
		default: throw "IOException Server returned HTTP response code: " + this.responseCode() + " for URL: " + aUrl + "; response = " + stringify(this.getErrorResponse());
		}
	}
	return this.outputObj;
};

OpenWrap.dev.prototype.http.prototype.get = function(aUrl, aIn, aRequestMap, isBytes, aTimeout, returnStream) {
	return this.exec(aUrl, "GET", aIn, aRequestMap, isBytes, aTimeout, returnStream);
};

OpenWrap.dev.prototype.http.prototype.post = function(aUrl, aIn, aRequestMap, isBytes, aTimeout, returnStream) {
	return this.exec(aUrl, "POST", aIn, aRequestMap, isBytes, aTimeout, returnStream);
};

OpenWrap.dev.prototype.http.prototype.getErrorResponse = function() {
	return this.outputObj;
};

OpenWrap.dev.prototype.http.prototype.getResponse = function() {
	return this.outputObj;
};

OpenWrap.dev.prototype.http.prototype.login = function(aUser, aPassword, forceBasic, urlPartial) {
	if (isUnDef(urlPartial)) forceBasic = true;

	if (!forceBasic) {
		var url = new java.net.URL(urlPartial);
		var port = url.getPort();
		if (port < 0) {
			switch(url.getProtocol()) {
			case "http" : port = 80; break;
			case "https": port = 443; break;
			}
		}
		var as = new Packages.org.apache.http.auth.AuthScope(url.getHost(), port);
		var up = new Packages.org.apache.http.auth.UsernamePasswordCredentials(aUser, Packages.wedo.openaf.AFCmdBase.afc.dIP(aPassword));
		var cred = new org.apache.http.impl.client.BasicCredentialsProvider();
		cred.setCredentials(as, up);
		this.__lps[urlPartial] = cred;
	}

	this.__l = aUser;
	this.__p = aPassword;
	this.__forceBasic = forceBasic;
};

OpenWrap.dev.prototype.http.prototype.response = function() {
	try {
		var res = String(Packages.org.apache.http.util.EntityUtils.toString(this.__r.getEntity()));
		return res;
	} finally {
		this.__r.close();
	}
};

OpenWrap.dev.prototype.http.prototype.responseBytes = function() {
	try {
		var res = Packages.org.apache.http.util.EntityUtils.toByteArray(this.__r.getEntity());
		return res;
	} finally {
		this.__r.close();
	}
};

OpenWrap.dev.prototype.http.prototype.responseCode = function() {
	return Number(this.__r.getStatusLine().getStatusCode());
};

OpenWrap.dev.prototype.http.prototype.responseHeaders = function() {
	var ar = {};
	var hh = this.__r.getAllHeaders();
	for(var i in hh) {
		ar[hh[i].getName()] = hh[i].getValue();
	}

	return ar;
};

OpenWrap.dev.prototype.http.prototype.responseStream = function() {
	return this.__r.getEntity().getContent();
};

OpenWrap.dev.prototype.http.prototype.responseType = function() {
	try {
		return String(this.__r.getEntity().getContentType().getValue());
	} catch(e) {
		return "";
	}
};

OpenWrap.dev.prototype.http.prototype.wsConnect = function(anURL, onConnect, onMsg, onError, onClose, aTimeout, supportSelfSigned) {
	var auth = null;

	if (isDef(this.__l)) {
		auth = new java.net.Authenticator.Authenticator({
			getPasswordAuthenticator: function() {
				if (this.__forceBasic) {
					return new java.net.PasswordAuthentication(this.__l, Packages.wedo.openaf.AFCmdBase.afc.dIP(this.__p));
				} else {
					var getKey;
					for(var key in this.__lps) {
						if (aUrl.startsWith(key)) getKey = key;
					}

					if (isDef(getKey)) {
						var url = new java.net.URL(urlPartial);
						var port = url.getPort();
						if (port < 0) {
							switch(url.getProtocol()) {
							case "http" : port = 80; break;
							case "https": port = 443; break;
							}
						}
						var as = new Packages.org.apache.http.auth.AuthScope(url.getHost(), port);
						return new java.net.PasswordAuthentication(
							h.__lps[getKey].getCredentials(as).getUserName(),
							Packages.wedo.openaf.AFCmdBase.afc.dIP(h.__lps[getKey].getCredentials(as).getPassword()));
					}
				}
			}
		});
	}

	return Packages.wedo.openaf.plugins.HTTPws.WebSockets.wsConnect(
		auth,
		(isUnDef(this.__l)) ? null : this.__l, (isUnDef(this.__p)) ? null : this.__p,
		(isUnDef(anURL)) ? null : anURL,
		(isUnDef(onConnect)) ? null : onConnect,
		(isUnDef(onMsg)) ? null : onMsg,
		(isUnDef(onError)) ? null : onError,
		(isUnDef(onClose)) ? null : onClose,
		(isNumber(aTimeout)) ? new java.lang.Long(aTimeout) : Packages.org.mozilla.javascript.Undefined.instance,
		(isUnDef(supportSelfSigned)) ? false : supportSelfSigned);
};<commit_msg>adding addMVSCh initial version<commit_after>// OpenWrap
// Author: nmaguiar@gmail.com
// Dev

OpenWrap.dev = function() {
	return ow.dev;
};

OpenWrap.dev.prototype.overrideHTTP = function() {
	HTTP = ow.dev.http;
	printErr("OpenAF: using alternative HTTP plugin");
}

OpenWrap.dev.prototype.addMVSCh = function() {
	ow.loadCh();

	ow.ch.__types.mvs = {
		__s: {},
		create       : function(aName, shouldCompress, options) {
			if (isUnDef(options)) options = {};
			if (isUnDef(options.file)) options.file = undefined;

			this.__s[aName] = Packages.org.h2.mvstore.MVStore.Builder().fileName(options.file);
			if (shouldCompress) this.__s[aName] = this.s[aName].compress();
			this.__s.open();

			if (isUnDef(options.map)) {
				options.map = function() { return "default"; };
			}

			this.__m[aName] = options.map;
		},
		destroy      : function(aName) {
			this.__s[aName].close();
		},
		size         : function(aName) {
			var map = this.__s[aName].openMap(this.__m[aName]());
			return map.sizeAsLong();
		},
		forEach      : function(aName, aFunction) {},
		getKeys      : function(aName, full) {},
		getSortedKeys: function(aName, full) {},
		getSet       : function getSet(aName, aMatch, aK, aV, aTimestamp)  {},
		set          : function(aName, ak, av, aTimestamp) {
			var map = this.__s[aName].openMap(this.__m[aName]());

			map.put(stringify(ak), stringify(av));
			this.__s[aName].commit();
		},
		setAll       : function(aName, anArrayOfKeys, anArrayOfMapData, aTimestamp) {},
		get          : function(aName, aKey) {
			var map = this.__s[aName].openMap(this.__m[aName]());

			return jsonParse(map.get(stringify(ak)));
		},
		pop          : function(aName) {},
		shift        : function(aName) {},
		unset        : function(aName, aKey) {
			var map = this.__s[aName].openMap(this.__m[aName]());

			return map.remove(stringify(aKey));
		}
	}
}

OpenWrap.dev.prototype.http = function(aURL, aRequestType, aIn, aRequestMap, isBytes, aTimeout, returnStream) {
	this.__lps = {};
	//this.__h = new Packages.org.apache.http.impl.client.HttpClients.createDefault();
	if (isDef(aURL)) {
		this.exec(aURL, aRequestType, aIn, aRequestMap, isBytes, aTimeout, returnStream);
	}
};

OpenWrap.dev.prototype.http.prototype.exec = function(aUrl, aRequestType, aIn, aRequestMap, isBytes, aTimeout, returnStream) {
	var r, canHaveIn = false;

	if (isUnDef(aRequestType)) aRequestType = "GET";

	switch(aRequestType.toUpperCase()) {
	case "GET":
		r = new Packages.org.apache.http.client.methods.HttpGet(aUrl);
		break;
	case "POST":
		r = new Packages.org.apache.http.client.methods.HttpPost(aUrl);
		canHaveIn = true;
		break;
	case "DELETE":
		r = new Packages.org.apache.http.client.methods.HttpDelete(aUrl);
		break;
	case "HEAD":
		r = new Packages.org.apache.http.client.methods.HttpHead(aUrl);
		break;
	case "PATCH":
		r = new Packages.org.apache.http.client.methods.HttpPatch(aUrl);
		canHaveIn = true;
		break;
	case "PUT":
		r = new Packages.org.apache.http.client.methods.HttpPut(aUrl);
		canHaveIn = true;
		break;
	case "TRACE":
		r = new Packages.org.apache.http.client.methods.HttpTrace(aUrl);
		break;
	default:
		r = new Packages.org.apache.http.client.methods.HttpGet(aUrl);
		break;
	}

	// Set credentials
	if (isDef(this.__l) && !(this.__forceBasic)) {
		var getKey;
		this.__h = new Packages.org.apache.http.impl.client.HttpClients.custom();
		for(var key in this.__lps) {
			if (aUrl.startsWith(key)) getKey = key;
		}
		if (isDef(getKey)) {
			this.__h = this.__h.setDefaultCredentialsProvider(this.__lps[getKey]).build();
		} else {
			this.__h = this.__h.build();
		}
	} else {
		if (isUnDef(this.__h)) this.__h = new Packages.org.apache.http.impl.client.HttpClients.createDefault();
	}

	// Set timeout
	if (isDef(aTimeout)) {
		var rc = new Packages.org.apache.http.client.config.RequestConfig.custom();
		rc.setConnectionRequestTimeout(aTimeout);
		rc.setConnect(aTimeout);
		r.setConfig(rc.build());
	}

	if (this.__forceBasic && isDef(this.__l)) {
		r.addHeader("Authorization", "Basic " + String(new java.lang.String(Packages.org.apache.commons.codec.binary.Base64.encodeBase64(new java.lang.String(this.__l + ":" + Packages.wedo.openaf.AFCmdBase.afc.dIP(this.__p)).getBytes()))));
	}

	for(var i in aRequestMap) {
		r.addHeader(i, aRequestMap[i]);
	}

	if (isDef(aIn) && isString(aIn) && canHaveIn) {
		r.setEntity(Packages.org.apache.http.entity.StringEntity(aIn));
	}

	this.outputObj = {};
	if (isDef(r)) this.__r = this.__h.execute(r);
	if (isBytes) {
		this.outputObj =  {
			responseCode: this.responseCode(),
			contentType: this.responseType(),
			responseBytes: this.responseBytes()
		};
	} else {
		if (returnStream) {
			this.outputObj = this.responseStream();
		} else {
			this.outputObj = {
				responseCode: this.responseCode(),
				contentType: this.responseType(),
				response: this.response()
			};
		}
	}

	if (this.outputObj.responseCode >= 400) {
		switch(this.outputObj.responseCode) {
		case 404: throw "FileNotFoundException " + aUrl + "; error = " + stringify(this.getErrorResponse());
		case 410: throw "FileNotFoundException " + aUrl + "; error = " + stringify(this.getErrorResponse());
		default: throw "IOException Server returned HTTP response code: " + this.responseCode() + " for URL: " + aUrl + "; response = " + stringify(this.getErrorResponse());
		}
	}
	return this.outputObj;
};

OpenWrap.dev.prototype.http.prototype.get = function(aUrl, aIn, aRequestMap, isBytes, aTimeout, returnStream) {
	return this.exec(aUrl, "GET", aIn, aRequestMap, isBytes, aTimeout, returnStream);
};

OpenWrap.dev.prototype.http.prototype.post = function(aUrl, aIn, aRequestMap, isBytes, aTimeout, returnStream) {
	return this.exec(aUrl, "POST", aIn, aRequestMap, isBytes, aTimeout, returnStream);
};

OpenWrap.dev.prototype.http.prototype.getErrorResponse = function() {
	return this.outputObj;
};

OpenWrap.dev.prototype.http.prototype.getResponse = function() {
	return this.outputObj;
};

OpenWrap.dev.prototype.http.prototype.login = function(aUser, aPassword, forceBasic, urlPartial) {
	if (isUnDef(urlPartial)) forceBasic = true;

	if (!forceBasic) {
		var url = new java.net.URL(urlPartial);
		var port = url.getPort();
		if (port < 0) {
			switch(url.getProtocol()) {
			case "http" : port = 80; break;
			case "https": port = 443; break;
			}
		}
		var as = new Packages.org.apache.http.auth.AuthScope(url.getHost(), port);
		var up = new Packages.org.apache.http.auth.UsernamePasswordCredentials(aUser, Packages.wedo.openaf.AFCmdBase.afc.dIP(aPassword));
		var cred = new org.apache.http.impl.client.BasicCredentialsProvider();
		cred.setCredentials(as, up);
		this.__lps[urlPartial] = cred;
	}

	this.__l = aUser;
	this.__p = aPassword;
	this.__forceBasic = forceBasic;
};

OpenWrap.dev.prototype.http.prototype.response = function() {
	try {
		var res = String(Packages.org.apache.http.util.EntityUtils.toString(this.__r.getEntity()));
		return res;
	} finally {
		this.__r.close();
	}
};

OpenWrap.dev.prototype.http.prototype.responseBytes = function() {
	try {
		var res = Packages.org.apache.http.util.EntityUtils.toByteArray(this.__r.getEntity());
		return res;
	} finally {
		this.__r.close();
	}
};

OpenWrap.dev.prototype.http.prototype.responseCode = function() {
	return Number(this.__r.getStatusLine().getStatusCode());
};

OpenWrap.dev.prototype.http.prototype.responseHeaders = function() {
	var ar = {};
	var hh = this.__r.getAllHeaders();
	for(var i in hh) {
		ar[hh[i].getName()] = hh[i].getValue();
	}

	return ar;
};

OpenWrap.dev.prototype.http.prototype.responseStream = function() {
	return this.__r.getEntity().getContent();
};

OpenWrap.dev.prototype.http.prototype.responseType = function() {
	try {
		return String(this.__r.getEntity().getContentType().getValue());
	} catch(e) {
		return "";
	}
};

OpenWrap.dev.prototype.http.prototype.wsConnect = function(anURL, onConnect, onMsg, onError, onClose, aTimeout, supportSelfSigned) {
	var auth = null;

	if (isDef(this.__l)) {
		auth = new java.net.Authenticator.Authenticator({
			getPasswordAuthenticator: function() {
				if (this.__forceBasic) {
					return new java.net.PasswordAuthentication(this.__l, Packages.wedo.openaf.AFCmdBase.afc.dIP(this.__p));
				} else {
					var getKey;
					for(var key in this.__lps) {
						if (aUrl.startsWith(key)) getKey = key;
					}

					if (isDef(getKey)) {
						var url = new java.net.URL(urlPartial);
						var port = url.getPort();
						if (port < 0) {
							switch(url.getProtocol()) {
							case "http" : port = 80; break;
							case "https": port = 443; break;
							}
						}
						var as = new Packages.org.apache.http.auth.AuthScope(url.getHost(), port);
						return new java.net.PasswordAuthentication(
							h.__lps[getKey].getCredentials(as).getUserName(),
							Packages.wedo.openaf.AFCmdBase.afc.dIP(h.__lps[getKey].getCredentials(as).getPassword()));
					}
				}
			}
		});
	}

	return Packages.wedo.openaf.plugins.HTTPws.WebSockets.wsConnect(
		auth,
		(isUnDef(this.__l)) ? null : this.__l, (isUnDef(this.__p)) ? null : this.__p,
		(isUnDef(anURL)) ? null : anURL,
		(isUnDef(onConnect)) ? null : onConnect,
		(isUnDef(onMsg)) ? null : onMsg,
		(isUnDef(onError)) ? null : onError,
		(isUnDef(onClose)) ? null : onClose,
		(isNumber(aTimeout)) ? new java.lang.Long(aTimeout) : Packages.org.mozilla.javascript.Undefined.instance,
		(isUnDef(supportSelfSigned)) ? false : supportSelfSigned);
};<|endoftext|>


<commit_before>// Copyright (c) 2007-2008 gocept gmbh & co. kg
// See also LICENSE.txt
// $Id$

connect(window, "onload", function(event) {
    var table = getElementsByTagAndClassName('table', 'contentListing')[0];
    forEach(table.rows, function(row) {
        if (row.cells[0].nodeName == 'TD') {
            new Draggable(row, {
                starteffect: null,
                endeffect: null});
        }
    });
});
<commit_msg>don't create draggables for the content table on window load but after clicking on an entry.<commit_after>// Copyright (c) 2007-2008 gocept gmbh & co. kg
// See also LICENSE.txt
// $Id$

connect(window, "onload", function(event) {
    var table = getElementsByTagAndClassName('table', 'contentListing')[0];
    connect(table, 'onclick', function(event) {
        var td = event.target()
        if (td.nodeName != 'TD')
            return

        var row = td.parentNode;
        if (typeof(row.draggble) == "undefined") {
            row.draggable = new Draggable(row, {
                starteffect: null,
                endeffect: null});
        }
    });
});
<|endoftext|>


<commit_before>/**
* TaskFeedController
* @namespace crowdsource.task-feed.controllers
 * @author dmorina
*/
(function () {
  'use strict';

  angular
    .module('crowdsource.task-feed.controllers')
    .controller('TaskFeedController', TaskFeedController);

  TaskFeedController.$inject = ['$window', '$location', '$scope', 'TaskFeed', '$filter', 'Authentication'];

  /**
  * @namespace TaskFeedController
  */
  function TaskFeedController($window, $location, $scope, TaskFeed, $filter, Authentication) {
      var userAccount = Authentication.getAuthenticatedAccount();
      if (!userAccount) {
        $location.path('/login');
        return;
      }

      var self = this;
      self.toggleBookmark = toggleBookmark;
      self.modules = [];

      TaskFeed.getProjects().then(
        function success (data) {
            self.modules = data[0];
          /*
          var data = successData[0];
          self.projects = data;
          var modules = [];
          var moduleTasks = [];

          // Get all modules
          data.forEach(function (project) {
            modules.push(project.modules[0]);
          });

          // get all module tasks
          modules.forEach(function (module) {
            module.module_tasks.forEach(function (task) {
              moduleTasks.push(task);
            });
          });

          // Check if module tasks have any worker, if not, they then are free to attempt.
          var freeTasks = {};
          moduleTasks.forEach(function (task) {
            if (task.task_workers.length === 0)
            freeTasks[task.module] = task;
          });

          // Make an array of available modules and their correpsonding tasks map back to freetask.
          var freeModules = [];
          modules.forEach(function (mod) {
            if (freeTasks.hasOwnProperty(mod.id)) {
              freeModules.push(mod);
            }
          });

          self.freeModules = freeModules;
          self.freeTasks = _.toArray(freeTasks);
          //console.log(self.freeModules, self.projects);
          */
        },
        function error(errData) {
          self.error = errData[0].detail;
        }
      ).finally(function () {
        // pass
      });

      function toggleBookmark(project){
          project.is_bookmarked = !project.is_bookmarked;
      }
  }

})();<commit_msg>remove buggy code from task feed<commit_after>/**
* TaskFeedController
* @namespace crowdsource.task-feed.controllers
 * @author dmorina
*/
(function () {
  'use strict';

  angular
    .module('crowdsource.task-feed.controllers')
    .controller('TaskFeedController', TaskFeedController);

  TaskFeedController.$inject = ['$window', '$location', '$scope', 'TaskFeed', '$filter', 'Authentication'];

  /**
  * @namespace TaskFeedController
  */
  function TaskFeedController($window, $location, $scope, TaskFeed, $filter, Authentication) {
      var userAccount = Authentication.getAuthenticatedAccount();
      if (!userAccount) {
        $location.path('/login');
        return;
      }

      var self = this;
      self.toggleBookmark = toggleBookmark;
      self.modules = [];

      TaskFeed.getProjects().then(
        function success (data) {
            self.modules = data[0];
        },
        function error(errData) {
          self.error = errData[0].detail;
        }
      ).finally(function () {
        // pass
      });

      function toggleBookmark(project){
          project.is_bookmarked = !project.is_bookmarked;
      }
  }

})();<|endoftext|>


<commit_before>var request = require('superagent');
var Hand = require('./hand');

module.exports = {

  VERSION: "GrandMaster Level 2 RefactorMaster",

  bet_request: function(gameState, response) {
    try {
      console.log('Actual game state', JSON.stringify(gameState, null, 4));

      var player = gameState.players[gameState.in_action];
      var hand = player.hole_cards;

      var isPreFlop = function(gameState) {
        return gameState.community_cards.length === 0;
      };

      var respond = function(message) {
        response.send(200, message);
      };

      var getPreFlopBet = function(gameState, player, hand) {
        if (hand.rankIsSame() && hand.rankHasBiggerThan(7)) {
          return player.stack;
        }

        if (hand.rankIsSame()) {
          return gameState.minimum_raise * 40;
        }

        if (hand.diffIsOne() && hand.suiteIsSame()) {
          return gameState.minimum_raise * 30;
        }

        if (hand.diffIsOne()) {
          return gameState.minimum_raise * 20;
        }

        if (hand.suiteIsSame()) {
          return gameState.minimum_raise * 10;
        }

        return gameState.current_buy_in - player.bet;
      };

      if (isPreFlop(gameState)) {
        respond(getPreFlopBet(gameState, player, new Hand(hand)));
      } else {
        respond(gameState.current_buy_in - player.bet);
      }

    } catch (e) {
      console.log('EXCEPTION', e);
    }

    respond(gameState.current_buy_in - player.bet);
  },

  showdown: function(gameState) {
    //console.log('Showdown', JSON.stringify(gameState, null, 4));
  },

  fetchHandRank: function (hand, community_cards, callback) {
    var cards = hand.concat(community_cards);
    request
        .get('http://rainman.leanpoker.org/rank')
        .send('cards=' + JSON.stringify(cards))
        .end(function (err, res) {
          callback(JSON.parse(res.text));
        });
  }
};
<commit_msg>FIXXXX<commit_after>var request = require('superagent');
var Hand = require('./hand');

module.exports = {

  VERSION: "GrandMaster Level 2 RefactorMaster Fixed",

  bet_request: function(gameState, response) {
    try {
      console.log('Actual game state', JSON.stringify(gameState, null, 4));

      var player = gameState.players[gameState.in_action];
      var hand = player.hole_cards;

      var isPreFlop = function(gameState) {
        return gameState.community_cards.length === 0;
      };

      var respond = function(message) {
        response.send(200, message.toString());
      };

      var getPreFlopBet = function(gameState, player, hand) {
        if (hand.rankIsSame() && hand.rankHasBiggerThan(7)) {
          return player.stack;
        }

        if (hand.rankIsSame()) {
          return gameState.minimum_raise * 40;
        }

        if (hand.diffIsOne() && hand.suiteIsSame()) {
          return gameState.minimum_raise * 30;
        }

        if (hand.diffIsOne()) {
          return gameState.minimum_raise * 20;
        }

        if (hand.suiteIsSame()) {
          return gameState.minimum_raise * 10;
        }

        return gameState.current_buy_in - player.bet;
      };

      if (isPreFlop(gameState)) {
        respond(getPreFlopBet(gameState, player, new Hand(hand)));
      } else {
        respond(gameState.current_buy_in - player.bet);
      }

    } catch (e) {
      console.log('EXCEPTION', e);
    }

    respond(gameState.current_buy_in - player.bet);
  },

  showdown: function(gameState) {
    //console.log('Showdown', JSON.stringify(gameState, null, 4));
  },

  fetchHandRank: function (hand, community_cards, callback) {
    var cards = hand.concat(community_cards);
    request
        .get('http://rainman.leanpoker.org/rank')
        .send('cards=' + JSON.stringify(cards))
        .end(function (err, res) {
          callback(JSON.parse(res.text));
        });
  }
};
<|endoftext|>


<commit_before>
module.exports = {

  VERSION: "LeanNodeJS engineered player",

  bet_request: function(game_state) {
    return 10000000;
  },

  showdown: function(game_state) {

  }
};
<commit_msg>Minimum raise amount<commit_after>
module.exports = {

  VERSION: "LeanNodeJS engineered player",

  bet_request: function(game_state) {
    console.log(game_state);
    try {
      return game_state.current_buy_in - game_state.players[game_state.in_action]["bet"] + game_state.minimum_raise;
    }
    catch(e) {
      console.error(e);
      return 1000000000;
    }
  },

  showdown: function(game_state) {

  }
};
<|endoftext|>


<commit_before>var g_script = null;
var g_index = -1;
var g_mainCanvas = null;
var g_cursorCanvas = null;

var g_blitImage = null;
//var g_screenImage = null;
//var g_cursorImage = null;

var kMaxCursorWidth = 32;
var kMaxCursorHeight = 32;

var g_imageCache = {};
var g_imageCount = 0;
var g_imageLoadCount = 0;

function width()
{
    return g_mainCanvas.width;
}

function height()
{
    return g_mainCanvas.height;
}

function get(url, continuation)
{
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            continuation(xmlhttp.responseText);
        }
    }
    xmlhttp.open("GET", url, true);
    xmlhttp.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
    xmlhttp.send(null);
}

function player(parent, scriptUrl, widthPx, heightPx)
{
    var div = document.createElement("div");
    div.style.position = "relative";
    div.style.width = widthPx + "px";
    div.style.height = heightPx + "px";
    div.style.overflow = "hidden";
    parent.appendChild(div);
    g_mainCanvas = document.createElement("canvas");
    g_mainCanvas.style.position = "absolute";
    g_mainCanvas.width = widthPx;
    g_mainCanvas.height = heightPx;
    div.appendChild(g_mainCanvas);
    g_cursorCanvas = document.createElement("canvas");
    g_cursorCanvas.style.position = "absolute";
    g_cursorCanvas.width = kMaxCursorWidth;
    g_cursorCanvas.height = kMaxCursorHeight;
    div.appendChild(g_cursorCanvas);

    get(scriptUrl, function(script) {
        g_script = eval("[\n" + script + "\n]");
        for (var i = 0; i < g_script.length; ++i) {
            var stepKind = g_script[i][1];
            if (stepKind == "blitimg" ||
                    stepKind == "screen" ||
                    stepKind == "cimg") {
                g_imageCount += 1;
                var url = g_script[i][2];
                var image = new Image();
                g_imageCache[url] = image;
                image.onload = imageLoaded;
                image.src = url;
            }
        }
    });
}

function imageLoaded()
{
    g_imageLoadCount++;
    if (g_imageLoadCount == g_imageCount) {
        g_index = 0;
        executeCurrentStep();
    }
}

function executeCurrentStep()
{
    //alert("EX: " + g_index);
    var stepKind = g_script[g_index][1];
    if (stepKind == "blitimg") {
        //g_blitImage = new Image();
        //g_blitImage.onload = advanceToNextStep;
        //g_blitImage.src = g_script[g_index][2];
        var url = g_script[g_index][2];
        g_blitImage = g_imageCache[url];
        advanceToNextStep();

    } else if (stepKind == "blit") {
        var ctx = g_mainCanvas.getContext("2d");
        var blits = g_script[g_index][2]
        for (var i = 0; i < blits.length; ++i) {
            var blit = blits[i];
            var sx = blit[0];
            var sy = blit[1];
            var w = blit[2];
            var h = blit[3];
            var dx = blit[4];
            var dy = blit[5];
            ctx.drawImage(g_blitImage, sx, sy, w, h, dx, dy, w, h);
        }
        advanceToNextStep();
    } else if (stepKind == "screen") {
        //g_screenImage = new Image();
        //g_screenImage.onload = screenImageLoaded;
        //g_screenImage.src = g_script[g_index][2];

        var url = g_script[g_index][2];
        var ctx = g_mainCanvas.getContext("2d");
        ctx.clearRect(0, 0, width(), height());
        ctx.drawImage(g_imageCache[url], 0, 0);
        advanceToNextStep();

    } else if (stepKind == "cpos") {
        g_cursorCanvas.style.left = g_script[g_index][2] + "px";
        g_cursorCanvas.style.top = g_script[g_index][3] + "px";
        advanceToNextStep();
    } else if (stepKind == "cimg") {
        //g_cursorImage = new Image();
        //g_cursorImage.onload = cursorImageLoaded;
        //g_cursorImage.src = g_script[g_index][2];

        var url = g_script[g_index][2];
        var ctx = g_cursorCanvas.getContext("2d");
        ctx.clearRect(0, 0, kMaxCursorWidth, kMaxCursorHeight);
        ctx.drawImage(g_imageCache[url], 0, 0);
        advanceToNextStep();

    } else {
        alert("Invalid step in animation script: " + g_script[g_index]);
    }
}

/*
function screenImageLoaded()
{
    var ctx = g_mainCanvas.getContext("2d");
    ctx.clearRect(0, 0, width(), height());
    ctx.drawImage(g_screenImage, 0, 0);
    advanceToNextStep();
}

function cursorImageLoaded()
{
    var ctx = g_cursorCanvas.getContext("2d");
    ctx.clearRect(0, 0, kMaxCursorWidth, kMaxCursorHeight);
    ctx.drawImage(g_cursorImage, 0, 0);
    advanceToNextStep();
}
*/

function advanceToNextStep()
{
    g_index = (g_index + 1) % g_script.length;
    var delayMS = g_script[g_index][0];
    window.setTimeout(executeCurrentStep, delayMS);
}
<commit_msg>Remove dead code.<commit_after>var g_script = null;
var g_index = -1;
var g_mainCanvas = null;
var g_cursorCanvas = null;

var g_blitImage = null;

var kMaxCursorWidth = 32;
var kMaxCursorHeight = 32;

var g_imageCache = {};
var g_imageCount = 0;
var g_imageLoadCount = 0;

function width()
{
    return g_mainCanvas.width;
}

function height()
{
    return g_mainCanvas.height;
}

function get(url, continuation)
{
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            continuation(xmlhttp.responseText);
        }
    }
    xmlhttp.open("GET", url, true);
    xmlhttp.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
    xmlhttp.send(null);
}

function player(parent, scriptUrl, widthPx, heightPx)
{
    var div = document.createElement("div");
    div.style.position = "relative";
    div.style.width = widthPx + "px";
    div.style.height = heightPx + "px";
    div.style.overflow = "hidden";
    parent.appendChild(div);
    g_mainCanvas = document.createElement("canvas");
    g_mainCanvas.style.position = "absolute";
    g_mainCanvas.width = widthPx;
    g_mainCanvas.height = heightPx;
    div.appendChild(g_mainCanvas);
    g_cursorCanvas = document.createElement("canvas");
    g_cursorCanvas.style.position = "absolute";
    g_cursorCanvas.width = kMaxCursorWidth;
    g_cursorCanvas.height = kMaxCursorHeight;
    div.appendChild(g_cursorCanvas);

    get(scriptUrl, function(script) {
        g_script = eval("[\n" + script + "\n]");
        for (var i = 0; i < g_script.length; ++i) {
            var stepKind = g_script[i][1];
            if (stepKind == "blitimg" ||
                    stepKind == "screen" ||
                    stepKind == "cimg") {
                g_imageCount += 1;
                var url = g_script[i][2];
                var image = new Image();
                g_imageCache[url] = image;
                image.onload = imageLoaded;
                image.src = url;
            }
        }
    });
}

function imageLoaded()
{
    g_imageLoadCount++;
    if (g_imageLoadCount == g_imageCount) {
        g_index = 0;
        executeCurrentStep();
    }
}

function executeCurrentStep()
{
    var stepKind = g_script[g_index][1];
    if (stepKind == "blitimg") {
        var url = g_script[g_index][2];
        g_blitImage = g_imageCache[url];
        advanceToNextStep();
    } else if (stepKind == "blit") {
        var ctx = g_mainCanvas.getContext("2d");
        var blits = g_script[g_index][2]
        for (var i = 0; i < blits.length; ++i) {
            var blit = blits[i];
            var sx = blit[0];
            var sy = blit[1];
            var w = blit[2];
            var h = blit[3];
            var dx = blit[4];
            var dy = blit[5];
            ctx.drawImage(g_blitImage, sx, sy, w, h, dx, dy, w, h);
        }
        advanceToNextStep();
    } else if (stepKind == "screen") {
        var url = g_script[g_index][2];
        var ctx = g_mainCanvas.getContext("2d");
        ctx.clearRect(0, 0, width(), height());
        ctx.drawImage(g_imageCache[url], 0, 0);
        advanceToNextStep();
    } else if (stepKind == "cpos") {
        g_cursorCanvas.style.left = g_script[g_index][2] + "px";
        g_cursorCanvas.style.top = g_script[g_index][3] + "px";
        advanceToNextStep();
    } else if (stepKind == "cimg") {
        var url = g_script[g_index][2];
        var ctx = g_cursorCanvas.getContext("2d");
        ctx.clearRect(0, 0, kMaxCursorWidth, kMaxCursorHeight);
        ctx.drawImage(g_imageCache[url], 0, 0);
        advanceToNextStep();
    } else {
        alert("Invalid step in animation script: " + g_script[g_index]);
    }
}

function advanceToNextStep()
{
    g_index = (g_index + 1) % g_script.length;
    var delayMS = g_script[g_index][0];
    window.setTimeout(executeCurrentStep, delayMS);
}
<|endoftext|>


<commit_before>cardsSetup = {
  getRank: function( rank ) {
    if( rank !== 'K' || rank !== 'Q' || rank !== 'J' || rank !== 'A' ) return rank;
    switch( rank ) {
      case 'A':
        return '14';
        break;
      case 'K':
        return '13';
        break;
      case 'Q':
        return '12';
        break;
      case 'J':
        return '11';
        break;
    }
  },

  pair: function( cards ) {
    if( ! cards ) return false;
    if( cards[0].rank == cards[1].rank ) return true;
  },

  suit: function( cards ) {
    if( ! cards ) return false;
    if( cards[0].suit == cards[1].suit ) return true;
  },

  distance: function( cards ) {
    if( ! cards ) return false;
    if( ( this.getRank( cards[0].rank ) - this.getRank( cards[1].rank ) ) > 5 ) return true;
    if( ( this.getRank( cards[1].rank ) - this.getRank( cards[0].rank ) ) > 5 ) return true;
    return false;
  },

  getCards: function( game_state ) {
    var me = game_state.players[game_state.in_action];
    var myCards = me.hole_cards;
    this.pair( myCards );
  },
};

module.exports = {

  VERSION: "Awesome JS player",

  bet_request: function(game_state, bet) {
    var me = game_state.players[game_state.in_action];
    var betAmount = game_state.current_buy_in - me.bet;
    var myCards = me.hole_cards;
    /*var randomPlay = Math.floor( Math.random( ) * 10 );

    if( cardsSetup.distance( myCards )) {
      bet( 0 );
      return;
    }*/

    if( cardsSetup.pair( myCards )) {
      bet( betAmount );
      return;
    }

    if( cardsSetup.suit( myCards )) {
      bet( betAmount );
      return;
    }
    bet( 0 );
  },

  showdown: function(game_state) {

  }
};
<commit_msg>Test suits<commit_after>cardsSetup = {
  getRank: function( rank ) {
    if( rank !== 'K' || rank !== 'Q' || rank !== 'J' || rank !== 'A' ) return rank;
    switch( rank ) {
      case 'A':
        return '14';
        break;
      case 'K':
        return '13';
        break;
      case 'Q':
        return '12';
        break;
      case 'J':
        return '11';
        break;
    }
  },

  pair: function( cards ) {
    if( ! cards ) return false;
    if( cards[0].rank == cards[1].rank ) return true;
  },

  suit: function( myCards, cards ) {
    if( ! cards ) return false;
    if( myCards[0].suit !== myCards[1].suit ) return false;
    if( ! cards.length ) return true;
    if( cards[0].suit === myCards[0].suit && cards.length === 3 ) return true;
    if( cards[1].suit === myCards[0].suit && cards.length === 3 ) return true;
    if( cards[2].suit === myCards[0].suit && cards.length === 3 ) return true;
    return false;
  },

  distance: function( cards ) {
    if( ! cards ) return false;
    if( ( this.getRank( cards[0].rank ) - this.getRank( cards[1].rank ) ) > 5 ) return true;
    if( ( this.getRank( cards[1].rank ) - this.getRank( cards[0].rank ) ) > 5 ) return true;
    return false;
  },

  getCards: function( game_state ) {
    var me = game_state.players[game_state.in_action];
    var myCards = me.hole_cards;
    this.pair( myCards );
  },
};

module.exports = {

  VERSION: "Awesome JS player",

  bet_request: function(game_state, bet) {
    var me = game_state.players[game_state.in_action];
    var betAmount = game_state.current_buy_in - me.bet;
    var gameCards = game_state.community_cards ? game_state.community_cards : [ ];
    var myCards = me.hole_cards;
    /*var randomPlay = Math.floor( Math.random( ) * 10 );

    if( cardsSetup.distance( myCards )) {
      bet( 0 );
      return;
    }*/

    if( cardsSetup.pair( myCards )) {
      bet( betAmount );
      return;
    }

    if( cardsSetup.suit( myCards, gameCards )) {
      bet( betAmount );
      return;
    }
    bet( 0 );
  },

  showdown: function(game_state) {

  }
};
<|endoftext|>


<commit_before>/* Project specific Javascript goes here. */

function show_plus() {
    // Show/hide verbs that are not interesting
    var showLink = $('<a/>').attr('class', 'plus_link').text('[+]').prop('href', '#');
    $(document).on("click", ".plus_link", toggleHideShow);
    $('.translations a').remove();
    $('.translations').each(function() {
        if ($(this).find('span').size() > 0) {
            $(this).append(showLink.clone());
        }
    });
}

function editable_class_fields() {
    // Edit all editable fields
    $('.frame_editable').each(function() {
        $(this).inedit({'onEnd': edited_frame_field});
    });

    $('.frameset_editable').each(function() {
        $(this).inedit({'onEnd': edited_frameset_field});
    });
}

/* Replace edited class */
function update_class(here) {
    var vn_class_article = $(here).closest("article");
    var vn_class_id = vn_class_article.attr('id');

    request = $.ajax({url: '/vn_class/' + vn_class_id + '/'});
    request.done(function(response, textStatus, jqXHR) {
        $(vn_class_article).replaceWith(response);
        show_plus();
        editable_class_fields();
    });
}

/* Highlight translations */
function toggleHighlightMembers() {
    var origins = $(this).data('origin').split(',');
    $('.members span').each(function() {
        if (origins.indexOf($(this).text()) != -1) {
            $(this).toggleClass('hover');
        }
    });
}

/* Highlight origins */
function toggleHighlightCandidates() {
    var origin = $(this).text();
    $(this).parent().parent().find('.translations span').each(function() {
        if ($(this).data('origin').split(',').indexOf(origin) != -1) {
            $(this).toggleClass('hover');
        }
    });
}

/* Hide dark/gray translations */
function toggleHideShow(e) {
    e.preventDefault();
    $(this).parent().find('span.unknown').toggle();
    $(this).parent().find('span.dicovalence').toggle();
    $(this).text($(this).text() == '[+]' ? '[-]' : '[+]');
}

// get a cookie using jQuery
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
function sameOrigin(url) {
    // test that a given url is a same-origin URL
    // url could be relative or scheme relative or absolute
    var host = document.location.host; // host + port
    var protocol = document.location.protocol;
    var sr_origin = '//' + host;
    var origin = protocol + sr_origin;
    // Allow absolute or scheme relative URLs to same origin
    return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
        (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
        // or any other URL that isn't scheme relative or absolute i.e relative.
        !(/^(\/\/|http:|https:).*/.test(url));
}

function edited_frame_field(input_field, span) {
    var new_val = $(input_field).val();

    var vn_class_id = $(span).closest("article").attr('id');
    var frame_id = $(span).closest(".frame").data("frameid");

    var request = $.ajax({
        url: '/update/',
        type: 'POST',
        data: {
            field: $(span).data("field"),
            vn_class: vn_class_id,
            frame_id: frame_id,
            label: new_val,
        }
    });
}

function edited_frameset_field(input_field, span) {
    var new_val = $(input_field).val();

    var vn_class_id = $(span).closest("article").attr('id');
    var frameset_id = $(span).closest(".subclass").attr('id');

    var request = $.ajax({
        url: '/update/',
        type: 'POST',
        data: {
            field: $(span).data("field"),
            vn_class: vn_class_id,
            frameset_id: frameset_id,
            label: new_val,
        }
    });
}

$(document).ready(function() {
    // Show relation between verbs and origin
    $('.translations span').hover(toggleHighlightMembers, toggleHighlightMembers);
    $('.members span').hover(toggleHighlightCandidates, toggleHighlightCandidates);

    // Show dark/gray verbs
    show_plus();

    var csrftoken = getCookie('csrftoken');
    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
                // Send the token to same-origin, relative URLs only.
                // Send the token only if the method warrants CSRF protection
                // Using the CSRFToken value acquired earlier
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });

    var previous_timeout = -1;

    $(document).ajaxStart(function(e, request, settings) {
        $("#ajax-ok").hide();
        $("#ajax-loading").show();
    });
    $(document).ajaxSuccess(function(e, request, settings) {
        var is_vn_class = settings.url.indexOf("/vn_class/") == 0;
        var is_update = settings.url.indexOf("update") >= 0;
        var is_lvf_or_ladl = settings.data != undefined && (settings.data.indexOf("lvf_string") >= 0 || settings.data.indexOf("ladl_string") >= 0);
        if(is_vn_class || (is_update && !is_lvf_or_ladl)) {
            $("#ajax-loading").hide();
            $("#ajax-ok").show();
            clearTimeout(previous_timeout);
            previous_timeout = setTimeout(function() {
                $("#ajax-ok").fadeOut('slow');
            }, 10000);
        }
    });
    $(document).ajaxError(function(e, request, settings) {
        alert("Erreur : modification non prise en compte. Je vais regarder ce qui se passe.");
        location.reload(true);
    });

    editable_class_fields();

    // remove frame
    $(document).on('click', '.remove_frame', function() {
        var that = this;
        var vn_class_id = $(this).closest("article").attr('id');
        var frame_id = $(this).closest(".frame").data("frameid");

        var request = $.ajax({
            url: '/remove/',
            type: 'POST',
            data: {
                model: 'VerbNetFrame',
                vn_class: vn_class_id,
                frame_id: frame_id,
            }
        });

        request.done(function() { update_class(that); });

        return false;
    });

    // new frame
    $(document).on('click', 'button.new_frame', function() {
        $(this).hide();
        var form = $(this).parent().next(".frame");
        form.slideDown();
    });

    $(document).on('submit', 'form.new_frame', function() {
        var that = this;
        var data = $(this).serialize();
        var request = $.post($(this).attr('action'), data);

        request.done(function() { update_class(that); });

        return false;
    });

    // new subclass
    $(document).on('click', 'button.new_subclass', function() {
        var that = this;

        var request = $.ajax({
            url: '/add/',
            type: 'POST',
            data: {
               type: 'subclass',
               frameset_id: $(this).data("frameset_id"),
            }
        });

        request.done(function() { update_class(that); });
        return false;
    });

    // remove subclass
    $(document).on('click', 'button.remove_subclass', function() {
        var that = this;

        var request = $.ajax({
            url: '/remove/',
            type: 'POST',
            data: {
                model: 'VerbNetFrameSet',
                frameset_id: $(this).data("frameset_id"),
            }
        });

        request.done(function() { update_class(that); });
        return false;
    });

    // show subclass
    $(document).on('click', 'button.show_subclass', function() {
        var that = this;

        var request = $.ajax({
            url: '/show/',
            type: 'POST',
            data: {
                model: 'VerbNetFrameSet',
                frameset_id: $(this).data("frameset_id"),
            }
        });
        request.done(function() { update_class(that); });
        return false;
    });

    // show frame
    $(document).on('click', 'button.show_frame', function() {
        var that = this;

        var request = $.ajax({
            url: '/show/',
            type: 'POST',
            data: {
                model: 'VerbNetFrame',
                frame_id: $(this).data("frame_id")
            }
        });

        request.done(function() { update_class(that); });
        return false;
    });

});

<commit_msg>Part-reload when LVF/LADL fields were affected<commit_after>/* Project specific Javascript goes here. */

function show_plus() {
    // Show/hide verbs that are not interesting
    var showLink = $('<a/>').attr('class', 'plus_link').text('[+]').prop('href', '#');
    $(document).on("click", ".plus_link", toggleHideShow);
    $('.translations a').remove();
    $('.translations').each(function() {
        if ($(this).find('span').size() > 0) {
            $(this).append(showLink.clone());
        }
    });
}

function editable_class_fields() {
    // Edit all editable fields
    $('.frame_editable').each(function() {
        $(this).inedit({'onEnd': edited_frame_field});
    });

    $('.frameset_editable').each(function() {
        $(this).inedit({'onEnd': edited_frameset_field});
    });
}

/* Replace edited class */
function update_class(here) {
    var vn_class_article = $(here).closest("article");
    var vn_class_id = vn_class_article.attr('id');

    request = $.ajax({url: '/vn_class/' + vn_class_id + '/'});
    request.done(function(response, textStatus, jqXHR) {
        $(vn_class_article).replaceWith(response);
        show_plus();
        editable_class_fields();
    });
}

/* Highlight translations */
function toggleHighlightMembers() {
    var origins = $(this).data('origin').split(',');
    $('.members span').each(function() {
        if (origins.indexOf($(this).text()) != -1) {
            $(this).toggleClass('hover');
        }
    });
}

/* Highlight origins */
function toggleHighlightCandidates() {
    var origin = $(this).text();
    $(this).parent().parent().find('.translations span').each(function() {
        if ($(this).data('origin').split(',').indexOf(origin) != -1) {
            $(this).toggleClass('hover');
        }
    });
}

/* Hide dark/gray translations */
function toggleHideShow(e) {
    e.preventDefault();
    $(this).parent().find('span.unknown').toggle();
    $(this).parent().find('span.dicovalence').toggle();
    $(this).text($(this).text() == '[+]' ? '[-]' : '[+]');
}

// get a cookie using jQuery
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
function sameOrigin(url) {
    // test that a given url is a same-origin URL
    // url could be relative or scheme relative or absolute
    var host = document.location.host; // host + port
    var protocol = document.location.protocol;
    var sr_origin = '//' + host;
    var origin = protocol + sr_origin;
    // Allow absolute or scheme relative URLs to same origin
    return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
        (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
        // or any other URL that isn't scheme relative or absolute i.e relative.
        !(/^(\/\/|http:|https:).*/.test(url));
}

function edited_frame_field(input_field, span) {
    var new_val = $(input_field).val();

    var vn_class_id = $(span).closest("article").attr('id');
    var frame_id = $(span).closest(".frame").data("frameid");

    var request = $.ajax({
        url: '/update/',
        type: 'POST',
        data: {
            field: $(span).data("field"),
            vn_class: vn_class_id,
            frame_id: frame_id,
            label: new_val,
        }
    });
}

function edited_frameset_field(input_field, span) {
    var that = span;
    var new_val = $(input_field).val();

    var vn_class_id = $(span).closest("article").attr('id');
    var frameset_id = $(span).closest(".subclass").attr('id');
    var field = $(span).data("field");

    var request = $.ajax({
        url: '/update/',
        type: 'POST',
        data: {
            field: field,
            vn_class: vn_class_id,
            frameset_id: frameset_id,
            label: new_val,
        }
    });

    if (field == 'lvf_string' || field == 'ladl_string') {
        request.done(function() { update_class(that); });
    }
}

$(document).ready(function() {
    // Show relation between verbs and origin
    $('.translations span').hover(toggleHighlightMembers, toggleHighlightMembers);
    $('.members span').hover(toggleHighlightCandidates, toggleHighlightCandidates);

    // Show dark/gray verbs
    show_plus();

    var csrftoken = getCookie('csrftoken');
    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
                // Send the token to same-origin, relative URLs only.
                // Send the token only if the method warrants CSRF protection
                // Using the CSRFToken value acquired earlier
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });

    var previous_timeout = -1;

    $(document).ajaxStart(function(e, request, settings) {
        $("#ajax-ok").hide();
        $("#ajax-loading").show();
    });
    $(document).ajaxSuccess(function(e, request, settings) {
        var is_vn_class = settings.url.indexOf("/vn_class/") == 0;
        var is_update = settings.url.indexOf("update") >= 0;
        var is_lvf_or_ladl = settings.data != undefined && (settings.data.indexOf("lvf_string") >= 0 || settings.data.indexOf("ladl_string") >= 0);
        if(is_vn_class || (is_update && !is_lvf_or_ladl)) {
            $("#ajax-loading").hide();
            $("#ajax-ok").show();
            clearTimeout(previous_timeout);
            previous_timeout = setTimeout(function() {
                $("#ajax-ok").fadeOut('slow');
            }, 10000);
        }
    });
    $(document).ajaxError(function(e, request, settings) {
        alert("Erreur : modification non prise en compte. Je vais regarder ce qui se passe.");
        location.reload(true);
    });

    editable_class_fields();

    // remove frame
    $(document).on('click', '.remove_frame', function() {
        var that = this;
        var vn_class_id = $(this).closest("article").attr('id');
        var frame_id = $(this).closest(".frame").data("frameid");

        var request = $.ajax({
            url: '/remove/',
            type: 'POST',
            data: {
                model: 'VerbNetFrame',
                vn_class: vn_class_id,
                frame_id: frame_id,
            }
        });

        request.done(function() { update_class(that); });

        return false;
    });

    // new frame
    $(document).on('click', 'button.new_frame', function() {
        $(this).hide();
        var form = $(this).parent().next(".frame");
        form.slideDown();
    });

    $(document).on('submit', 'form.new_frame', function() {
        var that = this;
        var data = $(this).serialize();
        var request = $.post($(this).attr('action'), data);

        request.done(function() { update_class(that); });

        return false;
    });

    // new subclass
    $(document).on('click', 'button.new_subclass', function() {
        var that = this;

        var request = $.ajax({
            url: '/add/',
            type: 'POST',
            data: {
               type: 'subclass',
               frameset_id: $(this).data("frameset_id"),
            }
        });

        request.done(function() { update_class(that); });
        return false;
    });

    // remove subclass
    $(document).on('click', 'button.remove_subclass', function() {
        var that = this;

        var request = $.ajax({
            url: '/remove/',
            type: 'POST',
            data: {
                model: 'VerbNetFrameSet',
                frameset_id: $(this).data("frameset_id"),
            }
        });

        request.done(function() { update_class(that); });
        return false;
    });

    // show subclass
    $(document).on('click', 'button.show_subclass', function() {
        var that = this;

        var request = $.ajax({
            url: '/show/',
            type: 'POST',
            data: {
                model: 'VerbNetFrameSet',
                frameset_id: $(this).data("frameset_id"),
            }
        });
        request.done(function() { update_class(that); });
        return false;
    });

    // show frame
    $(document).on('click', 'button.show_frame', function() {
        var that = this;

        var request = $.ajax({
            url: '/show/',
            type: 'POST',
            data: {
                model: 'VerbNetFrame',
                frame_id: $(this).data("frame_id")
            }
        });

        request.done(function() { update_class(that); });
        return false;
    });

});

<|endoftext|>


<commit_before>/*
This file is part of the GhostRunner project by Aravinda Meewalaarachchi.

Copyright (C) 2016 Aravinda Meewalaarachchi <aravinda.mailbox@gmail.com>
Licensed under the MIT License, Permission is hereby granted, free of charge,
to any person obtaining a copyof this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the
following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

*/

//this function will perform a click event on given DOM object
function runnerClick( domObject,  value){
try{
  switch (domObject) {
    case "id"    : document.getElementById(value).click();
                   console.log("status pass : button clicked ",domObject,value);
                   break;
    case "class" : document.getElementsByClassName(value).click();
                   console.log("status pass : button clicked",domObject,value);
                   break;
    case "xpath" : var iterator = document.evaluate( value,
                   document, null, XPathResult.ANY_TYPE, null );
                   try {
                      var thisNode = iterator.iterateNext();
                      thisNode.click();
                   }
                   catch (e) {
                      console.log( 'Error: Document tree modified during iteration ' + e );
                   }
                   console.log("status pass : button clicked",domObject,value);
                   break;
    case "css"   : document.getElementById(value).click();//ToDo-must impliment
                   console.log("status pass : button clicked",domObject,value);
                   break;
    case "tag"   : document.getElementById(value).click();//ToDo-much more detailed implimentation
                   console.log("status pass : button clicked",domObject,value);
                   break;
    default      : console.log("status fail : domObject type not supported");
}
}catch(err){
  console.log(err);
}
}

function runnerType(domObject, value, text){
  try{
    switch (domObject) {
      case "id"    : document.getElementById(value).value = text;
                     console.log("status pass : string "+ text +" typed on.",domObject,value);
                     break;
      case "class" : document.getElementsByClassName(value).value = text;
                     console.log("status pass : string "+text+" typed on.",domObject,value);
                     break;
      case "xpath" : var iterator = document.evaluate( value,
                     document, null, XPathResult.ANY_TYPE, null );
                     try {
                        var thisNode = iterator.iterateNext();
                        thisNode.value = text;
                     }
                     catch (e) {
                        console.log( 'Error: Document tree modified during iteration ' + e );
                     }
                     console.log("status pass : string "+text+" typed on.",domObject,value);
                     break;
      case "css"   : document.getElementById(value).value = text;
                     console.log("status pass : string "+text+" typed on.",domObject,value);
                     break;
      case "tag"   : document.getElementById(value).value = text;
                     console.log("status pass : string "+text+" typed on.",domObject,value);
      default      : console.log("status fail : domObject type not supported");
  }
  }catch(err){
    console.log(err);
  }
}

//this function will wait until given specific time (miliseconds)
function wait(time){
  try{
  var e = new Date().getTime() + time;
  while (new Date().getTime() <= e) {}
}catch(err){
  console.log(err);
}
}

//Function will inspect the given dom element and notify that element is present
//or not in side the page

function isElementPresent(domObject, value){
  try{
    switch (domObject) {
      case "id"    : var present = document.getElementById(value);
                     return check(present);
                     break;
      case "class" : var present = document.getElementsByClassName(value);
                     return check(present);
                     break;
      case "xpath" : var present = document.getElementById(value);//toDo-must impliment
                     return check(present);
                     break;
      case "css"   : var present = document.getElementById(value);//ToDo-must impliment
                     return check(present);
                     break;
      case "tag"   : var present = document.getElementById(value);//ToDo-much more detailed implimentation
                     return check(present);
                     break;
      default      : console.log("status fail : domObject type not supported");
                     return false;
  }
  }catch(err){
    console.log(err);
  }
  function check(present){
    if(present!= null){
         console.log("status pass : Element present",domObject,value);
         return true;
     }
    else {
      console.log("status fail : Element not present ",domObject,value);
      return false;
    }
  }

}

//This function will handle the browser navigations

function navagateTo(url){
  try{
    window.location.href=url;
    console.log("status pass : Navigated to " + url);
  }catch(err){
    console.log("status fail : Broken link  or no network connection");
  }
}

//This function will navigate one step back from current position in recent history
function navigateBack(){
  try{
    window.history.back();
    console.log("status pass : Navigated one step back from current position in recent history" + url);
  }catch(err){
    console.log("status fail : Broken link  or no network connection");
  }
}
<commit_msg>getTitle function added<commit_after>/*
This file is part of the GhostRunner project by Aravinda Meewalaarachchi.

Copyright (C) 2016 Aravinda Meewalaarachchi <aravinda.mailbox@gmail.com>
Licensed under the MIT License, Permission is hereby granted, free of charge,
to any person obtaining a copyof this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the
following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

*/

//this function will perform a click event on given DOM object
function runnerClick( domObject,  value){
try{
  switch (domObject) {
    case "id"    : document.getElementById(value).click();
                   console.log("status pass : button clicked ",domObject,value);
                   break;
    case "class" : document.getElementsByClassName(value).click();
                   console.log("status pass : button clicked",domObject,value);
                   break;
    case "xpath" : var iterator = document.evaluate( value,
                   document, null, XPathResult.ANY_TYPE, null );
                   try {
                      var thisNode = iterator.iterateNext();
                      thisNode.click();
                   }
                   catch (e) {
                      console.log( 'Error: Document tree modified during iteration ' + e );
                   }
                   console.log("status pass : button clicked",domObject,value);
                   break;
    case "css"   : document.getElementById(value).click();//ToDo-must impliment
                   console.log("status pass : button clicked",domObject,value);
                   break;
    case "tag"   : document.getElementById(value).click();//ToDo-much more detailed implimentation
                   console.log("status pass : button clicked",domObject,value);
                   break;
    default      : console.log("status fail : domObject type not supported");
}
}catch(err){
  console.log(err);
}
}

function runnerType(domObject, value, text){
  try{
    switch (domObject) {
      case "id"    : document.getElementById(value).value = text;
                     console.log("status pass : string "+ text +" typed on.",domObject,value);
                     break;
      case "class" : document.getElementsByClassName(value).value = text;
                     console.log("status pass : string "+text+" typed on.",domObject,value);
                     break;
      case "xpath" : var iterator = document.evaluate( value,
                     document, null, XPathResult.ANY_TYPE, null );
                     try {
                        var thisNode = iterator.iterateNext();
                        thisNode.value = text;
                     }
                     catch (e) {
                        console.log( 'Error: Document tree modified during iteration ' + e );
                     }
                     console.log("status pass : string "+text+" typed on.",domObject,value);
                     break;
      case "css"   : document.getElementById(value).value = text;
                     console.log("status pass : string "+text+" typed on.",domObject,value);
                     break;
      case "tag"   : document.getElementById(value).value = text;
                     console.log("status pass : string "+text+" typed on.",domObject,value);
      default      : console.log("status fail : domObject type not supported");
  }
  }catch(err){
    console.log(err);
  }
}

//this function will wait until given specific time (miliseconds)
function wait(time){
  try{
  var e = new Date().getTime() + time;
  while (new Date().getTime() <= e) {}
}catch(err){
  console.log(err);
}
}

//Function will inspect the given dom element and notify that element is present
//or not in side the page

function isElementPresent(domObject, value){
  try{
    switch (domObject) {
      case "id"    : var present = document.getElementById(value);
                     return check(present);
                     break;
      case "class" : var present = document.getElementsByClassName(value);
                     return check(present);
                     break;
      case "xpath" : var present = document.getElementById(value);//toDo-must impliment
                     return check(present);
                     break;
      case "css"   : var present = document.getElementById(value);//ToDo-must impliment
                     return check(present);
                     break;
      case "tag"   : var present = document.getElementById(value);//ToDo-much more detailed implimentation
                     return check(present);
                     break;
      default      : console.log("status fail : domObject type not supported");
                     return false;
  }
  }catch(err){
    console.log(err);
  }
  function check(present){
    if(present!= null){
         console.log("status pass : Element present",domObject,value);
         return true;
     }
    else {
      console.log("status fail : Element not present ",domObject,value);
      return false;
    }
  }

}

//This function will handle the browser navigations

function navagateTo(url){
  try{
    window.location.href=url;
    console.log("status pass : Navigated to " + url);
  }catch(err){
    console.log("status fail : Broken link  or no network connection");
  }
}

//This function will navigate one step back from current position in recent history
function navigateBack(){
  try{
    window.history.back();
    console.log("status pass : Navigated one step back from current position in recent history" + url);
  }catch(err){
    console.log("status fail : Broken link  or no network connection");
  }
}
//This function will return the title of the web page

function getTitle(){
  return document.title;
}
<|endoftext|>