text:
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Text;
using System.Xml;
using System.Xml.XPath;

namespace Meziantou.Framework.Html;

public abstract class HtmlNode : INotifyPropertyChanged, IXPathNavigable, IXmlNamespaceResolver
{
    private const int MaxRecursion = 300;

    public const string XmlnsPrefix = "xmlns";
    public const string XmlnsNamespaceURI = "http://www.w3.org/2000/xmlns/";

    public const string XmlPrefix = "xml";
    public const string XmlNamespaceURI = "http://www.w3.org/XML/1998/namespace";

    public const string XhtmlPrefix = "xhtml";
    public const string XhtmlNamespaceURI = "http://www.w3.org/1999/xhtml";
    private Collection<HtmlError> _errors;
    private HtmlNodeList _childNodes;
    private HtmlAttributeList _attributes;
    private HtmlNode _parentNode;
    private HtmlDocument _ownerDocument;
    private string _prefix;
    private string _localName;
    private object _tag;

    // caches
    private string _innerText;
    private string _outerHtml;
    private string _innerHtml;
    private string _outerXml;
    private string _innerXml;

    public event PropertyChangedEventHandler PropertyChanged;

    static HtmlNode()
    {
        NamespaceManager = new XmlNamespaceManager(new NameTable());
        NamespaceManager.AddNamespace(XmlPrefix, XmlNamespaceURI);
        NamespaceManager.AddNamespace(XhtmlPrefix, XhtmlNamespaceURI);
    }

    [SuppressMessage("Design", "CA1054:URI-like parameters should not be strings", Justification = "Breaking change")]
    protected HtmlNode(string prefix, string localName, string namespaceURI, HtmlDocument ownerDocument)
    {
        if (ownerDocument == null && this is not HtmlDocument)
            throw new ArgumentNullException(nameof(ownerDocument));

        _prefix = prefix ?? throw new ArgumentNullException(nameof(prefix));
        _localName = localName ?? throw new ArgumentNullException(nameof(localName));
        DeclaredNamespaceURI = namespaceURI;
        OwnerDocument = ownerDocument;
    }

    public static XmlNamespaceManager NamespaceManager { get; }

    public override string ToString()
    {
        return Name;
    }

    internal static string GetValidXmlName(string name)
    {
        if (string.IsNullOrEmpty(name))
            return name;

        return Utilities.GetValidXmlName(name);
    }

    protected internal virtual void ClearCaches()
    {
        ClearCaches(0);
    }

    private void ClearCaches(int index)
    {
        // deep recursion testing. incurred because of xslt in general
        if (index > MaxRecursion)
            throw new HtmlException($"HTML0005: Maximum recursion depth ({MaxRecursion.ToString(CultureInfo.InvariantCulture)}) exceeded. This may be caused by a recursive XSLT.");

        _innerHtml = null;
        _innerText = null;
        _innerXml = null;
        _outerHtml = null;
        _outerXml = null;

        _parentNode?.ClearCaches(index + 1);
    }

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        if (!RaisePropertyChanged)
            return;

        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        if (!RaisePropertyChanged)
            return;

