text:
namespace NLog.Targets
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.IO;
    using System.Net;
    using System.Text;
    using System.Xml;
    using NLog.Common;
    using NLog.Config;
    using NLog.Internal;

    ///
    /// Calls the specified web service on each log message.
    ///
    /// <seealso href="https://github.com/nlog/nlog/wiki/WebService-target">Documentation on NLog Wiki</seealso>
    /// <remarks>
    /// The web service must implement a method that accepts a number of string parameters.
    /// </remarks>
    /// <example>
    ///

    /// To set up the target in the configuration file,
    /// use the following syntax:
    ///

    ///
    ///

    /// This assumes just one target and a single rule. More configuration
    /// options are described here.
    ///

    ///

    /// To set up the log target programmatically use code like this:
    ///

    ///
    ///
The example web service that works with this example is shown below

    ///
    /// </example>
    [Target("WebService")]
    public sealed class WebServiceTarget : MethodCallTargetBase
    {
        private const string SoapEnvelopeNamespaceUri = "http://schemas.xmlsoap.org/soap/envelope/";
        private const string Soap12EnvelopeNamespaceUri = "http://www.w3.org/2003/05/soap-envelope";

        ///
        /// dictionary that maps a concrete <see cref="HttpPostFormatterBase"/> implementation
        /// to a specific <see cref="WebServiceProtocol"/>-value.
        ///
        private static Dictionary<WebServiceProtocol, Func<WebServiceTarget, HttpPostFormatterBase>> _postFormatterFactories =
            new Dictionary<WebServiceProtocol, Func<WebServiceTarget, HttpPostFormatterBase>>()
            {
                { WebServiceProtocol.Soap11, t => new HttpPostSoap11Formatter(t)},
                { WebServiceProtocol.Soap12, t => new HttpPostSoap12Formatter(t)},
                { WebServiceProtocol.HttpPost, t => new HttpPostFormEncodedFormatter(t)},
                { WebServiceProtocol.JsonPost, t => new HttpPostJsonFormatter(t)},
                { WebServiceProtocol.XmlPost, t => new HttpPostXmlDocumentFormatter(t)},
            };

        ///
        /// Initializes a new instance of the <see cref="WebServiceTarget" /> class.
        ///
        public WebServiceTarget()
        {
            Protocol = WebServiceProtocol.Soap11;

            //default NO utf-8 bom
            const bool writeBOM = false;
            Encoding = new UTF8Encoding(writeBOM);
            IncludeBOM = writeBOM;
            OptimizeBufferReuse = true;

            Headers = new List<MethodCallParameter>();

#if NETSTANDARD
            // WebRequest.GetSystemWebProxy throws PlatformNotSupportedException on NetCore, when Proxy is not configured
            ProxyType = WebServiceProxyType.NoProxy;
#endif
        }

        ///
        /// Initializes a new instance of the <see cref="WebServiceTarget" /> class.
        ///
        /// <param name="name">Name of the target</param>
        public WebServiceTarget(string name) : this()
        {
            Name = name;
        }

        ///
        /// Gets or sets the web service URL.
        ///
        /// <docgen category='Web Service Options' order='10' />
        public Uri Url { get; set; }

        ///
        /// Gets or sets the Web service method name. Only used with Soap.
        ///
        /// <docgen category='Web Service Options' order='10' />
        public string MethodName { get; set; }

        ///
        /// Gets or sets the Web service namespace. Only used with Soap.
        ///
        /// <docgen category='Web Service Options' order='10' />
        public string Namespace { get; set; }

        ///
        /// Gets or sets the protocol to be used when calling web service.
        ///
        /// <docgen category='Web Service Options' order='10' />
        [DefaultValue("Soap11")]
        public WebServiceProtocol Protocol
        {
            get => _activeProtocol.Key;
            set => _activeProtocol = new KeyValuePair<WebServiceProtocol, HttpPostFormatterBase>(value, null);
        }
        private KeyValuePair<WebServiceProtocol, HttpPostFormatterBase> _activeProtocol;

#if !SILVERLIGHT
        ///
        /// Gets or sets the proxy configuration when calling web service
        ///
        /// <docgen category='Web Service Options' order='10' />
        [DefaultValue("DefaultWebProxy")]
        public WebServiceProxyType ProxyType
        {
            get => _activeProxy.Key;
            set => _activeProxy = new KeyValuePair<WebServiceProxyType, IWebProxy>(value, null);
        }
        private KeyValuePair<WebServiceProxyType, IWebProxy> _activeProxy;
#endif

        ///
        /// Gets or sets the custom proxy address, include port separated by a colon
        ///
        /// <docgen category='Web Service Options' order='10' />
        public string ProxyAddress { get; set; }

        ///
        /// Should we include the BOM (Byte-order-mark) for UTF? Influences the <see cref="Encoding"/> property.
        ///
        /// This will only work for UTF-8.
        ///
        /// <docgen category='Web Service Options' order='10' />
        public bool? IncludeBOM { get; set; }

        ///
        /// Gets or sets the encoding.
        ///
        /// <docgen category='Web Service Options' order='10' />
        public Encoding Encoding { get; set; }

        ///
        /// Gets or sets a value whether escaping be done according to Rfc3986 (Supports Internationalized Resource Identifiers - IRIs)
        ///
        /// <value>A value of <c>true</c> if Rfc3986; otherwise, <c>false</c> for legacy Rfc2396.</value>
        /// <docgen category='Web Service Options' order='100' />
        public bool EscapeDataRfc3986 { get; set; }

        ///
        /// Gets or sets a value whether escaping be done according to the old NLog style (Very non-standard)
        ///
        /// <value>A value of <c>true</c> if legacy encoding; otherwise, <c>false</c> for standard UTF8 encoding.</value>
        /// <docgen category='Web Service Options' order='100' />
        public bool EscapeDataNLogLegacy { get; set; }

        ///
        /// Gets or sets the name of the root XML element,
        /// if POST of XML document chosen.
        /// If so, this property must not be <c>null</c>.
        /// (see <see cref="Protocol"/> and <see cref="WebServiceProtocol.XmlPost"/>).
        ///
        /// <docgen category='Web Service Options' order='100' />
        public string XmlRoot { get; set; }

        ///
        /// Gets or sets the (optional) root namespace of the XML document,
        /// if POST of XML document chosen.
        /// (see <see cref="Protocol"/> and <see cref="WebServiceProtocol.XmlPost"/>).
        ///
        /// <docgen category='Web Service Options' order='100' />
        public string XmlRootNamespace { get; set; }

        ///
        /// Gets the array of parameters to be passed.
        ///
        /// <docgen category='Web Service Options' order='10' />
        [ArrayParameter(typeof(MethodCallParameter), "header")]
        public IList<MethodCallParameter> Headers { get; private set; }

#if !SILVERLIGHT
        ///
        /// Indicates whether to pre-authenticate the HttpWebRequest (Requires 'Authorization' in <see cref="Headers"/> parameters)
        ///
        /// <docgen category='Web Service Options' order='100' />
        public bool PreAuthenticate { get; set; }
#endif

        private readonly AsyncOperationCounter _pendingManualFlushList = new AsyncOperationCounter();

        ///
        /// Calls the target method. Must be implemented in concrete classes.
        ///
        /// <param name="parameters">Method call parameters.</param>
        protected override void DoInvoke(object[] parameters)
        {
            // method is not used, instead asynchronous overload will be used
            throw new NotImplementedException();
        }

        ///
        /// Calls the target DoInvoke method, and handles AsyncContinuation callback
        ///
        /// <param name="parameters">Method call parameters.</param>
        /// <param name="continuation">The continuation.</param>
        protected override void DoInvoke(object[] parameters, AsyncContinuation continuation)
        {
            var webRequest = (HttpWebRequest)WebRequest.Create(BuildWebServiceUrl(parameters));
            DoInvoke(parameters, webRequest, continuation);
        }

        ///
        /// Invokes the web service method.
        ///
        /// <param name="parameters">Parameters to be passed.</param>
        /// <param name="logEvent">The logging event.</param>
        protected override void DoInvoke(object[] parameters, AsyncLogEventInfo logEvent)
        {
            var webRequest = (HttpWebRequest)WebRequest.Create(BuildWebServiceUrl(parameters));

            if (Headers != null && Headers.Count > 0)
            {
                for (int i = 0; i < Headers.Count; i++)
                {
                    string headerValue = RenderLogEvent(Headers[i].Layout, logEvent.LogEvent);
                    if (headerValue == null)
                        continue;

                    webRequest.Headers[Headers[i].Name] = headerValue;
                }
            }

            DoInvoke(parameters, webRequest, logEvent.Continuation);
        }

        void DoInvoke(object[] parameters, HttpWebRequest webRequest, AsyncContinuation continuation)
        {
            Func<HttpWebRequest, AsyncCallback, IAsyncResult> beginGetRequest = (request, result) => request.BeginGetRequestStream(result, null);
            Func<HttpWebRequest, IAsyncResult, Stream> getRequestStream = (request, result) => request.EndGetRequestStream(result);

#if !SILVERLIGHT
            switch (ProxyType)
            {
                case WebServiceProxyType.DefaultWebProxy:
                    break;
#if !NETSTANDARD1_0
                case WebServiceProxyType.AutoProxy:
                    if (_activeProxy.Value == null)
                    {
                        IWebProxy proxy = WebRequest.GetSystemWebProxy();
                        proxy.Credentials = CredentialCache.DefaultCredentials;
                        _activeProxy = new KeyValuePair<WebServiceProxyType, IWebProxy>(ProxyType, proxy);
                    }
                    webRequest.Proxy = _activeProxy.Value;
                    break;
                case WebServiceProxyType.ProxyAddress:
                    if (!string.IsNullOrEmpty(ProxyAddress))
                    {
                        if (_activeProxy.Value == null)
                        {
                            IWebProxy proxy = new WebProxy(ProxyAddress, true);
                            _activeProxy = new KeyValuePair<WebServiceProxyType, IWebProxy>(ProxyType, proxy);
                        }
                        webRequest.Proxy = _activeProxy.Value;
                    }
                    break;
#endif
                default:
                    webRequest.Proxy = null;
                    break;
            }
#endif

#if !SILVERLIGHT && !NETSTANDARD1_0
            if (PreAuthenticate || ProxyType == WebServiceProxyType.AutoProxy)
            {
                webRequest.PreAuthenticate = true;
            }
#endif

            DoInvoke(parameters, continuation, webRequest, beginGetRequest, getRequestStream);
        }

        internal void DoInvoke(object[] parameters, AsyncContinuation continuation, HttpWebRequest webRequest, Func<HttpWebRequest, AsyncCallback, IAsyncResult> beginGetRequest,
            Func<HttpWebRequest, IAsyncResult, Stream> getRequestStream)
        {
            Stream postPayload = null;

            if (Protocol == WebServiceProtocol.HttpGet)
            {
                PrepareGetRequest(webRequest);
            }
            else
            {
                if (_activeProtocol.Value == null)
                    _activeProtocol = new KeyValuePair<WebServiceProtocol, HttpPostFormatterBase>(Protocol, _postFormatterFactories[Protocol](this));
                postPayload = _activeProtocol.Value.PrepareRequest(webRequest, parameters);
            }

            var sendContinuation = CreateSendContinuation(continuation, webRequest);

            PostPayload(continuation, webRequest, beginGetRequest, getRequestStream, postPayload, sendContinuation);
        }

        private AsyncContinuation CreateSendContinuation(AsyncContinuation continuation, HttpWebRequest webRequest)
        {
            AsyncContinuation sendContinuation =
                ex =>
                {
                    if (ex != null)
                    {
                        DoInvokeCompleted(continuation, ex);
                        return;
                    }

                    try
                    {
                        webRequest.BeginGetResponse(
                            r =>
                            {
                                try
                                {
                                    using (var response = webRequest.EndGetResponse(r))
                                    {
                                        // Request successfully initialized
                                    }

                                    DoInvokeCompleted(continuation, null);
                                }
                                catch (Exception ex2)
                                {
                                    InternalLogger.Error(ex2, "WebServiceTarget(Name={0}): Error sending request", Name);
                                    if (ex2.MustBeRethrownImmediately())
                                    {
                                        throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior)
                                    }

                                    DoInvokeCompleted(continuation, ex2);
                                }
                            },
                            null);
                    }
                    catch (Exception ex2)
                    {
                        InternalLogger.Error(ex2, "WebServiceTarget(Name={0}): Error starting request", Name);
                        if (ExceptionMustBeRethrown(ex2))
                        {
                            throw;
                        }

                        DoInvokeCompleted(continuation, ex2);
                    }
                };
            return sendContinuation;
        }

        private void PostPayload(AsyncContinuation continuation, HttpWebRequest webRequest, Func<HttpWebRequest, AsyncCallback, IAsyncResult> beginGetRequest, Func<HttpWebRequest, IAsyncResult, Stream> getRequestStream, Stream postPayload, AsyncContinuation sendContinuation)
        {
            if (postPayload != null && postPayload.Length > 0)
            {
                postPayload.Position = 0;
                try
                {
                    _pendingManualFlushList.BeginOperation();

                    beginGetRequest(webRequest,
                        result =>
                        {
                            try
                            {
                                using (Stream stream = getRequestStream(webRequest, result))
                                {
                                    WriteStreamAndFixPreamble(postPayload, stream, IncludeBOM, Encoding);

                                    postPayload.Dispose();
                                }

                                sendContinuation(null);
                            }
                            catch (Exception ex)
                            {
                                InternalLogger.Error(ex, "WebServiceTarget(Name={0}): Error sending post data", Name);
                                if (ex.MustBeRethrownImmediately())
                                {
                                    throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior)
                                }

                                postPayload.Dispose();
                                DoInvokeCompleted(continuation, ex);
                            }
                        });
                }
                catch (Exception ex)
                {
                    InternalLogger.Error(ex, "WebServiceTarget(Name={0}): Error starting post data", Name);
                    if (ExceptionMustBeRethrown(ex))
                    {
                        throw;
                    }

                    DoInvokeCompleted(continuation, ex);
                }
            }
            else
            {
                _pendingManualFlushList.BeginOperation();
                sendContinuation(null);
            }
        }

        private void DoInvokeCompleted(AsyncContinuation continuation, Exception ex)
        {
            _pendingManualFlushList.CompleteOperation(ex);
            continuation(ex);
        }

        ///
        /// Flush any pending log messages asynchronously (in case of asynchronous targets).
        ///
        /// <param name="asyncContinuation">The asynchronous continuation.</param>
        protected override void FlushAsync(AsyncContinuation asyncContinuation)
        {
            _pendingManualFlushList.RegisterCompletionNotification(asyncContinuation).Invoke(null);
        }

        ///
        /// Closes the target.
        ///
        protected override void CloseTarget()
        {
            _pendingManualFlushList.Clear();   // Maybe consider to wait a short while if pending requests?
            base.CloseTarget();
        }

        ///
        /// Builds the URL to use when calling the web service for a message, depending on the WebServiceProtocol.
        ///
        /// <param name="parameterValues"></param>
        /// <returns></returns>
        private Uri BuildWebServiceUrl(object[] parameterValues)
        {
            if (Protocol != WebServiceProtocol.HttpGet)
            {
                return Url;
            }

            //if the protocol is HttpGet, we need to add the parameters to the query string of the url
            string queryParameters;
            using (var targetBuilder = OptimizeBufferReuse ? ReusableLayoutBuilder.Allocate() : ReusableLayoutBuilder.None)
            {
                StringBuilder sb = targetBuilder.Result ?? new StringBuilder();
                UrlHelper.EscapeEncodingOptions encodingOptions = UrlHelper.GetUriStringEncodingFlags(EscapeDataNLogLegacy, false, EscapeDataRfc3986);
                BuildWebServiceQueryParameters(parameterValues, sb, encodingOptions);
                queryParameters = sb.ToString();
            }

            var builder = new UriBuilder(Url);
            //append our query string to the URL following
            //the recommendations at https://msdn.microsoft.com/en-us/library/system.uribuilder.query.aspx
            if (builder.Query != null && builder.Query.Length > 1)
            {
                builder.Query = string.Concat(builder.Query.Substring(1), "&", queryParameters);
            }
            else
            {
                builder.Query = queryParameters;
            }

            return builder.Uri;
        }

        private void BuildWebServiceQueryParameters(object[] parameterValues, StringBuilder sb, UrlHelper.EscapeEncodingOptions encodingOptions)
        {
            string separator = string.Empty;
            for (int i = 0; i < Parameters.Count; i++)
            {
                sb.Append(separator);
                sb.Append(Parameters[i].Name);
                sb.Append("=");
                string parameterValue = XmlHelper.XmlConvertToString(parameterValues[i]);
                if (!string.IsNullOrEmpty(parameterValue))
                {
                    UrlHelper.EscapeDataEncode(parameterValue, sb, encodingOptions);
                }
                separator = "&";
            }
        }

        private void PrepareGetRequest(HttpWebRequest webRequest)
        {
            webRequest.Method = "GET";
        }

        ///
        /// Write from input to output. Fix the UTF-8 bom
        ///
        /// <param name="input"></param>
        /// <param name="output"></param>
        /// <param name="writeUtf8BOM"></param>
        /// <param name="encoding"></param>
        private static void WriteStreamAndFixPreamble(Stream input, Stream output, bool? writeUtf8BOM, Encoding encoding)
        {
            //only when utf-8 encoding is used, the Encoding preamble is optional
            var nothingToDo = writeUtf8BOM == null || !(encoding is UTF8Encoding);

            const int preambleSize = 3;
            if (!nothingToDo)
            {
                //it's UTF-8
                var hasBomInEncoding = encoding.GetPreamble().Length == preambleSize;

                //BOM already in Encoding.
                nothingToDo = writeUtf8BOM.Value && hasBomInEncoding;

                //Bom already not in Encoding
                nothingToDo = nothingToDo || !writeUtf8BOM.Value && !hasBomInEncoding;
            }
            var offset = nothingToDo ? 0 : preambleSize;
            input.CopyWithOffset(output, offset);

        }

        ///
        /// base class for POST formatters, that
        /// implement former <c>PrepareRequest()</c> method,
        /// that creates the content for
        /// the requested kind of HTTP request
        ///
        private abstract class HttpPostFormatterBase
        {
            protected HttpPostFormatterBase(WebServiceTarget target)
            {
                Target = target;
            }

            protected string ContentType => _contentType ?? (_contentType = GetContentType(Target));
            private string _contentType;

            protected WebServiceTarget Target { get; private set; }

            protected virtual string GetContentType(WebServiceTarget target)
            {
                return string.Concat("charset=", target.Encoding.WebName);
            }

            public MemoryStream PrepareRequest(HttpWebRequest request, object[] parameterValues)
            {
                InitRequest(request);

                var ms = new MemoryStream();
                WriteContent(ms, parameterValues);
                return ms;
            }

            protected virtual void InitRequest(HttpWebRequest request)
            {
                request.Method = "POST";
                request.ContentType = ContentType;
            }

            protected abstract void WriteContent(MemoryStream ms, object[] parameterValues);
        }

        private class HttpPostFormEncodedFormatter : HttpPostTextFormatterBase
        {
            readonly UrlHelper.EscapeEncodingOptions _encodingOptions;

            public HttpPostFormEncodedFormatter(WebServiceTarget target) : base(target)
            {
                _encodingOptions = UrlHelper.GetUriStringEncodingFlags(target.EscapeDataNLogLegacy, true, target.EscapeDataRfc3986);
            }

            protected override string GetContentType(WebServiceTarget target)
            {
                return string.Concat("application/x-www-form-urlencoded", "; ", base.GetContentType(target));
            }

            protected override void WriteStringContent(StringBuilder builder, object[] parameterValues)
            {
                Target.BuildWebServiceQueryParameters(parameterValues, builder, _encodingOptions);
            }
        }

        private class HttpPostJsonFormatter : HttpPostTextFormatterBase
        {
            private IJsonConverter JsonConverter => _jsonConverter ?? (_jsonConverter = ConfigurationItemFactory.Default.JsonConverter);
            private IJsonConverter _jsonConverter;

            public HttpPostJsonFormatter(WebServiceTarget target)
                : base(target)
            {
            }

            protected override string GetContentType(WebServiceTarget target)
            {
                return string.Concat("application/json", "; ", base.GetContentType(target));
            }

            protected override void WriteStringContent(StringBuilder builder, object[] parameterValues)
            {
                if (Target.Parameters.Count == 1 && string.IsNullOrEmpty(Target.Parameters[0].Name) && parameterValues[0] is string s)
                {
                    // JsonPost with single nameless parameter means complex JsonLayout
                    builder.Append(s);
                }
                else
                {
                    builder.Append("{");
                    string separator = string.Empty;
                    for (int i = 0; i < Target.Parameters.Count; ++i)
                    {
                        var parameter = Target.Parameters[i];
                        builder.Append(separator);
                        builder.Append('"');
                        builder.Append(parameter.Name);
                        builder.Append("\":");
                        JsonConverter.SerializeObject(parameterValues[i], builder);
                        separator = ",";
                    }
                    builder.Append('}');
                }
            }
        }

        private class HttpPostSoap11Formatter : HttpPostSoapFormatterBase
        {
            private readonly string _defaultSoapAction;

            public HttpPostSoap11Formatter(WebServiceTarget target) : base(target)
            {
                _defaultSoapAction = GetDefaultSoapAction(target);
            }

            protected override string SoapEnvelopeNamespace => SoapEnvelopeNamespaceUri;

            protected override string SoapName => "soap";

            protected override string GetContentType(WebServiceTarget target)
            {
                return string.Concat("text/xml", "; ", base.GetContentType(target));
            }

            protected override void InitRequest(HttpWebRequest request)
            {
                base.InitRequest(request);
                if (Target.Headers?.Count == 0 || string.IsNullOrEmpty(request.Headers["SOAPAction"]))
                    request.Headers["SOAPAction"] = _defaultSoapAction;
            }
        }

        private class HttpPostSoap12Formatter : HttpPostSoapFormatterBase
        {
            public HttpPostSoap12Formatter(WebServiceTarget target) : base(target)
            {
            }

            protected override string SoapEnvelopeNamespace => Soap12EnvelopeNamespaceUri;

            protected override string SoapName => "soap12";

            protected override string GetContentType(WebServiceTarget target)
            {
                return GetContentTypeSoap12(target, GetDefaultSoapAction(target));
            }

            protected override void InitRequest(HttpWebRequest request)
            {
                base.InitRequest(request);
                string nonDefaultSoapAction = Target.Headers?.Count > 0 ? request.Headers["SOAPAction"] : string.Empty;
                if (!string.IsNullOrEmpty(nonDefaultSoapAction))
                    request.ContentType = GetContentTypeSoap12(Target, nonDefaultSoapAction);
            }

            private string GetContentTypeSoap12(WebServiceTarget target, string soapAction)
            {
                return string.Concat("application/soap+xml", "; ", base.GetContentType(target), "; action=\"", soapAction, "\"");
            }
        }

        private abstract class HttpPostSoapFormatterBase : HttpPostXmlFormatterBase
        {
            private readonly XmlWriterSettings _xmlWriterSettings;

            protected HttpPostSoapFormatterBase(WebServiceTarget target) : base(target)
            {
                _xmlWriterSettings = new XmlWriterSettings { Encoding = target.Encoding };
            }

            protected abstract string SoapEnvelopeNamespace { get; }
            protected abstract string SoapName { get; }

            protected override void WriteContent(MemoryStream ms, object[] parameterValues)
            {
                XmlWriter xtw = XmlWriter.Create(ms, _xmlWriterSettings);

                xtw.WriteStartElement(SoapName, "Envelope", SoapEnvelopeNamespace);
                xtw.WriteStartElement("Body", SoapEnvelopeNamespace);
                xtw.WriteStartElement(Target.MethodName, Target.Namespace);

                WriteAllParametersToCurrenElement(xtw, parameterValues);

                xtw.WriteEndElement(); // method name
                xtw.WriteEndElement(); // Body
                xtw.WriteEndElement(); // soap:Envelope
                xtw.Flush();
            }

            protected static string GetDefaultSoapAction(WebServiceTarget target)
            {
                return target.Namespace.EndsWith("/", StringComparison.Ordinal)
                    ? string.Concat(target.Namespace, target.MethodName)
                    : string.Concat(target.Namespace, "/", target.MethodName);
            }
        }

        private abstract class HttpPostTextFormatterBase : HttpPostFormatterBase
        {
            readonly ReusableBuilderCreator _reusableStringBuilder = new ReusableBuilderCreator();
            readonly ReusableBufferCreator _reusableEncodingBuffer = new ReusableBufferCreator(1024);
            readonly byte[] _encodingPreamble;

            protected HttpPostTextFormatterBase(WebServiceTarget target) : base(target)
            {
                _encodingPreamble = target.Encoding.GetPreamble();
            }

            protected override void WriteContent(MemoryStream ms, object[] parameterValues)
            {
                lock (_reusableStringBuilder)
                {
                    using (var targetBuilder = _reusableStringBuilder.Allocate())
                    {
                        WriteStringContent(targetBuilder.Result, parameterValues);

                        using (var transformBuffer = _reusableEncodingBuffer.Allocate())
                        {
                            if (_encodingPreamble.Length > 0)
                                ms.Write(_encodingPreamble, 0, _encodingPreamble.Length);
                            targetBuilder.Result.CopyToStream(ms, Target.Encoding, transformBuffer.Result);
                        }
                    }
                }
            }

            protected abstract void WriteStringContent(StringBuilder builder, object[] parameterValues);
        }

        private class HttpPostXmlDocumentFormatter : HttpPostXmlFormatterBase
        {
            private readonly XmlWriterSettings _xmlWriterSettings;

            public HttpPostXmlDocumentFormatter(WebServiceTarget target) : base(target)
            {
                if (string.IsNullOrEmpty(target.XmlRoot))
                    throw new InvalidOperationException("WebServiceProtocol.Xml requires WebServiceTarget.XmlRoot to be set.");

                _xmlWriterSettings = new XmlWriterSettings { Encoding = target.Encoding, OmitXmlDeclaration = true, Indent = false };
            }

            protected override string GetContentType(WebServiceTarget target)
            {
                return string.Concat("application/xml", "; ", base.GetContentType(target));
            }

            protected override void WriteContent(MemoryStream ms, object[] parameterValues)
            {
                XmlWriter xtw = XmlWriter.Create(ms, _xmlWriterSettings);

                xtw.WriteStartElement(Target.XmlRoot, Target.XmlRootNamespace);

                WriteAllParametersToCurrenElement(xtw, parameterValues);

                xtw.WriteEndElement();
                xtw.Flush();
            }
        }

        private abstract class HttpPostXmlFormatterBase : HttpPostFormatterBase
        {
            protected HttpPostXmlFormatterBase(WebServiceTarget target) : base(target)
            {
            }

            protected void WriteAllParametersToCurrenElement(XmlWriter currentXmlWriter, object[] parameterValues)
            {
                for (int i = 0; i < Target.Parameters.Count; i++)
                {
                    string parameterValue = XmlHelper.XmlConvertToStringSafe(parameterValues[i]);
                    currentXmlWriter.WriteElementString(Target.Parameters[i].Name, parameterValue);
                }
            }
        }
    }
}


