text:
import pytest

from aioelasticsearch import (AIOHttpTransport, ConnectionError,
                              ConnectionTimeout, Elasticsearch, TransportError)
from aioelasticsearch.connection import AIOHttpConnection

class DummyConnection(AIOHttpConnection):
    def __init__(self, **kwargs):
        self.exception = kwargs.pop('exception', None)
        self.status = kwargs.pop('status', 200)
        self.data = kwargs.pop('data', '{}')
        self.headers = kwargs.pop('headers', {})
        self.calls = []
        super().__init__(**kwargs)

    async def perform_request(self, *args, **kwargs):
        self.calls.append((args, kwargs))
        if self.exception:
            raise self.exception
        return self.status, self.headers, self.data

@pytest.mark.run_loop
async def test_custom_serializers(auto_close, loop):
    serializer = object()
    t = auto_close(AIOHttpTransport([{}],
                                    serializers={'test': serializer},
                                    loop=loop))
    assert 'test' in t.deserializer.serializers
    assert t.deserializer.serializers['test'] is serializer

@pytest.mark.run_loop
async def test_no_sniff_on_start(auto_close, loop):
    t = auto_close(AIOHttpTransport([{}], sniff_on_start=False, loop=loop))
    assert t.initial_sniff_task is None

@pytest.mark.run_loop
async def test_sniff_on_start(auto_close, loop, es_server):
    t = auto_close(AIOHttpTransport([{'host': 'unknown_host',
                                      'port': 9200},
                                     {'host': es_server['host'],
                                      'port': es_server['port']}],
                                    http_auth=es_server['auth'],
                                    sniff_on_start=True, loop=loop))
    assert t.initial_sniff_task is not None
    await t.initial_sniff_task
    assert t.initial_sniff_task is None
    assert len(t.connection_pool.connections) == 1

@pytest.mark.run_loop
async def test_close_with_sniff_on_start(loop, es_server):
    t = AIOHttpTransport([{'host': es_server['host'],
                           'port': es_server['port']}],
                         http_auth=es_server['auth'],
                         sniff_on_start=True, loop=loop)
    assert t.initial_sniff_task is not None
    await t.close()
    assert t.initial_sniff_task is None
    assert t._closed

@pytest.mark.run_loop
async def test_get_connection_with_sniff_on_start(auto_close, loop, es_server):
    t = auto_close(AIOHttpTransport([{'host': es_server['host'],
                                      'port': es_server['port']}],
                                    http_auth=es_server['auth'],
                                    sniff_on_start=True, loop=loop))
    conn = await t.get_connection()
    assert conn is not None
    assert t.initial_sniff_task is None

@pytest.mark.run_loop
async def test_get_connection_with_sniffer_timeout(auto_close,
                                                   loop, es_server):
    t = auto_close(AIOHttpTransport([{'host': 'unknown_host',
                                      'port': 9200},
                                     {'host': es_server['host'],
                                      'port': es_server['port']}],
                                    http_auth=es_server['auth'],
                                    sniffer_timeout=10, loop=loop))
    assert t.initial_sniff_task is None
    t.last_sniff -= 15
    conn = await t.get_connection()
    assert conn is not None
    assert t.initial_sniff_task is None
    assert len(t.connection_pool.connections) == 1

@pytest.mark.run_loop
async def test_get_connection_without_sniffer_timeout(auto_close,
                                                      loop, es_server):
    t = auto_close(AIOHttpTransport([{'host': 'unknown_host',
                                      'port': 9200},
                                     {'host': es_server['host'],
                                      'port': es_server['port']}],
                                    http_auth=es_server['auth'],
                                    sniffer_timeout=1e12, loop=loop))
    conn = await t.get_connection()
    assert conn is not None
    assert t.initial_sniff_task is None
    assert len(t.connection_pool.connections) == 2

@pytest.mark.run_loop
async def test_sniff_hosts_error(auto_close, loop, es_server):
    t = auto_close(AIOHttpTransport([{'host': 'unknown_host',
                                      'port': 9200}],
                                    loop=loop))
    with pytest.raises(TransportError):
        await t.sniff_hosts()

@pytest.mark.run_loop
async def test_sniff_hosts_no_hosts(auto_close, loop, es_server):
    t = auto_close(AIOHttpTransport([{'host': es_server['host'],
                                      'port': es_server['port']}],
                                    http_auth=es_server['auth'],
                                    loop=loop))
    t.host_info_callback = lambda host_info, host: None
    with pytest.raises(TransportError):
        await t.sniff_hosts()

@pytest.mark.run_loop
async def test_mark_dead(auto_close, loop, es_server):
    t = auto_close(AIOHttpTransport([{'host': 'unknown_host',
                                      'port': 9200},
                                     {'host': es_server['host'],
                                      'port': es_server['port']}],
                                    http_auth=es_server['auth'],
                                    randomize_hosts=False,
                                    loop=loop))
    conn = t.connection_pool.connections[0]
    assert conn is not None
    assert conn.host == 'http://unknown_host:9200'
    await t.mark_dead(conn)
    assert len(t.connection_pool.connections) == 1

@pytest.mark.run_loop
async def test_mark_dead_with_sniff(auto_close, loop, es_server):
    t = auto_close(AIOHttpTransport([{'host': 'unknown_host',
                                      'port': 9200},
                                     {'host': 'unknown_host2',
                                      'port': 9200},
                                     {'host': es_server['host'],
                                      'port': es_server['port']}],
                                    http_auth=es_server['auth'],
                                    sniff_on_connection_fail=True,
                                    randomize_hosts=False,
                                    loop=loop))
    conn = t.connection_pool.connections[0]
    assert conn is not None
    assert conn.host == 'http://unknown_host:9200'
    await t.mark_dead(conn)
    assert len(t.connection_pool.connections) == 1

@pytest.mark.run_loop
async def test_send_get_body_as_post(es_server, auto_close, loop):
    cl = auto_close(Elasticsearch([{'host': es_server['host'],
                                   'port': es_server['port']}],
                                  send_get_body_as='POST',
                                  http_auth=es_server['auth'],
                                  loop=loop))
    await cl.create('test', '1', {'val': '1'})
    await cl.create('test', '2', {'val': '2'})
    ret = await cl.mget(
        {"docs": [
                {"_id": "1"},
                {"_id": "2"}
        ]},
        index='test',
    )
    assert ret == {'docs': [{'_id': '1',
                             '_index': 'test',
                             '_source': {'val': '1'},
                             '_type': '_doc',
                             '_version': 1,
                             '_primary_term': 1,
                             '_seq_no': 0,
                             'found': True},
                            {'_id': '2',
                             '_index': 'test',
                             '_source': {'val': '2'},
                             '_type': '_doc',
                             '_version': 1,
                             '_primary_term': 1,
                             '_seq_no': 1,
                             'found': True}]}

@pytest.mark.run_loop
async def test_send_get_body_as_source(es_server, auto_close, loop):
    cl = auto_close(Elasticsearch([{'host': es_server['host'],
                                   'port': es_server['port']}],
                                  send_get_body_as='source',
                                  http_auth=es_server['auth'],
                                  loop=loop))
    await cl.create('test', '1', {'val': '1'})
    await cl.create('test', '2', {'val': '2'})
    ret = await cl.mget(
        {"docs": [
                {"_id": "1"},
                {"_id": "2"}
        ]},
        index='test',
    )
    assert ret == {'docs': [{'_id': '1',
                             '_index': 'test',
                             '_source': {'val': '1'},
                             '_type': '_doc',
                             '_version': 1,
                             '_primary_term': 1,
                             '_seq_no': 0,
                             'found': True},
                            {'_id': '2',
                             '_index': 'test',
                             '_source': {'val': '2'},
                             '_type': '_doc',
                             '_version': 1,
                             '_primary_term': 1,
                             '_seq_no': 1,
                             'found': True}]}

@pytest.mark.run_loop
async def test_send_get_body_as_get(es_server, auto_close, loop):
    cl = auto_close(Elasticsearch([{'host': es_server['host'],
                                   'port': es_server['port']}],
                                  http_auth=es_server['auth'],
                                  loop=loop))
    await cl.create('test', '1', {'val': '1'})
    await cl.create('test', '2', {'val': '2'})
    ret = await cl.mget(
        {"docs": [
                {"_id": "1"},
                {"_id": "2"}
        ]},
        index='test',
    )
    assert ret == {'docs': [{'_id': '1',
                             '_index': 'test',
                             '_source': {'val': '1'},
                             '_type': '_doc',
                             '_version': 1,
                             '_primary_term': 1,
                             '_seq_no': 0,
                             'found': True},
                            {'_id': '2',
                             '_index': 'test',
                             '_source': {'val': '2'},
                             '_type': '_doc',
                             '_version': 1,
                             '_primary_term': 1,
                             '_seq_no': 1,
                             'found': True}]}

@pytest.mark.run_loop
async def test_send_get_body_as_source_none_params(es_server,
                                                   auto_close, loop):
    cl = auto_close(Elasticsearch([{'host': es_server['host'],
                                   'port': es_server['port']}],
                                  send_get_body_as='source',
                                  http_auth=es_server['auth'],
                                  loop=loop))
    await cl.create('test', '1', {'val': '1'})
    await cl.create('test', '2', {'val': '2'})
    ret = await cl.transport.perform_request(
        'GET', 'test/_mget',
        body={"docs": [
            {"_id": "1"},
            {"_id": "2"}
        ]})
    assert ret == {'docs': [{'_id': '1',
                             '_index': 'test',
                             '_source': {'val': '1'},
                             '_type': '_doc',
                             '_version': 1,
                             '_primary_term': 1,
                             '_seq_no': 0,
                             'found': True},
                            {'_id': '2',
                             '_index': 'test',
                             '_source': {'val': '2'},
                             '_type': '_doc',
                             '_version': 1,
                             '_primary_term': 1,
                             '_seq_no': 1,
                             'found': True}]}

@pytest.mark.run_loop
async def test_set_connections_closed(es):
    await es.close()
    with pytest.raises(RuntimeError):
        es.transport.set_connections(['host1', 'host2'])

@pytest.mark.run_loop
async def test_sniff_hosts_closed(es):
    await es.close()
    with pytest.raises(RuntimeError):
        await es.transport.sniff_hosts()

@pytest.mark.run_loop
async def test_close_closed(es):
    await es.close()
    await es.close()

@pytest.mark.run_loop
async def test_get_connection_closed(es):
    await es.close()
    with pytest.raises(RuntimeError):
        await es.transport.get_connection()

@pytest.mark.run_loop
async def test_mark_dead_closed(es):
    await es.close()
    conn = object()
    with pytest.raises(RuntimeError):
        await es.transport.mark_dead(conn)

@pytest.mark.run_loop
async def test_perform_request_closed(es):
    await es.close()
    with pytest.raises(RuntimeError):
        await es.transport.perform_request('GET', '/')

@pytest.mark.run_loop
async def test_request_error_404_on_head(loop, auto_close):
    exc = TransportError(404)
    t = AIOHttpTransport([{}], connection_class=DummyConnection, loop=loop,
                         exception=exc)
    auto_close(t)

    ret = await t.perform_request('HEAD', '/')
    assert not ret

@pytest.mark.run_loop
async def test_request_connection_error(loop, auto_close):
    exc = ConnectionError()
    t = AIOHttpTransport([{}], connection_class=DummyConnection, loop=loop,
                         exception=exc)
    auto_close(t)

    with pytest.raises(ConnectionError):
        await t.perform_request('GET', '/')

    conn = await t.get_connection()
    assert len(conn.calls) == 3

