<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,succesfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc) {
		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 = $(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"; }
							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(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,succesfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc );
								return false;
							}
							e.stopPropagation();
						});
					}
					if( $.isFunction(oneditfunc)) { oneditfunc.call($t, rowid); }
				}
			}
		});
	},
	saveRow : function(rowid, succesfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc) {
		return this.each(function(){
		var $t = this, nm, tmp={}, tmp2={}, editable, fr, cv, ind;
		if (!$t.grid ) { return; }
		ind = $($t).jqGrid("getInd",rowid,true);
		if(ind === false) {return;}
		editable = $(ind).attr("editable");
		url = url ? 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') {
					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 (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;
			}
			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 ={}; }
				if(typeof(extraparam) == 'undefined') { extraparam ={}; }
				tmp = $.extend({},tmp,$t.p.inlineData,extraparam);
			}
			if (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(aftersavefunc) ) { aftersavefunc.call($t, rowid,resp); }
			} else {
				$("#lui_"+$t.p.id).show();
				$.ajax($.extend({
					url:url,
					data: $.isFunction($t.p.serializeRowData) ? $t.p.serializeRowData.call($t, tmp) : tmp,
					type: "POST",
					complete: function(res,stat){
						$("#lui_"+$t.p.id).hide();
						if (stat === "success"){
							var ret;
							if( $.isFunction(succesfunc)) { ret = succesfunc.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(aftersavefunc) ) { aftersavefunc.call($t, rowid,res); }
							} else {
								if($.isFunction(errorfunc) ) {
									errorfunc.call($t, rowid, res, stat);
								}
								$($t).jqGrid("restoreRow",rowid, afterrestorefunc);
							}
						}
					},
					error:function(res,stat){
						$("#lui_"+$t.p.id).hide();
						if($.isFunction(errorfunc) ) {
							errorfunc.call($t, rowid, res, stat);
						} else {
							alert("Error Row: "+rowid+" Result: " +res.status+":"+res.statusText+" Status: "+stat);
						}
						$($t).jqGrid("restoreRow",rowid, afterrestorefunc);
					}
				}, $.jgrid.ajaxOptions, $t.p.ajaxRowOptions || {}));
			}
			$(ind).unbind("keydown");
		}
		});
	},
	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]) {
						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>Making saveRow to accept second parameter as object. The function now return true on success false otherviese. To do this we need to set ajax async to true. If some on do not need this this can be overwritten with the ajax options<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,succesfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc) {
		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 = $(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"; }
							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(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,succesfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc );
								return false;
							}
							e.stopPropagation();
						});
					}
					if( $.isFunction(oneditfunc)) { oneditfunc.call($t, rowid); }
				}
			}
		});
	},
	saveRow : function(rowid, succesfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc) {
		// Compatible mode old versions
		var settings = {
			"successfunc" : succesfunc || 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={}, 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') {
					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 (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;
			} else {
				$("#lui_"+$t.p.id).show();
				$.ajax($.extend({
					url:o.url,
					data: $.isFunction($t.p.serializeRowData) ? $t.p.serializeRowData.call($t, tmp) : tmp,
					type: "POST",
					async : false, //?!?
					complete: function(res,stat){
						$("#lui_"+$t.p.id).hide();
						if (stat === "success"){
							var ret;
							if( $.isFunction(o.succesfunc)) { ret = o.succesfunc.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;
							} 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 || {}));
			}
			$(ind).unbind("keydown");
		}
		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]) {
						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>const path = require("path");
const _ = require("lodash");
const moment = require("moment");
const siteConfig = require("./data/SiteConfig");

const postNodes = [];

function addSiblingNodes(createNodeField) {
  postNodes.sort(
    ({ frontmatter: { date: date1 } }, { frontmatter: { date: date2 } }) => {
      const dateA = moment(date1, siteConfig.dateFromFormat);
      const dateB = moment(date2, siteConfig.dateFromFormat);

      if (dateA.isBefore(dateB)) return 1;

      if (dateB.isBefore(dateA)) return -1;

      return 0;
    }
  );
  for (let i = 0; i < postNodes.length; i += 1) {
    const nextID = i + 1 < postNodes.length ? i + 1 : 0;
    const prevID = i - 1 > 0 ? i - 1 : postNodes.length - 1;
    const currNode = postNodes[i];
    const nextNode = postNodes[nextID];
    const prevNode = postNodes[prevID];
    createNodeField({
      node: currNode,
      name: "nextTitle",
      value: nextNode.frontmatter.title
    });
    createNodeField({
      node: currNode,
      name: "nextSlug",
      value: nextNode.fields.slug
    });
    createNodeField({
      node: currNode,
      name: "prevTitle",
      value: prevNode.frontmatter.title
    });
    createNodeField({
      node: currNode,
      name: "prevSlug",
      value: prevNode.fields.slug
    });
  }
}

exports.onCreateNode = ({ node, actions, getNode }) => {
  const { createNodeField } = actions;
  let slug;
  if (node.internal.type === "MarkdownRemark") {
    const fileNode = getNode(node.parent);
    const parsedFilePath = path.parse(fileNode.relativePath);
    if (
      Object.prototype.hasOwnProperty.call(node, "frontmatter") &&
      Object.prototype.hasOwnProperty.call(node.frontmatter, "title")
    ) {
      slug = `/${_.kebabCase(node.frontmatter.title)}`;
    } else if (parsedFilePath.name !== "index" && parsedFilePath.dir !== "") {
      slug = `/${parsedFilePath.dir}/${parsedFilePath.name}/`;
    } else if (parsedFilePath.dir === "") {
      slug = `/${parsedFilePath.name}/`;
    } else {
      slug = `/${parsedFilePath.dir}/`;
    }

    if (Object.prototype.hasOwnProperty.call(node, "frontmatter")) {
      if (Object.prototype.hasOwnProperty.call(node.frontmatter, "slug"))
        slug = `/${_.kebabCase(node.frontmatter.slug)}`;
      if (Object.prototype.hasOwnProperty.call(node.frontmatter, "date")) {
        const date = moment(node.frontmatter.date, siteConfig.dateFromFormat);
        if (!date.isValid)
          console.warn(`WARNING: Invalid date.`, node.frontmatter);

        createNodeField({
          node,
          name: "date",
          value: date.toISOString()
        });
      }
    }
    createNodeField({ node, name: "slug", value: slug });
    postNodes.push(node);
  }
};

exports.setFieldsOnGraphQLNodeType = ({ type, actions }) => {
  const { name } = type;
  const { createNodeField } = actions;
  if (name === "MarkdownRemark") {
    addSiblingNodes(createNodeField);
  }
};

exports.createPages = ({ graphql, actions }) => {
  const { createPage } = actions;

  return new Promise((resolve, reject) => {
    const postPage = path.resolve("src/templates/post.jsx");
    const tagPage = path.resolve("src/templates/tag.jsx");
    const categoryPage = path.resolve("src/templates/category.jsx");
    resolve(
      graphql(
        `
          {
            allMarkdownRemark {
              edges {
                node {
                  frontmatter {
                    tags
                    category
                  }
                  fields {
                    slug
                  }
                }
              }
            }
          }
        `
      ).then(result => {
        if (result.errors) {
          /* eslint no-console: "off" */
          console.log(result.errors);
          reject(result.errors);
        }

        const tagSet = new Set();
        const categorySet = new Set();
        result.data.allMarkdownRemark.edges.forEach(edge => {
          if (edge.node.frontmatter.tags) {
            edge.node.frontmatter.tags.forEach(tag => {
              tagSet.add(tag);
            });
          }

          if (edge.node.frontmatter.category) {
            categorySet.add(edge.node.frontmatter.category);
          }

          createPage({
            path: edge.node.fields.slug,
            component: postPage,
            context: {
              slug: edge.node.fields.slug
            }
          });
        });

        const tagList = Array.from(tagSet);
        tagList.forEach(tag => {
          createPage({
            path: `/tags/${_.kebabCase(tag)}/`,
            component: tagPage,
            context: {
              tag
            }
          });
        });

        const categoryList = Array.from(categorySet);
        categoryList.forEach(category => {
          createPage({
            path: `/categories/${_.kebabCase(category)}/`,
            component: categoryPage,
            context: {
              category
            }
          });
        });
      })
    );
  });
};
<commit_msg>[WORKAROUND] Add babel-polyfill as an import to gatsby-node.<commit_after>const path = require("path");
const _ = require("lodash");
const moment = require("moment");
const siteConfig = require("./data/SiteConfig");
require("babel-polyfill");

const postNodes = [];

function addSiblingNodes(createNodeField) {
  postNodes.sort(
    ({ frontmatter: { date: date1 } }, { frontmatter: { date: date2 } }) => {
      const dateA = moment(date1, siteConfig.dateFromFormat);
      const dateB = moment(date2, siteConfig.dateFromFormat);

      if (dateA.isBefore(dateB)) return 1;

      if (dateB.isBefore(dateA)) return -1;

      return 0;
    }
  );
  for (let i = 0; i < postNodes.length; i += 1) {
    const nextID = i + 1 < postNodes.length ? i + 1 : 0;
    const prevID = i - 1 > 0 ? i - 1 : postNodes.length - 1;
    const currNode = postNodes[i];
    const nextNode = postNodes[nextID];
    const prevNode = postNodes[prevID];
    createNodeField({
      node: currNode,
      name: "nextTitle",
      value: nextNode.frontmatter.title
    });
    createNodeField({
      node: currNode,
      name: "nextSlug",
      value: nextNode.fields.slug
    });
    createNodeField({
      node: currNode,
      name: "prevTitle",
      value: prevNode.frontmatter.title
    });
    createNodeField({
      node: currNode,
      name: "prevSlug",
      value: prevNode.fields.slug
    });
  }
}

exports.onCreateNode = ({ node, actions, getNode }) => {
  const { createNodeField } = actions;
  let slug;
  if (node.internal.type === "MarkdownRemark") {
    const fileNode = getNode(node.parent);
    const parsedFilePath = path.parse(fileNode.relativePath);
    if (
      Object.prototype.hasOwnProperty.call(node, "frontmatter") &&
      Object.prototype.hasOwnProperty.call(node.frontmatter, "title")
    ) {
      slug = `/${_.kebabCase(node.frontmatter.title)}`;
    } else if (parsedFilePath.name !== "index" && parsedFilePath.dir !== "") {
      slug = `/${parsedFilePath.dir}/${parsedFilePath.name}/`;
    } else if (parsedFilePath.dir === "") {
      slug = `/${parsedFilePath.name}/`;
    } else {
      slug = `/${parsedFilePath.dir}/`;
    }

    if (Object.prototype.hasOwnProperty.call(node, "frontmatter")) {
      if (Object.prototype.hasOwnProperty.call(node.frontmatter, "slug"))
        slug = `/${_.kebabCase(node.frontmatter.slug)}`;
      if (Object.prototype.hasOwnProperty.call(node.frontmatter, "date")) {
        const date = moment(node.frontmatter.date, siteConfig.dateFromFormat);
        if (!date.isValid)
          console.warn(`WARNING: Invalid date.`, node.frontmatter);

        createNodeField({
          node,
          name: "date",
          value: date.toISOString()
        });
      }
    }
    createNodeField({ node, name: "slug", value: slug });
    postNodes.push(node);
  }
};

exports.setFieldsOnGraphQLNodeType = ({ type, actions }) => {
  const { name } = type;
  const { createNodeField } = actions;
  if (name === "MarkdownRemark") {
    addSiblingNodes(createNodeField);
  }
};

exports.createPages = ({ graphql, actions }) => {
  const { createPage } = actions;

  return new Promise((resolve, reject) => {
    const postPage = path.resolve("src/templates/post.jsx");
    const tagPage = path.resolve("src/templates/tag.jsx");
    const categoryPage = path.resolve("src/templates/category.jsx");
    resolve(
      graphql(
        `
          {
            allMarkdownRemark {
              edges {
                node {
                  frontmatter {
                    tags
                    category
                  }
                  fields {
                    slug
                  }
                }
              }
            }
          }
        `
      ).then(result => {
        if (result.errors) {
          /* eslint no-console: "off" */
          console.log(result.errors);
          reject(result.errors);
        }

        const tagSet = new Set();
        const categorySet = new Set();
        result.data.allMarkdownRemark.edges.forEach(edge => {
          if (edge.node.frontmatter.tags) {
            edge.node.frontmatter.tags.forEach(tag => {
              tagSet.add(tag);
            });
          }

          if (edge.node.frontmatter.category) {
            categorySet.add(edge.node.frontmatter.category);
          }

          createPage({
            path: edge.node.fields.slug,
            component: postPage,
            context: {
              slug: edge.node.fields.slug
            }
          });
        });

        const tagList = Array.from(tagSet);
        tagList.forEach(tag => {
          createPage({
            path: `/tags/${_.kebabCase(tag)}/`,
            component: tagPage,
            context: {
              tag
            }
          });
        });

        const categoryList = Array.from(categorySet);
        categoryList.forEach(category => {
          createPage({
            path: `/categories/${_.kebabCase(category)}/`,
            component: categoryPage,
            context: {
              category
            }
          });
        });
      })
    );
  });
};
<|endoftext|>


<commit_before>const path = require('path');

exports.createPages = ({ boundActionCreators, graphql }) => {
  const { createPage } = boundActionCreators;

  return graphql(`
    {
      allMarkdownRemark(sort: { order: DESC, fields: [frontmatter___date] }, limit: 1000) {
        edges {
          node {
            excerpt(pruneLength: 400)
            html
            id
            frontmatter {
              templateKey
              path
              date
              title
              image
              heading
              description
              intro {
                blurbs {
                  image
                  text
                }
                heading
                description
              }
              main {
                heading
                description
                image1 {
                  alt
                  image
                }
                image2 {
                  alt
                  image
                }
                image3 {
                  alt
                  image
                }
              }
              testimonials {
                author
                quote
              }
              full_image
              pricing {
                heading
                description
                plans {
                  description
                  items
                  plan
                  price
                }
              }
            }
          }
        }
      }
    }
  `).then((result) => {
    if (result.errors) {
      result.errors.forEach(e => console.error(e.toString()));
      return Promise.reject(result.errors);
    }
    result.data.allMarkdownRemark.edges.forEach(({ node }) => {
      createPage({
        path: node.frontmatter.path,
        component: path.resolve(`src/templates/${String(node.frontmatter.templateKey)}.js`),
        context: {}, // additional data can be passed via context
      });
    });
  });
};
<commit_msg>fix file extension<commit_after>const path = require('path');

exports.createPages = ({ boundActionCreators, graphql }) => {
  const { createPage } = boundActionCreators;

  return graphql(`
    {
      allMarkdownRemark(sort: { order: DESC, fields: [frontmatter___date] }, limit: 1000) {
        edges {
          node {
            excerpt(pruneLength: 400)
            html
            id
            frontmatter {
              templateKey
              path
              date
              title
              image
              heading
              description
              intro {
                blurbs {
                  image
                  text
                }
                heading
                description
              }
              main {
                heading
                description
                image1 {
                  alt
                  image
                }
                image2 {
                  alt
                  image
                }
                image3 {
                  alt
                  image
                }
              }
              testimonials {
                author
                quote
              }
              full_image
              pricing {
                heading
                description
                plans {
                  description
                  items
                  plan
                  price
                }
              }
            }
          }
        }
      }
    }
  `).then((result) => {
    if (result.errors) {
      result.errors.forEach(e => console.error(e.toString()));
      return Promise.reject(result.errors);
    }

    return result.data.allMarkdownRemark.edges.forEach(({ node }) => {
      createPage({
        path: node.frontmatter.path,
        component: path.resolve(`src/templates/${String(node.frontmatter.templateKey)}.jsx`),
        context: {}, // additional data can be passed via context
      });
    });
  });
};
<|endoftext|>


<commit_before>var net          = require('net')
  , Serializer   = require('./serializer')
  , Deserializer = require('./deserializer')
  ;

/**
 * Creates a Client object for making XML-RPC method calls.
 *
 * @constructor
 * @param {Object|String} options - Server options to make the HTTP request to.
 *                                  Either a URI string
 *                                  (e.g. 'http://localhost:9090') or an object
 *                                  with fields:
 *   - {String} host              - (optional)
 *   - {Number} port
 * @param {Boolean} isSecure      - True if using https for making calls,
 *                                  otherwise false.
 * @return {Client}
 */
function Client(port, host, callback) {
	// Invokes with new if called without
	if (false === (this instanceof Client)) {
		return new Client(port, host, callback)
	}

	// Set the options

	if (typeof host === 'function') {
		callback = host;
		host = 'localhost';
	}

	this.host = host || 'localhost';
	this.port = port;

	this.isConnected = false;
	this.isReady = false;
	this.reqhandle = 0x80000000;
	this.callbacks = {};

	this.connect(callback);
}

// Inherit EventEmitter
Client.prototype = Object.create(require('events').EventEmitter.prototype);

/**
 * Connects to the server
 *
 * @param {Function} callback	- function(error) { ... }
 *   - {Object|null} error    - Any errors when making the call, otherwise null.
 */
Client.prototype.connect = function(callback, timeout) {
	if (this.isConnected)
		return;

	var self = this
	  , timeout = timeout || 2000;

	if (typeof callback !== 'function')
		callback = function(){};

	this.socket = net.connect(this.port, this.host);

	this.socket.on('connect', function() {

		self.isConnected = true;

		// Timeout for handshake
		var to = setTimeout(function() {
			var err = new Error('timeout - handshake timed out');
			callback(err);
			self.emit('error', err);

			self.terminate();
		}, timeout);

		self.on('connect', function() {
			clearTimeout(to);
		});
	});

	this.socket.on('error', function(err) {
		self.isConnected = self.isReady = false;

		callback(err);
		self.emit('error', err);
	});

	var doHandshake = function(data) {
		if (this.hsdata == null) {
			this.hsdata = new Buffer(data.length);
			data.copy(this.hsdata);
		} else {
			var tmp = new Buffer(this.hsdata.length + data.length);
			this.hsdata.copy(tmp);
			data.copy(tmp, this.hsdata.length);

			this.hsdata = tmp;
		}

		// Need moar buffer
		if (this.hsdata.length <= 4)
			return;

		var size = this.hsdata.readUInt32LE(0);
		if (size > 64) {
			var err = new Error('transport error - wrong lowlevel protocol header');
			callback(err);
			self.emit('error', err);
			return false;
		}

		// Handshake
		var handshake = this.hsdata.toString('utf8', 4, 4 + size);

		if (handshake == 'GBXRemote 1') {
			// We dont support v1
			self.protocol = 1;
			// TODO: Fix error
			var err = new Error('transport error - wrong lowlevel protocol version');
			callback(err);
			self.emit('error', err);
			return false;
		} else if (handshake == 'GBXRemote 2') {
			self.protocol = 2;
		} else {
			var err = new Error('transport error - wrong lowlevel protocol version');
			callback(err);
			self.emit('error', err);
			return false;
		}

		// Handshake successfull

		self.isReady = true;

		callback();
		self.emit('connect');
	};

	var onData = function(data) {
		if (data == null)
			data = new Buffer(0);

		if (this.buff == null) {
			this.buff = new Buffer(data.length);
			data.copy(this.buff);
		} else {
			var tmp = new Buffer(this.buff.length + data.length);
			this.buff.copy(tmp);
			data.copy(tmp, this.buff.length);
			this.buff = tmp;
		}

		// Need moar buffer to read size
		if (this.buff.length < 4)
			return;

		var targetSize = this.buff.readUInt32LE(0);

		// headerSize = size + reqhandle = 8
		var headerSize = 8;

		// Need moar buffer to read data
		if (this.buff.length < headerSize + targetSize)
			return;

		var response = this.buff.toString('utf8', headerSize, headerSize + targetSize);

		var reqhandle = this.buff.readUInt32LE(4);

		var deserializer = new Deserializer();

		// Reponse
		if (self.callbacks.hasOwnProperty(reqhandle)) {
			deserializer.deserializeMethodResponse(response, function(a, b) {
				self.callbacks[reqhandle].apply(this, arguments);
				delete self.callbacks[reqhandle];
			});
		}
		// Callback
		else {
			deserializer.deserializeMethodCall(response, function(err, method, res) {
				if (err) {
					// This should never happen....
					// There is nothing we can do about this one.
					// Its not a response to a request, and its not a valid callback (MethodCall)
					//console.log(err);
					console.warn('Not a response, nor a callback! (reqhandle: 0x%s)', reqhandle.toString(16));
					return;
				} else {
					// its a callback from the server
					self.emit('callback', method, res);
					self.emit(method, res);
				}
			});
		}

		// Cut away this reponse/callback
		var tmp = new Buffer(this.buff.length - headerSize - targetSize);
		this.buff.copy(tmp, 0, headerSize + targetSize);
		this.buff = tmp;

		// Fake a onData call if more data left
		if (this.buff.length) {
			process.nextTick(function(){
				onData()
			});
		}
	};

	// TODO: Fix the ondata callback, and its functions (kinda messy)
	this.socket.on('data', function(data) {
		// TODO: Do buffering here

		if (!self.isReady)
			doHandshake(data);
		else
			onData(data);
	});
};

Client.prototype.terminate = function() {
	if (this.socket) {
		this.socket.end();
		this.isConnected = false;
	}
}

/**
 * Makes an XML-RPC call to the server specified by the constructor's options.
 *
 * @param {String} method     - The method name.
 * @param {Array} params      - Params to send in the call.
 * @param {Function} callback - function(error, value) { ... }
 *   - {Object|null} error    - Any errors when making the call, otherwise null.
 *   - {mixed} value          - The value returned in the method response.
 */
Client.prototype.methodCall = function(method, params, callback) {

	if (!this.isReady) {
		callback(new Error('Not connected!'));
		return false;
	}

	// An attempt on method overloading
	if (typeof params === 'function') {
		callback = params;
		params = [];
	}
	params = params || [];

	// Returns JSON of the xml
	var xml = Serializer.serializeMethodCall(method, params);

	// Check if request is larger than 1024 Kbytes (limit of maniaplanet)
	if (xml.length > 1024*1024-8) {
		callback(new Error('transport error - request too large (' + xml.length + ')'));
		return false;
	}

	this.reqhandle++;
	this.callbacks[this.reqhandle] = (typeof callback === 'function') ? callback : function() {};

	// $bytes = pack('VVa*', strlen($xml), $this->reqhandle, $xml);
	var len = Buffer.byteLength(xml);
	var buf = new Buffer(8 + len);
	buf.writeInt32LE(len, 0);
	buf.writeUInt32LE(this.reqhandle, 4);
	buf.write(xml, 8);

	this.socket.write(buf, 'utf8');

	return true;
};

module.exports = Client;

<commit_msg>Rename .methodCall() to .query()<commit_after>var net          = require('net')
  , Serializer   = require('./serializer')
  , Deserializer = require('./deserializer')
  ;

/**
 * Creates a Client object for making XML-RPC method calls.
 *
 * @constructor
 * @param {Object|String} options - Server options to make the HTTP request to.
 *                                  Either a URI string
 *                                  (e.g. 'http://localhost:9090') or an object
 *                                  with fields:
 *   - {String} host              - (optional)
 *   - {Number} port
 * @param {Boolean} isSecure      - True if using https for making calls,
 *                                  otherwise false.
 * @return {Client}
 */
function Client(port, host, callback) {
	// Invokes with new if called without
	if (false === (this instanceof Client)) {
		return new Client(port, host, callback)
	}

	// Set the options

	if (typeof host === 'function') {
		callback = host;
		host = 'localhost';
	}

	this.host = host || 'localhost';
	this.port = port;

	this.isConnected = false;
	this.isReady = false;
	this.reqhandle = 0x80000000;
	this.callbacks = {};

	this.connect(callback);
}

// Inherit EventEmitter
Client.prototype = Object.create(require('events').EventEmitter.prototype);

/**
 * Connects to the server
 *
 * @param {Function} callback (optional)	- function(error) { ... }
 *   - {Number} timeout (optional)    - Timeout to connect
 */
Client.prototype.connect = function(callback, timeout) {
	if (this.isConnected)
		return;

	var self = this
	  , timeout = typeof timeout === 'number' ? timeout : typeof callback === 'number' ? callback : 2000; // TODO: test

	// Mess with the callback function so we never have to `if` it later
	// If: no callback given, make an empty function
	// Else: Untested: Only call the callback once.
	//               - E.g. If successfully connected to the server, and later some weird socket error occurs,
	//                 then the callback function will be called twice. Once with success, and once with error.
	//                 Thats what we're trying to prevent... >>> ^^^^^
	if (typeof callback !== 'function') {
		callback = function(){};
	} else {
		// Closure to hide `cb`
		(function() { // TODO: test
			var cb = callback;
			callback = function() {
				// Forward call
				cb.apply(this, arguments);

				// If called again, ignore
				callback = function() {};
			}
		})();
	}

	// Connect to the server
	this.socket = net.connect(this.port, this.host);

	// TODO: Move timeout out of onConnect? (currently timeout is a handshake timeout)
	this.socket.on('connect', function() {

		self.isConnected = true;

		// Timeout for handshake
		var to = setTimeout(function() {
			var err = new Error('timeout - handshake timed out');
			callback(err);
			self.emit('error', err);

			self.terminate();
		}, timeout);

		self.on('connect', function() {
			clearTimeout(to);
		});
	});

	this.socket.on('error', function(err) {
		self.isConnected = self.isReady = false;

		callback(err);
		self.emit('error', err);
	});

	var doHandshake = function(data) {
		if (this.hsdata == null) {
			this.hsdata = new Buffer(data.length);
			data.copy(this.hsdata);
		} else {
			var tmp = new Buffer(this.hsdata.length + data.length);
			this.hsdata.copy(tmp);
			data.copy(tmp, this.hsdata.length);

			this.hsdata = tmp;
		}

		// Need moar buffer
		if (this.hsdata.length <= 4)
			return;

		var size = this.hsdata.readUInt32LE(0);
		if (size > 64) {
			var err = new Error('transport error - wrong lowlevel protocol header');
			callback(err);
			self.emit('error', err);
			return false;
		}

		// Handshake
		var handshake = this.hsdata.toString('utf8', 4, 4 + size);

		if (handshake == 'GBXRemote 1') {
			// We dont support v1
			self.protocol = 1;
			// TODO: Fix error?
			var err = new Error('transport error - wrong lowlevel protocol version');
			callback(err);
			self.emit('error', err);
			return false;
		} else if (handshake == 'GBXRemote 2') {
			self.protocol = 2;
		} else {
			var err = new Error('transport error - wrong lowlevel protocol version');
			callback(err);
			self.emit('error', err);
			return false;
		}

		// Handshake successfull

		self.isReady = true;

		callback();
		self.emit('connect');
	};

	var onData = function(data) {
		if (data == null)
			data = new Buffer(0);

		if (this.buff == null) {
			this.buff = new Buffer(data.length);
			data.copy(this.buff);
		} else {
			// TODO: Use Buffer.concat()? - requires node v0.8!
			var tmp = new Buffer(this.buff.length + data.length);
			this.buff.copy(tmp);
			data.copy(tmp, this.buff.length);
			this.buff = tmp;
		}

		// Need moar buffer to read size
		if (this.buff.length < 4)
			return;

		var targetSize = this.buff.readUInt32LE(0);

		// headerSize = targetSize + reqhandle = 8
		var headerSize = 8;

		// Need moar buffer to read data
		if (this.buff.length < headerSize + targetSize)
			return;

		var response = this.buff.toString('utf8', headerSize, headerSize + targetSize);

		var reqhandle = this.buff.readUInt32LE(4);

		var deserializer = new Deserializer();

		// TODO: Use reqhandle to determine if its a response or callback
		// Reponse
		if (self.callbacks.hasOwnProperty(reqhandle)) {
			deserializer.deserializeMethodResponse(response, function(a, b) {
				self.callbacks[reqhandle].apply(this, arguments);
				delete self.callbacks[reqhandle];
			});
		}
		// Callback
		else {
			deserializer.deserializeMethodCall(response, function(err, method, res) {
				if (err) {
					// This should never happen....
					// There is nothing we can do about this one.
					// Its not a response to a request, and its not a valid callback (MethodCall)
					//console.log(err);
					console.warn('Not a response, nor a callback! (reqhandle: 0x%s)', reqhandle.toString(16));
					return;
				} else {
					// its a callback from the server
					self.emit('callback', method, res);
					self.emit(method, res);
				}
			});
		}

		// Cut away this message...
		var tmp = new Buffer(this.buff.length - headerSize - targetSize);
		this.buff.copy(tmp, 0, headerSize + targetSize);
		this.buff = tmp;

		// ... and fake an onData call if more data left
		if (this.buff.length) {
			process.nextTick(function(){
				onData()
			});
		}
	};

	// TODO: Fix the ondata callback, and its functions (kinda messy)
	this.socket.on('data', function(data) {
		// TODO: Do buffering here

		if (!self.isReady)
			doHandshake(data);
		else
			onData(data);
	});
};

Client.prototype.terminate = function() {
	if (this.socket) {
		this.socket.end();
		this.isConnected = false;
	}
}

/**
 * Makes an XML-RPC call to the server specified by the constructor's options.
 *
 * @param {String} method     - The method name.
 * @param {Array} params      - Params to send in the call.
 * @param {Function} callback - function(error, value) { ... }
 *   - {Object|null} error    - Any errors when making the call, otherwise null.
 *   - {mixed} value          - The value returned in the method response.
 */
Client.prototype.query = function(method, params, callback) {

	if (!this.isReady) {
		// Call again when ready instead of erroring?.. maybe? yes? no?
		/*this.on('connect', function() {
			this.methodCall.apply(this, arguments);
		});*/

		callback(new Error('Not connected!'));
		return false;
	}

	// An attempt on method overloading
	if (typeof params === 'function') {
		callback = params;
		params = [];
	}
	params = params || [];

	// Make sure its an array
	if (typeof params !== 'object')
		params = [params];

	// Returns JSON of the xml
	var xml = Serializer.serializeMethodCall(method, params);

	// Check if request (xml + header) is larger than 1024 Kbytes (limit of maniaplanet)
	if (xml.length + 8 > 1024*1024) {
		callback(new Error('transport error - request too large (' + xml.length + ')'));
		return false;
	}

	this.reqhandle++;
	this.callbacks[this.reqhandle] = (typeof callback === 'function') ? callback : function() {};

	// $bytes = pack('VVa*', strlen($xml), $this->reqhandle, $xml);
	var len = Buffer.byteLength(xml);
	var buf = new Buffer(8 + len);
	buf.writeInt32LE(len, 0);
	buf.writeUInt32LE(this.reqhandle, 4);
	buf.write(xml, 8);

	this.socket.write(buf, 'utf8');

	return true;
};

// DEPRECATED - Function name changed.
Client.prototype.methodCall = Client.prototype.query;

module.exports = Client;

<|endoftext|>


<commit_before>/**
 * Template Plugin : Includes handlebars templates associated with a given file
 *      when said file is imported.
 *
 * Config:
 *    root:
 *      templates:
 *          template: Defines the template that is used to output the template in the module. See consts below.
 *          precompile:
 *            Flag/hash that enable precompilation. Truthy will enable precompilation. A hash with
 *            the key name "template" will override the rendering template. (See the template value above.)
 *          cache: Name of the javascript object that templates will be assigned to.
 *            Defaults to `$AppModule.templates` if an app module exists, otherwise `templates`
 *
 * Mixins:
 *  The template plugin will mixin any special values directly, giving priority to the local version.
 *
 */
var _ = require('underscore'),
    build = require('../build'),
    handlebars = require('handlebars'),
    path = require('path'),
    templateUtil = require('../templateUtil');

handlebars.registerHelper('without-extension', function(str) {
  return str.replace(/\.[a-zA-Z0-9]+$/, '');
});

const DEFAULT_TEMPLATE_TEMPLATE = "/* handsfree : {{{name}}}*/\n{{{templateCache}}}['{{{name}}}'] = Handlebars.compile('{{{data}}}');\n";
const PRECOMPILED_TEMPLATE = "/* handsfree : {{{name}}}*/\n{{{templateCache}}}['{{{name}}}'] = Handlebars.template({{{data}}});\n";

function ensureTemplateTemplates(context, complete) {
  function setTemplateTemplate() {
    if (!context.configCache.templateTemplate) {
      var templateTemplate = (context.config.attributes.templates && context.config.attributes.templates.template) || DEFAULT_TEMPLATE_TEMPLATE;
      context.fileUtil.loadTemplate(templateTemplate, false, function(err, compiled) {
        if (err) {
          complete(err);
        } else {
          context.configCache.templateTemplate = compiled;
          setPrecompiledTemplate();
        }
      });
    } else {
      setPrecompiledTemplate();
    }
  }

  function setPrecompiledTemplate() {
    if (!context.configCache.precompiledTemplate) {
      var precompiledTemplate = (context.config.attributes.templates &&
        context.config.attributes.templates.precompile &&
        context.config.attributes.templates.precompile.template) ||
        PRECOMPILED_TEMPLATE;

      context.fileUtil.loadTemplate(precompiledTemplate, false, function(err, compiled) {
        if (err) {
          complete(err);
        } else {
          context.configCache.precompiledTemplate = compiled;
          complete();
        }
      });
    } else {
      complete();
    }
  }

  setTemplateTemplate(); //will call setPrecompiledTemplate when done
}

function loadTemplate(name, context, callback) {
  ensureTemplateTemplates(context, function(err) {
    if (err) {
      return callback(err);
    }
    context.fileUtil.readFileArtifact(name, 'template', function(err, cache) {
      if (err) {
        callback(new Error('Failed to load template "' + name + '"\n\t' + err));
        return;
      }

      var artifact = cache.artifact || {},
          data = artifact.data || cache.data.toString(),
          attr = context.config.attributes,
          templates = attr.templates || attr.views,
          appModule = context.config.scopedAppModuleName(context.module),
          templateCache = (context.config.attributes.templates && context.config.attributes.templates.cache) ||
            context.config.attributes.templateCache ||
            ((appModule ? appModule + '.' : '') + 'templates'),
          template = context.configCache.templateTemplate;

      // We have the template data, now convert it into the proper format
      name = templateUtil.escapeJsString(name);
      if (!cache.artifact) {
        if (templates.precompile) {
          var options = context.configCache.precompileTemplates;
          if (!options) {
            context.configCache.precompileTemplates = options = _.clone(templates.precompile);
            if (options.knownHelpers) {
              options.knownHelpers = options.knownHelpers.reduce(
                  function(value, helper) {
                    value[helper] = true;
                    return value;
                  }, {});
            }
          }
          try {
            data = handlebars.precompile(data, options);
            template = context.configCache.precompiledTemplate;
          } catch (err) {
            return callback(err);
          }
        } else {
          data = templateUtil.escapeJsString(data);
        }
        context.fileUtil.setFileArtifact(name, 'template', {data: data, template: template});
      } else {
        template = artifact.template;
      }

      callback(
        undefined,
        template({
          name: name,
          templateCache: templateCache,
          data: data
        })
      );
    });
  });
}

module.exports = {
  mode: 'scripts',
  priority: 50,

  loadMixin: function(context, next, complete) {
    var mixinTemplates = context.loadedMixin.templates;
    if (mixinTemplates) {
      var templates = context.mixins.originalConfig.templates || {},
          configTemplates = _.clone(context.config.attributes.templates || templates),
          assigned = false;

      ['template', 'precompile', 'cache'].forEach(function(key) {
        if (mixinTemplates[key] && !templates[key]) {
          configTemplates[key] = mixinTemplates[key];
          assigned = true;
        }
      });

      if (assigned) {
        context.config.attributes.templates = configTemplates;
      }
    }
    next(complete);
  },

  resource: function(context, next, complete) {
    var resource = context.resource;

    if (/\.handlebars$/.test(resource.src) || resource.template) {
      var loadedTemplates = context.fileCache.loadedTemplates;
      if (!loadedTemplates) {
        loadedTemplates = context.fileCache.loadedTemplates = {};
      }

      var templatePath = resource.src;
      if (loadedTemplates[templatePath]) {
        return complete();
      } else {
        loadedTemplates[templatePath] = true;

        var generator = function(buildContext, callback) {
          var output = [],
              inputs = [];
          context.fileUtil.fileList(templatePath, /\.handlebars$/, function(err, files) {
            if (err) {
              callback(err);
              return;
            }

            inputs = files.filter(function(file) { return file.dir; });

            files.forEach(function(file) {
              if (file.dir) {
                return;
              }

              loadTemplate(file.src || file, context, function(err, data) {
                if (err) {
                  return callback(err);
                }

                output.push(data.data || data);
                inputs.push(file.src || file);

                if (inputs.length === files.length) {
                  // Sorting is effectively sorting on the file name due to the name comment in the template
                  callback(undefined, { inputs: inputs, data: output.sort().join(''), noSeparator: true});
                }
              });
            });
          });
        };
        generator.sourceFile = templatePath;
        complete(undefined, generator);
      }
    } else {
      next(complete);
    }
  }
};
<commit_msg>Protect from NPE<commit_after>/**
 * Template Plugin : Includes handlebars templates associated with a given file
 *      when said file is imported.
 *
 * Config:
 *    root:
 *      templates:
 *          template: Defines the template that is used to output the template in the module. See consts below.
 *          precompile:
 *            Flag/hash that enable precompilation. Truthy will enable precompilation. A hash with
 *            the key name "template" will override the rendering template. (See the template value above.)
 *          cache: Name of the javascript object that templates will be assigned to.
 *            Defaults to `$AppModule.templates` if an app module exists, otherwise `templates`
 *
 * Mixins:
 *  The template plugin will mixin any special values directly, giving priority to the local version.
 *
 */
var _ = require('underscore'),
    build = require('../build'),
    handlebars = require('handlebars'),
    path = require('path'),
    templateUtil = require('../templateUtil');

handlebars.registerHelper('without-extension', function(str) {
  return str.replace(/\.[a-zA-Z0-9]+$/, '');
});

const DEFAULT_TEMPLATE_TEMPLATE = "/* handsfree : {{{name}}}*/\n{{{templateCache}}}['{{{name}}}'] = Handlebars.compile('{{{data}}}');\n";
const PRECOMPILED_TEMPLATE = "/* handsfree : {{{name}}}*/\n{{{templateCache}}}['{{{name}}}'] = Handlebars.template({{{data}}});\n";

function ensureTemplateTemplates(context, complete) {
  function setTemplateTemplate() {
    if (!context.configCache.templateTemplate) {
      var templateTemplate = (context.config.attributes.templates && context.config.attributes.templates.template) || DEFAULT_TEMPLATE_TEMPLATE;
      context.fileUtil.loadTemplate(templateTemplate, false, function(err, compiled) {
        if (err) {
          complete(err);
        } else {
          context.configCache.templateTemplate = compiled;
          setPrecompiledTemplate();
        }
      });
    } else {
      setPrecompiledTemplate();
    }
  }

  function setPrecompiledTemplate() {
    if (!context.configCache.precompiledTemplate) {
      var precompiledTemplate = (context.config.attributes.templates &&
        context.config.attributes.templates.precompile &&
        context.config.attributes.templates.precompile.template) ||
        PRECOMPILED_TEMPLATE;

      context.fileUtil.loadTemplate(precompiledTemplate, false, function(err, compiled) {
        if (err) {
          complete(err);
        } else {
          context.configCache.precompiledTemplate = compiled;
          complete();
        }
      });
    } else {
      complete();
    }
  }

  setTemplateTemplate(); //will call setPrecompiledTemplate when done
}

function loadTemplate(name, context, callback) {
  ensureTemplateTemplates(context, function(err) {
    if (err) {
      return callback(err);
    }
    context.fileUtil.readFileArtifact(name, 'template', function(err, cache) {
      if (err) {
        callback(new Error('Failed to load template "' + name + '"\n\t' + err));
        return;
      }

      var artifact = cache.artifact || {},
          data = artifact.data || cache.data.toString(),
          attr = context.config.attributes,
          templates = attr.templates || attr.views || {},
          appModule = context.config.scopedAppModuleName(context.module),
          templateCache = (context.config.attributes.templates && context.config.attributes.templates.cache) ||
            context.config.attributes.templateCache ||
            ((appModule ? appModule + '.' : '') + 'templates'),
          template = context.configCache.templateTemplate;

      // We have the template data, now convert it into the proper format
      name = templateUtil.escapeJsString(name);
      if (!cache.artifact) {
        if (templates.precompile) {
          var options = context.configCache.precompileTemplates;
          if (!options) {
            context.configCache.precompileTemplates = options = _.clone(templates.precompile);
            if (options.knownHelpers) {
              options.knownHelpers = options.knownHelpers.reduce(
                  function(value, helper) {
                    value[helper] = true;
                    return value;
                  }, {});
            }
          }
          try {
            data = handlebars.precompile(data, options);
            template = context.configCache.precompiledTemplate;
          } catch (err) {
            return callback(err);
          }
        } else {
          data = templateUtil.escapeJsString(data);
        }
        context.fileUtil.setFileArtifact(name, 'template', {data: data, template: template});
      } else {
        template = artifact.template;
      }

      callback(
        undefined,
        template({
          name: name,
          templateCache: templateCache,
          data: data
        })
      );
    });
  });
}

module.exports = {
  mode: 'scripts',
  priority: 50,

  loadMixin: function(context, next, complete) {
    var mixinTemplates = context.loadedMixin.templates;
    if (mixinTemplates) {
      var templates = context.mixins.originalConfig.templates || {},
          configTemplates = _.clone(context.config.attributes.templates || templates),
          assigned = false;

      ['template', 'precompile', 'cache'].forEach(function(key) {
        if (mixinTemplates[key] && !templates[key]) {
          configTemplates[key] = mixinTemplates[key];
          assigned = true;
        }
      });

      if (assigned) {
        context.config.attributes.templates = configTemplates;
      }
    }
    next(complete);
  },

  resource: function(context, next, complete) {
    var resource = context.resource;

    if (/\.handlebars$/.test(resource.src) || resource.template) {
      var loadedTemplates = context.fileCache.loadedTemplates;
      if (!loadedTemplates) {
        loadedTemplates = context.fileCache.loadedTemplates = {};
      }

      var templatePath = resource.src;
      if (loadedTemplates[templatePath]) {
        return complete();
      } else {
        loadedTemplates[templatePath] = true;

        var generator = function(buildContext, callback) {
          var output = [],
              inputs = [];
          context.fileUtil.fileList(templatePath, /\.handlebars$/, function(err, files) {
            if (err) {
              callback(err);
              return;
            }

            inputs = files.filter(function(file) { return file.dir; });

            files.forEach(function(file) {
              if (file.dir) {
                return;
              }

              loadTemplate(file.src || file, context, function(err, data) {
                if (err) {
                  return callback(err);
                }

                output.push(data.data || data);
                inputs.push(file.src || file);

                if (inputs.length === files.length) {
                  // Sorting is effectively sorting on the file name due to the name comment in the template
                  callback(undefined, { inputs: inputs, data: output.sort().join(''), noSeparator: true});
                }
              });
            });
          });
        };
        generator.sourceFile = templatePath;
        complete(undefined, generator);
      }
    } else {
      next(complete);
    }
  }
};
<|endoftext|>


<commit_before>import { module, test } from 'qunit';
import { setupApplicationTest } from 'ember-qunit';
import { fillIn, currentURL, triggerEvent, visit, blur } from '@ember/test-helpers';
import a11yAudit from 'ember-a11y-testing/test-support/audit';
import { triggerKeyDown, triggerKeyPress } from 'ember-keyboard';
import axeConfig from '../axe-config';
import { title } from '../helpers/dom';
import setupMirage from '../helpers/setup-mirage';
import { percySnapshot } from 'ember-percy';

module('Acceptance | search', function(hooks) {
  setupApplicationTest(hooks);
  setupMirage(hooks);

  test('/search?q=rust is accessible', async function(assert) {
    assert.expect(0);

    this.server.loadFixtures();

    await visit('/search?q=rust');
    percySnapshot(assert);

    await a11yAudit(axeConfig);
  });

  test('searching for "rust"', async function(assert) {
    this.server.loadFixtures();

    await visit('/');
    await fillIn('[data-test-search-input]', 'rust');
    await triggerEvent('[data-test-search-form]', 'submit');

    assert.equal(currentURL(), '/search?q=rust');
    assert.equal(title(), "Search Results for 'rust' - crates.io: Rust Package Registry");

    assert.dom('[data-test-heading]').hasText("Search Results for 'rust'");
    assert.dom('[data-test-search-nav]').hasText('Displaying 1-8 of 8 total results');
    assert
      .dom('[data-test-search-sort]')
      .hasText('Sort by Relevance Relevance All-Time Downloads Recent Downloads Recent Updates');
    assert.dom('[data-test-crate-row="0"] [data-test-crate-link]').hasText('kinetic-rust');
    assert.dom('[data-test-crate-row="0"] [data-test-version-badge]').hasAttribute('alt', '0.0.16');

    assert
      .dom('[data-test-crate-row="0"] [data-test-description]')
      .hasText('A Kinetic protocol library written in Rust');
    assert.dom('[data-test-crate-row="0"] [data-test-downloads]').hasText('All-Time: 225');
    assert.dom('[data-test-crate-row="0"] [data-test-badge="maintenance"]').exists();
    assert.dom('[data-test-crate-row="0"] [data-test-updated-at]').exists();
  });

  test('searching for "rust" from query', async function(assert) {
    this.server.loadFixtures();

    await visit('/search?q=rust');

    assert.equal(currentURL(), '/search?q=rust');
    assert.equal(title(), "Search Results for 'rust' - crates.io: Rust Package Registry");

    assert.dom('[data-test-search-input]').hasValue('rust');
    assert.dom('[data-test-heading]').hasText("Search Results for 'rust'");
    assert.dom('[data-test-search-nav]').hasText('Displaying 1-8 of 8 total results');
  });

  test('clearing search results', async function(assert) {
    this.server.loadFixtures();

    await visit('/search?q=rust');

    assert.equal(currentURL(), '/search?q=rust');
    assert.dom('[data-test-search-input]').hasValue('rust');

    await visit('/');

    assert.equal(currentURL(), '/');
    assert.dom('[data-test-search-input]').hasValue('');
  });

  test('pressing S key to focus the search bar', async function(assert) {
    this.server.loadFixtures();

    await visit('/');

    await blur('[data-test-search-input]');
    await triggerKeyPress('KeyA');
    assert.dom('[data-test-search-input]').isNotFocused();

    await blur('[data-test-search-input]');
    await triggerKeyPress('KeyS');
    assert.dom('[data-test-search-input]').isFocused();

    await blur('[data-test-search-input]');
    await triggerKeyDown('KeyS');
    assert.dom('[data-test-search-input]').isFocused();

    await blur('[data-test-search-input]');
    await triggerKeyDown('shift+KeyS');
    assert.dom('[data-test-search-input]').isFocused();
  });

  test('check search results are by default displayed by relevance', async function(assert) {
    this.server.loadFixtures();

    await visit('/');
    await fillIn('[data-test-search-input]', 'rust');
    await triggerEvent('[data-test-search-form]', 'submit');

    assert.dom('[data-test-search-sort] [data-test-current-order]').hasText('Relevance');
  });
});
<commit_msg>Auto merge of #2124 - Turbo87:keyboard, r=locks<commit_after>import { module, test } from 'qunit';
import { setupApplicationTest } from 'ember-qunit';
import { fillIn, currentURL, triggerEvent, visit, blur } from '@ember/test-helpers';
import a11yAudit from 'ember-a11y-testing/test-support/audit';
import { keyDown, keyPress } from 'ember-keyboard/test-support/test-helpers';
import axeConfig from '../axe-config';
import { title } from '../helpers/dom';
import setupMirage from '../helpers/setup-mirage';
import { percySnapshot } from 'ember-percy';

module('Acceptance | search', function(hooks) {
  setupApplicationTest(hooks);
  setupMirage(hooks);

  test('/search?q=rust is accessible', async function(assert) {
    assert.expect(0);

    this.server.loadFixtures();

    await visit('/search?q=rust');
    percySnapshot(assert);

    await a11yAudit(axeConfig);
  });

  test('searching for "rust"', async function(assert) {
    this.server.loadFixtures();

    await visit('/');
    await fillIn('[data-test-search-input]', 'rust');
    await triggerEvent('[data-test-search-form]', 'submit');

    assert.equal(currentURL(), '/search?q=rust');
    assert.equal(title(), "Search Results for 'rust' - crates.io: Rust Package Registry");

    assert.dom('[data-test-heading]').hasText("Search Results for 'rust'");
    assert.dom('[data-test-search-nav]').hasText('Displaying 1-8 of 8 total results');
    assert
      .dom('[data-test-search-sort]')
      .hasText('Sort by Relevance Relevance All-Time Downloads Recent Downloads Recent Updates');
    assert.dom('[data-test-crate-row="0"] [data-test-crate-link]').hasText('kinetic-rust');
    assert.dom('[data-test-crate-row="0"] [data-test-version-badge]').hasAttribute('alt', '0.0.16');

    assert
      .dom('[data-test-crate-row="0"] [data-test-description]')
      .hasText('A Kinetic protocol library written in Rust');
    assert.dom('[data-test-crate-row="0"] [data-test-downloads]').hasText('All-Time: 225');
    assert.dom('[data-test-crate-row="0"] [data-test-badge="maintenance"]').exists();
    assert.dom('[data-test-crate-row="0"] [data-test-updated-at]').exists();
  });

  test('searching for "rust" from query', async function(assert) {
    this.server.loadFixtures();

    await visit('/search?q=rust');

    assert.equal(currentURL(), '/search?q=rust');
    assert.equal(title(), "Search Results for 'rust' - crates.io: Rust Package Registry");

    assert.dom('[data-test-search-input]').hasValue('rust');
    assert.dom('[data-test-heading]').hasText("Search Results for 'rust'");
    assert.dom('[data-test-search-nav]').hasText('Displaying 1-8 of 8 total results');
  });

  test('clearing search results', async function(assert) {
    this.server.loadFixtures();

    await visit('/search?q=rust');

    assert.equal(currentURL(), '/search?q=rust');
    assert.dom('[data-test-search-input]').hasValue('rust');

    await visit('/');

    assert.equal(currentURL(), '/');
    assert.dom('[data-test-search-input]').hasValue('');
  });

  test('pressing S key to focus the search bar', async function(assert) {
    this.server.loadFixtures();

    await visit('/');

    await blur('[data-test-search-input]');
    await keyPress('KeyA');
    assert.dom('[data-test-search-input]').isNotFocused();

    await blur('[data-test-search-input]');
    await keyPress('KeyS');
    assert.dom('[data-test-search-input]').isFocused();

    await blur('[data-test-search-input]');
    await keyDown('KeyS');
    assert.dom('[data-test-search-input]').isFocused();

    await blur('[data-test-search-input]');
    await keyDown('shift+KeyS');
    assert.dom('[data-test-search-input]').isFocused();
  });

  test('check search results are by default displayed by relevance', async function(assert) {
    this.server.loadFixtures();

    await visit('/');
    await fillIn('[data-test-search-input]', 'rust');
    await triggerEvent('[data-test-search-form]', 'submit');

    assert.dom('[data-test-search-sort] [data-test-current-order]').hasText('Relevance');
  });
});
<|endoftext|>


<commit_before>/**
* The MIT License (MIT)
*
* Copyright (c) 2016-2017 Mickael Jeanroy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

const path = require('path');
const nodeResolve = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');
const conf = require('./app.conf');

module.exports = (config) => ({
  // base path that will be used to resolve all patterns (eg. files, exclude)
  basePath: conf.root,

  // frameworks to use
  // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
  frameworks: ['jasmine'],

  // Files to load in the browser.
  files: [
    path.join(conf.root, 'node_modules', 'jasmine-ajax', 'lib', 'mock-ajax.js'),
    path.join(conf.root, 'test', 'index.js'),
  ],

  // list of files to exclude
  exclude: [
  ],

  // preprocess matching files before serving them to the browser
  // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
  preprocessors: {
    'test/**/*.js': ['rollup', 'babel'],
  },

  // test results reporter to use
  // possible values: 'dots', 'progress'
  // available reporters: https://npmjs.org/browse/keyword/karma-reporter
  reporters: ['progress'],

  // web server port
  port: 9876,

  // enable / disable colors in the output (reporters and logs)
  colors: true,

  // level of logging
  // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
  logLevel: config.LOG_INFO,

  // enable / disable watching file and executing tests whenever any file changes
  autoWatch: true,

  // start these browsers
  // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
  browsers: ['PhantomJS'],

  // Continuous Integration mode
  // if true, Karma captures browsers, runs the tests and exits
  singleRun: false,

  // Rollup Configuration
  rollupPreprocessor: {
    sourcemap: 'inline',
    format: 'iife',
    name: conf.moduleName,
    plugins: [
      nodeResolve(),
      commonjs(),
    ],
  },
});
<commit_msg>core: update rollup test configuration<commit_after>/**
* The MIT License (MIT)
*
* Copyright (c) 2016-2017 Mickael Jeanroy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

const path = require('path');
const nodeResolve = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');
const conf = require('./app.conf');

module.exports = (config) => ({
  // base path that will be used to resolve all patterns (eg. files, exclude)
  basePath: conf.root,

  // frameworks to use
  // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
  frameworks: ['jasmine'],

  // Files to load in the browser.
  files: [
    path.join(conf.root, 'node_modules', 'jasmine-ajax', 'lib', 'mock-ajax.js'),
    path.join(conf.root, 'test', 'index.js'),
  ],

  // list of files to exclude
  exclude: [
  ],

  // preprocess matching files before serving them to the browser
  // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
  preprocessors: {
    'test/**/*.js': ['rollup', 'babel'],
  },

  // test results reporter to use
  // possible values: 'dots', 'progress'
  // available reporters: https://npmjs.org/browse/keyword/karma-reporter
  reporters: ['progress'],

  // web server port
  port: 9876,

  // enable / disable colors in the output (reporters and logs)
  colors: true,

  // level of logging
  // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
  logLevel: config.LOG_INFO,

  // enable / disable watching file and executing tests whenever any file changes
  autoWatch: true,

  // start these browsers
  // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
  browsers: ['PhantomJS'],

  // Continuous Integration mode
  // if true, Karma captures browsers, runs the tests and exits
  singleRun: false,

  // Rollup Configuration
  rollupPreprocessor: {
    output: {
      sourcemap: 'inline',
      format: 'iife',
      name: conf.moduleName,
    },

    plugins: [
      nodeResolve(),
      commonjs(),
    ],

    legacy: true,
  },
});
<|endoftext|>


