<commit_before>// ==UserScript==
// @name           futaba ID+IP popup
// @namespace      https://github.com/himuro-majika
// @description    同じIDやIPのレスをポップアップしちゃう
// @author         himuro_majika
// @include        http://*.2chan.net/*/res/*.htm
// @include        https://*.2chan.net/*/res/*.htm
// @version        1.2.1
// @grant          GM_addStyle
// @run-at      document-idle
// @license        MIT
// @icon         data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAAPUExURYv4i2PQYy2aLUe0R////zorx9oAAAAFdFJOU/////8A+7YOUwAAAElJREFUeNqUj1EOwDAIQoHn/c88bX+2fq0kRsAoUXVAfwzCttWsDWzw0kNVWd2tZ5K9gqmMZB8libt4pSg6YlO3RnTzyxePAAMAzqMDgTX8hYYAAAAASUVORK5CYII=
// ==/UserScript==
(function () {
	var USE_COUNTER = true;	// IDカウンターを表示する
	// USE_COUNTER = false;
	var USE_COUNTER_CURRENT = true;	// IDカウンターに現在の出現数を表示
	// USE_COUNTER_CURRENT = false;

	var Start = new Date().getTime();//count parsing time
	var saba = location.host.replace(".2chan.net","") +
		location.pathname.replace("futaba.htm","");
	var timer_show, timer_hide;
	var isIDIPThread = checkThreadMail();

	setClassAndNameThread();
	setClassAndNameRes();
	if (USE_COUNTER) {
		createCounter();
	}
	setEvent();
	setStyle();
	observeInserted();

	// ID表示・IP表示スレかどうか
	function checkThreadMail() {
		var mail = document.querySelector("html > body > form > font > b > a");
		if (mail && mail.href.match(/^mailto:i[dp]/i)) {
			return true;
		} else {
			return false;
		}
	}
	// ID/IPにclass,nameを設定する
	// 本文
	function setClassAndNameThread() {
		var form = document.querySelector(".thre") ?
			document.querySelector(".thre") :
			document.querySelector("html > body > form:not([enctype])");
		for (var i = 0; i < form.childNodes.length; i++) {
			var text = form.childNodes[i];
			if (text.tagName == "BLOCKQUOTE") {
				break;
			} else if (text.nodeValue) {
				var matchText = text.nodeValue.match(/(.+)(I[DP]:\S{8})(.*)/);
				if (matchText) {
					var date = document.createTextNode(matchText[1]);
					var id = matchText[2];
					var no = document.createTextNode(matchText[3]);
					var ida = document.createElement("a");
					ida.textContent = id;
					ida.setAttribute("class", "GM_fip_name GM_fip_name_thread");
					ida.setAttribute("name", id);
					text.parentNode.insertBefore(date, text);
					text.parentNode.insertBefore(ida, text);
					text.parentNode.insertBefore(no, text);
					text.parentNode.removeChild(text);
					break;
				}
			}
		}
	}
	// レス
	function setClassAndNameRes(node) {
		var atd = document.getElementsByClassName("rtd");
		if (arguments.length) {
			atd = node;
		}
		for (var i = 0; i < atd.length; i++) {
			var td = atd[i];
			for (var j = 0; j < td.childNodes.length; j++) {
				var text = td.childNodes[j];
				if (text.tagName == "BLOCKQUOTE") {
					break;
				} else if (text.nodeValue) {
					var matchText = text.nodeValue.match(/(.+)(I[DP]:\S{8})(.*)/);
					if (matchText) {
						var date = document.createTextNode(matchText[1]);
						var id = matchText[2];
						var no = document.createTextNode(matchText[3]);
						var ida = document.createElement("a");
						ida.textContent = id;
						ida.setAttribute("class", "GM_fip_name");
						ida.setAttribute("name", id);
						text.parentNode.insertBefore(date, text);
						text.parentNode.insertBefore(ida, text);
						text.parentNode.insertBefore(no, text);
						text.parentNode.removeChild(text);
						break;
					}
				}
			}
		}
	}
	// 出現数の表示
	function createCounter() {
		// return;
		var a = document.getElementsByClassName("GM_fip_name");
		var ids = {};
		for (var i = 0; i < a.length; i++) {
			var node = a[i];
			var id = node.name;
			if (USE_COUNTER_CURRENT) {
				if (ids[id]) {
					ids[id]++;
				} else {
					ids[id] = 1;
				}
			}
			// var name = document.querySelectorAll(".GM_fip_name[name='" + id + "']");
			var name = document.getElementsByName(id);
			var span;
			if (node.childNodes[1]) {
			// if (node.nextSibling.tagName == "SPAN") {
				// console.log(node.childNodes.length);
				// node.removeChild(node.childNodes[1]);
				span = node.childNodes[1];
				// span = node.nextSibling;
			} else {
				span = document.createElement("span");
				node.appendChild(span);
				// node.parentNode.insertBefore(span, node.nextSibling);
				span.setAttribute("class", "GM_fip_counter");
			}
			if (USE_COUNTER_CURRENT) {
				span.textContent = "[" + ids[id] + "/" + name.length + "]";
			} else {
				span.textContent = "[" + name.length + "]";
			}
		}
	}
	// イベントを設定
	function setEvent() {
		var aa = document.getElementsByClassName("GM_fip_name");
		for (var i = 0; i < aa.length; i++) {
			var a = aa[i];
			a.addEventListener("mouseover", show, true);
			a.addEventListener("mouseout", hide, true);
		}
	}
	// ポップアップを表示する
	function show(event) {
		clearTimeout(timer_show);
		delpop();
		var name = this.name;
		timer_show = setTimeout(function() {
			var wX;	//ポップアップ表示位置X
			var wY;	//ポップアップ表示位置Y
			var popup = document.createElement("div");
			popup.setAttribute("style", "visibility: hidden;");
			var divThread = document.createElement("div");
			var table = document.createElement("table");
			var tbody = document.createElement("tbody");
			popup.appendChild(divThread);
			popup.appendChild(table);
			table.appendChild(tbody);
			var tda = document.getElementsByName(name);
			for (var i = 0; i < tda.length; i++) {
				if (tda[i].classList.contains("GM_fip_name_thread")) {
					// スレ
					var form = tda[i].parentNode.cloneNode(true);
					for (var j = 0; j < form.childNodes.length; j++) {
						// 広告
						if (form.childNodes[j].className !== "tue") {
							divThread.appendChild(form.childNodes[j].cloneNode(true));
						}
						if (form.childNodes[j].tagName == "BLOCKQUOTE") {
							break;
						}
					}
				} else {
					// レス
					var tr = tda[i].parentNode.parentNode.cloneNode(true);
					tbody.appendChild(tr);
				}
			}
			var restable = [];
			popup.id = "GM_fip_pop";
			popup.setAttribute("class", "GM_fip_pop akahuku_reply_popup");
			popup.setAttribute("__akahuku_reply_popup_index", "");
			// popup.innerHTML = restable.join(" ");
			popup.addEventListener("mouseover",function() {
				clearTimeout(timer_hide);
			}, true);
			popup.addEventListener("mouseout",hide,true);
			var body = document.getElementsByTagName("body");
			body[0].appendChild(popup);
			wX = event.clientX + 10;
			wY = window.scrollY + event.clientY - popup.clientHeight - 10;
			if ( wY < 0 ) {	//ポップアップが上に見きれる時は下に表示
				wY = window.scrollY + event.clientY;
			}
			popup.setAttribute("style",
				"left:" + wX + "px; top:" + wY + "px; visibility: visible;");
		}, 100);
	}
	// ポップアップを消す
	function hide() {
		clearTimeout(timer_show);
		clearTimeout(timer_hide);
		timer_hide = setTimeout(delpop, 500);
	}

	function delpop() {
		clearTimeout(timer_hide);
		var doc_pop = document.getElementsByClassName("GM_fip_pop");
		if ( doc_pop ) {
			for (var i = 0; i < doc_pop.length; i++) {
				doc_pop[i].parentNode.removeChild(doc_pop[i]);
			}
		}
	}
	/*
	 * スタイル設定
	 */
	function setStyle() {
		var css = ".GM_fip_pop {" +
		"  position: absolute;" +
		"  z-index: 350;" +
		"  background-color: #eeaa88 !important;"+
		"}" +
		// ".GM_fip_pop > form {" +
		// "  background-color: #ffe" +
		// "}" +
		".GM_fip_pop > table {" +
		"  clear: both;" +
		"}" +
		".GM_fip_pop > div," +
		".GM_fip_pop > table > tbody > tr > td {" +
		"  color: #800000;" +
		"  font-size: 8pt !important;" +
		"}" +
		".GM_fip_pop > div," +
		".GM_fip_pop > table > tbody > tr > td > blockquote {" +
		"  margin-top: 0px !important;" +
		"  margin-bottom: 0px !important;" +
		"}" +
		".GM_fip_name {" +
		"  color: #F00;" +
		// "  font-family: monospace;" +
		"}" +
		".GM_fip_counter {" +
		"  margin: 0 0.3em;" +
		// "  color: #cc1105;" +
		"}";
		if (typeof GM_addStyle != "undefined") {
			GM_addStyle(css);
		} else if (typeof addStyle != "undefined") {
			addStyle(css);
		} else {
			var heads = document.getElementsByTagName("head");
			if (heads.length > 0) {
				var node = document.createElement("style");
				node.type = "text/css";
				node.appendChild(document.createTextNode(css));
				heads[0].appendChild(node);
			}
		}
	}
	// 続きを読むで追加されるレスを監視
	function observeInserted() {
		observeReloadStatus();
		var target = document.querySelector(".thre") ?
			document.querySelector(".thre") :
			document.querySelector("html > body > form[action]:not([enctype])");
		var timer_reload;
		var observer = new MutationObserver(function(mutations) {
			mutations.forEach(function(mutation) {
				delpop();
				var nodes = mutation.addedNodes;
				for (var i = 0; i < nodes.length; i++) {
					// console.log(nodes[i]);
					if (
						nodes[i].tagName == "TABLE" &&
						nodes[i].id !== "akahuku_bottom_container"
					) {
						if (isIDIPThread) {
							setClassAndNameRes(nodes[i].childNodes[0].childNodes[0].childNodes);
						}
						clearTimeout(timer_reload);
						timer_reload = setTimeout(rel, 50);
					}
				}
			});
		});
		observer.observe(target, { childList: true });
		function rel() {
			if (!isIDIPThread) {
				setClassAndNameThread();
				setClassAndNameRes();
			}
			createCounter();
			setEvent();
		}
	}
	// 赤福のリロード状態を監視
	function observeReloadStatus() {
		var target = document.getElementById("akahuku_reload_status");
		if (!target) {
			return;
		}
		var observer = new MutationObserver(function(mutations) {
			mutations.forEach(function(mutation) {
				delpop();
			});
		});
		observer.observe(target, { childList: true });
	}
	console.log('Parsing '+saba+': '+((new Date()).getTime()-Start) +'msec');//log parsing time
})();
<commit_msg>Bump version to 1.2.2<commit_after>// ==UserScript==
// @name           futaba ID+IP popup
// @namespace      https://github.com/himuro-majika
// @description    同じIDやIPのレスをポップアップしちゃう
// @author         himuro_majika
// @include        http://*.2chan.net/*/res/*.htm
// @include        https://*.2chan.net/*/res/*.htm
// @version        1.2.2
// @grant          GM_addStyle
// @run-at      document-idle
// @license        MIT
// @icon         data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAAPUExURYv4i2PQYy2aLUe0R////zorx9oAAAAFdFJOU/////8A+7YOUwAAAElJREFUeNqUj1EOwDAIQoHn/c88bX+2fq0kRsAoUXVAfwzCttWsDWzw0kNVWd2tZ5K9gqmMZB8libt4pSg6YlO3RnTzyxePAAMAzqMDgTX8hYYAAAAASUVORK5CYII=
// ==/UserScript==
(function () {
	var USE_COUNTER = true;	// IDカウンターを表示する
	// USE_COUNTER = false;
	var USE_COUNTER_CURRENT = true;	// IDカウンターに現在の出現数を表示
	// USE_COUNTER_CURRENT = false;

	var Start = new Date().getTime();//count parsing time
	var saba = location.host.replace(".2chan.net","") +
		location.pathname.replace("futaba.htm","");
	var timer_show, timer_hide;
	var isIDIPThread = checkThreadMail();

	setClassAndNameThread();
	setClassAndNameRes();
	if (USE_COUNTER) {
		createCounter();
	}
	setEvent();
	setStyle();
	observeInserted();

	// ID表示・IP表示スレかどうか
	function checkThreadMail() {
		var mail = document.querySelector("html > body > form > font > b > a");
		if (mail && mail.href.match(/^mailto:i[dp]/i)) {
			return true;
		} else {
			return false;
		}
	}
	// ID/IPにclass,nameを設定する
	// 本文
	function setClassAndNameThread() {
		var form = document.querySelector(".thre") ?
			document.querySelector(".thre") :
			document.querySelector("html > body > form:not([enctype])");
		for (var i = 0; i < form.childNodes.length; i++) {
			var text = form.childNodes[i];
			if (text.tagName == "BLOCKQUOTE") {
				break;
			} else if (text.nodeValue) {
				var matchText = text.nodeValue.match(/(.+)(I[DP]:\S{8})(.*)/);
				if (matchText) {
					var date = document.createTextNode(matchText[1]);
					var id = matchText[2];
					var no = document.createTextNode(matchText[3]);
					var ida = document.createElement("a");
					ida.textContent = id;
					ida.setAttribute("class", "GM_fip_name GM_fip_name_thread");
					ida.setAttribute("name", id);
					text.parentNode.insertBefore(date, text);
					text.parentNode.insertBefore(ida, text);
					text.parentNode.insertBefore(no, text);
					text.parentNode.removeChild(text);
					break;
				}
			}
		}
	}
	// レス
	function setClassAndNameRes(node) {
		var atd = document.getElementsByClassName("rtd");
		if (arguments.length) {
			atd = node;
		}
		for (var i = 0; i < atd.length; i++) {
			var td = atd[i];
			for (var j = 0; j < td.childNodes.length; j++) {
				var text = td.childNodes[j];
				if (text.tagName == "BLOCKQUOTE") {
					break;
				} else if (text.nodeValue) {
					var matchText = text.nodeValue.match(/(.+)(I[DP]:\S{8})(.*)/);
					if (matchText) {
						var date = document.createTextNode(matchText[1]);
						var id = matchText[2];
						var no = document.createTextNode(matchText[3]);
						var ida = document.createElement("a");
						ida.textContent = id;
						ida.setAttribute("class", "GM_fip_name");
						ida.setAttribute("name", id);
						text.parentNode.insertBefore(date, text);
						text.parentNode.insertBefore(ida, text);
						text.parentNode.insertBefore(no, text);
						text.parentNode.removeChild(text);
						break;
					}
				}
			}
		}
	}
	// 出現数の表示
	function createCounter() {
		// return;
		var a = document.getElementsByClassName("GM_fip_name");
		var ids = {};
		for (var i = 0; i < a.length; i++) {
			var node = a[i];
			var id = node.name;
			if (USE_COUNTER_CURRENT) {
				if (ids[id]) {
					ids[id]++;
				} else {
					ids[id] = 1;
				}
			}
			// var name = document.querySelectorAll(".GM_fip_name[name='" + id + "']");
			var name = document.getElementsByName(id);
			var span;
			if (node.childNodes[1]) {
			// if (node.nextSibling.tagName == "SPAN") {
				// console.log(node.childNodes.length);
				// node.removeChild(node.childNodes[1]);
				span = node.childNodes[1];
				// span = node.nextSibling;
			} else {
				span = document.createElement("span");
				node.appendChild(span);
				// node.parentNode.insertBefore(span, node.nextSibling);
				span.setAttribute("class", "GM_fip_counter");
			}
			if (USE_COUNTER_CURRENT) {
				span.textContent = "[" + ids[id] + "/" + name.length + "]";
			} else {
				span.textContent = "[" + name.length + "]";
			}
		}
	}
	// イベントを設定
	function setEvent() {
		var aa = document.getElementsByClassName("GM_fip_name");
		for (var i = 0; i < aa.length; i++) {
			var a = aa[i];
			a.addEventListener("mouseover", show, true);
			a.addEventListener("mouseout", hide, true);
		}
	}
	// ポップアップを表示する
	function show(event) {
		clearTimeout(timer_show);
		delpop();
		var name = this.name;
		timer_show = setTimeout(function() {
			var wX;	//ポップアップ表示位置X
			var wY;	//ポップアップ表示位置Y
			var popup = document.createElement("div");
			popup.setAttribute("style", "visibility: hidden;");
			var divThread = document.createElement("div");
			var table = document.createElement("table");
			var tbody = document.createElement("tbody");
			popup.appendChild(divThread);
			popup.appendChild(table);
			table.appendChild(tbody);
			var tda = document.getElementsByName(name);
			for (var i = 0; i < tda.length; i++) {
				if (tda[i].classList.contains("GM_fip_name_thread")) {
					// スレ
					var form = tda[i].parentNode.cloneNode(true);
					for (var j = 0; j < form.childNodes.length; j++) {
						// 広告
						if (form.childNodes[j].className !== "tue") {
							divThread.appendChild(form.childNodes[j].cloneNode(true));
						}
						if (form.childNodes[j].tagName == "BLOCKQUOTE") {
							break;
						}
					}
				} else {
					// レス
					var tr = tda[i].parentNode.parentNode.cloneNode(true);
					tbody.appendChild(tr);
				}
			}
			var restable = [];
			popup.id = "GM_fip_pop";
			popup.setAttribute("class", "GM_fip_pop akahuku_reply_popup");
			popup.setAttribute("__akahuku_reply_popup_index", "");
			// popup.innerHTML = restable.join(" ");
			popup.addEventListener("mouseover",function() {
				clearTimeout(timer_hide);
			}, true);
			popup.addEventListener("mouseout",hide,true);
			var body = document.getElementsByTagName("body");
			body[0].appendChild(popup);
			wX = event.clientX + 10;
			wY = window.scrollY + event.clientY - popup.clientHeight - 10;
			if ( wY < 0 ) {	//ポップアップが上に見きれる時は下に表示
				wY = window.scrollY + event.clientY;
			}
			popup.setAttribute("style",
				"left:" + wX + "px; top:" + wY + "px; visibility: visible;");
		}, 100);
	}
	// ポップアップを消す
	function hide() {
		clearTimeout(timer_show);
		clearTimeout(timer_hide);
		timer_hide = setTimeout(delpop, 500);
	}

	function delpop() {
		clearTimeout(timer_hide);
		var doc_pop = document.getElementsByClassName("GM_fip_pop");
		if ( doc_pop ) {
			for (var i = 0; i < doc_pop.length; i++) {
				doc_pop[i].parentNode.removeChild(doc_pop[i]);
			}
		}
	}
	/*
	 * スタイル設定
	 */
	function setStyle() {
		var css = ".GM_fip_pop {" +
		"  position: absolute;" +
		"  z-index: 350;" +
		"  background-color: #eeaa88 !important;"+
		"}" +
		// ".GM_fip_pop > form {" +
		// "  background-color: #ffe" +
		// "}" +
		".GM_fip_pop > table {" +
		"  clear: both;" +
		"}" +
		".GM_fip_pop > div," +
		".GM_fip_pop > table > tbody > tr > td {" +
		"  color: #800000;" +
		"  font-size: 8pt !important;" +
		"}" +
		".GM_fip_pop > div," +
		".GM_fip_pop > table > tbody > tr > td > blockquote {" +
		"  margin-top: 0px !important;" +
		"  margin-bottom: 0px !important;" +
		"}" +
		".GM_fip_name {" +
		"  color: #F00;" +
		// "  font-family: monospace;" +
		"}" +
		".GM_fip_counter {" +
		"  margin: 0 0.3em;" +
		// "  color: #cc1105;" +
		"}";
		if (typeof GM_addStyle != "undefined") {
			GM_addStyle(css);
		} else if (typeof addStyle != "undefined") {
			addStyle(css);
		} else {
			var heads = document.getElementsByTagName("head");
			if (heads.length > 0) {
				var node = document.createElement("style");
				node.type = "text/css";
				node.appendChild(document.createTextNode(css));
				heads[0].appendChild(node);
			}
		}
	}
	// 続きを読むで追加されるレスを監視
	function observeInserted() {
		observeReloadStatus();
		var target = document.querySelector(".thre") ?
			document.querySelector(".thre") :
			document.querySelector("html > body > form[action]:not([enctype])");
		var timer_reload;
		var observer = new MutationObserver(function(mutations) {
			mutations.forEach(function(mutation) {
				delpop();
				var nodes = mutation.addedNodes;
				for (var i = 0; i < nodes.length; i++) {
					// console.log(nodes[i]);
					if (
						nodes[i].tagName == "TABLE" &&
						nodes[i].id !== "akahuku_bottom_container"
					) {
						if (isIDIPThread) {
							setClassAndNameRes(nodes[i].childNodes[0].childNodes[0].childNodes);
						}
						clearTimeout(timer_reload);
						timer_reload = setTimeout(rel, 50);
					}
				}
			});
		});
		observer.observe(target, { childList: true });
		function rel() {
			if (!isIDIPThread) {
				setClassAndNameThread();
				setClassAndNameRes();
			}
			createCounter();
			setEvent();
		}
	}
	// 赤福のリロード状態を監視
	function observeReloadStatus() {
		var target = document.getElementById("akahuku_reload_status");
		if (!target) {
			return;
		}
		var observer = new MutationObserver(function(mutations) {
			mutations.forEach(function(mutation) {
				delpop();
			});
		});
		observer.observe(target, { childList: true });
	}
	console.log('Parsing '+saba+': '+((new Date()).getTime()-Start) +'msec');//log parsing time
})();
<|endoftext|>


