text:
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com

/* IrbisConnection.cs -- client for IRBIS-server
 * Ars Magna project, http://arsmagna.ru
 * -------------------------------------------------------
 * Status: poor
 */

#region Using directives

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Reflection;

using AM;
using AM.Collections;
using AM.IO;
using AM.Logging;
using AM.Runtime;
using AM.Threading;

using CodeJam;

using JetBrains.Annotations;

using ManagedIrbis.Infrastructure;
using ManagedIrbis.Gbl;
using ManagedIrbis.Infrastructure.Commands;
using ManagedIrbis.Infrastructure.Sockets;
using ManagedIrbis.Search;

using MoonSharp.Interpreter;

#endregion

namespace ManagedIrbis
{
    /// <summary>
    /// Client for IRBIS-server.
    /// </summary>
    [PublicAPI]
    [MoonSharpUserData]
    public class IrbisConnection
        : IIrbisConnection
    {
        #region Constants

        /// <summary>
        /// Таймаут получения ответа от сервера по умолчанию.
        /// </summary>
        public const int DefaultTimeout = 30000;

        #endregion

        #region Events

        /// <summary>
        /// Вызывается перед уничтожением объекта.
        /// </summary>
        public event EventHandler Disposing;

        #endregion

        #region Properties

#if !UAP

        // TODO Implement properly

        /// <summary>
        /// Версия клиента.
        /// </summary>
        public static Version ClientVersion = Assembly
            .GetExecutingAssembly()
            .GetName()
            .Version;

#endif

        /// <summary>
        /// Признак занятости клиента.
        /// </summary>
        [NotNull]
        public BusyState Busy { get; private set; }

        /// <summary>
        /// Адрес сервера.
        /// </summary>
        /// <value>Адрес сервера в цифровом виде.</value>
        [NotNull]
        public string Host
        {
            get { return _host; }
            set
            {
                Code.NotNullNorEmpty(value, "value");

                ThrowIfConnected();
                _host = value;
            }
        }

        /// <summary>
        /// Порт сервера.
        /// </summary>
        /// <value>Порт сервера (по умолчанию 6666).</value>
        public int Port
        {
            get { return _port; }
            set
            {
                Code.Positive(value, "value");

                ThrowIfConnected();
                _port = value;
            }
        }

        /// <summary>
        /// Имя пользователя.
        /// </summary>
        /// <value>Имя пользователя.</value>
        [NotNull]
        public string Username
        {
            get { return _username; }
            set
            {
                Code.NotNullNorEmpty(value, "value");

                ThrowIfConnected();
                _username = value;
            }
        }

        /// <summary>
        /// Пароль пользователя.
        /// </summary>
        /// <value>Пароль пользователя.</value>
        [NotNull]
        public string Password
        {
            get { return _password; }
            set
            {
                Code.NotNull(value, "value");

                ThrowIfConnected();
                _password = value;
            }
        }

        /// <summary>
        /// Имя базы данных.
        /// </summary>
        /// <value>Служебное имя базы данных (например, "IBIS").
        /// </value>
        [NotNull]
        public string Database
        {
            get { return _database; }
            set
            {
                Code.NotNullNorEmpty(value, "value");

                _database = value;
            }
        }

        /// <summary>
        /// Тип АРМ.
        /// </summary>
        /// <value>По умолчанию
        /// <see cref="IrbisWorkstation.Cataloger"/>.
        /// </value>
        public IrbisWorkstation Workstation
        {
            get { return _workstation; }
            set
            {
                ThrowIfConnected();
                _workstation = value;
            }
        }

        /// <summary>
        /// Идентификатор клиента.
        /// </summary>
        public int ClientID { get { return _clientID; } }

        /// <summary>
        /// Номер команды.
        /// </summary>
        public int QueryID { get { return _queryID; } }

        /// <summary>
        /// Executive engine.
        /// </summary>
        [NotNull]
        public AbstractEngine Executive { get; private set; }

        /// <summary>
        /// Command factory.
        /// </summary>
        [NotNull]
        public CommandFactory CommandFactory { get; private set; }

        /// <summary>
        /// Remote INI-file for the client.
        /// </summary>
        [CanBeNull]
        public IniFile IniFile
        {
            get { return _iniFile; }
        }

        /// <summary>
        /// Server version.
        /// </summary>
        [CanBeNull]
        public IrbisVersion ServerVersion { get; internal set; }

        /// <summary>
        /// Статус подключения к серверу.
        /// </summary>
        /// <value>Устанавливается в true при успешном выполнении
        /// <see cref="Connect"/>, сбрасывается при выполнении
        /// <see cref="Dispose"/>.
        /// </value>
        public bool Connected
        {
            get { return _connected; }
        }

        /// <summary>
        /// Флаг отключения.
        /// </summary>
        public bool Disposed
        {
            get { return _disposed; }
        }

        /// <summary>
        /// Таймаут получения ответа от сервера в миллисекундах
        /// (для продвинутых функций).
        /// </summary>
        [DefaultValue(DefaultTimeout)]
        public int Timeout { get; set; }

        /// <summary>
        /// Признак: команда прервана.
        /// </summary>
        [DefaultValue(false)]
        public bool Interrupted { get; internal set; }

        /// <summary>
        /// Socket.
        /// </summary>
        [NotNull]
        public AbstractClientSocket Socket { get; private set; }

        /// <summary>
        /// Arbitrary user data.
        /// </summary>
        [CanBeNull]
        public object UserData { get; set; }

        #endregion

        #region Construction

        /// <summary>
        /// Конструктор по умолчанию
        /// </summary>
        /// <remarks>
        /// Обратите внимание, деструктор не нужен!
        /// Он помешает сохранению состояния клиента
        /// при сериализации и последующему восстановлению,
        /// т. к. попытается закрыть уже установленное
        /// соединение. Восстановленная копия клиента
        /// ломанётся в закрытое соедиение, и выйдет облом.
        /// </remarks>
        public IrbisConnection()
        {
            Log.Trace("IrbisConnection::Constructor");

            Busy = new BusyState();

            Host = ConnectionSettings.DefaultHost;
            Port = ConnectionSettings.DefaultPort;
            Database = ConnectionSettings.DefaultDatabase;
            //Username = "111";
            //Password = "111";
            Workstation = ConnectionSettings.DefaultWorkstation;

            Executive = new StandardEngine(this, null);
            CommandFactory = CommandFactory
                .GetDefaultFactory(this);
            Socket = new SimpleClientSocket(this);
        }

        /// <summary>
        /// Конструктор с подключением.
        /// </summary>
        public IrbisConnection
            (
                [NotNull] string connectionString
            )
            : this()
        {
            Code.NotNullNorEmpty(connectionString, "connectionString");

            // ReSharper disable VirtualMemberCallInConstructor
            ParseConnectionString(connectionString); //-V3068
            Connect(); //-V3068
            // ReSharper restore VirtualMemberCallInConstructor
        }

        #endregion

        #region Private members

        // ReSharper disable InconsistentNaming
        internal bool _connected;
        internal bool _disposed;
        private int _clientID;
        private int _queryID;
        // ReSharper restore InconsistentNaming

        private static Random _random = new Random();

        private readonly Stack<string> _databaseStack
            = new Stack<string>();

        private string _host;
        private int _port;
        private string _username;
        private string _password;
        private string _database;
        private IrbisWorkstation _workstation;

        private IniFile _iniFile;

        /// <summary>
        /// Raw last client query.
        /// </summary>
        [CanBeNull]
        internal byte[][] RawClientRequest { get; set; }

        /// <summary>
        /// Raw last server response.
        /// </summary>
        [CanBeNull]
        internal byte[] RawServerResponse { get; set; }

        internal void ThrowIfConnected()
        {
            if (Connected)
            {
                throw new IrbisException("Already connected");
            }
        }

        // ReSharper disable InconsistentNaming
        internal int GenerateClientID()
        {
            _clientID = _random.Next(1000000, 9999999);

            return _clientID;
        }
        // ReSharper restore InconsistentNaming

        internal int IncrementCommandNumber()
        {
            return ++_queryID;
        }

        internal void ResetCommandNumber()
        {
            _queryID = 0;
        }

        #endregion

        // =========================================================

        #region Public methods

        /// <inheritdoc cref="IIrbisConnection.ActualizeRecord" />
        public virtual void ActualizeRecord
            (
                string database,
                int mfn
            )
        {
            Code.NotNullNorEmpty(database, "database");
            Code.Nonnegative(mfn, "mfn");

            ActualizeRecordCommand command
                = CommandFactory.GetActualizeRecordCommand();
            command.Database = database;
            command.Mfn = mfn;

            ExecuteCommand(command);
        }

        // =========================================================

        /// <inheritdoc cref="IIrbisConnection.Clone()" />
        public virtual IrbisConnection Clone()
        {
            IrbisConnection result = Clone(Connected);

            return result;
        }

        /// <inheritdoc cref="IIrbisConnection.Clone(bool)" />
        public virtual IrbisConnection Clone
            (
                bool connect
            )
        {
            // TODO clone socket?

            IrbisConnection result = new IrbisConnection
            {
                Host = Host,
                Port = Port,
                Username = Username,
                Password = Password,
                Database = Database,
                Workstation = Workstation,
                Timeout = Timeout,
                // Socket = Socket.Clone ()
            };

            if (connect)
            {
                result.Connect();
            }

            return result;
        }

        // ========================================================

        /// <inheritdoc cref="IIrbisConnection.Connect" />
        public virtual IniFile Connect()
        {
            // TODO use Executive

            if (!_connected)
            {
                Log.Trace
                    (
                        "IrbisConnection::Connect"
                    );

                ConnectCommand command = CommandFactory.GetConnectCommand();
                ClientQuery query = command.CreateQuery();
                ServerResponse response = command.Execute(query);
                command.CheckResponse(response);
                _connected = true;

                string iniText = command.Configuration
                    .ThrowIfNull("command.Configuration");
                IniFile result = new IniFile();
                StringReader reader = new StringReader(iniText);
                result.Read(reader);
                _iniFile = result;

                if (!string.IsNullOrEmpty(command.ServerVersion))
                {
                    ServerVersion = new IrbisVersion
                    {
                        Version = command.ServerVersion
                    };
                }

                return result;
            }

            return _iniFile;
        }

        // ========================================================

        /// <inheritdoc cref="IIrbisConnection.CorrectVirtualRecord(string,MarcRecord,GblStatement[])"/>
        public virtual MarcRecord CorrectVirtualRecord
            (
                string database,
                MarcRecord record,
                GblStatement[] statements
            )
        {
            Code.NotNullNorEmpty(database, "database");
            Code.NotNull(record, "record");
            Code.NotNull(statements, "statements");

            GblVirtualCommand command = CommandFactory.GetGblVirtualCommand();
            command.Database = database;
            command.Record = record;
            command.Statements = statements;

            ExecuteCommand(command);

            return command.Result
                .ThrowIfNull("command.Result");
        }

        /// <inheritdoc cref="IIrbisConnection.CorrectVirtualRecord(string,MarcRecord,string)"/>
        public virtual MarcRecord CorrectVirtualRecord
            (
                string database,
                MarcRecord record,
                string filename
            )
        {
            Code.NotNullNorEmpty(database, "database");
            Code.NotNull(record, "record");
            Code.NotNullNorEmpty(filename, "filename");

            GblVirtualCommand command = CommandFactory.GetGblVirtualCommand();
            command.Database = database;
            command.Record = record;
            command.FileName = filename;

            ExecuteCommand(command);

            return command.Result
                .ThrowIfNull("command.Result");
        }

        // ========================================================

        /// <inheritdoc cref="IIrbisConnection.CreateDatabase" />
        public virtual void CreateDatabase
            (
                string databaseName,
                string description,
                bool readerAccess,
                string template
            )
        {
            Code.NotNullNorEmpty(databaseName, "databaseName");
            Code.NotNullNorEmpty(description, "description");

            CreateDatabaseCommand command
                = CommandFactory.GetCreateDatabaseCommand();
            command.Database = databaseName;
            command.Description = description;
            command.ReaderAccess = readerAccess;
            command.Template = template;

            ExecuteCommand(command);
        }

        // =========================================================

        /// <inheritdoc cref="IIrbisConnection.CreateDictionary" />
        public virtual void CreateDictionary
            (
                string database
            )
        {
            Code.NotNullNorEmpty(database, "database");

            CreateDictionaryCommand command
                = CommandFactory.GetCreateDictionaryCommand();
            command.Database = database;
            command.RelaxResponse = true;

            ExecuteCommand(command);
        }

        // ========================================================

        /// <inheritdoc cref="IIrbisConnection.DeleteDatabase" />
        public virtual void DeleteDatabase
            (
                string database
            )
        {
            Code.NotNullNorEmpty(database, "database");

            DeleteDatabaseCommand command
                = CommandFactory.GetDeleteDatabaseCommand();
            command.Database = database;

            ExecuteCommand(command);
        }

        // =========================================================

        #region ExecuteCommand

        /// <inheritdoc cref="IIrbisConnection.ExecuteCommand(AbstractCommand)" />
        public virtual ServerResponse ExecuteCommand
            (
                AbstractCommand command
            )
        {
            Code.NotNull(command, "command");

            Log.Trace("IrbisConnection::ExecuteCommand");

            RawClientRequest = null;
            RawServerResponse = null;

            ExecutionContext context = new ExecutionContext
                (
                    this,
                    command
                );
            ServerResponse result = Executive.ExecuteCommand(context);

            RawClientRequest = null;
            RawServerResponse = null;

            return result;
        }

        /// <inheritdoc cref="IIrbisConnection.ExecuteCommand(string,object[])" />
        public virtual ServerResponse ExecuteCommand
            (
                string commandCode,
                params object[] arguments
            )
        {
            Code.NotNullNorEmpty(commandCode, "commandCode");

            UniversalCommand command
                = CommandFactory.GetUniversalCommand
                (
                    commandCode,
                    arguments
                );

            return ExecuteCommand(command);
        }

        #endregion

        // =========================================================

        #region FormatRecord

        /// <inheritdoc cref="IIrbisConnection.FormatRecord(string,int)" />
        public virtual string FormatRecord
            (
                string format,
                int mfn
            )
        {
            Code.NotNull(format, "format");
            Code.Positive(mfn, "mfn");

            FormatCommand command = CommandFactory.GetFormatCommand();
            command.FormatSpecification = format;
            command.MfnList.Add(mfn);

            ExecuteCommand(command);

            string result = command.FormatResult
                .ThrowIfNullOrEmpty("command.FormatResult")
                [0];

            return result;
        }

        /// <inheritdoc cref="IIrbisConnection.FormatRecord(string,MarcRecord)" />
        public string FormatRecord
            (
                string format,
                MarcRecord record
            )
        {
            Code.NotNull(format, "format");
            Code.NotNull(record, "record");

            FormatCommand command = CommandFactory.GetFormatCommand();
            command.FormatSpecification = format;
            command.VirtualRecord = record;

            ExecuteCommand(command);

            string result = command.FormatResult
                .ThrowIfNullOrEmpty("command.FormatResult")
                [0];

            return result;
        }

        /// <inheritdoc cref="IIrbisConnection.FormatRecords" />
        public virtual string[] FormatRecords
            (
                string database,
                string format,
                IEnumerable<int> mfnList
            )
        {
            Code.NotNull(mfnList, "mfnList");
            Code.NotNullNorEmpty(database, "database");
            Code.NotNull(format, "format");

            FormatCommand command = CommandFactory.GetFormatCommand();
            command.Database = database;
            command.FormatSpecification = format;
            command.MfnList.AddRange(mfnList);

            if (command.MfnList.Count == 0)
            {
                return StringUtility.EmptyArray;
            }

            ExecuteCommand(command);

            string[] result = command.FormatResult
                .ThrowIfNull("command.FormatResult");

            return result;
        }

        #endregion

        // =========================================================

        /// <inheritdoc cref="IIrbisConnection.GetDatabaseInfo" />
        public virtual DatabaseInfo GetDatabaseInfo
            (
                string databaseName
            )
        {
            Code.NotNullNorEmpty(databaseName, "databaseName");

            DatabaseInfoCommand command
                = CommandFactory.GetDatabaseInfoCommand();
            command.Database = databaseName;

            ExecuteCommand(command);
            DatabaseInfo result = command.Result
                .ThrowIfNull("command.Result");

            return result;
        }

        // =========================================================

        /// <inheritdoc cref="IIrbisConnection.GetDatabaseStat" />
        public virtual string GetDatabaseStat
            (
                StatDefinition definition
            )
        {
            Code.NotNull(definition, "definition");

            DatabaseStatCommand command
                = CommandFactory.GetDatabaseStatCommand();
            command.Definition = definition;

            ExecuteCommand(command);
            string result = command.Result
                .ThrowIfNull("command.Result");

            return result;
        }

        // =========================================================

        /// <inheritdoc cref="IIrbisConnection.GetMaxMfn()" />
        public virtual int GetMaxMfn()
        {
            return GetMaxMfn(Database);
        }

        /// <inheritdoc cref="IIrbisConnection.GetMaxMfn(string)" />
        public virtual int GetMaxMfn
            (
                string database
            )
        {
            if (ReferenceEquals(database, null))
            {
                database = Database;
            }

            MaxMfnCommand command = CommandFactory.GetMaxMfnCommand();
            command.Database = database;

            ServerResponse response = ExecuteCommand(command);
            int result = response.ReturnCode;

            return result;
        }

        // =========================================================

        /// <inheritdoc cref="IIrbisConnection.GetRecordPostings" />
        public virtual TermPosting[] GetRecordPostings
            (
                int mfn,
                string prefix
            )
        {
            GetRecordPostingsCommand command = CommandFactory.GetRecordPostingsCommand();
            command.Mfn = mfn;
            command.Prefix = prefix;

            ExecuteCommand(command);
            TermPosting[] result = command.Result;

            return result;
        }

        // =========================================================

        /// <inheritdoc cref="IIrbisConnection.GetServerStat" />
        public virtual ServerStat GetServerStat()
        {
            ServerStatCommand command
                = CommandFactory.GetServerStatCommand();
            ExecuteCommand(command);

            ServerStat result = command.Result
                .ThrowIfNull("command.Result");

            return result;
        }

        // =========================================================

        /// <inheritdoc cref="IIrbisConnection.GetServerVersion" />
        public virtual IrbisVersion GetServerVersion()
        {
            ServerVersionCommand command
                = CommandFactory.GetServerVersionCommand();
            ExecuteCommand(command);

            IrbisVersion result = command.Result
                .ThrowIfNull("command.Result");

            ServerVersion = result;

            return result;
        }

        // =========================================================

        /// <inheritdoc cref="IIrbisConnection.GlobalCorrection" />
        public virtual GblResult GlobalCorrection
            (
                GblSettings settings
            )
        {
            Code.NotNull(settings, "settings");

            if (string.IsNullOrEmpty(settings.Database))
            {
                settings.Database = Database;
            }

            GblCommand command
                = CommandFactory.GetGblCommand(settings);

            ExecuteCommand(command);

            return command.Result
                .ThrowIfNull("command.Result");
        }

        // =========================================================

        /// <inheritdoc cref="IIrbisConnection.ListFiles(FileSpecification)" />
        public virtual string[] ListFiles
            (
                FileSpecification specification
            )
        {
            Code.NotNull(specification, "specification");

            specification.Verify(true);

            ListFilesCommand command = new ListFilesCommand(this);
            command.Specifications.Add(specification);

            ExecuteCommand(command);

            string[] result = command.Files
                .ThrowIfNull("command.Files");

            return result;
        }

        /// <inheritdoc cref="IIrbisConnection.ListFiles(FileSpecification[])" />
        public virtual string[] ListFiles
            (
                FileSpecification[] specifications
            )
        {
            Code.NotNull(specifications, "specifications");

            ListFilesCommand command = new ListFilesCommand(this);
            foreach (FileSpecification specification in specifications)
            {
                specification.Verify(true);
                command.Specifications.Add(specification);
            }

            ExecuteCommand(command);

            string[] result = command.Files
                .ThrowIfNull("command.Files");

            return result;
        }

        // =========================================================

        /// <inheritdoc cref="IIrbisConnection.ListProcesses" />
        public virtual IrbisProcessInfo[] ListProcesses()
        {
            ListProcessesCommand command
                = CommandFactory.GetListProcessCommand();
            ExecuteCommand(command);

            IrbisProcessInfo[] result = command.Result
                .ThrowIfNullOrEmpty("command.Result");

            return result;
        }

        // =========================================================

        /// <inheritdoc cref="IIrbisConnection.ListUsers" />
        public virtual UserInfo[] ListUsers()
        {
            ListUsersCommand command
                = CommandFactory.GetListUsersCommand();
            ExecuteCommand(command);

            UserInfo[] result = command.Result
                .ThrowIfNull("command.Result");

            return result;
        }

        // =========================================================

        /// <inheritdoc cref="IIrbisConnection.NoOp" />
        public virtual void NoOp()
        {
            NopCommand command = CommandFactory.GetNopCommand();

            ExecuteCommand(command);
        }

        /// <inheritdoc cref="IIrbisConnection.ParseConnectionString" />
        public virtual void ParseConnectionString
            (
                string connectionString
            )
        {
            Code.NotNull(connectionString, "connectionString");

            ConnectionSettings settings = new ConnectionSettings();
            settings.ParseConnectionString(connectionString);
            settings.ApplyToConnection(this);
        }

        // ========================================================

        /// <inheritdoc cref="IIrbisConnection.PopDatabase" />
        public virtual string PopDatabase()
        {
            string result = Database;

            if (_databaseStack.Count != 0)
            {
                Database = _databaseStack.Pop();
            }

            return result;
        }

        // ========================================================

        /// <inheritdoc cref="IIrbisConnection.PrintTable" />
        public virtual string PrintTable
            (
                TableDefinition tableDefinition
            )
        {
            Code.NotNull(tableDefinition, "tableDefinition");

            PrintTableCommand command
                = CommandFactory.GetPrintTableCommand();
            command.Definition = tableDefinition;

            ExecuteCommand(command);

            return command.Result;
        }

        // ========================================================

        /// <inheritdoc cref="IIrbisConnection.PushDatabase" />
        public virtual string PushDatabase
            (
                string newDatabase
            )
        {
            Code.NotNullNorEmpty(newDatabase, "newDatabase");

            string result = Database;
            _databaseStack.Push(Database);
            Database = newDatabase;

            return result;
        }

        // ========================================================

        /// <summary>
        /// Read binary file from server file system.
        /// </summary>
        [CanBeNull]
        public virtual byte[] ReadBinaryFile
            (
                FileSpecification file
            )
        {
            Code.NotNull(file, "file");

            ReadBinaryFileCommand command
                = CommandFactory.GetReadBinaryFileCommand();
            command.File = file;

            ExecuteCommand(command);

            return command.Content;
        }

        // ========================================================

        /// <summary>
        /// Read term postings.
        /// </summary>
        [NotNull]
        public virtual TermPosting[] ReadPostings
            (
                PostingParameters parameters
            )
        {
            Code.NotNull(parameters, "parameters");

            ReadPostingsCommand command
                = CommandFactory.GetReadPostingsCommand();
            command.ApplyParameters(parameters);

            ExecuteCommand(command);

            return command.Postings
                .ThrowIfNull("command.Postings");
        }

        // ========================================================

        #region ReadRecord

        /// <summary>
        /// Чтение, блокирование и расформатирование записи.
        /// </summary>
        [NotNull]
        public virtual MarcRecord ReadRecord
            (
                string database,
                int mfn,
                bool lockFlag,
                string format
            )
        {
            Code.NotNullNorEmpty(database, "database");
            Code.Positive(mfn, "mfn");

            ReadRecordCommand command = CommandFactory.GetReadRecordCommand();
            command.Mfn = mfn;
            command.Database = database;
            command.Lock = lockFlag;
            command.Format = format;

            ExecuteCommand(command);

            return command.Record
                .ThrowIfNull("no record retrieved");
        }

        /// <summary>
        /// Чтение указанной версии и расформатирование записи.
        /// </summary>
        /// <remarks><c>null</c>означает, что затребованной
        /// версии записи нет.</remarks>
        [CanBeNull]
        public virtual MarcRecord ReadRecord
            (
                string database,
                int mfn,
                int versionNumber,
                string format
            )
        {
            Code.NotNullNorEmpty(database, "database");
            Code.Positive(mfn, "mfn");

            ReadRecordCommand command = CommandFactory.GetReadRecordCommand();
            command.Mfn = mfn;
            command.Database = database;
            command.VersionNumber = versionNumber;
            command.Format = format;

            ExecuteCommand(command);

            return command.Record;
        }

        #endregion

        // ========================================================

        /// <summary>
        /// Read search terms from index.
        /// </summary>
        [NotNull]
        public virtual TermInfo[] ReadTerms
            (
                TermParameters parameters
            )
        {
            Code.NotNull(parameters, "parameters");

            ReadTermsCommand command = CommandFactory.GetReadTermsCommand();
            command.ApplyParameters(parameters);

            ExecuteCommand(command);

            return command.Terms.ThrowIfNull("command.Terms");
        }

        // ========================================================

        /// <summary>
        /// Read text file from the server.
        /// </summary>
        [CanBeNull]
        public virtual string ReadTextFile
            (
                FileSpecification fileSpecification
            )
        {
            Code.NotNull(fileSpecification, "fileSpecification");

            ReadFileCommand command = new ReadFileCommand(this);
            command.Files.Add(fileSpecification);

            ExecuteCommand(command);
            string result = command.Result
                .ThrowIfNullOrEmpty("command.Result")[0];

            return result;
        }

        /// <summary>
        /// Чтение текстовых файлов с сервера.
        /// </summary>
        [NotNull]
        public virtual string[] ReadTextFiles
            (
                FileSpecification[] files
            )
        {
            Code.NotNull(files, "files");

            if (files.Length == 0)
            {
                return StringUtility.EmptyArray;
            }

            ReadFileCommand command = CommandFactory.GetReadFileCommand();
            command.Files.AddRange(files);

            ExecuteCommand(command);

            string[] result = command.Result
                .ThrowIfNullOrEmpty("command.Result");

            return result;
        }

        // =========================================================

        /// <summary>
        /// Reconnect to the server.
        /// </summary>
        public virtual void Reconnect()
        {
            Log.Trace
                (
                    "IrbisConnection::Reconnect"
                );

            if (_connected)
            {
                DisconnectCommand command
                    = CommandFactory.GetDisconnectCommand();

                ExecuteCommand(command);
            }

            if (!ReferenceEquals(_iniFile, null))
            {
                _iniFile.Dispose();
                _iniFile = null;
            }

            Connect();
        }

        // =========================================================

        /// <summary>
        /// Reload dictionary index for specified database.
        /// </summary>
        /// <remarks>For Administrator only.</remarks>
        public virtual void ReloadDictionary
            (
                string databaseName
            )
        {
            Code.NotNullNorEmpty(databaseName, "databaseName");

            ReloadDictionaryCommand command
                = CommandFactory.GetReloadDictionaryCommand();
            command.Database = databaseName;

            ExecuteCommand(command);
        }

        // =========================================================

        /// <summary>
        /// Reload master file for specified database.
        /// </summary>
        /// <remarks>For Administrator only.</remarks>
        public virtual void ReloadMasterFile
            (
                string databaseName
            )
        {
            Code.NotNullNorEmpty(databaseName, "databaseName");

            ReloadMasterFileCommand command
                = CommandFactory.GetReloadMasterFileCommand();
            command.Database = databaseName;

            ExecuteCommand(command);
        }

        // =========================================================

        /// <summary>
        /// Restart server.
        /// </summary>
        /// <remarks>For Administrator only.</remarks>
        public virtual void RestartServer()
        {
            RestartServerCommand command
                = CommandFactory.GetRestartServerCommand();

            ExecuteCommand(command);
        }

        // =========================================================

        /// <summary>
        /// Restore previously suspended connection.
        /// </summary>
        [NotNull]
        public static IrbisConnection Restore
            (
                [NotNull] string state
            )
        {
            Code.NotNullNorEmpty(state, "state");

            ConnectionSettings settings = ConnectionSettings.Decrypt(state);

            if (ReferenceEquals(settings, null))
            {
                throw new IrbisException
                    (
                        "Decrypted state is null"
                    );
            }

            IrbisConnection result = new IrbisConnection();
            settings.ApplyToConnection(result);

            return result;
        }

        // =========================================================

        /// <summary>
        /// Восстановление флага подключения, ранее погашенного
        /// при помощи <see cref="Suspend"/>.
        /// </summary>
        public virtual void Rise()
        {
            _connected = true;
        }

        // =========================================================

        /// <summary>
        /// Поиск записей.
        /// </summary>
        [NotNull]
        public virtual int[] Search
            (
                string expression
            )
        {
            Code.NotNull(expression, "expression");

            SearchCommand command = CommandFactory.GetSearchCommand();
            command.SearchExpression = expression;

            ExecuteCommand(command);

            int[] result = FoundItem.ConvertToMfn
                (
                    command.Found.ThrowIfNull("Found")
                );

            return result;
        }

        // =========================================================

        /// <summary>
        /// Sequential search.
        /// </summary>
        [NotNull]
        public virtual int[] SequentialSearch
            (
                SearchParameters parameters
            )
        {
            Code.NotNull(parameters, "parameters");

            SearchCommand command = CommandFactory.GetSearchCommand();
            command.ApplyParameters(parameters);

            ExecuteCommand(command);

            int[] result = FoundItem.ConvertToMfn
                (
                    command.Found.ThrowIfNull("Found")
                );

            return result;
        }

        // =========================================================

        /// <summary>
        /// Set new <see cref="CommandFactory"/>.
        /// </summary>
        /// <returns>Previous <see cref="CommandFactory"/>.
        /// </returns>
        [NotNull]
        public virtual CommandFactory SetCommandFactory
            (
                CommandFactory newFactory
            )
        {
            Code.NotNull(newFactory, "newFactory");

            CommandFactory previous = CommandFactory;
            newFactory.Connection = this;
            CommandFactory = newFactory;

            return previous;
        }

        /// <summary>
        /// Set new <see cref="CommandFactory"/>.
        /// </summary>
        /// <returns>Previous <see cref="CommandFactory"/>.
        /// </returns>
        [NotNull]
        public virtual CommandFactory SetCommandFactory
            (
                string typeName
            )
        {
            Code.NotNull(typeName, "typeName");

#if !WINMOBILE && !PocketPC

            Type type = Type.GetType(typeName, true);
            CommandFactory newFactory
                = (CommandFactory)Activator.CreateInstance
                (
                    type,
                    this
                );
            CommandFactory previous = SetCommandFactory(newFactory);

            return previous;

#else
            return CommandFactory;

#endif
        }

        // =========================================================

        /// <summary>
        /// Set execution engine.
        /// </summary>
        [NotNull]
        public virtual AbstractEngine SetEngine
            (
                AbstractEngine engine
            )
        {
            Code.NotNull(engine, "engine");

            AbstractEngine previous = Executive;
            Executive = engine;

            return previous;
        }

        /// <summary>
        /// Set new <see cref="Executive"/>.
        /// </summary>
        /// <returns>Previous <see cref="Executive"/>.
        /// </returns>
        [NotNull]
        public virtual AbstractEngine SetEngine
            (
                string typeName
            )
        {
            Code.NotNull(typeName, "typeName");

#if !WINMOBILE && !PocketPC

            Type type = Type.GetType(typeName, true);
            AbstractEngine newEngine
                = (AbstractEngine)Activator.CreateInstance
                (
                    type,
                    this,
                    Executive
                );
            AbstractEngine previous = SetEngine(newEngine);

            return previous;

#else

            return Executive;

#endif
        }

        // =========================================================

        /// <summary>
        /// Set logging socket, gather debug info to specified path.
        /// </summary>
        public virtual void SetNetworkLogging
            (
                string loggingPath
            )
        {
            Code.NotNullNorEmpty(loggingPath, "loggingPath");

#if !WINMOBILE && !PocketPC

            AbstractClientSocket oldSocket = Socket;
            if (oldSocket is LoggingClientSocket)
            {
                return;
            }

            LoggingClientSocket newSocket = new LoggingClientSocket
                (
                    this,
                    Socket,
                    loggingPath
                );

            SetSocket(newSocket);

#endif

        }

        // =========================================================

        /// <summary>
        ///
        /// </summary>
        public virtual void SetRetry
            (
                int retryCount,
                Func<Exception, bool> resolver
            )
        {
            RetryClientSocket oldSocket
                = ClientSocketUtility.FindSocket<RetryClientSocket>(this);

            if (retryCount <= 0)
            {
                if (!ReferenceEquals(oldSocket, null))
                {
                    SetSocket
                        (
                            oldSocket.InnerSocket
                            .ThrowIfNull("oldSocket.InnerSocket")
                        );
                }
            }
            else
            {
                RetryClientSocket newSocket = new RetryClientSocket
                    (
                        this,
                        Socket,
                        new RetryManager(retryCount, resolver)
                    );

                if (ReferenceEquals(oldSocket, null))
                {
                    SetSocket(newSocket);
                }
            }
        }

        // =========================================================

        /// <summary>
        /// Set
        /// <see cref="T:ManagedIrbis.Network.Sockets.AbstractClientSocket"/>.
        /// </summary>
        public virtual void SetSocket
            (
                AbstractClientSocket socket
            )
        {
            Code.NotNull(socket, "socket");

            if (Connected)
            {
                throw new IrbisException
                    (
                        "Can't set socket while connected"
                    );
            }

            socket.Connection = this;
            Socket = socket;
        }

        // =========================================================

        /// <summary>
        /// Temporary "shutdown" the connection for some reason.
        /// </summary>
        /// <seealso cref="Restore"/>
        /// <seealso cref="Rise"/>
        [NotNull]
        public virtual string Suspend()
        {
            ConnectionSettings settings
                = ConnectionSettings.FromConnection(this);
            string result = settings.Encrypt();

            _connected = false;

            return result;
        }

        // =========================================================

        /// <summary>
        /// Опустошение базы данных.
        /// </summary>
        /// <remarks>For Administrator only.</remarks>
        public virtual void TruncateDatabase
            (
                string databaseName
            )
        {
            Code.NotNullNorEmpty(databaseName, "databaseName");

            TruncateDatabaseCommand command
                = CommandFactory.GetTruncateDatabaseCommand();
            command.Database = databaseName;

            ExecuteCommand(command);
        }

        // =========================================================

        /// <summary>
        /// Unlock the specified database.
        /// </summary>
        /// <remarks>For Administrator only.</remarks>
        public virtual void UnlockDatabase
            (
                string databaseName
            )
        {
            Code.NotNullNorEmpty(databaseName, "databaseName");

            UnlockDatabaseCommand command
                = CommandFactory.GetUnlockDatabaseCommand();
            command.Database = databaseName;

            ExecuteCommand(command);
        }

        // =========================================================

        /// <summary>
        /// Unlock specified records.
        /// </summary>
        public virtual void UnlockRecords
            (
                string database,
                params int[] mfnList
            )
        {
            // TODO: write UnlockRecordsTest

            Code.NotNullNorEmpty(database, "database");

            if (mfnList.Length == 0)
            {
                return;
            }

            UnlockRecordsCommand command
                = CommandFactory.GetUnlockRecordsCommand();
            command.Database = database;
            command.Records.AddRange(mfnList);

            ExecuteCommand(command);
        }

        // =========================================================

        /// <summary>
        /// Update server INI-file for current client.
        /// </summary>
        public virtual void UpdateIniFile
            (
                string[] lines
            )
        {
            if (lines.IsNullOrEmpty())
            {
                return;
            }

            UpdateIniFileCommand command
                = CommandFactory.GetUpdateIniFileCommand();
            command.Lines = lines;

            ExecuteCommand(command);
        }

        // ========================================================

        /// <inheritdoc cref="IIrbisConnection.UpdateUserList" />
        public virtual void UpdateUserList
            (
                UserInfo[] userList
            )
        {
            Code.NotNull(userList, "userList");

            UpdateUserListCommand command
                = CommandFactory.GetUpdateUserListCommand();
            command.UserList = userList;

            ExecuteCommand(command);
        }

        // ========================================================

        #region WriteRecord

        /// <inheritdoc cref="IIrbisConnection.WriteRecord(ManagedIrbis.MarcRecord,bool,bool,bool)" />
        public virtual MarcRecord WriteRecord
            (
                MarcRecord record,
                bool lockFlag,
                bool actualize,
                bool dontParseResponse
            )
        {
            Code.NotNull(record, "record");

            WriteRecordCommand command = new WriteRecordCommand(this)
            {
                Record = record,
                Actualize = actualize,
                Lock = lockFlag,
                DontParseResponse = dontParseResponse
            };

            ExecuteCommand(command);

            MarcRecord result = command.Record;

            if (ReferenceEquals(result, null))
            {
                throw new IrbisException("result record is null");
            }

            return result;
        }

        // ========================================================

        /// <inheritdoc cref="IIrbisConnection.WriteRecords" />
        public virtual MarcRecord[] WriteRecords
            (
                MarcRecord[] records,
                bool lockFlag,
                bool actualize
            )
        {
            Code.NotNull(records, "records");

            if (records.Length == 0)
            {
                return records;
            }

            WriteRecordsCommand command = new WriteRecordsCommand(this)
            {
                Actualize = actualize,
                Lock = lockFlag
            };
            foreach (MarcRecord record in records)
            {
                RecordReference reference = new RecordReference(record)
                {
                    HostName = Host,
                    Database = Database
                };
                command.References.Add(reference);
            }

            ExecuteCommand(command);

            return records;
        }

        #endregion

        // ========================================================

        /// <inheritdoc cref="IIrbisConnection.WriteTextFile" />
        public virtual void WriteTextFile
            (
                FileSpecification file
            )
        {
            Code.NotNull(file, "file");

            WriteFileCommand command
                = CommandFactory.GetWriteFileCommand();
            command.Files.Add(file);

            ExecuteCommand(command);
        }

        /// <inheritdoc cref="IIrbisConnection.WriteTextFiles" />
        public virtual void WriteTextFiles
            (
                params FileSpecification[] files
            )
        {
            WriteFileCommand command = CommandFactory.GetWriteFileCommand();
            foreach (FileSpecification file in files)
            {
                command.Files.Add(file);
            }

            ExecuteCommand(command);
        }

        #endregion

        #region IDisposable members

        /// <inheritdoc cref="IDisposable.Dispose" />
        public virtual void Dispose()
        {
            Log.Trace("IrbisConnection::Dispose");

            Disposing.Raise(this);

            if (_disposed)
            {
                Log.Warn("IrbisConnection::Dispose: already disposed");
            }

            if (_connected)
            {
                DisconnectCommand command = CommandFactory.GetDisconnectCommand();
                ExecuteCommand(command);
            }

            if (!ReferenceEquals(_iniFile, null))
            {
                _iniFile.Dispose();
                _iniFile = null;
            }

            Socket.Dispose();

            _disposed = true;
        }

        #endregion

        #region IHandmadeSerializable members

        /// <inheritdoc cref="IHandmadeSerializable.RestoreFromStream" />
        public virtual void RestoreFromStream
            (
                BinaryReader reader
            )
        {
            Code.NotNull(reader, "reader");

            Host = reader.ReadNullableString()
                .ThrowIfNull("Host");
            Port = reader.ReadPackedInt32();
            string username = reader.ReadNullableString();
            if (!string.IsNullOrEmpty(username))
            {
                Username = username;
            }
            string password = reader.ReadNullableString();
            if (!ReferenceEquals(password, null))
            {
                Password = password;
            }
            Database = reader.ReadNullableString()
                .ThrowIfNull("Database");
            Workstation = (IrbisWorkstation)reader.ReadPackedInt32();
        }

        /// <inheritdoc cref="IHandmadeSerializable.SaveToStream" />
        public virtual void SaveToStream
            (
                BinaryWriter writer
            )
        {
            writer
                .WriteNullable(Host)
                .WritePackedInt32(Port)
                .WriteNullable(Username)
                .WriteNullable(Password)
                .WriteNullable(Database)
                .WritePackedInt32((int)Workstation);
        }

        #endregion
    }
}