@pytest.mark.run_loop
async def test_request_connection_timeout(loop, auto_close):
    exc = ConnectionTimeout()
    t = AIOHttpTransport([{}], connection_class=DummyConnection, loop=loop,
                         exception=exc)
    auto_close(t)

    with pytest.raises(ConnectionTimeout):
        await t.perform_request('GET', '/')

    conn = await t.get_connection()
    assert len(conn.calls) == 1

@pytest.mark.run_loop
async def test_request_connection_timeout_with_retry(loop, auto_close):
    exc = ConnectionTimeout()
    t = AIOHttpTransport([{}], connection_class=DummyConnection, loop=loop,
                         exception=exc, retry_on_timeout=True)
    auto_close(t)

    with pytest.raises(ConnectionTimeout):
        await t.perform_request('GET', '/')

    conn = await t.get_connection()
    assert len(conn.calls) == 3

@pytest.mark.run_loop
async def test_request_retry_on_status(loop, auto_close):
    exc = TransportError(500)
    t = AIOHttpTransport([{}], connection_class=DummyConnection, loop=loop,
                         exception=exc, retry_on_status=(500,))
    auto_close(t)

    with pytest.raises(TransportError):
        await t.perform_request('GET', '/')

    conn = await t.get_connection()
    assert len(conn.calls) == 3

@pytest.mark.run_loop
async def test_request_without_data(loop, auto_close):
    t = AIOHttpTransport([{}], connection_class=DummyConnection, loop=loop,
                         data='')
    auto_close(t)

    ret = await t.perform_request('GET', '/')
    assert ret == ''

@pytest.mark.run_loop
async def test_request_headers(loop, auto_close, es_server, mocker):
    t = auto_close(AIOHttpTransport(
        [{'host': es_server['host'],
          'port': es_server['port']}],
        http_auth=es_server['auth'],
        loop=loop,
        headers={'H1': 'V1', 'H2': 'V2'},
    ))

    for conn in t.connection_pool.connections:
        mocker.spy(conn.session, 'request')

    await t.perform_request('GET', '/', headers={'H1': 'VV1', 'H3': 'V3'})

    session = (await t.get_connection()).session
    _, kwargs = session.request.call_args
    assert kwargs['headers'] == {
        'H1': 'VV1',
        'H2': 'V2',
        'H3': 'V3',
        'Content-Type': 'application/json',
    }


text:
SHELL := /usr/bin/env bash

# Project settings
PROJECT := cf-predict
PACKAGE := cf_predict
SOURCES := Makefile setup.py $(shell find $(PACKAGE) -name '*.py')

# Python settings
ifndef TRAVIS
	PYTHON_MAJOR ?= 3
	PYTHON_MINOR ?= 5
endif

# Test settings
UNIT_TEST_COVERAGE := 80
INTEGRATION_TEST_COVERAGE := 40
COMBINED_TEST_COVERAGE := 80

# System paths
PLATFORM := $(shell python -c 'import sys; print(sys.platform)')
SYS_PYTHON := python

# Conda environment paths
ENV := env
# ACTIVATE := $(shell source activate $(ENV)/)
OPEN := open
BIN := $(ENV)/bin

# Environment executables
ifndef TRAVIS
	BIN_ := $(BIN)/
endif
PYTHON := $(BIN_)python
PIP := $(BIN_)pip
EASY_INSTALL := $(BIN_)easy_install
RST2HTML := $(PYTHON) $(BIN_)rst2html.py
PDOC := $(PYTHON) $(BIN_)pdoc
MKDOCS := $(BIN_)mkdocs
PEP8 := $(BIN_)pep8
PEP8RADIUS := $(BIN_)pep8radius
PEP257 := $(BIN_)pep257
PYLINT := $(BIN_)pylint
PYREVERSE := $(BIN_)pyreverse
NOSE := $(BIN_)nosetests
PYTEST := $(BIN_)py.test
COVERAGE := $(BIN_)coverage
SNIFFER := $(BIN_)sniffer

# Flags for PHONY targets
INSTALLED_FLAG := $(ENV)/.installed
DEPENDS_CI_FLAG := $(ENV)/.depends-ci
DEPENDS_DOC_FLAG := $(ENV)/.depends-doc
DEPENDS_DEV_FLAG := $(ENV)/.depends-dev
DOCS_FLAG := $(ENV)/.docs
ALL_FLAG := $(ENV)/.all

# Main Targets #################################################################

.PHONY: all
all: depends doc $(ALL_FLAG)
$(ALL_FLAG): $(SOURCES)
	$(MAKE) check
	touch $(ALL_FLAG)  # flag to indicate all setup steps were successful

.PHONY: ci
ifdef TRAVIS
ci: check test tests
else
ci: doc check test tests
endif

.PHONY: watch
watch: depends .clean-test
	@ rm -rf $(FAILED_FLAG)
	$(SNIFFER)

.PHONY: deploy
ifdef PORT
deploy: install
	gunicorn --bind 0.0.0.0:$(PORT) cf_predict.wsgi:app
else
deploy: install
	$(PYTHON) -m cf_predict
endif

# Development Installation #####################################################

.PHONY: env
env: $(PIP) $(INSTALLED_FLAG)
$(INSTALLED_FLAG): Makefile setup.py requirements.txt
	VIRTUAL_ENV=$(ENV) $(PYTHON) setup.py develop
	@ touch $(INSTALLED_FLAG)  # flag to indicate package is installed
ifdef TRAVIS
$(PIP):
	if [ -n "$(CONDA_ENV_PATH)" ]; then . $(TRAVIS_BUILD_DIR)/$(BIN)/deactivate; else exit 0; fi && conda remove -p $(TRAVIS_BUILD_DIR)/$(ENV) --all -y
	$(HOME)/anaconda/bin/conda create -y -p $(TRAVIS_BUILD_DIR)/$(ENV)/ -q python=$(TRAVIS_PYTHON_VERSION) numpy scikit-learn pip wheel flask
	source activate $(TRAVIS_BUILD_DIR)/$(ENV)/ && $(TRAVIS_BUILD_DIR)/$(BIN)/$(PIP) install flask-restful flask-redis mockredispy coveralls
else
$(PIP):
	if [ -n "$(CONDA_ENV_PATH)" ]; then . $(BIN)/deactivate; else exit 0; fi && conda remove -p $(ENV) --all -y
	$(HOME)/anaconda/bin/conda create -y -p $(ENV) -q python=$(PYTHON_MAJOR).$(PYTHON_MINOR) numpy scikit-learn pip wheel flask
	source activate $(ENV)/ && $(PIP) install flask-restful flask-redis mockredispy && \
	$(PIP) install --upgrade pip
endif

# Tools Installation ###########################################################

.PHONY: depends
depends: depends-ci depends-doc depends-dev

.PHONY: depends-ci
depends-ci: env Makefile $(DEPENDS_CI_FLAG)
$(DEPENDS_CI_FLAG): Makefile
	$(PIP) install --upgrade pep8 pep257 pylint coverage coveralls pytest pytest-describe pytest-expecter pytest-cov pytest-random
	@ touch $(DEPENDS_CI_FLAG)  # flag to indicate dependencies are installed

.PHONY: depends-doc
depends-doc: env Makefile $(DEPENDS_DOC_FLAG)
$(DEPENDS_DOC_FLAG): Makefile
	$(PIP) install --upgrade pylint docutils readme pdoc mkdocs pygments
	@ touch $(DEPENDS_DOC_FLAG)  # flag to indicate dependencies are installed

.PHONY: depends-dev
depends-dev: env Makefile $(DEPENDS_DEV_FLAG)
$(DEPENDS_DEV_FLAG): Makefile
	$(PIP) install --upgrade pip pep8radius wheel sniffer
ifdef WINDOWS
	$(PIP) install --upgrade pywin32
else ifdef MAC
	$(PIP) install --upgrade pync MacFSEvents==0.4
else ifdef LINUX
	$(PIP) install --upgrade pyinotify
endif
	@ touch $(DEPENDS_DEV_FLAG)  # flag to indicate dependencies are installed

# Documentation ################################################################

.PHONY: doc
doc: readme verify-readme uml apidocs mkdocs

.PHONY: doc-live
doc-live: doc
	eval "sleep 3; open http://127.0.0.1:8000" &
	$(MKDOCS) serve

.PHONY: read
read: doc
	$(OPEN) site/index.html
	$(OPEN) apidocs/$(PACKAGE)/index.html
	$(OPEN) README-pypi.html
	$(OPEN) README-github.html

.PHONY: readme
readme: depends-doc README-github.html README-pypi.html
README-github.html: README.md
	pandoc -f markdown_github -t html -o README-github.html README.md
README-pypi.html: README.rst
	$(RST2HTML) README.rst README-pypi.html
%.rst: %.md
	pandoc -f markdown_github -t rst -o $@ $<

.PHONY: verify-readme
verify-readme: $(DOCS_FLAG)
$(DOCS_FLAG): README.rst CHANGES.rst
	$(PYTHON) setup.py check --restructuredtext --strict --metadata
	@ touch $(DOCS_FLAG)  # flag to indicate README has been checked

