text:
"use strict";
var DateTimePrecision_1 = require("../../Enumerations/DateTimePrecision");
var EwsLogging_1 = require("../EwsLogging");
var EwsServiceXmlReader_1 = require("../EwsServiceXmlReader");
var EwsServiceXmlWriter_1 = require("../EwsServiceXmlWriter");
var EwsUtilities_1 = require("../EwsUtilities");
var ExchangeServerInfo_1 = require("../ExchangeServerInfo");
var ArgumentException_1 = require("../../Exceptions/ArgumentException");
var ExchangeVersion_1 = require("../../Enumerations/ExchangeVersion");
var RenderingMode_1 = require("../../Enumerations/RenderingMode");
var ServiceResponse_1 = require("../Responses/ServiceResponse");
var ServiceVersionException_1 = require("../../Exceptions/ServiceVersionException");
var SoapFaultDetails_1 = require("../../Misc/SoapFaultDetails");
var ExtensionMethods_1 = require("../../ExtensionMethods");
var Strings_1 = require("../../Strings");
var XmlAttributeNames_1 = require("../XmlAttributeNames");
var XmlElementNames_1 = require("../XmlElementNames");
var XmlNamespace_1 = require("../../Enumerations/XmlNamespace");
/**
 * @internal Represents an abstract service request.
 */