<commit_before>;(function($B) {
  var _b_=$B.builtins,
      // Static binding in function closure needed for import hooks
      // to stick to builtin cache even if module is overriden in sys.modules
      $sys = $B.imported['_sys'];

  /**
   * [Import spec] [PEP 302] Brython import machinery
   *
   * @param mod_name        {string}    name of module to load
   * @param origin          {string}    name of module context invoking the import
   * @param _path           {list}      Brython's None for top-level modules
   *                                    Value of parent package's __path__
   * @param module          {module}    [Optional] Existing module, for reload only
   */
  function import_hooks(mod_name, origin, _path, module) {
    // Default argument binding
    if (is_none(module)) {
        module = undefined;
    }

    var _meta_path=_b_.getattr($sys, 'meta_path');

    var spec = undefined;
    for (var i=0, _len_i = _meta_path.length; i < _len_i && is_none(spec); i++) {
        var _finder=_meta_path[i];
        spec=_b_.getattr(_b_.getattr(_finder, 'find_spec'),
                         '__call__')(_finder, mod_name, _path, undefined);
    } //for

    if (is_none(spec)) {
        // No import spec found
        throw _b_.ImportError(mod_name);
    }

    var _loader = _b_.getattr(spec, 'loader', _b_.None),
        _sys_modules = $B.imported,
        _spec_name = _b_.getattr(spec, 'name');
    // Import spec represents a match
    if (is_none(module)) {
        // Create module object
        if (!is_none(_loader)) {
            var create_module = _b_.getattr(_loader, 'create_module', _b_.None);
            if (!is_none(create_module)) {
                module = _b_.getattr(create_module, '__call__')(_loader, spec);
            }
        }
        if (is_none(module)) {
            // FIXME : Initialize __doc__ and __package__
            module = $B.$ModuleDict.$factory(mod_name);
            var mod_desc = _b_.getattr(spec, 'origin');
            if (_b_.getattr(spec, 'has_location')) {
                mod_desc = "from '" + mod_desc + "'";
            }
            else {
                mod_desc = '(' + mod_desc + ')';
            }
            module.toString = module.__repr__ = module.__str__ =
                    function(){return "<module '" + mod_name + "' " + mod_desc + ">"}
        }
    }
    module.__loader__ = _loader;
    // FIXME : Fall back to None ?
    module.__package__ = _b_.getattr(spec, 'parent', _b_.None);
    module.__spec__ = spec;
    var locs = _b_.getattr(spec, 'submodule_search_locations');
    // Brython-specific var
    module.$is_package = !is_none(locs);
    module.__path__ = locs;
    if (_b_.getattr(spec, 'has_location')) {
        module.__file__ = _b_.getattr(spec, 'origin')
    }
    var cached = _b_.getattr(spec, 'cached');
    if (!is_none(cached)) {
        module.__cached__ = cached;
    }

    if (is_none(_loader)) {
        if (!is_none(locs)) {
            $B.modules[_spec_name] = _sys_modules[_spec_name] = module;
        }
        else {
            throw _b_.ImportError(mod_name);
        }
    }
    else {
        var exec_module = _b_.getattr(_loader, 'exec_module', _b_.None);
        if (is_none(exec_module)) {
            // FIXME : Remove !!! Backwards compat in CPython
            module = _b_.getattr(_b_.getattr(_loader, 'load_module'),
                                 '__call__')(_loader, _spec_name);
        }
        else {
            $B.modules[_spec_name] = _sys_modules[_spec_name] = module;
            try { _b_.getattr(exec_module, '__call__')(_loader, module) }
            catch (e) {
                delete $B.modules[_spec_name];
                delete _sys_modules[_spec_name];
                throw e;
           }
        }
    }

    return _sys_modules[_spec_name];
  }

window.import_hooks=import_hooks
})(__BRYTHON__)
<commit_msg>[import] #189 - Module __name__ and registration in py_module_path ...<commit_after>;(function($B) {
  var _b_=$B.builtins,
      // Static binding in function closure needed for import hooks
      // to stick to builtin cache even if module is overriden in sys.modules
      $sys = $B.imported['_sys'];

  /**
   * [Import spec] [PEP 302] Brython import machinery
   *
   * @param mod_name        {string}    name of module to load
   * @param origin          {string}    name of module context invoking the import
   * @param _path           {list}      Brython's None for top-level modules
   *                                    Value of parent package's __path__
   * @param module          {module}    [Optional] Existing module, for reload only
   */
  function import_hooks(mod_name, origin, _path, module) {
    // Default argument binding
    if (is_none(module)) {
        module = undefined;
    }

    var _meta_path=_b_.getattr($sys, 'meta_path');

    var spec = undefined;
    for (var i=0, _len_i = _meta_path.length; i < _len_i && is_none(spec); i++) {
        var _finder=_meta_path[i];
        spec=_b_.getattr(_b_.getattr(_finder, 'find_spec'),
                         '__call__')(_finder, mod_name, _path, undefined);
    } //for

    if (is_none(spec)) {
        // No import spec found
        throw _b_.ImportError(mod_name);
    }

    var _loader = _b_.getattr(spec, 'loader', _b_.None),
        _sys_modules = $B.imported,
        _spec_name = _b_.getattr(spec, 'name');
    // Import spec represents a match
    if (is_none(module)) {
        // Create module object
        if (!is_none(_loader)) {
            var create_module = _b_.getattr(_loader, 'create_module', _b_.None);
            if (!is_none(create_module)) {
                module = _b_.getattr(create_module, '__call__')(_loader, spec);
            }
        }
        if (is_none(module)) {
            // FIXME : Initialize __doc__ and __package__
            module = $B.$ModuleDict.$factory(mod_name);
            var mod_desc = _b_.getattr(spec, 'origin');
            if (_b_.getattr(spec, 'has_location')) {
                mod_desc = "from '" + mod_desc + "'";
            }
            else {
                mod_desc = '(' + mod_desc + ')';
            }
            module.toString = module.__repr__ = module.__str__ =
                    function(){return "<module '" + mod_name + "' " + mod_desc + ">"}
        }
    }
    module.__name__ = _spec_name;
    module.__loader__ = _loader;
    // FIXME : Fall back to None ?
    module.__package__ = _b_.getattr(spec, 'parent', _b_.None);
    module.__spec__ = spec;
    var locs = _b_.getattr(spec, 'submodule_search_locations');
    // Brython-specific var
    module.$is_package = !is_none(locs);
    module.__path__ = locs;
    if (_b_.getattr(spec, 'has_location')) {
        module.__file__ = _b_.getattr(spec, 'origin')
        $B.$py_module_path[module.__name__] = module.__file__;
    }
    var cached = _b_.getattr(spec, 'cached');
    if (!is_none(cached)) {
        module.__cached__ = cached;
    }

    if (is_none(_loader)) {
        if (!is_none(locs)) {
            $B.modules[_spec_name] = _sys_modules[_spec_name] = module;
        }
        else {
            throw _b_.ImportError(mod_name);
        }
    }
    else {
        var exec_module = _b_.getattr(_loader, 'exec_module', _b_.None);
        if (is_none(exec_module)) {
            // FIXME : Remove !!! Backwards compat in CPython
            module = _b_.getattr(_b_.getattr(_loader, 'load_module'),
                                 '__call__')(_loader, _spec_name);
        }
        else {
            $B.modules[_spec_name] = _sys_modules[_spec_name] = module;
            try { _b_.getattr(exec_module, '__call__')(_loader, module) }
            catch (e) {
                delete $B.modules[_spec_name];
                delete _sys_modules[_spec_name];
                throw e;
           }
        }
    }

    return _sys_modules[_spec_name];
  }

