text:
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
 // ERROR: Not supported in C#: OptionDeclaration
using VB = Microsoft.VisualBasic;
namespace _4PosBackOffice.NET
{
	internal partial class frmStockTakeLIQ : System.Windows.Forms.Form
	{
		ADODB.Recordset rs;
		string Te_Name;
		string MyFTypes;
		string sql1;

			// picture loading
		Scripting.FileSystemObject fso = new Scripting.FileSystemObject();
			// to select W/H for stock take
		int lMWNo;
		ADODB.Recordset rsLIQ = new ADODB.Recordset();

		private byte[] arData;
		private byte[] arPWord;
		private short m_intCipher;
//serialization

		public void Reset_frmEncStrings()
		{
			string strMsg = null;

			arData = null;
			arPWord = null;
		}

//UPGRADE_NOTE: Form_Initialize was upgraded to Form_Initialize_Renamed. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A9E4979A-37FA-4718-9994-97DD76ED70A7"'
		private void Form_Initialize_Renamed()
		{
			//ChDrive App.Path
			//ChDir App.Path
			basCryptoProcs.Initial_settings();
			Reset_frmEncStrings();
		}

		private void cmdReg_Click(System.Object eventSender, System.EventArgs eventArgs)
		{
			if (My.MyProject.Forms.frmStockTakeLIQCode.setupCode() == true) {
				Picture1.Visible = false;
			}
		}

		private string getSerialNumber()
		{
			string functionReturnValue = null;
			Scripting.FileSystemObject fso = new Scripting.FileSystemObject();
			Scripting.Folder fsoFolder = default(Scripting.Folder);
			Scripting.Drive fsoDrive = default(Scripting.Drive);
			functionReturnValue = "";
			if (fso.FolderExists(modRecordSet.serverPath)) {
				fsoFolder = fso.GetFolder(modRecordSet.serverPath);
				functionReturnValue = Convert.ToString(fsoFolder.Drive.SerialNumber);
			}
			return functionReturnValue;
		}

		private string Encrypt(string secret, string password)
		{
			int l = 0;
			short x = 0;
			//UPGRADE_NOTE: Char was upgraded to Char_Renamed. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A9E4979A-37FA-4718-9994-97DD76ED70A7"'
			string Char_Renamed = null;
			l = Strings.Len(password);
			for (x = 1; x <= Strings.Len(secret); x++) {
				Char_Renamed = Convert.ToString(Strings.Asc(Strings.Mid(password, (x % l) - l * Convert.ToInt16((x % l) == 0), 1)));
				Strings.Mid(secret, x, 1) = Strings.Chr(Strings.Asc(Strings.Mid(secret, x, 1)) ^ Char_Renamed);
			}
			return secret;
		}

		private bool checkSecurity()
		{
			bool functionReturnValue = false;
			object intMonth = null;
			object intYear = null;
			string lCode = null;
			string leCode = null;
			string lPassword = null;
			ADODB.Recordset rs = default(ADODB.Recordset);
			short x = 0;
			functionReturnValue = false;
			string strSerial = null;
			object strTmp = null;
			short intDate = 0;
			string dtDate = null;
			string dtMonth = null;
			string dtYear = null;
			string stPass = null;
			// clsCryptoAPI
			//UPGRADE_ISSUE: clsCryptoAPI object was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6B85A2A7-FE9F-4FBE-AA0C-CF11AC86A305"'
			clsCryptoAPI cCrypto = null;
			if (modRecordSet.openConnection()) {
				rs = modRecordSet.getRS(ref "SELECT * From Company");
				if (rs.RecordCount) {

					//if old database don't chk secuirty
					if (rs.Fields.Count <= 55){functionReturnValue = true;return functionReturnValue;}

					//UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					if (Information.IsDBNull(rs.Fields("Company_ResMS").Value)){functionReturnValue = false;return functionReturnValue;}

					cCrypto = new clsCryptoAPI();
					//clsCryptoAPI
					System.Windows.Forms.Application.DoEvents();
					//strTmp = cCrypto.ConvertStringFromHex(Left(rs("Company_ResMS"), 6))
					//UPGRADE_WARNING: Couldn't resolve default property of object cCrypto.ConvertStringFromHex. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
					//UPGRADE_WARNING: Couldn't resolve default property of object strTmp. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
					strTmp = cCrypto.ConvertStringFromHex(Strings.Left(rs.Fields("Company_ResMS").Value, Strings.Len(rs.Fields("Company_ResMS").Value) - 5));
					System.Windows.Forms.Application.DoEvents();
					//UPGRADE_WARNING: Couldn't resolve default property of object cCrypto.StringToByteArray. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
					arData = cCrypto.StringToByteArray(strTmp);
					System.Windows.Forms.Application.DoEvents();
					//UPGRADE_WARNING: Couldn't resolve default property of object cCrypto.StringToByteArray. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
					arPWord = cCrypto.StringToByteArray(Conversion.Val(Strings.Right(rs.Fields("Company_ResMS").Value, 5)));
					System.Windows.Forms.Application.DoEvents();
					//UPGRADE_WARNING: Couldn't resolve default property of object cCrypto.password. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
					//UPGRADE_TODO: Code was upgraded to use System.Text.UnicodeEncoding.Unicode.GetString() which may not have the same behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="93DD716C-10E3-41BE-A4A8-3BA40157905B"'
					cCrypto.PassWord = arPWord;
					System.Windows.Forms.Application.DoEvents();
					//UPGRADE_WARNING: Couldn't resolve default property of object cCrypto.InputData. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
					//UPGRADE_TODO: Code was upgraded to use System.Text.UnicodeEncoding.Unicode.GetString() which may not have the same behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="93DD716C-10E3-41BE-A4A8-3BA40157905B"'
					cCrypto.InputData = System.Text.UnicodeEncoding.Unicode.GetString(arData);
					System.Windows.Forms.Application.DoEvents();

					// Decrypt the data input from the encrypted text box
					//If cCrypto.Decrypt(g_intHashType, m_intCipher) Then
					//UPGRADE_WARNING: Couldn't resolve default property of object cCrypto.Decrypt. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
					if (cCrypto.Decrypt(2, 1)) {
						System.Windows.Forms.Application.DoEvents();
						//UPGRADE_WARNING: Couldn't resolve default property of object cCrypto.OutputData. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
						arData = cCrypto.OutputData.Clone();
						//UPGRADE_WARNING: Couldn't resolve default property of object cCrypto.ByteArrayToString. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
						strSerial = cCrypto.ByteArrayToString(arData);
					}

					if (Strings.Left(strSerial, 3) == "liq") {

						//Create date password
						if (Information.IsNumeric(Strings.Mid(strSerial, 4, Strings.Len(strSerial)))) {

							functionReturnValue = true;
							goto jumpOut;

							strSerial = Strings.Mid(strSerial, 4, Strings.Len(strSerial));
							//UPGRADE_WARNING: Couldn't resolve default property of object intYear. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
							intYear = Strings.Mid(strSerial, 5, 2);
							//UPGRADE_WARNING: Couldn't resolve default property of object intMonth. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
							intMonth = Strings.Mid(strSerial, 3, 2);
							intDate = Convert.ToInt16(Strings.Left(strSerial, 2));

							if ((intDate / 2) == System.Math.Round(intDate / 2)) {
								intDate = intDate / 2;
							} else {
								goto jumpOut;
							}

							//UPGRADE_WARNING: Couldn't resolve default property of object intMonth. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
							if ((intMonth / 3) == System.Math.Round(intMonth / 3)) {
								//UPGRADE_WARNING: Couldn't resolve default property of object intMonth. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
								intMonth = intMonth / 3;
							} else {
								goto jumpOut;
							}

							//UPGRADE_WARNING: Couldn't resolve default property of object intYear. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
							if ((intYear / 4) == System.Math.Round(intYear / 4)) {
								//UPGRADE_WARNING: Couldn't resolve default property of object intYear. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
								intYear = intYear / 4;
							} else {
								goto jumpOut;
							}

							stPass = "20";
							//UPGRADE_WARNING: Couldn't resolve default property of object intYear. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
							if (Strings.Len(Convert.ToString(intYear)) == 1) {
								stPass = stPass + "0" + intYear + "/";
							} else {
								//UPGRADE_WARNING: Couldn't resolve default property of object intYear. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
								stPass = stPass + intYear + "/";
							}
							//UPGRADE_WARNING: Couldn't resolve default property of object intMonth. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
							if (Strings.Len(Convert.ToString(intMonth)) == 1) {
								stPass = stPass + "0" + intMonth + "/";
							} else {
								//UPGRADE_WARNING: Couldn't resolve default property of object intMonth. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
								stPass = stPass + intMonth + "/";
							}
							if (Strings.Len(Convert.ToString(intDate)) == 1)
								stPass = stPass + "0" + intDate;
							else
								stPass = stPass + intDate;

							if (Information.IsDate(stPass)) {
								if (Convert.ToDateTime(stPass) >= (System.Date.FromOADate(DateAndTime.Today.ToOADate() - 31))) {
									functionReturnValue = true;
								}
							}

						} else {
							//MsgBox "Not a Valid 4MEAT Key!", vbCritical
						}
					} else {
						//MsgBox "Not a Valid 4MEAT Key!", vbCritical
					}
					jumpOut:
					//UPGRADE_NOTE: Object cCrypto may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
					cCrypto = null;
					// Free the Crypto class from memory
					//UPGRADE_WARNING: Couldn't resolve default property of object strTmp. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
					strTmp = new string(Strings.Chr(0), 250);
					return functionReturnValue;
					// overwrite data in temp variable

				} else {
					Interaction.MsgBox("Unable to locate the '4POS Application Suite' database.", MsgBoxStyle.Critical, "4POS");
					//End
				}
			} else {
				Interaction.MsgBox("Unable to locate the '4POS Application Suite' database.", MsgBoxStyle.Critical, "4POS");
				//End
			}
			return functionReturnValue;
		}

		private void loadLanguage()
		{

			//NOTE: Caption has a spelling mistake, DB Entry 1213 is correct!
			modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1213;
			//Stock Take
			if (modRecordSet.rsLang.RecordCount){this.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;this.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}

			modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2506;
			//Show Differendce|Checked
			if (modRecordSet.rsLang.RecordCount){cmdDiff.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdDiff.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}

			//NOTE: DB Entry 2507 requires "&" for accelerator key
			modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2507;
			//Save and Exit|Checked
			if (modRecordSet.rsLang.RecordCount){cmdClose.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdClose.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}

			modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1838;
			//Barcode|Checked
			if (modRecordSet.rsLang.RecordCount){Label1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;Label1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}

			modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1674;
			//Description|Checked
			if (modRecordSet.rsLang.RecordCount){Label2.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;Label2.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}

			modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1676;
			//Qty|Checked
			if (modRecordSet.rsLang.RecordCount){Label3.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;Label3.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}

			modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1080;
			//Search|Checked
			if (modRecordSet.rsLang.RecordCount){cmdsearch.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdsearch.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}

			modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2512;
			//Show Pictures|Checked
			if (modRecordSet.rsLang.RecordCount){chkPic.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;chkPic.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}

			modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'";
			//UPGRADE_ISSUE: Form property frmStockTakeLIQ.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
			if (modRecordSet.rsHelp.RecordCount)
				this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value;

		}

//UPGRADE_WARNING: Event chkPic.CheckStateChanged may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="88B12AE1-6DE0-48A0-86F1-60C0686C026A"'
		private void chkPic_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
		{
			if (chkPic.CheckState) {
				this.Width = sizeConvertors.twipsToPixels(12675, true);
				picBC.Visible = true;
				imgBC.Visible = true;
				this.Left = sizeConvertors.twipsToPixels(400, true);
			} else {
				this.Width = sizeConvertors.twipsToPixels(8640, true);
				picBC.Visible = false;
				imgBC.Visible = false;
			}
		}