var ServiceRequestBase = (function () {
    /**
     *  @internal Initializes a new instance of the **ServiceRequestBase** class.
     *
     * @param   {ExchangeService}   service   The service.
     */
    function ServiceRequestBase(service) {
        //#endregion
        /**
         * @internal Gets or sets the anchor mailbox associated with the request
         *
         * @remarks Setting this value will add special headers to the request which in turn will route the request directly to the mailbox server against which the request is to be executed.
         */
        this.AnchorMailbox = null;
        if (service == null) {
            throw new ArgumentException_1.ArgumentNullException("service");
        }
        this.service = service;
        this.ThrowIfNotSupportedByRequestedServerVersion();
    }
    Object.defineProperty(ServiceRequestBase.prototype, "Service", {
        /**
         * @internal Gets the service.
         *
         * @value   The service.
         */
        get: function () {
            return this.service;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(ServiceRequestBase.prototype, "EmitTimeZoneHeader", {
        // #region abstract Methods for subclasses to override
        /**
         *  @internal Gets a value indicating whether the TimeZoneContext SOAP header should be eimitted.
         *
         * @value   true if the time zone should be emitted; otherwise, false.
         */
        get: function () {
            return false;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * @internal Gets the name of the XML element.
     *
     * @return  {string}      XML element name,
     */
    ServiceRequestBase.prototype.GetXmlElementName = function () { throw new Error("abstract method, must override"); };
    /**
     * @internal Gets the minimum server version required to process this request.
     *
     * @return  {ExchangeVersion}      Exchange server version.
     */
    ServiceRequestBase.prototype.GetMinimumRequiredServerVersion = function () { throw new Error("abstract method, must override"); };
    /**
     * @internal Gets the name of the response XML element.
     *
     * @return  {string}      XML element name,
     */
    ServiceRequestBase.prototype.GetResponseXmlElementName = function () { throw new Error("abstract method, must override"); };
    /**
     * @internal Parses the response.
     *
     * @param   {any}   jsonBody   The js object response body.
     * @return  {any}              Response object.
     */
    ServiceRequestBase.prototype.ParseResponse = function (jsonBody) {
        var serviceResponse = new ServiceResponse_1.ServiceResponse();
        serviceResponse.LoadFromXmlJsObject(jsonBody, this.Service);
        return serviceResponse;
    };
    /**
     * @internal Writes XML elements.
     *
     * @param   {EwsServiceXmlWriter}   writer   The writer.
     */
    ServiceRequestBase.prototype.WriteElementsToXml = function (writer) { throw new Error("abstract method, must override"); };
    //#endregion
    /**
     * @internal Allows the subclasses to add their own header information
     *
     * @param   {any}   webHeaderCollection   The HTTP request headers
     */
    ServiceRequestBase.prototype.AddHeaders = function (webHeaderCollection /*WebHeaderCollection*/) {
        if (!ExtensionMethods_1.StringHelper.IsNullOrEmpty(this.AnchorMailbox)) {
            webHeaderCollection.Set(ServiceRequestBase.AnchorMailboxHeaderName, this.AnchorMailbox);
            webHeaderCollection.Set(ServiceRequestBase.ExplicitLogonUserHeaderName, this.AnchorMailbox);
        }
    };
    //BuildEwsHttpWebRequest(): IEwsHttpWebRequest { throw new Error("Could not implemented."); }
    ServiceRequestBase.prototype.BuildXHR = function () {
        var request = this.Service.PrepareHttpWebRequest(this.GetXmlElementName());
        //try
        //{
        //    IEwsHttpWebRequest request = this.Service.PrepareHttpWebRequest(this.GetXmlElementName());
        //    this.Service.TraceHttpRequestHeaders(TraceFlags.EwsRequestHttpHeaders, request);
        //    bool needSignature = this.Service.Credentials != null && this.Service.Credentials.NeedSignature;
        //    bool needTrace = this.Service.IsTraceEnabledFor(TraceFlags.EwsRequest);
        //    // If tracing is enabled, we generate the request in-memory so that we
        //    // can pass it along to the ITraceListener. Then we copy the stream to
        //    // the request stream.
        //    if (needSignature || needTrace) {
        //        this.TraceAndEmitRequest(request, needSignature, needTrace);
        //    }
        //    else {
        this.EmitRequest(request);
        //    }
        return request;
        //}
        //catch (WebException ex)
        //{
        //    if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null) {
        //        this.ProcessWebException(ex);
        //    }
        //    // Wrap exception if the above code block didn't throw
        //    throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, ex.Message), ex);
        //}
        //catch (IOException e)
        //{
        //    // Wrap exception.
        //    throw new ServiceRequestException(string.Format(Strings.ServiceRequestFailed, e.Message), e);
        //}
    };
    ServiceRequestBase.prototype.BuildResponseObjectFromJson = function (jsObject) {
        if (jsObject[XmlElementNames_1.XmlElementNames.SOAPHeaderElementName]) {
            this.ReadSoapHeader(jsObject[XmlElementNames_1.XmlElementNames.SOAPHeaderElementName]);
        }
        return this.ParseResponse(jsObject[XmlElementNames_1.XmlElementNames.SOAPBodyElementName]);
    };
    //CreateJsonHeaders(): JsonObject { throw new Error("Could not implemented."); }
    //CreateJsonRequest(): JsonObject { throw new Error("Could not implemented."); }
    /**
     * Emits the request.
     *
     * @param   {IXHROptions}   request   The request.
     */
    ServiceRequestBase.prototype.EmitRequest = function (request) {
        if (this.Service.RenderingMethod === RenderingMode_1.RenderingMode.Xml) {
            var writer = new EwsServiceXmlWriter_1.EwsServiceXmlWriter(this.service); //writer.Service
            this.WriteToXml(writer);
            request.data = writer.GetXML();
        }
        else if (this.Service.RenderingMethod === RenderingMode_1.RenderingMode.JSON) {
            //JsonObject requestObject = this.CreateJsonRequest();
            //using(Stream serviceRequestStream = this.GetWebRequestStream(request))
            //{
            //    requestObject.SerializeToJson(serviceRequestStream);
            //}
            debugger;
        }
    };
    //EndGetEwsHttpWebResponse(request: IEwsHttpWebRequest, asyncResult: any /*System.IAsyncResult*/): IEwsHttpWebResponse { throw new Error("Could not implemented."); }
    ServiceRequestBase.prototype.GetEwsHttpWebResponse = function (request /*IEwsHttpWebRequest*/) { return this.service.GetXHRApi.xhr(request); };
    /**
     * Gets string representation of requested server version.
     *
     * @remarks In order to support E12 RTM servers, ExchangeService has another flag indicating that we should use "Exchange2007" as the server version string rather than Exchange2007_SP1.
     * @return  {string}      String representation of requested server version.
     */
    ServiceRequestBase.prototype.GetRequestedServiceVersionString = function () {
        if (this.Service.Exchange2007CompatibilityMode && this.Service.RequestedServerVersion == ExchangeVersion_1.ExchangeVersion.Exchange2007_SP1) {
            return "Exchange2007";
        }
        else {
            return ExchangeVersion_1.ExchangeVersion[this.Service.RequestedServerVersion];
        }
    };
    //GetResponseStream(response: IEwsHttpWebResponse): any /*System.IO.Stream*/ { throw new Error("Could not implemented."); }
    //GetResponseStream(response: IEwsHttpWebResponse, readTimeout: number):any /*System.IO.Stream*/{ throw new Error("ServiceRequestBase.ts - GetResponseStream : Not implemented.");}
    //GetWebRequestStream(request: IEwsHttpWebRequest): any /*System.IO.Stream*/ { throw new Error("Could not implemented."); }
    /**
     * Processes the web exception.
     *
     * @param   {XMLHttpRequest}   webException   The web response XHR object.
     * @return  {SoapFaultDetails}      Soap fault details if any.
     */
    ServiceRequestBase.prototype.ProcessWebException = function (webException) {
        if (webException) {
            //IEwsHttpWebResponse httpWebResponse = this.Service.HttpWebRequestFactory.CreateExceptionResponse(webException);
            var soapFaultDetails = null;
            if (webException.status == 500 /*System.Net.HttpStatusCode.InternalServerError*/) {
                //this.Service.ProcessHttpResponseHeaders(TraceFlags.EwsResponseHttpHeaders, httpWebResponse);
                // If tracing is enabled, we read the entire response into a MemoryStream so that we
                // can pass it along to the ITraceListener. Then we parse the response from the
                // MemoryStream.
                //if (this.Service.IsTraceEnabledFor(TraceFlags.EwsResponse)) {
                //    using(MemoryStream memoryStream = new MemoryStream())
                //    {
                //        using(Stream serviceResponseStream = ServiceRequestBase.GetResponseStream(httpWebResponse))
                //        {
                //            // Copy response to in-memory stream and reset position to start.
                //            EwsUtilities.CopyStream(serviceResponseStream, memoryStream);
                //            memoryStream.Position = 0;
                //        }
                //        if (this.Service.RenderingMethod == ExchangeService.RenderingMode.Xml) {
                //            this.TraceResponseXml(httpWebResponse, memoryStream);
                //            EwsServiceXmlReader reader = new EwsServiceXmlReader(memoryStream, this.Service);
                //            soapFaultDetails = this.ReadSoapFault(reader);
                //        }
                //        else if (this.Service.RenderingMethod == ExchangeService.RenderingMode.JSON) {
                //            this.TraceResponseJson(httpWebResponse, memoryStream);
                //            try {
                //                JsonObject jsonSoapFault = new JsonParser(memoryStream).Parse();
                //                soapFaultDetails = this.ReadSoapFault(jsonSoapFault);
                //            }
                //            catch (ServiceJsonDeserializationException) {
                //                // If no valid JSON response was returned, just return null SoapFault details
                //            }
                //        }
                //        else {
                //            throw new InvalidOperationException();
                //        }
                //    }
                //}
                //else {
                //    using(Stream stream = ServiceRequestBase.GetResponseStream(httpWebResponse))
                //    {
                //        if (this.Service.RenderingMethod == ExchangeService.RenderingMode.Xml) {
                //            EwsServiceXmlReader reader = new EwsServiceXmlReader(stream, this.Service);
                //            soapFaultDetails = this.ReadSoapFault(reader);
                //        }
                //        else if (this.Service.RenderingMethod == ExchangeService.RenderingMode.JSON) {
                //            try {
                //                JsonObject jsonSoapFault = new JsonParser(stream).Parse();
                //                soapFaultDetails = this.ReadSoapFault(jsonSoapFault);
                //            }
                //            catch (ServiceJsonDeserializationException) {
                //                // If no valid JSON response was returned, just return null SoapFault details
                //            }
                //        }
                //        else {
                //            throw new InvalidOperationException();
                //        }
                //    }
                //}
                //todo: fix tracing and other operations here
                var reader = new EwsServiceXmlReader_1.EwsServiceXmlReader(webException.responseText, this.Service);
                soapFaultDetails = this.ReadSoapFault(reader.JsObject);
                if (soapFaultDetails != null) {
                    //todo: implement soap fault error throw
                    this.SoapFaultDetails = soapFaultDetails;
                }
            }
            else {
                soapFaultDetails = new SoapFaultDetails_1.SoapFaultDetails();
                this.Service.ProcessHttpErrorResponse(webException, soapFaultDetails);
            }
            return soapFaultDetails;
        }
    };
    /**
     * Reads the response from converted XML JS Object Soap enevlop is is omited, object has Body and Header as direct member.
     *
     * @param   {any}   jsObject    The converted XMl JS Object.
     * @return  {any}               Service response.
     */
    ServiceRequestBase.prototype.ReadResponseXmlJsObject = function (jsObject) {
        if (jsObject[XmlElementNames_1.XmlElementNames.SOAPHeaderElementName]) {
            this.ReadSoapHeader(jsObject[XmlElementNames_1.XmlElementNames.SOAPHeaderElementName]);
        }
        if (!jsObject[XmlElementNames_1.XmlElementNames.SOAPBodyElementName]) {
            throw new Error("invalid soap message");
        }
        var serviceResponse;
        var jsBody = jsObject[XmlElementNames_1.XmlElementNames.SOAPBodyElementName];
        var jsResponse = jsBody[this.GetResponseXmlElementName()];
        serviceResponse = this.ParseResponse(jsResponse);
        return serviceResponse;
    };
    /**
     * Reads the SOAP fault.
     *
     * @param   {any}   jsonSoapFault   The SOAP fault.
     * @return  {SoapFaultDetails}      Parsed SoapFaultDetails
     */
    ServiceRequestBase.prototype.ReadSoapFault = function (jsSoapFault) {
        var soapFaultDetails = null;
        if (jsSoapFault[XmlElementNames_1.XmlElementNames.SOAPHeaderElementName]) {
            this.ReadSoapHeader(jsSoapFault[XmlElementNames_1.XmlElementNames.SOAPHeaderElementName]);
        }
        if (jsSoapFault[XmlElementNames_1.XmlElementNames.SOAPBodyElementName]) {
            var jsSoapBody = jsSoapFault[XmlElementNames_1.XmlElementNames.SOAPBodyElementName];
            if (jsSoapBody[XmlElementNames_1.XmlElementNames.SOAPFaultElementName]) {
                soapFaultDetails = SoapFaultDetails_1.SoapFaultDetails.Parse(jsSoapBody[XmlElementNames_1.XmlElementNames.SOAPFaultElementName]);
            }
        }
        return soapFaultDetails;
    };
    /**
     * Read SOAP header and extract server version
     *
     * @param   {any}   jsObject   Header value in JsObject
     */
    ServiceRequestBase.prototype.ReadSoapHeader = function (jsObject) {
        if (jsObject[XmlElementNames_1.XmlElementNames.ServerVersionInfo]) {
            this.Service.ServerInfo = ExchangeServerInfo_1.ExchangeServerInfo.Parse(jsObject[XmlElementNames_1.XmlElementNames.ServerVersionInfo]);
        }
    };
    /**
     * @internal Throw exception if request is not supported in requested server version.
     *
     * @exception   {ServiceVersionException}   Raised if request requires a later version of Exchange.
     */
    ServiceRequestBase.prototype.ThrowIfNotSupportedByRequestedServerVersion = function () {
        if (this.Service.RequestedServerVersion < this.GetMinimumRequiredServerVersion()) {
            throw new ServiceVersionException_1.ServiceVersionException(ExtensionMethods_1.StringHelper.Format(Strings_1.Strings.RequestIncompatibleWithRequestVersion, this.GetXmlElementName(), ExchangeVersion_1.ExchangeVersion[this.GetMinimumRequiredServerVersion()]), null);
        }
    };
    //TraceAndEmitRequest(request: IEwsHttpWebRequest, needSignature: boolean, needTrace: boolean): any { throw new Error("Could not implemented."); }
    //TraceJsonRequest(requestObject: JsonObject): any { throw new Error("Could not implemented."); }
    //TraceResponseJson(response: IEwsHttpWebResponse, memoryStream: any): any { throw new Error("Could not implemented."); }
    //TraceResponseXml(response: IEwsHttpWebResponse, memoryStream: any): any { throw new Error("Could not implemented."); }
    //TraceXmlRequest(memoryStream: any): any { throw new Error("Could not implemented."); }
    /**
     * @internal Validate request.
     */
    ServiceRequestBase.prototype.Validate = function () {
        this.Service.Validate();
    };
    /**
     * Validates request parameters, and emits the request to the server.
     *
     * @param   {IXHROptions}               request   The request.
     * @return  {IPromise<XMLHttpRequest>}  The response returned by the server.
     */
    ServiceRequestBase.prototype.ValidateAndEmitRequest = function (request) {
        this.Validate();
        //var request = this.BuildXHR();
        if (this.service.SendClientLatencies) {
            var clientStatisticsToAdd = '';
            //lock(clientStatisticsCache)
            //{
            if (ServiceRequestBase.clientStatisticsCache.length > 0) {
                clientStatisticsToAdd = ServiceRequestBase.clientStatisticsCache[0];
                ServiceRequestBase.clientStatisticsCache.splice(0, 1);
            }
            //}
            if (!ExtensionMethods_1.StringHelper.IsNullOrEmpty(clientStatisticsToAdd)) {
                if (request.headers[ServiceRequestBase.ClientStatisticsRequestHeader]) {
                    request.headers[ServiceRequestBase.ClientStatisticsRequestHeader] =
                        request.headers[ServiceRequestBase.ClientStatisticsRequestHeader] + clientStatisticsToAdd;
                }
                else {
                    request.headers[ServiceRequestBase.ClientStatisticsRequestHeader] = clientStatisticsToAdd;
                }
            }
        }
        //var startTime = Date.now();// DateTime.UtcNow;
        //var response = XHR(request);
        EwsLogging_1.EwsLogging.DebugLog("sending ews request");
        EwsLogging_1.EwsLogging.DebugLog(request, true);
        return this.service.GetXHRApi.xhr(request);
        //try
        //{
        //    var response = this.GetEwsHttpWebResponse(request);
        //}
        //finally {
        //    if (this.service.SendClientLatencies) {
        //        int clientSideLatency = (int)(DateTime.UtcNow - startTime).TotalMilliseconds;
        //        string requestId = string.Empty;
        //        string soapAction = this.GetType().Name.Replace("Request", string.Empty);
        //        if (response != null && response.Headers != null) {
        //            foreach(string requestIdHeader in ServiceRequestBase.RequestIdResponseHeaders)
        //            {
        //                string requestIdValue = response.Headers.Get(requestIdHeader);
        //                if (!string.IsNullOrEmpty(requestIdValue)) {
        //                    requestId = requestIdValue;
        //                    break;
        //                }
        //            }
        //        }
        //        StringBuilder sb = new StringBuilder();
        //        sb.Append("MessageId=");
        //        sb.Append(requestId);
        //        sb.Append(",ResponseTime=");
        //        sb.Append(clientSideLatency);
        //        sb.Append(",SoapAction=");
        //        sb.Append(soapAction);
        //        sb.Append(";");
        //        lock(clientStatisticsCache)
        //        {
        //            clientStatisticsCache.Add(sb.ToString());
        //        }
        //    }
        //}
        //return response;
    };
    //WrapStream(responseStream: any /*System.IO.Stream*/, contentEncoding: string): any /*System.IO.Stream*/ { throw new Error("Could not implemented."); }
    /**
     * @internal Writes XML attributes.
     *
     * @param   {EwsServiceXmlWriter}   writer   The writer.
     *
     * @remarks Subclass will override if it has XML attributes.
     */
    ServiceRequestBase.prototype.WriteAttributesToXml = function (writer) { };
    /**
     * @internal Writes XML body.
     *
     * @param   {EwsServiceXmlWriter}   writer   The writer.
     */
    ServiceRequestBase.prototype.WriteBodyToXml = function (writer) {
        writer.WriteStartElement(XmlNamespace_1.XmlNamespace.Messages, this.GetXmlElementName());
        this.WriteAttributesToXml(writer);
        this.WriteElementsToXml(writer);
        writer.WriteEndElement(); // m:this.GetXmlElementName()
    };
    //#region HttpWebRequest-based implementation
    /**
     * @internal Writes XML.
     *
     * @param   {EwsServiceXmlWriter}   writer   The writer.
     */
    ServiceRequestBase.prototype.WriteToXml = function (writer) {
        writer.WriteStartElement(XmlNamespace_1.XmlNamespace.Soap, XmlElementNames_1.XmlElementNames.SOAPEnvelopeElementName);
        writer.WriteAttributeValue("xmlns", EwsUtilities_1.EwsUtilities.EwsXmlSchemaInstanceNamespacePrefix, EwsUtilities_1.EwsUtilities.EwsXmlSchemaInstanceNamespace);
        writer.WriteAttributeValue("xmlns", EwsUtilities_1.EwsUtilities.EwsMessagesNamespacePrefix, EwsUtilities_1.EwsUtilities.EwsMessagesNamespace);
        writer.WriteAttributeValue("xmlns", EwsUtilities_1.EwsUtilities.EwsTypesNamespacePrefix, EwsUtilities_1.EwsUtilities.EwsTypesNamespace);
        if (writer.RequireWSSecurityUtilityNamespace) {
            writer.WriteAttributeValue("xmlns", EwsUtilities_1.EwsUtilities.WSSecurityUtilityNamespacePrefix, EwsUtilities_1.EwsUtilities.WSSecurityUtilityNamespace);
        }
        writer.WriteStartElement(XmlNamespace_1.XmlNamespace.Soap, XmlElementNames_1.XmlElementNames.SOAPHeaderElementName);
        if (this.Service.Credentials != null) {
            //todo: fix extra soap headers if required
            this.Service.Credentials.EmitExtraSoapHeaderNamespaceAliases(null);
        }
        // Emit the RequestServerVersion header
        if (!this.Service.SuppressXmlVersionHeader) {
            writer.WriteStartElement(XmlNamespace_1.XmlNamespace.Types, XmlElementNames_1.XmlElementNames.RequestServerVersion);
            writer.WriteAttributeValue(XmlAttributeNames_1.XmlAttributeNames.Version, this.GetRequestedServiceVersionString());
            writer.WriteEndElement(); // RequestServerVersion
        }
        // Against Exchange 2007 SP1, we always emit the simplified time zone header. It adds very little to
        // the request, so bandwidth consumption is not an issue. Against Exchange 2010 and above, we emit
        // the full time zone header but only when the request actually needs it.
        //
        // The exception to this is if we are in Exchange2007 Compat Mode, in which case we should never emit
        // the header.  (Note: Exchange2007 Compat Mode is enabled for testability purposes only.)
        //
        if ((this.Service.RequestedServerVersion == ExchangeVersion_1.ExchangeVersion.Exchange2007_SP1 || this.EmitTimeZoneHeader) &&
            (!this.Service.Exchange2007CompatibilityMode)) {
            writer.WriteStartElement(XmlNamespace_1.XmlNamespace.Types, XmlElementNames_1.XmlElementNames.TimeZoneContext);
            this.Service.TimeZoneDefinition.WriteToXml(writer);
            writer.WriteEndElement(); // TimeZoneContext
            writer.IsTimeZoneHeaderEmitted = true;
        }
        // Emit the MailboxCulture header
        if (this.Service.PreferredCulture != null) {
            //todo: fix preferred culture.
            writer.WriteElementValue(XmlNamespace_1.XmlNamespace.Types, XmlElementNames_1.XmlElementNames.MailboxCulture, this.Service.PreferredCulture.Name);
        }
        // Emit the DateTimePrecision header
        if (this.Service.DateTimePrecision != DateTimePrecision_1.DateTimePrecision.Default) {
            writer.WriteElementValue(XmlNamespace_1.XmlNamespace.Types, XmlElementNames_1.XmlElementNames.DateTimePrecision, DateTimePrecision_1.DateTimePrecision[this.Service.DateTimePrecision]);
        }
        // Emit the ExchangeImpersonation header
        if (this.Service.ImpersonatedUserId != null) {
            this.Service.ImpersonatedUserId.WriteToXml(writer);
        }
        else if (this.Service.PrivilegedUserId != null) {
            //todo: find scenario if this is used anywhere, did not find any reference in MSDN
            this.Service.PrivilegedUserId.WriteToXml(writer, this.Service.RequestedServerVersion);
        }
        else if (this.Service.ManagementRoles != null) {
            this.Service.ManagementRoles.WriteToXml(writer);
        }
        if (this.Service.Credentials != null) {
            this.Service.Credentials.SerializeExtraSoapHeaders(writer, this.GetXmlElementName());
        }
        this.Service.DoOnSerializeCustomSoapHeaders(writer);
        writer.WriteEndElement(); // soap:Header
        writer.WriteStartElement(XmlNamespace_1.XmlNamespace.Soap, XmlElementNames_1.XmlElementNames.SOAPBodyElementName);
        this.WriteBodyToXml(writer);
        writer.WriteEndElement(); // soap:Body
        writer.WriteEndElement(); // soap:Envelope
    };
    //#region private static and const
    //ref:this may be from newer code overall i am using, update when updating from ews base code library //todo:
    /**
     * The two contants below are used to set the AnchorMailbox and ExplicitLogonUser values in the request header.
     *
     * @remarks Note: Setting this values will route the request directly to the backend hosting the AnchorMailbox. These headers should be used primarily for UnifiedGroup scenario where a request needs to be routed directly to the group mailbox versus the user mailbox.
     */
    ServiceRequestBase.AnchorMailboxHeaderName = "X-AnchorMailbox";
    ServiceRequestBase.ExplicitLogonUserHeaderName = "X-OWA-ExplicitLogonUser";
    ServiceRequestBase.RequestIdResponseHeaders = ["RequestId", "request-id"];
    ServiceRequestBase.XMLSchemaNamespace = "http://www.w3.org/2001/XMLSchema";
    ServiceRequestBase.XMLSchemaInstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance";
    ServiceRequestBase.ClientStatisticsRequestHeader = "X-ClientStatistics";
    /**
     * Maintains the collection of client side statistics for requests already completed
     */
    ServiceRequestBase.clientStatisticsCache = [];
    return ServiceRequestBase;
}());
exports.ServiceRequestBase = ServiceRequestBase;


text:
import guild from './guild';

export default function advisorView(period) {
  return guild({ subcmd: 'advisor', subcmd2: 'view', period });
}

redpajama_set_name: RedPajamaGithub


text:
class Consul050 < FPM::Cookery::Recipe
  name        'consul'
  version     '0.5.0'
  revision    0
  description 'A service discovery and configuration made easy.'
  homepage    'http://consul.io'
  section     'admin'

  source      "https://dl.bintray.com/mitchellh/consul/#{version}_linux_amd64.zip"
  sha256      "161f2a8803e31550bd92a00e95a3a517aa949714c19d3124c46e56cfdc97b088"

  build_depends 'zip', 'curl'

  pre_install   'files/preinstall'

  fpm_attributes["#{FPM::Cookery::Facts.target}_user".to_sym]   = 'consul'
  fpm_attributes["#{FPM::Cookery::Facts.target}_group".to_sym]  = 'consul'

  def build
    zip_file = get_ui_zip_name
    zip_path = File.join(builddir, zip_file)

    safesystem("curl -L -o #{zip_path} https://dl.bintray.com/mitchellh/consul/#{zip_file} ")
    safesystem("unzip #{zip_path}")
  end

  def install
    install_etc

    install_var_lib

    install_ui_files

    install_systemd_files

    install_bin
  end

  private

  def install_etc
    etc('consul.d/bootstrap').mkdir
    etc('consul.d/bootstrap').install workdir('files/etc/consul.d/bootstrap/consul.json')

    etc('consul.d/server').mkdir
    etc('consul.d/server').install workdir('files/etc/consul.d/server/consul.json')

    etc('consul.d/agent').mkdir
    etc('consul.d/agent').install workdir('files/etc/consul.d/agent/consul.json')
  end

  def install_var_lib
    var('lib/consul').mkdir
  end

  def install_ui_files
    share('consul').mkdir

    zip_path = File.join(builddir, '*', 'dist')

    Dir[zip_path].each do |file|
      share('consul').install file
    end
  end

  def install_systemd_files
    lib('systemd/system').install workdir('files/usr/lib/systemd/system/consul-bootstrap.service')
    lib('systemd/system').install workdir('files/usr/lib/systemd/system/consul-server.service')
    lib('systemd/system').install workdir('files/usr/lib/systemd/system/consul-agent.service')
  end

  def install_bin
    folder = File.join(File.basename(source, '.zip'))
    glob = File.join(builddir(folder), 'consul')

    Dir[glob].each do |file|
      bin.install(file)
    end
  end

  def get_ui_zip_name
    "#{version}_web_ui.zip"
  end
end


text:
package com.zhongying.mineweather.fragment.base;

import android.support.v4.app.Fragment;

/**
 * @class: 基层Fragment
 * Created by Administrator on 2017/9/14.
 */

public class BaseFragment extends Fragment {
}


text:
module Outback
  class TargetArchive < Archive
    attr_reader :target

    def initialize(filename, size, target)
      super(filename)
      @size = size
      @target = target
    end

    def match?(name)
      name == backup_name
    end

    def ttl
      target && target.ttl
    end

    def outdated?
      if timestamp && ttl
        Time.now - Time.strptime(timestamp, Outback::TIME_FORMAT) > ttl
      end
    end

    def to_s
      "#{target}: #{filename}"
    end

  end
end


text:
#include <ESP8266WiFi.h>
#include <NTPClient.h>
#include <Adafruit_LEDBackpack.h>
#include <Task.h>

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-parameter"
#define SSID "YOUR WIFI NETWORK"
#define PASS "AND ITS PASSWORD"
#define TZ -8 // your time zone offset
#define HOST "time.apple.com" // your favorite NTP server

TaskManager taskManager;
NTPClient timeClient(HOST, TZ * 3600);
Adafruit_7segment matrix = Adafruit_7segment();

/**
 * Is the colon supposed to be on or off?
 */
bool colon = true;

/**
 * Check this in the loop; if it differs from what NTPClient tells us
 * then it's time to update the time.
 */
unsigned long prevMin = 0;

void toggleColon(uint32_t delta);
void updateTime(uint32_t delta);
void waitForConnection(uint32_t delta);
void keepConnected(uint32_t delta);

FunctionTask taskToggleColon(toggleColon, MsToTaskTime(500));
FunctionTask taskUpdateTime(updateTime, MsToTaskTime(1000));
FunctionTask taskWaitForConnection(waitForConnection, MsToTaskTime(250));
FunctionTask taskKeepConnected(keepConnected, MsToTaskTime(250));

/**
 * Toggles the colon state and writes the display.
 */
void toggleColon(uint32_t delta) {
  colon = !colon;
  matrix.drawColon((boolean) colon);
  matrix.writeDisplay();
}

/**
 * Resets 7-segment display.
 */
void reset() {
  matrix.clear();
  colon = false;
  matrix.writeDisplay();
}

/**
 * Returns `true` if WiFi is offline.
 */
bool offline() {
  return WiFi.status() != WL_CONNECTED;
}

/**
 * Pauses normal behavior and waits until we have a WiFi connection again,
 * then resumes.
 */
void waitForConnection(uint32_t delta) {
  toggleColon(delta);
  if (!offline()) {
    Serial.println("Connected to " + String(SSID));
    taskManager.StopTask(&taskWaitForConnection);
    taskManager.StartTask(&taskToggleColon);
    taskManager.StartTask(&taskUpdateTime);
    taskManager.StartTask(&taskKeepConnected);
  }
}

/**
 * Connects to WiFi network.  Flashes colon quickly during this phase.
 */
void keepConnected(uint32_t delta) {
  if (offline()) {

    taskManager.StopTask(&taskKeepConnected);
    taskManager.StopTask(&taskToggleColon);
    taskManager.StopTask(&taskUpdateTime);

    Serial.println("Connecting to " + String(SSID));
    WiFi.begin(SSID, PASS);

    taskManager.StartTask(&taskWaitForConnection);
  }
}

/**
 * Shortcut to turn a char into an int.
 */
uint8_t charToInt(char c) {
  return (uint8_t) c - '0';
}

/**
 * Draws the time.  Make adjustments for single-digit values.
 */
void drawTime(String hours, String minutes) {
  if (hours.length() == 1) {
    matrix.writeDigitRaw(0, 0);
    matrix.writeDigitNum(1, charToInt(hours.charAt(0)));
  } else {
    matrix.writeDigitNum(0, charToInt(hours.charAt(0)));
    matrix.writeDigitNum(1, charToInt(hours.charAt(1)));
  }
  if (minutes.length() == 1) {
    matrix.writeDigitNum(3, 0);
    matrix.writeDigitNum(4, charToInt(minutes.charAt(0)));
  } else {
    matrix.writeDigitNum(3, charToInt(minutes.charAt(0)));
    matrix.writeDigitNum(4, charToInt(minutes.charAt(1)));
  }
}

/**
 * If a second or more has passed, ensure WiFi connectivity, then check the NTP
 * client for the time.  Note the client will not actually ping the host more
 * than every 60s as configured.
 *
 * If the time's "minute" value is not equal to the current value we're
 * displaying, then draw the new time and save its value.
 */
void updateTime(uint32_t delta) {
  timeClient.update();
  unsigned long min = (timeClient.getRawTime() % 3600) / 60;
  if (min != prevMin) {
    drawTime(timeClient.getHours(), timeClient.getMinutes());
    Serial.println("Updating time to " + timeClient.getFormattedTime());
    prevMin = min;
  }
}

#pragma clang diagnostic push
#pragma ide diagnostic ignored "OCUnusedGlobalDeclarationInspection"

/**
 * Initializes matrix and connects to WiFi.
 */
void setup() {
  WiFi.mode(WIFI_STA);
  Serial.begin(115200);
  matrix.begin(0x70);
  reset();
  taskManager.StartTask(&taskToggleColon);
  taskManager.StartTask(&taskUpdateTime);
  taskManager.StartTask(&taskKeepConnected);
}

/**
 * Flashes colon on/off every second.
 * Asks the NTP client for an update every second; if the minute has changed,
 * then update the display.
 * Keep WiFi connection alive.
 */
void loop() {
  taskManager.Loop();
}

#pragma clang diagnostic pop


text:
// This file is automatically generated.

package adila.db;

/*
 * Samsung Galaxy Tab S 10.5
 *
 * DEVICE: SCT21
 * MODEL: SCT21
 */
final class sct21_sct21 {
    public static final String DATA = "Samsung|Galaxy Tab S 10.5|Galaxy Tab";
}


text:
#include <aws/medialive/model/AvailSettings.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace MediaLive
{
namespace Model
{

AvailSettings::AvailSettings() :
    m_scte35SpliceInsertHasBeenSet(false),
    m_scte35TimeSignalAposHasBeenSet(false)
{
}

AvailSettings::AvailSettings(JsonView jsonValue) :
    m_scte35SpliceInsertHasBeenSet(false),
    m_scte35TimeSignalAposHasBeenSet(false)
{
  *this = jsonValue;
}

AvailSettings& AvailSettings::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("scte35SpliceInsert"))
  {
    m_scte35SpliceInsert = jsonValue.GetObject("scte35SpliceInsert");

    m_scte35SpliceInsertHasBeenSet = true;
  }

  if(jsonValue.ValueExists("scte35TimeSignalApos"))
  {
    m_scte35TimeSignalApos = jsonValue.GetObject("scte35TimeSignalApos");

    m_scte35TimeSignalAposHasBeenSet = true;
  }

  return *this;
}

JsonValue AvailSettings::Jsonize() const
{
  JsonValue payload;

  if(m_scte35SpliceInsertHasBeenSet)
  {
   payload.WithObject("scte35SpliceInsert", m_scte35SpliceInsert.Jsonize());

  }

  if(m_scte35TimeSignalAposHasBeenSet)
  {
   payload.WithObject("scte35TimeSignalApos", m_scte35TimeSignalApos.Jsonize());

  }

  return payload;
}

} // namespace Model
} // namespace MediaLive
} // namespace Aws


text:
<?php

namespace Goetas\TwitalBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Goetas\TwitalBundle\DependencyInjection\Compiler\AddExtensionsPass;
use Goetas\TwitalBundle\DependencyInjection\Compiler\TwigPass;

/**
 * @author Asmir Mustafic <goetas@gmail.com>
 */
class GoetasTwitalBundle extends Bundle
{
    public function build(ContainerBuilder $container)
    {
        $container->addCompilerPass(new AddExtensionsPass());
        $container->addCompilerPass(new TwigPass());
    }
}


text:
package models.sso.converters;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.sql.Date;
import java.time.LocalDate;

/**
 * Converts {@link LocalDate} to {@link Date} and back.
 * Consider removing this code after Hibernate 5.0 is used.
 */
@Converter(autoApply = true)
public class LocalDateAttributeConverter implements AttributeConverter<LocalDate, Date> {

    @Override
    public Date convertToDatabaseColumn(LocalDate locDate) {
        return (locDate == null ? null : Date.valueOf(locDate));
    }

    @Override
    public LocalDate convertToEntityAttribute(Date sqlDate) {
        return (sqlDate == null ? null : sqlDate.toLocalDate());
    }
}


text:
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.

package com.microsoft.azure.keyvault;

import com.microsoft.windowsazure.core.OperationResponse;

/**
 * Represents the response to a secret operation request.
 */
class SecretResponseMessageWithRawJsonContent extends OperationResponse {
    private String response;

    /**
     * Optional.
     *
     * @return The Response value.
     */
    public String getResponse() {
        return response;
    }

    /**
     * Optional.
     *
     * @param responseValue
     *            The Response value.
     */
    public void setResponse(final String responseValue) {
        response = responseValue;
    }
}


text:
{{ if .Site.Params.aboutme }}

    {{ if .Site.Params.avatar}}

    {{ end }}
    {{ .Site.Params.aboutme | safeHTML}}

{{ end }}


text:
require 'test_helper'
require 'sessions_controller'

# Re-raise errors caught by the controller.
class SessionsController; def rescue_action(e) raise e end; end

class SessionsControllerTest < ActionController::TestCase
  # Be sure to include AuthenticatedTestHelper in test/test_helper.rb instead
  # Then, you can remove it from this and the units test.
  include AuthenticatedTestHelper

  fixtures :users,:people

  def setup
    @controller = SessionsController.new
    @request    = ActionController::TestRequest.new
    @response   = ActionController::TestResponse.new
  end

  test "sessions#index redirects to session#new" do
    get :index
    assert_redirected_to login_url
  end

  test "session#show redirects to session#new" do
    get :show
    assert_redirected_to login_url
  end

  def test_index_not_logged_in
    get :new
    assert_response :success

    User.destroy_all #remove all users
    assert 0,User.count
    get :new
    assert_response :redirect
    assert_redirected_to signup_url
  end

  def test_title
    get :new
    assert_select "title",:text=>/The Sysmo SEEK.*/, :count=>1
  end

  def test_should_login_and_redirect
    post :create, :login => 'quentin', :password => 'test'
    assert session[:user_id]
    assert_response :redirect
  end

  #FIXME: check whether doing a redirect is a problem - this is a test generated by the restful_auth.. plugin, so is clearly there for a reason
#  def test_should_fail_login_and_not_redirect
#    post :create, :login => 'quentin', :password => 'bad password'
#    assert_nil session[:user_id]
#    assert_response :success
#  end

  def test_should_logout
    login_as :quentin
    @request.cookies[:open_id] = 'http://fred.openid.org'
    @request.env['HTTP_REFERER'] = '/data_files'
    get :destroy
    assert_nil session[:user_id]
    assert_nil cookies[:open_id]
    assert_response :redirect
  end

  def test_should_remember_me
    post :create, :login => 'quentin', :password => 'test', :remember_me => "on"
    assert_not_nil @response.cookies["auth_token"]
  end

  def test_should_not_remember_me
    post :create, :login => 'quentin', :password => 'test', :remember_me => "off"
    assert_nil @response.cookies["auth_token"]
  end

  def test_should_delete_token_on_logout
    login_as :quentin
    @request.env['HTTP_REFERER'] = '/data_files'
    get :destroy
    assert_equal @response.cookies["auth_token"], nil
  end

  def test_should_login_with_cookie
    users(:quentin).remember_me
    @request.cookies["auth_token"] = cookie_for(:quentin)
    get :new
    assert @controller.send(:logged_in?)
  end

  def test_should_fail_expired_cookie_login
    users(:quentin).remember_me
    users(:quentin).update_attribute :remember_token_expires_at, 5.minutes.ago
    @request.cookies["auth_token"] = cookie_for(:quentin)
    get :new
    assert !@controller.send(:logged_in?)
  end

  def test_should_fail_cookie_login
    users(:quentin).remember_me
    @request.cookies["auth_token"] = auth_token('invalid_auth_token')
    get :new
    assert !@controller.send(:logged_in?)
  end

  def test_non_validated_user_should_redirect_to_new_with_message
    post :create, :login => 'aaron', :password => 'test'
    assert !session[:user_id]
    assert_redirected_to "/"
    assert_not_nil flash[:error]
    assert flash[:error].include?("You still need to activate your account.")
  end

  def test_partly_registed_user_should_redirect_to_select_person
    post :create, :login => 'part_registered', :password => 'test'
    assert session[:user_id]
    assert_equal users(:part_registered).id,session[:user_id]
    assert_not_nil flash.now[:notice]
    assert_redirected_to select_people_path
  end

  test 'should redirect to root after logging out from the search result page' do
      login_as :quentin
      @request.env['HTTP_REFERER']= "http://test.host/search/"
      get :destroy
      assert_redirected_to :root
  end

  test 'should redirect to back after logging out from the page excepting search result page' do
      login_as :quentin
      @request.env['HTTP_REFERER']= "http://test.host/data_files/"
      get :destroy
      assert_redirected_to :back
  end

  test 'should redirect to root after logging in from the search result page' do
      @request.env['HTTP_REFERER']= "http://test.host/search"
      post :create, :login => 'quentin', :password => 'test'
      assert_redirected_to :root
  end

  test 'should redirect to back after logging in from the page excepting search result page' do
      @request.env['HTTP_REFERER']= "http://test.host/data_files/"
      post :create, :login => 'quentin', :password => 'test'
      assert_redirected_to :back
  end

  protected
    def auth_token(token)
      CGI::Cookie.new('name' => 'auth_token', 'value' => token)
    end

    def cookie_for(user)
      auth_token users(user).remember_token
    end
end


text:
using base::BindLambdaForTesting;
using chrome_browser_sharing::ResponseMessage;
using chrome_browser_sharing::SharingMessage;
using ::testing::_;
using ::testing::NiceMock;
using ::testing::Return;
using ::testing::SaveArg;
using ::testing::StrictMock;

namespace {

class MockSmsFetcher : public content::SmsFetcher {
 public:
  MockSmsFetcher() = default;
  ~MockSmsFetcher() = default;

  MOCK_METHOD2(Subscribe,
               void(const url::Origin& origin, Subscriber* subscriber));
  MOCK_METHOD3(Subscribe,
               void(const url::Origin& origin,
                    Subscriber* subscriber,
                    content::RenderFrameHost* rfh));
  MOCK_METHOD2(Unsubscribe,
               void(const url::Origin& origin, Subscriber* subscriber));
  MOCK_METHOD0(HasSubscribers, bool());

 private:
  DISALLOW_COPY_AND_ASSIGN(MockSmsFetcher);
};

SharingMessage CreateRequest(const std::string& origin) {
  SharingMessage message;
  message.mutable_sms_fetch_request()->set_origin(origin);
  return message;
}

}  // namespace

TEST(SmsFetchRequestHandlerTest, Basic) {
  base::test::SingleThreadTaskEnvironment task_environment;
  StrictMock<MockSmsFetcher> fetcher;
  SmsFetchRequestHandler handler(&fetcher);
  SharingMessage message = CreateRequest("https://a.com");

  base::RunLoop loop;

  content::SmsFetcher::Subscriber* subscriber;
  EXPECT_CALL(fetcher, Subscribe(_, _)).WillOnce(SaveArg<1>(&subscriber));
  EXPECT_CALL(fetcher, Unsubscribe(_, _));

  handler.OnMessage(
      message,
      BindLambdaForTesting([&loop](std::unique_ptr<ResponseMessage> response) {
        EXPECT_TRUE(response->has_sms_fetch_response());
        EXPECT_EQ("123", response->sms_fetch_response().one_time_code());
        loop.Quit();
      }));

  subscriber->OnReceive("123");
  loop.Run();
}

TEST(SmsFetchRequestHandlerTest, OutOfOrder) {
  base::test::SingleThreadTaskEnvironment task_environment;
  StrictMock<MockSmsFetcher> fetcher;
  SmsFetchRequestHandler handler(&fetcher);
  SharingMessage message = CreateRequest("https://a.com");

  base::RunLoop loop1;

  content::SmsFetcher::Subscriber* request1;
  EXPECT_CALL(fetcher, Subscribe(_, _)).WillOnce(SaveArg<1>(&request1));
  EXPECT_CALL(fetcher, Unsubscribe(_, _)).Times(2);

  handler.OnMessage(
      message,
      BindLambdaForTesting([&loop1](std::unique_ptr<ResponseMessage> response) {
        EXPECT_TRUE(response->has_sms_fetch_response());
        EXPECT_EQ("1", response->sms_fetch_response().one_time_code());
        loop1.Quit();
      }));

  base::RunLoop loop2;

  content::SmsFetcher::Subscriber* request2;
  EXPECT_CALL(fetcher, Subscribe(_, _)).WillOnce(SaveArg<1>(&request2));

  handler.OnMessage(
      message,
      BindLambdaForTesting([&loop2](std::unique_ptr<ResponseMessage> response) {
        EXPECT_TRUE(response->has_sms_fetch_response());
        EXPECT_EQ("2", response->sms_fetch_response().one_time_code());
        loop2.Quit();
      }));

  request2->OnReceive("2");
  loop2.Run();

  request1->OnReceive("1");
  loop1.Run();
}

TEST(SmsFetchRequestHandlerTest, HangingRequestUnsubscribedUponDestruction) {
  base::test::SingleThreadTaskEnvironment task_environment;
  StrictMock<MockSmsFetcher> fetcher;

  SmsFetchRequestHandler handler(&fetcher);
  SharingMessage message = CreateRequest("https://a.com");
  content::SmsFetcher::Subscriber* subscriber;
  EXPECT_CALL(fetcher, Subscribe(_, _)).WillOnce(SaveArg<1>(&subscriber));

  // Expects Unsubscribe to be called when SmsFetchRequestHandler goes out of
  // scope.
  EXPECT_CALL(fetcher, Unsubscribe(_, _));

  // Leaves the request deliberately hanging without a response to assert
  // that it gets cleaned up.
  handler.OnMessage(
      message,
      BindLambdaForTesting([&](std::unique_ptr<ResponseMessage> response) {}));
}


text:
namespace plusfish {

// Can be used to check if a content string starts with a specified prefix.
class PrefixMatcher : public MatcherInterface {
 public:
  explicit PrefixMatcher(const MatchRule_Match& match);
  ~PrefixMatcher() override {}

  // If negative matching is expected.
  bool negative() const override { return match_.negative_match(); }
  bool Prepare() override;
  // Returns true if any of the contained values are a prefix of the content
  // parameter.
  bool MatchAny(const Request* request,
                const std::string* content) const override;

 private:
  // Helper method to match a single string against the content and it's origin
  // Request. Returns true on success and false on failure.
  bool MatchSingle(const std::string& search_string,
                   const std::string* content) const;
  const MatchRule_Match match_;
  DISALLOW_COPY_AND_ASSIGN(PrefixMatcher);
};

}  // namespace plusfish

#endif  // OPS_SECURITY_PENTESTING_SCANNING_PLUSFISH_AUDIT_MATCHERS_PREFIX_MATCHER_H_


text:
package com.noprestige.kanaquiz.logs;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;

import com.noprestige.kanaquiz.R;
import com.noprestige.kanaquiz.questions.QuestionType;
import com.noprestige.kanaquiz.themes.ThemeManager;

import java.text.DecimalFormat;
import java.util.Locale;

public class LogDetailItem extends View
{
    private int correctAnswers = -1;
    private int totalAnswers = -1;
    private String question = "";
    private QuestionType type;
    private boolean isDynamicSize = true;

    private String correctString = "";
    private String totalString = "";
    private String percentageString = "";

    private final TextPaint mainPaint = new TextPaint();
    private final TextPaint percentagePaint = new TextPaint();
    private final TextPaint typePaint = new TextPaint();
    private final Paint linePaint = new Paint();

    private float originalFontSize;
    private int desiredHeight;

    private float questionXPoint;
    private float correctXPoint;
    private float slashXPoint;
    private float totalXPoint;
    private float percentageXPoint;
    private float dataYPoint;

    private float lineXPoint1;
    private float lineXPoint2;
    private float lineYPoint;

    private float questionWidth;
    private float correctWidth;
    private float slashWidth;
    private float totalWidth;
    private float percentageWidth;

    private float textHeight;

    private int internalVerticalPadding;

    private static final DecimalFormat PERCENT_FORMATTER = new DecimalFormat("#0%");
    private static final String SLASH = "/";

    public LogDetailItem(Context context)
    {
        super(context);
        init(null, 0);
    }

    public LogDetailItem(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        init(attrs, 0);
    }

    public LogDetailItem(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        init(attrs, defStyle);
    }

    private void init(AttributeSet attrs, int defStyle)
    {
        Context context = getContext();

        setFontSize(
                TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 42, context.getResources().getDisplayMetrics()));
        setMainColour(ThemeManager.getThemeColour(context, android.R.attr.textColorTertiary));

        mainPaint.setAntiAlias(true);
        typePaint.setAntiAlias(true);
        percentagePaint.setAntiAlias(true);

        Typeface font = ThemeManager.getDefaultThemeFont(context, Typeface.NORMAL);

        mainPaint.setTypeface(font);
        typePaint.setTypeface(font);
        percentagePaint.setTypeface(font);

        mainPaint.setTextLocale(Locale.JAPANESE);

        linePaint.setColor(ThemeManager.getThemeColour(context, android.R.attr.textColorPrimary));
        typePaint.setColor(ThemeManager.getThemeColour(context, android.R.attr.textColorTertiary));
        linePaint.setStrokeWidth(context.getResources().getDimension(R.dimen.dividingLine));

        internalVerticalPadding = getResources().getDimensionPixelSize(R.dimen.logItemInternalVerticalPadding);
    }

    @Override
    protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight)
    {
        super.onSizeChanged(width, height, oldWidth, oldHeight);

        repositionItems(width, height);
    }

    private void repositionItems(int width, int height)
    {
        int contentWidth = width - getPaddingLeft() - getPaddingRight();
        int contentHeight = height - getPaddingTop() - getPaddingBottom() - (internalVerticalPadding * 2);

        questionXPoint = getPaddingLeft();
        slashXPoint = getPaddingLeft() + ((contentWidth - slashWidth) / 2);
        correctXPoint = slashXPoint - correctWidth;
        totalXPoint = slashXPoint + slashWidth;
        percentageXPoint = getPaddingLeft() + (contentWidth - percentageWidth);
        dataYPoint = getPaddingTop() + internalVerticalPadding +
                (((contentHeight + textHeight) / 2) - mainPaint.getFontMetrics().descent);

        lineXPoint1 = getPaddingLeft();
        lineXPoint2 = width - getPaddingRight();
        lineYPoint = height - getPaddingBottom() - linePaint.getStrokeWidth();
    }

    //ref: http://stackoverflow.com/questions/13273838/onmeasure-wrap-content-how-do-i-know-the-size-to-wrap
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        int desiredWidth = desiredWidth();

        int width = calculateSize(widthMeasureSpec, desiredWidth);
        int height = calculateSize(heightMeasureSpec, desiredHeight);

        setMeasuredDimension(width, height);
    }

    private int desiredWidth()
    {
        return Math.round((Math.max(questionWidth + correctWidth +
                        TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources().getDisplayMetrics()),
                totalWidth + percentageWidth) * 2) + slashWidth) + getPaddingLeft() + getPaddingRight();
    }

    private static int calculateSize(int measureSpec, int desired)
    {
        switch (MeasureSpec.getMode(measureSpec))
        {
            case MeasureSpec.EXACTLY:
                return MeasureSpec.getSize(measureSpec);
            case MeasureSpec.AT_MOST:
                return Math.min(desired, MeasureSpec.getSize(measureSpec));
            case MeasureSpec.UNSPECIFIED:
            default:
                return desired;
        }
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);

        correctFontSize();

        canvas.drawText(question, questionXPoint, dataYPoint, mainPaint);
        canvas.drawText(correctString, correctXPoint, dataYPoint, mainPaint);
        canvas.drawText(SLASH, slashXPoint, dataYPoint, mainPaint);
        canvas.drawText(totalString, totalXPoint, dataYPoint, mainPaint);
        canvas.drawText(percentageString, percentageXPoint, dataYPoint, percentagePaint);
        canvas.drawLine(lineXPoint1, lineYPoint, lineXPoint2, lineYPoint, linePaint);

        if ((type != QuestionType.KANA) && (type != QuestionType.VOCABULARY))
            paintType(canvas);
    }

    private void paintType(Canvas canvas)
    {
        String typeString = null;
        if (type == QuestionType.KANJI)
            typeString = getResources().getString(R.string.kanji_question_type_option_meaning);
        else if (type == QuestionType.KUN_YOMI)
            typeString = getResources().getString(R.string.kanji_question_type_option_kunyomi);
        else if (type == QuestionType.ON_YOMI)
            typeString = getResources().getString(R.string.kanji_question_type_option_onyomi);

        typeString = '(' + typeString + ')';
        float padding = mainPaint.measureText(" ");
        float typeXPoint = questionXPoint + questionWidth + padding;
        float availableSpace = correctXPoint - typeXPoint - padding;

        typePaint.setTextSize(originalFontSize / 4f);
        while (typePaint.measureText(typeString) > availableSpace)
            typePaint.setTextSize(typePaint.getTextSize() - 1);

        canvas.drawText(typeString, typeXPoint, dataYPoint, typePaint);
    }

    public void correctFontSize()
    {
        if (mainPaint.getTextSize() != originalFontSize)
            forceFontSize(originalFontSize);
        if (isDynamicSize)
        {
            while (desiredWidth() > getWidth())
                forceFontSize(mainPaint.getTextSize() - 1);
            repositionItems(getWidth(), getHeight());
        }
    }

    public void setFromRecord(QuestionRecord record)
    {
        setQuestion(record.getQuestion());
        setType(record.getType());
        setCorrectAnswers(record.getCorrectAnswers());
        setTotalAnswers(record.getCorrectAnswers() + record.getIncorrectAnswers());
    }

    public String getQuestion()
    {
        return question;
    }

    public int getCorrectAnswers()
    {
        return correctAnswers;
    }

    public int getTotalAnswers()
    {
        return totalAnswers;
    }

    public float getFontSize()
    {
        return originalFontSize;
    }

    public int getMainColour()
    {
        return mainPaint.getColor();
    }

    public boolean getIsDynamicSize()
    {
        return isDynamicSize;
    }

    public void setQuestion(String question)
    {
        this.question = question;
        updateAnswers();
    }

    public void setType(QuestionType type)
    {
        this.type = type;
        updateAnswers();
    }

    public void setCorrectAnswers(int correctAnswers)
    {
        this.correctAnswers = correctAnswers;
        updateAnswers();
    }

    public void setTotalAnswers(int totalAnswers)
    {
        this.totalAnswers = totalAnswers;
        updateAnswers();
    }

    public void setFontSize(float fontSize)
    {
        originalFontSize = fontSize;
        forceFontSize(fontSize);
        desiredHeight = Math.round(textHeight + linePaint.getStrokeWidth()) + getPaddingTop() + getPaddingBottom() +
                (internalVerticalPadding * 2);
    }

    private void forceFontSize(float fontSize)
    {
        mainPaint.setTextSize(fontSize);
        percentagePaint.setTextSize(fontSize);

        textHeight = mainPaint.getFontMetrics().descent - mainPaint.getFontMetrics().ascent;

        questionWidth = mainPaint.measureText(question);
        correctWidth = mainPaint.measureText(correctString);
        slashWidth = mainPaint.measureText(SLASH);
        totalWidth = mainPaint.measureText(totalString);
        percentageWidth = percentagePaint.measureText(percentageString);
    }

    public void setMainColour(int colour)
    {
        mainPaint.setColor(colour);
    }

    public void setIsDynamicSize(boolean isDynamicSize)
    {
        this.isDynamicSize = isDynamicSize;
    }

    private void updateAnswers()
    {
        if ((correctAnswers >= 0) && (totalAnswers >= 0))
        {
            correctString = DailyLogItem.parseCount(correctAnswers);
            totalString = DailyLogItem.parseCount(totalAnswers);
            float percentage = correctAnswers / (float) totalAnswers;
            percentageString = PERCENT_FORMATTER.format(percentage);
            percentagePaint.setColor(DailyLogItem.getPercentageColour(percentage, getContext()));

            questionWidth = mainPaint.measureText(question);
            correctWidth = mainPaint.measureText(correctString);
            slashWidth = mainPaint.measureText(SLASH);
            totalWidth = mainPaint.measureText(totalString);
            percentageWidth = percentagePaint.measureText(percentageString);
        }
    }
}