        PropertyChanged?.Invoke(this, e);
    }

    [SuppressMessage("Design", "CA1056:URI-like properties should not be strings", Justification = "Breaking change")]
    protected string DeclaredNamespaceURI { get; private set; }

    public virtual int ParentIndex
    {
        get
        {
            if (ParentNode?.HasChildNodes == true)
            {
                for (var i = 0; i < ParentNode.ChildNodes.Count; i++)
                {
                    if (ParentNode.ChildNodes[i] == this)
                        return i;
                }
            }
            return -1;
        }
    }

    public virtual IEnumerable<HtmlNode> NextSiblings
    {
        get
        {
            if (ParentNode == null || !ParentNode.HasChildNodes)
                yield break;

            var index = ParentIndex;
            if (index < 0 || (index + 1) >= ParentNode.ChildNodes.Count)
                yield break;

            foreach (var node in ParentNode.ChildNodes.Skip(index + 1))
            {
                yield return node;
            }
        }
    }

    public virtual HtmlNode NextSibling
    {
        get
        {
            if (ParentNode == null || !ParentNode.HasChildNodes)
                return null;

            var index = ParentIndex;
            if (index < 0 || (index + 1) >= ParentNode.ChildNodes.Count)
                return null;

            return ParentNode.ChildNodes[index + 1];
        }
    }

    public virtual IEnumerable<HtmlNode> PreviousSiblings
    {
        get
        {
            if (ParentNode == null || !ParentNode.HasChildNodes)
                yield break;

            var index = ParentIndex;
            if (index <= 0)
                yield break;

            foreach (var node in ParentNode.ChildNodes.Take(index))
            {
                yield return node;
            }
        }
    }

    public virtual HtmlNode PreviousSibling
    {
        get
        {
            if (ParentNode == null || !ParentNode.HasChildNodes)
                return null;

            var index = ParentIndex;
            if (index <= 0)
                return null;

            return ParentNode.ChildNodes[index - 1];
        }
    }

    public virtual HtmlNodeList ChildNodes => _childNodes ??= new HtmlNodeList(this);

    public virtual HtmlAttributeList Attributes => _attributes ??= new HtmlAttributeList(this);

    public virtual bool RaisePropertyChanged { get; set; }
    public virtual int StreamOrder { get; set; }
    public abstract HtmlNodeType NodeType { get; }

    public int Depth => ParentNode != null ? ParentNode.Depth + 1 : 0;

    public string Prefix
    {
        get => _prefix;
        set
        {
            if (value == null)
                throw new ArgumentNullException(nameof(value));

            if (string.Equals(_prefix, value, StringComparison.Ordinal))
                return;

            ClearCaches();
            _prefix = value;
            OnPropertyChanged();
        }
    }

    protected virtual void ParseName(string name, out string prefix, out string localName)
    {
        if (name == null)
        {
            prefix = null;
            localName = null;
            return;
        }

        var pos = name.IndexOf(':', StringComparison.Ordinal);
        if (pos < 0)
        {
            prefix = string.Empty;
            localName = name;
            return;
        }

        prefix = Utilities.Nullify(name[..pos], trim: true);
        localName = Utilities.Nullify(name[(pos + 1)..], trim: true);
        if (prefix == null || localName == null)
        {
            prefix = string.Empty;
            localName = name;
        }
    }

    public virtual void ResetStreamOrder(int newOrder)
    {
        StreamOrder = newOrder;
        if (HasAttributes)
        {
            foreach (var att in Attributes)
            {
                att.ResetStreamOrder(newOrder);
            }
        }

        if (HasChildNodes)
        {
            foreach (var node in ChildNodes)
            {
                node.ResetStreamOrder(newOrder);
            }
        }
    }

    private void SetName(string name)
    {
        if (string.Equals(name, Name, StringComparison.Ordinal))
            return;

        ClearCaches();
        ParseName(name, out var prefix, out var localName);
        Prefix = prefix;
        LocalName = localName;
        OnPropertyChanged(nameof(Name));
    }

    [SuppressMessage("Style", "IDE0016:Use 'throw' expression", Justification = "Change the behavior of the method")]
    public string LocalName
    {
        get => _localName;
        set
        {
            if (value == null)
                throw new ArgumentNullException(nameof(value));

            ClearCaches();
            _localName = value;
            OnPropertyChanged();
        }
    }

    public HtmlDocument OwnerDocument
    {
        get
        {
            if (NodeType == HtmlNodeType.Document)
                return (HtmlDocument)this;

            return _ownerDocument;
        }
        private set => _ownerDocument = value;
    }

    [SuppressMessage("Design", "CA1056:URI-like properties should not be strings", Justification = "Breaking change")]
    public virtual string NamespaceURI
    {
        get => GetNamespaceOfPrefix(Prefix);
        set
        {
            if (value == null)
                throw new ArgumentNullException(nameof(value));

            if (!string.Equals(DeclaredNamespaceURI, value, StringComparison.Ordinal))
            {
                DeclaredNamespaceURI = value;
                OnPropertyChanged();
            }
        }
    }

    public virtual object Tag
    {
        get => _tag;
        set
        {
            if (Equals(_tag, value))
                return;

            _tag = value;
            OnPropertyChanged();
        }
    }

    public virtual string Value
    {
        get => null;
        set
        {
            //throw new InvalidOperationException();
        }
    }

    public virtual string Name
    {
        get
        {
            if (!string.IsNullOrWhiteSpace(Prefix))
                return Prefix + ":" + LocalName;

            return LocalName;
        }
        set
        {
            if (value == null)
                throw new ArgumentNullException(nameof(value));

            SetName(value);
        }
    }

    internal static bool IsHtmlNs(string ns)
    {
        return string.IsNullOrWhiteSpace(ns) || string.Equals(ns, XhtmlNamespaceURI, StringComparison.Ordinal);
    }

    public HtmlNode ParentNode
    {
        get => _parentNode;
        internal set
        {
            if (_parentNode != value)
            {
                if (value == null)
                {
                    // when detached, copy namespaces if it was computed
                    var nss = _parentNode.GetAllNamespaces();
                    foreach (var ns in nss)
                    {
                        if (IsHtmlNs(ns.Value))
                            continue;

                        Attributes.Add(XmlnsPrefix, ns.Key, string.Empty, ns.Value);
                    }
                }
            }

            _parentNode = value;
            _ownerDocument = _parentNode?.OwnerDocument;
        }
    }

    public HtmlElement ParentElement
    {
        get
        {
            for (var node = ParentNode; node != null; node = node.ParentNode)
            {
                if (node is HtmlElement parentElement)
                    return parentElement;
            }

            return null;
        }
    }

    public string Id => GetAttributeValue("id");

    protected internal virtual void AddError(HtmlError error)
    {
        if (error is null)
            throw new ArgumentNullException(nameof(error));

        _errors ??= new Collection<HtmlError>();
        _errors.Add(error);
    }

    protected internal virtual void ClearErrors()
    {
        if (_errors == null)
            return;

        _errors.Clear();
        _errors = null;
    }

    public virtual IEnumerable<HtmlError> Errors => _errors ??= new Collection<HtmlError>();

    public virtual string OuterHtml
    {
        get
        {
            if (_outerHtml == null)
            {
                using var w = new StringWriter(CultureInfo.InvariantCulture);
                WriteTo(w);
                _outerHtml = w.ToString();
            }
            return _outerHtml;
        }
    }

    public virtual string InnerText
    {
        get
        {
            if (_innerText == null)
            {
                var sb = new StringBuilder();
                AppendChildText(sb);
                _innerText = sb.ToString();
            }
            return _innerText;
        }
        set
        {
            if (!string.Equals(value, _innerText, StringComparison.Ordinal))
            {
                ClearCaches();
                var firstChild = FirstChild;
                if (firstChild != null && firstChild.NextSibling == null && firstChild.NodeType == HtmlNodeType.Text)
                {
                    firstChild.Value = value;
                }
                else
                {
                    if (OwnerDocument == null)
                        throw new ArgumentException("The node is not owned by a document", nameof(value));

                    RemoveAll();
                    var text = OwnerDocument.CreateText();
                    text.Value = value;
                    ChildNodes.Add(text);
                }
                OnPropertyChanged();
            }
        }
    }

    private void AppendChildText(StringBuilder builder)
    {
        if (HasChildNodes)
        {
            foreach (var node in ChildNodes)
            {
                if (node.NodeType == HtmlNodeType.Text)
                {
                    builder.Append(node.InnerText);
                }
                else
                {
                    node.AppendChildText(builder);
                }
            }
        }
    }

    public virtual string InnerHtml
    {
        get
        {
            if (_innerHtml == null)
            {
                using var w = new StringWriter(CultureInfo.InvariantCulture);
                WriteContentTo(w);
                _innerHtml = w.ToString();
            }
            return _innerHtml;
        }
        set => throw new InvalidOperationException();
    }

    public virtual string OuterXml
    {
        get
        {
            if (_outerXml == null)
            {
                using var w = new StringWriter(CultureInfo.InvariantCulture);
                using (var writer = XmlWriter.Create(w))
                {
                    WriteTo(writer);
                }
                _outerXml = w.ToString();
            }
            return _outerXml;
        }
    }

    public virtual string InnerXml
    {
        get
        {
            if (_innerXml == null)
            {
                using var w = new StringWriter(CultureInfo.InvariantCulture);
                using (var writer = XmlWriter.Create(w))
                {
                    WriteContentTo(writer);
                }
                _innerXml = w.ToString();
            }
            return _innerXml;
        }
        set => throw new InvalidOperationException();
    }

    public HtmlNode FirstChild
    {
        get
        {
            if (HasChildNodes)
                return ChildNodes[0];

            return null;
        }
    }

    public HtmlNode LastChild
    {
        get
        {
            if (HasChildNodes)
                return ChildNodes[^1];

            return null;
        }
    }

    [SuppressMessage("Design", "CA1054:URI-like parameters should not be strings", Justification = "Breaking change")]
    public HtmlAttribute SetAttribute(string localName, string namespaceURI, string value)
    {
        return SetAttribute(string.Empty, localName, namespaceURI, value);
    }

    [SuppressMessage("Design", "CA1054:URI-like parameters should not be strings", Justification = "Breaking change")]
    public HtmlAttribute SetAttribute(string prefix, string localName, string namespaceURI, string value)
    {
        if (prefix is null)
            throw new ArgumentNullException(nameof(prefix));

        if (localName is null)
            throw new ArgumentNullException(nameof(localName));

        if (namespaceURI is null)
            throw new ArgumentNullException(nameof(namespaceURI));

        var att = Attributes[localName, namespaceURI];
        if (att == null)
        {
            att = Attributes.Add(prefix, localName, namespaceURI, value);
        }
        else
        {
            att.Value = value;
        }
        return att;
    }

    public bool RemoveAttribute(string name)
    {
        if (name is null)
            throw new ArgumentNullException(nameof(name));

        if (_attributes == null)
            return false;

        return Attributes.Remove(name);
    }

    [SuppressMessage("Design", "CA1054:URI-like parameters should not be strings", Justification = "Breaking change")]
    public bool RemoveAttribute(string localName, string namespaceURI)
    {
        if (localName is null)
            throw new ArgumentNullException(nameof(localName));

        if (namespaceURI is null)
            throw new ArgumentNullException(nameof(namespaceURI));

        if (_attributes == null)
            return false;

        return Attributes.Remove(localName, namespaceURI);
    }

    public bool RemoveAttributeByPrefix(string prefix, string localName)
    {
        if (prefix is null)
            throw new ArgumentNullException(nameof(prefix));

        if (localName is null)
            throw new ArgumentNullException(nameof(localName));

        if (_attributes == null)
            return false;

        return Attributes.RemoveByPrefix(prefix, localName);
    }

    public HtmlAttribute SetAttribute(string name, string value)
    {
        if (name is null)
            throw new ArgumentNullException(nameof(name));

        var att = Attributes[name];
        if (att == null)
        {
            att = Attributes.Add(name, value);
        }
        else
        {
            att.Value = value;
        }
        return att;
    }

    public virtual bool HasAttributes => _attributes?.Count > 0;

    public virtual bool HasChildNodes => _childNodes?.Count > 0;

    [SuppressMessage("Design", "CA1054:URI-like parameters should not be strings", Justification = "Breaking change")]
    public bool HasAttribute(string localName, string namespaceURI)
    {
        if (localName is null)
            throw new ArgumentNullException(nameof(localName));

        if (namespaceURI is null)
            throw new ArgumentNullException(nameof(namespaceURI));

        if (_attributes == null)
            return false;

        return Attributes[localName, namespaceURI] != null;
    }

    public bool HasNonNullNorWhitespaceAttribute(string name)
    {
        if (name is null)
            throw new ArgumentNullException(nameof(name));

        return GetNullifiedAttributeValue(name) != null;
    }

    public bool HasAttribute(string name)
    {
        if (name is null)
            throw new ArgumentNullException(nameof(name));

        if (_attributes == null)
            return false;

        return Attributes[name] != null;
    }

    public string GetAttributeValue(string name)
    {
        if (name is null)
            throw new ArgumentNullException(nameof(name));

        if (_attributes == null)
            return null;

        var att = Attributes[name];
        if (att == null)
            return null;

        return att.Value;
    }

    public string GetAttributeValue(string name, string defaultValue)
    {
        if (name is null)
            throw new ArgumentNullException(nameof(name));

        if (_attributes == null)
            return defaultValue;

        var att = Attributes[name];
        if (att == null)
            return defaultValue;

        return att.Value;
    }

    public string GetAttributeValueByPrefix(string prefix, string localName, string defaultValue)
    {
        if (prefix is null)
            throw new ArgumentNullException(nameof(prefix));

        if (localName is null)
            throw new ArgumentNullException(nameof(localName));

        if (_attributes == null)
            return defaultValue;

        var att = Attributes.FirstOrDefault(a => string.Equals(a.Prefix, prefix, StringComparison.Ordinal) && a.LocalName.EqualsIgnoreCase(localName));
        if (att == null)
            return defaultValue;

        return att.Value;
    }

    public string GetNullifiedAttributeValue(string name)
    {
        if (name is null)
            throw new ArgumentNullException(nameof(name));

        if (_attributes == null)
            return null;

        var att = Attributes[name];
        if (att == null)
            return null;

        return Utilities.Nullify(att.Value, trim: true);
    }

    [SuppressMessage("Design", "CA1054:URI-like parameters should not be strings", Justification = "Breaking change")]
    public string GetNullifiedAttributeValue(string localName, string namespaceURI)
    {
        if (localName is null)
            throw new ArgumentNullException(nameof(localName));

        if (namespaceURI is null)
            throw new ArgumentNullException(nameof(namespaceURI));

        if (_attributes == null)
            return null;

        var att = Attributes[localName, namespaceURI];
        if (att == null)
            return null;

        return Utilities.Nullify(att.Value, trim: true);
    }

    [SuppressMessage("Design", "CA1054:URI-like parameters should not be strings", Justification = "Breaking change")]
    public string GetAttributeValue(string localName, string namespaceURI, string defaultValue)
    {
        if (localName is null)
            throw new ArgumentNullException(nameof(localName));

        if (namespaceURI is null)
            throw new ArgumentNullException(nameof(namespaceURI));

        if (_attributes == null)
            return defaultValue;

        var att = Attributes[localName, namespaceURI];
        if (att == null)
            return defaultValue;

        return att.Value;
    }

    public virtual void AppendChild(HtmlNode newChild)
    {
        if (newChild is HtmlAttribute)
            throw new ArgumentException("Cannot append an attribute", nameof(newChild));

        ChildNodes.Add(newChild);
    }

    public virtual void InsertAfter(HtmlNode newChild, HtmlNode refChild)
    {
        if (newChild is null)
            throw new ArgumentNullException(nameof(newChild));

        if (newChild is HtmlAttribute)
            throw new ArgumentException("Cannot insert an attribute", nameof(newChild));

        if (this == newChild || IsAncestor(newChild))
            throw new ArgumentException(message: null, nameof(newChild));

        if (newChild.NodeType == HtmlNodeType.Document)
            throw new ArgumentException(message: null, nameof(newChild));

        if (OwnerDocument == null)
            throw new InvalidOperationException();

        if (refChild == null)
        {
            PrependChild(newChild);
            return;
        }

        if (newChild == refChild)
            return;

        var index = -1;
        if (HasChildNodes)
        {
            for (var i = 0; i < ChildNodes.Count; i++)
            {
                var node = ChildNodes[i];
                if (node == refChild)
                {
                    index = i;
                    break;
                }
            }
        }

        if (index < 0)
            throw new ArgumentException(message: null, nameof(refChild));

        ChildNodes.Insert(index + 1, newChild);
    }

    public bool IsAncestor(HtmlNode node)
    {
        if (node is null)
            throw new ArgumentNullException(nameof(node));

        for (var n = ParentNode; (n != null) && (n != this); n = n.ParentNode)
        {
            if (n == node)
                return true;
        }
        return false;
    }

    public virtual void InsertBefore(HtmlNode newChild, HtmlNode refChild)
    {
        if (newChild is null)
            throw new ArgumentNullException(nameof(newChild));

        if (newChild is HtmlAttribute)
            throw new ArgumentException(message: null, nameof(newChild));

        if (this == newChild || IsAncestor(newChild))
            throw new ArgumentException(message: null, nameof(newChild));

        if (newChild.NodeType == HtmlNodeType.Document)
            throw new ArgumentException(message: null, nameof(newChild));

        if (refChild == null)
        {
            AppendChild(newChild);
            return;
        }

        if (newChild == refChild)
            return;

        var index = -1;
        if (HasChildNodes)
        {
            for (var i = 0; i < ChildNodes.Count; i++)
            {
                var node = ChildNodes[i];
                if (node == refChild)
                {
                    index = i;
                    break;
                }
            }
        }

        if (index < 0)
            throw new ArgumentException(message: null, nameof(refChild));

        ChildNodes.Insert(index, newChild);
    }

    public virtual void PrependChild(HtmlNode newChild)
    {
        if (newChild is HtmlAttribute)
            throw new ArgumentException(message: null, nameof(newChild));

        ChildNodes.Insert(0, newChild);
    }

    public bool Remove()
    {
        return Remove(keepChildren: false);
    }

    public virtual bool Remove(bool keepChildren)
    {
        if (ParentNode != null)
            return ParentNode.RemoveChild(this, keepChildren);

        return false;
    }

    public virtual void RemoveAll()
    {
        if (_childNodes == null)
            return;

        ChildNodes.RemoveAll();
    }

    public bool RemoveChild(HtmlNode oldChild)
    {
        return RemoveChild(oldChild, keepGrandChildren: false);
    }

    public virtual bool RemoveChild(HtmlNode oldChild, bool keepGrandChildren)
    {
        if (oldChild is HtmlAttribute att)
        {
            if (string.IsNullOrWhiteSpace(att.NamespaceURI))
                return RemoveAttribute(att.Name);

            return RemoveAttribute(att.LocalName, att.NamespaceURI);
        }

        if (_childNodes == null)
            return false;

        var index = ChildNodes.IndexOf(oldChild);
        if (index < 0)
            return false;

        if (keepGrandChildren)
        {
            var oldIndex = oldChild.ParentIndex;
            foreach (var child in oldChild.ChildNodes)
            {
                child._parentNode = null;
                ChildNodes.Insert(oldIndex++, child);
            }
            oldChild.ChildNodes.RemoveAllNoCheck();
        }

        return ChildNodes.Remove(oldChild);
    }

    public virtual void ReplaceChild(HtmlNode newChild, HtmlNode oldChild)
    {
        if (newChild is HtmlAttribute)
            throw new ArgumentException(message: "newChild must not be an HtmlAttribute", nameof(newChild));

        if (oldChild is HtmlAttribute)
            throw new ArgumentException(message: "oldChild must not be an HtmlAttribute", nameof(oldChild));

        ChildNodes.Replace(newChild, oldChild);
    }

    public virtual string GetNamespaceOfPrefix(string prefix)
    {
        if (prefix is null)
            throw new ArgumentNullException(nameof(prefix));

        if (prefix.EqualsIgnoreCase(Prefix) && DeclaredNamespaceURI != null)
            return DeclaredNamespaceURI;

        foreach (var att in Attributes)
        {
            if (att.Prefix.EqualsIgnoreCase(XmlnsPrefix) && att.LocalName.EqualsIgnoreCase(prefix))
                return att.Value;
        }

        if (ParentNode != null && ParentNode != this)
            return ParentNode.GetNamespaceOfPrefix(prefix);

        if (OwnerDocument != null && OwnerDocument != this)
            return OwnerDocument.GetNamespaceOfPrefix(prefix);

        return string.Empty;
    }

    [SuppressMessage("Design", "CA1054:URI-like parameters should not be strings", Justification = "Breaking change")]
    public virtual string GetPrefixOfNamespace(string namespaceURI)
    {
        if (namespaceURI is null)
            throw new ArgumentNullException(nameof(namespaceURI));

        if (namespaceURI.EqualsIgnoreCase(NamespaceURI))
            return Prefix;

        foreach (var att in Attributes)
        {
            if (att.Prefix.EqualsIgnoreCase(XmlnsPrefix) && att.Value.EqualsIgnoreCase(namespaceURI))
                return att.LocalName;
        }

        if (ParentNode != null && ParentNode != this)
            return ParentNode.GetPrefixOfNamespace(namespaceURI);

        if (OwnerDocument != null && OwnerDocument != this)
            return OwnerDocument.GetPrefixOfNamespace(namespaceURI);

        return string.Empty;
    }

    public virtual HtmlNode GetParent(Func<HtmlNode, bool> func)
    {
        if (func is null)
            throw new ArgumentNullException(nameof(func));

        if (ParentNode == null)
            return null;

        if (func(ParentNode))
            return ParentNode;

        return ParentNode.GetParent(func);
    }

    public IReadOnlyDictionary<string, string> GetAllNamespaces()
    {
        var namespaces = new Dictionary<string, string>(StringComparer.Ordinal);
        GetNamespaceAttributes(namespaces);
        return namespaces;
    }

    protected virtual void GetNamespaceAttributes(IDictionary<string, string> namespaces)
    {
        if (namespaces is null)
            throw new ArgumentNullException(nameof(namespaces));

        foreach (var att in Attributes)
        {
            if (att.Prefix.EqualsIgnoreCase(XmlnsPrefix))
            {
                namespaces[att.LocalName] = att.Value;
            }
        }

        ParentNode?.GetNamespaceAttributes(namespaces);
    }

    [SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "By design")]
    public Uri BaseAddress => null;

    public abstract void WriteTo(TextWriter writer);
    public abstract void WriteContentTo(TextWriter writer);
    public abstract void WriteTo(XmlWriter writer);
    public abstract void WriteContentTo(XmlWriter writer);

    public HtmlNode Clone()
    {
        return Clone(HtmlCloneOptions.All);
    }

    public HtmlNode Clone(HtmlCloneOptions options)
    {
        var clone = CreateNew();
        CopyTo(clone, options);
        return clone;
    }

    public virtual void CopyTo(HtmlNode target, HtmlCloneOptions options)
    {
        if (target is null)
            throw new ArgumentNullException(nameof(target));

        target.Value = Value;

        if ((options & HtmlCloneOptions.StreamOrder) == HtmlCloneOptions.StreamOrder)
        {
            target.StreamOrder = StreamOrder;
        }

        if (!IsHtmlNs(DeclaredNamespaceURI))
        {
            target.DeclaredNamespaceURI = DeclaredNamespaceURI;
        }
        else
        {
            var ns = NamespaceURI;
            if (!IsHtmlNs(ns))
            {
                target.DeclaredNamespaceURI = ns;
            }
        }

        if ((options & HtmlCloneOptions.Attributes) == HtmlCloneOptions.Attributes)
        {
            foreach (var att in Attributes)
            {
#if DEBUG_HTML_ID
                if (att.Name == HtmlElement.DebugIdAttributeName)
                    continue;
#endif
                var cloneAtt = (HtmlAttribute)att.Clone(options);

                if ((options & HtmlCloneOptions.OverwriteAttributes) == HtmlCloneOptions.OverwriteAttributes)
                {
                    target.Attributes[cloneAtt.Name] = cloneAtt;
                }
                else
                {
                    target.Attributes.Add(cloneAtt);
                }
            }
        }

        if ((options & HtmlCloneOptions.Deep) == HtmlCloneOptions.Deep)
        {
            foreach (var node in ChildNodes)
            {
                var cloneNode = node.Clone(options);
                target.AppendChild(cloneNode);
            }
        }

        if ((options & HtmlCloneOptions.Tag) == HtmlCloneOptions.Tag)
        {
            target._tag = _tag;
        }
    }

    // NOTE: the doc must have been loaded as an HtmlXPathDocument for this to be valid
    public virtual string XPathExpression => null;

    [Conditional("DEBUG")]
    internal virtual void CheckParenting()
    {
        if (HasAttributes)
        {
            foreach (var att in Attributes)
            {
                if (att.ParentNode != this)
                    throw new HtmlException("Internal error: node parenting is wrong. Attribute: " + att.Name);
            }
        }

        if (HasChildNodes)
        {
            foreach (var node in ChildNodes)
            {
                if (node.ParentNode != this)
                    throw new HtmlException("Internal error: node parenting is wrong. Node: " + node.Clone(HtmlCloneOptions.Attributes).OuterHtml);

                node.CheckParenting();
            }
        }
    }

    public virtual HtmlNode CreateNew()
    {
        if (OwnerDocument == null)
            throw new InvalidOperationException();

        switch (NodeType)
        {
            case HtmlNodeType.Attribute:
                return OwnerDocument.CreateAttribute(Prefix, LocalName, NamespaceURI);

            case HtmlNodeType.Comment:
                return OwnerDocument.CreateComment();

            case HtmlNodeType.Document:
                return OwnerDocument.CreateDocument();

            case HtmlNodeType.Element:
            case HtmlNodeType.ProcessingInstruction:
            case HtmlNodeType.DocumentType:
                return OwnerDocument.CreateElement(Prefix, LocalName, NamespaceURI);

            case HtmlNodeType.Text:
                return OwnerDocument.CreateText();

            case HtmlNodeType.XPathResult:
                var result = (HtmlXPathResult)this;
                return new HtmlXPathResult(OwnerDocument, result.Result);

            default:
                throw new NotSupportedException();
        }
    }

    protected virtual void AddNamespacesInScope(XmlNamespaceScope scope, IDictionary<string, string> dictionary)
    {
        if (dictionary is null)
            throw new ArgumentNullException(nameof(dictionary));

        if (!string.IsNullOrWhiteSpace(NamespaceURI))
        {
            if (Prefix != null && (scope != XmlNamespaceScope.ExcludeXml || !string.Equals(NamespaceURI, XmlnsNamespaceURI, StringComparison.Ordinal)))
            {
                dictionary[Prefix] = NamespaceURI;
            }
        }

        if (ParentNode != null && scope != XmlNamespaceScope.Local)
        {
            ParentNode.AddNamespacesInScope(scope, dictionary);
        }
    }

    public virtual IXmlNamespaceResolver ParentNamespaceResolver
    {
        get
        {
            if (OwnerDocument != null)
                return OwnerDocument;

            if (ParentNode != null)
                return ParentNode.ParentNamespaceResolver;

            return this;
        }
    }

    public virtual IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope)
    {
        var dic = new Dictionary<string, string>(StringComparer.Ordinal);
        AddNamespacesInScope(scope, dic);
        return dic;
    }

    string IXmlNamespaceResolver.LookupNamespace(string prefix)
    {
        return GetNamespaceOfPrefix(prefix);
    }

    string IXmlNamespaceResolver.LookupPrefix(string namespaceName)
    {
        return GetPrefixOfNamespace(namespaceName);
    }

    public XmlNode ImportAsXml(XmlDocument owner)
    {
        return ImportAsXml(owner, deep: true);
    }

    public virtual XmlNode ImportAsXml(XmlDocument owner, bool deep)
    {
        if (owner is null)
            throw new ArgumentNullException(nameof(owner));

        using var s = new StringWriter();
        using var writer = XmlWriter.Create(s);
        WriteTo(writer);
        var nodeDoc = new XmlDocument();
        using var txtReader = new StringReader(s.ToString());
        nodeDoc.Load(txtReader);
        return owner.ImportNode(nodeDoc.DocumentElement, deep);
    }

    public HtmlNode SelectSingleNode(string xpath)
    {
        return SelectSingleNode(xpath, nsmgr: null);
    }

    public HtmlNode SelectSingleNode(string xpath, XmlNamespaceManager nsmgr)
    {
        return SelectSingleNode(xpath, nsmgr, HtmlNodeNavigatorOptions.None);
    }

    public HtmlNode SelectSingleNode(string xpath, HtmlNodeNavigatorOptions options)
    {
        return SelectSingleNode(xpath, nsmgr: null, options);
    }

    public HtmlNode SelectSingleNode(string xpath, XmlNamespaceManager nsmgr, HtmlNodeNavigatorOptions options)
    {
        return SelectNodes(xpath, nsmgr, options).FirstOrDefault();
    }

    public IEnumerable<HtmlNode> SelectNodes(string xpath)
    {
        return SelectNodes(xpath, nsmgr: null);
    }

    public IEnumerable<HtmlNode> SelectNodes(string xpath, XmlNamespaceManager nsmgr)
    {
        return SelectNodes(xpath, nsmgr, HtmlNodeNavigatorOptions.None);
    }

    public IEnumerable<HtmlNode> SelectNodes(string xpath, HtmlNodeNavigatorOptions options)
    {
        return SelectNodes(xpath, namespaceManager: null, options);
    }

    public virtual IXPathNavigable CreateNavigable(HtmlNodeNavigatorOptions options)
    {
        return new Navigable(OwnerDocument, this, options);
    }

    public XPathNavigator CreateNavigator()
    {
        return CreateNavigator(HtmlNodeNavigatorOptions.None);
    }

    public virtual XPathNavigator CreateNavigator(HtmlNodeNavigatorOptions options)
    {
        return new HtmlNodeNavigator(OwnerDocument, this, options);
    }

    public virtual IEnumerable<HtmlNode> SelectNodes(string xpath, XmlNamespaceManager namespaceManager, HtmlNodeNavigatorOptions options)
    {
        if (xpath is null)
            throw new ArgumentNullException(nameof(xpath));

        if ((options & HtmlNodeNavigatorOptions.Dynamic) == HtmlNodeNavigatorOptions.Dynamic)
            return DoSelectNodes(xpath, namespaceManager, options);

        var list = DoSelectNodes(xpath, namespaceManager, options).ToList();

        if ((options & HtmlNodeNavigatorOptions.DepthFirst) == HtmlNodeNavigatorOptions.DepthFirst)
        {
            list.Sort(new HtmlNodeDepthComparer { Direction = ListSortDirection.Descending });
        }
        return list;
    }

    protected virtual IEnumerable<HtmlNode> DoSelectNodes(string xpath, XmlNamespaceManager nsmgr, HtmlNodeNavigatorOptions options)
    {
        var navigator = CreateNavigator(options);
        if (navigator == null)
            yield break;

        var expr = navigator.Compile(xpath);
        if (nsmgr != null)
        {
            expr.SetContext(nsmgr);
        }

        var eval = navigator.Evaluate(expr);
        if (eval is XPathNodeIterator it)
        {
            while (it.MoveNext())
            {
                var n = it.Current as HtmlNodeNavigator;
                if (n?.CurrentNode != null)
                    yield return n.CurrentNode;
            }
        }
        else
        {
            yield return new HtmlXPathResult(OwnerDocument, eval);
        }
    }

    private sealed class Navigable : IXPathNavigable
    {
        private readonly HtmlDocument _ownerDocument;
        private readonly HtmlNode _node;
        private readonly HtmlNodeNavigatorOptions _options;

        public Navigable(HtmlDocument ownerDocument, HtmlNode node, HtmlNodeNavigatorOptions options)
        {
            _ownerDocument = ownerDocument;
            _node = node;
            _options = options;
        }

        public XPathNavigator CreateNavigator()
        {
            return new HtmlNodeNavigator(_ownerDocument, _node, _options);
        }
    }
}


