text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;
using System.Xml;
using System.Runtime.Remoting.Channels.Ipc;
using System.Runtime.Remoting.Channels;
using System.Collections;
using System.Runtime.Remoting;
using System.Runtime.Serialization.Formatters;

using Microsoft.AspNet.SignalR.Client;
using log4net;

using DigitalPlatform;
using DigitalPlatform.Net;
using DigitalPlatform.MessageClient;
using DigitalPlatform.IO;
using DigitalPlatform.Z3950.Server;
using DigitalPlatform.Interfaces;
using DigitalPlatform.SIP.Server;
using DigitalPlatform.Text;
using System.Text;
using DigitalPlatform.Core;

namespace dp2Capo
{
    public static class ServerInfo
    {
        // 指示全局 Service 是否处在运行状态
        public static bool GlobalServiceRunning { get; set; }

        public static ZServer ZServer { get; set; }

        public static SipServer SipServer { get; set; }

        // 实例集合
        public static SafeList<Instance> _instances = new SafeList<Instance>();

        // 管理线程
        public static DefaultThread _defaultThread = new DefaultThread();

        public static LifeThread _lifeThread = new LifeThread();

        public static RecordLockCollection _recordLocks = new RecordLockCollection();

        public static string DataDir
        {
            get;
            set;
        }

        const int Z3950_DEFAULT_PORT = 210;

        static int _z3950_port = -1;   // -1 表示不启用 Z39.50 Server
        public static int Z3950ServerPort
        {
            get
            {
                return _z3950_port;
            }
            set
            {
                _z3950_port = value;
            }
        }

        static int _sip_port = -1;   // -1 表示不启用 SIP Server
        public static int SipServerPort
        {
            get
            {
                return _sip_port;
            }
            set
            {
                _sip_port = value;
            }
        }

        // 配置文件 XmlDocument
        public static XmlDocument ConfigDom = null; // new XmlDocument();

        internal static CancellationTokenSource _cancel = new CancellationTokenSource();

        public static void LoadGlobalCfg(string strDataDir, bool bAutoCreate = true)
        {
            string strCfgFileName = Path.Combine(strDataDir, "config.xml");
            try
            {
                ConfigDom = new XmlDocument();
                ConfigDom.Load(strCfgFileName);

                {
                    // 元素 <zServer>
                    // 属性 port
                    if (ConfigDom.DocumentElement.SelectSingleNode("zServer") is XmlElement node && node.HasAttribute("port"))
                    {
                        string v = node.GetAttribute("port");
                        if (string.IsNullOrEmpty(v))
                            _z3950_port = -1;
                        else
                        {
                            if (Int32.TryParse(v, out int port) == false)
                                throw new Exception("zServer/@port 属性值必须是整数");
                            _z3950_port = port;
                        }
                    }
                    else
                    {
                        _z3950_port = -1;  // -1 表示不启用 Z39.50 Server
                    }
                }

                {
                    // 元素 <zServer>
                    // 属性 port
                    if (ConfigDom.DocumentElement.SelectSingleNode("sipServer") is XmlElement node && node.HasAttribute("port"))
                    {
                        string v = node.GetAttribute("port");
                        if (string.IsNullOrEmpty(v))
                            _sip_port = -1;
                        else
                        {
                            if (Int32.TryParse(v, out int port) == false)
                                throw new Exception("sipServer/@port 属性值必须是整数");
                            _sip_port = port;
                        }
                    }
                    else
                    {
                        _sip_port = -1;  // -1 表示不启用 Z39.50 Server
                    }
                }
            }
            catch (FileNotFoundException ex)
            {
                if (bAutoCreate == true)
                {
                    ConfigDom.LoadXml("<root />");
                }
                else
                    throw new Exception("配置文件 '" + strCfgFileName + "' 不存在", ex);
            }
            catch (Exception ex)
            {
                // WriteErrorLog("装载配置文件 '" + strCfgFileName + "' 时出现异常: " + ExceptionUtil.GetExceptionText(ex));
                throw new Exception("装载配置文件 '" + strCfgFileName + "' 时出现异常: " + ex.Message, ex);
            }
        }

        // 暂时没有地方调用本函数。注意应该是有个 changed 表示为 true 时候才覆盖原有配置文件。避免和外面主动修改配置文件的时候互相覆盖
        public static void SaveGlobalCfg(string strDataDir)
        {
            if (ConfigDom == null)
                throw new Exception("尚未执行 Initial()");

            XmlElement node = ConfigDom.DocumentElement.SelectSingleNode("zServer") as XmlElement;
            if (node == null)
            {
                node = ConfigDom.CreateElement("zServer");
                ConfigDom.DocumentElement.AppendChild(node);
            }

            node.SetAttribute("port", _z3950_port.ToString());

            string strCfgFileName = Path.Combine(strDataDir, "config.xml");
            PathUtil.CreateDirIfNeed(strDataDir);
            ConfigDom.Save(strCfgFileName);
        }

        // static Mutex _mutex = null;

        // 首次从数据目录装载全部实例定义,并连接服务器
        public static void Initial(string strDataDir)
        {
            DataDir = strDataDir;
            LogDir = Path.Combine(strDataDir, "log");   // 日志目录
            PathUtil.CreateDirIfNeed(LogDir);

            // http://stackoverflow.com/questions/184084/how-to-force-c-sharp-net-app-to-run-only-one-instance-in-windows
            // mutex name need contains windows account name. or us programes file path, hashed
            // _mutex = new Mutex(true, "dp2Capo V1", out bool createdNew);

            // 要避免初始化发生两次
            // https://stackoverflow.com/questions/579688/why-is-the-date-appended-twice-on-filenames-when-using-log4net
            var repository = log4net.LogManager.CreateRepository("main");
            // if (createdNew)
            log4net.GlobalContext.Properties["LogFileName"] = Path.Combine(LogDir, "log_");
            log4net.Config.XmlConfigurator.Configure(repository);

            LibraryManager.Log = LogManager.GetLogger("main", "zlib");
            _log = LogManager.GetLogger("main", "capo");

            string strVersion = Assembly.GetAssembly(typeof(ServerInfo)).GetName().Version.ToString();

            // 验证一下日志文件是否允许写入。这样就可以设置一个标志,决定后面的日志信息写入文件还是 Windows 日志
            // DetectWriteErrorLog("*** dp2Capo 开始启动 (dp2Capo 版本: " + strVersion + ")");
            WriteLog("info", "*** dp2Capo 开始启动 (dp2Capo 版本: " + strVersion + ")");

#if NO
            try
            {
                ServerInfo.LoadGlobalCfg(DataDir);
            }
            catch (Exception ex)
            {
                WriteLog("fatal", "dp2Capo 装载全局配置文件阶段出错: " + ex.Message);
                throw ex;
            }
#endif

            _exited = false;

            DirectoryInfo root = new DirectoryInfo(strDataDir);
            var dis = root.GetDirectories();
            foreach (DirectoryInfo di in dis)
            {
                if (di.Name.ToLower() == "log")
                    continue;
                //string strXmlFileName = Path.Combine(di.FullName, "capo.xml");
                //if (File.Exists(strXmlFileName) == false)
                //    continue;
                Instance instance = new Instance();
                instance.DataDir = di.FullName;
                instance.Start();
                _instances.Add(instance);
            }

#if NO
            // 连接服务器,如果暂时连接失败,后面会不断自动重试连接
            foreach (Instance instance in _instances)
            {
                instance.BeginConnnect();
            }
#endif

            _defaultThread.BeginThread();

            _lifeThread.BeginThread();
        }

#if NO
        // 根据实例名,找到实例数据目录
        public static string FindInstanceDataDir(string strInstanceName)
        {
            DirectoryInfo root = new DirectoryInfo(DataDir);
            var dis = root.GetDirectories();
            foreach (DirectoryInfo di in dis)
            {
                if (di.Name.ToLower() == "log")
                    continue;
                string strXmlFileName = Path.Combine(di.FullName, "capo.xml");
                string strCurrentInstanceName = Instance.GetInstanceName(strXmlFileName);
                //if (File.Exists(strXmlFileName) == false)
                //    continue;
                if (strInstanceName == strCurrentInstanceName)
                    return di.FullName;
            }

            return null;
        }
#endif
        // 从 _instances 集合中查找一个实例
        public static Instance FindInstance(string strInstanceName)
        {
            Instance instance = null;
            if (string.IsNullOrEmpty(strInstanceName))
                instance = _instances[0];
            else
                instance = _instances.Find(
                    (o) =>
                    {
                        return (o.Name == strInstanceName);
                    });
            //if (instance == null)
            //    return instance;
            return instance;
        }

        // 尝试从数据目录装载一个尚未存在于 _instances 集合中的实例
        // exception:
        //      可能会抛出异常。XML 文件装载失败引起
        public static Instance LoadInstance(string strInstanceName)
        {
            var exist = _instances.Find((o) =>
            {
                if (o.Name == strInstanceName) return true;
                return false;
            });
            if (exist != null)
                return exist;

            DirectoryInfo root = new DirectoryInfo(DataDir);
            var dis = root.GetDirectories();
            foreach (DirectoryInfo di in dis)
            {
                if (di.Name.ToLower() == "log")
                    continue;
                string strXmlFileName = Path.Combine(di.FullName, "capo.xml");
                if (File.Exists(strXmlFileName) == false)
                    continue;

                string strCurrentInstanceName = Instance.GetInstanceName(strXmlFileName);
                if (strCurrentInstanceName == strInstanceName)
                {
                    Instance instance = new Instance();
                    instance.Name = strCurrentInstanceName;
                    instance.DataDir = di.FullName;
                    _instances.Add(instance);
                    return instance;
                }
            }

            return null;
        }

        // 启动一个实例
        // parameters:
        //      strInstanceName 实例名。如果为 ".global" 表示全局服务
        public static ServiceControlResult StartInstance(string strInstanceName)
        {
            if (strInstanceName == ".global")
            {
                StartGlobalService(true);
                return new ServiceControlResult();
            }

            Instance instance = FindInstance(strInstanceName);
            if (instance == null)
            {
                // 尝试从数据目录装载一个尚未存在于 _instances 集合中的实例
                // exception:
                //      可能会抛出异常。XML 文件装载失败引起
                try
                {
                    instance = LoadInstance(strInstanceName);
                }
                catch (Exception ex)
                {
                    return new ServiceControlResult
                    {
                        Value = -1,
                        ErrorCode = ex.GetType().ToString(),
                        ErrorInfo = "实例 '" + strInstanceName + "' LoadInstance() 时出现异常: " + ExceptionUtil.GetAutoText(ex)
                    };
                }
            }

            if (instance == null)
                return new ServiceControlResult
                {
                    Value = -1,
                    ErrorCode = "NotFound",
                    ErrorInfo = "实例 '" + strInstanceName + "' 没有找到"
                };
            try
            {
                instance.Start();
                return new ServiceControlResult();
            }
            catch (Exception ex)
            {
                return new ServiceControlResult
                {
                    Value = -1,
                    ErrorCode = ex.GetType().ToString(),
                    ErrorInfo = "启动实例 '" + strInstanceName + "' 时出现异常: " + ex.Message
                };
            }
        }