<commit_before>'use strict';

function get_firstname_parsed_descriptive(fullname) {
  var tokens = fullname.split(' ');
  if (tokens.length <= 1) {
    return fullname;
  } else if (fullname === 'Not Provided') {
    return 'NameNotProvided';
  } else {
    return tokens[0];
  }
}

function get_lastname_parsed_descriptive(fullname) {
    var tokens = fullname.split(' ');
  if (tokens.length <= 1) {
    return "";
  } else if (fullname === 'Not Provided') {
    return 'CreatedViaEasyText';
  } else {
    var firstname_length = tokens[0].length;
    return fullname.substring(firstname_length+1);
  }
}

function get_tapper_name_descriptive(fullname) {
    if (fullname === 'Not Provided') {
        return 'NameNotProvided CreatedViaEasyText';
    } else {
        return fullname;
    }
}

function get_referrer_name_descriptive(referrer_name,tapper_name) {
    if (isEmpty(referrer_name) && tapper_name === 'Not Provided') {
        return 'EasyText SMS';
    } else {
        return referrer_name;
    }
}

function get_tapper_email_clean(email_string) {
  if (!email_string.includes('@') || email_string.includes(' ')) {
    return '';
  } else {
    return email_string;
  }
}

function get_tapper_email_required_unique(email_string,external_id) {
  if (!email_string.includes('@') || email_string.includes(' ') || email_string === '') {
    return external_id + '@cardtapp.com';
  } else {
    return email_string;
  }
}