text:
package com.checkers.server.services;

import com.checkers.server.Consts;
import com.checkers.server.Context;
import com.checkers.server.beans.Message;
import com.checkers.server.dao.MessageDao;
import com.checkers.server.dao.UserDao;
import com.checkers.server.events.MessageEvent;
import com.checkers.server.exceptions.ApplicationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *
 *
 * @author Pavel Kuchin
 */
@Service("messageService")
public class MessageServiceImpl implements MessageService{
    @Autowired
    private MessageDao  messageDao;

    @Autowired
    private UserDao     userDao;

    @Autowired
    private Context     context;

    @PreAuthorize("hasAnyRole('ROLE_ADMIN,ROLE_USER')")
    @Override
    public Message newMessage(Message message) throws ApplicationException {
        Message result;

        Long from = userDao.getUserByLogin(Context.getAuthLogin()).getUuid();

        //Check, does user exits?
        Long to = userDao.getUser(message.getToUuid()).getUuid();

        if(message.getMessage() == null){
            throw new ApplicationException(6L, "Message cannot be null");
        }
        if(message.getMessage().length() > Consts.MAX_MESSAGE_LENGTH){
            throw new ApplicationException(3L, "The message length exceeds allowed.");
        }

        result = messageDao.newMessage(message.getMessage(), from, to);

        context.getApplicationContext()
                .publishEvent(new MessageEvent(context.getApplicationContext(), result));

        return result;
    }

