text:
import os
import re
import six
from six.moves.urllib import parse
from six.moves.urllib import request
import sys

import fixtures
import tempfile
import testscenarios
import testtools

from heatclient.openstack.common import jsonutils
from heatclient.openstack.common import strutils
from mox3 import mox

from keystoneclient.v2_0 import client as ksclient

from heatclient.common import http
from heatclient import exc
import heatclient.shell
from heatclient.tests import fakes

load_tests = testscenarios.load_tests_apply_scenarios
TEST_VAR_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),
                                            'var'))

class TestCase(testtools.TestCase):

    def set_fake_env(self, fake_env):
        client_env = ('OS_USERNAME', 'OS_PASSWORD', 'OS_TENANT_ID',
                      'OS_TENANT_NAME', 'OS_AUTH_URL', 'OS_REGION_NAME',
                      'OS_AUTH_TOKEN', 'OS_NO_CLIENT_AUTH', 'OS_SERVICE_TYPE',
                      'OS_ENDPOINT_TYPE', 'HEAT_URL')

        for key in client_env:
            self.useFixture(
                fixtures.EnvironmentVariable(key, fake_env.get(key)))

    # required for testing with Python 2.6
    def assertRegexpMatches(self, text, expected_regexp, msg=None):
        """Fail the test unless the text matches the regular expression."""
        if isinstance(expected_regexp, six.string_types):
            expected_regexp = re.compile(expected_regexp)
        if not expected_regexp.search(text):
            msg = msg or "Regexp didn't match"
            msg = '%s: %r not found in %r' % (
                msg, expected_regexp.pattern, text)
            raise self.failureException(msg)

    def shell_error(self, argstr, error_match):
        orig = sys.stderr
        sys.stderr = six.StringIO()
        _shell = heatclient.shell.HeatShell()
        e = self.assertRaises(Exception, _shell.main, argstr.split())
        self.assertRegexpMatches(e.__str__(), error_match)
        err = sys.stderr.getvalue()
        sys.stderr.close()
        sys.stderr = orig
        return err

class EnvVarTest(TestCase):

    scenarios = [
        ('username', dict(
            remove='OS_USERNAME',
            err='You must provide a username')),
        ('password', dict(
            remove='OS_PASSWORD',
            err='You must provide a password')),
        ('tenant_name', dict(
            remove='OS_TENANT_NAME',
            err='You must provide a tenant_id')),
        ('auth_url', dict(
            remove='OS_AUTH_URL',
            err='You must provide an auth url')),
    ]

    def test_missing_auth(self):

        fake_env = {
            'OS_USERNAME': 'username',
            'OS_PASSWORD': 'password',
            'OS_TENANT_NAME': 'tenant_name',
            'OS_AUTH_URL': 'http://no.where',
        }
        fake_env[self.remove] = None
        self.set_fake_env(fake_env)
        self.shell_error('stack-list', self.err)

class EnvVarTestToken(TestCase):

    scenarios = [
        ('tenant_id', dict(
            remove='OS_TENANT_ID',
            err='You must provide a tenant_id')),
        ('auth_url', dict(
            remove='OS_AUTH_URL',
            err='You must provide an auth url')),
    ]

    def test_missing_auth(self):

        fake_env = {
            'OS_AUTH_TOKEN': 'atoken',
            'OS_TENANT_ID': 'tenant_id',
            'OS_AUTH_URL': 'http://no.where',
        }
        fake_env[self.remove] = None
        self.set_fake_env(fake_env)
        self.shell_error('stack-list', self.err)

class ShellParamValidationTest(TestCase):

    scenarios = [
        ('create', dict(
            command='create ts -P "a!b"',
            err='Malformed parameter')),
        ('stack-create', dict(
            command='stack-create ts -P "ab"',
            err='Malformed parameter')),
        ('update', dict(
            command='update ts -P "a~b"',
            err='Malformed parameter')),
        ('stack-update', dict(
            command='stack-update ts -P "a-b"',
            err='Malformed parameter')),
        ('validate', dict(
            command='validate -P "a=b;c"',
            err='Malformed parameter')),
        ('template-validate', dict(
            command='template-validate -P "a$b"',
            err='Malformed parameter')),
    ]

    def setUp(self):
        super(ShellParamValidationTest, self).setUp()
        self.m = mox.Mox()
        self.addCleanup(self.m.VerifyAll)
        self.addCleanup(self.m.UnsetStubs)

    def test_bad_parameters(self):
        self.m.StubOutWithMock(ksclient, 'Client')
        self.m.StubOutWithMock(http.HTTPClient, 'json_request')
        fakes.script_keystone_client()

        self.m.ReplayAll()
        fake_env = {
            'OS_USERNAME': 'username',
            'OS_PASSWORD': 'password',
            'OS_TENANT_NAME': 'tenant_name',
            'OS_AUTH_URL': 'http://no.where',
        }
        self.set_fake_env(fake_env)
        template_file = os.path.join(TEST_VAR_DIR, 'minimal.template')
        cmd = '%s --template-file=%s ' % (self.command, template_file)
        self.shell_error(cmd, self.err)

class ShellValidationTest(TestCase):

    def setUp(self):
        super(ShellValidationTest, self).setUp()
        self.m = mox.Mox()
        self.addCleanup(self.m.VerifyAll)
        self.addCleanup(self.m.UnsetStubs)

    def test_failed_auth(self):
        self.m.StubOutWithMock(ksclient, 'Client')
        self.m.StubOutWithMock(http.HTTPClient, 'json_request')
        fakes.script_keystone_client()
        failed_msg = 'Unable to authenticate user with credentials provided'
        http.HTTPClient.json_request(
            'GET', '/stacks?').AndRaise(exc.Unauthorized(failed_msg))

        self.m.ReplayAll()
        fake_env = {
            'OS_USERNAME': 'username',
            'OS_PASSWORD': 'password',
            'OS_TENANT_NAME': 'tenant_name',
            'OS_AUTH_URL': 'http://no.where',
        }
        self.set_fake_env(fake_env)
        self.shell_error('stack-list', failed_msg)

    def test_stack_create_validation(self):
        self.m.StubOutWithMock(ksclient, 'Client')
        self.m.StubOutWithMock(http.HTTPClient, 'json_request')
        fakes.script_keystone_client()

        self.m.ReplayAll()
        fake_env = {
            'OS_USERNAME': 'username',
            'OS_PASSWORD': 'password',
            'OS_TENANT_NAME': 'tenant_name',
            'OS_AUTH_URL': 'http://no.where',
        }
        self.set_fake_env(fake_env)
        self.shell_error(
            'stack-create teststack '
            '--parameters="InstanceType=m1.large;DBUsername=wp;'
            'DBPassword=verybadpassword;KeyName=heat_key;'
            'LinuxDistribution=F17"',
            'Need to specify exactly one of')

class ShellBase(TestCase):

    def setUp(self):
        super(ShellBase, self).setUp()
        self.m = mox.Mox()
        self.m.StubOutWithMock(ksclient, 'Client')
        self.m.StubOutWithMock(http.HTTPClient, 'json_request')
        self.m.StubOutWithMock(http.HTTPClient, 'raw_request')
        self.addCleanup(self.m.VerifyAll)
        self.addCleanup(self.m.UnsetStubs)

        # Some tests set exc.verbose = 1, so reset on cleanup
        def unset_exc_verbose():
            exc.verbose = 0

        self.addCleanup(unset_exc_verbose)

    def shell(self, argstr):
        orig = sys.stdout
        try:
            sys.stdout = six.StringIO()
            _shell = heatclient.shell.HeatShell()
            _shell.main(argstr.split())
            self.subcommands = _shell.subcommands.keys()
        except SystemExit:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            self.assertEqual(0, exc_value.code)
        finally:
            out = sys.stdout.getvalue()
            sys.stdout.close()
            sys.stdout = orig

        return out

class ShellTestCommon(ShellBase):

    def setUp(self):
        super(ShellTestCommon, self).setUp()

    def test_help_unknown_command(self):
        self.assertRaises(exc.CommandError, self.shell, 'help foofoo')

    def test_help(self):
        required = [
            '^usage: heat',
            '(?m)^See "heat help COMMAND" for help on a specific command',
        ]
        for argstr in ['--help', 'help']:
            help_text = self.shell(argstr)
            for r in required:
                self.assertRegexpMatches(help_text, r)

    def test_command_help(self):
        output = self.shell('help help')
        self.assertIn('usage: heat help [<subcommand>]', output)
        subcommands = list(self.subcommands)
        for command in subcommands:
            if command.replace('_', '-') == 'bash-completion':
                continue
            output1 = self.shell('help %s' % command)
            output2 = self.shell('%s --help' % command)
            self.assertEqual(output1, output2)
            self.assertRegexpMatches(output1, '^usage: heat %s' % command)

    def test_debug_switch_raises_error(self):
        fakes.script_keystone_client()
        http.HTTPClient.json_request(
            'GET', '/stacks?').AndRaise(exc.Unauthorized("FAIL"))

        self.m.ReplayAll()

        fake_env = {
            'OS_USERNAME': 'username',
            'OS_PASSWORD': 'password',
            'OS_TENANT_NAME': 'tenant_name',
            'OS_AUTH_URL': 'http://no.where',
        }
        self.set_fake_env(fake_env)
        args = ['--debug', 'stack-list']
        self.assertRaises(exc.Unauthorized, heatclient.shell.main, args)

    def test_dash_d_switch_raises_error(self):
        fakes.script_keystone_client()
        http.HTTPClient.json_request(
            'GET', '/stacks?').AndRaise(exc.CommandError("FAIL"))

        self.m.ReplayAll()

        fake_env = {
            'OS_USERNAME': 'username',
            'OS_PASSWORD': 'password',
            'OS_TENANT_NAME': 'tenant_name',
            'OS_AUTH_URL': 'http://no.where',
        }
        self.set_fake_env(fake_env)
        args = ['-d', 'stack-list']
        self.assertRaises(exc.CommandError, heatclient.shell.main, args)

    def test_no_debug_switch_no_raises_errors(self):
        fakes.script_keystone_client()
        http.HTTPClient.json_request(
            'GET', '/stacks?').AndRaise(exc.Unauthorized("FAIL"))

        self.m.ReplayAll()

        fake_env = {
            'OS_USERNAME': 'username',
            'OS_PASSWORD': 'password',
            'OS_TENANT_NAME': 'tenant_name',
            'OS_AUTH_URL': 'http://no.where',
        }
        self.set_fake_env(fake_env)
        args = ['stack-list']
        self.assertRaises(SystemExit, heatclient.shell.main, args)

    def test_help_on_subcommand(self):
        required = [
            '^usage: heat stack-list',
            "(?m)^List the user's stacks",
        ]
        argstrings = [
            'help stack-list',
        ]
        for argstr in argstrings:
            help_text = self.shell(argstr)
            for r in required:
                self.assertRegexpMatches(help_text, r)

