text:
"""
test_http11.py
~~~~~~~~~~~~~~

Unit tests for hyper's HTTP/1.1 implementation.
"""
import os
import zlib
import brotli

from collections import namedtuple
from io import BytesIO, StringIO

import mock
import pytest

import hyper
from hyper.http11.connection import HTTP11Connection
from hyper.http11.response import HTTP11Response
from hyper.common.headers import HTTPHeaderMap
from hyper.common.exceptions import ChunkedDecodeError, ConnectionResetError
from hyper.common.util import HTTPVersion
from hyper.compat import bytes, zlib_compressobj

class TestHTTP11Connection(object):
    def test_pycohttpparser_installs_correctly(self):
        # This test is a debugging tool: if pycohttpparser is being tested by
        # Travis, we need to confirm it imports correctly. Hyper will normally
        # hide the import failure, so let's discover it here.
        # Alternatively, if we are *not* testing with nghttp2, this test should
        # confirm that it's not available.
        if os.environ.get('HYPER_FAST_PARSE') == 'true':
            import pycohttpparser
        else:
            with pytest.raises(ImportError):
                import pycohttpparser  # noqa

        assert True

    def test_initialization_no_port(self):
        c = HTTP11Connection('httpbin.org')

        assert c.host == 'httpbin.org'
        assert c.port == 80
        assert not c.secure
        assert not c.proxy_host

    def test_initialization_inline_port(self):
        c = HTTP11Connection('httpbin.org:443')

        assert c.host == 'httpbin.org'
        assert c.port == 443
        assert c.secure
        assert not c.proxy_host

    def test_initialization_separate_port(self):
        c = HTTP11Connection('localhost', 8080)

        assert c.host == 'localhost'
        assert c.port == 8080
        assert not c.secure
        assert not c.proxy_host

    def test_can_override_security(self):
        c = HTTP11Connection('localhost', 443, secure=False)

        assert c.host == 'localhost'
        assert c.port == 443
        assert not c.secure
        assert not c.proxy_host

    def test_initialization_proxy(self):
        c = HTTP11Connection('httpbin.org', proxy_host='localhost')

        assert c.host == 'httpbin.org'
        assert c.port == 80
        assert not c.secure
        assert c.proxy_host == 'localhost'
        assert c.proxy_port == 8080

    def test_initialization_proxy_with_inline_port(self):
        c = HTTP11Connection('httpbin.org', proxy_host='localhost:8443')

        assert c.host == 'httpbin.org'
        assert c.port == 80
        assert not c.secure
        assert c.proxy_host == 'localhost'
        assert c.proxy_port == 8443

    def test_initialization_proxy_with_separate_port(self):
        c = HTTP11Connection(
            'httpbin.org', proxy_host='localhost', proxy_port=8443
        )

        assert c.host == 'httpbin.org'
        assert c.port == 80
        assert not c.secure
        assert c.proxy_host == 'localhost'
        assert c.proxy_port == 8443

    def test_initialization_with_ipv6_addresses_proxy_inline_port(self):
        c = HTTP11Connection(
            '[abcd:dcba::1234]', proxy_host='[ffff:aaaa::1]:8443'
        )

        assert c.host == 'abcd:dcba::1234'
        assert c.port == 80
        assert not c.secure
        assert c.proxy_host == 'ffff:aaaa::1'
        assert c.proxy_port == 8443

    def test_initialization_timeout(self):
        c = HTTP11Connection('httpbin.org', timeout=30)

        assert c._timeout == 30

    def test_initialization_tuple_timeout(self):
        c = HTTP11Connection('httpbin.org', timeout=(5, 60))

        assert c._timeout == (5, 60)

    def test_basic_request(self):
        c = HTTP11Connection('httpbin.org')
        c._sock = sock = DummySocket()

        c.request('GET', '/get', headers={'User-Agent': 'hyper'})

        expected = (
            b"GET /get HTTP/1.1\r\n"
            b"User-Agent: hyper\r\n"
            b"connection: Upgrade, HTTP2-Settings\r\n"
            b"upgrade: h2c\r\n"
            b"HTTP2-Settings: AAQAAP__\r\n"
            b"host: httpbin.org\r\n"
            b"\r\n"
        )
        received = b''.join(sock.queue)

        assert received == expected

    def test_iterable_header(self):
        c = HTTP11Connection('httpbin.org')
        c._sock = sock = DummySocket()

        c.request('GET', '/get', headers=(
            ('User-Agent', 'hyper'),
            ('Custom-field', 'test'),
            ('Custom-field2', 'test'),
            ('Custom-field', 'test2'),
        ))

        expected = (
            b"GET /get HTTP/1.1\r\n"
            b"User-Agent: hyper\r\n"
            b"Custom-field: test\r\n"
            b"Custom-field2: test\r\n"
            b"Custom-field: test2\r\n"
            b"connection: Upgrade, HTTP2-Settings\r\n"
            b"upgrade: h2c\r\n"
            b"HTTP2-Settings: AAQAAP__\r\n"
            b"host: httpbin.org\r\n"
            b"\r\n"
        )
        received = b''.join(sock.queue)

        assert received == expected

    def test_invalid_header(self):
        c = HTTP11Connection('httpbin.org')
        c._sock = DummySocket()

        with pytest.raises(ValueError):
            c.request('GET', '/get', headers=42)

    def test_proxy_request(self):
        c = HTTP11Connection('httpbin.org', proxy_host='localhost')
        c._sock = sock = DummySocket()

        c.request('GET', '/get', headers={'User-Agent': 'hyper'})

        expected = (
            b"GET http://httpbin.org/get HTTP/1.1\r\n"
            b"User-Agent: hyper\r\n"
            b"connection: Upgrade, HTTP2-Settings\r\n"
            b"upgrade: h2c\r\n"
            b"HTTP2-Settings: AAQAAP__\r\n"
            b"host: httpbin.org\r\n"
            b"\r\n"
        )
        received = b''.join(sock.queue)

        assert received == expected

    def test_proxy_request_with_non_standard_port(self):
        c = HTTP11Connection('httpbin.org:8080', proxy_host='localhost')
        c._sock = sock = DummySocket()

        c.request('GET', '/get', headers={'User-Agent': 'hyper'})

        expected = (
            b"GET http://httpbin.org:8080/get HTTP/1.1\r\n"
            b"User-Agent: hyper\r\n"
            b"connection: Upgrade, HTTP2-Settings\r\n"
            b"upgrade: h2c\r\n"
            b"HTTP2-Settings: AAQAAP__\r\n"
            b"host: httpbin.org\r\n"
            b"\r\n"
        )
        received = b''.join(sock.queue)

        assert received == expected

    def test_proxy_headers_presence_for_insecure_request(self):
        c = HTTP11Connection(
            'httpbin.org', secure=False, proxy_host='localhost',
            proxy_headers={'Proxy-Authorization': 'Basic ==='})
        c._sock = sock = DummySocket()

        c.request('GET', '/get', headers={'User-Agent': 'hyper'})

        expected = (
            b"GET http://httpbin.org/get HTTP/1.1\r\n"
            b"User-Agent: hyper\r\n"
            b"proxy-authorization: Basic ===\r\n"
            b"connection: Upgrade, HTTP2-Settings\r\n"
            b"upgrade: h2c\r\n"
            b"HTTP2-Settings: AAQAAP__\r\n"
            b"host: httpbin.org\r\n"
            b"\r\n"
        )
        received = b''.join(sock.queue)

        assert received == expected

    def test_proxy_headers_absence_for_secure_request(self):
        c = HTTP11Connection(
            'httpbin.org', secure=True, proxy_host='localhost',
            proxy_headers={'Proxy-Authorization': 'Basic ==='})
        c._sock = sock = DummySocket()

        c.request('GET', '/get', headers={'User-Agent': 'hyper'})

        expected = (
            b"GET /get HTTP/1.1\r\n"
            b"User-Agent: hyper\r\n"
            b"host: httpbin.org\r\n"
            b"\r\n"
        )
        received = b''.join(sock.queue)

        assert received == expected

    def test_request_with_bytestring_body(self):
        c = HTTP11Connection('httpbin.org')
        c._sock = sock = DummySocket()

        c.request(
            'POST',
            '/post',
            headers=HTTPHeaderMap([('User-Agent', 'hyper')]),
            body=b'hi'
        )

        expected = (
            b"POST /post HTTP/1.1\r\n"
            b"User-Agent: hyper\r\n"
            b"connection: Upgrade, HTTP2-Settings\r\n"
            b"upgrade: h2c\r\n"
            b"HTTP2-Settings: AAQAAP__\r\n"
            b"content-length: 2\r\n"
            b"host: httpbin.org\r\n"
            b"\r\n"
            b"hi"
        )
        received = b''.join(sock.queue)

        assert received == expected

    def test_request_with_file_body(self):
        # Testing this is tricksy: in practice, we do this by passing a fake
        # file and monkeypatching out 'os.fstat'. This makes it look like a
        # real file.
        FstatRval = namedtuple('FstatRval', ['st_size'])

        def fake_fstat(*args):
            return FstatRval(16)

        old_fstat = hyper.http11.connection.os.fstat

        try:
            hyper.http11.connection.os.fstat = fake_fstat
            c = HTTP11Connection('httpbin.org')
            c._sock = sock = DummySocket()

            f = DummyFile(b'some binary data')
            c.request('POST', '/post',  body=f)

            expected = (
                b"POST /post HTTP/1.1\r\n"
                b"connection: Upgrade, HTTP2-Settings\r\n"
                b"upgrade: h2c\r\n"
                b"HTTP2-Settings: AAQAAP__\r\n"
                b"content-length: 16\r\n"
                b"host: httpbin.org\r\n"
                b"\r\n"
                b"some binary data"
            )
            received = b''.join(sock.queue)

            assert received == expected

        finally:
            # Put back the monkeypatch.
            hyper.http11.connection.os.fstat = old_fstat

    def test_request_with_generator_body(self):
        c = HTTP11Connection('httpbin.org')
        c._sock = sock = DummySocket()

        def body():
            yield b'hi'
            yield b'there'
            yield b'sir'

        c.request('POST', '/post', body=body())

        expected = (
            b"POST /post HTTP/1.1\r\n"
            b"connection: Upgrade, HTTP2-Settings\r\n"
            b"upgrade: h2c\r\n"
            b"HTTP2-Settings: AAQAAP__\r\n"
            b"transfer-encoding: chunked\r\n"
            b"host: httpbin.org\r\n"
            b"\r\n"
            b"2\r\nhi\r\n"
            b"5\r\nthere\r\n"
            b"3\r\nsir\r\n"
            b"0\r\n\r\n"
        )
        received = b''.join(sock.queue)

        assert received == expected

    def test_content_length_overrides_generator(self):
        c = HTTP11Connection('httpbin.org')
        c._sock = sock = DummySocket()

        def body():
            yield b'hi'
            yield b'there'
            yield b'sir'

        c.request(
            'POST', '/post', body=body(), headers={b'content-length': b'10'}
        )

        expected = (
            b"POST /post HTTP/1.1\r\n"
            b"content-length: 10\r\n"
            b"connection: Upgrade, HTTP2-Settings\r\n"
            b"upgrade: h2c\r\n"
            b"HTTP2-Settings: AAQAAP__\r\n"
            b"host: httpbin.org\r\n"
            b"\r\n"
            b"hitheresir"
        )

        received = b''.join(sock.queue)
        assert received == expected

    def test_chunked_overrides_body(self):
        c = HTTP11Connection('httpbin.org')
        c._sock = sock = DummySocket()

        f = DummyFile(b'oneline\nanotherline')

        c.request(
            'POST',
            '/post',
            headers={'transfer-encoding': 'chunked'},
            body=f
        )

        expected = (
            b"POST /post HTTP/1.1\r\n"
            b"transfer-encoding: chunked\r\n"
            b"connection: Upgrade, HTTP2-Settings\r\n"
            b"upgrade: h2c\r\n"
            b"HTTP2-Settings: AAQAAP__\r\n"
            b"host: httpbin.org\r\n"
            b"\r\n"
            b"8\r\noneline\n\r\n"
            b"b\r\nanotherline\r\n"
            b"0\r\n\r\n"
        )
        received = b''.join(sock.queue)

        assert received == expected

    def test_response_with_empty_reason(self):
        c = HTTP11Connection('httpbin.org')
        c._sock = sock = DummySocket()

        sock._buffer = BytesIO(
            b"HTTP/1.1 201 \r\n"
            b"Connection: close\r\n"
            b"Server: Socket\r\n"
            b"Content-Length: 0\r\n"
            b"\r\n"
        )

        r = c.get_response()

        assert r.status == 201
        assert r.reason == b''

    def test_get_response(self):
        c = HTTP11Connection('httpbin.org')
        c._sock = sock = DummySocket()

        sock._buffer = BytesIO(
            b"HTTP/1.1 201 No Content\r\n"
            b"Connection: close\r\n"
            b"Server: Socket\r\n"
            b"Content-Length: 0\r\n"
            b"\r\n"
        )

        r = c.get_response()

        assert r.status == 201
        assert r.reason == b'No Content'
        assert list(r.headers.iter_raw()) == [
            (b'Connection', b'close'),
            (b'Server', b'Socket'),
            (b'Content-Length', b'0')
        ]
        assert r.read() == b''

    def test_response_short_reads(self):
        c = HTTP11Connection('httpbin.org')
        c._sock = sock = DummySocket()

        sock._buffer = BytesIO(
            b"HTTP/1.1 200 OK\r\n"
            b"Content-Length: 15\r\n"
            b"\r\n"
            b"hellotherechamp"
        )

        r = c.get_response()

        assert r.status == 200
        assert r.reason == b'OK'
        assert r.read(5) == b'hello'
        assert r.read(5) == b'there'
        assert r.read(5) == b'champ'
        assert r.read(5) == b''

    def test_request_with_unicodestring_body(self):
        c = HTTP11Connection('httpbin.org')
        c._sock = DummySocket()

        with pytest.raises(ValueError):
            c.request(
                'POST',
                '/post',
                headers=HTTPHeaderMap([('User-Agent', 'hyper')]),
                body=u'hi'
            )

    def test_request_with_file_body_in_text_mode(self):
        # Testing this is tricksy: in practice, we do this by passing a fake
        # file and monkeypatching out 'os.fstat'. This makes it look like a
        # real file.
        FstatRval = namedtuple('FstatRval', ['st_size'])

        def fake_fstat(*args):
            return FstatRval(16)

        old_fstat = hyper.http11.connection.os.fstat

        try:
            hyper.http11.connection.os.fstat = fake_fstat
            c = HTTP11Connection('httpbin.org')
            c._sock = DummySocket()

            f = DummyFile(b'')
            f.buffer = StringIO(u'some binary data')

            with pytest.raises(ValueError):
                c.request('POST', '/post',  body=f)
        finally:
            # Put back the monkeypatch.
            hyper.http11.connection.os.fstat = old_fstat

    def test_request_with_unicode_generator_body(self):
        c = HTTP11Connection('httpbin.org')
        c._sock = DummySocket()

        def body():
            yield u'hi'
            yield u'there'
            yield u'sir'

        with pytest.raises(ValueError):
            c.request('POST', '/post', body=body())

    def test_content_length_overrides_generator_unicode(self):
        c = HTTP11Connection('httpbin.org')
        c._sock = DummySocket()

        def body():
            yield u'hi'
            yield u'there'
            yield u'sir'

        with pytest.raises(ValueError):
            c.request(
                'POST',
                '/post',
                headers={b'content-length': b'10'},
                body=body()
            )

    def test_http_upgrade_headers_only_sent_once(self):
        c = HTTP11Connection('httpbin.org')
        c._sock = sock = DummySocket()

        c.request('GET', '/get', headers={'User-Agent': 'hyper'})

        sock.queue = []
        c.request('GET', '/get', headers={'User-Agent': 'hyper'})
        received = b''.join(sock.queue)

        expected = (
            b"GET /get HTTP/1.1\r\n"
            b"User-Agent: hyper\r\n"
            b"host: httpbin.org\r\n"
            b"\r\n"
        )

        assert received == expected

    def test_exception_raised_for_illegal_body_type(self):
        c = HTTP11Connection('httpbin.org')

        with pytest.raises(ValueError) as exc_info:
            body = 1234
            # content-length set so body type is set to BODY_FLAT. value
            # doesn't matter
            c.request(
                'GET',
                '/get',
                body=body,
                headers={'content-length': str(len(str(body)))}
            )
        assert 'Request body must be a bytestring, a file-like object ' \
               'returning bytestrings or an iterable of bytestrings. ' \
               'Got: {}'.format(type(body)) in str(exc_info)

    def test_exception_raised_for_illegal_elements_in_iterable_body(self):
        c = HTTP11Connection('httpbin.org')

        rogue_element = 123
        body = [b'legal1', b'legal2', rogue_element]
        body_size = sum(len(bytes(x)) for x in body)
        with pytest.raises(ValueError) as exc_info:
            # content-length set so body type is set to BODY_FLAT. value
            # doesn't matter
            c.request(
                'GET',
                '/get',
                body=body,
                headers={'content-length': str(body_size)}
            )
        assert 'Elements in iterable body must be bytestrings. Illegal ' \
               'element: {}'.format(rogue_element) \
               in str(exc_info)

    def test_exception_raised_for_filelike_body_not_returning_bytes(self):
        c = HTTP11Connection('httpbin.org')

        class RogueFile(object):
            def read(self, size):
                return 42

        with pytest.raises(ValueError) as exc_info:
            # content-length set so body type is BODY_FLAT. value doesn't
            # matter
            c.request(
                'GET',
                '/get',
                body=RogueFile(),
                headers={'content-length': str(10)}
            )
        assert 'File-like bodies must return bytestrings. ' \
               'Got: {}'.format(int) in str(exc_info)

    def test_close_with_uninitialized_socket(self):
        c = HTTP11Connection('httpbin.org')
        c.close()