        public static void StartGlobalService(bool bLoadGlobalCfg)
        {
            if (bLoadGlobalCfg)
            {
                try
                {
                    ServerInfo.LoadGlobalCfg(DataDir);
                }
                catch (Exception ex)
                {
                    WriteLog("fatal", "dp2Capo 启动全局服务阶段,装载全局配置文件出错: " + ex.Message);
                    // throw ex;
                    return;
                }
            }

            if (ServerInfo.Z3950ServerPort != -1)
            {
                ServerInfo.ZServer = new ZServer(ServerInfo.Z3950ServerPort);
                Z3950Processor.AddEvents(ServerInfo.ZServer, true);
                ServerInfo.ZServer.Listen(1000);
            }

            if (ServerInfo.SipServerPort != -1)
            {
                ServerInfo.SipServer = new SipServer(ServerInfo.SipServerPort);
                SipProcessor.AddEvents(ServerInfo.SipServer, true);
                ServerInfo.SipServer.Listen(1000);
            }

            ServerInfo.GlobalServiceRunning = true;
        }

        public static void StopGlobalService()
        {
            if (ServerInfo.ZServer != null)
            {
                ServerInfo.ZServer.Close();
                ServerInfo.ZServer.Dispose();
                Z3950Processor.AddEvents(ServerInfo.ZServer, false);
                ServerInfo.ZServer = null;
            }

            if (ServerInfo.SipServer != null)
            {
                ServerInfo.SipServer.Close();
                ServerInfo.SipServer.Dispose();
                SipProcessor.AddEvents(ServerInfo.SipServer, false);
                ServerInfo.SipServer = null;
            }

            ServerInfo.GlobalServiceRunning = false;
        }

#if NO
        // TODO: 这里有个问题:什么能代表全局服务?
        public static bool IsGlobalServiceRunning()
        {
            if (ServerInfo.ZServer != null)
                return true;
            return false;
        }
#endif

        // 停止一个实例
        //      strInstanceName 实例名。如果为 ".global" 表示全局服务
        public static ServiceControlResult StopInstance(string strInstanceName)
        {
            if (strInstanceName == ".global")
            {
                StopGlobalService();
                return new ServiceControlResult();
            }

            Instance instance = FindInstance(strInstanceName);
            if (instance == null)
                return new ServiceControlResult
                {
                    Value = -1,
                    ErrorCode = "NotFound",
                    ErrorInfo = "实例 '" + strInstanceName + "' 没有找到"
                };
            try
            {
                instance.Close();
                return new ServiceControlResult();
            }
            catch (Exception ex)
            {
                return new ServiceControlResult
                {
                    Value = -1,
                    ErrorCode = ex.GetType().ToString(),
                    ErrorInfo = "停止实例 '" + strInstanceName + "' 时出现异常: " + ex.Message
                };
            }
        }

        #region Windows Service 控制命令设施

        static IpcServerChannel m_serverChannel = null;

        public static void StartRemotingServer()
        {
            // http://www.cnblogs.com/gisser/archive/2011/12/31/2308989.html
            // https://stackoverflow.com/questions/7126733/ipcserverchannel-properties-problem
            // https://stackoverflow.com/questions/2400320/dealing-with-security-on-ipc-remoting-channel
            BinaryServerFormatterSinkProvider provider = new BinaryServerFormatterSinkProvider();
            provider.TypeFilterLevel = TypeFilterLevel.Full;
            Hashtable ht = new Hashtable();
            ht["portName"] = "dp2capo_ServiceControlChannel";
            ht["name"] = "ipc";
            ht["authorizedGroup"] = "Administrators"; // "Everyone";
            m_serverChannel = new IpcServerChannel(ht, provider);

            //Register the server channel.
            ChannelServices.RegisterChannel(m_serverChannel, false);

            RemotingConfiguration.ApplicationName = "dp2library_ServiceControlServer";

            //Register this service type.
            RemotingConfiguration.RegisterWellKnownServiceType(
                typeof(ServiceControlServer),
                "dp2library_ServiceControlServer",
                WellKnownObjectMode.Singleton);
        }

        public static void EndRemotingServer()
        {
            if (m_serverChannel != null)
            {
                ChannelServices.UnregisterChannel(m_serverChannel);
                m_serverChannel = null;
            }
        }

        #endregion

        // 运用控制台显示方式,设置一个实例的基本参数
        // parameters:
        //      index   实例子目录下标。从 0 开始计数
        public static void ChangeInstanceSettings(string strDataDir, int index)
        {
            DirectoryInfo root = new DirectoryInfo(strDataDir);
            var dis = root.GetDirectories();
            int i = 0;
            foreach (DirectoryInfo di in dis)
            {
                string strXmlFileName = Path.Combine(di.FullName, "capo.xml");

                if (i == index)
                {
                    Instance.ChangeSettings(strXmlFileName);
                    return;
                }
                i++;
            }

            // throw new Exception("下标 "+index.ToString()+" 超过了当前实际存在的实例数");

            // 创建足够多的新实例子目录
            for (; i <= index; i++)
            {
                string strName = Guid.NewGuid().ToString();
                string strInstanceDir = Path.Combine(strDataDir, strName);
                Directory.CreateDirectory(strInstanceDir);
                if (i == index)
                {
                    string strXmlFileName = Path.Combine(strInstanceDir, "capo.xml");
                    Instance.ChangeSettings(strXmlFileName);
                    return;
                }
            }
        }

        static bool _exited = false;
        // 准备退出
        public static void Exit()
        {
            if (_exited == false)
            {
                _lifeThread.StopThread(true);
                _lifeThread.Dispose();

                _defaultThread.StopThread(true);    // 强制退出
                _defaultThread.Dispose();

                // 保存配置

                // 切断连接
                foreach (Instance instance in _instances)
                {
                    instance.Close();
                }
                _exited = true;

                WriteLog("info", "*** dp2Capo 成功降落");
                _logger.Dispose();
            }
        }

        static TimeSpan LongTime = TimeSpan.FromMinutes(5);    // 10

        static bool NeedCheckMessageServer(Instance instance)
        {
            // 2018/8/28
            if (instance.dp2mserver == null)
                return false;

            DateTime now = DateTime.Now;

            ConnectionState state = instance.MessageConnection.ConnectState;

            if (state == ConnectionState.Disconnected)
            {
                instance.LastCheckTime = now;
                return true;
            }
            else
            {
                if (now - instance.LastCheckTime >= LongTime)
                {
                    instance.LastCheckTime = now;
                    return true;
                }
            }

            return false;
        }

        static void EchoMessageServer(Instance instance, bool writeLog)
        {
            // 2018/8/28
            if (instance.dp2mserver == null)
                return;

            if (instance.MessageConnection.ConnectState != ConnectionState.Connected)
                return;

            // 验证一次请求
            // string text = Guid.NewGuid().ToString();
            string text = "!verify";

            if (writeLog)
                instance.WriteErrorLog("Begin echo: " + text);

            try
            {
                string result = instance.MessageConnection.EchoTaskAsync(text, TimeSpan.FromSeconds(5), instance._cancel.Token).Result;

                // 此用法在 dp2mserver 不存在 echo() API 的时候会挂起当前线程
                // string result = instance.MessageConnection.echo(text).Result;

                if (result == null)
                    result = "(timeout)";

                if (writeLog)
                    instance.WriteErrorLog("End   echo: " + result);
            }
            catch (Exception ex)
            {
                instance.WriteErrorLog("echo 出现异常: " + ExceptionUtil.GetExceptionText(ex));
                {
                    string strErrorCode = "";
                    if (MessageConnection.IsHttpClientException(ex, out strErrorCode))
                    {
                        // echo 的时候有小概率可能会返回用户认证异常?重置连接
                        Task.Run(() => instance.TryResetConnection());
                    }
                }
            }

        }

        /*
*
.NET Runtime 	Error 	2016/11/4 13:19:54
Application: dp2capo.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Net.Sockets.SocketException
   at System.Net.Dns.GetAddrInfo(System.String)
   at System.Net.Dns.InternalGetHostByName(System.String, Boolean)
   at System.Net.Dns.GetHostAddresses(System.String)
   at System.Net.NetworkInformation.Ping.Send(System.String, Int32, Byte[], System.Net.NetworkInformation.PingOptions)

Exception Info: System.Net.NetworkInformation.PingException
   at System.Net.NetworkInformation.Ping.Send(System.String, Int32, Byte[], System.Net.NetworkInformation.PingOptions)
   at DigitalPlatform.Net.NetUtil.Ping(System.String, System.String ByRef)
   at dp2Capo.ServerInfo.Check(dp2Capo.Instance, System.Collections.Generic.List`1<System.Threading.Tasks.Task>)
   at dp2Capo.ServerInfo.BackgroundWork()
   at dp2Capo.DefaultThread.Worker()
   at DigitalPlatform.ThreadBase.ThreadMain()
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
   at System.Threading.ThreadHelper.ThreadStart()
         * */
        static void CheckMessageServer(Instance instance, List<Task> tasks)
        {
            if (instance.dp2mserver == null || string.IsNullOrEmpty(instance.dp2mserver.Url))
                return;

            if (instance.MessageConnection.ConnectState == ConnectionState.Disconnected)    // 注:如果在 Connecting 和 Reconnecting 状态则不尝试 ConnectAsync
            {
                // instance.BeginConnnect();
                tasks.Add(instance.BeginConnectTask());

                Uri uri = new Uri(instance.dp2mserver.Url);
                try
                {
                    if (NetUtil.Ping(uri.DnsSafeHost, out string strInformation) == true)
                    {
                        instance.WriteErrorLog("ping '" + uri.DnsSafeHost + "' success");
                    }
                    else
                    {
                        instance.WriteErrorLog("ping '" + uri.DnsSafeHost + "' fail: " + strInformation);
                    }
                }
                catch (Exception ex)
                {
                    instance.WriteErrorLog("ping '" + uri.DnsSafeHost + "' 出现异常: " + ExceptionUtil.GetExceptionText(ex));
                }
            }
            else
            {
                EchoMessageServer(instance, true);
            }
        }

        // 检测是否发生了死锁
        // return:
        //      true    发生了死锁
        //      false   没有发生死锁
        public static bool DetectDeadLock()
        {
            if (_instances == null || _instances.Count == 0)
                return false;
            DateTime now = DateTime.Now;
            TimeSpan delta = TimeSpan.FromMinutes(10);  // 10 分钟没有动作就表明死锁了
            foreach (Instance instance in _instances)
            {
                // 2018/8/28
                if (instance.dp2mserver == null)
                    continue;
                if (now - instance.LastCheckTime > delta)
                    return true;
            }

            return false;
        }

#if NO
        // 向第一个实例的日志文件中写入
        public static void WriteFirstInstanceErrorLog(string strText)
        {
            if (_instances == null || _instances.Count == 0)
                return;
            else
            {
                try
                {
                    _instances[0].WriteErrorLog(strText);
                }
                catch
                {
                    Program.WriteWindowsLog(strText);
                }
            }
        }
#endif

        static int _statisCount = 0;

        static DateTime _lastCleanTime = DateTime.Now;