function get_mobile_phone_formatted(phone) {
  if (!isEmpty(phone) && phone.length === 10 && phone.substring(0,1) != '1') {
    return phone.substring(0,3) + '-' + phone.substring(3,6) + '-' + phone.substring(6,10);
  } else {
     return phone;
  }
}

function isEmpty(obj) {
  if (obj === null) return true;
  if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
  for (var key in obj) if (_.has(obj, key)) return false;
  return true;
}

function isReferral(referrer_name,referrer_status,member_name) {
  switch (referrer_name) {
     case member_name:
     case null:
     case "":
     case "Sent from Dashboard":
     case "Desktop Marketing Page":
        return 0;
  }
  if (referrer_status === "This is me") {
    return 0;
  } else {
    return 1;
  }
}

function get_token_required(lastname) {
  var a = (new Date()/1000*1000).toString();
  var key = a.substr(a.length - 7);

  if (lastname === null || lastname === '') {
    return 'NotProvided_' + key;
  } else {
    return lastname;
  }
}

function augement_tapper_payload(json_input) {
    json_input.tapper_firstname_descriptive = get_firstname_parsed_descriptive(json_input.tapper_name);
    json_input.tapper_lastname_descriptive = get_lastname_parsed_descriptive(json_input.tapper_name);
    json_input.tapper_firstname_required = get_token_required(get_firstname_parsed_descriptive(json_input.tapper_name));
    json_input.tapper_lastname_required = get_token_required(get_lastname_parsed_descriptive(json_input.tapper_name));
    json_input.tapper_name_descriptive = get_tapper_name_descriptive(json_input.tapper_name);
    json_input.referrer_name_descriptive = get_referrer_name_descriptive(json_input.referrer_name,json_input.tapper_name);
    json_input.tapper_email_clean = get_tapper_email_clean(json_input.tapper_email);
    json_input.tapper_email_required_unique = get_tapper_email_required_unique(json_input.tapper_email,json_input.tapper_external_id);
    json_input.tapper_mobile_phone_formatted = get_mobile_phone_formatted(json_input.tapper_phone_number);
    json_input.is_referral = isReferral(json_input.referrer_name,json_input.referrer_status,json_input.member_name);
    return json_input;
}

var Zap = {

  tapp_created_catch_hook: function(bundle) {
    var payload = augement_tapper_payload(bundle.cleaned_request);
    payload.tapp_action_data_string = JSON.stringify(payload.tapp_action_data);
    return payload;
  },

  tapp_created_post_poll: function(bundle) {
    var payload = augement_tapper_payload(JSON.parse(bundle.response.content)[0]);
    if (isEmpty(payload.tapp_action_data)) {
        payload.tapp_action_data = [
          {
            "field": "Sample Purchase Price",
            "value": "300000"
          },
          {
            "field": "Sample Down Payment",
            "value": "20"
          }];
    }
    payload.tapp_action_data_string = JSON.stringify(payload.tapp_action_data);
    return [payload];
  },

  tapper_created_catch_hook: function(bundle) {
    var payload = augement_tapper_payload(bundle.cleaned_request);
    payload.tapp_action_data_string = JSON.stringify(payload.tapp_action_data);
    return payload;
  },

  tapper_created_post_poll: function(bundle) {
    var payload = augement_tapper_payload(JSON.parse(bundle.response.content)[0]);
    return [payload];
  }

};<commit_msg>Checking in current production script for Cardtapp Internal app in Zapier<commit_after>"use strict";

function get_firstname_parsed_descriptive(fullname) {
  var tokens = fullname.split(" ");
  if (tokens.length <= 1) {
    return fullname;
  } else if (fullname === "Not Provided") {
    return "NameNotProvided";
  } else {
    return tokens[0];
  }
}

function get_lastname_parsed_descriptive(fullname) {
  var tokens = fullname.split(" ");
  if (tokens.length <= 1) {
    return "";
  } else if (fullname === "Not Provided") {
    return "CreatedViaEasyText";
  } else {
    var firstname_length = tokens[0].length;
    return fullname.substring(firstname_length + 1);
  }
}

function get_tapper_name_descriptive(fullname) {
  if (fullname === "Not Provided") {
    return "NameNotProvided CreatedViaEasyText";
  } else {
    return fullname;
  }
}

function get_referrer_name_descriptive(referrer_name, tapper_name) {
  if (isEmpty(referrer_name) && tapper_name === "Not Provided") {
    return "EasyText SMS";
  } else {
    return referrer_name;
  }
}

function get_email_clean(email_string) {
  if (
    typeof email_string === "undefined" ||
    email_string === null ||
    !email_string.includes("@") ||
    email_string.includes(" ")
  ) {
    return "";
  } else {
    return email_string;
  }
}

function get_tapper_email_required_unique(email_string, external_id) {
  if (
    typeof email_string === "undefined" ||
    email_string === null ||
    !email_string.includes("@") ||
    email_string.includes(" ") ||
    email_string === ""
  ) {
    return external_id + "@cardtapp.com";
  } else {
    return email_string;
  }
}

function get_mobile_phone_formatted(phone) {
  if (!isEmpty(phone) && phone.length === 10 && phone.substring(0, 1) != "1") {
    return (
      phone.substring(0, 3) +
      "-" +
      phone.substring(3, 6) +
      "-" +
      phone.substring(6, 10)
    );
  } else {
    return phone;
  }
}

function isEmpty(obj) {
  if (obj === null) return true;
  if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
  for (var key in obj) if (_.has(obj, key)) return false;
  return true;
}

function isReferral(referrer_name, referrer_status, member_name) {
  switch (referrer_name) {
    case member_name:
    case null:
    case "":
    case "Sent from Dashboard":
    case "Desktop Marketing Page":
      return 0;
  }
  if (referrer_status === "This is me") {
    return 0;
  } else {
    return 1;
  }
}

function get_token_required(lastname) {
  var a = (new Date() / 1000 * 1000).toString();
  var key = a.substr(a.length - 7);

  if (lastname === null || lastname === "") {
    return "NotProvided_" + key;
  } else {
    return lastname;
  }
}

function get_sample_tapper_data() {
  var sample_tapper_data = {
    tapper_meta_data: {
      tapper_crm_id: "a1b0034478921",
      tapper_crm_type: "salesforce"
    }
  };
  return sample_tapper_data;
}

function augement_tapper_payload(json_input, sample_data) {
  // add sample data if relevant
  for (var key in sample_data) {
    if (
      sample_data.hasOwnProperty(key) &&
      (typeof json_input[key] === "undefined" ||
        (Object.keys(json_input[key]).length === 0 &&
          json_input[key].constructor === Object))
    ) {
      json_input[key] = sample_data[key];
    }
  }

  // add properties
  json_input.tapper_firstname_descriptive = get_firstname_parsed_descriptive(
    json_input.tapper_name
  );
  json_input.tapper_lastname_descriptive = get_lastname_parsed_descriptive(
    json_input.tapper_name
  );
  json_input.tapper_firstname_required = get_token_required(
    get_firstname_parsed_descriptive(json_input.tapper_name)
  );
  json_input.tapper_lastname_required = get_token_required(
    get_lastname_parsed_descriptive(json_input.tapper_name)
  );
  json_input.tapper_name_descriptive = get_tapper_name_descriptive(
    json_input.tapper_name
  );
  json_input.referrer_name_descriptive = get_referrer_name_descriptive(
    json_input.referrer_name,
    json_input.tapper_name
  );
  json_input.tapper_email_clean = get_email_clean(json_input.tapper_email);
  json_input.referrer_email_clean = get_email_clean(json_input.referrer_email);
  json_input.tapper_email_required_unique = get_tapper_email_required_unique(
    json_input.tapper_email,
    json_input.tapper_external_id
  );
  json_input.tapper_mobile_phone_formatted = get_mobile_phone_formatted(
    json_input.tapper_phone_number
  );
  json_input.is_referral = isReferral(
    json_input.referrer_name,
    json_input.referrer_status,
    json_input.member_name
  );

  // stringify JS objects
  json_input.tapper_metadata_data_string = JSON.stringify(
    json_input.tapper_meta_data
  );

  if (!isEmpty(json_input.tapp_action_data)) {
    json_input.tapp_action_data_string = JSON.stringify(
      json_input.tapp_action_data
    );
  }

  return json_input;
}

var Zap = {
  tapp_created_catch_hook: function(bundle) {
    var payload = augement_tapper_payload(bundle.cleaned_request);
    return payload;
  },

  tapp_created_post_poll: function(bundle) {
    var sample_tapper_data = get_sample_tapper_data();
    sample_tapper_data.tapp_action_data = [
      {
        field: "Sample Purchase Price",
        value: "300000"
      },
      {
        field: "Sample Down Payment",
        value: "20"
      }
    ];

    var payload = augement_tapper_payload(
      JSON.parse(bundle.response.content)[0],
      sample_tapper_data
    );

    return [payload];
  },

  tapper_created_catch_hook: function(bundle) {
    var payload = augement_tapper_payload(bundle.cleaned_request);
    return payload;
  },

  tapper_created_post_poll: function(bundle) {
    var sample_tapper_data = get_sample_tapper_data();
    var payload = augement_tapper_payload(
      JSON.parse(bundle.response.content)[0],
      sample_tapper_data
    );
    return [payload];
  },

  tapper_updated_catch_hook: function(bundle) {
    var payload = augement_tapper_payload(bundle.cleaned_request);
    return payload;
  },

  tapper_updated_post_poll: function(bundle) {
    var sample_tapper_data = get_sample_tapper_data();
    var payload = augement_tapper_payload(
      JSON.parse(bundle.response.content)[0],
      sample_tapper_data
    );
    return [payload];
  },

  find_tapper_post_search: function(bundle) {
    var payload = augement_tapper_payload(
      JSON.parse(bundle.response.content)[0]
    );
    return [payload];
  },

  note_created_catch_hook: function(bundle) {
    var payload = augement_tapper_payload(bundle.cleaned_request);
    return payload;
  },

  note_created_post_poll: function(bundle) {
    var sample_tapper_data = get_sample_tapper_data();
    var payload = augement_tapper_payload(
      JSON.parse(bundle.response.content)[0],
      sample_tapper_data
    );
    return [payload];
  },

  call_created_catch_hook: function(bundle) {
    var payload = augement_tapper_payload(bundle.cleaned_request);
    return payload;
  },

  call_created_post_poll: function(bundle) {
    var sample_tapper_data = get_sample_tapper_data();
    var payload = augement_tapper_payload(
      JSON.parse(bundle.response.content)[0],
      sample_tapper_data
    );
    return [payload];
  },

  text_message_created_catch_hook: function(bundle) {
    var payload = augement_tapper_payload(bundle.cleaned_request);
    return payload;
  },

  text_message_created_post_poll: function(bundle) {
    var sample_tapper_data = get_sample_tapper_data();
    var payload = augement_tapper_payload(
      JSON.parse(bundle.response.content)[0],
      sample_tapper_data
    );
    return [payload];
  }
};
<|endoftext|>


<commit_before>var request = require('request');
var moment = require('moment');

function getDrinks() {
  request('http://104.131.47.86:8000/api/drinks', function (error, response, body) {
    var json = JSON.parse(body);
    addDrinkVolumes(json.objects);
  });
}

function checkRecentDrinks(drinks) {
  var currentTime = moment();
  for(var i = 0; i < drinks.length; i++) {
    console.log(currentTime.diff(drinks[i].time, 'minutes'));
  }
}