window.import_hooks=import_hooks
})(__BRYTHON__)
<|endoftext|>


<commit_before>import React, {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  Animated,
} from 'react-native';

import Icon from 'react-native-vector-icons/Ionicons';

const FacebookTabBar = React.createClass({
  selectedTabIcons: [],
  unselectedTabIcons: [],

  propTypes: {
    goToPage: React.PropTypes.func,
    activeTab: React.PropTypes.number,
    tabs: React.PropTypes.array,
  },

  renderTabOption(name, page) {
    const isTabActive = this.props.activeTab === page;

    return (
      <TouchableOpacity key={name} onPress={() => this.props.goToPage(page)} style={styles.tab}>
        <Icon name={name} size={30} color='#3B5998' style={styles.icon}
              ref={(icon) => { this.selectedTabIcons[page] = icon; }}/>
        <Icon name={name} size={30} color='#ccc' style={styles.icon}
              ref={(icon) => { this.unselectedTabIcons[page] = icon; }}/>
      </TouchableOpacity>
    );
  },

  componentDidMount() {
    this.setAnimationValue({ value: this.props.activeTab, });
    this._listener = this.props.scrollValue.addListener(this.setAnimationValue);
  },

  setAnimationValue({ value, }) {
    this.unselectedTabIcons.forEach((icon, i) => {
      let iconRef = icon;

      if (!icon.setNativeProps && icon !== null) {
        iconRef = icon.refs.icon_image;
      }

      const opacity = (value - i >= 0 && value - i <= 1) ? value - i : 1;
      iconRef.setNativeProps({
        style: {
          opacity,
        },
      });
    });
  },

  render() {
    const containerWidth = this.props.containerWidth;
    const numberOfTabs = this.props.tabs.length;
    const tabUnderlineStyle = {
      position: 'absolute',
      width: containerWidth / numberOfTabs,
      height: 3,
      backgroundColor: '#3b5998',
      bottom: 0,
    };

    const left = this.props.scrollValue.interpolate({
      inputRange: [0, 1, ], outputRange: [0, containerWidth / numberOfTabs, ],
    });

    return <View>
      <View style={[styles.tabs, this.props.style, ]}>
        {this.props.tabs.map((tab, i) => this.renderTabOption(tab, i))}
      </View>
      <Animated.View style={[tabUnderlineStyle, { left, }, ]} />
    </View>;
  },
});