text:
	import java.awt.BorderLayout;
	import java.awt.Color;
	import java.awt.Font;
	import java.awt.event.ActionEvent;
	import java.awt.event.ActionListener;
	import javax.swing.JButton;
	import javax.swing.JFrame;
	import javax.swing.JLabel;
	import javax.swing.UIManager;

	public class Cronometro extends JFrame implements Runnable, ActionListener
	{
	    public static int onoff = 0;
	    public Cronometro()
	    {
	        setTitle("Cronometro");
	        setSize(300, 200);
	        setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
	        setLayout( new BorderLayout() );

	        //Etiqueta donde se colocara el tiempo
	        tiempo = new JLabel( "00:00:000" );
	        tiempo.setFont( new Font( Font.SERIF, Font.BOLD, 50 ) );
	        tiempo.setHorizontalAlignment( JLabel.CENTER );
	        tiempo.setForeground( Color.BLUE );
	        tiempo.setBackground( Color.WHITE );
	        tiempo.setOpaque( true );

	        add( tiempo, BorderLayout.CENTER );

	        //Boton iniciar
	        JButton btn = new JButton( "Iniciar" );
	        btn.addActionListener( this );
	        add( btn, BorderLayout.NORTH );

	        //Boton reiniciar inicia nuevamente desde 0
	        JButton btnP = new JButton( "Reiniciar" );
	        btnP.addActionListener( this );
	        add( btnP, BorderLayout.SOUTH );

	        this.setLocationRelativeTo( null );
	        setVisible( true );
	    }

	    public void run(){
	        Integer minutos = 0 , segundos = 0, milesimas = 0;
	        //min es minutos, seg es segundos y mil es milesimas de segundo
	        String min="", seg="", mil="";
	        try
	        {
	            //Mientras cronometroActivo sea verdadero entonces seguira
	            //aumentando el tiempo
	            while( cronometroActivo )
	            {
	                Thread.sleep( 4 );
	                //Incrementamos 4 milesimas de segundo
	                milesimas += 4;

	                //Cuando llega a 1000 osea 1 segundo aumenta 1 segundo
	                //y las milesimas de segundo de nuevo a 0
	                if( milesimas == 1000 )
	                {
	                    milesimas = 0;
	                    segundos += 1;
	                    //Si los segundos llegan a 60 entonces aumenta 1 los minutos
	                    //y los segundos vuelven a 0
	                    if( segundos == 60 )
	                    {
	                        segundos = 0;
	                        minutos++;
	                    }
	                }

	                //Esto solamente es estetica para que siempre este en formato
	                //00:00:000
	                if( minutos < 10 ) min = "0" + minutos;
	                else min = minutos.toString();
	                if( segundos < 10 ) seg = "0" + segundos;
	                else seg = segundos.toString();

	                if( milesimas < 10 ) mil = "00" + milesimas;
	                else if( milesimas < 100 ) mil = "0" + milesimas;
	                else mil = milesimas.toString();

	                //Colocamos en la etiqueta la informacion
	                tiempo.setText( min + ":" + seg + ":" + mil );
	            }
	        }catch(Exception e){}
	        //Cuando se reincie se coloca nuevamente en 00:00:000
	        tiempo.setText( "00:00:000" );
	    }

	    //Esto es para el boton iniciar y reiniciar
	    public void actionPerformed( ActionEvent evt ) {
	        Object o = evt.getSource();
	        if( o instanceof JButton )
	        {
	            JButton btn = (JButton)o;
	            if( btn.getText().equals("Iniciar") ){
	                if(onoff == 0){
	                   onoff = 1;
	                   iniciarCronometro();
	                }
	            }
	            if( btn.getText().equals("Reiniciar") ) {
	                if (onoff == 1){
	                   onoff = 0;
	                   pararCronometro();
	                }
	            }
	        }
	    }

	    //Iniciar el cronometro poniendo cronometroActivo
	    //en verdadero para que entre en el while
	    public void iniciarCronometro() {
	        cronometroActivo = true;
	        hilo = new Thread( this );
	        hilo.start();
	    }

	    //Esto es para parar el cronometro
	    public void pararCronometro(){
	        cronometroActivo = false;
	    }

	    public static void main(String[] args) {
	        //Esta parte es para look and feel por lo tanto es opcional, solo hay que descomentarla
	        //try{
	        //    UIManager.setLookAndFeel( new com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel() );
	        //}catch( Exception e ){}
	        new Cronometro();
	    }

	    JLabel tiempo;
	    Thread hilo;
	    boolean cronometroActivo;

}

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