.PHONY: uml
uml: depends-doc docs/*.png
docs/*.png: $(SOURCES)
	$(PYREVERSE) $(PACKAGE) -p $(PACKAGE) -a 1 -f ALL -o png --ignore test
	- mv -f classes_$(PACKAGE).png docs/classes.png
	- mv -f packages_$(PACKAGE).png docs/packages.png

.PHONY: apidocs
apidocs: depends-doc apidocs/$(PACKAGE)/index.html
apidocs/$(PACKAGE)/index.html: $(SOURCES)
	$(PDOC) --html --overwrite $(PACKAGE) --html-dir apidocs

.PHONY: mkdocs
mkdocs: depends-doc site/index.html
site/index.html: mkdocs.yml docs/*.md
	$(MKDOCS) build --clean --strict

# Static Analysis ##############################################################

.PHONY: check
check: pep8 pep257 pylint

.PHONY: pep8
pep8: depends-ci
	$(PEP8) $(PACKAGE) tests --config=.pep8rc

.PHONY: pep257
pep257: depends-ci
	$(PEP257) $(PACKAGE) tests

.PHONY: pylint
pylint: depends-ci
	$(PYLINT) $(PACKAGE) tests --rcfile=.pylintrc

.PHONY: fix
fix: depends-dev
	$(PEP8RADIUS) --docformatter --in-place

# Testing ######################################################################

RANDOM_SEED ?= $(shell date +%s)

PYTEST_CORE_OPTS := -r xXw -vv
PYTEST_COV_OPTS := --cov=$(PACKAGE) --no-cov-on-fail --cov-report=term-missing
PYTEST_RANDOM_OPTS := --random --random-seed=$(RANDOM_SEED)

PYTEST_OPTS := $(PYTEST_CORE_OPTS) $(PYTEST_COV_OPTS) $(PYTEST_RANDOM_OPTS)
PYTEST_OPTS_FAILFAST := $(PYTEST_OPTS) --failed --exitfirst

FAILED_FLAG := .pytest/failed

.PHONY: test test-unit
test: test-unit
test-unit: depends-ci
	$(PYTEST) $(PYTEST_OPTS) $(PACKAGE)
ifndef TRAVIS
	$(COVERAGE) html --directory htmlcov --fail-under=$(UNIT_TEST_COVERAGE)
endif

.PHONY: test-int
test-int: depends-ci
	@ if test -e $(FAILED_FLAG); then $(MAKE) test-all; fi
	$(PYTEST) $(PYTEST_OPTS_FAILFAST) tests
ifndef TRAVIS
	@ rm -rf $(FAILED_FLAG)  # next time, don't run the previously failing test
	$(COVERAGE) html --directory htmlcov --fail-under=$(INTEGRATION_TEST_COVERAGE)
endif

.PHONY: tests test-all
tests: test-all
test-all: depends-ci
	@ if test -e $(FAILED_FLAG); then $(PYTEST) --failed $(PACKAGE) tests; fi
	$(PYTEST) $(PYTEST_OPTS_FAILFAST) $(PACKAGE) tests
ifndef TRAVIS
	@ rm -rf $(FAILED_FLAG)  # next time, don't run the previously failing test
	$(COVERAGE) html --directory htmlcov --fail-under=$(COMBINED_TEST_COVERAGE)
endif

.PHONY: read-coverage
read-coverage:
	$(OPEN) htmlcov/index.html

# Cleanup ######################################################################

.PHONY: clean
clean: .clean-dist .clean-test .clean-doc .clean-build
	rm -rf $(ALL_FLAG)

.PHONY: clean-all
clean-all: clean .clean-env

.PHONY: .clean-build
.clean-build:
	find $(PACKAGE) tests -name '*.pyc' -delete
	find $(PACKAGE) tests -name '__pycache__' -delete
	rm -rf $(INSTALLED_FLAG) *.egg-info

.PHONY: .clean-doc
.clean-doc:
	rm -rf README.rst apidocs *.html docs/*.png

.PHONY: .clean-test
.clean-test:
	rm -rf .pytest .coverage htmlcov

.PHONY: .clean-dist
.clean-dist:
	rm -rf dist build

.PHONY: .clean-env
.clean-env: clean
	@ if [ -n "$(CONDA_ENV_PATH)" ]; then . $(BIN)/activate root; else exit 0; fi
	rm -rf $(ENV)

# Release ######################################################################

.PHONY: register-test
register-test: doc
	$(PYTHON) setup.py register --strict --repository https://testpypi.python.org/pypi

.PHONY: upload-test
upload-test: register-test
	$(PYTHON) setup.py sdist upload --repository https://testpypi.python.org/pypi
	$(PYTHON) setup.py bdist_wheel upload --repository https://testpypi.python.org/pypi
	$(OPEN) https://testpypi.python.org/pypi/$(PROJECT)

.PHONY: register
register: doc
	$(PYTHON) setup.py register --strict

.PHONY: upload
upload: .git-no-changes register
	$(PYTHON) setup.py sdist upload
	$(PYTHON) setup.py bdist_wheel upload
	$(OPEN) https://pypi.python.org/pypi/$(PROJECT)

.PHONY: .git-no-changes
.git-no-changes:
	@ if git diff --name-only --exit-code;        \
	then                                          \
		echo Git working copy is clean...;        \
	else                                          \
		echo ERROR: Git working copy is dirty!;   \
		echo Commit your changes and try again.;  \
		exit -1;                                  \
	fi;

# System Installation ##########################################################

.PHONY: develop
develop:
	$(SYS_PYTHON) setup.py develop

.PHONY: install
install:
	$(SYS_PYTHON) setup.py install

.PHONY: download
download:
	$(SYS_PYTHON) -m pip install $(PROJECT)

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annls mycol. 35: 74 (1937)

#### Original name
Meliola convallata Petr.

### Remarks
null


text:
package uk.gov.nationalarchives.droid.command.action;

import java.io.PrintWriter;

import org.apache.commons.cli.HelpFormatter;

import static uk.gov.nationalarchives.droid.command.i18n.I18N.getResource;

import uk.gov.nationalarchives.droid.command.i18n.I18N;

/**
 * @author rflitcroft
 *
 */
public class HelpCommand implements DroidCommand {

    /** Options message. */
    public static final String USAGE = "droid [options]";
    /** Wrap width. */
    public static final int WRAP_WIDTH = 79;

    private PrintWriter writer;

    /**
     * @param writer a print writer
     */
    public HelpCommand(PrintWriter writer) {
        this.writer = writer;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void execute() {
        HelpFormatter formatter = new HelpFormatter();
/*        formatter.setOptionComparator(
            new Comparator() {
                public int compare(Object o1, Object o2) {
                    Option opt1 = (Option)o1;
                    Option opt2 = (Option)o2;
                    return opt2.getKey().compareToIgnoreCase(opt1.getKey());
                }
        }); */

        //CHECKSTYLE:OFF

        formatter.printHelp(writer, WRAP_WIDTH, USAGE,
                getResource(I18N.OPTIONS_HEADER), CommandLineParam.singleOptions(), 2, 3, null);
        formatter.printOptions(writer, WRAP_WIDTH,
                CommandLineParam.getOptions(CommandLineParam.RUN_NO_PROFILE), 2, 2);
        formatter.printOptions(writer, WRAP_WIDTH,
                CommandLineParam.noProfileRunSubOptions(), 5, 3);
        formatter.printOptions(writer, WRAP_WIDTH,
                CommandLineParam.getOptions(CommandLineParam.RUN_PROFILE), 2, 2);
        formatter.printOptions(writer, WRAP_WIDTH,
                CommandLineParam.profileRunSubOptions(), 5, 7);
        formatter.printOptions(writer, WRAP_WIDTH,
                CommandLineParam.getOptions(CommandLineParam.EXPORT_ONE_ROW_PER_FILE), 2, 9);
        formatter.printOptions(writer, WRAP_WIDTH,
                CommandLineParam.exportSubOptions(), 5, 7);
        formatter.printOptions(writer, WRAP_WIDTH,
                CommandLineParam.getOptions(CommandLineParam.EXPORT_ONE_ROW_PER_FORMAT), 2, 7);
        formatter.printOptions(writer, WRAP_WIDTH,
                CommandLineParam.exportSubOptions(), 5, 7);
        formatter.printOptions(writer, WRAP_WIDTH,
                CommandLineParam.getOptions(CommandLineParam.REPORT), 2, 14);
        formatter.printOptions(writer, WRAP_WIDTH,
                CommandLineParam.reportSubOptions(), 5, 6);

        //CHECKSTYLE:ON
    }
}


text:
<?php echo lang('edit_user_heading');?>

<?php echo lang('edit_user_subheading');?>

<?php echo $message;?>

<?php echo form_open(uri_string());?>

          <?php echo lang('edit_user_uname_label', 'username');?>

            <?php echo form_input($username);?>

            <?php echo lang('edit_user_email_label', 'email');?>

            <?php echo form_input($email);?>

            <?php echo lang('edit_user_phone_label', 'phone');?>

            <?php echo form_input($phone);?>

            <?php echo lang('edit_user_password_label', 'password');?>

            <?php echo form_input($password);?>

            <?php echo lang('edit_user_password_confirm_label', 'password_confirm');?>

            <?php echo form_input($password_confirm);?>

      <?php if ($this->ion_auth->is_admin()): ?>

<?php echo lang('edit_user_groups_heading');?>

          <?php foreach ($groups as $group):?>

              <?php
                  $gID=$group['id'];
                  $checked = null;
                  $item = null;
                  foreach($currentGroups as $grp) {
                      if ($gID == $grp->id) {
                          $checked= ' checked="checked"';
                      break;
                      }
                  }
              ?>
              <input type="checkbox" name="groups[]" value="<?php echo $group['id'];?>"<?php echo $checked;?>>
              <?php echo htmlspecialchars($group['name'],ENT_QUOTES,'UTF-8');?>

          <?php endforeach?>

      <?php endif ?>

      <?php echo form_hidden('id', $user->id);?>
      <?php echo form_hidden($csrf); ?>

<?php echo form_submit('submit', lang('edit_user_submit_btn'));?>

<?php echo form_close();?>


text:
package com.izforge.izpack.installer.automation;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.izforge.izpack.api.adaptator.IXMLElement;
import com.izforge.izpack.api.data.AutomatedInstallData;
import com.izforge.izpack.installer.panel.AbstractPanels;
import com.izforge.izpack.installer.panel.Panels;

/**
 * Implementation of {@link Panels} for {@link AutomatedPanelView}.
 *
 * @author Tim Anderson
 */
public class AutomatedPanels extends AbstractPanels<AutomatedPanelView, PanelAutomation>
{

    /**
     * The installation data.
     */
    private final AutomatedInstallData installData;

    /**
     * The logger.
     */
    private static final Logger logger = Logger.getLogger(AutomatedPanels.class.getName());

    /**
     * Constructs an {@code AutomatedPanels}.
     *
     * @param panels      the panels
     * @param installData the installation data
     */
    public AutomatedPanels(List<AutomatedPanelView> panels, AutomatedInstallData installData)
    {
        super(panels, installData);
        this.installData = installData;
    }

