<commit_before>;(function($){
/**
 * jqGrid extension for manipulating Grid Data
 * Tony Tomov tony@trirand.com
 * http://trirand.com/blog/
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl-2.0.html
**/
$.jgrid.extend({
//Editing
	editRow : function(rowid,keys,oneditfunc,successfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc) {
		// Compatible mode old versions
		var settings = {
			"keys" : keys || false,
			"oneditfunc" : oneditfunc || null,
			"successfunc" : successfunc || null,
			"url" : url || null,
			"extraparam" : extraparam || {},
			"aftersavefunc" : aftersavefunc || null,
			"errorfunc": errorfunc || null,
			"afterrestorefunc" : afterrestorefunc|| null,
			"restoreAfterErorr" : true
		},
		args = $.makeArray(arguments).slice(1), o;

		if(args[0] && typeof(args[0]) == "object" && !$.isFunction(args[0])) {
			o = $.extend(settings,args[0]);
		} else {
			o = settings;
		}
		// End compatible
		return this.each(function(){
			var $t = this, nm, tmp, editable, cnt=0, focus=null, svr={}, ind,cm;
			if (!$t.grid ) { return; }
			ind = $($t).jqGrid("getInd",rowid,true);
			if( ind === false ) {return;}
			editable = $(ind).attr("editable") || "0";
			if (editable == "0" && !$(ind).hasClass("not-editable-row")) {
				cm = $t.p.colModel;
				$('td',ind).each( function(i) {
					nm = cm[i].name;
					var treeg = $t.p.treeGrid===true && nm == $t.p.ExpandColumn;
					if(treeg) { tmp = $("span:first",this).html();}
					else {
						try {
							tmp =  $.unformat(this,{rowId:rowid, colModel:cm[i]},i);
						} catch (_) {
							tmp =  ( cm[i].edittype && cm[i].edittype == 'textarea' ) ? $(this).text() : $(this).html();
						}
					}
					if ( nm != 'cb' && nm != 'subgrid' && nm != 'rn') {
						if($t.p.autoencode) { tmp = $.jgrid.htmlDecode(tmp); }
						svr[nm]=tmp;
						if(cm[i].editable===true) {
							if(focus===null) { focus = i; }
							if (treeg) { $("span:first",this).html(""); }
							else { $(this).html(""); }
							var opt = $.extend({},cm[i].editoptions || {},{id:rowid+"_"+nm,name:nm});
							if(!cm[i].edittype) { cm[i].edittype = "text"; }
							if(tmp == " " || tmp == " " || (tmp.length==1 && tmp.charCodeAt(0)==160) ) {tmp='';}
							var elc = $.jgrid.createEl(cm[i].edittype,opt,tmp,true,$.extend({},$.jgrid.ajaxOptions,$t.p.ajaxSelectOptions || {}));
							$(elc).addClass("editable");
							if(treeg) { $("span:first",this).append(elc); }
							else { $(this).append(elc); }
							//Again IE
							if(cm[i].edittype == "select" && cm[i].editoptions.multiple===true && $.browser.msie) {
								$(elc).width($(elc).width());
							}
							cnt++;
						}
					}
				});
				if(cnt > 0) {
					svr.id = rowid; $t.p.savedRow.push(svr);
					$(ind).attr("editable","1");
					$("td:eq("+focus+") input",ind).focus();
					if(o.keys===true) {
						$(ind).bind("keydown",function(e) {
							if (e.keyCode === 27) {$($t).jqGrid("restoreRow",rowid, afterrestorefunc);}
							if (e.keyCode === 13) {
								var ta = e.target;
								if(ta.tagName == 'TEXTAREA') { return true; }
								$($t).jqGrid("saveRow", rowid, o );
								return false;
							}
							e.stopPropagation();
						});
					}
					if( $.isFunction(o.oneditfunc)) { o.oneditfunc.call($t, rowid); }
				}
			}
		});
	},
	saveRow : function(rowid, successfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc) {
		// Compatible mode old versions
		var settings = {
			"successfunc" : successfunc || null,
			"url" : url || null,
			"extraparam" : extraparam || {},
			"aftersavefunc" : aftersavefunc || null,
			"errorfunc": errorfunc || null,
			"afterrestorefunc" : afterrestorefunc|| null,
			"restoreAfterErorr" : true
		},
		args = $.makeArray(arguments).slice(1), o;

		if(args[0] && typeof(args[0]) == "object" && !$.isFunction(args[0])) {
			o = $.extend(settings,args[0]);
		} else {
			o = settings;
		}
		// End compatible
		var success = false;
		var $t = this[0], nm, tmp={}, tmp2={}, tmp3= {}, editable, fr, cv, ind;
		if (!$t.grid ) { return success; }
		ind = $($t).jqGrid("getInd",rowid,true);
		if(ind === false) {return success;}
		editable = $(ind).attr("editable");
		o.url = o.url ? o.url : $t.p.editurl;
		if (editable==="1") {
			var cm;
			$("td",ind).each(function(i) {
				cm = $t.p.colModel[i];
				nm = cm.name;
				if ( nm != 'cb' && nm != 'subgrid' && cm.editable===true && nm != 'rn' && !$(this).hasClass('not-editable-cell')) {
					switch (cm.edittype) {
						case "checkbox":
							var cbv = ["Yes","No"];
							if(cm.editoptions ) {
								cbv = cm.editoptions.value.split(":");
							}
							tmp[nm]=  $("input",this).attr("checked") ? cbv[0] : cbv[1];
							break;
						case 'text':
						case 'password':
						case 'textarea':
						case "button" :
							tmp[nm]=$("input, textarea",this).val();
							break;
						case 'select':
							if(!cm.editoptions.multiple) {
								tmp[nm] = $("select>option:selected",this).val();
								tmp2[nm] = $("select>option:selected", this).text();
							} else {
								var sel = $("select",this), selectedText = [];
								tmp[nm] = $(sel).val();
								if(tmp[nm]) { tmp[nm]= tmp[nm].join(","); } else { tmp[nm] =""; }
								$("select > option:selected",this).each(
									function(i,selected){
										selectedText[i] = $(selected).text();
									}
								);
								tmp2[nm] = selectedText.join(",");
							}
							if(cm.formatter && cm.formatter == 'select') { tmp2={}; }
							break;
						case 'custom' :
							try {
								if(cm.editoptions && $.isFunction(cm.editoptions.custom_value)) {
									tmp[nm] = cm.editoptions.custom_value.call($t, $(".customelement",this),'get');
									if (tmp[nm] === undefined) { throw "e2"; }
								} else { throw "e1"; }
							} catch (e) {
								if (e=="e1") { $.jgrid.info_dialog(jQuery.jgrid.errors.errcap,"function 'custom_value' "+$.jgrid.edit.msg.nodefined,jQuery.jgrid.edit.bClose); }
								if (e=="e2") { $.jgrid.info_dialog(jQuery.jgrid.errors.errcap,"function 'custom_value' "+$.jgrid.edit.msg.novalue,jQuery.jgrid.edit.bClose); }
								else { $.jgrid.info_dialog(jQuery.jgrid.errors.errcap,e.message,jQuery.jgrid.edit.bClose); }
							}
							break;
					}
					cv = $.jgrid.checkValues(tmp[nm],i,$t);
					if(cv[0] === false) {
						cv[1] = tmp[nm] + " " + cv[1];
						return false;
					}
					if($t.p.autoencode) { tmp[nm] = $.jgrid.htmlEncode(tmp[nm]); }
					if(o.url !== 'clientArray' && cm.editoptions && cm.editoptions.NullIfEmpty === true) {
						if(tmp[nm] == "") {
							tmp3[nm] = 'null';
				}
					}
				}
			});
			if (cv[0] === false){
				try {
					var positions = $.jgrid.findPos($("#"+$.jgrid.jqID(rowid), $t.grid.bDiv)[0]);
					$.jgrid.info_dialog($.jgrid.errors.errcap,cv[1],$.jgrid.edit.bClose,{left:positions[0],top:positions[1]});
				} catch (e) {
					alert(cv[1]);
				}
				return success;
			}
			if(tmp) {
				var idname, opers, oper;
				opers = $t.p.prmNames;
				oper = opers.oper;
				idname = opers.id;
				tmp[oper] = opers.editoper;
				tmp[idname] = rowid;
				if(typeof($t.p.inlineData) == 'undefined') { $t.p.inlineData ={}; }
				tmp = $.extend({},tmp,$t.p.inlineData,o.extraparam);
			}
			if (o.url == 'clientArray') {
				tmp = $.extend({},tmp, tmp2);
				if($t.p.autoencode) {
					$.each(tmp,function(n,v){
						tmp[n] = $.jgrid.htmlDecode(v);
					});
				}
				var resp = $($t).jqGrid("setRowData",rowid,tmp);
				$(ind).attr("editable","0");
				for( var k=0;k<$t.p.savedRow.length;k++) {
					if( $t.p.savedRow[k].id == rowid) {fr = k; break;}
				}
				if(fr >= 0) { $t.p.savedRow.splice(fr,1); }
				if( $.isFunction(o.aftersavefunc) ) { o.aftersavefunc.call($t, rowid,resp); }
				success = true;
				$(ind).unbind("keydown");
			} else {
				$("#lui_"+$t.p.id).show();
				tmp3 = $.extend({},tmp,tmp3);
				$.ajax($.extend({
					url:o.url,
					data: $.isFunction($t.p.serializeRowData) ? $t.p.serializeRowData.call($t, tmp3) : tmp3,
					type: "POST",
					async : false, //?!?
					complete: function(res,stat){
						$("#lui_"+$t.p.id).hide();
						if (stat === "success"){
							var ret;
							if( $.isFunction(o.successfunc)) { ret = o.successfunc.call($t, res);}
							else { ret = true; }
							if (ret===true) {
								if($t.p.autoencode) {
									$.each(tmp,function(n,v){
										tmp[n] = $.jgrid.htmlDecode(v);
									});
								}
								tmp = $.extend({},tmp, tmp2);
								$($t).jqGrid("setRowData",rowid,tmp);
								$(ind).attr("editable","0");
								for( var k=0;k<$t.p.savedRow.length;k++) {
									if( $t.p.savedRow[k].id == rowid) {fr = k; break;}
								}
								if(fr >= 0) { $t.p.savedRow.splice(fr,1); }
								if( $.isFunction(o.aftersavefunc) ) { o.aftersavefunc.call($t, rowid,res); }
								success = true;
								$(ind).unbind("keydown");
							} else {
								if($.isFunction(o.errorfunc) ) {
									o.errorfunc.call($t, rowid, res, stat);
								}
								if(o.restoreAfterError === true) {
									$($t).jqGrid("restoreRow",rowid, o.afterrestorefunc);
							}
						}
						}
					},
					error:function(res,stat){
						$("#lui_"+$t.p.id).hide();
						if($.isFunction(o.errorfunc) ) {
							o.errorfunc.call($t, rowid, res, stat);
						} else {
							try {
								jQuery.jgrid.info_dialog(jQuery.jgrid.errors.errcap,'
'+ res.responseText +'
', jQuery.jgrid.edit.bClose,{buttonalign:'right'});
						}
							catch(e) {
								alert(res.responseText);
					}
						}
						if(o.restoreAfterError === true) {
							$($t).jqGrid("restoreRow",rowid, o.afterrestorefunc);
						}
					}
				}, $.jgrid.ajaxOptions, $t.p.ajaxRowOptions || {}));
			}
		}
		return success;
	},
	restoreRow : function(rowid, afterrestorefunc) {
		return this.each(function(){
			var $t= this, fr, ind, ares={};
			if (!$t.grid ) { return; }
			ind = $($t).jqGrid("getInd",rowid,true);
			if(ind === false) {return;}
			for( var k=0;k<$t.p.savedRow.length;k++) {
				if( $t.p.savedRow[k].id == rowid) {fr = k; break;}
			}
			if(fr >= 0) {
				if($.isFunction($.fn.datepicker)) {
					try {
						$("input.hasDatepicker","#"+$.jgrid.jqID(ind.id)).datepicker('hide');
					} catch (e) {}
				}
				$.each($t.p.colModel, function(i,n){
					if(this.editable === true && this.name in $t.p.savedRow[fr] && !$(this).hasClass('not-editable-cell')) {
						ares[this.name] = $t.p.savedRow[fr][this.name];
					}
				});
				$($t).jqGrid("setRowData",rowid,ares);
				$(ind).attr("editable","0").unbind("keydown");
				$t.p.savedRow.splice(fr,1);
			}
			if ($.isFunction(afterrestorefunc))
			{
				afterrestorefunc.call($t, rowid);
			}
		});
	}
//end inline edit
});
})(jQuery);
<commit_msg>Support for optgroup in inline edit.<commit_after>;(function($){
/**
 * jqGrid extension for manipulating Grid Data
 * Tony Tomov tony@trirand.com
 * http://trirand.com/blog/
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl-2.0.html
**/
$.jgrid.extend({
//Editing
	editRow : function(rowid,keys,oneditfunc,successfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc) {
		// Compatible mode old versions
		var settings = {
			"keys" : keys || false,
			"oneditfunc" : oneditfunc || null,
			"successfunc" : successfunc || null,
			"url" : url || null,
			"extraparam" : extraparam || {},
			"aftersavefunc" : aftersavefunc || null,
			"errorfunc": errorfunc || null,
			"afterrestorefunc" : afterrestorefunc|| null,
			"restoreAfterErorr" : true
		},
		args = $.makeArray(arguments).slice(1), o;

		if(args[0] && typeof(args[0]) == "object" && !$.isFunction(args[0])) {
			o = $.extend(settings,args[0]);
		} else {
			o = settings;
		}
		// End compatible
		return this.each(function(){
			var $t = this, nm, tmp, editable, cnt=0, focus=null, svr={}, ind,cm;
			if (!$t.grid ) { return; }
			ind = $($t).jqGrid("getInd",rowid,true);
			if( ind === false ) {return;}
			editable = $(ind).attr("editable") || "0";
			if (editable == "0" && !$(ind).hasClass("not-editable-row")) {
				cm = $t.p.colModel;
				$('td',ind).each( function(i) {
					nm = cm[i].name;
					var treeg = $t.p.treeGrid===true && nm == $t.p.ExpandColumn;
					if(treeg) { tmp = $("span:first",this).html();}
					else {
						try {
							tmp =  $.unformat(this,{rowId:rowid, colModel:cm[i]},i);
						} catch (_) {
							tmp =  ( cm[i].edittype && cm[i].edittype == 'textarea' ) ? $(this).text() : $(this).html();
						}
					}
					if ( nm != 'cb' && nm != 'subgrid' && nm != 'rn') {
						if($t.p.autoencode) { tmp = $.jgrid.htmlDecode(tmp); }
						svr[nm]=tmp;
						if(cm[i].editable===true) {
							if(focus===null) { focus = i; }
							if (treeg) { $("span:first",this).html(""); }
							else { $(this).html(""); }
							var opt = $.extend({},cm[i].editoptions || {},{id:rowid+"_"+nm,name:nm});
							if(!cm[i].edittype) { cm[i].edittype = "text"; }
							if(tmp == " " || tmp == " " || (tmp.length==1 && tmp.charCodeAt(0)==160) ) {tmp='';}
							var elc = $.jgrid.createEl(cm[i].edittype,opt,tmp,true,$.extend({},$.jgrid.ajaxOptions,$t.p.ajaxSelectOptions || {}));
							$(elc).addClass("editable");
							if(treeg) { $("span:first",this).append(elc); }
							else { $(this).append(elc); }
							//Again IE
							if(cm[i].edittype == "select" && typeof(cm[i].editoptions)!=="undefined" && cm[i].editoptions.multiple===true  && typeof(cm[i].editoptions.dataUrl)==="undefined" && $.browser.msie) {
								$(elc).width($(elc).width());
							}
							cnt++;
						}
					}
				});
				if(cnt > 0) {
					svr.id = rowid; $t.p.savedRow.push(svr);
					$(ind).attr("editable","1");
					$("td:eq("+focus+") input",ind).focus();
					if(o.keys===true) {
						$(ind).bind("keydown",function(e) {
							if (e.keyCode === 27) {$($t).jqGrid("restoreRow",rowid, afterrestorefunc);}
							if (e.keyCode === 13) {
								var ta = e.target;
								if(ta.tagName == 'TEXTAREA') { return true; }
								$($t).jqGrid("saveRow", rowid, o );
								return false;
							}
							e.stopPropagation();
						});
					}
					if( $.isFunction(o.oneditfunc)) { o.oneditfunc.call($t, rowid); }
				}
			}
		});
	},
	saveRow : function(rowid, successfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc) {
		// Compatible mode old versions
		var settings = {
			"successfunc" : successfunc || null,
			"url" : url || null,
			"extraparam" : extraparam || {},
			"aftersavefunc" : aftersavefunc || null,
			"errorfunc": errorfunc || null,
			"afterrestorefunc" : afterrestorefunc|| null,
			"restoreAfterErorr" : true
		},
		args = $.makeArray(arguments).slice(1), o;

		if(args[0] && typeof(args[0]) == "object" && !$.isFunction(args[0])) {
			o = $.extend(settings,args[0]);
		} else {
			o = settings;
		}
		// End compatible
		var success = false;
		var $t = this[0], nm, tmp={}, tmp2={}, tmp3= {}, editable, fr, cv, ind;
		if (!$t.grid ) { return success; }
		ind = $($t).jqGrid("getInd",rowid,true);
		if(ind === false) {return success;}
		editable = $(ind).attr("editable");
		o.url = o.url ? o.url : $t.p.editurl;
		if (editable==="1") {
			var cm;
			$("td",ind).each(function(i) {
				cm = $t.p.colModel[i];
				nm = cm.name;
				if ( nm != 'cb' && nm != 'subgrid' && cm.editable===true && nm != 'rn' && !$(this).hasClass('not-editable-cell')) {
					switch (cm.edittype) {
						case "checkbox":
							var cbv = ["Yes","No"];
							if(cm.editoptions ) {
								cbv = cm.editoptions.value.split(":");
							}
							tmp[nm]=  $("input",this).attr("checked") ? cbv[0] : cbv[1];
							break;
						case 'text':
						case 'password':
						case 'textarea':
						case "button" :
							tmp[nm]=$("input, textarea",this).val();
							break;
						case 'select':
							if(!cm.editoptions.multiple) {
								tmp[nm] = $("select option:selected",this).val();
								tmp2[nm] = $("select option:selected", this).text();
							} else {
								var sel = $("select",this), selectedText = [];
								tmp[nm] = $(sel).val();
								if(tmp[nm]) { tmp[nm]= tmp[nm].join(","); } else { tmp[nm] =""; }
								$("select option:selected",this).each(
									function(i,selected){
										selectedText[i] = $(selected).text();
									}
								);
								tmp2[nm] = selectedText.join(",");
							}
							if(cm.formatter && cm.formatter == 'select') { tmp2={}; }
							break;
						case 'custom' :
							try {
								if(cm.editoptions && $.isFunction(cm.editoptions.custom_value)) {
									tmp[nm] = cm.editoptions.custom_value.call($t, $(".customelement",this),'get');
									if (tmp[nm] === undefined) { throw "e2"; }
								} else { throw "e1"; }
							} catch (e) {
								if (e=="e1") { $.jgrid.info_dialog(jQuery.jgrid.errors.errcap,"function 'custom_value' "+$.jgrid.edit.msg.nodefined,jQuery.jgrid.edit.bClose); }
								if (e=="e2") { $.jgrid.info_dialog(jQuery.jgrid.errors.errcap,"function 'custom_value' "+$.jgrid.edit.msg.novalue,jQuery.jgrid.edit.bClose); }
								else { $.jgrid.info_dialog(jQuery.jgrid.errors.errcap,e.message,jQuery.jgrid.edit.bClose); }
							}
							break;
					}
					cv = $.jgrid.checkValues(tmp[nm],i,$t);
					if(cv[0] === false) {
						cv[1] = tmp[nm] + " " + cv[1];
						return false;
					}
					if($t.p.autoencode) { tmp[nm] = $.jgrid.htmlEncode(tmp[nm]); }
					if(o.url !== 'clientArray' && cm.editoptions && cm.editoptions.NullIfEmpty === true) {
						if(tmp[nm] == "") {
							tmp3[nm] = 'null';
				}
					}
				}
			});
			if (cv[0] === false){
				try {
					var positions = $.jgrid.findPos($("#"+$.jgrid.jqID(rowid), $t.grid.bDiv)[0]);
					$.jgrid.info_dialog($.jgrid.errors.errcap,cv[1],$.jgrid.edit.bClose,{left:positions[0],top:positions[1]});
				} catch (e) {
					alert(cv[1]);
				}
				return success;
			}
			if(tmp) {
				var idname, opers, oper;
				opers = $t.p.prmNames;
				oper = opers.oper;
				idname = opers.id;
				tmp[oper] = opers.editoper;
				tmp[idname] = rowid;
				if(typeof($t.p.inlineData) == 'undefined') { $t.p.inlineData ={}; }
				tmp = $.extend({},tmp,$t.p.inlineData,o.extraparam);
			}
			if (o.url == 'clientArray') {
				tmp = $.extend({},tmp, tmp2);
				if($t.p.autoencode) {
					$.each(tmp,function(n,v){
						tmp[n] = $.jgrid.htmlDecode(v);
					});
				}
				var resp = $($t).jqGrid("setRowData",rowid,tmp);
				$(ind).attr("editable","0");
				for( var k=0;k<$t.p.savedRow.length;k++) {
					if( $t.p.savedRow[k].id == rowid) {fr = k; break;}
				}
				if(fr >= 0) { $t.p.savedRow.splice(fr,1); }
				if( $.isFunction(o.aftersavefunc) ) { o.aftersavefunc.call($t, rowid,resp); }
				success = true;
				$(ind).unbind("keydown");
			} else {
				$("#lui_"+$t.p.id).show();
				tmp3 = $.extend({},tmp,tmp3);
				$.ajax($.extend({
					url:o.url,
					data: $.isFunction($t.p.serializeRowData) ? $t.p.serializeRowData.call($t, tmp3) : tmp3,
					type: "POST",
					async : false, //?!?
					complete: function(res,stat){
						$("#lui_"+$t.p.id).hide();
						if (stat === "success"){
							var ret;
							if( $.isFunction(o.successfunc)) { ret = o.successfunc.call($t, res);}
							else { ret = true; }
							if (ret===true) {
								if($t.p.autoencode) {
									$.each(tmp,function(n,v){
										tmp[n] = $.jgrid.htmlDecode(v);
									});
								}
								tmp = $.extend({},tmp, tmp2);
								$($t).jqGrid("setRowData",rowid,tmp);
								$(ind).attr("editable","0");
								for( var k=0;k<$t.p.savedRow.length;k++) {
									if( $t.p.savedRow[k].id == rowid) {fr = k; break;}
								}
								if(fr >= 0) { $t.p.savedRow.splice(fr,1); }
								if( $.isFunction(o.aftersavefunc) ) { o.aftersavefunc.call($t, rowid,res); }
								success = true;
								$(ind).unbind("keydown");
							} else {
								if($.isFunction(o.errorfunc) ) {
									o.errorfunc.call($t, rowid, res, stat);
								}
								if(o.restoreAfterError === true) {
									$($t).jqGrid("restoreRow",rowid, o.afterrestorefunc);
							}
						}
						}
					},
					error:function(res,stat){
						$("#lui_"+$t.p.id).hide();
						if($.isFunction(o.errorfunc) ) {
							o.errorfunc.call($t, rowid, res, stat);
						} else {
							try {
								jQuery.jgrid.info_dialog(jQuery.jgrid.errors.errcap,'
'+ res.responseText +'
', jQuery.jgrid.edit.bClose,{buttonalign:'right'});
						}
							catch(e) {
								alert(res.responseText);
					}
						}
						if(o.restoreAfterError === true) {
							$($t).jqGrid("restoreRow",rowid, o.afterrestorefunc);
						}
					}
				}, $.jgrid.ajaxOptions, $t.p.ajaxRowOptions || {}));
			}
		}
		return success;
	},
	restoreRow : function(rowid, afterrestorefunc) {
		return this.each(function(){
			var $t= this, fr, ind, ares={};
			if (!$t.grid ) { return; }
			ind = $($t).jqGrid("getInd",rowid,true);
			if(ind === false) {return;}
			for( var k=0;k<$t.p.savedRow.length;k++) {
				if( $t.p.savedRow[k].id == rowid) {fr = k; break;}
			}
			if(fr >= 0) {
				if($.isFunction($.fn.datepicker)) {
					try {
						$("input.hasDatepicker","#"+$.jgrid.jqID(ind.id)).datepicker('hide');
					} catch (e) {}
				}
				$.each($t.p.colModel, function(i,n){
					if(this.editable === true && this.name in $t.p.savedRow[fr] && !$(this).hasClass('not-editable-cell')) {
						ares[this.name] = $t.p.savedRow[fr][this.name];
					}
				});
				$($t).jqGrid("setRowData",rowid,ares);
				$(ind).attr("editable","0").unbind("keydown");
				$t.p.savedRow.splice(fr,1);
			}
			if ($.isFunction(afterrestorefunc))
			{
				afterrestorefunc.call($t, rowid);
			}
		});
	}
//end inline edit
});
})(jQuery);
<|endoftext|>


<commit_before><commit_msg>test: Restore test for _addDataRatios of bubbleChart<commit_after><|endoftext|>


<commit_before>'use strict';

function draw_logic(){
    // Draw sky gradient.
    var gradient = buffer.createLinearGradient(
      x,
      10,
      x,
      y
    );
    gradient.addColorStop(
      0,
      '#ccc'
    );
    gradient.addColorStop(
      1,
      '#003'
    );
    buffer.fillStyle = gradient;
    buffer.fillRect(
      0,
      0,
      width,
      y
    );

    // Precalculate stuff.
    var math = [
      width / 100,
      width / 45,
      x * .4,
      y * .4,
      x * 1.6,
      height / 100,
      x * .9,
      x * .7,
      height / 7,
    ];

    // Draw mountains with gradient fillstyle.
    var j = y * .25;
    var k = y * .3;
    buffer.beginPath();
    var loop_counter = 2;
    do{
        buffer.moveTo(
          [
            x,
            math[2],
            math[4],
          ][loop_counter],
          [
            math[3],
            j,
            k,
          ][loop_counter]
        );
        buffer.lineTo(
          (
            [
              x,
              math[2],
              math[4],
            ][loop_counter]) + ([
              math[6],
              math[7],
              math[6],
            ][loop_counter]
          ),
          y
        );
        buffer.lineTo(
          (
            [
              x,
              0,
              math[4],
            ][loop_counter]) - ([
              math[7],
              math[7],
              math[6],
            ][loop_counter]
          ),
          y
        );
    }while(loop_counter--);
    buffer.closePath();

    // Draw ground gradient.
    gradient = buffer.createLinearGradient(
      x,
      math[3],
      x,
      y * .65
    );
    gradient.addColorStop(
      0,
      '#eee'
    );
    gradient.addColorStop(
      1,
      '#730'
    );
    buffer.fillStyle = gradient;
    buffer.fill();

    // Draw tree trunks.
    buffer.fillStyle = '#930';
    for(var tree in trees){
        buffer.fillRect(
          width * trees[tree][0] - math[0] * 2,
          trees[tree][1],
          math[0] * trees[tree][2],
          math[0] * trees[tree][2]
        );
    }

    // Draw tree leaves.
    loop_counter = trees.length - 1;
    do{
        buffer.beginPath();
        buffer.moveTo(
          width * trees[loop_counter][0],
          trees[loop_counter][1] - math[8] * trees[loop_counter][2]
        );
        buffer.lineTo(
          width * trees[loop_counter][0] + math[1] * trees[loop_counter][2],
          trees[loop_counter][1] + 1
        );
        buffer.lineTo(
          width * trees[loop_counter][0] - math[1] * trees[loop_counter][2],
          trees[loop_counter][1] + 1
        );
        buffer.closePath();
        buffer.fillStyle = trees[loop_counter][3];
        buffer.fill();
    }while(loop_counter--);

    // Draw wreathe on top of closest tree.
    loop_counter = 1;
    do{
        buffer.fillStyle = [
          trees[0][3],
          '#0d0',
        ][loop_counter];
        buffer.beginPath();
        buffer.arc(
          width * trees[0][0],
          trees[0][1] - math[8],
          height / (40 - 20 * loop_counter),
          0,
          tau,
          false
        );
        buffer.closePath();
        buffer.fill();
    }while(loop_counter--);

    // Draw red ornaments on top of wreathe.
    buffer.fillStyle = '#f00';
    loop_counter = 7;
    do{
        buffer.beginPath();
        buffer.arc(
          width * trees[0][0] + math[5] * (
            [
              -3.5,
              -2.5,
              0,
              2.5,
              3.5,
              2.5,
              0,
              -2.5,
            ][loop_counter]
          ),
          trees[0][1] - math[8] + math[5] * (
            [
              0,
              -2.5,
              -3.5,
              -2.5,
              0,
              2.5,
              3.5,
              2.5,
            ][loop_counter]
          ),
          math[5],
          0,
          tau,
          false
        );
        buffer.closePath();
        buffer.fill();
    }while(loop_counter--);

    buffer.fillStyle = '#fff';
    // Draw snowflakes.
    for(var snowflake in snowflakes){
        buffer.fillRect(
          snowflakes[snowflake]['x'],
          snowflakes[snowflake]['y'],
          snowflakes[snowflake]['size'],
          snowflakes[snowflake]['size']
        );
    }
}

function logic(){
    // Add 2 snowflakes.
    var loop_counter = 1;
    do{
        snowflakes.push({
          'size': random_number(2) + 3,
          'speed': random_number(4),
          'x': random_number(width),
          'y': 0,
        });
    }while(loop_counter--);

    for(var snowflake in snowflakes){
        if(snowflakes[snowflake]['y'] > height){
            // Remove snowflake that reached bottom of screen.
            snowflakes.splice(
              snowflake,
              1
            );

        }else{
            // Update snowflake position.
            snowflakes[snowflake]['x'] += Math.random() * 2 - 1;
            snowflakes[snowflake]['y'] += Math.random() * 4 + snowflakes[snowflake]['speed'];
        }
    }
}

function random_number(i){
    return Math.floor(Math.random() * i);
}

function resize_logic(){
    trees = [];

    var a = y * .75;
    var k = y * .35;
    var j = 0;

    // Create 300 trees.
    var loop_counter = 299;
    do{
        if(loop_counter > 200){
            j = random_number(y * 1.1) + a;

        }else if(loop_counter > 10){
            j = random_number(y * .7) + a;

        }else{
            j = random_number(y * .2) + a;
        }

        trees.push([
          Math.random(),
          j,
          -(y / 2 - j) / k,
          '#' + random_number(5)
            + (random_number(5) + 4)
            + random_number(5),
        ]);
    }while(loop_counter--);

    // Sort trees so closer trees are drawn on top.
    trees.sort(function(i, n){
        return parseFloat(n[2]) - parseFloat(i[2]);
    });
}

var snowflakes = [];
var tau = Math.PI * 2;
var trees = [];

window.onload = function(){
    document.body.style.background = '#fff';

    init_canvas();
};
<commit_msg>improved wreathe<commit_after>'use strict';

function draw_logic(){
    // Draw sky gradient.
    var gradient = buffer.createLinearGradient(
      x,
      10,
      x,
      y
    );
    gradient.addColorStop(
      0,
      '#ccc'
    );
    gradient.addColorStop(
      1,
      '#003'
    );
    buffer.fillStyle = gradient;
    buffer.fillRect(
      0,
      0,
      width,
      y
    );

    // Precalculate stuff.
    var math = [
      width / 100,
      width / 45,
      x * .4,
      y * .4,
      x * 1.6,
      height / 100,
      x * .9,
      x * .7,
      height / 7,
    ];

    // Draw mountains with gradient fillstyle.
    var j = y * .25;
    var k = y * .3;
    buffer.beginPath();
    var loop_counter = 2;
    do{
        buffer.moveTo(
          [
            x,
            math[2],
            math[4],
          ][loop_counter],
          [
            math[3],
            j,
            k,
          ][loop_counter]
        );
        buffer.lineTo(
          (
            [
              x,
              math[2],
              math[4],
            ][loop_counter]) + ([
              math[6],
              math[7],
              math[6],
            ][loop_counter]
          ),
          y
        );
        buffer.lineTo(
          (
            [
              x,
              0,
              math[4],
            ][loop_counter]) - ([
              math[7],
              math[7],
              math[6],
            ][loop_counter]
          ),
          y
        );
    }while(loop_counter--);
    buffer.closePath();

    // Draw ground gradient.
    gradient = buffer.createLinearGradient(
      x,
      math[3],
      x,
      y * .65
    );
    gradient.addColorStop(
      0,
      '#eee'
    );
    gradient.addColorStop(
      1,
      '#730'
    );
    buffer.fillStyle = gradient;
    buffer.fill();

    // Draw tree trunks.
    buffer.fillStyle = '#930';
    for(var tree in trees){
        buffer.fillRect(
          width * trees[tree][0] - math[0] * 2,
          trees[tree][1],
          math[0] * trees[tree][2],
          math[0] * trees[tree][2]
        );
    }

    // Draw tree leaves.
    loop_counter = trees.length - 1;
    do{
        buffer.beginPath();
        buffer.moveTo(
          width * trees[loop_counter][0],
          trees[loop_counter][1] - math[8] * trees[loop_counter][2]
        );
        buffer.lineTo(
          width * trees[loop_counter][0] + math[1] * trees[loop_counter][2],
          trees[loop_counter][1] + 1
        );
        buffer.lineTo(
          width * trees[loop_counter][0] - math[1] * trees[loop_counter][2],
          trees[loop_counter][1] + 1
        );
        buffer.closePath();
        buffer.fillStyle = trees[loop_counter][3];
        buffer.fill();
    }while(loop_counter--);

    // Draw wreathe on top of closest tree.
    loop_counter = 1;
    do{
        buffer.fillStyle = [
          trees[0][3],
          '#0d0',
        ][loop_counter];
        buffer.beginPath();
        buffer.arc(
          width * trees[0][0],
          trees[0][1] - math[8],
          height / (40 - 20 * loop_counter),
          0,
          tau,
          false
        );
        buffer.closePath();
        buffer.fill();
    }while(loop_counter--);

    // Draw red ornaments on top of wreathe.
    buffer.fillStyle = '#f00';
    loop_counter = 7;
    do{
        buffer.beginPath();
        buffer.arc(
          width * trees[0][0] + math[5] * (
            [
              -3.7,
              -2.7,
              0,
              2.7,
              3.7,
              2.7,
              0,
              -2.7,
            ][loop_counter]
          ),
          trees[0][1] - math[8] + math[5] * (
            [
              0,
              -2.7,
              -3.7,
              -2.7,
              0,
              2.7,
              3.7,
              2.7,
            ][loop_counter]
          ),
          math[5],
          0,
          tau,
          false
        );
        buffer.closePath();
        buffer.fill();
    }while(loop_counter--);

    buffer.fillStyle = '#fff';
    // Draw snowflakes.
    for(var snowflake in snowflakes){
        buffer.fillRect(
          snowflakes[snowflake]['x'],
          snowflakes[snowflake]['y'],
          snowflakes[snowflake]['size'],
          snowflakes[snowflake]['size']
        );
    }
}

function logic(){
    // Add 2 snowflakes.
    var loop_counter = 1;
    do{
        snowflakes.push({
          'size': random_number(2) + 3,
          'speed': random_number(4),
          'x': random_number(width),
          'y': 0,
        });
    }while(loop_counter--);

    for(var snowflake in snowflakes){
        if(snowflakes[snowflake]['y'] > height){
            // Remove snowflake that reached bottom of screen.
            snowflakes.splice(
              snowflake,
              1
            );

        }else{
            // Update snowflake position.
            snowflakes[snowflake]['x'] += Math.random() * 2 - 1;
            snowflakes[snowflake]['y'] += Math.random() * 4 + snowflakes[snowflake]['speed'];
        }
    }
}

function random_number(i){
    return Math.floor(Math.random() * i);
}

function resize_logic(){
    trees = [];

    var a = y * .75;
    var k = y * .35;
    var j = 0;

    // Create 300 trees.
    var loop_counter = 299;
    do{
        if(loop_counter > 200){
            j = random_number(y * 1.1) + a;

        }else if(loop_counter > 10){
            j = random_number(y * .7) + a;

        }else{
            j = random_number(y * .2) + a;
        }

        trees.push([
          Math.random(),
          j,
          -(y / 2 - j) / k,
          '#' + random_number(5)
            + (random_number(5) + 4)
            + random_number(5),
        ]);
    }while(loop_counter--);

    // Sort trees so closer trees are drawn on top.
    trees.sort(function(i, n){
        return parseFloat(n[2]) - parseFloat(i[2]);
    });
}

var snowflakes = [];
var tau = Math.PI * 2;
var trees = [];

window.onload = function(){
    document.body.style.background = '#fff';

    init_canvas();
};
<|endoftext|>


<commit_before>'use strict';
const express = require('express');

const root = 'C:\\';
const gitPull = () => {
  const
      spawn = require( 'child_process' ).exec,
      git = spawn( 'git', ['pull'] , {
          cwd:  "C:\\recordings-fs\\"
      });

      //console.log('test');
      //console.log('git', git);

  git.stdout.on( 'data', data => {
      console.log( `stdout: ${data}` );
  });

  git.stderr.on( 'data', data => {
      console.log( `stderr: ${data}` );
  });

  git.on( 'close', code => {
      console.log( `child process exiteds with code ${code}` );
  });
}

const app = express();

app.post('/repo', (req, res, rext) => {
  gitPull();
  res.status(200).end('oks');
});

app.get('/static', (req, res, next) => {
  var files = fs.readdirSync(root);

  var streamfiles = files.filter((file) => {
    return file.indexOf('tv') != -1;
  });

  res.status(200).end(JSON.stringify(streamfiles));
});

app.listen('8999', '0.0.0.0', () => {
  console.log('started');
});
<commit_msg>testing gitPull() 7<commit_after>'use strict';
const express = require('express');

const root = 'C:\\';
const gitPull = () => {
  const
      spawn = require( 'child_process' ).exec,
      git = spawn( 'git', [' pull'] , {
          cwd:  "C:\\recordings-fs\\"
      });

      //console.log('test');
      //console.log('git', git);

  git.stdout.on( 'data', data => {
      console.log( `stdout: ${data}` );
  });

  git.stderr.on( 'data', data => {
      console.log( `stderr: ${data}` );
  });

  git.on( 'close', code => {
      console.log( `child process exiteds with code ${code}` );
  });
}

const app = express();

app.post('/repo', (req, res, rext) => {
  gitPull();
  res.status(200).end('ok');
});

app.get('/static', (req, res, next) => {
  var files = fs.readdirSync(root);

  var streamfiles = files.filter((file) => {
    return file.indexOf('tv') != -1;
  });

  res.status(200).end(JSON.stringify(streamfiles));
});

app.listen('8999', '0.0.0.0', () => {
  console.log('started');
});
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */

var express = require('express'),
    routes = require('./routes'),
    user = require('./routes/user'),
    http = require('http'),
    path = require('path'),
    fs = require('fs');

var app = express();

var db;

var cloudant;

var fileToUpload;

var dbCredentials = {
    dbName: 'my_sample_db'
};

var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var logger = require('morgan');
var errorHandler = require('errorhandler');
var multipart = require('connect-multiparty')
var multipartMiddleware = multipart();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(logger('dev'));
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/style', express.static(path.join(__dirname, '/views/style')));

// development only
if ('development' == app.get('env')) {
    app.use(errorHandler());
}

function getDBCredentialsUrl(jsonData) {
    var vcapServices = JSON.parse(jsonData);
    // Pattern match to find the first instance of a Cloudant service in
    // VCAP_SERVICES. If you know your service key, you can access the
    // service credentials directly by using the vcapServices object.
    for (var vcapService in vcapServices) {
        if (vcapService.match(/cloudant/i)) {
            return vcapServices[vcapService][0].credentials.url;
        }
    }
}

function initDBConnection() {
    //When running on Bluemix, this variable will be set to a json object
    //containing all the service credentials of all the bound services
    if (process.env.VCAP_SERVICES) {
        dbCredentials.url = getDBCredentialsUrl(process.env.VCAP_SERVICES);
    } else { //When running locally, the VCAP_SERVICES will not be set

        // When running this app locally you can get your Cloudant credentials
        // from Bluemix (VCAP_SERVICES in "cf env" output or the Environment
        // Variables section for an app in the Bluemix console dashboard).
        // Once you have the credentials, paste them into a file called vcap-local.json.
        // Alternately you could point to a local database here instead of a
        // Bluemix service.
        // url will be in this format: https://username:password@xxxxxxxxx-bluemix.cloudant.com
        dbCredentials.url = getDBCredentialsUrl(fs.readFileSync("vcap-local.json", "utf-8"));
    }

    cloudant = require('cloudant')(dbCredentials.url);

    // check if DB exists if not create
    cloudant.db.create(dbCredentials.dbName, function(err, res) {
        if (err) {
            console.log('Could not create new db: ' + dbCredentials.dbName + ', it might already exist.');
        }
    });

    db = cloudant.use(dbCredentials.dbName);
}

initDBConnection();

app.get('/', routes.index);

function createResponseData(id, name, value, attachments) {

    var responseData = {
        id: id,
        name: sanitizeInput(name),
        value: sanitizeInput(value),
        attachements: []
    };

    attachments.forEach(function(item, index) {
        var attachmentData = {
            content_type: item.type,
            key: item.key,
            url: '/api/favorites/attach?id=' + id + '&key=' + item.key
        };
        responseData.attachements.push(attachmentData);

    });
    return responseData;
}

function sanitizeInput(str) {
    return String(str).replace(/&(?!amp;|lt;|gt;)/g, '&').replace(/</g, '<').replace(/>/g, '>');
}

var saveDocument = function(id, name, value, response) {

    if (id === undefined) {
        // Generated random id
        id = '';
    }

    db.insert({
        name: name,
        value: value
    }, id, function(err, doc) {
        if (err) {
            console.log(err);
            response.sendStatus(500);
        } else
            response.sendStatus(200);
        response.end();
    });

}

app.get('/api/favorites/attach', function(request, response) {
    var doc = request.query.id;
    var key = request.query.key;

    db.attachment.get(doc, key, function(err, body) {
        if (err) {
            response.status(500);
            response.setHeader('Content-Type', 'text/plain');
            response.write('Error: ' + err);
            response.end();
            return;
        }

        response.status(200);
        response.setHeader("Content-Disposition", 'inline; filename="' + key + '"');
        response.write(body);
        response.end();
        return;
    });
});

app.post('/api/favorites/attach', multipartMiddleware, function(request, response) {

    console.log("Upload File Invoked..");
    console.log('Request: ' + JSON.stringify(request.headers));

    var id;

    db.get(request.query.id, function(err, existingdoc) {

        var isExistingDoc = false;
        if (!existingdoc) {
            id = '-1';
        } else {
            id = existingdoc.id;
            isExistingDoc = true;
        }

        var name = sanitizeInput(request.query.name);
        var value = sanitizeInput(request.query.value);

        var file = request.files.file;
        var newPath = './public/uploads/' + file.name;

        var insertAttachment = function(file, id, rev, name, value, response) {

            fs.readFile(file.path, function(err, data) {
                if (!err) {

                    if (file) {

                        db.attachment.insert(id, file.name, data, file.type, {
                            rev: rev
                        }, function(err, document) {
                            if (!err) {
                                console.log('Attachment saved successfully.. ');

                                db.get(document.id, function(err, doc) {
                                    console.log('Attachements from server --> ' + JSON.stringify(doc._attachments));

                                    var attachements = [];
                                    var attachData;
                                    for (var attachment in doc._attachments) {
                                        if (attachment == value) {
                                            attachData = {
                                                "key": attachment,
                                                "type": file.type
                                            };
                                        } else {
                                            attachData = {
                                                "key": attachment,
                                                "type": doc._attachments[attachment]['content_type']
                                            };
                                        }
                                        attachements.push(attachData);
                                    }
                                    var responseData = createResponseData(
                                        id,
                                        name,
                                        value,
                                        attachements);
                                    console.log('Response after attachment: \n' + JSON.stringify(responseData));
                                    response.write(JSON.stringify(responseData));
                                    response.end();
                                    return;
                                });
                            } else {
                                console.log(err);
                            }
                        });
                    }
                }
            });
        }

        if (!isExistingDoc) {
            existingdoc = {
                name: name,
                value: value,
                create_date: new Date()
            };

            // save doc
            db.insert({
                name: name,
                value: value
            }, '', function(err, doc) {
                if (err) {
                    console.log(err);
                } else {

                    existingdoc = doc;
                    console.log("New doc created ..");
                    console.log(existingdoc);
                    insertAttachment(file, existingdoc.id, existingdoc.rev, name, value, response);

                }
            });

        } else {
            console.log('Adding attachment to existing doc.');
            console.log(existingdoc);
            insertAttachment(file, existingdoc._id, existingdoc._rev, name, value, response);
        }

    });

});

app.post('/api/logs', function(request, response) {

    console.log("Capturing the logs..");
    console.log("Log Data : " + request.body);
	response.status(200);
	response.end();
});

app.post('/api/favorites', function(request, response) {

    console.log("Create Invoked..");
    console.log("Name: " + request.body.name);
    console.log("Value: " + request.body.value);

    // var id = request.body.id;
    var name = sanitizeInput(request.body.name);
    var value = sanitizeInput(request.body.value);

    saveDocument(null, name, value, response);

});

app.delete('/api/favorites', function(request, response) {

    console.log("Delete Invoked..");
    var id = request.query.id;
    // var rev = request.query.rev; // Rev can be fetched from request. if
    // needed, send the rev from client
    console.log("Removing document of ID: " + id);
    console.log('Request Query: ' + JSON.stringify(request.query));

    db.get(id, {
        revs_info: true
    }, function(err, doc) {
        if (!err) {
            db.destroy(doc._id, doc._rev, function(err, res) {
                // Handle response
                if (err) {
                    console.log(err);
                    response.sendStatus(500);
                } else {
                    response.sendStatus(200);
                }
            });
        }
    });

});

app.put('/api/favorites', function(request, response) {

    console.log("Update Invoked..");

    var id = request.body.id;
    var name = sanitizeInput(request.body.name);
    var value = sanitizeInput(request.body.value);

    console.log("ID: " + id);

    db.get(id, {
        revs_info: true
    }, function(err, doc) {
        if (!err) {
            console.log(doc);
            doc.name = name;
            doc.value = value;
            db.insert(doc, doc.id, function(err, doc) {
                if (err) {
                    console.log('Error inserting data\n' + err);
                    return 500;
                }
                return 200;
            });
        }
    });
});

app.get('/api/favorites', function(request, response) {

    console.log("Get method invoked.. ")

    db = cloudant.use(dbCredentials.dbName);
    var docList = [];
    var i = 0;
    db.list(function(err, body) {
        if (!err) {
            var len = body.rows.length;
            console.log('total # of docs -> ' + len);
            if (len == 0) {
                // push sample data
                // save doc
                var docName = 'sample_doc';
                var docDesc = 'A sample Document';
                db.insert({
                    name: docName,
                    value: 'A sample Document'
                }, '', function(err, doc) {
                    if (err) {
                        console.log(err);
                    } else {

                        console.log('Document : ' + JSON.stringify(doc));
                        var responseData = createResponseData(
                            doc.id,
                            docName,
                            docDesc, []);
                        docList.push(responseData);
                        response.write(JSON.stringify(docList));
                        console.log(JSON.stringify(docList));
                        console.log('ending response...');
                        response.end();
                    }
                });
            } else {

                body.rows.forEach(function(document) {

                    db.get(document.id, {
                        revs_info: true
                    }, function(err, doc) {
                        if (!err) {
                            if (doc['_attachments']) {

                                var attachments = [];
                                for (var attribute in doc['_attachments']) {

                                    if (doc['_attachments'][attribute] && doc['_attachments'][attribute]['content_type']) {
                                        attachments.push({
                                            "key": attribute,
                                            "type": doc['_attachments'][attribute]['content_type']
                                        });
                                    }
                                    console.log(attribute + ": " + JSON.stringify(doc['_attachments'][attribute]));
                                }
                                var responseData = createResponseData(
                                    doc._id,
                                    doc.name,
                                    doc.value,
                                    attachments);

                            } else {
                                var responseData = createResponseData(
                                    doc._id,
                                    doc.name,
                                    doc.value, []);
                            }

                            docList.push(responseData);
                            i++;
                            if (i >= len) {
                                response.write(JSON.stringify(docList));
                                console.log('ending response...');
                                response.end();
                            }
                        } else {
                            console.log(err);
                        }
                    });

                });
            }

        } else {
            console.log(err);
        }
    });

});

http.createServer(app).listen(app.get('port'), '0.0.0.0', function() {
    console.log('Express server listening on port ' + app.get('port'));
});
<commit_msg>added bodyparser<commit_after>/**
 * Module dependencies.
 */

var express = require('express'),
    routes = require('./routes'),
    user = require('./routes/user'),
    http = require('http'),
    path = require('path'),
    fs = require('fs');

var bodyParser = require('body-parser');

var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

var db;

var cloudant;

var fileToUpload;

var dbCredentials = {
    dbName: 'my_sample_db'
};

var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var logger = require('morgan');
var errorHandler = require('errorhandler');
var multipart = require('connect-multiparty')
var multipartMiddleware = multipart();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(logger('dev'));
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/style', express.static(path.join(__dirname, '/views/style')));

// development only
if ('development' == app.get('env')) {
    app.use(errorHandler());
}

function getDBCredentialsUrl(jsonData) {
    var vcapServices = JSON.parse(jsonData);
    // Pattern match to find the first instance of a Cloudant service in
    // VCAP_SERVICES. If you know your service key, you can access the
    // service credentials directly by using the vcapServices object.
    for (var vcapService in vcapServices) {
        if (vcapService.match(/cloudant/i)) {
            return vcapServices[vcapService][0].credentials.url;
        }
    }
}

function initDBConnection() {
    //When running on Bluemix, this variable will be set to a json object
    //containing all the service credentials of all the bound services
    if (process.env.VCAP_SERVICES) {
        dbCredentials.url = getDBCredentialsUrl(process.env.VCAP_SERVICES);
    } else { //When running locally, the VCAP_SERVICES will not be set

        // When running this app locally you can get your Cloudant credentials
        // from Bluemix (VCAP_SERVICES in "cf env" output or the Environment
        // Variables section for an app in the Bluemix console dashboard).
        // Once you have the credentials, paste them into a file called vcap-local.json.
        // Alternately you could point to a local database here instead of a
        // Bluemix service.
        // url will be in this format: https://username:password@xxxxxxxxx-bluemix.cloudant.com
        dbCredentials.url = getDBCredentialsUrl(fs.readFileSync("vcap-local.json", "utf-8"));
    }

    cloudant = require('cloudant')(dbCredentials.url);

    // check if DB exists if not create
    cloudant.db.create(dbCredentials.dbName, function(err, res) {
        if (err) {
            console.log('Could not create new db: ' + dbCredentials.dbName + ', it might already exist.');
        }
    });

    db = cloudant.use(dbCredentials.dbName);
}

initDBConnection();

app.get('/', routes.index);

function createResponseData(id, name, value, attachments) {

    var responseData = {
        id: id,
        name: sanitizeInput(name),
        value: sanitizeInput(value),
        attachements: []
    };

    attachments.forEach(function(item, index) {
        var attachmentData = {
            content_type: item.type,
            key: item.key,
            url: '/api/favorites/attach?id=' + id + '&key=' + item.key
        };
        responseData.attachements.push(attachmentData);

    });
    return responseData;
}

function sanitizeInput(str) {
    return String(str).replace(/&(?!amp;|lt;|gt;)/g, '&').replace(/</g, '<').replace(/>/g, '>');
}

var saveDocument = function(id, name, value, response) {

    if (id === undefined) {
        // Generated random id
        id = '';
    }

    db.insert({
        name: name,
        value: value
    }, id, function(err, doc) {
        if (err) {
            console.log(err);
            response.sendStatus(500);
        } else
            response.sendStatus(200);
        response.end();
    });

}

app.get('/api/favorites/attach', function(request, response) {
    var doc = request.query.id;
    var key = request.query.key;

    db.attachment.get(doc, key, function(err, body) {
        if (err) {
            response.status(500);
            response.setHeader('Content-Type', 'text/plain');
            response.write('Error: ' + err);
            response.end();
            return;
        }

        response.status(200);
        response.setHeader("Content-Disposition", 'inline; filename="' + key + '"');
        response.write(body);
        response.end();
        return;
    });
});

app.post('/api/favorites/attach', multipartMiddleware, function(request, response) {

    console.log("Upload File Invoked..");
    console.log('Request: ' + JSON.stringify(request.headers));

    var id;

    db.get(request.query.id, function(err, existingdoc) {

        var isExistingDoc = false;
        if (!existingdoc) {
            id = '-1';
        } else {
            id = existingdoc.id;
            isExistingDoc = true;
        }

        var name = sanitizeInput(request.query.name);
        var value = sanitizeInput(request.query.value);

        var file = request.files.file;
        var newPath = './public/uploads/' + file.name;

        var insertAttachment = function(file, id, rev, name, value, response) {

            fs.readFile(file.path, function(err, data) {
                if (!err) {

                    if (file) {

                        db.attachment.insert(id, file.name, data, file.type, {
                            rev: rev
                        }, function(err, document) {
                            if (!err) {
                                console.log('Attachment saved successfully.. ');

                                db.get(document.id, function(err, doc) {
                                    console.log('Attachements from server --> ' + JSON.stringify(doc._attachments));

                                    var attachements = [];
                                    var attachData;
                                    for (var attachment in doc._attachments) {
                                        if (attachment == value) {
                                            attachData = {
                                                "key": attachment,
                                                "type": file.type
                                            };
                                        } else {
                                            attachData = {
                                                "key": attachment,
                                                "type": doc._attachments[attachment]['content_type']
                                            };
                                        }
                                        attachements.push(attachData);
                                    }
                                    var responseData = createResponseData(
                                        id,
                                        name,
                                        value,
                                        attachements);
                                    console.log('Response after attachment: \n' + JSON.stringify(responseData));
                                    response.write(JSON.stringify(responseData));
                                    response.end();
                                    return;
                                });
                            } else {
                                console.log(err);
                            }
                        });
                    }
                }
            });
        }

        if (!isExistingDoc) {
            existingdoc = {
                name: name,
                value: value,
                create_date: new Date()
            };

            // save doc
            db.insert({
                name: name,
                value: value
            }, '', function(err, doc) {
                if (err) {
                    console.log(err);
                } else {

                    existingdoc = doc;
                    console.log("New doc created ..");
                    console.log(existingdoc);
                    insertAttachment(file, existingdoc.id, existingdoc.rev, name, value, response);

                }
            });

        } else {
            console.log('Adding attachment to existing doc.');
            console.log(existingdoc);
            insertAttachment(file, existingdoc._id, existingdoc._rev, name, value, response);
        }

    });

});

app.post('/api/logs', function(request, response) {

    console.log("Capturing the logs..");
    console.log("Log Data : " + request.body);
	response.status(200);
	response.end();
});

app.post('/api/favorites', function(request, response) {

    console.log("Create Invoked..");
    console.log("Name: " + request.body.name);
    console.log("Value: " + request.body.value);

    // var id = request.body.id;
    var name = sanitizeInput(request.body.name);
    var value = sanitizeInput(request.body.value);

    saveDocument(null, name, value, response);

});

app.delete('/api/favorites', function(request, response) {

    console.log("Delete Invoked..");
    var id = request.query.id;
    // var rev = request.query.rev; // Rev can be fetched from request. if
    // needed, send the rev from client
    console.log("Removing document of ID: " + id);
    console.log('Request Query: ' + JSON.stringify(request.query));

    db.get(id, {
        revs_info: true
    }, function(err, doc) {
        if (!err) {
            db.destroy(doc._id, doc._rev, function(err, res) {
                // Handle response
                if (err) {
                    console.log(err);
                    response.sendStatus(500);
                } else {
                    response.sendStatus(200);
                }
            });
        }
    });

});

app.put('/api/favorites', function(request, response) {

    console.log("Update Invoked..");

    var id = request.body.id;
    var name = sanitizeInput(request.body.name);
    var value = sanitizeInput(request.body.value);

    console.log("ID: " + id);

    db.get(id, {
        revs_info: true
    }, function(err, doc) {
        if (!err) {
            console.log(doc);
            doc.name = name;
            doc.value = value;
            db.insert(doc, doc.id, function(err, doc) {
                if (err) {
                    console.log('Error inserting data\n' + err);
                    return 500;
                }
                return 200;
            });
        }
    });
});

app.get('/api/favorites', function(request, response) {

    console.log("Get method invoked.. ")

    db = cloudant.use(dbCredentials.dbName);
    var docList = [];
    var i = 0;
    db.list(function(err, body) {
        if (!err) {
            var len = body.rows.length;
            console.log('total # of docs -> ' + len);
            if (len == 0) {
                // push sample data
                // save doc
                var docName = 'sample_doc';
                var docDesc = 'A sample Document';
                db.insert({
                    name: docName,
                    value: 'A sample Document'
                }, '', function(err, doc) {
                    if (err) {
                        console.log(err);
                    } else {

                        console.log('Document : ' + JSON.stringify(doc));
                        var responseData = createResponseData(
                            doc.id,
                            docName,
                            docDesc, []);
                        docList.push(responseData);
                        response.write(JSON.stringify(docList));
                        console.log(JSON.stringify(docList));
                        console.log('ending response...');
                        response.end();
                    }
                });
            } else {

                body.rows.forEach(function(document) {

                    db.get(document.id, {
                        revs_info: true
                    }, function(err, doc) {
                        if (!err) {
                            if (doc['_attachments']) {

                                var attachments = [];
                                for (var attribute in doc['_attachments']) {

                                    if (doc['_attachments'][attribute] && doc['_attachments'][attribute]['content_type']) {
                                        attachments.push({
                                            "key": attribute,
                                            "type": doc['_attachments'][attribute]['content_type']
                                        });
                                    }
                                    console.log(attribute + ": " + JSON.stringify(doc['_attachments'][attribute]));
                                }
                                var responseData = createResponseData(
                                    doc._id,
                                    doc.name,
                                    doc.value,
                                    attachments);

                            } else {
                                var responseData = createResponseData(
                                    doc._id,
                                    doc.name,
                                    doc.value, []);
                            }

                            docList.push(responseData);
                            i++;
                            if (i >= len) {
                                response.write(JSON.stringify(docList));
                                console.log('ending response...');
                                response.end();
                            }
                        } else {
                            console.log(err);
                        }
                    });

                });
            }

        } else {
            console.log(err);
        }
    });

});

http.createServer(app).listen(app.get('port'), '0.0.0.0', function() {
    console.log('Express server listening on port ' + app.get('port'));
});
<|endoftext|>


<commit_before><commit_msg>Removing the comment....<commit_after><|endoftext|>


<commit_before>$(window).scroll(function() {
    // get current scroll top in px, add window height and
    // check if this is greater than the document height minus 300
    if ($(window).scrollTop() + $(window).height() >= $(document).height() - 300) {
        loadMoreContent(jQuery);
	masonry_gallery(jQuery);
    }
});

function loadMoreContent() {
    // there should be a button, which leads to next posts
    var next = $("a.next").first();
    var paginationnav = $("div.paginationnav").first();
    next.each(function(key, value) {
        var url = $(value).attr('href');
        // remove paginationnav, so we can't load multiple times
        next.remove();
        // adding a temp. dom object to load the next page
        var list = $("

");
        // call load method and get the div.post-list node
        list.load(url + " div.post-list", function(response, status, xhr) {
            // check if we doesn't get any error
            if ( status != "error" ) {
                // copy all childrens of our temp container to the real container
                // note: jQuery load will copy the div.post-list node as well,
                // so use the childrens and move them
                var container = $("div.post-list");
                list.children("div.post-list").children().each(
                    function(key, value){
                        container.append(value);
                    }
                );
            }
        });
	paginationnav.load(url + " div.paginationnav");
    });

}

/* ********* WINDOW LOAD ********** */
$(window).load(function() {
    masonry_gallery(jQuery)
    beforeafter(jQuery)
    var paginationnav = $("div.paginationnav").first();
    paginationnav.hide();
});

function masonry_gallery($)
{

    jQuery(window).load(function() {
	var $masonry_gallery = jQuery("div.gallery.masonry-gallery.post-list").first();
	if ( $masonry_gallery.length > 0 ) {
		$masonry_gallery.each( function(index, element) {
			var $masonry_items = $(element).find('.gallery-item');

			// set masonry layout
			$(element).isotope({
				masonry: { columnWidth: $(element).find('.gallery-item')[0] },
				itemSelector: '.gallery-item'
			});
			$(element).isotope('layout');

			// filtering
			jQuery('#gallery-filter li a').on('click', function(){
				jQuery('#gallery-filter li a').removeClass('active');
				jQuery(this).addClass('active');
				var selector = jQuery(this).attr('data-filter');
				$masonry_gallery.isotope({ filter: selector });
				return false;
			});

			// changing layout
			jQuery('#grid-changer li a').on('click', function(){
				jQuery('#grid-changer li a').removeClass('active');
				jQuery(this).toggleClass('active');

				$masonry_items.removeClass('col-3');
				$masonry_items.removeClass('col-4');
				$masonry_items.removeClass('col-5');
				$masonry_items.toggleClass(jQuery(this).closest('li').attr('class'));
				$masonry_gallery.isotope('layout');
			});

		});
	}
    }
}

function beforeafter($){
    var $before_after = jQuery('.before-after.gallery');
    if ( $before_after.length > 0 ) {
	    $before_after.imageReveal({
		    barWidth: 4,
		    touchBarWidth: 50,
		    startPosition: 0.5,
		    width: jQuery('.before-after img').width(),
		    height:  jQuery('.before-after img').height()
	    });
    }
}
<commit_msg>Script modif<commit_after>$(window).scroll(function() {
    // get current scroll top in px, add window height and
    // check if this is greater than the document height minus 300
    if ($(window).scrollTop() + $(window).height() >= $(document).height() - 300) {
        loadMoreContent(jQuery);
	masonry_gallery(jQuery);
    }
});

function loadMoreContent() {
    // there should be a button, which leads to next posts
    var next = $("a.next").first();
    var paginationnav = $("div.paginationnav").first();
    next.each(function(key, value) {
        var url = $(value).attr('href');
        // remove paginationnav, so we can't load multiple times
        next.remove();
        // adding a temp. dom object to load the next page
        var list = $("

");
        // call load method and get the div.post-list node
        list.load(url + " div.post-list", function(response, status, xhr) {
            // check if we doesn't get any error
            if ( status != "error" ) {
                // copy all childrens of our temp container to the real container
                // note: jQuery load will copy the div.post-list node as well,
                // so use the childrens and move them
                var container = $("div.post-list");
                list.children("div.post-list").children().each(
                    function(key, value){
                        container.append(value);
                    }
                );
            }
        });
	paginationnav.load(url + " div.paginationnav");
    });

}

/* ********* WINDOW LOAD ********** */
$(window).load(function() {
    masonry_gallery(jQuery)
    beforeafter(jQuery)
    var paginationnav = $("div.paginationnav").first();
    paginationnav.hide();
});

function masonry_gallery($)
{

    jQuery(window).load(function() {
	var $masonry_gallery = jQuery("div.gallery.masonry-gallery.post-list").first();
	if ( $masonry_gallery.length > 0 ) {
		$masonry_gallery.each( function(index, element) {
			var $masonry_items = $(element).find('.gallery-item');

			// set masonry layout
			$(element).isotope({
				masonry: { columnWidth: $(element).find('.gallery-item')[0] },
				itemSelector: '.gallery-item'
			});
			$(element).isotope('layout');

			// filtering
			jQuery('#gallery-filter li a').on('click', function(){
				jQuery('#gallery-filter li a').removeClass('active');
				jQuery(this).addClass('active');
				var selector = jQuery(this).attr('data-filter');
				$masonry_gallery.isotope({ filter: selector });
				return false;
			});

			// changing layout
			jQuery('#grid-changer li a').on('click', function(){
				jQuery('#grid-changer li a').removeClass('active');
				jQuery(this).toggleClass('active');

				$masonry_items.removeClass('col-3');
				$masonry_items.removeClass('col-4');
				$masonry_items.removeClass('col-5');
				$masonry_items.toggleClass(jQuery(this).closest('li').attr('class'));
				$masonry_gallery.isotope('layout');
			});

		});
	}
    });
}

function beforeafter($){
    var $before_after = jQuery('.before-after.gallery');
    if ( $before_after.length > 0 ) {
	    $before_after.imageReveal({
		    barWidth: 4,
		    touchBarWidth: 50,
		    startPosition: 0.5,
		    width: jQuery('.before-after img').width(),
		    height:  jQuery('.before-after img').height()
	    });
    }
}
<|endoftext|>


<commit_before>const mqtt = require("mqtt"),
      client = mqtt.connect("mqtt://127.0.0.1");

const status_topic = 'esp8266/status/led',
      control_topic = 'esp8266/control/led';

var ledstate, ledcontrol;

client.on('connect', ()=>{
    client.subscribe(status_topic);
    client.subscribe(control_topic);
});

client.on('message', (topic, message) => {
    switch(topic){
	case status_topic:
		handle_status_update(message);
		break;
  case control_topic:
    handle_control_topic(message);
    break;
	default:
		console.log("message from topic %s -> %s", topic, message);
    }
});

function handle_control_topic(message){
    ledcontrol = (message.toString()[0] === '1');
    console.log("control published, led to %s", ledcontrol?'up':'off');
}

function handle_status_update(message){
    ledstate = (message.toString()[0] === '1');
    console.log("status recvd from esp, led is %s", ledstate?'up':'off');
}

function command_esp(message){
    console.log("Sending message to esp %s %s", control_topic, message);
    client.publish(control_topic, message);
}

function start_loop(){
  setTimeout(()=>{
    looper();
  }, 15000);

  function looper(){
    if(ledcontrol !== undefined && ledstate !== ledcontrol)
      command_esp(ledcontrol ? '1': '0');
    start_loop();
  }
}

console.log("Hello IoT");
start_loop();
<commit_msg>override handling<commit_after>const mqtt = require("mqtt"),
      client = mqtt.connect("mqtt://127.0.0.1");

const status_topic = 'esp8266/status/led',
      control_topic = 'esp8266/control/led',
      override_topic = 'esp8266/override/led';

var ledstate, ledcontrol;

client.on('connect', ()=>{
    client.subscribe(status_topic);
    client.subscribe(control_topic);
    client.subscribe(override_topic);
});

client.on('message', (topic, message) => {
    switch(topic){
	case status_topic:
		handle_status_update(message);
		break;
  case control_topic:
    handle_control_topic(message);
    break;
  case override_topic:
    handle_override_topic(message);
    break;
	default:
		console.log("message from topic %s -> %s", topic, message);
    }
});

function handle_override_topic(message){
  ledcontrol = (message.toString()[0] === '1');
  console.log("override published, led to %s", ledcontrol?'up':'off');
}

function handle_control_topic(message){
    ledcontrol = (message.toString()[0] === '1');
    console.log("control published, led to %s", ledcontrol?'up':'off');
}

function handle_status_update(message){
    ledstate = (message.toString()[0] === '1');
    console.log("status recvd from esp, led is %s", ledstate?'up':'off');
}

function command_esp(message){
    console.log("Sending message to esp %s %s", control_topic, message);
    client.publish(control_topic, message);
}

function start_loop(){
  setTimeout(()=>{
    looper();
  }, 15000);

  function looper(){
    if(ledcontrol !== undefined && ledstate !== ledcontrol)
      command_esp(ledcontrol ? '1': '0');
    start_loop();
  }
}

console.log("Hello IoT");
start_loop();
<|endoftext|>