namespace Microsoft.Azure.WebJobs.Host.Queues.Listeners
{
    internal interface INotificationCommand
    {
        void Notify();
    }
}


text:
<resources>

  <style name="Theme.MaterialPainter" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/color_primary</item>
    <item name="colorAccent">@color/color_accent</item>
    <item name="colorPrimaryDark">@color/color_primary_dark</item>

    <item name="android:textColorPrimary">@color/color_primary_text</item>
    <item name="android:textColorSecondary">@color/color_secondary_text</item>

  </style>

</resources>


text:
package ru.sdroman.carstore.service;

import ru.sdroman.carstore.models.Body;
import ru.sdroman.carstore.models.Car;
import ru.sdroman.carstore.models.DriveType;
import ru.sdroman.carstore.models.Engine;
import ru.sdroman.carstore.models.Brand;
import ru.sdroman.carstore.models.Transmission;

import java.util.List;

/**
 * @author sdroman
 * @since 08.2018
 */
public interface CarService {

    /**
     * Returns body list.
     *
     * @return List
     */
    List<Body> getBodies();

    /**
     * Returns body by id.
     *
     * @param id int
     * @return Body
     */
    Body getBodyById(int id);

    /**
     * Returns engine list.
     *
     * @return List
     */
    List<Engine> getEngines();

    /**
     * Returns engine by id.
     *
     * @param id int
     * @return Engine
     */
    Engine getEngineById(int id);

    /**
     * Returns driveType list.
     *
     * @return List
     */
    List<DriveType> getDriveType();

    /**
     * Returns driveType by id.
     *
     * @param id int
     * @return DriveType
     */
    DriveType getDriveTypeById(int id);

    /**
     * Returns model list.
     *
     * @return List
     */
    List<Brand> getModels();

    /**
     * Returns model by id.
     *
     * @param id int
     * @return Model
     */
    Brand getModelById(int id);

    /**
     * Returns transmission list.
     *
     * @return List
     */
    List<Transmission> getTransmissions();

    /**
     * Returns transmission by id.
     *
     * @param id int
     * @return Transmission
     */
    Transmission getTransmissionById(int id);

    /**
     * Returns car list.
     *
     * @return List
     */
    List<Car> getAll();

    /**
     * Returns car by id.
     *
     * @param id int
     * @return Car
     */
    Car getById(int id);

    /**
     * Adds car to db.
     *
     * @param car Car without id
     * @return Car with id.
     */
    Car add(Car car);

    /**
     * Removes car from db.
     *
     * @param car Car
     */
    void delete(Car car);

    /**
     * Updates car.
     *
     * @param car Car
     * @return new Car
     */
    Car update(Car car);
}


text:
import { Todo } from '../models/todo';
import { Storage } from '../services/storage';
import { autoinject } from 'aurelia-framework';
import { Router } from 'aurelia-router';

@autoinject
export class List {
    public todos: Todo[];

    constructor(private storage: Storage, private router: Router) {
        this.todos = this.storage.getTodos();
    }

    public viewTodo(todo: Todo) {
        this.router.navigateToRoute('edit', {id: todo.id});
    }

    public addTodo() {
        this.router.navigate('/add');
    }

