text:
<?php

namespace Zend\View;

use Interop\Container\ContainerInterface;
use Zend\EventManager\EventManagerAwareInterface;
use Zend\EventManager\SharedEventManagerInterface;
use Zend\I18n\Translator\TranslatorAwareInterface;
use Zend\I18n\Translator\TranslatorInterface;
use Zend\ServiceManager\AbstractPluginManager;
use Zend\ServiceManager\Exception\InvalidServiceException;
use Zend\ServiceManager\Factory\InvokableFactory;
use Zend\View\Exception\InvalidHelperException;

/**
 * Plugin manager implementation for view helpers
 *
 * Enforces that helpers retrieved are instances of
 * Helper\HelperInterface. Additionally, it registers a number of default
 * helpers.
 */
class HelperPluginManager extends AbstractPluginManager
{
    /**
     * Default helper aliases
     *
     * Most of these are present for legacy purposes, as v2 of the service
     * manager normalized names when fetching services.
     *
     * @var string[]
     */
    protected $aliases = [
        'asset'               => Helper\Asset::class,
        'Asset'               => Helper\Asset::class,
        'basePath'            => Helper\BasePath::class,
        'BasePath'            => Helper\BasePath::class,
        'basepath'            => Helper\BasePath::class,
        'Cycle'               => Helper\Cycle::class,
        'cycle'               => Helper\Cycle::class,
        'declareVars'         => Helper\DeclareVars::class,
        'DeclareVars'         => Helper\DeclareVars::class,
        'declarevars'         => Helper\DeclareVars::class,
        'Doctype'             => Helper\Doctype::class,
        'doctype'             => Helper\Doctype::class, // overridden by a factory in ViewHelperManagerFactory
        'escapeCss'           => Helper\EscapeCss::class,
        'EscapeCss'           => Helper\EscapeCss::class,
        'escapecss'           => Helper\EscapeCss::class,
        'escapeHtmlAttr'      => Helper\EscapeHtmlAttr::class,
        'EscapeHtmlAttr'      => Helper\EscapeHtmlAttr::class,
        'escapehtmlattr'      => Helper\EscapeHtmlAttr::class,
        'escapeHtml'          => Helper\EscapeHtml::class,
        'EscapeHtml'          => Helper\EscapeHtml::class,
        'escapehtml'          => Helper\EscapeHtml::class,
        'escapeJs'            => Helper\EscapeJs::class,
        'EscapeJs'            => Helper\EscapeJs::class,
        'escapejs'            => Helper\EscapeJs::class,
        'escapeUrl'           => Helper\EscapeUrl::class,
        'EscapeUrl'           => Helper\EscapeUrl::class,
        'escapeurl'           => Helper\EscapeUrl::class,
        'flashmessenger'      => Helper\FlashMessenger::class,
        'flashMessenger'      => Helper\FlashMessenger::class,
        'FlashMessenger'      => Helper\FlashMessenger::class,
        'Gravatar'            => Helper\Gravatar::class,
        'gravatar'            => Helper\Gravatar::class,
        'headLink'            => Helper\HeadLink::class,
        'HeadLink'            => Helper\HeadLink::class,
        'headlink'            => Helper\HeadLink::class,
        'headMeta'            => Helper\HeadMeta::class,
        'HeadMeta'            => Helper\HeadMeta::class,
        'headmeta'            => Helper\HeadMeta::class,
        'headScript'          => Helper\HeadScript::class,
        'HeadScript'          => Helper\HeadScript::class,
        'headscript'          => Helper\HeadScript::class,
        'headStyle'           => Helper\HeadStyle::class,
        'HeadStyle'           => Helper\HeadStyle::class,
        'headstyle'           => Helper\HeadStyle::class,
        'headTitle'           => Helper\HeadTitle::class,
        'HeadTitle'           => Helper\HeadTitle::class,
        'headtitle'           => Helper\HeadTitle::class,
        'htmlflash'           => Helper\HtmlFlash::class,
        'htmlFlash'           => Helper\HtmlFlash::class,
        'HtmlFlash'           => Helper\HtmlFlash::class,
        'htmllist'            => Helper\HtmlList::class,
        'htmlList'            => Helper\HtmlList::class,
        'HtmlList'            => Helper\HtmlList::class,
        'htmlobject'          => Helper\HtmlObject::class,
        'htmlObject'          => Helper\HtmlObject::class,
        'HtmlObject'          => Helper\HtmlObject::class,
        'htmlpage'            => Helper\HtmlPage::class,
        'htmlPage'            => Helper\HtmlPage::class,
        'HtmlPage'            => Helper\HtmlPage::class,
        'htmlquicktime'       => Helper\HtmlQuicktime::class,
        'htmlQuicktime'       => Helper\HtmlQuicktime::class,
        'HtmlQuicktime'       => Helper\HtmlQuicktime::class,
        'htmltag'             => Helper\HtmlTag::class,
        'htmlTag'             => Helper\HtmlTag::class,
        'HtmlTag'             => Helper\HtmlTag::class,
        'identity'            => Helper\Identity::class,
        'Identity'            => Helper\Identity::class,
        'inlinescript'        => Helper\InlineScript::class,
        'inlineScript'        => Helper\InlineScript::class,
        'InlineScript'        => Helper\InlineScript::class,
        'json'                => Helper\Json::class,
        'Json'                => Helper\Json::class,
        'layout'              => Helper\Layout::class,
        'Layout'              => Helper\Layout::class,
        'paginationcontrol'   => Helper\PaginationControl::class,
        'paginationControl'   => Helper\PaginationControl::class,
        'PaginationControl'   => Helper\PaginationControl::class,
        'partial'             => Helper\Partial::class,
        'partialloop'         => Helper\PartialLoop::class,
        'partialLoop'         => Helper\PartialLoop::class,
        'PartialLoop'         => Helper\PartialLoop::class,
        'Partial'             => Helper\Partial::class,
        'placeholder'         => Helper\Placeholder::class,
        'Placeholder'         => Helper\Placeholder::class,
        'renderchildmodel'    => Helper\RenderChildModel::class,
        'renderChildModel'    => Helper\RenderChildModel::class,
        'RenderChildModel'    => Helper\RenderChildModel::class,
        'render_child_model'  => Helper\RenderChildModel::class,
        'rendertoplaceholder' => Helper\RenderToPlaceholder::class,
        'renderToPlaceholder' => Helper\RenderToPlaceholder::class,
        'RenderToPlaceholder' => Helper\RenderToPlaceholder::class,
        'serverurl'           => Helper\ServerUrl::class,
        'serverUrl'           => Helper\ServerUrl::class,
        'ServerUrl'           => Helper\ServerUrl::class,
        'url'                 => Helper\Url::class,
        'Url'                 => Helper\Url::class,
        'view_model'          => Helper\ViewModel::class,
        'viewmodel'           => Helper\ViewModel::class,
        'viewModel'           => Helper\ViewModel::class,
        'ViewModel'           => Helper\ViewModel::class,
    ];

