text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using TWCore.Diagnostics.Status;
using TWCore.Net.RPC.Client.Transports;
using TWCore.Net.RPC.Descriptors;
// ReSharper disable InconsistentNaming
// ReSharper disable InconsistentlySynchronizedField
// ReSharper disable InheritdocConsiderUsage
// ReSharper disable SuggestBaseTypeForParameter
// ReSharper disable AutoPropertyCanBeMadeGetOnly.Global
// ReSharper disable MemberCanBePrivate.Global

namespace TWCore.Net.RPC.Client
{
    /// <inheritdoc cref="IRPCClient" />
    /// <summary>
    /// RPC standard client
    /// </summary>
    [StatusName("RPC Client")]
    public class RPCClient : IRPCClient, IDisposable
    {
        private static readonly object[] _nullItemArgs = { null };
        private readonly ConcurrentDictionary<(string ServiceName, string Method, Type[] Types), MethodDescriptor> _methodDescriptorCache = new ConcurrentDictionary<(string, string, Type[]), MethodDescriptor>(new MethodDescriptionEqualityComparer());
        private ITransportClient _transport;
        private bool _transportInit;
        private ServiceDescriptorCollection _serverDescriptors;
        private ServiceDescriptorCollection _descriptors;
        private Func<(string, string, Type[]), MethodDescriptor> _getMethodDescriptorDelegate;

        #region Properties
        /// <summary>
        /// Service descriptor collection
        /// </summary>
        public ServiceDescriptorCollection Descriptors => GetDescriptorsAsync().WaitAndResults();
        /// <summary>
        /// Transport client object
        /// </summary>
        public ITransportClient Transport
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get { return _transport; }
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            set
            {
                if (_transport != null)
                    _transport.OnEventReceived -= Transport_OnEventReceived;
                _transport = value;
                if (_transport is null) return;
                _transport.OnEventReceived += Transport_OnEventReceived;
                InitTransportAsync().WaitAsync();
            }
        }
        /// <summary>
        /// Fires when an event from the RPC server fires
        /// </summary>
        public event EventHandler<EventDataEventArgs> OnEventReceived;
        /// <summary>
        /// Gets or Sets if the RPC client needs to get the server description for checks
        /// </summary>
        public bool UseServerDescriptor { get; set; } = false;
        #endregion

