text:
/**
 post reply box
 */

function table_insert_row(table, header, items) {
    var tr = document.createElement("tr");
    // insert header element
    var th = document.createElement("th");
    th.appendChild(header);
    tr.appendChild(th);
    // insert the rest of the elements
    for (var idx = 0; idx < items.length; idx ++ ) {
        var elem = document.createElement("td");
        elem.appendChild(items[idx]);
        tr.appendChild(elem);
    }
    table.appendChild(tr);
}

/**
 reply box
 */
function ReplyBox() {
    var elem = document.createElement("div");
    this.elem = elem;
    elem.setAttribute("class", "shadow shadow-box");
    // reference
    elem = document.createElement("input");
    elem.name = "reference";
    elem.type = "hidden";
    this.elem.appendChild(elem);

    var table = document.createElement("table");
    table.setAttribute("class", "postform");
    var tbody = document.createElement("tbody");

    var span = document.createElement("span");
    // name
    elem = document.createElement("input");
    elem.setAttribute("name", "name");
    elem.setAttribute("value", "Anonymous");
    this.name = elem;
    span.appendChild(elem);
    // error message
    var err_elem = document.createElement("span");
    span.appendChild(err_elem);
    this._error = err_elem;
    table_insert_row(tbody, document.createTextNode("Name"), [span]);

    // subject
    elem = document.createElement("input");
    elem.setAttribute("value", "");
    this.subject = elem;
    // submit
    var submit = document.createElement("button");
    submit.innerHTML = "reply";
    table_insert_row(tbody, document.createTextNode("Subject"), [elem]);
    this.submit = submit;

    // Comment
    elem = document.createElement("textarea");
    elem.setAttribute("cols", "40");
    elem.setAttribute("rows", "5");
    table_insert_row(tbody, document.createTextNode("Comment"), [elem]);
    this.message = elem;

    // file
    elem = document.createElement("input");
    elem.setAttribute("class", "postform_attachment");
    elem.setAttribute("type", "file");
    elem.setAttribute("multiple", "multiple");
    this.files = elem;
    table_insert_row(tbody, document.createTextNode("Files"), [elem]);

    // captcha
    elem = document.createElement("img");
    elem.alt = "captcha";
    table_insert_row(tbody, document.createTextNode("Captcha"), [elem]);
    this.captcha_img = elem;

    // captcha solution
    elem = document.createElement("input");
    elem.name = "captcha";
    elem.autocomplete = "off";
    table_insert_row(tbody, document.createTextNode("Solution"), [elem]);
    table_insert_row(tbody, document.createTextNode("Post"), [submit]);
    this.captcha_solution = elem;
    table.appendChild(tbody);
    this.elem.appendChild(table);
    document.body.appendChild(this.elem);
    $(this.elem).css("position", "fixed");
    $(this.elem).css("display", "none");
    this._open = false;
}

ReplyBox.prototype.result = function(msg, color) {
    var self = this;
    self._error.innerHTML = "";
    $(self._error).css("color", color);
    self._error.appendChild(document.createTextNode(msg));
    setTimeout(function() {
        $(self._error).fadeOut(1000, function() {
            self._error.innerHTML = "";
        });
    }, 1000);
}

ReplyBox.prototype.visible = function() {
    return this._open != false;
}

ReplyBox.prototype.makePost = function(info) {
    var self = this;
    var data = new FormData();
    data.append("name", self.name.value);
    data.append("subject", self.subject.value);
    data.append("captcha", self.captcha_solution.value);
    data.append("message", self.message.value);
    $(self.files.files).each(function(_, f) {
        data.append("attachment_uploaded", f);
    });
    data.append("reference", info.reference);
    return data;
}

ReplyBox.prototype.clear = function() {
    var self = this;
    self.name.value = "";
    self.subject.value = "";
    self.message.value = "";
    self.captcha_solution.value = "";
}

ReplyBox.prototype.reload = function() {
    var self = this;
    self.captcha_img.src = "/captcha/img?" + new Date().getTime();
}

ReplyBox.prototype.show = function(info) {
    var self = this;
    self.reload();
    self._open = true;
    console.log("reply box show for "+info.reference);
    $(self.elem).css("display", "inline-block");
    var off = $(info.elem).offset();
    $(self.elem).offset({
        top: off.top,
        left: $(info.elem).width() + off.left
    });
    self.submit.onclick = function(ev) {
        var post = self.makePost(info);
        var a = $.ajax({
            data: post,
            processData: false,
            contentType: false,
            url: info.url,
            method: "POST",
            dataType: "json"
        }).success(function(data, status, xhr) {
            if(data.message_id) {
                self.result("posted as "+data.message_id, "green");
                self.clear();
                setTimeout(function() {
                    self.hide();
                    if(data.url)
                        window.location = data.url;
                }, 1000);
            } else {
                self.result("error: " + data.error, "red");
            }
        }).fail(function() {
            self.result("request failed", "red");
        }).done(function() {
            self.reload();
        });
    };
}

ReplyBox.prototype.hide = function() {
    var self = this;
    if(!self.visible()) return;
    self._open = false;
    $(self.elem).fadeOut(400, function() {
        self.submit.onclick = function(ev) {};
    });
}

onready(function(){
    return; /* disabled */
    var replyBox = new ReplyBox();
    replyBox.hide();
    document.reply = replyBox;
    $(".post").each(function(_, elem) {
        var replyInfo = {
            show: false,
            url: (prefix || "/") + "post/" + elem.dataset.newsgroup + "/json",
            reference: elem.dataset.rootmsgid,
            board: elem.dataset.newsgroup,
            elem: elem
        };
        var elems = elem.getElementsByClassName("postreply");
        if(elems && elems[0]) {
            var e = elems[0].children[1];
            console.log("inject reply box into "+e);
            e.onclick = function(ev) {
                if(!replyInfo.show) {
                    // is hidden, show reply
                    replyBox.show(replyInfo);
                } else {
                    // is open, hide reply
                    replyBox.hide();
                }
                replyInfo.show = ! replyInfo.show;
                ev.preventDefault();
            }
        }
    });
});


text:
"""Signature Version 4 test suite.

AWS provides a test suite for signature version 4:

    http://docs.aws.amazon.com/general/latest/gr/signature-v4-test-suite.html

This module contains logic to run these tests.  The test files were
placed in ./aws4_testsuite, and we're using nose's test generators to
dynamically generate testcases based on these files.

"""
import os
import logging
import io
from six import BytesIO
from six.moves import BaseHTTPServer
import six

import nose.tools as t
from nose import with_setup

from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
from botocore.credentials import Credentials

try:
    from urllib.parse import urlsplit
    from urllib.parse import parse_qsl
except ImportError:
    from urlparse import urlsplit
    from urlparse import parse_qsl

CREDENTIAL_SCOPE = "KEYNAME/20110909/us-west-1/s3/aws4_request"
SECRET_KEY = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"
ACCESS_KEY = 'AKIDEXAMPLE'
DATE_STRING = 'Mon, 09 Sep 2011 23:36:00 GMT'
TIMESTAMP = '20110909T233600Z'

TESTSUITE_DIR = os.path.join(
    os.path.dirname(os.path.abspath(__file__)), 'aws4_testsuite')

# The following tests are not run.  Each test has a comment as
# to why the test is being ignored.
TESTS_TO_IGNORE = [
    # Bad POST syntax, python's HTTP parser chokes on this.
    'post-vanilla-query-space',
    # Bad POST syntax, python's HTTP parser chokes on this.
    'post-vanilla-query-nonunreserved',
    # Multiple query params of the same key not supported by
    # the SDKs.
    'get-vanilla-query-order-key-case',
    # Multiple query params of the same key not supported by
    # the SDKs.
    'get-vanilla-query-order-value',
]
if not six.PY3:
    TESTS_TO_IGNORE += [
        # NO support
        'get-header-key-duplicate',
        'get-header-value-order',
    ]

log = logging.getLogger(__name__)

class RawHTTPRequest(BaseHTTPServer.BaseHTTPRequestHandler):
    def __init__(self, raw_request):
        if isinstance(raw_request, six.text_type):
            raw_request = raw_request.encode('utf-8')
        self.rfile = BytesIO(raw_request)
        self.raw_requestline = self.rfile.readline()
        self.error_code = None
        self.error_message = None
        self.parse_request()

    def send_error(self, code, message):
        self.error_code = code
        self.error_message = message

def test_generator():
    for test_case in set(os.path.splitext(i)[0]
                         for i in os.listdir(TESTSUITE_DIR)):
        if test_case in TESTS_TO_IGNORE:
            log.debug("Skipping test: %s", test_case)
            continue
        yield (_test_signature_version_4, test_case)

def create_request_from_raw_request(raw_request):
    raw_request = raw_request.replace('http/1.1', 'HTTP/1.1')
    request = AWSRequest()
    raw = RawHTTPRequest(raw_request)
    if raw.error_code is not None:
        raise Exception(raw.error_message)
    request.method = raw.command
    for key, val in raw.headers.items():
        request.headers[key] = val
    request.data = raw.rfile.read().decode('utf-8')
    host = raw.headers.get('host', '')
    # For whatever reason, the BaseHTTPRequestHandler encodes
    # the first line of the response as 'iso-8859-1',
    # so we need decode this into utf-8.
    if isinstance(raw.path, six.text_type):
        raw.path = raw.path.encode('iso-8859-1').decode('utf-8')
    url = 'https://%s%s' % (host, raw.path)
    if '?' in url:
        split_url = urlsplit(url)
        params = dict(parse_qsl(split_url.query))
        request.url = split_url.path
        request.params = params
    else:
        request.url = url
    return request

def _test_signature_version_4(test_case):
    test_case = _SignatureTestCase(test_case)
    request = create_request_from_raw_request(test_case.raw_request)

    auth = SigV4Auth(test_case.credentials, 'host', 'us-east-1')
    auth.timestamp = TIMESTAMP

    actual_canonical_request = auth.canonical_request(request)
    assert_equal(actual_canonical_request, test_case.canonical_request,
                 test_case.raw_request, 'canonical_request')

    actual_string_to_sign = auth.string_to_sign(request,
                                                actual_canonical_request)
    assert_equal(actual_string_to_sign, test_case.string_to_sign,
                 test_case.raw_request, 'string_to_sign')

    auth.add_auth(request)
    actual_auth_header = request.headers['Authorization']
    assert_equal(actual_auth_header, test_case.authorization_header,
                 test_case.raw_request, 'authheader')

def assert_equal(actual, expected, raw_request, part):
    if actual != expected:
        message = "The %s did not match" % part
        message += "\nACTUAL:%r !=\nEXPECT:%r" % (actual, expected)
        message += '\nThe raw request was:\n%s' % raw_request
        raise AssertionError(message)

class _SignatureTestCase(object):
    def __init__(self, test_case):
        p = os.path.join
        # We're using io.open() because we need to open these files with
        # a specific encoding, and in 2.x io.open is the best way to do this.
        self.raw_request = io.open(p(TESTSUITE_DIR, test_case + '.req'),
                                   encoding='utf-8').read()
        self.canonical_request = io.open(
            p(TESTSUITE_DIR, test_case + '.creq'),
            encoding='utf-8').read().replace('\r', '')
        self.string_to_sign = io.open(
            p(TESTSUITE_DIR, test_case + '.sts'),
            encoding='utf-8').read().replace('\r', '')
        self.authorization_header = io.open(
            p(TESTSUITE_DIR, test_case + '.authz'),
            encoding='utf-8').read().replace('\r', '')
        self.signed_request = io.open(p(TESTSUITE_DIR, test_case + '.sreq'),
                                      encoding='utf-8').read()

        self.credentials = Credentials(ACCESS_KEY, SECRET_KEY)

redpajama_set_name: RedPajamaGithub


text:
using System.Runtime.Serialization;

namespace BungieNetPlatform.Enums {

	[DataContract]
	public enum ActivityType {

		[EnumMember]
		None = -1,

		[EnumMember]
		Create = 0,

		[EnumMember]
		Edit = 1,

		[EnumMember]
		Delete = 2,

		[EnumMember]
		Rate = 3,

		[EnumMember]
		Follow = 4,

		[EnumMember]
		Unfollow = 5,

		[EnumMember]
		Apply = 6,