class ShellTestUserPass(ShellBase):

    def setUp(self):
        super(ShellTestUserPass, self).setUp()
        self._set_fake_env()

    # Patch os.environ to avoid required auth info.
    def _set_fake_env(self):
        fake_env = {
            'OS_USERNAME': 'username',
            'OS_PASSWORD': 'password',
            'OS_TENANT_NAME': 'tenant_name',
            'OS_AUTH_URL': 'http://no.where',
        }
        self.set_fake_env(fake_env)

    def _script_keystone_client(self):
        fakes.script_keystone_client()

    def test_stack_list(self):
        self._script_keystone_client()
        fakes.script_heat_list()

        self.m.ReplayAll()

        list_text = self.shell('stack-list')

        required = [
            'id',
            'stack_status',
            'creation_time',
            'teststack',
            '1',
            'CREATE_COMPLETE',
            'IN_PROGRESS',
        ]
        for r in required:
            self.assertRegexpMatches(list_text, r)

    def test_stack_list_with_args(self):
        self._script_keystone_client()
        expected_url = '/stacks?%s' % parse.urlencode({
            'limit': 2,
            'status': ['COMPLETE', 'FAILED'],
            'marker': 'fake_id',
        }, True)
        fakes.script_heat_list(expected_url)

        self.m.ReplayAll()

        list_text = self.shell('stack-list'
                               ' --limit 2'
                               ' --marker fake_id'
                               ' --filters=status=COMPLETE'
                               ' --filters=status=FAILED')

        required = [
            'teststack',
            'teststack2',
        ]
        for r in required:
            self.assertRegexpMatches(list_text, r)

    def test_parsable_error(self):
        message = "The Stack (bad) could not be found."
        resp_dict = {
            "explanation": "The resource could not be found.",
            "code": 404,
            "error": {
                "message": message,
                "type": "StackNotFound",
                "traceback": "",
            },
            "title": "Not Found"
        }

        self._script_keystone_client()
        fakes.script_heat_error(jsonutils.dumps(resp_dict))

        self.m.ReplayAll()

        e = self.assertRaises(exc.HTTPException, self.shell, "stack-show bad")
        self.assertEqual("ERROR: " + message, str(e))

    def test_parsable_verbose(self):
        message = "The Stack (bad) could not be found."
        resp_dict = {
            "explanation": "The resource could not be found.",
            "code": 404,
            "error": {
                "message": message,
                "type": "StackNotFound",
                "traceback": "<TRACEBACK>",
            },
            "title": "Not Found"
        }

        self._script_keystone_client()
        fakes.script_heat_error(jsonutils.dumps(resp_dict))

        self.m.ReplayAll()

        exc.verbose = 1

        e = self.assertRaises(exc.HTTPException, self.shell, "stack-show bad")
        self.assertIn(message, str(e))

    def test_parsable_malformed_error(self):
        invalid_json = "ERROR: {Invalid JSON Error."
        self._script_keystone_client()
        fakes.script_heat_error(invalid_json)
        self.m.ReplayAll()
        e = self.assertRaises(exc.HTTPException, self.shell, "stack-show bad")
        self.assertEqual("ERROR: " + invalid_json, str(e))

    def test_parsable_malformed_error_missing_message(self):
        missing_message = {
            "explanation": "The resource could not be found.",
            "code": 404,
            "error": {
                "type": "StackNotFound",
                "traceback": "",
            },
            "title": "Not Found"
        }

        self._script_keystone_client()
        fakes.script_heat_error(jsonutils.dumps(missing_message))
        self.m.ReplayAll()

        e = self.assertRaises(exc.HTTPException, self.shell, "stack-show bad")
        self.assertEqual("ERROR: Internal Error", str(e))

    def test_parsable_malformed_error_missing_traceback(self):
        message = "The Stack (bad) could not be found."
        resp_dict = {
            "explanation": "The resource could not be found.",
            "code": 404,
            "error": {
                "message": message,
                "type": "StackNotFound",
            },
            "title": "Not Found"
        }

        self._script_keystone_client()
        fakes.script_heat_error(jsonutils.dumps(resp_dict))
        self.m.ReplayAll()

        exc.verbose = 1

        e = self.assertRaises(exc.HTTPException, self.shell, "stack-show bad")
        self.assertEqual("ERROR: The Stack (bad) could not be found.\n",
                         str(e))

    def test_stack_show(self):
        self._script_keystone_client()
        resp_dict = {"stack": {
            "id": "1",
            "stack_name": "teststack",
            "stack_status": 'CREATE_COMPLETE',
            "creation_time": "2012-10-25T01:58:47Z"
        }}
        resp = fakes.FakeHTTPResponse(
            200,
            'OK',
            {'content-type': 'application/json'},
            jsonutils.dumps(resp_dict))
        http.HTTPClient.json_request(
            'GET', '/stacks/teststack/1').AndReturn((resp, resp_dict))

        self.m.ReplayAll()

        list_text = self.shell('stack-show teststack/1')

        required = [
            'id',
            'stack_name',
            'stack_status',
            'creation_time',
            'teststack',
            'CREATE_COMPLETE',
            '2012-10-25T01:58:47Z'
        ]
        for r in required:
            self.assertRegexpMatches(list_text, r)

    def test_stack_abandon(self):
        self._script_keystone_client()

        resp_dict = {"stack": {
            "id": "1",
            "stack_name": "teststack",
            "stack_status": 'CREATE_COMPLETE',
            "creation_time": "2012-10-25T01:58:47Z"
        }}

        abandoned_stack = {
            "action": "CREATE",
            "status": "COMPLETE",
            "name": "teststack",
            "id": "1",
            "resources": {
                "foo": {
                    "name": "foo",
                    "resource_id": "test-res-id",
                    "action": "CREATE",
                    "status": "COMPLETE",
                    "resource_data": {},
                    "metadata": {},
                }
            }
        }

        resp = fakes.FakeHTTPResponse(
            200,
            'OK',
            {'content-type': 'application/json'},
            jsonutils.dumps(resp_dict))
        http.HTTPClient.json_request(
            'GET', '/stacks/teststack/1').AndReturn((resp, resp_dict))
        http.HTTPClient.json_request(
            'DELETE',
            '/stacks/teststack/1/abandon').AndReturn((resp, abandoned_stack))

        self.m.ReplayAll()
        abandon_resp = self.shell('stack-abandon teststack/1')
        self.assertEqual(abandoned_stack, jsonutils.loads(abandon_resp))

    def _output_fake_response(self):
        self._script_keystone_client()

        resp_dict = {"stack": {
            "id": "1",
            "stack_name": "teststack",
            "stack_status": 'CREATE_COMPLETE',
            "creation_time": "2012-10-25T01:58:47Z",
            "outputs": [
                {
                    "output_value": "value1",
                    "output_key": "output1",
                    "description": "test output 1",
                },
                {
                    "output_value": ["output", "value", "2"],
                    "output_key": "output2",
                    "description": "test output 2",
                },
            ],
            "creation_time": "2012-10-25T01:58:47Z"
        }}

        resp = fakes.FakeHTTPResponse(
            200,
            'OK',
            {'content-type': 'application/json'},
            jsonutils.dumps(resp_dict))

        http.HTTPClient.json_request(
            'GET', '/stacks/teststack/1').AndReturn((resp, resp_dict))

        self.m.ReplayAll()

    def test_output_list(self):
        self._output_fake_response()
        list_text = self.shell('output-list teststack/1')
        for r in ['output1', 'output2']:
            self.assertRegexpMatches(list_text, r)

    def test_output_show(self):
        self._output_fake_response()
        list_text = self.shell('output-show teststack/1 output1')
        self.assertRegexpMatches(list_text, 'value1')

    def test_template_show_cfn(self):
        self._script_keystone_client()
        template_data = open(os.path.join(TEST_VAR_DIR,
                                          'minimal.template')).read()
        resp = fakes.FakeHTTPResponse(
            200,
            'OK',
            {'content-type': 'application/json'},
            template_data)
        resp_dict = jsonutils.loads(template_data)
        http.HTTPClient.json_request(
            'GET', '/stacks/teststack/template').AndReturn((resp, resp_dict))

        self.m.ReplayAll()

        show_text = self.shell('template-show teststack')
        required = [
            '{',
            '  "AWSTemplateFormatVersion": "2010-09-09"',
            '  "Outputs": {}',
            '  "Resources": {}',
            '  "Parameters": {}',
            '}'
        ]
        for r in required:
            self.assertRegexpMatches(show_text, r)

    def test_template_show_hot(self):
        self._script_keystone_client()
        resp_dict = {"heat_template_version": "2013-05-23",
                     "parameters": {},
                     "resources": {},
                     "outputs": {}}
        resp = fakes.FakeHTTPResponse(
            200,
            'OK',
            {'content-type': 'application/json'},
            jsonutils.dumps(resp_dict))
        http.HTTPClient.json_request(
            'GET', '/stacks/teststack/template').AndReturn((resp, resp_dict))

        self.m.ReplayAll()

        show_text = self.shell('template-show teststack')
        required = [
            "heat_template_version: '2013-05-23'",
            "outputs: {}",
            "parameters: {}",
            "resources: {}"
        ]
        for r in required:
            self.assertRegexpMatches(show_text, r)

    def test_stack_preview(self):
        self._script_keystone_client()
        resp_dict = {"stack": {
            "id": "1",
            "stack_name": "teststack",
            "stack_status": 'CREATE_COMPLETE',
            "resources": {'1': {'name': 'r1'}},
            "creation_time": "2012-10-25T01:58:47Z",
        }}
        resp = fakes.FakeHTTPResponse(
            200,
            'OK',
            {'location': 'http://no.where/v1/tenant_id/stacks/teststack2/2'},
            jsonutils.dumps(resp_dict))
        http.HTTPClient.json_request(
            'POST', '/stacks/preview', data=mox.IgnoreArg(),
            headers={'X-Auth-Key': 'password', 'X-Auth-User': 'username'}
        ).AndReturn((resp, resp_dict))

        self.m.ReplayAll()

        template_file = os.path.join(TEST_VAR_DIR, 'minimal.template')
        preview_text = self.shell(
            'stack-preview teststack '
            '--template-file=%s '
            '--parameters="InstanceType=m1.large;DBUsername=wp;'
            'DBPassword=verybadpassword;KeyName=heat_key;'
            'LinuxDistribution=F17"' % template_file)

        required = [
            'stack_name',
            'id',
            'teststack',
            '1',
            'resources'
        ]

        for r in required:
            self.assertRegexpMatches(preview_text, r)

    def test_stack_create(self):
        self._script_keystone_client()
        resp = fakes.FakeHTTPResponse(
            201,
            'Created',
            {'location': 'http://no.where/v1/tenant_id/stacks/teststack2/2'},
            None)
        http.HTTPClient.json_request(
            'POST', '/stacks', data=mox.IgnoreArg(),
            headers={'X-Auth-Key': 'password', 'X-Auth-User': 'username'}
        ).AndReturn((resp, None))
        fakes.script_heat_list()

        self.m.ReplayAll()

        template_file = os.path.join(TEST_VAR_DIR, 'minimal.template')
        create_text = self.shell(
            'stack-create teststack '
            '--template-file=%s '
            '--parameters="InstanceType=m1.large;DBUsername=wp;'
            'DBPassword=verybadpassword;KeyName=heat_key;'
            'LinuxDistribution=F17"' % template_file)

        required = [
            'stack_name',
            'id',
            'teststack',
            '1'
        ]

        for r in required:
            self.assertRegexpMatches(create_text, r)

    def test_stack_create_timeout(self):
        self._script_keystone_client()
        template_file = os.path.join(TEST_VAR_DIR, 'minimal.template')
        template_data = open(template_file).read()
        resp = fakes.FakeHTTPResponse(
            201,
            'Created',
            {'location': 'http://no.where/v1/tenant_id/stacks/teststack2/2'},
            None)
        expected_data = {
            'files': {},
            'disable_rollback': True,
            'parameters': {'DBUsername': 'wp',
                           'KeyName': 'heat_key',
                           'LinuxDistribution': 'F17"',
                           '"InstanceType': 'm1.large',
                           'DBPassword': 'verybadpassword'},
            'stack_name': 'teststack',
            'environment': {},
            'template': jsonutils.loads(template_data),
            'timeout_mins': 123}
        http.HTTPClient.json_request(
            'POST', '/stacks', data=expected_data,
            headers={'X-Auth-Key': 'password', 'X-Auth-User': 'username'}
        ).AndReturn((resp, None))
        fakes.script_heat_list()

        self.m.ReplayAll()

        create_text = self.shell(
            'stack-create teststack '
            '--template-file=%s '
            '--timeout=123 '
            '--parameters="InstanceType=m1.large;DBUsername=wp;'
            'DBPassword=verybadpassword;KeyName=heat_key;'
            'LinuxDistribution=F17"' % template_file)

        required = [
            'stack_name',
            'id',
            'teststack',
            '1'
        ]

        for r in required:
            self.assertRegexpMatches(create_text, r)

    def test_stack_update_timeout(self):
        self._script_keystone_client()
        template_file = os.path.join(TEST_VAR_DIR, 'minimal.template')
        template_data = open(template_file).read()
        resp = fakes.FakeHTTPResponse(
            202,
            'Accepted',
            {},
            'The request is accepted for processing.')

        expected_data = {
            'files': {},
            'environment': {},
            'template': jsonutils.loads(template_data),
            'parameters': {'DBUsername': 'wp',
                           'KeyName': 'heat_key',
                           'LinuxDistribution': 'F17"',
                           '"InstanceType': 'm1.large',
                           'DBPassword': 'verybadpassword'},
            'timeout_mins': 123}
        http.HTTPClient.json_request(
            'PUT', '/stacks/teststack2/2',
            data=expected_data,
            headers={'X-Auth-Key': 'password', 'X-Auth-User': 'username'}
        ).AndReturn((resp, None))
        fakes.script_heat_list()

        self.m.ReplayAll()

        update_text = self.shell(
            'stack-update teststack2/2 '
            '--template-file=%s '
            '--timeout 123 '
            '--parameters="InstanceType=m1.large;DBUsername=wp;'
            'DBPassword=verybadpassword;KeyName=heat_key;'
            'LinuxDistribution=F17"' % template_file)

        required = [
            'stack_name',
            'id',
            'teststack2',
            '1'
        ]
        for r in required:
            self.assertRegexpMatches(update_text, r)

    def test_stack_create_url(self):

        self._script_keystone_client()
        resp = fakes.FakeHTTPResponse(
            201,
            'Created',
            {'location': 'http://no.where/v1/tenant_id/stacks/teststack2/2'},
            None)
        self.m.StubOutWithMock(request, 'urlopen')
        request.urlopen('http://no.where/minimal.template').AndReturn(
            six.StringIO('{"AWSTemplateFormatVersion" : "2010-09-09"}'))

        expected_data = {
            'files': {},
            'disable_rollback': True,
            'stack_name': 'teststack',
            'environment': {},
            'template': {"AWSTemplateFormatVersion": "2010-09-09"},
            'parameters': {'DBUsername': 'wp',
                           'KeyName': 'heat_key',
                           'LinuxDistribution': 'F17"',
                           '"InstanceType': 'm1.large',
                           'DBPassword': 'verybadpassword'}}

        http.HTTPClient.json_request(
            'POST', '/stacks', data=expected_data,
            headers={'X-Auth-Key': 'password', 'X-Auth-User': 'username'}
        ).AndReturn((resp, None))
        fakes.script_heat_list()

        self.m.ReplayAll()

        create_text = self.shell(
            'stack-create teststack '
            '--template-url=http://no.where/minimal.template '
            '--parameters="InstanceType=m1.large;DBUsername=wp;'
            'DBPassword=verybadpassword;KeyName=heat_key;'
            'LinuxDistribution=F17"')

        required = [
            'stack_name',
            'id',
            'teststack2',
            '2'
        ]
        for r in required:
            self.assertRegexpMatches(create_text, r)

    def test_stack_create_object(self):

        self._script_keystone_client()
        template_file = os.path.join(TEST_VAR_DIR, 'minimal.template')
        template_data = open(template_file).read()
        http.HTTPClient.raw_request(
            'GET',
            'http://no.where/container/minimal.template',
        ).AndReturn(template_data)

        resp = fakes.FakeHTTPResponse(
            201,
            'Created',
            {'location': 'http://no.where/v1/tenant_id/stacks/teststack2/2'},
            None)
        http.HTTPClient.json_request(
            'POST', '/stacks', data=mox.IgnoreArg(),
            headers={'X-Auth-Key': 'password', 'X-Auth-User': 'username'}
        ).AndReturn((resp, None))

        fakes.script_heat_list()

        self.m.ReplayAll()

        create_text = self.shell(
            'stack-create teststack2 '
            '--template-object=http://no.where/container/minimal.template '
            '--parameters="InstanceType=m1.large;DBUsername=wp;'
            'DBPassword=verybadpassword;KeyName=heat_key;'
            'LinuxDistribution=F17"')

        required = [
            'stack_name',
            'id',
            'teststack2',
            '2'
        ]
        for r in required:
            self.assertRegexpMatches(create_text, r)

    def test_stack_adopt(self):
        self._script_keystone_client()
        resp = fakes.FakeHTTPResponse(
            201,
            'Created',
            {'location': 'http://no.where/v1/tenant_id/stacks/teststack/1'},
            None)
        http.HTTPClient.json_request(
            'POST', '/stacks', data=mox.IgnoreArg(),
            headers={'X-Auth-Key': 'password', 'X-Auth-User': 'username'}
        ).AndReturn((resp, None))
        fakes.script_heat_list()

        self.m.ReplayAll()

        template_file = os.path.join(TEST_VAR_DIR, 'minimal.template')
        adopt_data_file = os.path.join(TEST_VAR_DIR, 'adopt_stack_data.json')
        adopt_text = self.shell(
            'stack-adopt teststack '
            '--template-file=%s '
            '--adopt-file=%s '
            '--parameters="InstanceType=m1.large;DBUsername=wp;'
            'DBPassword=verybadpassword;KeyName=heat_key;'
            'LinuxDistribution=F17"' % (template_file, adopt_data_file))

        required = [
            'stack_name',
            'id',
            'teststack',
            '1'
        ]

        for r in required:
            self.assertRegexpMatches(adopt_text, r)

    def test_stack_adopt_without_data(self):
        failed_msg = 'Need to specify --adopt-file'
        self._script_keystone_client()
        self.m.ReplayAll()
        template_file = os.path.join(TEST_VAR_DIR, 'minimal.template')
        self.shell_error(
            'stack-adopt teststack '
            '--template-file=%s ' % template_file, failed_msg)

    def test_stack_update(self):
        self._script_keystone_client()
        resp = fakes.FakeHTTPResponse(
            202,
            'Accepted',
            {},
            'The request is accepted for processing.')
        http.HTTPClient.json_request(
            'PUT', '/stacks/teststack2/2',
            data=mox.IgnoreArg(),
            headers={'X-Auth-Key': 'password', 'X-Auth-User': 'username'}
        ).AndReturn((resp, None))
        fakes.script_heat_list()

        self.m.ReplayAll()

        template_file = os.path.join(TEST_VAR_DIR, 'minimal.template')
        update_text = self.shell(
            'stack-update teststack2/2 '
            '--template-file=%s '
            '--parameters="InstanceType=m1.large;DBUsername=wp;'
            'DBPassword=verybadpassword;KeyName=heat_key;'
            'LinuxDistribution=F17"' % template_file)

        required = [
            'stack_name',
            'id',
            'teststack2',
            '1'
        ]
        for r in required:
            self.assertRegexpMatches(update_text, r)

    def test_stack_delete(self):
        self._script_keystone_client()
        resp = fakes.FakeHTTPResponse(
            204,
            'No Content',
            {},
            None)
        http.HTTPClient.raw_request(
            'DELETE', '/stacks/teststack2/2',
        ).AndReturn((resp, None))
        fakes.script_heat_list()

        self.m.ReplayAll()

        delete_text = self.shell('stack-delete teststack2/2')

        required = [
            'stack_name',
            'id',
            'teststack',
            '1'
        ]
        for r in required:
            self.assertRegexpMatches(delete_text, r)

    def test_stack_delete_multiple(self):
        self._script_keystone_client()
        resp = fakes.FakeHTTPResponse(
            204,
            'No Content',
            {},
            None)
        http.HTTPClient.raw_request(
            'DELETE', '/stacks/teststack1/1',
        ).AndReturn((resp, None))
        http.HTTPClient.raw_request(
            'DELETE', '/stacks/teststack2/2',
        ).AndReturn((resp, None))
        fakes.script_heat_list()

        self.m.ReplayAll()

        delete_text = self.shell('stack-delete teststack1/1 teststack2/2')

        required = [
            'stack_name',
            'id',
            'teststack',
            '1'
        ]
        for r in required:
            self.assertRegexpMatches(delete_text, r)

    def test_build_info(self):
        self._script_keystone_client()
        resp_dict = {
            'build_info': {
                'api': {'revision': 'api_revision'},
                'engine': {'revision': 'engine_revision'}
            }
        }
        resp_string = jsonutils.dumps(resp_dict)
        headers = {'content-type': 'application/json'}
        http_resp = fakes.FakeHTTPResponse(200, 'OK', headers, resp_string)
        response = (http_resp, resp_dict)
        http.HTTPClient.json_request('GET', '/build_info').AndReturn(response)

        self.m.ReplayAll()

        build_info_text = self.shell('build-info')

        required = [
            'api',
            'engine',
            'revision',
            'api_revision',
            'engine_revision',
        ]
        for r in required:
            self.assertRegexpMatches(build_info_text, r)