        // 执行一些后台管理任务
        public static void BackgroundWork()
        {
            try
            {
                List<Task> tasks = new List<Task>();

#if NO
                Instance first_instance = null;
                if (_instances.Count > 0)
                    first_instance = _instances[0];
#endif

                foreach (Instance instance in _instances)
                {
                    // 向 dp2mserver 发送心跳消息
                    // instance.SendHeartBeat();

                    bool bNeedCheckMessageServer = NeedCheckMessageServer(instance);
                    bool bOutputBegin = false;

                    if (bNeedCheckMessageServer)
                    {
                        instance.WriteErrorLog("<<< BackgroundWork 开始一轮处理\r\n状态:\r\n" + instance.GetDebugState());
                        bOutputBegin = true;
                    }

                    string strError = "";
                    // 利用 dp2library API 获取一些配置信息
                    if (instance.dp2library != null
                        && string.IsNullOrEmpty(instance.dp2library.LibraryUID) == true)
                    {
                        int nRet = instance.MessageConnection.GetConfigInfo(out strError);
                        if (nRet == -1)
                        {
                            // Program.WriteWindowsLog(strError);
                            instance.WriteErrorLog("获得 dp2library 配置时出错: " + strError);
                        }
                        else
                        {
#if NO
                        if (instance.MessageConnection.IsConnected == false)
                        {
                            tasks.Add(instance.BeginConnectTask()); // 2016/10/13 以前没有 if 语句,那样就容易导致重复 BeginConnect()
                        }
#endif
                            if (bNeedCheckMessageServer)
                                CheckMessageServer(instance, tasks);
                            else
                                EchoMessageServer(instance, false);
                        }
                    }
                    else
                    {
#if NO
                    if (instance.MessageConnection.IsConnected == false)
                    {
                        // instance.BeginConnnect();
                        tasks.Add(instance.BeginConnectTask());
                    }
                    else
                    {
                        // TODO: 验证一次请求
                    }
#endif

                        if (bNeedCheckMessageServer)
                            CheckMessageServer(instance, tasks);
                        else
                            EchoMessageServer(instance, false);

                        // 每隔二十分钟清理一次闲置的 dp2library 通道
                        if (DateTime.Now - _lastCleanTime >= TimeSpan.FromMinutes(20))
                        {
                            try
                            {
                                WriteLog("info", $"实例 {instance.Name} 开始释放空闲通道");
                                int count = instance.MessageConnection.CleanLibraryChannel();
                                WriteLog("info", $"实例 {instance.Name} 释放空闲通道 {count} 个。正在占用的通道为 {instance.MessageConnection._libraryChannelPool.GetUsingCount()} 个");
                            }
                            catch (Exception ex)
                            {
                                string error = $"实例 {instance.Name} 释放空闲通道时出现异常: {ExceptionUtil.GetExceptionText(ex)}";
                                instance.WriteErrorLog(error);
                                WriteLog("error", error);
                            }
                            _lastCleanTime = DateTime.Now;
                        }

                        // 重试初始化 ZHost 慢速参数
                        // instance.InitialZHostSlowConfig();

                        // 清除废弃的全局结果集
                        Task.Run(() => instance.FreeGlobalResultSets());
                    }

                    if (bOutputBegin == true)
                        instance.WriteErrorLog(">>> BackgroundWork 结束一轮处理\r\n");
                }

                {
                    // 写入统计信息
                    _statisCount++;
                    if ((_statisCount % 10) == 1)
                    {
                        LogCpuUsage("dp2capo");
                        WriteLog("info", "ZServer 统计信息: " + ZServer?.GetStatisInfo() + "LibraryChannel 占用: " + GetLibraryChannelCountText());
                    }

                    // 清理闲置超期的 Channels
                    ZServer?._tcpChannels?.CleanIdleChannels(TimeSpan.FromMinutes(2));
                    SipServer?._tcpChannels?.CleanIdleChannels(TimeSpan.MaxValue);   // TimeSpan.FromMinutes(2)

                    ZServer?.TryClearBlackList();
                    SipServer?.TryClearBlackList();

                    // 把紧凑日志写入日志文件。约十分钟写一次
                    if ((_statisCount % 10) == 1)
                        ZServer?.TryFlushCompactLog();

                    // 顺便清理一下 hangup 状态缓存
                    SipProcessor.ClearHangupStatusTable();
                }

                // 阻塞,直到全部任务完成。避免 BeginConnect() 函数被重叠调用
                if (tasks.Count > 0)
                {
                    // test 这一句可以用来制造死锁测试场景
                    // Thread.Sleep(60 * 60 * 1000);
                    WriteLog("info", "-- BackgroundWork - 等待 " + tasks.Count + " 个 Connect 任务完成");

                    Task.WaitAll(tasks.ToArray(), ServerInfo._cancel.Token);

                    WriteLog("info", "-- BackgroundWork - " + tasks.Count + " 个 Connect 任务已经完成");
                }

            }
            catch (Exception ex)
            {
                WriteLog("error", "BackgroundWork() 出现异常: " + ExceptionUtil.GetDebugText(ex));
            }
        }

        // 获得描述每个通道正在使用的 LibraryChannel 数量的文字
        static string GetLibraryChannelCountText()
        {
            try
            {
                StringBuilder text = new StringBuilder();
                foreach (Instance instance in _instances)
                {
                    text.AppendFormat("{0}={1}; ",
                        instance.Name,
                        instance.MessageConnection._libraryChannelPool.GetUsingCount());
                }
                return text.ToString().TrimEnd();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        // 检测高内存耗用
        public static bool DetectHighMemory(string appName, long threshold)
        {
            try
            {
                PerformanceCounter memory = new PerformanceCounter("Process", "Private Bytes", appName);

                for (int i = 0; i < 2; i++)
                {
                    if (i != 0)
                        System.Threading.Thread.Sleep(1000);

                    float m = memory.NextValue();
                    if (i != 0)
                    {
                        long mem_bytes = Convert.ToInt64(m);
                        if (mem_bytes >= threshold)
                        {
                            WriteLog("info", "*** 检测到高内存耗用 " + StringUtil.GetLengthText(mem_bytes));
                            return true;
                        }
                        return false;
                    }
                }

                return false;
            }
            catch (Exception ex)
            {
                WriteLog("error", "DetectHighMemory() 内出现异常: " + ExceptionUtil.GetExceptionText(ex));
                return false;
            }
        }

        private static void LogCpuUsage(string appName)
        {
            try
            {
                PerformanceCounter total_cpu = new PerformanceCounter("Process", "% Processor Time", "_Total");
                PerformanceCounter process_cpu = new PerformanceCounter("Process", "% Processor Time", appName);
                PerformanceCounter memory = new PerformanceCounter("Process", "Private Bytes", appName);

                for (int i = 0; i < 2; i++)
                {
                    if (i != 0)
                        System.Threading.Thread.Sleep(1000);

                    float t = total_cpu.NextValue();
                    float p = process_cpu.NextValue();
                    float m = memory.NextValue();
                    if (i != 0)
                    {
                        // Console.WriteLine(String.Format("_Total = {0}  App = {1} {2}%\n", t, p, p / t * 100));
                        WriteLog("info", "CPU " + Convert.ToInt64(p / t * 100).ToString() + "%, Memory " + StringUtil.GetLengthText(Convert.ToInt64(m)));
                    }
                }
            }
            catch (Exception ex)
            {
                WriteLog("error", "LogCpuUsage() 内出现异常: " + ExceptionUtil.GetExceptionText(ex));
            }
        }

        public static string Version
        {
            get
            {
                return Assembly.GetAssembly(typeof(Instance)).GetName().Version.ToString();
            }
        }

        #region 日志

        public static Logger _logger = new Logger();

        static string LogDir
        {
            get;
            set;
        }

        // private static readonly Object _syncRoot = new Object();

        static bool _errorLogError = false;    // 写入实例的日志文件是否发生过错误

#if NO
        static void _writeErrorLog(string strText)
        {
            _logger.Write(LogDir, strText);
        }

        // 尝试写入实例的错误日志文件
        // return:
        //      false   失败
        //      true    成功
        public static bool DetectWriteErrorLog(string strText)
        {
            _errorLogError = false;
            try
            {
                _writeErrorLog(strText);
            }
            catch (Exception ex)
            {
                WriteWindowsLog("尝试写入目录 " + LogDir + " 的日志文件发生异常, 后面将改为写入 Windows 日志。异常信息如下:'" + ExceptionUtil.GetDebugText(ex) + "'", EventLogEntryType.Error);
                _errorLogError = true;
                return false;
            }

            WriteWindowsLog("日志文件检测正常。从此开始关于 dp2Capo 的日志会写入目录 " + LogDir + " 中当天的日志文件",
                EventLogEntryType.Information);
            return true;
        }
#endif

#if NO
        // 写入实例的错误日志文件
        public static void WriteErrorLog(string strText)
        {
            Console.WriteLine(strText);

            if (_errorLogError == true) // 先前写入实例的日志文件发生过错误,所以改为写入 Windows 日志。会加上实例名前缀字符串
                WriteWindowsLog(strText, EventLogEntryType.Error);
            else
            {
                try
                {
                    _writeErrorLog(strText);
                }
                catch (Exception ex)
                {
                    WriteWindowsLog("因为原本要写入日志文件的操作发生异常, 所以不得不改为写入 Windows 日志(见后一条)。异常信息如下:'" + ExceptionUtil.GetDebugText(ex) + "'", EventLogEntryType.Error);
                    WriteWindowsLog(strText, EventLogEntryType.Error);
                }
            }
        }
#endif
        public static ILog Log
        {
            get
            {
                return _log;
            }
        }

        static ILog _log = null;

        // 写入全局日志文件
        public static void WriteErrorLog(string strText)
        {
            WriteLog("error", strText);
        }

        // 写入全局日志文件
        // parameters:
        //      level   info/error
        public static void WriteLog(string level, string strText)
        {
            Console.WriteLine(strText);

            if (_errorLogError == true || _log == null) // 先前写入实例的日志文件发生过错误,所以改为写入 Windows 日志。会加上实例名前缀字符串
                WriteWindowsLog(strText, EventLogEntryType.Error);
            else
            {
                try
                {
                    if (level == "info")
                        _log.Info(strText);
                    else if (level == "fatal")
                        _log.Fatal(strText);
                    else
                        _log.Error(strText);
                }
                catch (Exception ex)
                {
                    WriteWindowsLog("因为原本要写入日志文件的操作发生异常, 所以不得不改为写入 Windows 日志(见后一条)。异常信息如下:'" + ExceptionUtil.GetDebugText(ex) + "'", EventLogEntryType.Error);
                    WriteWindowsLog(strText, EventLogEntryType.Error);
                }
            }
        }

        // 写入 Windows 日志
        public static void WriteWindowsLog(string strText)
        {
            WriteWindowsLog(strText, EventLogEntryType.Error);
        }

        // 写入 Windows 日志
        public static void WriteWindowsLog(string strText,
            EventLogEntryType type)
        {
            EventLog Log = new EventLog();
            Log.Source = "dp2CapoService";
            Log.WriteEntry(strText, type);
        }

        #endregion

    }
}


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

namespace Fclp.Internals.Parsing.OptionParsers
{
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
public class ListCommandLineOptionParser<T> : ICommandLineOptionParser<List<T>>
{
    private readonly ICommandLineOptionParserFactory _parserFactory;