    @PreAuthorize("hasAnyRole('ROLE_ADMIN,ROLE_USER')")
    @Override
    public List<Message> getMyMessages() throws ApplicationException {
        Long to = userDao.getUserByLogin(Context.getAuthLogin()).getUuid();

        return messageDao.getMessagesByToWithRemoving(to);
    }
}

redpajama_set_name: RedPajamaGithub


text:
@interface Bluetooth ()

@property (weak, nonatomic)		NSTimer *timer;

@end

@implementation Bluetooth

#pragma mark - Bluetooth communication ( Konashi )

-(id)init {
	[self initKonashi];

	return self;
}

-(void)dealloc {

	[_timer invalidate];
}

-(void)initKonashi {

	// KONASHIの初期化(接続とレディのイベント通知を登録する)
	[Konashi initialize];
    [Konashi addObserver:self selector:@selector(connected) name:KONASHI_EVENT_CONNECTED];
    [Konashi addObserver:self selector:@selector(ready) name:KONASHI_EVENT_READY];

	_timer = [NSTimer scheduledTimerWithTimeInterval:4.0 target:self selector:@selector(timerJob) userInfo:nil repeats:YES];
}

// Bluetooth接続が切れた際に、再接続を自動的に行う
-(void)timerJob {
	if([Konashi isConnected]) {
	}
	else {
		[self autoFind];
	}
}