		private void cmdClose_Click(System.Object eventSender, System.EventArgs eventArgs)
		{
			int MStockNew = 0;
			 // ERROR: Not supported in C#: OnErrorStatement

			ADODB.Recordset rsB = default(ADODB.Recordset);
			ADODB.Recordset rsk = default(ADODB.Recordset);

			rsB = new ADODB.Recordset();
			rsk = new ADODB.Recordset();

			rsk = modRecordSet.getRS(ref "SELECT * FROM " + Te_Name + "");

			if (rsk.RecordCount > 0) {
				//UPGRADE_WARNING: Couldn't resolve default property of object MStockNew. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
				MStockNew = 2;
				rsB = modRecordSet.getRS(ref "INSERT INTO StockGroup(StockGroup_Name,StockGroup_Disabled)VALUES('" + Te_Name + "',0)");
				UpdateCatalogID(ref (Te_Name));
			}
			MyErH:
			if (rsLIQ.State)
				rsLIQ.Close();
			this.Close();

		}

		private void report_WHTransfer(ref string tblName)
		{
			ADODB.Recordset rs = default(ADODB.Recordset);
			string sql = null;
			CrystalDecisions.CrystalReports.Engine.ReportDocument Report = default(CrystalDecisions.CrystalReports.Engine.ReportDocument);
			CrystalDecisions.CrystalReports.Engine.ReportDocument ReportNone = default(CrystalDecisions.CrystalReports.Engine.ReportDocument);
			Report.Load("cryWHRecVerify.rpt");
			System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
			rs = modRecordSet.getRS(ref "SELECT Company.Company_Name FROM Company;");
			Report.SetParameterValue("txtCompanyName", rs.Fields("Company_Name"));
			rs.Close();

			sql = "SELECT Handheld777_0.HandHeldID, StockItem.StockItem_Name, Handheld777_0.Quantity";
			sql = sql + " FROM Handheld777_0 INNER JOIN StockItem ON Handheld777_0.HandHeldID = StockItem.StockItemID;";
			rs = modRecordSet.getRS(ref sql);

			ReportNone.Load("cryNoRecords.rpt");
			if (rs.BOF | rs.EOF) {
				ReportNone.SetParameterValue("txtCompanyName", Report.ParameterFields("txtCompanyName").ToString);
				ReportNone.SetParameterValue("txtTitle", Report.ParameterFields("txtTitle").ToString);
				My.MyProject.Forms.frmReportShow.Text = ReportNone.ParameterFields("txtTitle").ToString;
				My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = ReportNone;
				My.MyProject.Forms.frmReportShow.mReport = ReportNone;
				My.MyProject.Forms.frmReportShow.sMode = "0";
				My.MyProject.Forms.frmReportShow.CRViewer1.Refresh();
				System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
				My.MyProject.Forms.frmReportShow.ShowDialog();
				return;
			}
			Report.Database.Tables(1).SetDataSource(rs);

			//Report.VerifyOnEveryPrint = True
			My.MyProject.Forms.frmReportShow.Text = Report.ParameterFields("txtTitle").ToString;
			My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = Report;
			My.MyProject.Forms.frmReportShow.mReport = Report;
			My.MyProject.Forms.frmReportShow.sMode = "0";
			My.MyProject.Forms.frmReportShow.CRViewer1.Refresh();
			System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
			My.MyProject.Forms.frmReportShow.ShowDialog();
		}

		private void cmdDiff_Click(System.Object eventSender, System.EventArgs eventArgs)
		{
			string strIn = null;
			string strFldName = null;
			//Te_Name
			ADODB.Recordset rs = default(ADODB.Recordset);
			ADODB.Recordset rj = default(ADODB.Recordset);

			 // ERROR: Not supported in C#: OnErrorStatement

			//Set rs = getRS("SELECT * FROM Te_Name")

			modRecordSet.cnnDB.Execute("DELETE * FROM Handheld777_0;");
			modRecordSet.cnnDB.Execute("DROP TABLE Handheld777_0;");
			strFldName = "HandHeldID Number,Handheld_Barcode Text(50), Quantity Currency";
			modRecordSet.cnnDB.Execute("CREATE TABLE " + "Handheld777_0" + " (" + strFldName + ")");
			System.Windows.Forms.Application.DoEvents();

			rj = modRecordSet.getRS(ref "SELECT WarehouseStockItemLnk.WarehouseStockItemLnk_WarehouseID, WarehouseStockItemLnk.WarehouseStockItemLnk_StockItemID, WarehouseStockItemLnk.WarehouseStockItemLnk_Quantity From WarehouseStockItemLnk WHERE (((WarehouseStockItemLnk.WarehouseStockItemLnk_WarehouseID)=" + lMWNo + ") AND ((WarehouseStockItemLnk.WarehouseStockItemLnk_Quantity)>0))");
			while (rj.EOF == false) {

				rs = modRecordSet.getRS(ref "SELECT * FROM " + Te_Name + " WHERE HandHeldID=" + rj.Fields("WarehouseStockItemLnk_StockItemID").Value + ";");
				if (rs.RecordCount > 0) {
				} else {
					strIn = "INSERT INTO Handheld777_0 (HandHeldID,Handheld_Barcode,Quantity) VALUES (" + rj.Fields("WarehouseStockItemLnk_StockItemID").Value + ", '" + rj.Fields("WarehouseStockItemLnk_Quantity").Value + "', " + rj.Fields("WarehouseStockItemLnk_Quantity").Value + ")";
					modRecordSet.cnnDB.Execute(strIn);
				}

				rj.moveNext();
			}

			report_WHTransfer(ref "Handheld777_0");

			modRecordSet.cnnDB.Execute("DELETE * FROM Handheld777_0;");
			modRecordSet.cnnDB.Execute("DROP TABLE Handheld777_0;");
			return;
			diff_Error:
			Interaction.MsgBox(Err().Number + " " + Err().Description);
		}

		private void cmdsearch_Click(System.Object eventSender, System.EventArgs eventArgs)
		{
			object eroor = null;
			 // ERROR: Not supported in C#: OnErrorStatement

			//openConnection
			ADODB.Recordset rsP = default(ADODB.Recordset);
			ADODB.Recordset rsk = default(ADODB.Recordset);
			ADODB.Recordset rsTest = default(ADODB.Recordset);
			ADODB.Recordset rsNew = default(ADODB.Recordset);

			rs = new ADODB.Recordset();
			rsP = new ADODB.Recordset();
			rsk = new ADODB.Recordset();
			rsk = new ADODB.Recordset();
			rsTest = new ADODB.Recordset();
			rsNew = new ADODB.Recordset();
			if (string.IsNullOrEmpty(this.txtcode.Text))
				return;
			//If Me.txtCode.Text <> "" Then
			//creating table name
			//Te_Name = "HandHeld" & Trim(Year(Date)) & Trim(Month(Date)) & Trim(Day(Date)) & Trim(Hour(Now)) & Trim(Minute(Now)) & Trim(Second(Now)) & "_" & frmMenu.lblUser.Tag
			rsTest = modRecordSet.getRS(ref "SELECT Barcodes,Description,Quantity FROM " + Te_Name + "");

			//If rsTest.RecordCount And MStockNew = 0 Then
			rs = modRecordSet.getRS(ref "SELECT * FROM Catalogue WHERE Catalogue_Barcode='" + this.txtcode.Text + "'");

			//check if the barcode exists
			if (rs.RecordCount > 0) {
				rsP = modRecordSet.getRS(ref "SELECT StockItem_Name FROM StockItem WHERE StockItemID=" + rs.Fields("Catalogue_StockItemID").Value + "");
				this.txtdesc.Text = rsP.Fields("StockItem_Name").Value;
				this.txtqty.Focus();

				//show pic
				if (this.cmdsearch.Text != "&Add") {
					if (chkPic.CheckState & picBC.Visible == true) {
						if (fso.FileExists(modRecordSet.serverPath + "\\images\\" + this.txtcode.Text + ".jpg")) {
							picBC.Image = System.Drawing.Image.FromFile(modRecordSet.serverPath + "\\images\\" + this.txtcode.Text + ".jpg");
							imgBC.Image = picBC.Image;
						} else {
							Interaction.MsgBox("No picture found for " + this.txtcode.Text);
						}
					}
				}
				//show pic

				this.cmdsearch.Text = "&Add";

				//get Weight
				if (string.IsNullOrEmpty(this.txtqty.Text))
					tmrGetWei.Enabled = true;

				//if the barcode does not exist display a message
			} else if (rs.RecordCount < 1) {
				Interaction.MsgBox("The Item does not exist,Please add it in Stock Create/Edit, New Stock Item", MsgBoxStyle.ApplicationModal + MsgBoxStyle.OkOnly, "4POS");
				this.txtcode.Text = "";
				this.txtcode.Focus();
				return;
			}

			//Checking if the barcode was found and if the quantity textbox has a value
			double NewQty = 0;
			if (this.cmdsearch.Text == "&Add" & !string.IsNullOrEmpty(this.txtqty.Text)) {
				//creating fields with their data types
				MyFTypes = "HandHeldID Number,Barcodes Text(50),Description Text(50),Quantity Currency";

				rsk = modRecordSet.getRS(ref "SELECT * FROM " + Te_Name + "");
				//if the table has not been created yet create it
				switch (eroor) {
					case  // ERROR: Case labels with binary operators are unsupported : LessThan
0:
						 // ERROR: Not supported in C#: ErrorStatement

						break;
					case 1:
						goto erh;
						break;
				}
				erh:

				modRecordSet.cnnDB.Execute("CREATE TABLE " + Te_Name + " (" + MyFTypes + ")");

				//selecting from the new table created
				rsNew = modRecordSet.getRS(ref "SELECT * FROM " + Te_Name + " WHERE Barcodes='" + this.txtcode.Text + "'");
				//if the item is already in the newly created table then add the previous quantity to the new one then update it
				if (rsNew.RecordCount > 0) {

					NewQty = Convert.ToDouble(this.txtqty.Text);

					NewQty = NewQty + rsNew.Fields("Quantity").Value;
					//update the quantity
					rsk = modRecordSet.getRS(ref "UPDATE " + Te_Name + " SET Quantity=" + NewQty + " WHERE Barcodes='" + this.txtcode.Text + "'");
				} else if (rsNew.RecordCount < 1) {
					//inserting into the newly created table
					rsk = modRecordSet.getRS(ref "INSERT INTO " + Te_Name + "(HandHeldID,Barcodes,Description,Quantity)VALUES(" + rs.Fields("Catalogue_StockItemID").Value + ",'" + this.txtcode.Text + "','" + this.txtdesc.Text + "'," + this.txtqty.Text + " )");
				}

				//selecting from the newly created table
				rsk = modRecordSet.getRS(ref "SELECT Barcodes,Description,Quantity FROM " + Te_Name + "");
				//filling the datagrid with the record consisting of barcode,description,quantity if the barcode exist
				this.DataGrid1.DataSource = rsk;
				this.txtcode.Text = "";
				this.txtdesc.Text = "";
				this.txtqty.Text = "";
				this.cmdsearch.Text = "&Search";
				this.txtcode.Focus();

			}
			//ElseIf rsTest.RecordCount > 0 And MStockNew = 2 Then
			//MsgBox "A Table with the Same Name Already Exist", vbApplicationModal + vbOKOnly, "4POS"
			//Me.txtCode.Text = ""
			//Me.cmdClose.SetFocus
			//End If
		}

