text:
"""The tests for the hassio update entities."""

import os
from unittest.mock import patch

import pytest

from homeassistant.components.hassio import DOMAIN
from homeassistant.components.hassio.handler import HassioAPIError
from homeassistant.exceptions import HomeAssistantError
from homeassistant.setup import async_setup_component

from tests.common import MockConfigEntry

MOCK_ENVIRON = {"SUPERVISOR": "127.0.0.1", "SUPERVISOR_TOKEN": "abcdefgh"}

@pytest.fixture(autouse=True)
def mock_all(aioclient_mock, request):
    """Mock all setup requests."""
    aioclient_mock.post("http://127.0.0.1/homeassistant/options", json={"result": "ok"})
    aioclient_mock.get("http://127.0.0.1/supervisor/ping", json={"result": "ok"})
    aioclient_mock.post("http://127.0.0.1/supervisor/options", json={"result": "ok"})
    aioclient_mock.get(
        "http://127.0.0.1/info",
        json={
            "result": "ok",
            "data": {
                "supervisor": "222",
                "homeassistant": "0.110.0",
                "hassos": "1.2.3",
            },
        },
    )
    aioclient_mock.get(
        "http://127.0.0.1/store",
        json={
            "result": "ok",
            "data": {"addons": [], "repositories": []},
        },
    )
    aioclient_mock.get(
        "http://127.0.0.1/host/info",
        json={
            "result": "ok",
            "data": {
                "result": "ok",
                "data": {
                    "chassis": "vm",
                    "operating_system": "Debian GNU/Linux 10 (buster)",
                    "kernel": "4.19.0-6-amd64",
                },
            },
        },
    )
    aioclient_mock.get(
        "http://127.0.0.1/core/info",
        json={
            "result": "ok",
            "data": {"version_latest": "1.0.0dev222", "version": "1.0.0dev221"},
        },
    )
    aioclient_mock.get(
        "http://127.0.0.1/os/info",
        json={
            "result": "ok",
            "data": {
                "version_latest": "1.0.0dev2222",
                "version": "1.0.0dev2221",
                "update_available": False,
            },
        },
    )
    aioclient_mock.get(
        "http://127.0.0.1/supervisor/info",
        json={
            "result": "ok",
            "data": {
                "result": "ok",
                "version": "1.0.0",
                "version_latest": "1.0.1dev222",
                "addons": [
                    {
                        "name": "test",
                        "state": "started",
                        "slug": "test",
                        "installed": True,
                        "update_available": True,
                        "icon": False,
                        "version": "2.0.0",
                        "version_latest": "2.0.1",
                        "repository": "core",
                        "url": "https://github.com/home-assistant/addons/test",
                    },
                    {
                        "name": "test2",
                        "state": "stopped",
                        "slug": "test2",
                        "installed": True,
                        "update_available": False,
                        "icon": True,
                        "version": "3.1.0",
                        "version_latest": "3.1.0",
                        "repository": "core",
                        "url": "https://github.com",
                    },
                ],
            },
        },
    )
    aioclient_mock.get(
        "http://127.0.0.1/addons/test/stats",
        json={
            "result": "ok",
            "data": {
                "cpu_percent": 0.99,
                "memory_usage": 182611968,
                "memory_limit": 3977146368,
                "memory_percent": 4.59,
                "network_rx": 362570232,
                "network_tx": 82374138,
                "blk_read": 46010945536,
                "blk_write": 15051526144,
            },
        },
    )
    aioclient_mock.get("http://127.0.0.1/addons/test/changelog", text="")
    aioclient_mock.get(
        "http://127.0.0.1/addons/test/info",
        json={"result": "ok", "data": {"auto_update": True}},
    )
    aioclient_mock.get("http://127.0.0.1/addons/test2/changelog", text="")
    aioclient_mock.get(
        "http://127.0.0.1/addons/test2/info",
        json={"result": "ok", "data": {"auto_update": False}},
    )
    aioclient_mock.get(
        "http://127.0.0.1/ingress/panels", json={"result": "ok", "data": {"panels": {}}}
    )
    aioclient_mock.post("http://127.0.0.1/refresh_updates", json={"result": "ok"})

@pytest.mark.parametrize(
    "entity_id,expected_state, auto_update",
    [
        ("update.home_assistant_operating_system_update", "on", False),
        ("update.home_assistant_supervisor_update", "on", True),
        ("update.home_assistant_core_update", "on", False),
        ("update.test_update", "on", True),
        ("update.test2_update", "off", False),
    ],
)
async def test_update_entities(
    hass,
    entity_id,
    expected_state,
    auto_update,
    aioclient_mock,
):
    """Test update entities."""
    config_entry = MockConfigEntry(domain=DOMAIN, data={}, unique_id=DOMAIN)
    config_entry.add_to_hass(hass)

    with patch.dict(os.environ, MOCK_ENVIRON):
        result = await async_setup_component(
            hass,
            "hassio",
            {"http": {"server_port": 9999, "server_host": "127.0.0.1"}, "hassio": {}},
        )
        assert result
    await hass.async_block_till_done()

    # Verify that the entity have the expected state.
    state = hass.states.get(entity_id)
    assert state.state == expected_state

    # Verify that the auto_update attribute is correct
    assert state.attributes["auto_update"] is auto_update

async def test_update_addon(hass, aioclient_mock):
    """Test updating addon update entity."""
    config_entry = MockConfigEntry(domain=DOMAIN, data={}, unique_id=DOMAIN)
    config_entry.add_to_hass(hass)

    with patch.dict(os.environ, MOCK_ENVIRON):
        result = await async_setup_component(
            hass,
            "hassio",
            {"http": {"server_port": 9999, "server_host": "127.0.0.1"}, "hassio": {}},
        )
        assert result
    await hass.async_block_till_done()

    aioclient_mock.post(
        "http://127.0.0.1/addons/test/update",
        json={"result": "ok", "data": {}},
    )

    assert await hass.services.async_call(
        "update",
        "install",
        {"entity_id": "update.test_update"},
        blocking=True,
    )

async def test_update_os(hass, aioclient_mock):
    """Test updating OS update entity."""
    config_entry = MockConfigEntry(domain=DOMAIN, data={}, unique_id=DOMAIN)
    config_entry.add_to_hass(hass)

    with patch.dict(os.environ, MOCK_ENVIRON):
        result = await async_setup_component(
            hass,
            "hassio",
            {"http": {"server_port": 9999, "server_host": "127.0.0.1"}, "hassio": {}},
        )
        assert result
    await hass.async_block_till_done()

    aioclient_mock.post(
        "http://127.0.0.1/os/update",
        json={"result": "ok", "data": {}},
    )

    assert await hass.services.async_call(
        "update",
        "install",
        {"entity_id": "update.home_assistant_operating_system_update"},
        blocking=True,
    )

async def test_update_core(hass, aioclient_mock):
    """Test updating core update entity."""
    config_entry = MockConfigEntry(domain=DOMAIN, data={}, unique_id=DOMAIN)
    config_entry.add_to_hass(hass)

    with patch.dict(os.environ, MOCK_ENVIRON):
        result = await async_setup_component(
            hass,
            "hassio",
            {"http": {"server_port": 9999, "server_host": "127.0.0.1"}, "hassio": {}},
        )
        assert result
    await hass.async_block_till_done()

    aioclient_mock.post(
        "http://127.0.0.1/core/update",
        json={"result": "ok", "data": {}},
    )

    assert await hass.services.async_call(
        "update",
        "install",
        {"entity_id": "update.home_assistant_os_update"},
        blocking=True,
    )

async def test_update_supervisor(hass, aioclient_mock):
    """Test updating supervisor update entity."""
    config_entry = MockConfigEntry(domain=DOMAIN, data={}, unique_id=DOMAIN)
    config_entry.add_to_hass(hass)

    with patch.dict(os.environ, MOCK_ENVIRON):
        result = await async_setup_component(
            hass,
            "hassio",
            {"http": {"server_port": 9999, "server_host": "127.0.0.1"}, "hassio": {}},
        )
        assert result
    await hass.async_block_till_done()

    aioclient_mock.post(
        "http://127.0.0.1/supervisor/update",
        json={"result": "ok", "data": {}},
    )

    assert await hass.services.async_call(
        "update",
        "install",
        {"entity_id": "update.home_assistant_supervisor_update"},
        blocking=True,
    )

async def test_update_addon_with_error(hass, aioclient_mock):
    """Test updating addon update entity with error."""
    config_entry = MockConfigEntry(domain=DOMAIN, data={}, unique_id=DOMAIN)
    config_entry.add_to_hass(hass)

    with patch.dict(os.environ, MOCK_ENVIRON):
        assert await async_setup_component(
            hass,
            "hassio",
            {"http": {"server_port": 9999, "server_host": "127.0.0.1"}, "hassio": {}},
        )
    await hass.async_block_till_done()

    aioclient_mock.post(
        "http://127.0.0.1/addons/test/update",
        exc=HassioAPIError,
    )

    with pytest.raises(HomeAssistantError):
        assert not await hass.services.async_call(
            "update",
            "install",
            {"entity_id": "update.test_update"},
            blocking=True,
        )

async def test_update_os_with_error(hass, aioclient_mock):
    """Test updating OS update entity with error."""
    config_entry = MockConfigEntry(domain=DOMAIN, data={}, unique_id=DOMAIN)
    config_entry.add_to_hass(hass)

    with patch.dict(os.environ, MOCK_ENVIRON):
        assert await async_setup_component(
            hass,
            "hassio",
            {"http": {"server_port": 9999, "server_host": "127.0.0.1"}, "hassio": {}},
        )
    await hass.async_block_till_done()

    aioclient_mock.post(
        "http://127.0.0.1/os/update",
        exc=HassioAPIError,
    )

    with pytest.raises(HomeAssistantError):
        assert not await hass.services.async_call(
            "update",
            "install",
            {"entity_id": "update.home_assistant_operating_system_update"},
            blocking=True,
        )

async def test_update_supervisor_with_error(hass, aioclient_mock):
    """Test updating supervisor update entity with error."""
    config_entry = MockConfigEntry(domain=DOMAIN, data={}, unique_id=DOMAIN)
    config_entry.add_to_hass(hass)

    with patch.dict(os.environ, MOCK_ENVIRON):
        assert await async_setup_component(
            hass,
            "hassio",
            {"http": {"server_port": 9999, "server_host": "127.0.0.1"}, "hassio": {}},
        )
    await hass.async_block_till_done()

    aioclient_mock.post(
        "http://127.0.0.1/supervisor/update",
        exc=HassioAPIError,
    )

    with pytest.raises(HomeAssistantError):
        assert not await hass.services.async_call(
            "update",
            "install",
            {"entity_id": "update.home_assistant_supervisor_update"},
            blocking=True,
        )

async def test_update_core_with_error(hass, aioclient_mock):
    """Test updating core update entity with error."""
    config_entry = MockConfigEntry(domain=DOMAIN, data={}, unique_id=DOMAIN)
    config_entry.add_to_hass(hass)

    with patch.dict(os.environ, MOCK_ENVIRON):
        assert await async_setup_component(
            hass,
            "hassio",
            {"http": {"server_port": 9999, "server_host": "127.0.0.1"}, "hassio": {}},
        )
    await hass.async_block_till_done()

    aioclient_mock.post(
        "http://127.0.0.1/core/update",
        exc=HassioAPIError,
    )

    with pytest.raises(HomeAssistantError):
        assert not await hass.services.async_call(
            "update",
            "install",
            {"entity_id": "update.home_assistant_core_update"},
            blocking=True,
        )