    /**
     * Default factories
     *
     * basepath, doctype, and url are set up as factories in the ViewHelperManagerFactory.
     * basepath and url are not very useful without their factories, however the doctype
     * helper works fine as an invokable. The factory for doctype simply checks for the
     * config value from the merged config.
     *
     * @var array
     */
    protected $factories = [
        Helper\Asset::class               => Helper\Service\AssetFactory::class,
        Helper\FlashMessenger::class      => Helper\Service\FlashMessengerFactory::class,
        Helper\Identity::class            => Helper\Service\IdentityFactory::class,
        Helper\BasePath::class            => InvokableFactory::class,
        Helper\Cycle::class               => InvokableFactory::class,
        Helper\DeclareVars::class         => InvokableFactory::class,
        Helper\Doctype::class             => InvokableFactory::class, // overridden in ViewHelperManagerFactory
        Helper\EscapeHtml::class          => InvokableFactory::class,
        Helper\EscapeHtmlAttr::class      => InvokableFactory::class,
        Helper\EscapeJs::class            => InvokableFactory::class,
        Helper\EscapeCss::class           => InvokableFactory::class,
        Helper\EscapeUrl::class           => InvokableFactory::class,
        Helper\Gravatar::class            => InvokableFactory::class,
        Helper\HtmlTag::class             => InvokableFactory::class,
        Helper\HeadLink::class            => InvokableFactory::class,
        Helper\HeadMeta::class            => InvokableFactory::class,
        Helper\HeadScript::class          => InvokableFactory::class,
        Helper\HeadStyle::class           => InvokableFactory::class,
        Helper\HeadTitle::class           => InvokableFactory::class,
        Helper\HtmlFlash::class           => InvokableFactory::class,
        Helper\HtmlList::class            => InvokableFactory::class,
        Helper\HtmlObject::class          => InvokableFactory::class,
        Helper\HtmlPage::class            => InvokableFactory::class,
        Helper\HtmlQuicktime::class       => InvokableFactory::class,
        Helper\InlineScript::class        => InvokableFactory::class,
        Helper\Json::class                => InvokableFactory::class,
        Helper\Layout::class              => InvokableFactory::class,
        Helper\PaginationControl::class   => InvokableFactory::class,
        Helper\PartialLoop::class         => InvokableFactory::class,
        Helper\Partial::class             => InvokableFactory::class,
        Helper\Placeholder::class         => InvokableFactory::class,
        Helper\RenderChildModel::class    => InvokableFactory::class,
        Helper\RenderToPlaceholder::class => InvokableFactory::class,
        Helper\ServerUrl::class           => InvokableFactory::class,
        Helper\Url::class                 => InvokableFactory::class,
        Helper\ViewModel::class           => InvokableFactory::class,

        // v2 canonical FQCNs

        'zendviewhelperasset'             => Helper\Service\AssetFactory::class,
        'zendviewhelperflashmessenger'    => Helper\Service\FlashMessengerFactory::class,
        'zendviewhelperidentity'          => Helper\Service\IdentityFactory::class,
        'zendviewhelperbasepath'          => InvokableFactory::class,
        'zendviewhelpercycle'             => InvokableFactory::class,
        'zendviewhelperdeclarevars'       => InvokableFactory::class,
        'zendviewhelperdoctype'           => InvokableFactory::class,
        'zendviewhelperescapehtml'        => InvokableFactory::class,
        'zendviewhelperescapehtmlattr'    => InvokableFactory::class,
        'zendviewhelperescapejs'          => InvokableFactory::class,
        'zendviewhelperescapecss'         => InvokableFactory::class,
        'zendviewhelperescapeurl'         => InvokableFactory::class,
        'zendviewhelpergravatar'          => InvokableFactory::class,
        'zendviewhelperhtmltag'           => InvokableFactory::class,
        'zendviewhelperheadlink'          => InvokableFactory::class,
        'zendviewhelperheadmeta'          => InvokableFactory::class,
        'zendviewhelperheadscript'        => InvokableFactory::class,
        'zendviewhelperheadstyle'         => InvokableFactory::class,
        'zendviewhelperheadtitle'         => InvokableFactory::class,
        'zendviewhelperhtmlflash'         => InvokableFactory::class,
        'zendviewhelperhtmllist'          => InvokableFactory::class,
        'zendviewhelperhtmlobject'        => InvokableFactory::class,
        'zendviewhelperhtmlpage'          => InvokableFactory::class,
        'zendviewhelperhtmlquicktime'     => InvokableFactory::class,
        'zendviewhelperinlinescript'      => InvokableFactory::class,
        'zendviewhelperjson'              => InvokableFactory::class,
        'zendviewhelperlayout'            => InvokableFactory::class,
        'zendviewhelperpaginationcontrol' => InvokableFactory::class,
        'zendviewhelperpartialloop'       => InvokableFactory::class,
        'zendviewhelperpartial'           => InvokableFactory::class,
        'zendviewhelperplaceholder'       => InvokableFactory::class,
        'zendviewhelperrenderchildmodel'  => InvokableFactory::class,
        'zendviewhelperrendertoplaceholder' => InvokableFactory::class,
        'zendviewhelperserverurl'         => InvokableFactory::class,
        'zendviewhelperurl'               => InvokableFactory::class,
        'zendviewhelperviewmodel'         => InvokableFactory::class,
    ];

    /**
     * @var Renderer\RendererInterface
     */
    protected $renderer;

    /**
     * Constructor
     *
     * Merges provided configuration with default configuration.
     *
     * Adds initializers to inject the attached renderer and translator, if
     * any, to the currently requested helper.
     *
     * @param null|ConfigInterface|ContainerInterface $configOrContainerInstance
     * @param array $v3config If $configOrContainerInstance is a container, this
     *     value will be passed to the parent constructor.
     */
    public function __construct($configOrContainerInstance = null, array $v3config = [])
    {
        $this->initializers[] = [$this, 'injectRenderer'];
        $this->initializers[] = [$this, 'injectTranslator'];
        $this->initializers[] = [$this, 'injectEventManager'];

        parent::__construct($configOrContainerInstance, $v3config);
    }

    /**
     * Set renderer
     *
     * @param  Renderer\RendererInterface $renderer
     * @return HelperPluginManager
     */
    public function setRenderer(Renderer\RendererInterface $renderer)
    {
        $this->renderer = $renderer;

        return $this;
    }

    /**
     * Retrieve renderer instance
     *
     * @return null|Renderer\RendererInterface
     */
    public function getRenderer()
    {
        return $this->renderer;
    }

    /**
     * Inject a helper instance with the registered renderer
     *
     * @param ContainerInterface|Helper\HelperInterface $first helper instance
     *     under zend-servicemanager v2, ContainerInterface under v3.
     * @param ContainerInterface|Helper\HelperInterface $second
     *     ContainerInterface under zend-servicemanager v3, helper instance
     *     under v2. Ignored regardless.
     */
    public function injectRenderer($first, $second)
    {
        $helper = ($first instanceof ContainerInterface)
            ? $second
            : $first;

        if (! $helper instanceof Helper\HelperInterface) {
            return;
        }

        $renderer = $this->getRenderer();
        if (null === $renderer) {
            return;
        }
        $helper->setView($renderer);
    }

    /**
     * Inject a helper instance with the registered translator
     *
     * @param ContainerInterface|Helper\HelperInterface $first helper instance
     *     under zend-servicemanager v2, ContainerInterface under v3.
     * @param ContainerInterface|Helper\HelperInterface $second
     *     ContainerInterface under zend-servicemanager v3, helper instance
     *     under v2. Ignored regardless.
     */
    public function injectTranslator($first, $second)
    {
        if ($first instanceof ContainerInterface) {
            // v3 usage
            $container = $first;
            $helper = $second;
        } else {
            // v2 usage; grab the parent container
            $container = $second->getServiceLocator();
            $helper = $first;
        }

        // Allow either direct implementation or duck-typing.
        if (! $helper instanceof TranslatorAwareInterface
            && ! method_exists($helper, 'setTranslator')
        ) {
            return;
        }

        if (! $container) {
            // Under zend-navigation v2.5, the navigation PluginManager is
            // always lazy-loaded, which means it never has a parent
            // container.
            return;
        }

        if (method_exists($helper, 'hasTranslator') && $helper->hasTranslator()) {
            return;
        }

        if ($container->has('MvcTranslator')) {
            $helper->setTranslator($container->get('MvcTranslator'));
            return;
        }

        if ($container->has(TranslatorInterface::class)) {
            $helper->setTranslator($container->get(TranslatorInterface::class));
            return;
        }

        if ($container->has('Translator')) {
            $helper->setTranslator($container->get('Translator'));
            return;
        }
    }

    /**
     * Inject a helper instance with the registered event manager
     *
     * @param ContainerInterface|Helper\HelperInterface $first helper instance
     *     under zend-servicemanager v2, ContainerInterface under v3.
     * @param ContainerInterface|Helper\HelperInterface $second
     *     ContainerInterface under zend-servicemanager v3, helper instance
     *     under v2. Ignored regardless.
     */
    public function injectEventManager($first, $second)
    {
        if ($first instanceof ContainerInterface) {
            // v3 usage
            $container = $first;
            $helper = $second;
        } else {
            // v2 usage; grab the parent container
            $container = $second->getServiceLocator();
            $helper = $first;
        }

        if (! $container) {
            // Under zend-navigation v2.5, the navigation PluginManager is
            // always lazy-loaded, which means it never has a parent
            // container.
            return;
        }

        if (! $helper instanceof EventManagerAwareInterface) {
            return;
        }

        if (! $container->has('EventManager')) {
            // If the container doesn't have an EM service, do nothing.
            return;
        }

        $events = $helper->getEventManager();
        if (! $events || ! $events->getSharedManager() instanceof SharedEventManagerInterface) {
            $helper->setEventManager($container->get('EventManager'));
        }
    }