    toggleDone(todo: Todo) {
        if (todo.done) {
            todo.done = false;
        } else {
            todo.done = true;
        }

        this.storage.saveTodo(todo);
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.hybridcompute.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Map;

/**
 * A container holding only the Tags for a resource, allowing the user to update the tags on a PrivateLinkScope
 * instance.
 */
@Fluent
public final class TagsResource {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(TagsResource.class);

    /*
     * Resource tags
     */
    @JsonProperty(value = "tags")
    private Map<String, String> tags;

    /**
     * Get the tags property: Resource tags.
     *
     * @return the tags value.
     */
    public Map<String, String> tags() {
        return this.tags;
    }

    /**
     * Set the tags property: Resource tags.
     *
     * @param tags the tags value to set.
     * @return the TagsResource object itself.
     */
    public TagsResource withTags(Map<String, String> tags) {
        this.tags = tags;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
    }
}


text:
template <class T>
struct ReboundA {};

template <class T>
struct A
{
    typedef T value_type;

    template <class U> struct rebind {typedef ReboundA<U> other;};
};

template <class T, class U>
struct ReboundB {};

template <class T, class U>
struct B
{
    typedef T value_type;

    template <class V> struct rebind {typedef ReboundB<V, U> other;};
};

template <class T>
struct C
{
    typedef T value_type;
};

template <class T, class U>
struct D
{
    typedef T value_type;
};

template <class T>
struct E
{
    typedef T value_type;

    template <class U> struct rebind {typedef ReboundA<U> otter;};
};

int main()
{
#ifndef _LIBCPP_HAS_NO_TEMPLATE_ALIASES
    static_assert((std::is_same<std::allocator_traits<A<char> >::rebind_alloc<double>, ReboundA<double> >::value), "");
    static_assert((std::is_same<std::allocator_traits<B<int, char> >::rebind_alloc<double>, ReboundB<double, char> >::value), "");
    static_assert((std::is_same<std::allocator_traits<C<char> >::rebind_alloc<double>, C<double> >::value), "");
    static_assert((std::is_same<std::allocator_traits<D<int, char> >::rebind_alloc<double>, D<double, char> >::value), "");
    static_assert((std::is_same<std::allocator_traits<E<char> >::rebind_alloc<double>, E<double> >::value), "");
#else  // _LIBCPP_HAS_NO_TEMPLATE_ALIASES
    static_assert((std::is_same<std::allocator_traits<A<char> >::rebind_alloc<double>::other, ReboundA<double> >::value), "");
    static_assert((std::is_same<std::allocator_traits<B<int, char> >::rebind_alloc<double>::other, ReboundB<double, char> >::value), "");
    static_assert((std::is_same<std::allocator_traits<C<char> >::rebind_alloc<double>::other, C<double> >::value), "");
    static_assert((std::is_same<std::allocator_traits<D<int, char> >::rebind_alloc<double>::other, D<double, char> >::value), "");
    static_assert((std::is_same<std::allocator_traits<E<char> >::rebind_alloc<double>::other, E<double> >::value), "");
#endif  // _LIBCPP_HAS_NO_TEMPLATE_ALIASES
}


text:
struct EventStats {
  // Counts.
  int64_t cum_count = 0;
  int64_t curr_count = 0;

  // Execution stats.
  int64_t cum_execution_time = 0;
  int64_t running_count = 0;
};

/// Count and queueing statistics over all events.
struct GlobalStats {
  // Queue stats.
  int64_t cum_queue_time = 0;
  int64_t min_queue_time = std::numeric_limits<int64_t>::max();
  int64_t max_queue_time = -1;
};

/// A mutex wrapper around a handler stats struct.
struct GuardedEventStats {
  // Stats for some handler.
  EventStats stats GUARDED_BY(mutex);

  // The mutex protecting the reading and writing of these stats.
  // This mutex should be acquired with a reader lock before reading, and should be
  // acquired with a writer lock before writing.
  mutable absl::Mutex mutex;
};

/// A mutex wrapper around a handler stats struct.
struct GuardedGlobalStats {
  // Stats over all handlers.
  GlobalStats stats GUARDED_BY(mutex);

  // The mutex protecting the reading and writing of these stats.
  // This mutex should be acquired with a reader lock before reading, and should be
  // acquired with a writer lock before writing.
  mutable absl::Mutex mutex;
};

/// An opaque stats handle, used to manually instrument event handlers.
struct StatsHandle {
  std::string event_name;
  int64_t start_time;
  std::shared_ptr<GuardedEventStats> handler_stats;
  std::shared_ptr<GuardedGlobalStats> global_stats;
  std::atomic<bool> execution_recorded;

  StatsHandle(std::string event_name_,
              int64_t start_time_,
              std::shared_ptr<GuardedEventStats> handler_stats_,
              std::shared_ptr<GuardedGlobalStats> global_stats_)
      : event_name(std::move(event_name_)),
        start_time(start_time_),
        handler_stats(std::move(handler_stats_)),
        global_stats(std::move(global_stats_)),
        execution_recorded(false) {}

  void ZeroAccumulatedQueuingDelay() { start_time = absl::GetCurrentTimeNanos(); }

  ~StatsHandle() {
    if (!execution_recorded) {
      // If handler execution was never recorded, we need to clean up some queueing
      // stats in order to prevent those stats from leaking.
      absl::MutexLock lock(&(handler_stats->mutex));
      handler_stats->stats.curr_count--;
    }
  }
};

class EventTracker {
 public:
  /// Initializes the global stats struct after calling the base constructor.
  EventTracker() : global_stats_(std::make_shared<GuardedGlobalStats>()) {}

  /// Sets the queueing start time, increments the current and cumulative counts and
  /// returns an opaque handle for these stats. This is used in conjunction with
  /// RecordExecution() to manually instrument an event.
  ///
  /// The returned opaque stats handle should be given to a subsequent RecordExecution()
  /// call.
  ///
  /// \param name A human-readable name to which collected stats will be associated.
  /// \param expected_queueing_delay_ns How much to pad the observed queueing start time,
  ///  in nanoseconds.
  /// \return An opaque stats handle, to be given to RecordExecution().
  std::shared_ptr<StatsHandle> RecordStart(const std::string &name,
                                           int64_t expected_queueing_delay_ns = 0);

  /// Records stats about the provided function's execution. This is used in conjunction
  /// with RecordStart() to manually instrument an event loop handler that doesn't call
  /// .post().
  ///
  /// \param fn The function to execute and instrument.
  /// \param handle An opaque stats handle returned by RecordStart().
  static void RecordExecution(const std::function<void()> &fn,
                              std::shared_ptr<StatsHandle> handle);

  /// Returns a snapshot view of the global count, queueing, and execution statistics
  /// across all handlers.
  ///
  /// \return A snapshot view of the global handler stats.
  GlobalStats get_global_stats() const;

  /// Returns a snapshot view of the count, queueing, and execution statistics for the
  /// provided event type.
  ///
  /// \param event_name The name of the event whose stats should be returned.
  /// \return A snapshot view of the event's stats.
  absl::optional<EventStats> get_event_stats(const std::string &event_name) const
      LOCKS_EXCLUDED(mutex_);

  /// Returns snapshot views of the count, queueing, and execution statistics for all
  /// events.
  ///
  /// \return A vector containing snapshot views of stats for all events.
  std::vector<std::pair<std::string, EventStats>> get_event_stats() const
      LOCKS_EXCLUDED(mutex_);

  /// Builds and returns a statistics summary string. Used by the DebugString() of
  /// objects that used this io_context wrapper, such as the raylet and the core worker.
  ///
  /// \return A stats summary string, suitable for inclusion in an object's
  /// DebugString().
  std::string StatsString() const LOCKS_EXCLUDED(mutex_);

 private:
  using EventStatsTable =
      absl::flat_hash_map<std::string, std::shared_ptr<GuardedEventStats>>;
  /// Get the mutex-guarded stats for this event if it exists, otherwise create the
  /// stats for this handler and return an iterator pointing to it.
  ///
  /// \param name A human-readable name for the handler, to be used for viewing stats
  /// for the provided handler.
  std::shared_ptr<GuardedEventStats> GetOrCreate(const std::string &name);

  /// Global stats, across all handlers.
  std::shared_ptr<GuardedGlobalStats> global_stats_;

  /// Table of per-handler post stats.
  /// We use a std::shared_ptr value in order to ensure pointer stability.
  EventStatsTable post_handler_stats_ GUARDED_BY(mutex_);

  /// Protects access to the per-handler post stats table.
  mutable absl::Mutex mutex_;
};


text:
package io.getquill.jdbczio

import io.getquill.{ NamingStrategy, ReturnAction }
import io.getquill.context.{ ContextVerbStream, ExecutionInfo, ProtoContext }
import io.getquill.context.jdbc.JdbcContextTypes
import io.getquill.context.qzio.{ ZioContext, ZioJdbcContext, ZioTranslateContext }
import io.getquill.context.sql.idiom.SqlIdiom
import zio.{ ZEnvironment, ZIO }
import zio.stream.ZStream

import java.sql.{ Connection, PreparedStatement, ResultSet, SQLException }
import javax.sql.DataSource
import scala.util.Try

trait QuillBaseContext[+Dialect <: SqlIdiom, +Naming <: NamingStrategy] extends ZioContext[Dialect, Naming]
  with JdbcContextTypes[Dialect, Naming]
  with ProtoContext[Dialect, Naming]
  with ContextVerbStream[Dialect, Naming]
  with ZioTranslateContext {

  def ds: DataSource

  override type StreamResult[T] = ZStream[Environment, Error, T]
  override type Result[T] = ZIO[Environment, Error, T]
  override type RunQueryResult[T] = List[T]
  override type RunQuerySingleResult[T] = T
  override type RunActionResult = Long
  override type RunActionReturningResult[T] = T
  override type RunBatchActionResult = List[Long]
  override type RunBatchActionReturningResult[T] = List[T]

  override type Error = SQLException
  override type Environment = Any
  override type PrepareRow = PreparedStatement
  override type ResultRow = ResultSet

  override type TranslateResult[T] = ZIO[Environment, Error, T]
  override type Session = Connection

  lazy val underlying: ZioJdbcContext[Dialect, Naming] = dsDelegate
  private[getquill] val dsDelegate: ZioJdbcContext[Dialect, Naming]

  override def close() = ()

  override def probe(sql: String): Try[_] = dsDelegate.probe(sql)

  def executeAction(sql: String, prepare: Prepare = identityPrepare)(info: ExecutionInfo, dc: Runner): ZIO[Any, SQLException, Long] =
    onDS(dsDelegate.executeAction(sql, prepare)(info, dc))

  def executeQuery[T](sql: String, prepare: Prepare = identityPrepare, extractor: Extractor[T] = identityExtractor)(info: ExecutionInfo, dc: Runner): ZIO[Any, SQLException, List[T]] =
    onDS(dsDelegate.executeQuery[T](sql, prepare, extractor)(info, dc))

  override def executeQuerySingle[T](sql: String, prepare: Prepare = identityPrepare, extractor: Extractor[T] = identityExtractor)(info: ExecutionInfo, dc: Runner): ZIO[Any, SQLException, T] =
    onDS(dsDelegate.executeQuerySingle[T](sql, prepare, extractor)(info, dc))

  override def translateQuery[T](statement: String, prepare: Prepare = identityPrepare, extractor: Extractor[T] = identityExtractor, prettyPrint: Boolean = false)(executionInfo: ExecutionInfo, dc: Runner): TranslateResult[String] =
    onDS(dsDelegate.translateQuery[T](statement, prepare, extractor, prettyPrint)(executionInfo, dc))

  override def translateBatchQuery(groups: List[BatchGroup], prettyPrint: Boolean = false)(executionInfo: ExecutionInfo, dc: Runner): TranslateResult[List[String]] =
    onDS(dsDelegate.translateBatchQuery(groups.asInstanceOf[List[QuillBaseContext.this.dsDelegate.BatchGroup]], prettyPrint)(executionInfo, dc))

  def streamQuery[T](fetchSize: Option[Int], sql: String, prepare: Prepare = identityPrepare, extractor: Extractor[T] = identityExtractor)(info: ExecutionInfo, dc: Runner): ZStream[Any, SQLException, T] =
    onDSStream(dsDelegate.streamQuery[T](fetchSize, sql, prepare, extractor)(info, dc))

  def executeActionReturning[O](sql: String, prepare: Prepare = identityPrepare, extractor: Extractor[O], returningBehavior: ReturnAction)(info: ExecutionInfo, dc: Runner): ZIO[Any, SQLException, O] =
    onDS(dsDelegate.executeActionReturning[O](sql, prepare, extractor, returningBehavior)(info, dc))

  def executeActionReturningMany[O](sql: String, prepare: Prepare = identityPrepare, extractor: Extractor[O], returningBehavior: ReturnAction)(info: ExecutionInfo, dc: Runner): ZIO[Any, SQLException, List[O]] =
    onDS(dsDelegate.executeActionReturningMany[O](sql, prepare, extractor, returningBehavior)(info, dc))

  def executeBatchAction(groups: List[BatchGroup])(info: ExecutionInfo, dc: Runner): ZIO[Any, SQLException, List[Long]] =
    onDS(dsDelegate.executeBatchAction(groups.asInstanceOf[List[QuillBaseContext.this.dsDelegate.BatchGroup]])(info, dc))

  def executeBatchActionReturning[T](groups: List[BatchGroupReturning], extractor: Extractor[T])(info: ExecutionInfo, dc: Runner): ZIO[Any, SQLException, List[T]] =
    onDS(dsDelegate.executeBatchActionReturning[T](groups.asInstanceOf[List[QuillBaseContext.this.dsDelegate.BatchGroupReturning]], extractor)(info, dc))

  // Used in translation functions
  private[getquill] def prepareParams(statement: String, prepare: Prepare): ZIO[Any, SQLException, Seq[String]] =
    onDS(dsDelegate.prepareParams(statement, prepare))

  /**
   * Execute instructions in a transaction. For example, to add a Person row to the database and return
   * the contents of the Person table immediately after that:
   * {{{
   *   val a = run(query[Person].insert(Person(...)): ZIO[Has[DataSource], SQLException, Long]
   *   val b = run(query[Person]): ZIO[Has[DataSource], SQLException, Person]
   *   transaction(a *> b): ZIO[Has[DataSource], SQLException, Person]
   * }}}
   */
  def transaction[R, A](op: ZIO[R, Throwable, A]): ZIO[R, Throwable, A] =
    dsDelegate.transaction(op).provideSomeEnvironment[R]((env: ZEnvironment[R]) => env.add[DataSource](ds: DataSource))

  private def onDS[T](qio: ZIO[DataSource, SQLException, T]): ZIO[Any, SQLException, T] =
    qio.provideEnvironment(ZEnvironment(ds))

  private def onDSStream[T](qstream: ZStream[DataSource, SQLException, T]): ZStream[Any, SQLException, T] =
    qstream.provideEnvironment(ZEnvironment(ds))
}


text:
package org.pitest.mutationtest.engine.gregor.mutators;

import org.objectweb.asm.MethodVisitor;
import org.pitest.functional.F2;
import org.pitest.mutationtest.engine.gregor.Context;
import org.pitest.mutationtest.engine.gregor.MethodInfo;
import org.pitest.mutationtest.engine.gregor.MethodMutatorFactory;

public enum NonVoidMethodCallMutator implements MethodMutatorFactory {

  NON_VOID_METHOD_CALL_MUTATOR;

  public MethodVisitor create(final Context context,
      final MethodInfo methodInfo, final MethodVisitor methodVisitor) {
    return new MethodCallMethodVisitor(methodInfo, context, methodVisitor,
        this, nonVoidMethods());
  }

  public String getGloballyUniqueId() {
    return this.getClass().getName();
  }

  public String getName() {
    return name();
  }

  private F2<String, String, Boolean> nonVoidMethods() {
    return new F2<String, String, Boolean>() {

      public Boolean apply(final String name, final String desc) {
        return !MethodInfo.isVoid(desc);
      }

    };
  }

}


text:
package ro.pub.cs.systems.eim.lab05.startedservice.general;

import java.util.ArrayList;
import java.util.Arrays;

public interface Constants {

    final public static String TAG = "[Started Service]";

    final public static String ACTION_STRING = "ro.pub.cs.systems.eim.lab05.startedservice.string";
    final public static String ACTION_INTEGER = "ro.pub.cs.systems.eim.lab05.startedservice.integer";
    final public static String ACTION_ARRAY_LIST = "ro.pub.cs.systems.eim.lab05.startedservice.arraylist";

    final public static int MESSAGE_STRING = 1;
    final public static int MESSAGE_INTEGER = 2;
    final public static int MESSAGE_ARRAY_LIST = 3;

    final public static String DATA = "ro.pub.cs.systems.eim.lab05.startedservice.data";

    final public static String STRING_DATA = "EIM";
    final public static int INTEGER_DATA = 2016;
    final public static ArrayList<String> ARRAY_LIST_DATA = new ArrayList<>(Arrays.asList("EIM", "2016"));

    final public static long SLEEP_TIME = 5000;

}


text:
#pragma once
#include <aws/gamelift/GameLift_EXPORTS.h>
#include <aws/gamelift/GameLiftRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace GameLift
{
namespace Model
{

  /**
   *
Represents the input for a request operation.

See Also:
   AWS
   * API Reference

   */
  class AWS_GAMELIFT_API GetInstanceAccessRequest : public GameLiftRequest
  {
  public:
    GetInstanceAccessRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "GetInstanceAccess"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
A unique identifier for the fleet that contains the instance you want access
     * to. You can use either the fleet ID or ARN value. The fleet can be in any of the
     * following statuses: ACTIVATING, ACTIVE, or
     * ERROR. Fleets with an ERROR status may be accessible
     * for a short time before they are deleted.

     */
    inline const Aws::String& GetFleetId() const{ return m_fleetId; }

    /**
     *
A unique identifier for the fleet that contains the instance you want access
     * to. You can use either the fleet ID or ARN value. The fleet can be in any of the
     * following statuses: ACTIVATING, ACTIVE, or
     * ERROR. Fleets with an ERROR status may be accessible
     * for a short time before they are deleted.

     */
    inline bool FleetIdHasBeenSet() const { return m_fleetIdHasBeenSet; }

    /**
     *
A unique identifier for the fleet that contains the instance you want access
     * to. You can use either the fleet ID or ARN value. The fleet can be in any of the
     * following statuses: ACTIVATING, ACTIVE, or
     * ERROR. Fleets with an ERROR status may be accessible
     * for a short time before they are deleted.

     */
    inline void SetFleetId(const Aws::String& value) { m_fleetIdHasBeenSet = true; m_fleetId = value; }

    /**
     *
A unique identifier for the fleet that contains the instance you want access
     * to. You can use either the fleet ID or ARN value. The fleet can be in any of the
     * following statuses: ACTIVATING, ACTIVE, or
     * ERROR. Fleets with an ERROR status may be accessible
     * for a short time before they are deleted.

     */
    inline void SetFleetId(Aws::String&& value) { m_fleetIdHasBeenSet = true; m_fleetId = std::move(value); }

    /**
     *
A unique identifier for the fleet that contains the instance you want access
     * to. You can use either the fleet ID or ARN value. The fleet can be in any of the
     * following statuses: ACTIVATING, ACTIVE, or
     * ERROR. Fleets with an ERROR status may be accessible
     * for a short time before they are deleted.

     */
    inline void SetFleetId(const char* value) { m_fleetIdHasBeenSet = true; m_fleetId.assign(value); }

    /**
     *
A unique identifier for the fleet that contains the instance you want access
     * to. You can use either the fleet ID or ARN value. The fleet can be in any of the
     * following statuses: ACTIVATING, ACTIVE, or
     * ERROR. Fleets with an ERROR status may be accessible
     * for a short time before they are deleted.

     */
    inline GetInstanceAccessRequest& WithFleetId(const Aws::String& value) { SetFleetId(value); return *this;}

    /**
     *
A unique identifier for the fleet that contains the instance you want access
     * to. You can use either the fleet ID or ARN value. The fleet can be in any of the
     * following statuses: ACTIVATING, ACTIVE, or
     * ERROR. Fleets with an ERROR status may be accessible
     * for a short time before they are deleted.

     */
    inline GetInstanceAccessRequest& WithFleetId(Aws::String&& value) { SetFleetId(std::move(value)); return *this;}

    /**
     *
A unique identifier for the fleet that contains the instance you want access
     * to. You can use either the fleet ID or ARN value. The fleet can be in any of the
     * following statuses: ACTIVATING, ACTIVE, or
     * ERROR. Fleets with an ERROR status may be accessible
     * for a short time before they are deleted.

     */
    inline GetInstanceAccessRequest& WithFleetId(const char* value) { SetFleetId(value); return *this;}

    /**
     *
A unique identifier for the instance you want to get access to. You can
     * access an instance in any status.

     */
    inline const Aws::String& GetInstanceId() const{ return m_instanceId; }

    /**
     *
A unique identifier for the instance you want to get access to. You can
     * access an instance in any status.

     */
    inline bool InstanceIdHasBeenSet() const { return m_instanceIdHasBeenSet; }

    /**
     *
A unique identifier for the instance you want to get access to. You can
     * access an instance in any status.

     */
    inline void SetInstanceId(const Aws::String& value) { m_instanceIdHasBeenSet = true; m_instanceId = value; }

    /**
     *
A unique identifier for the instance you want to get access to. You can
     * access an instance in any status.

     */
    inline void SetInstanceId(Aws::String&& value) { m_instanceIdHasBeenSet = true; m_instanceId = std::move(value); }

    /**
     *
A unique identifier for the instance you want to get access to. You can
     * access an instance in any status.

     */
    inline void SetInstanceId(const char* value) { m_instanceIdHasBeenSet = true; m_instanceId.assign(value); }

    /**
     *
A unique identifier for the instance you want to get access to. You can
     * access an instance in any status.

     */
    inline GetInstanceAccessRequest& WithInstanceId(const Aws::String& value) { SetInstanceId(value); return *this;}

    /**
     *
A unique identifier for the instance you want to get access to. You can
     * access an instance in any status.

     */
    inline GetInstanceAccessRequest& WithInstanceId(Aws::String&& value) { SetInstanceId(std::move(value)); return *this;}

    /**
     *
A unique identifier for the instance you want to get access to. You can
     * access an instance in any status.

     */
    inline GetInstanceAccessRequest& WithInstanceId(const char* value) { SetInstanceId(value); return *this;}

  private:

    Aws::String m_fleetId;
    bool m_fleetIdHasBeenSet = false;

    Aws::String m_instanceId;
    bool m_instanceIdHasBeenSet = false;
  };

} // namespace Model
} // namespace GameLift
} // namespace Aws


text:
using Microsoft.WindowsAzure.Commands.ServiceManagement.Test.FunctionalTests.PowershellCore;

namespace Microsoft.WindowsAzure.Commands.ServiceManagement.Test.FunctionalTests.SubscriptionCmdletInfo
{
    public class GetAzureSubscriptionCmdletInfo : CmdletsInfo
    {
        public GetAzureSubscriptionCmdletInfo(string subscriptionName, string subscriptionDataFile, bool extendedDetails, bool currentSubscription, bool defaultSubscription)
        {
            cmdletName = Utilities.GetAzureSubscriptionCmdletName;

            if (!string.IsNullOrEmpty(subscriptionName))
            {
                this.cmdletParams.Add(new CmdletParam("SubscriptionName", subscriptionName));
            }
            if (!string.IsNullOrEmpty(subscriptionDataFile))
            {
                this.cmdletParams.Add(new CmdletParam("SubscriptionDataFile", subscriptionDataFile));
            }
            if (extendedDetails)
            {
                this.cmdletParams.Add(new CmdletParam("ExtendedDetails"));
            }
            if (currentSubscription)
            {
                this.cmdletParams.Add(new CmdletParam("Current"));
            }
            if (defaultSubscription)
            {
                this.cmdletParams.Add(new CmdletParam("Default"));
            }
        }
    }
}


text:
require 'spec_helper'

describe ThinkingSphinx::ActiveRecord::SQLSource do
  let(:model)      { double('model', :name => 'User', :column_names => [],
    :inheritance_column => 'type', :primary_key => :id) }
  let(:connection) {
    double('connection', :instance_variable_get => db_config) }
  let(:db_config)  { {:host => 'localhost', :user => 'root',
    :database => 'default'} }
  let(:source)     { ThinkingSphinx::ActiveRecord::SQLSource.new(model,
    :position => 3) }
  let(:adapter)    { double('adapter') }