text:
'use strict';
/*global eventsApp*/

eventsApp.filter('durations', function() {
  return function(duration) {
    switch(duration) {
      case 1:
        return '30 mins';
      case 2:
        return '1 Hour';
      case 3:
        return 'Half Day';
      case 4:
        return 'Full Day';
      default:
        return "Unknown duration";

    }
  };
});


text:
import pytest

import pandas as pd
from pandas.tests.arrays.masked_shared import (
    ComparisonOps,
    NumericOps,
)

class TestComparisonOps(NumericOps, ComparisonOps):
    @pytest.mark.parametrize("other", [True, False, pd.NA, -1, 0, 1])
    def test_scalar(self, other, comparison_op, dtype):
        ComparisonOps.test_scalar(self, other, comparison_op, dtype)

    def test_compare_to_int(self, dtype, comparison_op):
        # GH 28930
        op_name = f"__{comparison_op.__name__}__"
        s1 = pd.Series([1, None, 3], dtype=dtype)
        s2 = pd.Series([1, None, 3], dtype="float")

        method = getattr(s1, op_name)
        result = method(2)

        method = getattr(s2, op_name)
        expected = method(2).astype("boolean")
        expected[s2.isna()] = pd.NA

        self.assert_series_equal(result, expected)

def test_equals():
    # GH-30652
    # equals is generally tested in /tests/extension/base/methods, but this
    # specifically tests that two arrays of the same class but different dtype
    # do not evaluate equal
    a1 = pd.array([1, 2, None], dtype="Int64")
    a2 = pd.array([1, 2, None], dtype="Int32")
    assert a1.equals(a2) is False