		private void frmStockTakeLIQ_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
		{
			short KeyAscii = Strings.Asc(eventArgs.KeyChar);

			if (KeyAscii == 13 & this.cmdsearch.Text == "&Search" & !string.IsNullOrEmpty(this.txtcode.Text)) {
				cmdsearch_Click(cmdsearch, new System.EventArgs());
			} else if (KeyAscii == 13 & this.cmdsearch.Text == "&Add" & !string.IsNullOrEmpty(this.txtdesc.Text)) {
				cmdsearch_Click(cmdsearch, new System.EventArgs());
			} else if (KeyAscii == 27) {
				cmdClose_Click(cmdClose, new System.EventArgs());
			}

			eventArgs.KeyChar = Strings.Chr(KeyAscii);
			if (KeyAscii == 0) {
				eventArgs.Handled = true;
			}
		}

		public void UpdateCatalogID(ref string st_Name)
		{
			object strFldName = null;
			object strIn = null;
			ADODB.Recordset rj = default(ADODB.Recordset);
			ADODB.Recordset rs = default(ADODB.Recordset);
			ADODB.Recordset rID = default(ADODB.Recordset);

			//Set rID = getRS("SELECT * FROM " & st_Name)
			//Do While rID.EOF = False
			//        If prgUpdate.value = prgUpdate.Max Then
			//           prgUpdate.value = 0
			//        Else
			//           prgUpdate.value = prgUpdate.value + 1
			//        End If
			//    'rID("Handheld_Barcode") = 0
			//        rID("HandHeldID") = 0
			//        rID.update '"HandHeldID", 0
			// rID.moveNext
			//Loop

			//UPGRADE_WARNING: Couldn't resolve default property of object strIn. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
			strIn = "UPDATE " + st_Name + " SET HandHeldID = 0 WHERE Quantity > 0;";
			//UPGRADE_WARNING: Couldn't resolve default property of object strIn. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
			modRecordSet.cnnDB.Execute(strIn);

			rj = modRecordSet.getRS(ref "SELECT * FROM " + st_Name);
			while (rj.EOF == false) {
				//If prgUpdate.value = prgUpdate.Max Then
				//   prgUpdate.value = 0
				//Else
				//   prgUpdate.value = prgUpdate.value + 1
				//End If

				//Set rs = getRS("SELECT * FROM Catalogue WHERE Catalogue_Barcode = '" & rj("Handheld_Barcode") & "'")
				rs = modRecordSet.getRS(ref "SELECT StockItem.StockItem_Disabled, StockItem.StockItem_Discontinued, * FROM Catalogue INNER JOIN StockItem ON Catalogue.Catalogue_StockItemID = StockItem.StockItemID WHERE (((Catalogue.Catalogue_Barcode)='" + rj.Fields("Barcodes").Value + "') AND ((StockItem.StockItem_Disabled)=False) AND ((StockItem.StockItem_Discontinued)=False));");
				if (rs.RecordCount > 0)
					modRecordSet.cnnDB.Execute("UPDATE " + st_Name + " SET HandHeldID = " + rs.Fields("Catalogue_StockItemID").Value + ", Quantity = " + (rj.Fields("Quantity").Value * rs.Fields("Catalogue_Quantity").Value) + " WHERE Barcodes = '" + rj.Fields("Barcodes").Value + "'");

				rj.moveNext();
			}

			//chkDuplicate:
			//UPGRADE_WARNING: Couldn't resolve default property of object strFldName. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
			strFldName = "HandHeldID Number,Barcodes Text(50),Description Text(50),Quantity Currency";
			//UPGRADE_WARNING: Couldn't resolve default property of object strFldName. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
			modRecordSet.cnnDB.Execute("CREATE TABLE " + "Handheld777" + " (" + strFldName + ")");
			System.Windows.Forms.Application.DoEvents();

			rj = modRecordSet.getRS(ref "SELECT * FROM " + st_Name);

			while (rj.EOF == false) {
				rs = modRecordSet.getRS(ref "SELECT * FROM Handheld777 WHERE HandHeldID=" + rj.Fields("HandHeldID").Value + ";");
				if (rs.RecordCount > 0) {
					//UPGRADE_WARNING: Couldn't resolve default property of object strIn. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
					strIn = "UPDATE Handheld777 SET Quantity = " + (rs.Fields("Quantity").Value + rj.Fields("Quantity").Value) + " WHERE HandHeldID=" + rj.Fields("HandHeldID").Value + ";";
				} else {
					//UPGRADE_WARNING: Couldn't resolve default property of object strIn. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
					strIn = "INSERT INTO Handheld777 (HandHeldID,Barcodes,Quantity) VALUES (" + rj.Fields("HandHeldID").Value + ", '" + rj.Fields("Barcodes").Value + "', " + rj.Fields("Quantity").Value + ")";
				}
				//UPGRADE_WARNING: Couldn't resolve default property of object strIn. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
				modRecordSet.cnnDB.Execute(strIn);

				rj.moveNext();
			}

			modRecordSet.cnnDB.Execute("DELETE * FROM " + st_Name + ";");
			//strIn = "SELECT Handheld777.* INTO " & st_Name & " FROM Handheld777" '& ResolveTable(cmbTables.Text)
			modRecordSet.cnnDB.Execute("INSERT INTO " + st_Name + " SELECT * FROM Handheld777;");
			modRecordSet.cnnDB.Execute("DROP TABLE Handheld777;");
			//chkDuplicate:

			//DeleteBlankID
			//MsgBox "File was extracted and exported succesfully", vbApplicationModal + vbInformation + vbOKOnly, App.title
			//prgUpdate.value = 300

		}

		private void frmStockTakeLIQ_Load(System.Object eventSender, System.EventArgs eventArgs)
		{
			 // ERROR: Not supported in C#: OnErrorStatement

			if (modRecordSet.cnnDB == null) {

				if (openConnection() == true) {
				}
			}
			//creating table name
			Te_Name = "HandHeld" + Strings.Trim(Convert.ToString(DateAndTime.Year(DateAndTime.Today))) + Strings.Trim(Convert.ToString(DateAndTime.Month(DateAndTime.Today))) + Strings.Trim(Convert.ToString(DateAndTime.Day(DateAndTime.Today))) + Strings.Trim(Convert.ToString(DateAndTime.Hour(DateAndTime.Now))) + Strings.Trim(Convert.ToString(DateAndTime.Minute(DateAndTime.Now))) + Strings.Trim(Convert.ToString(DateAndTime.Second(DateAndTime.Now))) + "_" + My.MyProject.Forms.frmMenu.lblUser.Tag;

			loadLanguage();

			lMWNo = My.MyProject.Forms.frmMWSelect.getMWNo();
			if (lMWNo > 1) {
				//Set rsWH = getRS("SELECT * FROM Warehouse WHERE WarehouseID=" & lMWNo & ";")
				//Report.txtWH.SetText rsWH("Warehouse_Name")
			}
			Timer1.Enabled = true;
		}

		private void frmStockTakeLIQ_FormClosed(System.Object eventSender, System.Windows.Forms.FormClosedEventArgs eventArgs)
		{
			if (rsLIQ.State)
				rsLIQ.Close();
		}

		private void Timer1_Tick(System.Object eventSender, System.EventArgs eventArgs)
		{
			Timer1.Enabled = false;

			if (fso.FileExists(modRecordSet.serverPath + "4LIQ-DATA.pos")) {
				rsLIQ.Open(modRecordSet.serverPath + "\\4LIQ-DATA.pos", , ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockReadOnly);
				rsLIQ.filter = ADODB.FilterGroupEnum.adFilterNone;
				//        Do Until rsLIQ.EOF
				//            'Text1 = rsLIQ("StockItemName")
				//            'Text2 = rsLIQ("StockItemBC")
				//            'MsgBox "next"
				//            If LCase(rsLIQ("StockItemName")) = LCase(frmMenu.lblCompany.Caption) Then Exit Sub
				//            rsLIQ.moveNext
				//        Loop

				//Serial chk
				if (checkSecurity() == true) {
					return;
				} else {
					Label4.Text = "Please contact your 4POS representative or www.4pos.co.za.";
					cmdReg.Visible = true;
				}
				//        If date > #11/11/2012# Then
				//        Else
				//            Exit Sub
				//        End If
			} else {
				Label4.Text = "'4LIQ-DATA.pos' file is missing.";
			}

			var _with1 = Picture1;
			_with1.Top = 0;
			_with1.Left = 0;
			_with1.Width = this.Width;
			_with1.Height = this.Height;

		}

		private void tmrGetWei_Tick(System.Object eventSender, System.EventArgs eventArgs)
		{
			object frmDSWeight = null;
			decimal cScaleWeight = default(decimal);
			decimal cStockTots = default(decimal);
			tmrGetWei.Enabled = false;
			tryScaleWeight:

			//UPGRADE_WARNING: Couldn't resolve default property of object frmDSWeight.getScaleWeight. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
			cScaleWeight = frmDSWeight.getScaleWeight;
			//cScaleWeight = 0.874
			if (cScaleWeight <= 0) {
				if (Interaction.MsgBox("Do you wish to try again?", MsgBoxStyle.YesNo) == MsgBoxResult.Yes) {
					goto tryScaleWeight;
				} else {
					this.txtcode.Text = "";
					this.txtdesc.Text = "";
					this.txtqty.Text = "";
					this.cmdsearch.Text = "&Search";
					this.txtcode.Focus();
				}
			} else {
				rsLIQ.filter = "StockItemBC='" + this.txtcode.Text + "'";
				if (rsLIQ.RecordCount) {
					cStockTots = (cScaleWeight - Convert.ToDecimal(rsLIQ.Fields("Empty").Value)) / Convert.ToDecimal(rsLIQ.Fields("PerTotWeight").Value);
					this.txtqty.Text = Convert.ToString(cStockTots);
					frmStockTakeLIQ_KeyPress(this, new System.Windows.Forms.KeyPressEventArgs(Strings.Chr(13)));
				} else {
					Interaction.MsgBox("The Item does not exist in 4LIQ file.", MsgBoxStyle.ApplicationModal + MsgBoxStyle.OkOnly, "4POS");
					this.txtcode.Text = "";
					this.txtdesc.Text = "";
					this.txtqty.Text = "";
					this.cmdsearch.Text = "&Search";
					this.txtcode.Focus();
				}
			}

		}
	}
}