function addDrinkVolumes(drinks) {
  var volume = 0;
  for(var i = 0; i < drinks.length; i++) {
    volume = volume + drinks[i].volume_ml;
  }
  console.log(volume);
}
<commit_msg>added callbacks to all functions<commit_after>var request = require('request');
var moment = require('moment');

function getDrinks(callback) {
  request('http://104.131.47.86:8000/api/drinks', function (error, response, body) {
    var json = JSON.parse(body);
    callback = (typeof callback === 'function') ? callback : function() {};
    callback(json.objects);
  });
}

function checkRecentDrinks(drinks, callback) {
  var currentTime = moment();
  for(var i = 0; i < drinks.length; i++) {
    console.log(currentTime.diff(drinks[i].time, 'minutes'));
  }
  callback = (typeof callback === 'function') ? callback : function() {};
  callback();
}

function addDrinkVolumes(drinks, callback) {
  var volume = 0;
  for(var i = 0; i < drinks.length; i++) {
    volume = volume + drinks[i].volume_ml;
  }
  console.log(volume);
  callback = (typeof callback === 'function') ? callback : function() {};
  callback(volume);
}

getDrinks(addDrinkVolumes);
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import update from 'react/lib/update';
import {connect} from 'react-redux';
import Switch from '../Switch';
import {addNotification as notify} from '../../../../src/index';

class NotificationCreator extends Component {
  static propTypes = {
    notify: React.PropTypes.func.isRequired
  };

  /**
   * Bind methods and define initial state
   * @param {Object} props
   * @returns {void}
   */
  constructor(props) {
    super(props);
    this._addNotification = this._addNotification.bind(this);
    this._onTitleChange = this._onTitleChange.bind(this);
    this._onMessageChange = this._onMessageChange.bind(this);
    this._onPositionChange = this._onPositionChange.bind(this);
    this._onStatusChange = this._onStatusChange.bind(this);
    this._onDismissAfterChange = this._onDismissAfterChange.bind(this);
    this._onDismissibleChange = this._onDismissibleChange.bind(this);
    this._onAction1NameChange = this._onAction1NameChange.bind(this);
    this._onAction1PrimaryChange = this._onAction1PrimaryChange.bind(this);
    this._onAction2NameChange = this._onAction2NameChange.bind(this);
    this._onAction2PrimaryChange = this._onAction2PrimaryChange.bind(this);
    this._onAllowHTMLChange = this._onAllowHTMLChange.bind(this);
    this.state = {
      notification: {
        title: 'Welcome on demo!',
        message: 'Hey buddy, here you can see what you can do with it.',
        position: 'tr',
        status: 'default',
        dismissAfter: 5000,
        dismissible: true,
        actions: [{
          name: '',
          primary: true
        }, {
          name: '',
          primary: false
        }],
        allowHTML: false
      }
    };
  }

  /**
   * Add a notification
   * @param {Object} event
   * @returns {void}
   * @private
   */
  _addNotification(event) {
    event.preventDefault();
    const {notification, notification: {actions}} = this.state;
    const {notify} = this.props;
    let _actions = [];
    if (actions[0].name) {
      _actions.push(actions[0]);
    }
    if (actions[1].name) {
      _actions.push(actions[1]);
    }
    notify({
      title: notification.title,
      message: notification.message,
      position: notification.position,
      status: notification.status,
      dismissible: notification.dismissible,
      dismissAfter: notification.dismissAfter,
      actions: _actions,
      allowHTML: notification.allowHTML
    });
  }

  /**
   * Update title
   * @param {Object} event
   * @returns {void}
   * @private
   */
  _onTitleChange(event) {
    const newState = update(this.state, {
      notification: {
        title: {$set: event.target.value}
      }
    });
    this.setState(newState);
  }

  /**
   * Update message
   * @param {Object} event
   * @returns {void}
   * @private
   */
  _onMessageChange(event) {
    const newState = update(this.state, {
      notification: {
        message: {$set: event.target.value}
      }
    });
    this.setState(newState);
  }

  /**
   * Update status
   * @param {Object} event
   * @returns {void}
   * @private
   */
  _onStatusChange(event) {
    const newState = update(this.state, {
      notification: {
        status: {$set: event.target.value}
      }
    });
    this.setState(newState);
  }

  /**
   * Update position
   * @param {Object} event
   * @returns {void}
   * @private
   */
  _onPositionChange(event) {
    const newState = update(this.state, {
      notification: {
        position: {$set: event.target.value}
      }
    });
    this.setState(newState);
  }

  /**
   * Update dismiss duration
   * @param {Object} event
   * @returns {void}
   * @private
   */
  _onDismissAfterChange(event) {
    const newState = update(this.state, {
      notification: {
        dismissAfter: {$set: event.target.value}
      }
    });
    this.setState(newState);
  }

  /**
   * Update `dismissisble` variable state
   * @param {Object} event
   * @returns {void}
   * @private
   */
  _onDismissibleChange(event) {
    const newState = update(this.state, {
      notification: {
        dismissible: {$set: event.target.checked}
      }
    });
    this.setState(newState);
  }

  /**
   * Update first action name
   * @param {Object} event
   * @returns {void}
   * @private
   */
  _onAction1NameChange(event) {
    const newState = update(this.state, {
      notification: {
        actions: {
          0: {
            name: {$set: event.target.value}
          }
        }
      }
    });
    this.setState(newState);
  }

  /**
   * Update first action status
   * @param {Object} event
   * @returns {void}
   * @private
   */
  _onAction1PrimaryChange(event) {
    const newState = update(this.state, {
      notification: {
        actions: {
          0: {
            primary: {$set: event.target.checked}
          }
        }
      }
    });
    this.setState(newState);
  }

  /**
   * Update second action name
   * @param {Object} event
   * @returns {void}
   * @private
   */
  _onAction2NameChange(event) {
    const newState = update(this.state, {
      notification: {
        actions: {
          1: {
            name: {$set: event.target.value}
          }
        }
      }
    });
    this.setState(newState);
  }

  /**
   * Update second action status
   * @param {Object} event
   * @returns {void}
   * @private
   */
  _onAction2PrimaryChange(event) {
    const newState = update(this.state, {
      notification: {
        actions: {
          1: {
            primary: {$set: event.target.checked}
          }
        }
      }
    });
    this.setState(newState);
  }

  /**
   * Update `dismissisble` variable state
   * @param {Object} event
   * @returns {void}
   * @private
   */
  _onAllowHTMLChange(event) {
    const newState = update(this.state, {
      notification: {
        allowHTML: {$set: event.target.checked}
      }
    });
    this.setState(newState);
  }

  /**
   * Render form
   * @returns {XML}
   */
  render() {
    const {title, message, dismissAfter, dismissible, allowHTML, actions} = this.state.notification;
    return (

Notification Creator

        <form onSubmit={this._addNotification}>

            Title
            <input className='form-control' type='text' id='title' name='title' value={title}
              onChange={this._onTitleChange}/>

            Message
            <textarea className='form-control' id='message' value={message}
              onChange={this._onMessageChange}>
            </textarea>

                Position
                <select className='form-control' id='position' name='position'
                  onChange={this._onPositionChange}>
                  <option value='tr'>Top right</option>
                  <option value='tl'>Top left</option>
                  <option value='br'>Bottom right</option>
                  <option value='bl'>Bottom left</option>
                </select>

                Status
                <select className='form-control' id='status' name='status'
                  onChange={this._onStatusChange}>
                  <option value='default'>Default</option>
                  <option value='info'>Info</option>
                  <option value='success'>Success</option>
                  <option value='warning'>Warning</option>
                  <option value='error'>Error</option>
                </select>

                Dismiss after (ms)
                <input className='form-control' type='text' name='dismissAfter'
                  onChange={this._onDismissAfterChange} value={dismissAfter}/>

                Dismissible (by clicking on it)
                <Switch name='dismissible' checked={dismissible}
                  onChange={this._onDismissibleChange}/>

                First action
                <input className='form-control' type='text' name='action1-name'
                  value={actions[0].name} onChange={this._onAction1NameChange}/>

                Primary action
                <Switch name='action1-primary' checked={actions[0].primary}
                  onChange={this._onAction1PrimaryChange}/>

                Second action
                <input className='form-control' type='text' name='action2-name'
                  onChange={this._onAction2NameChange} value={actions[1].name}/>

                Primary action
                <Switch name='action2-primary' checked={actions[1].primary}
                  onChange={this._onAction2PrimaryChange}/>

            Allow HTML in message
            <Switch name='allowHTML' checked={allowHTML}
              onChange={this._onAllowHTMLChange}/>

          <button type='submit' className='btn btn-primary btn-block'>
            Notify
          </button>
        </form>

    );
  }
}

export default connect(null, {notify})(NotificationCreator);
<commit_msg>minor update on Demo (NotificationCreator)<commit_after>import React, {Component} from 'react';
import update from 'react/lib/update';
import {connect} from 'react-redux';
import Switch from '../Switch';
import {addNotification as notify} from '../../../../src/index';

class NotificationCreator extends Component {
  static propTypes = {
    notify: React.PropTypes.func.isRequired
  };

  /**
   * Bind methods and define initial state
   * @param {Object} props
   * @returns {void}
   */
  constructor(props) {
    super(props);
    this._addNotification = this._addNotification.bind(this);
    this._onTitleChange = this._onTitleChange.bind(this);
    this._onMessageChange = this._onMessageChange.bind(this);
    this._onPositionChange = this._onPositionChange.bind(this);
    this._onStatusChange = this._onStatusChange.bind(this);
    this._onDismissAfterChange = this._onDismissAfterChange.bind(this);
    this._onDismissibleChange = this._onDismissibleChange.bind(this);
    this._onAction1NameChange = this._onAction1NameChange.bind(this);
    this._onAction1PrimaryChange = this._onAction1PrimaryChange.bind(this);
    this._onAction2NameChange = this._onAction2NameChange.bind(this);
    this._onAction2PrimaryChange = this._onAction2PrimaryChange.bind(this);
    this._onAllowHTMLChange = this._onAllowHTMLChange.bind(this);
    this.state = {
      notification: {
        title: 'Welcome on demo!',
        message: 'Hey buddy, here you can see what you can do with it.',
        position: 'tr',
        status: 'default',
        dismissAfter: 5000,
        dismissible: true,
        actions: [{
          name: '',
          primary: true
        }, {
          name: '',
          primary: false
        }],
        allowHTML: false
      }
    };
  }

  /**
   * Add a notification
   * @param {Object} event
   * @returns {void}
   * @private
   */
  _addNotification(event) {
    event.preventDefault();
    const {notification, notification: {actions}} = this.state;
    const {notify} = this.props;
    let _actions = [];
    if (actions[0].name) {
      _actions.push(actions[0]);
    }
    if (actions[1].name) {
      _actions.push(actions[1]);
    }
    notify({
      title: notification.title,
      message: notification.message,
      position: notification.position,
      status: notification.status,
      dismissible: notification.dismissible,
      dismissAfter: notification.dismissAfter,
      actions: _actions,
      allowHTML: notification.allowHTML
    });
  }

  /**
   * Update title
   * @param {Object} event
   * @returns {void}
   * @private
   */
  _onTitleChange(event) {
    const newState = update(this.state, {
      notification: {
        title: {$set: event.target.value}
      }
    });
    this.setState(newState);
  }

  /**
   * Update message
   * @param {Object} event
   * @returns {void}
   * @private
   */
  _onMessageChange(event) {
    const newState = update(this.state, {
      notification: {
        message: {$set: event.target.value}
      }
    });
    this.setState(newState);
  }

  /**
   * Update status
   * @param {Object} event
   * @returns {void}
   * @private
   */
  _onStatusChange(event) {
    const newState = update(this.state, {
      notification: {
        status: {$set: event.target.value}
      }
    });
    this.setState(newState);
  }