class ShellTestEvents(ShellBase):
    def setUp(self):
        super(ShellTestEvents, self).setUp()
        self._set_fake_env()

    # Patch os.environ to avoid required auth info.
    def _set_fake_env(self):
        fake_env = {
            'OS_USERNAME': 'username',
            'OS_PASSWORD': 'password',
            'OS_TENANT_NAME': 'tenant_name',
            'OS_AUTH_URL': 'http://no.where',
        }
        self.set_fake_env(fake_env)

    def _script_keystone_client(self):
        fakes.script_keystone_client()

    scenarios = [
        ('integer_id', dict(
            event_id_one='24',
            event_id_two='42')),
        ('uuid_id', dict(
            event_id_one='3d68809e-c4aa-4dc9-a008-933823d2e44f',
            event_id_two='43b68bae-ed5d-4aed-a99f-0b3d39c2418a'))]

    def test_event_list(self):
        self._script_keystone_client()
        resp_dict = {"events": [
                     {"event_time": "2013-12-05T14:14:30Z",
                      "id": self.event_id_one,
                      "links": [{"href": "http://heat.example.com:8004/foo",
                                 "rel": "self"},
                                {"href": "http://heat.example.com:8004/foo2",
                                 "rel": "resource"},
                                {"href": "http://heat.example.com:8004/foo3",
                                 "rel": "stack"}],
                      "logical_resource_id": "aResource",
                      "physical_resource_id": None,
                      "resource_name": "aResource",
                      "resource_status": "CREATE_IN_PROGRESS",
                      "resource_status_reason": "state changed"},
                     {"event_time": "2013-12-05T14:14:30Z",
                      "id": self.event_id_two,
                      "links": [{"href": "http://heat.example.com:8004/foo",
                                 "rel": "self"},
                                {"href": "http://heat.example.com:8004/foo2",
                                 "rel": "resource"},
                                {"href": "http://heat.example.com:8004/foo3",
                                 "rel": "stack"}],
                      "logical_resource_id": "aResource",
                      "physical_resource_id":
                      "bce15ec4-8919-4a02-8a90-680960fb3731",
                      "resource_name": "aResource",
                      "resource_status": "CREATE_COMPLETE",
                      "resource_status_reason": "state changed"}]}
        resp = fakes.FakeHTTPResponse(
            200,
            'OK',
            {'content-type': 'application/json'},
            jsonutils.dumps(resp_dict))
        stack_id = 'teststack/1'
        resource_name = 'testresource/1'
        http.HTTPClient.json_request(
            'GET', '/stacks/%s/resources/%s/events' % (
                parse.quote(stack_id, ''),
                parse.quote(strutils.safe_encode(
                    resource_name), ''))).AndReturn((resp, resp_dict))

        self.m.ReplayAll()

        event_list_text = self.shell('event-list {0} --resource {1}'.format(
                                     stack_id, resource_name))

        required = [
            'resource_name',
            'id',
            'resource_status_reason',
            'resource_status',
            'event_time',
            'aResource',
            self.event_id_one,
            self.event_id_two,
            'state changed',
            'CREATE_IN_PROGRESS',
            'CREATE_COMPLETE',
            '2013-12-05T14:14:30Z',
            '2013-12-05T14:14:30Z',
        ]
        for r in required:
            self.assertRegexpMatches(event_list_text, r)

    def test_event_show(self):
        self._script_keystone_client()
        resp_dict = {"event":
                     {"event_time": "2013-12-05T14:14:30Z",
                      "id": self.event_id_one,
                      "links": [{"href": "http://heat.example.com:8004/foo",
                                 "rel": "self"},
                                {"href": "http://heat.example.com:8004/foo2",
                                 "rel": "resource"},
                                {"href": "http://heat.example.com:8004/foo3",
                                 "rel": "stack"}],
                      "logical_resource_id": "aResource",
                      "physical_resource_id": None,
                      "resource_name": "aResource",
                      "resource_properties": {"admin_user": "im_powerful",
                                              "availability_zone": "nova"},
                      "resource_status": "CREATE_IN_PROGRESS",
                      "resource_status_reason": "state changed",
                      "resource_type": "OS::Nova::Server"
                      }}
        resp = fakes.FakeHTTPResponse(
            200,
            'OK',
            {'content-type': 'application/json'},
            jsonutils.dumps(resp_dict))
        stack_id = 'teststack/1'
        resource_name = 'testresource/1'
        http.HTTPClient.json_request(
            'GET', '/stacks/%s/resources/%s/events/%s' %
            (
                parse.quote(stack_id, ''),
                parse.quote(strutils.safe_encode(
                    resource_name), ''),
                parse.quote(self.event_id_one, '')
            )).AndReturn((resp, resp_dict))

        self.m.ReplayAll()

        event_list_text = self.shell('event-show {0} {1} {2}'.format(
                                     stack_id, resource_name,
                                     self.event_id_one))

        required = [
            'Property',
            'Value',
            'event_time',
            '2013-12-05T14:14:30Z',
            'id',
            self.event_id_one,
            'links',
            'http://heat.example.com:8004/foo[0-9]',
            'logical_resource_id',
            'physical_resource_id',
            'resource_name',
            'aResource',
            'resource_properties',
            'admin_user',
            'availability_zone',
            'resource_status',
            'CREATE_IN_PROGRESS',
            'resource_status_reason',
            'state changed',
            'resource_type',
            'OS::Nova::Server',
        ]
        for r in required:
            self.assertRegexpMatches(event_list_text, r)