-(void)autoFind {
    [Konashi find];
}

-(void)connected
{
	NSLog(@"BLE Connected");
}

-(void) ready
{
    NSLog(@"BLE Ready");

	// 接続された事を示すために、Konashi本体のLEDを全て点灯する
	[Konashi pinMode:LED2 mode:OUTPUT];
	[Konashi pinMode:LED3 mode:OUTPUT];
	[Konashi pinMode:LED4 mode:OUTPUT];
	[Konashi pinMode:LED5 mode:OUTPUT];
	for(int i=LED2; i <= LED5; i++) {
		[Konashi digitalWrite:i value:HIGH];
	}

	// I2Cモードの接続を行う
	int ret = [Konashi i2cMode:KONASHI_I2C_ENABLE_100K];
	if(ret != 0)
		NSLog(@"i2cMode ret=%d", ret);
}

@end


text:
typedef struct krawedz Krawedz;
typedef struct wierzcholek Wierzcholek;

typedef struct krawedz
{
	Wierzcholek* wierzcholek1;
	Wierzcholek* wierzcholek2;
} KRAWEDZ;

typedef struct wierzcholek
{
	int id;
	int kolor;
	int krawedzStart;
} WIERZCHOLEK;

int wierzcholek_compare(const void *a, const void *b);