    /// <summary>
    /// Initialises a new instance of the <see cref="ListCommandLineOptionParser{T}"/>.
    /// </summary>
    /// <param name="parserFactory"></param>
    public ListCommandLineOptionParser(ICommandLineOptionParserFactory parserFactory)
    {
        _parserFactory = parserFactory;
    }

    /// <summary>
    /// Parses the specified <see cref="System.String"/> into the return type.
    /// </summary>
    /// <param name="parsedOption"></param>
    /// <returns>The parsed value.</returns>
    public List<T> Parse(ParsedOption parsedOption)
    {
        var parser = _parserFactory.CreateParser<T>();

        return parsedOption.Values.Select(value =>
        {
            var clone = parsedOption.Clone();
            clone.Value = value;
            return parser.Parse(clone);
        }).ToList();
    }

    /// <summary>
    /// Determines whether the specified <see cref="System.String"/> can be parsed by this <see cref="ICommandLineOptionParser{T}"/>.
    /// </summary>
    /// <param name="parsedOption"></param>
    /// <returns><c>true</c> if the specified <see cref="System.String"/> can be parsed by this <see cref="ICommandLineOptionParser{T}"/>; otherwise <c>false</c>.</returns>
    public bool CanParse(ParsedOption parsedOption)
    {
        if (parsedOption == null) return false;
        if (parsedOption.HasValue == false) return false;

        var parser = _parserFactory.CreateParser<T>();

        return parsedOption.Values.All(value =>
        {
            var clone = parsedOption.Clone();
            clone.Value = value;
            clone.Values = new [] { value };
            clone.AdditionalValues = new string[0];
            return parser.CanParse(clone);
        });
    }
}
}

redpajama_set_name: RedPajamaGithub


text:
.class Landroid/support/v4/provider/DocumentsContractApi21;
.super Ljava/lang/Object;
.source "DocumentsContractApi21.java"

# annotations
.annotation build Landroid/annotation/TargetApi;
    value = 0x15
.end annotation

.annotation build Landroid/support/annotation/RequiresApi;
    value = 0x15
.end annotation

# static fields
.field private static final TAG:Ljava/lang/String; = "DocumentFile"

# direct methods
.method constructor <init>()V
    .locals 0

    .prologue
    .line 32
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method private static closeQuietly(Ljava/lang/AutoCloseable;)V
    .locals 2
    .param p0, "closeable"    # Ljava/lang/AutoCloseable;

    .prologue
    .line 80
    if-eqz p0, :cond_0

    .line 82
    :try_start_0
    invoke-interface {p0}, Ljava/lang/AutoCloseable;->close()V
    :try_end_0
    .catch Ljava/lang/RuntimeException; {:try_start_0 .. :try_end_0} :catch_0
    .catch Ljava/lang/Exception; {:try_start_0 .. :try_end_0} :catch_1

    .line 88
    :cond_0
    :goto_0
    return-void

    .line 83
    :catch_0
    move-exception v0

    .line 84
    .local v0, "rethrown":Ljava/lang/RuntimeException;
    throw v0

    .line 85
    .end local v0    # "rethrown":Ljava/lang/RuntimeException;
    :catch_1
    move-exception v1

    goto :goto_0
.end method

.method public static createDirectory(Landroid/content/Context;Landroid/net/Uri;Ljava/lang/String;)Landroid/net/Uri;
    .locals 1
    .param p0, "context"    # Landroid/content/Context;
    .param p1, "self"    # Landroid/net/Uri;
    .param p2, "displayName"    # Ljava/lang/String;

    .prologue
    .line 42
    const-string v0, "vnd.android.document/directory"

    invoke-static {p0, p1, v0, p2}, Landroid/support/v4/provider/DocumentsContractApi21;->createFile(Landroid/content/Context;Landroid/net/Uri;Ljava/lang/String;Ljava/lang/String;)Landroid/net/Uri;

    move-result-object v0

    return-object v0
.end method

.method public static createFile(Landroid/content/Context;Landroid/net/Uri;Ljava/lang/String;Ljava/lang/String;)Landroid/net/Uri;
    .locals 1
    .param p0, "context"    # Landroid/content/Context;
    .param p1, "self"    # Landroid/net/Uri;
    .param p2, "mimeType"    # Ljava/lang/String;
    .param p3, "displayName"    # Ljava/lang/String;

    .prologue
    .line 37
    invoke-virtual {p0}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v0

    invoke-static {v0, p1, p2, p3}, Landroid/provider/DocumentsContract;->createDocument(Landroid/content/ContentResolver;Landroid/net/Uri;Ljava/lang/String;Ljava/lang/String;)Landroid/net/Uri;

    move-result-object v0