		[EnumMember]
		Rescind = 7,

		[EnumMember]
		Approve = 8,

		[EnumMember]
		Deny = 9,

		[EnumMember]
		Kick = 10,

		[EnumMember]
		EditMembershipType = 11,

		[EnumMember]
		Like = 12,

		[EnumMember]
		Unlike = 13,

		[EnumMember]
		Share = 14,

		[EnumMember]
		TaggedGroup = 15,

		[EnumMember]
		TaggedTopic = 16,

		[EnumMember]
		AvatarChanged = 17,

		[EnumMember]
		DisplayNameChanged = 18,

		[EnumMember]
		TitleChanged = 19,

		[EnumMember]
		TitleUnlocked = 20,

		[EnumMember]
		GroupTopicCreate = 21,

		[EnumMember]
		GroupReplyCreate = 22,

		[EnumMember]
		Reply = 23,

		[EnumMember]
		ChangeClanName = 24,

		[EnumMember]
		GroupAllianceRejected = 26,

		[EnumMember]
		GroupAllianceApproved = 27,

		[EnumMember]
		GroupAllianceBroken = 28

	}

}


text:
class DoublyLinkedListNode(object):
    def __init__(self, value):
        self.value = value
        self.next = None
        self.prev = None

class SinglyLinkedListNode(object):
    def __init__(self, value):
        self.value = value
        self.next = None


text:
<?xml version="1.0"?>
<!--

-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../vendor/magento/mtf/Magento/Mtf/ObjectManager/etc/config.xsd">
    <preference for="Mage\Downloadable\Test\Handler\DownloadableProductInterface" type="\Mage\Downloadable\Test\Handler\Curl" />
</config>


text:
namespace ot
{
namespace data_type
{

template<typename T>
constexpr T GetAndMask(size_t bits)
{
	return bits == 0 ? 0 : (GetAndMask<T>(bits - 1) << 1) | 1;
}

template<typename TSigned, size_t integerBits, size_t fractionBits>
class SignedFixedPoint
{
	using TUnsigned = typename std::make_unsigned<TSigned>::type;
	static_assert(std::is_signed<TSigned>::value, "TSigned must be signed");
	static_assert(std::is_arithmetic<TSigned>::value, "TSigned must be arithmetic");
	static_assert(fractionBits != 0, "fractionBits must be positive");
	static_assert(integerBits != 0, "integerBits must be positive");

public:
	SignedFixedPoint(TUnsigned raw)
		: m_raw { raw }
	{
	}

	TSigned GetInteger() const
	{
		return GetTwosComplementSignedValue<TUnsigned, integerBits>(m_raw >> fractionBits);
	}

	TUnsigned GetFractionNumerator() const
	{
		return m_raw & GetAndMask<TUnsigned>(fractionBits);
	}

	TUnsigned GetFractionDenominator() const
	{
		return 1 << fractionBits;
	}

	float GetFloatValue() const
	{
		return GetInteger() + GetFractionNumerator() / static_cast<float>(GetFractionDenominator());
	}

private:
	TUnsigned m_raw;
};

class Fixed
{
public:
	Fixed(std::array<uint8_t, 2> integer, std::array<uint8_t, 2> fraction)
		: m_integer(integer)
		, m_fraction(fraction)
	{
	}

	float GetValue() const { return m_integer.GetValue() + m_fraction.GetValue() / static_cast<float>(2 << 15); }
	int_fast16_t GetInteger() const { return m_integer.GetValue(); }
	uint_fast16_t GetFraction() const { return m_fraction.GetValue(); }

private:
	signed_big_endian<int_fast16_t, 2> m_integer;
	big_endian<uint_fast16_t, 2> m_fraction;
};
static_assert(sizeof(Fixed) == 4, "Fixed must be 4 bytes");

class F2DOT14
{
public:
	F2DOT14(big_endian<uint_fast16_t, 2> bytes)
		: m_bytes(bytes)
	{
	}

	float GetValue() const { return GetInteger() + (GetFraction() / static_cast<float>(2 << 13)); }

	int_fast8_t GetInteger() const
	{
		return GetTwosComplementSignedValue<uint_least16_t, 2>(m_bytes.GetValue() >> 14);
	}