int krawedz_compare(const void *a, const void *b);

#endif


text:
module Workplaces.HouseWork where

import Rules
import TestHelpers
import TestFramework

import Test.Tasty
import Test.Tasty.QuickCheck
import Test.QuickCheck.Monadic
import qualified Data.Set as S
import Data.Map (elems)
import Control.Monad (join)

houseWorkTests :: TestTree
houseWorkTests = localOption (QuickCheckMaxRatio 500) $ testGroup "House work tests" $ [
    testProperty "After working, player is building living room and can cancel" $ movingWorkerProperty $ do
      (playerId, _, _) <- startWorkingInHouseWork
      buildings <- getsUniverse currentlyBuiltBuildings <*> pure playerId
      assert $ buildings == [SingleSmallBuildingDesc LivingRoom],
    testProperty "After working and collecting resources, a dog is added" $ movingWorkerProperty $ do
      originalUniverse <- getUniverse
      (playerId, _, _) <- startWorkingInHouseWork
      checkPlayerHasValidOccupants playerId
      applyToUniverse $ collectResources playerId
      newUniverse <- getUniverse
      let originalDog = S.fromList $ getAnimals originalUniverse playerId
          newDog = S.fromList $ getAnimals newUniverse playerId
          animalDifference = (newDog S.\\ originalDog)
          isDog (Animal Dog _) = True
          isDog _ = False
      assert $ S.size animalDifference == 1
      assert $ all isDog animalDifference,
    testProperty "After working and collecting resources a dog is added to occupants" $ movingWorkerProperty $ do
      originalUniverse <- getUniverse
      (playerId, _, _) <- startWorkingInHouseWork
      checkPlayerHasValidOccupants playerId
      applyToUniverse $ collectResources playerId
      newUniverse <- getUniverse
      let isDogOccupant (AnimalOccupant (Animal Dog _)) = True
          isDogOccupant _ = False
          getDogOccupants universe = (S.fromList . filter isDogOccupant . join . elems) (getBuildingOccupants universe playerId)
          originalDogOccupants = getDogOccupants originalUniverse
          newDogOccupants = getDogOccupants newUniverse
      assert $ S.size (newDogOccupants S.\\ originalDogOccupants) == 1,
    testProperty "Working keeps occupants valid" $ movingWorkerProperty $ do
      originalUniverse <- getUniverse
      (playerId, _, _) <- startWorkingInHouseWork
      pre $ getOccupantErrors originalUniverse playerId == []
      validatePlayerHasValidOccupants playerId,
    testProperty "After working collecting resources and finishing action, next player moves" $ movingWorkerProperty $ do
      (playerId, _, _) <- startWorkingInHouseWork
      checkPlayerHasValidOccupants playerId
      applyToUniverse $ collectResources playerId
      applyToUniverse $ finishAction playerId
      validateNextPlayer playerId,
    testProperty "Selecting invalid position is not possible" $ movingWorkerProperty $ do
      (playerId, _, _) <- startWorkingInHouseWork
      checkPlayerHasValidOccupants playerId
      _ <- selectWrongPosition availableSingleCavePositions playerId
      shouldHaveFailed,
    testProperty "Selecting valid position builds a living room" $ movingWorkerProperty $ do
      (playerId, _, _) <- startWorkingInHouseWork
      checkPlayerHasValidOccupants playerId
      pre =<< getsUniverse currentPlayerCanBuildRoom
      (pos, _) <- selectCorrectPosition availableSingleCavePositions playerId
      buildings <- getsUniverse getBuildingSpace <*> pure playerId
      assert $ SmallBuilding LivingRoom pos `elem` buildings
  ]

