text:
import fixtures
import mock

from nova import exception
from nova import test
from nova.tests.unit.virt.disk.vfs import fakeguestfs
from nova.virt.disk.vfs import guestfs as vfsimpl
from nova.virt.image import model as imgmodel

class VirtDiskVFSGuestFSTest(test.NoDBTestCase):
    def setUp(self):
        super(VirtDiskVFSGuestFSTest, self).setUp()
        self.useFixture(
                fixtures.MonkeyPatch('nova.virt.disk.vfs.guestfs.guestfs',
                                     fakeguestfs))

        self.qcowfile = imgmodel.LocalFileImage("/dummy.qcow2",
                                                imgmodel.FORMAT_QCOW2)
        self.rawfile = imgmodel.LocalFileImage("/dummy.img",
                                               imgmodel.FORMAT_RAW)
        self.lvmfile = imgmodel.LocalBlockImage("/dev/volgroup/myvol")
        self.rbdfile = imgmodel.RBDImage("myvol", "mypool",
                                         "cthulu",
                                         "arrrrrgh",
                                         ["server1:123", "server2:123"])

    def _do_test_appliance_setup_inspect(self, image, drives, forcetcg):
        if forcetcg:
            vfsimpl.force_tcg()
        else:
            vfsimpl.force_tcg(False)

        vfs = vfsimpl.VFSGuestFS(
            image,
            partition=-1)
        vfs.setup()

        if forcetcg:
            self.assertEqual(["force_tcg"], vfs.handle.backend_settings)
            vfsimpl.force_tcg(False)
        else:
            self.assertIsNone(vfs.handle.backend_settings)

        self.assertTrue(vfs.handle.running)
        self.assertEqual(drives,
                         vfs.handle.drives)
        self.assertEqual(3, len(vfs.handle.mounts))
        self.assertEqual("/dev/mapper/guestvgf-lv_root",
                         vfs.handle.mounts[0][1])
        self.assertEqual("/dev/vda1",
                         vfs.handle.mounts[1][1])
        self.assertEqual("/dev/mapper/guestvgf-lv_home",
                         vfs.handle.mounts[2][1])
        self.assertEqual("/", vfs.handle.mounts[0][2])
        self.assertEqual("/boot", vfs.handle.mounts[1][2])
        self.assertEqual("/home", vfs.handle.mounts[2][2])

        handle = vfs.handle
        vfs.teardown()

        self.assertIsNone(vfs.handle)
        self.assertFalse(handle.running)
        self.assertTrue(handle.closed)
        self.assertEqual(0, len(handle.mounts))

    def test_appliance_setup_inspect_auto(self):
        drives = [("/dummy.qcow2", {"format": "qcow2"})]
        self._do_test_appliance_setup_inspect(self.qcowfile, drives, False)

    def test_appliance_setup_inspect_tcg(self):
        drives = [("/dummy.qcow2", {"format": "qcow2"})]
        self._do_test_appliance_setup_inspect(self.qcowfile, drives, True)

    def test_appliance_setup_inspect_raw(self):
        drives = [("/dummy.img", {"format": "raw"})]
        self._do_test_appliance_setup_inspect(self.rawfile, drives, True)

    def test_appliance_setup_inspect_lvm(self):
        drives = [("/dev/volgroup/myvol", {"format": "raw"})]
        self._do_test_appliance_setup_inspect(self.lvmfile, drives, True)

    def test_appliance_setup_inspect_rbd(self):
        drives = [("mypool/myvol", {"format": "raw",
                                    "protocol": "rbd",
                                    "username": "cthulu",
                                    "secret": "arrrrrgh",
                                    "server": ["server1:123",
                                               "server2:123"]})]
        self._do_test_appliance_setup_inspect(self.rbdfile, drives, True)

    def test_appliance_setup_inspect_no_root_raises(self):
        vfs = vfsimpl.VFSGuestFS(self.qcowfile,
                                 partition=-1)
        # call setup to init the handle so we can stub it
        vfs.setup()

        self.assertIsNone(vfs.handle.backend_settings)
        with mock.patch.object(
            vfs.handle, 'inspect_os', return_value=[]) as mock_inspect_os:
            self.assertRaises(exception.NovaException, vfs.setup_os_inspect)
            mock_inspect_os.assert_called_once_with()

    def test_appliance_setup_inspect_multi_boots_raises(self):
        vfs = vfsimpl.VFSGuestFS(self.qcowfile,
                                 partition=-1)
        # call setup to init the handle so we can stub it
        vfs.setup()

        self.assertIsNone(vfs.handle.backend_settings)

        with mock.patch.object(
            vfs.handle, 'inspect_os',
            return_value=['fake1', 'fake2']) as mock_inspect_os:
            self.assertRaises(exception.NovaException, vfs.setup_os_inspect)
            mock_inspect_os.assert_called_once_with()

    def test_appliance_setup_static_nopart(self):
        vfs = vfsimpl.VFSGuestFS(self.qcowfile,
                                 partition=None)
        vfs.setup()

        self.assertIsNone(vfs.handle.backend_settings)
        self.assertTrue(vfs.handle.running)
        self.assertEqual(1, len(vfs.handle.mounts))
        self.assertEqual("/dev/sda", vfs.handle.mounts[0][1])
        self.assertEqual("/", vfs.handle.mounts[0][2])

        handle = vfs.handle
        vfs.teardown()

        self.assertIsNone(vfs.handle)
        self.assertFalse(handle.running)
        self.assertTrue(handle.closed)
        self.assertEqual(0, len(handle.mounts))

    def test_appliance_setup_static_part(self):
        vfs = vfsimpl.VFSGuestFS(self.qcowfile,
                                 partition=2)
        vfs.setup()

        self.assertIsNone(vfs.handle.backend_settings)
        self.assertTrue(vfs.handle.running)
        self.assertEqual(1, len(vfs.handle.mounts))
        self.assertEqual("/dev/sda2", vfs.handle.mounts[0][1])
        self.assertEqual("/", vfs.handle.mounts[0][2])

        handle = vfs.handle
        vfs.teardown()

        self.assertIsNone(vfs.handle)
        self.assertFalse(handle.running)
        self.assertTrue(handle.closed)
        self.assertEqual(0, len(handle.mounts))

    def test_makepath(self):
        vfs = vfsimpl.VFSGuestFS(self.qcowfile)
        vfs.setup()
        vfs.make_path("/some/dir")
        vfs.make_path("/other/dir")

        self.assertIn("/some/dir", vfs.handle.files)
        self.assertIn("/other/dir", vfs.handle.files)
        self.assertTrue(vfs.handle.files["/some/dir"]["isdir"])
        self.assertTrue(vfs.handle.files["/other/dir"]["isdir"])

        vfs.teardown()

    def test_append_file(self):
        vfs = vfsimpl.VFSGuestFS(self.qcowfile)
        vfs.setup()
        vfs.append_file("/some/file", " Goodbye")

        self.assertIn("/some/file", vfs.handle.files)
        self.assertEqual("Hello World Goodbye",
                         vfs.handle.files["/some/file"]["content"])

        vfs.teardown()

    def test_replace_file(self):
        vfs = vfsimpl.VFSGuestFS(self.qcowfile)
        vfs.setup()
        vfs.replace_file("/some/file", "Goodbye")

        self.assertIn("/some/file", vfs.handle.files)
        self.assertEqual("Goodbye",
                         vfs.handle.files["/some/file"]["content"])

        vfs.teardown()

    def test_read_file(self):
        vfs = vfsimpl.VFSGuestFS(self.qcowfile)
        vfs.setup()
        self.assertEqual("Hello World", vfs.read_file("/some/file"))

        vfs.teardown()

    def test_has_file(self):
        vfs = vfsimpl.VFSGuestFS(self.qcowfile)
        vfs.setup()
        vfs.read_file("/some/file")

        self.assertTrue(vfs.has_file("/some/file"))
        self.assertFalse(vfs.has_file("/other/file"))

        vfs.teardown()

    def test_set_permissions(self):
        vfs = vfsimpl.VFSGuestFS(self.qcowfile)
        vfs.setup()
        vfs.read_file("/some/file")

        self.assertEqual(0o700, vfs.handle.files["/some/file"]["mode"])

        vfs.set_permissions("/some/file", 0o7777)
        self.assertEqual(0o7777, vfs.handle.files["/some/file"]["mode"])

        vfs.teardown()

    def test_set_ownership(self):
        vfs = vfsimpl.VFSGuestFS(self.qcowfile)
        vfs.setup()
        vfs.read_file("/some/file")

        self.assertEqual(100, vfs.handle.files["/some/file"]["uid"])
        self.assertEqual(100, vfs.handle.files["/some/file"]["gid"])

        vfs.set_ownership("/some/file", "fred", None)
        self.assertEqual(105, vfs.handle.files["/some/file"]["uid"])
        self.assertEqual(100, vfs.handle.files["/some/file"]["gid"])

        vfs.set_ownership("/some/file", None, "users")
        self.assertEqual(105, vfs.handle.files["/some/file"]["uid"])
        self.assertEqual(500, vfs.handle.files["/some/file"]["gid"])

        vfs.set_ownership("/some/file", "joe", "admins")
        self.assertEqual(110, vfs.handle.files["/some/file"]["uid"])
        self.assertEqual(600, vfs.handle.files["/some/file"]["gid"])

        vfs.teardown()

    def test_set_ownership_not_supported(self):
        # NOTE(andreaf) Setting ownership relies on /etc/passwd and/or
        # /etc/group being available in the image, which is not always the
        # case - e.g. CirrOS image before boot.
        vfs = vfsimpl.VFSGuestFS(self.qcowfile)
        vfs.setup()
        self.stub_out('nova.tests.unit.virt.disk.vfs.fakeguestfs.GuestFS.'
                      'CAN_SET_OWNERSHIP', False)

        self.assertRaises(exception.NovaException, vfs.set_ownership,
                          "/some/file", "fred", None)
        self.assertRaises(exception.NovaException, vfs.set_ownership,
                          "/some/file", None, "users")

    def test_close_on_error(self):
        vfs = vfsimpl.VFSGuestFS(self.qcowfile)
        vfs.setup()
        self.assertFalse(vfs.handle.kwargs['close_on_exit'])
        vfs.teardown()
        self.stub_out('nova.tests.unit.virt.disk.vfs.fakeguestfs.GuestFS.'
                      'SUPPORT_CLOSE_ON_EXIT', False)
        vfs = vfsimpl.VFSGuestFS(self.qcowfile)
        vfs.setup()
        self.assertNotIn('close_on_exit', vfs.handle.kwargs)
        vfs.teardown()

    def test_python_return_dict(self):
        vfs = vfsimpl.VFSGuestFS(self.qcowfile)
        vfs.setup()
        self.assertFalse(vfs.handle.kwargs['python_return_dict'])
        vfs.teardown()
        self.stub_out('nova.tests.unit.virt.disk.vfs.fakeguestfs.GuestFS.'
                      'SUPPORT_RETURN_DICT', False)
        vfs = vfsimpl.VFSGuestFS(self.qcowfile)
        vfs.setup()
        self.assertNotIn('python_return_dict', vfs.handle.kwargs)
        vfs.teardown()

    def test_setup_debug_disable(self):
        vfs = vfsimpl.VFSGuestFS(self.qcowfile)
        vfs.setup()
        self.assertFalse(vfs.handle.trace_enabled)
        self.assertFalse(vfs.handle.verbose_enabled)
        self.assertIsNone(vfs.handle.event_callback)

    def test_setup_debug_enabled(self):
        self.flags(debug=True, group='guestfs')
        vfs = vfsimpl.VFSGuestFS(self.qcowfile)
        vfs.setup()
        self.assertTrue(vfs.handle.trace_enabled)
        self.assertTrue(vfs.handle.verbose_enabled)
        self.assertIsNotNone(vfs.handle.event_callback)

    def test_get_format_fs(self):
        vfs = vfsimpl.VFSGuestFS(self.rawfile)
        vfs.setup()
        self.assertIsNotNone(vfs.handle)
        self.assertEqual('ext3', vfs.get_image_fs())
        vfs.teardown()

    @mock.patch.object(vfsimpl.VFSGuestFS, 'setup_os')
    def test_setup_mount(self, setup_os):
        vfs = vfsimpl.VFSGuestFS(self.qcowfile)
        vfs.setup()
        self.assertTrue(setup_os.called)

    @mock.patch.object(vfsimpl.VFSGuestFS, 'setup_os')
    def test_setup_mount_false(self, setup_os):
        vfs = vfsimpl.VFSGuestFS(self.qcowfile)
        vfs.setup(mount=False)
        self.assertFalse(setup_os.called)

    @mock.patch('os.access')
    @mock.patch('os.uname', return_value=('Linux', '', 'kernel_name'))
    def test_appliance_setup_inspect_capabilties_fail_with_ubuntu(self,
                                                                  mock_uname,
                                                                  mock_access):
        # In ubuntu os will default host kernel as 600 permission
        m = mock.MagicMock()
        m.launch.side_effect = Exception
        vfs = vfsimpl.VFSGuestFS(self.qcowfile)
        mock_access.return_value = False
        self.flags(debug=False, group='guestfs')
        with mock.patch('eventlet.tpool.Proxy', return_value=m) as tpool_mock:
            self.assertRaises(exception.LibguestfsCannotReadKernel,
                                    vfs.inspect_capabilities)
            m.add_drive.assert_called_once_with('/dev/null')
            m.launch.assert_called_once_with()
            mock_access.assert_called_once_with('/boot/vmlinuz-kernel_name',
                                                mock.ANY)
            mock_uname.assert_called_once_with()
            self.assertEqual(1, tpool_mock.call_count)

    def test_appliance_setup_inspect_capabilties_debug_mode(self):
        """Asserts that we do not use an eventlet thread pool when guestfs
        debug logging is enabled.
        """
        # We can't actually mock guestfs.GuestFS because it's an optional
        # native package import. All we really care about here is that
        # eventlet isn't used.
        self.flags(debug=True, group='guestfs')
        vfs = vfsimpl.VFSGuestFS(self.qcowfile)
        with mock.patch('eventlet.tpool.Proxy',
                        new_callable=mock.NonCallableMock):
            vfs.inspect_capabilities()