text:
package org.apache.asterix.runtime.job.listener;

import java.util.List;

import org.apache.asterix.common.api.IAppRuntimeContext;
import org.apache.asterix.common.exceptions.ACIDException;
import org.apache.asterix.common.transactions.DatasetId;
import org.apache.asterix.common.transactions.ITransactionContext;
import org.apache.asterix.common.transactions.ITransactionManager;
import org.apache.asterix.common.transactions.JobId;
import org.apache.hyracks.api.context.IHyracksJobletContext;
import org.apache.hyracks.api.job.IJobletEventListener;
import org.apache.hyracks.api.job.IJobletEventListenerFactory;
import org.apache.hyracks.api.job.JobStatus;

/**
 * This Joblet enable transactions on multiple datasets to take place in the same Hyracks Job
 * It takes a list of Transaction job ids instead of a single job Id
 */
public class MultiTransactionJobletEventListenerFactory implements IJobletEventListenerFactory {

    private static final long serialVersionUID = 1L;
    private final List<JobId> jobIds;
    private final boolean transactionalWrite;

    public MultiTransactionJobletEventListenerFactory(List<JobId> jobIds, boolean transactionalWrite) {
        this.jobIds = jobIds;
        this.transactionalWrite = transactionalWrite;
    }

    @Override
    public IJobletEventListener createListener(final IHyracksJobletContext jobletContext) {

        return new IJobletEventListener() {
            @Override
            public void jobletFinish(JobStatus jobStatus) {
                try {
                    ITransactionManager txnManager =
                            ((IAppRuntimeContext) jobletContext.getApplicationContext().getApplicationObject())
                                    .getTransactionSubsystem().getTransactionManager();
                    for (JobId jobId : jobIds) {
                        ITransactionContext txnContext = txnManager.getTransactionContext(jobId, false);
                        txnContext.setWriteTxn(transactionalWrite);
                        txnManager.completedTransaction(txnContext, new DatasetId(-1), -1,
                                !(jobStatus == JobStatus.FAILURE));
                    }
                } catch (ACIDException e) {
                    throw new Error(e);
                }
            }

            @Override
            public void jobletStart() {
                try {
                    for (JobId jobId : jobIds) {
                        ((IAppRuntimeContext) jobletContext.getApplicationContext().getApplicationObject())
                                .getTransactionSubsystem().getTransactionManager().getTransactionContext(jobId, true);
                    }
                } catch (ACIDException e) {
                    throw new Error(e);
                }
            }

        };
    }
}

redpajama_set_name: RedPajamaGithub


text:
define("frmClustered", function() {
    return function(controller) {
        function addWidgetsfrmClustered() {
            this.setDefaultUnit(kony.flex.DP);
            var zMap = new kony.ui.Map({
                "calloutWidth": 80,
                "defaultPinImage": "map_pin_red.png",
                "height": "100%",
                "id": "zMap",
                "isVisible": true,
                "left": "0dp",
                "onBoundsChanged": controller.AS_Map_f53548ec300c4e5aa660cd83714c3f73,
                "provider": constants.MAP_PROVIDER_GOOGLE,
                "top": "0dp",
                "width": "100%",
                "zIndex": 1
            }, {}, {
                "mapSource": constants.MAP_SOURCE_NON_NATIVE,
                "mode": constants.MAP_VIEW_MODE_NORMAL
            });
            var headerContainer08 = new kony.ui.FlexContainer({
                "clipBounds": true,
                "height": "44dp",
                "id": "headerContainer08",
                "isVisible": true,
                "layoutType": kony.flex.FREE_FORM,
                "left": "0dp",
                "masterType": constants.MASTER_TYPE_USERWIDGET,
                "skin": "headerContainerSknMaster",
                "top": "0dp",
                "width": "100%",
                "zIndex": 1
            }, {}, {});
            headerContainer08.setDefaultUnit(kony.flex.DP);
            var headerTitleLabel = new kony.ui.Label({
                "centerX": "50%",
                "height": "100%",
                "id": "headerTitleLabel",
                "isVisible": true,
                "left": "72dp",
                "right": "72dp",
                "skin": "headerTitleSkinMaster",
                "text": "Clustered pins",
                "textStyle": {},
                "top": "0dp",
                "zIndex": 1
            }, {
                "contentAlignment": constants.CONTENT_ALIGN_CENTER,
                "padding": [0, 0, 0, 0],
                "paddingInPixel": false
            }, {
                "renderAsAnchor": false,
                "textCopyable": false
            });
            var headerIconLeft = new kony.ui.Label({
                "height": "100%",
                "id": "headerIconLeft",
                "isVisible": true,
                "left": "4dp",
                "skin": "headerBackIconSkin",
                "text": "",
                "textStyle": {},
                "top": "0dp",
                "width": kony.flex.USE_PREFFERED_SIZE,
                "zIndex": 1
            }, {
                "contentAlignment": constants.CONTENT_ALIGN_MIDDLE_LEFT,
                "padding": [0, 0, 0, 0],
                "paddingInPixel": false
            }, {
                "renderAsAnchor": false,
                "textCopyable": false
            });
            var headerButtonLeft = new kony.ui.Button({
                "focusSkin": "headerIconCartSkin",
                "height": "100%",
                "id": "headerButtonLeft",
                "isVisible": true,
                "left": "0dp",
                "onClick": controller.AS_Button_aabecf47499b45df9523d0a474118be7,
                "skin": "headerButtonBackSkin",
                "text": "Back",
                "top": "0dp",
                "width": "74dp",
                "zIndex": 1
            }, {
                "contentAlignment": constants.CONTENT_ALIGN_MIDDLE_LEFT,
                "displayText": true,
                "padding": [27, 0, 0, 0],
                "paddingInPixel": false
            }, {});
            headerContainer08.add(headerTitleLabel, headerIconLeft, headerButtonLeft);
            this.add(zMap, headerContainer08);
        };
        return [{
            "addWidgets": addWidgetsfrmClustered,
            "enabledForIdleTimeout": false,
            "id": "frmClustered",
            "layoutType": kony.flex.FREE_FORM,
            "needAppMenu": false,
            "postShow": controller.AS_Form_ba0b80951fb74cb79f380698464dfbc6,
            "skin": "frmskin"
        }, {
            "displayOrientation": constants.FORM_DISPLAY_ORIENTATION_PORTRAIT,
            "layoutType": kony.flex.FREE_FORM,
            "padding": [0, 0, 0, 0],
            "paddingInPixel": false
        }, {
            "retainScrollPosition": false
        }]
    }
});


text:
// Copyright (c) 2012, 2013 Pierre MOULON.

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "openMVG/robust_estimation/robust_estimator_lineKernel_test.hpp"
#include "openMVG/robust_estimation/robust_estimator_MaxConsensus.hpp"
#include "openMVG/robust_estimation/score_evaluator.hpp"

#include "openMVG/numeric/numeric.h"

#include "testing/testing.h"

using namespace openMVG;
using namespace openMVG::robust;

// Test without outlier
TEST(MaxConsensusLineFitter, OutlierFree) {

  Mat2X xy(2, 5);
  // y = 2x + 1
  xy << 1, 2, 3, 4,  5,
        3, 5, 7, 9, 11;

  // The base estimator
  LineKernel kernel(xy);

  // Check the best model that fit the most of the data
  //  in a robust framework (Max-consensus).
  std::vector<size_t> vec_inliers;
  Vec2 model = MaxConsensus(kernel,
    ScorerEvaluator<LineKernel>(0.3), &vec_inliers);
  EXPECT_NEAR(2.0, model[1], 1e-9);
  EXPECT_NEAR(1.0, model[0], 1e-9);
  CHECK_EQUAL(5, vec_inliers.size());
}

// Test without getting back the model
TEST(MaxConsensusLineFitter, OutlierFree_DoNotGetBackModel) {

  Mat2X xy(2, 5);
  // y = 2x + 1
  xy << 1, 2, 3, 4,  5,
        3, 5, 7, 9, 11;

  LineKernel kernel(xy);
  std::vector<size_t> vec_inliers;
  Vec2 model = MaxConsensus(kernel,
    ScorerEvaluator<LineKernel>(0.3), &vec_inliers);
  CHECK_EQUAL(5, vec_inliers.size());
}

// Test efficiency of MaxConsensus to find (inlier/outlier) in contamined data
TEST(MaxConsensusLineFitter, OneOutlier) {

  Mat2X xy(2, 6);
  // y = 2x + 1 with an outlier
  xy << 1, 2, 3, 4,  5, 100, // outlier!
        3, 5, 7, 9, 11, -123; // outlier!

  LineKernel kernel(xy);

  std::vector<size_t> vec_inliers;
  Vec2 model = MaxConsensus(kernel,
    ScorerEvaluator<LineKernel>(0.3), &vec_inliers);
  EXPECT_NEAR(2.0, model[1], 1e-9);
  EXPECT_NEAR(1.0, model[0], 1e-9);
  CHECK_EQUAL(5, vec_inliers.size());
}

// Critical test:
// Test if the robust estimator do not return inlier if too few point
// was given for an estimation.
TEST(MaxConsensusLineFitter, TooFewPoints) {

  Mat2X xy(2, 1);
  xy << 1,
        3;   // y = 2x + 1 with x = 1
  LineKernel kernel(xy);
  std::vector<size_t> vec_inliers;
  Vec2 model = MaxConsensus(kernel,
    ScorerEvaluator<LineKernel>(0.3), &vec_inliers);
  CHECK_EQUAL(0, vec_inliers.size());
}

// From a GT model :
//  Compute a list of point that fit the model.
//  Add white noise to given amount of points in this list.
//  Check that the number of inliers and the model are correct.
TEST(MaxConsensusLineFitter, RealisticCase) {

  const int NbPoints = 30;
  const int inlierPourcentAmount = 30; //works with 40
  Mat2X xy(2, NbPoints);

  Vec2 GTModel; // y = 2x + 1
  GTModel <<  -2.0, 6.3;

  //-- Build the point list according the given model
  for(int i = 0; i < NbPoints; ++i)  {
    xy.col(i) << i, (double)i*GTModel[1] + GTModel[0];
  }

  //-- Add some noise (for the asked percentage amount)
  int nbPtToNoise = (int) NbPoints*inlierPourcentAmount/100.0;
  vector<size_t> vec_samples; // Fit with unique random index
  UniformSample(nbPtToNoise, NbPoints, &vec_samples);
  for(size_t i = 0; i <vec_samples.size(); ++i)
  {
    const size_t randomIndex = vec_samples[i];
    //Additive random noise
    xy.col(randomIndex) << xy.col(randomIndex)(0)+rand()%2-3,
                           xy.col(randomIndex)(1)+rand()%8-6;
  }

  LineKernel kernel(xy);
  std::vector<size_t> vec_inliers;
  Vec2 model = MaxConsensus(kernel,
    ScorerEvaluator<LineKernel>(0.3), &vec_inliers);
  CHECK_EQUAL(NbPoints-nbPtToNoise, vec_inliers.size());
  EXPECT_NEAR(-2.0, model[0], 1e-9);
  EXPECT_NEAR( 6.3, model[1], 1e-9);
}