  /**
   * Update position
   * @param {Object} event
   * @returns {void}
   * @private
   */
  _onPositionChange(event) {
    const newState = update(this.state, {
      notification: {
        position: {$set: event.target.value}
      }
    });
    this.setState(newState);
  }

  /**
   * Update dismiss duration
   * @param {Object} event
   * @returns {void}
   * @private
   */
  _onDismissAfterChange(event) {
    const newState = update(this.state, {
      notification: {
        dismissAfter: {$set: event.target.value}
      }
    });
    this.setState(newState);
  }

  /**
   * Update `dismissisble` variable state
   * @param {Object} event
   * @returns {void}
   * @private
   */
  _onDismissibleChange(event) {
    const newState = update(this.state, {
      notification: {
        dismissible: {$set: event.target.checked}
      }
    });
    this.setState(newState);
  }

  /**
   * Update first action name
   * @param {Object} event
   * @returns {void}
   * @private
   */
  _onAction1NameChange(event) {
    const newState = update(this.state, {
      notification: {
        actions: {
          0: {
            name: {$set: event.target.value}
          }
        }
      }
    });
    this.setState(newState);
  }

  /**
   * Update first action status
   * @param {Object} event
   * @returns {void}
   * @private
   */
  _onAction1PrimaryChange(event) {
    const newState = update(this.state, {
      notification: {
        actions: {
          0: {
            primary: {$set: event.target.checked}
          }
        }
      }
    });
    this.setState(newState);
  }

  /**
   * Update second action name
   * @param {Object} event
   * @returns {void}
   * @private
   */
  _onAction2NameChange(event) {
    const newState = update(this.state, {
      notification: {
        actions: {
          1: {
            name: {$set: event.target.value}
          }
        }
      }
    });
    this.setState(newState);
  }

  /**
   * Update second action status
   * @param {Object} event
   * @returns {void}
   * @private
   */
  _onAction2PrimaryChange(event) {
    const newState = update(this.state, {
      notification: {
        actions: {
          1: {
            primary: {$set: event.target.checked}
          }
        }
      }
    });
    this.setState(newState);
  }

  /**
   * Update `dismissisble` variable state
   * @param {Object} event
   * @returns {void}
   * @private
   */
  _onAllowHTMLChange(event) {
    const newState = update(this.state, {
      notification: {
        allowHTML: {$set: event.target.checked}
      }
    });
    this.setState(newState);
  }

  /**
   * Render form
   * @returns {XML}
   */
  render() {
    const {title, message, dismissAfter, dismissible, allowHTML, actions} = this.state.notification;
    return (

Notification Creator

        <form onSubmit={this._addNotification}>

            Title
            <input className='form-control' type='text' id='title' name='title' value={title}
              onChange={this._onTitleChange}/>

            Message
            <textarea className='form-control' id='message' value={message}
              onChange={this._onMessageChange}>
            </textarea>

                Position
                <select className='form-control' id='position' name='position'
                  onChange={this._onPositionChange}>
                  <option value='tr'>Top right</option>
                  <option value='tl'>Top left</option>
                  <option value='br'>Bottom right</option>
                  <option value='bl'>Bottom left</option>
                </select>

                Status
                <select className='form-control' id='status' name='status'
                  onChange={this._onStatusChange}>
                  <option value='default'>Default</option>
                  <option value='info'>Info</option>
                  <option value='success'>Success</option>
                  <option value='warning'>Warning</option>
                  <option value='error'>Error</option>
                </select>

                Dismiss after (ms)
                <input className='form-control' type='text' name='dismissAfter'
                  onChange={this._onDismissAfterChange} value={dismissAfter}/>

                Dismissible (by clicking on it)
                <Switch name='dismissible' checked={dismissible}
                  onChange={this._onDismissibleChange}/>

                First action
                <input className='form-control' type='text' name='action1-name'
                  value={actions[0].name} onChange={this._onAction1NameChange}/>

                Primary action
                <Switch name='action1-primary' checked={actions[0].primary}
                  onChange={this._onAction1PrimaryChange}/>

                Second action
                <input className='form-control' type='text' name='action2-name'
                  onChange={this._onAction2NameChange} value={actions[1].name}/>

                Primary action
                <Switch name='action2-primary' checked={actions[1].primary}
                  onChange={this._onAction2PrimaryChange}/>

            Allow HTML in message
            <Switch name='allowHTML' checked={allowHTML}
              onChange={this._onAllowHTMLChange}/>

          <button type='submit' className='btn btn-primary btn-block'>
            Notify
          </button>
        </form>

    );
  }
}

export default connect(null, {notify})(NotificationCreator);
<|endoftext|>


<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

// MODULES //