	uint_fast16_t GetFraction() const { return m_bytes.GetValue() & GetAndMask<uint_fast16_t>(14); }

private:
	big_endian<uint_fast16_t, 2> m_bytes;
};
static_assert(sizeof(F2DOT14) == 2, "F2DOT14 must be 2 bytes");

}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>org.apache.commons.codec (Apache Commons Codec 1.9 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

org.apache.commons.codec

Interfaces

BinaryDecoder

BinaryEncoder

Decoder

Encoder

StringDecoder

StringEncoder

Classes

CharEncoding

Charsets

StringEncoderComparator

Exceptions

DecoderException

EncoderException


text:
import hashlib

def hashfile(filepath):
    sha512 = hashlib.sha512()
    f = open(filepath, 'rb')
    try:
        sha512.update(f.read())
    finally:
        f.close()
    return sha512.hexdigest()


text:
package com.amazonaws.services.servicediscovery.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * A complex type that contains information about an operation that matches the criteria that you specified in a ListOperations request.
 *

 *
 * @see AWS
 *      API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class OperationSummary implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The ID for an operation.
     *

     */
    private String id;
    /**
     *

     * The status of the operation. Values include the following:
     *

     *

     *

     *

     * SUBMITTED: This is the initial state immediately after you submit a request.
     *

     *

     *

     *

     * PENDING: Cloud Map is performing the operation.
     *

     *

     *

     *

     * SUCCESS: The operation succeeded.
     *

     *

     *

     *

     * FAIL: The operation failed. For the failure reason, see ErrorMessage.
     *

     *

     *

     */
    private String status;

    /**
     *

     * The ID for an operation.
     *

     *
     * @param id
     *        The ID for an operation.
     */

    public void setId(String id) {
        this.id = id;
    }

    /**
     *

     * The ID for an operation.
     *

     *
     * @return The ID for an operation.
     */

    public String getId() {
        return this.id;
    }

    /**
     *

     * The ID for an operation.
     *

     *
     * @param id
     *        The ID for an operation.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public OperationSummary withId(String id) {
        setId(id);
        return this;
    }

    /**
     *

     * The status of the operation. Values include the following:
     *

     *

     *

     *

     * SUBMITTED: This is the initial state immediately after you submit a request.
     *

     *

     *

     *

     * PENDING: Cloud Map is performing the operation.
     *

     *

     *

     *

     * SUCCESS: The operation succeeded.
     *

     *

     *

     *

     * FAIL: The operation failed. For the failure reason, see ErrorMessage.
     *

     *

     *

     *
     * @param status
     *        The status of the operation. Values include the following:

     *

     *

     *

     *        SUBMITTED: This is the initial state immediately after you submit a request.
     *

     *

     *

     *

     *        PENDING: Cloud Map is performing the operation.
     *

     *

     *

     *

     *        SUCCESS: The operation succeeded.
     *

     *

     *

     *

     *        FAIL: The operation failed. For the failure reason, see ErrorMessage.
     *

     *

     * @see OperationStatus
     */

    public void setStatus(String status) {
        this.status = status;
    }

    /**
     *

     * The status of the operation. Values include the following:
     *

     *

     *

     *

     * SUBMITTED: This is the initial state immediately after you submit a request.
     *

     *

     *

     *

     * PENDING: Cloud Map is performing the operation.
     *

     *

     *

     *

     * SUCCESS: The operation succeeded.
     *

     *

     *

     *

     * FAIL: The operation failed. For the failure reason, see ErrorMessage.
     *

     *

     *

     *
     * @return The status of the operation. Values include the following:

     *

     *

     *

     *         SUBMITTED: This is the initial state immediately after you submit a request.
     *

     *

     *

     *

     *         PENDING: Cloud Map is performing the operation.
     *

     *

     *

     *

     *         SUCCESS: The operation succeeded.
     *

     *

     *

     *

     *         FAIL: The operation failed. For the failure reason, see ErrorMessage.
     *

     *

     * @see OperationStatus
     */

    public String getStatus() {
        return this.status;
    }

    /**
     *

     * The status of the operation. Values include the following:
     *

     *

     *

     *

     * SUBMITTED: This is the initial state immediately after you submit a request.
     *

     *

     *

     *

     * PENDING: Cloud Map is performing the operation.
     *

     *

     *

     *

     * SUCCESS: The operation succeeded.
     *

     *

     *

     *

     * FAIL: The operation failed. For the failure reason, see ErrorMessage.
     *

     *

     *

     *
     * @param status
     *        The status of the operation. Values include the following:

     *

     *

     *

     *        SUBMITTED: This is the initial state immediately after you submit a request.
     *

     *

     *

     *

     *        PENDING: Cloud Map is performing the operation.
     *

     *

     *

     *

     *        SUCCESS: The operation succeeded.
     *

     *

     *

     *

     *        FAIL: The operation failed. For the failure reason, see ErrorMessage.
     *

     *

     * @return Returns a reference to this object so that method calls can be chained together.
     * @see OperationStatus
     */

    public OperationSummary withStatus(String status) {
        setStatus(status);
        return this;
    }

    /**
     *

     * The status of the operation. Values include the following:
     *

     *

     *

     *

     * SUBMITTED: This is the initial state immediately after you submit a request.
     *

     *

     *

     *

     * PENDING: Cloud Map is performing the operation.
     *

     *

     *

     *

     * SUCCESS: The operation succeeded.
     *

     *

     *

     *

     * FAIL: The operation failed. For the failure reason, see ErrorMessage.
     *

     *

     *

     *
     * @param status
     *        The status of the operation. Values include the following:

     *

     *

     *

     *        SUBMITTED: This is the initial state immediately after you submit a request.
     *

     *

     *

     *

     *        PENDING: Cloud Map is performing the operation.
     *

     *

     *

     *

     *        SUCCESS: The operation succeeded.
     *

     *

     *

     *

     *        FAIL: The operation failed. For the failure reason, see ErrorMessage.
     *

     *

     * @return Returns a reference to this object so that method calls can be chained together.
     * @see OperationStatus
     */

    public OperationSummary withStatus(OperationStatus status) {
        this.status = status.toString();
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getId() != null)
            sb.append("Id: ").append(getId()).append(",");
        if (getStatus() != null)
            sb.append("Status: ").append(getStatus());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof OperationSummary == false)
            return false;
        OperationSummary other = (OperationSummary) obj;
        if (other.getId() == null ^ this.getId() == null)
            return false;
        if (other.getId() != null && other.getId().equals(this.getId()) == false)
            return false;
        if (other.getStatus() == null ^ this.getStatus() == null)
            return false;
        if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getId() == null) ? 0 : getId().hashCode());
        hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode());
        return hashCode;
    }

    @Override
    public OperationSummary clone() {
        try {
            return (OperationSummary) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.servicediscovery.model.transform.OperationSummaryMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
using Newtonsoft.Json;
using System.Net;

namespace HubSpot.Net
{
    public class HubSpotRefreshTokenInfoModel
    {
        [JsonProperty("token")]
        public string Token { get; set; }

        [JsonProperty("user")]
        public string UserEmail { get; set; }

        [JsonProperty("hub_domain")]
        public string HubDomain { get; set; }

        [JsonProperty("scopes")]
        public string[] Scopes { get; set; }

        [JsonProperty("hub_id")]
        public int HubId { get; set; }

        [JsonProperty("client_id")]
        public string AppClientId { get; set; }

        [JsonProperty("user_id")]
        public int HubSpotUserId { get; set; }

        public int UserId { get; set; }

        public HttpStatusCode StatusCode { get; set; }

    }
}


text:
'use strict';

angular.module('<%= appname %>')
    .factory('<%= camelName %>', function () {

        return {
        };

    });


text:
module.exports  = {

    // Convert an objecto to query string
    'toQueryString': function (parameters) {
        var queryString = _.reduce(parameters, function (components, value, key) {
            if(value !== undefined) {
                components.push( key + '=' + encodeURIComponent( value ) );
            }
            return components;
        },[]).join( '&' );
        if (queryString.length > 0) {
            queryString = '?' + queryString;
        }
        return queryString;
    }

};


text:
/*	$NetBSD: match_list.h,v 1.1.1.2 2013/01/02 18:59:13 tron Exp $	*/

#ifndef _MATCH_LIST_H_INCLUDED_
#define _MATCH_LIST_H_INCLUDED_

/*++
/* NAME
/*	match_list 3h
/* SUMMARY
/*	generic list-based pattern matching
/* SYNOPSIS
/*	#include <match_list.h>
/* DESCRIPTION
/* .nf

 /*
  * Utility library.
  */
#include <argv.h>

 /*
  * External interface.
  */
typedef struct MATCH_LIST MATCH_LIST;

typedef int (*MATCH_LIST_FN) (MATCH_LIST *, const char *, const char *);

struct MATCH_LIST {
    int     flags;			/* processing options */
    ARGV   *patterns;			/* one pattern each */
    int     match_count;		/* match function/argument count */
    MATCH_LIST_FN *match_func;		/* match functions */
    const char **match_args;		/* match arguments */
    int     error;			/* last operation */
};

#define MATCH_FLAG_NONE		0
#define MATCH_FLAG_PARENT	(1<<0)
#define MATCH_FLAG_RETURN	(1<<1)
#define MATCH_FLAG_ALL		(MATCH_FLAG_PARENT | MATCH_FLAG_RETURN)

extern MATCH_LIST *match_list_init(int, const char *, int,...);
extern int match_list_match(MATCH_LIST *,...);
extern void match_list_free(MATCH_LIST *);

 /*
  * The following functions are not part of the public interface. These
  * functions may be called only through match_list_match().
  */
extern int match_string(MATCH_LIST *, const char *, const char *);
extern int match_hostname(MATCH_LIST *, const char *, const char *);
extern int match_hostaddr(MATCH_LIST *, const char *, const char *);

/* LICENSE
/* .ad
/* .fi
/*	The Secure Mailer license must be distributed with this software.
/* AUTHOR(S)
/*	Wietse Venema
/*	IBM T.J. Watson Research
/*	P.O. Box 704
/*	Yorktown Heights, NY 10598, USA
/*--*/

#endif


text:
require File.dirname(__FILE__) + '/todo_next/version'

module TodoNext
  # Your code goes here...
end
require File.dirname(__FILE__) + '/todo_next/parser'

main = TOPLEVEL_BINDING.eval('self')
def main.todo_next(text, puts_code=true)
  code = TodoNext(text)
  if puts_code
    puts '---' ; puts code  ; puts '---'
  end
  eval code
end

def TodoNext(source)
  tree = TodoNext::Parser.parse(source)
  tree.to_rspec
end


text:
(function( $ ) {
  $.fn.DesignModeToolbar = function(iframe, o) {
    var o = $.extend({
      onButtonClick : function(button) {},
    }, o)

    this.initialize(iframe, o)
  }

  $.fn.DesignModeToolbar.prototype = {
    iframe : null,
    el     : null,

    initialize: function(iframe, o) {
      this.iframe = iframe
      this.o      = o
      this.x      = $.fn.DesignModeToolbarDefault // TODO make it pretty
      this.l      = $.fn.DesignModeLanguages.ru // TODO make it pretty

      this.build()
    },

    // Build Toolbar object
    build: function() {
      this.el = $(document.createElement('ul'))
        .insertBefore(this.iframe.el);

      $.each(this.x, $.proxy(function(key, value) {
        // Buttons with dropdown
        if (typeof value == 'object') {
          this.el.append(this.addDropdown(key, value))
        } else if (typeof value == 'boolean' && value == true) {
          var title = typeof this.l[key] == 'object' ? this.l[key].name : this.l[key]
          this.el.append(this.addButton(key, title, null))
        }
      }, this));
    },

    addButton: function(name, title, caption) {
      var li   = $(document.createElement('li')).addClass('button-' + name)
      var a    = $(document.createElement('a'))
        .attr('href', 'javascript:;')
        .attr('rel', name)
        .attr('title', title)
        .appendTo(li)
        // This executes a custom callback on button click
        .click($.proxy(function(){ this.o.onButtonClick.call(this, a) }, this))

      var span = $(document.createElement('span'))
        .html(caption)
        .appendTo(a);

      return li.append(a)
    },

    addDropdown: function(name, items) {
      var button = this.addButton(name, this.l[name].name, null)
      var ul     = $(document.createElement('ul'))

      button.addClass('has-dropdown')

      // Add dropdown items
      $.each(items, $.proxy(function(key, value) {
        if (typeof value == 'object') {
          var separator = true

          $.each(value, $.proxy(function(key2, value2) {
            if (value2 == true) {
              var item = this.addButton(key2, null, this.l[name][key][key2])
              if (separator) item.addClass('separator')

              ul.append(item)
              separator = false
            }
          }, this));
        } else if (typeof value == 'boolean' && value == true) {
          ul.append( this.addButton(key, null, this.l[name][key]) )
        }
      }, this));

      return button.append(ul)
    }
  }
})(jQuery);


text:
namespace boost {
namespace asio {
namespace detail {

template <typename T>
struct non_const_lvalue
{
#if defined(BOOST_ASIO_HAS_MOVE)
  explicit non_const_lvalue(T& t)
    : value(static_cast<typename conditional<
        is_same<T, typename decay<T>::type>::value,
          typename decay<T>::type&, T&&>::type>(t))
  {
  }

  typename conditional<is_same<T, typename decay<T>::type>::value,
      typename decay<T>::type&, typename decay<T>::type>::type value;
#else // defined(BOOST_ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
  explicit non_const_lvalue(const typename decay<T>::type& t)
    : value(t)
  {
  }

  typename decay<T>::type value;
#endif // defined(BOOST_ASIO_HAS_MOVE)
};

} // namespace detail
} // namespace asio
} // namespace boost

#include <boost/asio/detail/pop_options.hpp>

#endif // BOOST_ASIO_DETAIL_NON_CONST_LVALUE_HPP


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace Carbonfrost.Commons.Shared.Runtime.Components {

    [TypeConverter(typeof(ComponentNameConverter))]
    [Serializable]
    [Builder(typeof(ComponentNameBuilder))]
    public sealed class ComponentName
        : IEquatable<ComponentName>, IFormattable {

        private readonly string name;
        private readonly Version version;
        private readonly CultureInfo culture;
        private readonly ProcessorArchitecture architecture;
        private readonly byte[] publicKey;
        private readonly bool usePublicKeyToken;
        private readonly ComponentHash hash;
        [NonSerialized] private int hashCodeCache;

        private static readonly ComponentName s_instance = new ComponentName("Unknown", null); // $NON-NLS-1

        [SelfDescribingPriority(PriorityLevel.Low)]
        public ProcessorArchitecture Architecture { get { return architecture; } }

        [SelfDescribingPriority(PriorityLevel.High)]
        public CultureInfo Culture { get { return culture; } }

        public bool IsUnknown { get { return object.ReferenceEquals(this, ComponentName.Unknown); } }

        public ComponentHash Hash { get { return this.hash; } }

        [SelfDescribingPriority(PriorityLevel.High)]
        public string Name { get { return this.name; } }

        [SelfDescribingPriority(PriorityLevel.Low)]
        public ComponentNameQuality Quality {
            get {
                bool hasName = (Name != null && !Utility.IsAnonymousName(Name));
                bool hasVersion = (Version != null);
                bool hasPublicKey = (this.publicKey != null && this.publicKey.Length > 0);
                bool hasHash = (this.Hash != null);
                bool hasCulture = !object.Equals(this.Culture, CultureInfo.InvariantCulture);

                ComponentNameQuality result
                    = ((hasName) ? ComponentNameQuality.SpecifiedName : 0)
                    | ((hasVersion) ? ComponentNameQuality.SpecifiedVersion : 0)
                    | ((hasCulture) ? ComponentNameQuality.SpecifiedCulture : 0)
                    | ((hasPublicKey) ? ComponentNameQuality.SpecifiedPublicKey : 0)
                    | ((hasHash) ? ComponentNameQuality.SpecifiedHash : 0);
                return result;
            }
        }

        public static ComponentName Unknown { get { return s_instance; } }

        [SelfDescribingPriority(PriorityLevel.High)]
        public Version Version { get { return this.version; } }

        public ComponentName(string name, Version version)
            : this(name, version, null, null, CultureInfo.InvariantCulture) {}

        public ComponentName(string name, int majorVersion, int minorVersion, int build, int revision)
            : this(name, new Version(majorVersion, minorVersion, build, revision)) {}

        public ComponentName(string name, Version version, byte[] publicKey, byte[] hash, CultureInfo culture) {
            this.name = NameOrDefault(name);
            this.version = version;
            this.culture = culture ?? CultureInfo.InvariantCulture;
            this.publicKey = publicKey;

            if (hash != null) {
                this.hash = ComponentHash.Create(ComponentHashAlgorithm.MD5, hash);
            }
        }

        public ComponentName(string name, Version version,
                             byte[] publicKey, ComponentHash hash,
                             CultureInfo culture,
                             ProcessorArchitecture architecture)
            : this(name, version, publicKey, hash, culture, architecture, false)
        {
        }

        internal ComponentName(string name, Version version,
                               byte[] publicKey, ComponentHash hash,
                               CultureInfo culture,
                               ProcessorArchitecture architecture,
                               bool usePublicKeyToken)
        {
            this.name = NameOrDefault(name);
            this.version = version ?? new Version(0, 0, 0, 0);
            this.culture = culture ?? CultureInfo.InvariantCulture;
            this.usePublicKeyToken = usePublicKeyToken;
            this.publicKey = publicKey;

            this.architecture = architecture;

            this.hash = hash;
        }

        public static ComponentName FromAssemblyName(AssemblyName name) {
            if (name == null) { throw new ArgumentNullException("name"); } // $NON-NLS-1

            return new ComponentName(
                name.Name, name.Version, name.GetPublicKey(),
                null, name.CultureInfo, name.ProcessorArchitecture);
        }

        public static bool TryParse(string text, out ComponentName result) {
            return _TryParse(text, out result) == null;
        }

        internal static Exception _TryParse(string text, out ComponentName result) {
            result = null;

            if (text == null)
                return new ArgumentNullException("text"); // $NON-NLS-1
            if (text.Length == 0)
                return Failure.EmptyString("text");

            string[] items = text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            if (items.Length == 1)
                return _TryParseShortForm(text, out result);

            try {
                string name = items[0];

                Dictionary<string, string> lookup = new Dictionary<string, string>();
                for (int i = 1; i < items.Length; i++) {
                    string s = items[i];
                    int index = s.IndexOf('=');
                    if (index < 0) {
                        throw Failure.NotParsable("text", typeof(ComponentName)); // $NON-NLS-1

                    } else {
                        string key = s.Substring(0, index).Trim();
                        string value = s.Substring(index + 1).Trim();
                        lookup.Add(key, value);
                    }
                }

                ComponentNameBuilder builder = new ComponentNameBuilder();
                builder.Name = name;

                Exception exception = builder.ParseDictionary(lookup);
                if (exception == null) {
                    result = builder.Build();
                    return null;
                } else
                    return exception;

            } catch (ArgumentException a) {
                return Failure.NotParsable("text", typeof(ComponentName), a); // $NON-NLS-1

            } catch (FormatException f) {
                return Failure.NotParsable("text", typeof(ComponentName), f); // $NON-NLS-1
            }
        }

        static Exception _TryParseShortForm(string text,
                                            out ComponentName result)
        {
            // Name=1.0-ABCD-en-x86
            result = null;
            string[] items = text.Split('=');
            if (items.Length == 1) {
                result = new ComponentName(text, null);
                return null;
            }

            if (items.Length != 2)
                return ParseError();

            string[] qualifiers = items[1].Split('-');

            Version version;
            ProcessorArchitecture arch = ProcessorArchitecture.None;
            CultureInfo culture = null;
            int cultureStart = 1;
            int cultureLength = qualifiers.Length - 1;
            byte[] key = null;

            if (!Version.TryParse(qualifiers[0], out version))
                return ParseError();

            if (Enum.TryParse(qualifiers[qualifiers.Length - 1], true, out arch)) {
                cultureLength--;
            }

            if (qualifiers.Length > 1 && qualifiers[1].Length > 2) {
                try {
                    key = Utility.ConvertHexToBytes(qualifiers[1], false);
                    cultureStart++;
                } catch (FormatException) {
                }
            }

            try {
                string cultureText =
                    string.Join("-", qualifiers.Skip(cultureStart).Take(cultureLength));

                if (cultureText.Length > 0)
                    culture = CultureInfo.GetCultureInfo(cultureText);

            } catch (CultureNotFoundException) {
                return ParseError();
            }

            result = new ComponentName(items[0], version, key, null, culture, arch, true);
            return null;
        }

        private static Exception ParseError() {
            return Failure.NotParsable("text", typeof(ComponentName));
        }

        public static ComponentName Parse(string text) {
            ComponentName result;
            Exception ex = _TryParse(text, out result);
            if (ex == null)
                return result;
            else
                throw ex;
        }

        public byte[] GetPublicKey() {
            if (publicKey == null || usePublicKeyToken) {
                return Empty<byte>.Array;
            } else {
                return (byte[]) this.publicKey.Clone();
            }
        }

        public byte[] GetPublicKeyToken() {
            if (usePublicKeyToken)
                return publicKey ?? Empty<byte>.Array;

            if (publicKey == null) {
                return Empty<byte>.Array;
            } else {
                SHA1 sha1 = SHA1.Create();
                byte[] hashed = sha1.ComputeHash(publicKey);
                byte[] result = new byte[8];
                Array.Copy(hashed, hashed.Length - 8, result, 0, 8);
                Array.Reverse(result);
                return result;
            }
        }

        public AssemblyName ToAssemblyName() {
            return new AssemblyName(this.ToString());
        }

        public bool Matches(ComponentName name) {
            if (name == null)
                throw new ArgumentNullException("name");
            if (object.ReferenceEquals(this, name))
                return true;
            else
                return this.Name == name.Name
                    && BlobMatches(this, name)
                    && CultureMatches(this.Culture, name.Culture)
                    && VersionMatches(this.Version, name.Version);
        }

        static bool CultureMatches(CultureInfo a, CultureInfo b) {
            return a == null || (a.Equals(b));
        }

        static bool BlobMatches(ComponentName a, ComponentName b) {
            if (a.publicKey == null)
                return true;

            // TODO Possible (but highly unlikely) that this comparison needs to support the full key
            return a.GetPublicKeyToken().SequenceEqual(b.GetPublicKeyToken());
        }

        static bool VersionMatches(Version a, Version b) {
            return a == null || (a.Major == b.Major
                                 && a.Minor == b.Minor
                                 && (a.Build == -1 || a.Build == b.Build)
                                 && (a.Revision == -1 || a.Revision == b.Revision));
        }

        #region 'Object' overrides.

        public override int GetHashCode() {
            if (hashCodeCache == 0) {
                int hashCode = 0;
                unchecked {
                    hashCode += 1000000007 * name.GetHashCode();
                    if (version != null) {
                        hashCode += 1000000009 * version.GetHashCode();
                    }
                    if (culture != null) {
                        hashCode += 1000000021 * culture.GetHashCode();
                    }
                    if (publicKey != null) {
                        hashCode += 1000000087 * publicKey.GetHashCode();
                    }
                    if (hash != null) {
                        hashCode += 1000000093 * hash.GetHashCode();
                    }

                    hashCode += 37 * usePublicKeyToken.GetHashCode();
                    hashCode += 1000000097 * architecture.GetHashCode();
                }

                this.hashCodeCache = hashCode;
                if (this.hashCodeCache == 0) { hashCodeCache++; }
            }

            return this.hashCodeCache;
        }

        public override bool Equals(object obj) {
            ComponentName myIdentity = obj as ComponentName;

            if (myIdentity == null) {
                return false;
            } else if (this == obj) {
                return true;
            } else {

                return this.name == myIdentity.name
                    && object.Equals(this.version, myIdentity.version)
                    && object.Equals(this.culture, myIdentity.culture)
                    && object.Equals(this.usePublicKeyToken, myIdentity.usePublicKeyToken)
                    && this.GetPublicKeyEncoding() == myIdentity.GetPublicKeyEncoding()
                    && this.architecture == myIdentity.architecture
                    && object.Equals(this.Hash, myIdentity.Hash);
            }
        }

        public override string ToString() {
            StringBuilder result = new StringBuilder();

            // Carbonfrost.Framework, Version=1.0, Culture=en-US, PublicKey=deadbeef, Hash=MD5:deadbeef, Architecture=...
            // Carbonfrost.Framework;version:1.0;culture:en-US;publicKey:deadbeef;hash:MD5:deadbeef;os:...;architecture:...
            result.Append(this.name);

            if (this.version != null) {
                result.Append(", Version="); // $NON-NLS-1
                result.Append(version.ToString());
            }

            if (this.culture != null) {
                result.Append(", Culture="); // $NON-NLS-1

                if (this.culture.Equals(CultureInfo.InvariantCulture))
                    result.Append("neutral");
                else
                    result.Append(culture.ToString());
            }

            if (this.publicKey != null) {
                string t = Utility.BytesToHex(this.GetPublicKeyToken(), true);
                result.Append(", PublicKeyToken="); // $NON-NLS-1
                result.Append(t);
            }

            if (this.hash != null) {
                result.Append(", Hash="); // $NON-NLS-1
                result.Append(this.hash);
            }

            if (this.architecture != ProcessorArchitecture.None) {
                result.Append(", Architecture="); // $NON-NLS-1
                result.Append(this.architecture);
            }

            return result.ToString();
        }

        #endregion

        #region 'IEquatable`1' implementation.

        bool IEquatable<ComponentName>.Equals(ComponentName other) {
            return Equals(other);
        }

        #endregion

        private string GetPublicKeyEncoding() {
            if (this.publicKey == null) {
                return string.Empty;
            } else {
                return Utility.BytesToHex(this.publicKey, true);
            }
        }

        static string NameOrDefault(string name) {
            if (string.IsNullOrEmpty(name))
                return Guid.NewGuid().ToString();
            else return name;
        }

        public string ToString(string format, IFormatProvider formatProvider = null) {
            if (string.IsNullOrEmpty(format))
                format = "G";

            switch (format[0]) {
                case 'g':
                case 'G':
                    return ToString();

                case 's':
                    return ConvertToShortString();

                case 'c':
                    return Culture.Name;

                default:
                    throw new FormatException();
            }
        }

        private string ConvertToShortString() {
            StringBuilder sb = new StringBuilder();
            sb.Append(Name);
            sb.Append('=');
            sb.Append(Version);

            if (this.publicKey != null) {
                sb.Append('-');
                sb.Append(GetPublicKeyEncoding());
            }

            if (Culture != null) {
                sb.Append('-');
                sb.Append(Culture);
            }

            if (Architecture != ProcessorArchitecture.None) {
                sb.Append('-');
                sb.Append(Architecture.ToString().ToLowerInvariant());
            }

            return sb.ToString();
        }

    }
}


text:
<?php

/***************************************************************************
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version. Although none of the code may be
 *   sold. If you have been sold this script, get a refund.
 ***************************************************************************/

define('InAdmin', 1);
$current_page = 'banners';
include '../common.php';
include INCLUDE_PATH . 'functions_admin.php';
include 'loggedin.inc.php';

$id = $_REQUEST['id'];

if (isset($_POST['action']) && $_POST['action'] == 'update')
{
	if (empty($_POST['name']) || empty($_POST['company']) || empty($_POST['email']))
	{
		$template->assign_block_vars('alerts', array('TYPE' => 'error', 'MESSAGE' => $ERR_047));
		$USER = $_POST;
	}
	elseif (!preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+([\.][a-z0-9-]+)+$/i', $_POST['email']))
	{
		$template->assign_block_vars('alerts', array('TYPE' => 'error', 'MESSAGE' => $ERR_008));
		$USER = $_POST;
	}
	else
	{
		// Update database
		$query = "UPDATE " . $DBPrefix . "bannersusers SET
					name = :name,
					company = :company,
					email = :email
					WHERE id = :id";
		$params = array();
		$params[] = array(':name', $_POST['name'], 'str');
		$params[] = array(':company', $_POST['company'], 'str');
		$params[] = array(':email', $_POST['email'], 'str');
		$params[] = array(':id', $id, 'int');
		$db->query($query, $params);
		header('location: managebanners.php');
		exit;
	}
}
else
{
	$query = "SELECT * FROM " . $DBPrefix . "bannersusers WHERE id = :id";
	$params = array();
	$params[] = array(':id', $id, 'int');
	$db->query($query, $params);
	if ($db->numrows() > 0)
	{
		$USER = $db->result();
	}
}

$template->assign_vars(array(
		'ID' => $id,
		'NAME' => (isset($USER['name'])) ? $USER['name'] : '',
		'COMPANY' => (isset($USER['company'])) ? $USER['company'] : '',
		'EMAIL' => (isset($USER['email'])) ? $USER['email'] : ''
		));

include 'header.php';
$template->set_filenames(array(
		'body' => 'editbanneruser.tpl'
		));
$template->display('body');
include 'footer.php';
?>


text:
@class UIImageView, UILabel, UIView, UIViewController<TNDRURLNavigableProtocol>;

@interface TNDRCardCell : UICollectionViewCell
{
    BOOL _liked;
    BOOL _shouldUseCardSnapshot;
    BOOL _shouldAllowUndoButtonForPlusUsers;
    id <TNDRRecommendationViewControllerCardCellInteractionHandler> _interactionHandler;
    id <TNDRCardCellViewProvider> _viewProvider;
    id <TNDRCardCellStackControl> _stackControlDelegate;
    UIViewController<TNDRURLNavigableProtocol> *_stackViewController;
    UIView *_contents;
    UIImageView *_likeStampView;
    UIImageView *_passStampView;
    UILabel *_rewindLabel;
    UIView *_contentViewContainerView;
    UIView *_secondaryViewContainerView;
    UIView *_strongContentView;
    UIView *_strongSecondaryView;
}

- (void).cxx_destruct;
- (void)applyLayoutAttributes:(id)arg1;
@property(retain, nonatomic) UIView *contentViewContainerView; // @synthesize contentViewContainerView=_contentViewContainerView;
@property(retain, nonatomic) UIView *contents; // @synthesize contents=_contents;
- (id)initWithFrame:(struct CGRect)arg1;
@property(nonatomic) __weak id <TNDRRecommendationViewControllerCardCellInteractionHandler> interactionHandler; // @synthesize interactionHandler=_interactionHandler;
@property(retain, nonatomic) UIImageView *likeStampView; // @synthesize likeStampView=_likeStampView;
@property(nonatomic) BOOL liked; // @synthesize liked=_liked;
@property(retain, nonatomic) UIImageView *passStampView; // @synthesize passStampView=_passStampView;
- (void)prepareForReuse;
- (void)returnContentsViewToCell;
@property(retain, nonatomic) UILabel *rewindLabel; // @synthesize rewindLabel=_rewindLabel;
@property(retain, nonatomic) UIView *secondaryViewContainerView; // @synthesize secondaryViewContainerView=_secondaryViewContainerView;
- (void)setFrame:(struct CGRect)arg1;
@property(nonatomic) BOOL shouldAllowUndoButtonForPlusUsers; // @synthesize shouldAllowUndoButtonForPlusUsers=_shouldAllowUndoButtonForPlusUsers;
@property(nonatomic) BOOL shouldUseCardSnapshot; // @synthesize shouldUseCardSnapshot=_shouldUseCardSnapshot;
@property(nonatomic) __weak id <TNDRCardCellStackControl> stackControlDelegate; // @synthesize stackControlDelegate=_stackControlDelegate;
@property(nonatomic) __weak UIViewController<TNDRURLNavigableProtocol> *stackViewController; // @synthesize stackViewController=_stackViewController;
@property(retain, nonatomic) UIView *strongContentView; // @synthesize strongContentView=_strongContentView;
@property(retain, nonatomic) UIView *strongSecondaryView; // @synthesize strongSecondaryView=_strongSecondaryView;
@property(nonatomic) __weak id <TNDRCardCellViewProvider> viewProvider; // @synthesize viewProvider=_viewProvider;
- (void)setup;
- (void)setupCardBackground;
- (void)setupContentViewContainerView;
- (void)setupSecondaryViewContainerView;
- (void)setupcontents;

@end


text:
package de.etecture.opensource.dynamicresources.api;

/**
 *
 * @author rhk
 * @version
 * @since
 */
public class ResourceException extends Exception {
    private static final long serialVersionUID = 1L;

    /**
     * Creates a new instance of
     * ResourceException without detail message.
     */
    public ResourceException() {
    }

    /**
     * Constructs an instance of
     * ResourceException with the specified detail message.
     *
     * @param msg the detail message.
     */
    public ResourceException(String msg) {
        super(msg);
    }

    public ResourceException(String message, Throwable cause) {
        super(message, cause);
    }

    public ResourceException(Throwable cause) {
        super(cause);
    }
}


text:
sidebar_label: ElementHandle.$
---

# ElementHandle.$() method

Queries the current element for an element matching the given selector.

#### Signature:

```typescript
class ElementHandle {
  $<Selector extends string>(
    selector: Selector
  ): Promise<ElementHandle<NodeFor<Selector>> | null>;
}
```

## Parameters

| Parameter | Type     | Description                |
| --------- | -------- | -------------------------- |
| selector  | Selector | The selector to query for. |

**Returns:**

Promise<[ElementHandle](./puppeteer.elementhandle.md)<[NodeFor](./puppeteer.nodefor.md)<Selector>> \| null>

A [element handle](./puppeteer.elementhandle.md) to the first element matching the given selector. Otherwise, `null`.


text:
module EntropyPassword
  module EntropyCalculator
    # NIST entropy
    def self.calculate(password, repeats_weakened = true)
      if repeats_weakened
        bits_with_repeats_weakened(password)
      else
        bits(password)
      end
    end

    def self.bits(password)
      length = password.length
      bits = if length > 20
               4 +  (7*2)+(12*1.5)+length - 20
             elsif length > 8
               4 + (7 * 2) + ((length - 8) * - 1.5)
             elsif length > 1
               4 + ((length - 1) * 2)
             else
               (length == 1 ? 4 : 0)

             end
      bits + NISTBonusBits.bonus_bits(password)
    end

    def self.bits_with_repeats_weakened(password)
      resolver = EntropyResolver.new
      bits = password.chars.each.with_index.inject(0) do |result, (char, index)|
        char_value = resolver.entropy_for(char)
        result += bit_value_at_position(index, char_value)
      end
      bits + NISTBonusBits.bonus_bits(password)
    end

    private

      def self.bit_value_at_position(position, base = 1)
        if position > 19
          return base
        elsif position > 7
          return base * 1.5
        elsif position > 0
          return base * 2
        else
          return 4
        end
      end

    class EntropyResolver
      BASE_VALUE = 1
      REPEAT_WEAKENING_FACTOR = 0.75

      attr_reader :char_multiplier
      def initialize
        @char_multiplier = {}
      end

      def entropy_for(char)
        ordinal_value = char.ord
        char_multiplier[ordinal_value] ||= BASE_VALUE
        char_value = char_multiplier[ordinal_value]
        char_multiplier[ordinal_value] = char_multiplier[ordinal_value] * REPEAT_WEAKENING_FACTOR
        return char_value
      end
    end
  end
end


text:
package com.facebook.imagepipeline.datasource;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

import com.facebook.common.executors.CallerThreadExecutor;
import com.facebook.datasource.DataSource;
import com.facebook.datasource.DataSubscriber;
import com.facebook.imagepipeline.listener.RequestListener;
import com.facebook.imagepipeline.producers.BaseConsumer;
import com.facebook.imagepipeline.producers.Consumer;
import com.facebook.imagepipeline.producers.Producer;
import com.facebook.imagepipeline.producers.SettableProducerContext;
import org.junit.*;
import org.junit.runner.*;
import org.mockito.*;
import org.robolectric.*;

@RunWith(RobolectricTestRunner.class)
public class ProducerToDataSourceAdapterTest {

  @Mock public RequestListener mRequestListener;

  private static final boolean FINISHED = true;
  private static final boolean NOT_FINISHED = false;
  private static final boolean WITH_RESULT = true;
  private static final boolean WITHOUT_RESULT = false;
  private static final boolean FAILED = true;
  private static final boolean NOT_FAILED = false;
  private static final boolean LAST = true;
  private static final boolean INTERMEDIATE = false;
  private static final int NO_INTERACTIONS = 0;
  private static final int ON_NEW_RESULT = 1;
  private static final int ON_FAILURE = 2;

  private static final Exception NPE = new NullPointerException();
  private static final String mRequestId = "requestId";

  private Object mResult1;
  private Object mResult2;
  private Object mResult3;
  private Exception mException;

  private DataSubscriber<Object> mDataSubscriber1;
  private DataSubscriber<Object> mDataSubscriber2;

  private SettableProducerContext mSettableProducerContext;
  private Producer<Object> mProducer;
  private Consumer<Object> mInternalConsumer;

  private DataSource<Object> mDataSource;

  @Before
  public void setUp() {
    MockitoAnnotations.initMocks(this);
    mResult1 = new Object();
    mResult2 = new Object();
    mResult3 = new Object();
    mException = mock(Exception.class);

    mDataSubscriber1 = mock(DataSubscriber.class);
    mDataSubscriber2 = mock(DataSubscriber.class);

    mSettableProducerContext = mock(SettableProducerContext.class);
    when(mSettableProducerContext.getId()).thenReturn(mRequestId);
    when(mSettableProducerContext.isPrefetch()).thenReturn(true);
    mProducer = mock(Producer.class);
    mDataSource = ProducerToDataSourceAdapter.create(
        mProducer,
        mSettableProducerContext,
        mRequestListener);
    ArgumentCaptor<Consumer> captor = ArgumentCaptor.forClass(Consumer.class);
    verify(mRequestListener).onRequestStart(
        mSettableProducerContext.getImageRequest(),
        mSettableProducerContext.getCallerContext(),
        mRequestId,
        mSettableProducerContext.isPrefetch());
    verify(mProducer).produceResults(captor.capture(), any(SettableProducerContext.class));
    mInternalConsumer = captor.getValue();

    mDataSource.subscribe(mDataSubscriber1, CallerThreadExecutor.getInstance());
  }

  /* verification helpers */

  private void verifyState(
      boolean isFinished,
      boolean hasResult,
      Object result,
      boolean hasFailed,
      Throwable failureCause) {
    DataSource<Object> dataSource = mDataSource;
    assertEquals("isFinished", isFinished, dataSource.isFinished());
    assertEquals("hasResult", hasResult, dataSource.hasResult());
    assertSame("getResult", result, dataSource.getResult());
    assertEquals("hasFailed", hasFailed, dataSource.hasFailed());
    if (failureCause == NPE) {
      assertNotNull("failure", dataSource.getFailureCause());
      assertSame("failure", NullPointerException.class, dataSource.getFailureCause().getClass());
    } else {
      assertSame("failure", failureCause, dataSource.getFailureCause());
    }
  }

  private void verifyNoMoreInteractionsAndReset() {
    verifyNoMoreInteractions(mRequestListener, mDataSubscriber1, mDataSubscriber2);
    reset(mRequestListener, mDataSubscriber1, mDataSubscriber2);
  }

  /* state verification methods */

  private void verifyInitial() {
    verifyState(NOT_FINISHED, WITHOUT_RESULT, null, NOT_FAILED, null);
    verifyNoMoreInteractionsAndReset();
  }

  private void verifyWithResult(Object result, boolean isLast) {
    verifyState(isLast, result != null, result, NOT_FAILED, null);
    verifyNoMoreInteractionsAndReset();
  }

  private void verifyFailed(Object result, Throwable throwable) {
    verifyState(FINISHED, result != null, result, FAILED, throwable);
    verifyNoMoreInteractionsAndReset();
  }

  private void verifyClosed(boolean isFinished, Throwable throwable) {
    verifyState(isFinished, WITHOUT_RESULT, null, throwable != null, throwable);
    verifyNoMoreInteractionsAndReset();
  }

  /* event testing helpers */

  private void testSubscribe(int expected) {
    mDataSource.subscribe(mDataSubscriber2, CallerThreadExecutor.getInstance());
    switch (expected) {
      case NO_INTERACTIONS:
        break;
      case ON_NEW_RESULT:
        verify(mDataSubscriber2).onNewResult(mDataSource);
        break;
      case ON_FAILURE:
        verify(mDataSubscriber2).onFailure(mDataSource);
        break;
    }
    verifyNoMoreInteractionsAndReset();
  }

  private void testNewResult(
      Object result,
      boolean isLast,
      int numSubscribers) {
    mInternalConsumer.onNewResult(result, BaseConsumer.simpleStatusForIsLast(isLast));
    if (isLast) {
      verify(mRequestListener).onRequestSuccess(
          mSettableProducerContext.getImageRequest(),
          mRequestId,
          mSettableProducerContext.isPrefetch());
    }
    if (numSubscribers >= 1) {
      verify(mDataSubscriber1).onNewResult(mDataSource);
    }
    if (numSubscribers >= 2) {
      verify(mDataSubscriber2).onNewResult(mDataSource);
    }
    verifyWithResult(result, isLast);
  }

  private void testFailure(Object result, int numSubscribers) {
    mInternalConsumer.onFailure(mException);
    verify(mRequestListener).onRequestFailure(
        mSettableProducerContext.getImageRequest(),
        mRequestId,
        mException,
        mSettableProducerContext.isPrefetch());
    if (numSubscribers >= 1) {
      verify(mDataSubscriber1).onFailure(mDataSource);
    }
    if (numSubscribers >= 2) {
      verify(mDataSubscriber2).onFailure(mDataSource);
    }
    verifyFailed(result, mException);
  }

  private void testClose(Throwable throwable) {
    mDataSource.close();
    verifyClosed(FINISHED, throwable);
  }

  private void testClose(boolean isFinished, int numSubscribers) {
    mDataSource.close();
    if (!isFinished) {
      verify(mRequestListener).onRequestCancellation(mRequestId);
      if (numSubscribers >= 1) {
        verify(mDataSubscriber1).onCancellation(mDataSource);
      }
      if (numSubscribers >= 2) {
        verify(mDataSubscriber2).onCancellation(mDataSource);
      }
    }
    verifyClosed(isFinished, null);
  }

  @Test
  public void testInitialState() {
    verifyInitial();
  }

  @Test
  public void test_C_a() {
    testClose(NOT_FINISHED, 1);
    testSubscribe(NO_INTERACTIONS);
  }

  @Test
  public void test_C_I_a() {
    testClose(NOT_FINISHED, 1);
    mInternalConsumer.onNewResult(mResult2, Consumer.NO_FLAGS);
    verifyClosed(NOT_FINISHED, null);
    testSubscribe(NO_INTERACTIONS);
  }

  @Test
  public void test_C_L_a() {
    testClose(NOT_FINISHED, 1);
    mInternalConsumer.onNewResult(mResult2, Consumer.IS_LAST);
    verifyClosed(NOT_FINISHED, null);
    testSubscribe(NO_INTERACTIONS);
  }

  @Test
  public void testC_F_a() {
    testClose(NOT_FINISHED, 1);
    mInternalConsumer.onFailure(mException);
    verifyClosed(NOT_FINISHED, null);
    testSubscribe(NO_INTERACTIONS);
  }

  @Test
  public void test_I_a_C() {
    testNewResult(mResult1, INTERMEDIATE, 1);
    testSubscribe(ON_NEW_RESULT);
    testClose(NOT_FINISHED, 2);
  }

  @Test
  public void test_I_I_a_C() {
    testNewResult(mResult1, INTERMEDIATE, 1);
    testNewResult(mResult2, INTERMEDIATE, 1);
    testSubscribe(ON_NEW_RESULT);
    testClose(NOT_FINISHED, 2);
  }

  @Test
  public void test_I_I_L_a_C() {
    testNewResult(mResult1, INTERMEDIATE, 1);
    testNewResult(mResult2, INTERMEDIATE, 1);
    testNewResult(mResult3, LAST, 1);
    testSubscribe(ON_NEW_RESULT);
    testClose(FINISHED, 2);
  }

  @Test
  public void test_I_I_F_a_C() {
    testNewResult(mResult1, INTERMEDIATE, 1);
    testNewResult(mResult2, INTERMEDIATE, 1);
    testFailure(mResult2, 1);
    testSubscribe(ON_FAILURE);
    testClose(mException);
  }

  @Test
  public void test_I_L_a_C() {
    testNewResult(mResult1, INTERMEDIATE, 1);
    testNewResult(mResult2, LAST, 1);
    testSubscribe(ON_NEW_RESULT);
    testClose(FINISHED, 2);
  }

  @Test
  public void test_I_F_a_C() {
    testNewResult(mResult1, INTERMEDIATE, 1);
    testFailure(mResult1, 1);
    testSubscribe(ON_FAILURE);
    testClose(mException);
  }

  @Test
  public void test_L_a_C() {
    testNewResult(mResult1, LAST, 1);
    testSubscribe(ON_NEW_RESULT);
    testClose(FINISHED, 2);
  }

  @Test
  public void test_L_I_a_C() {
    testNewResult(mResult1, LAST, 1);
    mInternalConsumer.onNewResult(mResult2, Consumer.NO_FLAGS);
    verifyWithResult(mResult1, LAST);
    testSubscribe(ON_NEW_RESULT);
    testClose(FINISHED, 2);
  }

  @Test
  public void test_L_L_a_C() {
    testNewResult(mResult1, LAST, 1);
    mInternalConsumer.onNewResult(mResult2, Consumer.IS_LAST);
    verifyWithResult(mResult1, LAST);
    testSubscribe(ON_NEW_RESULT);
    testClose(FINISHED, 2);
  }

  @Test
  public void test_L_F_a_C() {
    testNewResult(mResult1, LAST, 1);
    mInternalConsumer.onFailure(mException);
    verifyWithResult(mResult1, LAST);
    testSubscribe(ON_NEW_RESULT);
    testClose(FINISHED, 2);
  }

  @Test
  public void test_F_a_C() {
    testFailure(null, 1);
    testSubscribe(ON_FAILURE);
    testClose(mException);
  }

  @Test
  public void test_F_I_a_C() {
    testFailure(null, 1);
    mInternalConsumer.onNewResult(mResult1, Consumer.NO_FLAGS);
    verifyFailed(null, mException);
    testSubscribe(ON_FAILURE);
    testClose(mException);
  }

  @Test
  public void test_F_L_a_C() {
    testFailure(null, 1);
    mInternalConsumer.onNewResult(mResult1, Consumer.IS_LAST);
    verifyFailed(null, mException);
    testSubscribe(ON_FAILURE);
    testClose(mException);
  }

  @Test
  public void test_F_F_a_C() {
    testFailure(null, 1);
    mInternalConsumer.onFailure(mock(Throwable.class));
    verifyFailed(null, mException);
    testSubscribe(ON_FAILURE);
    testClose(mException);
  }

  @Test
  public void test_NI_S_a_C() {
    mInternalConsumer.onNewResult(null, Consumer.NO_FLAGS);
    verify(mDataSubscriber1).onNewResult(mDataSource);
    verifyWithResult(null, INTERMEDIATE);

    testNewResult(mResult1, LAST, 1);
    testSubscribe(ON_NEW_RESULT);
    testClose(FINISHED, 2);
  }

  @Test
  public void test_NI_a_NL_C() {
    mInternalConsumer.onNewResult(null, Consumer.NO_FLAGS);
    verify(mDataSubscriber1).onNewResult(mDataSource);
    verifyWithResult(null, INTERMEDIATE);

    testSubscribe(NO_INTERACTIONS);

    mInternalConsumer.onNewResult(null, Consumer.IS_LAST);
    verify(mRequestListener).onRequestSuccess(
        mSettableProducerContext.getImageRequest(),
        mRequestId,
        mSettableProducerContext.isPrefetch());
    verify(mDataSubscriber1).onNewResult(mDataSource);
    verify(mDataSubscriber2).onNewResult(mDataSource);
    verifyWithResult(null, LAST);

    testClose(FINISHED, 2);
  }

  @Test
  public void test_I_NL_a_C() {
    testNewResult(mResult1, INTERMEDIATE, 1);

    mInternalConsumer.onNewResult(null, Consumer.IS_LAST);
    verify(mRequestListener).onRequestSuccess(
        mSettableProducerContext.getImageRequest(),
        mRequestId,
        mSettableProducerContext.isPrefetch());
    verify(mDataSubscriber1).onNewResult(mDataSource);
    verifyWithResult(null, LAST);

    testSubscribe(ON_NEW_RESULT);
    testClose(FINISHED, 2);
  }
}


text:
const chai = require('chai');
const chaiHttp = require('chai-http');
const sinon = require('sinon');

const sampleData = require('../../../sample-data');
const TestHelper = require('../../../test-helper');

const assert = chai.assert;
const expect = chai.expect;

chai.use(chaiHttp);

describe('Integration - DELETE /household-members/:uuid', function() {
  let controllers;
  let models;
  let server;
  const testHelper = new TestHelper();

  let deleteMemberSpy;

  let householdMemberUuid;
  let user1Token;
  let user1Uuid;
  let user2Token;
  let user2Uuid;

  before('get server', async function() {
    this.timeout(30000);
    const app = await testHelper.getApp();
    controllers = app.get('controllers');
    models = app.get('models');
    server = await testHelper.getServer();
  });

  before('create sinon spies', function() {
    deleteMemberSpy = sinon.spy(controllers.HouseholdCtrl, 'deleteMember');
  });

  after('restore sinon spies', function() {
    deleteMemberSpy.restore();
  });

  after('cleanup', async function() {
    await testHelper.cleanup();
  });

  beforeEach('create user 1', async function() {
    const apiCall = await models.Audit.ApiCall.create();
    user1Uuid = await controllers.UserCtrl.signUp({
      auditApiCallUuid: apiCall.get('uuid'),
      email: sampleData.users.user1.email,
      firstName: sampleData.users.user1.firstName,
      lastName: sampleData.users.user1.lastName,
      password: sampleData.users.user1.password,
    });
  });

  beforeEach('create user 1 token', async function() {
    user1Token = await controllers.UserCtrl.getToken(user1Uuid);
  });

  beforeEach('create user 2', async function() {
    const apiCall = await models.Audit.ApiCall.create();
    user2Uuid = await controllers.UserCtrl.signUp({
      auditApiCallUuid: apiCall.get('uuid'),
      email: sampleData.users.user2.email,
      firstName: sampleData.users.user2.firstName,
      lastName: sampleData.users.user2.lastName,
      password: sampleData.users.user2.password,
    });
  });

  beforeEach('create user 2 token', async function() {
    user2Token = await controllers.UserCtrl.getToken(user2Uuid);
  });

  beforeEach('create household member', async function() {
    const apiCall = await models.Audit.ApiCall.create({
      user_uuid: user1Uuid,
    });
    householdMemberUuid = await controllers.HouseholdCtrl.createMember({
      auditApiCallUuid: apiCall.get('uuid'),
      name: sampleData.users.user1.firstName,
    });
  });

  afterEach('reset history for sinon spies', function() {
    deleteMemberSpy.resetHistory();
  });

  afterEach('truncate tables', async function() {
    this.timeout(10000);
    await testHelper.truncateTables();
  });

  it('should return 401 with no auth token', async function() {
    const res = await chai.request(server)
      .delete(`/household-members/${householdMemberUuid}`)
      .set('Content-Type', 'application/vnd.api+json');
    expect(res).to.have.status(401);
    assert.deepEqual(res.body, {
      errors: [{
        detail: 'Unauthorized',
      }],
    });
    assert.strictEqual(deleteMemberSpy.callCount, 0);
  });

  it('should return 404 with the wrong auth token', async function() {
    const res = await chai.request(server)
      .delete(`/household-members/${householdMemberUuid}`)
      .set('Content-Type', 'application/vnd.api+json')
      .set('Authorization', `Bearer ${user2Token}`);
    expect(res).to.have.status(404);
    assert.deepEqual(res.body, {
      errors: [{
        detail: 'Unable to find member.',
      }],
    });

    assert.strictEqual(deleteMemberSpy.callCount, 1);
    const deleteMemberParams = deleteMemberSpy.getCall(0).args[0];
    assert.isOk(deleteMemberParams.auditApiCallUuid);
    assert.strictEqual(deleteMemberParams.householdMemberUuid, householdMemberUuid);
  });

  it('should return 204 with the correct auth token', async function() {
    const res = await chai.request(server)
      .delete(`/household-members/${householdMemberUuid}`)
      .set('Content-Type', 'application/vnd.api+json')
      .set('Authorization', `Bearer ${user1Token}`);
    expect(res).to.have.status(204);
    assert.deepEqual(res.body, {});

    // Validate HouseholdCtrl.deleteMember call.
    assert.strictEqual(deleteMemberSpy.callCount, 1);
    const deleteMemberParams = deleteMemberSpy.getCall(0).args[0];
    assert.isOk(deleteMemberParams.auditApiCallUuid);
    assert.strictEqual(deleteMemberParams.householdMemberUuid, householdMemberUuid);

    // Validate Audit API call.
    const apiCall = await models.Audit.ApiCall.findOne({
      attributes: [
        'http_method',
        'ip_address',
        'route',
        'user_agent',
        'user_uuid',
        'uuid',
      ],
      where: {
        uuid: deleteMemberParams.auditApiCallUuid,
      },
    });
    assert.isOk(apiCall);
    assert.strictEqual(apiCall.get('http_method'), 'DELETE');
    assert.isOk(apiCall.get('ip_address'));
    assert.strictEqual(apiCall.get('route'), `/household-members/${householdMemberUuid}`);
    assert.isOk(apiCall.get('user_agent'));
    assert.strictEqual(apiCall.get('user_uuid'), user1Uuid);
  });
});


text:
<?php

namespace Zend\Db\ResultSet\Exception;

use Zend\Db\Exception;

interface ExceptionInterface extends Exception\ExceptionInterface
{
}


text:
namespace base {
namespace {

// Returns a handle to the battery interface identified by |interface_data|, or
// nullopt if the request failed. |devices| is a device information set that
// contains battery devices information, obtained with ::SetupDiGetClassDevs().
base::win::ScopedHandle GetBatteryHandle(
    HDEVINFO devices,
    SP_DEVICE_INTERFACE_DATA* interface_data) {
  // Query size required to hold |interface_detail|.
  DWORD required_size = 0;
  ::SetupDiGetDeviceInterfaceDetail(devices, interface_data, nullptr, 0,
                                    &required_size, nullptr);
  DWORD error = ::GetLastError();
  if (error != ERROR_INSUFFICIENT_BUFFER)
    return base::win::ScopedHandle();

  // |interface_detail->DevicePath| is variable size.
  std::vector<uint8_t> raw_buf(required_size);
  auto* interface_detail =
      reinterpret_cast<SP_DEVICE_INTERFACE_DETAIL_DATA*>(raw_buf.data());
  interface_detail->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);

  BOOL success = ::SetupDiGetDeviceInterfaceDetail(
      devices, interface_data, interface_detail, required_size, nullptr,
      nullptr);
  if (!success)
    return base::win::ScopedHandle();

  base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
                                                base::BlockingType::MAY_BLOCK);
  base::win::ScopedHandle battery(
      ::CreateFile(interface_detail->DevicePath, GENERIC_READ | GENERIC_WRITE,
                   FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING,
                   FILE_ATTRIBUTE_NORMAL, nullptr));
  return battery;
}

// Returns the current tag for `battery` handle, BATTERY_TAG_INVALID if there is
// no battery present in this interface or nullopt on retrieval error.
// See
// https://docs.microsoft.com/en-us/windows/win32/power/ioctl-battery-query-tag
absl::optional<ULONG> GetBatteryTag(HANDLE battery) {
  ULONG battery_tag = 0;
  ULONG wait = 0;
  DWORD bytes_returned = 0;
  BOOL success = ::DeviceIoControl(
      battery, IOCTL_BATTERY_QUERY_TAG, &wait, sizeof(wait), &battery_tag,
      sizeof(battery_tag), &bytes_returned, nullptr);
  if (!success) {
    if (::GetLastError() == ERROR_FILE_NOT_FOUND) {
      // No battery present in this interface.
      //
      // TODO(crbug.com/1191045): Change CHECK to DCHECK in October 2022 after
      // verifying that there are no crash reports.
      CHECK_EQ(battery_tag, static_cast<ULONG>(BATTERY_TAG_INVALID));
      return battery_tag;
    }
    // Retrieval error.
    return absl::nullopt;
  }
  return battery_tag;
}

// Returns BATTERY_INFORMATION structure containing battery information, given
// battery handle and tag, or nullopt if the request failed. Battery handle and
// tag are obtained with GetBatteryHandle() and GetBatteryTag(), respectively.
absl::optional<BATTERY_INFORMATION> GetBatteryInformation(HANDLE battery,
                                                          ULONG battery_tag) {
  BATTERY_QUERY_INFORMATION query_information = {};
  query_information.BatteryTag = battery_tag;
  query_information.InformationLevel = BatteryInformation;
  BATTERY_INFORMATION battery_information = {};
  DWORD bytes_returned;
  BOOL success = ::DeviceIoControl(
      battery, IOCTL_BATTERY_QUERY_INFORMATION, &query_information,
      sizeof(query_information), &battery_information,
      sizeof(battery_information), &bytes_returned, nullptr);
  if (!success)
    return absl::nullopt;
  return battery_information;
}

// Returns BATTERY_STATUS structure containing battery state, given battery
// handle and tag, or nullopt if the request failed. Battery handle and tag are
// obtained with GetBatteryHandle() and GetBatteryTag(), respectively.
absl::optional<BATTERY_STATUS> GetBatteryStatus(HANDLE battery,
                                                ULONG battery_tag) {
  BATTERY_WAIT_STATUS wait_status = {};
  wait_status.BatteryTag = battery_tag;
  BATTERY_STATUS battery_status;
  DWORD bytes_returned;
  BOOL success = ::DeviceIoControl(
      battery, IOCTL_BATTERY_QUERY_STATUS, &wait_status, sizeof(wait_status),
      &battery_status, sizeof(battery_status), &bytes_returned, nullptr);
  if (!success)
    return absl::nullopt;
  return battery_status;
}

}  // namespace

class BatteryLevelProviderWin : public BatteryLevelProvider {
 public:
  BatteryLevelProviderWin() = default;
  ~BatteryLevelProviderWin() override = default;

  void GetBatteryState(
      base::OnceCallback<void(const absl::optional<BatteryState>&)> callback)
      override {
    // This is run on |blocking_task_runner_| since `GetBatteryStateImpl()` has
    // blocking calls and can take several seconds to complete.
    blocking_task_runner_->PostTaskAndReplyWithResult(
        FROM_HERE,
        base::BindOnce(&BatteryLevelProviderWin::GetBatteryStateImpl),
        base::BindOnce(&BatteryLevelProviderWin::OnBatteryStateObtained,
                       weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
  }

 private:
  static absl::optional<BatteryState> GetBatteryStateImpl();

  void OnBatteryStateObtained(
      base::OnceCallback<void(const absl::optional<BatteryState>&)> callback,
      const absl::optional<BatteryState>& battery_state) {
    std::move(callback).Run(battery_state);
  }

  // TaskRunner used to run blocking `GetBatteryStateImpl()` queries, sequenced
  // to avoid the performance cost of concurrent calls.
  scoped_refptr<base::SequencedTaskRunner> blocking_task_runner_{
      base::ThreadPool::CreateSequencedTaskRunner(
          {base::MayBlock(),
           base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN})};

  base::WeakPtrFactory<BatteryLevelProviderWin> weak_ptr_factory_{this};
};

std::unique_ptr<BatteryLevelProvider> BatteryLevelProvider::Create() {
  return std::make_unique<BatteryLevelProviderWin>();
}

// static
absl::optional<BatteryLevelProvider::BatteryState>
BatteryLevelProviderWin::GetBatteryStateImpl() {
  // Proactively mark as blocking to fail early, since calls below may also
  // trigger ScopedBlockingCall.
  base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
                                                base::BlockingType::MAY_BLOCK);

  // Battery interfaces are enumerated at every sample to detect when a new
  // interface is added, and avoid holding dangling handles when a battery is
  // disconnected.
  base::win::ScopedDevInfo devices(::SetupDiGetClassDevs(
      &GUID_DEVICE_BATTERY, 0, 0, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE));
  if (!devices.is_valid()) {
    return absl::nullopt;
  }

  std::vector<BatteryDetails> battery_details_list;

  // The algorithm to enumerate battery devices is taken from
  // https://docs.microsoft.com/en-us/windows/win32/power/enumerating-battery-devices
  // Limit search to 8 batteries max. A system may have several battery slots
  // and each slot may hold an actual battery.
  for (DWORD device_index = 0; device_index < 8; ++device_index) {
    SP_DEVICE_INTERFACE_DATA interface_data = {};
    interface_data.cbSize = sizeof(interface_data);

    BOOL success =
        ::SetupDiEnumDeviceInterfaces(devices.get(), 0, &GUID_DEVCLASS_BATTERY,
                                      device_index, &interface_data);
    if (!success) {
      // Enumeration ended normally.
      if (::GetLastError() == ERROR_NO_MORE_ITEMS)
        break;
      // Error.
      return absl::nullopt;
    }

    base::win::ScopedHandle battery =
        GetBatteryHandle(devices.get(), &interface_data);
    if (!battery.IsValid())
      return absl::nullopt;

    absl::optional<ULONG> battery_tag = GetBatteryTag(battery.Get());
    if (!battery_tag.has_value()) {
      return absl::nullopt;
    } else if (battery_tag.value() == BATTERY_TAG_INVALID) {
      // No battery present in this interface.
      continue;
    }

    auto battery_information =
        GetBatteryInformation(battery.Get(), *battery_tag);
    if (!battery_information.has_value()) {
      return absl::nullopt;
    }

    auto battery_status = GetBatteryStatus(battery.Get(), *battery_tag);
    if (!battery_status.has_value()) {
      return absl::nullopt;
    }

    battery_details_list.push_back(BatteryDetails(
        {.is_external_power_connected =
             !!(battery_status->PowerState & BATTERY_POWER_ON_LINE),
         .current_capacity = battery_status->Capacity,
         .full_charged_capacity = battery_information->FullChargedCapacity,
         .charge_unit =
             ((battery_information->Capabilities & BATTERY_CAPACITY_RELATIVE)
                  ? BatteryLevelUnit::kRelative
                  : BatteryLevelUnit::kMWh)}));
  }

  return MakeBatteryState(battery_details_list);
}

}  // namespace base


text:
#include <stdio.h>
#include <stdlib.h>
#include <sys/fcntl.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <stdint.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <time.h>
#include <stdarg.h>

#define APP_NAME "stm32w-wireshark"
#define VERSION "0.1, 11 April 2012"

#define TRUE 1
#define FALSE 0

// Define error codes used internally
const static int ERR_INVALID_CHANNEL = -60 ;
const static int ERR_INVALID_ADDRESS = -61 ;
const static int ERR_TIMEOUT = - 62 ;

// Output formats
const static int FORMAT_PCAP = 1;
const static int FORMAT_HEX = 2;

// PCAP constants
const static int PCAP_MAGIC = 0xa1b2c3d4;
const static short PCAP_VERSION_MAJOR = 2;
const static short PCAP_VERSION_MINOR = 4;
const static int PCAP_TZ = 0;				// thiszone: GMT to local correction
const static int PCAP_SIGFIGS = 0;			// sigfigs: accuracy of timestamps
const static int PCAP_SNAPLEN = 128;		// snaplen: max len of packets, in octets
const static int PCAP_LINKTYPE = 0xc3;		// data link type DLT_IEEE802_15_4 (see <pcap/bpf.h>)

// The debug level set with the -d command line switch
int debug_level = 0;

// Use -q flag to enable quiet mode. Warning messages will be suppressed.
int quiet_mode = FALSE;

// Set to true in signal_handler to signal exit from main loop
int exit_flag = FALSE;

void debug (int level, const char *msg, ...);
void warning (const char *msg, ...);

/**
 * Open serial IO device to STM32W-RFCKIT dongle.
 * (8N1, 57600bps, raw mode, no handshaking)
 *
 * @param deviceName Pointer to string with device name (eg "/dev/ttyACM0")
 * @return Operating system file descriptor or -1 if there was an error.
 */
int stm32w_open(char *deviceName) {

	int fd = open(deviceName,O_RDWR);
	if (fd==0) {
		fprintf (stderr,"Error: unable to open device %s\n",deviceName);
		return -1;
	}

	struct termios tios;
	int status=tcgetattr(fd,&tios);
	if (status < 0) {
    	fprintf (stderr,"Error: error calling tcgetattr\n");
		return -1;
	}

	// Set tx/rx speed at 115200bps, and set raw mode
 	cfsetispeed(&tios,B115200);
 	cfsetospeed(&tios,B115200);
	cfmakeraw(&tios);

	tios.c_cflag &= ~CSTOPB; // Set 1 stop bit
	tios.c_cflag |= (CREAD | CLOCAL); // Enable receiver and disable hardware flow control
	tios.c_oflag = 0; // Disable some modem settings

	//tios.c_cc[VMIN] = 1;
	//tios.c_cc[VTIME] = 0;

	tcsetattr(fd, TCSANOW, &tios);

	return fd;
}

/**
 * Close serial IO device.
 * @param fd File descriptor
 */
void stm32w_close(int fd) {
	close(fd);
}

/**
 * Calculate checksum. Checksum is the bitwise NOT of the arithemetic sum of
 * the frame (excluding the 0x15 0xFF prefix, but including the length field).
 * @param buf Pointer to start of frame (ie the length field)
 * @param len Length of frame (length field, command field + data)
 * @return 8 bit frame checksum
 */
int stm32w_checksum (uint8_t *buf, int len) {
	int sum = 0;
	uint8_t *end = buf+len;
	while (buf < end) {
		sum += *buf++;
	}
	return (~sum) & 0xff;
}

/**
 * Display to stderr current version of this application.
 */
void version () {
	fprintf (stderr,"%s, version %s\n", APP_NAME, VERSION);
}

/**
 * Display help and usage information.
 */
void usage () {
	fprintf (stderr,"\n");
	fprintf (stderr,"Usage: stm32w-wireskark [-q] [-v] [-h] [-d level] [-f format] device channel\n");

	//fprintf (stderr,"  -c channel \t Set channel. Allowed values: 11 to 26.\n");
	fprintf (stderr,"\n");
	fprintf (stderr,"Options:\n");
	fprintf (stderr,"  -d level \t Set debug level, 0 = min (default), 9 = max verbosity\n");
	fprintf (stderr,"  -f format \t Output format: pcap (default) | hex \n");
	fprintf (stderr,"  -q \t Quiet mode: suppress warning messages.\n");
	fprintf (stderr,"  -v \t Print version to stderr and exit\n");
	fprintf (stderr,"  -h \t Display this message to stderr and exit\n");
	fprintf (stderr,"\n");
	fprintf (stderr,"Parameters:\n");
	fprintf (stderr,"  device:  the unix device file corresponding to the dongle device (often /dev/ttyACM0)\n");
	fprintf (stderr,"  channel: the 802.15.4 channel. Allowed values from 11 to 26.\n");
	fprintf (stderr,"\n");
	fprintf (stderr,"See this blog post for details: \n    http://jdesbonnet.blogspot.com/2012/04/stm32w-rfckit-as-802154-network.html\n");
	fprintf (stderr,"Version: ");
	version();
	fprintf (stderr,"Author: Joe Desbonnet, jdesbonnet@gmail.com.\n");
	fprintf (stderr,"Copyright 2012. Source released under BSD licence.\n");
	fprintf (stderr,"\n");
}

/**
 * Display debug message if suitable log level is selected.
 * Use vararg mechanism to allow use similar to the fprintf()
 * function.
 *
 * @param level Display this message if log level is greater
 * or equal this level. Otherwise ignore the message.
 * @param msg  Format string as described in fprintf()
 */
void debug (int level, const char* msg, ...) {
	if (level >= debug_level) {
		return;
	}
	va_list args;
	va_start(args, msg);		// args after 'msg' are unknown
	vfprintf(stderr, msg, args);
	fprintf(stderr,"\n");
	fflush(stderr);
	va_end(args);
}
/**
 * Display warning message if unless quiet_mode is enabled.
 *
 * @param msg  Format string as described in fprintf()
 */
void warning (const char* msg, ...) {
	if (quiet_mode) {
		return;
	}
	fprintf(stderr,"WARNING: ");
	va_list args;
	va_start(args, msg);		// args after 'msg' are unknown
	vfprintf(stderr, msg, args);
	fprintf(stderr,"\n");
	fflush(stderr);
	va_end(args);
}

/**
 * Signal handler for handling SIGPIPE and...
 */
void signal_handler(int signum, siginfo_t *info, void *ptr) {
	debug (1, "Received signal %d originating from PID %lu\n", signum, (unsigned long)info->si_pid);
	//exit(EXIT_SUCCESS);
	exit_flag = TRUE;
}

/**
 * Continue to read from file handle fd until 'length' bytes
 * have been read.
 */
void read_n_bytes (int fd, uint8_t *buf, int length) {
	int n=0;
	while (n < length) {
		n += read(fd,buf+n,length-n);
	}
}

/**
 * Display length bytes from pointer buf in zero padded
 * hex.
 */
void display_hex(uint8_t *buf, int length) {
	int i;
	for (i = 0; i < length; i++) {
		fprintf (stderr,"%02X ",buf[i]);
	}
}

/**
 * Read a frame from the STM32W-RFCKIT USB dongle. The frame
 * is copied into buf. It includes the 0x15 0xFF prefix,
 * the checksum and 0x0C terminator.
 * If the checksum does not match with the computed value an
 * error code is returned.
 *
 * @return The entire frame length (including prefix 0x15 0xFF
 * and 0x0C terminator) if successful, -1 on error.
 */
int stm32w_read_frame (int fd, uint8_t *buf) {

		// Look for start of frame (0x15, 0xFF)
		while (1) {
			read_n_bytes (fd,buf,2);
			if ((buf[0]==0x15) && (buf[1]==0xFF) ) {
				break;
			}
		}

		// Read frame length field. This value includes the length field
		// but excludes the checksum and terminator (0x0C). Therefore
		// +1 to arrive at the remaining bytes left to be read in the
		// current frame
		read_n_bytes (fd,buf+2,1);
		int frame_length = *(buf+2);

		// Read frame into buf starting at index 3
		// (index 0,1,2 occupied by 0x15, 0xFF, frame length field)
		read_n_bytes (fd,buf+3,frame_length+1);

		// Calculate frame checksum (frame length + data)
		int cksum = stm32w_checksum(buf+2,frame_length);

		if (buf[2+frame_length+1] != 0x0C) {
			warning ("expecting 0x0C frame terminator, but got %02X",buf[2+frame_length+1]);
		}

		return (cksum == buf[2+frame_length]) ? frame_length+4 : -1;
}

int main( int argc, char **argv) {

	int channel=12;
	int output_format = FORMAT_PCAP;
	char *device;

	// Setup signal handler. Catching SIGPIPE allows for exit when
	// piping to Wireshark for live packet feed.
	//signal(SIGPIPE, signal_handler);
	struct sigaction act;
	memset(&act, 0, sizeof(act));
	act.sa_sigaction = signal_handler;
	act.sa_flags = SA_SIGINFO;
	sigaction(SIGPIPE, &act, NULL);

	// Parse command line arguments. See usage() for details.
	int c;
	while ((c = getopt(argc, argv, "c:d:f:hqs:t:v")) != -1) {
		switch(c) {

			/*
			case 'c':
				channel = atoi (optarg);
				if (channel < 11 || channel > 26) {
					fprintf (stderr, "Invalid channel. Must be in range 11 to 26. Use -h for help.\n");
					exit(-1);
				}
				break;
			*/
			case 'd':
				debug_level = atoi (optarg);
				break;

			case 'f':
				if (strncmp("pcap",optarg,4)==0) {
					output_format = FORMAT_PCAP;
				} else  if (strncmp("hex",optarg,3)==0) {
					output_format = FORMAT_HEX;
				}
				break;

			case 'h':
				version();
				usage();
				exit(EXIT_SUCCESS);

			case 'q':
				quiet_mode = TRUE;
				break;

			case 'v':
				version();
				exit(EXIT_SUCCESS);
			case '?':	// case when a command line switch argument is missing
				/*
				if (optopt == 'c') {
					fprintf (stderr,"ERROR: 802.15.4 channel 11 to 26 must be specified with -c\n");
					exit(-1);
				}
				*/
				if (optopt == 'd') {
					fprintf (stderr,"ERROR: debug level 0 .. 9 must be specified with -d\n");
					exit(-1);
				}
				break;
		}
	}

	// Two parameters are mandatory
	if (argc - optind < 2) {
		fprintf (stderr,"Error: missing command arguments. Use -h for help.");
		exit(EXIT_FAILURE);
	}

	device = argv[optind];
	channel = atoi(argv[optind+1]);

	if (channel < 11 || channel > 26) {
		fprintf (stderr, "Error: invalid channel. Must be in range 11 to 26. Use -h for help.\n");
		exit(EXIT_FAILURE);
	}

	if (debug_level > 0) {
		debug (1,"device=%s",device);
		debug (1,"channel=%d",channel);
	}

	if (debug_level > 0) {
		fprintf (stderr,"DEBUG: debug level %d\n",debug_level);
	}

	int n;

	// Get start time of capture. Won't worry about subsecond resolution for this.
	struct timespec tp;

	// Open dongle device
	int fd = stm32w_open(device);
	if (fd  < 1 ) {
		fprintf (stderr,"Error: unable to open device %s\n", device);
		return EXIT_FAILURE;
	}

	// Ignore anything aleady in the buffer
	tcflush (fd,TCIFLUSH);

	// Buffer for frame storage
	uint8_t buf[262];

	// Command 0x10: set channel
	buf[0] = 0x15;
	buf[1] = 0xFF;
	buf[2] = 0x03; // Len
	buf[3] = 0x10; // Set Channel command
	buf[4] = channel;
	buf[5] = stm32w_checksum(buf+2,3);
	buf[6] = 0x0C;
	fprintf (stderr, "Writing command 0x10 (set channel), ");
	write (fd, buf, 7);
	// Read response. Expect 15 FF 03 90 channel cksum 0C
	n = stm32w_read_frame (fd, buf);
	//fprintf (stderr,"response: n=%d ",n);
	//display_hex (buf,n);
	//fprintf (stderr,"\n");

	// Command 0x11: sniff mode on
	buf[0] = 0x15;
	buf[1] = 0xFF;
	buf[2] = 0x02;
	buf[3] = 0x11;
	buf[4] = stm32w_checksum(buf+2,2);
	buf[5] = 0x0C;
	fprintf (stderr, "Writing command 0x11 (start sniffing), ");
	write (fd, buf, 6);
	// Read response. Expect 15 FF ?? 91 ?? ?? cksum 0C
	n = stm32w_read_frame (fd, buf);
	//fprintf (stderr,"response: n=%d ",n);
	//display_hex (buf,n);
	//fprintf (stderr,"\n");

	// Write PCAP header
	if (output_format == FORMAT_PCAP) {
		fwrite(&PCAP_MAGIC, sizeof(int), 1, stdout);
		fwrite(&PCAP_VERSION_MAJOR, sizeof(short), 1, stdout);
		fwrite(&PCAP_VERSION_MINOR, sizeof(short), 1, stdout);
		fwrite(&PCAP_TZ, sizeof(int), 1, stdout);				// thiszone: GMT to local correction
		fwrite(&PCAP_SIGFIGS, sizeof(int), 1, stdout);			// sigfigs: accuracy of timestamps
		fwrite(&PCAP_SNAPLEN, sizeof(int), 1, stdout);			// snaplen: max len of packets, in octets
		fwrite(&PCAP_LINKTYPE, sizeof(int), 1, stdout);		// data link type
		fflush(stdout);
	}

	int frame_length;
	uint32_t stm32w_time;
	uint32_t stm32w_time_sec;
	uint32_t stm32w_time_usec;
	uint64_t stm32w_time_full;
	uint32_t host_ts_sec;
	uint32_t host_ts_usec;
	uint64_t host_ts_full;

	int delta;

	int ncapture = 0;

	clock_gettime(CLOCK_REALTIME, &tp);
	long host_start_sec = tp.tv_sec;

	while (1) {

		// Frame is the entire from from the dongle including 0x15, 0xFF preamble,
		// length field, 0xF0 command, 802.15.4 packet metadata and actual packet
		// 802.15.4 FCS, dongle frame checksum and 0x0C terminator.
		frame_length = stm32w_read_frame (fd, buf);

		if (frame_length < 0) {
			fprintf (stderr,"Warning: bad frame\n");
			continue;
		}

		// Write frame (excluding 0x15, 0xFF prefix, checksum and 0x0C)
		if (output_format == FORMAT_HEX) {
			display_hex (buf,frame_length);
			fprintf (stderr,"\n");
		}

		// Is this a frame type 0xF0?
		if (buf[3] != 0xF0) {
			fprintf (stderr,"Warning: unexpected frame type %02X\n", buf[3]);
			continue;
		}

		// Get host time of packet reception
		// TODO: might be better to capture time at start of frame
		clock_gettime(CLOCK_REALTIME, &tp);
		host_ts_sec = tp.tv_sec;
		host_ts_usec = tp.tv_nsec / 1000;

		/*
		fprintf (stderr, "\nstm32w_time: ");
		display_hex(buf+4,5);
		fprintf (stderr,"\n");
		stm32w_time =  *( (uint32_t*)(buf+4));
		stm32w_time_usec = (10000* (stm32w_time & 0x000fffff)) / 0xfffff;
		stm32w_time_usec *= 100;
		stm32w_time =  *( (uint32_t*)(buf+6));
		stm32w_time_sec = (stm32w_time&0xffffff) >> 4;
		stm32w_time_full = (long)stm32w_time_sec*1000000L + stm32w_time_usec;
		host_ts_full = (long)(host_ts_sec-host_start_sec)*1000000L + (long)host_ts_usec;
		delta = (int)(stm32w_time_full - host_ts_full);
		delta =  stm32w_time_sec - (host_ts_sec - host_start_sec);
		fprintf (stdout,"host_sec=%d ",host_ts_sec);
		fprintf (stdout,"host_usec=%d ",host_ts_usec);
		fprintf (stdout,"stm32w_sec=%d ", stm32w_time_sec);
		fprintf (stdout,"stm32w_usec=%d ", stm32w_time_usec);
		fprintf (stdout,"delta=%d ", delta);
		//fprintf (stdout," %d %d %d\n", buf[2],buf[8],buf[data_length-1],buf[data_length]);
		fprintf (stdout,"\n");
		fflush (stdout);
		*/

		// Remaining code applies to PCAP format only
		if (output_format != FORMAT_PCAP) {
			//continue;
		}

		ncapture++;

		fwrite (&host_ts_sec, sizeof(int), 1, stdout);	// ts_sec: timestamp seconds
		fwrite (&host_ts_usec, sizeof(int), 1, stdout);	// ts_usec: timestamp microseconds

		// 802.15.4 packet length including 2 bytes FCS
		int f802154length = frame_length - 13;
		fwrite (&f802154length, sizeof(uint32_t), 1, stdout);
		fwrite (&f802154length, sizeof(uint32_t), 1, stdout);
		fwrite (buf+11, 1, f802154length, stdout);
		fflush(stdout);
	}

	stm32w_close(fd);

	debug (1, "Normal exit");
	return EXIT_SUCCESS;
}


text:
PROPER_SORTING_ALGORITHM(SelectionSort)

template <class Cont>
struct SelectionSort
{
	// Check that container type provided
	static_assert(HasConstIterator<Cont>::value, "Please provide a valid container type with const iterator");

	// Check that value_type of a container is of integral type
	static_assert(HasArithmeticType<Cont>::value, "Container's elements should be of integral type");

	auto run(Cont& container) -> void
	{
		sort(container);
	}

private:

	auto sort(Cont& container) -> void
	{
		Cont::value_type min_idx = 0;

		size_t len = container.size();

		for (int i = 0; i < len; i++)
		{
			// Take i value as new min
			min_idx = i;

			// Search for min value among remaining items
			for (int j = i + 1; j < len; j++)
			{
				if (container[j] < container[min_idx])
					// Save new index
					min_idx = j;
			}

			// If we found number less then min, do swap
			if (container[i] != container[min_idx])
				std::swap(container[i], container[min_idx]);
		}
	}
};