/* ************************************************************************* */
int main() { TestResult tr; return TestRegistry::runAllTests(tr);}
/* ************************************************************************* */


text:
<?php

namespace ZF\Apigility\Admin\Model;

use Zend\Filter\FilterChain;
use ZF\Hal\Collection as HalCollection;

class RestServiceEntity
{
    protected $acceptWhitelist = [
        'application/json',
        'application/*+json',
    ];

    protected $collectionClass;

    protected $collectionHttpMethods = ['GET', 'POST'];

    protected $collectionName;

    protected $collectionQueryWhitelist = [];

    protected $contentTypeWhitelist = [
        'application/json',
    ];

    protected $controllerServiceName;

    protected $documentation;

    protected $entityClass;

    protected $entityHttpMethods = ['GET', 'PATCH', 'PUT', 'DELETE'];

    protected $entityIdentifierName = 'id';

    protected $filters = [];

    protected $hydratorName = 'Zend\Hydrator\ArraySerializable';

    protected $inputFilters;

    protected $module;

    protected $pageSize = 25;

    protected $pageSizeParam;

    protected $resourceClass;

    protected $routeIdentifierName;

    protected $routeMatch;

    protected $routeName;

    protected $selector = 'HalJson';

    protected $serviceName;

    public function __get($name)
    {
        if ($name === 'filter') {
            throw new \OutOfRangeException(sprintf(
                '%s does not contain a property by the name of "%s"',
                __CLASS__,
                $name
            ));
        }

        /**
         * @todo Remove this prior to 1.0; BC fix implemented prior to 0.9.0
         */
        if ($name === 'resourceHttpMethods') {
            $name = 'entityHttpMethods';
        }

        if (!property_exists($this, $name)) {
            throw new \OutOfRangeException(sprintf(
                '%s does not contain a property by the name of "%s"',
                __CLASS__,
                $name
            ));
        }
        return $this->{$name};
    }

    public function __isset($name)
    {
        if ($name === 'filter') {
            return false;
        }

        /**
         * @todo Remove this prior to 1.0; BC fix implemented prior to 0.9.0
         */
        if ($name === 'resourceHttpMethods') {
            $name = 'entityHttpMethods';
        }

        return (property_exists($this, $name));
    }

    public function exchangeArray(array $data)
    {
        $legacyIdentifierName = false;
        foreach ($data as $key => $value) {
            $key = strtolower($key);
            $key = str_replace('_', '', $key);
            switch ($key) {
                case 'acceptwhitelist':
                    $this->acceptWhitelist = $value;
                    break;
                case 'collectionclass':
                    $this->collectionClass = $value;
                    break;
                case 'collectionhttpmethods':
                    $this->collectionHttpMethods = $value;
                    break;
                case 'collectionname':
                    $this->collectionName = $value;
                    break;
                case 'collectionquerywhitelist':
                    $this->collectionQueryWhitelist = $value;
                    break;
                case 'contenttypewhitelist':
                    $this->contentTypeWhitelist = $value;
                    break;
                case 'controllerservicename':
                    $this->controllerServiceName = $value;
                    break;
                case 'entityclass':
                    $this->entityClass = $value;
                    break;
                case 'entityhttpmethods':
                    $this->entityHttpMethods = $value;
                    break;
                case 'entityidentifiername':
                    $this->entityIdentifierName = $value;
                    break;
                case 'hydratorname':
                    $this->hydratorName = $value;
                    break;
                case 'identifiername':
                    $legacyIdentifierName = $value;
                    break;
                case 'inputfilters':
                    if ($value instanceof InputFilterCollection
                        || $value instanceof HalCollection
                    ) {
                        $this->inputFilters = $value;
                    }
                    break;
                case 'documentation':
                    $this->documentation = $value;
                    break;
                case 'module':
                    $this->module = $value;
                    break;
                case 'pagesize':
                    $this->pageSize = $value;
                    break;
                case 'pagesizeparam':
                    $this->pageSizeParam = $value;
                    break;
                case 'resourceclass':
                    $this->resourceClass = $value;
                    break;
                case 'resourcehttpmethods':
                    $this->entityHttpMethods = $value;
                    break;
                case 'routeidentifiername':
                    $this->routeIdentifierName = $value;
                    break;
                case 'routematch':
                    $this->routeMatch = $value;
                    break;
                case 'routename':
                    $this->routeName = $value;
                    break;
                case 'selector':
                    $this->selector = $value;
                    break;
                case 'servicename':
                    $this->serviceName = $value;
                    break;
            }
        }

        if ($legacyIdentifierName && ! $this->routeIdentifierName) {
            $this->routeIdentifierName = $legacyIdentifierName;
        }

        if ($legacyIdentifierName && ! $this->entityIdentifierName) {
            $this->entityIdentifierName = $legacyIdentifierName;
        }
    }

    public function getArrayCopy()
    {
        $array = [
            'accept_whitelist'           => $this->acceptWhitelist,
            'collection_class'           => $this->collectionClass,
            'collection_http_methods'    => $this->collectionHttpMethods,
            'collection_name'            => $this->collectionName,
            'collection_query_whitelist' => $this->collectionQueryWhitelist,
            'content_type_whitelist'     => $this->contentTypeWhitelist,
            'controller_service_name'    => $this->controllerServiceName,
            'entity_class'               => $this->entityClass,
            'entity_http_methods'        => $this->entityHttpMethods,
            'entity_identifier_name'     => $this->entityIdentifierName,
            'hydrator_name'              => $this->hydratorName,
            'module'                     => $this->module,
            'page_size_param'            => $this->pageSizeParam,
            'page_size'                  => $this->pageSize,
            'resource_class'             => $this->resourceClass,
            'route_identifier_name'      => $this->routeIdentifierName,
            'route_match'                => $this->routeMatch,
            'route_name'                 => $this->routeName,
            'selector'                   => $this->selector,
            'service_name'               => $this->serviceName,
        ];
        if (null !== $this->inputFilters) {
            $array['input_filters'] = $this->inputFilters;
        }
        if (null !== $this->documentation) {
            $array['documentation'] = $this->documentation;
        }
        return $array;
    }

    protected function normalizeServiceNameForIdentifier($serviceName)
    {
        return $this->getIdentifierNormalizationFilter()->filter($serviceName);
    }

    protected function normalizeServiceNameForRoute($serviceName)
    {
        return $this->getRouteNormalizationFilter()->filter($serviceName);
    }

    /**
     * Retrieve and/or initialize the normalization filter chain for identifiers
     *
     * @return FilterChain
     */
    protected function getIdentifierNormalizationFilter()
    {
        if (isset($this->filters['identifier'])
            && $this->filters['identifier'] instanceof FilterChain
        ) {
            return $this->filters['identifier'];
        }
        $filter = new FilterChain();
        $filter->attachByName('WordCamelCaseToUnderscore')
               ->attachByName('StringToLower');
        $this->filters['identifier'] = $filter;
        return $filter;
    }

    /**
     * Retrieve and/or initialize the normalization filter chain
     *
     * @return FilterChain
     */
    protected function getRouteNormalizationFilter()
    {
        if (isset($this->filters['route'])
            && $this->filters['route'] instanceof FilterChain
        ) {
            return $this->filters['route'];
        }
        $filter = new FilterChain();
        $filter->attachByName('WordCamelCaseToDash')
               ->attachByName('StringToLower');
        $this->filters['route'] = $filter;
        return $filter;
    }
}


text:
<?php
	class dynamic_table_block_handler extends block_handler{

        function info()
        {
            $info['category_name'] = "Bootstrap";
            $info['category_icon'] = "dsf";

            $info['block_name'] = "Dynamic Table";
            $info['block_icon'] = "fa-envelope-o";

            return $info;
        }
        public function generate_admin()
        {
			$rows = $this->block->data('rows');
			$cols = $this->block->data('cols');
			$titles = $this->block->data('titles');
			$fields = $this->block->data('fields');
			?>

Summary

Column titles

Data Fields

							<?php
								$this->admin_input('rows','text', 'Rows: ', $rows);
								$this->admin_input('cols','text', 'Columns: ', $cols);
							?>

							<?php
							for($i=0;$i<$cols;$i++){
								$this->admin_input('titles['.$i.']','text', 'Column '.$num = $i+1 .': ', $titles[$i]);
							}
							?>

							<?php $f=0;
							for($i=0;$i<$rows;$i++){
								for($j=0;$j<$cols;$j++){
									$this->admin_input('fields['.$f.']','text', 'Row '.$frow = $i+1 .' Col '.$fcol = $j+1 .': ', $fields[$f]);
									$f++;
								}
								$f++;
							}
							?>

			<?php
        }
        public function generate_style()
        {
			$path = substr($_SERVER['SCRIPT_FILENAME'],0,strrpos($_SERVER['SCRIPT_FILENAME'],'/index.php'));
			include $path.'/builderengine/public/animations/animations.php';

			$animation_type = $this->block->data('animation_type');
		    $animation_duration = $this->block->data('animation_duration');
		    $animation_event = $this->block->data('animation_event');
		    $animation_delay = $this->block->data('animation_delay');

			$this->admin_select('animation_type', $types,'Animation type: ',$animation_type);
			$this->admin_select('animation_duration', $durations,'Animation duration: ',$animation_duration);
			$this->admin_select('animation_event', $events,'Animation Start: ',$animation_event);
			$this->admin_select('animation_delay', $delays,'Animation Delay: ',$animation_delay);
			$custom_css = $this->block->data('custom_css');
			$custom_classes = $this->block->data('custom_classes');
			$this->admin_textarea('custom_css','Custom CSS: ', $custom_css, 4);
			$this->admin_textarea('custom_classes','Custom Classes: ', $custom_classes, 2);
        }
        public function generate_content()
        {
			global $active_controller;
			$CI = &get_instance();
			$CI->load->module('layout_system');

			$custom_css = $this->block->data('custom_css');
			$style_arr['text'] = ';'.$custom_css;
			$this->block->set_data("style", $style_arr);

			$animation_type = $this->block->data('animation_type');
		    $animation_duration = $this->block->data('animation_duration');
		    $animation_event = $this->block->data('animation_event');
		    $animation_delay = $this->block->data('animation_delay');

			$settings[0][0] = 'dyntable'.$this->block->get_id();
			$settings[0][1] = $animation_event;
			$settings[0][2] = $animation_duration.' '.$animation_delay.' '.$animation_type;
			add_action("be_foot", generate_animation_events($settings));

			$rows = $this->block->data('rows');
			$cols = $this->block->data('cols');
			$titles = $this->block->data('titles');
			$fields = $this->block->data('fields');
			$this->block->force_data_modification();

			$output = '
						<link href="'.base_url('builderengine/public/animations/css/animate.min.css').'" rel="stylesheet" />

block->get_id().'" class="table table-striped table-hover table-bordered">

								#	';
									for($z=0;$z<$cols;$z++){
										$output .=''.$titles[$z] .'	';
									}
				$output .=	'
';
								$f=0;
								for($i=0;$i<$rows;$i++){
									$output .= '
';
									$output .=''.$num = $i+1 .'	';
									for($j=0;$j<$cols;$j++){
										$output .=''.$fields[$f].'	';
										$f++;
									}
									$f++;
									$output .='
';
								}
			$output .= '
';

			return $output.$CI->layout_system->load_new_block_scripts($this->block->get_id(), 'dyntable'.$this->block->get_id(), $CI->BuilderEngine->get_page_path(), '', $this->block->get_name(), 'with_settings');
        }
    }