class ShellTestResources(ShellBase):
    def setUp(self):
        super(ShellTestResources, self).setUp()
        self._set_fake_env()

    # Patch os.environ to avoid required auth info.
    def _set_fake_env(self):
        fake_env = {
            'OS_USERNAME': 'username',
            'OS_PASSWORD': 'password',
            'OS_TENANT_NAME': 'tenant_name',
            'OS_AUTH_URL': 'http://no.where',
        }
        self.set_fake_env(fake_env)

    def _script_keystone_client(self):
        fakes.script_keystone_client()

    def _test_resource_list(self, with_resource_name):
        self._script_keystone_client()
        resp_dict = {"resources": [
                     {"links": [{"href": "http://heat.example.com:8004/foo",
                                 "rel": "self"},
                                {"href": "http://heat.example.com:8004/foo2",
                                 "rel": "resource"}],
                      "logical_resource_id": "aLogicalResource",
                      "physical_resource_id":
                      "43b68bae-ed5d-4aed-a99f-0b3d39c2418a",
                      "resource_status": "CREATE_COMPLETE",
                      "resource_status_reason": "state changed",
                      "resource_type": "OS::Nova::Server",
                      "updated_time": "2014-01-06T16:14:26Z"}]}
        if with_resource_name:
            resp_dict["resources"][0]["resource_name"] = "aResource"
        resp = fakes.FakeHTTPResponse(
            200,
            'OK',
            {'content-type': 'application/json'},
            jsonutils.dumps(resp_dict))
        stack_id = 'teststack/1'
        http.HTTPClient.json_request(
            'GET', '/stacks/%s/resources' % (
                stack_id)).AndReturn((resp, resp_dict))

        self.m.ReplayAll()

        resource_list_text = self.shell('resource-list {0}'.format(stack_id))

        required = [
            'resource_type',
            'resource_status',
            'updated_time',
            'OS::Nova::Server',
            'CREATE_COMPLETE',
            '2014-01-06T16:14:26Z'
        ]
        if with_resource_name:
            required.append('resource_name')
            required.append('aResource')
        else:
            required.append('logical_resource_id')
            required.append("aLogicalResource")

        for r in required:
            self.assertRegexpMatches(resource_list_text, r)

    def test_resource_list(self):
        self._test_resource_list(True)

    def test_resource_list_no_resource_name(self):
        self._test_resource_list(False)

    def test_resource_list_empty(self):
        self._script_keystone_client()
        resp_dict = {"resources": []}
        resp = fakes.FakeHTTPResponse(
            200,
            'OK',
            {'content-type': 'application/json'},
            jsonutils.dumps(resp_dict))
        stack_id = 'teststack/1'
        http.HTTPClient.json_request(
            'GET', '/stacks/%s/resources' % (
                stack_id)).AndReturn((resp, resp_dict))

        self.m.ReplayAll()

        resource_list_text = self.shell('resource-list {0}'.format(stack_id))

        self.assertEqual('''\
+---------------+---------------+-----------------+--------------+
| resource_name | resource_type | resource_status | updated_time |
+---------------+---------------+-----------------+--------------+
+---------------+---------------+-----------------+--------------+
''', resource_list_text)

    def test_resource_show(self):
        self._script_keystone_client()
        resp_dict = {"resource":
                     {"description": "",
                      "links": [{"href": "http://heat.example.com:8004/foo",
                                 "rel": "self"},
                                {"href": "http://heat.example.com:8004/foo2",
                                 "rel": "resource"}],
                      "logical_resource_id": "aResource",
                      "physical_resource_id":
                      "43b68bae-ed5d-4aed-a99f-0b3d39c2418a",
                      "required_by": [],
                      "resource_name": "aResource",
                      "resource_status": "CREATE_COMPLETE",
                      "resource_status_reason": "state changed",
                      "resource_type": "OS::Nova::Server",
                      "updated_time": "2014-01-06T16:14:26Z"}}
        resp = fakes.FakeHTTPResponse(
            200,
            'OK',
            {'content-type': 'application/json'},
            jsonutils.dumps(resp_dict))
        stack_id = 'teststack/1'
        resource_name = 'aResource'
        http.HTTPClient.json_request(
            'GET', '/stacks/%s/resources/%s' %
            (
                parse.quote(stack_id, ''),
                parse.quote(strutils.safe_encode(
                    resource_name), '')
            )).AndReturn((resp, resp_dict))

        self.m.ReplayAll()

        resource_show_text = self.shell('resource-show {0} {1}'.format(
                                        stack_id, resource_name))

        required = [
            'description',
            'links',
            'http://heat.example.com:8004/foo[0-9]',
            'logical_resource_id',
            'aResource',
            'physical_resource_id',
            '43b68bae-ed5d-4aed-a99f-0b3d39c2418a',
            'required_by',
            'resource_name',
            'aResource',
            'resource_status',
            'CREATE_COMPLETE',
            'resource_status_reason',
            'state changed',
            'resource_type',
            'OS::Nova::Server',
            'updated_time',
            '2014-01-06T16:14:26Z',
        ]
        for r in required:
            self.assertRegexpMatches(resource_show_text, r)

    def test_resource_signal(self):
        self._script_keystone_client()
        resp = fakes.FakeHTTPResponse(
            200,
            'OK',
            {},
            '')
        stack_id = 'teststack/1'
        resource_name = 'aResource'
        http.HTTPClient.json_request(
            'POST', '/stacks/%s/resources/%s/signal' %
            (
                parse.quote(stack_id, ''),
                parse.quote(strutils.safe_encode(
                    resource_name), '')
            ),
            data={'message': 'Content'}).AndReturn((resp, ''))

        self.m.ReplayAll()

        text = self.shell(
            'resource-signal {0} {1} -D {{"message":"Content"}}'.format(
                stack_id, resource_name))
        self.assertEqual("", text)

    def test_resource_signal_no_data(self):
        self._script_keystone_client()
        resp = fakes.FakeHTTPResponse(
            200,
            'OK',
            {},
            '')
        stack_id = 'teststack/1'
        resource_name = 'aResource'
        http.HTTPClient.json_request(
            'POST', '/stacks/%s/resources/%s/signal' %
            (
                parse.quote(stack_id, ''),
                parse.quote(strutils.safe_encode(
                    resource_name), '')
            ), data=None).AndReturn((resp, ''))

        self.m.ReplayAll()

        text = self.shell(
            'resource-signal {0} {1}'.format(stack_id, resource_name))
        self.assertEqual("", text)

    def test_resource_signal_no_json(self):
        self._script_keystone_client()
        stack_id = 'teststack/1'
        resource_name = 'aResource'

        self.m.ReplayAll()

        error = self.assertRaises(
            exc.CommandError, self.shell,
            'resource-signal {0} {1} -D [2'.format(
                stack_id, resource_name))
        self.assertIn('Data should be in JSON format', str(error))

    def test_resource_signal_no_dict(self):
        self._script_keystone_client()
        stack_id = 'teststack/1'
        resource_name = 'aResource'

        self.m.ReplayAll()

        error = self.assertRaises(
            exc.CommandError, self.shell,
            'resource-signal {0} {1} -D "message"'.format(
                stack_id, resource_name))
        self.assertEqual('Data should be a JSON dict', str(error))

    def test_resource_signal_both_data(self):
        self._script_keystone_client()
        stack_id = 'teststack/1'
        resource_name = 'aResource'

        self.m.ReplayAll()

        error = self.assertRaises(
            exc.CommandError, self.shell,
            'resource-signal {0} {1} -D "message" -f foo'.format(
                stack_id, resource_name))
        self.assertEqual('Can only specify one of data and data-file',
                         str(error))

    def test_resource_signal_data_file(self):
        self._script_keystone_client()
        resp = fakes.FakeHTTPResponse(
            200,
            'OK',
            {},
            '')
        stack_id = 'teststack/1'
        resource_name = 'aResource'
        http.HTTPClient.json_request(
            'POST', '/stacks/%s/resources/%s/signal' %
            (
                parse.quote(stack_id, ''),
                parse.quote(strutils.safe_encode(
                    resource_name), '')
            ),
            data={'message': 'Content'}).AndReturn((resp, ''))

        self.m.ReplayAll()

        with tempfile.NamedTemporaryFile() as data_file:
            data_file.write(b'{"message":"Content"}')
            data_file.flush()
            text = self.shell(
                'resource-signal {0} {1} -f {2}'.format(
                    stack_id, resource_name, data_file.name))
            self.assertEqual("", text)

class ShellTestBuildInfo(ShellBase):
    def setUp(self):
        super(ShellTestBuildInfo, self).setUp()
        self._set_fake_env()

    def _set_fake_env(self):
        '''Patch os.environ to avoid required auth info.'''

        fake_env = {
            'OS_USERNAME': 'username',
            'OS_PASSWORD': 'password',
            'OS_TENANT_NAME': 'tenant_name',
            'OS_AUTH_URL': 'http://no.where',
        }
        self.set_fake_env(fake_env)

    def test_build_info(self):
        fakes.script_keystone_client()
        resp_dict = {
            'build_info': {
                'api': {'revision': 'api_revision'},
                'engine': {'revision': 'engine_revision'}
            }
        }
        resp_string = jsonutils.dumps(resp_dict)
        headers = {'content-type': 'application/json'}
        http_resp = fakes.FakeHTTPResponse(200, 'OK', headers, resp_string)
        response = (http_resp, resp_dict)
        http.HTTPClient.json_request('GET', '/build_info').AndReturn(response)

        self.m.ReplayAll()

        build_info_text = self.shell('build-info')

        required = [
            'api',
            'engine',
            'revision',
            'api_revision',
            'engine_revision',
        ]
        for r in required:
            self.assertRegexpMatches(build_info_text, r)

class ShellTestToken(ShellTestUserPass):

    # Rerun all ShellTestUserPass test with token auth
    def setUp(self):
        self.token = 'a_token'
        super(ShellTestToken, self).setUp()

    def _set_fake_env(self):
        fake_env = {
            'OS_AUTH_TOKEN': self.token,
            'OS_TENANT_ID': 'tenant_id',
            'OS_AUTH_URL': 'http://no.where',
            # Note we also set username/password, because create/update
            # pass them even if we have a token to support storing credentials
            # Hopefully at some point we can remove this and move to only
            # storing trust id's in heat-engine instead..
            'OS_USERNAME': 'username',
            'OS_PASSWORD': 'password'
        }
        self.set_fake_env(fake_env)

    def _script_keystone_client(self):
        fakes.script_keystone_client(token=self.token)

