<commit_before>$(function () {
	$(".tool-tip").each(function () {
		$(this).tooltip({
			container: 'body',
		});
	});

	$(".url-text").click(function() {
		$(this).select();
	});

	$("#delete-confirm-btn").click(function () {
		$("#delete-modal").modal('hide');
		deleteImage(function () {
			location.href = '/';
		});
	});

	$("#update-submit-btn").click(function () {
		updateImage();
	});

	function deleteImage(cb) {
		$.ajax({
			type: 'DELETE',
			success: function(res) {
				if (res.res == 'nosuchimage') {
					showError("존재하지 않는 이미지입니다");
				} else if (res.res == 'notmine') {
					showError("자신의 이미지가 아닌 이미지는 삭제 할 수 없습니다");
				} else if (res.res == 'success') {
					if (typeof cb == 'function') { cb(); }
				}
			}
		});
	}

	function updateImage() {
		$.ajax({
			type: 'PUT',
			data: {'nsfw': $("input:checkbox[name='nsfw']").is(":checked"),
					'anonymous': $("input:checkbox[name='anonymous']").is(":checked"),
					'private': $("input:checkbox[name='private']").is(":checked"),
					},
			success: function(res) {
				if (res.res == 'success') {
					showSuccess("설정을 저장하였습니다");
				} else if (res.res == 'nosuchimage') {
					showError("존재하지 않는 이미지입니다");
				} else if (res.res == 'notmine') {
					showError("자신의 이미지가 아닌 이미지의 설정은 바꿀 수 없습니다");
				}
			}
		});
	}

	$("#shownsfw-confirm-btn").click(function() {
		$(".content-image").removeClass("nsfw");
		$(".content-image").css("visibility", "visible");
		$(".canvas-area").remove();
		$("#nsfw-modal").modal("hide");
	});

	$("#nsfw-modal").on('hide.bs.modal', function(e) {
		if ($(".content-image").hasClass("nsfw")) {
			$(".content-area > .panel-body").css('visibility', 'hidden');
			showError("이미지를 표시하지 않습니다");
		}
	});

	if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
		if (new Number(RegExp.$1) >= 10.0 || !!navigator.userAgent.match(/Trident.*rv[ :]*11\./)) {
			if ($(".content-image").hasClass("nsfw")) {
				$(".content-image").css("visibility", "hidden");
				$(".content-image").attr('src', $(".content-image").parent().attr('href')).load(function() {
					console.log($(".content-image").parent().attr('href'));
					$(".content-area > .panel-body").append('
<canvas id="blur-canvas"></canvas>
');
					integralBlurImage( 'content-image', 'blur-canvas', 200, false, 1 );
					$(".canvas-area").offset($(".image-area").offset());
					$(".canvas-area").width($(".image-area").width()).height($(".image-area").height());
					$("#blur-canvas").width($(".image-area").width()).height($(".image-area").height());
				});
			}
		}
	}
});
<commit_msg>I HATE IE<commit_after>$(function () {
	$(".tool-tip").each(function () {
		$(this).tooltip({
			container: 'body',
		});
	});

	$(".url-text").click(function() {
		$(this).select();
	});

	$("#delete-confirm-btn").click(function () {
		$("#delete-modal").modal('hide');
		deleteImage(function () {
			location.href = '/';
		});
	});

	$("#update-submit-btn").click(function () {
		updateImage();
	});

	function deleteImage(cb) {
		$.ajax({
			type: 'DELETE',
			success: function(res) {
				if (res.res == 'nosuchimage') {
					showError("존재하지 않는 이미지입니다");
				} else if (res.res == 'notmine') {
					showError("자신의 이미지가 아닌 이미지는 삭제 할 수 없습니다");
				} else if (res.res == 'success') {
					if (typeof cb == 'function') { cb(); }
				}
			}
		});
	}

	function updateImage() {
		$.ajax({
			type: 'PUT',
			data: {'nsfw': $("input:checkbox[name='nsfw']").is(":checked"),
					'anonymous': $("input:checkbox[name='anonymous']").is(":checked"),
					'private': $("input:checkbox[name='private']").is(":checked"),
					},
			success: function(res) {
				if (res.res == 'success') {
					showSuccess("설정을 저장하였습니다");
				} else if (res.res == 'nosuchimage') {
					showError("존재하지 않는 이미지입니다");
				} else if (res.res == 'notmine') {
					showError("자신의 이미지가 아닌 이미지의 설정은 바꿀 수 없습니다");
				}
			}
		});
	}

	$("#shownsfw-confirm-btn").click(function() {
		$(".content-image").removeClass("nsfw");
		$(".content-image").css("visibility", "visible");
		$(".canvas-area").remove();
		$("#nsfw-modal").modal("hide");
	});

	$("#nsfw-modal").on('hide.bs.modal', function(e) {
		if ($(".content-image").hasClass("nsfw")) {
			$(".content-area > .panel-body").css('visibility', 'hidden');
			showError("이미지를 표시하지 않습니다");
		}
	});

	if ((/MSIE (\d+\.\d+);/.test(navigator.userAgent) && new Number(RegExp.$1) >= 10.0) || !!navigator.userAgent.match(/Trident.*rv[ :]*11\./)) {
		if ($(".content-image").hasClass("nsfw")) {
			$(".content-image").css("visibility", "hidden");
			$(".content-image").attr('src', $(".content-image").parent().attr('href')).load(function() {
				console.log($(".content-image").parent().attr('href'));
				$(".content-area > .panel-body").append('
<canvas id="blur-canvas"></canvas>
');
				integralBlurImage( 'content-image', 'blur-canvas', 200, false, 1 );
				$(".canvas-area").offset($(".image-area").offset());
				$(".canvas-area").width($(".image-area").width()).height($(".image-area").height());
				$("#blur-canvas").width($(".image-area").width()).height($(".image-area").height());
			});
		}
	}
});
<|endoftext|>


<commit_before>$('.dropdown-toggle').dropdown();

if ($('#messages').attr('data-show')) {
	$('#messages').modal();
}

function countProperties(obj) {
	var count = 0;
	for(var prop in obj) {
		if(obj.hasOwnProperty(prop))
			++count;
	}
	return count;
}

function GoreadCtrl($scope, $http, $timeout) {
	$scope.loading = 0;
	$scope.contents = {};

	$scope.importOpml = function() {
		$scope.shown = 'feeds';
		$scope.loading++;
		$('#import-opml-form').ajaxForm(function() {
			$('#import-opml-form')[0].reset();
			$scope.loaded();
			$scope.showMessage('OPML is importing. May take a bit. Refresh at will.');
		});
	};

	$scope.loaded = function() {
		$scope.loading--;
	};

	$scope.http = function(method, url, data) {
		return $http({
			method: method,
			url: url,
			data: $.param(data),
			headers: {'Content-Type': 'application/x-www-form-urlencoded'}
		});
	};

	$scope.addSubscription = function() {
		if (!$scope.addFeedUrl) {
			return false;
		}
		$scope.loading++;
		var f = $('#add-subscription-form');
		$scope.http('POST', f.attr('data-url'), {
			url: $scope.addFeedUrl
		}).then(function() {
			$scope.addFeedUrl = '';
			// I think this is needed due to the datastore's eventual consistency.
			// Without the delay we only get the feed data with no story data.
			$timeout(function() {
				$scope.refresh($scope.loaded);
			}, 250);
		}, function(data) {
			if (data.data) {
				alert(data.data);
			}
			$scope.loading--;
		});
	};

	$scope.refresh = function(cb) {
		$scope.loading++;
		$scope.shown = 'feeds';
		delete $scope.currentStory;
		$http.get($('#refresh').attr('data-url-feeds'))
			.success(function(data) {
				$scope.feeds = data;
				$scope.numfeeds = 0;
				$scope.stories = [];
				$scope.unreadStories = {};
				var today = new Date().toDateString();
				for(var p in $scope.feeds) {
					$scope.numfeeds++;
					var f = $scope.feeds[p];
					if (!f.Stories)
						continue;
					for(var i = 0; i < f.Stories.length; i++) {
						f.Stories[i].feed = f.Feed;
						var d = new Date(f.Stories[i].Date * 1000);
						if (d.toDateString() == today) {
							f.Stories[i].dispdate = d.format("shortTime");
						} else {
							f.Stories[i].dispdate = d.format("mediumDate");
						}
						f.Stories[i].read = false;
						f.Stories[i].guid = f.Feed.Url + '|' + f.Stories[i].Id;
						if (!f.Stories[i].Title) {
							f.Stories[i].Title = '(title unknown)';
						}
						$scope.stories.push(f.Stories[i]);
						$scope.unreadStories[f.Stories[i].Id] = true;
					}
					$scope.stories.sort(function(a, b) {
						return b.Date - a.Date;
					});
				}
				if (typeof cb === 'function') cb();
				$scope.loaded();
			})
			.error(function() {
				if (typeof cb === 'function') cb();
				$scope.loaded();
			});
	};

	$scope.setCurrent = function(i) {
		if (i == $scope.currentStory) {
			delete $scope.currentStory;
			return;
		}
		var story = $scope.stories[i];
		$scope.getContents(story);
		if (i > 0) {
			$scope.getContents($scope.stories[i - 1]);
		}
		if (i < $scope.stories.length - 2) {
			$scope.getContents($scope.stories[i + 1]);
		}
		$('#story' + $scope.currentStory).empty();
		$scope.currentStory = i;
		$scope.markRead(story);
		$('#story' + i).html($scope.contents[story.guid] || '');
		setTimeout(function() {
			se = $('#storydiv' + i);
			var docTop = $(window).scrollTop() + 40;
			var docBottom = docTop + $(window).height() + 40;
			var eTop = se.offset().top;
			if (docTop > eTop || docBottom < eTop) {
				window.scrollTo(0, eTop - 40);
			}
		});
	};
	$scope.prev = function() {
		if ($scope.currentStory > 0) {
			$scope.setCurrent($scope.currentStory - 1);
		}
	};
	$scope.next = function() {
		if ($scope.stories && typeof $scope.currentStory === 'undefined') {
			$scope.setCurrent(0);
		} else if ($scope.stories && $scope.currentStory < $scope.stories.length - 1) {
			$scope.setCurrent($scope.currentStory + 1);
		}
	};

	$scope.unread = function() {
		return countProperties($scope.unreadStories);
	};

	$scope.markRead = function(s) {
		if ($scope.unreadStories[s.Id]) {
			delete $scope.unreadStories[s.Id];
			s.read = true;
			$scope.http('POST', $('#mark-all-read').attr('data-url-read'), {
				feed: s.feed.Url,
				story: s.Id
			});
		}
	};

	$scope.markAllRead = function(s) {
		$scope.unreadStories = {};
		$scope.stories = [];
		$http.post($('#mark-all-read').attr('data-url'));
	};

	$scope.nothing = function() {
		return $scope.loading == 0 && $scope.stories && !$scope.numfeeds;
	};

	$scope.toggleNav = function() {
		$scope.nav = !$scope.nav;
	}
	$scope.navspan = function() {
		return 'span' + ($scope.nav ? '10' : '12');
	};
	$scope.navmargin = function() {
		return $scope.nav ? {} : {'margin-left': '0'};
	};

	$scope.overContents = function(s) {
		if (typeof $scope.contents[s.guid] !== 'undefined') {
			return;
		}
		s.getTimeout = $timeout(function() {
			$scope.getContents(s);
		}, 250);
	};
	$scope.leaveContents = function(s) {
		if (s.getTimeout) {
			$timeout.cancel(s.getTimeout);
		}
	};

	$scope.toFetch = [];
	$scope.getContents = function(s) {
		if (typeof $scope.contents[s.guid] !== 'undefined') {
			return;
		}
		$scope.toFetch.push(s);
		if (!$scope.fetchPromise) {
			$scope.fetchPromise = $timeout($scope.fetchContents);
		}
	};

	$scope.fetchContents = function() {
		delete $scope.fetchPromise;
		if ($scope.toFetch.length == 0) {
			return;
		}
		var tofetch = $scope.toFetch;
		$scope.toFetch = [];
		var data = [];
		for (var i = 0; i < tofetch.length; i++) {
			console.log("fetch " + tofetch[i].Title);
			$scope.contents[tofetch[i].guid] = '';
			data.push({
				Feed: tofetch[i].feed.Url,
				Story: tofetch[i].Id
			});
		}
		$http.post($('#mark-all-read').attr('data-url-contents'), data)
			.success(function(data) {
				var current = '';
				if ($scope.stories[$scope.currentStory]) {
					current = $scope.stories[$scope.currentStory].guid;
				}
				for (var i = 0; i < data.length; i++) {
					$scope.contents[tofetch[i].guid] = data[i];
					if (current == tofetch[i].guid) {
						$('#story' + $scope.currentStory).html(data[i]);
					}
				}
			});
	};

	var shortcuts = $('#shortcuts');
	Mousetrap.bind('?', function() {
		shortcuts.modal('toggle');
	});
	Mousetrap.bind('esc', function() {
		shortcuts.modal('hide');
	});
	Mousetrap.bind('r', function() {
		if ($scope.nouser) {
			return;
		}
		$scope.$apply($scope.refresh());
	});
	Mousetrap.bind(['j', 'n'], function() {
		$scope.$apply('next()');
	});
	Mousetrap.bind(['k', 'p'], function() {
		$scope.$apply('prev()');
	});
	Mousetrap.bind('v', function() {
		if ($scope.stories[$scope.currentStory]) {
			window.open($scope.stories[$scope.currentStory].Link);
		}
	});
	Mousetrap.bind('shift+a', function() {
		if ($scope.nouser) {
			return;
		}
		$scope.$apply($scope.markAllRead());
	});
	Mousetrap.bind('a', function() {
		if ($scope.nouser) {
			return;
		}
		$scope.$apply("shown = 'add-subscription'");

		// need to wait for the keypress to finish before focusing
		setTimeout(function() {
			$('#add-subscription-form input').focus();
		}, 0);
	});
	Mousetrap.bind('g a', function() {
		if ($scope.nouser) {
			return;
		}
		$scope.$apply("shown = 'feeds'");
	});
	Mousetrap.bind('u', function() {
		$scope.$apply("toggleNav()");
	});

	$scope.showMessage = function(m) {
		$('#message-list').text(m);
		$('#messages').modal('show');
	};
}
<commit_msg>Remove debug<commit_after>$('.dropdown-toggle').dropdown();

if ($('#messages').attr('data-show')) {
	$('#messages').modal();
}

function countProperties(obj) {
	var count = 0;
	for(var prop in obj) {
		if(obj.hasOwnProperty(prop))
			++count;
	}
	return count;
}

function GoreadCtrl($scope, $http, $timeout) {
	$scope.loading = 0;
	$scope.contents = {};

	$scope.importOpml = function() {
		$scope.shown = 'feeds';
		$scope.loading++;
		$('#import-opml-form').ajaxForm(function() {
			$('#import-opml-form')[0].reset();
			$scope.loaded();
			$scope.showMessage('OPML is importing. May take a bit. Refresh at will.');
		});
	};

	$scope.loaded = function() {
		$scope.loading--;
	};

	$scope.http = function(method, url, data) {
		return $http({
			method: method,
			url: url,
			data: $.param(data),
			headers: {'Content-Type': 'application/x-www-form-urlencoded'}
		});
	};

	$scope.addSubscription = function() {
		if (!$scope.addFeedUrl) {
			return false;
		}
		$scope.loading++;
		var f = $('#add-subscription-form');
		$scope.http('POST', f.attr('data-url'), {
			url: $scope.addFeedUrl
		}).then(function() {
			$scope.addFeedUrl = '';
			// I think this is needed due to the datastore's eventual consistency.
			// Without the delay we only get the feed data with no story data.
			$timeout(function() {
				$scope.refresh($scope.loaded);
			}, 250);
		}, function(data) {
			if (data.data) {
				alert(data.data);
			}
			$scope.loading--;
		});
	};

	$scope.refresh = function(cb) {
		$scope.loading++;
		$scope.shown = 'feeds';
		delete $scope.currentStory;
		$http.get($('#refresh').attr('data-url-feeds'))
			.success(function(data) {
				$scope.feeds = data;
				$scope.numfeeds = 0;
				$scope.stories = [];
				$scope.unreadStories = {};
				var today = new Date().toDateString();
				for(var p in $scope.feeds) {
					$scope.numfeeds++;
					var f = $scope.feeds[p];
					if (!f.Stories)
						continue;
					for(var i = 0; i < f.Stories.length; i++) {
						f.Stories[i].feed = f.Feed;
						var d = new Date(f.Stories[i].Date * 1000);
						if (d.toDateString() == today) {
							f.Stories[i].dispdate = d.format("shortTime");
						} else {
							f.Stories[i].dispdate = d.format("mediumDate");
						}
						f.Stories[i].read = false;
						f.Stories[i].guid = f.Feed.Url + '|' + f.Stories[i].Id;
						if (!f.Stories[i].Title) {
							f.Stories[i].Title = '(title unknown)';
						}
						$scope.stories.push(f.Stories[i]);
						$scope.unreadStories[f.Stories[i].Id] = true;
					}
					$scope.stories.sort(function(a, b) {
						return b.Date - a.Date;
					});
				}
				if (typeof cb === 'function') cb();
				$scope.loaded();
			})
			.error(function() {
				if (typeof cb === 'function') cb();
				$scope.loaded();
			});
	};

	$scope.setCurrent = function(i) {
		if (i == $scope.currentStory) {
			delete $scope.currentStory;
			return;
		}
		var story = $scope.stories[i];
		$scope.getContents(story);
		if (i > 0) {
			$scope.getContents($scope.stories[i - 1]);
		}
		if (i < $scope.stories.length - 2) {
			$scope.getContents($scope.stories[i + 1]);
		}
		$('#story' + $scope.currentStory).empty();
		$scope.currentStory = i;
		$scope.markRead(story);
		$('#story' + i).html($scope.contents[story.guid] || '');
		setTimeout(function() {
			se = $('#storydiv' + i);
			var docTop = $(window).scrollTop() + 40;
			var docBottom = docTop + $(window).height() + 40;
			var eTop = se.offset().top;
			if (docTop > eTop || docBottom < eTop) {
				window.scrollTo(0, eTop - 40);
			}
		});
	};
	$scope.prev = function() {
		if ($scope.currentStory > 0) {
			$scope.setCurrent($scope.currentStory - 1);
		}
	};
	$scope.next = function() {
		if ($scope.stories && typeof $scope.currentStory === 'undefined') {
			$scope.setCurrent(0);
		} else if ($scope.stories && $scope.currentStory < $scope.stories.length - 1) {
			$scope.setCurrent($scope.currentStory + 1);
		}
	};

	$scope.unread = function() {
		return countProperties($scope.unreadStories);
	};

	$scope.markRead = function(s) {
		if ($scope.unreadStories[s.Id]) {
			delete $scope.unreadStories[s.Id];
			s.read = true;
			$scope.http('POST', $('#mark-all-read').attr('data-url-read'), {
				feed: s.feed.Url,
				story: s.Id
			});
		}
	};

	$scope.markAllRead = function(s) {
		$scope.unreadStories = {};
		$scope.stories = [];
		$http.post($('#mark-all-read').attr('data-url'));
	};

	$scope.nothing = function() {
		return $scope.loading == 0 && $scope.stories && !$scope.numfeeds;
	};

	$scope.toggleNav = function() {
		$scope.nav = !$scope.nav;
	}
	$scope.navspan = function() {
		return 'span' + ($scope.nav ? '10' : '12');
	};
	$scope.navmargin = function() {
		return $scope.nav ? {} : {'margin-left': '0'};
	};

	$scope.overContents = function(s) {
		if (typeof $scope.contents[s.guid] !== 'undefined') {
			return;
		}
		s.getTimeout = $timeout(function() {
			$scope.getContents(s);
		}, 250);
	};
	$scope.leaveContents = function(s) {
		if (s.getTimeout) {
			$timeout.cancel(s.getTimeout);
		}
	};

	$scope.toFetch = [];
	$scope.getContents = function(s) {
		if (typeof $scope.contents[s.guid] !== 'undefined') {
			return;
		}
		$scope.toFetch.push(s);
		if (!$scope.fetchPromise) {
			$scope.fetchPromise = $timeout($scope.fetchContents);
		}
	};

	$scope.fetchContents = function() {
		delete $scope.fetchPromise;
		if ($scope.toFetch.length == 0) {
			return;
		}
		var tofetch = $scope.toFetch;
		$scope.toFetch = [];
		var data = [];
		for (var i = 0; i < tofetch.length; i++) {
			$scope.contents[tofetch[i].guid] = '';
			data.push({
				Feed: tofetch[i].feed.Url,
				Story: tofetch[i].Id
			});
		}
		$http.post($('#mark-all-read').attr('data-url-contents'), data)
			.success(function(data) {
				var current = '';
				if ($scope.stories[$scope.currentStory]) {
					current = $scope.stories[$scope.currentStory].guid;
				}
				for (var i = 0; i < data.length; i++) {
					$scope.contents[tofetch[i].guid] = data[i];
					if (current == tofetch[i].guid) {
						$('#story' + $scope.currentStory).html(data[i]);
					}
				}
			});
	};

	var shortcuts = $('#shortcuts');
	Mousetrap.bind('?', function() {
		shortcuts.modal('toggle');
	});
	Mousetrap.bind('esc', function() {
		shortcuts.modal('hide');
	});
	Mousetrap.bind('r', function() {
		if ($scope.nouser) {
			return;
		}
		$scope.$apply($scope.refresh());
	});
	Mousetrap.bind(['j', 'n'], function() {
		$scope.$apply('next()');
	});
	Mousetrap.bind(['k', 'p'], function() {
		$scope.$apply('prev()');
	});
	Mousetrap.bind('v', function() {
		if ($scope.stories[$scope.currentStory]) {
			window.open($scope.stories[$scope.currentStory].Link);
		}
	});
	Mousetrap.bind('shift+a', function() {
		if ($scope.nouser) {
			return;
		}
		$scope.$apply($scope.markAllRead());
	});
	Mousetrap.bind('a', function() {
		if ($scope.nouser) {
			return;
		}
		$scope.$apply("shown = 'add-subscription'");

		// need to wait for the keypress to finish before focusing
		setTimeout(function() {
			$('#add-subscription-form input').focus();
		}, 0);
	});
	Mousetrap.bind('g a', function() {
		if ($scope.nouser) {
			return;
		}
		$scope.$apply("shown = 'feeds'");
	});
	Mousetrap.bind('u', function() {
		$scope.$apply("toggleNav()");
	});

	$scope.showMessage = function(m) {
		$('#message-list').text(m);
		$('#messages').modal('show');
	};
}
<|endoftext|>


<commit_before>var handlers = {
    HelloWorld: function () {
        return helpers.HelloWorld();
    }
};<commit_msg>update<commit_after>var handlers = {
    GetHelloWorld: function () {
        return helpers.HelloWorld();
    }
};<|endoftext|>


<commit_before>
if (typeof jQuery === "undefined") {
    throw new Error("jQuery lib is missing.");
}

var handle_submit = function() {
    var query = $("#query").val();
    $.ajax('/answer', {
        method: "POST",
        dataType: "json",
        data: {
            q: query,
            lat: 39.983424,
            lng: 116.322987,
        },
        success: function(data, state, jqXHR) {
            if (!data || !('errno' in data) || !('errmsg' in data) ||
                    !('data' in data) || !('reprtype' in data)) {
                console.log("returned data is not valid.");
                return;
            }

            if (data.errno > 0) {
                console.log("server error: " + data.errno + "\n" + data.errmsg);
                return;
            }

            render_data(data.data, data.reprtype);
        },
        error: function(jqXHR, state, err) {
            console.log(state + ": answer server api error\n" + err)
        }
    });

    return false;
};

var render_data = function(pois, reprtype) {
    $("#searchresult").html("")
    for (var idx in pois) {
        var row = $("
").addClass("row");
        var name = $("").text(pois[idx].name).addClass("col-md-2");
        var addr = $("").text(pois[idx].addr).addClass("col-md-3");
        var rating = $("").text(pois[idx].rating).addClass("col-md-1");

        var phone_str = pois[idx].phone;
        if (phone_str) { phone_str = phone_str.replace(/[, \|]/g, '$& '); }
        var phone = $("").text(phone_str).addClass("col-md-1");

        var tag = $("").text(pois[idx].class).addClass("col-md-1");
        var loc = $("")
            .text(pois[idx].lng + "," + pois[idx].lat)
            .addClass("col-md-2");
        var more = $("").addClass("col-md-1")
            .append($("").attr("href", pois[idx].url)
                    .attr("target", "_blank").text("more"));

        row.append(name);
        row.append(addr);
        row.append(rating);
        row.append(phone);
        row.append(tag);
        row.append(loc);
        row.append(more);

        $("#searchresult").append(row);
    }
};

+function($){
    $("#searchform").submit(handle_submit);
}(jQuery);
<commit_msg>display the predicate-value on FE<commit_after>
if (typeof jQuery === "undefined") {
    throw new Error("jQuery lib is missing.");
}

var handle_submit = function() {
    var query = $("#query").val();
    $.ajax('/answer', {
        method: "POST",
        dataType: "json",
        data: {
            q: query,
            lat: 39.983424,
            lng: 116.322987,
        },
        success: function(data, state, jqXHR) {
            if (!data || !('errno' in data) || !('errmsg' in data) ||
                    !('data' in data)) {
                console.log("returned data is not valid.");
                return;
            }

            if (data.errno > 0) {
                console.log("server error: " + data.errno + "\n" + data.errmsg);
                return;
            }

            render_data(data.data, data.reprtype);
        },
        error: function(jqXHR, state, err) {
            console.log(state + ": answer server api error\n" + err)
        }
    });

    return false;
};

var render_data = function(pois, reprtype) {
    $("#searchresult").html("")
    for (var idx in pois) {
        var poi = pois[idx];

        var row = $("
").addClass("row");

        var name = $("
").addClass("col-md-2");
        var zh_name = $("");
        if (poi.name) { zh_name.text(poi.name); }
        else if (poi.zh) { zh_name.text(poi.zh); }
        var en_name = $("");
        if (poi.en) { en_name.text(poi.en); }
        var ja_name = $("");
        if (poi.ja) { ja_name.text(poi.ja); }
        name.append(zh_name);
        name.append('
').append(en_name);
        name.append('
').append(ja_name);

        var addr = $("").addClass("col-md-3");
        if (poi.addr) {
            addr.text(poi.addr);
        }

        var rating = $("").addClass("col-md-1");
        if (poi.rating) {
            rating.text(poi.rating);
        }

        var phone = $("").addClass("col-md-1");
        if (poi.phone) {
            phone_str = poi.phone.replace(/[, \|]/g, '$& ');
            phone.text(phone_str)
        }

        var tag = $("").addClass("col-md-1");
        if (poi.class) {
            tag.text(poi.class)
        }

        var loc = $("").addClass("col-md-2");
        if (poi.lng && poi.lat) {
            loc.text(poi.lng + "," + pois[idx].lat)
        }

        var more = $("").addClass("col-md-1");
        if (poi.url) {
            more.append($("").attr("href", poi.url)
                .attr("target", "_blank").text("more"));
        }

        row.append(name);
        row.append(addr);
        row.append(rating);
        row.append(phone);
        row.append(tag);
        row.append(loc);
        row.append(more);

        $("#searchresult").append(row);

        if (poi.general_val && poi.general_func) {
            $("#searchresult").append(
                $("
").addClass("row").append(
                    $("").addClass("col-md-12")
                    .text(poi.general_func + ": " + poi.general_val)
                    )
                )
        }

        $("#searchresult").append("
");
    }
};

+function($){
    $("#searchform").submit(handle_submit);
}(jQuery);
<|endoftext|>


<commit_before>/* eslint global-require: 0 */

const priceParse = require('../modules/priceParse');
const terabyteParse = require('./terabyte/priceparse');

const config = {
	kabum: require('./kabum/config'),
	terabyte: require('./terabyte/config'),
	pichau: require('./pichau/config'),
	balaodainformatica: require('./balaodainformatica/config'),
	americanas: require('./americanas/config'),
};

function StoreMethods() {}

function getName($, store) {
	if (store === 'balaodainformatica') {
		return $(config[store].name)[0].children[0].data.trim();
	}

	return $(config[store].name).text().trim();
}

function getCurrentPrices($, store) {
	let regularPrice = priceParse($(config[store].regularPrice).text().trim()).toString();
	let discountPrice = priceParse($(config[store].discountPrice).text().trim()).toString();

	if (store === 'terabyte') {
		regularPrice = terabyteParse($(config[store].regularPrice).text().trim().toString());
	}

	if (regularPrice === 'NaN' && store === 'kabum') {
		regularPrice = priceParse($(config[store].alternate.regularPrice).text().trim()).toString();
	}

	if (discountPrice === 'NaN' && store === 'kabum') {
		discountPrice = priceParse($(config[store].alternate.discountPrice).text().trim()).toString();
	}

	const json = {
		regularPrice,
		discountPrice,
	};

	return json;
}

function getThumbnail($, store) {
	const element = $(config[store].thumbnail)[0];

	if (store === 'balaodainformatica') {
		return element.attribs['data-zoom-image'] || $(config[store].backupThumbnail)[0].attribs['data-zoom-image'];
	}

	if (element) {
		return element.attribs.src;
	}

	const backup = $(config[store].backupThumbnail)[0];
	if (backup) {
		return backup.attribs.src;
	}

	return null;
}

function newItem($, uri, store) {
	const name = getName($, store);
	const prices = getCurrentPrices($, store);
	const thumbnail = getThumbnail($, store);

	const item = {
		vendor: config[store].vendor.name,
		name,
		regularPrice: prices.regularPrice,
		discountPrice: prices.discountPrice,
		thumbnail,
		uri,
		created_at: new Date(),
	};

	return item;
}

StoreMethods.prototype.getName = getName;
StoreMethods.prototype.getCurrentPrices = getCurrentPrices;
StoreMethods.prototype.getThumbnail = getThumbnail;
StoreMethods.prototype.newItem = newItem;

module.exports = exports = new StoreMethods();
<commit_msg>Terabyte check for NaN, in case of unavailable product.<commit_after>/* eslint global-require: 0 */

const priceParse = require('../modules/priceParse');
const terabyteParse = require('./terabyte/priceparse');

const config = {
	kabum: require('./kabum/config'),
	terabyte: require('./terabyte/config'),
	pichau: require('./pichau/config'),
	balaodainformatica: require('./balaodainformatica/config'),
	americanas: require('./americanas/config'),
};

function StoreMethods() {}

function getName($, store) {
	if (store === 'balaodainformatica') {
		return $(config[store].name)[0].children[0].data.trim();
	}

	return $(config[store].name).text().trim();
}

function getCurrentPrices($, store) {
	const rp = $(config[store].regularPrice);
	const dp = $(config[store].discountPrice);

	let regularPrice;
	let discountPrice;

	// regularPrice
	if (rp.length < 1) {
		regularPrice = NaN;
	} else if (store === 'terabyte') {
		regularPrice = terabyteParse(rp.text().trim().toString());
	} else {
		regularPrice = priceParse(rp.text().trim()).toString();
	}

	if (Number.isNaN(regularPrice)) {
		if (store === 'kabum') {
			regularPrice = priceParse($(config[store].alternate.regularPrice).text().trim()).toString();
		}
	}

	// discountPrice
	if (dp.length < 1) {
		discountPrice = NaN;
	} else {
		discountPrice = priceParse(dp.text().trim()).toString();
	}

	if (Number.isNaN(discountPrice)) {
		if (store === 'kabum') {
			discountPrice = priceParse($(config[store].alternate.discountPrice).text().trim()).toString();
		}
	}

	const json = {
		regularPrice,
		discountPrice,
	};

	return json;
}

function getThumbnail($, store) {
	const element = $(config[store].thumbnail)[0];

	if (store === 'balaodainformatica') {
		return element.attribs['data-zoom-image'] || $(config[store].backupThumbnail)[0].attribs['data-zoom-image'];
	}

	if (element) {
		return element.attribs.src;
	}

	const backup = $(config[store].backupThumbnail)[0];
	if (backup) {
		return backup.attribs.src;
	}

	return null;
}

function newItem($, uri, store) {
	const name = getName($, store);
	const prices = getCurrentPrices($, store);
	const thumbnail = getThumbnail($, store);

	const item = {
		vendor: config[store].vendor.name,
		name,
		regularPrice: prices.regularPrice,
		discountPrice: prices.discountPrice,
		thumbnail,
		uri,
		created_at: new Date(),
	};

	return item;
}

StoreMethods.prototype.getName = getName;
StoreMethods.prototype.getCurrentPrices = getCurrentPrices;
StoreMethods.prototype.getThumbnail = getThumbnail;
StoreMethods.prototype.newItem = newItem;

module.exports = exports = new StoreMethods();
<|endoftext|>


<commit_before>;
// Must first get all script tags if possible.
if(document && document.getElementsByTagName)
	var scripts = document.getElementsByTagName("script");
(function(_, _defineProperty, _doc, _script, _eval) {
// Allows eval to work within a scope.
_eval = function(code) {return _eval(code)};

// Used to store the options for calculating what to do with strap.
var options = {
		use: false,
		srcs: ""
	},
// Gets the parent of the _script tag to append more scripts to if need be.
	_parent = _script.parentNode || _script.parentElement;
/**
 *
 *
 */
function strap(srcs) {
	var collections = srcs.split(",");
	for(var i = 0; i < collections.length; ++i)
		if((collections[i] = collections[i].split(/\s/).join("")) !== "")
		{
			var script = _doc.createElement("script");
			script.src = collections[i];
			script.onload = function() {
				var temp = _doc.createElement("img");
				img.src =
			};
			_parent.insertBefore(script, _script);
		}
};

function src(string) {
	var me = this,
	    _s = string,
		_c = [];

	_defineProperty(me, "src", {
		get: function(){return _s},
		enumerable:true
	});
	_defineProperty(me, "children", {
		get: function(){return _c},
		enumerable:true
	});

	_defineProperty(me, "add", { value: function(child) {

	}});
	_defineProperty(me, "load", { value:function() {
		// loads children who continue to load each other...
		// essentially running each other in the correct scope...
		return me;
	}});
};

_defineProperty(strap, "breakdown", {value:function breakdown(srcs) {
	// reg for break down...
	// \s*(\<[\w|\W]*\>)\s*\,?|\s*(?:([\w|\W]*?)\s*(?:\,|(?:\(([\w|\_|,|\s]*?)\)\s*\{\s*([\w|\W]*?)\s*\}\s*\,?)))|(?:\s*([^\s]+)\s*\,?)
}});

// Determine whether or not to run strap on the current tag.
if(_script)
{
	// Grabs based off of .../strap<...>.js
	var strapJScheck = /\/{0,1}(strap)[\.]?[^\/]*(\.js)$/.exec(_script.src);
	// If a script tag using strap.js to load then check for options.
	if(strapJScheck != null && strapJScheck[1] + strapJScheck[2] === "strap.js")
	{
		// If data-use is provided then strap will not be loaded into the space.
		options.use = !(options.use = _script.getAttribute("data-use"))
					    && options.use !== "";
		options.srcs = _script.getAttribute("data-srcs") || options.srcs;
		// Run strap on the other srcs.
		strap(options.srcs);
	}
	// Logging for debugging.
	console.log(options);
}

// Adds strap to the loaded context if told to.
if(options.use)
	_defineProperty(_, "strap", {value:strap});
}).call(this, this, Object.defineProperty, document,
		scripts !== undefined ? scripts[scripts.length - 1] : undefined,
		this.eval || (window && window.eval));<commit_msg>breakdown<commit_after>;
// Must first get all script tags if possible.
if(document && document.getElementsByTagName)
	var scripts = document.getElementsByTagName("script");
(function(_, _defineProperty, _doc, _script, _eval) {
// Allows eval to work within a scope.
_eval = function(code) {return _eval(code)};

// Used to store the options for calculating what to do with strap.
var options = {
		use: false,
		srcs: ""
	},
// Gets the parent of the _script tag to append more scripts to if need be.
	_parent = _script.parentNode || _script.parentElement;
/**
 *
 *
 */
function strap(srcs) {
	var collections = srcs.split(",");
	for(var i = 0; i < collections.length; ++i)
		if((collections[i] = collections[i].split(/\s/).join("")) !== "")
		{
			var script = _doc.createElement("script");
			script.src = collections[i];
			script.onload = function() {
				var temp = _doc.createElement("img");
				img.src =
			};
			_parent.insertBefore(script, _script);
		}
};

function SRC(string, context) {
	var me = this,
	    _s = string,
		_c = context,
		_f = [],
		_o = [];

	_defineProperty(me, "src", {
		get: function(){return _s},
		enumerable:true
	});
	_defineProperty(me, "group", {
		get: function(){return _c},
		enumerable:true
	});
	_defineProperty(me, "add", { value: function(child) {

	}});
	_defineProperty(me, "load", { value:function() {
		// loads children who continue to load each other...
		// essentially running each other in the correct scope...
		return me;
	}});
};

var breakdownRegex =
	/\s*(?:([\w\$\.\\]*)\s*(?:\,|\(([\w\$\,\s]*)\)\s*\{([\w\W]*)\}\s*\,?)|(\<\$\<)([\w\W]*?)(\>\$\>)\s*\,?|([^\s]+)\s*\,?)/;
function g(regex, string, isThereMoreThanOneCapture) {
	// Forces isThereMoreThanOneCapture to be a boolean.
	isThereMoreThanOneCapture = !!isThereMoreThanOneCapture;
	// Executes the regex on the string to get first match.
	var getMatch = regex.exec(string),
		matches = [], i = 0;
	// While there is a match, keep grabbing.
	while(getMatch) {
		if(isThereMoreThanOneCapture)
		{
			// Stores the matches properly then adds them back.
			var captures = [], j = 1;
			// While there is a capture keep grabbing.
			while(getMatch[j]){
				captures[j-1] = getMatch[j++];
			};
			// Stores the captures.
			matches[i++] = captures;
		}
		else
			// Stores the capture.
			matches[i++] = getMatch[1];
		// Executes once again.
		getMatch = regex.exec(string);
	};
	// Returns the matches.
	return matches;
};
_defineProperty(strap, "breakdown", {value:function breakdown(srcsString, contexts) {
	// Regexp does not work with spaces in file names.
	var groups = g(breakdownRegex, srcsString, true),
		all    = [];
	// Makes sure there is a context.
	context = contexts && contexts.length > 0 ? contexts || [_];
	// Makes sure groups were actually found.
	if(groups)
		// Creates all of src objects.
		for(var i = 0; i < groups.length; ++i)
		{
			(function(group) {
				var srcs = [];
				if(group.length === 3 && group[0] + group[2] === "<$<>$>")
					for(var i in contexts)
						if(contexts[i])
							srcs.push(new SRC(group[1], contexts[i]).code(true));
				else
				{
					// Go through each context and create an src for it.
					for(var i in contexts)
						if(contexts[i])
						{
							var src = new SRC(group[0], contexts[i]);
							if(group.length === 3)
							{
								var temp     = group[1].split(/\s/).join("").split(","),
									objects  = [];
								// Get all of the objects used for loading the children.
								for(var j in temp)
									if(contexts[i][temp[j]])
										objects.push(contexts[i][temp[j]]);
								var children = breakdown(group[2], objects);
								// Add all of the children for the src.
								for(var j in children)
									src.add(children[j]);
							}
							// Prevents any referencing error.
							(function(src){srcs.push(src)})(src);
						}
				}
			})(groups[i]);
		}
	return all;
}});
// breakdown ready for testing...

// Determine whether or not to run strap on the current tag.
if(_script)
{
	// Grabs based off of .../strap<...>.js
	var strapJScheck = /\/{0,1}(strap)[\.]?[^\/]*(\.js)$/.exec(_script.src);
	// If a script tag using strap.js to load then check for options.
	if(strapJScheck != null && strapJScheck[1] + strapJScheck[2] === "strap.js")
	{
		// If data-use is provided then strap will not be loaded into the space.
		options.use = !(options.use = _script.getAttribute("data-use"))
					    && options.use !== "";
		options.srcs = _script.getAttribute("data-srcs") || options.srcs;
		// Run strap on the other srcs.
		strap(options.srcs);
	}
	// Logging for debugging.
	console.log(options);
}

// Adds strap to the loaded context if told to.
if(options.use)
	_defineProperty(_, "strap", {value:strap});
}).call(this, this, Object.defineProperty, document,
		scripts !== undefined ? scripts[scripts.length - 1] : undefined,
		this.eval || (window && window.eval));<|endoftext|>


<commit_before>// helpers
var _ = require('lodash');
var log = require('../core/log.js');

// let's create our own method
var method = {};

// prepare everything our method needs
method.init = function() {
  this.currentTrend;
  this.requiredHistory = this.tradingAdvisor.historySize;

  this.age = 0;
  this.trend = {
    direction: 'undefined',
    duration: 0,
    persisted: false,
    adviced: false
  };
  this.historySize = this.tradingAdvisor.historySize;
  this.ppoadv = 'none';
  this.uplevel = this.settings.thresholds.up;
  this.downlevel = this.settings.thresholds.down;
  this.persisted = this.settings.thresholds.persistence;

  // log.debug("CCI started with:\nup:\t", this.uplevel, "\ndown:\t", this.downlevel, "\npersistence:\t", this.persisted);
  // define the indicators we need
  this.addIndicator('cci', 'CCI', this.settings);
}

// what happens on every new candle?
method.update = function(candle) {
}

// for debugging purposes: log the last calculated
// EMAs and diff.
method.log = function() {
    var cci = this.indicators.cci;
    if (typeof(cci.result) == 'boolean') {
        log.debug('Insufficient data available. Age: ', cci.size, ' of ', cci.maxSize);
        log.debug('ind: ', cci.TP.result, ' ', cci.TP.age, ' ', cci.TP.depth);
        return;
    }

    log.debug('calculated CCI properties for candle:');
    log.debug('\t', 'Price:\t\t\t', this.lastPrice);
    log.debug('\t', 'CCI tp:\t', cci.tp.toFixed(8));
    log.debug('\t', 'CCI tp/n:\t', cci.TP.result.toFixed(8));
    log.debug('\t', 'CCI md:\t', cci.mean.toFixed(8));
    if (typeof(cci.result) == 'boolean' )
        log.debug('\t In sufficient data available.');
    else
        log.debug('\t', 'CCI:\t', cci.result.toFixed(2));
}

/*
 *
 */
method.check = function(candle) {

  var price = candle.close;

    this.age++;
    var cci = this.indicators.cci;

    if (typeof(cci.result) == 'number') {

        // overbought?
        if (cci.result >= this.uplevel && (this.trend.persisted || this.persisted == 0) && !this.trend.adviced && this.trend.direction == 'overbought' ) {
            this.trend.adviced = true;
            this.trend.duration++;
            this.advice('short');
        } else if (cci.result >= this.uplevel && this.trend.direction != 'overbought') {
            this.trend.duration = 1;
            this.trend.direction = 'overbought';
            this.trend.persisted = false;
            this.trend.adviced = false;
            if (this.persisted == 0) {
                this.trend.adviced = true;
                this.advice('short');
            }
        } else if (cci.result >= this.uplevel) {
            this.trend.duration++;
            if (this.trend.duration >= this.persisted) {
                this.trend.persisted = true;
            }
        } else if (cci.result <= this.downlevel && (this.trend.persisted || this.persisted == 0) && !this.trend.adviced && this.trend.direction == 'oversold') {
            this.trend.adviced = true;
            this.trend.duration++;
            this.advice('long');
        } else if (cci.result <= this.downlevel && this.trend.direction != 'oversold') {
            this.trend.duration = 1;
            this.trend.direction = 'oversold';
            this.trend.persisted = false;
            this.trend.adviced = false;
            if (this.persisted == 0) {
                this.trend.adviced = true;
                this.advice('long');
            }
        } else if (cci.result <= this.downlevel) {
            this.trend.duration++;
            if (this.trend.duration >= this.persisted) {
                this.trend.persisted = true;
            }
        } else {
            if( this.trend.direction != 'nodirection') {
                this.trend = {
                    direction: 'nodirection',
                    duration: 0,
                    persisted: false,
                    adviced: false
                };
            } else {
                this.trend.duration++;
            }
            this.advice();
        }

    } else {
        this.advice();
    }

    log.debug("Trend: ", this.trend.direction, " for ", this.trend.duration);
}

module.exports = method;
<commit_msg>Minor fixes to CCI strategy (#1569)<commit_after>// helpers
var _ = require('lodash');
var log = require('../core/log.js');

// let's create our own method
var method = {};

// prepare everything our method needs
method.init = function() {
  this.currentTrend;
  this.requiredHistory = this.tradingAdvisor.historySize;

  this.age = 0;
  this.trend = {
    direction: 'undefined',
    duration: 0,
    persisted: false,
    adviced: false
  };
  this.historySize = this.settings.history;
  this.ppoadv = 'none';
  this.uplevel = this.settings.thresholds.up;
  this.downlevel = this.settings.thresholds.down;
  this.persisted = this.settings.thresholds.persistence;

  // log.debug("CCI started with:\nup:\t", this.uplevel, "\ndown:\t", this.downlevel, "\npersistence:\t", this.persisted);
  // define the indicators we need
  this.addIndicator('cci', 'CCI', this.settings);
}

// what happens on every new candle?
method.update = function(candle) {
}

// for debugging purposes: log the last calculated
// EMAs and diff.
method.log = function(candle) {
    var cci = this.indicators.cci;
    if (typeof(cci.result) == 'boolean') {
        log.debug('Insufficient data available. Age: ', cci.size, ' of ', cci.maxSize);
        log.debug('ind: ', cci.TP.result, ' ', cci.TP.age, ' ', cci.TP.depth);
        return;
    }

    log.debug('calculated CCI properties for candle:');
    log.debug('\t', 'Price:\t\t', candle.close.toFixed(8));
    log.debug('\t', 'CCI tp:\t', cci.tp.toFixed(8));
    log.debug('\t', 'CCI tp/n:\t', cci.TP.result.toFixed(8));
    log.debug('\t', 'CCI md:\t', cci.mean.toFixed(8));
    if (typeof(cci.result) == 'boolean' )
        log.debug('\t In sufficient data available.');
    else
        log.debug('\t', 'CCI:\t\t', cci.result.toFixed(2));
}

/*
 *
 */
method.check = function(candle) {

    var lastPrice = candle.close;

    this.age++;
    var cci = this.indicators.cci;

    if (typeof(cci.result) == 'number') {

        // overbought?
        if (cci.result >= this.uplevel && (this.trend.persisted || this.persisted == 0) && !this.trend.adviced && this.trend.direction == 'overbought' ) {
            this.trend.adviced = true;
            this.trend.duration++;
            this.advice('short');
        } else if (cci.result >= this.uplevel && this.trend.direction != 'overbought') {
            this.trend.duration = 1;
            this.trend.direction = 'overbought';
            this.trend.persisted = false;
            this.trend.adviced = false;
            if (this.persisted == 0) {
                this.trend.adviced = true;
                this.advice('short');
            }
        } else if (cci.result >= this.uplevel) {
            this.trend.duration++;
            if (this.trend.duration >= this.persisted) {
                this.trend.persisted = true;
            }
        } else if (cci.result <= this.downlevel && (this.trend.persisted || this.persisted == 0) && !this.trend.adviced && this.trend.direction == 'oversold') {
            this.trend.adviced = true;
            this.trend.duration++;
            this.advice('long');
        } else if (cci.result <= this.downlevel && this.trend.direction != 'oversold') {
            this.trend.duration = 1;
            this.trend.direction = 'oversold';
            this.trend.persisted = false;
            this.trend.adviced = false;
            if (this.persisted == 0) {
                this.trend.adviced = true;
                this.advice('long');
            }
        } else if (cci.result <= this.downlevel) {
            this.trend.duration++;
            if (this.trend.duration >= this.persisted) {
                this.trend.persisted = true;
            }
        } else {
            if( this.trend.direction != 'nodirection') {
                this.trend = {
                    direction: 'nodirection',
                    duration: 0,
                    persisted: false,
                    adviced: false
                };
            } else {
                this.trend.duration++;
            }
            this.advice();
        }

    } else {
        this.advice();
    }

    log.debug("Trend: ", this.trend.direction, " for ", this.trend.duration);
}

module.exports = method;
<|endoftext|>


<commit_before>(function ($, count, window) {

    var ef = function () {},
    methods = {
        init: function (opts) {
            var T = this;
            if (!T.length || T.data('streamcomplete')) {
                // There are no elements or this object has already been initialised
                return T;
            } else if (T.length > 1) {
                T.each(function () {
                    $(this).streamComplete(opts);
                });
                return T;
            }
            var data = {
                instanceid: ++count,
                s: $.fn.extend({
                    delay: 250,
                    minlength: 2,
                    onajaxerror: ef,
                    onbeforeajaxsearch: ef,
                    onbeforesearch: ef,
                    onclose: ef,
                    onerror: ef,
                    oninit: ef,
                    onresponse: ef,
                    onsearch: ef,
                    onselect: ef,
                    src: []
                }, opts),
                searchterm: null
            },
            searchinterval = false,
            clear = false,
            keycodes = {
                DOWN: 40,
                ENTER: 13,
                SPACE: 32,
                TAB: 9,
                UP: 38,
                ESC: 27
            },
            selectpos = -1,
            cancelkeypress = false;

            /**
             * Render a single result
             * @param {object(plain)} desc An object with necessary properties. The obejct MUST have the properties 'id' and 'value'
             * @returns {Element} The rendered element, in this case a div
             */
            data.renderResult = function (desc) {
                var elem = document.createElement('div');
                $(elem).html(desc.value).data('sc-desc', desc).addClass('streamcomplete-result');
                return elem;
            };

            /**
             * Render the full autocomplete
             * @param {array} results An array of objects in the form [{id: int, value: value}, ...], or an array of values
             */
            data.render = function (results) {
                var output = $('.streamcomplete-body').show(),
                offset = T.offset(),
                rect = T[0].getBoundingClientRect();
                output.css({width: T.width(), top: offset.top + rect.height, left: offset.left}).empty();
                for (var i = 0; results ? i < results.length : 0; i++) {
                    var desc = results[i];
                    if (Object.prototype.toString.call(desc) !== '[object Object]') {
                        // The result is not an object, make it one
                        desc = {id: i, value: desc};
                    }
                    var res = data.renderResult(desc);
                    output.append(res);
                }
            };

            /**
             * The after render function. Seperate from the render function because the render function can be customised, whereas
             *  everything in this function is more or less always required. Makes customising the output easier
             */
            data.afterRender = function () {
                var output = $('.streamcomplete-body'),
                results = output.data('sc-results');
                output.data('sc-results', results);
                $('body').unbind('click.streamcomplete').bind('click.streamcomplete', data.close);
            };

            /**
             *
             * @param {type} e
             */
            data.close = function (e) {
                var selection = null;
                if (e) {
                    // This function was called as a result of an event
                    var target = $(e.target);
                    if (target.closest('.streamcomplete-body').length) {
                        // The user has clicked on one of the selections
                        var selection = target.data('sc-desc');
                        if (data.s.onselect.call(T, selection) === false) {
                            // The caller has prevented continuation
                            return false;
                        }
                        T[0].value = selection.value;
                        T.attr({'data-value': selection.id});
                    }
                }
                data.s.onclose.call(T, {selection: selection, results: $('.streamcomplete-body').hide().data('sc-results')});
            };

            T.keydown(function (e) {
                // If there is need to return false, then the keyboard event listener has to be onkeydown.
                if (inObj(keycodes, e.which)) {
                    // The user is navigating using the keyboard
                    var ans = keyboardAction(e.which);
                    if (ans === false) {
                        // The keyboard action returned false, so prevent the default action
                        e.preventDefault();
                        cancelkeypress = true;
                        return false;
                    }
                }
            });

            T.keyup(function () {
                if (cancelkeypress) {
                    // The keydown event listener says that the keyup event should not be registered
                    cancelkeypress = false;
                    return false;
                }
                data.searchterm = this.value;
                var payload = {
                    term: data.searchterm
                };
                selectpos = -1;
                if (data.s.onbeforesearch.call(T, payload) === false) {
                    // The caller cancelled the search: return
                    return false;
                }
                if (this.value.length >= +data.s.minlength) {
                    clear = false;
                    if (searchinterval !== false) {
                        // Clear the search interval
                        window.clearTimeout(searchinterval);
                    }
                    searchinterval = window.setTimeout(function () {
                        // Only perform searches in intervals as specified by the settings
                        if (clear) {
                            // A clear was called during the timeout
                            clear = false;
                            return;
                        }
                        var isarr = false;
                        switch (Object.prototype.toString.call(data.s.src)) {
                            case '[object String]':
                                // Assume that the given string is a URL to resolve
                                getDataAjax(data.s.src, payload);
                                break;
                            case '[object Array]':
                                // Note that the current item is an array and then do the same as would be done for a function
                                isarr = true;
                            case '[object Function]':
                                var results = isarr ? data.s.src : data.s.src();
                                if (data.s.onsearch.call(T, results) === false) {
                                    return false;
                                }
                                data.render(results);
                                data.afterRender();
                                break;
                        }
                    }, +data.s.delay);
                } else {
                    // No need to show the results because they are now wrong
                    clear = true;
                    data.close();
                }
                T.data('streamcomplete', data);
            });

            /**
             * Get data for the autocomplete via AJAX
             * @param {string} url The url to get the AJAX results from
             * @param {object(plain)} payload The payload to pass to as post data
             */
            var getDataAjax = function (url, payload) {
                $.ajax({
                    url: url,
                    type: 'post',
                    dataType: 'json',
                    beforeSend: function (e) {
                        data.s.onbeforeajaxsearch.call(T, e);
                    },
                    data: {payload: JSON.stringify(payload)}
                }).done(function (e) {
                    if (e.result === 'OK') {
                        if (clear) {
                            // A clear was called during the request
                            clear = false;
                            return;
                        }
                        if (data.s.onresponse.call(T, e) === false) {
                            return false;
                        };
                        searchinterval = false;
                        if (data.s.onsearch.call(T, e.data) === false) {
                            return false;
                        }
                        data.render(e.data);
                        data.afterRender();
                    } else {
                        data.s.onerror.call(T, e);
                    }
                }).fail(function (e) {
                    data.s.onajaxerror.call(T, e);
                });
            };

            /**
             * Perform a strict comparison with object values to determine whether a value exists in an object
             * @param {object} obj The object to look in
             * @param {mixed} val  The value to search for
             * @returns {Boolean} True if the value is in the object
             */
            var inObj = function (obj, val) {
                for (var x in obj) {
                    if (obj[x] === val) {
                        return true;
                    }
                }
                return false;
            };

            /**
             * Process keyboard navigation
             * @param {int} which The id of the key that was pressed
             * @returns {Boolean} False if the navigation require
             */
            var keyboardAction = function (which) {
                var resultlist = $('.streamcomplete-result'),
                len = resultlist.length;
                switch (which) {
                    case keycodes.UP:
                        selectpos = (selectpos - 1 < 0 ? len : selectpos) - 1;
                        $('.streamcomplete-result-hover').removeClass('streamcomplete-result-hover');
                        $(resultlist[selectpos]).addClass('streamcomplete-result-hover');
                        return false;
                    case keycodes.DOWN:
                        selectpos = selectpos + 1 === len ? 0 : selectpos + 1;
                        $('.streamcomplete-result-hover').removeClass('streamcomplete-result-hover');
                        $(resultlist[selectpos]).addClass('streamcomplete-result-hover');
                        return false;
                    case keycodes.SPACE:
                    case keycodes.ENTER:
                    case keycodes.TAB:
                        var res = $('.streamcomplete-result-hover');
                        if (res.length) {
                            $('.streamcomplete-result-hover').removeClass('streamcomplete-result-hover');
                            data.close({target: res[0]});
                            return false;
                        }
                        return true;
                    case keycodes.ESC:
                        var res = $('.streamcomplete-result-hover');
                        if (res.length) {
                            selectpos = -1;
                            $('.streamcomplete-result-hover').removeClass('streamcomplete-result-hover');
                            return false;
                        }
                        return true;
                }
            };

            // Catch all focusin events
            T.focusin(data.s.onfocusin);
            T.change(data.s.onchange);
            T.focusout(data.onfocusout);
            T.data('streamcomplete', data);
            draw();
            data.s.oninit.call(T);
            return T;
        },
        /**
         * Set the value for this autocomplete
         * @param {object} data An object with two properties, value (the human readable value for the input) and id (the system value)
         * @returns {jQUery}
         */
        setValue: function (data) {
            // Test to see whether the plugin has been initialised here first
            var scdata = this.data('streamcomplete');
            if (!scdata) {
                throw ex('InstanceError', "A call to 'setValue' on an uninitialised object");
            }
            this[0].value = data.value;
            this.data('value', data.id);
            return this;
        }
    };

    /**
     * StreamConfirm exception handler
     * @param {string} exceptiontype The name of the exception to replace xxx in the string "Uncaught StreamComplete::xxx - message"
     * @param {string} message The exception message
     * @returns {StreamComplete::Exception}
     */
    function ex(exceptiontype, message) {
        return {
            name: 'StreamComplete::' + exceptiontype,
            level: "Cannot continue",
            message: message,
            htmlMessage: message,
            toString: function() {
                return ['StreamComplete::', exceptiontype, ' - ', message].join('');
            }
        };
    };

    /**
     *
     * @returns {undefined}
     */
    function draw() {
        if ($('.streamcomplete-body').length) {
            // The body has already been drawn
            return;
        }
        $('body').append('

');
    }

    $.fn.streamComplete = function(methodOrOpts) {
        var T = this;
        if (methods[methodOrOpts]) {
            // The first option passed is a method, therefore call this method
            return methods[methodOrOpts].apply(T, Array.prototype.slice.call(arguments, 1));
        } else if (Object.prototype.toString.call(methodOrOpts) === '[object Object]' || !methodOrOpts) {
            // The default action is to call the init function
            return methods.init.apply(T, arguments);
        } else {
            // The user has passed us something dodgy, throw an error
            $.error(['The method ', methodOrOpts, ' does not exist'].join(''));
        }
    };

})(jQuery, 0, this);<commit_msg>Improved the method setVaue<commit_after>(function ($, count, window) {

    var ef = function () {},
    methods = {
        init: function (opts) {
            var T = this;
            if (!T.length || T.data('streamcomplete')) {
                // There are no elements or this object has already been initialised
                return T;
            } else if (T.length > 1) {
                T.each(function () {
                    $(this).streamComplete(opts);
                });
                return T;
            }
            var data = {
                instanceid: ++count,
                s: $.fn.extend({
                    delay: 250,
                    minlength: 2,
                    onajaxerror: ef,
                    onbeforeajaxsearch: ef,
                    onbeforesearch: ef,
                    onclose: ef,
                    onerror: ef,
                    oninit: ef,
                    onresponse: ef,
                    onsearch: ef,
                    onselect: ef,
                    src: []
                }, opts),
                searchterm: null
            },
            searchinterval = false,
            clear = false,
            keycodes = {
                DOWN: 40,
                ENTER: 13,
                SPACE: 32,
                TAB: 9,
                UP: 38,
                ESC: 27
            },
            selectpos = -1,
            cancelkeypress = false;

            /**
             * Render a single result
             * @param {object(plain)} desc An object with necessary properties. The obejct MUST have the properties 'id' and 'value'
             * @returns {Element} The rendered element, in this case a div
             */
            data.renderResult = function (desc) {
                var elem = document.createElement('div');
                $(elem).html(desc.value).data('sc-desc', desc).addClass('streamcomplete-result');
                return elem;
            };

            /**
             * Render the full autocomplete
             * @param {array} results An array of objects in the form [{id: int, value: value}, ...], or an array of values
             */
            data.render = function (results) {
                var output = $('.streamcomplete-body').show(),
                offset = T.offset(),
                rect = T[0].getBoundingClientRect();
                output.css({width: T.width(), top: offset.top + rect.height, left: offset.left}).empty();
                for (var i = 0; results ? i < results.length : 0; i++) {
                    var desc = results[i];
                    if (Object.prototype.toString.call(desc) !== '[object Object]') {
                        // The result is not an object, make it one
                        desc = {id: i, value: desc};
                    }
                    var res = data.renderResult(desc);
                    output.append(res);
                }
            };

            /**
             * The after render function. Seperate from the render function because the render function can be customised, whereas
             *  everything in this function is more or less always required. Makes customising the output easier
             */
            data.afterRender = function () {
                var output = $('.streamcomplete-body'),
                results = output.data('sc-results');
                output.data('sc-results', results);
                $('body').unbind('click.streamcomplete').bind('click.streamcomplete', data.close);
            };

            /**
             *
             * @param {type} e
             */
            data.close = function (e) {
                var selection = null;
                if (e) {
                    // This function was called as a result of an event
                    var target = $(e.target);
                    if (target.closest('.streamcomplete-body').length) {
                        // The user has clicked on one of the selections
                        var selection = target.data('sc-desc');
                        if (data.s.onselect.call(T, selection) === false) {
                            // The caller has prevented continuation
                            return false;
                        }
                        T[0].value = selection.value;
                        T.attr({'data-value': selection.id});
                    }
                }
                data.s.onclose.call(T, {selection: selection, results: $('.streamcomplete-body').hide().data('sc-results')});
            };

            T.keydown(function (e) {
                // If there is need to return false, then the keyboard event listener has to be onkeydown.
                if (inObj(keycodes, e.which)) {
                    // The user is navigating using the keyboard
                    var ans = keyboardAction(e.which);
                    if (ans === false) {
                        // The keyboard action returned false, so prevent the default action
                        e.preventDefault();
                        cancelkeypress = true;
                        return false;
                    }
                }
            });

            T.keyup(function () {
                if (cancelkeypress) {
                    // The keydown event listener says that the keyup event should not be registered
                    cancelkeypress = false;
                    return false;
                }
                data.searchterm = this.value;
                var payload = {
                    term: data.searchterm
                };
                selectpos = -1;
                if (data.s.onbeforesearch.call(T, payload) === false) {
                    // The caller cancelled the search: return
                    return false;
                }
                if (this.value.length >= +data.s.minlength) {
                    clear = false;
                    if (searchinterval !== false) {
                        // Clear the search interval
                        window.clearTimeout(searchinterval);
                    }
                    searchinterval = window.setTimeout(function () {
                        // Only perform searches in intervals as specified by the settings
                        if (clear) {
                            // A clear was called during the timeout
                            clear = false;
                            return;
                        }
                        var isarr = false;
                        switch (Object.prototype.toString.call(data.s.src)) {
                            case '[object String]':
                                // Assume that the given string is a URL to resolve
                                getDataAjax(data.s.src, payload);
                                break;
                            case '[object Array]':
                                // Note that the current item is an array and then do the same as would be done for a function
                                isarr = true;
                            case '[object Function]':
                                var results = isarr ? data.s.src : data.s.src();
                                if (data.s.onsearch.call(T, results) === false) {
                                    return false;
                                }
                                data.render(results);
                                data.afterRender();
                                break;
                        }
                    }, +data.s.delay);
                } else {
                    // No need to show the results because they are now wrong
                    clear = true;
                    data.close();
                }
                T.data('streamcomplete', data);
            });

            /**
             * Get data for the autocomplete via AJAX
             * @param {string} url The url to get the AJAX results from
             * @param {object(plain)} payload The payload to pass to as post data
             */
            var getDataAjax = function (url, payload) {
                $.ajax({
                    url: url,
                    type: 'post',
                    dataType: 'json',
                    beforeSend: function (e) {
                        data.s.onbeforeajaxsearch.call(T, e);
                    },
                    data: {payload: JSON.stringify(payload)}
                }).done(function (e) {
                    if (e.result === 'OK') {
                        if (clear) {
                            // A clear was called during the request
                            clear = false;
                            return;
                        }
                        if (data.s.onresponse.call(T, e) === false) {
                            return false;
                        };
                        searchinterval = false;
                        if (data.s.onsearch.call(T, e.data) === false) {
                            return false;
                        }
                        data.render(e.data);
                        data.afterRender();
                    } else {
                        data.s.onerror.call(T, e);
                    }
                }).fail(function (e) {
                    data.s.onajaxerror.call(T, e);
                });
            };

            /**
             * Perform a strict comparison with object values to determine whether a value exists in an object
             * @param {object} obj The object to look in
             * @param {mixed} val  The value to search for
             * @returns {Boolean} True if the value is in the object
             */
            var inObj = function (obj, val) {
                for (var x in obj) {
                    if (obj[x] === val) {
                        return true;
                    }
                }
                return false;
            };

            /**
             * Process keyboard navigation
             * @param {int} which The id of the key that was pressed
             * @returns {Boolean} False if the navigation require
             */
            var keyboardAction = function (which) {
                var resultlist = $('.streamcomplete-result'),
                len = resultlist.length;
                switch (which) {
                    case keycodes.UP:
                        selectpos = (selectpos - 1 < 0 ? len : selectpos) - 1;
                        $('.streamcomplete-result-hover').removeClass('streamcomplete-result-hover');
                        $(resultlist[selectpos]).addClass('streamcomplete-result-hover');
                        return false;
                    case keycodes.DOWN:
                        selectpos = selectpos + 1 === len ? 0 : selectpos + 1;
                        $('.streamcomplete-result-hover').removeClass('streamcomplete-result-hover');
                        $(resultlist[selectpos]).addClass('streamcomplete-result-hover');
                        return false;
                    case keycodes.SPACE:
                    case keycodes.ENTER:
                    case keycodes.TAB:
                        var res = $('.streamcomplete-result-hover');
                        if (res.length) {
                            $('.streamcomplete-result-hover').removeClass('streamcomplete-result-hover');
                            data.close({target: res[0]});
                            return false;
                        }
                        return true;
                    case keycodes.ESC:
                        var res = $('.streamcomplete-result-hover');
                        if (res.length) {
                            selectpos = -1;
                            $('.streamcomplete-result-hover').removeClass('streamcomplete-result-hover');
                            return false;
                        }
                        return true;
                }
            };

            // Catch all focusin events
            T.focusin(data.s.onfocusin);
            T.change(data.s.onchange);
            T.focusout(data.onfocusout);
            T.data('streamcomplete', data);
            draw();
            data.s.oninit.call(T);
            return T;
        },
        /**
         * Set the value for this autocomplete
         * @param {object} data An object with at least two properties, value (the human readable value for the input) and id
         *  (the system value). Any more properties will be added into data attributes of the given key
         * @returns {jQUery}
         */
        setValue: function (data) {
            // Test to see whether the plugin has been initialised here first
            var scdata = this.data('streamcomplete');
            if (!scdata) {
                throw ex('InstanceError', "A call to 'setValue' on an uninitialised object");
            }
            this[0].value = data.value;
            this.data('value', data.id);
            // Delete the known properties in this object and then add in data attributes for all of the other ones
            delete data.value;
            delete data.id;
            for (var x in data) {
                this.data(x, data[x]);
            }
            return this;
        }
    };

    /**
     * StreamConfirm exception handler
     * @param {string} exceptiontype The name of the exception to replace xxx in the string "Uncaught StreamComplete::xxx - message"
     * @param {string} message The exception message
     * @returns {StreamComplete::Exception}
     */
    function ex(exceptiontype, message) {
        return {
            name: 'StreamComplete::' + exceptiontype,
            level: "Cannot continue",
            message: message,
            htmlMessage: message,
            toString: function() {
                return ['StreamComplete::', exceptiontype, ' - ', message].join('');
            }
        };
    };

    /**
     *
     * @returns {undefined}
     */
    function draw() {
        if ($('.streamcomplete-body').length) {
            // The body has already been drawn
            return;
        }
        $('body').append('

');
    }

    $.fn.streamComplete = function(methodOrOpts) {
        var T = this;
        if (methods[methodOrOpts]) {
            // The first option passed is a method, therefore call this method
            return methods[methodOrOpts].apply(T, Array.prototype.slice.call(arguments, 1));
        } else if (Object.prototype.toString.call(methodOrOpts) === '[object Object]' || !methodOrOpts) {
            // The default action is to call the init function
            return methods.init.apply(T, arguments);
        } else {
            // The user has passed us something dodgy, throw an error
            $.error(['The method ', methodOrOpts, ' does not exist'].join(''));
        }
    };

})(jQuery, 0, this);<|endoftext|>


<commit_before>dojo.provide("dojox.string.Builder");

(function(){
	dojox.string.Builder = function(/*String?*/str){
		// summary:
		//		A fast buffer for creating large strings
		// str: The initial string to seed the buffer with
		this.b = dojo.isIE ? [] : "";
		if(str){ this.append(str); }
	};

	var m = {
	 	append: function(/*String*/s){
			// summary: Append all arguments to the end of the buffer
			if(arguments.length>1){
				/*
					This is a loop unroll designed specifically for Firefox;
					it would seem that static index access on an Arguments
					object is a LOT faster than doing dynamic index access.
					Therefore, we create a buffer string and take advantage
					of JS's switch fallthrough.  The peformance of this method
					comes very close to straight up string concatenation (+=).

					If the arguments object length is greater than 9, we fall
					back to standard dynamic access.

					This optimization seems to have no real effect on either
					Safari or Opera, so we just use it for all.

					Loop unroll per suggestion from Kris Zyp, implemented by
					Tom Trenka.
				 */
				var tmp="", l=arguments.length;
				switch(l){
					case 9: tmp=arguments[8]+tmp;
					case 8: tmp=arguments[7]+tmp;
					case 7: tmp=arguments[6]+tmp;
					case 6: tmp=arguments[5]+tmp;
					case 5: tmp=arguments[4]+tmp;
					case 4: tmp=arguments[3]+tmp;
					case 3: tmp=arguments[2]+tmp;
					case 2: {
						this.b+=arguments[0]+arguments[1]+tmp;
						break;
					}
					default: {
						var i=0;
						while(i<arguments.length){
							this.b += arguments[i++];
						}
					}
				}
			} else {
				this.b += s;
			}
			return this;	//	dojox.string.Builder
		},
		concat: function(/*String*/s){
			return this.append(s);
		},
		appendArray: function(/*Array*/strings) {
			this.b = String.prototype.concat.apply(this.b, strings);
			return this;
		},
		clear: function(){
			// summary: Remove all characters from the buffer
			this._clear();
			this.length = 0;
			return this;
		},
		replace: function(oldStr,newStr){
			// summary: Replace instances of one string with another in the buffer
			var s = this.toString();
			s = s.replace(oldStr,newStr);
			this._reset(s);
			this.length = s.length;
			return this;
		},
		remove: function(start, len){
			// summary: Remove len characters starting at index start
			if(len == 0){ return this; }
			var s = this.toString();
			this.clear();
			if(start > 0){
				this.append(s.substring(0, start));
			}
			if(start+len < s.length){
				this.append(s.substring(start+len));
			}
			return this;
		},
		insert: function(index, str){
			// summary: Insert string str starting at index
			var s = this.toString();
			this.clear();
			if(index == 0){
				this.append(str);
				this.append(s);
				return this;
			}else{
				this.append(s.substring(0, index));
				this.append(str);
				this.append(s.substring(index));
			}
			return this;
		},
		toString: function(){
			return this.b;
		},
		_clear: function(){
			this.b = "";
		},
		_reset: function(s){
			this.b = s;
		}
	}; // will hold methods for Builder

	if(dojo.isIE){
		dojo.mixin(m, {
			toString: function(){
				// Summary: Get the buffer as a string
				return this.b.join("");
			},
			append: function(/*String*/s){
				// summary: Append all arguments to the end of the buffer
				if(arguments.length>1){
					//	Some Duff's device love here.
					var n = Math.floor(arguments.length/8), r = arguments.length%8, i=0;
					do {
						switch(r){
							case 0: this.b[this.b.length]=arguments[i++];
							case 7: this.b[this.b.length]=arguments[i++];
							case 6: this.b[this.b.length]=arguments[i++];
							case 5: this.b[this.b.length]=arguments[i++];
							case 4: this.b[this.b.length]=arguments[i++];
							case 3: this.b[this.b.length]=arguments[i++];
							case 2: this.b[this.b.length]=arguments[i++];
							case 1: this.b[this.b.length]=arguments[i++];
						}
						r = 0;
					} while(--n>0);
				} else {
					//	this seems to shave off a little time over .push().
					this.b[this.b.length]=s;
				}
				return this;	//	dojox.string.Builder
			},
			appendArray: function(strings){
				this.b = this.b.concat(strings);
				return this;
			},
			_clear: function(){
				this.b = [];
			},
			_reset: function(s){
				this.b = [ s ];
			}
		});
	}

	dojo.extend(dojox.string.Builder, m);
})();
<commit_msg>Additional IE optimization from a tip by Erik Arvidsson.  !strict.<commit_after>dojo.provide("dojox.string.Builder");

(function(){
	dojox.string.Builder = function(/*String?*/str){
		// summary:
		//		A fast buffer for creating large strings
		// str: The initial string to seed the buffer with
		this.b = dojo.isIE ? [] : "";
		if(str){ this.append(str); }
	};

	var m = {
	 	append: function(/*String*/s){
			// summary: Append all arguments to the end of the buffer
			if(arguments.length>1){
				/*
					This is a loop unroll designed specifically for Firefox;
					it would seem that static index access on an Arguments
					object is a LOT faster than doing dynamic index access.
					Therefore, we create a buffer string and take advantage
					of JS's switch fallthrough.  The peformance of this method
					comes very close to straight up string concatenation (+=).

					If the arguments object length is greater than 9, we fall
					back to standard dynamic access.

					This optimization seems to have no real effect on either
					Safari or Opera, so we just use it for all.

					Loop unroll per suggestion from Kris Zyp, implemented by
					Tom Trenka.
				 */
				var tmp="", l=arguments.length;
				switch(l){
					case 9: tmp=arguments[8]+tmp;
					case 8: tmp=arguments[7]+tmp;
					case 7: tmp=arguments[6]+tmp;
					case 6: tmp=arguments[5]+tmp;
					case 5: tmp=arguments[4]+tmp;
					case 4: tmp=arguments[3]+tmp;
					case 3: tmp=arguments[2]+tmp;
					case 2: {
						this.b+=arguments[0]+arguments[1]+tmp;
						break;
					}
					default: {
						var i=0;
						while(i<arguments.length){
							this.b += arguments[i++];
						}
					}
				}
			} else {
				this.b += s;
			}
			return this;	//	dojox.string.Builder
		},
		concat: function(/*String*/s){
			return this.append(s);
		},
		appendArray: function(/*Array*/strings) {
			this.b = String.prototype.concat.apply(this.b, strings);
			return this;
		},
		clear: function(){
			// summary: Remove all characters from the buffer
			this._clear();
			this.length = 0;
			return this;
		},
		replace: function(oldStr,newStr){
			// summary: Replace instances of one string with another in the buffer
			var s = this.toString();
			s = s.replace(oldStr,newStr);
			this._reset(s);
			this.length = s.length;
			return this;
		},
		remove: function(start, len){
			// summary: Remove len characters starting at index start
			if(len == 0){ return this; }
			var s = this.toString();
			this.clear();
			if(start > 0){
				this.append(s.substring(0, start));
			}
			if(start+len < s.length){
				this.append(s.substring(start+len));
			}
			return this;
		},
		insert: function(index, str){
			// summary: Insert string str starting at index
			var s = this.toString();
			this.clear();
			if(index == 0){
				this.append(str);
				this.append(s);
				return this;
			}else{
				this.append(s.substring(0, index));
				this.append(str);
				this.append(s.substring(index));
			}
			return this;
		},
		toString: function(){
			return this.b;
		},
		_clear: function(){
			this.b = "";
		},
		_reset: function(s){
			this.b = s;
		}
	}; // will hold methods for Builder

	if(dojo.isIE){
		dojo.mixin(m, {
			toString: function(){
				// Summary: Get the buffer as a string
				return this.b.join("");
			},
			append: function(/*String*/s){
				// summary: Append all arguments to the end of the buffer
				if(arguments.length>1){
					this.b.push.apply(this.b, arguments);
				} else {
					//	this seems to shave off a little time over .push().
					this.b[this.b.length]=s;
				}
				return this;	//	dojox.string.Builder
			},
			appendArray: function(strings){
				this.b = this.b.concat(strings);
				return this;
			},
			_clear: function(){
				this.b = [];
			},
			_reset: function(s){
				this.b = [ s ];
			}
		});
	}

	dojo.extend(dojox.string.Builder, m);
})();
<|endoftext|>


<commit_before>var React = require('react');
var CollectionLoader = require('./components/CollectionLoader.react');

var filterConfig = {
  name: "Filtered",
  idAttr: "id",
  basePath: "http://localhost:8083/api/",
  endpoint: "children",
  storeType: "shared",
  filter: { age: { '$gt': 10 } },
  sortBy: { age: false }
};

var Transform = React.createClass({
  propTypes: {
    funk: React.PropTypes.func.isRequired
  },
  render() {
    return (

    );
  }
});

var FilterPane = React.createClass({
  propTypes: {
    tag: React.PropTypes.string.isRequired
  },

  render() {
    return (

        <CollectionLoader {...filterConfig}>
          <Transform funk={someMapFunction}>
            <GenericSelectDropdown/>
          </Transform>

          <Transform funk={someMapFunction}>
            <GenericSelectDropdown/>
          </Transform>

          <Transform funk={someMapFunction}>
            <GenericSelectDropdown/>
          </Transform>

          <Transform funk={someMapFunction}>
            <GenericSelectDropdown/>
          </Transform>
        </CollectionLoader>

    );
  }
});

module.exports = FilterPane;
<commit_msg>implemented function<commit_after>var React = require('react');
var CollectionLoader = require('./components/CollectionLoader.react');
var _ = require('underscore');

var filterConfig = {
  name: "Filtered",
  idAttr: "id",
  basePath: "http://localhost:8083/api/",
  endpoint: "children",
  storeType: "shared",
  filter: { age: { '$gt': 10 } },
  sortBy: { age: false }
};

function uniqueValuesForKey(key, array) {
  return _.chain(array)
          .map(element => { return element[key]; })
          .uniq()
          .compact()
          .value();
}

var FilterPane = React.createClass({
  propTypes: {
    tag: React.PropTypes.string.isRequired
  },

  render() {
    return (
      <CollectionLoader {...filterConfig}>

        <Transformer mapFunction={uniqueValuesForKey().bind(null, 'name')}>
          <GenericSelectDropdown/>
        </Transformer>

        <Transformer mapFunction={uniqueValuesForKey().bind(null, 'age')}>
          <GenericSelectDropdown/>
        </Transformer>

      </CollectionLoader>
    );
  }
});

module.exports = FilterPane;
<|endoftext|>