startWorkingInHouseWork :: UniversePropertyMonad (PlayerId, WorkerId, WorkplaceId)
startWorkingInHouseWork = startWorkingInWorkplaceType HouseWork


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**address_line1** | **str** | The building number, street name, street suffix, and any street directionals. For US addresses, the max length is 64 characters. | [optional]
**address_line2** | **str, none_type** | The suite or apartment number of the recipient address, if applicable. For US addresses, the max length is 64 characters. | [optional]
**address_city** | **str, none_type** |  | [optional]
**address_state** | **str, none_type** |  | [optional]
**address_zip** | **str, none_type** | Optional postal code. For US addresses, must be either 5 or 9 digits. | [optional]
**address_country** | [**CountryExtended**](CountryExtended.md) |  | [optional]
**description** | [**ResourceDescription**](ResourceDescription.md) |  | [optional]
**name** | **str, none_type** | name associated with address. | [optional]
**company** | [**Company**](Company.md) |  | [optional]
**phone** | **str, none_type** | Must be no longer than 40 characters. | [optional]
**email** | **str, none_type** | Must be no longer than 100 characters. | [optional]
**metadata** | [**MetadataModel**](MetadataModel.md) |  | [optional]
**any string name** | **bool, date, datetime, dict, float, int, list, str, none_type** | any string name can be used but the value must be the correct type | [optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
<!DOCTYPE html>

    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>mne.beamformer.rap_music — MNE 0.16.1 documentation</title>
    <link rel="stylesheet" href="../_static/bootstrap-sphinx.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../_static/gallery.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/favicon.ico"/>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />

    <link rel="stylesheet" href="../_static/style.css " type="text/css" />
    <link rel="stylesheet" href="../_static/font-awesome.css" type="text/css" />
    <link rel="stylesheet" href="../_static/flag-icon.css" type="text/css" />

  <link rel="canonical" href="https://mne.tools/stable/index.html" />

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">

        </button>

        0.16.1

Install

Documentation

API

Examples

Contribute

  Site

  <button type="button" class="btn btn-primary navbar-btn dropdown-toggle" id="dropdownMenu1" data-toggle="dropdown">
    v0.16.1

  </button>

Development

v0.16 (stable)

v0.15

v0.14

v0.13

v0.12

v0.11

<form class="navbar-form navbar-right" action="../search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

mne.beamformer.rap_music

Examples using mne.beamformer.rap_music

<form action="../search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

mne.beamformer.rap_music¶

mne.beamformer.rap_music(evoked, forward, noise_cov, n_dipoles=5, return_residual=False, verbose=None)[source]¶

RAP-MUSIC source localization method.

Compute Recursively Applied and Projected MUltiple SIgnal Classification
(RAP-MUSIC) on evoked data.

Note

The goodness of fit (GOF) of all the returned dipoles is the
same and corresponds to the GOF of the full set of dipoles.

<col class="field-name" />
<col class="field-body" />

Parameters:

evoked : instance of Evoked

Evoked data to localize.

forward : instance of Forward

Forward operator.

noise_cov : instance of Covariance

The noise covariance.

n_dipoles : int

The number of dipoles to look for. The default value is 5.

return_residual : bool

If True, the residual is returned as an Evoked instance.

verbose : bool, str, int, or None

If not None, override default verbose level (see mne.verbose()
and Logging documentation for more).

Returns:

dipoles : list of instance of Dipole

The dipole fits.

residual : instance of Evoked

The residual a.k.a. data not explained by the dipoles.
Only returned if return_residual is True.

See also

mne.fit_dipole

Notes

The references are:

J.C. Mosher and R.M. Leahy. 1999. Source localization using recursively
applied and projected (RAP) MUSIC. Signal Processing, IEEE Trans. 47, 2
(February 1999), 332-340.
DOI=10.1109/78.740118 https://doi.org/10.1109/78.740118

Mosher, J.C.; Leahy, R.M., EEG and MEG source localization using
recursively applied (RAP) MUSIC, Signals, Systems and Computers, 1996.
pp.1201,1207 vol.2, 3-6 Nov. 1996
doi: 10.1109/ACSSC.1996.599135

New in version 0.9.0.

Examples using mne.beamformer.rap_music¶

Compute Rap-Music on evoked data

GitHub

·

Mailing list

·

Gitter

·

What's new

·

Cite MNE

Back to top

© Copyright 2012-2018, MNE Developers. Last updated on 2018-06-24.


text:
import test from 'ava';

import { isHTMLDocument } from '../../src/network';

test('isHTMLDocument retursn blindly true if protocol is "file:"', (t) => {
    const url = 'file://index.html';

    t.true(isHTMLDocument(url, {}), `isHTMLDocument doesn't return true if URL protocol is "file:"`);
});

test('isHTMLDocument guesses if response is HTML based on the media type', (t) => {
    const url = 'https://someresource.com/index.html';
    const htmlResponse = { 'content-type': 'text/html' };
    const noHtmlResponse = { 'content-type': 'text/javascript' };
    const invalidContentType = { 'content-type': 'asdasdasda' };

    t.true(isHTMLDocument(url, htmlResponse), `isHTMLDocument doesn't recognize HTML if header is text/html`);
    t.false(isHTMLDocument(url, noHtmlResponse), `isHTMLDocument doesn't recognize is not HTML if header is text/javascript`);
    t.false(isHTMLDocument(url, invalidContentType), `isHTMLDocument doesn't recognize invalid content types are not HTML`);
});


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>yaml: Data Structures</title>

<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />

yaml
    0.1.5

Main Page

Modules

Data Structures

Files

Data Structures

Data Fields

Data Structures

Here are the data structures with brief descriptions:

yaml_alias_data_s	This structure holds aliases data

yaml_document_s	The document structure

yaml_emitter_s	The emitter structure

yaml_event_s	The event structure

yaml_mark_s	The pointer position

yaml_node_pair_s	An element of a mapping node

yaml_node_s	The node structure

yaml_parser_s	The parser structure

yaml_simple_key_s	This structure holds information about a potential simple key

yaml_tag_directive_s	The tag directive data

yaml_token_s	The token structure

yaml_version_directive_s	The version directive data

<address class="footer">
Generated on Sun Jan 12 2014 18:25:30 for yaml by

 1.7.6.1
</address>


text:
/*jslint bitwise: true, eqeqeq: true, immed: true, newcap: true, nomen: false,
 onevar: false, plusplus: false, regexp: true, undef: true, white: false, indent: 2
 browser: true */

/*global window: true define: true jQuery: true */

/**
 * A jQuery plugin.
 *
 * Register arbitrary functions to be fired against jQuery objects when
 * specified break points are entered.
 *
 * Author: Jesse Renee Beach
 * Author URI: http://qemist.us
 * Author Twitter: @jessebeach
 * Author Github: https://github.com/jessebeach
 *
 */

(function (factory) {
  // Load this plugin with require.js if available.
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['jquery'], factory);
  }
  else {
    // If jQuery is not defined, warn the user and return.
    if (window.jQuery === undefined) {
      if (typeof window.console === 'object' && typeof window.console.log === 'function') {
        console.log("The plugin \"BreakUp\" failed to run because jQuery is not present.");
      }
      return null;
    }
    // Call the plugin factory. jQuery is a global object.
    factory();
  }
}
// The plugin factory function.
(function () {
  var pluginName = 'BreakUp';
  var $ = jQuery;
  // plugin defaults
  var defaults = {
    'breakpoints': {
      '0': $.noop
    },
    'options': {
      'namespace': pluginName
    }
  };
  // Add the plugin as a property of the jQuery fn object.
  $[pluginName] = (function () {
    // Functions for manipulating the arguments variable.
    var shift = Array.prototype.shift;
    var unshift = Array.prototype.unshift;
    var slice = Array.prototype.slice;
    var splice = Array.prototype.splice;
    /**
     * Build a new BreakUp object.
     */
    function BreakUp() {
      this.currentBreak = undefined;
      this.breakPoints = {};
      this.updated = false;
      this.namespace = pluginName;
      this.$elements = $();
      // Initialize the plugin instance.
      this.initialize.apply(this, arguments);
    }

    BreakUp.prototype.initialize = function (breakpoints, options, selector) {
      var bp, opts, fn;
      // Determine if breakpoints were passed in. If not, return, there's nothing to do.
      if (typeof breakpoints === 'string' || (typeof breakpoints === 'object' && 'jquery' in breakpoints)) {
        this.log('[' + pluginName + '] No breakpoints were provided for BreakUp to act on.', 'info');
        return;
      }
      // Merge user options with default options.
      bp = $.extend({}, defaults.breakpoints, breakpoints);
      // Strip the breakpoints from the arguments list.
      shift.call(arguments);
      // Unshift the merged breakpoints back into the arguments.
      unshift.call(arguments, bp);
      // Options is a jquery object or selector
      if ((typeof options === 'object' && 'jquery' in options) || typeof options === 'string') {
        // Slip an undefined into the arguments where the options should be.
        splice.call(arguments, 1, 0, undefined);
      }
      // Process the options.
      if (options) {
        opts = $.extend({}, defaults.options, options);
        this.namespace = opts.namespace;
        // More options to come...
      }
      // A selector is necessary to create a context. It cannot be empty. First check
      // for a string selector.
      if (typeof selector === 'string' || selector === window || selector === document) {
        this.$elements = $(selector);
        // If the selector was provided as something other than a jQuery obejct,
        // we need to replace the corresponding argument with the jQuery selector version.
        splice.call(arguments, 2, 1, this.$elements);
      }
      // Then check for a jQuery object.
      else if (typeof selector === 'object' && 'jquery' in selector) {
        this.$elements = selector;
      }
      // If the selector matched nothing, error out.
      if (this.$elements.length === 0) {
        this.log('[' + pluginName + '] Neither a jQuery object nor a valid selector were provided for BreakUp to act on.', 'info');
        return;
      }
      // The arguments should only contain the breakpoints, the context elements,
      // and additional arguments for the callbacks from this point on.
      // The options are needed only for initialization, so we remove them.
      splice.call(arguments, 1, 1);
      this.registerBreakPoints.apply(this, arguments);
      // Register a handler on the window resize and load events.
      fn = this.buildProxy(this.breakCheck, this);
      $(window).bind('resize' + '.' + this.namespace, fn);
      $(window).bind('load' + '.' + this.namespace, fn);
    };
    /**
     * Given an object of breakpoint properties and functions associated with those properties,
     * store them internally for reference later.
     */
    BreakUp.prototype.registerBreakPoints = function (breakpoints) {
      var bps = breakpoints;
      var br;
      var index;
      if (typeof bps === 'object') {
        // Remove the breakpoints from the arguments array.
        shift.call(arguments);
        // Loop through the breakpoints.
        for (br in bps) {
          if (bps.hasOwnProperty(br)) {
            if (isNaN(br) && br !== 'default') {
              this.log('[' + pluginName + '] The breakpoint property name \"' + br + '\" is not valid. The property must convert to a number or be the word \"default\".', 'info');
              continue;
            }
            if (typeof bps[br] === 'function') {
              // Represent the default breakpoint as zero internally.
              index = (br === 'default') ? '0': br;
              // Unshift the function into the arguments.
              unshift.call(arguments, bps[br]);
              var args = slice.call(arguments);
              // Build a proxy from the function and store it.
              this.breakPoints[index] = this.buildProxy.apply(this, arguments);
              // Shift the function off the arguments.
              shift.call(arguments);
            }
            else {
              this.log('[' + pluginName + '] ' + bps[br] + ', for the breakpoint ' + br + ' is not a function.', 'info');
            }
          }
        }
      }
    };
    /**
     * Gets the current breakpoint.
     *
     * @return (String) candidate: the number-as-a-string index in the list of breakPoints
     * of the current break point as determined by the screen size.
     */
    BreakUp.prototype.getBreakPoint = function () {
      var br;
      var candidate;
      var screen = this.getScreenWidth();
      for (br in this.breakPoints) {
        if (this.breakPoints.hasOwnProperty(br)) {
          if (Number(br) <= screen && (Number(br) > Number(candidate) || Number(br) === 0)) {
            candidate = br;
          }
        }
      }
      return candidate;
    };
    /**
     * Returns the stored set of breakpoints and their functions.
     */
    BreakUp.prototype.listBreakPoints = function () {
      return this.breakPoints;
    };
     /**
     * Get the current break point and call the function associated with it.
     */
    BreakUp.prototype.breakChangeHandler = function (event) {
      // updated will be set to false when a new breakpoint is encountered.
      if (!this.updated) {
        var callback = this.getBreakPointHandler();
        if (typeof callback === 'function') {
          // Pass the event object through to the callback.
          callback(event);
          this.updated = true;
          return;
        }
        else {
          this.log('[' + pluginName + '] The handler for the current breakpoint is not a function.', 'info');
        }
      }
    };
    /**
     * Get the function associated with a stored breakpoint.
     */
    BreakUp.prototype.getBreakPointHandler = function () {
      return this.breakPoints[this.getBreakPoint()];
    };
    /**
     * Check to see if the screen is in a new breakpoint. Also
     * called on page load.
     */
    BreakUp.prototype.breakCheck = function (event) {
      var br = this.getBreakPoint();
      if (this.currentBreak !== br) {
        // Note the current breakpoint.
        this.currentBreak = br;
        this.updated = false;
        // And do something.
        this.breakChangeHandler(event);
      }
    };

    /**
     * Returns a function with 'this' set as the context object.
     *
     * All additional arguments are passed through to the returned function.
     */
    BreakUp.prototype.buildProxy = function (fn, context) {
      var f = fn;
      var c = context;
      // Pull the top two args -- fn and context -- off the arguments array.
      for (var i = 0; i < 2; i++) {
        Array.prototype.shift.call(arguments);
      }
      // Get a local reference to the arguments.
      var args = Array.prototype.slice.call(arguments);
      return function () {
        // Push the callers arguments into the arguments list.
        // This will most likely be an $.Event object.
        for (var i = 0; i < arguments.length; i++) {
          args.unshift(arguments[i]);
        }
        f.apply(c, args);
      };
    };
    /**
    * Get the screen width.
    */
    BreakUp.prototype.getScreenWidth = function () {
      return window.innerWidth || document.documentElement.offsetWidth || document.documentElement.clientWidth;
    };
    /**
     *
     */
    BreakUp.prototype.setNameSpace = function (ns) {
      this.namespace = ns;
    };
    /**
     *
     */
    BreakUp.prototype.getNameSpace = function () {
      return this.namespace;
    };
  	/**
     * Simple console logging utility that won't blow up in older browsers.
     */
    BreakUp.prototype.log = function (message, type) {
      if ('console' in window) {
        var t = type || 'log';
        console[t](message);
      }
    };
    // Return a new BreakUp object.
    return BreakUp;
  }());
}));