const styles = StyleSheet.create({
  tab: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingBottom: 10,
  },
  tabs: {
    height: 45,
    flexDirection: 'row',
    paddingTop: 5,
    borderWidth: 1,
    borderTopWidth: 0,
    borderLeftWidth: 0,
    borderRightWidth: 0,
    borderBottomColor: 'rgba(0,0,0,0.05)',
  },
  icon: {
    position: 'absolute',
    top: 0,
    left: 20,
  },
});

export default FacebookTabBar;
<commit_msg>remove strange condition<commit_after>import React, {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  Animated,
} from 'react-native';

import Icon from 'react-native-vector-icons/Ionicons';

const FacebookTabBar = React.createClass({
  selectedTabIcons: [],
  unselectedTabIcons: [],

  propTypes: {
    goToPage: React.PropTypes.func,
    activeTab: React.PropTypes.number,
    tabs: React.PropTypes.array,
  },

  renderTabOption(name, page) {
    const isTabActive = this.props.activeTab === page;

    return (
      <TouchableOpacity key={name} onPress={() => this.props.goToPage(page)} style={styles.tab}>
        <Icon name={name} size={30} color='#3B5998' style={styles.icon}
              ref={(icon) => { this.selectedTabIcons[page] = icon; }}/>
        <Icon name={name} size={30} color='#ccc' style={styles.icon}
              ref={(icon) => { this.unselectedTabIcons[page] = icon; }}/>
      </TouchableOpacity>
    );
  },

  componentDidMount() {
    this.setAnimationValue({ value: this.props.activeTab, });
    this._listener = this.props.scrollValue.addListener(this.setAnimationValue);
  },

  setAnimationValue({ value, }) {
    this.unselectedTabIcons.forEach((icon, i) => {
      const opacity = (value - i >= 0 && value - i <= 1) ? value - i : 1;
      icon.setNativeProps({
        style: {
          opacity,
        },
      });
    });
  },

  render() {
    const containerWidth = this.props.containerWidth;
    const numberOfTabs = this.props.tabs.length;
    const tabUnderlineStyle = {
      position: 'absolute',
      width: containerWidth / numberOfTabs,
      height: 3,
      backgroundColor: '#3b5998',
      bottom: 0,
    };

    const left = this.props.scrollValue.interpolate({
      inputRange: [0, 1, ], outputRange: [0, containerWidth / numberOfTabs, ],
    });

    return <View>
      <View style={[styles.tabs, this.props.style, ]}>
        {this.props.tabs.map((tab, i) => this.renderTabOption(tab, i))}
      </View>
      <Animated.View style={[tabUnderlineStyle, { left, }, ]} />
    </View>;
  },
});