async def test_release_notes_between_versions(hass, aioclient_mock, hass_ws_client):
    """Test release notes between versions."""
    config_entry = MockConfigEntry(domain=DOMAIN, data={}, unique_id=DOMAIN)
    config_entry.add_to_hass(hass)

    with patch.dict(os.environ, MOCK_ENVIRON), patch(
        "homeassistant.components.hassio.get_addons_changelogs",
        return_value={"test": "# 2.0.1\nNew updates\n# 2.0.0\nOld updates"},
    ):
        result = await async_setup_component(
            hass,
            "hassio",
            {"http": {"server_port": 9999, "server_host": "127.0.0.1"}, "hassio": {}},
        )
        assert result
    await hass.async_block_till_done()

    client = await hass_ws_client(hass)
    await hass.async_block_till_done()

    await client.send_json(
        {
            "id": 1,
            "type": "update/release_notes",
            "entity_id": "update.test_update",
        }
    )
    result = await client.receive_json()
    assert "Old updates" not in result["result"]
    assert "New updates" in result["result"]

async def test_release_notes_full(hass, aioclient_mock, hass_ws_client):
    """Test release notes no match."""
    config_entry = MockConfigEntry(domain=DOMAIN, data={}, unique_id=DOMAIN)
    config_entry.add_to_hass(hass)

    with patch.dict(os.environ, MOCK_ENVIRON), patch(
        "homeassistant.components.hassio.get_addons_changelogs",
        return_value={"test": "# 2.0.0\nNew updates\n# 2.0.0\nOld updates"},
    ):
        result = await async_setup_component(
            hass,
            "hassio",
            {"http": {"server_port": 9999, "server_host": "127.0.0.1"}, "hassio": {}},
        )
        assert result
    await hass.async_block_till_done()

    client = await hass_ws_client(hass)
    await hass.async_block_till_done()

    await client.send_json(
        {
            "id": 1,
            "type": "update/release_notes",
            "entity_id": "update.test_update",
        }
    )
    result = await client.receive_json()
    assert "Old updates" in result["result"]
    assert "New updates" in result["result"]

async def test_not_release_notes(hass, aioclient_mock, hass_ws_client):
    """Test handling where there are no release notes."""
    config_entry = MockConfigEntry(domain=DOMAIN, data={}, unique_id=DOMAIN)
    config_entry.add_to_hass(hass)

    with patch.dict(os.environ, MOCK_ENVIRON), patch(
        "homeassistant.components.hassio.get_addons_changelogs",
        return_value={"test": None},
    ):
        result = await async_setup_component(
            hass,
            "hassio",
            {"http": {"server_port": 9999, "server_host": "127.0.0.1"}, "hassio": {}},
        )
        assert result
    await hass.async_block_till_done()

    client = await hass_ws_client(hass)
    await hass.async_block_till_done()

    await client.send_json(
        {
            "id": 1,
            "type": "update/release_notes",
            "entity_id": "update.test_update",
        }
    )
    result = await client.receive_json()
    assert result["result"] is None

async def test_no_os_entity(hass):
    """Test handling where there is no os entity."""
    with patch.dict(os.environ, MOCK_ENVIRON), patch(
        "homeassistant.components.hassio.HassIO.get_info",
        return_value={
            "supervisor": "222",
            "homeassistant": "0.110.0",
            "hassos": None,
        },
    ):
        result = await async_setup_component(
            hass,
            "hassio",
            {"http": {"server_port": 9999, "server_host": "127.0.0.1"}, "hassio": {}},
        )
        assert result
    await hass.async_block_till_done()

    # Verify that the entity does not exist
    assert not hass.states.get("update.home_assistant_operating_system_update")

async def test_setting_up_core_update_when_addon_fails(hass, caplog):
    """Test setting up core update when single addon fails."""
    with patch.dict(os.environ, MOCK_ENVIRON), patch(
        "homeassistant.components.hassio.HassIO.get_addon_stats",
        side_effect=HassioAPIError("add-on is not running"),
    ), patch(
        "homeassistant.components.hassio.HassIO.get_addon_changelog",
        side_effect=HassioAPIError("add-on is not running"),
    ), patch(
        "homeassistant.components.hassio.HassIO.get_addon_info",
        side_effect=HassioAPIError("add-on is not running"),
    ):
        result = await async_setup_component(
            hass,
            "hassio",
            {"http": {"server_port": 9999, "server_host": "127.0.0.1"}, "hassio": {}},
        )
        assert result
    await hass.async_block_till_done()

    # Verify that the core update entity does exist
    state = hass.states.get("update.home_assistant_core_update")
    assert state
    assert state.state == "on"
    assert "Could not fetch stats for test: add-on is not running" in caplog.text


text:
package org.elasticsearch.search;

import org.apache.lucene.index.BinaryDocValues;
import org.apache.lucene.index.SortedDocValues;
import org.apache.lucene.index.SortedNumericDocValues;
import org.apache.lucene.index.SortedSetDocValues;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefBuilder;
import org.elasticsearch.index.fielddata.SortedBinaryDocValues;
import org.elasticsearch.index.fielddata.SortedNumericDoubleValues;

import java.io.IOException;
import java.util.Locale;

/**
 * Defines what values to pick in the case a document contains multiple values for a particular field.
 */
public enum MultiValueMode {
    /**
     * Pick the sum of all the values.
     */
    SUM {
        @Override
        protected long pick(SortedNumericDocValues values) throws IOException {
            final int count = values.docValueCount();
            long total = 0;
            for (int index = 0; index < count; ++index) {
                total += values.nextValue();
            }
            return total;
        }

        @Override
        protected long pick(SortedNumericDocValues values, long missingValue, DocIdSetIterator docItr, int startDoc, int endDoc, int maxChildren) throws IOException {
            int totalCount = 0;
            long totalValue = 0;
            int count = 0;
            for (int doc = startDoc; doc < endDoc; doc = docItr.nextDoc()) {
                if (values.advanceExact(doc)) {
                    if (++count > maxChildren) {
                        break;
                    }

                    final int docCount = values.docValueCount();
                    for (int index = 0; index < docCount; ++index) {
                        totalValue += values.nextValue();
                    }
                    totalCount += docCount;
                }
            }
            return totalCount > 0 ? totalValue : missingValue;
        }

        @Override
        protected double pick(SortedNumericDoubleValues values) throws IOException {
            final int count = values.docValueCount();
            double total = 0;
            for (int index = 0; index < count; ++index) {
                total += values.nextValue();
            }
            return total;
        }

        @Override
        protected double pick(SortedNumericDoubleValues values, double missingValue, DocIdSetIterator docItr, int startDoc, int endDoc, int maxChildren) throws IOException {
            int totalCount = 0;
            double totalValue = 0;
            int count = 0;
            for (int doc = startDoc; doc < endDoc; doc = docItr.nextDoc()) {
                if (values.advanceExact(doc)) {
                    if (++count > maxChildren) {
                        break;
                    }
                    final int docCount = values.docValueCount();
                    for (int index = 0; index < docCount; ++index) {
                        totalValue += values.nextValue();
                    }
                    totalCount += docCount;
                }
            }

            return totalCount > 0 ? totalValue : missingValue;
        }
    },

    /**
     * Pick the average of all the values.
     */
    AVG {
        @Override
        protected long pick(SortedNumericDocValues values) throws IOException {
            final int count = values.docValueCount();
            long total = 0;
            for (int index = 0; index < count; ++index) {
                total += values.nextValue();
            }
            return count > 1 ? Math.round((double) total / (double) count) : total;
        }

        @Override
        protected long pick(SortedNumericDocValues values, long missingValue, DocIdSetIterator docItr, int startDoc, int endDoc, int maxChildren) throws IOException {
            int totalCount = 0;
            long totalValue = 0;
            int count = 0;
            for (int doc = startDoc; doc < endDoc; doc = docItr.nextDoc()) {
                if (values.advanceExact(doc)) {
                    if (++count > maxChildren) {
                        break;
                    }
                    final int docCount = values.docValueCount();
                    for (int index = 0; index < docCount; ++index) {
                        totalValue += values.nextValue();
                    }
                    totalCount += docCount;
                }
            }
            if (totalCount < 1) {
                return missingValue;
            }
            return totalCount > 1 ? Math.round((double) totalValue / (double) totalCount) : totalValue;
        }

        @Override
        protected double pick(SortedNumericDoubleValues values) throws IOException {
            final int count = values.docValueCount();
            double total = 0;
            for (int index = 0; index < count; ++index) {
                total += values.nextValue();
            }
            return total / count;
        }

        @Override
        protected double pick(SortedNumericDoubleValues values, double missingValue, DocIdSetIterator docItr, int startDoc, int endDoc, int maxChildren) throws IOException {
            int totalCount = 0;
            double totalValue = 0;
            int count = 0;
            for (int doc = startDoc; doc < endDoc; doc = docItr.nextDoc()) {
                if (values.advanceExact(doc)) {
                    if (++count > maxChildren) {
                        break;
                    }
                    final int docCount = values.docValueCount();
                    for (int index = 0; index < docCount; ++index) {
                        totalValue += values.nextValue();
                    }
                    totalCount += docCount;
                }
            }
            if (totalCount < 1) {
                return missingValue;
            }
            return totalValue / totalCount;
        }
    },

    /**
     * Pick the median of the values.
     */
    MEDIAN {
        @Override
        protected long pick(SortedNumericDocValues values) throws IOException {
            int count = values.docValueCount();
            for (int i = 0; i < (count - 1) / 2; ++i) {
                values.nextValue();
            }
            if (count % 2 == 0) {
                return Math.round(((double) values.nextValue() + values.nextValue()) / 2);
            } else {
                return values.nextValue();
            }
        }

        @Override
        protected double pick(SortedNumericDoubleValues values) throws IOException {
            int count = values.docValueCount();
            for (int i = 0; i < (count - 1) / 2; ++i) {
                values.nextValue();
            }
            if (count % 2 == 0) {
                return (values.nextValue() + values.nextValue()) / 2;
            } else {
                return values.nextValue();
            }
        }
    },