class TestHTTP11Response(object):
    def test_short_circuit_read(self):
        r = HTTP11Response(200, 'OK', {b'content-length': [b'0']}, None, None)

        assert r.read() == b''

    def test_aborted_reads(self):
        d = DummySocket()
        r = HTTP11Response(200, 'OK', {b'content-length': [b'15']}, d, None)

        with pytest.raises(ConnectionResetError):
            r.read()

    def test_read_expect_close(self):
        d = DummySocket()
        r = HTTP11Response(200, 'OK', {b'connection': [b'close']}, d, None)

        assert r.read() == b''

    def test_response_as_context_manager(self):
        r = HTTP11Response(
            200, 'OK', {b'content-length': [b'0']}, DummySocket(), None
        )

        with r:
            assert r.read() == b''

        assert r._sock is None

    def test_response_transparently_decrypts_gzip(self):
        d = DummySocket()
        headers = {b'content-encoding': [b'gzip'], b'connection': [b'close']}
        r = HTTP11Response(200, 'OK', headers, d, None)

        c = zlib_compressobj(wbits=25)
        body = c.compress(b'this is test data')
        body += c.flush()
        d._buffer = BytesIO(body)

        assert r.read() == b'this is test data'

    def test_response_transparently_decrypts_brotli(self):
        d = DummySocket()
        headers = {b'content-encoding': [b'br'], b'connection': [b'close']}
        r = HTTP11Response(200, 'OK', headers, d, None)

        body = brotli.compress(b'this is test data')
        d._buffer = BytesIO(body)

        assert r.read() == b'this is test data'

    def test_response_transparently_decrypts_real_deflate(self):
        d = DummySocket()
        headers = {
            b'content-encoding': [b'deflate'],
            b'connection': [b'close'],
        }
        r = HTTP11Response(200, 'OK', headers, d, None)
        c = zlib_compressobj(wbits=zlib.MAX_WBITS)
        body = c.compress(b'this is test data')
        body += c.flush()
        d._buffer = BytesIO(body)

        assert r.read() == b'this is test data'

    def test_response_transparently_decrypts_wrong_deflate(self):
        c = zlib_compressobj(wbits=-zlib.MAX_WBITS)
        body = c.compress(b'this is test data')
        body += c.flush()
        body_len = ('%s' % len(body)).encode('ascii')

        headers = {
            b'content-encoding': [b'deflate'], b'content-length': [body_len]
        }
        d = DummySocket()
        d._buffer = BytesIO(body)
        r = HTTP11Response(200, 'OK', headers, d, None)

        assert r.read() == b'this is test data'

    def test_basic_chunked_read(self):
        d = DummySocket()
        r = HTTP11Response(
            200, 'OK', {b'transfer-encoding': [b'chunked']}, d, None
        )

        data = (
            b'4\r\nwell\r\n'
            b'4\r\nwell\r\n'
            b'4\r\nwhat\r\n'
            b'4\r\nhave\r\n'
            b'2\r\nwe\r\n'
            b'a\r\nhereabouts\r\n'
            b'0\r\n\r\n'
        )
        d._buffer = BytesIO(data)
        results = [
            b'well', b'well', b'what', b'have', b'we', b'hereabouts'
        ]

        for c1, c2 in zip(results, r.read_chunked()):
            assert c1 == c2

        assert not list(r.read_chunked())

    def test_chunked_read_of_non_chunked(self):
        r = HTTP11Response(200, 'OK', {b'content-length': [b'0']}, None, None)

        with pytest.raises(ChunkedDecodeError):
            list(r.read_chunked())

    def test_chunked_read_aborts_early(self):
        r = HTTP11Response(
            200, 'OK', {b'transfer-encoding': [b'chunked']}, None, None
        )

        assert not list(r.read_chunked())

    def test_response_transparently_decrypts_chunked_gzip(self):
        d = DummySocket()
        headers = {
            b'content-encoding': [b'gzip'],
            b'transfer-encoding': [b'chunked'],
        }
        r = HTTP11Response(200, 'OK', headers, d, None)

        c = zlib_compressobj(wbits=25)
        body = c.compress(b'this is test data')
        body += c.flush()

        data = b''
        for index in range(0, len(body), 2):
            data += b'2\r\n' + body[index:index+2] + b'\r\n'

        data += b'0\r\n\r\n'
        d._buffer = BytesIO(data)

        received_body = b''
        for chunk in r.read_chunked():
            received_body += chunk

        assert received_body == b'this is test data'

    def test_chunked_normal_read(self):
        d = DummySocket()
        r = HTTP11Response(
            200, 'OK', {b'transfer-encoding': [b'chunked']}, d, None)

        data = (
            b'4\r\nwell\r\n'
            b'4\r\nwell\r\n'
            b'4\r\nwhat\r\n'
            b'4\r\nhave\r\n'
            b'2\r\nwe\r\n'
            b'a\r\nhereabouts\r\n'
            b'0\r\n\r\n'
        )
        d._buffer = BytesIO(data)

        assert r.read() == b'wellwellwhathavewehereabouts'

    def test_chunk_length_read(self):
        d = DummySocket()
        r = HTTP11Response(
            200, 'OK', {b'transfer-encoding': [b'chunked']}, d, None
        )

        data = (
            b'4\r\nwell\r\n'
            b'4\r\nwell\r\n'
            b'4\r\nwhat\r\n'
            b'4\r\nhave\r\n'
            b'2\r\nwe\r\n'
            b'a\r\nhereabouts\r\n'
            b'0\r\n\r\n'
        )
        d._buffer = BytesIO(data)

        assert r.read(5) == b'wellw'
        assert r.read(15) == b'ellwhathavewehe'
        assert r.read(20) == b'reabouts'
        assert r.read() == b''

    def test_bounded_read_expect_close_no_content_length(self):
        d = DummySocket()
        r = HTTP11Response(200, 'OK', {b'connection': [b'close']}, d, None)
        d._buffer = BytesIO(b'hello there sir')

        assert r.read(5) == b'hello'
        assert r.read(6) == b' there'
        assert r.read(8) == b' sir'
        assert r.read(9) == b''

        assert r._sock is None

    def test_bounded_read_expect_close_with_content_length(self):
        headers = {b'connection': [b'close'], b'content-length': [b'15']}
        d = DummySocket()
        r = HTTP11Response(200, 'OK', headers, d, None)
        d._buffer = BytesIO(b'hello there sir')

        assert r.read(5) == b'hello'
        assert r.read(6) == b' there'
        assert r.read(8) == b' sir'
        assert r.read(9) == b''

        assert r._sock is None

    def test_compressed_bounded_read_expect_close(self):
        headers = {b'connection': [b'close'], b'content-encoding': [b'gzip']}

        c = zlib_compressobj(wbits=25)
        body = c.compress(b'hello there sir')
        body += c.flush()

        d = DummySocket()
        r = HTTP11Response(200, 'OK', headers, d, None)
        d._buffer = BytesIO(body)

        response = b''
        while True:
            # 12 is magic here: it's the smallest read that actually
            # decompresses immediately.
            chunk = r.read(15)
            if not chunk:
                break

            response += chunk

        assert response == b'hello there sir'

        assert r._sock is None

    def test_expect_close_reads_call_close_callback(self):
        connection = mock.MagicMock()

        d = DummySocket()
        r = HTTP11Response(
            200, 'OK', {b'connection': [b'close']}, d, connection
        )
        d._buffer = BytesIO(b'hello there sir')

        assert r.read(5) == b'hello'
        assert r.read(6) == b' there'
        assert r.read(8) == b' sir'
        assert r.read(9) == b''

        assert r._sock is None
        assert connection.close.call_count == 1

    def test_expect_close_unbounded_reads_call_close_callback(self):
        connection = mock.MagicMock()

        d = DummySocket()
        r = HTTP11Response(
            200, 'OK', {b'connection': [b'close']}, d, connection
        )
        d._buffer = BytesIO(b'hello there sir')

        r.read()

        assert r._sock is None
        assert connection.close.call_count == 1

    def test_content_length_expect_close_reads_call_close_callback(self):
        connection = mock.MagicMock()
        headers = {b'connection': [b'close'], b'content-length': [b'15']}

        d = DummySocket()
        r = HTTP11Response(200, 'OK', headers, d, connection)
        d._buffer = BytesIO(b'hello there sir')

        r.read()

        assert r._sock is None
        assert connection.close.call_count == 1

    def test_content_length_reads_dont_call_close_callback(self):
        connection = mock.MagicMock()
        headers = {b'content-length': [b'15']}

        d = DummySocket()
        r = HTTP11Response(200, 'OK', headers, d, connection)
        d._buffer = BytesIO(b'hello there sir')

        r.read()

        assert r._sock is None
        assert connection.close.call_count == 0

    def test_chunked_reads_dont_call_close_callback(self):
        connection = mock.MagicMock()
        headers = {b'transfer-encoding': [b'chunked']}

        d = DummySocket()
        r = HTTP11Response(200, 'OK', headers, d, connection)

        data = (
            b'4\r\nwell\r\n'
            b'4\r\nwell\r\n'
            b'4\r\nwhat\r\n'
            b'4\r\nhave\r\n'
            b'2\r\nwe\r\n'
            b'a\r\nhereabouts\r\n'
            b'0\r\n\r\n'
        )
        d._buffer = BytesIO(data)
        list(r.read_chunked())

        assert r._sock is None
        assert connection.close.call_count == 0

    def test_closing_chunked_reads_dont_call_close_callback(self):
        connection = mock.MagicMock()
        headers = {
            b'transfer-encoding': [b'chunked'], b'connection': [b'close']
        }

        d = DummySocket()
        r = HTTP11Response(200, 'OK', headers, d, connection)

        data = (
            b'4\r\nwell\r\n'
            b'4\r\nwell\r\n'
            b'4\r\nwhat\r\n'
            b'4\r\nhave\r\n'
            b'2\r\nwe\r\n'
            b'a\r\nhereabouts\r\n'
            b'0\r\n\r\n'
        )
        d._buffer = BytesIO(data)
        list(r.read_chunked())

        assert r._sock is None
        assert connection.close.call_count == 1

    def test_connection_version(self):
        c = HTTP11Connection('httpbin.org')
        assert c.version is HTTPVersion.http11

    def test_response_version(self):
        d = DummySocket()
        headers = {
            b'transfer-encoding': [b'chunked'], b'connection': [b'close']
        }
        r = HTTP11Response(200, 'OK', headers, d)
        assert r.version is HTTPVersion.http11

    def test_response_body_length(self):
        methods = [b'HEAD', b'GET']
        headers = {b'content-length': [b'15']}
        d = DummySocket()
        for method in methods:
            d.queue = []
            r = HTTP11Response(200, 'OK', headers, d, request_method=method)
            if method == b'HEAD':
                assert r._length == 0
            else:
                assert r._length == int(r.headers[b'content-length'][0])