const styles = StyleSheet.create({
  tab: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingBottom: 10,
  },
  tabs: {
    height: 45,
    flexDirection: 'row',
    paddingTop: 5,
    borderWidth: 1,
    borderTopWidth: 0,
    borderLeftWidth: 0,
    borderRightWidth: 0,
    borderBottomColor: 'rgba(0,0,0,0.05)',
  },
  icon: {
    position: 'absolute',
    top: 0,
    left: 20,
  },
});

export default FacebookTabBar;
<|endoftext|>


<commit_before>casper.on('remote.message', function (message) {
  // uncommet to print all messages from console.log
  //this.echo(message);
});

function addValue(casper, property, value) {
  casper.sendKeys('input[data-automation-id="http://127.0.0.1:7777/ontology#' + property + '_0"]', value);
}

casper.test.begin("Catalinker grensesnitt (verk)", 6, function (test) {
  casper.start('http://127.0.0.1:7777/work', function () {
    test.assertHttpStatus(200);
    test.assertTitle("Katalogisering", "har riktig tittel");
    casper.waitForResource("/ontology").then(function () {
      test.assertSelectorHasText('h2[data-automation-id="page-heading"]', "Katalogisering av verk");
    });
  });

  casper.waitFor(function check() {
    return this.evaluate(function () {
      return document.querySelectorAll('[data-automation-id="resource_uri"]')[0].value !== "";
    });
  }, function then() {
    var resource_uri = this.evaluate(function () {
      return document.querySelectorAll('[data-automation-id="resource_uri"]')[0].value;
    });
    test.assertEqual(resource_uri, "http://127.0.0.1:7777/work/1");
  });

  casper.then(function () {
    test.assertNotExists('a[href="http://koha.deichman.no/cgi-bin/koha/opac-detail.pl?biblionumber=5"]');
    addValue(this, "biblio", "5");
    test.assertExists('a[href="http://koha.deichman.no/cgi-bin/koha/opac-detail.pl?biblionumber=5"]');
  });

  casper.run(function () {
    test.done();
  });

});