    /**
     * Pick the lowest value.
     */
    MIN {
        @Override
        protected long pick(SortedNumericDocValues values) throws IOException {
            return values.nextValue();
        }

        @Override
        protected long pick(SortedNumericDocValues values, long missingValue, DocIdSetIterator docItr, int startDoc, int endDoc, int maxChildren) throws IOException {
            boolean hasValue = false;
            long minValue = Long.MAX_VALUE;
            int count = 0;
            for (int doc = startDoc; doc < endDoc; doc = docItr.nextDoc()) {
                if (values.advanceExact(doc)) {
                    if (++count > maxChildren) {
                        break;
                    }
                    minValue = Math.min(minValue, values.nextValue());
                    hasValue = true;
                }
            }
            return hasValue ? minValue : missingValue;
        }

        @Override
        protected double pick(SortedNumericDoubleValues values) throws IOException {
            return values.nextValue();
        }

        @Override
        protected double pick(SortedNumericDoubleValues values, double missingValue, DocIdSetIterator docItr, int startDoc, int endDoc, int maxChildren) throws IOException {
            boolean hasValue = false;
            double minValue = Double.POSITIVE_INFINITY;
            int count = 0;
            for (int doc = startDoc; doc < endDoc; doc = docItr.nextDoc()) {
                if (values.advanceExact(doc)) {
                    if (++count > maxChildren) {
                        break;
                    }
                    minValue = Math.min(minValue, values.nextValue());
                    hasValue = true;
                }
            }
            return hasValue ? minValue : missingValue;
        }

        @Override
        protected BytesRef pick(SortedBinaryDocValues values) throws IOException {
            return values.nextValue();
        }

        @Override
        protected BytesRef pick(BinaryDocValues values, BytesRefBuilder builder, DocIdSetIterator docItr, int startDoc, int endDoc, int maxChildren) throws IOException {
            BytesRefBuilder bytesRefBuilder = null;
            int count = 0;
            for (int doc = startDoc; doc < endDoc; doc = docItr.nextDoc()) {
                if (values.advanceExact(doc)) {
                    if (++count > maxChildren) {
                        break;
                    }
                    final BytesRef innerValue = values.binaryValue();
                    if (bytesRefBuilder == null) {
                        builder.copyBytes(innerValue);
                        bytesRefBuilder = builder;
                    } else {
                        final BytesRef min = bytesRefBuilder.get().compareTo(innerValue) <= 0 ? bytesRefBuilder.get() : innerValue;
                        if (min == innerValue) {
                            bytesRefBuilder.copyBytes(min);
                        }
                    }
                }
            }
            return bytesRefBuilder == null ? null : bytesRefBuilder.get();
        }

        @Override
        protected int pick(SortedSetDocValues values) throws IOException {
            return Math.toIntExact(values.nextOrd());
        }

        @Override
        protected int pick(SortedDocValues values, DocIdSetIterator docItr, int startDoc, int endDoc, int maxChildren) throws IOException {
            int ord = Integer.MAX_VALUE;
            boolean hasValue = false;
            int count = 0;
            for (int doc = startDoc; doc < endDoc; doc = docItr.nextDoc()) {
                if (values.advanceExact(doc)) {
                    if (++count > maxChildren) {
                        break;
                    }
                    final int innerOrd = values.ordValue();
                    ord = Math.min(ord, innerOrd);
                    hasValue = true;
                }
            }

            return hasValue ? ord : -1;
        }
    },

    /**
     * Pick the highest value.
     */
    MAX {
        @Override
        protected long pick(SortedNumericDocValues values) throws IOException {
            final int count = values.docValueCount();
            for (int i = 0; i < count - 1; ++i) {
                values.nextValue();
            }
            return values.nextValue();
        }

        @Override
        protected long pick(SortedNumericDocValues values, long missingValue, DocIdSetIterator docItr, int startDoc, int endDoc, int maxChildren) throws IOException {
            boolean hasValue = false;
            long maxValue = Long.MIN_VALUE;
            int count = 0;
            for (int doc = startDoc; doc < endDoc; doc = docItr.nextDoc()) {
                if (values.advanceExact(doc)) {
                    if (++count > maxChildren) {
                        break;
                    }
                    final int docCount = values.docValueCount();
                    for (int i = 0; i < docCount - 1; ++i) {
                        values.nextValue();
                    }
                    maxValue = Math.max(maxValue, values.nextValue());
                    hasValue = true;
                }
            }
            return hasValue ? maxValue : missingValue;
        }

        @Override
        protected double pick(SortedNumericDoubleValues values) throws IOException {
            final int count = values.docValueCount();
            for (int i = 0; i < count - 1; ++i) {
                values.nextValue();
            }
            return values.nextValue();
        }

        @Override
        protected double pick(SortedNumericDoubleValues values, double missingValue, DocIdSetIterator docItr, int startDoc, int endDoc, int maxChildren) throws IOException {
            boolean hasValue = false;
            double maxValue = Double.NEGATIVE_INFINITY;
            int count = 0;
            for (int doc = startDoc; doc < endDoc; doc = docItr.nextDoc()) {
                if (values.advanceExact(doc)) {
                    if (++count > maxChildren) {
                        break;
                    }
                    final int docCount = values.docValueCount();
                    for (int i = 0; i < docCount - 1; ++i) {
                        values.nextValue();
                    }
                    maxValue = Math.max(maxValue, values.nextValue());
                    hasValue = true;
                }
            }
            return hasValue ? maxValue : missingValue;
        }

        @Override
        protected BytesRef pick(SortedBinaryDocValues values) throws IOException {
            int count = values.docValueCount();
            for (int i = 0; i < count - 1; ++i) {
                values.nextValue();
            }
            return values.nextValue();
        }

        @Override
        protected BytesRef pick(BinaryDocValues values, BytesRefBuilder builder, DocIdSetIterator docItr, int startDoc, int endDoc, int maxChildren) throws IOException {
            BytesRefBuilder bytesRefBuilder = null;
            int count = 0;
            for (int doc = startDoc; doc < endDoc; doc = docItr.nextDoc()) {
                if (values.advanceExact(doc)) {
                    if (++count > maxChildren) {
                        break;
                    }
                    final BytesRef innerValue = values.binaryValue();
                    if (bytesRefBuilder == null) {
                        builder.copyBytes(innerValue);
                        bytesRefBuilder = builder;
                    } else {
                        final BytesRef max = bytesRefBuilder.get().compareTo(innerValue) > 0 ? bytesRefBuilder.get() : innerValue;
                        if (max == innerValue) {
                            bytesRefBuilder.copyBytes(max);
                        }
                    }
                }
            }
            return bytesRefBuilder == null ? null : bytesRefBuilder.get();
        }

        @Override
        protected int pick(SortedSetDocValues values) throws IOException {
            long maxOrd = -1;
            for (int i = 0; i < values.docValueCount(); i++) {
                maxOrd = values.nextOrd();
            }
            return Math.toIntExact(maxOrd);
        }

        @Override
        protected int pick(SortedDocValues values, DocIdSetIterator docItr, int startDoc, int endDoc, int maxChildren) throws IOException {
            int ord = -1;
            int count = 0;
            for (int doc = startDoc; doc < endDoc; doc = docItr.nextDoc()) {
                if (values.advanceExact(doc)) {
                    if (++count > maxChildren) {
                        break;
                    }
                    ord = Math.max(ord, values.ordValue());
                }
            }
            return ord;
        }
    };

    /**
     * A case insensitive version of {@link #valueOf(String)}
     *
     * @throws IllegalArgumentException if the given string doesn't match a sort mode or is null.
     */
    public static MultiValueMode fromString(String sortMode) {
        try {
            return valueOf(sortMode.toUpperCase(Locale.ROOT));
        } catch (Exception e) {
            throw new IllegalArgumentException("Illegal sort mode: " + sortMode);
        }
    }

    protected long pick(SortedNumericDocValues values) throws IOException {
        throw new IllegalArgumentException("Unsupported sort mode: " + this);
    }

    protected long pick(SortedNumericDocValues values, long missingValue, DocIdSetIterator docItr, int startDoc, int endDoc, int maxChildren) throws IOException {
        throw new IllegalArgumentException("Unsupported sort mode: " + this);
    }

    protected double pick(SortedNumericDoubleValues values) throws IOException {
        throw new IllegalArgumentException("Unsupported sort mode: " + this);
    }

    protected double pick(SortedNumericDoubleValues values, double missingValue, DocIdSetIterator docItr, int startDoc, int endDoc, int maxChildren) throws IOException {
        throw new IllegalArgumentException("Unsupported sort mode: " + this);
    }

    protected BytesRef pick(SortedBinaryDocValues values) throws IOException {
        throw new IllegalArgumentException("Unsupported sort mode: " + this);
    }

    protected BytesRef pick(BinaryDocValues values, BytesRefBuilder builder, DocIdSetIterator docItr, int startDoc, int endDoc, int maxChildren) throws IOException {
        throw new IllegalArgumentException("Unsupported sort mode: " + this);
    }

    protected int pick(SortedSetDocValues values) throws IOException {
        throw new IllegalArgumentException("Unsupported sort mode: " + this);
    }