class DummySocket(object):
    def __init__(self):
        self.queue = []
        self._buffer = BytesIO()
        self._read_counter = 0
        self.can_read = False

    @property
    def buffer(self):
        return memoryview(self._buffer.getvalue()[self._read_counter:])

    def advance_buffer(self, amt):
        self._read_counter += amt
        self._buffer.read(amt)

    def send(self, data):
        if not isinstance(data, bytes):
            raise TypeError()

        self.queue.append(data)

    def recv(self, l):
        data = self._buffer.read(l)
        self._read_counter += len(data)
        return memoryview(data)

    def close(self):
        pass

    def readline(self):
        line = self._buffer.readline()
        self._read_counter += len(line)
        return memoryview(line)

    def fill(self):
        pass

class DummyFile(object):
    def __init__(self, data):
        self.buffer = BytesIO(data)

    def read(self, amt=None):
        return self.buffer.read(amt)

    def fileno(self):
        return -1

    def readline(self):
        self.buffer.readline()

    def __iter__(self):
        return self.buffer.__iter__()


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

using Microsoft.WindowsAzure.Commands.ServiceManagement.Test.FunctionalTests.ConfigDataInfo;
using Microsoft.WindowsAzure.Commands.ServiceManagement.Test.FunctionalTests.PowershellCore;

namespace Microsoft.WindowsAzure.Commands.ServiceManagement.Test.FunctionalTests.IaasCmdletInfo
{
    public class SetAzureDataDiskCmdletInfo : CmdletsInfo
    {
        public SetAzureDataDiskCmdletInfo(SetAzureDataDiskConfig discCfg)
        {
            cmdletName = Utilities.SetAzureDataDiskCmdletName;

            this.cmdletParams.Add(new CmdletParam("HostCaching", discCfg.hostCaching));
            this.cmdletParams.Add(new CmdletParam("LUN", discCfg.lun));
            this.cmdletParams.Add(new CmdletParam("VM", discCfg.Vm));
        }