casper.test.begin("Catalinker grensesnitt (utgivelse)", 4, function (test) {
  casper.start('http://127.0.0.1:7777/publication', function () {
    test.assertHttpStatus(200);
    test.assertTitle("Katalogisering", "har riktig tittel");
    casper.waitForResource("/ontology").then(function () {
      test.assertSelectorHasText('h2[data-automation-id="page-heading"]', "Katalogisering av utgivelse");
    });
  });

  casper.waitFor(function check() {
    return this.evaluate(function () {
      return document.querySelectorAll('[data-automation-id="resource_uri"]')[0].value !== "";
    });
  }, function then() {
    var resource_uri = this.evaluate(function () {
      return document.querySelectorAll('[data-automation-id="resource_uri"]')[0].value;
    });
    test.assertEqual(resource_uri, "http://127.0.0.1:7777/publication/1");
  });

  casper.run(function () {
    test.done();
  });

});
<commit_msg>Add check for change in text when text-change expected<commit_after>casper.on('remote.message', function (message) {
  // uncommet to print all messages from console.log
  //this.echo(message);
});

function addValue(casper, property, value) {
  casper.sendKeys('input[data-automation-id="http://127.0.0.1:7777/ontology#' + property + '_0"]', value);
}

casper.test.begin("Catalinker grensesnitt (verk)", 6, function (test) {
  casper.start('http://127.0.0.1:7777/work', function () {
    test.assertHttpStatus(200);
    test.assertTitle("Katalogisering", "har riktig tittel");
    casper.waitForSelectorTextChange('h2[data-automation-id="page-heading"]', function () {
      test.assertSelectorHasText('h2[data-automation-id="page-heading"]', "Katalogisering av verk");
    });
  });

  casper.waitFor(function check() {
    return this.evaluate(function () {
      return document.querySelectorAll('[data-automation-id="resource_uri"]')[0].value !== "";
    });
  }, function then() {
    var resource_uri = this.evaluate(function () {
      return document.querySelectorAll('[data-automation-id="resource_uri"]')[0].value;
    });
    test.assertEqual(resource_uri, "http://127.0.0.1:7777/work/1");
  });

  casper.then(function () {
    test.assertNotExists('a[href="http://koha.deichman.no/cgi-bin/koha/opac-detail.pl?biblionumber=5"]');
    addValue(this, "biblio", "5");
    test.assertExists('a[href="http://koha.deichman.no/cgi-bin/koha/opac-detail.pl?biblionumber=5"]');
  });

  casper.run(function () {
    test.done();
  });

});