class ShellTestStandaloneToken(ShellTestUserPass):

    # Rerun all ShellTestUserPass test in standalone mode, where we
    # specify --os-no-client-auth, a token and Heat endpoint
    def setUp(self):
        self.token = 'a_token'
        super(ShellTestStandaloneToken, self).setUp()

    def _set_fake_env(self):
        fake_env = {
            'OS_AUTH_TOKEN': self.token,
            'OS_NO_CLIENT_AUTH': 'True',
            'HEAT_URL': 'http://no.where',
            # Note we also set username/password, because create/update
            # pass them even if we have a token to support storing credentials
            # Hopefully at some point we can remove this and move to only
            # storing trust id's in heat-engine instead..
            'OS_USERNAME': 'username',
            'OS_PASSWORD': 'password'
        }
        self.set_fake_env(fake_env)

    def _script_keystone_client(self):
        # The StanaloneMode shouldn't need any keystoneclient stubbing
        pass

    def test_bad_template_file(self):
        failed_msg = 'Error parsing template '

        with tempfile.NamedTemporaryFile() as bad_json_file:
            bad_json_file.write(b"{foo:}")
            bad_json_file.flush()
            self.shell_error("stack-create ts -f %s" % bad_json_file.name,
                             failed_msg)

        with tempfile.NamedTemporaryFile() as bad_json_file:
            bad_json_file.write(b'{"foo": None}')
            bad_json_file.flush()
            self.shell_error("stack-create ts -f %s" % bad_json_file.name,
                             failed_msg)


text:
'use strict';

var BatchedBridge = require('BatchedBridge');
var React = require('React');
var RecordingModule = require('NativeModules').PickerAndroidRecordingModule;
var Picker = require('Picker');
var View = require('View');

var Item = Picker.Item;

var appInstance;

class PickerAndroidTestApp extends React.Component {
  state = {
    selected: 1,
    mode: 'dropdown',
    style: {},
  };

  componentWillMount() {
    appInstance = this;
  }

  render() {
    return (
      <View collapsable={false}>
        <Picker
          mode="dialog"
          prompt="prompt"
          style={this.state.style}
          selectedValue={this.state.selected}
          onValueChange={this.onValueChange}>
          <Item label="item1" color="#ff0000" value={0} />
          <Item label="item2" color="#00ff00" value={1} />
          <Item label="item3" color="#0000ff" value={2} />
        </Picker>
        <Picker mode={this.state.mode}>
          <Item label="item1" />
          <Item label="item2" />
        </Picker>
        <Picker enabled={false}>
          <Item label="item1" />
          <Item label="item2" />
        </Picker>
        <Picker
          mode="dropdown"
          selectedValue={this.state.selected}
          onValueChange={this.onValueChange}>
          <Item label="item in sync 1" value={0} />
          <Item label="item in sync 2" value={1} />
          <Item label="item in sync 3" value={2} />
        </Picker>
      </View>
    );
  }

  onValueChange = (value) => {
    this.setState({selected: value});
    RecordingModule.recordSelection(value);
  };
}

var PickerAndroidTestModule = {
  PickerAndroidTestApp: PickerAndroidTestApp,
  selectItem: function(value) {
    appInstance.setState({selected: value});
  },
  setMode: function(mode) {
    appInstance.setState({mode: mode});
  },
  setPrimaryColor: function(color) {
    appInstance.setState({style: {color}});
  },
};

BatchedBridge.registerCallableModule(
  'PickerAndroidTestModule',
  PickerAndroidTestModule
);

module.exports = PickerAndroidTestModule;

redpajama_set_name: RedPajamaGithub


text: docker build -t alexellis2/learnyounodedocker .


text:
#define _GNU_SOURCE
#define _XOPEN_SOURCE
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <limits.h>
#include <fcntl.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <dirent.h>
#include <expat.h>

#include "pool.h"
#include "repo.h"
#include "util.h"
#define DISABLE_SPLIT
#include "tools_util.h"
#include "repo_content.h"
#include "repo_zyppdb.h"
#include "repo_products.h"
#include "repo_releasefile_products.h"

enum state {
  STATE_START,
  STATE_PRODUCT,
  STATE_VENDOR,
  STATE_NAME,
  STATE_VERSION,
  STATE_RELEASE,
  STATE_ARCH,
  STATE_SUMMARY,
  STATE_SHORTSUMMARY,
  STATE_DESCRIPTION,
  STATE_UPDATEREPOKEY,
  STATE_CPEID,
  STATE_URLS,
  STATE_URL,
  STATE_RUNTIMECONFIG,
  STATE_LINGUAS,
  STATE_LANG,
  STATE_REGISTER,
  STATE_TARGET,
  STATE_REGRELEASE,
  STATE_PRODUCTLINE,
  STATE_REGUPDATES,
  STATE_REGUPDREPO,
  STATE_ENDOFLIFE,
  NUMSTATES
};

struct stateswitch {
  enum state from;
  char *ename;
  enum state to;
  int docontent;
};

/* !! must be sorted by first column !! */
static struct stateswitch stateswitches[] = {
  { STATE_START,     "product",       STATE_PRODUCT,       0 },
  { STATE_PRODUCT,   "vendor",        STATE_VENDOR,        1 },
  { STATE_PRODUCT,   "name",          STATE_NAME,          1 },
  { STATE_PRODUCT,   "version",       STATE_VERSION,       1 },
  { STATE_PRODUCT,   "release",       STATE_RELEASE,       1 },
  { STATE_PRODUCT,   "arch",          STATE_ARCH,          1 },
  { STATE_PRODUCT,   "productline",   STATE_PRODUCTLINE,   1 },
  { STATE_PRODUCT,   "summary",       STATE_SUMMARY,       1 },
  { STATE_PRODUCT,   "shortsummary",  STATE_SHORTSUMMARY,  1 },
  { STATE_PRODUCT,   "description",   STATE_DESCRIPTION,   1 },
  { STATE_PRODUCT,   "register",      STATE_REGISTER,      0 },
  { STATE_PRODUCT,   "urls",          STATE_URLS,          0 },
  { STATE_PRODUCT,   "runtimeconfig", STATE_RUNTIMECONFIG, 0 },
  { STATE_PRODUCT,   "linguas",       STATE_LINGUAS,       0 },
  { STATE_PRODUCT,   "updaterepokey", STATE_UPDATEREPOKEY, 1 },
  { STATE_PRODUCT,   "cpeid",         STATE_CPEID,         1 },
  { STATE_PRODUCT,   "endoflife",     STATE_ENDOFLIFE,     1 },
  { STATE_URLS,      "url",           STATE_URL,           1 },
  { STATE_LINGUAS,   "lang",          STATE_LANG,          0 },
  { STATE_REGISTER,  "target",        STATE_TARGET,        1 },
  { STATE_REGISTER,  "release",       STATE_REGRELEASE,    1 },
  { STATE_REGISTER,  "updates",       STATE_REGUPDATES,    0 },
  { STATE_REGUPDATES, "repository",   STATE_REGUPDREPO,    0 },
  { NUMSTATES }
};

struct parsedata {
  const char *filename;
  const char *basename;
  int depth;
  enum state state;
  int statedepth;
  char *content;
  int lcontent;
  int acontent;
  int docontent;
  Pool *pool;
  Repo *repo;
  Repodata *data;

  struct stateswitch *swtab[NUMSTATES];
  enum state sbtab[NUMSTATES];
  struct joindata jd;

  const char *tmplang;

  const char *tmpvers;
  const char *tmprel;
  Id urltype;

  unsigned int ctime;

  Solvable *solvable;
  Id handle;

  ino_t baseproduct;
  ino_t currentproduct;
  int productscheme;
};

/*
 * find_attr
 * find value for xml attribute
 * I: txt, name of attribute
 * I: atts, list of key/value attributes
 * O: pointer to value of matching key, or NULL
 *
 */

static inline const char *
find_attr(const char *txt, const char **atts)
{
  for (; *atts; atts += 2)
    {
      if (!strcmp(*atts, txt))
        return atts[1];
    }
  return 0;
}

static time_t
datestr2timestamp(const char *date)
{
  const char *p;
  struct tm tm;

  if (!date || !*date)
    return 0;
  for (p = date; *p >= '0' && *p <= '9'; p++)
    ;
  if (!*p)
    return atoi(date);
  memset(&tm, 0, sizeof(tm));
  p = strptime(date, "%F%T", &tm);
  if (!p)
    {
      memset(&tm, 0, sizeof(tm));
      p = strptime(date, "%F", &tm);
      if (!p || *p)
	return 0;
    }
  return timegm(&tm);
}

/*
 * XML callback: startElement
 */

static void XMLCALL
startElement(void *userData, const char *name, const char **atts)
{
  struct parsedata *pd = userData;
  Pool *pool = pd->pool;
  Solvable *s = pd->solvable;
  struct stateswitch *sw;

#if 0
  fprintf(stderr, "start: [%d]%s\n", pd->state, name);
#endif
  if (pd->depth != pd->statedepth)
    {
      pd->depth++;
      return;
    }

  pd->depth++;
  if (!pd->swtab[pd->state])	/* no statetable -> no substates */
    {
#if 0
      fprintf(stderr, "into unknown: %s (from: %d)\n", name, pd->state);
#endif
      return;
    }
  for (sw = pd->swtab[pd->state]; sw->from == pd->state; sw++)  /* find name in statetable */
    if (!strcmp(sw->ename, name))
      break;

  if (sw->from != pd->state)
    {
#if 0
      fprintf(stderr, "into unknown: %s (from: %d)\n", name, pd->state);
#endif
      return;
    }
  pd->state = sw->to;
  pd->docontent = sw->docontent;
  pd->statedepth = pd->depth;
  pd->lcontent = 0;
  *pd->content = 0;

  switch(pd->state)
    {
    case STATE_PRODUCT:
      /* parse 'schemeversion' and store in global variable */
      {
        const char * scheme = find_attr("schemeversion", atts);
        pd->productscheme = (scheme && *scheme) ? atoi(scheme) : -1;
      }
      if (!s)
	{
	  s = pd->solvable = pool_id2solvable(pool, repo_add_solvable(pd->repo));
	  pd->handle = s - pool->solvables;
	}
      break;

      /* <summary lang="xy">... */
    case STATE_SUMMARY:
    case STATE_DESCRIPTION:
      pd->tmplang = join_dup(&pd->jd, find_attr("lang", atts));
      break;
    case STATE_URL:
      pd->urltype = pool_str2id(pd->pool, find_attr("name", atts), 1);
      break;
    case STATE_REGUPDREPO:
      {
        const char *repoid = find_attr("repoid", atts);
	if (repoid && *repoid)
	  {
	    Id h = repodata_new_handle(pd->data);
	    repodata_set_str(pd->data, h, PRODUCT_UPDATES_REPOID, repoid);
	    repodata_add_flexarray(pd->data, pd->handle, PRODUCT_UPDATES, h);
	  }
	break;
      }
    default:
      break;
    }
}