?>


text:
package com.anaplan.client.transport;

import com.anaplan.client.dto.Paging;
import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * Created by Spondon Saha
 * User: spondonsaha
 * Date: 6/26/17
 * Time: 11:32 AM
 */
public abstract class Paginator<ENTITY> implements Iterable<ENTITY> {

    private Paging pageInfo;
    private int currentIndex = 0;
    private ENTITY[] entities;

    public Paginator() {
        setEntities(getPage(0));
    }

    public abstract ENTITY[] getPage(int offset);

    @Override
    public Iterator<ENTITY> iterator() {
        return new Iterator<ENTITY>() {
            @Override
            public boolean hasNext() {
                return currentIndex + pageInfo.getOffset() < pageInfo.getTotalSize();
            }

            @Override
            public ENTITY next() {
                if (hasNext()) {
                    if (currentIndex == entities.length) {
                        entities = getPage(pageInfo.getOffset() + pageInfo.getCurrentPageSize());
                        currentIndex = 0;
                    }
                    return entities[currentIndex++];
                }
                throw new NoSuchElementException();
            }
        };
    }

    public Paging getPageInfo() {
        return pageInfo;
    }

    public void setPageInfo(Paging pageInfo) {
        this.pageInfo = pageInfo;
    }

    public void setEntities(ENTITY[] entities) {
        this.entities = entities;
    }
}


text:
{% extends "my_ummeli_base.html" %}

{% block content %}

Home » My Ummeli » Work Profile » Personal Details

Personal Details

    <form class='content-form' method="post">
    <fieldset>
        First name: *
        {% include "form_field_errors_snippet.html" with form_field=form.first_name %}
        <input name="first_name" type="text" class="txt" value="{{form.first_name.value}}"/>

        Surname:
        {% include "form_field_errors_snippet.html" with form_field=form.surname %}
        <input name="surname" type="text" class="txt" value="{{form.surname.value}}"/>

        Date of birth:
        {% include "form_field_errors_snippet.html" with form_field=form.date_of_birth %}
        <input name="date_of_birth" type="text" class="txt" value="{% if form.date_of_birth.value %}{{form.date_of_birth.value}}{% endif %}"/>

        Gender:
        {% include "form_field_errors_snippet.html" with form_field=form.gender %}

        {% if not form.gender.value or form.gender.value.lower == 'male' or form.gender.value.lower == 'm' %}
        <input type="radio" name="gender" value="Male" checked="checked"/> Male

        <input type="radio" name="gender" value="Female" /> Female

        {% else %}
        <input type="radio" name="gender" value="Male"/> Male

        <input type="radio" name="gender" value="Female" checked="checked"/> Female

        {% endif %}

        <input type="submit" class="btn" value="Save" name="submit" />
        {% csrf_token %}
    </fieldset>
    </form>

← Back

{% endblock %}


text:
package javasmmr.zoowsome.models.animals;

public abstract class Aquatic extends Animal {

	int avgSwimDepth;
	boolean isDangerous;

	public Aquatic(double cost, double danger) {
		super(cost, danger);
	}

	public void setAvgSwimDepth(int depth) {
		avgSwimDepth = depth;
	}

	public int getAvgSwimDepth() {
		return avgSwimDepth;
	}

	public void setIsDangerous(boolean dangerous) {
		isDangerous = dangerous;
	}

	public boolean getIsDangerous() {
		return isDangerous;
	}

}


text: sudo sslocal -c ./shadowsocks.json -d start


text:
package tec.application.jwm;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

public class Index extends Fragment {
	ImageView ivIcon;
	TextView tvItemName;
	public static final String IMAGE_RESOURCE_ID="iconResourceID";
	public static final String ITEM_NAME="itemName";

	public Index(){}

	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {

          View view = inflater.inflate(R.layout.fragment_index, container,
                      false);

          ivIcon = (ImageView) view.findViewById(R.id.frag_index_icon);
          tvItemName = (TextView) view.findViewById(R.id.frag_index_text);

          tvItemName.setText(getArguments().getString(ITEM_NAME));
          ivIcon.setImageDrawable(view.getResources().getDrawable(
                      getArguments().getInt(IMAGE_RESOURCE_ID)));
          return view;
    }

}


text:
//==================================================
// Copyright (c) 2015 Deividas Kazlauskas
//
// See the file license.txt for copying permission.
//==================================================

#ifndef VIRTUALMATCHFUNCTOR_695UA513
#define VIRTUALMATCHFUNCTOR_695UA513

#include <utility>
#include <memory>

#include <templatious/detail/TypeList.hpp>
#include <templatious/detail/VirtualPack.hpp>

namespace templatious {

TEMPLATIOUS_BOILERPLATE_EXCEPTION(
    VirtualPackMatcherNoMatchException,
    "No virtual matcher could handle the message."
);

/**
 * Main purpose of this class
 * is to match virtual packs
 * to functions by their types
 * at runtime with typesafety.
 */
struct VirtualMatchFunctor {

    /**
     * Try to match VirtualPack. Returns true
     * if matched, false otherwise.
     *
     * @param[in] p Virtual pack to match.
     *
     * Example:
     * ~~~~~~~
     * auto vmf = SF::virtualMatchFunctorPtr(
     *     SF::virtualMatch<int>(
     *         [](int i) {
     *             std::cout << "INT MATCHED - "
     *                       << i << std::endl;
     *         }
     *     ),
     *     SF::virtualMatch<char>(
     *         [](char i) {
     *             std::cout << "CHAR MATCHED - "
     *                       << i << std::endl;
     *         }
     *     )
     * );
     *
     * auto p1 = SF::vpack<int>(40);
     * auto p2 = SF::vpack<char>('7');
     * auto p3 = SF::vpack<long>(7);
     *
     * bool aMatch = vmf->tryMatch(p1);
     * bool bMatch = vmf->tryMatch(p2);
     * bool cMatch = vmf->tryMatch(p3);
     *
     * // prints out:
     * // INT MATCHED - 40
     * // CHAR MATCHED - 7
     *
     * assert( aMatch);
     * assert( bMatch);
     * assert(!cMatch);
     * ~~~~~~~
     */
    virtual bool tryMatch(VirtualPack& p) = 0;

    /**
     * Try to match VirtualPack. Returns true
     * if matched, false otherwise.
     *
     * @param[in] p Virtual pack to match.
     *
     * Example:
     * ~~~~~~~
     * auto vmf = SF::virtualMatchFunctorPtr(
     *     SF::virtualMatch<int>(
     *         [](int i) {
     *             std::cout << "INT MATCHED - "
     *                       << i << std::endl;
     *         }
     *     ),
     *     SF::virtualMatch<char>(
     *         [](char i) {
     *             std::cout << "CHAR MATCHED - "
     *                       << i << std::endl;
     *         }
     *     )
     * );
     *
     * auto p1 = SF::vpack<int>(40);
     * auto p2 = SF::vpack<char>('7');
     * auto p3 = SF::vpack<long>(7);
     *
     * bool aMatch = vmf->tryMatch(p1);
     * bool bMatch = vmf->tryMatch(p2);
     * bool cMatch = vmf->tryMatch(p3);
     *
     * // prints out:
     * // INT MATCHED - 40
     * // CHAR MATCHED - 7
     *
     * assert( aMatch);
     * assert( bMatch);
     * assert(!cMatch);
     * ~~~~~~~
     */
    virtual bool tryMatch(const VirtualPack& p) = 0;

    /**
     * Try to match VirtualPack. Returns true
     * if matched, false otherwise.
     *
     * @param[in] p Virtual pack to match.
     *
     * Example:
     * ~~~~~~~
     * auto vmf = SF::virtualMatchFunctorPtr(
     *     SF::virtualMatch<int>(
     *         [](int i) {
     *             std::cout << "INT MATCHED - "
     *                       << i << std::endl;
     *         }
     *     ),
     *     SF::virtualMatch<char>(
     *         [](char i) {
     *             std::cout << "CHAR MATCHED - "
     *                       << i << std::endl;
     *         }
     *     )
     * );
     *
     * auto p1 = SF::vpack<int>(40);
     * auto p2 = SF::vpack<char>('7');
     * auto p3 = SF::vpack<long>(7);
     *
     * bool aMatch = vmf->tryMatch(p1);
     * bool bMatch = vmf->tryMatch(p2);
     * bool cMatch = vmf->tryMatch(p3);
     *
     * // prints out:
     * // INT MATCHED - 40
     * // CHAR MATCHED - 7
     *
     * assert( aMatch);
     * assert( bMatch);
     * assert(!cMatch);
     * ~~~~~~~
     */
    virtual bool tryMatch(VirtualPack& p) const = 0;

    /**
     * Try to match VirtualPack. Returns true
     * if matched, false otherwise.
     *
     * @param[in] p Virtual pack to match.
     *
     * Example:
     * ~~~~~~~
     * auto vmf = SF::virtualMatchFunctorPtr(
     *     SF::virtualMatch<int>(
     *         [](int i) {
     *             std::cout << "INT MATCHED - "
     *                       << i << std::endl;
     *         }
     *     ),
     *     SF::virtualMatch<char>(
     *         [](char i) {
     *             std::cout << "CHAR MATCHED - "
     *                       << i << std::endl;
     *         }
     *     )
     * );
     *
     * auto p1 = SF::vpack<int>(40);
     * auto p2 = SF::vpack<char>('7');
     * auto p3 = SF::vpack<long>(7);
     *
     * bool aMatch = vmf->tryMatch(p1);
     * bool bMatch = vmf->tryMatch(p2);
     * bool cMatch = vmf->tryMatch(p3);
     *
     * // prints out:
     * // INT MATCHED - 40
     * // CHAR MATCHED - 7
     *
     * assert( aMatch);
     * assert( bMatch);
     * assert(!cMatch);
     * ~~~~~~~
     */
    virtual bool tryMatch(const VirtualPack& p) const = 0;