casper.test.begin("Catalinker grensesnitt (utgivelse)", 4, function (test) {
  casper.start('http://127.0.0.1:7777/publication', function () {
    test.assertHttpStatus(200);
    test.assertTitle("Katalogisering", "har riktig tittel");
    casper.waitForSelectorTextChange('h2[data-automation-id="page-heading"]', function () {
      test.assertSelectorHasText('h2[data-automation-id="page-heading"]', "Katalogisering av utgivelse");
    });
  });

  casper.waitFor(function check() {
    return this.evaluate(function () {
      return document.querySelectorAll('[data-automation-id="resource_uri"]')[0].value !== "";
    });
  }, function then() {
    var resource_uri = this.evaluate(function () {
      return document.querySelectorAll('[data-automation-id="resource_uri"]')[0].value;
    });
    test.assertEqual(resource_uri, "http://127.0.0.1:7777/publication/1");
  });

  casper.run(function () {
    test.done();
  });

});
<|endoftext|>


<commit_before>var ReleaseReports = function (_http) {
    this._http = _http;
};

/**
 * Create a Release Report
 * @param int repoId github id of repository
 * @param object payload contains estimate to set for the issue, see https://github.com/ZenHubIO/API#create-a-release-report for payload format
 * @callback    complete
 * @memberof    ReleaseReports
 * @method      createReleaseReport
 */