var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isObject = require( '@stdlib/assert/is-plain-object' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isArray = require( '@stdlib/assert/is-array' );
var isndarrayLike = require( '@stdlib/assert/is-ndarray-like' );
var shape2strides = require( '@stdlib/ndarray/base/shape2strides' );
var strides2offset = require( '@stdlib/ndarray/base/strides2offset' );
var strides2order = require( '@stdlib/ndarray/base/strides2order' );
var numel = require( '@stdlib/ndarray/base/numel' );
var ctor = require( '@stdlib/ndarray/memoized-ctor' );
var isDataType = require( '@stdlib/ndarray/base/assert/is-data-type' );
var isOrder = require( '@stdlib/ndarray/base/assert/is-order' );
var getType = require( '@stdlib/ndarray/base/buffer-dtype' );
var createBuffer = require( '@stdlib/ndarray/base/buffer' );
var arrayShape = require( '@stdlib/array/shape' );
var flattenArray = require( '@stdlib/utils/flatten-array' );
var isArrayLikeObject = require( './is_array_like_object.js' );
var defaults = require( './defaults.json' );
var castBuffer = require( './cast_buffer.js' );
var copyView = require( './copy_view.js' );

// MAIN //

/**
* Returns a multidimensional array.
*
* @param {(ArrayLikeObject|TypedArrayLike|Buffer|ndarrayLike)} [buffer] - data source
* @param {Options} [options] - function options
* @param {(ArrayLikeObject|TypedArrayLike|Buffer|ndarrayLike)} [options.buffer] - data source
* @param {string} [options.dtype="float64"] - underlying storage data type (if the input data is not of the same type, this option specifies the data type to which to cast the input data)
* @param {string} [options.order="row-major"] - specifies the memory layout of the array as either row-major (C-style) or column-major (Fortran-style)
* @param {NonNegativeIntegerArray} [options.shape] - array shape
* @param {boolean} [options.codegen=true] - boolean indicating whether to use code generation
* @param {string} [options.mode="throw"] - specifies how to handle indices which exceed array dimensions
* @param {StringArray} [options.submode=["throw"]] - specifies how to handle subscripts which exceed array dimensions on a per dimension basis
* @param {boolean} [options.copy=false] - boolean indicating whether to copy source data to a new data buffer
* @param {boolean} [options.flatten=true] - boolean indicating whether to automatically flatten generic array data sources
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {Error} must provide either an array shape, data source, or both
* @throws {RangeError} data source must be compatible with specified meta data
* @returns {ndarray} ndarray instance
*
* @example
* var arr = array( [ [ 1, 2 ], [ 3, 4 ] ] );
* // returns <ndarray>
*
* var v = arr.get( 0, 0 );
* // returns 1
*
* @example
* var opts = {
*     'dtype': 'generic',
*     'flatten': false
* };
*
* var arr = array( [ [ 1, 2 ], [ 3, 4 ] ], opts );
* // returns <ndarray>
*
* var v = arr.get( 0 );
* // returns [ 1, 2 ]
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
*
* var opts = {
*     'shape': [ 2, 2 ]
* };
*
* var arr = array( new Float64Array( [ 1.0, 2.0, 3.0, 4.0 ] ), opts );
* // returns <ndarray>
*
* var v = arr.get( 0, 0 );
* // returns 1.0
*/
function array() {
	var options;
	var strides;
	var buffer;
	var offset;
	var order;
	var dtype;
	var btype;
	var shape;
	var ndims;
	var nopts;
	var opts;
	var len;
	var ord;
	var FLG;

	if ( arguments.length === 1 ) {
		if ( isArrayLikeObject( arguments[ 0 ] ) ) {
			buffer = arguments[ 0 ];
			options = {};
		} else {
			options = arguments[ 0 ];
			if ( !isObject( options ) ) {
				throw new TypeError( 'invalid input argument. Must provide either a valid data source, options argument, or both. Value: `' + options + '`.' );
			}
		}
	} else {
		buffer = arguments[ 0 ];
		if ( !isArrayLikeObject( buffer ) ) { // weak test
			throw new TypeError( 'invalid option. Data source must be an array-like object, typed-array-like, a Buffer, or an ndarray. Value: `' + buffer + '`.' );
		}
		options = arguments[ 1 ];
		if ( !isObject( options ) ) {
			throw new TypeError( 'invalid input argument. Options argument must be an object. Value: `' + options + '`.' );
		}
	}
	if ( buffer && isndarrayLike( buffer ) ) {
		FLG = true;
	}
	nopts = {};
	opts = {};
	if ( hasOwnProp( options, 'dtype' ) ) {
		dtype = options.dtype;
		if ( !isDataType( dtype ) ) {
			throw new TypeError( 'invalid option. `dtype` option must be a recognized data type. Option: `' + dtype + '`.' );
		}
	} else {
		dtype = defaults.dtype;
	}
	if ( hasOwnProp( options, 'order' ) ) {
		order = options.order;
		if ( order === 'any' || order === 'same' ) {
			if ( FLG ) {
				// If the user indicated that "any" order suffices (meaning the user does not care about ndarray order), then we use the default order, unless the input ndarray is either unequivocally "row-major" or "column-major" or configured as such....
				if ( order === 'any' ) {
					// Compute the layout order in order to ascertain whether an ndarray can be considered both "row-major" and "column-major":
					ord = strides2order( buffer.strides );

					// If the ndarray can be considered both "row-major" and "column-major", then use the default order; otherwise, use the ndarray's stated layout order...
					if ( ord === 'both' ) {
						order = defaults.order;
					} else {
						order = buffer.order;
					}
				}
				// Otherwise, use the same order as the provided ndarray...
				else if ( order === 'same' ) {
					order = buffer.order;
				}
			} else {
				order = defaults.order;
			}
		} else if ( !isOrder( order ) ) {
			throw new TypeError( 'invalid option. `order` option must be a recognized order. Option: `' + order + '`.' );
		}
	} else {
		order = defaults.order;
	}
	if ( hasOwnProp( options, 'codegen' ) ) {
		nopts.codegen = options.codegen;
	} else {
		nopts.codegen = defaults.codegen;
	}
	if ( hasOwnProp( options, 'mode' ) ) {
		nopts.mode = options.mode;
	} else {
		nopts.mode = defaults.mode;
	}
	if ( hasOwnProp( options, 'submode' ) ) {
		nopts.submode = options.submode;
	} else {
		nopts.submode = [ nopts.mode ];
	}
	if ( hasOwnProp( options, 'copy' ) ) {
		opts.copy = options.copy;
		if ( !isBoolean( opts.copy ) ) {
			throw new TypeError( 'invalid option. `copy` option must be a boolean. Option: `' + opts.copy + '`.' );
		}
	} else {
		opts.copy = defaults.copy;
	}
	if ( hasOwnProp( options, 'flatten' ) ) {
		opts.flatten = options.flatten;
		if ( !isBoolean( opts.flatten ) ) {
			throw new TypeError( 'invalid option. `flatten` option must be a boolean. Option: `' + opts.flatten + '`.' );
		}
	} else {
		opts.flatten = defaults.flatten;
	}
	if ( buffer === void 0 && hasOwnProp( options, 'buffer' ) ) {
		buffer = options.buffer;
		if ( !isArrayLikeObject( buffer ) ) { // weak test
			throw new TypeError( 'invalid option. `buffer` option must be an array-like object, typed-array-like, a Buffer, or an ndarray. Option: `' + buffer + '`.' );
		}
	}
	// If not provided a shape, infer from a provided data source...
	if ( hasOwnProp( options, 'shape' ) ) {
		shape = options.shape;
		if ( !isArrayLikeObject( shape ) ) { // weak test
			throw new TypeError( 'invalid option. `shape` option must be an array-like object containing nonnegative integers. Option: `' + shape + '`.' );
		}
		ndims = shape.length;
		len = numel( shape );
	} else if ( buffer ) {
		if ( FLG ) {
			shape = buffer.shape;
			ndims = buffer.ndims;
			len = buffer.length;
		} else if ( opts.flatten && isArray( buffer ) ) {
			shape = arrayShape( buffer );
			ndims = shape.length;
			len = numel( shape );
		} else {
			ndims = 1;
			len = buffer.length;
			shape = [ len ]; // assume a 1-dimensional array (vector)
		}
	} else {
		throw new Error( 'invalid input arguments. Must provide either a data source, array shape, or both.' );
	}
	// If provided an ndarray, then we can use the ndarray's strides and index offset...
	if ( FLG ) {
		strides = buffer.strides;
		offset = buffer.offset;
	}
	// For all other data source inputs, we assume we've been provided a contiguous data source for which we can simply compute the strides and index offset pointing to the first indexed element based on the shape...
	else {
		strides = shape2strides( shape, order );
		offset = strides2offset( shape, strides );
	}
	// If not provided a data buffer, create it; otherwise, see if we need to cast a provided data buffer to another data type or perform a copy...
	if ( buffer ) {
		if ( FLG ) {
			btype = buffer.dtype;
			if ( buffer.length !== len ) {
				throw new RangeError( 'invalid input arguments. Array shape is incompatible with provided data source. Number of data source elements does not match array shape.' );
			}
			if ( btype !== dtype || opts.copy ) {
				buffer = copyView( buffer, dtype );

				// Because we copied the view, we need to compute the strides and index offset:
				strides = shape2strides( shape, order );
				offset = strides2offset( shape, strides );
			} else {
				buffer = buffer.data;
			}
		} else {
			btype = getType( buffer );
			if ( btype === 'generic' && opts.flatten ) {
				buffer = flattenArray( buffer );
			}
			if ( buffer.length !== len ) {
				throw new RangeError( 'invalid input arguments. Array shape is incompatible with provided data source. Number of data source elements does not match array shape.' );
			}
			if ( btype !== dtype || opts.copy ) {
				buffer = castBuffer( buffer, len, dtype );
			}
		}
	} else {
		buffer = createBuffer( dtype, len );
	}
	// Return a new ndarray:
	return ctor( dtype, ndims, nopts )( buffer, shape, strides, offset, order );
}

// EXPORTS //

module.exports = array;
<commit_msg>Refactor logic for determining strides and offset<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

// MODULES //

var hasOwnProp = require( '@stdlib/assert/has-own-property' );
var isObject = require( '@stdlib/assert/is-plain-object' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var isArray = require( '@stdlib/assert/is-array' );
var isndarrayLike = require( '@stdlib/assert/is-ndarray-like' );
var shape2strides = require( '@stdlib/ndarray/base/shape2strides' );
var strides2offset = require( '@stdlib/ndarray/base/strides2offset' );
var strides2order = require( '@stdlib/ndarray/base/strides2order' );
var numel = require( '@stdlib/ndarray/base/numel' );
var ctor = require( '@stdlib/ndarray/memoized-ctor' );
var isDataType = require( '@stdlib/ndarray/base/assert/is-data-type' );
var isOrder = require( '@stdlib/ndarray/base/assert/is-order' );
var getType = require( '@stdlib/ndarray/base/buffer-dtype' );
var createBuffer = require( '@stdlib/ndarray/base/buffer' );
var arrayShape = require( '@stdlib/array/shape' );
var flattenArray = require( '@stdlib/utils/flatten-array' );
var isArrayLikeObject = require( './is_array_like_object.js' );
var defaults = require( './defaults.json' );
var castBuffer = require( './cast_buffer.js' );
var copyView = require( './copy_view.js' );

// MAIN //

/**
* Returns a multidimensional array.
*
* @param {(ArrayLikeObject|TypedArrayLike|Buffer|ndarrayLike)} [buffer] - data source
* @param {Options} [options] - function options
* @param {(ArrayLikeObject|TypedArrayLike|Buffer|ndarrayLike)} [options.buffer] - data source
* @param {string} [options.dtype="float64"] - underlying storage data type (if the input data is not of the same type, this option specifies the data type to which to cast the input data)
* @param {string} [options.order="row-major"] - specifies the memory layout of the array as either row-major (C-style) or column-major (Fortran-style)
* @param {NonNegativeIntegerArray} [options.shape] - array shape
* @param {boolean} [options.codegen=true] - boolean indicating whether to use code generation
* @param {string} [options.mode="throw"] - specifies how to handle indices which exceed array dimensions
* @param {StringArray} [options.submode=["throw"]] - specifies how to handle subscripts which exceed array dimensions on a per dimension basis
* @param {boolean} [options.copy=false] - boolean indicating whether to copy source data to a new data buffer
* @param {boolean} [options.flatten=true] - boolean indicating whether to automatically flatten generic array data sources
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {Error} must provide either an array shape, data source, or both
* @throws {RangeError} data source must be compatible with specified meta data
* @returns {ndarray} ndarray instance
*
* @example
* var arr = array( [ [ 1, 2 ], [ 3, 4 ] ] );
* // returns <ndarray>
*
* var v = arr.get( 0, 0 );
* // returns 1
*
* @example
* var opts = {
*     'dtype': 'generic',
*     'flatten': false
* };
*
* var arr = array( [ [ 1, 2 ], [ 3, 4 ] ], opts );
* // returns <ndarray>
*
* var v = arr.get( 0 );
* // returns [ 1, 2 ]
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
*
* var opts = {
*     'shape': [ 2, 2 ]
* };
*
* var arr = array( new Float64Array( [ 1.0, 2.0, 3.0, 4.0 ] ), opts );
* // returns <ndarray>
*
* var v = arr.get( 0, 0 );
* // returns 1.0
*/
function array() {
	var options;
	var strides;
	var buffer;
	var offset;
	var order;
	var dtype;
	var btype;
	var shape;
	var ndims;
	var nopts;
	var opts;
	var len;
	var ord;
	var FLG;

	if ( arguments.length === 1 ) {
		if ( isArrayLikeObject( arguments[ 0 ] ) ) {
			buffer = arguments[ 0 ];
			options = {};
		} else {
			options = arguments[ 0 ];
			if ( !isObject( options ) ) {
				throw new TypeError( 'invalid input argument. Must provide either a valid data source, options argument, or both. Value: `' + options + '`.' );
			}
		}
	} else {
		buffer = arguments[ 0 ];
		if ( !isArrayLikeObject( buffer ) ) { // weak test
			throw new TypeError( 'invalid option. Data source must be an array-like object, typed-array-like, a Buffer, or an ndarray. Value: `' + buffer + '`.' );
		}
		options = arguments[ 1 ];
		if ( !isObject( options ) ) {
			throw new TypeError( 'invalid input argument. Options argument must be an object. Value: `' + options + '`.' );
		}
	}
	if ( buffer && isndarrayLike( buffer ) ) {
		FLG = true;
	}
	nopts = {};
	opts = {};
	if ( hasOwnProp( options, 'dtype' ) ) {
		dtype = options.dtype;
		if ( !isDataType( dtype ) ) {
			throw new TypeError( 'invalid option. `dtype` option must be a recognized data type. Option: `' + dtype + '`.' );
		}
	} else {
		dtype = defaults.dtype;
	}
	if ( hasOwnProp( options, 'order' ) ) {
		order = options.order;
		if ( order === 'any' || order === 'same' ) {
			if ( FLG ) {
				// If the user indicated that "any" order suffices (meaning the user does not care about ndarray order), then we use the default order, unless the input ndarray is either unequivocally "row-major" or "column-major" or configured as such....
				if ( order === 'any' ) {
					// Compute the layout order in order to ascertain whether an ndarray can be considered both "row-major" and "column-major":
					ord = strides2order( buffer.strides );

					// If the ndarray can be considered both "row-major" and "column-major", then use the default order; otherwise, use the ndarray's stated layout order...
					if ( ord === 'both' ) {
						order = defaults.order;
					} else {
						order = buffer.order;
					}
				}
				// Otherwise, use the same order as the provided ndarray...
				else if ( order === 'same' ) {
					order = buffer.order;
				}
			} else {
				order = defaults.order;
			}
		} else if ( !isOrder( order ) ) {
			throw new TypeError( 'invalid option. `order` option must be a recognized order. Option: `' + order + '`.' );
		}
	} else {
		order = defaults.order;
	}
	if ( hasOwnProp( options, 'codegen' ) ) {
		nopts.codegen = options.codegen;
	} else {
		nopts.codegen = defaults.codegen;
	}
	if ( hasOwnProp( options, 'mode' ) ) {
		nopts.mode = options.mode;
	} else {
		nopts.mode = defaults.mode;
	}
	if ( hasOwnProp( options, 'submode' ) ) {
		nopts.submode = options.submode;
	} else {
		nopts.submode = [ nopts.mode ];
	}
	if ( hasOwnProp( options, 'copy' ) ) {
		opts.copy = options.copy;
		if ( !isBoolean( opts.copy ) ) {
			throw new TypeError( 'invalid option. `copy` option must be a boolean. Option: `' + opts.copy + '`.' );
		}
	} else {
		opts.copy = defaults.copy;
	}
	if ( hasOwnProp( options, 'flatten' ) ) {
		opts.flatten = options.flatten;
		if ( !isBoolean( opts.flatten ) ) {
			throw new TypeError( 'invalid option. `flatten` option must be a boolean. Option: `' + opts.flatten + '`.' );
		}
	} else {
		opts.flatten = defaults.flatten;
	}
	if ( buffer === void 0 && hasOwnProp( options, 'buffer' ) ) {
		buffer = options.buffer;
		if ( !isArrayLikeObject( buffer ) ) { // weak test
			throw new TypeError( 'invalid option. `buffer` option must be an array-like object, typed-array-like, a Buffer, or an ndarray. Option: `' + buffer + '`.' );
		}
	}
	// If not provided a shape, infer from a provided data source...
	if ( hasOwnProp( options, 'shape' ) ) {
		shape = options.shape;
		if ( !isArrayLikeObject( shape ) ) { // weak test
			throw new TypeError( 'invalid option. `shape` option must be an array-like object containing nonnegative integers. Option: `' + shape + '`.' );
		}
		ndims = shape.length;
		len = numel( shape );
	} else if ( buffer ) {
		if ( FLG ) {
			shape = buffer.shape;
			ndims = buffer.ndims;
			len = buffer.length;
		} else if ( opts.flatten && isArray( buffer ) ) {
			shape = arrayShape( buffer );
			ndims = shape.length;
			len = numel( shape );
		} else {
			ndims = 1;
			len = buffer.length;
			shape = [ len ]; // assume a 1-dimensional array (vector)
		}
	} else {
		throw new Error( 'invalid input arguments. Must provide either a data source, array shape, or both.' );
	}
	// For non-ndarray data source inputs, we assume we've been provided a contiguous data source for which we can simply compute the strides and index offset pointing to the first indexed element solely based on the shape and specified memory layout order...
	if ( !FLG ) {
		strides = shape2strides( shape, order );
		offset = strides2offset( shape, strides );
	}
	// If not provided a data buffer, create it; otherwise, see if we need to cast a provided data buffer to another data type or perform a copy...
	if ( buffer ) {
		if ( FLG ) {
			btype = buffer.dtype;
			if ( buffer.length !== len ) {
				throw new RangeError( 'invalid input arguments. Array shape is incompatible with provided data source. Number of data source elements does not match array shape.' );
			}
			if ( btype !== dtype || opts.copy ) {
				buffer = copyView( buffer, dtype );
				strides = shape2strides( shape, order ); // computed, as we copied elements based on the ndarray view
				offset = strides2offset( shape, strides );
			} else {
				strides = buffer.strides;
				offset = buffer.offset;
				buffer = buffer.data;
			}
		} else {
			btype = getType( buffer );
			if ( btype === 'generic' && opts.flatten ) {
				buffer = flattenArray( buffer );
			}
			if ( buffer.length !== len ) {
				throw new RangeError( 'invalid input arguments. Array shape is incompatible with provided data source. Number of data source elements does not match array shape.' );
			}
			if ( btype !== dtype || opts.copy ) {
				buffer = castBuffer( buffer, len, dtype );
			}
		}
	} else {
		buffer = createBuffer( dtype, len );
	}
	// Return a new ndarray:
	return ctor( dtype, ndims, nopts )( buffer, shape, strides, offset, order );
}

// EXPORTS //

module.exports = array;
<|endoftext|>


<commit_before>// Transforming journald fields to Sematext Common Schema https://sematext.com/docs/tags/common-schema/
// see https://sematext.com/docs/agents/sematext-agent/processes/metadata/
const Parser = require('../../parser/parser.js')
const logParser = new Parser()

// journald fields for lowercase access
const __REALTIME_TIMESTAMP = '__realtime_timestamp'
const __SOURCE_REALTIME_TIMESTAMP = '_source_realtime_timestamp'
const SYSLOG_IDENTIFIER = 'syslog_identifier'
const _HOSTNAME = '_hostname'
const _SYSTEMD_UNIT = '_systemd_unit'
const PRIORITY = 'priority'
const SYSLOG_FACILITY = 'syslog_facility'
const CONTAINER_TAG = 'container_tag'
const CONTAINER_ID_FULL = 'container_id_full'
const CONTAINER_NAME = 'container_name'

// field mapping for Sematext Common Schema
const processFields = {
  '_pid': 'pid',
  '_uid': 'uid',
  '_gid': 'gid',
  '_cmdline': 'cmd',
  '_systemd_cgroup': 'cgroup'
}
// mapping for syslog priority and facility values
const SEVERITY = [
  'emerg',
  'alert',
  'crit',
  'err',
  'warning',
  'notice',
  'info',
  'debug'
]
const FACILITY = [
  'kern',
  'user',
  'mail',
  'daemon',
  'auth',
  'syslog',
  'lpr',
  'news',
  'uucp',
  'cron',
  'authpriv',
  'ftp',
  'ntp',
  'logaudit',
  'logalert',
  'clock',
  'local0',
  'local1',
  'local2',
  'local3',
  'local4',
  'local5',
  'local6',
  'local7'
]

function applySematextCommonSchema (context, config, eventEmitter, log, callback) {
  try {
    // use Sematext common schema os.host = hostname
    let hostname = log[_HOSTNAME]
    if (hostname) {
      log.os = {host: hostname}
      delete log[_HOSTNAME]
    }
    let timestamp = log[__REALTIME_TIMESTAMP] || log[__SOURCE_REALTIME_TIMESTAMP]
    if (timestamp) {
      var d = new Date(Number(timestamp) / 1000)
      if (d instanceof Date && !isNaN(d)) {
        log['@timestamp'] = d
      }
    }
    let prio = log[PRIORITY]
    let facility = log[log[SYSLOG_FACILITY]]
    // handling syslog priorit and facility values
    if (prio || facility) {
      log.facility = FACILITY[facility] || String(facility)
      log.severity = SEVERITY[prio] || String(prio)
      delete log[PRIORITY]
      delete log[log[SYSLOG_FACILITY]]
    }
    // handling docker journald-drive fields
    if (log[CONTAINER_ID_FULL]) {
      log.container = {
        id: log[CONTAINER_ID_FULL],
        name: log[CONTAINER_NAME],
        tag: log[CONTAINER_TAG]
      }
      delete log[CONTAINER_NAME]
      delete log[CONTAINER_TAG]
      delete log[CONTAINER_ID_FULL]
    }
    if (log['_pid']) {
      log.process = {}
      for (field in processFields) {
        if (log[field]) {
          log.process[processFields[field]] = log[field]
          delete log[field]
        }
      }
    }
    // optional parsing of message field with logagent patterns
    if (config.parseMessageField === true && log.message !== undefined) {
      let source = log[_SYSTEMD_UNIT]
      if (log.container) {
        source = log.container.tag || log.container.name
      }
      logParser.parseLine(log.message, source, function (err, data) {
        if (data && data._type) {
          let type = `${data._type}`
          delete data['@timestamp']
          delete data['logSource']
          delete data._type
          log[type] = {}
          Object.assign(log[type], data)
        }
        callback(null, log)
      }.bind(this))
    } else {
      callback(null, log)
    }
  } catch (ex) {
    callback(ex, log)
  }
}

module.exports = applySematextCommonSchema
<commit_msg>better detection of container logs<commit_after>// Transforming journald fields to Sematext Common Schema https://sematext.com/docs/tags/common-schema/
// see https://sematext.com/docs/agents/sematext-agent/processes/metadata/
const Parser = require('../../parser/parser.js')
const logParser = new Parser()

// journald fields for lowercase access
const __REALTIME_TIMESTAMP = '__realtime_timestamp'
const __SOURCE_REALTIME_TIMESTAMP = '_source_realtime_timestamp'
const SYSLOG_IDENTIFIER = 'syslog_identifier'
const _HOSTNAME = '_hostname'
const _SYSTEMD_UNIT = '_systemd_unit'
const PRIORITY = 'priority'
const SYSLOG_FACILITY = 'syslog_facility'
const CONTAINER_TAG = 'container_tag'
const CONTAINER_ID_FULL = 'container_id_full'
const CONTAINER_ID = 'container_id'
const CONTAINER_NAME = 'container_name'

// field mapping for Sematext Common Schema
const processFields = {
  '_pid': 'pid',
  '_uid': 'uid',
  '_gid': 'gid',
  '_cmdline': 'cmd',
  '_systemd_cgroup': 'cgroup'
}
// mapping for syslog priority and facility values
const SEVERITY = [
  'emerg',
  'alert',
  'crit',
  'err',
  'warning',
  'notice',
  'info',
  'debug'
]
const FACILITY = [
  'kern',
  'user',
  'mail',
  'daemon',
  'auth',
  'syslog',
  'lpr',
  'news',
  'uucp',
  'cron',
  'authpriv',
  'ftp',
  'ntp',
  'logaudit',
  'logalert',
  'clock',
  'local0',
  'local1',
  'local2',
  'local3',
  'local4',
  'local5',
  'local6',
  'local7'
]

function applySematextCommonSchema (context, config, eventEmitter, log, callback) {
  try {
    // use Sematext common schema os.host = hostname
    let hostname = log[_HOSTNAME]
    if (hostname) {
      log.os = {host: hostname}
      delete log[_HOSTNAME]
    }
    let timestamp = log[__REALTIME_TIMESTAMP] || log[__SOURCE_REALTIME_TIMESTAMP]
    if (timestamp) {
      var d = new Date(Number(timestamp) / 1000)
      if (d instanceof Date && !isNaN(d)) {
        log['@timestamp'] = d
      }
    }
    let prio = log[PRIORITY]
    let facility = log[log[SYSLOG_FACILITY]]
    // handling syslog priorit and facility values
    if (prio || facility) {
      log.facility = FACILITY[facility] || String(facility)
      log.severity = SEVERITY[prio] || String(prio)
      delete log[PRIORITY]
      delete log[log[SYSLOG_FACILITY]]
    }
    // handling docker journald-drive fields
    if (log[CONTAINER_ID_FULL] || log[CONTAINER_NAME]) {
      log.container = {
        id: log[CONTAINER_ID_FULL] || log[CONTAINER_ID],
        name: log[CONTAINER_NAME],
        tag: log[CONTAINER_TAG]
      }
      delete log[CONTAINER_NAME]
      delete log[CONTAINER_TAG]
      delete log[CONTAINER_ID_FULL]
    }
    if (log['_pid']) {
      log.process = {}
      for (field in processFields) {
        if (log[field]) {
          log.process[processFields[field]] = log[field]
          delete log[field]
        }
      }
    }
    // optional parsing of message field with logagent patterns
    if (config.parseMessageField === true && log.message !== undefined) {
      let source = log[_SYSTEMD_UNIT]
      if (log.container) {
        source = log.container.tag || log.container.name
      }
      logParser.parseLine(log.message, source, function (err, data) {
        if (data && data._type) {
          let type = `${data._type}`
          delete data['@timestamp']
          delete data['logSource']
          delete data._type
          log[type] = {}
          Object.assign(log[type], data)
        }
        callback(null, log)
      }.bind(this))
    } else {
      callback(null, log)
    }
  } catch (ex) {
    callback(ex, log)
  }
}

module.exports = applySematextCommonSchema
<|endoftext|>


<commit_before>function runPreFlightChecks() {
  const isHttp      = window.location.protocol == 'http:',
        isLocalhost = window.location.hostname == 'localhost'
        isUnsafe    = isHttp && !isLocalhost;

  if (isUnsafe) {
    const isHttpMessage = [
      'This page is running over the web over HTTP.',
      'You should use HTTPS and rotate your access token.',
    ].join(' ');
    alert(isHttpMessage);
  }

  // We will:
  // - Make a request to the github rate limit endpoint
  //   (This will not affect the rate limit)
  // - Check what scopes we have access to
  const queryVars         = new FourthWall.getQueryVariables(),
        token             = queryVars.token,
        extraScopes       = (queryVars.extra_scopes || '').split(',').filter(
          function(scope) { return scope.length > 0 }
        ),
        ghUrl             = 'https://api.github.com/rate_limit';

  if (!token) {
    FourthWall.appendErrorMessage(`You need to <a href="https://github.com/alphagov/fourth-wall#how-to-use">provide a valid token</a> in order to use Fourth Wall.`);
    return;
  }

  fetch(ghUrl, {
    headers: {
      'Authorization': 'token ' + token
    }
  })
    .then(function(response) {
      if (response.ok) {
        return response;
      } else {
        response.text()
          .then(function(text) {
            FourthWall.appendErrorMessage(`Something went wrong during preflight request: ${text}`);
          });
      }
    })
    .then(function (response) { return response.headers; })
    .then(function (headers)  { return headers.get('x-oauth-scopes')  })
    .then(function (scopes)   { return scopes.split(', '); })
    .then(function (scopes)   {
      const allowedScopes = [
        'repo:status', 'repo_deployment', 'read:org'
      ].concat(extraScopes);
      let badScopes = scopes.filter(function(scope) {
        return allowedScopes.indexOf(scope) < 0;
      });

      if (badScopes.length > 0) {
        let badScopesString = badScopes.join(' '),
            badScopesMessage = [
              'You have the following unnecessary scopes: <',
              badScopesString,
              '>; these scopes should be removed.',
              'Clicking accept will reload this page.',
              'Reloading the page will show this message unless the scopes are correct.',
            ].join(' ');

        alert(badScopesMessage);
        window.location.reload(true);
      }
    });
}
<commit_msg>Warn users about retirement on 22 September<commit_after>function runPreFlightChecks() {
  const isHttp      = window.location.protocol == 'http:',
        isLocalhost = window.location.hostname == 'localhost'
        isUnsafe    = isHttp && !isLocalhost;

  if (isUnsafe) {
    const isHttpMessage = [
      'This page is running over the web over HTTP.',
      'You should use HTTPS and rotate your access token.',
    ].join(' ');
    alert(isHttpMessage);
  }

  FourthWall.appendErrorMessage(`This service will be retired on 22nd September. Contact the Digital Marketplace team if you would like to take it over instead.`);

  // We will:
  // - Make a request to the github rate limit endpoint
  //   (This will not affect the rate limit)
  // - Check what scopes we have access to
  const queryVars         = new FourthWall.getQueryVariables(),
        token             = queryVars.token,
        extraScopes       = (queryVars.extra_scopes || '').split(',').filter(
          function(scope) { return scope.length > 0 }
        ),
        ghUrl             = 'https://api.github.com/rate_limit';

  if (!token) {
    FourthWall.appendErrorMessage(`You need to <a href="https://github.com/alphagov/fourth-wall#how-to-use">provide a valid token</a> in order to use Fourth Wall.`);
    return;
  }

  fetch(ghUrl, {
    headers: {
      'Authorization': 'token ' + token
    }
  })
    .then(function(response) {
      if (response.ok) {
        return response;
      } else {
        response.text()
          .then(function(text) {
            FourthWall.appendErrorMessage(`Something went wrong during preflight request: ${text}`);
          });
      }
    })
    .then(function (response) { return response.headers; })
    .then(function (headers)  { return headers.get('x-oauth-scopes')  })
    .then(function (scopes)   { return scopes.split(', '); })
    .then(function (scopes)   {
      const allowedScopes = [
        'repo:status', 'repo_deployment', 'read:org'
      ].concat(extraScopes);
      let badScopes = scopes.filter(function(scope) {
        return allowedScopes.indexOf(scope) < 0;
      });

      if (badScopes.length > 0) {
        let badScopesString = badScopes.join(' '),
            badScopesMessage = [
              'You have the following unnecessary scopes: <',
              badScopesString,
              '>; these scopes should be removed.',
              'Clicking accept will reload this page.',
              'Reloading the page will show this message unless the scopes are correct.',
            ].join(' ');

        alert(badScopesMessage);
        window.location.reload(true);
      }
    });
}
<|endoftext|>


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

function usage() {
    console.log("usage: stemwords.js [-l <language>] -i <input file> -o <output file> [-c <character encoding>] [-p[2]] [-h]\n");
    console.log("The input file consists of a list of words to be stemmed, one per");
    console.log("line. Words should be in lower case.\n");
    console.log("If -c is given, the argument is the character encoding of the input");
    console.log("and output files.  If it is omitted, the UTF-8 encoding is used.\n");
    console.log("If -p is given the output file consists of each word of the input");
    console.log("file followed by \"->\" followed by its stemmed equivalent.");
    console.log("If -p2 is given the output file is a two column layout containing");
    console.log("the input words in the first column and the stemmed eqivalents in");
    console.log("the second column.\n");
    console.log("Otherwise, the output file consists of the stemmed words, one per");
    console.log("line.\n");
    console.log("-h displays this help");
}

if (process.argv.length < 5)
{
    usage();
}
else
{
    var pretty = 0;
    var input = '';
    var output = '';
    var encoding = 'utf8';
    var language = 'English';
    var show_help = false;
    while (process.argv.length > 0)
    {
        var arg = process.argv.shift();
        switch (arg)
        {
        case "-h":
            show_help = true;
            process.argv.length = 0;
            break;
        case "-p":
            pretty = 1;
            break;
        case "-p2":
            pretty = 2;
            break;
        case "-l":
            if (process.argv.length == 0)
            {
                show_help = true;
                break;
            }
            language = process.argv.shift();
            break;
        case "-i":
            if (process.argv.length == 0)
            {
                show_help = true;
                break;
            }
            input = process.argv.shift();
            break;
        case "-o":
            if (process.argv.length == 0)
            {
                show_help = true;
                break;
            }
            output = process.argv.shift();
            break;
        case "-c":
            if (process.argv.length == 0)
            {
                show_help = true;
                break;
            }
            encoding = process.argv.shift();
            break;
        }
    }
    if (show_help || input == '' || output == '')
    {
        usage();
    }
    else
    {
        stemming(language, input, output, encoding, pretty);
    }
}

// function stemming (lang : string, input : string, output : string, encoding : string, pretty : int) {
function stemming (lang, input, output, encoding, pretty) {
        var lines = fs.readFileSync(input, encoding).split("\n");
        if (lines[lines.length - 1] == "") {
            lines.pop();
        }
        var stemmer = create(lang);
        for (var i in lines)
        {
            var original = lines[i];
            var stemmed = stemmer.stemWord(original);
            switch (pretty)
            {
            case 0:
                lines[i] = stemmed;
                break;
            case 1:
                lines[i] += " -> " + stemmed;
                break;
            case 2:
                if (original.length < 30)
                {
                    for (var j = original.length; j < 30; j++)
                    {
                        lines[i] += " ";
                    }
                }
                else
                {
                    lines[i] += "\n";
                    for (var j = 0; j < 30; j++)
                    {
                        lines[i] += " ";
                    }
                }
                lines[i] += stemmed;
            }
        }
        lines.push("");
        fs.writeFileSync(output, lines.join('\n'), encoding);
}

function create (name) {
    var lc_name = name.toLowerCase();
    if (!lc_name.match('\\W') && lc_name != 'base') {
        try {
            const Stemmer = require(lc_name + '-stemmer.js');
            return new Stemmer();
        } catch (error) {
            console.log(error);
        }
    }
    console.log('Unknown stemming language: ' + name + '\n');
    usage();
    process.exit(1);
}
<commit_msg>Revert accidentally include code change<commit_after>const stemmer = require('base-stemmer.js');

const fs = require('fs');

function usage() {
    console.log("usage: stemwords.js [-l <language>] -i <input file> -o <output file> [-c <character encoding>] [-p[2]] [-h]\n");
    console.log("The input file consists of a list of words to be stemmed, one per");
    console.log("line. Words should be in lower case.\n");
    console.log("If -c is given, the argument is the character encoding of the input");
    console.log("and output files.  If it is omitted, the UTF-8 encoding is used.\n");
    console.log("If -p is given the output file consists of each word of the input");
    console.log("file followed by \"->\" followed by its stemmed equivalent.");
    console.log("If -p2 is given the output file is a two column layout containing");
    console.log("the input words in the first column and the stemmed eqivalents in");
    console.log("the second column.\n");
    console.log("Otherwise, the output file consists of the stemmed words, one per");
    console.log("line.\n");
    console.log("-h displays this help");
}

if (process.argv.length < 5)
{
    usage();
}
else
{
    var pretty = 0;
    var input = '';
    var output = '';
    var encoding = 'utf8';
    var language = 'English';
    var show_help = false;
    while (process.argv.length > 0)
    {
        var arg = process.argv.shift();
        switch (arg)
        {
        case "-h":
            show_help = true;
            process.argv.length = 0;
            break;
        case "-p":
            pretty = 1;
            break;
        case "-p2":
            pretty = 2;
            break;
        case "-l":
            if (process.argv.length == 0)
            {
                show_help = true;
                break;
            }
            language = process.argv.shift();
            break;
        case "-i":
            if (process.argv.length == 0)
            {
                show_help = true;
                break;
            }
            input = process.argv.shift();
            break;
        case "-o":
            if (process.argv.length == 0)
            {
                show_help = true;
                break;
            }
            output = process.argv.shift();
            break;
        case "-c":
            if (process.argv.length == 0)
            {
                show_help = true;
                break;
            }
            encoding = process.argv.shift();
            break;
        }
    }
    if (show_help || input == '' || output == '')
    {
        usage();
    }
    else
    {
        stemming(language, input, output, encoding, pretty);
    }
}

// function stemming (lang : string, input : string, output : string, encoding : string, pretty : int) {
function stemming (lang, input, output, encoding, pretty) {
        var lines = fs.readFileSync(input, encoding).split("\n");
        if (lines[lines.length - 1] == "") {
            lines.pop();
        }
        var stemmer = create(lang);
        for (var i in lines)
        {
            var original = lines[i];
            var stemmed = stemmer.stemWord(original);
            switch (pretty)
            {
            case 0:
                lines[i] = stemmed;
                break;
            case 1:
                lines[i] += " -> " + stemmed;
                break;
            case 2:
                if (original.length < 30)
                {
                    for (var j = original.length; j < 30; j++)
                    {
                        lines[i] += " ";
                    }
                }
                else
                {
                    lines[i] += "\n";
                    for (var j = 0; j < 30; j++)
                    {
                        lines[i] += " ";
                    }
                }
                lines[i] += stemmed;
            }
        }
        lines.push("");
        fs.writeFileSync(output, lines.join('\n'), encoding);
}

function create (name) {
    var lc_name = name.toLowerCase();
    if (!lc_name.match('\\W') && lc_name != 'base') {
        var algo = lc_name.substr(0, 1).toUpperCase() + lc_name.substr(1);
        try {
            const stemmer = require(lc_name + '-stemmer.js');
            return Function('return new ' + algo + 'Stemmer()')();
        } catch (error) {
        }
    }
    console.log('Unknown stemming language: ' + name + '\n');
    usage();
    process.exit(1);
}
<|endoftext|>


<commit_before>'use strict';

var httpDefault = require('http');
var _ = require('lodash');
var repositories = require('./repositories');

var Dispatcher = function(http) {
    this.http = http || httpDefault;
    this.countries = new repositories.Countries();
};

Dispatcher.prototype = {
    sendOrder: function(seller, order) {
        var options = {
            hostname: seller.hostname,
            port: seller.port,
            path: seller.path,
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        };
        var request = this.http.request(options);
        request.write(order);
        request.end();
    },

    createOrder: function(numberOfItems) {
        var items = numberOfItems || 1;
        var prices = new Array(items);
        var quantities = new Array(items);

        for(var item = 0; item < items; item++) {
            prices[item] = _.random(1, 1000, true).toFixed(2);
            quantities[item] = _.random(1, 100);
        }

        return {
            prices: prices,
            quantities: quantities,
            country: _.sample(this.countries.fromEurope)
        };
    }
};

exports = module.exports;

exports.Dispatcher = Dispatcher;<commit_msg>Chose a random number of items when no number is given for order creation.<commit_after>'use strict';

var httpDefault = require('http');
var _ = require('lodash');
var repositories = require('./repositories');

var Dispatcher = function(http) {
    this.http = http || httpDefault;
    this.countries = new repositories.Countries();
};

Dispatcher.prototype = {
    sendOrder: function(seller, order) {
        var options = {
            hostname: seller.hostname,
            port: seller.port,
            path: seller.path,
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        };
        var request = this.http.request(options);
        request.write(order);
        request.end();
    },

    createOrder: function(numberOfItems) {
        var items = numberOfItems || _.random(1, 100);
        var prices = new Array(items);
        var quantities = new Array(items);

        for(var item = 0; item < items; item++) {
            prices[item] = _.random(1, 1000, true).toFixed(2);
            quantities[item] = _.random(1, 100);
        }

        return {
            prices: prices,
            quantities: quantities,
            country: _.sample(this.countries.fromEurope)
        };
    }
};

exports = module.exports;

exports.Dispatcher = Dispatcher;<|endoftext|>