text:
describe("typingSkillTraining panel tests", function() {
  var sh = specHelper()
    , panel
  ;

  beforeEach(function() {
    $("#sandbox")
      .append("

")
      .find(".panel")
      .append("

");

    sh.defaultOpt.panel = $(".panel");
    sh.enablePlugin();
    panel = $(sh.global).data("typingSkillTraining").panel;
  });

  afterEach(function(){
    sh.disablePlugin();
    sh.clearSandbox();
  });

  it("initial text of lastTimeLabel is 0.000 seconds", function() {
    expect(panel).toBeDefined();
    expect(panel.find(".lastTimeSpan").text()).toBe("0.000 seconds");
  });
});

redpajama_set_name: RedPajamaGithub


text:
require 'json'
require 'sqreen/event'

module Sqreen
  # When a request is deeemed worthy of being sent to the backend
  class RequestRecord < Sqreen::Event
    def observed
      (payload && payload[:observed]) || {}
    end

    def to_hash
      res = { :version => '20171208' }
      if payload[:observed]
        res[:observed] = payload[:observed].dup
        rulespack = nil
        if observed[:attacks]
          res[:observed][:attacks] = observed[:attacks].map do |att|
            natt = att.dup
            rulespack = natt.delete(:rulespack_id) || rulespack
            natt
          end
        end
        if observed[:sqreen_exceptions]
          res[:observed][:sqreen_exceptions] = observed[:sqreen_exceptions].map do |exc|
            nex = exc.dup
            excp = nex.delete(:exception)
            if excp
              nex[:message] = excp.message
              nex[:klass] = excp.class.name
            end
            rulespack = nex.delete(:rulespack_id) || rulespack
            nex
          end
        end
        res[:rulespack_id] = rulespack unless rulespack.nil?
        if observed[:observations]
          res[:observed][:observations] = observed[:observations].map do |cat, key, value, time|
            { :category => cat, :key => key, :value => value, :time => time }
          end
        end
        if observed[:sdk]
          res[:observed][:sdk] = observed[:sdk].map do |meth, time, *args|
            { :name => meth, :time => time, :args => args }
          end
        end
      end
      res[:local] = payload['local'] if payload['local']
      if payload['request']
        res[:request] = payload['request'].dup
        res[:client_ip] = res[:request].delete(:client_ip) if res[:request][:client_ip]
      else
        res[:request] = {}
      end
      res[:request][:parameters] = payload['params'] if payload['params']
      res[:request][:headers] = payload['headers'] if payload['headers']
      res
    end
  end
end


text:
package net.teamio.taam.content.conveyors;

import net.minecraft.block.SoundType;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.inventory.Container;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumFacing.Axis;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.property.ExtendedBlockState;
import net.minecraftforge.common.property.IUnlistedProperty;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.teamio.taam.Config;
import net.teamio.taam.Log;
import net.teamio.taam.Taam;
import net.teamio.taam.Taam.BLOCK_PRODUCTIONLINE_META;
import net.teamio.taam.TaamMain;
import net.teamio.taam.content.BaseBlock;
import net.teamio.taam.content.BaseTileEntity;
import net.teamio.taam.content.IRotatable;
import net.teamio.taam.content.MaterialMachinesTransparent;
import net.teamio.taam.content.common.TileEntityChute;
import net.teamio.taam.conveyors.ConveyorUtil;
import net.teamio.taam.rendering.obj.OBJModel;

public class BlockProductionLine extends BaseBlock {

	public static final PropertyEnum<Taam.BLOCK_PRODUCTIONLINE_META> VARIANT = PropertyEnum.create("variant", Taam.BLOCK_PRODUCTIONLINE_META.class);
	public static final PropertyEnum<EnumFacing> DIRECTION = PropertyEnum.create("direction", EnumFacing.class);

	public static final AxisAlignedBB BOUNDS_CONVEYORS = new AxisAlignedBB(0, 0, 0, 1, 0.5f, 1);
	public static final AxisAlignedBB BOUNDS_ELEVATOR_X = new AxisAlignedBB(ConveyorUtil.oneThird, 0, 0, 1 - ConveyorUtil.oneThird, 1, 1);
	public static final AxisAlignedBB BOUNDS_ELEVATOR_Z = new AxisAlignedBB(0, 0, ConveyorUtil.oneThird, 1, 1, 1 - ConveyorUtil.oneThird);

	public BlockProductionLine() {
		super(MaterialMachinesTransparent.INSTANCE);
		setHardness(3.5f);
		setSoundType(SoundType.METAL);
		this.setHarvestLevel("pickaxe", 1);
	}

	@Override
	protected BlockStateContainer createBlockState() {
		return new ExtendedBlockState(this, new IProperty[] { DIRECTION, VARIANT },
				new IUnlistedProperty[] { OBJModel.OBJProperty.instance });
	}

	@Override
	public int getMetaFromState(IBlockState state) {
		Taam.BLOCK_PRODUCTIONLINE_META meta = state.getValue(VARIANT);
		return meta.ordinal();
	}

	@Override
	public IBlockState getStateFromMeta(int meta) {
		Taam.BLOCK_PRODUCTIONLINE_META[] values = Taam.BLOCK_PRODUCTIONLINE_META.values();
		if (meta < 0 || meta > values.length) {
			return getDefaultState();
		}
		return getDefaultState().withProperty(VARIANT, values[meta]);
	}

	@Override
	public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos) {

		// Let the tile entity update anything that is required for rendering
		BaseTileEntity te = (BaseTileEntity) worldIn.getTileEntity(pos);
		if(te.getWorld().isRemote) {
			te.renderUpdate();
		}

		// This makes the state shows up in F3. Previously it was not actually applied on the rendering, though.
		// Rendering Transform was applied in getExtendedState
		// Since 1.9 this seems to work, though

		// Add rotation to state
		if(te instanceof IRotatable) {
			return state.withProperty(DIRECTION, ((IRotatable)te).getFacingDirection());
		}
		return state.withProperty(DIRECTION, EnumFacing.DOWN);
	}

	public String getUnlocalizedName(ItemStack itemStack) {
		int i = itemStack.getItemDamage();
		Enum<?>[] values = Taam.BLOCK_PRODUCTIONLINE_META.values();

		if (i < 0 || i >= values.length) {
			i = 0;
		}

		return super.getTranslationKey() + "." + values[i].name();
	}

	@Override
	@SideOnly(Side.CLIENT)
	public BlockRenderLayer getRenderLayer() {
		return BlockRenderLayer.CUTOUT;
	}

	@Override
	public void getSubBlocks(CreativeTabs itemIn, NonNullList<ItemStack> items) {
		Enum<?>[] values = Taam.BLOCK_PRODUCTIONLINE_META.values();
		for (int i = 0; i < values.length; i++) {
			items.add(new ItemStack(this, 1, i));
		}
	}

	@Override
	public TileEntity createTileEntity(World world, IBlockState state) {
		Taam.BLOCK_PRODUCTIONLINE_META variant = state.getValue(VARIANT);
		switch (variant) {
		case conveyor1:
			// Plain Conveyor, Tier 1
			return new TileEntityConveyor(0);
		case conveyor2:
			// Plain Conveyor, Tier 2
			return new TileEntityConveyor(1);
		case conveyor3:
			// Plain Conveyor, Tier 2
			return new TileEntityConveyor(2);
		case hopper:
			// Hopper, Regular
			return new TileEntityConveyorHopper(false);
		case hopper_hs:
			// Hopper, High-Speed
			return new TileEntityConveyorHopper(true);
		case sieve:
			// Sieve
			return new TileEntityConveyorSieve();
		case shredder:
			// Shredder
			return new TileEntityConveyorProcessor(TileEntityConveyorProcessor.Shredder);
		case grinder:
			// Grinder
			return new TileEntityConveyorProcessor(TileEntityConveyorProcessor.Grinder);
		case crusher:
			// Crusher
			return new TileEntityConveyorProcessor(TileEntityConveyorProcessor.Crusher);
		case chute:
			// Conveyor Chute
			return new TileEntityChute(true);
		case elevator:
			// Elevator
			return new TileEntityConveyorElevator();
		default:
			Log.error("Was not able to create a TileEntity for " + getClass().getName());
			return null;
		}
	}

	@Override
	public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) {
		if(state.getBlock() != TaamMain.blockProductionLine) {
			// Can only work for actual production line, else we crash with wrong variant
			return BOUNDS_CONVEYORS;
		}
		if(state.getValue(VARIANT) == BLOCK_PRODUCTIONLINE_META.elevator) {
			TileEntityConveyorElevator te = (TileEntityConveyorElevator) source.getTileEntity(pos);
			if(te != null && te.getFacingDirection().getAxis() == Axis.X) {
				return BOUNDS_ELEVATOR_X;
			}
			return BOUNDS_ELEVATOR_Z;
		}
		return BOUNDS_CONVEYORS;
	}

	@Override
	public boolean isLadder(IBlockState state, IBlockAccess world, BlockPos pos, EntityLivingBase entity) {
		if(state.getBlock() != TaamMain.blockProductionLine) {
			// Can only work for actual production line, else we crash with wrong variant
			return false;
		}
		return state.getValue(VARIANT) == BLOCK_PRODUCTIONLINE_META.elevator;
	}

	@Override
	public boolean causesSuffocation(IBlockState state) {
		return false;
	}

	@Override
	public boolean isSideSolid(IBlockState base_state, IBlockAccess world, BlockPos pos, EnumFacing side) {
		if(base_state.getBlock() != TaamMain.blockProductionLine) {
			// Can only work for actual production line, else we crash with wrong variant
			return false;
		}
		BLOCK_PRODUCTIONLINE_META variant = base_state.getValue(VARIANT);
		if(variant == BLOCK_PRODUCTIONLINE_META.elevator) {
			return side == EnumFacing.UP;
		}
		if(variant == BLOCK_PRODUCTIONLINE_META.conveyor1 ||
				variant == BLOCK_PRODUCTIONLINE_META.conveyor2 ||
				variant == BLOCK_PRODUCTIONLINE_META.conveyor3) {
			return side == EnumFacing.DOWN;
		}
		return false;
	}

	@Override
	public boolean hasComparatorInputOverride(IBlockState state) {
		return true;
	}

	@Override
	public int getComparatorInputOverride(IBlockState blockState, World worldIn, BlockPos pos) {
		TileEntity te = worldIn.getTileEntity(pos);
		return Container.calcRedstone(te);
	}

	@Override
	public boolean canBlockStay(World worldIn, BlockPos pos, IBlockState state) {
		return canPlaceBlockAt(worldIn, pos);
	}

	@Override
	public boolean canPlaceBlockAt(World world, BlockPos pos) {
		TileEntity ent = world.getTileEntity(pos);

		EnumFacing myDir;
		if (ent instanceof TileEntityConveyor) {
			myDir = ((TileEntityConveyor) ent).getFacingDirection();
		} else {
			myDir = null;
		}
		return canBlockStay(world, pos, myDir);
	}

	public static boolean canBlockStay(World world, BlockPos pos, EnumFacing myDir) {
		return checkSupport(world, pos, EnumFacing.DOWN, myDir, Config.pl_conveyor_supportrange, false)
				|| checkSupport(world, pos, EnumFacing.UP, myDir, Config.pl_conveyor_supportrange, false)
				|| checkSupport(world, pos, EnumFacing.NORTH, myDir, Config.pl_conveyor_supportrange, false)
				|| checkSupport(world, pos, EnumFacing.SOUTH, myDir, Config.pl_conveyor_supportrange, false)
				|| checkSupport(world, pos, EnumFacing.WEST, myDir, Config.pl_conveyor_supportrange, false)
				|| checkSupport(world, pos, EnumFacing.EAST, myDir, Config.pl_conveyor_supportrange, false);
	}

	public static boolean checkSupport(World world, BlockPos pos, EnumFacing side, EnumFacing myDir, int supportCount,
			boolean conveyorOnly) {
		EnumFacing otherDir = null;

		if (checkDirectSupport(world, pos)) {
			return true;
		}
		TileEntity ent = world.getTileEntity(pos.offset(side));
		if (ent instanceof TileEntityConveyor) {

			boolean checkFurther = false;

			// The other is a conveyor and we are not a conveyor (no myDir)
			if (myDir == null && !conveyorOnly) {
				switch (side) {
				case UP:
				default:
					// Up is usually not connected
					return false;
				case NORTH:
				case EAST:
				case SOUTH:
				case WEST:
				case DOWN:
					// Attach to the side of or above a conveyor
					return true;
				}
			}
			if (side == EnumFacing.UP || side == EnumFacing.DOWN) {
				// Up and Down are connected by the supports
				checkFurther = true;
			} else {
				// Only connect conveyors directly working with each
				// other (no sidealongs)
				otherDir = ((TileEntityConveyor) ent).getFacingDirection();
				checkFurther = myDir == otherDir && (myDir == side || myDir == side.getOpposite());
			}
			if (checkFurther && supportCount > 0) {
				if (checkDirectSupport(world, pos.offset(side))) {
					return true;
				}
				if (checkSupport(world, pos.offset(side), side, myDir, supportCount - 1, conveyorOnly)) {
					return true;
				}
			}
		}
		return false;
	}

	public static boolean checkDirectSupport(World world, BlockPos pos) {
		for (EnumFacing side : EnumFacing.VALUES) {
			if (world.isSideSolid(pos.offset(side), side.getOpposite())) {
				return true;
			}
		}
		return false;
	}
}