ReleaseReports.prototype.createReleaseReport = function (repoId, payload, callback) {
    this._http._post('repositories/' + repoId + '/reports/releases', {}, payload, function(error, body) {
        callback(error, body);
    });
};

/**
 * Get a Release Report
 * @param int releaseId
 * @callback    complete
 * @memberof    ReleaseReports
 * @method      getReleaseReport
 */
ReleaseReports.prototype.getReleaseReport = function (releaseId, callback) {
    this._http._get('reports/release/' + releaseId, {}, function(error, body) {
        callback(error, body);
    });
};

/**
 * Get a Release Report
 * @param int repoId
 * @callback    complete
 * @memberof    ReleaseReports
 * @method      getReleaseReportsForRepository
 */
ReleaseReports.prototype.getReleaseReportsForRepository = function (repoId, callback) {
    this._http._get('repositories/' + repoId + '/reports/release', {}, function(error, body) {
        callback(error, body);
    });
};

module.exports = ReleaseReports;<commit_msg>issue #20: fix (reports) changed url for getReleaseReportsForRepository (#23)<commit_after>var ReleaseReports = function (_http) {
    this._http = _http;
};

/**
 * Create a Release Report
 * @param int repoId github id of repository
 * @param object payload contains estimate to set for the issue, see https://github.com/ZenHubIO/API#create-a-release-report for payload format
 * @callback    complete
 * @memberof    ReleaseReports
 * @method      createReleaseReport
 */
ReleaseReports.prototype.createReleaseReport = function (repoId, payload, callback) {
    this._http._post('repositories/' + repoId + '/reports/release', {}, payload, function(error, body) {
        callback(error, body);
    });
};

/**
 * Get a Release Report
 * @param int releaseId
 * @callback    complete
 * @memberof    ReleaseReports
 * @method      getReleaseReport
 */
ReleaseReports.prototype.getReleaseReport = function (releaseId, callback) {
    this._http._get('reports/release/' + releaseId, {}, function(error, body) {
        callback(error, body);
    });
};

/**
 * Get a Release Report
 * @param int repoId
 * @callback    complete
 * @memberof    ReleaseReports
 * @method      getReleaseReportsForRepository
 */
ReleaseReports.prototype.getReleaseReportsForRepository = function (repoId, callback) {
    this._http._get('repositories/' + repoId + '/reports/releases', {}, function(error, body) {
        callback(error, body);
    });
};

module.exports = ReleaseReports;<|endoftext|>