    /**
     * Match VirtualPack. Throws an exception
     * if pack couldn't be matched.
     *
     * @param[in] p Virtual pack to match.
     *
     * Example:
     * ~~~~~~~
     * auto vmf = SF::virtualMatchFunctorPtr(
     *     SF::virtualMatch<int>(
     *         [](int i) {
     *             std::cout << "INT MATCHED - "
     *                       << i << std::endl;
     *         }
     *     ),
     *     SF::virtualMatch<char>(
     *         [](char i) {
     *             std::cout << "CHAR MATCHED - "
     *                       << i << std::endl;
     *         }
     *     )
     * );
     *
     * auto p1 = SF::vpack<int>(40);
     * auto p2 = SF::vpack<char>('7');
     * auto p3 = SF::vpack<long>(7);
     *
     * (*vmf)(p1);
     * (*vmf)(p2);
     * (*vmf)(p3);
     *
     * // prints out:
     * // INT MATCHED - 40
     * // CHAR MATCHED - 7
     * // throws...
     * ~~~~~~~
     */
    virtual void operator()(VirtualPack& p) {
        if (!this->tryMatch(p)) {
            throw VirtualPackMatcherNoMatchException();
        }
    }

    /**
     * Match VirtualPack. Throws an exception
     * if pack couldn't be matched.
     *
     * @param[in] p Virtual pack to match.
     *
     * Example:
     * ~~~~~~~
     * auto vmf = SF::virtualMatchFunctorPtr(
     *     SF::virtualMatch<int>(
     *         [](int i) {
     *             std::cout << "INT MATCHED - "
     *                       << i << std::endl;
     *         }
     *     ),
     *     SF::virtualMatch<char>(
     *         [](char i) {
     *             std::cout << "CHAR MATCHED - "
     *                       << i << std::endl;
     *         }
     *     )
     * );
     *
     * auto p1 = SF::vpack<int>(40);
     * auto p2 = SF::vpack<char>('7');
     * auto p3 = SF::vpack<long>(7);
     *
     * (*vmf)(p1);
     * (*vmf)(p2);
     * (*vmf)(p3);
     *
     * // prints out:
     * // INT MATCHED - 40
     * // CHAR MATCHED - 7
     * // throws...
     * ~~~~~~~
     */
    virtual void operator()(const VirtualPack& p) {
        if (!this->tryMatch(p)) {
            throw VirtualPackMatcherNoMatchException();
        }
    }

    /**
     * Match VirtualPack. Throws an exception
     * if pack couldn't be matched.
     *
     * @param[in] p Virtual pack to match.
     *
     * Example:
     * ~~~~~~~
     * auto vmf = SF::virtualMatchFunctorPtr(
     *     SF::virtualMatch<int>(
     *         [](int i) {
     *             std::cout << "INT MATCHED - "
     *                       << i << std::endl;
     *         }
     *     ),
     *     SF::virtualMatch<char>(
     *         [](char i) {
     *             std::cout << "CHAR MATCHED - "
     *                       << i << std::endl;
     *         }
     *     )
     * );
     *
     * auto p1 = SF::vpack<int>(40);
     * auto p2 = SF::vpack<char>('7');
     * auto p3 = SF::vpack<long>(7);
     *
     * (*vmf)(p1);
     * (*vmf)(p2);
     * (*vmf)(p3);
     *
     * // prints out:
     * // INT MATCHED - 40
     * // CHAR MATCHED - 7
     * // throws...
     * ~~~~~~~
     */
    virtual void operator()(VirtualPack& p) const {
        if (!this->tryMatch(p)) {
            throw VirtualPackMatcherNoMatchException();
        }
    }

    /**
     * Match VirtualPack. Throws an exception
     * if pack couldn't be matched.
     *
     * @param[in] p Virtual pack to match.
     *
     * Example:
     * ~~~~~~~
     * auto vmf = SF::virtualMatchFunctorPtr(
     *     SF::virtualMatch<int>(
     *         [](int i) {
     *             std::cout << "INT MATCHED - "
     *                       << i << std::endl;
     *         }
     *     ),
     *     SF::virtualMatch<char>(
     *         [](char i) {
     *             std::cout << "CHAR MATCHED - "
     *                       << i << std::endl;
     *         }
     *     )
     * );
     *
     * auto p1 = SF::vpack<int>(40);
     * auto p2 = SF::vpack<char>('7');
     * auto p3 = SF::vpack<long>(7);
     *
     * (*vmf)(p1);
     * (*vmf)(p2);
     * (*vmf)(p3);
     *
     * // prints out:
     * // INT MATCHED - 40
     * // CHAR MATCHED - 7
     * // throws...
     * ~~~~~~~
     */
    virtual void operator()(const VirtualPack& p) const {
        if (!this->tryMatch(p)) {
            throw VirtualPackMatcherNoMatchException();
        }
    }

    virtual ~VirtualMatchFunctor() {}
};

template <
    class F,
    bool transparent,
    template <class> class StoragePolicy,
    class... Args
>
struct VirtualMatch {
    typedef typename StoragePolicy<F>::Container Cont;
    typedef VirtualMatch<
        F,
        transparent,
        StoragePolicy,
        Args...
    > ThisMatch;

    typedef TypeList< Args... > TheList;
    static const bool allConst = TheList::
        template ForAll< std::is_const >::value;

    static const bool isTransparent = transparent;

    template <class Function>
    VirtualMatch(Function&& f) :
        _hash(templatious::util::hashTypes<Args...>()),
        _cf(std::forward<Function>(f)) {}

    VirtualMatch(ThisMatch&& other) :
        _hash(other._hash),
        _cf(other._cf.cpy()) {}

    VirtualMatch(const ThisMatch& other) :
        _hash(other._hash),
        _cf(other._cf.constCpy()) {}

    template <bool consts = allConst>
    typename std::enable_if< consts, bool >::type
    operator()(const VirtualPack& vp) {
        return vp.tryCallFunction<Args...>(_cf.getRef())
            && !isTransparent;
    }

    template <bool consts = allConst>
    typename std::enable_if< consts, bool >::type
    operator()(const VirtualPack& vp) const {
        return vp.tryCallFunction<Args...>(_cf.cgetRef())
            && !isTransparent;
    }

    // if we receive const but we know
    // we're not asking const just return false
    template <bool consts = allConst>
    typename std::enable_if< !consts, bool >::type
    operator()(const VirtualPack& vp) {
        return false;
    }

    // if we receive const but we know
    // we're not asking const just return false
    template <bool consts = allConst>
    typename std::enable_if< !consts, bool >::type
    operator()(const VirtualPack& vp) const {
        return false;
    }

    template <bool consts = allConst>
    typename std::enable_if< !consts, bool >::type
    operator()(VirtualPack& vp) {
        return vp.tryCallFunction<Args...>(_cf.getRef())
            && !isTransparent;
    }

    template <bool consts = allConst>
    typename std::enable_if< !consts, bool >::type
    operator()(VirtualPack& vp) const {
        return vp.tryCallFunction<Args...>(_cf.cgetRef())
            && !isTransparent;
    }

    size_t getHash() const {
        return _hash;
    }

private:
    size_t _hash;
    Cont _cf;
};

template <class T>
struct IsVirtualMatch {
    static const bool value = false;
};

template <
    class F,
    bool transparent,
    template <class> class StoragePolicy,
    class... Args
>
struct IsVirtualMatch<
    VirtualMatch<
        F, transparent, StoragePolicy, Args...
    >
>
{
    static const bool value = true;
};

template <>
struct IsVirtualMatch<
    std::unique_ptr< VirtualMatchFunctor >
>
{
    static const bool value = true;
};

template <
    template <class> class StoragePolicy,
    class... Args
>
struct VirtualMatchFunctorImpl;

struct ExpVmfConInvoke {};

template <
    template <class> class StoragePolicy,
    class... Args
>
struct IsVirtualMatch<
    VirtualMatchFunctorImpl<
        StoragePolicy,
        Args...
    >
> {
    static const bool value = true;
};

struct SingleMatchCalls {
    template <class M,class V>
    static bool tryMatch(M&& m,V&& v) {
        if (v.getHash() != m.getHash()) {
            return false;
        }

        return m(std::forward<V>(v));
    }
};

struct VirtualMatchFunctorCalls {
    template <class M,class V>
    static bool tryMatch(M&& m,V&& v) {
        return m.tryMatch(std::forward<V>(v));
    }
};

struct VirtualMatchFunctorPtrCalls {
    template <class V>
    static bool tryMatch(std::unique_ptr< VirtualMatchFunctor >& m,V&& v) {
        return m->tryMatch(std::forward<V>(v));
    }

    template <class V>
    static bool tryMatch(const std::unique_ptr< VirtualMatchFunctor >& m,V&& v) {
        return m->tryMatch(std::forward<V>(v));
    }
};

template <class T>
struct VMatchFunctorCallHndl {
    typedef void CallHandler;
};

template <
    class F,
    bool transparent,
    template <class> class StoragePolicy,
    class... Args
>
struct VMatchFunctorCallHndl<
    VirtualMatch<
        F, transparent, StoragePolicy, Args...
    >
>
{
    typedef SingleMatchCalls CallHandler;
};

template <
    template <class> class StoragePolicy,
    class... Args
>
struct VMatchFunctorCallHndl<
    VirtualMatchFunctorImpl<
        StoragePolicy,
        Args...
    >
> {
    typedef VirtualMatchFunctorCalls CallHandler;
};

template <>
struct VMatchFunctorCallHndl<
    std::unique_ptr<
        VirtualMatchFunctor
    >
> {
    typedef VirtualMatchFunctorPtrCalls CallHandler;
};

template <
    template <class> class StoragePolicy,
    class... Args
>
struct VirtualMatchFunctorVImpl : public VirtualMatchFunctor {
    typedef VirtualMatchFunctorImpl<
        StoragePolicy, Args... > Impl;

    template <class... V>
    explicit VirtualMatchFunctorVImpl(V&&... v)
        : _impl(ExpVmfConInvoke(),std::forward<V>(v)...) {}

    bool tryMatch(VirtualPack& p) override {
        return _impl.tryMatch(p);
    }

    bool tryMatch(const VirtualPack& p) override {
        return _impl.tryMatch(p);
    }

    bool tryMatch(VirtualPack& p) const override {
        return _impl.tryMatch(p);
    }

    bool tryMatch(const VirtualPack& p) const override {
        return _impl.tryMatch(p);
    }

    Impl _impl;
};

template <
    template <class> class StoragePolicy,
    class Head,class... Tail
>
struct VirtualMatchFunctorImpl< StoragePolicy, Head, Tail... > {
    typedef typename std::decay< Head >::type DecHead;
    typedef typename StoragePolicy<Head>::Container Container;
    typedef VirtualMatchFunctorImpl< StoragePolicy, Tail... > TailFunct;
    typedef VirtualMatchFunctorImpl< StoragePolicy, Head, Tail... > ThisImpl;

    static const bool can_copy =
        std::is_copy_constructible< ThisImpl >::value;

    static const bool doesMatch = IsVirtualMatch< DecHead >::value;
    static_assert(doesMatch,
        "Class does not belong in a VirtualMatchFunctorImpl.");

    typedef typename VMatchFunctorCallHndl<
        DecHead >::CallHandler Caller;