static void XMLCALL
endElement(void *userData, const char *name)
{
  struct parsedata *pd = userData;
  Solvable *s = pd->solvable;

#if 0
  fprintf(stderr, "end: [%d]%s\n", pd->state, name);
#endif
  if (pd->depth != pd->statedepth)
    {
      pd->depth--;
#if 0
      fprintf(stderr, "back from unknown %d %d %d\n", pd->state, pd->depth, pd->statedepth);
#endif
      return;
    }

  pd->depth--;
  pd->statedepth--;

  switch (pd->state)
    {
    case STATE_PRODUCT:
      /* product done, finish solvable */
      if (pd->ctime)
        repodata_set_num(pd->data, pd->handle, SOLVABLE_INSTALLTIME, pd->ctime);

      if (pd->basename)
        repodata_set_str(pd->data, pd->handle, PRODUCT_REFERENCEFILE, pd->basename);

      /* this is where <productsdir>/baseproduct points to */
      if (pd->currentproduct == pd->baseproduct)
	repodata_set_str(pd->data, pd->handle, PRODUCT_TYPE, "base");

      if (pd->tmprel)
	{
	  if (pd->tmpvers)
	    s->evr = makeevr(pd->pool, join2(&pd->jd, pd->tmpvers, "-", pd->tmprel));
	  else
	    {
	      fprintf(stderr, "Seen <release> but no <version>\n");
	    }
	}
      else if (pd->tmpvers)
	s->evr = makeevr(pd->pool, pd->tmpvers); /* just version, no release */
      pd->tmpvers = solv_free((void *)pd->tmpvers);
      pd->tmprel = solv_free((void *)pd->tmprel);
      if (!s->arch)
	s->arch = ARCH_NOARCH;
      if (!s->evr)
	s->evr = ID_EMPTY;
      if (s->name && s->arch != ARCH_SRC && s->arch != ARCH_NOSRC)
	s->provides = repo_addid_dep(pd->repo, s->provides, pool_rel2id(pd->pool, s->name, s->evr, REL_EQ, 1), 0);
      pd->solvable = 0;
      break;
    case STATE_VENDOR:
      s->vendor = pool_str2id(pd->pool, pd->content, 1);
      break;
    case STATE_NAME:
      s->name = pool_str2id(pd->pool, join2(&pd->jd, "product", ":", pd->content), 1);
      break;
    case STATE_VERSION:
      pd->tmpvers = solv_strdup(pd->content);
      break;
    case STATE_RELEASE:
      pd->tmprel = solv_strdup(pd->content);
      break;
    case STATE_ARCH:
      s->arch = pool_str2id(pd->pool, pd->content, 1);
      break;
    case STATE_PRODUCTLINE:
      repodata_set_str(pd->data, pd->handle, PRODUCT_PRODUCTLINE, pd->content);
    break;
    case STATE_UPDATEREPOKEY:
      /** obsolete **/
      break;
    case STATE_SUMMARY:
      repodata_set_str(pd->data, pd->handle, pool_id2langid(pd->pool, SOLVABLE_SUMMARY, pd->tmplang, 1), pd->content);
      break;
    case STATE_SHORTSUMMARY:
      repodata_set_str(pd->data, pd->handle, PRODUCT_SHORTLABEL, pd->content);
      break;
    case STATE_DESCRIPTION:
      repodata_set_str(pd->data, pd->handle, pool_id2langid(pd->pool, SOLVABLE_DESCRIPTION, pd->tmplang, 1), pd->content);
      break;
    case STATE_URL:
      if (pd->urltype)
        {
          repodata_add_poolstr_array(pd->data, pd->handle, PRODUCT_URL, pd->content);
          repodata_add_idarray(pd->data, pd->handle, PRODUCT_URL_TYPE, pd->urltype);
        }
      break;
    case STATE_TARGET:
      repodata_set_str(pd->data, pd->handle, PRODUCT_REGISTER_TARGET, pd->content);
      break;
    case STATE_REGRELEASE:
      repodata_set_str(pd->data, pd->handle, PRODUCT_REGISTER_RELEASE, pd->content);
      break;
    case STATE_CPEID:
      if (*pd->content)
        repodata_set_str(pd->data, pd->handle, SOLVABLE_CPEID, pd->content);
      break;
    case STATE_ENDOFLIFE:
      if (*pd->content)
	{
	  time_t t = datestr2timestamp(pd->content);
	  if (t)
	    repodata_set_num(pd->data, pd->handle, PRODUCT_ENDOFLIFE, (unsigned long long)t);
	}
      break;
    default:
      break;
    }

  pd->state = pd->sbtab[pd->state];
  pd->docontent = 0;

#if 0
      fprintf(stderr, "end: [%s] -> %d\n", name, pd->state);
#endif
}

static void XMLCALL
characterData(void *userData, const XML_Char *s, int len)
{
  struct parsedata *pd = userData;
  int l;
  char *c;
  if (!pd->docontent)
    return;
  l = pd->lcontent + len + 1;
  if (l > pd->acontent)
    {
      pd->content = solv_realloc(pd->content, l + 256);
      pd->acontent = l + 256;
    }
  c = pd->content + pd->lcontent;
  pd->lcontent += len;
  while (len-- > 0)
    *c++ = *s++;
  *c = 0;
}

#define BUFF_SIZE 8192

/*
 * add single product to repo
 *
 */

static void
add_code11_product(struct parsedata *pd, FILE *fp)
{
  char buf[BUFF_SIZE];
  int l;
  struct stat st;
  XML_Parser parser;

  if (!fstat(fileno(fp), &st))
    {
      pd->currentproduct = st.st_ino;
      pd->ctime = (unsigned int)st.st_ctime;
    }
  else
    {
      pd->currentproduct = pd->baseproduct + 1; /* make it != baseproduct if stat fails */
      pool_error(pd->pool, 0, "fstat: %s", strerror(errno));
      pd->ctime = 0;
    }

  parser = XML_ParserCreate(NULL);
  XML_SetUserData(parser, pd);
  XML_SetElementHandler(parser, startElement, endElement);
  XML_SetCharacterDataHandler(parser, characterData);

  for (;;)
    {
      l = fread(buf, 1, sizeof(buf), fp);
      if (XML_Parse(parser, buf, l, l == 0) == XML_STATUS_ERROR)
	{
	  pool_debug(pd->pool, SOLV_ERROR, "%s: %s at line %u:%u\n", pd->filename, XML_ErrorString(XML_GetErrorCode(parser)), (unsigned int)XML_GetCurrentLineNumber(parser), (unsigned int)XML_GetCurrentColumnNumber(parser));
	  XML_ParserFree(parser);
	  if (pd->solvable)
	    {
	      repo_free_solvable(pd->repo, pd->solvable - pd->pool->solvables, 1);
	      pd->solvable = 0;
	    }
	  return;
	}
      if (l == 0)
	break;
    }
  XML_ParserFree(parser);
}

int
repo_add_code11_products(Repo *repo, const char *dirpath, int flags)
{
  Repodata *data;
  struct parsedata pd;
  struct stateswitch *sw;
  DIR *dir;
  int i;

  data = repo_add_repodata(repo, flags);

  memset(&pd, 0, sizeof(pd));
  pd.repo = repo;
  pd.pool = repo->pool;
  pd.data = data;

  pd.content = solv_malloc(256);
  pd.acontent = 256;

  for (i = 0, sw = stateswitches; sw->from != NUMSTATES; i++, sw++)
    {
      if (!pd.swtab[sw->from])
        pd.swtab[sw->from] = sw;
      pd.sbtab[sw->to] = sw->from;
    }

  if (flags & REPO_USE_ROOTDIR)
    dirpath = pool_prepend_rootdir(repo->pool, dirpath);
  dir = opendir(dirpath);
  if (dir)
    {
      struct dirent *entry;
      struct stat st;
      char *fullpath;

      /* check for <productsdir>/baseproduct on code11 and remember its target inode */
      if (stat(join2(&pd.jd, dirpath, "/", "baseproduct"), &st) == 0) /* follow symlink */
	pd.baseproduct = st.st_ino;
      else
	pd.baseproduct = 0;

      while ((entry = readdir(dir)))
	{
	  int len = strlen(entry->d_name);
	  FILE *fp;
	  if (len <= 5 || strcmp(entry->d_name + len - 5, ".prod") != 0)
	    continue;
	  fullpath = join2(&pd.jd, dirpath, "/", entry->d_name);
	  fp = fopen(fullpath, "r");
	  if (!fp)
	    {
	      pool_error(repo->pool, 0, "%s: %s", fullpath, strerror(errno));
	      continue;
	    }
	  pd.filename = fullpath;
	  pd.basename = entry->d_name;
	  add_code11_product(&pd, fp);
	  fclose(fp);
	}
      closedir(dir);
    }
  solv_free(pd.content);
  join_freemem(&pd.jd);
  if (flags & REPO_USE_ROOTDIR)
    solv_free((char *)dirpath);

  if (!(flags & REPO_NO_INTERNALIZE))
    repodata_internalize(data);
  return 0;
}

/******************************************************************************************/

/*
 * read all installed products
 *
 * try proddir (reading all .xml files from this directory) first
 * if not available, assume non-code11 layout and parse /etc/xyz-release
 *
 * parse each one as a product
 */

/* Oh joy! Three parsers for the price of one! */

int
repo_add_products(Repo *repo, const char *proddir, int flags)
{
  const char *fullpath;
  DIR *dir;

  if (proddir)
    {
      dir = opendir(flags & REPO_USE_ROOTDIR ? pool_prepend_rootdir_tmp(repo->pool, proddir) : proddir);
      if (dir)
	{
	  /* assume code11 stype products */
	  closedir(dir);
	  return repo_add_code11_products(repo, proddir, flags);
	}
    }

  /* code11 didn't work, try old code10 zyppdb */
  fullpath = "/var/lib/zypp/db/products";
  if (flags & REPO_USE_ROOTDIR)
    fullpath = pool_prepend_rootdir_tmp(repo->pool, fullpath);
  dir = opendir(fullpath);
  if (dir)
    {
      closedir(dir);
      /* assume code10 style products */
      return repo_add_zyppdb_products(repo, "/var/lib/zypp/db/products", flags);
    }

  /* code10/11 didn't work, try -release files parsing */
  fullpath = "/etc";
  if (flags & REPO_USE_ROOTDIR)
    fullpath = pool_prepend_rootdir_tmp(repo->pool, fullpath);
  dir = opendir(fullpath);
  if (dir)
    {
      closedir(dir);
      return repo_add_releasefile_products(repo, "/etc", flags);
    }

  /* no luck. check if the rootdir exists */
  fullpath = pool_get_rootdir(repo->pool);
  if (fullpath && *fullpath)
    {
      dir = opendir(fullpath);
      if (!dir)
	return pool_error(repo->pool, -1, "%s: %s", fullpath, strerror(errno));
      closedir(dir);
    }

  /* the least we can do... */
  if (!(flags & REPO_NO_INTERNALIZE) && (flags & REPO_REUSE_REPODATA) != 0)
    repodata_internalize(repo_last_repodata(repo));
  return 0;
}

/* EOF */


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title><dom-bind-notifier></title>
    <link rel="stylesheet" href="http://juicy.github.io/github-markdown-css/github-markdown.css">

    <link rel="import" href="../polymer/polymer.html">
    <link rel="import" href="simple-component.html">
    <link rel="import" href="array-component.html">

    <dom-bind-notifier>

      Adds good old Object.observe to Polymer 1.5 template binding (dom-bind)

    Here we bind external static JS object literal to Polymer's dom-bind.
    All changes on it, are automatically notified to Polymer templates.
    Open debug console, and fiddle with simple, deep, arrays objects

Examples

Simple

<dom-module id="simple-component">
  <template>
    <h4>ToDo list for {{model.user}}:</h4>
    <button on-tap="ChangeName" >Change Name</button>
	<dom-bind-notifier path="model" observed-object="{{model}}"></dom-bind-notifier>
  </template>
</dom-module>
<script>
Polymer({
  is: 'simple-component',
  ready: function() {
	this.model = {user: 'Artur'};
  },
  ChangeName: function() {
	this.model.user = this.model.user + "_1";
  }
});
</script>

     <simple-component id="component1"/>

      <button onclick="document.getElementById('component1').model.user='New Name'">Modify externally</button>

Arrays

<dom-module id="array-component">
	<template is="dom-bind" id="arrays">
	  <h4><span>{{organization.name}}</span> people:</h4>
	  <ul>
		<template  is="dom-repeat" items="{{organization.people}}">
		  <li><span>{{item.first}}</span> <span>{{item.last}}</span></li>
		</template>
	  </ul>

	  <button on-tap="ChangeName">Click to change <code>arrays.people[1].first</code>to an apple</button>
	  <dom-bind-notifier path="organization" observed-object="{{organization}}" deep></dom-bind-notifier>
	</template>
</dom-module>

<script>
Polymer({
  is: 'array-component',
  ready: function() {
	this.organization = {
	  name: "Juicy",
	  people: [
		{
		  first: "Tomek",
		  last: "Wytrębowicz"
		}
	  ]
	};
  },
  ChangeName: function() {
	this.organization.people[1].first= 'An Apple';
  }
});
</script>

     <array-component id="component2"/>

      <button onclick="document.getElementById('component2').organization.people.push({first:'New', last:'Guy'});">Click to push a new guy to arrays.people</button>
      <button onclick="document.getElementById('component2').organization.people.splice(1,0,{first:'Some', last:'One'});">Click to splice someone in the middle ofarrays.people</button>
      <button onclick="document.getElementById('component2').organization.people.shift();">Click to shift a person from arrays.people</button>


text:
require "backbone/deep/rails/version"
require 'backbone/deep/rails/engine'