    protected int pick(SortedDocValues values, DocIdSetIterator docItr, int startDoc, int endDoc, int maxChildren) throws IOException {
        throw new IllegalArgumentException("Unsupported sort mode: " + this);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<map>
  <entry>
    <string>plugin_status</string>
    <string>down. Waiting for publisher</string>
  </entry>
  <entry>
    <string>plugin_identifier</string>
    <string>org.lockss.plugin.ingenta.ClockssIngentaBooksPlugin</string>
  </entry>
  <entry>
    <string>plugin_version</string>
    <string>2</string>
  </entry>
  <entry>
    <string>plugin_parent</string>
    <string>org.lockss.plugin.ingenta.IngentaBooksPlugin</string>
  </entry>
   <entry>
    <string>plugin_parent_version</string>
    <string>2</string>
  </entry>
  <entry>
    <string>au_name</string>
    <string>"Ingenta Books Plugin (CLOCKSS), Base URL %s, Publisher ID %s, Book ISBN %s", base_url, publisher_id, book_isbn</string>
  </entry>
  <entry>
    <string>plugin_name</string>
    <string>Ingenta Books Plugin (CLOCKSS)</string>
  </entry>
  <entry>
    <string>au_start_url</string>
    <list>
      <string>"%scontent/%s?format=clockss", base_url, book_isbn</string>
    </list>
  </entry>
  <entry>
    <string>clockss_override</string>
    <map>
      <entry>
        <string>au_def_pause_time</string>
        <long>100</long>
      </entry>
    </map>
  </entry>
</map>


text:
namespace boost {
namespace asio {
namespace detail {

template <typename Handler, typename Executor, typename = void>
struct is_work_dispatcher_required : true_type
{
};

template <typename Handler, typename Executor>
struct is_work_dispatcher_required<Handler, Executor,
    typename enable_if<
      is_same<
        typename associated_executor<Handler,
          Executor>::asio_associated_executor_is_unspecialised,
        void
      >::value
    >::type> : false_type
{
};

template <typename Handler, typename Executor, typename = void>
class work_dispatcher
{
public:
  template <typename CompletionHandler>
  work_dispatcher(BOOST_ASIO_MOVE_ARG(CompletionHandler) handler,
      const Executor& handler_ex)
    : handler_(BOOST_ASIO_MOVE_CAST(CompletionHandler)(handler)),
      executor_(boost::asio::prefer(handler_ex,
          execution::outstanding_work.tracked))
  {
  }

#if defined(BOOST_ASIO_HAS_MOVE)
  work_dispatcher(const work_dispatcher& other)
    : handler_(other.handler_),
      executor_(other.executor_)
  {
  }

  work_dispatcher(work_dispatcher&& other)
    : handler_(BOOST_ASIO_MOVE_CAST(Handler)(other.handler_)),
      executor_(BOOST_ASIO_MOVE_CAST(work_executor_type)(other.executor_))
  {
  }
#endif // defined(BOOST_ASIO_HAS_MOVE)

  void operator()()
  {
    execution::execute(
        boost::asio::prefer(executor_,
          execution::blocking.possibly,
          execution::allocator((get_associated_allocator)(handler_))),
        BOOST_ASIO_MOVE_CAST(Handler)(handler_));
  }

private:
  typedef typename decay<
      typename prefer_result<const Executor&,
        execution::outstanding_work_t::tracked_t
      >::type
    >::type work_executor_type;

  Handler handler_;
  work_executor_type executor_;
};

#if !defined(BOOST_ASIO_NO_TS_EXECUTORS)

template <typename Handler, typename Executor>
class work_dispatcher<Handler, Executor,
    typename enable_if<!execution::is_executor<Executor>::value>::type>
{
public:
  template <typename CompletionHandler>
  work_dispatcher(BOOST_ASIO_MOVE_ARG(CompletionHandler) handler,
      const Executor& handler_ex)
    : work_(handler_ex),
      handler_(BOOST_ASIO_MOVE_CAST(CompletionHandler)(handler))
  {
  }

#if defined(BOOST_ASIO_HAS_MOVE)
  work_dispatcher(const work_dispatcher& other)
    : work_(other.work_),
      handler_(other.handler_)
  {
  }

  work_dispatcher(work_dispatcher&& other)
    : work_(BOOST_ASIO_MOVE_CAST(executor_work_guard<Executor>)(other.work_)),
      handler_(BOOST_ASIO_MOVE_CAST(Handler)(other.handler_))
  {
  }
#endif // defined(BOOST_ASIO_HAS_MOVE)

  void operator()()
  {
    typename associated_allocator<Handler>::type alloc(
        (get_associated_allocator)(handler_));
    work_.get_executor().dispatch(
        BOOST_ASIO_MOVE_CAST(Handler)(handler_), alloc);
    work_.reset();
  }

private:
  executor_work_guard<Executor> work_;
  Handler handler_;
};

#endif // !defined(BOOST_ASIO_NO_TS_EXECUTORS)

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

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

#endif // BOOST_ASIO_DETAIL_WORK_DISPATCHER_HPP


text:
namespace OpenThreadTalk
{
    class ContextHelper
    {
    public:
        ContextHelper(IAsyncThreadPage^ page);

        void NotifyFromAsyncThread(String^ message, NotifyType type)
        {
            page_->NotifyFromAsyncThread(message, type);
        }

        String^ ReadString(DataReader^ dataReader);

    protected:
        IAsyncThreadPage^ page_;
    };
}


text:
package com.wyf.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.wyf.Bean.Records;

public class RecordsDao {

	private DataBaseHelper mdbhelper;
	private SQLiteDatabase db;

	private static RecordsDao mrecordsDao;

	private RecordsDao(Context context) {
		mdbhelper = new DataBaseHelper(context, null, null, 0);
	}

	public void closeAll() {
		mdbhelper.close();
		db.close();
	}

	public static RecordsDao getInstance(Context context) {
		if (mrecordsDao == null) {
			mrecordsDao = new RecordsDao(context);
			return mrecordsDao;
		}
		return mrecordsDao;
	}

	// ÑéÖ¤Óû§µÇ¼
	public boolean checkLogin(String username, String password) {
		db = mdbhelper.getWritableDatabase();
		Cursor cursor = db.query(DataBaseHelper.TABLE_NAME, null, "number = ?",
				new String[] { username }, null, null, null);
		cursor.moveToFirst();
		String passwdFromDb = cursor.getString(cursor.getColumnIndex("passwd"));
		if (passwdFromDb.equals(password))
			return true;
		return false;
	}

	// Ôö
	public void insert(Records r) {
		db = mdbhelper.getWritableDatabase();
		ContentValues cv = new ContentValues();
		cv.put(DataBaseHelper.COLUMN_NAME, r.getName());
		cv.put(DataBaseHelper.COLUME_NUMBER, r.getNumber());
		cv.put(DataBaseHelper.COLUMN_PASSWD, r.getPasswd());
		cv.put(DataBaseHelper.COLUMN_AGE, r.getAge());
		cv.put(DataBaseHelper.COLUMN_CLASSNAME, r.getClassname());
		cv.put(DataBaseHelper.COLUMN_TEL, r.getTel());
		db.insert(DataBaseHelper.TABLE_NAME, null, cv);
	}

	// ɾ
	public void delete(int id) {
		db = mdbhelper.getWritableDatabase();
		db.delete(DataBaseHelper.TABLE_NAME, "id = ?", new String[] { id + "" });
	}

	// ¸Ä
	public int update(Records r, int id) {
		db = mdbhelper.getWritableDatabase();
		ContentValues cv = new ContentValues();
		cv.put(DataBaseHelper.COLUMN_NAME, r.getName());
		cv.put(DataBaseHelper.COLUME_NUMBER, r.getNumber());
		cv.put(DataBaseHelper.COLUMN_PASSWD, r.getPasswd());
		cv.put(DataBaseHelper.COLUMN_AGE, r.getAge());
		cv.put(DataBaseHelper.COLUMN_CLASSNAME, r.getClassname());
		cv.put(DataBaseHelper.COLUMN_TEL, r.getTel());
		return db.update(DataBaseHelper.TABLE_NAME, cv, "id = ?",
				new String[] { id + "" });
	}

	// ²é
	public Cursor selectById(int id) {
		db = mdbhelper.getWritableDatabase();
		Cursor cursor = db.query(DataBaseHelper.TABLE_NAME, null, "id = ?",
				new String[] { id + "" }, null, null, null);
		return cursor;
	}

	// ²é
	public Cursor selectByNumber(String number) {
		db = mdbhelper.getWritableDatabase();
		Cursor cursor = db.query(DataBaseHelper.TABLE_NAME, null, "number = ?",
				new String[] { number }, null, null, null);
		return cursor;
	}

	public void execSQL(String sql) {
		db = mdbhelper.getWritableDatabase();
		db.execSQL(sql);
	}
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the MIT license.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.NetCore.Analyzers.Performance;

namespace Microsoft.NetCore.CSharp.Analyzers.Performance
{
    /// <summary>
    /// CA1831, CA1832, CA1833: Use AsSpan or AsMemory instead of Range-based indexers when appropriate.
    /// </summary>
    [ExportCodeFixProvider(LanguageNames.CSharp), Shared]
    public sealed class CSharpUseAsSpanInsteadOfRangeIndexerFixer : UseAsSpanInsteadOfRangeIndexerFixer
    {
        protected override bool TrySplitExpression(
            SyntaxNode node,
            out SyntaxNode toReplace,
            [NotNullWhen(true)] out SyntaxNode? target,
            [NotNullWhen(true)] out IEnumerable<SyntaxNode>? arguments)
        {
            if (node is ArgumentSyntax arg)
            {
                node = arg.Expression;
            }

            toReplace = node;

            if (node is ElementAccessExpressionSyntax elementAccess)
            {
                target = elementAccess.Expression;
                arguments = elementAccess.ArgumentList.Arguments;
                return true;
            }

            if (node is object)
            {
                throw new InvalidOperationException(node.GetType().FullName);
            }

            target = null;
            arguments = null;
            return false;
        }
    }
}


text:
Se34 - pomocné třídy pro práci se Seleniem
==========================================

# Toto README je silně neaktuální, připravuju lepší.
# This README is outdated, better documentation coming soon.

Tato knihovna závisí na:
- Nette
- PHPUnit
- PHPUnit_Selenium

V každém projektu je potřeba vytvořit tyto project-specific třídy:

- **SeleniumConfigurator** - Vytváří systémový kontejner a testovací databázi.
- **SeleniumRouteList** - Ke každé URL přidává parametr s názvem používané databáze.
- **SeleniumTemplateFactory** - Přenastavuje `$baseUrl`, aby linky na statické soubory vedly do normálního rootu.
- **SeleniumTestCase extends Se34\TestCase** - Musí implementovat `createContext()`.

Systémový kontejner, vytvářený SeleniumConfiguratorem, musí poskytovat tyto parametry:

```
parameters:
	selenium:
		server: http://localhost:4444
		desiredCapabilities
			browserName: firefox
		baseUrl: http://localhost/projekt/test-www/
		# keepWindowOpenOnFailure: FALSE # Volitelné, výchozí hodnota je TRUE.
```

Dál je potřeba vytvořit alternativní root (přes který budou k aplikaci přistupovat testy):
- index.php - V podstatě normální bootstrap, ale používá SeleniumConfigurator.
- tmp
- `.htaccess` - Copy&paste z rootu, ale přidat `Deny from all` a `Allow from 127.0.0.1`.

Selenium Server
---------------

Pro spuštění testů je potřeba:
- Java.
- [Selenium Server](http://seleniumhq.org/download/)
- Pro spouštění jiných prohlížečů než Firefox (lze nastavit v `tests/inc/selenium.neon`):
	- [Internet Explorer driver](http://seleniumhq.org/download/) (stáhnout a umístit do PATH)
	- [Chrome driver](http://code.google.com/p/chromedriver/downloads/list) (stáhnout a umístit do PATH)
	- **Opera Driver** je součástí aktuálního Selenium Serveru, ale zatím [nepodporuje Alert API](https://github.com/operasoftware/operadriver/issues/31), takže některé testy neprojdou.
	- **HtmlUnit** se mi zatím nepodařilo rozběhat, ale taky by měl být součástí Serveru.

Před spuštěním samotných testů je nutné spustit Selenium Server, ideálně z příkazové řádky (protože pak lze snadno killnout ctrl-c):

```
java -jar selenium-server-standalone-2.25.0.jar
```

Tahle knihovna umožňuje ponechat otevřené okno prohlížeče i po skončení testu (hodí se to při chybě). V takovém případě ale zůstane v paměti viset proces Chrome Driveru (asi to dělají i jiné drivery). Po nějaké době se jich může nakupit hodně a můžou zdržovat, na Windows se killnou `taskkill /F /IM chrome-driver.exe`.

Přístup k Seleniovým příkazům
-----------------------------

Základní třída zpřístupňuje objekt session, přes který se volají selenové příkazy:

```php
public function testFoo()
{
	$this->session->byXpath('//button[text()="Text"]')->click();
}
```

Předtím jsem zkoušel `PHPUnit_Extensions_Selenium2TestCase`, ve které se ke všemu přistupuje přes `$this`, ale přišlo mi to jako děsnej bordel.

Selenium 2 (WebDriver)
----------------------

Testy používají Selenium 2. Hlavní rozdíly oproti Seleniu 1:

- Jiné API, více objektově orientované. Místo `$session->type('name', 'value')` se píše `$session->byName('name')->value('value')` - tzn. nejdřív vyberete element a potom na něm provedete nějakou akci. Pokud element není nalezen, vyskočí RuntimeException.
- Provádění příkazů se víc blíží tomu, jak by to dělal uživatel. Například:
  - Příkaz *value* na objektu elementu nepřepisuje přímo jeho javascriptovou vlastnost *value*, ale předá elementu focus a simuluje stisky kláves. Díky tomu například:
    - Lze odeslat formulář enterem.
    - Lze vybrat ze selectu napsáním prvních pár znaků.
    - Provedou se případné JS události navěšené na stisk kláves.
  - Není možné kliknout na element, pokud není vidět. Pokud se nějaké menu rozbalí až po najetí na nějaký jiný prvek, je potřeba nejdřív na tento prvek "najet" (př. `$session->moveto($session->byLinkText('Menu'))`).
  - Stejně tak nelze na nic kliknout, pokud je přes celou stránku Laděnka (stejně jako ve skutečnosti). Ovšem Laděnku standardně odchytává BrowserSession.

WebDriver API
-------------

Dokumentace WebDriver API příkazů je zde: http://code.google.com/p/selenium/wiki/JsonWireProtocol

Příkazy z WebDriver API, které BrowserSession zatím nenabízí, lze případně velmi snadno přidat (`BrowserSession::initCommands()`).

WaitForAjax atd.
----------------

Session objekt nabízí několik čekacích metod:

- `waitForAlert()` - pokud je na stránce klasický JS dialog (alert, confirm, nebo prompt), tak většina příkazů končí chybou. Jenže dokud se ten alert neobjeví, tak končí chybou i příkaz `alertText`. Tahle metoda proto provádí `alertText` tak dlouho, dokud neskončí úspěšně. Potom je možné dál s dialogem pracovat:
  - `alertText($text)` - vloží text do promptu.
  - `acceptAlert()` - potvrdí dialog.
  - `dismissAlert()` - zruší dialog.
- `waitForCondition($condition)` - čeká na splnění nějaké JS podmínky.
- `waitForDocument()` - čeká na `document.readyState == "complete"`
- `waitForAjax()` - čeká na `jQuery.active == 0`

Asserts
-------

`Se34\TestCase` přidává tyto aserce:

- `assertPresenter`
- `assertTagName`
- `assertTagAttributes`
- `assertElementEquals`

Page Objects
------------

Aby testy nebyly tolik závislé na aktuálním HTML kódu, je vhodné použít tzv. Page Objects. Články o návrhovém vzoru Page Objects:
- http://blog.activelylazy.co.uk/2011/07/09/page-objects-in-selenium-2-0/
- http://code.google.com/p/selenium/wiki/PageObjects
- http://css.dzone.com/articles/page-object-pattern

Základní třída pro page objects
-------------------------------

`Se34\PageObject`

- Podporované anotace:
  - `@property-read` - zkratky pro přístup k elementům.
  - `@method` - metody pro akce nad elementy.
- Provádí kontrolu stavu.
  - Při přístupu k elementům přes zkratky.
  - Při volání magických metod.
  - Na požádání (`->checkState()`).

Příklad: todo

Formát `@property-read`
-----------------------

```
/**
 * @property-read Element $searchBox name=q, input, (type=text) # Poznámka
 * @property-read Element[] $allLinks xpath='//a', a # Příklad na pole elementů
 */
```

- `@property-read`
- `Element` - pokud je `Element[]` (resp. `Cokoli[]`), tak jde o pole všech elementů, které vyhovují kritériím, jinak jeden element.
- `$searchBox` - název zkratky, nezapomenout `$`.
- `name = q` - [locator strategy = value](http://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element)
- `input` - nepovinné. Pokud je uvedeno, kontroluje se název nalezeného elementu/nalezených elementů.
- `(type = text)` - nepovinné. Pokud je uvedeno, kontrolují se hodnoty atributů.
- ` # Poznámka` - poznámku lze oddělit mezerou a křížkem.

Část mezi názvem property a poznámkou se parsuje Neonem.

Formát `@method`
----------------

```
/**
 * @method ReturnType methodShortcut() Description
 */
```

- `@method`
- `ReturnType` - návratový typ, musí implementovat `Se34\IPageObject`. Pokud nezačíná zpětným lomítkem, hledá se nejdřív v namespacu definující třídy (tj. třídy, ve které je uvedená ta anotace `@method`).

  Pokud `$this instanceof ReturnType`, tak se vrátí přímo `$this`.
- `methodShortcut` - volání `$page->methodShortcut($arg)` se převede na `$page->shortcut->method($arg)`, rozdíl je jen v té návratovce.

getNextPage()
-------------

Tam, kde nestačí `@method` anotace, lze pro výběr následujícího page objectu použít tuto protected metodu:

```php
/**
 * @return AnotherPage|YetAnotherPage Možné návratové typy.
 */
public function clickSomething()
{
	$this->something->click();
	$this->session->waitForAjax();
	return $this->getNextPage(); // vybírá z typů v @return
}
```

fill()
------

Podpůrná magie pro vyplňování formulářů:

```php
$page->fillFoo($value); // $page->foo->value($value);

$page->fill(array(
	'foo' => 'bar',     // $page->fillFoo('bar');
	'e' => 'mc^2',      // $page->fillE('mc^2');
));
```


text:
from parsl.channels import OAuthSSHChannel

def test_channel():
    channel = OAuthSSHChannel(hostname='ssh.demo.globus.org', username='yadunand')
    x, stdout, stderr = channel.execute_wait('ls')
    print(x, stdout, stderr)
    assert x == 0, "Expected exit code 0, got {}".format(x)

if __name__ == '__main__':

    test_channel()


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Uredo pseudocyperi Rabenh.

### Remarks
null


text:
import grpc
import numpy
import os
import time

import tensorrtserver.api.model_config_pb2 as model_config
from tensorrtserver.api import api_pb2
from tensorrtserver.api import grpc_service_pb2
from tensorrtserver.api import grpc_service_pb2_grpc

from PIL import Image

DATA_DIR = 'data'
DATA_SIZE = 3
TIMEOUT_MSEC = 2000
MODEL_NAME = os.environ['MODEL_NAME']
SERVER_ADDRESS = os.environ['SERVER_ADDRESS']

def init_stub(server_address):
  return stub

def init_request(model_name, data_dir, data_size):
  image_id = numpy.random.randint(data_size) + 1
  image_file = '{}/{:0>5}.jpg'.format(data_dir, image_id)
  image = Image.open(image_file).convert('RGB')
  image = image.resize((224, 224), Image.BILINEAR)
  image = numpy.array(image).astype(numpy.float32)

  input_bytes = image.tobytes()
  request = grpc_service_pb2.InferRequest()

  request.model_name = model_name
  request.model_version = -1
  request.meta_data.batch_size = 1

  output_message = api_pb2.InferRequestHeader.Output()
  output_message.name = 'probabilities'
  output_message.cls.count = 1

  request.meta_data.output.extend([output_message])
  request.meta_data.input.add(name='input')
  request.raw_input.extend([input_bytes])

  return request

def main():
  hostport = "{}:8001".format(SERVER_ADDRESS)
  channel = grpc.insecure_channel(hostport)
  stub = grpc_service_pb2_grpc.GRPCServiceStub(channel)
  request = init_request(MODEL_NAME, DATA_DIR, DATA_SIZE)

  while(True):
    request_per_sec = int(os.environ['REQUEST_PER_SEC'])
    result = stub.Infer(request, TIMEOUT_MSEC)
    time.sleep(1./request_per_sec)

if __name__ == "__main__":
  main()


text:
package org.spoofax.jsglr.client;

import org.spoofax.jsglr.client.imploder.TopdownTreeBuilder;

public class ParseProductionNode extends AbstractParseNode {

	private static final AbstractParseNode[] NO_CHILDREN =
		new AbstractParseNode[0];

	public final int prod;

    public ParseProductionNode(int prod, int line, int column) {
      super(line, column);
        this.prod = prod;
    }

    @Override
    public void reject() {
    	throw new UnsupportedOperationException();
    }

    @Override
	public boolean isParseProductionChain() {
    	return true;
    }

    @Override
    public Object toTreeBottomup(BottomupTreeBuilder builder) {
    	return builder.buildProduction(prod);
    }

    @Override
    public Object toTreeTopdown(TopdownTreeBuilder builder) {
      return builder.buildTreeProduction(this);
    }

    @Override
    public String toString() {
        return "\"" + prod + (prod >= 32 ? (":" + (char) prod) : "").replace("\"", "\\\"") + "\"";
    }

    @Override
    public int getLabel() { return prod; }

    @Override
    public boolean equals(Object obj) {
        if(!(obj instanceof ParseProductionNode) ||!super.equals(obj))
            return false;
        return prod == ((ParseProductionNode)obj).prod;
    }

    @Override
    public int hashCode() {
        return 6359 * prod + super.hashCode();
    }

    @Override
    public String toStringShallow() {
        return "prod*(" + prod + ")";
    }

	@Override
	public int getNodeType() {
		return AbstractParseNode.PARSE_PRODUCTION_NODE;
	}

	@Override
	public AbstractParseNode[] getChildren() {
		return NO_CHILDREN;
	}

  @Override
  public boolean isEmpty() {
    return false;
  }

  @Override
  public AbstractParseNode getLeft() {
    return this;
  }

  @Override
  public boolean isLayout() {
    return false;
  }

  @Override
  public boolean isIgnoreLayout() {
    return false;
  }

  @Override public boolean isPlaceholderInsertionNode() {
      // TODO Auto-generated method stub
      return false;
  }

  @Override public boolean isLiteralCompletionNode() {
      // TODO Auto-generated method stub
      return false;
  }
}


text:
<xml id="toolbox" style="display: none">
  <category name="Events">
    <block type="when_pressed"></block>
    <block type="when_clicked"></block>
  </category>
  <category name="Elements">
    <block type="circle_element">
      <field name="name">ball</field>
    </block>
  </category>
  <category name="Variables">
    <!--<block type="create_slider"></block>-->
    <block type="variables_set"></block>
    <block type="variables_get"></block>
  </category>
  <category name="Text">
    <block type="text_element">
      <value name="text">
      </value>
    </block>
    <block type="text">
    </block>
    <block type="text_join">
      <value name="ADD0">
      </value>
    </block>
  </category>
  <category name="Numbers">
    <block type="math_arithmetic"></block>
    <block type="math_number">
      <field name="NUM">50</field>
    </block>
  </category>
</xml>


text:
FROM nginx:alpine
MAINTAINER goya "rudd@adobe.com"

COPY ./nginx.conf /etc/nginx/nginx.conf

EXPOSE 8080


text: {{ forField.select_lookup(fieldValue).name }}


text:
package com.manning.androidhacks.hack042.db;

import java.io.File;
import java.util.List;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.manning.androidhacks.hack042.model.Poi;

public class DatabaseHelper extends SQLiteOpenHelper {
  public static final String DATABASE_NAME = "pois.db";
  private static final int DATABASE_VERSION = 1;
  private Context mContext;

  static {
    System.loadLibrary("hack042-native");
  }

  public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    mContext = context;
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE " + "pois ("
        + "_id INTEGER PRIMARY KEY AUTOINCREMENT," + "title TEXT,"
        + "longitude FLOAT," + "latitude FLOAT);");
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion,
      int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS pois;");

  }

  public List<Poi> getNear(float latitude, float longitude) {
    File file = mContext.getDatabasePath(DATABASE_NAME);
    return getNear(file.getAbsolutePath(), latitude, longitude);
  }

  private native List<Poi> getNear(String dbPath, float latitude,
      float longitude);
}


text:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Baud.Deployment.BusinessLogic.Domain.Security.Contracts;
using Baud.Deployment.BusinessLogic.Domain.Security.Entities;
using Baud.Deployment.BusinessLogic.Domain.Security.Queries;

namespace Baud.Deployment.Database.Security
{
    public class UsersRepository : RepositoryBase<SecurityDbContext>, IUsersRepository
    {
        public UsersRepository(SecurityDbContext context)
            : base(context)
        {
        }

        public IQueryable<User> GetUsers()
        {
            return Context.Users.OnlyNonSystem();
        }

        public User GetUserDetail(short id)
        {
            return Context.Users
                .FilterByID(id)
                .Include(x => x.PositionLinks)
                .Include("PositionLinks.Position")
                .FirstOrDefault();
        }

        public void UpdateUser(short id, User user)
        {
            user.ID = id;

            Context.AttachAsModified(user,
                x => x.FirstName,
                x => x.LastName,
                x => x.Email,
                x => x.Note,
                x => x.ActiveFrom,
                x => x.ActiveTo);
        }

        public void AddUser(User user)
        {
            Context.Users.Add(user);
        }
    }
}


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/diag/attn/hostboot/test/attnfakesys.H $               */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2014                             */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#ifndef __TEST_ATTNFAKESYS_H
#define __TEST_ATTNFAKESYS_H

/**
 * @file attnfakesys.H
 *
 * @brief HBATTN fake system class definition.
 */

#include "../../common/attnscom.H"
#include "attntest.H"
#include "attncomp.H"
#include "attninject.H"
#include <map>

namespace ATTN
{

/**
 * @brief FakeSystem
 *
 * Container that presents an interface to fake hardware
 * implementations.
 */
class FakeSystem : public ScomImpl, public InjectSink
{
    public:

        /**
         * @brief putReg
         *
         * Simulate register modification originating in hardware.
         *
         * @param[in] i_target Target to write register on.
         * @param[in] i_address Register address to write to.
         * @param[in] i_data Data to write to register.
         *
         * @retval[0] No errors.
         * @retval[!0] Unexpected error occurred.
         */
        errlHndl_t putReg(
                TARGETING::TargetHandle_t i_target,
                uint64_t i_address,
                uint64_t i_data);

        /**
         * @brief modifyReg
         *
         * Simulate register modification originating in hardware.
         *
         * @param[in] i_target Target to update register on.
         * @param[in] i_address Register address to update.
         * @param[in] i_data Data to write to register.
         * @param[in] i_op and/or behavior.
         *
         * @retval[0] No errors.
         * @retval[!0] Unexpected error occurred.
         */
        errlHndl_t modifyReg(
                TARGETING::TargetHandle_t i_target,
                uint64_t i_address,
                uint64_t i_data,
                ScomOp i_op);

        /**
         * @brief getReg Register read originating in hardware.
         *
         * @param[in] i_target Target to read register from.
         * @param[in] i_address Register address to read from.
         *
         * @return Register data.
         */
        uint64_t getReg(
                TARGETING::TargetHandle_t i_target,
                uint64_t i_address);

        /**
         * @brief putAttentions
         *
         * Instruct the system to inject the specified attention.
         *
         * @param[in] i_list The attentions to inject.
         *
         * @retval[0] No error occurred.
         * @retval[!0] Unexpected error occurred.
         */
        errlHndl_t putAttentions(
                const PRDF::AttnList & i_list);

        /**
         * @brief clearAttention
         *
         * Instruct the system clear the specified attention.
         *
         * @param[in] i_attn The attention to clear.
         *
         * @retval[0] No error occurred.
         * @retval[!0] Unexpected error occurred.
         */
        errlHndl_t clearAttention(
                const PRDF::AttnData & i_attn);

        /**
         * @brief clearAllAttentions
         *
         * Instruct the system clear all instances of the specified attention.
         *
         * @param[in] i_attn The attention to clear.
         *
         * @retval[0] No error occurred.
         * @retval[!0] Unexpected error occurred.
         */
        errlHndl_t clearAllAttentions(
                const PRDF::AttnData & i_attn);

        /**
         * @brief count
         *
         * For the provided attention type, obtain the number
         * of times it is being reported by the system.
         *
         * @param[in] i_attn The attention type for which the count should be
         *                obtained.
         */
        uint64_t count(
                const PRDF::AttnData & i_attn);

        /**
         * @brief wait
         *
         * Block the calling thread until no attentions are
         * being reported on the system.
         *
         * @param[in] i_maxTimeNs Max amount of time to wait
         *                once system has reached stable state
         *                (number of attentions isn't changing)
         *
         * @retval[true] No attentions being reported.
         * @retval[false].Attentions still being reported
         *                  after waiting i_maxTimeNs.
         */
        bool wait(uint64_t i_maxTimeNs);

        /**
         * @brief wait
         *
         * Block the calling thread until no attentions are
         * being reported on the system.
         */
        void wait();

        /**
         * @brief addReg
         *
         * Register a register implementaion with the system.
         *
         * @param[in] i_address The address for which the implementation
         *              wishes to monitor.
         * @param[in] i_reg The register implementation to add to the system.
         */
        void addReg(
                uint64_t i_address,
                FakeReg & i_reg);

        /**
         * @brief addSource
         *
         * Register an attention source implementation with the system.
         *
         * @param[in] i_targetType The target type for which the implementation
         *              wishes to monitor.
         * @param[in] i_type The attention type for which the implementation
         *              wishes to monitor.
         * @param[in] i_source The source to add to the system.
         */
        void addSource(
                TARGETING::TYPE i_targetType,
                PRDF::ATTENTION_VALUE_TYPE i_type,
                FakeSource & i_source);

        /**
         * @brief putScom Write a register using SCOM.
         *
         * @param[in] i_target Target to write register on.
         * @param[in] i_address Register address to write to.
         * @param[in] i_data Data to write to register.
         *
         * @retval[0] No errors.
         * @retval[!0] Unexpected error occurred.
         */
        errlHndl_t putScom(
                TARGETING::TargetHandle_t i_target,
                uint64_t i_address,
                uint64_t i_data);

        /**
         * @brief getScom Read a register using SCOM.
         *
         * @param[in] i_target Target to read register from.
         * @param[in] i_address Register address to read from.
         * @param[out] o_data Buffer to write register content to.
         *
         * @retval[0] No errors.
         * @retval[!0] Unexpected error occurred.
         */
        errlHndl_t getScom(
                TARGETING::TargetHandle_t i_target,
                uint64_t i_address,
                uint64_t & o_data);

        /**
         * @brief modifyScom RMW a register using SCOM.
         *
         * @param[in] i_target Target to update register on.
         * @param[in] i_address Register address to update.
         * @param[in] i_data Data to write to register.
         * @param[out] o_data Data read from register.
         * @param[in] i_op and/or behavior.
         *
         * @retval[0] No errors.
         * @retval[!0] Unexpected error occurred.
         */
        errlHndl_t modifyScom(
                TARGETING::TargetHandle_t i_target,
                uint64_t i_address,
                uint64_t i_data,
                uint64_t & o_data,
                ScomOp i_op);

        /**
         * @brief dump Dump active attentions to trace.
         */
        void dump();

        /*
         * @brief count Obtain the number of attentions present
         *          on the system.
         *
         * @return The number of attentions present on the system.
         */
        uint64_t count();

        /**
         * @brief ctor
         */
        FakeSystem();

        /**
         * @brief dtor
         */
        virtual ~FakeSystem();

    private:

        /**
         * @brief Reg Register/address association alias.
         */
        typedef std::map<uint64_t, uint64_t> RegAddrDataAssoc;

        /**
         * @brief Regs Registers/target association alias.
         */
        typedef std::map<TARGETING::TargetHandle_t, RegAddrDataAssoc> Regs;

        /**
         * @brief iv_regs Current register content.
         */
        Regs iv_regs;

        /**
         * @brief makeAttnCallbacks
         *
         * Notify registered sources of attention state changes.
         *
         * @param[in] i_list List of attentions changing state.
         * @param[in] i_set Attentions turning on / off.
         *
         * @retval[0] No error occurred.
         * @retval[!0] Unexpected error occurred.
         */
        errlHndl_t makeAttnCallbacks(
                const PRDF::AttnList & i_list,
                bool i_set);

        /**
         * @brief makeRegCallbacks
         *
         * Notify registered registers of content changes.
         *
         * @param[in] i_target Target being updated.
         * @param[in] i_address Address of register being updated.
         * @param[in] i_new Post update register content.
         * @param[in] i_new Pre update register content.
         *
         * @retval[0] No error occurred.
         * @retval[!0] Unexpected error occurred.
         */
        errlHndl_t makeRegCallbacks(
                TARGETING::TargetHandle_t i_target,
                uint64_t i_address,
                uint64_t i_new,
                uint64_t i_old);

        /**
         * @brief clearAttentionUnsafe
         *
         * Thread unsafe wrapper for clearAttention.
         *
         * @param[in] i_attn The attention to clear.
         *
         * @retval[0] No error occurred.
         * @retval[!0] Unexpected error occurred.
         */
        void clearAttentionUnsafe(
                const PRDF::AttnData & i_attn);

        /**
         * @brief putRegUnsafe
         *
         * Thread unsafe wrapper for putReg.
         *
         * @param[in] i_target Target to write register on.
         * @param[in] i_address Register address to write to.
         * @param[in] i_data Data to write to register.
         */
        void putRegUnsafe(
                TARGETING::TargetHandle_t i_target,
                uint64_t i_address,
                uint64_t i_data);

        /**
         * @brief iv_attentions Current active attentions.
         */
        AttnDataMap<uint64_t> iv_attentions;

        /**
         * @brief iv_regImpl registered register implementations.
         */
        std::vector<std::pair<uint64_t, FakeReg *> > iv_regImpl;

        /**
         * @brief Key Registered source key alias.
         */
        typedef std::pair<TARGETING::TYPE, PRDF::ATTENTION_VALUE_TYPE> Key;

        /**
         * @brief Entry Registered source key/value alias.
         */
        typedef std::pair<Key, FakeSource *> Entry;

        /**
         * @brief iv_source Registered sources.
         */
        std::vector<Entry> iv_sources;

        /**
         * @brief iv_mutex Shared data access serialization.
         */
        mutex_t iv_mutex;

        /**
         * @brief iv_cond Zero attentions condition.
         */
        sync_cond_t iv_cond;
};
}
#endif


text:
package br.com.yanaga.samples.academico.query;

import com.mysema.query.BooleanBuilder;
import com.mysema.query.types.path.ComparablePath;

import java.io.Serializable;

class ArgumentoComparableSimples implements ArgumentoComparable, Serializable {

	private final String value;

	ArgumentoComparableSimples(String value) {
		this.value = value;
	}

	@Override
	public void append(BooleanBuilder builder, ComparablePath<?> path) {
		builder.and(path.stringValue().containsIgnoreCase(value));
	}

	@Override
	public String toString() {
		return value;
	}

}


text:
<?php

namespace Vipa\InstallerBundle\Controller;

use Vipa\CoreBundle\Controller\VipaController as Controller;

class SummaryController extends Controller
{

    public function summaryAction()
    {
        $data['page'] = 'summary';

        return $this->render("VipaInstallerBundle:Default:summary.html.twig", array('data' => $data));
    }
}


text:
require 'rails_helper'

RSpec.describe LetterPdf do
  include ActionView::Helpers::NumberHelper
  before :each do
    @creditor = create :person, name: 'Meier', first_name: 'Albert', title: 'Dr.',
        street_number: 'Strasse 1', zip: '79100', city: 'Freiburg'
    @letter = create :standard_letter, content: 'Something to tell', subject: 'TheSubject'
  end

  context "without a registered_society project address " do
    before :each do
      @project_address = create :project_address, :with_legals, :with_contacts, name: 'Das Projekt',
        street_number: 'Weg 1', zip: '7800', city: "Städtl", email: 'info@example.org', phone: 'PhoneNumber',
        legal_form: 'limited'
      @account = create :account, address: @project_address, bank: 'DiBaDu', default: true
    end

    it "raises an error about it" do
      expect{
        @pdf = LetterPdf.new(@creditor, @letter)
      }.to raise_error(MissingRegisteredSocietyError)
    end
  end

  context "with project_address is registered_society" do
    before :each do
      @project_address = create :project_address, :with_legals, :with_contacts, name: 'Das Projekt',
        street_number: 'Weg 1', zip: '7800', city: "Städtl", email: 'info@example.org', phone: 'PhoneNumber',
        legal_form: 'registered_society'
      @account = create :account, address: @project_address, bank: 'DiBaDu', default: true
      @pdf = LetterPdf.new(@creditor, @letter)
    end

    it "has the right content" do
      page_analysis = PDF::Inspector::Page.analyze(@pdf.render)
      expect(page_analysis.pages.size).to eq(1)

      ### FIRST PAGE: covering letter
      text_analysis = page_analysis.pages[0][:strings]
      #address_field
      expect(text_analysis).to include("Das Projekt e.V.")
      expect(text_analysis).to include(" | Weg 1 | 7800 Städtl")
      expect(text_analysis).to include("Dr. Albert Meier")
      expect(text_analysis).to include("Strasse 1")
      expect(text_analysis).to include("79100 Freiburg")
      expect(text_analysis).to include("Deutschland")

      #main part
      expect(text_analysis).to include(I18n.l(Date.today))
      expect(text_analysis).to include("Betreff:")
      expect(text_analysis).to include(" TheSubject")
      expect(text_analysis).to include("Something to tell")

      #footer
      #FIXME: footer ist not found by PDFInspector (repeated content)
      #expect(text_analysis).to include("Das Projekt e.V.")
      #expect(text_analysis).to include("Court")
      #expect(text_analysis).to include(" RegistragionNumber | ")
      #expect(text_analysis).to include("Vorstand")
      #expect(text_analysis).to include(" Vorname Test Name")
      #expect(text_analysis).to include("DiBaDu")
      #expect(text_analysis).to include("BIC")
      #expect(text_analysis).to include(" GENODEF1S02 | ")
      #expect(text_analysis).to include("IBAN")
      #expect(text_analysis).to include(" RO49 AAAA 1B31 0075 9384 0000 | ")
    end
  end
end


text:
using System;

namespace Marketplace.Client.Models.Security
{
    public class PasswordResetModel
    {
        public string IdentityId { get; set; }
        public string NewPassword { get; set; }
    }
}


text:
@implementation NSTimer (YBTools)
+ (void)_yb_ExecBlock:(NSTimer *)timer {
    if ([timer userInfo]) {
        void (^block)(NSTimer *timer) = (void (^)(NSTimer *timer))[timer userInfo];
        block(timer);
    }
}

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds block:(void (^)(NSTimer *timer))block repeats:(BOOL)repeats {
    return [NSTimer scheduledTimerWithTimeInterval:seconds target:self selector:@selector(_yb_ExecBlock:) userInfo:[block copy] repeats:repeats];
}

+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)seconds block:(void (^)(NSTimer *timer))block repeats:(BOOL)repeats {
    return [NSTimer timerWithTimeInterval:seconds target:self selector:@selector(_yb_ExecBlock:) userInfo:[block copy] repeats:repeats];
}
@end


text:
package org.apache.spark.sql.carbondata.execution.datasources

import scala.collection.mutable.ArrayBuffer

import org.apache.hadoop.fs.Path
import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
import org.apache.spark.sql.catalyst.rules.Rule
import org.apache.spark.sql.execution.datasources.{FileIndex, HadoopFsRelation, InMemoryFileIndex, InsertIntoHadoopFsRelationCommand, LogicalRelation}
import org.apache.spark.sql.sources.BaseRelation

import org.apache.carbondata.core.datastore.filesystem.CarbonFile
import org.apache.carbondata.core.datastore.impl.FileFactory
import org.apache.carbondata.core.util.CarbonProperties
import org.apache.carbondata.core.util.path.CarbonTablePath

/**
 * Rule to replace FileIndex with CarbonFileIndex for better driver pruning.
 */
class CarbonFileIndexReplaceRule extends Rule[LogicalPlan] {

  /**
   * This property creates subfolder for every load
   */
  private val createSubFolder = CarbonProperties.getInstance()
    .getProperty("carbonfileformat.create.folder.perload", "false").toBoolean

  override def apply(plan: LogicalPlan): LogicalPlan = {
    val transformedPlan = plan.transform {
      case l: LogicalRelation
        if l.relation.isInstanceOf[HadoopFsRelation] &&
           l.relation.asInstanceOf[HadoopFsRelation].fileFormat.toString.equals("carbon") &&
           !l.relation.asInstanceOf[HadoopFsRelation].location.isInstanceOf[CarbonFileIndex] =>
        val fsRelation = l.relation.asInstanceOf[HadoopFsRelation]
        val fileIndex = fsRelation.location
        val carbonFileIndex = CarbonFileIndex(fsRelation.sparkSession,
          fsRelation.dataSchema,
          fsRelation.options,
          updateFileIndex(fileIndex, fsRelation))
        val fsRelationCopy = fsRelation.copy(location = carbonFileIndex)(fsRelation.sparkSession)
        val logicalRelation = l.copy(relation = fsRelationCopy.asInstanceOf[BaseRelation])
        logicalRelation
      case insert: InsertIntoHadoopFsRelationCommand
        if createSubFolder && insert.fileFormat.toString.equals("carbon") &&
           FileFactory.getUpdatedFilePath(insert.outputPath.toString).equals(
             FileFactory.getUpdatedFilePath(insert.options("path"))) &&
           insert.partitionColumns.isEmpty =>
        val path = new Path(insert.outputPath, System.nanoTime().toString)
        insert.copy(outputPath = path)
    }
    transformedPlan
  }

  private def updateFileIndex(fileIndex: FileIndex,
      hadoopFsRelation: HadoopFsRelation): FileIndex = {
    if (fileIndex.isInstanceOf[InMemoryFileIndex] && fileIndex.rootPaths.length == 1) {
      val carbonFile = FileFactory.getCarbonFile(fileIndex.rootPaths.head.toUri.toString)
      val dataFolders = new ArrayBuffer[CarbonFile]()
      getDataFolders(carbonFile, dataFolders)
      if (dataFolders.nonEmpty && dataFolders.length > 1) {
        val paths = dataFolders.map(p => new Path(p.getAbsolutePath))
        new InMemoryFileIndex(hadoopFsRelation.sparkSession,
          paths,
          hadoopFsRelation.options,
          Some(hadoopFsRelation.partitionSchema))
      } else {
        fileIndex
      }
    } else {
      fileIndex
    }
  }

  /**
   * Get data folders recursively
   */
  private def getDataFolders(
      tableFolder: CarbonFile,
      dataFolders: ArrayBuffer[CarbonFile]): Unit = {
    val files = tableFolder.listFiles()
    files.foreach { f =>
      if (f.isDirectory) {
        val files = f.listFiles()
        if (files.nonEmpty && !files(0).isDirectory) {
          dataFolders += f
        } else {
          getDataFolders(f, dataFolders)
        }
      }
    }
  }
}


text:
module Locomotive
  module API
    module Middlewares

      class LocaleMiddleware

        def initialize(app)
          @app = app
        end

        # Rules (order is important):
        #
        # 1. check for the X-Locomotive-Locale header
        # 2. check for the locale request param
        # 3. check for the site default locale
        # 4. if none, take the default locomotive locale
        #
        def call(env)
          locale = find_locale(env)
          setup_i18n_fallback(env['locomotive.site'])
          ::Mongoid::Fields::I18n.with_locale(locale) do
            @app.call(env)
          end
        end

        private

        def find_locale(env)
          env['HTTP_X_LOCOMOTIVE_LOCALE'].presence ||
          params(env)[:locale].presence ||
          params(env)['locale'].presence ||
          env['locomotive.site'].try(:default_locale).presence ||
          Locomotive.config.site_locales.first
        end

        def setup_i18n_fallback(site)
          ::Mongoid::Fields::I18n.clear_fallbacks
          (site.try(:locales) || []).each do |locale|
            ::Mongoid::Fields::I18n.fallbacks_for(locale, site.locale_fallbacks(locale))
          end
        end

        def params(env)
          @params ||= Rack::Request.new(env).params
        end

      end

    end
  end
end


text:
#ifndef POINT_H_
#define POINT_H_

#include <cmath>

class Point
{
  public:
    Point();
    Point(float x, float y);

    void set(float x, float y);
    void set(const Point& point);

    float getX() const;
    float getY() const;

    void movePointWithAngle(float distance, float angle);

    float findAngle(const Point& point) const;
    bool equals(const Point& point);
    float distance(const Point& point);

    Point operator+(const Point& rhs) const;
    Point operator-(const Point& rhs) const;
    Point operator*(const float rhs) const;
    Point operator/(const float rhs) const;
    bool operator==(const Point& rhs) const;

  private:
    float x, y;
};

#endif // POINT_H_


text:
module Puffer
  module Controller
    module Mutate
      extend ActiveSupport::Concern

      included do
        helper 'puffer/helpers/puffer'

        delegate :model, :model_name, :to => 'self.class'
        helper_method :puffer_filters, :puffer_namespace, :resource, :record, :records
      end

      def process_action method_name, *args
        params[:puffer] = Rails.application.routes.resources_tree[params[:puffer]] if params[:puffer]
        super
      end

      def puffer_filters
        @puffer_filters ||= begin
          filters = params[Puffer::Filters.model_name.param_key] || {}
          filters.reverse_merge! :puffer_order => configuration.order if configuration.order.present?
          filters.reverse_merge! :puffer_per_page => configuration.per_page if configuration.per_page.present?
          Puffer::Filters.new filter_fields, filters
        end
      end

      def puffer_namespace
        request.path_info.split('/').delete_if(&:blank?).first.try(:to_sym)
      end

      def resource
        @resource ||= Puffer::Resource.new resource_params, self
      end

      def resource_params
        params
      end

      def record
        @record || instance_variable_get("@#{resource.model_name}")
      end

      def records
        @records || instance_variable_get("@#{resource.model_name.pluralize}")
      end

      module ClassMethods

        def puffer?
          true
        end

        def model_name
          @model_name ||= (configuration.model_name || controller_name.singularize).to_s
        end

        def model
          return nil if model_name.blank?
          @model ||= begin
            camelized = model_name.camelize
            if camelized.respond_to?(:safe_constantize)
              camelized.safe_constantize || raise_no_model_error
            else
              begin
                camelized.constantize
              rescue NameError
                raise_no_model_error
              end
            end
          end
        end

        def raise_no_model_error
          raise Puffer::NoModelError.new(to_s, model_name.camelize)
        end

      end

    end
  end
end


text:
using System;

namespace DotLiquid.Exceptions
{
#if !CORE
    [Serializable]
#endif
    public class ArgumentException : LiquidException
    {
        public ArgumentException(string message, params string[] args)
            : base(string.Format(message, args))
        {
        }

        public ArgumentException()
        {
        }
    }
}


text:
package com.planet_ink.coffee_mud.Abilities.Common;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.Common.CraftingSkill.CraftingActivity;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.ListingLibrary;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

public class Smelting extends CraftingSkill implements CraftorAbility
{
	@Override
	public String ID()
	{
		return "Smelting";
	}

	private final static String	localizedName	= CMLib.lang().L("Smelting");

	@Override
	public String name()
	{
		return localizedName;
	}

	private static final String[]	triggerStrings	= I(new String[] { "SMELT", "SMELTING" });

	@Override
	public String[] triggerStrings()
	{
		return triggerStrings;
	}

	@Override
	public String supportedResourceString()
	{
		return "METAL|MITHRIL";
	}

	@Override
	public String parametersFormat()
	{
		return "ITEM_NAME\tITEM_LEVEL\tBUILD_TIME_TICKS\tFUTURE_USE\tFUTURE_USE\tITEM_CLASS_ID\tRESOURCE_NAME\tRESOURCE_NAME";
	}

	//protected static final int RCP_FINALNAME=0;
	//protected static final int RCP_LEVEL=1;
	//protected static final int RCP_TICKS=2;
	//private static final int RCP_WOOD_ALWAYSONEONE=3;
	//private static final int RCP_VALUE_DONTMATTER=4;
	//private static final int RCP_CLASSTYPE=5;
	protected static final int RCP_METALONE=6;
	protected static final int RCP_METALTWO=7;

	protected int amountMaking=0;

	@Override
	public boolean tick(Tickable ticking, int tickID)
	{
		if((affected!=null)&&(affected instanceof MOB)&&(tickID==Tickable.TICKID_MOB))
		{
			final MOB mob=(MOB)affected;
			if((buildingI==null)
			||(amountMaking<1)
			||(getRequiredFire(mob,0)==null))
			{
				messedUp=true;
				unInvoke();
			}
		}
		return super.tick(ticking,tickID);
	}

	@Override
	public String parametersFile()
	{
		return "smelting.txt";
	}

	@Override
	protected List<List<String>> loadRecipes()
	{
		return super.loadRecipes(parametersFile());
	}

	@Override
	public String getDecodedComponentsDescription(MOB mob, List<String> recipe)
	{
		return "1";
	}

	@Override
	public void unInvoke()
	{
		if(canBeUninvoked())
		{
			if(affected instanceof MOB)
			{
				final MOB mob=(MOB)affected;
				if((buildingI!=null)&&(!aborted))
				{
					amountMaking=amountMaking*(abilityCode());
					if(messedUp)
						commonEmote(mob,L("<S-NAME> ruin(s) @x1!",buildingI.name()));
					else
					for(int i=0;i<amountMaking;i++)
					{
						final Item copy=(Item)buildingI.copyOf();
						copy.setMiscText(buildingI.text());
						copy.recoverPhyStats();
						mob.location().addItem(copy,ItemPossessor.Expire.Player_Drop);
					}
				}
				buildingI=null;
			}
		}
		super.unInvoke();
	}

	@Override
	public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
	{
		if(super.checkStop(mob, commands))
			return true;
		randomRecipeFix(mob,addRecipes(mob,loadRecipes()),commands,0);
		if(commands.size()==0)
		{
			commonTell(mob,L("Make what? Enter \"smelt list\" for a list, or \"smelt stop\" to cancel."));
			return false;
		}
		final List<List<String>> recipes=addRecipes(mob,loadRecipes());
		final String str=commands.get(0);
		String startStr=null;
		int duration=4;
		if(str.equalsIgnoreCase("list"))
		{
			String mask=CMParms.combine(commands,1);
			boolean allFlag=false;
			if(mask.equalsIgnoreCase("all"))
			{
				allFlag=true;
				mask="";
			}
			final int[] cols={
				CMLib.lister().fixColWidth(20,mob.session()),
				CMLib.lister().fixColWidth(3,mob.session()),
				CMLib.lister().fixColWidth(16,mob.session())
			};
			final StringBuffer buf=new StringBuffer(L("@x1 @x2 @x3 Metal #2\n\r",CMStrings.padRight(L("Item"),cols[0]),CMStrings.padRight(L("Lvl"),cols[1]),CMStrings.padRight(L("Metal #1"),cols[2])));
			for(int r=0;r<recipes.size();r++)
			{
				final List<String> V=recipes.get(r);
				if(V.size()>0)
				{
					final String item=replacePercent(V.get(RCP_FINALNAME),"");
					final int level=CMath.s_int(V.get(RCP_LEVEL));
					final String metal1=V.get(RCP_METALONE).toLowerCase();
					final String metal2=V.get(RCP_METALTWO).toLowerCase();
					if(((level<=xlevel(mob))||allFlag)
					&&((mask.length()==0)||mask.equalsIgnoreCase("all")||CMLib.english().containsString(item,mask)))
						buf.append(CMStrings.padRight(item,cols[0])+" "+CMStrings.padRight(""+level,cols[1])+" "+CMStrings.padRight(metal1,cols[2])+" "+metal2+"\n\r");
				}
			}
			commonTell(mob,buf.toString());
			return true;
		}
		final Item fire=getRequiredFire(mob,0);
		if(fire==null)
			return false;
		activity = CraftingActivity.CRAFTING;
		buildingI=null;
		messedUp=false;
		String recipeName=CMParms.combine(commands,0);
		int maxAmount=1;
		if((commands.size()>1)&&(CMath.isNumber(commands.get(commands.size()-1))))
		{
			maxAmount=CMath.s_int(commands.get(commands.size()-1));
			commands.remove(commands.size()-1);
			recipeName=CMParms.combine(commands,0);
		}
		List<String> foundRecipe=null;
		final List<List<String>> matches=matchingRecipeNames(recipes,recipeName,true);
		for(int r=0;r<matches.size();r++)
		{
			final List<String> V=matches.get(r);
			if(V.size()>0)
			{
				final int level=CMath.s_int(V.get(RCP_LEVEL));
				if(level<=xlevel(mob))
				{
					foundRecipe=V;
					break;
				}
			}
		}
		if(foundRecipe==null)
		{
			commonTell(mob,L("You don't know how to make '@x1'.  Try \"smelt list\" for a list.",recipeName));
			return false;
		}
		final String doneResourceDesc=foundRecipe.get(RCP_FINALNAME);
		final String resourceDesc1=foundRecipe.get(RCP_METALONE);
		final String resourceDesc2=foundRecipe.get(RCP_METALTWO);
		final int resourceCode1=RawMaterial.CODES.FIND_IgnoreCase(resourceDesc1);
		final int resourceCode2=RawMaterial.CODES.FIND_IgnoreCase(resourceDesc2);
		final int doneResourceCode=RawMaterial.CODES.FIND_IgnoreCase(doneResourceDesc);
		if((resourceCode1<0)||(resourceCode2<0)||(doneResourceCode<0))
		{
			commonTell(mob,L("CoffeeMud error in this alloy.  Please let your local Archon know."));
			return false;
		}
		final int amountResource1=CMLib.materials().findNumberOfResource(mob.location(),RawMaterial.CODES.GET(resourceCode1));
		final int amountResource2=CMLib.materials().findNumberOfResource(mob.location(),RawMaterial.CODES.GET(resourceCode2));
		if(amountResource1==0)
		{
			commonTell(mob,L("There is no @x1 here to make @x2 from.  It might need to be put down first.",resourceDesc1,doneResourceDesc));
			return false;
		}
		if(amountResource2==0)
		{
			commonTell(mob,L("There is no @x1 here to make @x2 from.  It might need to be put down first.",resourceDesc2,doneResourceDesc));
			return false;
		}
		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;
		amountMaking=amountResource1;
		if(amountResource2<amountResource1)
			amountMaking=amountResource2;
		if((maxAmount>0)&&(amountMaking>maxAmount))
			amountMaking=maxAmount;
		CMLib.materials().destroyResourcesValue(mob.location(),amountMaking,RawMaterial.CODES.GET(resourceCode1),0,null);
		CMLib.materials().destroyResourcesValue(mob.location(),amountMaking,RawMaterial.CODES.GET(resourceCode2),0,null);
		duration=getDuration(CMath.s_int(foundRecipe.get(RCP_TICKS)),mob,CMath.s_int(foundRecipe.get(RCP_LEVEL)),6);
		amountMaking+=amountMaking;
		buildingI=(Item)CMLib.materials().makeResource(RawMaterial.CODES.GET(doneResourceCode),null,false,null);
		startStr=L("<S-NAME> start(s) smelting @x1.",doneResourceDesc.toLowerCase());
		displayText=L("You are smelting @x1",doneResourceDesc.toLowerCase());
		playSound="sizzling.wav";
		verb=L("smelting @x1",doneResourceDesc.toLowerCase());

		messedUp=!proficiencyCheck(mob,0,auto);

		final CMMsg msg=CMClass.getMsg(mob,buildingI,this,getActivityMessageType(),startStr);
		if(mob.location().okMessage(mob,msg))
		{
			mob.location().send(mob,msg);
			buildingI=(Item)msg.target();
			beneficialAffect(mob,mob,asLevel,duration);
		}
		return true;
	}
}


text:
package com.mazaiting.crash;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import com.mazaiting.util.CrashLogUtil;
import java.io.File;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 处理异常信息Handler
 * Created by mazaiting on 2017/9/12.
 */
public class CrashHandler implements UncaughtExceptionHandler {
  // 创建当前对象
  private static CrashHandler mHandler = new CrashHandler();
  // 获取当前默认的异常处理器
  // private static final UncaughtExceptionHandler sDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
  // 单线程池
  private static final ExecutorService THREAD_POOL = Executors.newCachedThreadPool();
  // Crash监听
  private CrashListener mCrashListener = null;
  // 异常文件
  private File mExceptionFile = null;

  @Override public void uncaughtException(Thread thread, Throwable throwable) {
    Log.e("TAG", throwable.getMessage());
    CrashLogUtil.writeFile(mExceptionFile, throwable);
    // 线程池执行任务
    THREAD_POOL.execute(new Runnable() {
      @Override public void run() {
        if (null != mCrashListener) {
          mCrashListener.saveCrash(mExceptionFile);
        }
      }
    });
    //sDefaultHandler.uncaughtException(thread, throwable);
  }

  /**
   * 获取实例
   * @return CrashHandler实例
   */
  public static CrashHandler getInstance() {
    return mHandler;
  }

  /**
   * 初始化文件与监听器
   * @param file 文件
   * @param listener 监听器
   */
  public void init(File file, CrashListener listener) {
    this.mExceptionFile = file;
    this.mCrashListener = listener;
    // 处理点击后无反应的状态
    new Handler(Looper.getMainLooper()).post(new Runnable() {
      @Override public void run() {

        while (true) {
          try {
            Looper.loop();
          } catch (Throwable e) {
            if (mHandler != null) {
              mHandler.uncaughtException(Looper.getMainLooper().getThread(), e);
            }
          }
        }
      }
    });
  }
}


text:
set -e

echo "Installing Repository..."
apt-get install -y software-properties-common  python-software-properties
apt-add-repository  -y  ppa:ansible/ansible

echo "Updating Ubuntu ..."
apt-get update -y

echo "Installing Ansible..."
apt-get install -y   ansible

echo "Copying Ansible Configuration..."
cp /vagrant/ansible/ansible.cfg /etc/ansible/ansible.cfg

echo "Script  Endbootstrap_ansible.sh..."