text:
#ifndef OSCAP_SOURCE_DOC_TYPE_H
#define OSCAP_SOURCE_DOC_TYPE_H

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <libxml/xmlreader.h>

#include "common/public/oscap.h"
#include "common/util.h"

OSCAP_HIDDEN_START;

/**
 * Determines the SCAP type of the document xmlTextReder. This function is deemed
 * to be private forever, as it moves with the reader context.
 * @param reader xmlTextReader to determine document type
 * @param doc_type determined document type (output parameter)
 * @returns -1 on error, 0 otherwise
 */
int oscap_determine_document_type_reader(xmlTextReader *reader, oscap_document_type_t *doc_type);

OSCAP_HIDDEN_END;
#endif


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Pholiota nana E. Horak

### Remarks
null


text:
class Room < ActiveRecord::Base

  # Associations
  has_many :sessions
end


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="action_settings">Settings</string>
    <string name="cap_manual">MANUAL</string>
    <string name="cap_bulbs">BULBS</string>
    <string name="cap_hue_sat_mode">HUE</string>
    <string name="cap_color_temp_mode">TEMPERATURE</string>
    <string name="groups">Groups</string>
    <string name="moods">Moods</string>
    <string name="mood_intro">Mood:</string>
    <string name="group_intro">Group:</string>
    <string name="accept">Okay</string>
    <string name="cancel">Cancel</string>
    <string name="register_success">Link successful</string>
    <string name="register_fail">Could not connect to bridge. Please make sure this device is connected to the same wifi as the hub and has internet access, then try again.</string>
    <string name="link_prompt">Press the link button on your hub</string>
    <string name="advanced">Advanced</string>
    <string name="auto_discover">Auto-Connect</string>
    <string name="contextmenu_delete">Delete</string>
    <string name="contextmenu_edit">Edit</string>
    <string name="contextmenu_rename">Rename</string>
    <string name="actionmenu_new_group">New Group</string>
    <string name="actionmenu_new_mood">New Mood</string>
    <string name="actionmenu_new_color">New State</string>
    <string name="actionmenu_new_alarm">New Alarm</string>
    <string name="hint_mood_name">mood name</string>
    <string name="hint_group_name">group name</string>
    <string name="hint_bulb_name">bulb name</string>
    <string name="brightness">Brightness</string>
    <string name="temperature">Color Temperature (K)</string>
    <string name="toggleColorLoop">Loop Colors :</string>
    <string name="rate_on_google_play">Rate on Google Play</string>
    <string name="nfc_tag_detected">Tag Detected</string>
    <string name="nfc_tag_not_detected">Tag Not Found</string>
    <string name="nfc_tag_write_prompt">Write to Tag</string>
    <string name="nfc_tag_write_success">Saved to Tag</string>
    <string name="nfc_tag_write_fail">Save to Tag Failed</string>
    <string name="nfc_disabled">NFC is not enabled. Turn it on in your device settings</string>
    <string name="nfc_read_done">Done</string>
    <string name="nfc_tag_read_success">NFC tag read</string>
    <string name="nfc_tag_not_supported">Your phone does not support writing data to this NFC tag!</string>
    <string name="alarms">Alarms</string>
    <string name="transition_intro">Fade In:</string>
    <string name="alarm_repeat">Repeat:</string>
    <string name="cap_short_every_day">EVERY DAY</string>
    <string name="next_scheduled_intro">Next LampShade alarm</string>
    <string name="hub_discovery_disclaimer">Searching for the hub. This may take a minute.</string>
    <string name="update_message">Please update LampShade to the newest version.</string>
    <string name="update_opt_out">Disable update reminders</string>
    <string name="update">Update</string>
    <string name="hub_connection_error">Not connected to hub!</string>
    <string name="empty_view_text">No alarms found…</string>
    <string name="cap_all">ALL</string>
    <string name="cap_on">ON</string>
    <string name="cap_off">OFF</string>
    <string name="broken_mood_link">Oops! This mood link cannot be read</string>
    <string name="update_required">This mood requires an updated version of LampShade</string>
    <string name="corrupted_mood">This mood cannot be read</string>
    <string name="contextmenu_delete_timeslot">Delete timeslot</string>
	<string name="contextmenu_delete_channel">Delete channel</string>
	<string name="grid_col_title_channels">Channels</string>
	<string name="infinite_loop">Loop</string>
	<string name="save">Save</string>
	<string name="cap_sample_state">SAMPLE</string>
	<string name="cap_recent_state">RECENT</string>
	<string name="share">Share</string>
	<string name="seconds">Seconds</string>
	<string name="preview">Preview</string>
	<string name="advanced_timeslot_limit">Sorry, moods are limited to 64 timeslots in this version</string>
	<string name="advanced_channel_limit">Sorry, moods are limited to 64 channels in this version</string>
	<string name="community_facebook">LampShade.io on Facebook</string>
	<string name="community_google_plus">LampShade.io on Google+</string>
	<string name="community_twitter">LampShade.io on Twitter</string>
	<string name="action_communities">Community and Support</string>
	<string name="community_message">Join the LampShade.io online community to share moods and discuss LampShade.io features</string>
	<string name="action_welcome">Welcome</string>
	<string name="welcome_message">Welcome to LampShade.io, a powerful app for controlling the Philips Hue smarthome lighting system</string>
	<string name="welcome_get_started">Connect to my Hue</string>
	<string name="welcome_get_hue">Buy a Philips Hue</string>
	<string name="unnamed_group">Unnamed Group</string>
	<string name="unnamed_mood">Unnamed Mood</string>
	<string name="empty_group_list_text">No groups found…</string>
	<string name="widget_alarms_label">LampShade Alarms</string>
	<string name="widget_groups_label">LampShade Groups</string>
	<string name="include_brightness">Include Brightness</string>
	<string name="action_play">Preview Mood</string>
	<string name="action_help">Help</string>
	<string name="minutes">Minutes</string>
	<string name="daily_mood_start_time">Start Time</string>
	<string name="timed_mood_start_time">Start Time</string>
	<string name="action_connections">Connections</string>
	<string name="action_bulbs">Bulbs</string>
	<string name="actionmenu_new_connection">Connect to a smart lighting device</string>
	<string name="prompt_new_connection_type">Select device type</string>
	<string name="prompt_local_address">Local address of Hub</string>
	<string name="hint_local_address">IP Address</string>
	<string name="prompt_remote_address">Remote access address (optional)</string>
	<string name="hint_remote_address">IP Address or URL</string>
	<string name="toast_hue_connection_updated">Connection Updated</string>
	<string name="notification_overflow_more">more</string>
	<string name="max_brightness">Mood Brightness</string>
	<string name="saved">Saved</string>
	<string name="action_connection_error">Connection Error</string>
    <string name="empty_list_connections">Not paired with any lights. Click the plus button to add a new connection.</string>
    <string name="empty_list_bulbs">Not paired with any lights. Go to the Connections page to setup lights.</string>
    <string name="empty_list_groups">Not paired with any lights. Go to the Connections page to setup lights.</string>
    <string name="mark_favorite">Favorite ★</string>
    <string name="mark_not_favorite">UnFavorite ☆</string>
    <string name="dialog_title_searching_for_lights">Searching for lights</string>
    <string name="dialog_title_import_mood">Shared Mood</string>
    <string name="language_prompt">Language</string>
    <string name="action_stop">Stop</string>
    <string name="action_stop_all">Stop All</string>
    <string name="widget_small_groups_label">LampShade Small Groups</string>
    <string name="settings_build_version">LampShade version</string>
    <string name="settings_use_system_language">Use system language</string>
    <string name="settings_nfc_controls_title">Show NFC quick controls</string>
    <string name="settings_nfc_controls_descriptor">When NFC tags read</string>
    <string name="settings_ignore_doze_title">Skip foreground check</string>
    <string name="settings_ignore_doze_descriptor">Only use if you know what you\'re doing. Your phone may cancel long-running moods.</string>
    <string name="settings_category_general">General</string>
    <string name="settings_category_about">About</string>
    <string name="doze_message">LampShade needs permission to run in the background.</string>

	<string name="help_title_gettingstarted">Getting Started</string>
	<string name="help_title_editingmoods">Creating and Editing Moods</string>
	<string name="help_title_alarms">Alarms</string>
	<string name="help_title_nfc">Using with NFC Tags</string>
	<string name="help_title_automationpluggin">Pluggin for Tasker/Locale/Llama</string>
	<string name="help_title_faq">FAQ</string>

	<string name="help_content_gettingstarted">Once you have wirelessly connected to your lights, you can begin controlling them.\n\nFirst, click on a light bulb or bulb group to select it.\n\nNext, you are shown a page of moods you may play on your selected bulb(s). Moods can be simple color paterns or dynamic lighting animations.\n\nDynamic moods will continue playing until stopped. To view ongoing moods, look for the LampShade icon in your device\'s notification bar. To stop a mood, play a simple mood(such as ON or OFF) on the same bulb(s).</string>
	<string name="help_content_editingmoods">Moods contain lighting states such as colors and on/off commands.\n\nWhile a mood is played on a group or bulb, these states take effect.\n\nThe states are set to take effect either immediately, over time relative to when the playing starts, or at specific times of the day while the mood is playing.\n\nChannels (columns of states) allow you to play multiple colors at the same time. Each time a mood is played on a group, the group\'s lights will be assigned equally among the channels, round-robin style.</string>
	<string name="help_content_alarms">\nAlarms allow you to schedule moods to play at some time in the future.\n\nAlarms can be set to repeat on specific days each week.\n\nWhen using alarms with moods that change in brightness over time(such as Gentle Sunrise), the alarm brightness bar sets the maximum brightness for that mood.\n\nAlarms are stored on your device, so they only take effect when your device can reach the lights over the network.</string>
	<string name="help_content_nfc">\nLampShade supports saving moods to electronic NFC tags.\n\nOnce a mood+group+brightness is saved on the tag, it will play anytime you touch the tag to your Android device (if the device is unlocked).\n\nTo use this feature, your device must support writing to NFC tags, and you need tags your device can write to.</string>
	<string name="help_content_automationpluggin">\nThe LampShade automation plugin supports many apps including Tasker, Locale, and Llama. These apps can use the plugin to play moods based on various conditions such as gps location, incoming notifications, and much more.\n\nThe plugin is accessed from within these apps, and provides a page for selecting which mood+group+brightness to trigger.</string>
	<string name="help_content_faq">Q. Why aren\'t my Philips lights changing to bright green?\nA. The Philips Hue regular and downlight models only contain Blue, Red and Yellow LEDs so they cannot display intense greens.\n\nQ. Why aren\'t my Philips lights changing to dark reds or blues?\nA. Your Philips lights might be running outdated software. Use the offcial Philips app to update the firmware on your hub and lightbulbs.\n\nQ. Do LampShade alarms work when I\'m away from home?\nA. LampShade alarms can only take effect when LampShade is connected to your lights. They will only work when away from home if you are using the remote access feature.</string>

	<string-array name="mood_types">
        <item>Simple</item>
        <item>Timed</item>
        <item>Daily</item>
    </string-array>
   	<string-array name="repeat_days">
        <item>Sunday</item>
        <item>Monday</item>
        <item>Tuesday</item>
        <item>Wednesday</item>
        <item>Thursday</item>
        <item>Friday</item>
        <item>Saturday</item>
    </string-array>
    <string-array name="cap_short_repeat_days">
        <item>SUN</item>
        <item>MON</item>
        <item>TUE</item>
        <item>WED</item>
        <item>THU</item>
        <item>FRI</item>
        <item>SAT</item>
    </string-array>
    <string-array name="transition_names_array">
        <item>Default</item>
        <item>1 Second</item>
        <item>10 Seconds</item>
        <item>1 Minute</item>
        <item>10 Minutes</item>
        <item>1 Hour</item>
    </string-array>