module Backbone
  module Deep
    module Rails
    end
  end
end


text:
void test01()
{
  bool test __attribute__((unused)) = true;
  using std::is_function;
  using namespace __gnu_test;

  VERIFY( (test_category<is_function, IncompleteClass>(false)) );
}

int main()
{
  test01();
  return 0;
}


text:
package org.apache.hadoop.yarn.server.resourcemanager.recovery;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.security.client.RMDelegationTokenIdentifier;
import org.apache.hadoop.yarn.server.resourcemanager.ResourceManager;
import org.junit.Test;

import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;

public class TestMemoryRMStateStore {

  @Test
  public void testNotifyStoreOperationFailed() throws Exception {
    RMStateStore store = new MemoryRMStateStore() {
      @Override
      public synchronized void removeRMDelegationTokenState(
          RMDelegationTokenIdentifier rmDTIdentifier) throws Exception {
        throw new Exception("testNotifyStoreOperationFailed");
      }
    };
    Configuration conf = new Configuration();
    conf.setBoolean(YarnConfiguration.RM_HA_ENABLED, true);
    store.init(conf);
    ResourceManager mockRM = mock(ResourceManager.class);
    store.setResourceManager(mockRM);
    RMDelegationTokenIdentifier mockTokenId =
        mock(RMDelegationTokenIdentifier.class);
    store.removeRMDelegationToken(mockTokenId);
    assertTrue("RMStateStore should have been in fenced state",
        store.isFencedState());
    store = new MemoryRMStateStore() {
      @Override
      public synchronized void removeRMDelegationToken(
          RMDelegationTokenIdentifier rmDTIdentifier) {
        notifyStoreOperationFailed(new Exception(
            "testNotifyStoreOperationFailed"));
      }
    };
    store.init(conf);
    store.setResourceManager(mockRM);
    store.removeRMDelegationToken(mockTokenId);
    assertTrue("RMStateStore should have been in fenced state",
        store.isFencedState());
  }
}


text:
namespace {

static const wchar_t kTrayClassName[] = L"Shell_TrayWnd";

// If the mouse cursor is less than this distance, in pixels, away from the
// taskbar, it is considered to be in the taskbar for the purpose of anchoring.
static const int kSnapDistance = 50;

// The minimum distance, in pixels, to position the app list from the taskbar or
// edge of screen.
static const int kMinDistanceFromEdge = 3;

// Utility methods for showing the app list.
// Attempts to find the bounds of the Windows taskbar. Returns true on success.
// |rect| is in screen coordinates. If the taskbar is in autohide mode and is
// not visible, |rect| will be outside the current monitor's bounds, except for
// one pixel of overlap where the edge of the taskbar is shown.
bool GetTaskbarRect(gfx::Rect* rect) {
  HWND taskbar_hwnd = FindWindow(kTrayClassName, NULL);
  if (!taskbar_hwnd)
    return false;

  RECT win_rect;
  if (!GetWindowRect(taskbar_hwnd, &win_rect))
    return false;

  *rect = gfx::Rect(win_rect);
  return true;
}

}  // namespace

AppListWin::AppListWin(app_list::AppListView* view,
                       const base::Closure& on_should_dismiss)
    : view_(view),
      activation_tracker_(view, on_should_dismiss),
      window_icon_updated_(false) {}

AppListWin::~AppListWin() {}

gfx::Point AppListWin::FindAnchorPoint(const gfx::Size& view_size,
                                       const gfx::Display& display,
                                       const gfx::Point& cursor,
                                       const gfx::Rect& taskbar_rect) {
  AppListPositioner positioner(display, view_size, kMinDistanceFromEdge);

  // Subtract the taskbar area since the display's default work_area will not
  // subtract it if the taskbar is set to auto-hide, and the app list should
  // never overlap the taskbar.
  positioner.WorkAreaSubtract(taskbar_rect);

  // Find which edge of the screen the taskbar is attached to.
  AppListPositioner::ScreenEdge edge = positioner.GetShelfEdge(taskbar_rect);

  // Snap to the taskbar edge. If the cursor is greater than kSnapDistance away,
  // anchor to the corner. Otherwise, anchor to the cursor position.
  gfx::Point anchor;
  if (edge == AppListPositioner::SCREEN_EDGE_UNKNOWN) {
    // If we can't find the taskbar, snap to the bottom left.
    return positioner.GetAnchorPointForScreenCorner(
        AppListPositioner::SCREEN_CORNER_BOTTOM_LEFT);
  }

  if (positioner.GetCursorDistanceFromShelf(edge, cursor) > kSnapDistance)
    return positioner.GetAnchorPointForShelfCorner(edge);

  return positioner.GetAnchorPointForShelfCursor(edge, cursor);
}

void AppListWin::Show() {
  view_->GetWidget()->Show();
  if (!window_icon_updated_) {
    view_->GetWidget()->GetTopLevelWidget()->UpdateWindowIcon();
    window_icon_updated_ = true;
  }
  view_->GetWidget()->Activate();
}

void AppListWin::Hide() {
  view_->GetWidget()->Hide();
  activation_tracker_.OnViewHidden();
}

void AppListWin::MoveNearCursor() {
  gfx::Point cursor = gfx::Screen::GetNativeScreen()->GetCursorScreenPoint();
  gfx::Screen* screen =
      gfx::Screen::GetScreenFor(view_->GetWidget()->GetNativeView());
  gfx::Display display = screen->GetDisplayNearestPoint(cursor);

  view_->SetBubbleArrow(views::BubbleBorder::FLOAT);
  gfx::Rect taskbar_rect;
  GetTaskbarRect(&taskbar_rect);
  view_->SetAnchorPoint(FindAnchorPoint(view_->GetPreferredSize(), display,
                                        cursor, taskbar_rect));
}

bool AppListWin::IsVisible() {
  return view_->GetWidget()->IsVisible();
}

void AppListWin::Prerender() {
  view_->Prerender();
}

void AppListWin::ReactivateOnNextFocusLoss() {
  activation_tracker_.ReactivateOnNextFocusLoss();
}

gfx::NativeWindow AppListWin::GetWindow() {
  return view_->GetWidget()->GetNativeWindow();
}

void AppListWin::SetProfile(Profile* profile) {
  view_->SetProfileByPath(profile->GetPath());
}


text:
ReadFifo = {}

function ReadFifo:close()
  self.readfd:close()
  os.remove(self.path)
end

function ReadFifo:truncate()
  self.readfd:close()
  local fd = assert(io.open(self.path, "w"))
  fd:flush()
  fd:close()
  self.readfd = assert(io.open(self.path, "r"))
end

function ReadFifo:read(mode)
  if not mode then mode = "a" end
  if io.type(self.readfd) ~= "file" then return nil end
  local result = self.readfd:read(mode)
  return result
end

function ReadFifo.new(name)
  local fifo = setmetatable({}, {__index=ReadFifo})
  fifo.path = name
  fifo.readfd = assert(io.open(fifo.path, "r"))
  return fifo
end


text:
'''
Uses the 'ecl_summary' command found in the Ensambles ERT software package
created by statoil to read and plot data from an eclipse summary file.
Requires both a *.UNSMRY and *.SMSPEC file to be present.

https://github.com/Ensembles/ert
'''

from matplotlib import pyplot as plt
import subprocess

def list_summary_files():
    summary_files = subprocess.check_output(['find', '.', '-name', '*.UNSMRY'])
    summary_files = summary_files.split('\n')
    if summary_files[-1] == '':
        summary_files.pop()  # Deleting empty element at end
    # Removing ./ and .UNSMRY
    summary_files = [sumfile[2:-7] for sumfile in summary_files]

    print '\n',
    print '|-----------------------------------------------------------------|'
    print '| The following files are available in the active folder:         |'
    print '|-----------------------------------------------------------------|'
    for i in range(len(summary_files)):
        print '| (%i) %s' % (i, summary_files[i])
    print '|-----------------------------------------------------------------|'
    return summary_files

def get_file_name():
    summary_files = list_summary_files()
    input_file = raw_input('\nFilename or number: ')
    try:
        file_number = int(input_file)
        filename = summary_files[file_number]
    except Exception:
        filename = input_file
    return filename

def get_wells(filename):
    wellist = subprocess.check_output([
                                      "ecl_summary",
                                      filename,
                                      "--list", "WBHP:*"
                                      ])
    wellist = wellist.split(' ')
    while '' in wellist:
        wellist.remove('')
    wellist.pop()  # Last element is \n
    wellist = [well.strip().split(':') for well in wellist]
    wellist = [well[1] for well in wellist]

    print '\n\n',
    print '|-----------------------------------------------------------------|'
    print '| The following wells are available:                              |'
    print '|-----------------------------------------------------------------|'
    print '| ',
    for well in range(len(wellist)):
        print wellist[well] + '\t',
        if (well % 6) == 0 and well != 0:
            print '\n| ',
    print '\n|-----------------------------------------------------------------|'
    wells = raw_input('\nSelect wells (space-separated): ').split(' ')
    print '\n'
    return wells

def get_properties(filename, wells):
    print "The following properties are available for the selected wells:"
    print '==================================================================='
    proplist = []
    for well in wells:
        proplist.append(subprocess.check_output([
                                                "ecl_summary",
                                                filename, "--list",
                                                '*:' + well]))
    for well in range(len(proplist)):
        proplist[well] = proplist[well].split(' ')
        proplist[well].pop()
        while '' in proplist[well]:
            proplist[well].remove('')
        proplist[well] = [prop.strip().split(':') for prop in proplist[well]]
        proplist[well] = [prop[0] for prop in proplist[well]]

    for well in range(len(proplist)):
        print '|-----------------------------------------------------------------|'
        print '| Properties for well ' + wells[well]
        print '|-----------------------------------------------------------------|'
        #print proplist[well]
        for prop in range(len(proplist[well])):
            print proplist[well][prop] + '\t',
            if (prop % 8) == 0 and prop != 0 and prop < len(proplist[well]):
                print '\n',
        print '\n'
    props = raw_input('Properties to plot (space-separated): ').split(' ')
    return props

def get_field_props(filename):
    print 'Available properties are:'
    proplist = subprocess.check_output([
                                       "ecl_summary",
                                       filename,
                                       "--list",
                                       "F*"])
    proplist = proplist.replace('\n', "")
    proplist = proplist.split(' ')
    while '' in proplist:
        proplist.remove('')
    for prop in range(len(proplist)):
        print proplist[prop] + '\t',
        if (prop % 8) == 0 and prop != 0 and prop < len(proplist):
            print '\n',
    print '\n'
    props = raw_input('Properties to plot (space-separated): ').split(' ')
    return props

def create_propery_selection_string(props, wells):
    propstrings = []
    for p in range(len(props)):
        for w in range(len(wells)):
            propstrings.append(props[p] + ':' + wells[w])
    return propstrings

def get_summary_output(filename, propstrings):
    command = ["ecl_summary", filename]
    for propstring in propstrings:
        command.append(propstring)
    return subprocess.check_output(command)

def parse_output(output):
    lines = output.split("\n")
    headers = lines[0].split(" ")
    headers = [x for x in headers if x != ' ' and x != '' and x != '--']
    valuelines = lines[2:]
    valuelines = [line.split(' ') for line in valuelines]
    for line in valuelines:
        while '' in line:
            line.remove('')
    valuelines.pop()  # Removing \n at the end
    return (headers, valuelines)

def create_time_vector(valuelines):
    time = []
    for line in valuelines:
        time.append(line[0])
    return time

def create_value_vectors(valuelines, props, wells):
    values = [[]]
    for i in range(len(props)):
        for j in range(len(wells)):
            for line in valuelines:
                values[i*len(wells)+j].append(line[2+i*len(wells)+j])
            values.append([])
    values.pop()
    return values

def plot_values(propstrings, values, time, props, wells):
    fig = plt.figure(figsize=(10, 5))
    plots = []
    for i in range(len(props)):
        for j in range(len(wells)):
            line, = plt.plot(time, values[i*len(wells)+j])
            plots.append(line)

    plt.legend(plots, propstrings, loc=2)
    fig1 = plt.gcf()
    fig1.set_size_inches(10.5, 10.5)
    plt.show()

    save = raw_input('Save figure (y/n)? ')
    if save.lower() == 'y':
        figname = raw_input('Figure name: ')
        fig1.savefig('%s.pdf' % figname)

    next_action = raw_input('Quit program (q) or write data to csv (w)? ')

    if next_action.lower() == 'q':
        plt.close()
    elif next_action.lower() == 'w':
        plt.close()
        write_data_to_csv(propstrings, values, time, wells, props)