        #region Nested Types
        private sealed class MethodDescriptionEqualityComparer : IEqualityComparer<(string ServiceName, string Method, Type[] Types)>
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public bool Equals((string ServiceName, string Method, Type[] Types) x, (string ServiceName, string Method, Type[] Types) y)
            {
                if (x.ServiceName != y.ServiceName) return false;
                if (x.Method != y.Method) return false;
                if (x.Types is null && y.Types is null) return true;
                if (x.Types is null) return false;
                if (y.Types is null) return false;
                if (x.Types.Length != y.Types.Length) return false;
                for(var i = 0; i < x.Types.Length; i++)
                    if (x.Types[i] != y.Types[i]) return false;
                return true;
            }

            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public int GetHashCode((string ServiceName, string Method, Type[] Types) obj)
                => (obj.ServiceName?.GetHashCode() ?? 11) + (obj.Method?.GetHashCode() ?? 17) + obj.Types?.Length * 19 ?? 19;
        }
        #endregion

        #region .ctor
        /// <summary>
        /// RPC standard client
        /// </summary>
        /// <param name="transport">Client transport</param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public RPCClient(ITransportClient transport = null)
        {
            Transport = transport;
            _getMethodDescriptorDelegate = GetMethodDescriptor;
            Core.Status.AttachChild(transport, this);
        }
        #endregion

        #region Exceptions
        private static void ThrowArgumentException() => throw new ArgumentException("The type of the dynamic proxy should be an interface.");
        private static void ThrowNotImplementedException() => throw new NotImplementedException("The server doesn't have an implementation for this Type.");
        private static void ThrowResponseNullException() => throw new Exception("RPC Response is null.");
        private static void ThrowSerializableException(SerializableException se) => throw se.GetException();
        private static void ThrowMethodDescriptionNull(string serviceName, string method, object[] args)
            => throw new MissingMemberException($"The method '{method}' with {args?.Length} arguments on service {serviceName} can't be found in the service description.");
        #endregion

        #region Create Proxy
        /// <summary>
        /// Creates a dynamic object to act as client proxy
        /// </summary>
        /// <typeparam name="T">Type of the service to create the proxy</typeparam>
        /// <returns>Dynamic proxy instance, use dynamic keyword to dynamically invoke methods to the server</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public Task<DynamicProxy> CreateDynamicProxyAsync<T>()
            => CreateDynamicProxyAsync(typeof(T));
        /// <summary>
        /// Creates a dynamic object to act as client proxy
        /// </summary>
        /// <param name="interfaceType">Type of the service to create the proxy</param>
        /// <returns>Dynamic proxy instance, use dynamic keyword to dynamically invoke methods to the server</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public async Task<DynamicProxy> CreateDynamicProxyAsync(Type interfaceType)
        {
            if (!interfaceType.IsInterface)
                ThrowArgumentException();
            await InitTransportAsync().ConfigureAwait(false);
            Transport.Descriptors = Descriptors;
            if (Descriptors.Items.TryGetValue(interfaceType.FullName, out var descriptor))
                return new DynamicProxy(this, descriptor);
            if (!UseServerDescriptor)
            {
                descriptor = ServiceDescriptor.GetDescriptor(interfaceType);
                Descriptors.Add(descriptor);
            }
            else
                ThrowNotImplementedException();
            return new DynamicProxy(this, descriptor);
        }
        /// <summary>
        /// Creates a client proxy using this client.
        /// </summary>
        /// <typeparam name="T">Type of proxy</typeparam>
        /// <returns>Client proxy object instance to invoke methods to the server</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public async Task<T> CreateProxyAsync<T>() where T : RPCProxy, new()
        {
            var typeInterfaces = typeof(T).GetInterfaces();
            var typeInterface = typeInterfaces.FirstOrDefault(i => i != typeof(IDisposable) && i != typeof(IEnumerable<>) && i != typeof(IDictionary<,>));
            if (typeInterface is null)
                ThrowArgumentException();
            var rpcClient = new T();
            await InitTransportAsync().ConfigureAwait(false);
            Transport.Descriptors = Descriptors;
            if (!Descriptors.Items.TryGetValue(typeInterface.FullName, out var descriptor))
            {
                if (!UseServerDescriptor)
                {
                    descriptor = ServiceDescriptor.GetDescriptor(typeInterface);
                    Descriptors.Add(descriptor);
                }
                else
                    ThrowNotImplementedException();
            }
            rpcClient.SetClient(this, descriptor.Name);
            return rpcClient;
        }
        #endregion

        #region ServerInvoke Async
        /// <summary>
        /// Invokes a Server RPC method
        /// </summary>
        /// <typeparam name="T">Response object type</typeparam>
        /// <param name="serviceName">Service name</param>
        /// <param name="method">Server method name</param>
        /// <param name="args">Server method arguments</param>
        /// <returns>Server method return value</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public async Task<T> ServerInvokeAsync<T>(string serviceName, string method, params object[] args)
        {
            var response = await ServerInvokeAsync(serviceName, method, args).ConfigureAwait(false);
            return (T)response;
        }

        /// <summary>
        /// Invokes a Server RPC method
        /// </summary>
        /// <param name="serviceName">Service name</param>
        /// <param name="method">Server method name</param>
        /// <param name="args">Server method arguments</param>
        /// <returns>Server method return value</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public async Task<object> ServerInvokeAsync(string serviceName, string method, params object[] args)
        {
            var request = CreateRequest(serviceName, method, args, null, false);
            var response = await Transport.InvokeMethodAsync(request).ConfigureAwait(false);
            RPCRequestMessage.Store(request);
            if (response is null)
                ThrowResponseNullException();
            if (response.Exception != null)
                ThrowSerializableException(response.Exception);
            return response.ReturnValue;
        }

        /// <summary>
        /// Invokes a Server RPC method
        /// </summary>
        /// <typeparam name="T">Response object type</typeparam>
        /// <param name="serviceName">Service name</param>
        /// <param name="method">Server method name</param>
        /// <param name="args">Server method arguments</param>
        /// <param name="cancellationToken">Cancellation Token instance</param>
        /// <returns>Server method return value</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public async Task<T> ServerInvokeAsync<T>(string serviceName, string method, object[] args, CancellationToken cancellationToken)
        {
            var response = await ServerInvokeAsync(serviceName, method, args, cancellationToken).ConfigureAwait(false);
            return (T)response;
        }

        /// <summary>
        /// Invokes a Server RPC method
        /// </summary>
        /// <param name="serviceName">Service name</param>
        /// <param name="method">Server method name</param>
        /// <param name="args">Server method arguments</param>
        /// <param name="cancellationToken">Cancellation Token instance</param>
        /// <returns>Server method return value</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public async Task<object> ServerInvokeAsync(string serviceName, string method, object[] args, CancellationToken cancellationToken)
        {
            var request = CreateRequest(serviceName, method, args, null, true);
            var response = await Transport.InvokeMethodAsync(request, cancellationToken).ConfigureAwait(false);
            RPCRequestMessage.Store(request);
            if (response is null)
                ThrowResponseNullException();
            if (response.Exception != null)
                ThrowSerializableException(response.Exception);
            return response.ReturnValue;
        }
        #endregion

        #region Alternative ServerInvoke Async
        private static readonly ObjectPool<Tuple<object[], Type[]>, Args1Allocator> ServiceInvokeArgs1Pool = new ObjectPool<Tuple<object[], Type[]>, Args1Allocator>();
        private static readonly ObjectPool<Tuple<object[], Type[]>, Args2Allocator> ServiceInvokeArgs2Pool = new ObjectPool<Tuple<object[], Type[]>, Args2Allocator>();
        private static readonly ObjectPool<Tuple<object[], Type[]>, Args3Allocator> ServiceInvokeArgs3Pool = new ObjectPool<Tuple<object[], Type[]>, Args3Allocator>();
        private static readonly ObjectPool<Tuple<object[], Type[]>, Args4Allocator> ServiceInvokeArgs4Pool = new ObjectPool<Tuple<object[], Type[]>, Args4Allocator>();
        private static readonly ObjectPool<Tuple<object[], Type[]>, Args5Allocator> ServiceInvokeArgs5Pool = new ObjectPool<Tuple<object[], Type[]>, Args5Allocator>();

        private readonly struct Args1Allocator : IPoolObjectLifecycle<Tuple<object[], Type[]>>
        {
            public int InitialSize => 1;
            public PoolResetMode ResetMode => PoolResetMode.AfterUse;
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public Tuple<object[], Type[]> New() => Tuple.Create(new object[1], new Type[1]);
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public void Reset(Tuple<object[], Type[]> value)
            {
                value.Item1[0] = null;
            }
            public int DropTimeFrequencyInSeconds => 120;
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public void DropAction(Tuple<object[], Type[]> value)
            {
            }
            public int DropMaxSizeThreshold => 10;
            public int MaximumSize => 500;
            public int DropQuantity => 5;
        }
        private readonly struct Args2Allocator : IPoolObjectLifecycle<Tuple<object[], Type[]>>
        {
            public int InitialSize => 1;
            public PoolResetMode ResetMode => PoolResetMode.AfterUse;
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public Tuple<object[], Type[]> New() => Tuple.Create(new object[2], new Type[2]);
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public void Reset(Tuple<object[], Type[]> value)
            {
                value.Item1[0] = null;
                value.Item1[1] = null;
            }
            public int DropTimeFrequencyInSeconds => 120;
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public void DropAction(Tuple<object[], Type[]> value)
            {
            }
            public int DropMaxSizeThreshold => 10;
            public int MaximumSize => 500;
            public int DropQuantity => 5;
        }
        private readonly struct Args3Allocator : IPoolObjectLifecycle<Tuple<object[], Type[]>>
        {
            public int InitialSize => 1;
            public PoolResetMode ResetMode => PoolResetMode.AfterUse;
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public Tuple<object[], Type[]> New() => Tuple.Create(new object[3], new Type[3]);
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public void Reset(Tuple<object[], Type[]> value)
            {
                value.Item1[0] = null;
                value.Item1[1] = null;
                value.Item1[2] = null;
            }
            public int DropTimeFrequencyInSeconds => 120;
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public void DropAction(Tuple<object[], Type[]> value)
            {
            }
            public int DropMaxSizeThreshold => 10;
            public int MaximumSize => 500;
            public int DropQuantity => 5;
        }
        private readonly struct Args4Allocator : IPoolObjectLifecycle<Tuple<object[], Type[]>>
        {
            public int InitialSize => 1;
            public PoolResetMode ResetMode => PoolResetMode.AfterUse;
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public Tuple<object[], Type[]> New() => Tuple.Create(new object[4], new Type[4]);
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public void Reset(Tuple<object[], Type[]> value)
            {
                value.Item1[0] = null;
                value.Item1[1] = null;
                value.Item1[2] = null;
                value.Item1[3] = null;
            }
            public int DropTimeFrequencyInSeconds => 120;
            public void DropAction(Tuple<object[], Type[]> value)
            {
            }
            public int DropMaxSizeThreshold => 10;
            public int MaximumSize => 500;
            public int DropQuantity => 5;
        }
        private readonly struct Args5Allocator : IPoolObjectLifecycle<Tuple<object[], Type[]>>
        {
            public int InitialSize => 1;
            public PoolResetMode ResetMode => PoolResetMode.AfterUse;
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public Tuple<object[], Type[]> New() => Tuple.Create(new object[5], new Type[5]);
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public void Reset(Tuple<object[], Type[]> value)
            {
                value.Item1[0] = null;
                value.Item1[1] = null;
                value.Item1[2] = null;
                value.Item1[3] = null;
                value.Item1[4] = null;
            }
            public int DropTimeFrequencyInSeconds => 120;
            public void DropAction(Tuple<object[], Type[]> value)
            {
            }
            public int DropMaxSizeThreshold => 10;
            public int MaximumSize => 500;
            public int DropQuantity => 5;
        }

        #region Generic
        /// <summary>
        /// Invoke a Server RPC method with 1 argument
        /// </summary>
        /// <typeparam name="TArg1">Argument 1 type</typeparam>
        /// <typeparam name="TReturn">Return type</typeparam>
        /// <param name="serviceName">Service name</param>
        /// <param name="method">Method name</param>
        /// <param name="arg1">Argument 1</param>
        /// <param name="cancellationToken">Cancellation token</param>
        /// <returns>Return value</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public async Task<TReturn> ServerInvokeAsync<TArg1, TReturn>(string serviceName, string method, TArg1 arg1, CancellationToken? cancellationToken = null)
        {
            var arrayArgs = ServiceInvokeArgs1Pool.New();
            arrayArgs.Item1[0] = arg1;
            arrayArgs.Item2[0] = typeof(TArg1);
            var request = CreateRequest(serviceName, method, arrayArgs.Item1, arrayArgs.Item2, cancellationToken != null);
            var response = cancellationToken.HasValue ?
                await Transport.InvokeMethodAsync(request, cancellationToken.Value).ConfigureAwait(false) :
                await Transport.InvokeMethodAsync(request).ConfigureAwait(false);
            RPCRequestMessage.Store(request);
            ServiceInvokeArgs1Pool.Store(arrayArgs);
            if (response is null)
                ThrowResponseNullException();
            if (response.Exception != null)
                ThrowSerializableException(response.Exception);
            return (TReturn)response.ReturnValue;
        }
        /// <summary>
        /// Invoke a Server RPC method with 2 argument
        /// </summary>
        /// <typeparam name="TArg1">Argument 1 type</typeparam>
        /// <typeparam name="TArg2">Argument 2 type</typeparam>
        /// <typeparam name="TReturn">Return type</typeparam>
        /// <param name="serviceName">Service name</param>
        /// <param name="method">Method name</param>
        /// <param name="arg1">Argument 1</param>
        /// <param name="arg2">Argument 2</param>
        /// <param name="cancellationToken">Cancellation token</param>
        /// <returns>Return value</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public async Task<TReturn> ServerInvokeAsync<TArg1, TArg2, TReturn>(string serviceName, string method, TArg1 arg1, TArg2 arg2, CancellationToken? cancellationToken = null)
        {
            var arrayArgs = ServiceInvokeArgs2Pool.New();
            arrayArgs.Item1[0] = arg1;
            arrayArgs.Item1[1] = arg2;
            arrayArgs.Item2[0] = typeof(TArg1);
            arrayArgs.Item2[1] = typeof(TArg2);
            var request = CreateRequest(serviceName, method, arrayArgs.Item1, arrayArgs.Item2, cancellationToken != null);
            var response = cancellationToken.HasValue ?
                await Transport.InvokeMethodAsync(request, cancellationToken.Value).ConfigureAwait(false) :
                await Transport.InvokeMethodAsync(request).ConfigureAwait(false);
            RPCRequestMessage.Store(request);
            ServiceInvokeArgs2Pool.Store(arrayArgs);
            if (response is null)
                ThrowResponseNullException();
            if (response.Exception != null)
                ThrowSerializableException(response.Exception);
            return (TReturn)response.ReturnValue;
        }
        /// <summary>
        /// Invoke a Server RPC method with 3 argument
        /// </summary>
        /// <typeparam name="TArg1">Argument 1 type</typeparam>
        /// <typeparam name="TArg2">Argument 2 type</typeparam>
        /// <typeparam name="TArg3">Argument 3 type</typeparam>
        /// <typeparam name="TReturn">Return type</typeparam>
        /// <param name="serviceName">Service name</param>
        /// <param name="method">Method name</param>
        /// <param name="arg1">Argument 1</param>
        /// <param name="arg2">Argument 2</param>
        /// <param name="arg3">Argument 3</param>
        /// <param name="cancellationToken">Cancellation token</param>
        /// <returns>Return value</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public async Task<TReturn> ServerInvokeAsync<TArg1, TArg2, TArg3, TReturn>(string serviceName, string method, TArg1 arg1, TArg2 arg2, TArg3 arg3, CancellationToken? cancellationToken = null)
        {
            var arrayArgs = ServiceInvokeArgs3Pool.New();
            arrayArgs.Item1[0] = arg1;
            arrayArgs.Item1[1] = arg2;
            arrayArgs.Item1[2] = arg3;
            arrayArgs.Item2[0] = typeof(TArg1);
            arrayArgs.Item2[1] = typeof(TArg2);
            arrayArgs.Item2[2] = typeof(TArg3);
            var request = CreateRequest(serviceName, method, arrayArgs.Item1, arrayArgs.Item2, cancellationToken != null);
            var response = cancellationToken.HasValue ?
                await Transport.InvokeMethodAsync(request, cancellationToken.Value).ConfigureAwait(false) :
                await Transport.InvokeMethodAsync(request).ConfigureAwait(false);
            RPCRequestMessage.Store(request);
            ServiceInvokeArgs3Pool.Store(arrayArgs);
            if (response is null)
                ThrowResponseNullException();
            if (response.Exception != null)
                ThrowSerializableException(response.Exception);
            return (TReturn)response.ReturnValue;
        }
        /// <summary>
        /// Invoke a Server RPC method with 4 argument
        /// </summary>
        /// <typeparam name="TArg1">Argument 1 type</typeparam>
        /// <typeparam name="TArg2">Argument 2 type</typeparam>
        /// <typeparam name="TArg3">Argument 3 type</typeparam>
        /// <typeparam name="TArg4">Argument 4 type</typeparam>
        /// <typeparam name="TReturn">Return type</typeparam>
        /// <param name="serviceName">Service name</param>
        /// <param name="method">Method name</param>
        /// <param name="arg1">Argument 1</param>
        /// <param name="arg2">Argument 2</param>
        /// <param name="arg3">Argument 3</param>
        /// <param name="arg4">Argument 4</param>
        /// <param name="cancellationToken">Cancellation token</param>
        /// <returns>Return value</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public async Task<TReturn> ServerInvokeAsync<TArg1, TArg2, TArg3, TArg4, TReturn>(string serviceName, string method, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, CancellationToken? cancellationToken = null)
        {
            var arrayArgs = ServiceInvokeArgs4Pool.New();
            arrayArgs.Item1[0] = arg1;
            arrayArgs.Item1[1] = arg2;
            arrayArgs.Item1[2] = arg3;
            arrayArgs.Item1[3] = arg4;
            arrayArgs.Item2[0] = typeof(TArg1);
            arrayArgs.Item2[1] = typeof(TArg2);
            arrayArgs.Item2[2] = typeof(TArg3);
            arrayArgs.Item2[3] = typeof(TArg4);
            var request = CreateRequest(serviceName, method, arrayArgs.Item1, arrayArgs.Item2, cancellationToken != null);
            var response = cancellationToken.HasValue ?
                await Transport.InvokeMethodAsync(request, cancellationToken.Value).ConfigureAwait(false) :
                await Transport.InvokeMethodAsync(request).ConfigureAwait(false);
            RPCRequestMessage.Store(request);
            ServiceInvokeArgs4Pool.Store(arrayArgs);
            if (response is null)
                ThrowResponseNullException();
            if (response.Exception != null)
                ThrowSerializableException(response.Exception);
            return (TReturn)response.ReturnValue;
        }
        /// <summary>
        /// Invoke a Server RPC method with 5 argument
        /// </summary>
        /// <typeparam name="TArg1">Argument 1 type</typeparam>
        /// <typeparam name="TArg2">Argument 2 type</typeparam>
        /// <typeparam name="TArg3">Argument 3 type</typeparam>
        /// <typeparam name="TArg4">Argument 4 type</typeparam>
        /// <typeparam name="TArg5">Argument 5 type</typeparam>
        /// <typeparam name="TReturn">Return type</typeparam>
        /// <param name="serviceName">Service name</param>
        /// <param name="method">Method name</param>
        /// <param name="arg1">Argument 1</param>
        /// <param name="arg2">Argument 2</param>
        /// <param name="arg3">Argument 3</param>
        /// <param name="arg4">Argument 4</param>
        /// <param name="arg5">Argument 5</param>
        /// <param name="cancellationToken">Cancellation token</param>
        /// <returns>Return value</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public async Task<TReturn> ServerInvokeAsync<TArg1, TArg2, TArg3, TArg4, TArg5, TReturn>(string serviceName, string method, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5, CancellationToken? cancellationToken = null)
        {
            var arrayArgs = ServiceInvokeArgs5Pool.New();
            arrayArgs.Item1[0] = arg1;
            arrayArgs.Item1[1] = arg2;
            arrayArgs.Item1[2] = arg3;
            arrayArgs.Item1[3] = arg4;
            arrayArgs.Item1[4] = arg5;
            arrayArgs.Item2[0] = typeof(TArg1);
            arrayArgs.Item2[1] = typeof(TArg2);
            arrayArgs.Item2[2] = typeof(TArg3);
            arrayArgs.Item2[3] = typeof(TArg4);
            arrayArgs.Item2[4] = typeof(TArg5);
            var request = CreateRequest(serviceName, method, arrayArgs.Item1, arrayArgs.Item2, cancellationToken != null);
            var response = cancellationToken.HasValue ?
                await Transport.InvokeMethodAsync(request, cancellationToken.Value).ConfigureAwait(false) :
                await Transport.InvokeMethodAsync(request).ConfigureAwait(false);
            RPCRequestMessage.Store(request);
            ServiceInvokeArgs5Pool.Store(arrayArgs);
            if (response is null)
                ThrowResponseNullException();
            if (response.Exception != null)
                ThrowSerializableException(response.Exception);
            return (TReturn)response.ReturnValue;
        }

        #endregion

        #region Object
        /// <summary>
        /// Invokes a Server RPC method with no arguments
        /// </summary>
        /// <param name="serviceName">Service name</param>
        /// <param name="method">Server method name</param>
        /// <param name="cancellationToken">Cancellation Token instance</param>
        /// <returns>Server method return value</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public async Task<TReturn> ServerInvokeObjectAsync<TReturn>(string serviceName, string method, CancellationToken? cancellationToken = null)
        {
            var request = CreateRequest(serviceName, method, null, null, cancellationToken != null);
            var response = cancellationToken.HasValue ?
                await Transport.InvokeMethodAsync(request, cancellationToken.Value).ConfigureAwait(false) :
                await Transport.InvokeMethodAsync(request).ConfigureAwait(false);
            RPCRequestMessage.Store(request);
            if (response is null)
                ThrowResponseNullException();
            if (response.Exception != null)
                ThrowSerializableException(response.Exception);
            return (TReturn)response.ReturnValue;
        }
        /// <summary>
        /// Invoke a Server RPC method with 1 argument
        /// </summary>
        /// <typeparam name="TReturn">Return type</typeparam>
        /// <param name="serviceName">Service name</param>
        /// <param name="method">Method name</param>
        /// <param name="arg1">Argument 1</param>
        /// <param name="cancellationToken">Cancellation token</param>
        /// <returns>Return value</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public async Task<TReturn> ServerInvokeObjectAsync<TReturn>(string serviceName, string method, object arg1, CancellationToken? cancellationToken = null)
        {
            var arrayArgs = ServiceInvokeArgs1Pool.New();
            arrayArgs.Item1[0] = arg1;
            var request = CreateRequest(serviceName, method, arrayArgs.Item1, null, cancellationToken != null);
            var response = cancellationToken.HasValue ?
                await Transport.InvokeMethodAsync(request, cancellationToken.Value).ConfigureAwait(false) :
                await Transport.InvokeMethodAsync(request).ConfigureAwait(false);
            RPCRequestMessage.Store(request);
            ServiceInvokeArgs1Pool.Store(arrayArgs);
            if (response is null)
                ThrowResponseNullException();
            if (response.Exception != null)
                ThrowSerializableException(response.Exception);
            return (TReturn)response.ReturnValue;
        }
        /// <summary>
        /// Invoke a Server RPC method with 2 argument
        /// </summary>
        /// <typeparam name="TReturn">Return type</typeparam>
        /// <param name="serviceName">Service name</param>
        /// <param name="method">Method name</param>
        /// <param name="arg1">Argument 1</param>
        /// <param name="arg2">Argument 2</param>
        /// <param name="cancellationToken">Cancellation token</param>
        /// <returns>Return value</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public async Task<TReturn> ServerInvokeObjectAsync<TReturn>(string serviceName, string method, object arg1, object arg2, CancellationToken? cancellationToken = null)
        {
            var arrayArgs = ServiceInvokeArgs2Pool.New();
            arrayArgs.Item1[0] = arg1;
            arrayArgs.Item1[1] = arg2;
            var request = CreateRequest(serviceName, method, arrayArgs.Item1, null, cancellationToken != null);
            var response = cancellationToken.HasValue ?
                await Transport.InvokeMethodAsync(request, cancellationToken.Value).ConfigureAwait(false) :
                await Transport.InvokeMethodAsync(request).ConfigureAwait(false);
            RPCRequestMessage.Store(request);
            ServiceInvokeArgs2Pool.Store(arrayArgs);
            if (response is null)
                ThrowResponseNullException();
            if (response.Exception != null)
                ThrowSerializableException(response.Exception);
            return (TReturn)response.ReturnValue;
        }
        /// <summary>
        /// Invoke a Server RPC method with 3 argument
        /// </summary>
        /// <typeparam name="TReturn">Return type</typeparam>
        /// <param name="serviceName">Service name</param>
        /// <param name="method">Method name</param>
        /// <param name="arg1">Argument 1</param>
        /// <param name="arg2">Argument 2</param>
        /// <param name="arg3">Argument 3</param>
        /// <param name="cancellationToken">Cancellation token</param>
        /// <returns>Return value</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public async Task<TReturn> ServerInvokeObjectAsync<TReturn>(string serviceName, string method, object arg1, object arg2, object arg3, CancellationToken? cancellationToken = null)
        {
            var arrayArgs = ServiceInvokeArgs3Pool.New();
            arrayArgs.Item1[0] = arg1;
            arrayArgs.Item1[1] = arg2;
            arrayArgs.Item1[2] = arg3;
            var request = CreateRequest(serviceName, method, arrayArgs.Item1, null, cancellationToken != null);
            var response = cancellationToken.HasValue ?
                await Transport.InvokeMethodAsync(request, cancellationToken.Value).ConfigureAwait(false) :
                await Transport.InvokeMethodAsync(request).ConfigureAwait(false);
            RPCRequestMessage.Store(request);
            ServiceInvokeArgs3Pool.Store(arrayArgs);
            if (response is null)
                ThrowResponseNullException();
            if (response.Exception != null)
                ThrowSerializableException(response.Exception);
            return (TReturn)response.ReturnValue;
        }
        /// <summary>
        /// Invoke a Server RPC method with 4 argument
        /// </summary>
        /// <typeparam name="TReturn">Return type</typeparam>
        /// <param name="serviceName">Service name</param>
        /// <param name="method">Method name</param>
        /// <param name="arg1">Argument 1</param>
        /// <param name="arg2">Argument 2</param>
        /// <param name="arg3">Argument 3</param>
        /// <param name="arg4">Argument 4</param>
        /// <param name="cancellationToken">Cancellation token</param>
        /// <returns>Return value</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public async Task<TReturn> ServerInvokeObjectAsync<TReturn>(string serviceName, string method, object arg1, object arg2, object arg3, object arg4, CancellationToken? cancellationToken = null)
        {
            var arrayArgs = ServiceInvokeArgs4Pool.New();
            arrayArgs.Item1[0] = arg1;
            arrayArgs.Item1[1] = arg2;
            arrayArgs.Item1[2] = arg3;
            arrayArgs.Item1[3] = arg4;
            var request = CreateRequest(serviceName, method, arrayArgs.Item1, null, cancellationToken != null);
            var response = cancellationToken.HasValue ?
                await Transport.InvokeMethodAsync(request, cancellationToken.Value).ConfigureAwait(false) :
                await Transport.InvokeMethodAsync(request).ConfigureAwait(false);
            RPCRequestMessage.Store(request);
            ServiceInvokeArgs4Pool.Store(arrayArgs);
            if (response is null)
                ThrowResponseNullException();
            if (response.Exception != null)
                ThrowSerializableException(response.Exception);
            return (TReturn)response.ReturnValue;
        }
        /// <summary>
        /// Invoke a Server RPC method with 5 argument
        /// </summary>
        /// <typeparam name="TReturn">Return type</typeparam>
        /// <param name="serviceName">Service name</param>
        /// <param name="method">Method name</param>
        /// <param name="arg1">Argument 1</param>
        /// <param name="arg2">Argument 2</param>
        /// <param name="arg3">Argument 3</param>
        /// <param name="arg4">Argument 4</param>
        /// <param name="arg5">Argument 5</param>
        /// <param name="cancellationToken">Cancellation token</param>
        /// <returns>Return value</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public async Task<TReturn> ServerInvokeObjectAsync<TReturn>(string serviceName, string method, object arg1, object arg2, object arg3, object arg4, object arg5, CancellationToken? cancellationToken = null)
        {
            var arrayArgs = ServiceInvokeArgs5Pool.New();
            arrayArgs.Item1[0] = arg1;
            arrayArgs.Item1[1] = arg2;
            arrayArgs.Item1[2] = arg3;
            arrayArgs.Item1[3] = arg4;
            arrayArgs.Item1[4] = arg5;
            var request = CreateRequest(serviceName, method, arrayArgs.Item1, null, cancellationToken != null);
            var response = cancellationToken.HasValue ?
                await Transport.InvokeMethodAsync(request, cancellationToken.Value).ConfigureAwait(false) :
                await Transport.InvokeMethodAsync(request).ConfigureAwait(false);
            RPCRequestMessage.Store(request);
            ServiceInvokeArgs5Pool.Store(arrayArgs);
            if (response is null)
                ThrowResponseNullException();
            if (response.Exception != null)
                ThrowSerializableException(response.Exception);
            return (TReturn)response.ReturnValue;
        }
        #endregion

        /// <summary>
        /// Get Method Descriptor
        /// </summary>
        /// <param name="serviceName">Service name</param>
        /// <param name="method">Server method name</param>
        /// <param name="args">Server method arguments</param>
        /// <returns>Method descriptor</returns>
        public MethodDescriptor GetMethodDescriptor(string serviceName, string method, object[] args)
        {
            Type[] types = null;
            if (args != null)
            {
                types = new Type[args.Length];
                for (var i = 0; i < args.Length; i++)
                {
                    if (args[i] != null)
                        types[i] = args[i].GetType();
                }
            }
            return _methodDescriptorCache.GetOrAdd((serviceName, method, types), _getMethodDescriptorDelegate);
        }
        #endregion

        #region Private Methods
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private async Task InitTransportAsync()
        {
            if (_transportInit) return;
            await Transport.InitAsync().ConfigureAwait(false);
            _transportInit = true;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private async ValueTask<ServiceDescriptorCollection> GetDescriptorsAsync()
        {
            if (_descriptors != null) return _descriptors;
            if (_serverDescriptors is null && UseServerDescriptor)
                _serverDescriptors = await Transport.GetDescriptorsAsync().ConfigureAwait(false);
            lock (this)
            {
                _descriptors = new ServiceDescriptorCollection();
                if (UseServerDescriptor)
                    _descriptors.Combine(_serverDescriptors);
                return _descriptors;
            }
        }
        /// <summary>
        /// Handles OnEventReceived event of the transport
        /// </summary>
        /// <param name="sender">Object sender</param>
        /// <param name="e">Event args</param>
        private void Transport_OnEventReceived(object sender, EventDataEventArgs e)
        {
            if (!Descriptors.Items.TryGetValue(e.ServiceName, out var descriptor)) return;
            if (descriptor.Events.ContainsKey(e.EventName))
                OnEventReceived?.Invoke(sender, e);
        }
        /// <summary>
        /// Creates a new RPC Request message
        /// </summary>
        /// <param name="serviceName">Service name</param>
        /// <param name="method">Method name to call</param>
        /// <param name="args">Method arguments</param>
        /// <param name="types">Types array</param>
        /// <param name="useCancellationToken">Use cancellation token</param>
        /// <returns>RPC Request message object instance</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private RPCRequestMessage CreateRequest(string serviceName, string method, object[] args, Type[] types, bool useCancellationToken)
        {
            if (types is null && args != null)
            {
                types = new Type[args.Length];
                for (var i = 0; i < args.Length; i++)
                {
                    if (args[i] != null)
                        types[i] = args[i].GetType();
                }
            }
            var mDesc = _methodDescriptorCache.GetOrAdd((serviceName, method, types), _getMethodDescriptorDelegate);
            if (mDesc is null)
                ThrowMethodDescriptionNull(serviceName, method, args);

            if (mDesc.Parameters?.Length == 1 && (args is null || args.Length == 0))
                args = _nullItemArgs;

            return RPCRequestMessage.Retrieve(mDesc.Id, args, useCancellationToken);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private MethodDescriptor GetMethodDescriptor((string ServiceName, string Method, Type[] Types) key)
        {
            if (!Descriptors.Items.TryGetValue(key.ServiceName, out var descriptor)) return null;
            var lstMethods = new List<MethodDescriptor>();
            var types = key.Types ?? Array.Empty<Type>();
            foreach (var method in descriptor.Methods.Values)
            {
                if (method.Name == key.Method && (method.Parameters?.Length ?? 0) == types.Length)
                    lstMethods.Add(method);
            }
            var mCount = lstMethods.Count;
            if (mCount == 0)
                return null;
            else if (mCount == 1)
                return lstMethods[0];
            else
            {
                foreach (var method in lstMethods)
                {
                    var found = true;
                    for (var i = 0; i < method.Parameters.Length; i++)
                    {
                        var p1 = method.Parameters[i].Parameter;
                        var t2 = types[i];
                        if (t2 != null && !p1.ParameterType.IsAssignableFrom(t2))
                        {
                            found = false;
                            break;
                        }
                        if (t2 != null || !p1.ParameterType.IsValueType) continue;
                        if (!p1.ParameterType.IsGenericType || p1.ParameterType.GetGenericTypeDefinition() != typeof(Nullable<>))
                        {
                            found = false;
                            break;
                        }
                    }
                    if (found)
                        return method;
                }
                return null;
            }
        }
        #endregion

        /// <summary>
        /// Dispose all resource
        /// </summary>
        public void Dispose()
        {
            _transport?.Dispose();
            _transport = null;
            _descriptors = null;
            _serverDescriptors = null;
            _transportInit = false;
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using System.Runtime.InteropServices;
using OpenSSL.Crypto;
using OpenSSL.Core;
using Mono.Options;
using System.Reflection;

namespace scallion
{
    public enum Mode
    {
        Normal,
        NonOptimized,
        Help,
        ListDevices,
		WriteModuli,
		ReadResults
    }

    public class ProgramParameters
    {
        private static ProgramParameters _instance = new ProgramParameters();
        public static ProgramParameters Instance
        {
            get { return _instance; }
        }
        public uint CpuThreads = 1;
        public uint WorkSize = 1024 * 1024 * 16;
        public uint WorkGroupSize = 0;
        public uint DeviceId = 0;
        public uint KeySize = 1024;
        public uint ResultsArraySize = 128;
        public Mode ProgramMode = Mode.Normal;
        public string SaveGeneratedKernelPath = null;
        public bool ContinueGeneration = false;
        public string Regex = null;
        public string KeyOutputPath = null;
		public string PIDFile = null;

		public int ExponentIndex {
			get {
				switch (KeySize) {
				case 4096:
				case 2048:
					return 11;
				case 1024:
					return 9;
				default:
					throw new System.NotImplementedException();
				}
			}
		}

		public string RSAModuliPath = null;
		public string InputResultsPath = null;

		public Queue<BigNumber> RSAPublicModuli = null;
		public StreamWriter UsedModuliFile = null;

        public KernelType KernelType
        {
            get
            {
                if (ProgramMode == Mode.NonOptimized)
                    return KernelType.Normal;
				return KernelType.Optimized4;
                throw new System.NotImplementedException();
            }
        }
        public string CreateDefinesString()
        {
            StringBuilder builder = new StringBuilder();
            var fields = this.GetType()
                .GetFields(BindingFlags.Public | BindingFlags.Instance)
                .Cast<object>()
                .Concat(this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).Cast<object>());
            foreach (var field in fields)
            {
                KeyValuePair<string, object> value = new KeyValuePair<string, object>();
                if (field as FieldInfo != null)
                    value = new KeyValuePair<string, object>(((FieldInfo)field).Name, ((FieldInfo)field).GetValue(this));
                else if (field as PropertyInfo != null)
                    value = new KeyValuePair<string, object>(((PropertyInfo)field).Name, ((PropertyInfo)field).GetValue(this, null));
                if (value.Value == null) continue;
                if (value.Value.GetType() == typeof(uint))
                    builder.AppendLine(string.Format("#define {0} {1}", value.Key, value.Value));
                if (value.Value.GetType() == typeof(KernelType))
                    builder.AppendLine(string.Format("#define KT_{0}", value.Value));
            }
            return builder.ToString();
        }
    }

    class Program
    {
        // returns the queried preferred work group size for a device
        // moved to external function as we call it also in Main
        public static ulong getPreferredWorkGroupSize(IntPtr deviceId)
        {
            //get preferredWorkGroupSize
            ulong preferredWorkGroupSize;
            {
                CLContext context = new CLContext(deviceId);
                IntPtr program = context.CreateAndCompileProgram(@"__kernel void get_size(__global float2 *in) { }");
                CLKernel kernel = context.CreateKernel(program, "get_size");
                preferredWorkGroupSize = kernel.KernelPreferredWorkGroupSizeMultiple;
                kernel.Dispose();
                OpenTK.Compute.CL10.CL.ReleaseProgram(program);
                context.Dispose();
            }
            return preferredWorkGroupSize;
        }

        public static void ListDevices()
        {
            int deviceId = 0;
            foreach (CLDeviceInfo device in CLRuntime.GetDevices())
            {
                if (!device.CompilerAvailable) continue;
                //get preferredWorkGroupSize
                ulong preferredWorkGroupSize = getPreferredWorkGroupSize(device.DeviceId);  // moved to external function as we call it also in Main

                //display device
                Console.WriteLine("Id:{0} Name:{1}",
                    deviceId, device.Name.Trim());
                Console.WriteLine("    PreferredGroupSizeMultiple:{0} ComputeUnits:{1} ClockFrequency:{2}",
                    preferredWorkGroupSize, device.MaxComputeUnits, device.MaxClockFrequency);
                Console.WriteLine("    MaxConstantBufferSize:{0} MaxConstantArgs:{1} MaxMemAllocSize:{2}",
                    device.MaxConstantBufferSize, device.MaxConstantArgs, device.MaxMemAllocSize);
                Console.WriteLine("");
                deviceId++;
            }
        }

		public static void WriteModuli()
		{
			ProgramParameters parms = ProgramParameters.Instance;

			var rp = new RegexPattern(parms.Regex);
			ulong hashes_per_win = (ulong)(0.5 / rp.GenerateAllOnionPatternsForRegex().Select(t=>Math.Pow(2,-5*t.Count(q=>q!='.'))).Sum());
			ulong hashes_per_key = (CLRuntime.EXP_MAX - CLRuntime.EXP_MIN) / 2;
			ulong keys_needed = hashes_per_win / hashes_per_key;
			uint SF = 5;

			Console.WriteLine("Generating that pattern will require approximately {0:0.000} gigahashes.", hashes_per_win / 1e9);
			Console.WriteLine("That will require on average {0} public keys.", keys_needed);
			Console.WriteLine("Generating {0} keys (for safety's sake).", keys_needed * SF);

			RSAWrapper rsa = new RSAWrapper();

			StreamWriter priv_sw = new StreamWriter(parms.RSAModuliPath + ".priv");
			StreamWriter pub_sw = new StreamWriter(parms.RSAModuliPath);
			for (ulong i = 0; i < keys_needed * SF; i++)
			{
				if (i % 100 == 0) {
					Console.WriteLine("Generating key {0} of {1}...", i, keys_needed*SF);
				}
				rsa.GenerateKey((int)parms.KeySize);
				pub_sw.WriteLine(rsa.Rsa.PublicModulus.ToDecimalString());
				priv_sw.WriteLine("Public Modulus: " + rsa.Rsa.PublicModulus.ToDecimalString());
				priv_sw.WriteLine(rsa.Rsa.PrivateKeyAsPEM);
				priv_sw.WriteLine("");
			}
			pub_sw.Close();
			priv_sw.Close();
		}

		public static void ReadResults()
		{
			ProgramParameters parms = ProgramParameters.Instance;

			string rsaPrivFn = parms.RSAModuliPath + ".priv";
			if (!File.Exists(rsaPrivFn)) {
				Console.WriteLine("Error: expecting private key file at {0}.", rsaPrivFn);
				return;
			}
			if (!File.Exists(parms.InputResultsPath)) {
				Console.WriteLine("Error: expecting results from miner at {0}.", parms.InputResultsPath);
				return;
			}

			// Create a map to hold (public modulus as decimal string) -> (private key as pem)
			IDictionary<string, string> modulusKeyMap = new Dictionary<string, string>();

			// Read the priv key list file
			string currentModulus = null, currentPEM = null;
			foreach (string l in File.ReadAllLines(rsaPrivFn)) {
				string line = l.Trim();
				if (line.StartsWith("Public Modulus: ")) {
					currentModulus = line.Replace("Public Modulus: ","");
				}

				if (line.StartsWith("-----BEGIN RSA PRIVATE KEY-----")) {
					currentPEM = "";
				}
				currentPEM += line + "\n";
				if (line.StartsWith("-----END RSA PRIVATE KEY-----")) {
					modulusKeyMap.Add(currentModulus, currentPEM);
				}
			}

			// Read the results file
			string modulus = null, exponent = null, address = null;
			foreach (string l in File.ReadAllLines(parms.InputResultsPath))	{
				//string[] split = l.Trim().Split(":".ToCharArray(), 2);
				string line = l.Trim();
				if (line.StartsWith("Public Modulus: ")) {
					modulus = line.Replace("Public Modulus: ","");
				}
				if (line.StartsWith("Public Exponent: ")) {
					exponent = line.Replace("Public Exponent: ","");
				}
				if (line.StartsWith("Address/Hash: ")) {
					address = line.Replace("Address/Hash: ","");
				}

				if (modulus != null && exponent != null && address != null) {
					// Find the modulus in the private key map
					string pem;
					if (!modulusKeyMap.TryGetValue(modulus, out pem)) {
						throw new InvalidDataException(String.Format("Modulus {0} is missing from the private key data file.", modulus));
					}

					// Load the PEM into the RSA
					RSAWrapper rsa = new RSAWrapper();
					rsa.FromPrivateKeyPEM(pem);

					// Verify that modulus matches
					if (rsa.Rsa.PublicModulus != BigNumber.FromDecimalString(modulus)) {
						throw new InvalidDataException("Modulus of PEM does not match declared value.");
					}

					// Change the public exponent
					rsa.ChangePublicExponent(BigNumber.FromDecimalString(exponent));

					// Check the key's sanity
					rsa.CheckSanity();

					// Verify the hash
					if (rsa.OnionHash + ".onion" != address) {
						throw new InvalidDataException("Onion hash of key does not match declared value.");
					}

					// Yay the key is good! Output it as required
					CLRuntime.OutputKey(rsa);

					modulus = null;
					exponent = null;
					address = null;
				}

			}
		}

        public static void Help(OptionSet p)
        {
            Console.WriteLine("Usage: scallion [OPTIONS]+ regex [regex]+");
            Console.WriteLine("Searches for a tor hidden service address that matches one of the provided regexes.");
            Console.WriteLine();
            Console.WriteLine("Options:");
            p.WriteOptionDescriptions(Console.Out);
        }
        static CLRuntime _runtime = new CLRuntime();
        static void Main(string[] args)
        {
            ProgramParameters parms = ProgramParameters.Instance;
            Func<Mode, Action<string>> parseMode = (m) => (s) => { if (!string.IsNullOrEmpty(s)) { parms.ProgramMode = m; } };
            OptionSet p = new OptionSet()
                .Add<uint>("k|keysize=", "Specifies keysize for the RSA key", (i) => parms.KeySize = i)
                .Add("n|nonoptimized", "Runs non-optimized kernel", parseMode(Mode.NonOptimized))
                .Add("l|listdevices", "Lists the devices that can be used.", parseMode(Mode.ListDevices))
                .Add("h|?|help", "Displays command line usage help.", parseMode(Mode.Help))
                .Add<uint>("d|device=", "Specifies the opencl device that should be used.", (i) => parms.DeviceId = i)
                .Add<uint>("g|groupsize=", "Specifies the number of threads in a workgroup.", (i) => parms.WorkGroupSize = i)
                .Add<uint>("w|worksize=", "Specifies the number of hashes preformed at one time.", (i) => parms.WorkSize = i)
                .Add<uint>("t|cputhreads=", "Specifies the number of CPU threads to use when creating work. (EXPERIMENTAL - OpenSSL not thread-safe)", (i) => parms.CpuThreads = i)
				.Add<string>("pidfile=", "Specifies a file where the process id will be written; file will be deleted at exit", (i) => parms.PIDFile = i)
				.Add<string>("m|modulifile=", "Specifies a file containing public key moduli", (i) => parms.RSAModuliPath = i)
				.Add("s|write-moduli", "Writes moduli and private keys for a given pattern to the file specified with -m", (i) => { if (parms.ProgramMode != Mode.Help) parms.ProgramMode = Mode.WriteModuli; })
				.Add("r|read-results=", "Reads a results file (generated by a remote miner) and output the winning key (-m must be specified)", (i) => parms.InputResultsPath = i)
				.Add<string>("p|save-kernel=", "Saves the generated kernel to this path.", (i) => parms.SaveGeneratedKernelPath = i)
                .Add<string>("o|output=", "Saves the generated key(s) and address(es) to this path.", (i) => parms.KeyOutputPath = i)
                .Add("c|continue", "Continue to search for keys rather than exiting when a key is found.", (i) => { if (!string.IsNullOrEmpty(i)) parms.ContinueGeneration = true; })
                ;

            List<string> extra = p.Parse(args);

			if (parms.InputResultsPath != null && parms.ProgramMode != Mode.Help) {
				parms.ProgramMode = Mode.ReadResults;
			}

            if (parms.ProgramMode == Mode.NonOptimized || parms.ProgramMode == Mode.Normal || parms.ProgramMode == Mode.WriteModuli)
            {
                if (extra.Count < 1) parms.ProgramMode = Mode.Help;
                else parms.Regex = extra.ToDelimitedString("|");
            }

			if (parms.PIDFile != null)
			{
				File.WriteAllText(parms.PIDFile, System.Diagnostics.Process.GetCurrentProcess().Id.ToString());
			}

            //_runtime.Run(ProgramParameters.Instance,"prefix[abcdef]");
            switch (parms.ProgramMode)
            {
                case Mode.Help:
                    Help(p);
                    break;
                case Mode.ListDevices:
                    ListDevices();
                    break;
				case Mode.WriteModuli:
					WriteModuli();
					break;
				case Mode.ReadResults:
					ReadResults();
					break;
                case Mode.Normal:
		        case Mode.NonOptimized:
		            {

		                // If no Work Group Size provided, then query the selected device for preferred, if not found set to 32.
		                if (parms.WorkGroupSize == 0)
		                {
		                    ulong preferredWorkGroupSize = 32;
		                    uint deviceId = 0;
		                    foreach (CLDeviceInfo device in CLRuntime.GetDevices())
		                    {
		                        if (!device.CompilerAvailable) continue;
		                        if (deviceId == parms.DeviceId)
		                        {
		                            preferredWorkGroupSize = getPreferredWorkGroupSize(device.DeviceId);
		                            break;
		                        }
		                        deviceId++;
		                    }

		                    parms.WorkGroupSize = (uint)preferredWorkGroupSize;
		                }

						// If a moduli file is specified, read it and create or read a .used file
						if (parms.RSAModuliPath != null)
						{
							if (File.Exists(parms.RSAModuliPath))
							{
								// Read and/or create used file
								string usedPath = parms.RSAModuliPath + ".used";
								HashSet<string> used = null;
								if (File.Exists(usedPath))
								{
									used = new HashSet<string>();
									foreach (var line in File.ReadAllLines(usedPath))
									{
										used.Add(line.Trim());
									}
								}
								else
								{
									File.WriteAllText(usedPath, "");
								}

								// Set up used file to be written later
								parms.UsedModuliFile = new StreamWriter(usedPath, true);

								// Read moduli file
								parms.RSAPublicModuli = new Queue<BigNumber>();
								foreach (var line in File.ReadAllLines(parms.RSAModuliPath))
								{
									if (used == null || !used.Contains(line.Trim()))
										parms.RSAPublicModuli.Enqueue(BigNumber.FromDecimalString(line.Trim()));
								}
							}
						}

		                Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
						try {
		                	_runtime.Run(ProgramParameters.Instance);
						}
						finally {
							Shutdown();
						}
		            }
            break;
            }

        }

		static void Shutdown()
		{
			ProgramParameters parms = ProgramParameters.Instance;
			if (parms.UsedModuliFile != null)
				parms.UsedModuliFile.Close();
			if (parms.PIDFile != null && File.Exists(parms.PIDFile))
				File.Delete(parms.PIDFile);
			Console.WriteLine();
			Console.WriteLine("Stopping the GPU and shutting down...");
			Console.WriteLine();
			lock (_runtime) { _runtime.Abort = true; }
		}

        static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
        {
			Shutdown();
            e.Cancel = true;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""URLs for the ``django-user-media`` app."""
from django.conf.urls import patterns, url

from user_media.views import (
    AJAXImageCropView,
    AJAXMultipleImageUploadView,
    AJAXSingleImageUploadView,
    CreateImageView,
    DeleteImageView,
    UpdateImageView,
)

urlpatterns = patterns(
    '',
    url(r'^image/create/$',
        CreateImageView.as_view(),
        name='user_media_image_create_no_ctype'),
    url(r'^image/(?P<content_type>[-\w]+)/(?P<object_id>\d+)/create/$',
        CreateImageView.as_view(),
        name='user_media_image_create'),
    url(r'^image/(?P<pk>\d+)/$',
        UpdateImageView.as_view(),
        name='user_media_image_edit'),
    url(r'^image/(?P<pk>\d+)/crop/$',
        AJAXImageCropView.as_view(),
        name='user_media_image_crop'),
    url(r'^image/(?P<pk>\d+)/delete/$',
        DeleteImageView.as_view(),
        name='user_media_image_delete'),
    url(r'^upload-single/(?P<c_type>[-\w]+)/(?P<obj_id>\d+)/(?P<field>\w+)/$',
        AJAXSingleImageUploadView.as_view(),
        name='user_media_ajax_single_upload'),
    url(r'^upload-multiple/(?P<c_type>[-\w]+)/(?P<obj_id>\d+)/$',
        AJAXMultipleImageUploadView.as_view(),
        name='user_media_ajax_multiple_upload'),
)


text:
{% extends 'layout.html' %}

{% block pageheader %}
Rename {{ page.title }}
{% endblock %}

{% block content %}

❮ Back

    <form method="POST">
        {{ form.hidden_tag() }}

        {% with messages = get_flashed_messages() %}
            {% if messages %}
                {% for message in messages %}

                    ×
                    {{ message }}

                {% endfor %}
            {% endif %}
        {% endwith %}

        {% if form.new_title.errors %}
            {% for error in form.new_title.errors %}

                    ×
                    {{ error }}

            {% endfor %}
        {% endif %}

        {{ form.new_title.label(class="sr-only") }}
        {{ form.new_title(class="form-control", placeholder="New title") }}

        {{ form.submit(class="btn btn-primary col-2") }}

    </form>

        The new page title will be updated for all the pages which referenced it.

{% endblock %}


text:
/*globals describe, it, expect*/

describe('jasmine-firefoxaddon', function () {
  'use strict';
  it('Runs & Reports', function () {
    expect(true).toBe(true);
  });

  it('Copies resource files', function () {
    var datapath = 'resource://grunt-jasmine-firefoxaddon-runner/data/';
    Components.utils.import(datapath + 'test/resource1.jsm');
    Components.utils.import(datapath + 'test/resource2.jsm');
    expect(resource1).toBe('Loaded first resource file');
    expect(resource2).toBe('Loaded second resource file');
  });

  it('Has helper files copied appropriately', function () {
    // Checks to see that testHelper.jsm was loaded
    expect(test()).toBe('helper loaded');
  });
});


text:
package com.icegreen.greenmail.imap.commands;

import com.icegreen.greenmail.imap.ImapRequestLineReader;
import com.icegreen.greenmail.imap.ImapResponse;
import com.icegreen.greenmail.imap.ImapSession;
import com.icegreen.greenmail.imap.ProtocolException;

/**
 * Handles processing for the AUTHENTICATE imap command.
 *
 * @author Darrell DeBoer <darrell@apache.org>
 * @version $Revision: 109034 $
 */
class AuthenticateCommand extends NonAuthenticatedStateCommand {
    public static final String NAME = "AUTHENTICATE";
    public static final String ARGS = "<auth_type> *(CRLF base64)";

    /**
     * @see CommandTemplate#doProcess
     */
    protected void doProcess(ImapRequestLineReader request,
                             ImapResponse response,
                             ImapSession session) throws ProtocolException {
        String authType = parser.astring(request);
        parser.endLine(request);

        response.commandFailed(this, "Unsupported authentication mechanism '" +
                authType + "'");
    }

    /**
     * @see ImapCommand#getName
     */
    public String getName() {
        return NAME;
    }

    /**
     * @see CommandTemplate#getArgSyntax
     */
    public String getArgSyntax() {
        return ARGS;
    }
}

/*
6.2.1.  AUTHENTICATE Command

   Arguments:  authentication mechanism name

   Responses:  continuation data can be requested

   Result:     OK - authenticate completed, now in authenticated state
               NO - authenticate failure: unsupported authentication
                    mechanism, credentials rejected
              BAD - command unknown or arguments invalid,
                    authentication exchange cancelled

      The AUTHENTICATE command indicates an authentication mechanism,
      such as described in [IMAP-AUTH], to the server.  If the server
      supports the requested authentication mechanism, it performs an
      authentication protocol exchange to authenticate and identify the
      client.  It MAY also negotiate an OPTIONAL protection mechanism
      for subsequent protocol interactions.  If the requested
      authentication mechanism is not supported, the server SHOULD
      reject the AUTHENTICATE command by sending a tagged NO response.

      The authentication protocol exchange consists of a series of
      server challenges and client answers that are specific to the
      authentication mechanism.  A server challenge consists of a
      command continuation request response with the "+" token followed
      by a BASE64 encoded string.  The client answer consists of a line
      consisting of a BASE64 encoded string.  If the client wishes to
      cancel an authentication exchange, it issues a line with a single
      "*".  If the server receives such an answer, it MUST reject the
      AUTHENTICATE command by sending a tagged BAD response.

      A protection mechanism provides integrity and privacy protection
      to the connection.  If a protection mechanism is negotiated, it is
      applied to all subsequent data sent over the connection.  The
      protection mechanism takes effect immediately following the CRLF
      that concludes the authentication exchange for the client, and the
      CRLF of the tagged OK response for the server.  Once the
      protection mechanism is in effect, the stream of command and
      response octets is processed into buffers of ciphertext.  Each
      buffer is transferred over the connection as a stream of octets
      prepended with a four octet field in network byte order that
      represents the length of the following data.  The maximum
      ciphertext buffer length is defined by the protection mechanism.

      Authentication mechanisms are OPTIONAL.  Protection mechanisms are
      also OPTIONAL; an authentication mechanism MAY be implemented
      without any protection mechanism.  If an AUTHENTICATE command
      fails with a NO response, the client MAY try another
      authentication mechanism by issuing another AUTHENTICATE command,
      or MAY attempt to authenticate by using the LOGIN command.  In
      other words, the client MAY request authentication types in
      decreasing order of preference, with the LOGIN command as a last
      resort.

   Example:    S: * OK KerberosV4 IMAP4rev1 Server
               C: A001 AUTHENTICATE KERBEROS_V4
               S: + AmFYig==
               C: BAcAQU5EUkVXLkNNVS5FRFUAOCAsho84kLN3/IJmrMG+25a4DT
                  +nZImJjnTNHJUtxAA+o0KPKfHEcAFs9a3CL5Oebe/ydHJUwYFd
                  WwuQ1MWiy6IesKvjL5rL9WjXUb9MwT9bpObYLGOKi1Qh
               S: + or//EoAADZI=
               C: DiAF5A4gA+oOIALuBkAAmw==
               S: A001 OK Kerberos V4 authentication successful

      Note: the line breaks in the first client answer are for editorial
      clarity and are not in real authenticators.
*/


text:
package com.intellij.codeInsight.daemon.impl.quickfix;

import com.intellij.codeInsight.CodeInsightUtilBase;
import com.intellij.codeInsight.daemon.QuickFixBundle;
import com.intellij.codeInsight.intention.impl.BaseIntentionAction;
import com.intellij.codeInsight.template.Template;
import com.intellij.codeInsight.template.TemplateEditingListener;
import com.intellij.codeInsight.template.TemplateManager;
import com.intellij.ide.util.PsiClassListCellRenderer;
import com.intellij.ide.util.PsiElementListCellRenderer;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.PopupChooserBuilder;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.ui.components.JBList;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.VisibilityUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author Mike
 */
public abstract class CreateFromUsageBaseFix extends BaseIntentionAction {
  private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageBaseFix");

  protected CreateFromUsageBaseFix() {
  }

  public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
    int offset = editor.getCaretModel().getOffset();
    PsiElement element = getElement();
    if (element == null) {
      return false;
    }

    List<PsiClass> targetClasses = getTargetClasses(element);
    return !targetClasses.isEmpty() && !isValidElement(element) && isAvailableImpl(offset);
  }

  protected abstract boolean isAvailableImpl(int offset);

  protected abstract void invokeImpl(PsiClass targetClass);

  protected abstract boolean isValidElement(PsiElement result);

  public void invoke(@NotNull Project project, Editor editor, PsiFile file) {
    PsiDocumentManager.getInstance(project).commitAllDocuments();

    PsiElement element = getElement();

    if (LOG.isDebugEnabled()) {
      LOG.debug("CreateFromUsage: element =" + element);
    }

    if (element == null) {
      return;
    }

    List<PsiClass> targetClasses = getTargetClasses(element);
    if (targetClasses.isEmpty()) return;

    if (targetClasses.size() == 1) {
      doInvoke(project, targetClasses.get(0));
    } else {
      chooseTargetClass(targetClasses, editor);
    }
  }

  private void doInvoke(Project project, final PsiClass targetClass) {
    if (!CodeInsightUtilBase.prepareFileForWrite(targetClass.getContainingFile())) {
      return;
    }

    IdeDocumentHistory.getInstance(project).includeCurrentPlaceAsChangePlace();
    ApplicationManager.getApplication().runWriteAction(new Runnable() {
      public void run() {
        invokeImpl(targetClass);
      }
    });
  }

  @Nullable
  protected abstract PsiElement getElement();

  private void chooseTargetClass(List<PsiClass> classes, final Editor editor) {
    final Project project = classes.get(0).getProject();

    final JList list = new JBList(classes);
    PsiElementListCellRenderer renderer = new PsiClassListCellRenderer();
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setCellRenderer(renderer);
    final PopupChooserBuilder builder = new PopupChooserBuilder(list);
    renderer.installSpeedSearch(builder);

    Runnable runnable = new Runnable() {
      public void run() {
        int index = list.getSelectedIndex();
        if (index < 0) return;
        final PsiClass aClass = (PsiClass) list.getSelectedValue();
        doInvoke(project, aClass);
      }
    };

    builder.
      setTitle(QuickFixBundle.message("target.class.chooser.title")).
      setItemChoosenCallback(runnable).
      createPopup().
      showInBestPositionFor(editor);
  }

  protected static Editor positionCursor(Project project, @NotNull PsiFile targetFile, @NotNull PsiElement element) {
    TextRange range = element.getTextRange();
    int textOffset = range.getStartOffset();

    OpenFileDescriptor descriptor = new OpenFileDescriptor(project, targetFile.getVirtualFile(), textOffset);
    return FileEditorManager.getInstance(project).openTextEditor(descriptor, true);
  }

  protected void setupVisibility(PsiClass parentClass, PsiClass targetClass, PsiModifierList list) throws IncorrectOperationException {
    if (targetClass.isInterface()) {
      list.deleteChildRange(list.getFirstChild(), list.getLastChild());
      return;
    }
    VisibilityUtil.setVisibility(list, getVisibility(parentClass, targetClass));
  }

  protected String getVisibility(PsiClass parentClass, PsiClass targetClass) {
    if (parentClass != null && (parentClass.equals(targetClass) || PsiTreeUtil.isAncestor(targetClass, parentClass, true))) {
      return PsiModifier.PRIVATE;
    } else {
      return PsiModifier.PUBLIC;
    }
  }

  protected static boolean shouldCreateStaticMember(PsiReferenceExpression ref, PsiClass targetClass) {
    if (targetClass.isInterface()) {
      return false;
    }

    PsiExpression qualifierExpression = ref.getQualifierExpression();
    while (qualifierExpression instanceof PsiParenthesizedExpression) {
      qualifierExpression = ((PsiParenthesizedExpression) qualifierExpression).getExpression();
    }

    if (qualifierExpression instanceof PsiReferenceExpression) {
      PsiReferenceExpression referenceExpression = (PsiReferenceExpression) qualifierExpression;

      PsiElement resolvedElement = referenceExpression.resolve();

      return resolvedElement instanceof PsiClass;
    } else if (qualifierExpression != null) {
      return false;
    } else {
      assert PsiTreeUtil.isAncestor(targetClass, ref, true);
      PsiModifierListOwner owner = PsiTreeUtil.getParentOfType(ref, PsiModifierListOwner.class);
      if (owner instanceof PsiMethod && ((PsiMethod)owner).isConstructor()) {
        //usages inside delegating constructor call
        PsiExpression run = ref;
        while (true) {
          if (!(run.getParent() instanceof PsiExpression)) break;
          run = (PsiExpression)run.getParent();
        }
        if (run.getParent() instanceof PsiExpressionList &&
          run.getParent().getParent() instanceof PsiMethodCallExpression) {
          @NonNls String calleeText = ((PsiMethodCallExpression)run.getParent().getParent()).getMethodExpression().getText();
          if (calleeText.equals("this") || calleeText.equals("super")) return true;
        }
      }

      while (owner != null && owner != targetClass) {
        if (owner.hasModifierProperty(PsiModifier.STATIC)) return true;
        owner = PsiTreeUtil.getParentOfType(owner, PsiModifierListOwner.class);
      }
    }

    return false;
  }

  @Nullable
  private static PsiExpression getQualifier (PsiElement element) {
    if (element instanceof PsiNewExpression) {
      PsiJavaCodeReferenceElement ref = ((PsiNewExpression) element).getClassReference();
      if (ref instanceof PsiReferenceExpression) {
        return ((PsiReferenceExpression) ref).getQualifierExpression();
      }
    } else if (element instanceof PsiReferenceExpression) {
      return ((PsiReferenceExpression) element).getQualifierExpression();
    } else if (element instanceof PsiMethodCallExpression) {
      return ((PsiMethodCallExpression) element).getMethodExpression().getQualifierExpression();
    }

    return null;
  }

  protected static PsiSubstitutor getTargetSubstitutor (PsiElement element) {
    if (element instanceof PsiNewExpression) {
      JavaResolveResult result = ((PsiNewExpression)element).getClassOrAnonymousClassReference().advancedResolve(false);
      PsiSubstitutor substitutor = result.getSubstitutor();
      return substitutor == null ? PsiSubstitutor.EMPTY : substitutor;
    }

    PsiExpression qualifier = getQualifier(element);
    if (qualifier != null) {
      PsiType type = qualifier.getType();
      if (type instanceof PsiClassType) {
        return ((PsiClassType)type).resolveGenerics().getSubstitutor();
      }
    }

    return PsiSubstitutor.EMPTY;
  }

  protected boolean isAllowOuterTargetClass() {
    return true;
  }

  //Should return only valid inproject classes
  @NotNull
  protected List<PsiClass> getTargetClasses(PsiElement element) {
    PsiClass psiClass = null;
    PsiExpression qualifier = null;

    if (element instanceof PsiNewExpression) {
      final PsiNewExpression newExpression = (PsiNewExpression)element;
      PsiJavaCodeReferenceElement ref = newExpression.getClassOrAnonymousClassReference();
      if (ref != null) {
        PsiElement refElement = ref.resolve();
        if (refElement instanceof PsiClass) psiClass = (PsiClass)refElement;
      }
    }
    else if (element instanceof PsiReferenceExpression) {
      qualifier = ((PsiReferenceExpression)element).getQualifierExpression();
    }
    else if (element instanceof PsiMethodCallExpression) {
      final PsiReferenceExpression methodExpression = ((PsiMethodCallExpression)element).getMethodExpression();
      qualifier = methodExpression.getQualifierExpression();
      @NonNls final String referenceName = methodExpression.getReferenceName();
      if (referenceName == null) return Collections.emptyList();
    }
    boolean allowOuterClasses = false;
    if (qualifier != null) {
      PsiType type = qualifier.getType();
      if (type instanceof PsiClassType) {
        psiClass = ((PsiClassType)type).resolve();
      }

      if (qualifier instanceof PsiJavaCodeReferenceElement) {
        final PsiElement resolved = ((PsiJavaCodeReferenceElement)qualifier).resolve();
        if (resolved instanceof PsiClass) {
          if (psiClass == null) psiClass = (PsiClass)resolved;
        }
      }
    } else if (psiClass == null) {
      psiClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
      allowOuterClasses = true;
    }

    if (psiClass instanceof PsiTypeParameter) {
      PsiClass[] supers = psiClass.getSupers();
      List<PsiClass> filtered = new ArrayList<PsiClass>();
      for (PsiClass aSuper : supers) {
        if (!aSuper.getManager().isInProject(aSuper)) continue;
        if (!(aSuper instanceof PsiTypeParameter)) filtered.add(aSuper);
      }
      return filtered;
    }
    else {
      if (psiClass == null || !psiClass.getManager().isInProject(psiClass)) {
        return Collections.emptyList();
      }

      if (!allowOuterClasses ||
          !isAllowOuterTargetClass() ||
          ApplicationManager.getApplication().isUnitTestMode())
        return Collections.singletonList(psiClass);

      List<PsiClass> result = new ArrayList<PsiClass>();

      while (psiClass != null) {
        result.add(psiClass);
        if (psiClass.hasModifierProperty(PsiModifier.STATIC)) break;
        psiClass = PsiTreeUtil.getParentOfType(psiClass, PsiClass.class);
      }
      return result;
    }
  }

  protected static void startTemplate (@NotNull Editor editor, final Template template, @NotNull final Project project) {
    startTemplate(editor, template, project, null);
  }

  protected static void startTemplate (@NotNull final Editor editor, final Template template, @NotNull final Project project, final TemplateEditingListener listener) {
    Runnable runnable = new Runnable() {
      public void run() {
        if (project.isDisposed() || editor.isDisposed()) return;
        TemplateManager.getInstance(project).startTemplate(editor, template, listener);
      }
    };
    if (ApplicationManager.getApplication().isUnitTestMode()) {
      runnable.run();
    }
    else {
      ApplicationManager.getApplication().invokeLater(runnable);
    }
  }

  @Override
  public boolean startInWriteAction() {
    return false;
  }
}


text:
class AvailabilitiesController < ApplicationController
  before_action :authenticate_user!

  def new
  end

  def index

    @group = Group.find(params[:group_id])
    user_groups = UserGroup.where(group_id: @group.id)
    @users = []
    user_groups.each do |user_group|
      if user_group.user_id != current_user.id
        @users << User.find(user_group.user_id)
      end
    end

    current_user_selected_topics = UserSelectedTopic.where(user_id: current_user.id, selected: true)
    current_user_availabilities = []

    current_user_selected_topics.each do |cust|
      cust.availabilities.each do |avail|
        current_user_availabilities << avail
      end
    end

    usts = []
    @users.each do |user|
      current_user_selected_topics.each do |cust|
        UserSelectedTopic.where(user_id: user.id, selected: true).each do |ust|
          if ust.topic_id == cust.topic_id
            usts << ust
          end
        end
      end
    end

    availabilities = []
    usts.each do |ust|
      ust.availabilities.each do |avail|
        availabilities << avail
      end
    end

    @possible_availability_matches = []
    availabilities.each do |avail|
      current_user_availabilities.each do |current_avail|
        if Hour.find(avail.hour_id).day == Hour.find(current_avail.hour_id).day && Hour.find(avail.hour_id).hr == Hour.find(current_avail.hour_id).hr && Hour.find(avail.hour_id).month == Hour.find(current_avail.hour_id).month && UserSelectedTopic.find(avail.user_selected_topic_id).topic_id == UserSelectedTopic.find(current_avail.user_selected_topic_id).topic_id
          # find PotentialPair for the current_avail && avail check to see if accped is false for either user.
          if(PotentialPair.exists?(availability1_id: current_avail.id, availability2_id: avail.id))
            pp = PotentialPair.find_by(availability1_id: current_avail.id, availability2_id: avail.id)
            current_avail_1_or_2 = 1
          elsif
            (PotentialPair.exists?(availability1_id: avail.id, availability2_id: current_avail.id))
            pp = PotentialPair.find_by(availability1_id: avail.id, availability2_id: current_avail.id)
            current_avail_1_or_2 = 2
          else
            pp = nil
          end
          if pp == nil
            @possible_availability_matches << avail
          else
            if (pp.user1_accepted != false && pp.user2_accepted != false) && (pp.user1_accepted != true || pp.user2_accepted != true)
              #check if this user accepted it:
              if !(current_avail_1_or_2 == 1 && pp.user1_accepted == true)
                if !(current_avail_1_or_2 == 2 && pp.user2_accepted == true)
                  @possible_availability_matches << avail
                end
              end
            end
          end

        end
      end
    end
    if @possible_availability_matches.length == 0
      @no_matches = true
    end

    @possible_availability_matches = @possible_availability_matches.uniq
    @current_user = current_user

  end

  def create
  end

  def edit
  end

  def update
  end

  def destroy
  end

end


text:
    <md-spinner></md-spinner>

                {{customizedTextJson.error.noservice}}

            <md-card class="primaryBackground settingBorder" (click)="incomingCallExpanded()">
                <md-list>
                    <md-list-item class="itemHeight44" >

                        {{customizedTextJson.incoming_calls}}

                    </md-list-item>
                </md-list>
            </md-card>

            <incoming></incoming>

            <md-card class="primaryBackground settingBorder" (click)="outgoingCallExpanded()">
                <md-list >
                    <md-list-item class="itemHeight44">

                        {{customizedTextJson.outgoing_calls}}

                    </md-list-item>
                </md-list>
            </md-card>

            <outgoing></outgoing>

            <md-card class="primaryBackground settingBorder" (click)="voicemailExpanded()">
                <md-list>
                    <md-list-item class="itemHeight44">

                        {{customizedTextJson.voice_mail}}

                    </md-list-item>
                </md-list>
            </md-card>

            <voicemail></voicemail>

            <md-card class="primaryBackground settingBorder" (click)="callControlExpanded()">
                <md-list>
                    <md-list-item class="itemHeight44">

                        {{customizedTextJson.call_control}}

                    </md-list-item>
                </md-list>
            </md-card>

            <callControl></callControl>


text:
package org.jetbrains.debugger;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.concurrency.Promise;
import org.jetbrains.debugger.values.ValueManager;

import java.util.List;

/**
 * An object that matches the execution state of the VM while suspended
 */
public interface SuspendContext {
  @NotNull
  SuspendState getState();

  @Nullable("if no frames (paused by user)")
  Script getScript();

  /**
   * @return the current exception state, or {@code null} if current state is
   *         not {@code EXCEPTION}
   * @see #getState()
   */
  @Nullable
  ExceptionData getExceptionData();

  @Nullable
  CallFrame getTopFrame();

  /**
   * Call frames for the current suspended state (from the innermost (top) frame to the main (bottom) frame)
   */
  @NotNull
  Promise<CallFrame[]> getFrames();

  /**
   * list of the breakpoints hit on VM suspension with which this
   * context is associated. An empty collection if the suspension was
   * not related to hitting breakpoints (e.g. a step end)
   */
  @NotNull
  List<Breakpoint> getBreakpointsHit();

  @NotNull
  ValueManager getValueManager();
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.

namespace Microsoft.Azure.Search.Serialization
{
    using System;
    using System.Reflection;
    using Microsoft.Azure.Search.Models;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;

    /// <summary>
    /// Deserializes SearchResult instances from OData-compliant JSON.
    /// </summary>
    /// <typeparam name="TDoc">
    /// The CLR type that maps to the index schema. Instances of this type can be stored as documents in the index.
    /// </typeparam>
    /// <typeparam name="TResult">
    /// Type of the model class that encapsulates documents in a search response.
    /// </typeparam>
    internal class SearchResultConverter<TResult, TDoc> : JsonConverter
        where TResult : SearchResultBase<TDoc>, new()
        where TDoc : class
    {
        public override bool CanRead
        {
            get
            {
                return true;
            }
        }

        public override bool CanWrite
        {
            get
            {
                return false;
            }
        }

        public override bool CanConvert(Type objectType)
        {
            return typeof(TResult).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
        }

        public override object ReadJson(
            JsonReader reader,
            Type objectType,
            object existingValue,
            JsonSerializer serializer)
        {
            JObject propertyBag = serializer.Deserialize<JObject>(reader);
            JToken score = propertyBag["@search.score"];
            JToken highlights = propertyBag["@search.highlights"];

            var result = new TResult();
            result.Score = score.Value<double>();

            if (highlights != null)
            {
                var highlightReader = new JTokenReader(highlights);
                result.Highlights = serializer.Deserialize<HitHighlights>(highlightReader);
            }

            var docReader = new JTokenReader(propertyBag);
            result.Document = serializer.Deserialize<TDoc>(docReader);
            return result;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }
}


text:
from functools import partial

from ..params.encodings import EncodingParam
from ..params.values import URLParam
from .base import StringProp

__all__ = ["PhotoProp"]

class PhotoProp(StringProp):

    authorized_params = ["ENCODING", "TYPE", "VALUE"]

    name = "PHOTO"

    def export(self, path):
        """Export value to a file.

        """
        pass

    def import(self, path):
        """Import a file to the value.

        """
        if URLParam in self.params:
            ## Do not import.
            return
        ## Check and get encodings.
        encoders = {p for p in self.params if isinstance(p, EncodingParam)}
        if   len(encoders) == 0:
            raise ValueError("No encoding found.")
        elif len(encoders) > 1:
            raise ValueError("More than one encoding, ambigous.")
        encoder = next(encoders)
        ## Check path.
        if not path.exists():
            raise FileNotFoundError( str(path) )
        ## TODO: Check file extension.
        ## Do import.
        with path.open("rb") as file:
            self.value = encoder.encode(file.read())


text:
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
    <link href="css/repose.css" rel="stylesheet" media="screen">
    <title>Atom Hopper</title>

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

      </button>
      Home

Running Tests

Applications

Results

Atom Hopper

atom feed applications that acts as a repository for feeds from other projects

Applications

Applications can be configured by users.  You can view application setup here and can set up/edit/delete your application.

View details »

Results

Historical results per application can be found here.

View details »

Running tests

Check out which tests are running and results.

View details »

© Rackspace Hosting 2013


text:
/*
 * Zookaba.h
 *
 *  Created on: 7 feb 2013
 *      Author: mattias
 */

#ifndef ZOOKABA_H_
#define ZOOKABA_H_

#include "Weapon.h"

class Zookaba: public Weapon {
	int Delay;
public:
	Zookaba();
	virtual ~Zookaba();
	void Fire(double X, double Y, double XAim, double YAim, int Turn, bool isFire);
};

#endif /* ZOOKABA_H_ */