text:
// RobotBuilder Version: 2.0
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.

package org.usfirst.frc5725.AmyCerberus.commands;
import edu.wpi.first.wpilibj.command.Command;
import org.usfirst.frc5725.AmyCerberus.Robot;

/**
 *
 */
public class latchClose extends Command {
		public double timeClose = Robot.latch.closeTime;
    // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_DECLARATIONS

    // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_DECLARATIONS

    // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR
    public latchClose() {

    // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR
        // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_SETTING

        // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_SETTING
        // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
        requires(Robot.latch);

    // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
        setTimeout(timeClose);
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    	Robot.latch.latchClose();
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return isTimedOut();
    }

    // Called once after isFinished returns true
    protected void end() {
    	Robot.latch.stop();
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    	end();
    }
}

redpajama_set_name: RedPajamaGithub


text:
.class Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;
.super Ljava/lang/Object;
.source ""

# interfaces
.implements Lcom/thoughtworks/xstream/core/util/CustomObjectOutputStream$StreamCallback;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter;->doMarshal(Ljava/lang/Object;Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;Lcom/thoughtworks/xstream/converters/MarshallingContext;)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter;

.field final synthetic val$context:Lcom/thoughtworks/xstream/converters/MarshallingContext;

.field final synthetic val$currentType:[Ljava/lang/Class;

.field final synthetic val$source:Ljava/lang/Object;

.field final synthetic val$writer:Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;

.field final synthetic val$writtenClassWrapper:[Z

# direct methods
.method constructor <init>(Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter;Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;Lcom/thoughtworks/xstream/converters/MarshallingContext;[Ljava/lang/Class;Ljava/lang/Object;[Z)V
    .locals 0

    .line 132
    iput-object p1, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->this$0:Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter;

    iput-object p2, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$writer:Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;

    iput-object p3, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$context:Lcom/thoughtworks/xstream/converters/MarshallingContext;

    iput-object p4, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$currentType:[Ljava/lang/Class;

    iput-object p5, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$source:Ljava/lang/Object;

    iput-object p6, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$writtenClassWrapper:[Z

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public close()V
    .locals 2

    .line 232
    new-instance v0, Ljava/lang/UnsupportedOperationException;

    const-string v1, "Objects are not allowed to call ObjectOutputStream.close() from writeObject()"

    invoke-direct {v0, v1}, Ljava/lang/UnsupportedOperationException;-><init>(Ljava/lang/String;)V

    throw v0
.end method

.method public defaultWriteObject()V
    .locals 10

    .line 178
    const/4 v4, 0x0

    .line 180
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$currentType:[Ljava/lang/Class;

    const/4 v1, 0x0

    aget-object v0, v0, v1

    invoke-static {v0}, Ljava/io/ObjectStreamClass;->lookup(Ljava/lang/Class;)Ljava/io/ObjectStreamClass;

    move-result-object v0

    .line 182
    move-object v5, v0

    if-nez v0, :cond_0

    .line 183
    return-void

    .line 186
    :cond_0
    invoke-virtual {v5}, Ljava/io/ObjectStreamClass;->getFields()[Ljava/io/ObjectStreamField;

    move-result-object v5

    .line 187
    const/4 v6, 0x0

    :goto_0
    array-length v0, v5

    if-ge v6, v0, :cond_5

    .line 188
    aget-object v7, v5, v6

    .line 189
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->this$0:Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter;

    iget-object v1, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$currentType:[Ljava/lang/Class;

    const/4 v2, 0x0

    aget-object v1, v1, v2

    iget-object v2, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$source:Ljava/lang/Object;

    #calls: Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter;->readField(Ljava/io/ObjectStreamField;Ljava/lang/Class;Ljava/lang/Object;)Ljava/lang/Object;
    invoke-static {v0, v7, v1, v2}, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter;->access$000(Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter;Ljava/io/ObjectStreamField;Ljava/lang/Class;Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v0

    .line 190
    move-object v8, v0

    if-eqz v0, :cond_4

    .line 191
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$writtenClassWrapper:[Z

    const/4 v1, 0x0

    aget-boolean v0, v0, v1

    if-nez v0, :cond_1

    .line 192
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$writer:Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;

    iget-object v1, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->this$0:Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter;

    iget-object v1, v1, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter;->mapper:Lcom/thoughtworks/xstream/mapper/Mapper;

    iget-object v2, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$currentType:[Ljava/lang/Class;

    const/4 v3, 0x0

    aget-object v2, v2, v3

    invoke-interface {v1, v2}, Lcom/thoughtworks/xstream/mapper/Mapper;->serializedClass(Ljava/lang/Class;)Ljava/lang/String;

    move-result-object v1

    invoke-interface {v0, v1}, Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;->startNode(Ljava/lang/String;)V

    .line 193
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$writtenClassWrapper:[Z

    const/4 v1, 0x1

    const/4 v2, 0x0

    aput-boolean v1, v0, v2

    .line 195
    :cond_1
    if-nez v4, :cond_2

    .line 196
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$writer:Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;

    const-string v1, "default"

    invoke-interface {v0, v1}, Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;->startNode(Ljava/lang/String;)V

    .line 197
    const/4 v4, 0x1

    .line 199
    :cond_2
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->this$0:Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter;

    iget-object v0, v0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter;->mapper:Lcom/thoughtworks/xstream/mapper/Mapper;

    iget-object v1, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$currentType:[Ljava/lang/Class;

    const/4 v2, 0x0

    aget-object v1, v1, v2

    invoke-virtual {v7}, Ljava/io/ObjectStreamField;->getName()Ljava/lang/String;

    move-result-object v2

    invoke-interface {v0, v1, v2}, Lcom/thoughtworks/xstream/mapper/Mapper;->shouldSerializeMember(Ljava/lang/Class;Ljava/lang/String;)Z

    move-result v0

    if-eqz v0, :cond_4

    .line 200
    invoke-virtual {v8}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v9

    .line 204
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$writer:Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;

    iget-object v1, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->this$0:Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter;

    iget-object v1, v1, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter;->mapper:Lcom/thoughtworks/xstream/mapper/Mapper;

    iget-object v2, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$source:Ljava/lang/Object;

    invoke-virtual {v2}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v2

    invoke-virtual {v7}, Ljava/io/ObjectStreamField;->getName()Ljava/lang/String;

    move-result-object v3

    invoke-interface {v1, v2, v3}, Lcom/thoughtworks/xstream/mapper/Mapper;->serializedMember(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/String;

    move-result-object v1

    invoke-static {v0, v1, v9}, Lcom/thoughtworks/xstream/io/ExtendedHierarchicalStreamWriterHelper;->startNode(Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;Ljava/lang/String;Ljava/lang/Class;)V

    .line 206
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->this$0:Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter;

    iget-object v0, v0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter;->mapper:Lcom/thoughtworks/xstream/mapper/Mapper;

    invoke-virtual {v7}, Ljava/io/ObjectStreamField;->getType()Ljava/lang/Class;

    move-result-object v1

    invoke-interface {v0, v1}, Lcom/thoughtworks/xstream/mapper/Mapper;->defaultImplementationOf(Ljava/lang/Class;)Ljava/lang/Class;

    move-result-object v7

    .line 207
    invoke-virtual {v9, v7}, Ljava/lang/Object;->equals(Ljava/lang/Object;)Z

    move-result v0

    if-nez v0, :cond_3

    .line 208
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->this$0:Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter;

    iget-object v0, v0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter;->mapper:Lcom/thoughtworks/xstream/mapper/Mapper;

    const-string v1, "class"

    invoke-interface {v0, v1}, Lcom/thoughtworks/xstream/mapper/Mapper;->aliasForSystemAttribute(Ljava/lang/String;)Ljava/lang/String;

    move-result-object v0

    .line 209
    move-object v7, v0

    if-eqz v0, :cond_3

    .line 210
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$writer:Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;

    iget-object v1, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->this$0:Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter;

    iget-object v1, v1, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter;->mapper:Lcom/thoughtworks/xstream/mapper/Mapper;

    invoke-interface {v1, v9}, Lcom/thoughtworks/xstream/mapper/Mapper;->serializedClass(Ljava/lang/Class;)Ljava/lang/String;

    move-result-object v1

    invoke-interface {v0, v7, v1}, Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;->addAttribute(Ljava/lang/String;Ljava/lang/String;)V

    .line 214
    :cond_3
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$context:Lcom/thoughtworks/xstream/converters/MarshallingContext;

    invoke-interface {v0, v8}, Lcom/thoughtworks/xstream/converters/MarshallingContext;->convertAnother(Ljava/lang/Object;)V

    .line 216
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$writer:Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;

    invoke-interface {v0}, Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;->endNode()V

    .line 187
    :cond_4
    add-int/lit8 v6, v6, 0x1

    goto/16 :goto_0

    .line 219
    :cond_5
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$writtenClassWrapper:[Z

    const/4 v1, 0x0

    aget-boolean v0, v0, v1

    if-eqz v0, :cond_6

    if-nez v4, :cond_6

    .line 220
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$writer:Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;

    const-string v1, "default"

    invoke-interface {v0, v1}, Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;->startNode(Ljava/lang/String;)V

    .line 221
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$writer:Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;

    invoke-interface {v0}, Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;->endNode()V

    return-void

    .line 222
    :cond_6
    if-eqz v4, :cond_7

    .line 223
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$writer:Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;

    invoke-interface {v0}, Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;->endNode()V

    .line 225
    :cond_7
    return-void
.end method

.method public flush()V
    .locals 1

    .line 228
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$writer:Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;

    invoke-interface {v0}, Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;->flush()V

    .line 229
    return-void
.end method

.method public writeFieldsToStream(Ljava/util/Map;)V
    .locals 8

    .line 146
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$currentType:[Ljava/lang/Class;

    const/4 v1, 0x0

    aget-object v0, v0, v1

    invoke-static {v0}, Ljava/io/ObjectStreamClass;->lookup(Ljava/lang/Class;)Ljava/io/ObjectStreamClass;

    move-result-object v3

    .line 148
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$writer:Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;

    const-string v1, "default"

    invoke-interface {v0, v1}, Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;->startNode(Ljava/lang/String;)V

    .line 149
    invoke-interface {p1}, Ljava/util/Map;->keySet()Ljava/util/Set;

    move-result-object v0

    invoke-interface {v0}, Ljava/util/Set;->iterator()Ljava/util/Iterator;

    move-result-object v4

    :cond_0
    :goto_0
    invoke-interface {v4}, Ljava/util/Iterator;->hasNext()Z

    move-result v0

    if-eqz v0, :cond_4

    .line 150
    invoke-interface {v4}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Ljava/lang/String;

    move-object v5, v0

    .line 151
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->this$0:Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter;

    iget-object v0, v0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter;->mapper:Lcom/thoughtworks/xstream/mapper/Mapper;

    iget-object v1, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$currentType:[Ljava/lang/Class;

    const/4 v2, 0x0

    aget-object v1, v1, v2

    invoke-interface {v0, v1, v5}, Lcom/thoughtworks/xstream/mapper/Mapper;->shouldSerializeMember(Ljava/lang/Class;Ljava/lang/String;)Z

    move-result v0

    if-eqz v0, :cond_0

    .line 152
    invoke-virtual {v3, v5}, Ljava/io/ObjectStreamClass;->getField(Ljava/lang/String;)Ljava/io/ObjectStreamField;

    move-result-object v6

    .line 155
    invoke-interface {p1, v5}, Ljava/util/Map;->get(Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v7

    .line 156
    if-nez v6, :cond_1

    .line 157
    new-instance v0, Lcom/thoughtworks/xstream/converters/reflection/ObjectAccessException;

    new-instance v1, Ljava/lang/StringBuilder;

    const-string v2, "Class "

    invoke-direct {v1, v2}, Ljava/lang/StringBuilder;-><init>(Ljava/lang/String;)V

    invoke-virtual {v7}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v2

    invoke-virtual {v2}, Ljava/lang/Class;->getName()Ljava/lang/String;

    move-result-object v2

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    const-string v2, " may not write a field named \'"

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    const-string v2, "\'"

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    invoke-direct {v0, v1}, Lcom/thoughtworks/xstream/converters/reflection/ObjectAccessException;-><init>(Ljava/lang/String;)V

    throw v0

    .line 160
    :cond_1
    if-eqz v7, :cond_3

    .line 161
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$writer:Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;

    iget-object v1, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->this$0:Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter;

    iget-object v1, v1, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter;->mapper:Lcom/thoughtworks/xstream/mapper/Mapper;

    iget-object v2, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$source:Ljava/lang/Object;

    invoke-virtual {v2}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v2

    invoke-interface {v1, v2, v5}, Lcom/thoughtworks/xstream/mapper/Mapper;->serializedMember(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/String;

    move-result-object v1

    invoke-virtual {v7}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v2

    invoke-static {v0, v1, v2}, Lcom/thoughtworks/xstream/io/ExtendedHierarchicalStreamWriterHelper;->startNode(Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;Ljava/lang/String;Ljava/lang/Class;)V

    .line 164
    invoke-virtual {v6}, Ljava/io/ObjectStreamField;->getType()Ljava/lang/Class;

    move-result-object v0

    invoke-virtual {v7}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v1

    if-eq v0, v1, :cond_2

    invoke-virtual {v6}, Ljava/io/ObjectStreamField;->getType()Ljava/lang/Class;

    move-result-object v0

    invoke-virtual {v0}, Ljava/lang/Class;->isPrimitive()Z

    move-result v0

    if-nez v0, :cond_2

    .line 165
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->this$0:Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter;

    iget-object v0, v0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter;->mapper:Lcom/thoughtworks/xstream/mapper/Mapper;

    const-string v1, "class"

    invoke-interface {v0, v1}, Lcom/thoughtworks/xstream/mapper/Mapper;->aliasForSystemAttribute(Ljava/lang/String;)Ljava/lang/String;

    move-result-object v0

    .line 166
    move-object v5, v0

    if-eqz v0, :cond_2

    .line 167
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$writer:Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;

    iget-object v1, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->this$0:Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter;

    iget-object v1, v1, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter;->mapper:Lcom/thoughtworks/xstream/mapper/Mapper;

    invoke-virtual {v7}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v2

    invoke-interface {v1, v2}, Lcom/thoughtworks/xstream/mapper/Mapper;->serializedClass(Ljava/lang/Class;)Ljava/lang/String;

    move-result-object v1

    invoke-interface {v0, v5, v1}, Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;->addAttribute(Ljava/lang/String;Ljava/lang/String;)V

    .line 170
    :cond_2
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$context:Lcom/thoughtworks/xstream/converters/MarshallingContext;

    invoke-interface {v0, v7}, Lcom/thoughtworks/xstream/converters/MarshallingContext;->convertAnother(Ljava/lang/Object;)V

    .line 171
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$writer:Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;

    invoke-interface {v0}, Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;->endNode()V

    .line 173
    :cond_3
    goto/16 :goto_0

    .line 174
    :cond_4
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$writer:Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;

    invoke-interface {v0}, Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;->endNode()V

    .line 175
    return-void
.end method

.method public writeToStream(Ljava/lang/Object;)V
    .locals 3

    .line 135
    if-nez p1, :cond_0

    .line 136
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$writer:Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;

    const-string v1, "null"

    invoke-interface {v0, v1}, Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;->startNode(Ljava/lang/String;)V

    .line 137
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$writer:Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;

    invoke-interface {v0}, Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;->endNode()V

    return-void

    .line 139
    :cond_0
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$writer:Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;

    iget-object v1, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->this$0:Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter;

    iget-object v1, v1, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter;->mapper:Lcom/thoughtworks/xstream/mapper/Mapper;

    invoke-virtual {p1}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v2

    invoke-interface {v1, v2}, Lcom/thoughtworks/xstream/mapper/Mapper;->serializedClass(Ljava/lang/Class;)Ljava/lang/String;

    move-result-object v1

    invoke-virtual {p1}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v2

    invoke-static {v0, v1, v2}, Lcom/thoughtworks/xstream/io/ExtendedHierarchicalStreamWriterHelper;->startNode(Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;Ljava/lang/String;Ljava/lang/Class;)V

    .line 140
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$context:Lcom/thoughtworks/xstream/converters/MarshallingContext;

    invoke-interface {v0, p1}, Lcom/thoughtworks/xstream/converters/MarshallingContext;->convertAnother(Ljava/lang/Object;)V

    .line 141
    iget-object v0, p0, Lcom/thoughtworks/xstream/converters/reflection/SerializableConverter$1;->val$writer:Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;

    invoke-interface {v0}, Lcom/thoughtworks/xstream/io/HierarchicalStreamWriter;->endNode()V

    .line 143
    return-void
.end method


text:
import { Component } from '@angular/core';

@Component({
  // eslint-disable-next-line @angular-eslint/component-selector
  selector: 'demo-popover-delay',
  templateUrl: './delay.html'
})
export class DemoPopoverDelayComponent {}


text:
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
**Table of Contents**  *generated with [DocToc](https://github.com/thlorenz/doctoc)*

- [learning for guice](#learning-for-guice)
  - [1. Hello World](#1-hello-world)
  - [2.Bindings](#2bindings)
    - [2.1 Linked Bindings](#21-linked-bindings)
    - [2.2 Annotation Bindings](#22-annotation-bindings)
    - [2.3 Instance Bindings](#23-instance-bindings)
    - [2.4 @Providers Methods](#24-providers-methods)

<!-- END doctoc generated TOC please keep comment here to allow auto update -->

learning for guice
===
[![](https://img.shields.io/badge/guice-4.1.0-green.svg?style=flat)](https://github.com/google/guice)
![](https://img.shields.io/badge/Java-1.8-orange.svg)
[![Build Status](https://travis-ci.org/Ryan-Miao/l4guice.svg?branch=master)](https://travis-ci.org/Ryan-Miao/l4guice)
[![codecov](https://codecov.io/gh/Ryan-Miao/l4guice/branch/master/graph/badge.svg)](https://codecov.io/gh/Ryan-Miao/l4guice)
[![license](https://img.shields.io/github/license/mashape/apistatus.svg)](https://github.com/winsnow/l4guice/blob/master/LICENSE)

>The dependency injection pattern leads to code that's modular and
 testable, and Guice makes it easy to write.

## 1. Hello World
Example code@`com.test.guice.hello`
Main class: `com.test.guice.hello.BillingModule`

Note that it will throw a `com.google.inject.CreationException`
if bind multiple class with the same key.

## 2.Bindings
>To specify how dependencies are resolved, configure your injector with bindings.

Guice is different from spring since I don't find the scan package. I guess it may scan
all the classes in the classloader. Thus guice could produce any instance for the class.

### 2.1 Linked Bindings
Example code@ `com.test.guice.bindings.LinkedBindings.BillingModule`

The code may like this:
```java
bind(Father.class).to(Child.class);
```
This will inject `Father` with `Child`. When you get `Father`
from injector, you will get `Child`.

Linked bindings can also be chained:
```java
public class BillingModule extends AbstractModule {
  @Override
  protected void configure() {
    bind(TransactionLog.class).to(DatabaseTransactionLog.class);
    bind(DatabaseTransactionLog.class).to(MySqlDatabaseTransactionLog.class);
  }
}
```

### 2.2 Annotation Bindings
Example code@ `com.test.guice.bindings.AnnotationsBindgings.AnnotationBindingModule`

The father class such as `IPersonSay` has many implementations.
If we just want to inject to a special one, just like `@Qualifier`
does in spring, guice bindings support an optional binding
annotation. The annotation and type together identify a
binding.

We specified an annotation `@Chinese` to mark that the
`IPersonSay` should inject with `ShenZhenSay`.
```java
public class AnnotationBindingModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(IPersonSay.class)
                .annotatedWith(Chinese.class)
                .to(ShenZhenSay.class);
    }
}
```
```java
public class HelloAnnotations {

    private IPersonSay personSay;

    @Inject
    public HelloAnnotations(@Chinese IPersonSay personSay) {
        this.personSay = personSay;
    }

}
```
As a comparison, in spring:
```java
@Autowired
@Qualifier("shenZhenSay")
private IPersonSay person;
```

If we don't want to create an annotation, we could use `@Named` instead.
```java
public class RealBillingService implements BillingService {

  @Inject
  public RealBillingService(@Named("Checkout") CreditCardProcessor processor,
      TransactionLog transactionLog) {
  }
}
```
```java
public class AnnotationBindingModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(CreditCardProcessor.class)
        .annotatedWith(Names.named("Checkout"))
        .to(CheckoutCreditCardProcessor.class);
    }
}
```

### 2.3 Instance Bindings
>You can bind a type to specific instance of that type. This is usually only
useful only for objects that don't have dependencies of their own, such
as value objects.

Example code@ `com.test.guice.bindings.InstanceBindings.ConfigBind`
`com.test.guice.bindings.InstanceBindings.ConfigModule`

**Bind**:
```java
public class ConfigModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(String.class)
                .annotatedWith(Names.named("jdbc.url"))
                .toInstance("jdbc:mysql://localhost/pizza");
        bind(Integer.class)
                .annotatedWith(Names.named("jdbc.timeout"))
                .toInstance(10);
    }

}

```

**Inject**:
```java
@Inject
@Named("jdbc.url")
private String jdbcUrl;

@Inject
@Named("jdbc.timeout")
private Integer timeout;

```
Or:
```java
@Inject
public ConfigBind(@Named("jdbc.url")String jdbcUrl,
    @Named("jdbc.timeout")Integer timeout) {
    this.jdbcUrl = jdbcUrl;
    this.timeout = timeout;
}
```

>Avoid using `.toInstance` with objects that are complicated to create, since it
can slow down application startup. You can use an `@Provides` method instead.

### 2.4 @Providers Methods
>When you need code to create an object, use an `@Provides` method. The method must be defined
within a module, and it must have an `@Provides` annotation. The method's return
type is the bound type. Whenever the injector needs an instance of that type, it
will invoke the method.
If the `@Provides` method has a binding annotation liken `@Chinese` or `@Named("xx")`,
Guice binds the annotated type. Dependencies can be passed in as
parameters to the method. The injector will exercise the
bindings for each of these before invoking the method.

Example code@ `com.test.guice.bindings.ProvidesBindings.ObjectInstanceModule`

**Bind by @Providers**:
```java
public class ObjectInstanceModule extends AbstractModule {

    public static final String JDBC_URL = "jdbc:mysql://localhost/pizaa";
    public static final Integer THREAD_POOL_SIZE = 30;

    @Override
    protected void configure() {
        bind(IPersonSay.class)
                .to(NewYorkSay.class);
    }

    @Provides
    TransactionLog provideTransactionLog(){
        return new MySqlDatabaseTrannsactionLog(
                JDBC_URL, THREAD_POOL_SIZE);
    }

    @Provides @Chinese
    IPersonSay providePerson(){
        return new ShenZhenSay();
    }

}
```
**Throwing Exceptions**:
>`Guice` does not allow exceptions to be thrown from Providers.
Exceptions thrown by `Provides` methods will be wrapped in
a `ProvisionException`. It is bad practice to allow any
kind of exception to be thrown--runtime or checked--from
an `@Provides` method. If you need to throw an exception for some
reason, you may want to use the [ThhrowingProviders extension](https://github.com/google/guice/wiki/ThrowingProviders)
`@CheckedProvides` methods.


text:
package armstorage

import (
	"encoding/json"
	"fmt"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"reflect"
	"regexp"
	"strings"
	"time"
)

const (
	utcLayoutJSON = `"2006-01-02T15:04:05.999999999"`
	utcLayout     = "2006-01-02T15:04:05.999999999"
	rfc3339JSON   = `"` + time.RFC3339Nano + `"`
)

// Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases.
var tzOffsetRegex = regexp.MustCompile(`(Z|z|\+|-)(\d+:\d+)*"*$`)

type timeRFC3339 time.Time

func (t timeRFC3339) MarshalJSON() (json []byte, err error) {
	tt := time.Time(t)
	return tt.MarshalJSON()
}

func (t timeRFC3339) MarshalText() (text []byte, err error) {
	tt := time.Time(t)
	return tt.MarshalText()
}

func (t *timeRFC3339) UnmarshalJSON(data []byte) error {
	layout := utcLayoutJSON
	if tzOffsetRegex.Match(data) {
		layout = rfc3339JSON
	}
	return t.Parse(layout, string(data))
}

func (t *timeRFC3339) UnmarshalText(data []byte) (err error) {
	layout := utcLayout
	if tzOffsetRegex.Match(data) {
		layout = time.RFC3339Nano
	}
	return t.Parse(layout, string(data))
}

func (t *timeRFC3339) Parse(layout, value string) error {
	p, err := time.Parse(layout, strings.ToUpper(value))
	*t = timeRFC3339(p)
	return err
}

func populateTimeRFC3339(m map[string]interface{}, k string, t *time.Time) {
	if t == nil {
		return
	} else if azcore.IsNullValue(t) {
		m[k] = nil
		return
	} else if reflect.ValueOf(t).IsNil() {
		return
	}
	m[k] = (*timeRFC3339)(t)
}

func unpopulateTimeRFC3339(data json.RawMessage, fn string, t **time.Time) error {
	if data == nil || strings.EqualFold(string(data), "null") {
		return nil
	}
	var aux timeRFC3339
	if err := json.Unmarshal(data, &aux); err != nil {
		return fmt.Errorf("struct field %s: %v", fn, err)
	}
	*t = (*time.Time)(&aux)
	return nil
}


text:
/*-------------------------------------------------------------------------
  Copyright 2011 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
  -------------------------------------------------------------------------*/
// .NAME vtkContingencyStatisticsGnuR - A class for bivariate correlation contigency
// tables, conditional probabilities, and information entropy. The p-value are
// calculated using R.
//
// .SECTION Description
// Given a pair of columns of interest, this class provides the
// following functionalities, depending on the operation in which it is executed:
// * Learn: calculate contigency tables and corresponding discrete joint
//   probability distribution.
// * Derive: calculate conditional probabilities, information entropies, and
//   pointwise mutual information.
// * Assess: given two columns of interest with the same number of entries as
//   input in port INPUT_DATA, and a corresponding bivariate probability distribution,
// * Test: calculate Chi-square independence statistic and, if VTK to R interface is available,
//   retrieve corresponding p-value for independence testing.
//
// .SECTION Thanks
// Thanks to Philippe Pebay and David Thompson from Sandia National Laboratories
// for implementing this class.
// Updated by Philippe Pebay, Kitware SAS 2012

#ifndef vtkContingencyStatisticsGnuR_h
#define vtkContingencyStatisticsGnuR_h

#include "vtkFiltersStatisticsGnuRModule.h" // For export macro
#include "vtkContingencyStatistics.h"

class vtkIdTypeArray;
class vtkTable;

class VTKFILTERSSTATISTICSGNUR_EXPORT vtkContingencyStatisticsGnuR : public vtkContingencyStatistics
{
public:
  vtkTypeMacro(vtkContingencyStatisticsGnuR, vtkContingencyStatistics);
  void PrintSelf(ostream& os, vtkIndent indent);
  static vtkContingencyStatisticsGnuR* New();

protected:
  vtkContingencyStatisticsGnuR();
  ~vtkContingencyStatisticsGnuR();

//BTX
  virtual void CalculatePValues(vtkTable*);
//ETX

private:
  vtkContingencyStatisticsGnuR(const vtkContingencyStatisticsGnuR&); // Not implemented
  void operator=(const vtkContingencyStatisticsGnuR&); // Not implemented
};

#endif


text:
package net.ontopia.topicmaps.entry;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.ontopia.utils.OntopiaRuntimeException;
import net.ontopia.utils.URIUtils;
import net.ontopia.xml.DefaultXMLReaderFactory;
import net.ontopia.xml.Slf4jSaxErrorHandler;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

/**
 * PUBLIC: Reads store configuration parameters from an XML
 * file. The config source is able to handle multiple sources at the
 * same time by using an instance of the {@link TopicMapRepositoryIF}
 * class.

 *
 * The class understands XML documents using the following DTD:

 *
 *

 * <!ELEMENT repository (source+)              >
 * <!ELEMENT source     (param*)               >
 * <!ATTLIST source      id    ID    #IMPLIED  >
 * <!ATTLIST source      class CDATA #REQUIRED >
 * <!ELEMENT param       EMPTY                 >
 * <!ATTLIST param       name  CDATA #REQUIRED
 *                          value CDATA #REQUIRED >
 *

 *
 * Example:

 *
 *

 * <repository>
 *   <!-- source that references all .xtm files in a directory -->
 *   <source class="net.ontopia.topicmaps.xml.XTMPathTopicMapSource">
 *     <param name="path" value="/ontopia/topicmaps"/>
 *     <param name="suffix" value=".xtm"/>
 *   </source>
 *   <!-- source that references a topic map in a relational database -->
 *   <source class="net.ontopia.topicmaps.impl.rdbms.RDBMSSingleTopicMapSource">
 *     <param name="topicMapId" value="5001"/>
 *     <param name="title" value="My RDBMS Topic Map"/>
 *     <param name="referenceId" value="mytm"/>
 *     <param name="propertyFile" value="${CWD}/db.postgresql.props"/>
 *   </source>
 * </repository>
 *

 *
 * This example makes XMLConfigSource use a TopicMapRepositoryIF that
 * contains two other topic maps sources, namely instances of the two
 * specifed in the class attributes of the source elements. Note that
 * the classes must have empty constructors for them to be used with
 * this class.

 *
 * The two sources would locate all XTM files with the .xtm extension
 * in the /ontopia/topicmaps directory in which the config file is
 * located.

 *
 * The param element is used to set bean properties on
 * the source instance. This way the config source can be configured.

 *
 *
Environment variables:

 *
 *
XMLConfigSource is able to replace environment variables in the
 * param value attribute. The only environment variable available at
 * this time is ${CWD}, which contains the full path of the directory
 * in which the config file is located.

 *
 *
NOTE: Topic map sources with supportsCreate set to true will get
 * ids assigned automatically. This is done so that the sources can be
 * referred to from the outside.

 *
 */
public class XMLConfigSource {
  private static final String CWD = "CWD";

  // Define a logging category.
  private static final Logger log = LoggerFactory.getLogger(XMLConfigSource.class.getName());

  /**
   * INTERNAL: Don't call constructor directly. Instead used static
   * factory methods.
   */
  private XMLConfigSource() {
  }

  /**
   * PUBLIC: Get the topic map repository that is created by loading
   * the 'tm-sources.xml' configuration file from the classpath.

   *
   * @since 3.0
   */
  public static TopicMapRepositoryIF getRepositoryFromClassPath() {
    return getRepositoryFromClassPath("tm-sources.xml");
  }

  /**
   * PUBLIC: Get the topic map repository that is created by loading
   * the named resource from the classpath.

   *
   * @since 3.0
   */
  public static TopicMapRepositoryIF getRepositoryFromClassPath(String resourceName) {
    return getRepositoryFromClassPath(resourceName, null);
  }

  /**
   * INTERNAL:
   */
  public static TopicMapRepositoryIF getRepositoryFromClassPath(Map<String, String> environ) {
    return getRepositoryFromClassPath("tm-sources.xml", environ);
  }

  /**
   * INTERNAL:
   */
  public static TopicMapRepositoryIF getRepositoryFromClassPath(String resourceName, Map<String, String> environ) {

    // look up configuration via classpath
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    URL url = cl.getResource(resourceName);
    if (url == null) {
      throw new OntopiaRuntimeException("Could not find resource '" + resourceName + "' on CLASSPATH.");
    }

    // build configuration environment
    if (environ == null) {
      environ = new HashMap<String, String>(1);
    }
    if ("file".equals(url.getProtocol())) {
      String file = url.getFile();
      environ.put(CWD, file.substring(0, file.lastIndexOf('/')));
    } else {
      environ.put(CWD, ".");
    }

    // read configuration and create the repository instance
    try {
      return createRepository(readSources(new InputSource(url.openStream()),
                                          environ));
    } catch (IOException e) {
      throw new OntopiaRuntimeException(e);
    }

  }

  /**
   * PUBLIC: Gets the topic map repository that is created by reading
   * the configuration file.

   */
  public static TopicMapRepositoryIF getRepository(String config_file) {
    return createRepository(readSources(config_file));
  }

  /**
   * INTERNAL: Gets the topic map repository that is created by
   * reading the configuration file with the given environment.

   */
  public static TopicMapRepositoryIF getRepository(String config_file, Map<String, String> environ) {
    return createRepository(readSources(config_file, environ));
  }

  /**
   * PUBLIC: Gets the topic map repository that is created by reading
   * the configuration file from the reader.

   *
   * @since 3.0
   */
  public static TopicMapRepositoryIF getRepository(Reader config_file) {
    return createRepository(readSources(new InputSource(config_file), null));
  }

  /**
   * INTERNAL: Gets the topic map repository that is created by
   * reading the configuration file from the reader with the given
   * environment.

   *
   * @since 3.0
   */
  public static TopicMapRepositoryIF getRepository(Reader config_file, Map<String, String> environ) {
    return createRepository(readSources(new InputSource(config_file), environ));
  }

  private static TopicMapSourceManager createRepository(Collection<TopicMapSourceIF> sources) {
    // assign default source ids and titles
    int counter = 1;
    Iterator<TopicMapSourceIF> iter = sources.iterator();
    while (iter.hasNext()) {
      TopicMapSourceIF source = iter.next();
      if (source.getId() == null && source.supportsCreate()) {
        String newId = source.getClass().getName() + "-" + (counter++);
        source.setId(newId);
        if (source.getTitle() == null) {
          source.setTitle(newId);
        }
      }
    }
    return new TopicMapSourceManager(sources);
  }

  /**
   * INTERNAL: Returns a collection containing the topic map sources
   * created by reading the configuration file.
   */
  public static List<TopicMapSourceIF> readSources(String config_file) {
    return readSources(config_file, new HashMap<String, String>(1));
  }

  /**
   * INTERNAL: Returns a collection containing the topic map sources
   * created by reading the configuration file.
   */
  public static List<TopicMapSourceIF> readSources(String config_file, Map<String, String> environ) {
    if (environ == null) {
      environ = new HashMap<String, String>(1);
    }
    // add CWD entry
    if (!environ.containsKey(CWD)) {
      File file = new File(config_file);
      if (!file.exists()) {
        throw new OntopiaRuntimeException("Config file '" + config_file +
                                          "' does not exist.");
      }
      environ.put(CWD, file.getParent());
    }

    return readSources(new InputSource(URIUtils.toURL(new File(config_file)).toString()), environ);
  }

  // ------------------------------------------------------------
  // internal helper method(s)
  // ------------------------------------------------------------

  private static List<TopicMapSourceIF> readSources(InputSource inp_source, Map<String, String> environ) {
    ConfigHandler handler = new ConfigHandler(environ);

    try {
      XMLReader parser = DefaultXMLReaderFactory.createXMLReader();
      parser.setContentHandler(handler);
      parser.setErrorHandler(new Slf4jSaxErrorHandler(log));
      parser.parse(inp_source);
    } catch (SAXParseException e) {
      String msg = "" + e.getSystemId() + ":" + e.getLineNumber() + ":" +
                   e.getColumnNumber() + ": " + e.getMessage();
      throw new OntopiaRuntimeException(msg, e);
    } catch (Exception e) {
      throw new OntopiaRuntimeException(e);
    }
    return handler.sources;
  }

  // ------------------------------------------------------------
  // internal ContentHandler class
  // ------------------------------------------------------------

  static class ConfigHandler extends DefaultHandler {
    private Map<String, String> environ;
    //Map params = new HashMap();
    private List<TopicMapSourceIF> sources = new ArrayList<TopicMapSourceIF>();

    private TopicMapSourceIF source;

    ConfigHandler(Map<String, String> environ) {
      this.environ = environ;
    }

    @Override
    public void startElement(String uri, String name, String qName,
                              Attributes atts) throws SAXException {
      if ("source".equals(qName)) {
        // Clear source member
        source = null;
        try {
          ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
          source = (TopicMapSourceIF) Class.forName(atts.getValue("class"), true, classLoader).newInstance();
          String id = atts.getValue("id");
          if (id != null) {
            source.setId(id);
          }
          sources.add(source);
          //log.debug("Added source " + source + ".");
        } catch (ClassNotFoundException e) {
          log.error("Cannot find class " + e.getMessage());
        } catch (Exception e) {
          log.error("Exception: " + e.getClass().getName() + ": " + e.getMessage());
        }
      }
      else if ("param".equals(qName) && source != null) {
        String param_name = atts.getValue("name");
        String param_value = atts.getValue("value");
        Iterator<String> iter = environ.keySet().iterator();
        while (iter.hasNext()) {
          String environ_key = iter.next();
          param_value = StringUtils.replace(param_value, "${" + environ_key + "}", environ.get(environ_key));
        }

        try {
          BeanInfo bean_info = Introspector.getBeanInfo(source.getClass());
          PropertyDescriptor[] props = bean_info.getPropertyDescriptors();
          boolean found_property = false;
          for (int i = 0; i < props.length; i++) {
            //log.debug("property: " + props[i].getName());
            //System.out.println("P: " + props[i].getName() + " T: " + props[i].getPropertyType());
            if (props[i].getName().equals(param_name)) {
              Method setter = props[i].getWriteMethod();
              if (props[i].getPropertyType().equals(String.class)) {
                setter.invoke(source, new Object[] {param_value});
                found_property = true;
                break;
              }
              else if (props[i].getPropertyType().equals(boolean.class)) {
                setter.invoke(source, new Object[] {Boolean.parseBoolean(param_value)});
                found_property = true;
                break;
              }
            }
          }
          if (!found_property) {
            throw new SAXException("Cannot find property '" + param_name + "' " +
                                   "on source " + source);
          }
        } catch (IntrospectionException e) {
          throw new SAXException(e);
        } catch (InvocationTargetException e) {
          throw new SAXException(e);
        } catch (IllegalAccessException e) {
          throw new SAXException(e);
        }
      }
    }

    @Override
    public void endElement(String uri, String name, String qName) throws SAXException {
      if ("source".equals(qName)) {
        source = null;
      }
    }

  }
}


text:
package org.nosceon.titanite.xml;

import org.nosceon.titanite.BodyReader;
import org.nosceon.titanite.BodyWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.*;
import java.util.Map;
import java.util.WeakHashMap;

/**
 * @author Johan Siebens
 */
public final class JaxbMapper {

    private static JaxbMapper INSTANCE = new JaxbMapper(false);

    public static <T> BodyReader<T> xml(Class<T> type) {
        return INSTANCE.reader(type);
    }

    public static BodyWriter xml(Object value) {
        return INSTANCE.writer(value);
    }

    private static final Map<Class, JAXBContext> JAXB_CONTEXTS = new WeakHashMap<>();

    private final boolean formatted;

    public JaxbMapper(boolean formatted) {
        this.formatted = formatted;
    }

    public <T> BodyReader<T> reader(Class<T> type) {
        return in -> {
            try (Reader reader = new InputStreamReader(in)) {
                return type.cast(unmarshaller(type).unmarshal(reader));
            }
        };
    }

    public BodyWriter writer(Object value) {
        return out -> {
            try (Writer w = new BufferedWriter(new OutputStreamWriter(out))) {
                marshaller(value.getClass()).marshal(value, w);
            }
        };
    }

    private Marshaller marshaller(Class<?> type) throws JAXBException {
        Marshaller marshaller = getJAXBContext(type).createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, formatted);
        return marshaller;
    }

    private Unmarshaller unmarshaller(Class<?> type) throws JAXBException {
        return getJAXBContext(type).createUnmarshaller();
    }

    private static JAXBContext getJAXBContext(Class<?> type) throws JAXBException {
        synchronized (JAXB_CONTEXTS) {
            JAXBContext c = JAXB_CONTEXTS.get(type);
            if (c == null) {
                c = JAXBContext.newInstance(type);
                JAXB_CONTEXTS.put(type, c);
            }
            return c;
        }
    }

}


text:
package com.jme3.system.jopenvr;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import java.util.Arrays;
import java.util.List;
/**
 * native declaration : headers\openvr_capi.h:1633

 * This file was autogenerated by JNAerator,

 * a tool written by Olivier Chafik that uses a few opensource projects..

 * For help, please visit NativeLibs4Java , Rococoa, or JNA.
 */
public class VRActiveActionSet_t extends Structure {
	/** C type : VRActionSetHandle_t */
	public long ulActionSet;
	/** C type : VRInputValueHandle_t */
	public long ulRestrictedToDevice;
	/** C type : VRActionSetHandle_t */
	public long ulSecondaryActionSet;
	public int unPadding;
	public int nPriority;
	public VRActiveActionSet_t() {
		super();
	}
        @Override
	protected List<String> getFieldOrder() {
		return Arrays.asList("ulActionSet", "ulRestrictedToDevice", "ulSecondaryActionSet", "unPadding", "nPriority");
	}
	/**
	 * @param ulActionSet C type : VRActionSetHandle_t

	 * @param ulRestrictedToDevice C type : VRInputValueHandle_t

	 * @param ulSecondaryActionSet C type : VRActionSetHandle_t
	 */
	public VRActiveActionSet_t(long ulActionSet, long ulRestrictedToDevice, long ulSecondaryActionSet, int unPadding, int nPriority) {
		super();
		this.ulActionSet = ulActionSet;
		this.ulRestrictedToDevice = ulRestrictedToDevice;
		this.ulSecondaryActionSet = ulSecondaryActionSet;
		this.unPadding = unPadding;
		this.nPriority = nPriority;
	}
	public VRActiveActionSet_t(Pointer peer) {
		super(peer);
	}
	public static class ByReference extends VRActiveActionSet_t implements Structure.ByReference {

	};
	public static class ByValue extends VRActiveActionSet_t implements Structure.ByValue {

	};
}


text:
oauth2-reverse-proxy
====================

do oauth2 authentication before reverse proxy request to backend resource api server


text:
using CertiPay.Common.Logging;
using CertiPay.Common.Redis;
using CertiPay.Common.Testing;
using CertiPay.Common.WorkQueue;
using NUnit.Framework;
using System;
using System.Linq;

namespace CertiPay.Services.Redis
{
    public class RedisQueueManagerTests
    {
        private static readonly ILog Log = LogManager.GetLogger<RedisQueueManagerTests>();

        private String queueName = "TestQueue";
        private String message = "This is a test!";

        private RedisConnection conn;
        private RedisQueueManager queue;

        [SetUp]
        public void SetUp()
        {
            // Arrange

            conn = new RedisConnection();
            queue = new RedisQueueManager(conn);
        }

        [Test, Integration]
        public void Should_Enqueue_Items()
        {
            // Act

            AddTestMessages(count: 1, queueName: queueName);

            var item = queue.GetWork<TestMessage>(queueName).Result;

            // Assert
            Assert.AreEqual(message, item.Message);
            Assert.IsTrue(item.Created > DateTime.UtcNow.AddSeconds(-2));
        }

        [Test, Integration]
        public void Should_Enqueue_Items_Performance_Test()
        {
            // Arrange

            var range = 1000;

            var queueNames = new[] { "TestQueue1", "TestQueue2", "TestQueue3", "TestQueue4", "TestQueue5" };

            using (Log.Timer("Iterating through all queues"))
            {
                foreach (var queueName in queueNames)
                {
                    using (Log.Timer("Loading into queue", queueName))
                    {
                        // Act

                        AddTestMessages(count: range, queueName: queueName);
                    }
                }
                using (Log.Timer("Loading from queue", queueName))
                {
                    foreach (var msg in queue.GetConsumingEnumerable<TestMessage>(queueName))
                    {
                        Assert.AreEqual(message, msg.Message);
                        Assert.AreEqual(msg.Created.Date, DateTime.UtcNow.Date);

                        if (msg.Created.Ticks % 2 == 0)
                        {
                            queue.MarkComplete(queueName, new CompletedWorkItem<TestMessage> { WorkItem = msg });
                        }
                        else
                        {
                            queue.MarkFailed(queueName, new FailedWorkItem<TestMessage> { WorkItem = msg, ErrorMessage = "Shitz broke!" });
                        }
                    }
                }
            }
        }

        [Test, Integration]
        public void Should_Consume_Until_Empty()
        {
            // Act

            var range = 1000;

            AddTestMessages(count: range, queueName: queueName);

            int count = 0;

            // Assert - kind of

            foreach (var item in queue.GetConsumingEnumerable<TestMessage>(queueName))
            {
                Assert.AreEqual(message, item.Message);

                count++;
            }

            Assert.AreEqual(range, count);
        }

        [Test, Integration]
        public void Should_Batch_Work_Dequeue()
        {
            var range = 1000;

            AddTestMessages(count: range, queueName: queueName);

            var batch_size = 5;

            var batches = (range / batch_size);

            var batch_count = 0;

            foreach (var batch_id in Enumerable.Range(0, batches))
            {
                var batch = queue.GetConsumingEnumerable<TestMessage>(queueName).Take(batch_size).ToList();

                Assert.AreEqual(batch_size, batch.Count);

                Assert.IsTrue(batch.All(m => m.Message == message));

                batch_count++;
            }

            Assert.AreEqual(batches, batch_count);
        }

        [Test, Integration]
        public void Should_Batch_Work_Uneven_Batch()
        {
            var range = 13;

            AddTestMessages(count: range, queueName: queueName);

            var batch_size = 5;

            var batches = (int)Math.Ceiling((double)range / batch_size);

            var batch_count = 0;

            foreach (var batch_id in Enumerable.Range(0, batches))
            {
                var batch = queue.GetConsumingEnumerable<TestMessage>(queueName).Take(batch_size).ToList();

                Assert.IsTrue(batch.All(m => m.Message == message));
                Assert.IsTrue(batch.Count == 3 || batch.Count == 5);

                batch_count++;
            }

            Assert.AreEqual(batches, batch_count);
        }

        private void AddTestMessages(int count, string queueName)
        {
            queue.Purge(queueName);

            foreach (var i in Enumerable.Range(1, count))
            {
                queue.Enqueue(queueName, new TestMessage
                {
                    Message = message,
                    Active = false,
                    ID = Guid.NewGuid()
                });
            };
        }

        public class TestMessage
        {
            public Guid ID { get; set; }

            public String Message { get; set; }

            public Boolean Active { get; set; }

            public DateTime Created = DateTime.UtcNow;
        }
    }
}


text:
echo "Installing python-dev and build-essential"
sudo apt-get update && sudo apt-get install -y python-dev build-essential
echo "Done!"

echo "Installing pip..."
wget https://raw.github.com/pypa/pip/master/contrib/get-pip.py
sudo python get-pip.py
echo "Done!"
echo "Installing virtualenv..."
sudo pip install virtualenv
echo "Done!"
echo "Making a virtualenv and installing swiftclient and keystoneclient..."
mkdir swiftclient
virtualenv swiftclient
cd swiftclient
source bin/activate
pip install python-swiftclient
pip install python-keystoneclient
echo "Done!"

echo "Successfully installed swift command line tools."
echo "Remember: you need to activate the virtualenv to use them!"
echo "cd ~/swiftclient"
echo "source bin/activate"
echo "You also need to add your credentials to your .profile"


text:
#include <aws/cloudtrail/model/DescribeQueryRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::CloudTrail::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

DescribeQueryRequest::DescribeQueryRequest() :
    m_eventDataStoreHasBeenSet(false),
    m_queryIdHasBeenSet(false)
{
}

Aws::String DescribeQueryRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_eventDataStoreHasBeenSet)
  {
   payload.WithString("EventDataStore", m_eventDataStore);

  }

  if(m_queryIdHasBeenSet)
  {
   payload.WithString("QueryId", m_queryId);

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection DescribeQueryRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101.DescribeQuery"));
  return headers;

}


text:
<?php
namespace MofgForm;

class Html{
	use MultiMethodNameTrait;

	/**
	 * @var object
	 */
	private $Form = null;

	/**
	 * @param object $Form
	 */
	function __construct($Form){
		$this->Form = $Form;
	}

	/**
	 * @param string $name
	 * @param array $items
	 * @param array $attrs (optional)
	 */
	public function checkbox($name, $items, $attrs = []){
		if( is_string($items) ) $items = [$items];
		if( !is_array($items) ) return;
		$out = "";
		$data = $this->Form->get_value(str_replace("[]", "", $name));
		if( !is_array($data) ) $data = [$data];
		$attr_txt = $this->get_attr_text($attrs);
		foreach($items as $k => $v){
			if( !is_string($v) ) continue;
			if( is_int($k) ) $k = $v;
			$checked = ( in_array($k, $data, true) ) ? " checked=\"checked\"" : "";
			$brackets = ( count($items) > 1 ) ? "[]" : "";
			$k = htmlspecialchars($k);
			$v = htmlspecialchars($v);
			$out .= "<input type=\"checkbox\" name=\"{$name}{$brackets}\" value=\"{$k}\"{$checked} /> {$v}";
		}
		echo $out;
	}

	/**
	 * @param string $name
	 * @param array $items
	 * @param array $attrs (optional)
	 */
	public function radio($name, $items, $attrs = []){
		if( is_string($items) ) $items = [$items];
		if( !is_array($items) ) return;
		$out = "";
		$data = $this->Form->get_value($name);
		$attr_txt = $this->get_attr_text($attrs);
		foreach($items as $k => $v){
			if( !is_string($v) ) continue;
			if( is_int($k) ) $k = $v;
			$checked = ( $k === $data ) ? " checked=\"checked\"" : "";
			$k = htmlspecialchars($k);
			$v = htmlspecialchars($v);
			$out .= "<input type=\"radio\" name=\"{$name}\" value=\"{$k}\"{$checked} /> {$v}";
		}
		echo $out;
	}

	/**
	 * @param string $name
	 * @param array $options
	 * @param string $empty (optional)
	 * @param array $attrs (optional)
	 */
	public function select($name, $options, $empty = "", $attrs = []){
		if( is_string($options) ) $options = [$options];
		if( !is_array($options) ) return;
		$attr_txt = $this->get_attr_text($attrs);
		$out = "<select name=\"".htmlspecialchars($name)."\"{$attr_txt}>";
		if( is_string($empty) && $empty !== "" ){
			$out .= "<option value=\"\">".htmlspecialchars($empty)."</option>";
		}
		foreach($options as $i){
			if( !is_string($i) ) continue;
			$selected = ( $this->Form->get_value($name) === $i ) ? " selected=\"selected\"" : "";
			$i = htmlspecialchars($i);
			$out .= "<option value=\"{$i}\"{$selected}>{$i}</option>";
		}
		$out .= "</select>";
		echo $out;
	}

	/**
	 * @param string $name
	 * @param array $attrs (optional)
	 */
	public function text($name, $attrs = []){
		$attr_txt = $this->get_attr_text($attrs);
		$data = $this->Form->get_value($name);
		$data = ( is_string($data) ) ? htmlspecialchars($data) : "";
		echo "<input type=\"text\" name=\"{$name}\" value=\"{$data}\"{$attr_txt} />";
	}

	/**
	 * @param string $name
	 * @param array $attrs (optional)
	 */
	public function password($name, $attrs = []){
		$attr_txt = $this->get_attr_text($attrs);
		$data = $this->Form->get_value($name);
		$data = ( is_string($data) ) ? htmlspecialchars($data) : "";
		echo "<input type=\"password\" name=\"{$name}\" value=\"{$data}\"{$attr_txt} />";
	}

	/**
	 * @param string $name
	 * @param array $attrs (optional)
	 */
	public function textarea($name, $attrs = []){
		$attr_txt = $this->get_attr_text($attrs);
		$data = $this->Form->get_value($name);
		$data = ( is_string($data) ) ? htmlspecialchars($data) : "";
		echo "<textarea name=\"{$name}\"{$attr_txt}>{$data}</textarea>";
	}

	/**
	 * @param array $attrs (optional)
	 * @return string
	 */
	public function get_attr_text($attrs = []){
		$result = "";
		if( !empty($attrs) && is_array($attrs) ){
			foreach($attrs as $k => $v){
				if( !is_string($k) || !is_string($v) ) continue;
				$v = htmlspecialchars($v);
				$result .= " {$k}=\"{$v}\"";
			}
		}
		return $result;
	}
}


text:
package liquibase.statementexecute;

import liquibase.database.Database;
import liquibase.database.core.MSSQLDatabase;
import liquibase.database.core.MaxDBDatabase;
import liquibase.database.core.MySQLDatabase;
import liquibase.database.core.PostgresDatabase;
import liquibase.database.core.SQLiteDatabase;
import liquibase.database.core.SybaseASADatabase;
import liquibase.database.core.SybaseDatabase;
import liquibase.database.core.CacheDatabase;
import liquibase.database.core.*;
import liquibase.database.typeconversion.TypeConverterFactory;
import liquibase.test.TestContext;
import liquibase.test.DatabaseTestContext;
import liquibase.statement.*;
import liquibase.statement.core.AddColumnStatement;
import liquibase.statement.core.CreateTableStatement;
import liquibase.sqlgenerator.SqlGeneratorFactory;
import liquibase.sql.Sql;

import java.util.List;
import java.util.ArrayList;

import org.junit.Test;

public class AddColumnExecutorTest extends AbstractExecuteTest {

    protected static final String TABLE_NAME = "table_name";

    @Override
    protected List<? extends SqlStatement> setupStatements(Database database) {
        ArrayList<CreateTableStatement> statements = new ArrayList<CreateTableStatement>();
        CreateTableStatement table = new CreateTableStatement(null, TABLE_NAME);
        table.addColumn("id", TypeConverterFactory.getInstance().findTypeConverter(database).getDataType("int", false), null, new NotNullConstraint());
        statements.add(table);

        if (database.supportsSchemas()) {
            table = new CreateTableStatement(DatabaseTestContext.ALT_SCHEMA, TABLE_NAME);
            table.addColumn("id", TypeConverterFactory.getInstance().findTypeConverter(database).getDataType("int", false), null, new NotNullConstraint());
            statements.add(table);
        }
        return statements;
    }

    @SuppressWarnings("unchecked")
	@Test
    public void generateSql_autoIncrement() throws Exception {
        this.statementUnderTest = new AddColumnStatement(null, "table_name", "column_name", "int", null, new AutoIncrementConstraint("column_name"));

        assertCorrect("alter table table_name add column_name serial", InformixDatabase.class);
        assertCorrect("alter table [table_name] add [column_name] int default autoincrement null", SybaseASADatabase.class);
        assertCorrect("alter table [table_name] add [column_name] serial", PostgresDatabase.class);
        assertCorrect("alter table [dbo].[table_name] add [column_name] int identity", MSSQLDatabase.class);
        assertCorrect("alter table [table_name] add [column_name] int identity null", SybaseDatabase.class);
        assertCorrect("not supported. fixme!!", SQLiteDatabase.class);
        assertCorrect("alter table table_name add column_name int auto_increment_clause");
    }

    @SuppressWarnings("unchecked")
	@Test
    public void generateSql_notNull() throws Exception {
        this.statementUnderTest = new AddColumnStatement(null, "table_name", "column_name", "int", 42, new NotNullConstraint());
        assertCorrect("alter table [table_name] add [column_name] int not null default 42", CacheDatabase.class, MaxDBDatabase.class);
        assertCorrect("alter table [table_name] add [column_name] int default 42 not null", SybaseASADatabase.class, SybaseDatabase.class);
        assertCorrect("alter table table_name add column_name int not null default 42", PostgresDatabase.class);
        assertCorrect("alter table [dbo].[table_name] add [column_name] int not null constraint df_table_name_column_name default 42", MSSQLDatabase.class);
        assertCorrect("alter table `table_name` add `column_name` int not null default 42", MySQLDatabase.class);
        assertCorrect("not supported. fixme!!", SQLiteDatabase.class);
        assertCorrect("ALTER TABLE [table_name] ADD [column_name] int DEFAULT 42 NOT NULL");
    }

    @SuppressWarnings("unchecked")
	@Test
    public void generateSql_primaryKey() throws Exception {
        this.statementUnderTest = new AddColumnStatement(null, "table_name", "column_name", "int", null, new PrimaryKeyConstraint());

        assertCorrect("alter table [table_name] add [column_name] int not null primary key", HsqlDatabase.class, MaxDBDatabase.class);
        assertCorrect("alter table [table_name] add [column_name] int primary key not null", SybaseASADatabase.class, SybaseDatabase.class);
        assertCorrect("alter table [dbo].[table_name] add [column_name] int not null primary key", MSSQLDatabase.class);
        assertCorrect("alter table table_name add column_name int not null primary key", PostgresDatabase.class);
        assertCorrect("alter table `table_name` add `column_name` int not null primary key", MySQLDatabase.class);
        assertCorrect("ALTER TABLE [table_name] ADD [column_name] int PRIMARY KEY NOT NULL");
    }

    @SuppressWarnings("unchecked")
	@Test
    public void generateSql_foreignKey() throws Exception {
        this.statementUnderTest = new AddColumnStatement(null, "table_name", "column_name", "int", null, new PrimaryKeyConstraint(), new ForeignKeyConstraint("fk_test_fk", "table_name(column_name)"));

        assertCorrect(new String[] {"alter table [table_name] add [column_name] int not null primary key", "alter table [table_name] add constraint [fk_test_fk] foreign key ([column_name]) references [table_name]([column_name])"}, HsqlDatabase.class, MaxDBDatabase.class);
        assertCorrect(new String[] {"alter table [table_name] add [column_name] int primary key not null", "alter table [table_name] add constraint [fk_test_fk] foreign key ([column_name]) references [table_name]([column_name])"}, SybaseASADatabase.class, SybaseDatabase.class);
        assertCorrect(new String[] {"alter table [dbo].[table_name] add [column_name] int not null primary key", "alter table [dbo].[table_name] add constraint [fk_test_fk] foreign key ([column_name]) references [dbo].[table_name]([column_name])"}, MSSQLDatabase.class);
        assertCorrect(new String[] {"alter table table_name add column_name int not null primary key", "alter table [table_name] add constraint [fk_test_fk] foreign key ([column_name]) references [table_name]([column_name])"}, PostgresDatabase.class);
        assertCorrect(new String[] {"alter table `table_name` add `column_name` int not null primary key", "alter table [table_name] add constraint [fk_test_fk] foreign key ([column_name]) references [table_name]([column_name])"}, MySQLDatabase.class);
        assertCorrect(new String[] {"ALTER TABLE [table_name] ADD [column_name] int PRIMARY KEY NOT NULL", "alter table [table_name] add constraint  foreign key ([column_name]) references [table_name]([column_name]) constraint [fk_test_fk]"}, InformixDatabase.class);
        assertCorrect(new String[] {"ALTER TABLE [table_name] ADD [column_name] int PRIMARY KEY NOT NULL", "alter table [table_name] add constraint [fk_test_fk] foreign key ([column_name]) references [table_name]([column_name])"});
    }

}


text:
"""Text file trace backend

Store sampling values as CSV files.

File format
-----------

Sampling values for each chain are saved in a separate file (under a
directory specified by the `name` argument).  The rows correspond to
sampling iterations.  The column names consist of variable names and
index labels.  For example, the heading

  x,y__0_0,y__0_1,y__1_0,y__1_1,y__2_0,y__2_1

represents two variables, x and y, where x is a scalar and y has a
shape of (3, 2).
"""
from glob import glob
import numpy as np
import os
import pandas as pd

from ..backends import base, ndarray
from . import tracetab as ttab

class Text(base.BaseTrace):
    """Text trace object

    Parameters
    ----------
    name : str
        Name of directory to store text files
    model : Model
        If None, the model is taken from the `with` context.
    vars : list of variables
        Sampling values will be stored for these variables. If None,
        `model.unobserved_RVs` is used.
    """

    def __init__(self, name, model=None, vars=None):
        if not os.path.exists(name):
            os.mkdir(name)
        super(Text, self).__init__(name, model, vars)

        self.flat_names = {v: ttab.create_flat_names(v, shape)
                           for v, shape in self.var_shapes.items()}

        self.filename = None
        self._fh = None
        self.df = None

    # Sampling methods

    def setup(self, draws, chain):
        """Perform chain-specific setup.

        Parameters
        ----------
        draws : int
            Expected number of draws
        chain : int
            Chain number
        """
        self.chain = chain
        self.filename = os.path.join(self.name, 'chain-{}.csv'.format(chain))

        cnames = [fv for v in self.varnames for fv in self.flat_names[v]]

        if os.path.exists(self.filename):
            with open(self.filename) as fh:
                prev_cnames = next(fh).strip().split(',')
            if prev_cnames != cnames:
                raise base.BackendError(
                    "Previous file '{}' has different variables names "
                    "than current model.".format(self.filename))
            self._fh = open(self.filename, 'a')
        else:
            self._fh = open(self.filename, 'w')
            self._fh.write(','.join(cnames) + '\n')

    def record(self, point):
        """Record results of a sampling iteration.

        Parameters
        ----------
        point : dict
            Values mapped to variable names
        """
        vals = {}
        for varname, value in zip(self.varnames, self.fn(point)):
            vals[varname] = value.ravel()
        columns = [str(val) for var in self.varnames for val in vals[var]]
        self._fh.write(','.join(columns) + '\n')

    def close(self):
        self._fh.close()
        self._fh = None  # Avoid serialization issue.

    # Selection methods

    def _load_df(self):
        if self.df is None:
            self.df = pd.read_csv(self.filename)

    def __len__(self):
        if self.filename is None:
            return 0
        self._load_df()
        return self.df.shape[0]

    def get_values(self, varname, burn=0, thin=1):
        """Get values from trace.

        Parameters
        ----------
        varname : str
        burn : int
        thin : int

        Returns
        -------
        A NumPy array
        """
        self._load_df()
        var_df = self.df[self.flat_names[varname]]
        shape = (self.df.shape[0],) + self.var_shapes[varname]
        vals = var_df.values.ravel().reshape(shape)
        return vals[burn::thin]

    def _slice(self, idx):
        if idx.stop is not None:
            raise ValueError('Stop value in slice not supported.')
        return ndarray._slice_as_ndarray(self, idx)

    def point(self, idx):
        """Return dictionary of point values at `idx` for current chain
        with variables names as keys.
        """
        idx = int(idx)
        self._load_df()
        pt = {}
        for varname in self.varnames:
            vals = self.df[self.flat_names[varname]].iloc[idx].values
            pt[varname] = vals.reshape(self.var_shapes[varname])
        return pt

def load(name, model=None):
    """Load Text database.

    Parameters
    ----------
    name : str
        Name of directory with files (one per chain)
    model : Model
        If None, the model is taken from the `with` context.

    Returns
    -------
    A MultiTrace instance
    """
    files = glob(os.path.join(name, 'chain-*.csv'))

    if len(files) == 0:
        raise ValueError('No files present in directory {}'.format(name))

    straces = []
    for f in files:
        chain = int(os.path.splitext(f)[0].rsplit('-', 1)[1])
        strace = Text(name, model=model)
        strace.chain = chain
        strace.filename = f
        straces.append(strace)
    return base.MultiTrace(straces)

def dump(name, trace, chains=None):
    """Store values from NDArray trace as CSV files.

    Parameters
    ----------
    name : str
        Name of directory to store CSV files in
    trace : MultiTrace of NDArray traces
        Result of MCMC run with default NDArray backend
    chains : list
        Chains to dump. If None, all chains are dumped.
    """
    if not os.path.exists(name):
        os.mkdir(name)
    if chains is None:
        chains = trace.chains

    var_shapes = trace._straces[chains[0]].var_shapes
    flat_names = {v: ttab.create_flat_names(v, shape)
                  for v, shape in var_shapes.items()}

    for chain in chains:
        filename = os.path.join(name, 'chain-{}.csv'.format(chain))
        df = ttab.trace_to_dataframe(
            trace, chains=chain, flat_names=flat_names,hide_transformed_vars=False)
        df.to_csv(filename, index=False)


text:
package org.scaladebugger.api.profiles.java.requests.vm

import java.util.concurrent.atomic.AtomicBoolean

import org.scaladebugger.api.profiles.java.JavaDebugProfile
import org.scaladebugger.api.virtualmachines.DummyScalaVirtualMachine
import org.scaladebugger.test.helpers.ParallelMockFunSpec
import test.{ApiTestUtilities, VirtualMachineFixtures}

class JavaVMStartRequestIntegrationSpec extends ParallelMockFunSpec
  with VirtualMachineFixtures
  with ApiTestUtilities
{
  describe("JavaVMStartRequest") {
    it("should trigger when a virtual machine starts") {
      val testClass = "org.scaladebugger.test.misc.MainUsingApp"

      val detectedStart = new AtomicBoolean(false)

      val s = DummyScalaVirtualMachine.newInstance()

      s.withProfile(JavaDebugProfile.Name)
        .getOrCreateVMStartRequest()
        .foreach(_ => detectedStart.set(true))

      // Start our VM and listen for the start event
      withVirtualMachine(testClass, pendingScalaVirtualMachines = Seq(s)) { (s) =>
        // Eventually, we should receive the start event
        logTimeTaken(eventually {
          detectedStart.get() should be (true)
        })
      }
    }
  }
}


text:
void ServerSocket::Listen( uint16 port, int queue_size )
{
	if( m_fd >= 0 )
	{
		THROW_ERROR( "Socket is already listening" );
	}

    // TODO: socket configuration modifiers

	// Create the TCP socket
	m_fd = socket( PF_INET, SOCK_STREAM, IPPROTO_TCP );
	if( m_fd < 0 )
	{
		THROW_ERROR( "Failed to create server socket" );
	}

	int sockopt = 1;
	if( setsockopt( m_fd, SOL_SOCKET, SO_REUSEADDR,
	                &sockopt, sizeof(sockopt) ) )
	{
		THROW_ERROR( "Failed to set socket options" );
	}

	// Construct address structure
	struct sockaddr_in addr;
	memset( &addr, 0, sizeof(addr) ); // Clear struct
	addr.sin_family = AF_INET; // Internet/IP
	addr.sin_addr.s_addr = htonl( INADDR_ANY ); // Incoming addr (any local)
	addr.sin_port = htons( port ); // Server port

	// Bind the server socket
	if( bind( m_fd, (struct sockaddr*)&addr, sizeof(addr) ) < 0 )
	{
		THROW_ERROR( "Failed to bind the server socket" );
	}

	// Listen on the server socket
	if( listen( m_fd, queue_size ) < 0 )
	{
		THROW_ERROR( "Failed to listen on server socket" );
	}

	LOG_DEBUG( "Server socket listening on port %d (fd = %d)", port, m_fd );
}

RemoteSocket::Ptr ServerSocket::Accept()
{
	int client_socket;
	struct sockaddr_in client_addr;
	unsigned int addr_size = sizeof(client_addr);

	// Wait for client connection
	client_socket = accept( m_fd, (struct sockaddr *) &client_addr, &addr_size );
	if( client_socket < 0 )
	{
		THROW_ERROR( "Failed to accept client connection" );
	}
	else
	{
	  LOG_DEBUG( "Remote client '%s:%d' connected (fd = %d)",
	             inet_ntoa(client_addr.sin_addr),
	             ntohs(client_addr.sin_port),
	             client_socket );
	  return new RemoteSocket( client_socket );
	}
}

bool ServerSocket::Wait( int timeout )
{
    if( m_fd < 0 )
    {
        THROW_ERROR( "Can't wait connections from a closed socket" );
    }

    struct timeval* ts_timeout = NULL;
    struct timeval _ts_timeout;
    if( timeout >= 0 )
    {
        _ts_timeout.tv_sec = (timeout / 1000);
        _ts_timeout.tv_usec = (timeout % 1000)*1000;
        ts_timeout = &_ts_timeout;
    }

    fd_set fds;
    FD_ZERO( &fds );
    FD_SET( m_fd, &fds );

    // Check if we've got a data ready
    int n = 0;
    while(true)
    {
        n = select( m_fd+1, &fds, NULL, NULL, ts_timeout );
        if( n < 0 )
        {
            if( errno == EINTR ) continue;

            THROW_ERROR( "Error waiting for data (Error=%s)", strerror(errno) );
        }

        break;
    }

    return (n > 0);
}

void ServerSocket::GetInfo( std::string &address, uint16 &port )
{
	if( m_fd < 0 )
	{
		THROW_ERROR( "Can't wait for read from a closed socket" );
	}

	struct sockaddr_in addr;
	socklen_t addr_sz = sizeof(addr);

	if( getsockname( m_fd, (struct sockaddr*) &addr, &addr_sz ) )
	{
		THROW_ERROR( "Can't get remote address (Error=%s)", strerror(errno) );
	}

	address =  inet_ntoa( addr.sin_addr );
	port = ntohs( addr.sin_port );
}

std::string ServerSocket::GetAddress()
{
	std::string address;
	uint16 port;

	GetInfo( address, port );
	return address;
}

uint16 ServerSocket::GetPort()
{
	std::string address;
	uint16 port;

	GetInfo( address, port );
	return port;
}


text:
package path_mgmt

import (
	"fmt"
	"strings"

	//log "github.com/inconshreveable/log15"

	"github.com/scionproto/scion/go/lib/common"
	"github.com/scionproto/scion/go/proto"
)

// union represents the contents of the unnamed capnp union.
type union struct {
	Which        proto.PathMgmt_Which
	SegReq       *SegReq
	SegReply     *SegReply
	SegReg       *SegReg
	SegSync      *SegSync
	RevInfo      *RevInfo
	IFStateReq   *IFStateReq   `capnp:"ifStateReq"`
	IFStateInfos *IFStateInfos `capnp:"ifStateInfos"`
}

func (u *union) set(c proto.Cerealizable) error {
	switch p := c.(type) {
	case *SegReq:
		u.Which = proto.PathMgmt_Which_segReq
		u.SegReq = p
	case *SegReply:
		u.Which = proto.PathMgmt_Which_segReply
		u.SegReply = p
	case *SegReg:
		u.Which = proto.PathMgmt_Which_segReg
		u.SegReg = p
	case *SegSync:
		u.Which = proto.PathMgmt_Which_segSync
		u.SegSync = p
	case *RevInfo:
		u.Which = proto.PathMgmt_Which_revInfo
		u.RevInfo = p
	case *IFStateReq:
		u.Which = proto.PathMgmt_Which_ifStateReq
		u.IFStateReq = p
	case *IFStateInfos:
		u.Which = proto.PathMgmt_Which_ifStateInfos
		u.IFStateInfos = p
	default:
		return common.NewBasicError("Unsupported path mgmt union type (set)", nil,
			"type", common.TypeOf(c))
	}
	return nil
}

func (u *union) get() (proto.Cerealizable, error) {
	switch u.Which {
	case proto.PathMgmt_Which_segReq:
		return u.SegReq, nil
	case proto.PathMgmt_Which_segReply:
		return u.SegReply, nil
	case proto.PathMgmt_Which_segReg:
		return u.SegReg, nil
	case proto.PathMgmt_Which_segSync:
		return u.SegSync, nil
	case proto.PathMgmt_Which_revInfo:
		return u.RevInfo, nil
	case proto.PathMgmt_Which_ifStateReq:
		return u.IFStateReq, nil
	case proto.PathMgmt_Which_ifStateInfos:
		return u.IFStateInfos, nil
	}
	return nil, common.NewBasicError("Unsupported path mgmt union type (get)", nil, "type", u.Which)
}

var _ proto.Cerealizable = (*Pld)(nil)

type Pld struct {
	union
	*Data
}

// NewPld creates a new path mgmt payload, containing the supplied Cerealizable instance.
func NewPld(u proto.Cerealizable, d *Data) (*Pld, error) {
	p := &Pld{Data: d}
	return p, p.union.set(u)
}

func (p *Pld) Union() (proto.Cerealizable, error) {
	return p.union.get()
}

func (p *Pld) ProtoId() proto.ProtoIdType {
	return proto.PathMgmt_TypeID
}

func (p *Pld) String() string {
	desc := []string{"PathMgmt: Union:"}
	u, err := p.Union()
	if err != nil {
		desc = append(desc, err.Error())
	} else {
		desc = append(desc, fmt.Sprintf("%+v", u))
	}
	return strings.Join(desc, " ")
}

type Data struct {
	// For passing any future non-union data.
}


text:
require 'erv/distribution'

module ERV

  class ConstantDistribution < Distribution
    def initialize(opts={})
      super(opts)

      raise ArgumentError unless opts[:value]
      @val = opts[:value].to_f
    end

    def mean
      @val
    end

    def variance
      0.0
    end

    def sample
      @val
    end
  end

end