  before :each do
    stub_const 'ActiveRecord::Base', double(:connection => connection)

    ThinkingSphinx::ActiveRecord::DatabaseAdapters::MySQLAdapter.
      stub!(:=== => true)
    ThinkingSphinx::ActiveRecord::DatabaseAdapters.
      stub!(:adapter_for => adapter)
  end

  describe '#adapter' do
    it "returns a database adapter for the model" do
      ThinkingSphinx::ActiveRecord::DatabaseAdapters.
        should_receive(:adapter_for).with(model).and_return(adapter)

      source.adapter.should == adapter
    end
  end

  describe '#attributes' do
    it "has the internal id attribute by default" do
      source.attributes.collect(&:name).should include('sphinx_internal_id')
    end

    it "has the class name attribute by default" do
      source.attributes.collect(&:name).should include('sphinx_internal_class')
    end

    it "has the internal deleted attribute by default" do
      source.attributes.collect(&:name).should include('sphinx_deleted')
    end

    it "marks the internal class attribute as a facet" do
      source.attributes.detect { |attribute|
        attribute.name == 'sphinx_internal_class'
      }.options[:facet].should be_true
    end
  end

  describe '#delta_processor' do
    let(:processor_class) { double('processor class', :try => processor) }
    let(:processor)       { double('processor') }
    let(:source)          {
      ThinkingSphinx::ActiveRecord::SQLSource.new model,
        :delta_processor => processor_class
    }