        public SetAzureDataDiskCmdletInfo(SetAzureDataDiskResizeConfig discCfg)
        {
            cmdletName = Utilities.SetAzureDataDiskCmdletName;

            this.cmdletParams.Add(new CmdletParam("DiskName", discCfg.DiskName));
            this.cmdletParams.Add(new CmdletParam("ResizedSizeInGB", discCfg.ResizedSizeInGB));
            this.cmdletParams.Add(new CmdletParam("VM", discCfg.Vm));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Data;
using System.Linq;
using FluentAssertions.Data;
using FluentAssertions.Execution;

namespace FluentAssertions.Equivalency.Steps;

public class DataRowCollectionEquivalencyStep : EquivalencyStep<DataRowCollection>
{
    protected override EquivalencyResult OnHandle(Comparands comparands, IEquivalencyValidationContext context, IEquivalencyValidator nestedValidator)
    {
        if (comparands.Subject is not DataRowCollection)
        {
            AssertionScope.Current
                .FailWith("Expected {context:value} to be of type DataRowCollection, but found {0}",
                    comparands.Subject.GetType());
        }
        else
        {
            RowMatchMode rowMatchMode = RowMatchMode.Index;

            if (context.Options is DataEquivalencyAssertionOptions<DataSet> dataSetConfig)
            {
                rowMatchMode = dataSetConfig.RowMatchMode;
            }
            else if (context.Options is DataEquivalencyAssertionOptions<DataTable> dataTableConfig)
            {
                rowMatchMode = dataTableConfig.RowMatchMode;
            }

            var subject = (DataRowCollection)comparands.Subject;
            var expectation = (DataRowCollection)comparands.Expectation;

            bool success = AssertionScope.Current
                .ForCondition(subject.Count == expectation.Count)
                .FailWith("Expected {context:DataRowCollection} to contain {0} row(s){reason}, but found {1}",
                    expectation.Count, subject.Count);

            if (success)
            {
                switch (rowMatchMode)
                {
                    case RowMatchMode.Index:
                        MatchRowsByIndexAndCompare(context, nestedValidator, subject, expectation);
                        break;

                    case RowMatchMode.PrimaryKey:
                        MatchRowsByPrimaryKeyAndCompare(nestedValidator, context, subject, expectation);
                        break;

                    default:
                        AssertionScope.Current.FailWith(
                            "Unknown RowMatchMode {0} when trying to compare {context:DataRowCollection}", rowMatchMode);
                        break;
                }
            }
        }

        return EquivalencyResult.AssertionCompleted;
    }

    private static void MatchRowsByIndexAndCompare(IEquivalencyValidationContext context, IEquivalencyValidator parent, DataRowCollection subject, DataRowCollection expectation)
    {
        for (int index = 0; index < expectation.Count; index++)
        {
            IEquivalencyValidationContext nestedContext = context.AsCollectionItem<DataRow>(index);
            parent.RecursivelyAssertEquality(new Comparands(subject[index], expectation[index], typeof(DataRow)), nestedContext);
        }
    }

    private static void MatchRowsByPrimaryKeyAndCompare(IEquivalencyValidator parent, IEquivalencyValidationContext context, DataRowCollection subject, DataRowCollection expectation)
    {
        Type[] subjectPrimaryKeyTypes = null;
        Type[] expectationPrimaryKeyTypes = null;

        if (subject.Count > 0)
        {
            subjectPrimaryKeyTypes = GatherPrimaryKeyColumnTypes(subject[0].Table, "subject");
        }

        if (expectation.Count > 0)
        {
            expectationPrimaryKeyTypes = GatherPrimaryKeyColumnTypes(expectation[0].Table, "expectation");
        }

        bool matchingTypes = ComparePrimaryKeyTypes(subjectPrimaryKeyTypes, expectationPrimaryKeyTypes);

        if (matchingTypes)
        {
            GatherRowsByPrimaryKeyAndCompareData(parent, context, subject, expectation);
        }
    }

    private static Type[] GatherPrimaryKeyColumnTypes(DataTable table, string comparisonTerm)
    {
        Type[] primaryKeyTypes = null;

        if ((table.PrimaryKey is null) || (table.PrimaryKey.Length == 0))
        {
            AssertionScope.Current
                .FailWith("Table {0} containing {1} {context:DataRowCollection} does not have a primary key. RowMatchMode.PrimaryKey cannot be applied.", table.TableName, comparisonTerm);
        }
        else
        {
            primaryKeyTypes = new Type[table.PrimaryKey.Length];

            for (int i = 0; i < table.PrimaryKey.Length; i++)
            {
                primaryKeyTypes[i] = table.PrimaryKey[i].DataType;
            }
        }

        return primaryKeyTypes;
    }

    private static bool ComparePrimaryKeyTypes(Type[] subjectPrimaryKeyTypes, Type[] expectationPrimaryKeyTypes)
    {
        bool matchingTypes = false;

        if ((subjectPrimaryKeyTypes is not null) && (expectationPrimaryKeyTypes is not null))
        {
            matchingTypes = subjectPrimaryKeyTypes.Length == expectationPrimaryKeyTypes.Length;

            for (int i = 0; matchingTypes && (i < subjectPrimaryKeyTypes.Length); i++)
            {
                if (subjectPrimaryKeyTypes[i] != expectationPrimaryKeyTypes[i])
                {
                    matchingTypes = false;
                }
            }

            if (!matchingTypes)
            {
                AssertionScope.Current
                    .FailWith("Subject and expectation primary keys of table containing {context:DataRowCollection} do not have the same schema and cannot be compared. RowMatchMode.PrimaryKey cannot be applied.");
            }
        }

        return matchingTypes;
    }

    private static void GatherRowsByPrimaryKeyAndCompareData(IEquivalencyValidator parent, IEquivalencyValidationContext context, DataRowCollection subject, DataRowCollection expectation)
    {
        var expectationRowByKey = expectation.Cast<DataRow>()
            .ToDictionary(row => ExtractPrimaryKey(row));

        foreach (DataRow subjectRow in subject.Cast<DataRow>())
        {
            CompoundKey key = ExtractPrimaryKey(subjectRow);

            if (!expectationRowByKey.TryGetValue(key, out DataRow expectationRow))
            {
                AssertionScope.Current
                    .FailWith("Found unexpected row in {context:DataRowCollection} with key {0}", key);
            }
            else
            {
                expectationRowByKey.Remove(key);

                IEquivalencyValidationContext nestedContext = context.AsCollectionItem<DataRow>(key.ToString());
                parent.RecursivelyAssertEquality(new Comparands(subjectRow, expectationRow, typeof(DataRow)), nestedContext);
            }
        }

        if (expectationRowByKey.Count > 0)
        {
            if (expectationRowByKey.Count > 1)
            {
                AssertionScope.Current
                    .FailWith("{0} rows were expected in {context:DataRowCollection} and not found", expectationRowByKey.Count);
            }
            else
            {
                AssertionScope.Current
                    .FailWith("Expected to find a row with key {0} in {context:DataRowCollection}{reason}, but no such row was found", expectationRowByKey.Keys.Single());
            }
        }
    }

    private class CompoundKey : IEquatable<CompoundKey>
    {
        private readonly object[] values;

        public CompoundKey(params object[] values)
        {
            this.values = values;
        }

        public bool Equals(CompoundKey other)
        {
            if (other is null)
            {
                return false;
            }

            if (values.Length != other.values.Length)
            {
                return false;
            }

            for (int i = 0; i < values.Length; i++)
            {
                if (!values[i].Equals(other.values[i]))
                {
                    return false;
                }
            }

            return true;
        }

        public override bool Equals(object obj) => Equals(obj as CompoundKey);

        public override int GetHashCode()
        {
            int hash = 0;

            for (int i = 0; i < values.Length; i++)
            {
                hash = (hash * 389) ^ values[i].GetHashCode();
            }

            return hash;
        }

        public override string ToString()
        {
            return "{ " + string.Join(", ", values) + " }";
        }
    }

    private static CompoundKey ExtractPrimaryKey(DataRow row)
    {
        DataColumn[] primaryKey = row.Table.PrimaryKey;

        var values = new object[primaryKey.Length];

        for (int i = 0; i < values.Length; i++)
        {
            values[i] = row[primaryKey[i]];
        }

        return new CompoundKey(values);
    }
}


text:
package de.jcup.egradle.junit;

public enum EGradleJUnitTestTasksType {
    CLEAN_ALL("egradle.junit.clean.all", "clean test"),

    CLEAN_ONLY_TESTS("egradle.junit.clean.onlytests", "cleanTest test"),

    CLEAN_NOTHING("egradle.junit.clean.nothing", "test");

    private String id;
    private String testTasks;

    EGradleJUnitTestTasksType(String id, String testTasks) {
        this.id = id;
        this.testTasks = testTasks;
    }

    public String getId() {
        return id;
    }

    public String getTestTasks() {
        return testTasks;
    }

    public static EGradleJUnitTestTasksType findById(String id) {
        for (EGradleJUnitTestTasksType c : values()) {
            if (c.getId().equals(id)) {
                return c;
            }
        }
        return null;
    }
}


text:
module.exports = {
  root: true,
  parserOptions: {
    sourceType: 'module'
  },
  extends: 'standard', // https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style
  plugins: [
    'jest'
  ],
  rules: { // add your custom rules here
    'arrow-parens': 0, // allow paren-less arrow functions
    'generator-star-spacing': 0, // allow async-await
    'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0, // allow debugger during development
    indent: [2, 2]
  },
  env: {
    browser: true,
    'jest/globals': true
  }
}


text:
<?php use_stylesheet('/opCalendarPlugin/css/main') ?>
<div class="dparts weeklyCalendarTable" id="homeCalendarList_<?php echo $gadget->id ?>">

<?php echo __('Weekly Calendar') ?>

<?php if ($isSelf): ?>

<?php echo $form->renderFormTag(url_for('@schedule_create_mini')), "\n" ?>
<?php echo $form->renderHiddenFields(), "\n" ?>
<?php echo __('Schedule') ?>
<?php echo $form['title']->render(array('class' => 'input_text')), "\n" ?>
<?php echo $form['start_date']->render(), "\n" ?>
<input type="hidden" value="<?php echo $w ?>" name="calendar_weekparam" />
<input type="submit" value="<?php echo __('Add') ?>" class="input_submit" />

 <?php echo link_to('<<', '@homepage?calendar_weekparam='.$pw, array('class' => 'prev', 'title' => __('Prev week'))), "\n" ?>
 <?php echo link_to('■', '@homepage', array('class' => 'curr', 'title' => __('This week')), "\n") ?>
 <?php echo link_to('>>', '@homepage?calendar_weekparam='.$nw , array('class' => 'next', 'title' => __('Next week'))), "\n" ?>

</form>

<?php endif; ?>

<?php foreach ($calendar as $item): ?>

<?php
$cls_today = $item['today'] ? ' today' : '';
$cls_holiday = count($item['holidays']) ? ' holiday' : '';

$str_month = '';
if (1 == $item['day'] || 'mon' === $item['dayofweek_class_name'])
{
   $str_month = sprintf('%d/', $item['month']);
}
?>
<?php echo sprintf('', $item['dayofweek_class_name'], $cls_today, $cls_holiday), "\n" ?>
<?php echo sprintf('
%s%d (%s)
', $str_month, $item['day'], __($item['dayofweek_item_name'])), "\n" ?>
<?php foreach ($item['holidays'] as $holiday): ?>

<?php echo $holiday ?>

<?php endforeach ?>
<?php foreach ($item['births'] as $birth_member): ?>

<?php echo op_link_to_member($birth_member, array('link_target' => sprintf('%s %sさん', image_tag('/opCalendarPlugin/images/icon_birthday.gif', array('alt' => '[誕]')), $birth_member->getName()))) ?>

<?php endforeach ?>
<?php foreach ($item['events'] as $event): ?>
<?php
if ($event['is_join'])
{
  $eventIcon = 'icon_event_R.gif';
  $eventAlt  = '[参]';
}
else
{
  $eventIcon = 'icon_event_B.gif';
  $eventAlt  = '[イ]';
}
?>

<?php echo link_to(sprintf('%s %s', image_tag('/opCalendarPlugin/images/'.$eventIcon, array('alt' => $eventAlt)), op_truncate($event['name'], 20, '...', 1)), '@communityEvent_show?id='.$event['id']) ?>

<?php endforeach ?>
<?php foreach ($item['schedules'] as $schedule): ?>
<?php if ($schedule->isShowable($sf_user->getMemberId())): ?>

<?php echo link_to(sprintf('%s %s', image_tag('/opCalendarPlugin/images/icon_pen.gif', array('alt' => '[予]')), op_truncate($schedule->title, 20, '...', 1)), '@schedule_show?id='.$schedule->id) ?>

<?php endif ?>
<?php endforeach ?>

<?php endforeach ?>

<?php echo link_to(__('Monthly Calendar'), 'calendar_member_obj', $member) ?>


text:
package org.cr.crawler.node.executor;

import org.cr.crawler.common.model.Task;
import org.cr.crawler.common.utils.BlockingThreadPoolExecutor;
import org.cr.crawler.node.handle.CallbackHandler;
import org.cr.crawler.node.operation.Operation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Author: caorong
 * Date: 13-11-16
 * Time: 下午9:37
 * To change this template use File | Settings | File Templates.
 */
public class SimpleTaskExecutor implements TaskExecutor {
    private Logger logger = LoggerFactory.getLogger(SimpleTaskExecutor.class);

    protected Operation operation;

    protected ExecutorService executorService;

    private int poolSize;

    private int queueSize;

    private String poolName;

    private volatile AtomicInteger count = new AtomicInteger();

    protected CallbackHandler handler;

    public void init() {
        if (poolName == null) {
            executorService = new BlockingThreadPoolExecutor(poolSize, new ArrayBlockingQueue<Runnable>(queueSize));
        } else {
            executorService = new BlockingThreadPoolExecutor(poolSize, poolName, new ArrayBlockingQueue<Runnable>(
                    queueSize));
        }
        logger.debug("initialize taskexecutor with operation={},poolSize={},queueSize={},poolName={},handler={}",
                operation, poolSize, queueSize, poolName, handler);
    }

    @Override
    public void execute(Task task) {
        TaskRunner taskRunner = new TaskRunner(operation, handler, task, count);
        logger.debug("prepare to execute task[{}] with operation[{}] and handler[{}]", task, operation, handler);
        executorService.submit(taskRunner);
    }

    @Override
    public void refresh() {
    }

    @Override
    public AtomicInteger getCount() {
        return count;
    }

    public void setOperation(Operation operation) {
        this.operation = operation;
    }

    public int getPoolSize() {
        return poolSize;
    }

    public void setPoolSize(int poolSize) {
        this.poolSize = poolSize;
    }

    public void setPoolName(String poolName) {
        this.poolName = poolName;
    }

    public void setHandler(CallbackHandler handler) {
        this.handler = handler;
    }

    public int getQueueSize() {
        return queueSize;
    }

    public void setQueueSize(int queueSize) {
        this.queueSize = queueSize;
    }
}


text:
namespace Microsoft.Azure.Management.Logic.Models
{
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// The workflow run action correlation properties.
    /// </summary>
    public partial class RunActionCorrelation : RunCorrelation
    {
        /// <summary>
        /// Initializes a new instance of the RunActionCorrelation class.
        /// </summary>
        public RunActionCorrelation()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the RunActionCorrelation class.
        /// </summary>
        /// <param name="clientTrackingId">The client tracking
        /// identifier.</param>
        /// <param name="clientKeywords">The client keywords.</param>
        /// <param name="actionTrackingId">The action tracking
        /// identifier.</param>
        public RunActionCorrelation(string clientTrackingId = default(string), IList<string> clientKeywords = default(IList<string>), string actionTrackingId = default(string))
            : base(clientTrackingId, clientKeywords)
        {
            ActionTrackingId = actionTrackingId;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the action tracking identifier.
        /// </summary>
        [JsonProperty(PropertyName = "actionTrackingId")]
        public string ActionTrackingId { get; set; }

    }
}


text:
import React from "react";
import { act, render, RenderResult } from "@testing-library/react";
import { MatrixClient, MatrixEvent } from "matrix-js-sdk/src/matrix";

import UserMenu from "../../../src/components/structures/UserMenu";
import { stubClient } from "../../test-utils";
import {
    VoiceBroadcastInfoState,
    VoiceBroadcastRecording,
    VoiceBroadcastRecordingsStore,
} from "../../../src/voice-broadcast";
import { mkVoiceBroadcastInfoStateEvent } from "../../voice-broadcast/utils/test-utils";

describe("<UserMenu>", () => {
    let client: MatrixClient;
    let renderResult: RenderResult;
    let voiceBroadcastInfoEvent: MatrixEvent;
    let voiceBroadcastRecording: VoiceBroadcastRecording;
    let voiceBroadcastRecordingsStore: VoiceBroadcastRecordingsStore;

    beforeAll(() => {
        client = stubClient();
        voiceBroadcastInfoEvent = mkVoiceBroadcastInfoStateEvent(
            "!room:example.com",
            VoiceBroadcastInfoState.Started,
            client.getUserId() || "",
            client.getDeviceId() || "",
        );
        voiceBroadcastRecording = new VoiceBroadcastRecording(
            voiceBroadcastInfoEvent,
            client,
        );
    });

    beforeEach(() => {
        voiceBroadcastRecordingsStore = VoiceBroadcastRecordingsStore.instance();
    });

    describe("when rendered", () => {
        beforeEach(() => {
            renderResult = render(<UserMenu isPanelCollapsed={true} />);
        });

        it("should render as expected", () => {
            expect(renderResult.container).toMatchSnapshot();
        });

        describe("and a live voice broadcast starts", () => {
            beforeEach(() => {
                act(() => {
                    voiceBroadcastRecordingsStore.setCurrent(voiceBroadcastRecording);
                });
            });

            it("should render the live voice broadcast avatar addon", () => {
                expect(renderResult.queryByTestId("user-menu-live-vb")).toBeInTheDocument();
            });

            describe("and the broadcast ends", () => {
                beforeEach(() => {
                    act(() => {
                        voiceBroadcastRecordingsStore.clearCurrent();
                    });
                });

                it("should not render the live voice broadcast avatar addon", () => {
                    expect(renderResult.queryByTestId("user-menu-live-vb")).not.toBeInTheDocument();
                });
            });
        });
    });
});


text:
/* DO NOT EDIT!  This file is generated by sdlgenblit.pl */
/*
    SDL - Simple DirectMedia Layer
    Copyright (C) 1997-2010 Sam Lantinga

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

    Sam Lantinga
    slouken@libsdl.org
*/
#include "SDL_config.h"

/* *INDENT-OFF* */

extern SDL_BlitFuncEntry SDL_GeneratedBlitFuncTable[];

/* *INDENT-ON* */

/* vi: set ts=4 sw=4 expandtab: */


text:
"""The tests for the Radarr platform."""
import unittest

import pytest

from homeassistant.components.sensor import radarr

from tests.common import get_test_home_assistant

def mocked_exception(*args, **kwargs):
    """Mock exception thrown by requests.get."""
    raise OSError

def mocked_requests_get(*args, **kwargs):
    """Mock requests.get invocations."""
    class MockResponse:
        """Class to represent a mocked response."""

        def __init__(self, json_data, status_code):
            """Initialize the mock response class."""
            self.json_data = json_data
            self.status_code = status_code

        def json(self):
            """Return the json of the response."""
            return self.json_data

    url = str(args[0])
    if 'api/calendar' in url:
        return MockResponse([
            {
                "title": "Resident Evil",
                "sortTitle": "resident evil final chapter",
                "sizeOnDisk": 0,
                "status": "announced",
                "overview": "Alice, Jill, Claire, Chris, Leon, Ada, and...",
                "inCinemas": "2017-01-25T00:00:00Z",
                "physicalRelease": "2017-01-27T00:00:00Z",
                "images": [
                    {
                        "coverType": "poster",
                        "url": ("/radarr/MediaCover/12/poster.jpg"
                                "?lastWrite=636208663600000000")
                    },
                    {
                        "coverType": "banner",
                        "url": ("/radarr/MediaCover/12/banner.jpg"
                                "?lastWrite=636208663600000000")
                    }
                ],
                "website": "",
                "downloaded": "false",
                "year": 2017,
                "hasFile": "false",
                "youTubeTrailerId": "B5yxr7lmxhg",
                "studio": "Impact Pictures",
                "path": "/path/to/Resident Evil The Final Chapter (2017)",
                "profileId": 3,
                "monitored": "false",
                "runtime": 106,
                "lastInfoSync": "2017-01-24T14:52:40.315434Z",
                "cleanTitle": "residentevilfinalchapter",
                "imdbId": "tt2592614",
                "tmdbId": 173897,
                "titleSlug": "resident-evil-the-final-chapter-2017",
                "genres": [
                    "Action",
                    "Horror",
                    "Science Fiction"
                ],
                "tags": [],
                "added": "2017-01-24T14:52:39.989964Z",
                "ratings": {
                    "votes": 363,
                    "value": 4.3
                },
                "alternativeTitles": [
                    "Resident Evil: Rising"
                ],
                "qualityProfileId": 3,
                "id": 12
            }
        ], 200)
    elif 'api/command' in url:
        return MockResponse([
            {
                "name": "RescanMovie",
                "startedOn": "0001-01-01T00:00:00Z",
                "stateChangeTime": "2014-02-05T05:09:09.2366139Z",
                "sendUpdatesToClient": "true",
                "state": "pending",
                "id": 24
            }
        ], 200)
    elif 'api/movie' in url:
        return MockResponse([
            {
                "title": "Assassin's Creed",
                "sortTitle": "assassins creed",
                "sizeOnDisk": 0,
                "status": "released",
                "overview": "Lynch discovers he is a descendant of...",
                "inCinemas": "2016-12-21T00:00:00Z",
                "images": [
                    {
                        "coverType": "poster",
                        "url": ("/radarr/MediaCover/1/poster.jpg"
                                "?lastWrite=636200219330000000")
                    },
                    {
                        "coverType": "banner",
                        "url": ("/radarr/MediaCover/1/banner.jpg"
                                "?lastWrite=636200219340000000")
                    }
                ],
                "website": "https://www.ubisoft.com/en-US/",
                "downloaded": "false",
                "year": 2016,
                "hasFile": "false",
                "youTubeTrailerId": "pgALJgMjXN4",
                "studio": "20th Century Fox",
                "path": "/path/to/Assassin's Creed (2016)",
                "profileId": 6,
                "monitored": "true",
                "runtime": 115,
                "lastInfoSync": "2017-01-23T22:05:32.365337Z",
                "cleanTitle": "assassinscreed",
                "imdbId": "tt2094766",
                "tmdbId": 121856,
                "titleSlug": "assassins-creed-121856",
                "genres": [
                    "Action",
                    "Adventure",
                    "Fantasy",
                    "Science Fiction"
                ],
                "tags": [],
                "added": "2017-01-14T20:18:52.938244Z",
                "ratings": {
                    "votes": 711,
                    "value": 5.2
                },
                "alternativeTitles": [
                    "Assassin's Creed: The IMAX Experience"
                ],
                "qualityProfileId": 6,
                "id": 1
            }
        ], 200)
    elif 'api/diskspace' in url:
        return MockResponse([
            {
                "path": "/data",
                "label": "",
                "freeSpace": 282500067328,
                "totalSpace": 499738734592
            }
        ], 200)
    elif 'api/system/status' in url:
        return MockResponse({
            "version": "0.2.0.210",
            "buildTime": "2017-01-22T23:12:49Z",
            "isDebug": "false",
            "isProduction": "true",
            "isAdmin": "false",
            "isUserInteractive": "false",
            "startupPath": "/path/to/radarr",
            "appData": "/path/to/radarr/data",
            "osVersion": "4.8.13.1",
            "isMonoRuntime": "true",
            "isMono": "true",
            "isLinux": "true",
            "isOsx": "false",
            "isWindows": "false",
            "branch": "develop",
            "authentication": "forms",
            "sqliteVersion": "3.16.2",
            "urlBase": "",
            "runtimeVersion": ("4.6.1 "
                               "(Stable 4.6.1.3/abb06f1 "
                               "Mon Oct  3 07:57:59 UTC 2016)")
        }, 200)
    else:
        return MockResponse({
            "error": "Unauthorized"
        }, 401)

class TestRadarrSetup(unittest.TestCase):
    """Test the Radarr platform."""

    # pylint: disable=invalid-name
    DEVICES = []

    def add_devices(self, devices, update):
        """Mock add devices."""
        for device in devices:
            self.DEVICES.append(device)

    def setUp(self):
        """Initialize values for this testcase class."""
        self.DEVICES = []
        self.hass = get_test_home_assistant()
        self.hass.config.time_zone = 'America/Los_Angeles'

    def tearDown(self):  # pylint: disable=invalid-name
        """Stop everything that was started."""
        self.hass.stop()

    @unittest.mock.patch('requests.get', side_effect=mocked_requests_get)
    def test_diskspace_no_paths(self, req_mock):
        """Test getting all disk space."""
        config = {
            'platform': 'radarr',
            'api_key': 'foo',
            'days': '2',
            'unit': 'GB',
            "include_paths": [],
            'monitored_conditions': [
                'diskspace'
            ]
        }
        radarr.setup_platform(self.hass, config, self.add_devices, None)
        for device in self.DEVICES:
            device.update()
            self.assertEqual('263.10', device.state)
            self.assertEqual('mdi:harddisk', device.icon)
            self.assertEqual('GB', device.unit_of_measurement)
            self.assertEqual('Radarr Disk Space', device.name)
            self.assertEqual(
                '263.10/465.42GB (56.53%)',
                device.device_state_attributes["/data"]
            )

    @unittest.mock.patch('requests.get', side_effect=mocked_requests_get)
    def test_diskspace_paths(self, req_mock):
        """Test getting diskspace for included paths."""
        config = {
            'platform': 'radarr',
            'api_key': 'foo',
            'days': '2',
            'unit': 'GB',
            "include_paths": [
                '/data'
            ],
            'monitored_conditions': [
                'diskspace'
            ]
        }
        radarr.setup_platform(self.hass, config, self.add_devices, None)
        for device in self.DEVICES:
            device.update()
            self.assertEqual('263.10', device.state)
            self.assertEqual('mdi:harddisk', device.icon)
            self.assertEqual('GB', device.unit_of_measurement)
            self.assertEqual('Radarr Disk Space', device.name)
            self.assertEqual(
                '263.10/465.42GB (56.53%)',
                device.device_state_attributes["/data"]
            )

    @unittest.mock.patch('requests.get', side_effect=mocked_requests_get)
    def test_commands(self, req_mock):
        """Test getting running commands."""
        config = {
            'platform': 'radarr',
            'api_key': 'foo',
            'days': '2',
            'unit': 'GB',
            "include_paths": [
                '/data'
            ],
            'monitored_conditions': [
                'commands'
            ]
        }
        radarr.setup_platform(self.hass, config, self.add_devices, None)
        for device in self.DEVICES:
            device.update()
            self.assertEqual(1, device.state)
            self.assertEqual('mdi:code-braces', device.icon)
            self.assertEqual('Commands', device.unit_of_measurement)
            self.assertEqual('Radarr Commands', device.name)
            self.assertEqual(
                'pending',
                device.device_state_attributes["RescanMovie"]
            )

    @unittest.mock.patch('requests.get', side_effect=mocked_requests_get)
    def test_movies(self, req_mock):
        """Test getting the number of movies."""
        config = {
            'platform': 'radarr',
            'api_key': 'foo',
            'days': '2',
            'unit': 'GB',
            "include_paths": [
                '/data'
            ],
            'monitored_conditions': [
                'movies'
            ]
        }
        radarr.setup_platform(self.hass, config, self.add_devices, None)
        for device in self.DEVICES:
            device.update()
            self.assertEqual(1, device.state)
            self.assertEqual('mdi:television', device.icon)
            self.assertEqual('Movies', device.unit_of_measurement)
            self.assertEqual('Radarr Movies', device.name)
            self.assertEqual(
                'false',
                device.device_state_attributes["Assassin's Creed (2016)"]
            )

    @unittest.mock.patch('requests.get', side_effect=mocked_requests_get)
    def test_upcoming_multiple_days(self, req_mock):
        """Test the upcoming movies for multiple days."""
        config = {
            'platform': 'radarr',
            'api_key': 'foo',
            'days': '2',
            'unit': 'GB',
            "include_paths": [
                '/data'
            ],
            'monitored_conditions': [
                'upcoming'
            ]
        }
        radarr.setup_platform(self.hass, config, self.add_devices, None)
        for device in self.DEVICES:
            device.update()
            self.assertEqual(1, device.state)
            self.assertEqual('mdi:television', device.icon)
            self.assertEqual('Movies', device.unit_of_measurement)
            self.assertEqual('Radarr Upcoming', device.name)
            self.assertEqual(
                '2017-01-27T00:00:00Z',
                device.device_state_attributes["Resident Evil (2017)"]
            )

    @pytest.mark.skip
    @unittest.mock.patch('requests.get', side_effect=mocked_requests_get)
    def test_upcoming_today(self, req_mock):
        """Test filtering for a single day.

        Radarr needs to respond with at least 2 days.
        """
        config = {
            'platform': 'radarr',
            'api_key': 'foo',
            'days': '1',
            'unit': 'GB',
            "include_paths": [
                '/data'
            ],
            'monitored_conditions': [
                'upcoming'
            ]
        }
        radarr.setup_platform(self.hass, config, self.add_devices, None)
        for device in self.DEVICES:
            device.update()
            self.assertEqual(1, device.state)
            self.assertEqual('mdi:television', device.icon)
            self.assertEqual('Movies', device.unit_of_measurement)
            self.assertEqual('Radarr Upcoming', device.name)
            self.assertEqual(
                '2017-01-27T00:00:00Z',
                device.device_state_attributes["Resident Evil (2017)"]
            )

    @unittest.mock.patch('requests.get', side_effect=mocked_requests_get)
    def test_system_status(self, req_mock):
        """Test the getting of the system status."""
        config = {
            'platform': 'radarr',
            'api_key': 'foo',
            'days': '2',
            'unit': 'GB',
            "include_paths": [
                '/data'
            ],
            'monitored_conditions': [
                'status'
            ]
        }
        radarr.setup_platform(self.hass, config, self.add_devices, None)
        for device in self.DEVICES:
            device.update()
            self.assertEqual('0.2.0.210', device.state)
            self.assertEqual('mdi:information', device.icon)
            self.assertEqual('Radarr Status', device.name)
            self.assertEqual(
                '4.8.13.1', device.device_state_attributes['osVersion'])

    @pytest.mark.skip
    @unittest.mock.patch('requests.get', side_effect=mocked_requests_get)
    def test_ssl(self, req_mock):
        """Test SSL being enabled."""
        config = {
            'platform': 'radarr',
            'api_key': 'foo',
            'days': '1',
            'unit': 'GB',
            "include_paths": [
                '/data'
            ],
            'monitored_conditions': [
                'upcoming'
            ],
            "ssl": "true"
        }
        radarr.setup_platform(self.hass, config, self.add_devices, None)
        for device in self.DEVICES:
            device.update()
            self.assertEqual(1, device.state)
            self.assertEqual('s', device.ssl)
            self.assertEqual('mdi:television', device.icon)
            self.assertEqual('Movies', device.unit_of_measurement)
            self.assertEqual('Radarr Upcoming', device.name)
            self.assertEqual(
                '2017-01-27T00:00:00Z',
                device.device_state_attributes["Resident Evil (2017)"]
            )

    @unittest.mock.patch('requests.get', side_effect=mocked_exception)
    def test_exception_handling(self, req_mock):
        """Test exception being handled."""
        config = {
            'platform': 'radarr',
            'api_key': 'foo',
            'days': '1',
            'unit': 'GB',
            "include_paths": [
                '/data'
            ],
            'monitored_conditions': [
                'upcoming'
            ]
        }
        radarr.setup_platform(self.hass, config, self.add_devices, None)
        for device in self.DEVICES:
            device.update()
            self.assertEqual(None, device.state)


text:
using System.Runtime.CompilerServices;

namespace System.Html.Media.Graphics.SVG {
	[IgnoreNamespace, Imported(ObeysTypeSystem = true)]
	public partial class SVGPathSegLinetoHorizontalRel : SVGPathSeg {
		internal SVGPathSegLinetoHorizontalRel() {
		}

		[IntrinsicProperty]
		public double X {
			get {
				return 0;
			}
			set {
			}
		}
	}
}


text:
SELECT dept_name, COUNT(DISTINCT student_id) student_number
FROM department d LEFT JOIN student s
    ON s.dept_id = d.dept_id
GROUP BY dept_name
ORDER BY student_number DESC, dept_name;


text:
/**
 * Created by yi on 2015/3/29.
 */

import List from "templates/List";

const DATA_URL = "../app/data/skills.json";

class SkillList extends List {

    constructor() {
        this.dataUrl = DATA_URL;
    }
}

Graph.put("SkillList", SkillList);


text:
[![LICENSE](http://img.shields.io/badge/LICENSE-MIT-brightgreen.svg)](http://opensource.org/licenses/MIT) [![meteor package version](http://img.shields.io/badge/atmosphere-1.1.0-brightgreen.svg)](https://atmospherejs.com/lifelynl/focuspoint)

Using Focuspoint v1.0.5

## Usage

```
meteor add lifelynl:focuspoint
```

`Focuspoint` is defined if used in a package.


text:
package org.elasticsearch.cluster.serialization;

import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.cluster.routing.allocation.AllocationService;
import org.elasticsearch.common.io.stream.BytesStreamInput;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.test.ElasticsearchAllocationTestCase;
import org.junit.Test;

import static org.hamcrest.Matchers.equalTo;

/**
 *
 */
public class ClusterSerializationTests extends ElasticsearchAllocationTestCase {

    @Test
    public void testClusterStateSerialization() throws Exception {
        MetaData metaData = MetaData.builder()
                .put(IndexMetaData.builder("test").numberOfShards(10).numberOfReplicas(1))
                .build();

        RoutingTable routingTable = RoutingTable.builder()
                .addAsNew(metaData.index("test"))
                .build();

        DiscoveryNodes nodes = DiscoveryNodes.builder().put(newNode("node1")).put(newNode("node2")).put(newNode("node3")).localNodeId("node1").masterNodeId("node2").build();

        ClusterState clusterState = ClusterState.builder(new ClusterName("clusterName1")).nodes(nodes).metaData(metaData).routingTable(routingTable).build();

        AllocationService strategy = createAllocationService();
        clusterState = ClusterState.builder(clusterState).routingTable(strategy.reroute(clusterState).routingTable()).build();

        ClusterState serializedClusterState = ClusterState.Builder.fromBytes(ClusterState.Builder.toBytes(clusterState), newNode("node1"), new ClusterName("clusterName2"));

        assertThat(serializedClusterState.getClusterName().value(), equalTo(clusterState.getClusterName().value()));
        assertThat(serializedClusterState.routingTable().prettyPrint(), equalTo(clusterState.routingTable().prettyPrint()));
    }

    @Test
    public void testRoutingTableSerialization() throws Exception {
        MetaData metaData = MetaData.builder()
                .put(IndexMetaData.builder("test").numberOfShards(10).numberOfReplicas(1))
                .build();

        RoutingTable routingTable = RoutingTable.builder()
                .addAsNew(metaData.index("test"))
                .build();

        DiscoveryNodes nodes = DiscoveryNodes.builder().put(newNode("node1")).put(newNode("node2")).put(newNode("node3")).build();

        ClusterState clusterState = ClusterState.builder(org.elasticsearch.cluster.ClusterName.DEFAULT).nodes(nodes).metaData(metaData).routingTable(routingTable).build();

        AllocationService strategy = createAllocationService();
        RoutingTable source = strategy.reroute(clusterState).routingTable();

        BytesStreamOutput outStream = new BytesStreamOutput();
        RoutingTable.Builder.writeTo(source, outStream);
        BytesStreamInput inStream = new BytesStreamInput(outStream.bytes().toBytes());
        RoutingTable target = RoutingTable.Builder.readFrom(inStream);

        assertThat(target.prettyPrint(), equalTo(source.prettyPrint()));
    }

}


text:
<?php

namespace Opifer\CmsBundle\Controller\Backend;

use Opifer\CmsBundle\Form\Type\SettingFormType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class SettingController extends Controller
{
    /**
     * @param Request $request
     *
     * @return Response
     */
    public function indexAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $settings = $em->getRepository('OpiferCmsBundle:Setting')->findAll();

        $form = $this->createForm(new SettingFormType(), $settings);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $config = [];
            foreach ($form->getData() as $key => $value) {
                if (!is_int($key)) {
                    $config[$key] = $value;
                }
            }

            foreach ($settings as $setting) {
                $name = $setting->getExtension().'_'.str_replace('.', '_', $setting->getName());

                $setting->setValue($config[$name]);
            }
            $em->flush();

            $this->addFlash('success', $this->get('translator')->trans('settings.edit.success'));
        }

        return $this->render('OpiferCmsBundle:Backend/Setting:index.html.twig', array(
            'form' => $form->createView(),
        ));
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="app_name">pumexgpucull example</string>
</resources>


text: some personal works.


text:
var test       = require('tape')
  , excel      = require('../')
  , fs         = require('fs')
  , csvParser  = require('csv-parser')
  , concat     = require('concat-stream')
  , through2   = require('through2').obj
  , equal      = require('deep-equal')

test('functional', function(t){
  t.plan(1)

  var file = require.resolve('./air_pollution_nl.xlsx')
  var expected = require('./air_pollution_nl.json')

  fs.createReadStream(file)
    .pipe( excel() ).on('error', function(err){
      throw err
    })
    .pipe( csvParser() )

    // Ignore tiny rounding differences
    .pipe( through2(function(obj, _, next){
      for(var k in obj) {
        var val = obj[k]
        if (!isNaN(val)) obj[k] = (+val).toFixed(2)
      }

      next(null, obj)
    }))

    .pipe( concat(function(data){
      t.ok(equal(data, expected), 'equal')
    }))
})


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class RemovePermissionColumnFromPages extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('pages', function (Blueprint $table) {
            $table->dropColumn('permissions');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('pages', function (Blueprint $table) {
            $table->mediumText('permissions')->nullable();
        });
    }
}


text: export { Education24 as default } from "../../";


text:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">

  <title>WebRTC PyAuto Test</title>

      Local Preview
      Remote Video

      <video width="320" height="240" id="local_view"
          autoplay="autoplay"></video>
      <video width="320" height="240" id="remote_view"
          autoplay="autoplay"></video>
      <canvas id="frame_buffer" style="visibility:hidden"></canvas>


text:
#include <Model/Materials/MaterialTable.h>

#include <Interface/RayPacket.h>
#include <Interface/Context.h>

using namespace Manta;

MaterialTable::~MaterialTable() {

  // Delete all of the owned materials.
  for (size_t i=0;i<material_table.size();++i) {
    if (material_table[i].material && material_table[i].owned) {
      delete material_table[i].material;
    }
  }
}

void MaterialTable::preprocess(const PreprocessContext& context) {

  // Call preprocess on each material.
  for (size_t i=0;i<material_table.size();++i) {
    if (material_table[i].material) {
      material_table[i].material->preprocess( context );
    }
  }
}

void MaterialTable::shade(const RenderContext& context, RayPacket& rays) const {

  // Determine material id's.
  Packet<int> id;
  id_texture->mapValues( id, context, rays );

  // Shade continuous subpackets of matching materials.
  for(int i = rays.begin();i<rays.end();){
    const Material *hit_matl = material_table[ id.data[i] ].material;
    int end = i+1;

    while(end < rays.end() && rays.wasHit(end) &&
          material_table[id.data[end]].material == hit_matl)
      end++;

    // Shade the subpacket of rays.
    RayPacket subPacket(rays, i, end);
    hit_matl->shade(context, subPacket);
    i=end;

  }
}

void MaterialTable::setMaterial(unsigned int material_id, Material *material, bool owned ) {
  // Check to see that the table size is correct.
  if (material_id >= material_table.size()) {
    material_table.resize( material_id+1, Entry( 0, false ) );
  }

  // Check to see if another owned material already occupies the spot.
  if (material_table[material_id].material &&
      material_table[material_id].owned) {
    delete material_table[material_id].material;
    material_table[material_id].material = 0;
  }

  // Lastly assign the pointer.
  material_table[material_id].material = material;
  material_table[material_id].owned = owned;
}

Material *MaterialTable::getMaterial( unsigned int material_id ) {

  return material_table[material_id].material;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AH.PRMS.MODEL;
using AH.HR.MODEL;
using AH.HR.DAL;
using AH.Shared.MODEL;

namespace AH.HR.BLL
{
    public class EmployeeMasterReportBLL
    {
        public List<EmployeeMasterRO> RptGetEmpMaster(string EmpMaster, string oLvTpSet, string Param)
        {
            return new EmployeeMasterReportDAL().RptGetEmpMaster(EmpMaster, oLvTpSet, Param);
        }
        public List<EmployeeMasterRO> RptGetAllEmployeeMas(string DeptType, string DeptGrp, string Dept, string Unit)
        {
            return new EmployeeMasterReportDAL().RptGetAllEmployeeMas(DeptType, DeptGrp, Dept, Unit);
        }
        public List<EmployeeMasterRO> RptGetAllEmployee()
        {
            return new EmployeeMasterReportDAL().RptGetAllEmployee();
        }
        public List<EmployeeMasterRO> GetEmployeeInfo(string mode, string param)
        {
            return new EmployeeMasterReportDAL().GetEmployeeInfo(mode, param);
        }
        public List<EmployeeMasterRO> GetEmpJoiningReport(string Mode, string DeptGroup, string Dept,string Unit,string StartDate,string EndDate)
        {
            return new EmployeeMasterReportDAL().GetEmpJoiningReport(Mode, DeptGroup, Dept, Unit, StartDate, EndDate);
        }
        public List<EmployeeMasterRO> GetEmpResigReport(string Mode, string DeptGroup, string Dept, string Unit, string StartDate, string EndDate)
        {
            return new EmployeeMasterReportDAL().GetEmpResigReport(Mode, DeptGroup, Dept, Unit, StartDate, EndDate);
        }
        public List<EmployeeMasterRO> GetEmpConfDateReport(string Mode, string DeptGroup, string Dept, string Unit, string StartDate, string EndDate)
        {
            return new EmployeeMasterReportDAL().GetEmpConfDateReport(Mode, DeptGroup, Dept, Unit, StartDate, EndDate);
        }
        public List<EmployeeMasterRO> GetEmpOthersReport(string Mode, string DeptGroup, string Dept, string Unit,string DropType,string StartDate, string EndDate)
        {
            return new EmployeeMasterReportDAL().GetEmpOthersReport(Mode, DeptGroup, Dept, Unit,DropType,StartDate, EndDate);
        }
    }
}


text:
import click
from flanker.addresslib import address
import time
import logging

from requeue.requeue import DistributedQueue, DistributedQueueEmpty
from workers.logger import LoggerBackend
from workers.aws import AWSBackend
from workers.sg import SendgridBackend
from workers.exceptions import WorkerInvalidEmail

workers = {
    'logger': LoggerBackend,
    'aws': AWSBackend,
    'sendgrid': SendgridBackend
}

logger = logging.getLogger('reworker')
logger.addHandler(logging.NullHandler())  # hide errors about missing handlers

def _validate_email(email):
    """
    Validate well-formness of email

    E.g. that subject and body are non-empty, and to and from email addresses are valid.

    :return: valid, reason where valid is a boolean and reason is a string
    """

    # TODO This should be more defensive. What if subject and body are not strings?
    # We could also return better error messages.

    # 1. subject and body are non-empty
    if email.get('subject', '').strip() == '':
        return False, 'Subject is empty'
    if email.get('body', '').strip() == '':
        return False, 'Body is empty'

    # 2. to_email and from_email are valid e-mails
    # We use mailgun's flanker (https://github.com/mailgun/flanker) for the heavy lifting
    email['to_email'] = address.parse(email.get('to_email', ''), addr_spec_only=True)
    email['from_email'] = address.parse(email.get('from_email', ''), addr_spec_only=True)  # TODO cache this check?

    if email['to_email'] is None:
        return False, 'To-Email is not valid'

    if email['from_email'] is None:
        return False, 'From-Email is not valid'

    return True, ''

def run(worker, queue, terminate_after_one_iteration=False, wait_on_empty=5, connection_timeout=0):

    while 1:
        try:
            email, token = queue.reserve(connection_timeout=connection_timeout)
            valid, reason = _validate_email(email)

            if valid:

                try:
                    email['connection_timeout'] = connection_timeout  # pass connection timeout settings to worker
                    worker.send(**email)
                except WorkerInvalidEmail:
                    queue.discard(token, connection_timeout=connection_timeout)
                else:
                    queue.complete(token, connection_timeout=connection_timeout)

            else:
                queue.discard(token, connection_timeout=connection_timeout)

        except DistributedQueueEmpty:
            time.sleep(wait_on_empty)
        except Exception:
            # This should never happen, log the error and stop running so we can restart (let the exception bubble up)
            logger.exception('An exception occurred when processing emails')
            raise

        if terminate_after_one_iteration:
            break

@click.group()
def cli():
    pass

@cli.command()
@click.option('--redis-url', default=None, help='Redis cluster used to persist email queue.')
@click.option('--log', default=None, help='Path to log file')
@click.option('--verbose', default=False, is_flag=True)
@click.argument('backend')
@click.pass_context
def start(ctx, redis_url, log, verbose, backend):
    if redis_url is None:
        redis_url = 'redis://localhost:6379?db=0'

    if log is not None:
        handler = logging.FileHandler(log)
        handler.setLevel(logging.DEBUG)
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        handler.setFormatter(formatter)
        logger.addHandler(handler)
        logger.setLevel(logging.DEBUG)

    if verbose:
        handler = logging.StreamHandler(click.get_text_stream('stdout'))
        handler.setLevel(logging.DEBUG)
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        handler.setFormatter(formatter)
        logger.addHandler(handler)
        logger.setLevel(logging.DEBUG)

    worker = workers.get(backend, None)

    if worker is None:
        ctx.fail('Unknown backend: %s' % backend)

    click.echo('Starting worker using backend: %s' % backend)

    queue = DistributedQueue(redis_url)
    run(worker(), queue)

@cli.command()
def available():
    for key in workers.keys():
        click.echo(key)

if __name__ == '__main__':
    cli()


text:
:host {
    position: relative;
}
.l-chart-wrapper {
    color: #333;
    height: 100%;
    display: grid;
    position: relative;
    font-size: 13px;
    font-family: 'Open Sans', sans-serif;
    grid-template-columns: auto;
    grid-template-rows: 48px calc(100% - 48px);
}
.l-chart-title {
    display: flex;
    padding: 0px 15px;
    align-items: center;
    font-weight: 600;
    border: 1px solid #e5e8f0;
    justify-content: space-between;
    background-color: #f6f8fb;
}
.l-chart-list {
    /* overflow-y: auto; */
}


text:
namespace security::binexport {

class DumpWriter : public Writer {
 public:
  explicit DumpWriter(std::ostream& stream);
  explicit DumpWriter(const std::string& file_name);

  absl::Status Write(const CallGraph& call_graph, const FlowGraph& flow_graph,
                     const Instructions&, const AddressReferences&,
                     const AddressSpace&) override;

 private:
  std::ofstream file_;
  std::ostream& stream_;
};

}  // namespace security::binexport

#endif  // DUMP_WRITER_H_


text:
UPDATE pg_database SET datallowconn = TRUE WHERE datname = 'template0';

\c template0
UPDATE pg_database SET datistemplate = FALSE WHERE datname = 'template1';
DROP DATABASE template1;
CREATE DATABASE template1 WITH ENCODING = 'UTF-8' LC_CTYPE = 'en_US.utf8' LC_COLLATE = 'en_US.utf8' template = template0;
UPDATE pg_database SET datistemplate = TRUE WHERE datname = 'template1';

\c template1
UPDATE pg_database SET datallowconn = FALSE WHERE datname = 'template0';


text:
'use strict';

const Hoek = require('hoek');

const init = require('./init');
const read = require('./read');
const define = require('./define');
const sync = require('./sync');
const parseName = require('./parsename');

/**
 * Models loader

 * Execution process:

 *

 *   .load() :
 *      call read(): parse associates(references)/hooks of the models
 *      call define()
 *      create associates
 *   .sync() :
 *      if the files be modified
 *        create schemas
 *        beforeSync
 *        sync
 *        afterSync. alter table, insert, etc.
 *

 * @example
 * const Loader = require('sequelize-load');
 * const loader = new Loader(sequelize, syncInfoFile);
 * @example
 *
The model script:

 * module.exports = function(sequelize, Sequelize) {
 *   return {
 *     // can use 'schemaName.tableName'.
 *     // The . and \ in the name need to be escaped: '.' -> '\\.' , '\\' -> '\\\\'
 *     model1: {
 *       attributes: {
 *         colA: {
 *           // can reference itself. can use 'schemaName.tableName'.
 *           // if the col is non composite primaryKey/unique, call Model2.hasOne(Model1, {...})
 *           // otherwise call Model2.hasMany(Model1, {sourceKey: 'id'...})
 *           // sourceKey: defaults to the primary key of the Model2
 *           references: 'model2'|{model: 'model2', id: 'id'},
 *           onUpdate, onDelete...
 *         },...
 *       },
 *       options: {       // optional
 *         enableId: true // The default is false, the id created by the sequelize will be deleted
 *       },
 *       associates: [    // optional.
 *         { // associate options:
 *           // method:     'one'      | 'many'      | 'to'            | 'toMany'
 *           //     call    Ref.hasOne | Ref.hasMany | .belongsTo(Ref) | .belongsToMany(Ref)
 *           //
 *           // The function param options uses the following key value pair:
 *           // foreignKey: foreignKey | foreignKey  | foreignKey      | foreignKey
 *           // refKey:     not use    | sourceKey   | targetKey       | otherKey
 *           // Other options can be found in the sequelize document
 *           method: 'one|many|to|toMany',
 *           ref: 'refmodel',
 *           foreignKey: 'col1', // optional // alias: key
 *           refKey: 'refcol',   // optional
 *           ...
 *         },...
 *       ],
 *       // optional.
 *       // An empty string/array does not create a table,
 *       // otherwise the SQL statement is used instead of the Model.sync().
 *       sync: 'SQL'|['Create SQL'...],
 *       beforeSync: {   // optional
 *         '2010-1-1': ['SQL',function()...]       // execute if ver < '2010-1-1'
 *       },
 *       afterSync: {    // optional. ALTER TABLE / CREATE VIEW will be placed here
 *         '2010-1-1': ['ANY SQL',function()...]   // execute if ver < '2010-1-1'.
 *       }
 *     },
 *     'modelName2': {
 *       attributes: {colC...}
 *     }...
 *   };
 * };
 * @example
 *
The keys of beforeSync/afterSync is a date string: "YYYY-M-D[ h:m[:s]]".

 * '2017-10-1'
 * '2017-10-01 8:0:0'
 * '2017-10-01 08:0'
 * @example
 *
syncInfoFile - sync data:

 * {
 *     lastSync: 0,          // the last sync time
 *     syncVer: 0            // the last sync version
 * }
 * @constructor Loader
 * @param {object} sequelize - Instance of Sequelize
 * @param {string} syncInfoFile - DB sync information file.
 */
module.exports = function loader(sequelize, syncInfoFile) {
    //Hoek.assert(sequelize && sequelize instanceof Sequelize, 'Invalid sequelize: must be an instance of Sequelize');
    Hoek.assert(syncInfoFile, 'Invalid sync data file');

    if (!(this instanceof loader)) return new loader(sequelize, syncInfoFile);

    var data = init({ sequelize, syncInfoFile, instance: this });

    /**
     * The instance of Sequelize
     * @member {object} Loader#sequelize
     * @readonly
     */
    this.__defineGetter__('sequelize', () => sequelize);

    /**
     * sequelize.query
     * @method Loader#query
     * @param {string} sql - The model names.
     * @param {object} [options] - Query options.
     * @returns {Promise}
     */
    this.query = function () {
        return sequelize.query.apply(sequelize, arguments);
    };

    /**
     * read the model files, parse references/hooks of the models
     * @method Loader#read
     * @param {...(string|array)} filepath - The file path of the model script
     * @returns {object} this - loader
     * @example
     * loader.read('foo', glob.sync('**.js'));
     */
    this.read = function () {
        Array.prototype.slice.apply(arguments)
            .reduce((cur, next) => cur.concat(Array.isArray(next) ? next : [next]), [])
            .map((file) => read(data, file));
        return this;
    };

    /**
     * read the model files, create associates of the models
     * @method Loader#load
     * @param {...(string|array)} [filepath] - The file path of the model script
     * @returns {object} this - loader
     * @example
     * loader.read('foo', glob.sync('**.js'));
     * loader.load();
     */
    this.load = function () {
        this.read.apply(this, arguments);
        for (let name in data.defines) {
            define(data, name);
        }
        return this;
    };

    /**
     * get the models
     * @method Loader#getModels
     * @param {...(string)} modelname - The model names.
     * @returns {object|array} Models
     * @example
     * loader.load('foo', glob.sync('**.js'))
     * const Groups = loader.getModels('groups');
     * @example
     * loader.load('foo', glob.sync('**.js'))
     * const dbs = loader.getModels('public.Users', 'HR.Dept', 'HR.Emp');
     * // dbs[0] == dbs['public.Users'] == dbs['"public"."Users"']
     * // dbs[1] == dbs['HR.Dept'] == dbs['"HR"."Dept"']
     * // dbs[2] == dbs['HR.Emp'] == dbs['"HR"."Emp"']
     *
     * // or
     * const [Users, Dept, Emp] = loader.getModels('public.Users', 'HR.Dept', 'HR.Emp');
     */
    this.getModels = function () {
        var m = [];
        Array.prototype.slice.apply(arguments).map((name0) => {
            var name = parseName(data.useSchema, name0).name;
            if (!data.models[name]) {
                define(data, name);
            }
            m.push(data.models[name]);
            m[name] = m[name0] = data.models[name];
        });
        return m.length == 1 ? m[0] : m;
    };

    /**
     * try sync.

     * It will call sync when the model's modification time is later than the sync time.
     * @method Loader#sync
     * @returns {Promise}
     * @example
     * loader.load('foo', glob.sync('**.js'))
     *     .sync().then(...);
     */
    this.sync = function () {
        return sync(data);
    };
};


text:
package pt.trycatch.javax.sound.midi;

/**
 * A MidiDeviceProvider is a factory or provider for a particular
 * type of MIDI device.
 * This mechanism allows the implementation to determine
 * how resources are managed in the creation and management of
 * a device.
 *
 * @author Kara Kytle
 */
public abstract class MidiDeviceProvider {

    /**
     * Indicates whether the device provider supports the device represented by
     * the specified device info object.
     * @param info an info object that describes the device for which support is queried
     * @return true if the specified device is supported,
     * otherwise false
     */
    public boolean isDeviceSupported(MidiDevice.Info info) {

        MidiDevice.Info infos[] = getDeviceInfo();

        for(int i=0; i<infos.length; i++) {
            if( info.equals( infos[i] ) ) {
                return true;
            }
        }
        return false;
    }

    /**
     * Obtains the set of info objects representing the device
     * or devices provided by this MidiDeviceProvider.
     * @return set of device info objects
     */
    public abstract MidiDevice.Info[] getDeviceInfo();

    /**
     * Obtains an instance of the device represented by the info object.
     * @param info an info object that describes the desired device
     * @return device instance
     * @throws IllegalArgumentException if the info object specified does not
     * match the info object for a device supported by this MidiDeviceProvider.
     */
    public abstract MidiDevice getDevice(MidiDevice.Info info);
}


text:
- add conference posters to the Presentations page
- add socialpros logo (maybe others?) to the Design page
- publish post on logo design