text:
declare namespace accounting {
    interface IAccountingCurrencyFormat {
        pos: string;         // for positive values, eg. "$ 1.00"
        neg?: string;        // for negative values, eg. "$ (1.00)"
        zero?: string;       // for zero values, eg. "$  --"
    }

    interface IAccountingCurrencySettings<TFormat> {
        symbol?: string;     // default currency symbol is '$'
        format?: TFormat;    // controls output: %s = symbol, %v = value/number
        decimal?: string;    // decimal point separator
        thousand?: string;   // thousands separator
        precision?: number;   // decimal places
    }

    interface IAccountingNumberSettings {
        precision?: number;  // default precision on numbers is 0
        thousand?: string;
        decimal?: string;
    }

    interface IAccountingSettings {
        currency: IAccountingCurrencySettings<any>; // IAccountingCurrencySettings<string> or IAccountingCurrencySettings<IAccountingCurrencyFormat>
        number: IAccountingNumberSettings;
    }

    interface IAccountingStatic {
        // format any number into currency
        formatMoney(number: number, symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string;
        formatMoney(number: number, options: IAccountingCurrencySettings<string> | IAccountingCurrencySettings<IAccountingCurrencyFormat>): string;

        formatMoney(numbers: number[], symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string[];
        formatMoney(numbers: number[], options: IAccountingCurrencySettings<string> | IAccountingCurrencySettings<IAccountingCurrencyFormat>): string[];

        // generic case (any array of numbers)
        formatMoney(numbers: any[], symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): any[];
        formatMoney(numbers: any[], options: IAccountingCurrencySettings<string> | IAccountingCurrencySettings<IAccountingCurrencyFormat>): any[];

        // format a list of values for column-display
        formatColumn(numbers: number[], symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string[];
        formatColumn(numbers: number[], options: IAccountingCurrencySettings<string> | IAccountingCurrencySettings<IAccountingCurrencyFormat>): string[];

        formatColumn(numbers: number[][], symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string[][];
        formatColumn(numbers: number[][], options: IAccountingCurrencySettings<string> | IAccountingCurrencySettings<IAccountingCurrencyFormat>): string[][];

        // format a number with custom precision and localisation
        formatNumber(number: number, precision?: number, thousand?: string, decimal?: string): string;
        formatNumber(number: number, options: IAccountingNumberSettings): string;

        formatNumber(number: number[], precision?: number, thousand?: string, decimal?: string): string[];
        formatNumber(number: number[], options: IAccountingNumberSettings): string[];

        formatNumber(number: any[], precision?: number, thousand?: string, decimal?: string): any[];
        formatNumber(number: any[], options: IAccountingNumberSettings): any[];

        // better rounding for floating point numbers
        toFixed(number: number, precision?: number): string;

        // get a value from any formatted number/currency string
        unformat(string: string, decimal?: string): number;

        // settings object that controls default parameters for library methods
        settings: IAccountingSettings;
    }
}

declare var accounting: accounting.IAccountingStatic;
export = accounting;
export as namespace accounting;


text:
namespace base {
class PortProvider;
}  // namespace base

namespace IPC {

// This class is a concrete subclass of AttachmentBrokerPrivileged for the
// OSX platform.
//
// An example of the typical process by which a Mach port gets brokered.
// Definitions:
//   1. Let there be three processes P1, U2, U3. P1 is privileged.
//   2. U2 wants to send a Mach port M2 to U3. If this port is inserted into P1,
//   it will be called M1. If it is inserted into U3, it will be called M3.
//   3. name() returns a serializable representation of a Mach port that can be
//   passed over chrome IPC.
//   4. pid() returns the process id of a process.
//
// Process:
//   1. U2 sends a AttachmentBrokerMsg_DuplicateMachPort message to P1. The
//   message contains name(M2), and pid(U3).
//   2. P1 extracts M2 into its own namespace, making M1.
//   3. P1 makes a new Mach port R in U3.
//   4. P1 sends a mach_msg with M1 to R.
//   5. P1 sends name(R) to U3.
//   6. U3 retrieves the queued message from R. The kernel automatically
//   translates M1 into the namespace of U3, making M3.
//
// The logic of this class is a little bit more complex becauese any or all of
// P1, U2 and U3 may be the same, and depending on the exact configuration,
// the creation of R may not be necessary.
//
// For the rest of this file, and the corresponding implementation file, R will
// be called the "intermediate Mach port" and M3 the "final Mach port".
class IPC_EXPORT AttachmentBrokerPrivilegedMac
    : public AttachmentBrokerPrivileged,
      public base::PortProvider::Observer {
 public:
  explicit AttachmentBrokerPrivilegedMac(base::PortProvider* port_provider);
  ~AttachmentBrokerPrivilegedMac() override;

  // IPC::AttachmentBroker overrides.
  bool SendAttachmentToProcess(
      const scoped_refptr<IPC::BrokerableAttachment>& attachment,
      base::ProcessId destination_process) override;
  void DeregisterCommunicationChannel(Endpoint* endpoint) override;

  // IPC::Listener overrides.
  bool OnMessageReceived(const Message& message) override;

  // base::PortProvider::Observer override.
  void OnReceivedTaskPort(base::ProcessHandle process) override;

 private:
  FRIEND_TEST_ALL_PREFIXES(AttachmentBrokerPrivilegedMacMultiProcessTest,
                           InsertRight);
  FRIEND_TEST_ALL_PREFIXES(AttachmentBrokerPrivilegedMacMultiProcessTest,
                           InsertSameRightTwice);
  FRIEND_TEST_ALL_PREFIXES(AttachmentBrokerPrivilegedMacMultiProcessTest,
                           InsertTwoRights);
  using MachPortWireFormat = internal::MachPortAttachmentMac::WireFormat;

  // Contains all the information necessary to broker an attachment into a
  // destination process. The only thing that prevents an AttachmentPrecusor
  // from being immediately processed is if |port_provider_| does not yet have a
  // task port for |pid|.
  class IPC_EXPORT AttachmentPrecursor {
   public:
    AttachmentPrecursor(const base::ProcessId& pid,
                        base::mac::ScopedMachSendRight port_to_insert,
                        const BrokerableAttachment::AttachmentId& id);
    ~AttachmentPrecursor();

    // Caller takes ownership of |port_|.
    base::mac::ScopedMachSendRight TakePort();

    base::ProcessId pid() const { return pid_; }
    const BrokerableAttachment::AttachmentId id() const { return id_; }

   private:
    // The pid of the destination process.
    const base::ProcessId pid_;
    // The final Mach port, as per definition at the top of this file.
    base::mac::ScopedMachSendRight port_;
    // The id of the attachment.
    const BrokerableAttachment::AttachmentId id_;
    DISALLOW_COPY_AND_ASSIGN(AttachmentPrecursor);
  };

  // Contains all the information necessary to extract a send right and create
  // an AttachmentPrecursor. The only thing that prevents an AttachmentExtractor
  // from being immediately processed is if |port_provider_| does not yet have a
  // task port for |source_pid|.
  class IPC_EXPORT AttachmentExtractor {
   public:
    AttachmentExtractor(const base::ProcessId& source_pid,
                        const base::ProcessId& dest_pid,
                        mach_port_name_t port,
                        const BrokerableAttachment::AttachmentId& id);
    ~AttachmentExtractor();

    base::ProcessId source_pid() const { return source_pid_; }
    base::ProcessId dest_pid() const { return dest_pid_; }
    mach_port_name_t port() const { return port_to_extract_; }
    const BrokerableAttachment::AttachmentId id() const { return id_; }

   private:
    const base::ProcessId source_pid_;
    const base::ProcessId dest_pid_;
    mach_port_name_t port_to_extract_;
    const BrokerableAttachment::AttachmentId id_;
  };

  // IPC message handlers.
  void OnDuplicateMachPort(const Message& message);

  // Duplicates the Mach port referenced from |wire_format| from
  // |source_process| into |wire_format|'s destination process.
  MachPortWireFormat DuplicateMachPort(const MachPortWireFormat& wire_format,
                                       base::ProcessId source_process);

  // |task_port| is the task port of another process.
  // |port_to_insert| must be a send right in the current task's name space.
  // Creates an intermediate Mach port in |pid| and sends |port_to_insert| as a
  // mach_msg to the intermediate Mach port.
  // Returns the intermediate port on success, and MACH_PORT_NULL on failure.
  // This method takes ownership of |port_to_insert|. On success, ownership is
  // passed to the intermediate Mach port.
  mach_port_name_t CreateIntermediateMachPort(
      mach_port_t task_port,
      base::mac::ScopedMachSendRight port_to_insert);

  // Extracts a copy of the send right to |named_right| from |task_port|.
  // Returns MACH_PORT_NULL on error.
  base::mac::ScopedMachSendRight ExtractNamedRight(
      mach_port_t task_port,
      mach_port_name_t named_right);

  // Copies an existing |wire_format|, but substitutes in a different mach port.
  MachPortWireFormat CopyWireFormat(const MachPortWireFormat& wire_format,
                                    uint32_t mach_port);

  // |wire_format.destination_process| must be this process.
  // |wire_format.mach_port| must be the final Mach port.
  // Consumes a reference to |wire_format.mach_port|, as ownership is implicitly
  // passed to the consumer of the Chrome IPC message.
  // Makes an attachment, queues it, and notifies the observers.
  void RoutePrecursorToSelf(AttachmentPrecursor* precursor);

  // |wire_format.destination_process| must be another process.
  // |wire_format.mach_port| must be the intermediate Mach port.
  // Ownership of |wire_format.mach_port| is implicitly passed to the process
  // that receives the Chrome IPC message.
  // Returns |false| on irrecoverable error.
  bool RouteWireFormatToAnother(const MachPortWireFormat& wire_format);

  // Atempts to broker all precursors whose destination is |pid|. Has no effect
  // if |port_provider_| does not have the task port for |pid|.
  void SendPrecursorsForProcess(base::ProcessId pid);

  // Brokers a single precursor into the task represented by |task_port|.
  // Returns |false| on irrecoverable error.
  bool SendPrecursor(AttachmentPrecursor* precursor, mach_port_t task_port);

  // Add a precursor to |precursors_|. Takes ownership of |port|.
  void AddPrecursor(base::ProcessId pid,
                    base::mac::ScopedMachSendRight port,
                    const BrokerableAttachment::AttachmentId& id);

  // Atempts to process all extractors whose source is |pid|. Has no effect
  // if |port_provider_| does not have the task port for |pid|.
  void ProcessExtractorsForProcess(base::ProcessId pid);

  // Processes a single extractor whose source pid is represented by
  // |task_port|.
  void ProcessExtractor(AttachmentExtractor* extractor, mach_port_t task_port);

  // Add an extractor to |extractors_|.
  void AddExtractor(base::ProcessId source_pid,
                    base::ProcessId dest_pid,
                    mach_port_name_t port,
                    const BrokerableAttachment::AttachmentId& id);

  // The port provider must live at least as long as the AttachmentBroker.
  base::PortProvider* port_provider_;

  // For each ProcessId, a vector of precursors that are waiting to be
  // sent.
  std::map<base::ProcessId, ScopedVector<AttachmentPrecursor>*> precursors_;
  base::Lock precursors_lock_;

  // For each ProcessId, a vector of extractors that are waiting to be
  // processed.
  std::map<base::ProcessId, ScopedVector<AttachmentExtractor>*> extractors_;
  base::Lock extractors_lock_;

  DISALLOW_COPY_AND_ASSIGN(AttachmentBrokerPrivilegedMac);
};

}  // namespace IPC

#endif  // IPC_ATTACHMENT_BROKER_PRIVILEGED_MAC_H_


text:
var app = angular.module('gitHubUserInfo', [], function($interpolateProvider) {
  $interpolateProvider.startSymbol('[[');
  $interpolateProvider.endSymbol(']]');
});

app.controller('userInfoCtrl', function($scope, $http) {
	var onSuccess = function(response) {
        $scope.user = response.data;
    };

    var onFailure = function(failureReason) {
        $scope.failureMsg = failureReason.data;
        $scope.user = null;
    };

    $http.get('https://api.github.com/users/PrashanthAmbure')
        .then(onSuccess, onFailure);
});


text:
package com.microsoft.azure.management.resources.fluentcore.arm.collection.implementation;

import com.microsoft.azure.PagedList;
import com.microsoft.azure.management.apigeneration.LangDefinition;
import com.microsoft.azure.management.resources.fluentcore.arm.ResourceId;
import com.microsoft.azure.management.resources.fluentcore.arm.collection.SupportsDeletingByParent;
import com.microsoft.azure.management.resources.fluentcore.arm.collection.SupportsGettingById;
import com.microsoft.azure.management.resources.fluentcore.arm.collection.SupportsGettingByParent;
import com.microsoft.azure.management.resources.fluentcore.arm.collection.SupportsListingByParent;
import com.microsoft.azure.management.resources.fluentcore.arm.implementation.ManagerBase;
import com.microsoft.azure.management.resources.fluentcore.arm.models.HasManager;
import com.microsoft.azure.management.resources.fluentcore.arm.models.HasResourceGroup;
import com.microsoft.azure.management.resources.fluentcore.arm.models.IndependentChild;
import com.microsoft.azure.management.resources.fluentcore.arm.models.Resource;
import com.microsoft.azure.management.resources.fluentcore.collection.SupportsDeletingById;
import com.microsoft.azure.management.resources.fluentcore.model.HasInner;
import com.microsoft.rest.ServiceFuture;
import com.microsoft.rest.ServiceCallback;
import rx.Completable;
import rx.Observable;

/**
 * Base class for independent child collection class.
 * (Internal use only)
 * @param <T> the individual resource type returned
 * @param <ImplT> the individual resource implementation
 * @param <InnerT> the wrapper inner type
 * @param <InnerCollectionT> the inner type of the collection object
 * @param <ManagerT> the manager type for this resource provider type
 * @param <ParentT> the type of the parent resource
 */
@LangDefinition
public abstract class IndependentChildrenImpl<
        T extends IndependentChild<ManagerT>,
        ImplT extends T,
        InnerT,
        InnerCollectionT,
        ManagerT extends ManagerBase,
        ParentT extends Resource & HasResourceGroup>
    extends CreatableResourcesImpl<T, ImplT, InnerT>
    implements
        SupportsGettingById<T>,
        SupportsGettingByParent<T, ParentT, ManagerT>,
        SupportsListingByParent<T, ParentT, ManagerT>,
        SupportsDeletingById,
        SupportsDeletingByParent,
        HasManager<ManagerT>,
        HasInner<InnerCollectionT> {
    protected final InnerCollectionT innerCollection;
    protected final ManagerT manager;

    protected IndependentChildrenImpl(InnerCollectionT innerCollection, ManagerT manager) {
        this.innerCollection = innerCollection;
        this.manager = manager;
    }

    @Override
    public InnerCollectionT inner() {
        return this.innerCollection;
    }

    @Override
    public T getByParent(String resourceGroup, String parentName, String name) {
        return getByParentAsync(resourceGroup, parentName, name).toBlocking().last();
    }

    @Override
    public T getByParent(ParentT parentResource, String name) {
        return getByParentAsync(parentResource, name).toBlocking().last();
    }

    @Override
    public Observable<T> getByParentAsync(ParentT parentResource, String name) {
        return getByParentAsync(parentResource.resourceGroupName(), parentResource.name(), name);
    }

    @Override
    public T getById(String id) {
        return getByIdAsync(id).toBlocking().last();
    }

    @Override
    public Observable<T> getByIdAsync(String id) {
        ResourceId resourceId = ResourceId.fromString(id);
        if (resourceId == null) {
            return null;
        }

        return getByParentAsync(resourceId.resourceGroupName(), resourceId.parent().name(), resourceId.name());
    }

    @Override
    public ServiceFuture<T> getByIdAsync(String id, ServiceCallback<T> callback) {
        return ServiceFuture.fromBody(getByIdAsync(id), callback);
    }

    @Override
    public PagedList<T> listByParent(ParentT parentResource) {
        return listByParent(parentResource.resourceGroupName(), parentResource.name());
    }

    @Override
    public void deleteByParent(String groupName, String parentName, String name) {
        deleteByParentAsync(groupName, parentName, name).await();
    }

    @Override
    public ServiceFuture<Void> deleteByParentAsync(String groupName, String parentName, String name, ServiceCallback<Void> callback) {
        return ServiceFuture.fromBody(deleteByParentAsync(groupName, parentName, name).<Void>toObservable(), callback);
    }

    @Override
    public Completable deleteByIdAsync(String id) {
        ResourceId resourceId = ResourceId.fromString(id);
        return deleteByParentAsync(resourceId.resourceGroupName(), resourceId.parent().name(), resourceId.name());
    }

    @Override
    public ManagerT manager() {
        return this.manager;
    }
}


text:
#ifndef __INCLUDE_NUTTX_BINFMT_NXFLAT_H
#define __INCLUDE_NUTTX_BINFMT_NXFLAT_H

/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <nuttx/config.h>

#include <stdint.h>
#include <nxflat.h>

#include <nuttx/sched.h>
#include <nuttx/arch.h>

/****************************************************************************
 * Pre-processor Definitions
 ****************************************************************************/

/****************************************************************************
 * Public Types
 ****************************************************************************/

/* This struct provides a desciption of the currently loaded instantiation
 * of an nxflat binary.
 */

struct nxflat_loadinfo_s
{
  /* Instruction Space (ISpace):  This region contains the nxflat file header
   * plus everything from the text section.
   *
   * The ISpace region is allocated using mmap() and, thus, can be shared by
   * multiple tasks.  Ideally, will have only one mmap'ed text section
   * instance in the system for each module.
   */

  uintptr_t ispace;        /* Address where hdr/text is loaded */
  uint32_t entryoffs;      /* Offset from ispace to entry point */
  uint32_t isize;          /* Size of ispace. */

  /* Data Space (DSpace): This region contains all information that is
   * referenced as data (other than the stack which is separately allocated).
   *
   * If CONFIG_ARCH_ADDRENV=n, DSpace will be allocated using kmm_malloc() (or
   * kmm_zalloc()).  If CONFIG_ARCH_ADDRENV-y, then DSpace will be allocated using
   * up_addrenv_create().  In either case, there will be a unique instance
   * of DSpace (and stack) for each instance of a process.
   */

  struct dspace_s *dspace; /* Allocated D-Space (data/bss/etc) */
  uint32_t datasize;       /* Size of data segment in dspace */
  uint32_t bsssize;        /* Size of bss segment in dspace */
  uint32_t stacksize;      /* Size of stack (not allocated) */
  uint32_t dsize;          /* Size of dspace (may be large than parts) */

  /* This is temporary memory where relocation records will be loaded. */

  uint32_t relocstart;     /* Start of array of struct flat_reloc */
  uint16_t reloccount;     /* Number of elements in reloc array */

  /* Address environment.
   *
   * addrenv - This is the handle created by up_addrenv_create() that can be
   *   used to manage the tasks address space.
   * oldenv  - This is a value returned by up_addrenv_select() that must be
   *   used to restore the current address environment.
   */

#ifdef CONFIG_ARCH_ADDRENV
  group_addrenv_t addrenv; /* Task group address environment */
  save_addrenv_t oldenv;   /* Saved address environment */
#endif

  /* File descriptors */

  int filfd;               /* Descriptor for the file being loaded */

  /* This is a copy of the NXFLAT header (still in network order) */

  struct nxflat_hdr_s header;
};

/****************************************************************************
 * Public Functions
 ****************************************************************************/

#undef EXTERN
#if defined(__cplusplus)
#define EXTERN extern "C"
extern "C" {
#else
#define EXTERN extern
#endif

/****************************************************************************
 * These are APIs exported by libnxflat (and may be used outside of NuttX):
 ****************************************************************************/

/****************************************************************************
 * Name: nxflat_verifyheader
 *
 * Description:
 *   Given the header from a possible NXFLAT executable, verify that it is
 *   an NXFLAT executable.
 *
 * Returned Value:
 *   0 (OK) is returned on success and a negated errno is returned on
 *   failure.
 *
 ****************************************************************************/

int nxflat_verifyheader(const struct nxflat_hdr_s *header);

/****************************************************************************
 * Name: nxflat_init
 *
 * Description:
 *   This function is called to configure the library to process an NXFLAT
 *   program binary.
 *
 * Returned Value:
 *   0 (OK) is returned on success and a negated errno is returned on
 *   failure.
 *
 ****************************************************************************/

int nxflat_init(const char *filename, struct nxflat_loadinfo_s *loadinfo);

/****************************************************************************
 * Name: nxflat_uninit
 *
 * Description:
 *   Releases any resources committed by nxflat_init().  This essentially
 *   undoes the actions of nxflat_init.
 *
 * Returned Value:
 *   0 (OK) is returned on success and a negated errno is returned on
 *   failure.
 *
 ****************************************************************************/

int nxflat_uninit(struct nxflat_loadinfo_s *loadinfo);

/****************************************************************************
 * Name: nxflat_load
 *
 * Description:
 *   Loads the binary specified by nxflat_init into memory, mapping
 *   the I-space executable regions, allocating the D-Space region,
 *   and initializing the data segment (relocation information is
 *   temporarily loaded into the BSS region.  BSS will be cleared
 *   by nxflat_bind() after the relocation data has been processed).
 *
 * Returned Value:
 *   0 (OK) is returned on success and a negated errno is returned on
 *   failure.
 *
 ****************************************************************************/

int nxflat_load(struct nxflat_loadinfo_s *loadinfo);

/****************************************************************************
 * Name: nxflat_read
 *
 * Description:
 *   Read 'readsize' bytes from the object file at 'offset'
 *
 * Returned Value:
 *   0 (OK) is returned on success and a negated errno is returned on
 *   failure.
 *
 ****************************************************************************/

int nxflat_read(struct nxflat_loadinfo_s *loadinfo, char *buffer,
                int readsize, int offset);

/****************************************************************************
 * Name: nxflat_bind
 *
 * Description:
 *   Bind the imported symbol names in the loaded module described by
 *   'loadinfo' using the exported symbol values provided by 'symtab'
 *   After binding the module, clear the BSS region (which held the relocation
 *   data) in preparation for execution.
 *
 * Returned Value:
 *   0 (OK) is returned on success and a negated errno is returned on
 *   failure.
 *
 ****************************************************************************/

struct symtab_s;
int nxflat_bind(FAR struct nxflat_loadinfo_s *loadinfo,
                FAR const struct symtab_s *exports, int nexports);

/****************************************************************************
 * Name: nxflat_unload
 *
 * Description:
 *   This function unloads the object from memory. This essentially undoes
 *   the actions of nxflat_load.  It is called only under certain error
 *   conditions after the module has been loaded but not yet started.
 *
 * Returned Value:
 *   0 (OK) is returned on success and a negated errno is returned on
 *   failure.
 *
 ****************************************************************************/

int nxflat_unload(struct nxflat_loadinfo_s *loadinfo);

/****************************************************************************
 * These are APIs used internally only by NuttX:
 ****************************************************************************/
/***********************************************************************
 * Name: nxflat_initialize
 *
 * Description:
 *   NXFLAT support is built unconditionally.  However, in order to
 *   use this binary format, this function must be called during system
 *   initialization in order to register the NXFLAT binary format.
 *
 * Returned Value:
 *   This is a NuttX internal function so it follows the convention that
 *   0 (OK) is returned on success and a negated errno is returned on
 *   failure.
 *
 ***********************************************************************/

int nxflat_initialize(void);

/****************************************************************************
 * Name: nxflat_uninitialize
 *
 * Description:
 *   Unregister the NXFLAT binary loader
 *
 * Returned Value:
 *   None
 *
 ****************************************************************************/

void nxflat_uninitialize(void);

#undef EXTERN
#if defined(__cplusplus)
}
#endif

#endif /* __INCLUDE_NUTTX_BINFMT_NXFLAT_H */


text:
import get from './get'
import isEqual from './isEqual'
import isObject from './isObject'

export default function isIterateeCall(value, index, object) {
  if (!isObject(object)) {
    return false
  }
  return isEqual(get(object, index), value)
}


text:
 # -*- coding: utf-8 -*-

import arrow
import datetime
import ujson
import timeit

from flask.ext.login import login_required

from flask import (
    Blueprint, render_template
)

from feedback.dashboard.vendorsurveys import (
    get_rating_scale, get_surveys_by_role,
    get_surveys_by_completion, get_surveys_by_purpose,
    get_all_survey_responses, get_rating_by_lang,
    get_rating_by_purpose, get_rating_by_role
)

from feedback.surveys.constants import SURVEY_DAYS
from feedback.surveys.models import Survey

from feedback.dashboard.permits import (
    api_health, get_lifespan,
    get_permit_types, trade,
    get_master_permit_counts,
    dump_socrata_api
)

blueprint = Blueprint(
    "dashboard", __name__,
    template_folder='../templates',
    static_folder="../static"
)

def to_bucket(str_date):
    ''' Converts the DB string time to a MM-DD string format.
    '''
    result = arrow.get(str_date)
    return result.strftime("%m-%d")

@blueprint.route("/", methods=["GET", "POST"])
def home():

    json_obj = {}
    json_obj_home = {}

    surveys_by_date = {}
    surveys_date_array = []
    surveys_value_array = []

    for i in range(SURVEY_DAYS, -1, -1):
        time_i = (datetime.date.today() - datetime.timedelta(i))
        date_index = time_i.strftime("%m-%d")
        surveys_by_date[date_index] = 0
        surveys_date_array.append(date_index)

    survey_table = get_all_survey_responses(SURVEY_DAYS)

    sms_rows = [x.lang for x in survey_table if x.method == 'sms']
    web_rows = [x.lang for x in survey_table if x.method == 'web']

    # ANALYTICS CODE
    for i in range(SURVEY_DAYS, -1, -1):
        time_i = (datetime.date.today() - datetime.timedelta(i))
        date_index = time_i.strftime("%m-%d")
        surveys_value_array.append(
            len([x for x in survey_table if to_bucket(x.date_submitted) == date_index]))

    dashboard_collection_home = [
        {
            "id": "graph",
            "title": "Surveys Submitted".format(SURVEY_DAYS),
            "data": {
                "graph": {
                    "datetime": {
                        "data": surveys_date_array
                    },
                    "series": [
                        {
                            "data": surveys_value_array
                        }
                    ]
                }
            }
        },
        {
            "title": "Satisfaction Rating".format(SURVEY_DAYS),
            "data": "{0:.2f}".format(get_rating_scale(survey_table))
        },
        {
            "title": "Survey Type".format(SURVEY_DAYS),
            "data": {
                "web_en": web_rows.count('en'),
                "web_es": web_rows.count('es'),
                "sms_en": sms_rows.count('en'),
                "sms_es": sms_rows.count('es')
            },
            "labels": {
                "web_en": "Web (English)",
                "web_es": "Web (Spanish)",
                "sms_en": "Text (English)",
                "sms_es": "Text (Spanish)"
            }
        },
        {},
        {},
        {},
        {},
        {},
        {},
        {},
        {
            "title": "Surveys by Survey Role",
            "data": get_surveys_by_role(survey_table)
        },
        {},
        {
            "title": "How many completions?",
            "data": get_surveys_by_completion(survey_table)
        },
        {
            "title": "Respondents by Purpose",
            "data": get_surveys_by_purpose(survey_table)
        },
        {
            "title": "Ratings",
            "data": {
                "en": get_rating_by_lang(survey_table, 'en'),
                "es": get_rating_by_lang(survey_table, 'es'),
                "p1": get_rating_by_purpose(survey_table, 1),
                "p2": get_rating_by_purpose(survey_table, 2),
                "p3": get_rating_by_purpose(survey_table, 3),
                "p4": get_rating_by_purpose(survey_table, 4),
                "p5": get_rating_by_purpose(survey_table, 5),
                "contractor": get_rating_by_role(survey_table, 1),
                "architect": get_rating_by_role(survey_table, 2),
                "permitconsultant": get_rating_by_role(survey_table, 3),
                "homeowner": get_rating_by_role(survey_table, 4),
                "bizowner": get_rating_by_role(survey_table, 5)
            }
        }
    ]

    json_obj_home['daily_graph'] = ujson.dumps(dashboard_collection_home[0]['data']['graph'])
    json_obj_home['surveys_type'] = ujson.dumps(dashboard_collection_home[2])
    json_obj_home['survey_role'] = ujson.dumps(dashboard_collection_home[10])
    json_obj_home['survey_complete'] = ujson.dumps(dashboard_collection_home[12])
    json_obj_home['survey_purpose'] = ujson.dumps(dashboard_collection_home[13])

    today = datetime.date.today()

    return render_template(
        "public/home.html",
        api=1,
        date=today.strftime('%B %d, %Y'),
        json_obj=json_obj_home,
        dash_obj=dashboard_collection_home,
        resp_obj=survey_table,
        title='Dashboard - Main'
        )

@blueprint.route("/metrics", methods=["GET", "POST"])
def metrics():

    json_obj = {}

    surveys_by_date = {}
    surveys_date_array = []
    surveys_value_array = []

    for i in range(SURVEY_DAYS, -1, -1):
        time_i = (datetime.date.today() - datetime.timedelta(i))
        date_index = time_i.strftime("%m-%d")
        surveys_by_date[date_index] = 0
        surveys_date_array.append(date_index)

    survey_table = get_all_survey_responses(SURVEY_DAYS)

    sms_rows = [x.lang for x in survey_table if x.method == 'sms']
    web_rows = [x.lang for x in survey_table if x.method == 'web']

    # ANALYTICS CODE
    for i in range(SURVEY_DAYS, -1, -1):
        time_i = (datetime.date.today() - datetime.timedelta(i))
        date_index = time_i.strftime("%m-%d")
        surveys_value_array.append(
            len([x for x in survey_table if to_bucket(x.date_submitted) == date_index]))

    dashboard_collection = [
        {
            "id": "graph",
            "title": "Surveys Submitted".format(SURVEY_DAYS),
            "data": {
                "graph": {
                    "datetime": {
                        "data": surveys_date_array
                    },
                    "series": [
                        {
                            "data": surveys_value_array
                        }
                    ]
                }
            }
        },
        {
            "title": "Satisfaction Rating".format(SURVEY_DAYS),
            "data": "{0:.2f}".format(get_rating_scale(survey_table))
        },
        {
            "title": "Survey Type".format(SURVEY_DAYS),
            "data": {
                "web_en": web_rows.count('en'),
                "web_es": web_rows.count('es'),
                "sms_en": sms_rows.count('en'),
                "sms_es": sms_rows.count('es')
            },
            "labels": {
                "web_en": "Web (English)",
                "web_es": "Web (Spanish)",
                "sms_en": "Text (English)",
                "sms_es": "Text (Spanish)"
            }
        },
        {
            "title": "Commercial",
            "data": {
                "nc": get_lifespan('nc'),
                "rc": get_lifespan('rc'),
                "s":  get_lifespan('s')
            }
        },
        {
            "title": "Residential",
            "data": {
                "nr": get_lifespan('nr'),
                "rr": get_lifespan('rr'),
                "p":  get_lifespan('p'),
                "f":  get_lifespan('f'),
                "e":  get_lifespan('e')
            }
        },
        {
            "title": "Average time from application date to permit issuance, Owner/Builder Permits, Last 30 Days",
            "data": 0
        },
        {
            "title": "Same Day Trade Permits",
            "data": {
                "PLUM": trade(30, 'PLUM'),
                "BLDG": trade(30, 'BLDG'),
                "ELEC": trade(30, 'ELEC'),
                "FIRE": trade(30, 'FIRE'),
                "ZIPS": trade(30, 'ZIPS')
            }
        },
        {
            "title": "(UNUSED) Avg Cost of an Open Residential Permit",
            "data": 0
        },
        {
            "title": "(UNUSED) Avg Cost of an Owner/Builder Permit",
            "data": 0
        },
        {
            "title": "Permits & sub-permits issued by type, Last 30 Days",
            "data": get_permit_types()
        },
        {
            "title": "Surveys by Survey Role",
            "data": get_surveys_by_role(survey_table)
        },
        {
            "title": "Master Permits Issued, Last 30 Days",
            "data": get_master_permit_counts('permit_issued_date')
        },
        {
            "title": "How many completions?",
            "data": get_surveys_by_completion(survey_table)
        },
        {
            "title": "Purpose",
            "data": get_surveys_by_purpose(survey_table)
        },
        {
            "title": "Ratings",
            "data": {
                "en": get_rating_by_lang(survey_table, 'en'),
                "es": get_rating_by_lang(survey_table, 'es'),
                "p1": get_rating_by_purpose(survey_table, 1),
                "p2": get_rating_by_purpose(survey_table, 2),
                "p3": get_rating_by_purpose(survey_table, 3),
                "p4": get_rating_by_purpose(survey_table, 4),
                "p5": get_rating_by_purpose(survey_table, 5),
                "contractor": get_rating_by_role(survey_table, 1),
                "architect": get_rating_by_role(survey_table, 2),
                "permitconsultant": get_rating_by_role(survey_table, 3),
                "homeowner": get_rating_by_role(survey_table, 4),
                "bizowner": get_rating_by_role(survey_table, 5)
            }
        }
    ]

    json_obj['daily_graph'] = ujson.dumps(dashboard_collection[0]['data']['graph'])
    json_obj['surveys_type'] = ujson.dumps(dashboard_collection[2])
    json_obj['permits_type'] = ujson.dumps(dashboard_collection[9])
    json_obj['survey_role'] = ujson.dumps(dashboard_collection[10])
    json_obj['survey_complete'] = ujson.dumps(dashboard_collection[12])
    json_obj['survey_purpose'] = ujson.dumps(dashboard_collection[13])
    json_obj['permits_rawjson'] = ujson.dumps(dump_socrata_api('p'))
    json_obj['violations_rawjson'] = ujson.dumps(dump_socrata_api('v'))
    json_obj['violations_locations_json'] = ujson.dumps(dump_socrata_api('vl'))
    json_obj['violations_type_json'] = ujson.dumps(dump_socrata_api('vt'))
    json_obj['violations_per_month_json'] = ujson.dumps(dump_socrata_api('vm'))

    today = datetime.date.today()

    return render_template(
        "public/home-metrics.html",
        api=api_health(),
        date=today.strftime('%B %d, %Y'),
        json_obj=json_obj,
        dash_obj=dashboard_collection,
        resp_obj=survey_table,
        title='Dashboard - PIC Metrics'
        )

@blueprint.route("/violations", methods=["GET", "POST"])
def violations():

    json_obj = {}

    surveys_by_date = {}
    surveys_date_array = []
    surveys_value_array = []

    for i in range(SURVEY_DAYS, -1, -1):
        time_i = (datetime.date.today() - datetime.timedelta(i))
        date_index = time_i.strftime("%m-%d")
        surveys_by_date[date_index] = 0
        surveys_date_array.append(date_index)

    survey_table = get_all_survey_responses(SURVEY_DAYS)

    sms_rows = [x.lang for x in survey_table if x.method == 'sms']
    web_rows = [x.lang for x in survey_table if x.method == 'web']

    # ANALYTICS CODE
    for i in range(SURVEY_DAYS, -1, -1):
        time_i = (datetime.date.today() - datetime.timedelta(i))
        date_index = time_i.strftime("%m-%d")
        surveys_value_array.append(
            len([x for x in survey_table if to_bucket(x.date_submitted) == date_index]))

    dashboard_collection = [
        {
            "id": "graph",
            "title": "Surveys Submitted".format(SURVEY_DAYS),
            "data": {
                "graph": {
                    "datetime": {
                        "data": surveys_date_array
                    },
                    "series": [
                        {
                            "data": surveys_value_array
                        }
                    ]
                }
            }
        },
        {
            "title": "Satisfaction Rating".format(SURVEY_DAYS),
            "data": "{0:.2f}".format(get_rating_scale(survey_table))
        },
        {
            "title": "Survey Type".format(SURVEY_DAYS),
            "data": {
                "web_en": web_rows.count('en'),
                "web_es": web_rows.count('es'),
                "sms_en": sms_rows.count('en'),
                "sms_es": sms_rows.count('es')
            },
            "labels": {
                "web_en": "Web (English)",
                "web_es": "Web (Spanish)",
                "sms_en": "Text (English)",
                "sms_es": "Text (Spanish)"
            }
        },
        {
            "title": "Commercial",
            "data": {
                "nc": get_lifespan('nc'),
                "rc": get_lifespan('rc'),
                "s":  get_lifespan('s')
            }
        },
        {
            "title": "Residential",
            "data": {
                "nr": get_lifespan('nr'),
                "rr": get_lifespan('rr'),
                "p":  get_lifespan('p'),
                "f":  get_lifespan('f'),
                "e":  get_lifespan('e')
            }
        },
        {
            "title": "Average time from application date to permit issuance, Owner/Builder Permits, Last 30 Days",
            "data": 0
        },
        {
            "title": "Same Day Trade Permits",
            "data": {
                "PLUM": trade(30, 'PLUM'),
                "BLDG": trade(30, 'BLDG'),
                "ELEC": trade(30, 'ELEC'),
                "FIRE": trade(30, 'FIRE'),
                "ZIPS": trade(30, 'ZIPS')
            }
        },
        {
            "title": "(UNUSED) Avg Cost of an Open Residential Permit",
            "data": 0
        },
        {
            "title": "(UNUSED) Avg Cost of an Owner/Builder Permit",
            "data": 0
        },
        {
            "title": "Permits & sub-permits issued by type, Last 30 Days",
            "data": get_permit_types()
        },
        {
            "title": "Surveys by Survey Role",
            "data": get_surveys_by_role(survey_table)
        },
        {
            "title": "Master Permits Issued, Last 30 Days",
            "data": get_master_permit_counts('permit_issued_date')
        },
        {
            "title": "How many completions?",
            "data": get_surveys_by_completion(survey_table)
        },
        {
            "title": "Purpose",
            "data": get_surveys_by_purpose(survey_table)
        },
        {
            "title": "Ratings",
            "data": {
                "en": get_rating_by_lang(survey_table, 'en'),
                "es": get_rating_by_lang(survey_table, 'es'),
                "p1": get_rating_by_purpose(survey_table, 1),
                "p2": get_rating_by_purpose(survey_table, 2),
                "p3": get_rating_by_purpose(survey_table, 3),
                "p4": get_rating_by_purpose(survey_table, 4),
                "p5": get_rating_by_purpose(survey_table, 5),
                "contractor": get_rating_by_role(survey_table, 1),
                "architect": get_rating_by_role(survey_table, 2),
                "permitconsultant": get_rating_by_role(survey_table, 3),
                "homeowner": get_rating_by_role(survey_table, 4),
                "bizowner": get_rating_by_role(survey_table, 5)
            }
        }
    ]

    json_obj['daily_graph'] = ujson.dumps(dashboard_collection[0]['data']['graph'])
    json_obj['surveys_type'] = ujson.dumps(dashboard_collection[2])
    json_obj['permits_type'] = ujson.dumps(dashboard_collection[9])
    json_obj['survey_role'] = ujson.dumps(dashboard_collection[10])
    json_obj['survey_complete'] = ujson.dumps(dashboard_collection[12])
    json_obj['survey_purpose'] = ujson.dumps(dashboard_collection[13])
    json_obj['permits_rawjson'] = ujson.dumps(dump_socrata_api('p'))
    json_obj['violations_rawjson'] = ujson.dumps(dump_socrata_api('v'))
    json_obj['violations_locations_json'] = ujson.dumps(dump_socrata_api('vl'))
    json_obj['violations_type_json'] = ujson.dumps(dump_socrata_api('vt'))
    json_obj['violations_per_month_json'] = ujson.dumps(dump_socrata_api('vm'))

    today = datetime.date.today()

    return render_template(
        "public/home-violations.html",
        api=api_health(),
        date=today.strftime('%B %d, %Y'),
        json_obj=json_obj,
        dash_obj=dashboard_collection,
        resp_obj=survey_table,
        title='Dashboard - Neighborhood Compliance'
        )

@blueprint.route('/dashboard/feedback/', methods=['GET'])
def all_surveys():
    survey_table = get_all_survey_responses(SURVEY_DAYS)

    today = datetime.date.today()

    return render_template(
        "dashboard/all-surveys.html",
        resp_obj=survey_table,
        title='All Survey Responses',
        date=today.strftime('%B %d, %Y')
    )

@blueprint.route('/dashboard/feedback/<id>', methods=['GET'])
@login_required
def survey_detail(id):
    survey = Survey.query.filter_by(id=id)
    today = datetime.date.today()

    return render_template(
        "dashboard/survey-detail.html",
        resp_obj=survey,
        title='Permitting & Inspection Center User Survey Metrics: Detail',
        date=today.strftime('%B %d, %Y'))

@blueprint.route("/dashboard/violations/",  methods=['GET'])
def violations_detail():
    json_obj = {}
    json_obj['violations_type_json'] = ujson.dumps(dump_socrata_api('vt'))
    today = datetime.date.today()
    return render_template(
        "public/violations-detail.html",
        title='Violations by Type: Detail',
        json_obj=json_obj,
        date=today.strftime('%B %d, %Y'))


text:
<?php
namespace BK2K\BootstrapPackage\Hooks\TceMain;

use TYPO3\CMS\Core\DataHandling\DataHandler;
use TYPO3\CMS\Core\Utility\GeneralUtility;

/**
 * @author Benjamin Kott <info@bk2k.info>
 */
class ClearCacheHook
{
    /**
     * @param array $params
     * @param \TYPO3\CMS\Core\DataHandling\DataHandler $pObj
     */
    public function clearLessCache(array $params, DataHandler &$pObj)
    {
        if (!isset($params['cacheCmd'])) {
            return;
        }
        switch ($params['cacheCmd']) {
            case 'all':
                GeneralUtility::rmdir(
                    PATH_site . 'typo3temp/bootstrappackage',
                    true
                );
                break;
            default:
        }
    }
}


text:
<html>
  <head>
    <title>Reflex theme - Auth0 Lock</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/>
    <link rel="stylesheet" type="text/css" href="index.css">
  </head>
  <body>
    <script src="https://cdn.auth0.com/js/lock-6.min.js"></script>
    <script>
      var lock = new Auth0Lock('0HP71GSd6PuoRYJ3DXKdiXCUUdGmBbup', 'mdocs.auth0.com')

      lock.show({
        closable: false
      });

      lock.parseHash(window.location.hash, function (profile, id_token, access_token, state) {
        $('#userinfo').text(JSON.stringify(profile, 0, 2));
      });
    </script>
  </body>
</html>