    it "loads the processor with the adapter" do
      processor_class.should_receive(:try).with(:new, adapter).
        and_return processor

      source.delta_processor
    end

    it "returns the given processor" do
      source.delta_processor.should == processor
    end
  end

  describe '#delta?' do
    it "returns the given delta setting" do
      source = ThinkingSphinx::ActiveRecord::SQLSource.new model,
        :delta? => true

      source.should be_a_delta
    end
  end

  describe '#disable_range?' do
    it "returns the given range setting" do
      source = ThinkingSphinx::ActiveRecord::SQLSource.new model,
        :disable_range? => true

      source.disable_range?.should be_true
    end
  end

  describe '#fields' do
    it "has the internal class field by default" do
      source.fields.collect(&:name).
        should include('sphinx_internal_class_name')
    end

    it "sets the sphinx class field to use a string of the class name" do
      source.fields.detect { |field|
        field.name == 'sphinx_internal_class_name'
      }.columns.first.__name.should == "'User'"
    end

    it "uses the inheritance column if it exists for the sphinx class field" do
      adapter.stub :quoted_table_name => '"users"', :quote => '"type"'
      adapter.stub(:convert_nulls) { |clause, default|
        "ifnull(#{clause}, #{default})"
      }
      model.stub :column_names => ['type'], :sti_name => 'User'

      source.fields.detect { |field|
        field.name == 'sphinx_internal_class_name'
      }.columns.first.__name.
        should == "ifnull(\"users\".\"type\", 'User')"
    end
  end

  describe '#name' do
    it "defaults to the model name downcased with the given position" do
      source.name.should == 'user_3'
    end

    it "allows for custom names, but adds the position suffix" do
      source = ThinkingSphinx::ActiveRecord::SQLSource.new model,
        :name => 'people', :position => 2

      source.name.should == 'people_2'
    end
  end

  describe '#offset' do
    it "returns the given offset" do
      source = ThinkingSphinx::ActiveRecord::SQLSource.new model, :offset => 12

      source.offset.should == 12
    end
  end

  describe '#options' do
    it "defaults to having utf8? set to false" do
      source.options[:utf8?].should be_false
    end

    it "sets utf8? to true if the database encoding is utf8" do
      db_config[:encoding] = 'utf8'

      source.options[:utf8?].should be_true
    end
  end

  describe '#render' do
    let(:builder)   { double('builder', :sql_query_pre => []).as_null_object }
    let(:config)    { double('config', :settings => {}) }
    let(:presenter) { double('presenter', :collection_type => :uint) }
    let(:template)  { double('template', :apply => true) }

    before :each do
      ThinkingSphinx::ActiveRecord::SQLBuilder.stub! :new => builder
      ThinkingSphinx::ActiveRecord::Attribute::SphinxPresenter.stub :new => presenter
      ThinkingSphinx::ActiveRecord::SQLSource::Template.stub :new => template
      ThinkingSphinx::Configuration.stub :instance => config
    end

    it "sets the sql_host setting from the model's database settings" do
      db_config[:host] = '12.34.56.78'

      source.render

      source.sql_host.should == '12.34.56.78'
    end

    it "defaults sql_host to localhost if the model has no host" do
      db_config[:host] = nil

      source.render

      source.sql_host.should == 'localhost'
    end

    it "sets the sql_user setting from the model's database settings" do
      db_config[:username] = 'pat'

      source.render

      source.sql_user.should == 'pat'
    end

    it "uses the user setting if username is not set in the model" do
      db_config[:username] = nil
      db_config[:user]     = 'pat'

      source.render

      source.sql_user.should == 'pat'
    end

    it "sets the sql_pass setting from the model's database settings" do
      db_config[:password] = 'swordfish'

      source.render

      source.sql_pass.should == 'swordfish'
    end

    it "escapes hashes in the password for sql_pass" do
      db_config[:password] = 'sword#fish'

      source.render

      source.sql_pass.should == 'sword\#fish'
    end

    it "sets the sql_db setting from the model's database settings" do
      db_config[:database] = 'rails_app'

      source.render

      source.sql_db.should == 'rails_app'
    end

    it "sets the sql_port setting from the model's database settings" do
      db_config[:port] = 5432

      source.render

      source.sql_port.should == 5432
    end

    it "sets the sql_sock setting from the model's database settings" do
      db_config[:socket] = '/unix/socket'

      source.render

      source.sql_sock.should == '/unix/socket'
    end

    it "uses the builder's sql_query value" do
      builder.stub! :sql_query => 'select * from table'

      source.render

      source.sql_query.should == 'select * from table'
    end

    it "uses the builder's sql_query_range value" do
      builder.stub! :sql_query_range => 'select 0, 10 from table'

      source.render

      source.sql_query_range.should == 'select 0, 10 from table'
    end

    it "uses the builder's sql_query_info value" do
      builder.stub! :sql_query_info => 'select * from table where id = ?'

      source.render

      source.sql_query_info.should == 'select * from table where id = ?'
    end

    it "appends the builder's sql_query_pre value" do
      builder.stub! :sql_query_pre => ['Change Setting']

      source.render

      source.sql_query_pre.should == ['Change Setting']
    end

    it "adds fields with attributes to sql_field_string" do
      source.fields << double('field', :name => 'title', :source_type => nil,
        :with_attribute? => true, :file? => false, :wordcount? => false)

      source.render

      source.sql_field_string.should include('title')
    end

    it "adds any joined or file fields" do
      source.fields << double('field', :name => 'title', :file? => true,
        :with_attribute? => false, :wordcount? => false,  :source_type => nil)

      source.render

      source.sql_file_field.should include('title')
    end

    it "adds wordcounted fields to sql_field_str2wordcount" do
      source.fields << double('field', :name => 'title', :source_type => nil,
        :with_attribute? => false, :file? => false, :wordcount? => true)

      source.render

      source.sql_field_str2wordcount.should include('title')
    end

    it "adds any joined fields" do
      ThinkingSphinx::ActiveRecord::PropertyQuery.stub(
        :new => double(:to_s => 'query for title')
      )
      source.fields << double('field', :name => 'title',
        :source_type => :query, :with_attribute? => false, :file? => false,
        :wordcount? => false)

      source.render

      source.sql_joined_field.should include('query for title')
    end

    it "adds integer attributes to sql_attr_uint" do
      source.attributes << double('attribute')
      presenter.stub :declaration => 'count', :collection_type => :uint

      source.render

      source.sql_attr_uint.should include('count')
    end

    it "adds boolean attributes to sql_attr_bool" do
      source.attributes << double('attribute')
      presenter.stub :declaration => 'published', :collection_type => :bool

      source.render

      source.sql_attr_bool.should include('published')
    end

    it "adds string attributes to sql_attr_string" do
      source.attributes << double('attribute')
      presenter.stub :declaration => 'name', :collection_type => :string

      source.render

      source.sql_attr_string.should include('name')
    end

    it "adds timestamp attributes to sql_attr_timestamp" do
      source.attributes << double('attribute')
      presenter.stub :declaration => 'created_at',
        :collection_type => :timestamp

      source.render

      source.sql_attr_timestamp.should include('created_at')
    end

    it "adds float attributes to sql_attr_float" do
      source.attributes << double('attribute')
      presenter.stub :declaration => 'rating', :collection_type => :float

      source.render

      source.sql_attr_float.should include('rating')
    end

    it "adds bigint attributes to sql_attr_bigint" do
      source.attributes << double('attribute')
      presenter.stub :declaration => 'super_id', :collection_type => :bigint

      source.render

      source.sql_attr_bigint.should include('super_id')
    end

    it "adds ordinal strings to sql_attr_str2ordinal" do
      source.attributes << double('attribute')
      presenter.stub :declaration => 'name', :collection_type => :str2ordinal

      source.render

      source.sql_attr_str2ordinal.should include('name')
    end

    it "adds multi-value attributes to sql_attr_multi" do
      source.attributes << double('attribute')
      presenter.stub :declaration => 'uint tag_ids from field',
        :collection_type => :multi

      source.render

      source.sql_attr_multi.should include('uint tag_ids from field')
    end

    it "adds word count attributes to sql_attr_str2wordcount" do
      source.attributes << double('attribute')
      presenter.stub :declaration => 'name', :collection_type => :str2wordcount

      source.render

      source.sql_attr_str2wordcount.should include('name')
    end

    it "adds relevant settings from thinking_sphinx.yml" do
      config.settings['mysql_ssl_cert'] = 'foo.cert'
      config.settings['morphology']     = 'stem_en' # should be ignored

      source.render

      source.mysql_ssl_cert.should == 'foo.cert'
    end
  end

  describe '#type' do
    it "is mysql when using the MySQL Adapter" do
      ThinkingSphinx::ActiveRecord::DatabaseAdapters::MySQLAdapter.
        stub!(:=== => true)
      ThinkingSphinx::ActiveRecord::DatabaseAdapters::PostgreSQLAdapter.
        stub!(:=== => false)

      source.type.should == 'mysql'
    end

    it "is pgsql when using the PostgreSQL Adapter" do
      ThinkingSphinx::ActiveRecord::DatabaseAdapters::MySQLAdapter.
        stub!(:=== => false)
      ThinkingSphinx::ActiveRecord::DatabaseAdapters::PostgreSQLAdapter.
        stub!(:=== => true)

      source.type.should == 'pgsql'
    end

    it "raises an exception for any other adapter" do
      ThinkingSphinx::ActiveRecord::DatabaseAdapters::MySQLAdapter.
        stub!(:=== => false)
      ThinkingSphinx::ActiveRecord::DatabaseAdapters::PostgreSQLAdapter.
        stub!(:=== => false)

      lambda { source.type }.should raise_error
    end
  end
end


text:
package kafka.javaapi.producer

import kafka.producer.ProducerConfig
import kafka.producer.KeyedMessage
import scala.collection.mutable

class Producer[K,V](private val underlying: kafka.producer.Producer[K,V]) // for testing only
{
  def this(config: ProducerConfig) = this(new kafka.producer.Producer[K,V](config))
  /**
   * Sends the data to a single topic, partitioned by key, using either the
   * synchronous or the asynchronous producer
   * @param message the producer data object that encapsulates the topic, key and message data
   */
  def send(message: KeyedMessage[K,V]) {
    underlying.send(message)
  }