def write_data_to_csv(propstrings, values, time, wells, props):
    output_filename = raw_input("Name of output file:")
    f = open(output_filename, 'w')

    # Write headers
    f.write('TIME,')
    for header in propstrings:
        f.write(header + ',')

    for value in range(len(values[0])):
        f.write('\n')
        f.write(time[value] + ',')
        for prop in range(len(props)):
            for well in range(len(wells)):
                f.write(values[prop*len(wells)+well][value] + ',')

    f.close()

def get_action(action):
    if action.lower() == 'p':
        plot_values(propstrings, values, time, props, wells)
    elif action.lower() == 'w':
        write_data_to_csv(propstrings, values, time, wells, props)

# Getting input from user
filename = get_file_name()  # Getting file from user input

# Asking for well/field data
field_data = (raw_input('\n Plot field (f) or well (w) data? ') == 'f')

# Getting well and property lists
if field_data:
    print 'Selected field data.'
    props = propstrings = get_field_props(filename)
    wells = ['FIELD']
else:
    print 'Selected well data.'
    wells = get_wells(filename)  # Getting wells from user input
    props = get_properties(filename, wells)  # Getting props from user input
    propstrings = create_propery_selection_string(props, wells)  # Parsing props

# Getting the ecl_summary output and parsing it
output = get_summary_output(filename, propstrings)
(headers, valuelines) = parse_output(output)

# Creating vectors creating vectors from parsed output
time = create_time_vector(valuelines)
values = create_value_vectors(valuelines, props, wells)

action = raw_input('Plot results (p) or write to csv file (w)? ')

get_action(action)


text:
package statemachine;

import java.io.Serializable;
import java.util.Map;

/**
 * @author patrick
 *
 * @param <S>
 */
public interface TransitionSelector<S extends StatefulObject<?>> {

	/**
	 * @param defaultTransition
	 * @param validTransitions
	 * @param obj
	 * @param transitionData
	 * @return
	 */
	String selectTransition( String defaultTransition, Map<String,Serializable> validTransitions, S obj, Object... transitionData );

}


text:
pushd $(dirname "${0}") > /dev/null
DIR=$(pwd -L)
popd > /dev/null
# GProM binary
CONF_FILE=.gprom
GPROM=${DIR}/../../src/command_line/gprom
GPROM_CONF=${DIR}/../../${CONF_FILE}
########################################
# READ USER CONFIGUATION
source ${DIR}/../gprom_basic.sh
########################################
if [ $# -lt 2 ]; then
    echo "give at least two parameters, the first one is loglevel, the second one is SQL code"
	echo " "
    echo "callgrind_gprom.sh 3 \"SELECT * FROM r;\""
    exit 1
fi

LOGLEVEL=$1
SQL=$2
ARGS="${*:3}"

valgrind --tool=callgrind -v ${GPROM} ${CONNECTION_PARAMS} ${LOG} -sql "${SQL}" -treeify-algebra-graphs ${ARGS}


text:
package de.gmcs.benchmark;

import java.util.function.Consumer;
import java.util.function.Function;

public class Task<T> {

    private String name;

    private Function<Integer, T> warmupDataSupplier;
    private Function<Integer, T> benchmarkDataSupplier;

    private Consumer<T> test;

    public Task(String name, Function<Integer, T> warmupDataSupplier, Function<Integer, T> benchmarkDataSupplier, Consumer<T> test) {
        this.name = name;
        this.warmupDataSupplier = warmupDataSupplier;
        this.benchmarkDataSupplier = benchmarkDataSupplier;
        this.test = test;
    }

    public String getName() {
        return name;
    }

    public T getWarmupData(Integer loopIndex) {
        return warmupDataSupplier.apply(loopIndex);
    }

    public T getBenchmarkData(Integer loopIndex) {
        return benchmarkDataSupplier.apply(loopIndex);
    }

    public void execute(T data) {
        test.accept(data);
    }
}


text:
title: What I love about Autumn
date: 2015-09-14 00:00:00 Z
layout: post
---

There's nothing better than to go out on a really chilly, crisp Autumn morning, wrapped up in warm clothes, cup of steaming coffee in hand (there's a bit of a coffee theme going on here :smirk:) and walking to work through all the crunchy, brightly coloured leaves that litter the floor.

<!--more-->

![What I love about Autumn](/uploads/IMG_2606.jpg)

You can definitely feel that things are changing. The air and light are different; there's a whisper of bitterness in the wind; the nights are drawing in once again, preparing us for winter. That and now the summer holidays are over, the kids are back in school.

I never really liked school that much, but one of my favourite memories of going back for a new term was being taken to pick out a new school bag and all the stationery ー I'm a bit of a stationery fiend :pencil2: :black_nib: :straight_ruler: :notebook:.

Below are 10 things that I absolutely love about the season and think make it really special:

1. Crisp, cold mornings
2. Stomping through all the crunchy leaves :maple_leaf: :fallen_leaf: :leaves:
3. The amazing colours everywhere
4. Wrapping up warm in a nice coat, scarf and hat etc
5. Hot drinks
6. Wearing chunky boots and loads of layers
7. Snuggling up on the sofa with a blanket and the Boy, with a nice fire going and some films
8. Making soup
9. The fact that it's nearly my birthday (and bonfire night!)
10. Planning for Christmas

In the next few weeks, I plan on taking the Boy and my camera to our local [Arboretum](http://www.forestry.gov.uk/westonbirt) to get some shots of the amazing trees and foliage. Everything is absolutely beautiful there this time of year.

It may be pouring with rain today, but I look forward to the next time I'm out in the yellowish light of an Autumnal sun, feeling the cold prickle my cheeks and anticipating all the exciting things to come - lots of birthdays (including mine!), Christmas, and the promise of a new year.


text:
package org.jgroups.protocols;

import org.jgroups.Address;
import org.jgroups.Event;
import org.jgroups.Message;
import org.jgroups.annotations.MBean;
import org.jgroups.annotations.Property;
import org.jgroups.conf.AttributeType;
import org.jgroups.stack.Protocol;
import org.jgroups.util.AsciiString;
import org.jgroups.util.MessageBatch;
import org.jgroups.util.TimeScheduler;

import java.util.*;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * Intercepts individual up messages and creates batches from them, passing the batches up. Used by unit tests, not
 * meant to be used in production.
 * @author Bela Ban
 * @since  3.5
 */
@MBean(description="Intercepts single messages and passes them up as batches")
public class MAKE_BATCH extends Protocol {
    @Property(description="handle multicast messages")
    protected boolean multicasts=false;

    @Property(description="handle unicast messages")
    protected boolean unicasts=false;

    @Property(description="Do not add OOB messages to a batch if true")
    protected boolean skip_oob=true;

    @Property(description="Time to sleep (in ms) from the reception of the first message to sending a batch up",
      type=AttributeType.TIME)
    protected long sleep_time=100;

    // all maps have sender and msg list pairs
    protected final Map<Address,List<Message>> reg_map_mcast=new HashMap<>();
    protected final Map<Address,List<Message>> reg_map_ucast=new HashMap<>();

    protected final Map<Address,List<Message>> oob_map_mcast=new HashMap<>();
    protected final Map<Address,List<Message>> oob_map_ucast=new HashMap<>();

    protected TimeScheduler                     timer;
    protected AsciiString                       cluster_name;
    protected Future<?>                         batcher;

    public MAKE_BATCH multicasts(boolean flag) {this.multicasts=flag; return this;}
    public MAKE_BATCH unicasts(boolean flag)   {this.unicasts=flag;   return this;}
    public MAKE_BATCH sleepTime(long time)     {this.sleep_time=time; return this;}
    public boolean    skipOOB()                {return skip_oob;}
    public MAKE_BATCH skipOOB(boolean s)       {this.skip_oob=s; return this;}

    public void start() throws Exception {
        super.init();
        timer=getTransport().getTimer();
        startBatcher();
    }

    public void stop() {
        super.stop();
        stopBatcher();
    }

    public Object down(Event evt) {
        switch(evt.getType()) {
            case Event.CONNECT:
            case Event.CONNECT_USE_FLUSH:
            case Event.CONNECT_WITH_STATE_TRANSFER:
            case Event.CONNECT_WITH_STATE_TRANSFER_USE_FLUSH:
                cluster_name=new AsciiString((String)evt.getArg());
                break;
        }
        return down_prot.down(evt);
    }

    public Object up(Message msg) {
        if(msg.isFlagSet(Message.Flag.OOB) && skip_oob)
            return up_prot.up(msg);

        if((msg.getDest() == null && multicasts) || (msg.getDest() != null && unicasts)) {
            queue(msg);
            return null;
        }
        return up_prot.up(msg);
    }

    public void up(MessageBatch batch) {
        for(Iterator<Message> it=batch.iterator(); it.hasNext();) {
            Message msg=it.next();
            if(msg.isFlagSet(Message.Flag.OOB) && skip_oob) {
                up_prot.up(msg);
                it.remove();
                continue;
            }
            if((msg.dest() == null && multicasts) || (msg.dest() != null && unicasts)) {
                queue(msg);
                it.remove();
            }
        }
        if(!batch.isEmpty())
            up_prot.up(batch);
    }

    protected void queue(Message msg) {
        Address dest=msg.getDest();
        Map<Address,List<Message>> map;
        if(dest == null)
            map=msg.isFlagSet(Message.Flag.OOB)? oob_map_mcast : reg_map_mcast;
        else
            map=msg.isFlagSet(Message.Flag.OOB)? oob_map_ucast : reg_map_ucast;

        List<Message> list=map.computeIfAbsent(msg.src(), k -> new ArrayList<>());
        list.add(msg);
    }

    public synchronized MAKE_BATCH startBatcher() {
        if(timer == null)
            timer=getTransport().getTimer();
        if(batcher == null || batcher.isDone())
            batcher=timer.scheduleWithFixedDelay(new Batcher(), sleep_time, sleep_time, TimeUnit.MILLISECONDS);
        return this;
    }

    protected synchronized MAKE_BATCH stopBatcher() {
        if(batcher != null) {
            batcher.cancel(true);
            batcher=null;
        }
        return this;
    }

    protected class Batcher implements Runnable {

        public void run() {
            List<MessageBatch> batches=new ArrayList<>();

            synchronized(oob_map_mcast) {
                for(Map.Entry<Address,List<Message>> entry: oob_map_mcast.entrySet()) {
                    MessageBatch batch=new MessageBatch(null, entry.getKey(), cluster_name, true, entry.getValue()).mode(MessageBatch.Mode.OOB);
                    batches.add(batch);
                }
                oob_map_mcast.clear();
            }

            synchronized(oob_map_ucast) {
                for(Map.Entry<Address,List<Message>> entry: oob_map_ucast.entrySet()) {
                    MessageBatch batch=new MessageBatch(local_addr, entry.getKey(), cluster_name, false, entry.getValue()).mode(MessageBatch.Mode.OOB);
                    batches.add(batch);
                }
                oob_map_ucast.clear();
            }

            synchronized(reg_map_mcast) {
                for(Map.Entry<Address,List<Message>> entry: reg_map_mcast.entrySet()) {
                    MessageBatch batch=new MessageBatch(null, entry.getKey(), cluster_name, true, entry.getValue()).mode(MessageBatch.Mode.REG);
                    batches.add(batch);
                }
                reg_map_mcast.clear();
            }

            synchronized(reg_map_ucast) {
                for(Map.Entry<Address,List<Message>> entry: reg_map_ucast.entrySet()) {
                    MessageBatch batch=new MessageBatch(local_addr, entry.getKey(), cluster_name, false, entry.getValue()).mode(MessageBatch.Mode.REG);
                    batches.add(batch);
                }
                reg_map_ucast.clear();
            }
            batches.stream().filter(batch -> !batch.isEmpty()).forEach(batch -> up_prot.up(batch));
        }
    }
}