</resources>


text:
class Admin::UsersController < ApplicationController
  authorize_resource

  before_filter lambda { @roles = %w'admin contact_admin contact_user' }, only: [:edit, :update]

  def edit
    @user = User.find(params[:id])
  end

  def index
    @users = User.order(:name).all
  end

  def show
    @user = User.find(params[:id])
  end

  def update
    @user = User.find(params[:id])
    @user.assign_attributes(user_params)
    @user.roles = (params[:role_names] || []).join(',')
    if @user.save
      redirect_to(admin_users_url(), notice: 'User was updated successfully.')
    else
      render :edit
    end
  end

  private

  def user_params
    params.require(:user).permit(:is_active, :roles)
  end
end


text:
using System;
using System.IO;
using System.Collections.Specialized;
using System.Net;
using System.Net.Cache;
using System.Text;
using System.Web;
using System.Security.Cryptography;
using Newtonsoft.Json;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using SteamKit2;

namespace SteamTrade
{
    public class SteamWeb
    {
        public const string SteamCommunityDomain = "steamcommunity.com";
        public string Token { get; private set; }
        public string SessionId { get; private set; }
        public string TokenSecure { get; private set; }
        private CookieContainer _cookies = new CookieContainer();

        public string Fetch(string url, string method, NameValueCollection data = null, bool ajax = true, string referer = "")
        {
            using (HttpWebResponse response = Request(url, method, data, ajax, referer))
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(responseStream))
                    {
                        return reader.ReadToEnd();
                    }
                }
            }
        }

        public HttpWebResponse Request(string url, string method, NameValueCollection data = null, bool ajax = true, string referer = "")
        {
            //Append the data to the URL for GET-requests
            bool isGetMethod = (method.ToLower() == "get");
            string dataString = (data == null ? null : String.Join("&", Array.ConvertAll(data.AllKeys, key =>
                String.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(data[key]))
            )));

            if (isGetMethod && !String.IsNullOrEmpty(dataString))
            {
                url += (url.Contains("?") ? "&" : "?") + dataString;
            }
            //Console.WriteLine("Voila le dataString envoyé : "+dataString);
            //Console.WriteLine(url);
            //Setup the request
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = method;
            request.Accept = "application/json, text/javascript;q=0.9, */*;q=0.5";
            request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            //request.Host is set automatically
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
            request.Referer = string.IsNullOrEmpty(referer) ? "http://steamcommunity.com/trade/1" : referer;
            request.Timeout = 50000; //Timeout after 50 seconds
            request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Revalidate);
            request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;

            if (ajax)
            {
                request.Headers.Add("X-Requested-With", "XMLHttpRequest");
                request.Headers.Add("X-Prototype-Version", "1.7");
            }

            // Cookies
            request.CookieContainer = _cookies;

            // Write the data to the body for POST and other methods
            if (!isGetMethod && !String.IsNullOrEmpty(dataString))
            {
                byte[] dataBytes = Encoding.UTF8.GetBytes(dataString);
                request.ContentLength = dataBytes.Length;

                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(dataBytes, 0, dataBytes.Length);
                }
            }

            // Get the response
            return request.GetResponse() as HttpWebResponse;
        }

        /// <summary>
        /// Executes the login by using the Steam Website.
        /// </summary>
        public bool DoLogin(string username, string password)
        {
            var data = new NameValueCollection();
            data.Add("username", username);
            string response = Fetch("https://steamcommunity.com/login/getrsakey", "POST", data, false);
            GetRsaKey rsaJSON = JsonConvert.DeserializeObject<GetRsaKey>(response);

            // Validate
            if (!rsaJSON.success)
            {
                return false;
            }

            //RSA Encryption
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            RSAParameters rsaParameters = new RSAParameters();

            rsaParameters.Exponent = HexToByte(rsaJSON.publickey_exp);
            rsaParameters.Modulus = HexToByte(rsaJSON.publickey_mod);

            rsa.ImportParameters(rsaParameters);

            byte[] bytePassword = Encoding.ASCII.GetBytes(password);
            byte[] encodedPassword = rsa.Encrypt(bytePassword, false);
            string encryptedBase64Password = Convert.ToBase64String(encodedPassword);

            SteamResult loginJson = null;
            CookieCollection cookieCollection;
            string steamGuardText = "";
            string steamGuardId = "";
            do
            {
                Console.WriteLine("SteamWeb: Logging In...");

                bool captcha = loginJson != null && loginJson.captcha_needed == true;
                bool steamGuard = loginJson != null && loginJson.emailauth_needed == true;

                string time = Uri.EscapeDataString(rsaJSON.timestamp);
                string capGID = loginJson == null ? null : Uri.EscapeDataString(loginJson.captcha_gid);

                data = new NameValueCollection();
                data.Add("password", encryptedBase64Password);
                data.Add("username", username);

                // Captcha
                string capText = "";
                if (captcha)
                {
                    Console.WriteLine("SteamWeb: Captcha is needed.");
                    System.Diagnostics.Process.Start("https://steamcommunity.com/public/captcha.php?gid=" + loginJson.captcha_gid);
                    Console.WriteLine("SteamWeb: Type the captcha:");
                    capText = Uri.EscapeDataString(Console.ReadLine());
                }

                data.Add("captchagid", captcha ? capGID : "");
                data.Add("captcha_text", captcha ? capText : "");
                // Captcha end

                // SteamGuard
                if (steamGuard)
                {
                    Console.WriteLine("SteamWeb: SteamGuard is needed.");
                    Console.WriteLine("SteamWeb: Type the code:");
                    steamGuardText = Uri.EscapeDataString(Console.ReadLine());
                    steamGuardId = loginJson.emailsteamid;
                }

                data.Add("emailauth", steamGuardText);
                data.Add("emailsteamid", steamGuardId);
                // SteamGuard end

                data.Add("rsatimestamp", time);

                using(HttpWebResponse webResponse = Request("https://steamcommunity.com/login/dologin/", "POST", data, false))
                {
                    using(StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
                    {
                        string json = reader.ReadToEnd();
                        loginJson = JsonConvert.DeserializeObject<SteamResult>(json);
                        cookieCollection = webResponse.Cookies;
                    }
                }
            } while (loginJson.captcha_needed || loginJson.emailauth_needed);

            if (loginJson.success)
            {
                _cookies = new CookieContainer();
                foreach (Cookie cookie in cookieCollection)
                {
                    _cookies.Add(cookie);
                }
                SubmitCookies(_cookies);
                return true;
            }
            else
            {
                Console.WriteLine("SteamWeb Error: " + loginJson.message);
                return false;
            }

        }

        ///<summary>
        /// Authenticate using SteamKit2 and ISteamUserAuth.
        /// This does the same as SteamWeb.DoLogin(), but without contacting the Steam Website.
        /// </summary>
        /// <remarks>Should this one doesnt work anymore, use <see cref="SteamWeb.DoLogin"/></remarks>
        public bool Authenticate(string myUniqueId, SteamClient client, string myLoginKey)
        {
            Token = TokenSecure = "";
            SessionId = Convert.ToBase64String(Encoding.UTF8.GetBytes(myUniqueId));
            _cookies = new CookieContainer();

            using (dynamic userAuth = WebAPI.GetInterface("ISteamUserAuth"))
            {
                // generate an AES session key
                var sessionKey = CryptoHelper.GenerateRandomBlock(32);

                // rsa encrypt it with the public key for the universe we're on
                byte[] cryptedSessionKey = null;
                using (RSACrypto rsa = new RSACrypto(KeyDictionary.GetPublicKey(client.ConnectedUniverse)))
                {
                    cryptedSessionKey = rsa.Encrypt(sessionKey);
                }

                byte[] loginKey = new byte[20];
                Array.Copy(Encoding.ASCII.GetBytes(myLoginKey), loginKey, myLoginKey.Length);

                // aes encrypt the loginkey with our session key
                byte[] cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey);

                KeyValue authResult;

                try
                {
                    authResult = userAuth.AuthenticateUser(
                        steamid: client.SteamID.ConvertToUInt64(),
                        sessionkey: HttpUtility.UrlEncode(cryptedSessionKey),
                        encrypted_loginkey: HttpUtility.UrlEncode(cryptedLoginKey),
                        method: "POST",
                        secure: true
                        );
                }
                catch (Exception)
                {
                    Token = TokenSecure = null;
                    return false;
                }

                Token = authResult["token"].AsString();
                TokenSecure = authResult["tokensecure"].AsString();

                _cookies.Add(new Cookie("sessionid", SessionId, String.Empty, SteamCommunityDomain));
                _cookies.Add(new Cookie("steamLogin", Token, String.Empty, SteamCommunityDomain));
                _cookies.Add(new Cookie("steamLoginSecure", TokenSecure, String.Empty, SteamCommunityDomain));

                return true;
            }
        }

        /// <summary>
        /// Helper method to verify our precious cookies.
        /// </summary>
        /// <param name="cookies">CookieContainer with our cookies.</param>
        /// <returns>true if cookies are correct; false otherwise</returns>
        public bool VerifyCookies()
        {
            using (HttpWebResponse response = Request("http://steamcommunity.com/", "HEAD"))
            {
                return response.Cookies["steamLogin"] == null || !response.Cookies["steamLogin"].Value.Equals("deleted");
            }
        }

        static void SubmitCookies (CookieContainer cookies)
        {
            HttpWebRequest w = WebRequest.Create("https://steamcommunity.com/") as HttpWebRequest;

            w.Method = "POST";
            w.ContentType = "application/x-www-form-urlencoded";
            w.CookieContainer = cookies;

            w.GetResponse().Close();
        }

        private byte[] HexToByte(string hex)
        {
            if (hex.Length % 2 == 1)
                throw new Exception("The binary key cannot have an odd number of digits");

            byte[] arr = new byte[hex.Length >> 1];
            int l = hex.Length;

            for (int i = 0; i < (l >> 1); ++i)
            {
                arr[i] = (byte)((GetHexVal(hex[i << 1]) << 4) + (GetHexVal(hex[(i << 1) + 1])));
            }

            return arr;
        }

        private int GetHexVal(char hex)
        {
            int val = (int)hex;
            return val - (val < 58 ? 48 : 55);
        }

        public bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors)
        {
            // allow all certificates
            return true;
        }

    }

    // JSON Classes
    public class GetRsaKey
    {
        public bool success { get; set; }

        public string publickey_mod { get; set; }

        public string publickey_exp { get; set; }

        public string timestamp { get; set; }
    }

    public class SteamResult
    {
        public bool success { get; set; }

        public string message { get; set; }

        public bool captcha_needed { get; set; }

        public string captcha_gid { get; set; }

        public bool emailauth_needed { get; set; }

        public string emailsteamid { get; set; }

    }

}


text:
/* optional assembler bits */
#if defined(__GNUC__) && defined(__i386__)
#  include "src/asm_gcc_x86.c"
#endif

#if defined(__GNUC__) && defined(__amd64__)
/* No implementation for the moment. */
/* #  include "src/asm_gcc_x86_64.c" */
#endif

#if defined(_MSC_VER)
#  include "src/asm_msvc.c"
#endif


text:
from django.core.exceptions import ValidationError
import re

ERROR_TOO_LONG = 'MAC address is too long'

mac_pattern = re.compile(r'^([0-9a-f]{2}:){5}[0-9a-f]{2}$')

def validate_mac(mac):
    if mac == ERROR_TOO_LONG:
        raise ValidationError(ERROR_TOO_LONG)
    elif mac == '00:00:00:00:00:00':
        raise ValidationError('Invalid MAC address—to disable DHCP for this '
                              'interface, uncheck "Enable DHCP"')
    elif not mac_pattern.match(mac):
        raise ValidationError('Invalid MAC address')