    template <class A,class... V>
    explicit VirtualMatchFunctorImpl(
        const ExpVmfConInvoke& i,A&& a,V&&... v) :
        _c(std::forward<A>(a)),
        _t(i,std::forward<V>(v)...) {}

    template <bool canCpy = can_copy>
    VirtualMatchFunctorImpl(
        typename std::enable_if<canCpy,const ThisImpl&>::type impl)
        : _c(impl._c), _t(impl._t) {}

    VirtualMatchFunctorImpl(ThisImpl&& impl)
        : _c(std::move(impl._c)), _t(std::move(impl._t)) {}

    bool tryMatch(VirtualPack& p) {
        if (Caller::tryMatch(_c.getRef(),p)) {
            return true;
        }

        return _t.tryMatch(p);
    }

    bool tryMatch(const VirtualPack& p) {
        if (Caller::tryMatch(_c.getRef(),p)) {
            return true;
        }

        return _t.tryMatch(p);
    }

    bool tryMatch(VirtualPack& p) const {
        if (Caller::tryMatch(_c.cgetRef(),p)) {
            return true;
        }

        return _t.tryMatch(p);
    }

    bool tryMatch(const VirtualPack& p) const {
        if (Caller::tryMatch(_c.cgetRef(),p)) {
            return true;
        }

        return _t.tryMatch(p);
    }

private:
    Container _c;
    TailFunct _t;
};

template <
    template <class> class StoragePolicy,
    class Head
>
struct VirtualMatchFunctorImpl< StoragePolicy, Head > {
    typedef typename std::decay< Head >::type DecHead;
    typedef typename StoragePolicy<Head>::Container Container;
    typedef VirtualMatchFunctorImpl< StoragePolicy, Head > ThisImpl;

    static const bool can_copy =
        std::is_copy_constructible< ThisImpl >::value;

    static const bool doesMatch = IsVirtualMatch< DecHead >::value;
    static_assert(doesMatch,
        "Class does not belong in a VirtualMatchFunctorImpl.");

    typedef typename VMatchFunctorCallHndl<
        DecHead >::CallHandler Caller;

    template <class A>
    explicit VirtualMatchFunctorImpl(
        const ExpVmfConInvoke&,A&& a) :
        _c(std::forward<A>(a)) {}

    VirtualMatchFunctorImpl(ThisImpl&& impl) :
        _c(std::move(impl._c)) {}

    template <bool canCpy = can_copy>
    VirtualMatchFunctorImpl(
        typename std::enable_if<canCpy,const ThisImpl&>::type impl) :
        _c(impl._c) {}

    bool tryMatch(VirtualPack& p) {
        return Caller::tryMatch(_c.getRef(),p);
    }

    bool tryMatch(const VirtualPack& p) {
        return Caller::tryMatch(_c.getRef(),p);
    }

    bool tryMatch(VirtualPack& p) const {
        return Caller::tryMatch(_c.cgetRef(),p);
    }

    bool tryMatch(const VirtualPack& p) const {
        return Caller::tryMatch(_c.cgetRef(),p);
    }

private:
    Container _c;
};

}

#endif /* end of include guard: VIRTUALMATCHFUNCTOR_695UA513 */


text:
<?xml version="1.0" encoding="utf-8"?>
<TextView
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/title"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_marginTop="@dimen/margin_base"
  android:layout_marginLeft="@dimen/margin_half_plus"
  android:layout_marginStart="@dimen/margin_half_plus"
  android:layout_marginRight="@dimen/margin_half_plus"
  android:layout_marginEnd="@dimen/margin_half_plus"
  android:layout_marginBottom="@dimen/margin_double_and_half"
  android:textAppearance="@style/MwmTextAppearance.Body3"
  android:fontFamily="@string/robotoMedium"
  android:lines="2"
  tools:targetApi="jelly_bean"
  tools:showIn="@layout/item_discovery_simple_loading"/>


text:
require "active_support/core_ext/numeric/time"

module ActiveJob
  # Provides behavior for retrying and discarding jobs on exceptions.
  module Exceptions
    extend ActiveSupport::Concern

    module ClassMethods
      # Catch the exception and reschedule job for re-execution after so many seconds, for a specific number of attempts.
      # If the exception keeps getting raised beyond the specified number of attempts, the exception is allowed to
      # bubble up to the underlying queuing system, which may have its own retry mechanism or place it in a
      # holding queue for inspection.
      #
      # You can also pass a block that'll be invoked if the retry attempts fail for custom logic rather than letting
      # the exception bubble up. This block is yielded with the job instance as the first and the error instance as the second parameter.
      #
      # ==== Options
      # * <tt>:wait</tt> - Re-enqueues the job with a delay specified either in seconds (default: 3 seconds),
      #   as a computing proc that the number of executions so far as an argument, or as a symbol reference of
      #   <tt>:exponentially_longer</tt>, which applies the wait algorithm of <tt>(executions ** 4) + 2</tt>
      #   (first wait 3s, then 18s, then 83s, etc)
      # * <tt>:attempts</tt> - Re-enqueues the job the specified number of times (default: 5 attempts)
      # * <tt>:queue</tt> - Re-enqueues the job on a different queue
      # * <tt>:priority</tt> - Re-enqueues the job with a different priority
      #
      # ==== Examples
      #
      #  class RemoteServiceJob < ActiveJob::Base
      #    retry_on CustomAppException # defaults to 3s wait, 5 attempts
      #    retry_on AnotherCustomAppException, wait: ->(executions) { executions * 2 }
      #    retry_on(YetAnotherCustomAppException) do |job, exception|
      #      ExceptionNotifier.caught(exception)
      #    end
      #    retry_on ActiveRecord::Deadlocked, wait: 5.seconds, attempts: 3
      #    retry_on Net::OpenTimeout, wait: :exponentially_longer, attempts: 10
      #
      #    def perform(*args)
      #      # Might raise CustomAppException, AnotherCustomAppException, or YetAnotherCustomAppException for something domain specific
      #      # Might raise ActiveRecord::Deadlocked when a local db deadlock is detected
      #      # Might raise Net::OpenTimeout when the remote service is down
      #    end
      #  end
      def retry_on(exception, wait: 3.seconds, attempts: 5, queue: nil, priority: nil)
        rescue_from exception do |error|
          if executions < attempts
            logger.error "Retrying #{self.class} in #{wait} seconds, due to a #{exception}. The original exception was #{error.cause.inspect}."
            retry_job wait: determine_delay(wait), queue: queue, priority: priority
          else
            if block_given?
              yield self, error
            else
              logger.error "Stopped retrying #{self.class} due to a #{exception}, which reoccurred on #{executions} attempts. The original exception was #{error.cause.inspect}."
              raise error
            end
          end
        end
      end

      # Discard the job with no attempts to retry, if the exception is raised. This is useful when the subject of the job,
      # like an Active Record, is no longer available, and the job is thus no longer relevant.
      #
      # You can also pass a block that'll be invoked. This block is yielded with the job instance as the first and the error instance as the second parameter.
      #
      # ==== Example
      #
      #  class SearchIndexingJob < ActiveJob::Base
      #    discard_on ActiveJob::DeserializationError
      #    discard_on(CustomAppException) do |job, exception|
      #      ExceptionNotifier.caught(exception)
      #    end
      #
      #    def perform(record)
      #      # Will raise ActiveJob::DeserializationError if the record can't be deserialized
      #      # Might raise CustomAppException for something domain specific
      #    end
      #  end
      def discard_on(exception)
        rescue_from exception do |error|
          if block_given?
            yield self, exception
          else
            logger.error "Discarded #{self.class} due to a #{exception}. The original exception was #{error.cause.inspect}."
          end
        end
      end
    end

    # Reschedules the job to be re-executed. This is useful in combination
    # with the +rescue_from+ option. When you rescue an exception from your job
    # you can ask Active Job to retry performing your job.
    #
    # ==== Options
    # * <tt>:wait</tt> - Enqueues the job with the specified delay in seconds
    # * <tt>:wait_until</tt> - Enqueues the job at the time specified
    # * <tt>:queue</tt> - Enqueues the job on the specified queue
    # * <tt>:priority</tt> - Enqueues the job with the specified priority
    #
    # ==== Examples
    #
    #  class SiteScraperJob < ActiveJob::Base
    #    rescue_from(ErrorLoadingSite) do
    #      retry_job queue: :low_priority
    #    end
    #
    #    def perform(*args)
    #      # raise ErrorLoadingSite if cannot scrape
    #    end
    #  end
    def retry_job(options = {})
      enqueue options
    end

    private
      def determine_delay(seconds_or_duration_or_algorithm)
        case seconds_or_duration_or_algorithm
        when :exponentially_longer
          (executions**4) + 2
        when ActiveSupport::Duration
          duration = seconds_or_duration_or_algorithm
          duration.to_i
        when Integer
          seconds = seconds_or_duration_or_algorithm
          seconds
        when Proc
          algorithm = seconds_or_duration_or_algorithm
          algorithm.call(executions)
        else
          raise "Couldn't determine a delay based on #{seconds_or_duration_or_algorithm.inspect}"
        end
      end
  end
end


text:
[![npm](https://nodei.co/npm/tiny-di.png?downloads=true&stars=true)](https://nodei.co/npm/tiny-di/)

A tini tiny dependency injection container for node.js/io.js

# example

```javascript
// main.js
var tiny = require('tiny-di')();

// `require` the module now and bind it to `app`
tiny.bind('app').load('lib/app');

var something = require('something');
something.setup();

// bind an existing object to `something`
tiny.bind('something').to(something);

// layz bind
// this module is loaded as soon as somebody requests the binding `another`
tiny.bind('another').lazy('v1/another');

// use namespaces
tiny.ns('some/ns').to('./some/local/dir/');
tiny.get('some/ns/foo'); // will require('./some/local/dir/foo')

// use custom providers
tiny.provide('Something').by(somethingProvider);

// this function is called whenever a module requires `Somehing`
function somethingProvider(env, injector) {
  return 'I was required by ' + env.binding;
}

// tiny-di comes with built-in resolver which tries
// to cover basic use cases.
// if you need a more advanced resolving of your deps, you can
// set a custom resolver
// have a look at the built-in resolver before doing this!
tiny.setResolver(function(file) {
  return require(file);
});

...
```

```javascript
// module
module.exports = Module;

Module.$inject = ['app', 'something', 'another'];
function Module(app, something, another) {

  // use the constructor pattern for your modules/libs/classes..
  if (!(this instanceof Module)) {
    return new Module(app, something, another);
  }

  var self = this;

  // app, something and another are injected :)
  ...
}

```

## advanced $inject configuration

```javascript
// module
module.exports = Module;

Module.$inject = {
  deps: ['app', 'something', 'another'],
  callAs: 'class' // or: 'function' (default is 'function')
};
function Module(app, something, another) {

  // callAs='class' tells the injector to instantiate a new class
  // now you don't need to use the constructor pattern. yah!

  var self = this;

  // (this instanceof Module) -> true!
}
```

# examples

look at the `example`-folder for a simple howto

# develop

```javascript
npm install
npm run watch

```

# tests

Test coverage is quite good at the moment (see badge above).

```javascript
npm install
npm test
```

# license

MIT