    /**
     * Switches panels.
     *
     * @param newPanel the panel to switch to
     * @param oldPanel the panel to switch from, or {@code null} if there was no prior panel
     * @return {@code true} if the switch was successful
     */
    @Override
    protected boolean switchPanel(AutomatedPanelView newPanel, AutomatedPanelView oldPanel)
    {
        boolean result;
        if (newPanel.getViewClass() == null)
        {
            // panel has no view. This is apparently OK - not all panels have/need automation support.
            logger.warning("AutomationHelper class not found for panel class: " + newPanel.getPanel().getClassName());
            result = executeValidationActions(newPanel, true);
        }
        else
        {
        	PanelAutomation view = newPanel.getView();
            newPanel.executePreActivationActions();

            IXMLElement xml = installData.getInstallationRecordPanelRoot(newPanel.getPanelId());
            if (xml != null)
            {
                view.runAutomated(installData, xml);
                result = executeValidationActions(newPanel, true);
            }
            else
            {
                logger.log(Level.SEVERE, "No configuration for panel: " + newPanel.getPanel().getPanelId());
                result = false;
            }
        }
        return result;
    }
}


text:
namespace Diamond.Block
{
    public class BlockShulkerBoxYellow : Block
    {
    }
}


text:
static CCriticalSection cs_nTimeOffset;
static uint32_t NOVACOIN_TIMEDATA_MAX_SAMPLES = 200;

// Trusted NTP offset or median of NTP samples.
extern int64_t nNtpOffset;

// Median of time samples given by other nodes.
static int64_t nNodesOffset = std::numeric_limits<int64_t>::max();

//
// "Never go to sea with two chronometers; take one or three."
// Our three time sources are:
//  - System clock
//  - Median of other nodes clocks
//  - The user (asking the user to fix the system clock if the first two disagree)
//

// Select time offset:
int64_t GetTimeOffset()
{
    LOCK(cs_nTimeOffset);
    // If NTP and system clock are in agreement within 40 minutes, then use NTP.
    if (std::abs(nNtpOffset) < 40 * 60)
        return nNtpOffset;

    // If not, then choose between median peer time and system clock.
    if (std::abs(nNodesOffset) < 70 * 60)
        return nNodesOffset;

    return 0;
}

int64_t GetNodesOffset()
{
        return nNodesOffset;
}

int64_t GetAdjustedTime()
{
    return GetTime() + GetTimeOffset();
}

void AddTimeData(const CNetAddr& ip, int64_t nTime)
{
    int64_t nOffsetSample = nTime - GetTime();

    LOCK(cs_nTimeOffset);
    // Ignore duplicates
    static std::set<CNetAddr> setKnown;
    if (setKnown.size() == NOVACOIN_TIMEDATA_MAX_SAMPLES)
        return;
    if (!setKnown.insert(ip).second)
        return;

    // Add data
    static CMedianFilter<int64_t> vTimeOffsets(NOVACOIN_TIMEDATA_MAX_SAMPLES,0);
    vTimeOffsets.input(nOffsetSample);
    printf("Added time data, samples %d, offset %+" PRId64 " (%+" PRId64 " minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
    if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
    {
        int64_t nMedian = vTimeOffsets.median();
        std::vector<int64_t> vSorted = vTimeOffsets.sorted();
        // Only let other nodes change our time by so much
        if (std::abs(nMedian) < 70 * 60)
        {
            nNodesOffset = nMedian;
        }
        else
        {
            nNodesOffset = std::numeric_limits<int64_t>::max();

            static bool fDone;
            if (!fDone)
            {
                bool fMatch = false;

                // If nobody has a time different than ours but within 5 minutes of ours, give a warning
                for (int64_t nOffset : vSorted)
                    if (nOffset != 0 && std::abs(nOffset) < 5 * 60)
                        fMatch = true;

                if (!fMatch)
                {
                    fDone = true;
                    std::string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong NovaCoin will not work properly.");
                    strMiscWarning = strMessage;
                    printf("*** %s\n", strMessage.c_str());
                    uiInterface.ThreadSafeMessageBox(strMessage+" ", std::string("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION);
                }
            }
        }
        if (fDebug) {
            for (int64_t n : vSorted)
                printf("%+" PRId64 "  ", n);
            printf("|  ");
        }
        if (nNodesOffset != std::numeric_limits<int64_t>::max())
            printf("nNodesOffset = %+" PRId64 "  (%+" PRId64 " minutes)\n", nNodesOffset, nNodesOffset/60);
    }
}


text:
#include<iostream>
#include<iomanip>

#include <configment/undefined.h>
#include <configment/none.h>
#include <configment/int.h>
#include <configment/float.h>
#include <configment/bool.h>
#include <configment/str.h>
#include <configment/pathname.h>
#include <configment/list.h>
#include <configment/tuple.h>
#include <configment/mapping.h>
#include <configment/config.h>
#include <configment/configspec.h>
#include <configment/parser.h>

using namespace std;
using namespace configment;

#include "create_md.h"

int main(int argc, char ** argv)
{
    //cout << "WARNING! DebugInfo::set_visible(true)" << endl;
    //DebugInfo::set_visible(true); // not visible, to avoid differences in the output

BEGIN_H1("Configment")
//HEAD: [![Build Status](https://travis-ci.org/simone-campagna/Configment.svg?branch=master)](https://travis-ci.org/simone-campagna/Configment)
//HEAD: [![Coverage Status](https://coveralls.io/repos/simone-campagna/Configment/badge.png?branch=master)](https://coveralls.io/r/simone-campagna/Configment?branch=master)
//HEAD:
//HEAD: Configment is a C++ library to read/write files with a format similar to the python *ConfigObj* library (see http://www.voidspace.org.uk/python/configobj.html; see also https://github.com/simone-campagna/configobj-py3 for a python3 porting of ConfigObj).
//HEAD: It is not intended to provide a general serialization library between python and C++ applications, but it allows reading and writing the same config files.
//HEAD:
//HEAD: The C++ interface is similar to the *OpenContainers* library that is distributed together with the excellent *PicklingTools* (see http://picklingtools.com/).
//HEAD: Configment provides also the _argparser_ library, which can be used to parse command line arguments. It has almost the same functionalities as the python `argparse` module. It can set arguments from command line, environment variables and configuration files.

//HEAD: Configment introduces also some new functionalities to the ConfigObj library: the configspec format has the following extensions:
//HEAD:  * _pathname_ check: checks for relative and absolute paths;
//HEAD:  * _ __base_dir__ _ key: sets the base directory for relative paths in the section;
//HEAD:  * _ __validate__ _ key: allows to enable/disable validation of the section;
//HEAD: These extensions are made available also to python by the [py-configment](https://github.com/simone-campagna/py-configment "py-configment") project.

//HEAD:
//HEAD: _Configment_ offers three ways to serialize simple objects and to exchange them between c++ and python applications:
//HEAD:  * the _repr_ serialization, corresponding to the *PicklingTools* _SERIALIZE_TEXT_;
//HEAD:  * the _pretty_ serialization, corresponding to the *PicklingTools* _SERIALIZE_PRETTY_;
//HEAD:  * the _dump_ serialization, corresponding to the *ConfigObj* format.

//HEAD:
//HEAD: While the _repr_ and _pretty_ serializations are available for any _Configment_ object, the _dump_ serialization is available only for _Configs_ and _Sections_, since it is does not make sense for other types.
//HEAD:
//HEAD: As an example, consider a dictionary having the keys
//HEAD:  * `"alpha"` (string) with value `10` (integer), and
//HEAD:  * `"beta"`  (string) with value `True` (boolean).
//HEAD:
//HEAD: Its _repr_ serialization is the string `{"alpha": 10, "beta": True}`; its _pretty_ serialization is the multi-line string:
//HEAD: ```
//HEAD: {
//HEAD: 	"alpha": 10,
//HEAD:		"beta": True
//HEAD: }
//HEAD: ```
//HEAD: This is an example of configuration file using the *ConfigObj* format (the _dump_ serialization):
//HEAD_INCLUDE_FILE: example.config
//HEAD:
//HEAD: It can be loaded to obtain a _Config_ object, that is a particular kind of dictionary. In the example, the _config_ object contains the _main_ _Section_, which is a sub-dictionary. The _main_ _Section_ itself contains two sub-sections named _alpha_ and _beta_. A _Section_ can contain other _Sections_, or any kind of key/value pairs; for instance, _main_ has the key _a_float_ with the floating point value `10.5`.
//HEAD:
//HEAD: _Configs_ can be validated; in this case it is necessary to have a _Configspec_ instance. A _Configspec_ describes the schema of a _Config_ file. As an example:
//HEAD_INCLUDE_FILE: example.configspec
//HEAD:
//HEAD: The config file `example.config` does not fully respect the `example.configspec` schema; for instance, the value for the key "a_float" is 10.5, which is greater than 10.0. Validating this config file with respect to the `example.confispec` will produce some validation errors (see below for the full example).
//HEAD:
BREAK
//HEAD: The python dictionaries require an hashable type as key. For instance, python _dict_ cannot have a _list_ key, since python _lists_ are not hashable. The _Configment_ mappings ( _Dict_, _Section_, _Config_) do not have such limitation, you can use any _Object_ instance as key. So be careful, since some _Configment_ dictionaries cannot be deserialized in python.
//HEAD:
//HEAD: Given a configspec file, it can be used to compile a specific c++ library to write/read config files having that format. The produced library declares a specific struct, with the advantage of having a strict static type checking, as usual in c++. The library can be produced through the utility `configment_compile_libstruct`.
//HEAD: This conversion to a struct-based library has some limitations. For instance, only scalar types and homogeneous lists are supported.
END

BEGIN_H3("Object")
//HEAD: The library is based on the polymorphic type _Object_. There are four scalar types:
//HEAD:  * _Bool_, the type to represent integer values (python: _bool_, c++: _bool_); two string literals are defined: _True_ and _False_;
//HEAD:  * _Int_, the type to represent integer values (python: _int_, c++: _int_)
//HEAD:  * _Float_, the type to represent floating point values (python: _float_, c++: _double_)
//HEAD:  * _Str_, the type to represent strings (python: _str_, c++: _std::string_)
//HEAD:
//HEAD: There are two additional "singleton" scalar classes:
//HEAD:  * _NONE_ (class _None_) is equivalent to the python _None_ object;
//HEAD:  * _UNDEFINED_ (class _Undefined_) is a new object, which is used to represent an invalid value (when _NONE_ is an acceptable value).
//HEAD:
//HEAD: The additional _Pathname_ class can be used to store paths. A _Pathname_ is a string that behaves as a path. It can store an absolute path, or a relative path and its base dir.
//HEAD:  * _Path_, the type to represent strings describing paths.
//HEAD:
    Bool b_value = false;
    cout << b_value << endl;

    Int i_value = 10;
    cout << i_value << endl;

    Float f_value = 0.0405;
    cout << f_value << endl;

    Str s_value = "Hello, world!";
    cout << s_value << endl;

    cout << NONE << endl;

    cout << UNDEFINED << endl;
END

BEGIN_H3("Converting Objects to strings and printing objects")
//HEAD: There are three ways to converto Objects to strings:
//HEAD:  * _str_ the usual representation of the Object as string; this is the way we usually want to print Objects;
//HEAD:  * _repr_ is the representation of an Object as string literal
//HEAD:  * _pretty_ is a nicer representation of the _repr_, on multiple lines and using indentation.
//HEAD:
//HEAD: Except for Str objects, _str_ and _repr_ are the same. For Str objects, the _repr_ representation includes the '"' symbols.
//HEAD: The _pretty_ representation is the same as the _repr_ for scalar types (Str, Int, Float and None); it is different for the containers (Tuple, List, Dict).
    Str s("Hello, world!");
    cout << "=== str(s) is: " << str(s) << endl;
    cout << "=== repr(s) is: " << repr(s) << endl;
    cout << "=== pretty(s) is: " << pretty(s) << endl;

BREAK
//HEAD: The standard way to print object is with "str":
    cout << "=== `cout << s << endl;` gives " << endl;
    cout << s << endl;

BREAK
//HEAD: _str_, _repr_ and _pretty_ are available as external functions and as methods:
    cout << "=== repr(s) is " << repr(s) << endl;
    cout << "=== s.repr() is " << s.repr() << endl;
END

BEGIN_H2("Containers")
//HEAD: The library provides four containers, two _Sequences_ and two _Mappings_; the hierarchy is:
//HEAD:  * _Container_:
//HEAD:    * _Sequence_:
//HEAD:      * _List_, a  mutable container implementing the _append_ method (python: _list_, c++: ~ _std::vector_);
//HEAD:      * _Tuple_, a _List_ whose size cannot change (python: ~ _tuple_, c++: ~ _std::vector_);
//HEAD:    * _Mapping_:
//HEAD:      * _Dict_, a  dictionary (python: _dict_, c++: ~ _std::map_);
//HEAD:      * _Section_, a  dictionary used to store configuration data.
//HEAD:
//HEAD: All these containers can be converted to string as in python, with _str_ and _repr_; in addition, the _pretty_ method generates a prettier representation.
//HEAD: All these containers are heterogeneous; for instance, a _Dict_ can have keys and values of any _Object_ type.
//HEAD: The _Dict_ dictionary is ordered like the python _collections.OrderedDict_: keys are kept in insertion order.
//HEAD:
//HEAD: Notice that the _Tuple_ container is not an immutable _List_: indeed, _Tuple_ items can be changed. Only the size of the container is immutable.

END

BEGIN_H3("List")
    List l;
    l.append("10");
    l.append("string_item");
    cout << "=== l is: " << l << endl;
    cout << "=== str(l) is: " << str(l) << endl;
    cout << "=== repr(l) is: " << repr(l) << endl;
    cout << "=== pretty(l) is:\n" << pretty(l) << endl;
END

BEGIN_H3("Tuple")
//HEAD: Since _Tuple_ objects are immutable, the only way to give them a content is through the constructor:
    Tuple t(l);
    cout << "=== t is: " << t << endl;
//HEAD: Then, you can change their content, but not their size (you cannot add or remove items):
    t[1] = "changed_item";
    cout << "=== t is: " << t << endl;
END

BEGIN_H3("Dict")
    Dict d;
    d["y"] = 0.5;
    d["x"] = 100;
    d[t] = l;
    d["a list"] = List();
    d["a list"].append(4);
    cout << "=== d is: " << d << endl;
END

BEGIN_H3("Referencing objects")
//HEAD: All the containers provide _operator []_ and _at_ methods or iterators that return references to the value instances. Since _Object_ is a polymorphic type, these references can be used to access and modify the contained value:

    Object & l_ref = d["a list"];
    l_ref.append("4");
    cout << "=== l_ref is: " << l_ref << endl;
    cout << "=== d is: " << d << endl;

//TAIL: The container has been modified too.
BREAK
//HEAD: In general, every object can be referenced through an _Object &_ (or pointed through an _Object *_).

    Str a_string("alpha");
    Object & a_reference_to_a_string = a_string;
    cout << "=== a_reference_to_a_string is: " << a_reference_to_a_string << endl;
END

BEGIN_H3("Copying objects")
//HEAD: You may want to copy objects instead of referencing them. For instance, suppose you want to have a copy of the `d["a list"]` object. You can simply assign it to an _Object_ instance:
//HEAD:

    Object l_object = d["a list"];
    cout << "=== d[\"a list\"] is: " << d["a list"] << endl;
    cout << "=== *l_object is: " << l_object << endl;
    l_object.append("new element");
    cout << "=== d[\"a list\"] is: " << d["a list"] << endl;
    cout << "=== *l_object is: " << l_object << endl;
//TAIL: As expected, the `d` object did not change. The same happens if you assign the object to a mapping or sequence item.

END

BEGIN_H3("Undefined")
//HEAD: When accessing an undefined key on a _Dict_, the key is inserted with the special _UNDEFINED_ value:
    cout << "=== d[\"an undefined key\"] is: " << d["an undefined key"] << endl;
    cout << "=== now d is: " << d << endl;
END

BEGIN_H3("The _unrepr_ function")
//HEAD: It is possible to create Objects from their string representation. The _unrepr_ function does the magic! It is particularly useful to construct complex containers from strings:
    std::string s0 = "{(1,2,3) : 10.5,'alpha': 6,45:0.1}";
    cout << "===unrepr(\"" << s0 << "\") is: " << unrepr(s0) << endl;
BREAK
//HEAD: You can also _unrepr_ a _pretty_ representation of any _Object_. This can be useful to serialize an _Object_ to a human readable file, and then to restore it:
//HEAD: Since the _repr_ (or _pretty_) serialization is the same as for the corresponding python objects, it can be used to exchange objects between the two languages.
//HEAD: The string obtained by the Configment _repr_ or _pretty_ functions can be evaluated in python (with the built-in `eval` function) to obtain the corresponding object; and, vice versa, if a python object includes only _bool_, _int_, _float_, _str_, _None_, _list_, _tuple_ and _dict_, its _repr_ can be loaded in a c++ application using the _unrepr_ function.
//HEAD: As said before, _Configment_ dictionaries can have any _Object_ instance as key, while python dictionaries require hashable types. So, be careful when exchanging dictionaries between c++ and python.
//HEAD: Notice also that `{"alpha": 1, "beta": 2}` is always deserialized to an ordered dict ( _Dict_ ) by _Configment_, and to an unordered dict ( _dict_ ) in python.

BREAK
//HEAD: You can use an _Object_ instance to store the _unrepr_ result:
    Object o = unrepr(s0);
    cout << "===o is: " << o << endl;
    cout << "===o[45] is: " << o[45] << endl;

END

BEGIN_H3("Inspecting the object types")
//HEAD: _Configment_ provides some tools for introspection of live objects.
//HEAD: The template is<class> method can be used to inspect the actual type of an _Object_ instance:
//HEAD:  * is<None>()
//HEAD:  * is<Undefined>()
//HEAD:  * is<Int>()
//HEAD:  * is<Bool>()
//HEAD:  * is<Str(>)
//HEAD:  * is<Container>()
//HEAD:  * is<Sequence>()
//HEAD:  * is<Tuple>()
//HEAD:  * is<List>()
//HEAD:  * is<Mapping>()
//HEAD:  * is<Dict>()
//HEAD:  * is<Config>()
//HEAD:  * is<Section>()
//HEAD:  * is<Scalar>()
//HEAD:  * is<Numeric>()
//HEAD:

    Object & o0 = d["a list"];
    cout << "=== o0 is:			" << o0 << endl;
    cout << "=== o0.is<Int>() is:	" << o0.is<Int>() << endl;
    cout << "=== o0.is<None>() is:	" << o0.is<None>() << endl;
    cout << "=== o0.is<Container>() is:	" << o0.is<Container>() << endl;
    cout << "=== o0.is<Sequence>() is:	" << o0.is<Sequence>() << endl;
    cout << "=== o0.is<List>() is:	" << o0.is<List>() << endl;
    cout << "=== o0.is<Tuple>() is:	" << o0.is<Tuple>() << endl;
    cout << "=== o0.is<Mapping>() is:	" << o0.is<Mapping>() << endl;
    cout << "=== o0.is<Dict>() is:	" << o0.is<Dict>() << endl;
    cout << "=== o0.is<Container>() is:	" << o0.is<Container>() << endl;
    cout << "=== o0.is<Scalar>() is:	" << o0.is<Scalar>() << endl;
    cout << "=== o0.is<Numeric>() is:	" << o0.is<Numeric>() << endl;

//TAIL: The actual value ov _o0_ is a _List_, so `o0.is<List>()` is `True`. And since _List_ is a _Sequence_, and a _Sequence_ is a _Container_, `o0.is<Container>()` and `o0.is<Sequence>()` are `True` too.

BREAK
//HEAD: If you want to know if an _Object_ instance has the _Sequence_ interface, the _is<Sequence>()_ method is fine. But if you want to know the exact class of an _Object_, you can inspect its _class name()_:

    cout << "=== o0.class_name() is: " << o0.class_name() << endl;

BREAK
//HEAD: _Object_ objects implement also the `Object & get_object()` and `const Object & get_object() const` methods, returning a (const) reference to the held object:

    cout << "=== o0.get_object().is<Tuple>() is: " << o0.get_object().is<Tuple>() << endl;
    cout << "=== o0.get_object().is<List>() is: " << o0.get_object().is<List>() << endl;
    cout << "=== o0.get_object().class_name() is: " << o0.get_object().class_name() << endl;

BREAK
//HEAD: The `is_instance<BASE>` template is also available; it simply returns _true_ if the argument class is `BASE` or inherits from it. This template is not specific of the _Object_ hierarchy, and works with any class hierarchy.

    cout << "=== is_instance<List>(o0) is: " << is_instance<List>(o0) << endl;
    cout << "=== is_instance<List>(o0.get_object()) is: " << is_instance<List>(o0.get_object()) << endl;

END

BEGIN_H3("Instantiating containers from a repr")
//HEAD: It is possible to instantiate a container object by passing to the constructor its _repr_:
    List l_o("[1, 2, 5]");
    cout << "=== l_o is: " << l_o << endl;
END

BEGIN_H3("Iterating over containers")
//HEAD: You can iterate over containers, for instance:
    cout << "=== remember that d is:" << d << endl;
    cout << "=== iterating over d:" << endl;
    for(Dict::const_iterator i = d.begin(); i != d.end(); ++i)
    {
        cout << "    " << repr(i->first) << " = " << repr(i->second) << endl;
    }

END

BEGIN_H3("Not implemented methods")
//HEAD: Not all objects implement all the available methods; when a method is executed on an object that does not implement it, a _NotImplementedError_ exectpion is thrown. For instance, the _dump_ method is implemented only by _Config_ and _Section_; the _append_ method only by _List_. The exception message shows the prototype of the method.

    try
    {
        // trying to append to a Tuple; it will fail, since only List implements
        // the append method
        Tuple t("(1, 2, 3)");
        cout << "=== t is: " << t << endl;
        cout << "=== trying to execute the Tuple::append(...) method:" << endl;
        t.append(20);
    }
    catch(NotImplementedError & error)
    {
        cerr << "ERR: " << error.what() << endl;
    }
END

BEGIN_H3("The _Config_ and _Section_ objects")
//HEAD: The main goal of this library is to read/write configuration files in the form of the python ConfigObj module. This can be considered an alternative serialization/deserialization method, that has the following advantages:
//HEAD:  * it is human friendly;
//HEAD:  * it is suitable for configuration files;
//HEAD:  * it can be validated
//HEAD:
//HEAD: A _Section_ Object inherits from _Mapping_. It can store other _Sections_, or _key/value_ pairs.
//HEAD:
//HEAD: A _Config_ Object is the root _Section_ object, and provides a way to load from files or strings.
//HEAD:
//HEAD: Consider the following configuration file:
//HEAD_INCLUDE_FILE: example.config
//HEAD: It can be easily loaded to a _Config_ object:

    Config config("example.config");

END

BEGIN_H3("Accessing and printing the _Config_ object")
//HEAD: The _Config_ object is a _Mapping_:

    cout << "=== config is:\n" << config << endl;

    cout << "=== pretty(config) is:\n" << pretty(config) << endl;

BREAK
//HEAD: Printing the "main" Section
    cout << "=== config[\"main\"] is:\n" << config["main"] << endl;

BREAK
//HEAD: Printing the "main/a_bool_tuple" value
    cout << "=== config[\"main\"][\"a_bool_tuple\"] is:\n" << config["main"]["a_bool_tuple"] << endl;

BREAK
//HEAD: Printing the "main/alpha" Section
    cout << "=== config[\"main\"][\"alpha\"] is:\n" << config["main"]["alpha"] << endl;

BREAK
//HEAD: Printing the "main/alpha/an_integer_list" List
    cout << "=== config[\"main\"][\"alpha\"][\"an_integer_list\"] is:\n" << config["main"]["alpha"]["an_integer_list"] << endl;
END

BEGIN_H3("Modifying the _Config_ object")
//HEAD: Its easy to modify a _Config_ object:

//HEAD: Adding a key:
    config["main"]["a_negative_integer"] = -5;

BREAK
//HEAD: Modifying a key:
    config["main"]["alpha"]["an_integer_list"].append("this is a string");
//TAIL: ooops, it's no more an integer list!

BREAK
//HEAD: Adding a Section:
    config["main"]["new section"] = Section();
    config["main"]["new section"]["x"] = 7.5;
    config["main"]["new section"]["y"] = -4.5;
    config["main"]["new section"]["a_tuple"] = unrepr("(4.5, 6.7)");

BREAK
//HEAD: Removing a Section:
    config["main"].remove("beta");

BREAK
//HEAD: Removing a key:
    config["main"].remove("an_integer");

BREAK
//HEAD: Removing a List value:
    config["main"]["alpha"]["an_integer_list"].remove(3);

BREAK
//HEAD: The final result is:
    cout << "=== now pretty(config) is:\n" << pretty(config) << endl;
END

BEGIN_H3("Dumping the _Config_ object")
//HEAD: The _Config_ and _Section_ objects implement the _dump_ method, that is used to serialize the object with the _ConfigObj_ format. The external _dump_ function is also available.

//HEAD: Dumping a _Config_:
   cout << "=== dumping the entire config:" << endl;
   cout << dump(config) << endl;

   cout << endl;

BREAK
//HEAD: Dumping a _Section_:
   cout << "=== dumping the \"main\" config:" << endl;
   cout << dump(config["main"]) << endl;

   cout << endl;

END

BEGIN_H3("Merging _Configs_")
//HEAD: _Config_ can be easily merged
    Config c0;
    c0["a"] = Section();
    c0["a"]["x"] = Dict();
    c0["a"]["y"] = 10.6;
    c0["a"]["aa"] = Section();
    c0["a"]["aa"]["f"] = 1.0;
    c0["main"] = Section();
    c0["main"]["i"] = 1000;

    Config c1;
    c1["a"] = Section();
    c1["a"]["x"] = 1.0;
    c1["a"]["z"] = -0.01;
    c0["a"]["aa"]["i"] = 1;
    c1["c"] = Section();
    c1["c"]["s"] = "string";

    cout << "=== c0 is:\n" << dump(c0) << endl;
    cout << "=== c1 is:\n" << dump(c1) << endl;
    c0.merge(c1);
    cout << "=== c0 is:\n" << dump(c0) << endl;
END

BEGIN_H3("Loading and merging config files")
//HEAD: The _load_file(const STR & filename, bool merge=false)_ method allows to load a new _Config_ into an existing one. If the optional _merge_ parameters is _true_, then the loaded file is merged into the existing config; this means that existing keys/sections are replaced. If it is _false_, then an exception is thrown when trying to override an existing key/section.
//HEAD: The _merge_file(const STR & filename)_ method is a synonim for _load_file(filename, true)_.
    c0.merge_file("example.config");
    cout << "=== c0 is:\n" << dump(c0) << endl;
END

BEGIN_H2("Validating configs")
//HEAD: It is possible to validate a _Config_ with respect to a _Configspec_. _Configment_ validation is a subset of the _ConfigObj_ validation mechanism, see http://www.voidspace.org.uk/python/validate.html for details. The format of the _configspec_ files is the same.
//HEAD: In order to validate a _Config_, you need a _Configspec_ object (more in general, you can use every _Section_ object whose keys are _KeyValidator_ instances; a _KeyValidator_ validates other objects). You can store a _Configspec_ in a config file.
//HEAD_INCLUDE_FILE: example.configspec

    Configspec configspec("example.configspec");
    cout << "=== configspec is:" << dump(configspec) << endl;

BREAK
//HEAD: The result of a validation is a _Section_ object reporting all the errors; it is empty if validation was successful. Since containers can be casted to bool, and in this case they evaluate to _true_ if not empty, you can directly test the validation result in a conditional expression to check if validation was successful.
    Config c2("example.config");
    cout << "=== c2 is:\n" << dump(c2) << endl;
    Section validation_result = configspec.validate(c2);
    if(validation_result)  // validation_result is not empty
    {
        cout << "=== validation failed:\n" << dump(validation_result) << endl;
    }
    else
    {
        cout << "=== validation was successful\n" << endl;
    }
    cout << "=== c2 is:\n" << dump(c2) << endl;
//TAIL: The validation failed, since two errors have been found. You have to check the resulting ValidationResult instance to verify if validation was successful.
BREAK
//HEAD: The `dump` method has an optional _dump_options_ parameter whose type is _DumpOptions_; a _DumpOptions_ object contains two parameters used to change the _dump_ output:
//HEAD: * _default_mode_, which has type _DefaultMode_: it is used to define how values matching defaults must be shown:
//HEAD:   * _DefaultMode::DEFAULT_: the default behavior (-> HIDE)
//HEAD:   * _DefaultMode::HIDE_: if a value matches the default, it is not shown (default)
//HEAD:   * _DefaultMode::SHOW_: all the values are shown
//HEAD:   * _DefaultMode::COMMENT_: if a value matches the default, it is shown commented
//HEAD: * _pathname_mode_, which has type _PathnameMode_: it is used to define how pathname values must be shown:
//HEAD:   * _PathnameMode::DEFAULT_: the default behavior (-> RELATIVE)
//HEAD:   * _PathnameMode::ABSOLUTE: show absolute pathnames
//HEAD:   * _PathnameMode::RELATIVE: show relative pathnames
//HEAD:   * _PathnameMode::SPLIT: show absolute:relative pathnames
//HEAD: In the example above, the _main/gamma_ section and the _main/a_list_, _main/a_string_ keys have been added:
    cout << "=== c2[\"main\"][\"a_list\"] is: " << c2["main"]["a_list"] << std::endl;
    cout << "=== c2 is:\n" << dump(c2, DumpOptions(DefaultMode::SHOW, PathnameMode::RELATIVE)) << endl;
//TAIL: The `__validate__` and `__base_dir__` fields are internal fields that are automatically added to every section:
//TAIL:  * `__validate__` is a _boolean_ that can be used to enable/disable validation on the section;
//TAIL:  * `__base_dir__` is a _string_ that is used as base dir for pathnames (it overrides the path of the containing file).
BREAK
//HEAD: Now we'll change the invalid values according to the _configspec_:
    Config c3("example.config");
    c3["main"]["a_positive_integer"] = 8;
    c3["main"]["a_float"] = 2.5;
    c3["main"]["alpha"]["a_negative_float"] = -2.0;
    cout << "=== c3 is:\n" << dump(c3) << endl;
    // clear the ValidationResult instance:
    validation_result = configspec.validate(c3);
    if(validation_result)
    {
        cout << "=== validation failed:\n" << dump(validation_result) << endl;
    }
    else
    {
        cout << "=== validation was successful\n" << endl;
    }
//TAIL: Now everything is ok!

END

BEGIN_H2("The argparser library")
//HEAD: This library, which is built on top of the configment library, supports command line argument parsing. See the related [argparser](https://github.com/simone-campagna/Configment/wiki/argparser) page.
END

}


text:
/*!
	@file
	@author		Albert Semenov
	@date		03/2011
*/

#include "MyGUI_Precompiled.h"
#include <MyGUI_ResourceImageSet.h>
#include <MyGUI_ImageBox.h>
#include <MyGUI_TextBox.h>
#include <MyGUI_WidgetManager.h>
#include <MyGUI_FontManager.h>
#include <MyGUI_IFont.h>
#include "HyperTextBox.h"

namespace MyGUI
{

	HyperTextBox::HyperTextBox() :
		mBold(false),
		mItalic(false),
		mStrike(false),
		mUnder(false),
		mImage(false),
		mHeader1(false),
		mHeader2(false),
		mHeader3(false),
		mColour(false),
		mUrl(false),
		mStackPanel(nullptr),
		mScrollViewPanel(nullptr),
		mTextSkin("TextBox"),
		mImageSkin("ImageBox"),
		mParagraphSkin("Default"),
		mLineSkin("WhiteSkin"),
		mLinkPoiner("link"),
		mHeader1Font("Default"),
		mHeader2Font("Default"),
		mHeader3Font("Default"),
		mDefaultFont("Default"),
		mBoldFont("Default"),
		mItalicFont("Default"),
		mBoldItalicFont("Default"),
		mCurrentWrapPanel(nullptr),
		mBreakHeight(0)
	{
	}

	void HyperTextBox::initialiseOverride()
	{
		Base::initialiseOverride();

		assignWidget(mScrollViewPanel, "ScrollViewPanel");
		assignWidget(mStackPanel, "StackPanel");

		if (isUserString("TextSkin"))
			mTextSkin = getUserString("TextSkin");
		if (isUserString("ImageSkin"))
			mImageSkin = getUserString("ImageSkin");
		if (isUserString("ParagraphSkin"))
			mParagraphSkin = getUserString("ParagraphSkin");
		if (isUserString("LineSkin"))
			mLineSkin = getUserString("LineSkin");
		if (isUserString("LinkPointer"))
			mLinkPoiner = getUserString("LinkPointer");

		updateBreakHeight();
	}

	void HyperTextBox::shutdownOverride()
	{
		Base::shutdownOverride();
	}

	void HyperTextBox::addItem(const std::string& _value)
	{
		parseParagraph(mStackPanel, _value);
		mCurrentWrapPanel = nullptr;
	}

	void HyperTextBox::parseParagraph(Widget* _parent, const std::string& _value)
	{
		std::string::const_iterator textItem = _value.end();
		for (std::string::const_iterator item = _value.begin(); item != _value.end(); ++ item)
		{
			if ((*item) == '<')
			{
				// îòðåçàåì òåêñò
				if (textItem < item)
				{
					if (mCurrentWrapPanel != nullptr)
						parseText(mCurrentWrapPanel,	_value.substr(textItem - _value.begin(), item - textItem));
				}

				// èùåì êîíåö òåãà
				for (std::string::const_iterator tagItem = item; tagItem != _value.end(); ++ tagItem)
				{
					if ((*tagItem) == '>')
					{
						parseTag(_value.substr(item - _value.begin(), tagItem - item + 1));

						item = tagItem;
						textItem = tagItem + 1;
						break;
					}
				}
			}
		}
	}

	void HyperTextBox::parseText(Widget* _parent, const std::string& _value)
	{
		const int defaultSize = 16;

		if (mImage)
		{
			if (mImageSize.width == 0 || mImageSize.height == 0)
			{
				IResource* resource = ResourceManager::getInstance().getByName(_value, false);
				if (resource != nullptr)
				{
					ResourceImageSet* imageSet = resource->castType<ResourceImageSet>(false);
					if (imageSet != nullptr)
					{
						ImageIndexInfo info = imageSet->getIndexInfo(0, 0);
						mImageSize = info.size;
					}
				}
			}

			ImageBox* image = _parent->createWidget<ImageBox>(mImageSkin, IntCoord(0, 0, mImageSize.width, mImageSize.height), Align::Default);
			image->setItemResource(_value);
			// êàðòèíêà êàê óðë
			if (mUrl)
			{
				image->setPointer(mLinkPoiner);
				image->eventMouseButtonClick += newDelegate(this, &HyperTextBox::OnTextClick);
				image->setUserString("URL", mUrlValue);
			}
		}
		else if (mUrl)
		{
			TextBox* text = _parent->createWidget<TextBox>(mTextSkin, IntCoord(0, 0, defaultSize, defaultSize), Align::Default);
			text->setCaption(_value);
			text->setPointer(mLinkPoiner);
			if (mBold)
			{
				if (mItalic)
					text->setFontName(mBoldItalicFont);
				else
					text->setFontName(mBoldFont);
			}
			else if (mItalic)
			{
				text->setFontName(mItalicFont);
			}

			Widget* line = text->createWidget<Widget>(mLineSkin, IntCoord(0, defaultSize - 1, defaultSize, 1), Align::HStretch | Align::Bottom);
			line->setColour(Colour::Black);
			line->setVisible(false);
			line->setNeedMouseFocus(false);

			text->eventMouseLostFocus += newDelegate(this, &HyperTextBox::OnTextLostFocus);
			text->eventMouseSetFocus += newDelegate(this, &HyperTextBox::OnTextSetFocus);
			text->eventMouseButtonClick += newDelegate(this, &HyperTextBox::OnTextClick);
			text->setUserString("URL", mUrlValue);
		}
		else
		{
			VectorString result = utility::split(_value);
			for (VectorString::const_iterator item = result.begin(); item != result.end(); ++ item)
			{
				TextBox* text = _parent->createWidget<TextBox>(mTextSkin, IntCoord(0, 0, defaultSize, defaultSize), Align::Default);
				text->setCaption(*item);
				if (mBold)
				{
					if (mItalic)
						text->setFontName(mBoldItalicFont);
					else
						text->setFontName(mBoldFont);
				}
				else if (mItalic)
				{
					text->setFontName(mItalicFont);
				}
				else if (mHeader1)
				{
					text->setFontName(mHeader1Font);
				}
				else if (mHeader2)
				{
					text->setFontName(mHeader2Font);
				}
				else if (mHeader3)
				{
					text->setFontName(mHeader3Font);
				}

				if (mColour)
				{
					text->setTextColour(mColourValue);
				}

				if (mStrike)
				{
					Widget* line = text->createWidget<Widget>(mLineSkin, IntCoord(0, 0, defaultSize, 1), Align::HStretch | Align::VCenter);
					line->setColour(Colour::Black);
					line->setNeedMouseFocus(false);
					if (mColour)
						line->setColour(mColourValue);
				}

				if (mUnder)
				{
					Widget* line = text->createWidget<Widget>(mLineSkin, IntCoord(0, defaultSize - 1, defaultSize, 1), Align::HStretch | Align::Bottom);
					line->setColour(Colour::Black);
					line->setNeedMouseFocus(false);
					if (mColour)
						line->setColour(mColourValue);
				}
			}
		}
	}

	void HyperTextBox::parseTag(const std::string& _value)
	{
		const std::string imageStartTagName = "";

		const std::string paragraphStartTagName = "
";

		const std::string colourStartTagName = "<color";
		const std::string colourEndTagName = ">";

		const std::string urlStartTagName = "<url";
		const std::string urlEndTagName = ">";

		if (_value == "
")
		{
			mHeader1 = true;
		}
		else if (_value == "
")
		{
			mHeader1 = false;
		}
		else if (_value == "
")
		{
			mHeader2 = true;
		}
		else if (_value == "
")
		{
			mHeader2 = false;
		}
		else if (_value == "
")
		{
			mHeader3 = true;
		}
		else if (_value == "
")
		{
			mHeader3 = false;
		}
		else if (_value == "")
		{
			mBold = true;
		}
		else if (_value == "")
		{
			mBold = false;
		}
		else if (_value == "")
		{
			mItalic = true;
		}
		else if (_value == "")
		{
			mItalic = false;
		}
		else if (_value == "<s>")
		{
			mStrike = true;
		}
		else if (_value == "</s>")
		{
			mStrike = false;
		}
		else if (_value == "")
		{
			mUnder = true;
		}
		else if (_value == "")
		{
			mUnder = false;
		}
		else if (utility::startWith(_value, colourStartTagName))
		{
			mColour = true;
			mColourValue = Colour::Black;

			const std::string colourTagName = "value=";

			std::string valueColour = _value.substr(colourStartTagName.size(), _value.size() - (colourStartTagName.size() + colourEndTagName.size()));
			VectorString result = utility::split(valueColour);
			for (VectorString::const_iterator item = result.begin(); item != result.end(); ++ item)
			{
				if (utility::startWith(*item, colourTagName))
				{
					if ((colourTagName.size() + 2) < ((*item).size()))
					{
						std::string value = (*item).substr(colourTagName.size() + 1, (*item).size() - (colourTagName.size() + 2));
						mColourValue = Colour::parse(value);
					}
				}
			}
		}
		else if (_value == "</color>")
		{
			mColour = false;
		}
		else if (utility::startWith(_value, urlStartTagName))
		{
			mUrl = true;
			mUrlValue.clear();

			const std::string urlTagName = "value=";

			std::string valueUrl = _value.substr(urlStartTagName.size(), _value.size() - (urlStartTagName.size() + urlEndTagName.size()));
			VectorString result = utility::split(valueUrl);
			for (VectorString::const_iterator item = result.begin(); item != result.end(); ++ item)
			{
				if (utility::startWith(*item, urlTagName))
				{
					if ((urlTagName.size() + 2) < ((*item).size()))
					{
						mUrlValue = (*item).substr(urlTagName.size() + 1, (*item).size() - (urlTagName.size() + 2));
					}
				}
			}
		}
		else if (_value == "</url>")
		{
			mUrl = false;
		}
		else if (utility::startWith(_value, paragraphStartTagName))
		{
			mCurrentWrapPanel = mStackPanel->createWidget<WrapPanel>(mParagraphSkin, IntCoord(), Align::Default);
			mCurrentWrapPanel->setContentAlign(Align::Left | Align::Bottom);
			mCurrentWrapPanel->setSpacer(mSpacer);

			Align alignResult = Align::Default;
			bool needAlign = false;

			Align floatResult = Align::Default;
			bool needFloat = false;

			const std::string alightTagName = "align=";
			const std::string floatTagName = "float=";

			std::string valueParagraph = _value.substr(paragraphStartTagName.size(), _value.size() - (paragraphStartTagName.size() + paragraphEndTagName.size()));
			VectorString result = utility::split(valueParagraph);
			for (VectorString::const_iterator item = result.begin(); item != result.end(); ++ item)
			{
				if (utility::startWith(*item, alightTagName))
				{
					if ((alightTagName.size() + 2) < ((*item).size()))
					{
						needAlign = true;
						std::string value = (*item).substr(alightTagName.size() + 1, (*item).size() - (alightTagName.size() + 2));
						if (value == "left")
							alignResult = Align::Default;
						else if (value == "center")
							alignResult = Align::HCenter | Align::Top;
						else if (value == "right")
							alignResult = Align::Right | Align::Top;
						else
							alignResult = Align::Default;
					}
				}
				else if (utility::startWith(*item, floatTagName))
				{
					if ((floatTagName.size() + 2) < ((*item).size()))
					{
						needFloat = true;
						std::string value = (*item).substr(floatTagName.size() + 1, (*item).size() - (floatTagName.size() + 2));
						if (value == "left")
							floatResult = Align::Default;
						else if (value == "center")
							floatResult = Align::HCenter | Align::Top;
						else if (value == "right")
							floatResult = Align::Right | Align::Top;
						else
							floatResult = Align::Default;
					}
				}
			}

			if (needAlign)
			{
				mCurrentWrapPanel->setContentAlign(alignResult);
			}
			if (needFloat)
			{
				mCurrentWrapPanel->setContentFloat(true);
				mCurrentWrapPanel->setSnapFloat(floatResult);
			}
		}
		else if (_value == "
")
		{
			mCurrentWrapPanel = nullptr;
		}
		else if (utility::startWith(_value, imageStartTagName))
		{
			mImageSize.clear();
			mImage = true;

			const std::string widthTagName = "width=";
			const std::string heightTagName = "height=";

			std::string valueImage = _value.substr(imageStartTagName.size(), _value.size() - (imageStartTagName.size() + imageEndTagName.size()));
			VectorString result = utility::split(valueImage);
			for (VectorString::const_iterator item = result.begin(); item != result.end(); ++ item)
			{
				if (utility::startWith(*item, widthTagName))
				{
					if ((widthTagName.size() + 2) < ((*item).size()))
					{
						std::string value = (*item).substr(widthTagName.size() + 1, (*item).size() - (widthTagName.size() + 2));
						mImageSize.width = utility::parseValue<int>(value);
					}
				}
				else if (utility::startWith(*item, heightTagName))
				{
					if ((heightTagName.size() + 2) < ((*item).size()))
					{
						std::string value = (*item).substr(heightTagName.size() + 1, (*item).size() - (heightTagName.size() + 2));
						mImageSize.height = utility::parseValue<int>(value);
					}
				}
			}
		}
		else if (_value == "")
		{
			mImage = false;
		}
		else if (_value == "
")
		{
			if (mCurrentWrapPanel == nullptr)
			{
				WrapPanel* panel = mStackPanel->createWidget<WrapPanel>(mParagraphSkin, IntCoord(), Align::Default);
				panel->setContentAlign(Align::Left | Align::Bottom);
				panel->setSpacer(mSpacer);
				panel->createWidget<Widget>("Default", IntCoord(0, 0, 0, mBreakHeight), Align::Default);
			}
		}
		else if (_value == "<t/>")
		{
			if (mCurrentWrapPanel != nullptr)
			{
				const int countInTab = 4;
				mCurrentWrapPanel->createWidget<Widget>("Default", IntCoord(0, 0, countInTab * mSpacer.width, 0), Align::Default);
			}
		}
	}

	void HyperTextBox::OnTextLostFocus(Widget* _sender, Widget* _new)
	{
		size_t count = _sender->getChildCount();
		if (count > 0)
			_sender->getChildAt(0)->setVisible(false);
	}

	void HyperTextBox::OnTextSetFocus(Widget* _sender, Widget* _old)
	{
		size_t count = _sender->getChildCount();
		if (count > 0)
			_sender->getChildAt(0)->setVisible(true);
	}

	void HyperTextBox::OnTextClick(Widget* _sender)
	{
		std::string url = _sender->getUserString("URL");
		eventUrlClick(this, url);
	}

	void HyperTextBox::updateContent()
	{
		mStackPanel->setSpacer(IntSize(0, mSpacer.height));
		mScrollViewPanel->updateContent();
	}

	const IntSize& HyperTextBox::getSpacer() const
	{
		return mSpacer;
	}

	void HyperTextBox::setSpacer(const IntSize& _value)
	{
		mSpacer = _value;
	}

	const std::string& HyperTextBox::getHeader1Font() const
	{
		return mHeader1Font;
	}

	void HyperTextBox::setHeader1Font(const std::string& _value)
	{
		mHeader1Font = _value;
	}

	const std::string& HyperTextBox::getHeader2Font() const
	{
		return mHeader2Font;
	}

	void HyperTextBox::setHeader2Font(const std::string& _value)
	{
		mHeader2Font = _value;
	}

	const std::string& HyperTextBox::getHeader3Font() const
	{
		return mHeader3Font;
	}

	void HyperTextBox::setHeader3Font(const std::string& _value)
	{
		mHeader3Font = _value;
	}

	const std::string& HyperTextBox::getDefaultFont() const
	{
		return mDefaultFont;
	}

	void HyperTextBox::setDefaultFont(const std::string& _value)
	{
		mDefaultFont = _value;
		updateBreakHeight();
	}

	const std::string& HyperTextBox::getBoldFont() const
	{
		return mBoldFont;
	}

	void HyperTextBox::setBoldFont(const std::string& _value)
	{
		mBoldFont = _value;
	}

	const std::string& HyperTextBox::getItalicFont() const
	{
		return mItalicFont;
	}

	void HyperTextBox::setItalicFont(const std::string& _value)
	{
		mItalicFont = _value;
	}

	const std::string& HyperTextBox::getBoldItalicFont() const
	{
		return mBoldItalicFont;
	}

	void HyperTextBox::setBoldItalicFont(const std::string& _value)
	{
		mBoldItalicFont =_value;
	}

	void HyperTextBox::setPropertyOverride(const std::string& _key, const std::string& _value)
	{
		if (_key == "Spacer")
			setSpacer(utility::parseValue<IntSize>(_value));
		else if (_key == "DefaultFont")
			setDefaultFont(_value);
		else if (_key == "BoldFont")
			setBoldFont(_value);
		else if (_key == "ItalicFont")
			setItalicFont(_value);
		else if (_key == "BoldItalicFont")
			setBoldItalicFont(_value);
		else if (_key == "Header1Font")
			setHeader1Font(_value);
		else if (_key == "Header2Font")
			setHeader2Font(_value);
		else if (_key == "Header3Font")
			setHeader3Font(_value);
		else
		{
			Base::setPropertyOverride(_key, _value);
			return;
		}
		eventChangeProperty(this, _key, _value);
	}

	void HyperTextBox::setCaption(const UString& _value)
	{
		removeAllItems();

		addItem(_value);

		updateContent();
	}

	void HyperTextBox::removeAllItems()
	{
		while (mStackPanel->getChildCount() != 0)
			WidgetManager::getInstancePtr()->destroyWidget(mStackPanel->getChildAt(0));
	}

	size_t HyperTextBox::getItemsCount() const
	{
		return mStackPanel->getChildCount();
	}

	void HyperTextBox::removeItemAt(size_t _index)
	{
		MYGUI_ASSERT_RANGE(_index, mStackPanel->getChildCount(), "HyperTextBox::removeItemAt");
		WidgetManager::getInstancePtr()->destroyWidget(mStackPanel->getChildAt(_index));
	}

	void HyperTextBox::updateBreakHeight()
	{
		mBreakHeight = 0;

		IFont* font = FontManager::getInstancePtr()->getByName(getDefaultFont());
		if (font != nullptr)
			mBreakHeight = font->getDefaultHeight();
	}

} // namespace MyGUI


text:
/**
* @description Helper functions that allow you to easily access any API requests
* offered by the Blue Alliance in the Team Requests section.
* @see For more documentation see https://www.thebluealliance.com/apidocs#team-requests
* @see For more information regarding specific event codes see https://docs.google.com/spreadsheets/d/1HqsReMjr5uBuyZjqv14t6bQF2n038GfMmWi3B6vFGiA/edit
* @author Dacotah Harvey
* @author John-Curtis Mcdonald
* @requires configuration.js
*/

/*--------------------------------------------------------------------------
-------------------------------Module Setup---------------------------------
--------------------------------------------------------------------------*/

// Load our base configuration file
var configuration = require('../configurations/configuration.js');

// Quick references for some of the options we offer in the configuration file
var client = configuration.client;
var extend = configuration.extend;
var headers = configuration.headers;

/**
 * @description Define the base Options that this API section accepts.
 * This contains all of the base options that we need. It allows the user to
 * override them as they need.
 * These also act as the default values. If not overriden on function call
 * these will be set as the default @param
 */
var __base_options = {
    page_num:   1,
    team_key:   "frc1114",
    event_key:  "2014cmp",
    year:       2016
}

/**
 * @description The base module that we build our functions into. We instantiate
 * this blank object that we then add our helper functions to. We then export
 * this @module at the end of the script to allow our functions to import it
 * and use the helper functions defined
 * @type {Object}
 */
var teamRequests = {};

/*--------------------------------------------------------------------------
--------------------------------FRC Teams-----------------------------------
--------------------------------------------------------------------------*/

/**
 * @function Returns all teams in a pages format
 * @param  {[Array]}   options  - Options for the URL
 *                              @param page_num: Integer
 *                                     A page of teams, zero-indexed. Each page
 *                                     consists of teams whose numbers start at
 *                                     start = 500 * page_num and end at
 *                                     end = start + 499, inclusive.
 * @param  {Function} callback - Callback function that returns the response from the request
 * @return {[JSON]}            - Error, Response, and Body from the request
 */
teamRequests.getTeams = function(options, callback) {

    base_options = extend(__base_options, options);

    return client.get(
        {
            headers: headers,
            url: configuration.base_url + "/teams/" + base_options.page_num
        },
        function(error, response, body) {
            callback(error, response, body);
        }
    );
}

/**
 * @function Returns all information about a given team
 * @param  {[Array]}   options  - Options for the URL
 *                              @param team_key: String
 *                              A team key name where the format is frcyyyy where
 *                              yyyy is the a valid, official team number issued
 *                              by FIRST
 * @param  {Function} callback - Callback function that returns the response from the request
 * @return {[JSON]}            - Error, Response, and Body from the request
 */
teamRequests.getTeam = function(options, callback) {

    base_options = extend(__base_options, options);

    return client.get(
        {
            headers: headers,
            url: configuration.base_url + "/team/" + base_options.team_key
        },
        function(error, response, body) {
            callback(error, response, body);
        }
    );
}

/**
 * @function Returns all information regarding all events a given team attended
 * in a given year
 * @param  {[Array]}   options  - Options for the URL
 *                              @param team_key: String
 *                              A team key name where the format is frcyyyy where
 *                              yyyy is the a valid, official team number issued
 *                              by FIRST
 *                              @param year: Integer
 *                              A specific year you would like to grab data for
 *                              this team. Defaults to current year if not provided.
 * @param  {Function} callback - Callback function that returns the response from the request
 * @return {[JSON]}            - Error, Response, and Body from the request
 */
teamRequests.getTeamEvents = function(options, callback) {

    base_options = extend(__base_options, options);

    return client.get(
        {
            headers: headers,
            url: configuration.base_url + "/team/" + base_options.team_key + "/events"
        },
        function(error, response, body) {
            callback(error, response, body);
        }
    );
}

/**
 * @function Returns all awards won by a given team at a given event
 * @param  {[Array]}   options  - Options for the URL
 *                              @param team_key: String
 *                              A team key name where the format is frcyyyy where
 *                              yyyy is the a valid, official team number issued
 *                              by FIRST
 *                              @param event_key: String
 *                              TBA event key with the format yyyy[EVENT_CODE],
 *                              where yyyy is the year, and EVENT_CODE is the
 *                              event code of the event.
 * @param  {Function} callback - Callback function that returns the response from the request
 * @return {[JSON]}            - Error, Response, and Body from the request

 */
teamRequests.getTeamEventAwards = function(options, callback) {

    base_options = extend(__base_options, options);

    return client.get(
        {
            headers: headers,
            url: configuration.base_url + "/team/" + base_options.team_key + "/event/" + base_options.event_key + "/awards"
        },
        function(error, response, body) {
            callback(error, response, body);
        }
    );
}

/**
 * @function REturns all matches that a given team participated in at a given event
 * @param  {[Array]}   options  - Options for the URL
 *                              @param team_key: String
 *                              A team key name where the format is frcyyyy where
 *                              yyyy is the a valid, official team number issued
 *                              by FIRST
 *                              @param event_key: String
 *                              TBA event key with the format yyyy[EVENT_CODE],
 *                              where yyyy is the year, and EVENT_CODE is the
 *                              event code of the event.
 * @param  {Function} callback - Callback function that returns the response from the request
 * @return {[JSON]}            - Error, Response, and Body from the request
 */
teamRequests.getTeamEventMatches = function(options, callback) {

    base_options = extend(__base_options, options);

    return client.get(
        {
            headers: headers,
            url: configuration.base_url + "/team/" + base_options.team_key + "/event/" + base_options.event_key + "/matches"
        },
        function(error, response, body) {
            callback(error, response, body);
        }
    );
}

/**
 * @function returns all the years that a given team has participated in FRC
 * @param  {[Array]}   options  - Options for the URL
 *                              @param team_key: String
 *                              A team key name where the format is frcyyyy where
 *                              yyyy is the a valid, official team number issued
 *                              by FIRST
 * @param  {Function} callback - Callback function that returns the response from the request
 * @return {[JSON]}            - Error, Response, and Body from the request
 */
teamRequests.getTeamYearsParticipated = function(options, callback) {

    base_options = extend(__base_options, options);

    return client.get(
        {
            headers: headers,
            url: configuration.base_url + "/team/" + base_options.team_key + "/years_participated"
        },
        function(error, response, body) {
            callback(error, response, body);
        }
    );
}

/**
 * @function Returns any media that is stored on hand for a given team
 * (Such as a youtube channel)
 * @param  {[Array]}   options  - Options for the URL
 *                              @param team_key: String
 *                              A team key name where the format is frcyyyy where
 *                              yyyy is the a valid, official team number issued
 *                              by FIRST
 *                              @param year: Integer
 *                              A specific year you would like to grab data for
 *                              this team. Defaults to current year if not provided.
 * @param  {Function} callback - Callback function that returns the response from the request
 * @return {[JSON]}            - Error, Response, and Body from the request
 */
teamRequests.getTeamMedia = function(options, callback) {

    base_options = extend(__base_options, options);

    return client.get(
        {
            headers: headers,
            url: configuration.base_url + "/team/" + base_options.team_key + "/" + base_options.year + "/media"
        },
        function(error, response, body) {
            callback(error, response, body);
        }
    );
}

/*--------------------------------------------------------------------------
-------------------------------FRC History----------------------------------
--------------------------------------------------------------------------*/

/**
 * @function Returns the outcome of a given team at every event they have competed in
 * @param  {[Array]}   options  - Options for the URL
 *                              @param team_key: String
 *                              A team key name where the format is frcyyyy where
 *                              yyyy is the a valid, official team number issued
 *                              by FIRST
 * @param  {Function} callback - Callback function that returns the response from the request
 * @return {[JSON]}            - Error, Response, and Body from the request
 */
teamRequests.getTeamEventHistory = function(options, callback) {

    base_options = extend(__base_options, options);

    return client.get(
        {
            headers: headers,
            url: configuration.base_url + "/team/" + base_options.team_key + "/history/events"
        },
        function(error, response, body) {
            callback(error, response, body);
        }
    );
}

/**
 * @function Returns any awards that a given team has won at any event they have attended
 * @param  {[Array]}   options  - Options for the URL
 *                              @param team_key: String
 *                              A team key name where the format is frcyyyy where
 *                              yyyy is the a valid, official team number issued
 *                              by FIRST
 * @param  {Function} callback - Callback function that returns the response from the request
 * @return {[JSON]}            - Error, Response, and Body from the request
 */
teamRequests.getTeamAwardHistory = function(options, callback) {

    base_options = extend(__base_options, options);

    return client.get(
        {
            headers: headers,
            url: configuration.base_url + "/team/" + base_options.team_key + "/history/awards"
        },
        function(error, response, body) {
            callback(error, response, body);
        }
    );
}

/**
 * @function Returns information on the Robot that a given team has used
 * in every respective year that they have competed
 * @param  {[Array]}   options  - Options for the URL
 *                              @param team_key: String
 *                              A team key name where the format is frcyyyy where
 *                              yyyy is the a valid, official team number issued
 *                              by FIRST
 * @param  {Function} callback - Callback function that returns the response from the request
 * @return {[JSON]}            - Error, Response, and Body from the request
 */
teamRequests.getTeamRobotHistory = function(options, callback) {

    base_options = extend(__base_options, options);

    return client.get(
        {
            headers: headers,
            url: configuration.base_url + "/team/" + base_options.team_key + "/history/robots"
        },
        function(error, response, body) {
            callback(error, response, body);
        }
    );
}

/**
 * @function Returns information about a given team at any distric they have
 * attended
 * @param  {[Array]}   options  - Options for the URL
 *                              @param team_key: String
 *                              A team key name where the format is frcyyyy where
 *                              yyyy is the a valid, official team number issued
 *                              by FIRST
 * @param  {Function} callback - Callback function that returns the response from the request
 * @return {[JSON]}            - Error, Response, and Body from the request
 */
teamRequests.getTeamDistricHistory = function(options, callback) {

    base_options = extend(__base_options, options);

    return client.get(
        {
            headers: headers,
            url: configuration.base_url + "/team/" + base_options.team_key + "/history/districts"
        },
        function(error, response, body) {
            callback(error, response, body);
        }
    );
}

// Export our base object so it can be used in other contexts
module.exports = teamRequests;


text:
/**
 * Metadata on a language's string formatting syntax.
 */
export class StringFormatSyntax {
    /**
     * Abbreviated middle of a format string if no inputs are provided.
     */
    public formatAbbreviated: string;

    /**
     * Start of a format string input.
     */
    public formatInputLeft: string;

    /**
     * End of a format string input.
     */
    public formatInputRight: string;

    /**
     * Start of a format string.
     */
    public formatLeft: string;

    /**
     * Middle of a format string (between the template and inputs).
     */
    public formatMiddle: string;

    /**
     * End of a format string.
     */
    public formatRight: string;

    /**
     * Whether input replacement formats include the printed index.
     */
    public includeIndexInFormatting: boolean;

    /**
     * Whether to include C-syle type descriptors in format string inputs.
     */
    public inputTypes: boolean;

    /**
     * Type names matched to their C-style type descriptors, if includeTypes is true.
     */
    public typeCodes: { [i: string]: string };

    /**
     * Whether to use string interpolation instead of formatting.
     */
    public useInterpolation: boolean;
}