  /**
   * Use this API to send data to multiple topics
   * @param messages list of producer data objects that encapsulate the topic, key and message data
   */
  def send(messages: java.util.List[KeyedMessage[K,V]]) {
    import collection.JavaConversions._
    underlying.send((messages: mutable.Buffer[KeyedMessage[K,V]]).toSeq: _*)
  }

  /**
   * Close API to close the producer pool connections to all Kafka brokers. Also closes
   * the zookeeper client connection if one exists
   */
  def close = underlying.close
}


text:
package org.dbflute.intro.dbflute.exbhv;

import org.dbflute.intro.dbflute.bsbhv.BsClsTargetDatabaseBhv;

/**
 * The behavior of CLS_TARGET_DATABASE.
 * <p>
 * You can implement your original methods here.
 * This class remains when re-generating.
 * </p>
 * @author DBFlute(AutoGenerator)
 */
public class ClsTargetDatabaseBhv extends BsClsTargetDatabaseBhv {
}


text:
require 'google/protobuf'

require 'google/api/field_behavior_pb'
require 'google/api/resource_pb'
require 'google/cloud/retail/v2/common_pb'
require 'google/cloud/retail/v2/promotion_pb'
require 'google/protobuf/duration_pb'
require 'google/protobuf/field_mask_pb'
require 'google/protobuf/timestamp_pb'
require 'google/protobuf/wrappers_pb'

Google::Protobuf::DescriptorPool.generated_pool.build do
  add_file("google/cloud/retail/v2/product.proto", :syntax => :proto3) do
    add_message "google.cloud.retail.v2.Product" do
      optional :name, :string, 1
      optional :id, :string, 2
      optional :type, :enum, 3, "google.cloud.retail.v2.Product.Type"
      optional :primary_product_id, :string, 4
      repeated :collection_member_ids, :string, 5
      optional :gtin, :string, 6
      repeated :categories, :string, 7
      optional :title, :string, 8
      repeated :brands, :string, 9
      optional :description, :string, 10
      optional :language_code, :string, 11
      map :attributes, :string, :message, 12, "google.cloud.retail.v2.CustomAttribute"
      repeated :tags, :string, 13
      optional :price_info, :message, 14, "google.cloud.retail.v2.PriceInfo"
      optional :rating, :message, 15, "google.cloud.retail.v2.Rating"
      optional :available_time, :message, 18, "google.protobuf.Timestamp"
      optional :availability, :enum, 19, "google.cloud.retail.v2.Product.Availability"
      optional :available_quantity, :message, 20, "google.protobuf.Int32Value"
      repeated :fulfillment_info, :message, 21, "google.cloud.retail.v2.FulfillmentInfo"
      optional :uri, :string, 22
      repeated :images, :message, 23, "google.cloud.retail.v2.Image"
      optional :audience, :message, 24, "google.cloud.retail.v2.Audience"
      optional :color_info, :message, 25, "google.cloud.retail.v2.ColorInfo"
      repeated :sizes, :string, 26
      repeated :materials, :string, 27
      repeated :patterns, :string, 28
      repeated :conditions, :string, 29
      repeated :promotions, :message, 34, "google.cloud.retail.v2.Promotion"
      optional :publish_time, :message, 33, "google.protobuf.Timestamp"
      optional :retrievable_fields, :message, 30, "google.protobuf.FieldMask"
      repeated :variants, :message, 31, "google.cloud.retail.v2.Product"
      repeated :local_inventories, :message, 35, "google.cloud.retail.v2.LocalInventory"
      oneof :expiration do
        optional :expire_time, :message, 16, "google.protobuf.Timestamp"
        optional :ttl, :message, 17, "google.protobuf.Duration"
      end
    end
    add_enum "google.cloud.retail.v2.Product.Type" do
      value :TYPE_UNSPECIFIED, 0
      value :PRIMARY, 1
      value :VARIANT, 2
      value :COLLECTION, 3
    end
    add_enum "google.cloud.retail.v2.Product.Availability" do
      value :AVAILABILITY_UNSPECIFIED, 0
      value :IN_STOCK, 1
      value :OUT_OF_STOCK, 2
      value :PREORDER, 3
      value :BACKORDER, 4
    end
  end
end

module Google
  module Cloud
    module Retail
      module V2
        Product = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.retail.v2.Product").msgclass
        Product::Type = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.retail.v2.Product.Type").enummodule
        Product::Availability = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.retail.v2.Product.Availability").enummodule
      end
    end
  end
end


text: getting-started works!


text:
<?php

/**
 * User Agent Normalizer
 * @package	WURFL_Request_UserAgentNormalizer_Specific
 */
class WURFL_Request_UserAgentNormalizer_Specific_Kindle implements WURFL_Request_UserAgentNormalizer_Interface {
	public function normalize($userAgent) {
		if (WURFL_Handlers_Utils::checkIfContains($userAgent, 'Android')) {
			$model = WURFL_Handlers_AndroidHandler::getAndroidModel($userAgent, false);
			$version = WURFL_Handlers_AndroidHandler::getAndroidVersion($userAgent, false);
			if ($model !== null && $version !== null) {
				$prefix = $version.' '.$model.WURFL_Constants::RIS_DELIMITER;
				return $prefix.$userAgent;
			}
		}
		return $userAgent;
	}
}


text:
namespace cc {
class CompositorFrameMetadata;
}

namespace content {

class BrowserContext;
class DevToolsProtocolHandler;
class RenderViewHost;
class RenderViewHostImpl;

#if defined(OS_ANDROID)
class PowerSaveBlockerImpl;
#endif

namespace devtools {
namespace dom { class DOMHandler; }
namespace input { class InputHandler; }
namespace inspector { class InspectorHandler; }
namespace network { class NetworkHandler; }
namespace page { class PageHandler; }
namespace power { class PowerHandler; }
namespace tracing { class TracingHandler; }
}

class CONTENT_EXPORT RenderViewDevToolsAgentHost
    : public IPCDevToolsAgentHost,
      private WebContentsObserver,
      public NotificationObserver {
 public:
  static void OnCancelPendingNavigation(RenderViewHost* pending,
                                        RenderViewHost* current);

  RenderViewDevToolsAgentHost(RenderViewHost*);

  void SynchronousSwapCompositorFrame(
      const cc::CompositorFrameMetadata& frame_metadata);

  // DevTooolsAgentHost overrides.
  void DisconnectWebContents() override;
  void ConnectWebContents(WebContents* web_contents) override;
  BrowserContext* GetBrowserContext() override;
  WebContents* GetWebContents() override;
  Type GetType() override;
  std::string GetTitle() override;
  GURL GetURL() override;
  bool Activate() override;
  bool Close() override;

 private:
  friend class DevToolsAgentHost;
  ~RenderViewDevToolsAgentHost() override;

  // IPCDevToolsAgentHost overrides.
  void DispatchProtocolMessage(const std::string& message) override;
  void SendMessageToAgent(IPC::Message* msg) override;
  void OnClientAttached() override;
  void OnClientDetached() override;

  // WebContentsObserver overrides.
  void AboutToNavigateRenderFrame(RenderFrameHost* render_frame_host) override;
  void RenderViewHostChanged(RenderViewHost* old_host,
                             RenderViewHost* new_host) override;
  void RenderViewDeleted(RenderViewHost* rvh) override;
  void RenderProcessGone(base::TerminationStatus status) override;
  bool OnMessageReceived(const IPC::Message& message,
                         RenderFrameHost* render_frame_host) override;
  bool OnMessageReceived(const IPC::Message& message) override;
  void DidAttachInterstitialPage() override;
  void DidDetachInterstitialPage() override;
  void TitleWasSet(NavigationEntry* entry, bool explicit_set) override;
  void NavigationEntryCommitted(
      const LoadCommittedDetails& load_details) override;

  // NotificationObserver overrides:
  void Observe(int type,
               const NotificationSource& source,
               const NotificationDetails& details) override;

  void DisconnectRenderViewHost();
  void ConnectRenderViewHost(RenderViewHost* rvh);
  void ReattachToRenderViewHost(RenderViewHost* rvh);

  void SetRenderViewHost(RenderViewHost* rvh);
  void ClearRenderViewHost();

  void RenderViewCrashed();
  void OnSwapCompositorFrame(const IPC::Message& message);
  bool OnSetTouchEventEmulationEnabled(const IPC::Message& message);

  void OnDispatchOnInspectorFrontend(const std::string& message,
                                     uint32 total_size);
  void DispatchOnInspectorFrontend(const std::string& message);
  void OnSaveAgentRuntimeState(const std::string& state);

  void ClientDetachedFromRenderer();

  void InnerOnClientAttached();
  void InnerClientDetachedFromRenderer();

  RenderViewHostImpl* render_view_host_;
  scoped_ptr<devtools::dom::DOMHandler> dom_handler_;
  scoped_ptr<devtools::input::InputHandler> input_handler_;
  scoped_ptr<devtools::inspector::InspectorHandler> inspector_handler_;
  scoped_ptr<devtools::network::NetworkHandler> network_handler_;
  scoped_ptr<devtools::page::PageHandler> page_handler_;
  scoped_ptr<devtools::power::PowerHandler> power_handler_;
  scoped_ptr<devtools::tracing::TracingHandler> tracing_handler_;
  scoped_ptr<DevToolsProtocolHandler> protocol_handler_;
#if defined(OS_ANDROID)
  scoped_ptr<PowerSaveBlockerImpl> power_save_blocker_;
#endif
  std::string state_;
  NotificationRegistrar registrar_;
  bool reattaching_;

  DISALLOW_COPY_AND_ASSIGN(RenderViewDevToolsAgentHost);
};

}  // namespace content

#endif  // CONTENT_BROWSER_DEVTOOLS_RENDER_VIEW_DEVTOOLS_AGENT_HOST_H_


text:
layout: relation
title:  'nmod:arg'
shortdef : 'nominal modifier used as an argument'
udver: '2'
---

`nmod:arg` is used for a nominal modifier which used as an argument of the following derivational suffix. This relation is used for the morpheme level annotations only.

```
pagungha-ligh-naq-a-qa						.
pagunghagh*(N)-ligh(N→V)-@~fnaqe(V→V)-[Ind.Trns]-[1Sg.3Sg]	.
"I am going to put crowberries in it."
```

~~~ sdparse
pagungha ligh naq a qa . \n crowberry to-put-N-in to-be-going-to-V Ind.Trns 1Sg.3Sg .
nmod:arg(ligh, pagungha)
nmod:arg(to-put-N-in, crowberry)
~~~
<!-- Interlanguage links updated Po lis 14 15:35:31 CET 2022 -->


text:
package io.jboot.test.lock;

import io.jboot.app.JbootApplication;
import io.jboot.objects.lock.JbootLock;
import io.jboot.objects.lock.JbootLockManager;

public class JbootLocalLockTester {

    static int  index = 0;

    public static void main(String[] args) {

        JbootApplication.setBootArg("jboot.object.lock.type","local");

        JbootLock lock = JbootLockManager.me().create("myLock");

        for (int i=0;i<10;i++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        lock.lock();
                        JbootLocalLockTester.run();
                    }finally {
                        lock.unlock();
                    }
                }
            }).start();
        }

    }

    private static void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        index += 1;
        System.out.println("run " + index);
    }
}