    /**
     * Validate the plugin is of the expected type (v3).
     *
     * Validates against callables and HelperInterface implementations.
     *
     * @param mixed $instance
     * @throws InvalidServiceException
     */
    public function validate($instance)
    {
        if (! is_callable($instance) && ! $instance instanceof Helper\HelperInterface) {
            throw new InvalidServiceException(
                sprintf(
                    '%s can only create instances of %s and/or callables; %s is invalid',
                    get_class($this),
                    Helper\HelperInterface::class,
                    (is_object($instance) ? get_class($instance) : gettype($instance))
                )
            );
        }
    }

    /**
     * Validate the plugin is of the expected type (v2).
     *
     * Proxies to `validate()`.
     *
     * @param mixed $instance
     * @throws InvalidHelperException
     */
    public function validatePlugin($instance)
    {
        try {
            $this->validate($instance);
        } catch (InvalidServiceException $e) {
            throw new InvalidHelperException($e->getMessage(), $e->getCode(), $e);
        }
    }
}


text:
from cloudconsole import app
import unittest

class FlaskBookshelfTests(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        pass

    @classmethod
    def tearDownClass(cls):
        pass

    def setUp(self):
        # creates a test client
        self.app = app.test_client()
        # propagate the exceptions to the test client
        self.app.testing = True

    def tearDown(self):
        pass

    def test_home_status_code(self):
        # sends HTTP GET request to the application
        # on the specified path
        result = self.app.get('/')

        # assert the status code of the response
        self.assertEqual(result.status_code, 200)

    # def test_home_data(self):
    #     # sends HTTP GET request to the application
    #     # on the specified path
    #     result = self.app.get('/')
    #
    #     # assert the response data
    #     self.assertEqual(result.data, "Cloud Console")

redpajama_set_name: RedPajamaGithub


text:
package datenbanken;
import filter.Ampelindikator;
import filter.Inhaltsstoff;

/**
 * Project: LIV - Lebensmittelinhaltsstoffverifizierer
 *
 * class NussDatenbankMock Mock Up fuer die Datenbankabfrage
 * Filter "Nuss"
 *
 * @author team equal-IT
 * @mail team@equal-it.de
 * @version 1.0 2016/07/08
 */

public class NussDatenbankMock implements Lebensmitteldatenbank {

	/**
	 * @param ean
	 *            abzufragende EAN
	 * @param antwort
	 *            Rückgabe der Abfrage
	 * @return antwort
	 */
	@Override
	public String frageNach(String ean) {
		String antwort = "";
		switch (ean) {
		case "1":
			antwort = "<nuss>yes</nuss>";
			break;
		case "2":
			antwort = "<nuss>no</nuss>";
			break;
		default:
			break;
		}
		return antwort;
	}

	/**
	 * @param anfrageergebnis
	 * @param inhaltsstoff
	 * @return Ampelindikator
	 */
	@Override
	public Ampelindikator antwortEnthaeltInhaltsstoff(String anfrageergebnis, Inhaltsstoff inhaltsstoff) {
		return Ampelindikator.UNBEKANNT;
		/**
		 * Variante fuer NussDatenbankMock antwort. Wenn Filter gesetzt return
		 * Enthalten, wenn Filter nicht gesetzt return nicht Enthalten
		 *
		 * if (inhaltsstoff == Inhaltsstoff.NUSS) { return
		 * Ampelindikator.ENTHALTEN; } return Ampelindikator.NICHT_ENTHALTEN;
		 */
	}
}


text:
<?php

namespace Insider\UserBundle\Security;

use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserChecker;
use Symfony\Component\Security\Core\Exception\LockedException;
use Symfony\Component\Security\Core\Exception\DisabledException;
use Insider\UserBundle\Exception\RegistrationException;
use Insider\UserBundle\Entity\User;

class InsiderUserChecker extends UserChecker
{
    public function checkPreAuth(UserInterface $user)
    {
        // check anything
        if (!$user instanceof User) {
            return;
        }

        if ($user->getStatus() == User::STATUS_REGISTERED && !$user->getConfirmationToken()) {
            $ex = new RegistrationException('Регистрация не закончена');
            $ex->setUser($user);
            throw $ex;
        }

        if ($user->getStatus() == User::STATUS_REGISTERED) {
            $ex = new DisabledException('User account is disabled.!!!');
            $ex->setUser($user);
            throw $ex;
        }

        if ($user->getStatus() == User::STATUS_BLOCKED) {
            // TODO вынести в транслятор
            $ex = new LockedException('Пользователь заблокирован.');
            $ex->setUser($user);
            throw $ex;
        }

        if ($user->getStatus() == User::STATUS_DELETED) {
            // TODO вынести в транслятор
            $ex = new LockedException('Пользователь удален');
            $ex->setUser($user);
            throw $ex;
        }
    }

    public function checkPostAuth(UserInterface $user)
    {
        parent::checkPostAuth($user);
    }
}


text:
using FTAnalyzer.Forms;
using FTAnalyzer.Mapping;
using NetTopologySuite.Geometries;
using Ionic.Zip;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Diagnostics;

namespace FTAnalyzer.Utilities
{
    public class DatabaseHelper : IDisposable
    {
        public string DatabaseFile { get; private set; }
        public string CurrentFilename { get; private set; }
        public string DatabasePath { get; private set; }
        static DatabaseHelper instance;
        static string connectionString;
        static SQLiteConnection InstanceConnection { get; set; }
        Version ProgramVersion { get; set; }
        bool restoring;

        #region Constructor/Destructor
        DatabaseHelper()
        {
            DatabasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Family Tree Analyzer");
            CurrentFilename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Family Tree Analyzer\FTA-RestoreTemp.s3db");
            if (CheckDatabaseConnection())
            {
                InstanceConnection = new SQLiteConnection(connectionString);
                restoring = false;
            }
        }

        public static DatabaseHelper Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new DatabaseHelper();
                }
                return instance;
            }
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                try
                {
                    if (InstanceConnection?.State == ConnectionState.Open)
                        InstanceConnection.Close();
                    InstanceConnection?.Dispose();
                    // dispose of things here
                }
                catch (Exception) { }
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        bool CheckDatabaseConnection()
        {
            try
            {
                DatabaseFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Family Tree Analyzer\Geocodes.s3db");
                if (!File.Exists(DatabaseFile))
                {
                    string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Family Tree Analyzer");
                    if (!Directory.Exists(path))
                        Directory.CreateDirectory(path);
                    File.Copy(Path.Combine(Application.StartupPath, @"Resources\Geocodes-Empty.s3db"), DatabaseFile);
                }
                connectionString = $"Data Source={DatabaseFile};Version=3;";
                return true;
            }
            catch (Exception ex)
            {
                UIHelpers.ShowMessage($"Error opening database - Filename: {DatabaseFile}. Error is :{ex.Message}", "FTAnalyzer");
                return false;
            }
        }
        #endregion

        #region Database Update Functions
        public void CheckDatabaseVersion(Version programVersion)
        {
            try
            {
                ProgramVersion = programVersion;
                Version dbVersion = GetDatabaseVersion();
                if (dbVersion < programVersion)
                    UpgradeDatabase(dbVersion);
            }
            catch (SQLiteException)
            {
                //                log.Debug("Caught Exception in CheckDatabaseVersion " + e.Message);
                UpgradeDatabase(new Version("0.0.0.0"));
            }
        }

        static Version GetDatabaseVersion()
        {
            string db = null;
            try
            {
                if (InstanceConnection.State != ConnectionState.Open)
                    InstanceConnection.Open();
                using (SQLiteCommand cmd = new SQLiteCommand("select Database from versions where platform='PC'", InstanceConnection))
                {
                    db = (string)cmd.ExecuteScalar();
                }
            }
            catch (Exception)
            {  // use old method if current method fails
                try
                {
                    using (SQLiteCommand cmd = new SQLiteCommand("select Database from versions", InstanceConnection))
                    {
                        db = (string)cmd.ExecuteScalar();
                    }
                }
                catch { }
            }
            finally
            {
                InstanceConnection?.Close();
            }
            Version dbVersion = db == null ? new Version("0.0.0.0") : new Version(db);
            if (dbVersion == new Version("7.3.0.0"))
                return new Version("7.0.0.0"); // force old version so it updates after beta fix on v7.3.0.0
            return dbVersion;
        }

        public bool BackupDatabase(SaveFileDialog saveDatabase, string comment)
        {
            try
            {
                string directory = Application.UserAppDataRegistry.GetValue("Geocode Backup Directory", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)).ToString();
                saveDatabase.FileName = "FTAnalyzer-Geocodes-" + DateTime.Now.ToString("yyyy-MM-dd") + "-v" + MainForm.VERSION + ".zip";
                saveDatabase.InitialDirectory = directory;
                DialogResult result = saveDatabase.ShowDialog();
                if (result == DialogResult.OK)
                {
                    StartBackupRestoreDatabase();
                    if (File.Exists(saveDatabase.FileName))
                        File.Delete(saveDatabase.FileName);
                    ZipFile zip = new ZipFile(saveDatabase.FileName);
                    zip.AddFile(DatabaseFile, string.Empty);
                    zip.Comment = comment + " on " + DateTime.Now.ToString("dd MMM yyyy HH:mm");
                    zip.Save();
                    //EndBackupDatabase();
                    Application.UserAppDataRegistry.SetValue("Geocode Backup Directory", Path.GetDirectoryName(saveDatabase.FileName));
                    UIHelpers.ShowMessage($"Database exported to {saveDatabase.FileName}", "FTAnalyzer Database Export Complete");
                    zip.Dispose();
                    return true;
                }
            }
            catch(Exception ex)
            {
                UIHelpers.ShowMessage($"Problem exporting database. Error was {ex.Message}");
            }
            return false;
            }

            void UpgradeDatabase(Version dbVersion)
        {
            try
            {
                Version v3_0_0_0 = new Version("3.0.0.0");
                Version v3_0_2_0 = new Version("3.0.2.0");
                Version v3_1_2_0 = new Version("3.1.2.0");
                Version v3_3_2_5 = new Version("3.3.2.5");
                Version v7_0_0_0 = new Version("7.0.0.0");
                Version v7_3_0_0 = new Version("7.3.0.0");
                Version v7_3_0_1 = new Version("7.3.0.1");
                Version v7_3_3_2 = new Version("7.3.3.2");
                Version v7_4_0_0 = new Version("7.4.0.0");
                Version v8_0_0_0 = new Version("8.0.0.0");
                Version v8_3_1_0 = new Version("8.3.1.0");
                if (dbVersion < v3_0_0_0)
                {
                    // Version is less than 3.0.0.0 or none existent so copy latest database from empty database
                    GC.Collect(); // needed to force a cleanup of connections prior to replacing the file.
                    if (File.Exists(DatabaseFile))
                    {
                        File.Delete(DatabaseFile);
                    }
                    File.Copy(Path.Combine(Application.StartupPath, @"Resources\Geocodes-Empty.s3db"), DatabaseFile);
                }
                if (InstanceConnection.State != ConnectionState.Open)
                    InstanceConnection.Open();
                if (dbVersion < v3_0_2_0)
                {
                    // Version v3.0.2.0 needs to reset Google Matches to not searched and set partials to level
                    //SQLiteCommand cmd = new SQLiteCommand("alter table geocode add column GeocodeStatus integer default 0", conn);
                    using (SQLiteCommand cmd = new SQLiteCommand("update geocode set geocodestatus=0 where geocodestatus=1", InstanceConnection))
                    {
                        cmd.ExecuteNonQuery(); // reset Google Match to Not Searched
                    }
                    using (SQLiteCommand cmd = new SQLiteCommand("update geocode set geocodestatus=7 where geocodestatus=2", InstanceConnection))
                    {
                        cmd.ExecuteNonQuery(); // set to level mismatch if partial
                    }
                    using (SQLiteCommand cmd = new SQLiteCommand("update versions set Database = '3.0.2.0'", InstanceConnection))
                    {
                        cmd.ExecuteNonQuery();
                    }
                    MessageBox.Show("Please note that due to fixes in the way Google reports\nlocations your 'Google Matched' geocodes have been reset.", "FTAnalyzer");
                }
                if (dbVersion < v3_1_2_0)
                {
                    bool proceed = false;
                    if (restoring)
                        proceed = true;
                    else
                    {
                        DialogResult result = MessageBox.Show("In order to improve speed of the maps a database upgrade is needed.\nThis may take several minutes and must be allowed to complete.\nYou must backup your database first. Ok to proceed?", "Database upgrading", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        Application.UseWaitCursor = true;
                        if (result == DialogResult.Yes)
                        {
                            SaveFileDialog sfd = new SaveFileDialog();
                            proceed = BackupDatabase(sfd, "FTAnalyzer zip file created by Database upgrade for v3.2.1.0");
                            sfd.Dispose();
                        }
                        Application.UseWaitCursor = false;
                    }
                    if (proceed)
                    {
                        bool latm = false;
                        bool longm = false;
                        using (SQLiteCommand cmd = new SQLiteCommand("PRAGMA table_info('geocode')", InstanceConnection))
                        {
                            using (SQLiteDataReader reader = cmd.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    string column = reader[1].ToString();
                                    if (column.Equals("Latm"))
                                        latm = true;
                                    if (column.Equals("Longm"))
                                        longm = true;
                                }
                            }
                        }
                        if (!latm)
                        {
                            using (SQLiteCommand cmd = new SQLiteCommand("alter table geocode add column Latm real default 0.0", InstanceConnection))
                            {
                                cmd.ExecuteNonQuery();
                            }
                        }
                        if (!longm)
                        {
                            using (SQLiteCommand cmd = new SQLiteCommand("alter table geocode add column Longm real default 0.0", InstanceConnection))
                            {
                                cmd.ExecuteNonQuery();
                                ConvertLatLongs();
                            }
                        }
                        using (SQLiteCommand cmd = new SQLiteCommand("update geocode set foundlocation='', foundlevel=-2 where geocodestatus=3", InstanceConnection))
                        {
                            cmd.ExecuteNonQuery();
                        }
                        using (SQLiteCommand cmd = new SQLiteCommand("update versions set Database = '3.2.1.0'", InstanceConnection))
                        {
                            cmd.ExecuteNonQuery();
                        }
                        MessageBox.Show("Database lat/long upgrade complete", "FTAnalyzer");
                    }
                    else
                    {
                        MessageBox.Show("Database not backed up we cannot proceed to update maps without a safe database backup.\nMapping features will not work correctly.", "Database backup Required");
                    }
                }
                if (dbVersion < v3_3_2_5)
                {
                    // mark all bad viewports as not searched
                    using (SQLiteCommand cmd = new SQLiteCommand("update Geocode set latitude = 0, longitude = 0, founddate = date('now'), foundlocation = '', foundlevel = -2, viewport_x_ne = 0, viewport_y_ne = 0, viewport_x_sw = 0, viewport_y_sw = 0, geocodestatus = 0, foundresulttype = '' where latitude<>0 and longitude<>0 and abs(viewport_x_ne) <= 180", InstanceConnection))
                    {
                        cmd.ExecuteNonQuery();
                    }
                    using (SQLiteCommand cmd = new SQLiteCommand("update versions set Database = '3.3.2.5'", InstanceConnection))
                    {
                        cmd.ExecuteNonQuery();
                    }
                }
                if (dbVersion < v7_0_0_0)
                {
                    using (SQLiteCommand cmd = new SQLiteCommand("update Geocode set geocodestatus = 0 where latitude=0 and longitude=0 and geocodestatus=3", InstanceConnection))
                    {
                        cmd.ExecuteNonQuery();
                    }
                    using (SQLiteCommand cmd = new SQLiteCommand("update versions set Database = '7.0.0.0'", InstanceConnection))
                    {
                        cmd.ExecuteNonQuery();
                    }
                }
                if (dbVersion < v7_3_0_0)
                {
                    try
                    {
                        using (SQLiteCommand cmd = new SQLiteCommand("create table if not exists LostCousins (CensusYear INTEGER(4), CensusCountry STRING (20), CensusRef STRING(25), IndID STRING(10), FullName String(80), constraint pkLostCousins primary key (CensusYear, CensusCountry, CensusRef, IndID))", InstanceConnection))
                        {
                            cmd.ExecuteNonQuery();
                        }
                        using (SQLiteCommand cmd = new SQLiteCommand("update versions set Database = '7.3.0.0'", InstanceConnection))
                        {
                            cmd.ExecuteNonQuery();
                        }
                    }
                    catch (SQLiteException) { } // skip if table already exists.
                }
                if (dbVersion < v7_3_0_1)
                {
                    try
                    {
                        using (SQLiteCommand cmd = new SQLiteCommand("update table LostCousins add column FullName Varchar(80)", InstanceConnection))
                        {
                            cmd.ExecuteNonQuery();
                        }
                    }
                    catch (SQLiteException) { } // don't complain if adding field already exists due to beta testing.
                    using (SQLiteCommand cmd = new SQLiteCommand("update versions set Database = '7.3.0.1'", InstanceConnection))
                    {
                        cmd.ExecuteNonQuery();
                    }
                }
                if (dbVersion < v7_3_3_2)
                {
                    try
                    {
                        using (SQLiteCommand cmd = new SQLiteCommand("SELECT count(*) FROM LostCousins", InstanceConnection))
                        {
                            cmd.ExecuteNonQuery();
                        }
                    }
                    catch (SQLiteException)
                    {
                        using (SQLiteCommand cmd = new SQLiteCommand("create table IF NOT EXISTS LostCousins (CensusYear INTEGER(4), CensusCountry STRING (20), CensusRef STRING(25), IndID STRING(10), FullName String(80), constraint pkLostCousins primary key (CensusYear, CensusCountry, CensusRef, IndID))", InstanceConnection))
                        {
                            cmd.ExecuteNonQuery();
                        }
                    }
                    using (SQLiteCommand cmd = new SQLiteCommand("update versions set Database = '7.3.3.2'", InstanceConnection))
                    {
                        cmd.ExecuteNonQuery();
                    }
                }
                if (dbVersion < v7_4_0_0)
                {

                    using (SQLiteCommand cmd = new SQLiteCommand("drop table versions", InstanceConnection))
                    {
                            cmd.ExecuteNonQuery();
                    }
                    using (SQLiteCommand cmd = new SQLiteCommand("CREATE TABLE IF NOT EXISTS Versions(Platform VARCHAR(10) PRIMARY KEY, [Database] VARCHAR(10));", InstanceConnection))
                    {
                        cmd.ExecuteNonQuery();
                    }
                    using (SQLiteCommand cmd = new SQLiteCommand("insert into Versions(platform, database) values('PC', '7.4.0.0')", InstanceConnection))
                    {
                        cmd.ExecuteNonQuery();
                    }
                    using (SQLiteCommand cmd = new SQLiteCommand("insert into Versions(platform, database) values('Mac', '1.2.0.42')", InstanceConnection))
                    {
                        cmd.ExecuteNonQuery();
                    }
                }
                if(dbVersion < v8_0_0_0)
                {
                    using (SQLiteCommand cmd = new SQLiteCommand("CREATE TABLE IF NOT EXISTS CustomFacts (FactType STRING(60) PRIMARY KEY, [Ignore] BOOLEAN)", InstanceConnection))
                    {
                        cmd.ExecuteNonQuery();
                    }
                    using (SQLiteCommand cmd = new SQLiteCommand("update Versions set database = '8.0.0.0' where platform = 'PC'", InstanceConnection))
                    {
                        cmd.ExecuteNonQuery();
                    }
                }
                if (dbVersion < v8_3_1_0)
                {
                    if (dbVersion < v8_3_1_0)
                    {
                        try
                        {
                            using (SQLiteCommand cmd = new SQLiteCommand("alter table LostCousins add column FullName VARCHAR(80)", InstanceConnection))
                            {
                                cmd.ExecuteNonQuery();
                            }
                        }
                        catch (SQLiteException) { } // don't complain if adding field already exists due to beta testing.
                        using (SQLiteCommand cmd = new SQLiteCommand("update versions set Database = '8.3.1.0'", InstanceConnection))
                        {
                            cmd.ExecuteNonQuery();
                        }
                    }
                }
                InstanceConnection.Close();
            }
            catch (Exception ex)
            {
                UIHelpers.ShowMessage($"Error upgrading database. Error is :{ex.Message}", "FTAnalyzer");
            }
        }
        #endregion

        #region Lat/Long Routines
        void ConvertLatLongs()
        {
            Coordinate Point, NorthEast, SouthWest;
            Coordinate mPoint, mNorthEast, mSouthWest;
            double latitude, longitude, viewport_x_ne, viewport_y_ne, viewport_x_sw, viewport_y_sw;

            if (InstanceConnection.State != ConnectionState.Open)
                InstanceConnection.Open();
            int rowcount = 0;
            using (SQLiteCommand cmd = new SQLiteCommand("select count(*) from geocode where latitude <> 0 and longitude <> 0", InstanceConnection))
            {
                using (SQLiteDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleResult))
                {
                    reader.Read();
                    int.TryParse(reader[0].ToString(), out rowcount);
                }
            }
            #region update cmd
            using (SQLiteCommand updateCmd = new SQLiteCommand("update geocode set latm=?, longm=?, viewport_x_ne=?, viewport_y_ne=?, viewport_x_sw=?, viewport_y_sw=?  where location = ?", InstanceConnection))
            {
                SQLiteParameter param = updateCmd.CreateParameter();
                param.DbType = DbType.Double;
                updateCmd.Parameters.Add(param);

                param = updateCmd.CreateParameter();
                param.DbType = DbType.Double;
                updateCmd.Parameters.Add(param);

                param = updateCmd.CreateParameter();
                param.DbType = DbType.Double;
                updateCmd.Parameters.Add(param);

                param = updateCmd.CreateParameter();
                param.DbType = DbType.Double;
                updateCmd.Parameters.Add(param);

                param = updateCmd.CreateParameter();
                param.DbType = DbType.Double;
                updateCmd.Parameters.Add(param);

                param = updateCmd.CreateParameter();
                param.DbType = DbType.Double;
                updateCmd.Parameters.Add(param);

                param = updateCmd.CreateParameter();
                param.DbType = DbType.String;
                updateCmd.Parameters.Add(param);
                updateCmd.Prepare();
                Progress p = new Progress(rowcount);
                p.Show();
                int row = 0;
                using (SQLiteCommand cmd = new SQLiteCommand("select location, latitude, longitude, viewport_x_ne, viewport_y_ne, viewport_x_sw, viewport_y_sw from geocode where latitude <> 0 and longitude <> 0", InstanceConnection))
                {
                    using (SQLiteDataReader reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            latitude = longitude = viewport_x_ne = viewport_x_sw = viewport_y_ne = viewport_y_sw = 0;
                            string location = reader["location"].ToString();
                            double.TryParse(reader["latitude"].ToString(), out latitude);
                            double.TryParse(reader["longitude"].ToString(), out longitude);
                            double.TryParse(reader["viewport_x_ne"].ToString(), out viewport_x_ne);
                            double.TryParse(reader["viewport_y_ne"].ToString(), out viewport_y_ne);
                            double.TryParse(reader["viewport_x_sw"].ToString(), out viewport_x_sw);
                            double.TryParse(reader["viewport_y_sw"].ToString(), out viewport_y_sw);
                            Point = new Coordinate(longitude, latitude);
                            NorthEast = new Coordinate(viewport_y_ne, viewport_x_ne); // old viewports had x & y wrong way round
                            SouthWest = new Coordinate(viewport_y_sw, viewport_x_sw); // x is stored as lat y as long
                            mPoint = MapTransforms.TransformCoordinate(Point);
                            mNorthEast = MapTransforms.TransformCoordinate(NorthEast);
                            mSouthWest = MapTransforms.TransformCoordinate(SouthWest);
                            // now write back the m versions
                            updateCmd.Parameters[0].Value = mPoint.Y;
                            updateCmd.Parameters[1].Value = mPoint.X;
                            updateCmd.Parameters[2].Value = mNorthEast.X;
                            updateCmd.Parameters[3].Value = mNorthEast.Y;
                            updateCmd.Parameters[4].Value = mSouthWest.X;
                            updateCmd.Parameters[5].Value = mSouthWest.Y;
                            updateCmd.Parameters[6].Value = location;
                            updateCmd.ExecuteNonQuery();
                            p.Update(++row);
                        }
                    }
                }
                p.Dispose();
            }
            #endregion
        }

        public static string LatLongHashKey(double latitude, double longitude) => latitude.ToString("F6") + longitude.ToString("F6");

        public Dictionary<string, Tuple<string, string>> LatLongIndex
        {
            get
            {
                Dictionary<string, Tuple<string, string>> results = new Dictionary<string, Tuple<string, string>>();

                if (InstanceConnection.State != ConnectionState.Open)
                    InstanceConnection.Open();
                string hashkey;
                string foundlocation;
                string foundresulttype;
                using (SQLiteCommand cmd = new SQLiteCommand(
                    "select distinct latitude, longitude, foundlocation, foundresulttype from geocode where latitude <> 0 and longitude <> 0 and foundlocation<>''", InstanceConnection))
                {
                    using (SQLiteDataReader reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            _ = double.TryParse(reader[0].ToString(), out double latitude);
                            _ = double.TryParse(reader[1].ToString(), out double longitude);
                            hashkey = LatLongHashKey(latitude, longitude);
                            foundlocation = reader[2].ToString();
                            foundresulttype = reader[3].ToString();
                            if (!results.ContainsKey(hashkey))
                                results.Add(hashkey, new Tuple<string, string>(foundlocation, foundresulttype));
                        }
                    }
                }
                return results;
            }
        }
        #endregion

        #region Commands
        public static bool IsLocationInDatabase(string location)
        {
            bool inDatabase;
            if (InstanceConnection.State != ConnectionState.Open)
                InstanceConnection.Open();
            using (SQLiteCommand cmd = new SQLiteCommand("select location from geocode where location = ?", InstanceConnection))
            {
                SQLiteParameter param = cmd.CreateParameter();
                param.DbType = DbType.String;
                cmd.Parameters.Add(param);
                cmd.Prepare();
                cmd.Parameters[0].Value = location;
                using (SQLiteDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleResult))
                {
                    inDatabase = reader.Read();
                }
            }
            return inDatabase;
        }

        public static void ResetPartials()
        {
            if (InstanceConnection.State != ConnectionState.Open)
                InstanceConnection.Open();
            using (SQLiteCommand cmd = new SQLiteCommand("update geocode set latitude = 0, longitude = 0, founddate = date('now'), foundlocation = '', foundlevel = -2, viewport_x_ne = 0, viewport_y_ne = 0, viewport_x_sw = 0, viewport_y_sw = 0, geocodestatus = 0, foundresulttype = '' where geocodestatus in (2,7,9)", InstanceConnection))
            {
                cmd.ExecuteNonQuery();
            }
            InstanceConnection.Close();
        }

        public static void LoadGeoLocations()
        {
            if (InstanceConnection.State != ConnectionState.Open)
                InstanceConnection.Open();
            foreach (FactLocation loc in FactLocation.AllLocations)
            {
                ReadLocationIntoFact(loc, InstanceConnection);
            }
            InstanceConnection.Close();
        }

        public static void GetLocationDetails(FactLocation location)
        {
            if (location is null) return;
            if (string.IsNullOrEmpty(location.ToString())) return;
            if (InstanceConnection.State != ConnectionState.Open)
                InstanceConnection.Open();
            ReadLocationIntoFact(location, InstanceConnection);
        }

        static void ReadLocationIntoFact(FactLocation location, SQLiteConnection conn)
        {
            if (location is null) return;
            using (SQLiteCommand cmd = new SQLiteCommand("select latitude, longitude, latm, longm, viewport_x_ne, viewport_y_ne, viewport_x_sw, viewport_y_sw, geocodestatus, foundlevel, foundlocation, foundresulttype from geocode where location = ?", conn))
            {
                SQLiteParameter param = cmd.CreateParameter();
                param.DbType = DbType.String;
                cmd.Parameters.Add(param);
                cmd.Prepare();
                cmd.Parameters[0].Value = location.ToString();
                using (SQLiteDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
                {
                    if (reader.Read())
                    {
                        double.TryParse(reader["latitude"].ToString(), out double latitude);
                        double.TryParse(reader["longitude"].ToString(), out double longitude);
                        double.TryParse(reader["latm"].ToString(), out double latm);
                        double.TryParse(reader["longm"].ToString(), out double longm);
                        double.TryParse(reader["viewport_x_ne"].ToString(), out double viewport_x_ne);
                        double.TryParse(reader["viewport_y_ne"].ToString(), out double viewport_y_ne);
                        double.TryParse(reader["viewport_x_sw"].ToString(), out double viewport_x_sw);
                        double.TryParse(reader["viewport_y_sw"].ToString(), out double viewport_y_sw);
                        location.Latitude = latitude;
                        location.Longitude = longitude;
                        location.LatitudeM = latm;
                        location.LongitudeM = longm;
                        if (location.ViewPort == null)
                        {
                            location.ViewPort = new GeoResponse.CResult.CGeometry.CViewPort
                            {
                                NorthEast = new GeoResponse.CResult.CGeometry.CLocation(),
                                SouthWest = new GeoResponse.CResult.CGeometry.CLocation()
                            };
                        }
                        location.ViewPort.NorthEast.Lat = viewport_y_ne;
                        location.ViewPort.NorthEast.Long = viewport_x_ne;
                        location.ViewPort.SouthWest.Lat = viewport_y_sw;
                        location.ViewPort.SouthWest.Long = viewport_x_sw;
                        location.GeocodeStatus = (FactLocation.Geocode)Enum.Parse(typeof(FactLocation.Geocode), reader["geocodestatus"].ToString());
                        location.FoundLocation = reader["foundlocation"].ToString();
                        location.FoundResultType = reader["foundresulttype"].ToString();
                        int.TryParse(reader["foundlevel"].ToString(), out int foundlevel);
                        location.FoundLevel = foundlevel;
                    }
                }
                if(location.ViewPort.NorthEast.Lat !=0 && location.ViewPort.NorthEast.Long != 0 &&
                   location.ViewPort.NorthEast.Long >-180 && location.ViewPort.NorthEast.Long < 180) // fix any ViewPorts stored as mPoints
                {
                    location.ViewPort = MapTransforms.TransformViewport(location.ViewPort);
                    UpdateGeocode(location);
                }
            }
        }
        public static void InsertGeocode(FactLocation loc)
        {
            if (loc is null) return;
            if (InstanceConnection.State != ConnectionState.Open)
                InstanceConnection.Open();
            SQLiteParameter param;
            using (SQLiteCommand insertCmd = new SQLiteCommand("insert into geocode (location, level, latitude, longitude, founddate, foundlocation, foundlevel, viewport_x_ne, viewport_y_ne, viewport_x_sw, viewport_y_sw, geocodestatus, foundresulttype, latm, longm) values(?,?,?,?,date('now'),?,?,?,?,?,?,?,?,?,?)", InstanceConnection))
            {
                param = insertCmd.CreateParameter();
                param.DbType = DbType.String;
                insertCmd.Parameters.Add(param);

                param = insertCmd.CreateParameter();
                param.DbType = DbType.Int32;
                insertCmd.Parameters.Add(param);

                param = insertCmd.CreateParameter();
                param.DbType = DbType.Double;
                insertCmd.Parameters.Add(param);

                param = insertCmd.CreateParameter();
                param.DbType = DbType.Double;
                insertCmd.Parameters.Add(param);

                param = insertCmd.CreateParameter();
                param.DbType = DbType.String;
                insertCmd.Parameters.Add(param);

                param = insertCmd.CreateParameter();
                param.DbType = DbType.Int32;
                insertCmd.Parameters.Add(param);

                param = insertCmd.CreateParameter();
                param.DbType = DbType.Double;
                insertCmd.Parameters.Add(param);

                param = insertCmd.CreateParameter();
                param.DbType = DbType.Double;
                insertCmd.Parameters.Add(param);

                param = insertCmd.CreateParameter();
                param.DbType = DbType.Double;
                insertCmd.Parameters.Add(param);

                param = insertCmd.CreateParameter();
                param.DbType = DbType.Double;
                insertCmd.Parameters.Add(param);

                param = insertCmd.CreateParameter();
                param.DbType = DbType.Int32;
                insertCmd.Parameters.Add(param);

                param = insertCmd.CreateParameter();
                param.DbType = DbType.String;
                insertCmd.Parameters.Add(param);

                param = insertCmd.CreateParameter();
                param.DbType = DbType.Double;
                insertCmd.Parameters.Add(param);

                param = insertCmd.CreateParameter();
                param.DbType = DbType.Double;
                insertCmd.Parameters.Add(param);

                insertCmd.Prepare();

                insertCmd.Parameters[0].Value = loc.ToString();
                insertCmd.Parameters[1].Value = loc.Level;
                insertCmd.Parameters[2].Value = loc.Latitude;
                insertCmd.Parameters[3].Value = loc.Longitude;
                insertCmd.Parameters[4].Value = loc.FoundLocation;
                insertCmd.Parameters[5].Value = loc.FoundLevel;
                insertCmd.Parameters[6].Value = loc.ViewPort.NorthEast.Long;
                insertCmd.Parameters[7].Value = loc.ViewPort.NorthEast.Lat;
                insertCmd.Parameters[8].Value = loc.ViewPort.SouthWest.Long;
                insertCmd.Parameters[9].Value = loc.ViewPort.SouthWest.Lat;
                insertCmd.Parameters[10].Value = loc.GeocodeStatus;
                insertCmd.Parameters[11].Value = loc.FoundResultType;
                insertCmd.Parameters[12].Value = loc.LatitudeM;
                insertCmd.Parameters[13].Value = loc.LongitudeM;

                int rowsaffected = insertCmd.ExecuteNonQuery();
            }
        }

        public static void UpdateGeocode(FactLocation loc)
        {
            if (loc is null) return;
            if (InstanceConnection.State != ConnectionState.Open)
                InstanceConnection.Open();
            using (SQLiteCommand updateCmd = new SQLiteCommand("update geocode set founddate=date('now'), level = ?, latitude = ?, longitude = ?, foundlocation = ?, foundlevel = ?, viewport_x_ne = ?, viewport_y_ne = ?, viewport_x_sw = ?, viewport_y_sw = ?, geocodestatus = ?, foundresulttype = ?, latm = ?, longm = ? where location = ?", InstanceConnection))
            {
                SQLiteParameter param = updateCmd.CreateParameter();
                param.DbType = DbType.Int32;
                updateCmd.Parameters.Add(param);

                param = updateCmd.CreateParameter();
                param.DbType = DbType.Double;
                updateCmd.Parameters.Add(param);

                param = updateCmd.CreateParameter();
                param.DbType = DbType.Double;
                updateCmd.Parameters.Add(param);

                param = updateCmd.CreateParameter();
                param.DbType = DbType.String;
                updateCmd.Parameters.Add(param);

                param = updateCmd.CreateParameter();
                param.DbType = DbType.Int32;
                updateCmd.Parameters.Add(param);

                param = updateCmd.CreateParameter();
                param.DbType = DbType.Double;
                updateCmd.Parameters.Add(param);

                param = updateCmd.CreateParameter();
                param.DbType = DbType.Double;
                updateCmd.Parameters.Add(param);

                param = updateCmd.CreateParameter();
                param.DbType = DbType.Double;
                updateCmd.Parameters.Add(param);

                param = updateCmd.CreateParameter();
                param.DbType = DbType.Double;
                updateCmd.Parameters.Add(param);

                param = updateCmd.CreateParameter();
                param.DbType = DbType.Int32;
                updateCmd.Parameters.Add(param);

                param = updateCmd.CreateParameter();
                param.DbType = DbType.String;
                updateCmd.Parameters.Add(param);

                param = updateCmd.CreateParameter();
                param.DbType = DbType.Double;
                updateCmd.Parameters.Add(param);

                param = updateCmd.CreateParameter();
                param.DbType = DbType.Double;
                updateCmd.Parameters.Add(param);

                param = updateCmd.CreateParameter();
                param.DbType = DbType.String;
                updateCmd.Parameters.Add(param);

                updateCmd.Prepare();

                updateCmd.Parameters[0].Value = loc.Level;
                updateCmd.Parameters[1].Value = loc.Latitude;
                updateCmd.Parameters[2].Value = loc.Longitude;
                updateCmd.Parameters[3].Value = loc.FoundLocation;
                updateCmd.Parameters[4].Value = loc.FoundLevel;
                updateCmd.Parameters[5].Value = loc.ViewPort.NorthEast.Long;
                updateCmd.Parameters[6].Value = loc.ViewPort.NorthEast.Lat;
                updateCmd.Parameters[7].Value = loc.ViewPort.SouthWest.Long;
                updateCmd.Parameters[8].Value = loc.ViewPort.SouthWest.Lat;
                updateCmd.Parameters[9].Value = loc.GeocodeStatus;
                updateCmd.Parameters[10].Value = loc.FoundResultType;
                updateCmd.Parameters[11].Value = loc.LatitudeM;
                updateCmd.Parameters[12].Value = loc.LongitudeM;
                updateCmd.Parameters[13].Value = loc.ToString();
                int rowsaffected = updateCmd.ExecuteNonQuery();
                if (rowsaffected != 1)
                    Debug.WriteLine("Problem updating");
                OnGeoLocationUpdated(loc);
            }
        }
        #endregion

        #region LostCousins
        public static int AddLostCousinsFacts()
        {
            int count = 0;
            if (InstanceConnection.State != ConnectionState.Open)
                InstanceConnection.Open();
            using (SQLiteCommand cmd = new SQLiteCommand("select CensusYear, CensusCountry, CensusRef, IndID, FullName from LostCousins", InstanceConnection))
            {
                using (SQLiteDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        string indID = reader["IndID"].ToString();
                        string fullName = reader["FullName"].ToString();
                        Individual ind = FamilyTree.Instance.GetIndividual(indID);
                        if (ind?.Name == fullName) // only load if individual exists in this tree.
                        {
                            string CensusYear = reader["CensusYear"].ToString();
                            string CensusCountry = reader["CensusCountry"].ToString();
                            string CensusRef = reader["CensusRef"].ToString();
                            if (!ind.IsLostCousinsEntered(CensusDate.GetLostCousinsCensusYear(new FactDate(CensusYear), true)))
                            {
                                FactLocation location = FactLocation.GetLocation(CensusCountry);
                                Fact f = new Fact(CensusRef, Fact.LOSTCOUSINS, new FactDate(CensusYear), location, string.Empty, true, true);
                                ind?.AddFact(f);
                            }
                            count++;
                        }
                        else
                        {
                            Console.Write("name wrong");
                            // UpdateFullName(reader, ind.Name); needed during testing
                        }
                    }
                }
            }
            return count;
        }

        //void UpdateFullName(SQLiteDataReader reader, string name)
        //{
        //    using (SQLiteCommand updateCmd = new SQLiteCommand("update LostCousins set FullName=? Where CensusYear=? and CensusCountry=? and CensusRef=? and IndID=?", InstanceConnection))
        //    {
        //        SQLiteParameter param = updateCmd.CreateParameter();
        //        param.DbType = DbType.String;
        //        updateCmd.Parameters.Add(param);
        //        param = updateCmd.CreateParameter();
        //        param.DbType = DbType.Int32;
        //        updateCmd.Parameters.Add(param);
        //        param = updateCmd.CreateParameter();
        //        param.DbType = DbType.String;
        //        updateCmd.Parameters.Add(param);
        //        param = updateCmd.CreateParameter();
        //        param.DbType = DbType.String;
        //        updateCmd.Parameters.Add(param);
        //        param = updateCmd.CreateParameter();
        //        param.DbType = DbType.String;
        //        updateCmd.Parameters.Add(param);
        //        updateCmd.Prepare();

        //        updateCmd.Parameters[0].Value = name;
        //        updateCmd.Parameters[1].Value = reader["CensusYear"];
        //        updateCmd.Parameters[2].Value = reader["CensusCountry"];
        //        updateCmd.Parameters[3].Value = reader["CensusRef"];
        //        updateCmd.Parameters[4].Value = reader["IndID"];
        //        int rowsaffected = updateCmd.ExecuteNonQuery();
        //        if (rowsaffected != 1)
        //            Debug.WriteLine("Problem updating");
        //    }
        //}

        public static bool LostCousinsExists(CensusIndividual ind)
        {
            if (ind is null) return false;
            if (InstanceConnection.State != ConnectionState.Open)
                InstanceConnection.Open();
            bool result = false;
            using (SQLiteCommand cmd = new SQLiteCommand("SELECT EXISTS(SELECT 1 FROM LostCousins where CensusYear=? and CensusCountry=? and CensusRef=? and IndID=?)", InstanceConnection))
            {
                SQLiteParameter param = cmd.CreateParameter();
                param.DbType = DbType.Int32;
                cmd.Parameters.Add(param);
                param = cmd.CreateParameter();
                param.DbType = DbType.String;
                cmd.Parameters.Add(param);
                param = cmd.CreateParameter();
                param.DbType = DbType.String;
                cmd.Parameters.Add(param);
                param = cmd.CreateParameter();
                param.DbType = DbType.String;
                cmd.Parameters.Add(param);
                param = cmd.CreateParameter();
                param.DbType = DbType.String;
                cmd.Parameters.Add(param);
                cmd.Prepare();
                cmd.Parameters[0].Value = ind.CensusDate.BestYear;
                cmd.Parameters[1].Value = ind.CensusCountry;
                cmd.Parameters[2].Value = ind.CensusReference;
                cmd.Parameters[3].Value = ind.IndividualID;
                using (SQLiteDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleResult))
                {
                    if (reader.Read())
                        result = reader[0].ToString() == "1";
                }
            }
            return result;
        }

        public static void StoreLostCousinsFact(CensusIndividual ind, IProgress<string> outputText)
        {
            try
            {
                if (InstanceConnection.State != ConnectionState.Open)
                    InstanceConnection.Open();
                SQLiteParameter param;

                using (SQLiteCommand cmd = new SQLiteCommand("insert into LostCousins (CensusYear, CensusCountry, CensusRef, IndID, FullName) values(?,?,?,?,?)", InstanceConnection))
                {
                    param = cmd.CreateParameter();
                    param.DbType = DbType.Int32;
                    cmd.Parameters.Add(param);
                    param = cmd.CreateParameter();
                    param.DbType = DbType.String;
                    cmd.Parameters.Add(param);
                    param = cmd.CreateParameter();
                    param.DbType = DbType.String;
                    cmd.Parameters.Add(param);
                    param = cmd.CreateParameter();
                    param.DbType = DbType.String;
                    cmd.Parameters.Add(param);
                    param = cmd.CreateParameter();
                    param.DbType = DbType.String;
                    cmd.Parameters.Add(param);
                    cmd.Prepare();

                    if (ind.CensusReference != null)
                    {
                        cmd.Parameters[0].Value = ind.CensusDate.BestYear;
                        cmd.Parameters[1].Value = ind.CensusCountry;
                        cmd.Parameters[2].Value = ind.CensusReference;
                        cmd.Parameters[3].Value = ind.IndividualID;
                        cmd.Parameters[4].Value = ind.Name;

                        int rowsaffected = cmd.ExecuteNonQuery();
                        if (rowsaffected != 1)
                            outputText.Report($"\nProblem updating record in database update affected {rowsaffected} records.");
                    }
                }
            }
            catch (Exception e)
            {
                outputText.Report($"\nFailed to save Lost Cousins record in database error was: {e.Message}");
            }
        }
        #endregion

        #region Custom Facts

        public static bool IgnoreCustomFact(string factType)
        {
            if (InstanceConnection.State != ConnectionState.Open)
                InstanceConnection.Open();
            bool result = false;
            using (SQLiteCommand cmd = new SQLiteCommand("SELECT EXISTS(SELECT ignore FROM CustomFacts where FactType=?)", InstanceConnection))
            {
                SQLiteParameter param = cmd.CreateParameter();
                param.DbType = DbType.String;
                cmd.Parameters.Add(param);
                param = cmd.CreateParameter();
                cmd.Prepare();
                cmd.Parameters[0].Value = factType;
                using (SQLiteDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleResult))
                {
                    if (reader.Read())
                        result = reader[0].ToString() == "1";
                }
            }
            return result;
        }

        public static void IgnoreCustomFact(string factType, bool ignore)
        {
            using (SQLiteCommand cmd = new SQLiteCommand("insert or replace into CustomFacts(FactType,Ignore) values(?,?)", InstanceConnection))
            {
                SQLiteParameter param = cmd.CreateParameter();
                param.DbType = DbType.String;
                cmd.Parameters.Add(param);
                param = cmd.CreateParameter();
                param.DbType = DbType.Boolean;
                cmd.Parameters.Add(param);
                param = cmd.CreateParameter();
                cmd.Prepare();
                cmd.Parameters[0].Value = factType;
                cmd.Parameters[1].Value = ignore;
                int rowsaffected = cmd.ExecuteNonQuery();
            }
        }

            #endregion

            #region Cursor Queries

            public static void AddEmptyLocationsToQueue(ConcurrentQueue<FactLocation> queue)
        {
            if (queue is null) return;
            if (InstanceConnection.State != ConnectionState.Open)
                InstanceConnection.Open();
            using (SQLiteCommand cmd = new SQLiteCommand("select location from geocode where foundlocation='' and geocodestatus in (3, 8, 9) order by level", InstanceConnection))
            {
                using (SQLiteDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        FactLocation loc = FactLocation.LookupLocation(reader[0].ToString());
                        if (!queue.Contains(loc) && loc.Latitude != 0 && loc.Longitude != 0)
                            queue.Enqueue(loc);
                    }
                }
            }
            InstanceConnection.Close();
        }

        //public SQLiteCommand NeedsReverseGeocode()
        //{
        //    return new SQLiteCommand("select location from geocode where foundlocation='' and geocodestatus in (3, 8, 9)", xxx);
        //}

        #endregion

        #region BackupRestore
        public static bool StartBackupRestoreDatabase()
        {
            string tempFilename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Family Tree Analyzer\Geocodes.s3db.tmp");
            try
            {
                GC.Collect(); // needed to force a cleanup of connections prior to replacing the file.
                if (File.Exists(tempFilename))
                    File.Delete(tempFilename);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool RestoreDatabase(IProgress<string> outputText)
        {
            bool result = true;
            try
            {
                // finally check for updates
                restoring = true;
                CheckDatabaseVersion(ProgramVersion);
                restoring = false;
                FamilyTree ft = FamilyTree.Instance;
                if (ft.DataLoaded)
                    return FamilyTree.LoadGeoLocationsFromDataBase(outputText);
            }
            catch (Exception)
            {
                result = false;
            }
            return result;
        }
        #endregion

        #region EventHandler
        public static event EventHandler GeoLocationUpdated;
        protected static void OnGeoLocationUpdated(FactLocation loc)
        {
            GeoLocationUpdated?.Invoke(loc, EventArgs.Empty);
        }
        #endregion
    }
}


text:
<!DOCTYPE html>

	<title>HTML Forms</title>

<form name="registration" method="post" action="http://www.likeateam.com/wp-content/uploads/2012/04/grumpy1.jpg">
	<fieldset>
		<legend>Enter member details: </legend>
		Member name:
		<input id="member"
			   type="text" maxlength="150"
			   required="required"
			   autofocus="autofocus"/> *req

		E-mail:
		<input id="email"
			   type="email" maxlength="70"
			   required="required"
			   pattern="[^@]*@[^ @].[^@]" /> *req

		School:
		<input id="school"
			   type="text"
			   required="required" /> *req

		<input type="image" src="submit.jpg" width="80" alt="Register" name="submitBtn"/>
	</fieldset>
</form>