    return-object v0
.end method

.method public static listFiles(Landroid/content/Context;Landroid/net/Uri;)[Landroid/net/Uri;
    .locals 11
    .param p0, "context"    # Landroid/content/Context;
    .param p1, "self"    # Landroid/net/Uri;

    .prologue
    .line 51
    invoke-virtual {p0}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v0

    .line 53
    .local v0, "resolver":Landroid/content/ContentResolver;
    invoke-static {p1}, Landroid/provider/DocumentsContract;->getDocumentId(Landroid/net/Uri;)Ljava/lang/String;

    move-result-object v2

    .line 52
    invoke-static {p1, v2}, Landroid/provider/DocumentsContract;->buildChildDocumentsUriUsingTree(Landroid/net/Uri;Ljava/lang/String;)Landroid/net/Uri;

    move-result-object v1

    .line 54
    .local v1, "childrenUri":Landroid/net/Uri;
    new-instance v10, Ljava/util/ArrayList;

    invoke-direct {v10}, Ljava/util/ArrayList;-><init>()V

    .line 56
    .local v10, "results":Ljava/util/ArrayList;, "Ljava/util/ArrayList<Landroid/net/Uri;>;"
    const/4 v6, 0x0

    .line 58
    .local v6, "c":Landroid/database/Cursor;
    const/4 v2, 0x1

    :try_start_0
    new-array v2, v2, [Ljava/lang/String;

    const/4 v3, 0x0

    const-string v4, "document_id"

    aput-object v4, v2, v3

    const/4 v3, 0x0

    const/4 v4, 0x0

    const/4 v5, 0x0

    invoke-virtual/range {v0 .. v5}, Landroid/content/ContentResolver;->query(Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;

    move-result-object v6

    .line 60
    :goto_0
    invoke-interface {v6}, Landroid/database/Cursor;->moveToNext()Z

    move-result v2

    if-eqz v2, :cond_0

    .line 61
    const/4 v2, 0x0

    invoke-interface {v6, v2}, Landroid/database/Cursor;->getString(I)Ljava/lang/String;

    move-result-object v7

    .line 62
    .local v7, "documentId":Ljava/lang/String;
    invoke-static {p1, v7}, Landroid/provider/DocumentsContract;->buildDocumentUriUsingTree(Landroid/net/Uri;Ljava/lang/String;)Landroid/net/Uri;

    move-result-object v8

    .line 64
    .local v8, "documentUri":Landroid/net/Uri;
    invoke-virtual {v10, v8}, Ljava/util/ArrayList;->add(Ljava/lang/Object;)Z
    :try_end_0
    .catch Ljava/lang/Exception; {:try_start_0 .. :try_end_0} :catch_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    goto :goto_0

    .line 66
    .end local v7    # "documentId":Ljava/lang/String;
    .end local v8    # "documentUri":Landroid/net/Uri;
    :catch_0
    move-exception v9

    .line 67
    .local v9, "e":Ljava/lang/Exception;
    :try_start_1
    const-string v2, "DocumentFile"

    new-instance v3, Ljava/lang/StringBuilder;

    invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V

    const-string v4, "Failed query: "

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3, v9}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v3

    invoke-static {v2, v3}, Landroid/util/Log;->w(Ljava/lang/String;Ljava/lang/String;)I
    :try_end_1
    .catchall {:try_start_1 .. :try_end_1} :catchall_0

    .line 69
    invoke-static {v6}, Landroid/support/v4/provider/DocumentsContractApi21;->closeQuietly(Ljava/lang/AutoCloseable;)V

    .line 72
    .end local v9    # "e":Ljava/lang/Exception;
    :goto_1
    invoke-virtual {v10}, Ljava/util/ArrayList;->size()I

    move-result v2

    new-array v2, v2, [Landroid/net/Uri;

    invoke-virtual {v10, v2}, Ljava/util/ArrayList;->toArray([Ljava/lang/Object;)[Ljava/lang/Object;

    move-result-object v2

    check-cast v2, [Landroid/net/Uri;

    return-object v2

    .line 69
    :cond_0
    invoke-static {v6}, Landroid/support/v4/provider/DocumentsContractApi21;->closeQuietly(Ljava/lang/AutoCloseable;)V

    goto :goto_1

    :catchall_0
    move-exception v2

    invoke-static {v6}, Landroid/support/v4/provider/DocumentsContractApi21;->closeQuietly(Ljava/lang/AutoCloseable;)V

    throw v2
.end method

.method public static prepareTreeUri(Landroid/net/Uri;)Landroid/net/Uri;
    .locals 1
    .param p0, "treeUri"    # Landroid/net/Uri;

    .prologue
    .line 46
    .line 47
    invoke-static {p0}, Landroid/provider/DocumentsContract;->getTreeDocumentId(Landroid/net/Uri;)Ljava/lang/String;

    move-result-object v0

    .line 46
    invoke-static {p0, v0}, Landroid/provider/DocumentsContract;->buildDocumentUriUsingTree(Landroid/net/Uri;Ljava/lang/String;)Landroid/net/Uri;

    move-result-object v0

    return-object v0
.end method

.method public static renameTo(Landroid/content/Context;Landroid/net/Uri;Ljava/lang/String;)Landroid/net/Uri;
    .locals 1
    .param p0, "context"    # Landroid/content/Context;
    .param p1, "self"    # Landroid/net/Uri;
    .param p2, "displayName"    # Ljava/lang/String;

    .prologue
    .line 76
    invoke-virtual {p0}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v0

    invoke-static {v0, p1, p2}, Landroid/provider/DocumentsContract;->renameDocument(Landroid/content/ContentResolver;Landroid/net/Uri;Ljava/lang/String;)Landroid/net/Uri;

    move-result-object v0

    return-object v0
.end method


text:
#include "src/profiling/memory/wire_protocol.h"

#include <sys/socket.h>
#include <sys/types.h>

#include "perfetto/base/logging.h"
#include "perfetto/ext/base/scoped_file.h"
#include "perfetto/ext/base/unix_socket.h"
#include "test/gtest_and_gmock.h"

namespace perfetto {
namespace profiling {

bool operator==(const AllocMetadata& one, const AllocMetadata& other);
bool operator==(const AllocMetadata& one, const AllocMetadata& other) {
  return std::tie(one.sequence_number, one.alloc_size, one.alloc_address,
                  one.stack_pointer, one.stack_pointer_offset, one.arch) ==
             std::tie(other.sequence_number, other.alloc_size,
                      other.alloc_address, other.stack_pointer,
                      other.stack_pointer_offset, other.arch) &&
         memcmp(one.register_data, other.register_data, kMaxRegisterDataSize) ==
             0;
}

bool operator==(const FreeBatch& one, const FreeBatch& other);
bool operator==(const FreeBatch& one, const FreeBatch& other) {
  if (one.num_entries != other.num_entries)
    return false;
  for (size_t i = 0; i < one.num_entries; ++i) {
    if (std::tie(one.entries[i].sequence_number, one.entries[i].addr) !=
        std::tie(other.entries[i].sequence_number, other.entries[i].addr))
      return false;
  }
  return true;
}

namespace {

base::ScopedFile CopyFD(int fd) {
  int sv[2];
  PERFETTO_CHECK(socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == 0);
  base::UnixSocketRaw send_sock(base::ScopedFile(sv[0]),
                                base::SockFamily::kUnix,
                                base::SockType::kStream);
  base::UnixSocketRaw recv_sock(base::ScopedFile(sv[1]),
                                base::SockFamily::kUnix,
                                base::SockType::kStream);
  char msg[] = "a";
  PERFETTO_CHECK(send_sock.Send(msg, sizeof(msg), &fd, 1));
  base::ScopedFile res;
  recv_sock.Receive(msg, sizeof(msg), &res, 1);
  return res;
}

constexpr auto kShmemSize = 1048576;

TEST(WireProtocolTest, AllocMessage) {
  char payload[] = {0x77, 0x77, 0x77, 0x00};
  WireMessage msg = {};
  msg.record_type = RecordType::Malloc;
  AllocMetadata metadata = {};
  metadata.sequence_number = 0xA1A2A3A4A5A6A7A8;
  metadata.alloc_size = 0xB1B2B3B4B5B6B7B8;
  metadata.alloc_address = 0xC1C2C3C4C5C6C7C8;
  metadata.stack_pointer = 0xD1D2D3D4D5D6D7D8;
  metadata.stack_pointer_offset = 0xE1E2E3E4E5E6E7E8;
  metadata.arch = unwindstack::ARCH_X86;
  for (size_t i = 0; i < kMaxRegisterDataSize; ++i)
    metadata.register_data[i] = 0x66;
  msg.alloc_header = &metadata;
  msg.payload = payload;
  msg.payload_size = sizeof(payload);

  auto shmem_client = SharedRingBuffer::Create(kShmemSize);
  ASSERT_TRUE(shmem_client);
  ASSERT_TRUE(shmem_client->is_valid());
  auto shmem_server = SharedRingBuffer::Attach(CopyFD(shmem_client->fd()));

  ASSERT_TRUE(SendWireMessage(&shmem_client.value(), msg));

  auto buf = shmem_server->BeginRead();
  ASSERT_TRUE(buf);
  WireMessage recv_msg;
  ASSERT_TRUE(ReceiveWireMessage(reinterpret_cast<char*>(buf.data), buf.size,
                                 &recv_msg));
  shmem_server->EndRead(std::move(buf));

  ASSERT_EQ(recv_msg.record_type, msg.record_type);
  ASSERT_EQ(*recv_msg.alloc_header, *msg.alloc_header);
  ASSERT_EQ(recv_msg.payload_size, msg.payload_size);
  ASSERT_STREQ(recv_msg.payload, msg.payload);
}

TEST(WireProtocolTest, FreeMessage) {
  WireMessage msg = {};
  msg.record_type = RecordType::Free;
  FreeBatch batch = {};
  batch.num_entries = kFreeBatchSize;
  for (size_t i = 0; i < kFreeBatchSize; ++i) {
    batch.entries[i].sequence_number = 0x111111111111111;
    batch.entries[i].addr = 0x222222222222222;
  }
  msg.free_header = &batch;

  auto shmem_client = SharedRingBuffer::Create(kShmemSize);
  ASSERT_TRUE(shmem_client);
  ASSERT_TRUE(shmem_client->is_valid());
  auto shmem_server = SharedRingBuffer::Attach(CopyFD(shmem_client->fd()));

  ASSERT_TRUE(SendWireMessage(&shmem_client.value(), msg));

  auto buf = shmem_server->BeginRead();
  ASSERT_TRUE(buf);
  WireMessage recv_msg;
  ASSERT_TRUE(ReceiveWireMessage(reinterpret_cast<char*>(buf.data), buf.size,
                                 &recv_msg));
  shmem_server->EndRead(std::move(buf));

  ASSERT_EQ(recv_msg.record_type, msg.record_type);
  ASSERT_EQ(*recv_msg.free_header, *msg.free_header);
  ASSERT_EQ(recv_msg.payload_size, msg.payload_size);
}

}  // namespace
}  // namespace profiling
}  // namespace perfetto


text:
package org.artifactory.ui.rest.model.admin.configuration.generalconfig;

import org.artifactory.rest.common.model.BaseModel;
import org.artifactory.ui.rest.model.utils.FileUpload;

/**
 * @author Chen keinan
 */
public class LookAndFeelSettings extends BaseModel {

    private FileUpload fileUpload;
    private String logoUrl;

    public FileUpload getFileUpload() {
        return fileUpload;
    }

    public void setFileUpload(FileUpload fileUpload) {
        this.fileUpload = fileUpload;
    }

    public String getLogoUrl() {
        return logoUrl;
    }

    public void setLogoUrl(String logoUrl) {
        this.logoUrl = logoUrl;
    }
}


text:
var express = require('express');
var router = express.Router();
var quizController = require('../controllers/quiz_controller');
var commentController = require('../controllers/comment_controller');
var sessionController = require('../controllers/session_controller');

// Autoload de comandos con :quizId y :commentId
router.param('quizId', quizController.load);
router.param('commentId', commentController.load);

// Rutas de sesion
router.get('/login', sessionController.new); //Form de login
router.post('/login', sessionController.create); //Crear sesion
router.get('/logout', sessionController.destroy); //Destruir sesion

// Ruta home page.
router.get('/', quizController.home);
// Ruta About us
router.get('/author', quizController.author);
// Rutas de quizes
router.get('/quizes', quizController.index);
router.get('/quizes/:quizId(\\d+)', quizController.show);
router.get('/quizes/:quizId(\\d+)/answer', quizController.answer);
router.get('/quizes/new', sessionController.loginRequired, quizController.new);
router.post('/quizes/create', sessionController.loginRequired, quizController.create);
router.get('/quizes/:quizId(\\d+)/edit', sessionController.loginRequired, quizController.edit);
router.put('/quizes/:quizId(\\d+)', sessionController.loginRequired, quizController.update);
router.delete('/quizes/:quizId(\\d+)', sessionController.loginRequired, quizController.borrar);
// Rutas de comentarios
router.get('/quizes/:quizId(\\d+)/comments/new', commentController.new);
router.post('/quizes/:quizId(\\d+)/comments', commentController.create);
router.get('/quizes/:quizId(\\d+)/comments/:commentId(\\d+)/publish', sessionController.loginRequired, commentController.publish);

module.exports = router;


text:
/***************************************************************************//**
* \file cyhal_system.c
*
* \brief
* Provides a high level interface for interacting with the Infineon power
* management and system clock configuration. This interface abstracts out the
* chip specific details. If any chip specific functionality is necessary, or
* performance is critical the low level functions can be used directly.
*
********************************************************************************
* \copyright
* Copyright 2018-2021 Cypress Semiconductor Corporation (an Infineon company) or
* an affiliate of Cypress Semiconductor Corporation
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/

#include "cyhal_system.h"

#if (defined(COMPONENT_CAT1A) || defined(COMPONENT_CAT1B) || defined(COMPONENT_CAT1C) || defined(COMPONENT_CAT1D))
#include "cy_syslib.h"
#endif

#if defined(CY_RTOS_AWARE) || defined(COMPONENT_RTOS_AWARE)
#include "cyabs_rtos.h"
#endif

#if (CYHAL_DRIVER_AVAILABLE_SYSTEM)

#if defined(__cplusplus)
extern "C"
{
#endif

#define _CYHAL_SYSTEM_HZ_PER_MHZ 1000000

#if (defined(COMPONENT_CAT1A) || defined(COMPONENT_CAT1B) || defined(COMPONENT_CAT1C) || defined(COMPONENT_CAT1D)) &&\
    !defined(CYHAL_DISABLE_WEAK_FUNC_IMPL)
/* Overrides weak implemenation for Cy_SysLib_Rtos_Delay to provide a way
* to call into a RTOS if so configured. This function is only available
* in mtb-pdl-cat1 version 2.2.0 or later.
*/
void Cy_SysLib_Rtos_Delay(uint32_t milliseconds)
{
    cy_rslt_t result = cyhal_system_delay_ms(milliseconds);
    CY_ASSERT(CY_RSLT_SUCCESS == result);
    CY_UNUSED_PARAMETER(result);
}
#endif

cy_rslt_t cyhal_system_delay_ms(uint32_t milliseconds)
{
#if defined(CY_RTOS_AWARE) || defined(COMPONENT_RTOS_AWARE)
    // The RTOS is configured to round down, while this API is intended to wait at least the
    // requested time. Add 1 to the requested time to make it behave the same.
    return cy_rtos_delay_milliseconds(milliseconds + 1);
#else
    Cy_SysLib_Delay(milliseconds);
    return CY_RSLT_SUCCESS;
#endif
}

cyhal_reset_reason_t cyhal_system_get_reset_reason(void)
{
    uint32_t pdl_reason = Cy_SysLib_GetResetReason();
    cyhal_reset_reason_t reason = CYHAL_SYSTEM_RESET_NONE;

    if (CY_SYSLIB_RESET_SOFT & pdl_reason)
        reason |= CYHAL_SYSTEM_RESET_SOFT;
    if (CY_SYSLIB_RESET_HWWDT & pdl_reason)
        reason |= CYHAL_SYSTEM_RESET_WDT;
#if defined(CY_IP_S8SRSSLT)
    if (CY_SYSLIB_PROT_FAULT & pdl_reason)
        reason |= CYHAL_SYSTEM_RESET_PROTECTION;
#endif
#if defined(CY_IP_MXS40SRSS) || defined(CY_IP_MXS40SSRSS) || defined(CY_IP_MXS22SSRSS)
    if (CY_SYSLIB_RESET_ACT_FAULT & pdl_reason)
        reason |= CYHAL_SYSTEM_RESET_ACTIVE_FAULT;
    if (CY_SYSLIB_RESET_DPSLP_FAULT & pdl_reason)
        reason |= CYHAL_SYSTEM_RESET_DEEPSLEEP_FAULT;
    if (CY_SYSLIB_RESET_HIB_WAKEUP & pdl_reason)
        reason |= CYHAL_SYSTEM_RESET_HIB_WAKEUP;
    if (CY_SYSLIB_RESET_CSV_LOSS_WAKEUP & pdl_reason)
        reason |= CYHAL_SYSTEM_RESET_SYS_CLK_ERR;
    if (CY_SYSLIB_RESET_CSV_ERROR_WAKEUP & pdl_reason)
        reason |= CYHAL_SYSTEM_RESET_SYS_CLK_ERR;
    if ((CY_SYSLIB_RESET_SWWDT0 | CY_SYSLIB_RESET_SWWDT1 | CY_SYSLIB_RESET_SWWDT2 | CY_SYSLIB_RESET_SWWDT3) & pdl_reason)
        reason |= CYHAL_SYSTEM_RESET_WDT;
#endif
#if (SRSS_WCOCSV_PRESENT != 0U)
    if (CY_SYSLIB_RESET_CSV_WCO_LOSS & pdl_reason)
        reason |= CYHAL_SYSTEM_RESET_WCO_ERR;
#endif
#if (SRSS_MASK_HFCSV != 0U)
    if ((CY_SYSLIB_RESET_HFCLK_LOSS | CY_SYSLIB_RESET_HFCLK_ERR) & pdl_reason)
        reason |= CYHAL_SYSTEM_RESET_SYS_CLK_ERR;
#endif
    return reason;
}

cy_rslt_t cyhal_system_set_isr(int32_t irq_num, int32_t irq_src, uint8_t priority, cyhal_irq_handler handler)
{
    CY_UNUSED_PARAMETER(irq_src); // Not used by most configurations as there is a 1:1 mapping from irq_src to irq_num
    cy_stc_sysint_t cfg =
    {
#if defined (CY_IP_M7CPUSS)
        .intrSrc = (uint32_t)irq_src | ((uint32_t)irq_num << 16),
#else
        .intrSrc = (IRQn_Type)irq_num,
#endif
        .intrPriority = priority,
#if (CY_CPU_CORTEX_M0P) && defined (CY_IP_M4CPUSS)
        .cm0pSrc = (cy_en_intr_t)irq_src,
#endif
    };
    return Cy_SysInt_Init(&cfg, (cy_israddress)handler);
}

#if defined(__cplusplus)
}
#endif

#endif /* CYHAL_DRIVER_AVAILABLE_SYSTEM */


text:
package com.intellij.formatting;

import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import javax.annotation.Nonnull;

/**
 * Defines the formatting model for a file. A formatting model defines how a file is broken
 * into non-whitespace blocks and different types of whitespace (alignment, indents and wraps)
 * between them.
 * <p>
 * Typically, a plugin does not need to provide a complete FormattingModel implementation -
 * it can either use a complete implementation provided by
 * {@link FormattingModelProvider#createFormattingModelForPsiFile(com.intellij.psi.PsiFile, Block, com.intellij.psi.codeStyle.CodeStyleSettings)}
 * or implement the necessary extra features and delegate the rest to the factory implementation.
 *
 * @see FormattingModelBuilder#createModel(com.intellij.psi.PsiElement, com.intellij.psi.codeStyle.CodeStyleSettings)
 * @see FormattingModelProvider#createFormattingModelForPsiFile(com.intellij.psi.PsiFile, Block, com.intellij.psi.codeStyle.CodeStyleSettings)
 */

public interface FormattingModel {
  /**
   * Returns the root block of the formatting model. The root block corresponds to the
   * top-level element passed to
   * {@link FormattingModelBuilder#createModel(com.intellij.psi.PsiElement, com.intellij.psi.codeStyle.CodeStyleSettings)}.
   *
   * @return the root block of the model.
   */
  @Nonnull
  Block getRootBlock();

  /**
   * Returns the formatting document model, which allows the formatter to access information about
   * the document containing the text to be formatted.
   *
   * @return the formatting document model.
   */
  @Nonnull
  FormattingDocumentModel getDocumentModel();

  /**
   * Replaces the contents of the specified text range in the document with the specified text
   * string consisting of whitespace characters. If necessary, other characters may be inserted
   * in addition to the passed whitespace (for example, \ characters for breaking lines in
   * languages like Python).
   *
   * @param textRange  the text range to replace with whitespace.
   * @param whiteSpace the whitespace to replace with.
   * @return new white space text range
   */
  TextRange replaceWhiteSpace(TextRange textRange, String whiteSpace);

  /**
   * Indents every line except for the first in the specified text range representing a multiline block
   * by the specified amount.
   *
   *
   * @param node the owner of the text range, if defined.
   * @param range  the text range to indent.
   * @param indent the amount by which every line should be indented.
   * @return the text range covering the block with added indents.
   */
  TextRange shiftIndentInsideRange(ASTNode node, TextRange range, int indent);

  /**
   * Commits the changes made by the formatter to the document. Called after the formatter
   * has finished making all changes in a formatting operation.
   */
  void commitChanges();
}


text:
% A filter to select a virtual channel from a DSP scope

% Author/Date : Blake Johnson and Colm Ryan / August 29, 2014

% Copyright 2014 Raytheon BBN Technologies
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
%     http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
classdef StreamSelector < MeasFilters.MeasFilter

    properties
        stream=struct()
        saveRecords
        fileHandleReal
        fileHandleImag
        headerWritten = false;
        streamMode
    end
    properties(Constant)
        DIGITZER_STREAM = 0;
        AVERAGER_STREAM = 1;
    end

    methods
        function obj = StreamSelector(label, settings)
            obj = obj@MeasFilters.MeasFilter(label, settings);

            % stream property is a list of stream tuples of the form: (a,b,c), (u,v,w), ...
            tokens = regexp(settings.stream, '(\([\d\w,]+\))', 'tokens');
            for ct = 1:length(tokens)
                % convert round brackets to square brackets so that it becomes a vector
                streamVec = eval(strrep(strrep(tokens{ct}{1}, '(', '['), ')', ']'));
                if ct==1
                    obj.stream = struct('a', streamVec(1), 'b', streamVec(2), 'c', streamVec(3));
                else
                    obj.stream(ct) = struct('a', streamVec(1), 'b', streamVec(2), 'c', streamVec(3));
                end
            end

            obj.saveRecords = settings.saveRecords;
            if obj.saveRecords
                obj.fileHandleReal = fopen([settings.recordsFilePath, '.real'], 'wb');
                obj.fileHandleImag = fopen([settings.recordsFilePath, '.imag'], 'wb');
            end
            obj.streamMode = obj.DIGITZER_STREAM;
        end

        function delete(obj)
            if obj.saveRecords
                fclose(obj.fileHandleReal);
                fclose(obj.fileHandleImag);
            end
        end

        function apply(obj, src, ~)

            %Pull the raw stream from the digitizer
            obj.latestData = src.transfer_stream(obj.stream);
            if strcmp(src.digitizerMode, 'AVERAGER')
                % in averager mode, the variance is calculated by the driver
                obj.accumulatedVar = src.transfer_stream_variance(obj.stream);
                obj.streamMode = obj.AVERAGER_STREAM;
                obj.avgct = 1;
            end

            %If we have a file to save to then do so
            if obj.saveRecords
                if ~obj.headerWritten
                    %Write the first three dimensions of the signal:
                    %recordLength, numWaveforms, numSegments
                    sizes = size(obj.latestData);
                    if length(sizes) == 2
                        sizes = [sizes(1), 1, sizes(2)];
                    end
                    fwrite(obj.fileHandleReal, sizes(1:3), 'int32');
                    fwrite(obj.fileHandleImag, sizes(1:3), 'int32');
                    obj.headerWritten = true;
                end

                fwrite(obj.fileHandleReal, real(obj.latestData), 'single');
                fwrite(obj.fileHandleImag, imag(obj.latestData), 'single');
            end

            if obj.streamMode == obj.AVERAGER_STREAM
                %Data accumulated in driver
                obj.accumulatedData = obj.latestData;
            else
                accumulate(obj);
            end
            notify(obj, 'DataReady');
        end

        function out = get_var(obj)
            if obj.streamMode == obj.AVERAGER_STREAM
                out = struct();
                out.realvar = obj.accumulatedVar.real;
                out.imagvar = obj.accumulatedVar.imag;
                out.prodvar = obj.accumulatedVar.prod;
            else
                out = get_var@MeasFilters.MeasFilter(obj);
            end
        end
    end
end


text:
from __future__ import unicode_literals
from django.contrib.sites.managers import CurrentSiteManager
from django.contrib.sites.models import Site
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from parler.managers import TranslatableManager, TranslatableQuerySet
from parler.models import TranslatableModel, TranslatedFields
from polymorphic import PolymorphicManager
from polymorphic import PolymorphicModel
from polymorphic.query import PolymorphicQuerySet

class SettingQuerySet(TranslatableQuerySet, PolymorphicQuerySet):
    pass

class SettingManager(PolymorphicManager, TranslatableManager):
    queryset_class = SettingQuerySet

    def current_site(self):
        return

@python_2_unicode_compatible
class Key(models.Model):
    name = models.CharField(_('name'), max_length=140, unique=True, db_index=True)
    description = models.TextField(_('description'), blank=True, null=True)
    allow_multiples = models.BooleanField(_('allow multiples per site?'), default=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = _('key')
        verbose_name_plural = _('keys')
        ordering = ('name', )

@python_2_unicode_compatible
class Setting(PolymorphicModel, TranslatableModel):
    """
    A setting for a site
    """

    site = models.ForeignKey(Site)
    key = models.ForeignKey(Key, error_messages={
        'too_many_for_key': _("The %(key_name)s only allows a single value per site."),
    })
    weight = models.IntegerField(_('weight'), default=0)

    objects = SettingManager()
    on_site = CurrentSiteManager()

    def __str__(self):
        return '{} {}'.format(self.site.name, self.key.name)

    def site_name(self):
        return self.site.name
    site_name.short_description = _('site')
    site_name.admin_order_field = 'site__name'

    def clean(self, *args, **kwargs):
        super(Setting, self).clean(*args, **kwargs)

        if self.key.allow_multiples:
            return

        errors = {}

        settings_count = Setting.objects.filter(site=self.site, key=self.key).exclude(pk=self.pk).count()

        if settings_count > 0:
            err = ValidationError(
                message=self.key.field.error_messages['too_many_for_key'],
                code='too_many_for_key',
                params={
                    'key_name': self.key.name,
                },
            )
            errors.setdefault('key', []).append(err)

        if errors:
            raise ValidationError(errors)

    class Meta:
        verbose_name = _('Site setting')
        verbose_name_plural = _('Site settings')
        ordering = ('site', 'key', '-weight', )
        index_together = ['site', 'key']

class CharSetting(Setting):
    translations = TranslatedFields(
        value = models.CharField(_('value'), max_length=140)
    )

    class Meta:
        verbose_name = _('short text')
        verbose_name_plural = _('short text')

class DateTimeSetting(Setting):
    value = models.DateTimeField(_('value'))
    translations = TranslatedFields()

    class Meta:
        verbose_name = _('date and time')
        verbose_name_plural = _('date and time')

class DateSetting(Setting):
    value = models.DateField(_('value'))
    translations = TranslatedFields()

    class Meta:
        verbose_name = _('date')
        verbose_name_plural = _('date')

class TimeSetting(Setting):
    value = models.TimeField(_('value'))
    translations = TranslatedFields()

    class Meta:
        verbose_name = _('time')
        verbose_name_plural = _('time')

class BooleanSetting(Setting):
    value = models.BooleanField(_('value'), default=True)
    translations = TranslatedFields()

    class Meta:
        verbose_name = _('boolean')
        verbose_name_plural = _('boolean')

class NumberSetting(Setting):
    value = models.IntegerField(_('value'))
    translations = TranslatedFields()

    class Meta:
        verbose_name = _('number')
        verbose_name_plural = _('number')

class DecimalSetting(Setting):
    value = models.DecimalField(_('value'), decimal_places=4, max_digits=9)
    translations = TranslatedFields()

    class Meta:
        verbose_name = _('decimal')
        verbose_name_plural = _('decimal')

class TextSetting(Setting):
    translations = TranslatedFields(
        value = models.TextField(_('value'))
    )

    class Meta:
        verbose_name = _('text')
        verbose_name_plural = _('text')

class EmailSetting(Setting):
    value = models.EmailField(_('value'), max_length=254)
    translations = TranslatedFields()

    class Meta:
        verbose_name = _('email')
        verbose_name_plural = _('email')

class SlugSetting(Setting):
    translations = TranslatedFields(
        value = models.SlugField(_('value'), max_length=140)
    )

    class Meta:
        verbose_name = _('slug')
        verbose_name_plural = _('slug')

class URLSetting(Setting):
    translations = TranslatedFields(
        value = models.URLField(_('value'), max_length=2048)
    )

    class Meta:
        verbose_name = _('URL')
        verbose_name_plural = _('URL')


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.fcrepo</groupId>
    <artifactId>fcrepo</artifactId>
    <version>6.0.0-SNAPSHOT</version>
  </parent>
  <artifactId>fcrepo-auth-webac</artifactId>
  <name>Fedora Repository WebAC Authorization Module</name>
  <description>
    An authorization module for the Fedora Commons Repository framework, implementing the
    RDF-based WebAccessControl authorization mechanism, as proposed by the W3C. This makes
    it possible to define fine-grained repository access controls on individual resources or
    classes of resources to specific users and/or groups.
  </description>
  <packaging>bundle</packaging>

  <properties>
    <!-- OSGi -->
    <osgi.import.packages>
      *
    </osgi.import.packages>
    <osgi.export.packages>
      org.fcrepo.auth.webac;version=${project.version}
    </osgi.export.packages>
    <shiro.version>1.4.0</shiro.version>
  </properties>

  <repositories>
    <repository>
      <id>snapshots-repo</id>
      <url>http://oss.sonatype.org/content/repositories/snapshots</url>
      <releases>
        <enabled>false</enabled>
      </releases>
      <snapshots>
        <enabled>true</enabled>
      </snapshots>
    </repository>
  </repositories>

  <dependencies>

    <dependency>
      <groupId>org.fcrepo</groupId>
      <artifactId>fcrepo-auth-common</artifactId>
      <version>6.0.0-SNAPSHOT</version>
    </dependency>

    <dependency>
      <groupId>org.fcrepo</groupId>
      <artifactId>fcrepo-kernel-api</artifactId>
      <version>6.0.0-SNAPSHOT</version>
    </dependency>

    <dependency>
      <groupId>org.apache.jena</groupId>
      <artifactId>jena-core</artifactId>
    </dependency>

    <dependency>
      <groupId>org.apache.jena</groupId>
      <artifactId>jena-arq</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
    </dependency>

    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
    </dependency>

    <!-- test gear -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>com.github.stefanbirkner</groupId>
      <artifactId>system-rules</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.glassfish.grizzly</groupId>
      <artifactId>grizzly-http-server</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.glassfish.grizzly</groupId>
      <artifactId>grizzly-http-servlet</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.glassfish.jersey.test-framework.providers</groupId>
      <artifactId>jersey-test-framework-provider-grizzly2</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.glassfish.jersey.ext</groupId>
      <artifactId>jersey-spring5</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.glassfish.jersey.core</groupId>
      <artifactId>jersey-common</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpcore</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.fcrepo</groupId>
      <artifactId>fcrepo-configs</artifactId>
      <version>6.0.0-SNAPSHOT</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.fcrepo</groupId>
      <artifactId>fcrepo-http-commons</artifactId>
      <version>6.0.0-SNAPSHOT</version>
      <scope>test</scope>
      <type>test-jar</type>
    </dependency>

    <dependency>
      <groupId>org.fcrepo</groupId>
      <artifactId>fcrepo-http-api</artifactId>
      <version>6.0.0-SNAPSHOT</version>
    </dependency>

    <dependency>
      <groupId>org.fcrepo</groupId>
      <artifactId>fcrepo-http-api</artifactId>
      <version>6.0.0-SNAPSHOT</version>
      <scope>test</scope>
      <type>test-jar</type>
    </dependency>

	<dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-core</artifactId>
      <version>${shiro.version}</version>
      <exclusions>
        <exclusion>
          <groupId>commons-collections</groupId>
		  <artifactId>commons-collections</artifactId>
		</exclusion>
	  </exclusions>
	</dependency>

		<dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-spring</artifactId>
      <version>${shiro.version}</version>
	</dependency>
  </dependencies>

  <build>

    <plugins>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
      </plugin>

      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
      </plugin>

      <plugin>
        <groupId>com.github.github</groupId>
        <artifactId>site-maven-plugin</artifactId>
      </plugin>

      <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
      </plugin>

      <plugin>
        <groupId>com.mycila</groupId>
        <artifactId>license-maven-plugin</artifactId>
      </plugin>

      <plugin>
        <artifactId>maven-failsafe-plugin</artifactId>
      </plugin>

    </plugins>
  </build>

</project>


text:
package io.leopard.schema;

import org.junit.Test;
import org.mockito.Mockito;
import org.w3c.dom.Element;

public class MemcacheBeanDefinitionParserTest {

	protected MemcacheBeanDefinitionParser befinitionParser = new MemcacheBeanDefinitionParser();

	protected Element element = Mockito.mock(Element.class);

	@Test
	public void createRedisImpl() {
		// AUTO
	}

	// @Test
	// public void doParse() {
	// {
	// Mockito.doReturn("server:11211").when(this.element).getAttribute("server");
	// BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition();
	// befinitionParser.doParse(element, builder);
	// Assert.assertEquals("server:11211", (String) builder.getBeanDefinition().getPropertyValues().getPropertyValue("server").getValue());
	// }
	// {
	// Mockito.doReturn(null).when(this.element).getAttribute("server");
	// // Mockito.doReturn("15").when(this.element).getAttribute("maxPoolSize");
	// BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition();
	// befinitionParser.doParse(element, builder);
	// Assert.assertNull(builder.getBeanDefinition().getPropertyValues().getPropertyValue("server"));
	// }
	// }
	//
	// @Test
	// public void doParse2() {
	//
	// Mockito.doReturn("server:11211").when(this.element).getAttribute("server");
	// Mockito.doReturn("memcached").when(this.element).getAttribute("type");
	// Mockito.doReturn("true").when(this.element).getAttribute("sanitizeKeys");
	// Mockito.doReturn("40").when(this.element).getAttribute("maxConn");
	// BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition();
	// befinitionParser.doParse(element, builder);
	// Assert.assertEquals("server:11211", (String) builder.getBeanDefinition().getPropertyValues().getPropertyValue("server").getValue());
	// Assert.assertEquals("true", (String) builder.getBeanDefinition().getPropertyValues().getPropertyValue("sanitizeKeys").getValue());
	// Assert.assertEquals("40", (String) builder.getBeanDefinition().getPropertyValues().getPropertyValue("maxConn").getValue());
	//
	// }
	//
	// @Test
	// public void doParse3() {
	//
	// Mockito.doReturn("server:11211").when(this.element).getAttribute("server");
	// Mockito.doReturn("memcached").when(this.element).getAttribute("type");
	// Mockito.doReturn(null).when(this.element).getAttribute("sanitizeKeys");
	// Mockito.doReturn(null).when(this.element).getAttribute("maxConn");
	// BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition();
	// befinitionParser.doParse(element, builder);
	// Assert.assertEquals("server:11211", (String) builder.getBeanDefinition().getPropertyValues().getPropertyValue("server").getValue());
	// Assert.assertNull(builder.getBeanDefinition().getPropertyValues().getPropertyValue("sanitizeKeys"));
	// Assert.assertNull(builder.getBeanDefinition().getPropertyValues().getPropertyValue("maxConn"));
	//
	// }
}


text:
/** \page dep-eigen3 External dependency: eigen3
 *

 Back to list of dependencies

Dependency: eigen3

MRPT crucially relies on Eigen3, so this dependency is mandatory. Still, for convenience of users, if Eigen3 is not present
in the system MRPT's CMake build system will automatically switch to an embedded version of this library.

Read more about the integration of MRPT and Eigen3 in http://www.mrpt.org/Matrices_vectors_arrays_and_Linear_Algebra_MRPT_and_Eigen_classes

*/


text:
title: Periodic Table of Office 365
link: https://app.jumpto365.com
byline: Matt Wade (@thatmattwade) & Niels Gregers Johansen (@niegrejoh)
imageurl: https://cdn-images-1.medium.com/max/800/1*RD-XvOqoRKoLkJtVl1jJmw.png
imagecopyright: (C) 2018 jumpto365.com
inshort: Which tool to use when in Office 365
icon: https://jumpto365.com/resources/images/app/jumpto365-Icon-white.png
color: #2a7ab9
layout: service
contexts: 35tiles,microsoft365,dynamics365
previewer: pto
self: context
selfdescriptor: office365
---


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IdleLandsGUI.Model
{
    public class EventInfo
    {
        public string createdAt { get; set; }
        public string player { get; set; }
        public string message { get; set; }
        public string type { get; set; }
        public string extra { get; set; }
        public string _id { get; set; }
    }
}


text:
@font-face {
  font-family: 'TradeGothicLTStd-Light';
  src: url('TradeGothicLTStd-Light.eot');
  src: url('TradeGothicLTStd-Light.eot?#iefix') format('embedded-opentype'),
       url('TradeGothicLTStd-Light.woff2') format('woff2'),
       url('TradeGothicLTStd-Light.woff') format('woff'),
       url('TradeGothicLTStd-Light.ttf') format('truetype'),
       url('TradeGothicLTStd-Light.svg#TradeGothicLTStd-Light') format('svg');
  font-weight: normal;
  font-style: normal;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;

namespace Google.Api.Gax.Grpc.Tests
{
    public class RoutingHeaderExtractorTest
    {
        /// <summary>
        /// Extracting a field from the request to put into the routing header,
        /// while matching a path template syntax on the field's value.
        /// </summary>
        [Theory]
        [InlineData("projects/100/instances/200", "table_name=projects%2F100%2Finstances%2F200")]
        [InlineData("projects/100/instances/200/whatever", "table_name=projects%2F100%2Finstances%2F200%2Fwhatever")]
        [InlineData("regions/100/zones/200", "table_name=regions%2F100%2Fzones%2F200")]
        [InlineData("foo", null)]
        public void WithExtractedGoogleRequestParam_FieldMatch(string fieldValue, string expectedHeader)
        {
            // call corresponding to the following routing parameters:
            // { field: "table_name", path_template: "{table_name=projects/*/instances/*/**}" }
            // { field: "table_name", path_template: "{table_name=regions/*/zones/*/**}" }
            var extractor = new RoutingHeaderExtractor<ExtractedRequestParamRequest>()
                .WithExtractedParameter("table_name",
                    "^(projects/[^/]+/instances/[^/]+(?:/.*)?)$", request => request.TableName)
                .WithExtractedParameter("table_name",
                    "^(regions/[^/]+/zones/[^/]+(?:/.*)?)$", request => request.TableName);

            var header = extractor.ExtractHeader(new ExtractedRequestParamRequest { TableName = fieldValue });
            Assert.Equal(expectedHeader, header);
        }

        /// <summary>
        /// Extracting a single routing header key-value pair by matching a
        /// template syntax on (a part of) a single request field.
        /// </summary>
        [Theory]
        [InlineData("projects/100", "routing_id=projects%2F100")]
        [InlineData("projects/100/instances/200", "routing_id=projects%2F100")]
        [InlineData("foo/10/projects/100", null)]
        [InlineData("foo", null)]
        public void WithExtractedGoogleRequestParam_SimpleExtract(string fieldValue, string expectedHeader)
        {
            // call corresponding to the following routing parameters:
            // { field: "table_name", path_template: "{routing_id=projects/*}/**" }
            var extractor = new RoutingHeaderExtractor<ExtractedRequestParamRequest>().WithExtractedParameter("routing_id",
                "^(projects/[^/]+)(?:/.*)?$", request => request.TableName);
            var header = extractor.ExtractHeader(new ExtractedRequestParamRequest { TableName = fieldValue });

            Assert.Equal(expectedHeader, header);
        }

        /// <summary>
        /// Extracting a single routing header key-value pair by matching
        /// several conflictingly named path templates on (parts of) a single request
        /// field. The last template to match "wins" the conflict.
        /// </summary>
        [Theory]
        [InlineData("projects/100", "routing_id=projects%2F100")]
        [InlineData("projects/100/shards/300", "routing_id=projects%2F100")]
        [InlineData("projects/100/instances/200", "routing_id=projects%2F100%2Finstances%2F200")]
        [InlineData("projects/100/instances/200/shards/300", "routing_id=projects%2F100%2Finstances%2F200")]
        [InlineData("orgs/1/projects/100/instances/200", null)]
        [InlineData("foo", null)]
        public void WithExtractedGoogleRequestParam_OverlappingPatterns(string fieldValue, string expectedHeader)
        {
            // call corresponding to the following routing parameters:
            // { field: "table_name", path_template: "{routing_id=projects/*}/**" }
            // { field: "table_name", path_template: "{routing_id=projects/*/instances/*}/**" }
            var extractor = new RoutingHeaderExtractor<ExtractedRequestParamRequest>()
                .WithExtractedParameter("routing_id",
                    "^(projects/[^/]+)(?:/.*)?$", request => request.TableName)
                .WithExtractedParameter("routing_id",
                    "^(projects/[^/]+/instances/[^/]+)(?:/.*)?$", request => request.TableName);
            var header = extractor.ExtractHeader(new ExtractedRequestParamRequest { TableName = fieldValue });

            Assert.Equal(expectedHeader, header);
        }

        /// <summary>
        /// Extracting multiple routing header key-value pairs by matching
        /// several non-conflicting path templates on (parts of) a single request field.
        /// Make the templates strict, so that if the `table_name` does not
        /// have an instance information, nothing is sent.
        /// </summary>
        [Theory]
        [InlineData("projects/100/instances/200/tables/300", "project_id=projects%2F100&instance_id=instances%2F200")]
        [InlineData("projects/100", null)]
        public void WithExtractedGoogleRequestParam_MultiplePairs(string fieldValue, string expectedHeader)
        {
            // call corresponding to the following routing parameters:
            // { field: "table_name", path_template: "{project_id=projects/*}/instances/*/**" }
            // { field: "table_name", path_template: "projects/*/{instance_id=instances/*}/**" }
            var extractor = new RoutingHeaderExtractor<ExtractedRequestParamRequest>()
                .WithExtractedParameter("project_id",
                    "^(projects/[^/]+)/instances/[^/]+(?:/.*)?$", request => request.TableName)
                .WithExtractedParameter("instance_id",
                    "^projects/[^/]+/(instances/[^/]+)(?:/.*)?$", request => request.TableName);
            var header = extractor.ExtractHeader(new ExtractedRequestParamRequest { TableName = fieldValue });

            Assert.Equal(expectedHeader, header);
        }

        /// <summary>
        /// Extracting multiple routing header key-value pairs by matching
        /// several non-conflicting path templates on (parts of) a single request field.
        /// Make the templates loose, so that if the `table_name` does not
        /// have an instance information, just the project id part is sent.
        /// </summary>
        [Theory]
        [InlineData("projects/100/instances/200/tables/300", "project_id=projects%2F100&instance_id=instances%2F200")]
        [InlineData("projects/100", "project_id=projects%2F100")]
        [InlineData("org/projects/100", null)]
        public void WithExtractedGoogleRequestParam_MultiplePairsLoose(string fieldValue, string expectedHeader)
        {
            // call corresponding to the following routing parameters:
            // { field: "table_name", path_template: "{project_id=projects/*}/**" }
            // { field: "table_name", path_template: "projects/*/{instance_id=instances/*}/**" }
            var extractor = new RoutingHeaderExtractor<ExtractedRequestParamRequest>().WithExtractedParameter("project_id",
                    "^(projects/[^/]+)(?:/.*)?$", request => request.TableName)
                .WithExtractedParameter("instance_id",
                    "^projects/[^/]+/(instances/[^/]+)(?:/.*)?$", request => request.TableName);
            var header = extractor.ExtractHeader(new ExtractedRequestParamRequest { TableName = fieldValue });

            Assert.Equal(expectedHeader, header);
        }

        /// <summary>
        /// Extracting multiple routing header key-value pairs by matching
        /// several path templates on multiple request fields.
        /// Also tests the parameter names with the `.` and extracting values from a sub-request's field.
        /// </summary>
        [Theory]
        [InlineData("projects/100/instances/200/tables/300", "profiles/profile_17", "subs/sub13", "project_id=projects%2F100&sub_name=sub13&legacy.routing_id=profiles%2Fprofile_17")]
        [InlineData("projects/100", "", "", "project_id=projects%2F100")]
        [InlineData("projects/100", null, null, "project_id=projects%2F100")]
        [InlineData(null, null, null, null)]
        public void WithExtractedGoogleRequestParam_MultipleFields(string tableNameValue, string appProfileIdValue, string subName, string expectedHeader)
        {
            // call corresponding to the following routing parameters:
            // { field: "table_name", path_template: "{project_id=projects/*}/**" }
            // { field: "sub_name", path_template: "subs/{sub.sub_name}" }
            // { field: "app_profile_id", path_template: "{legacy.routing_id=**}" }
            var extractor = new RoutingHeaderExtractor<ExtractedRequestParamRequest>()
                .WithExtractedParameter("project_id",
                    "^(projects/[^/]+)(?:/.*)?$", request => request.TableName)
                .WithExtractedParameter("sub_name",
                    "^subs/([^/]+)/?$", request => request.Sub.TableName)
                .WithExtractedParameter("legacy.routing_id",
                    "^(.*)$", request => request.AppProfileId);
            var header = extractor.ExtractHeader(new ExtractedRequestParamRequest
            {
                TableName = tableNameValue,
                AppProfileId = appProfileIdValue,
                Sub = new ExtractedRequestParamRequest { TableName = subName }
            });

            Assert.Equal(expectedHeader, header);
        }

        /// <summary>
        /// Extracting multiple routing header key-value pairs by matching
        /// several conflictingly named path templates on several request fields. The
        /// last template to match "wins" the conflict.
        /// </summary>
        [Theory]
        [InlineData("projects/100/instances/200/tables/300", "profiles/profile_17", "routing_id=profiles%2Fprofile_17")]
        [InlineData("regions/100", "", "routing_id=regions%2F100")]
        public void WithExtractedGoogleRequestParam_MultipleConflictsFields(string tableNameValue, string appProfileIdValue, string expectedHeader)
        {
            // call corresponding to the following routing parameters:
            // { field: "table_name", path_template: "{routing_id=projects/*}/**" }
            // { field: "table_name", path_template: "{routing_id=regions/*}/**" }
            // { field: "app_profile_id", path_template: "{routing_id=**}" }
            var extractor = new RoutingHeaderExtractor<ExtractedRequestParamRequest>()
                .WithExtractedParameter("routing_id",
                    "^(projects/[^/]+)(?:/.*)?$", request => request.TableName)
                .WithExtractedParameter("routing_id",
                    "^(regions/[^/]+)(?:/.*)?$", request => request.TableName)
                .WithExtractedParameter("routing_id",
                    "^(.*)$", request => request.AppProfileId);
            var header = extractor.ExtractHeader(new ExtractedRequestParamRequest { TableName = tableNameValue, AppProfileId = appProfileIdValue});

            Assert.Equal(expectedHeader, header);
        }

        /// <summary>
        /// Test a complex scenario with a kitchen sink of concerns
        /// </summary>
        [Theory]
        [InlineData("projects/100/instances/200/tables/300", "profiles/profile_17", "table_location=instances%2F200&routing_id=profile_17")]
        [InlineData("projects/100/instances/200/tables/300", "profile_17", "table_location=instances%2F200&routing_id=profile_17")]
        [InlineData("projects/100/instances/200/tables/300", null, "table_location=instances%2F200&routing_id=projects%2F100")]
        public void WithExtractedGoogleRequestParam_KitchenSink(string tableNameValue, string appProfileIdValue, string expectedHeader)
        {
            // call corresponding to the following routing parameters:
            // { field: "table_name", path_template: "projects/*/{table_location=instances/*}/tables/*" }
            // { field: "table_name", path_template: "{table_location=regions/*/zones/*}/tables/*" }
            // { field: "table_name", path_template: "{routing_id=projects/*}/**" }
            // { field: "app_profile_id", path_template: "{routing_id=**}" }
            // { field: "app_profile_id", path_template: "profiles/{routing_id=*}" }
            var extractor = new RoutingHeaderExtractor<ExtractedRequestParamRequest>()
                .WithExtractedParameter("table_location",
                    "^projects/[^/]+/(instances/[^/]+)/tables/[^/]+/?$", request => request.TableName)
                .WithExtractedParameter("table_location",
                    "^(regions/[^/]+/zones/[^/]+)/tables/[^/]+/?$", request => request.TableName)
                .WithExtractedParameter("routing_id",
                    "^(projects/[^/]+)(?:/.*)?$", request => request.TableName)
                .WithExtractedParameter("routing_id",
                    "^(.*)$", request => request.AppProfileId)
                .WithExtractedParameter("routing_id",
                    "^profiles/([^/]+)/?$", request => request.AppProfileId);
            var header = extractor.ExtractHeader(new ExtractedRequestParamRequest { TableName = tableNameValue, AppProfileId = appProfileIdValue});

            Assert.Equal(expectedHeader, header);
        }

        internal class ExtractedRequestParamRequest
        {
            public string TableName { get; set; }
            public string AppProfileId { get; set; }
            public ExtractedRequestParamRequest Sub { get; set; }
        }
    }
}