text:
"""
Tests for Violin Memory 7000 Series All-Flash Array Fibrechannel Driver
"""

import mock

from cinder import exception
from cinder import test
from cinder.tests.unit import fake_vmem_client as vmemclient
from cinder.volume import configuration as conf
from cinder.volume.drivers.violin import v7000_common
from cinder.volume.drivers.violin import v7000_fcp

VOLUME_ID = "abcdabcd-1234-abcd-1234-abcdeffedcba"
VOLUME = {
    "name": "volume-" + VOLUME_ID,
    "id": VOLUME_ID,
    "display_name": "fake_volume",
    "size": 2,
    "host": "myhost",
    "volume_type": None,
    "volume_type_id": None,
}
SNAPSHOT_ID = "abcdabcd-1234-abcd-1234-abcdeffedcbb"
SNAPSHOT = {
    "name": "snapshot-" + SNAPSHOT_ID,
    "id": SNAPSHOT_ID,
    "volume_id": VOLUME_ID,
    "volume_name": "volume-" + VOLUME_ID,
    "volume_size": 2,
    "display_name": "fake_snapshot",
    "volume": VOLUME,
}
SRC_VOL_ID = "abcdabcd-1234-abcd-1234-abcdeffedcbc"
SRC_VOL = {
    "name": "volume-" + SRC_VOL_ID,
    "id": SRC_VOL_ID,
    "display_name": "fake_src_vol",
    "size": 2,
    "host": "myhost",
    "volume_type": None,
    "volume_type_id": None,
}
INITIATOR_IQN = "iqn.1111-22.org.debian:11:222"
CONNECTOR = {
    "initiator": INITIATOR_IQN,
    "host": "irrelevant",
    'wwpns': ['50014380186b3f65', '50014380186b3f67'],
}
FC_TARGET_WWPNS = [
    '31000024ff45fb22', '21000024ff45fb23',
    '51000024ff45f1be', '41000024ff45f1bf'
]
FC_INITIATOR_WWPNS = [
    '50014380186b3f65', '50014380186b3f67'
]
FC_FABRIC_MAP = {
    'fabricA':
    {'target_port_wwn_list': [FC_TARGET_WWPNS[0], FC_TARGET_WWPNS[1]],
     'initiator_port_wwn_list': [FC_INITIATOR_WWPNS[0]]},
    'fabricB':
    {'target_port_wwn_list': [FC_TARGET_WWPNS[2], FC_TARGET_WWPNS[3]],
     'initiator_port_wwn_list': [FC_INITIATOR_WWPNS[1]]}
}
FC_INITIATOR_TARGET_MAP = {
    FC_INITIATOR_WWPNS[0]: [FC_TARGET_WWPNS[0], FC_TARGET_WWPNS[1]],
    FC_INITIATOR_WWPNS[1]: [FC_TARGET_WWPNS[2], FC_TARGET_WWPNS[3]]
}

PHY_DEVICES_RESPONSE = {
    'data':
    {'physical_devices':
        [{'availsize': 1099504287744,
          'availsize_mb': 524284,
          'category': 'Virtual Device',
          'connection_type': 'block',
          'firmware': 'v1.0',
          'guid': '3cc4d6dd-166d-77d2-4967-00005463f597',
          'inquiry_string': '000002122b000032BKSC    OTHDISK-MFCN01  v1.0',
          'is_foreign': True,
          'name': 'BKSC:OTHDISK-MFCN01.000',
          'object_id': '84b834fb-1f4d-5d3b-b7ae-5796f9868151',
          'owner': 'example.com',
          'pool': None,
          'product': 'OTHDISK-MFCN01',
          'scsi_address':
          {'adapter': '98',
           'channel': '0',
           'id': '0',
           'lun': '0',
           'object_id': '6e0106fc-9c1c-52a2-95c9-396b7a653ac1'},
          'size': 1099504287744,
          'size_mb': 1048569,
          'type': 'Direct-Access',
          'usedsize': 0,
          'usedsize_mb': 0,
          'vendor': 'BKSC',
          'wwid': 'BKSC    OTHDISK-MFCN01  v1.0-0-0-00'},
         {'availsize': 1099504287744,
          'availsize_mb': 524284,
          'category': 'Virtual Device',
          'connection_type': 'block',
          'firmware': 'v1.0',
          'guid': '283b2694-192b-4745-6768-00005463f673',
          'inquiry_string': '000002122b000032BKSC    OTHDISK-MFCN08  v1.0',
          'is_foreign': False,
          'name': 'BKSC:OTHDISK-MFCN08.000',
          'object_id': '8555b888-bf43-5083-a433-f0c7b0282370',
          'owner': 'example.com',
          'pool':
          {'name': 'mga-pool',
           'object_id': '0818d3de-4437-535f-9cac-cc100a2c9313'},
          'product': 'OTHDISK-MFCN08',
          'scsi_address':
          {'adapter': '98',
           'channel': '0',
           'id': '11',
           'lun': '0',
           'object_id': '6e0106fc-9c1c-52a2-95c9-396b7a653ac1'},
          'size': 1099504287744,
          'size_mb': 1048569,
          'type': 'Direct-Access',
          'usedsize': 0,
          'usedsize_mb': 0,
          'vendor': 'BKSC',
          'wwid': 'BKSC    OTHDISK-MFCN08  v1.0-0-0-00'},
         {'availsize': 1099504287744,
          'availsize_mb': 1048569,
          'category': 'Virtual Device',
          'connection_type': 'block',
          'firmware': 'v1.0',
          'guid': '7f47db19-019c-707d-0df1-00005463f949',
          'inquiry_string': '000002122b000032BKSC    OTHDISK-MFCN09  v1.0',
          'is_foreign': False,
          'name': 'BKSC:OTHDISK-MFCN09.000',
          'object_id': '62a98898-f8b8-5837-af2b-764f5a72e291',
          'owner': 'a.b.c.d',
          'pool':
          {'name': 'mga-pool',
           'object_id': '0818d3de-4437-535f-9cac-cc100a2c9313'},
          'product': 'OTHDISK-MFCN09',
          'scsi_address':
          {'adapter': '98',
           'channel': '0',
           'id': '12',
           'lun': '0',
           'object_id': '6e0106fc-9c1c-52a2-95c9-396b7a653ac1'},
          'size': 1099504287744,
          'size_mb': 524284,
          'type': 'Direct-Access',
          'usedsize': 0,
          'usedsize_mb': 0,
          'vendor': 'BKSC',
          'wwid': 'BKSC    OTHDISK-MFCN09  v1.0-0-0-00'}],
        'total_physical_devices': 3},
    'msg': 'Successful',
    'success': True
}

# The FC_INFO dict returned by the backend is keyed on
# object_id of the FC adapter and the values are the
# wwmns
FC_INFO = {
    '1a3cdb6a-383d-5ba6-a50b-4ba598074510': ['2100001b9745e25e'],
    '4a6bc10a-5547-5cc0-94f2-76222a8f8dff': ['2100001b9745e230'],
    'b21bfff5-d89e-51ff-9920-d990a061d722': ['2100001b9745e25f'],
    'b508cc6b-f78a-51f9-81cf-47c1aaf53dd1': ['2100001b9745e231']
}

CLIENT_INFO = {
    'FCPolicy':
    {'AS400enabled': False,
     'VSAenabled': False,
     'initiatorWWPNList': ['50-01-43-80-18-6b-3f-66',
                           '50-01-43-80-18-6b-3f-64']},
    'FibreChannelDevices':
    [{'access': 'ReadWrite',
      'id': 'v0000004',
      'initiatorWWPN': '*',
      'lun': '8',
      'name': 'abcdabcd-1234-abcd-1234-abcdeffedcba',
      'sizeMB': 10240,
      'targetWWPN': '*',
      'type': 'SAN'}]
}

CLIENT_INFO1 = {
    'FCPolicy':
    {'AS400enabled': False,
     'VSAenabled': False,
     'initiatorWWPNList': ['50-01-43-80-18-6b-3f-66',
                           '50-01-43-80-18-6b-3f-64']},
    'FibreChannelDevices': []
}

class V7000FCPDriverTestCase(test.TestCase):
    """Test cases for VMEM FCP driver."""
    def setUp(self):
        super(V7000FCPDriverTestCase, self).setUp()
        self.conf = self.setup_configuration()
        self.driver = v7000_fcp.V7000FCPDriver(configuration=self.conf)
        self.driver.common.container = 'myContainer'
        self.driver.device_id = 'ata-VIOLIN_MEMORY_ARRAY_23109R00000022'
        self.driver.gateway_fc_wwns = FC_TARGET_WWPNS
        self.stats = {}
        self.driver.set_initialized()

    def tearDown(self):
        super(V7000FCPDriverTestCase, self).tearDown()

    def setup_configuration(self):
        config = mock.Mock(spec=conf.Configuration)
        config.volume_backend_name = 'v7000_fcp'
        config.san_ip = '8.8.8.8'
        config.san_login = 'admin'
        config.san_password = ''
        config.san_thin_provision = False
        config.san_is_local = False
        config.request_timeout = 300
        config.container = 'myContainer'
        return config

    def setup_mock_concerto(self, m_conf=None):
        """Create a fake Concerto communication object."""
        _m_concerto = mock.Mock(name='Concerto',
                                version='1.1.1',
                                spec=vmemclient.mock_client_conf)

        if m_conf:
            _m_concerto.configure_mock(**m_conf)

        return _m_concerto

    @mock.patch.object(v7000_common.V7000Common, 'check_for_setup_error')
    def test_check_for_setup_error(self, m_setup_func):
        """No setup errors are found."""
        result = self.driver.check_for_setup_error()
        m_setup_func.assert_called_with()
        self.assertIsNone(result)

    @mock.patch.object(v7000_common.V7000Common, 'check_for_setup_error')
    def test_check_for_setup_error_no_wwn_config(self, m_setup_func):
        """No wwns were found during setup."""
        self.driver.gateway_fc_wwns = []
        failure = exception.ViolinInvalidBackendConfig
        self.assertRaises(failure, self.driver.check_for_setup_error)

    def test_create_volume(self):
        """Volume created successfully."""
        self.driver.common._create_lun = mock.Mock()

        result = self.driver.create_volume(VOLUME)

        self.driver.common._create_lun.assert_called_with(VOLUME)
        self.assertIsNone(result)

    def test_create_volume_from_snapshot(self):
        self.driver.common._create_volume_from_snapshot = mock.Mock()

        result = self.driver.create_volume_from_snapshot(VOLUME, SNAPSHOT)

        self.driver.common._create_volume_from_snapshot.assert_called_with(
            SNAPSHOT, VOLUME)

        self.assertIsNone(result)

    def test_create_cloned_volume(self):
        self.driver.common._create_lun_from_lun = mock.Mock()

        result = self.driver.create_cloned_volume(VOLUME, SRC_VOL)

        self.driver.common._create_lun_from_lun.assert_called_with(
            SRC_VOL, VOLUME)
        self.assertIsNone(result)

    def test_delete_volume(self):
        """Volume deleted successfully."""
        self.driver.common._delete_lun = mock.Mock()

        result = self.driver.delete_volume(VOLUME)

        self.driver.common._delete_lun.assert_called_with(VOLUME)
        self.assertIsNone(result)

    def test_extend_volume(self):
        """Volume extended successfully."""
        new_size = 10
        self.driver.common._extend_lun = mock.Mock()

        result = self.driver.extend_volume(VOLUME, new_size)

        self.driver.common._extend_lun.assert_called_with(VOLUME, new_size)
        self.assertIsNone(result)

    def test_create_snapshot(self):
        self.driver.common._create_lun_snapshot = mock.Mock()

        result = self.driver.create_snapshot(SNAPSHOT)
        self.driver.common._create_lun_snapshot.assert_called_with(SNAPSHOT)
        self.assertIsNone(result)

    def test_delete_snapshot(self):
        self.driver.common._delete_lun_snapshot = mock.Mock()

        result = self.driver.delete_snapshot(SNAPSHOT)
        self.driver.common._delete_lun_snapshot.assert_called_with(SNAPSHOT)
        self.assertIsNone(result)

    def test_get_volume_stats(self):
        self.driver._update_volume_stats = mock.Mock()
        self.driver._update_volume_stats()

        result = self.driver.get_volume_stats(True)

        self.driver._update_volume_stats.assert_called_with()
        self.assertEqual(self.driver.stats, result)

    @mock.patch('socket.gethostbyaddr')
    def test_update_volume_stats(self, mock_gethost):
        """Test Update Volume Stats.

        Makes a mock query to the backend to collect stats on all physical
        devices.
        """

        def gethostbyaddr(addr):
            if addr == '8.8.8.8' or addr == 'example.com':
                return ('example.com', [], ['8.8.8.8'])
            else:
                return ('a.b.c.d', [], addr)
        mock_gethost.side_effect = gethostbyaddr

        backend_name = self.conf.volume_backend_name
        vendor_name = "Violin Memory, Inc."
        tot_gb = 2046
        free_gb = 1022

        phy_devices = "/batch/physicalresource/physicaldevice"

        conf = {
            'basic.get.side_effect': [PHY_DEVICES_RESPONSE, ],
        }

        self.driver.common.vmem_mg = self.setup_mock_concerto(m_conf=conf)

        result = self.driver._update_volume_stats()

        calls = [mock.call(phy_devices)]
        self.driver.common.vmem_mg.basic.get.assert_has_calls(calls)
        self.assertEqual(tot_gb, self.driver.stats['total_capacity_gb'])
        self.assertEqual(free_gb, self.driver.stats['free_capacity_gb'])
        self.assertEqual(backend_name,
                         self.driver.stats['volume_backend_name'])
        self.assertEqual(vendor_name, self.driver.stats['vendor_name'])
        self.assertIsNone(result)

    def test_get_active_fc_targets(self):
        """Test Get Active FC Targets.

        Makes a mock query to the backend to collect all the physical
        adapters and extract the WWNs.
        """

        conf = {
            'adapter.get_fc_info.return_value': FC_INFO,
        }

        self.driver.common.vmem_mg = self.setup_mock_concerto(m_conf=conf)

        result = self.driver._get_active_fc_targets()

        self.assertEqual({'2100001b9745e230', '2100001b9745e25f',
                          '2100001b9745e231', '2100001b9745e25e'},
                         set(result))

    def test_initialize_connection(self):
        lun_id = 1
        target_wwns = self.driver.gateway_fc_wwns
        init_targ_map = {}

        conf = {
            'client.create_client.return_value': None,
        }
        self.driver.common.vmem_mg = self.setup_mock_concerto(m_conf=conf)
        self.driver._export_lun = mock.Mock(return_value=lun_id)
        self.driver._build_initiator_target_map = mock.Mock(
            return_value=(target_wwns, init_targ_map))

        props = self.driver.initialize_connection(VOLUME, CONNECTOR)

        self.driver.common.vmem_mg.client.create_client.assert_called_with(
            name=CONNECTOR['host'], proto='FC', fc_wwns=CONNECTOR['wwpns'])
        self.driver._export_lun.assert_called_with(VOLUME, CONNECTOR)
        self.driver._build_initiator_target_map.assert_called_with(
            CONNECTOR)
        self.assertEqual("fibre_channel", props['driver_volume_type'])
        self.assertTrue(props['data']['target_discovered'])
        self.assertEqual(self.driver.gateway_fc_wwns,
                         props['data']['target_wwn'])
        self.assertEqual(lun_id, props['data']['target_lun'])

    def test_terminate_connection(self):
        target_wwns = self.driver.gateway_fc_wwns
        init_targ_map = {}

        self.driver.common.vmem_mg = self.setup_mock_concerto()
        self.driver._unexport_lun = mock.Mock()
        self.driver._is_initiator_connected_to_array = mock.Mock(
            return_value=False)
        self.driver._build_initiator_target_map = mock.Mock(
            return_value=(target_wwns, init_targ_map))

        props = self.driver.terminate_connection(VOLUME, CONNECTOR)

        self.driver._unexport_lun.assert_called_with(VOLUME, CONNECTOR)
        self.driver._is_initiator_connected_to_array.assert_called_with(
            CONNECTOR)
        self.driver._build_initiator_target_map.assert_called_with(
            CONNECTOR)
        self.assertEqual("fibre_channel", props['driver_volume_type'])
        self.assertEqual(target_wwns, props['data']['target_wwn'])
        self.assertEqual(init_targ_map, props['data']['initiator_target_map'])

    def test_export_lun(self):
        lun_id = '1'
        response = {'success': True, 'msg': 'Assign SAN client successfully'}

        conf = {
            'client.get_client_info.return_value': CLIENT_INFO,
        }
        self.driver.common.vmem_mg = self.setup_mock_concerto(m_conf=conf)

        self.driver.common._send_cmd_and_verify = mock.Mock(
            return_value=response)

        self.driver._get_lun_id = mock.Mock(return_value=lun_id)

        result = self.driver._export_lun(VOLUME, CONNECTOR)

        self.driver.common._send_cmd_and_verify.assert_called_with(
            self.driver.common.vmem_mg.lun.assign_lun_to_client,
            self.driver._is_lun_id_ready,
            'Assign SAN client successfully',
            [VOLUME['id'], CONNECTOR['host'], "ReadWrite"],
            [VOLUME['id'], CONNECTOR['host']])
        self.driver._get_lun_id.assert_called_with(
            VOLUME['id'], CONNECTOR['host'])
        self.assertEqual(lun_id, result)

    def test_export_lun_fails_with_exception(self):
        lun_id = '1'
        response = {'status': False, 'msg': 'Generic error'}
        failure = exception.ViolinBackendErr

        self.driver.common.vmem_mg = self.setup_mock_concerto()
        self.driver.common._send_cmd_and_verify = mock.Mock(
            side_effect=exception.ViolinBackendErr(response['msg']))
        self.driver._get_lun_id = mock.Mock(return_value=lun_id)

        self.assertRaises(failure, self.driver._export_lun, VOLUME, CONNECTOR)

    def test_unexport_lun(self):
        response = {'success': True, 'msg': 'Unassign SAN client successfully'}

        self.driver.common.vmem_mg = self.setup_mock_concerto()
        self.driver.common._send_cmd = mock.Mock(
            return_value=response)

        result = self.driver._unexport_lun(VOLUME, CONNECTOR)

        self.driver.common._send_cmd.assert_called_with(
            self.driver.common.vmem_mg.lun.unassign_client_lun,
            "Unassign SAN client successfully",
            VOLUME['id'], CONNECTOR['host'], True)
        self.assertIsNone(result)

    def test_get_lun_id(self):

        conf = {
            'client.get_client_info.return_value': CLIENT_INFO,
        }
        self.driver.common.vmem_mg = self.setup_mock_concerto(m_conf=conf)

        result = self.driver._get_lun_id(VOLUME['id'], CONNECTOR['host'])

        self.assertEqual(8, result)

    def test_is_lun_id_ready(self):
        lun_id = '1'
        self.driver.common.vmem_mg = self.setup_mock_concerto()

        self.driver._get_lun_id = mock.Mock(return_value=lun_id)

        result = self.driver._is_lun_id_ready(
            VOLUME['id'], CONNECTOR['host'])
        self.assertTrue(result)

    def test_build_initiator_target_map(self):
        """Successfully build a map when zoning is enabled."""
        expected_targ_wwns = FC_TARGET_WWPNS

        self.driver.lookup_service = mock.Mock()
        (self.driver.lookup_service.get_device_mapping_from_network.
         return_value) = FC_FABRIC_MAP

        result = self.driver._build_initiator_target_map(CONNECTOR)
        (targ_wwns, init_targ_map) = result

        (self.driver.lookup_service.get_device_mapping_from_network.
         assert_called_with(CONNECTOR['wwpns'], self.driver.gateway_fc_wwns))
        self.assertEqual(set(expected_targ_wwns), set(targ_wwns))

        i = FC_INITIATOR_WWPNS[0]
        self.assertIn(FC_TARGET_WWPNS[0], init_targ_map[i])
        self.assertIn(FC_TARGET_WWPNS[1], init_targ_map[i])
        self.assertEqual(2, len(init_targ_map[i]))

        i = FC_INITIATOR_WWPNS[1]
        self.assertIn(FC_TARGET_WWPNS[2], init_targ_map[i])
        self.assertIn(FC_TARGET_WWPNS[3], init_targ_map[i])
        self.assertEqual(2, len(init_targ_map[i]))

        self.assertEqual(2, len(init_targ_map))

    def test_build_initiator_target_map_no_lookup_service(self):
        """Successfully build a map when zoning is disabled."""
        expected_targ_wwns = FC_TARGET_WWPNS
        expected_init_targ_map = {
            CONNECTOR['wwpns'][0]: FC_TARGET_WWPNS,
            CONNECTOR['wwpns'][1]: FC_TARGET_WWPNS
        }
        self.driver.lookup_service = None

        targ_wwns, init_targ_map = self.driver._build_initiator_target_map(
            CONNECTOR)

        self.assertEqual(expected_targ_wwns, targ_wwns)
        self.assertEqual(expected_init_targ_map, init_targ_map)

    def test_is_initiator_connected_to_array(self):
        """Successfully finds an initiator with remaining active session."""
        conf = {
            'client.get_client_info.return_value': CLIENT_INFO,
        }
        self.driver.common.vmem_mg = self.setup_mock_concerto(m_conf=conf)

        self.assertTrue(self.driver._is_initiator_connected_to_array(
            CONNECTOR))
        self.driver.common.vmem_mg.client.get_client_info.assert_called_with(
            CONNECTOR['host'])

    def test_is_initiator_connected_to_array_empty_response(self):
        """Successfully finds no initiators with remaining active sessions."""
        conf = {
            'client.get_client_info.return_value': CLIENT_INFO1
        }
        self.driver.common.vmem_mg = self.setup_mock_concerto(m_conf=conf)

        self.assertFalse(self.driver._is_initiator_connected_to_array(
            CONNECTOR))


text:
'use strict';

angular.module('myApp.cities', [
	'myApp.stats',
	'myApp.city'
])
.component('cities', {
  templateUrl: 'components/cities/cities.html',
  controller: CitiesController
});

function CitiesController( StatsFactory ) {
	var $ctrl = this;

	var currentColorIndex = -1;
	var colors = ['transparent', 'wheat'];

	function init (){
		$ctrl.changeStyle();

		console.time('loadCities');

		StatsFactory.getCities()
		.then( function(data) {
			console.time('renderCities');
			$ctrl.cities = data.fitxes.v;
			console.timeEnd('loadCities');

			setTimeout(
				function(){
					console.timeEnd('renderCities');
				}
			);
		});
	}

	$ctrl.onInputChanged = function() {
		console.time('inputChange');

		setTimeout(
			function(){
				console.timeEnd('inputChange');
			}
		);
	}

	$ctrl.changeStyle = function(){
		console.time('styleChange');

		currentColorIndex = (currentColorIndex + 1) % colors.length;
		$ctrl.currentColor = colors[currentColorIndex];

		setTimeout(
			function(){
				console.timeEnd('styleChange');
			}
		);
	}

	init();
}

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe ILoveSudoku::ArrayValidator do
  include TestPuzzlesAndSolutions

  describe "#valid?" do
    context "as row validator" do
      it "returns true when valid and complete" do
        validator = ILoveSudoku::ArrayValidator.new(easy_solution)
        expect(validator.valid?).to eq true
      end

      it "returns true when valid and incomplete" do
        validator = ILoveSudoku::ArrayValidator.new(easy_puzzle)
        expect(validator.valid?).to eq true
      end

      it "returns false when invalid due to row dupe" do
        validator = ILoveSudoku::ArrayValidator.new(invalid_due_to_row_dupe_puzzle)
        expect(validator.valid?).to eq false
      end
    end

    context "as column validator with transposed input" do
      it "returns true when valid and complete" do
        validator = ILoveSudoku::ArrayValidator.new(easy_solution.transpose)
        expect(validator.valid?).to eq true
      end

      it "returns true when valid and incomplete" do
        validator = ILoveSudoku::ArrayValidator.new(easy_puzzle.transpose)
        expect(validator.valid?).to eq true
      end

      it "returns false when invalid due to column dupe" do
        validator = ILoveSudoku::ArrayValidator.new(invalid_due_to_column_dupe_puzzle.transpose)
        expect(validator.valid?).to eq false
      end
    end
  end
end


text:
package test.obv;

//
// IDL:TestNode:1.0
//
/***/

public abstract class TestNode implements org.omg.CORBA.portable.StreamableValue
{
    //
    // IDL:TestNode/left:1.0
    //
    /***/

    public TestNode left;

    //
    // IDL:TestNode/right:1.0
    //
    /***/

    public TestNode right;

    //
    // IDL:TestNode/count:1.0
    //
    /***/

    protected int count;

    //
    // IDL:TestNode/compute_count:1.0
    //
    /***/

    public abstract int
    compute_count();

    private static String[] _OB_truncatableIds_ =
    {
        TestNodeHelper.id()
    };

    public String[]
    _truncatable_ids()
    {
        return _OB_truncatableIds_;
    }

    public void
    _read(org.omg.CORBA.portable.InputStream in)
    {
        left = TestNodeHelper.read(in);
        right = TestNodeHelper.read(in);
        count = in.read_ulong();
    }

    public void
    _write(org.omg.CORBA.portable.OutputStream out)
    {
        TestNodeHelper.write(out, left);
        TestNodeHelper.write(out, right);
        out.write_ulong(count);
    }

    public org.omg.CORBA.TypeCode
    _type()
    {
        return TestNodeHelper.type();
    }
}


text:
.. _hello_world:

Hello World
===========

The first thing we'll do today is explore Twilio's REST API calls. Soon, you'll
see how SMS and phone calls can be originated from your web browser with Twilio.

Twilio Account Portal
---------------------

When you log into your Twilio Account, the first page you come across is
your Account Dashboard. This is where your Account Sid and Auth Token are
displayed.

.. image:: _static/bar.png
	:class: screenshot

These are your account credentials. The Account Sid acts as a username and the
Auth Token acts as a password. Twilio uses your Account Sid and Auth Token to
authenticate the API requests made by your application.

Analytics about your Voice and SMS application are also shown here. We'll go
over these after we've made some calls and sent some SMS messages.

At the bottom of your Account Dashboard is the API Explorer and the Debugger.

Twilio API Explorer
-------------------

The `API Explorer`_ is a helpful application built into the Account Dashboard
that allows you to easily try out Twilio's API without getting into the details
of scripting and :ref:`HTTP <http>` calls.

You can get to the `API Explorer`_ from the bottom of your Account Dashboard.
You may also click on the `Dev Tools
<https://www.twilio.com/user/account/developer-tools/api-explorer>`_  tab to
access the API Explorer.

.. image:: _static/api_explorer.png
	:class: screenshot

Getting Account Information
^^^^^^^^^^^^^^^^^^^^^^^^^^^

Let's start of with a basic request for your account information. Go to your
Twilio Account Portal, click on `Dev Tools`, then click on `Accounts` (on the
right near the bottom), then click on `View Account`.

.. image:: _static/explore-account.png
	:class: screenshot

You can see there are a couple of pre-filled fields that make up the request
parameters:

============ ==========
Parameter    Definition
============ ==========
`Format`     The `Format` field tells the API in what format we want the API to respond with. For our purposes right now this doesn't matter, but you can request the response in either `XML`_ or `JSON`_ format.
`AccountSid` The `AccountSid` field tells the API which Account we want to use to send the SMS. This is pre-populated with your account.
============ ==========

Go ahead and click on the `Make Request` button. A response with your Account
information should appear at the end of the page.

**Ok, so what did we just do?**

Let's take a look at the key parts of the request we just made:

.. code-block:: bash

	GET /2010-04-01/Accounts/AC000.xml

- **GET**: this is the type of request to make, a ``GET`` request, meaning that the intent of this call is to retrieve information from the server.
- **/2010-04-01/Accounts/AC000.xml**: this is the endpoint for retrieving Account data from the Twilio API. Lets break it down further:
	- **/2010-04-01/** is the version of the API that we want to request. The version of the API we want to talk to is important because we want to make sure that the way we talk to the API doesn't change. If Twilio makes a major change to how to talk to the API the version will change, but the old version will continue to work the same way so that your application doesn't break.
	- **Accounts/AC000.xml** means that we want to retrieve an Account resource for the account "AC000" and that we want the response in XML format.

Now lets look at the response. The server responded with an XML formatted
representation of your account information including, but not limited to, your
AccountSid, Account Name, Auth Token, and Resource URIs for the resources
available to your account.

Sending an SMS
^^^^^^^^^^^^^^

Let's send a text message using the `API Explorer`_. Go to your Twilio `Account
Portal`_, click on `Dev Tools`, then click on `SMS Messages`, then on `Send
SMS`.

.. image:: _static/explore-sms.png
	:class: screenshot

Here we can try out the Twilio API for sending SMS Messages. All the fields
required to send an SMS are visible. This request will add 2 new parameters:

============ ==========
Parameter    Definition
============ ==========
`From`       The `From` field tells the API which phone number to use to send the Message. This can only be one of the phone numbers you've purchased or ported into Twilio.
`To`         The `To` field tells the API where to send the message. The phone number should be in `E.164`_ format. Twilio will assume that `To` phone numbers without a "+" will have the same country code as the `From` phone number.
`Body`       The body is a freeform field to enter your message. You can enter a message up to 160 characters long.
============ ==========

Enter your cell phone number in the `To` field along with a text message
`Body`, and click the `Make Request` button at the bottom of the page. This
will send the information you've just entered to the Twilio API. You will be
prompted to confirm the use of funds from your account. Aren't you glad you got
the Promo credit?

Twilio will process the information you have submitted and your phone will
receive a text message shortly.

**So how was that different from our Accounts information request?**

Lets take a look at the key parts of this request:

.. code-block:: bash

	POST /2010-04-01/Accounts/AC000/SMS/Messages.xml

There are a few key differences to note:

- **POST** this time we're making a ``POST`` request, meaning that the purpose
  of this request is to pass data in to the API for the purposes of modifying
  the ``SMS Messages`` resource.

- **Parameters**: if you look at the `Code Example` right above the `Make
  Request` button you see **-d 'From=xxx'*** et al... these tell cURL what data
  to pass to the API. You can see each entry you modified in the form is
  represented here. You'll also notice that each entry contains special
  characters (ie: ``%2B`` instead of ``+``). This is called `Url Encoding`_ and
  is required to make sure that special characters are properly transmitted to
  the API.

Now lets examine the response. You'll see that the message was given a `Sid`, a
unique identifier, how Twilio interpreted the information you sent, and you can
see that it was queued for delivery.

Click on the Message Sid and you'll be taken to another page where we can get
information about the message.

Now click on `Make Request` to see the current status of the message. You can
see, among other information, that the message was sent and how much it cost to
send.

Making a Phone Call
^^^^^^^^^^^^^^^^^^^

Now let's make a phone call using the `API Explorer`_. Click on the Calls link
on the left hand sidebar, then on the sublink `"Make call"
<https://www.twilio.com/user/account/developer-tools/api-explorer#POST/2010-04-01/Accounts/[AccountSid]/Calls.[format]>`_.

.. image:: _static/explore-call.png
	:class: screenshot

The request parameters should look familiar by now. This request replaces the
`Body` field with a `Url` field:

============ ==========
Parameter    Definition
============ ==========
`Url`        The `Url` field tells the API where to load TwiML instructions for handling the call. `TwiML`_ is a set of instructions that tells Twilio what to do. Don't worry, we'll get more into TwiML later.
============ ==========

Enter your cell phone number in the `To` field. To make things easy, we're
going to use a `Twimlet`_ for the `Url`. We'll get into the details of building
TwiML later on. For now, copy the URL below into the `Url` field.

.. code-block:: bash

	http://twimlets.com/message?Message=Hello+World

Click on the `Make Request` button at the bottom of the page. Again, the
information you've submitted is sent off to Twilio and your phone should start
ringing momentarily.

**How was that different from our SMS request?**

In this request we replaced the `Body` parameter with a `Url` parameter. The
URL is required to be an endpoint that returns TwiML. This TwiML will tell
Twilio how to handle the phone call.

If you load the URL we supplied directly in to a web browser you can see the
TwiML that was used to handle the phone call. Don't worry about understanding
it right now, we'll get in to that in the next section.

If you examine the API response you'll notice it looks much like the response
we got from sending the SMS, but with a few different values. Click on the
`Sid` in the response to be taken to a page where we can request call details.

Click on `Make Request` to see the details on the completed call.

**Have any questions? Ask your TA!**

Additional Information
----------------------
- `TwiML: the Twilio Markup Language <http://www.twilio.com/docs/api/twiml>`_
- `Twilio REST API - Calls Resource <http://www.twilio.com/docs/api/rest/call>`_
- `Twilio REST API - SMS/Messages Resource <http://www.twilio.com/docs/api/rest/sms>`_

.. _API Explorer: https://www.twilio.com/user/account/developer-tools/api-explorer
.. _Account Portal: https://www.twilio.com/user/account
.. _XML: http://en.wikipedia.org/wiki/XML
.. _JSON: http://en.wikipedia.org/wiki/JSON
.. _E.164: http://en.wikipedia.org/wiki/E.164
.. _TwiML: http://www.twilio.com/docs/api/twiml
.. _Twimlet: https://www.twilio.com/labs/twimlets
.. _Url Encoding: http://en.wikipedia.org/wiki/Percent-encoding


text:
package org.wso2.carbon.identity.recovery.endpoint.Utils;

import org.testng.annotations.Test;
import org.wso2.carbon.identity.captcha.util.CaptchaConstants;
import org.wso2.carbon.identity.recovery.IdentityRecoveryException;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;

import static org.testng.Assert.assertEquals;

/**
 * Unit tests for RecoveryUtils.java
 */
public class RecoveryUtilsTest {

    @Test(description = "To test the getValidatedCaptchaConfigs method.")
    public void testGetValidatedCaptchaConfigs() throws IdentityRecoveryException {

        Path path = Paths.get("src/test/resources", "repository", "conf", "identity",
                CaptchaConstants.CAPTCHA_CONFIG_FILE_NAME);
        Properties sampleProperties = new Properties();

        if (Files.exists(path)) {
            try (Reader in = new InputStreamReader(Files.newInputStream(path), StandardCharsets.UTF_8)) {
                sampleProperties.load(in);
            } catch (IOException e) {
                throw new IdentityRecoveryException("Unable to read captcha config file.", e);
            }
        }

        System.setProperty("carbon.home", "src/test/resources");
        Properties properties = RecoveryUtil.getValidatedCaptchaConfigs();
        assertEquals(properties, sampleProperties);
        assertEquals(properties.size(), sampleProperties.size());
    }
}


text:
import numpy as np
import tricubic

n = 3
f = np.zeros((n,n,n), dtype='float')

for i in range(n):
  for j in range(n):
    for k in range(n):
      f[i][j][k] = i+j+k #some function f(x,y,z) is given on a cubic grid indexed by i,j,k

ip = tricubic.tricubic(list(f), [n,n,n]) #initialize interpolator with input data on cubic grid
for i in range(100000):
  res = ip.ip(list(np.random.rand(3)*(n-1))) #interpolate the function f at a random point in space
  #print res


text:
using System;
using System.Net.Sockets;
using System.Collections.Generic;
using System.Linq;

namespace FastCgiNet.Streams
{
    public class SocketStream : FastCgiStream, IDisposable
    {
        private Socket Socket;

        /// <summary>
        /// Before flushing or closing this stream, make sure you set a proper RequestId through this field.
        /// </summary>
        public ushort RequestId;

        public readonly RecordType RecordType;

        private RecordContentsStream LastFlushedStream;

        private void Send(RecordBase rec)
        {
            foreach (var seg in rec.GetBytes())
                Socket.Send(seg.Array, seg.Offset, seg.Count, SocketFlags.None);
        }

        /// <summary>
        /// Sends all written data that has not been sent over the socket. If nothing has been written to the stream
        /// or everything has already been flushed, this method does not throw and does not send anything through the socket.
        /// If this stream is in read mode or has been closed or disposed, this method throws.
        /// </summary>
        public override void Flush()
        {
            if (IsDisposed)
                throw new ObjectDisposedException("SocketStream");
            if (IsReadMode)
                throw new InvalidOperationException("Can't flush a SocketStream that is in Read Mode");

            IEnumerator<RecordContentsStream> it = UnderlyingStreams.GetEnumerator();
            try
            {
                // Move until the last flushed stream
                if (LastFlushedStream != null)
                {
                    while (it.MoveNext())
                    {
                        if (it.Current == LastFlushedStream)
                            break;
                    }
                }

                // Now flush the ones that haven't been flushed for real!
                while (it.MoveNext())
                {
                    // We have to make sure that the current stream is not empty,
                    // because that would mean us sending an empty record here, when it should only happen in Close()
                    if (it.Current.Length == 0)
                        continue;

                    using (var record = (StreamRecordBase)RecordFactory.CreateRecord(RequestId, RecordType))
                    {
                        record.Contents = it.Current;
                        Send(record);
                    }
                }
            }
            catch
            {
                it.Dispose();
                throw;
            }

            // Internal bookkeeping
            LastFlushedStream = LastUnfilledStream;
            var newLastStream = new RecordContentsStream();
            underlyingStreams.AddLast(newLastStream);
            LastUnfilledStream = newLastStream;
        }

        /// <summary>
        /// Flushes this stream (<see cref="Flush()"/>) and disposes it. If no data has been flushed, this method does nothing else. If some data was flushed,
        /// then this method flushes the remaining data and also sends an empty record through the socket, meaning end of stream to the other communicating party.
        /// If the stream is in read mode, this method does nothing.
        /// If this stream has already been disposed, this method does nothing, but does not throw either.
        /// This method never closes the underlying socket.
        /// </summary>
        public override void Close()
        {
            if (IsDisposed)
                return;

            // If this stream is empty, don't bother wasting network resources with an empty record
            // Or if this is in Read Mode, then we just don't send anything at all!
            if (Length == 0 || IsReadMode)
            {
                IsDisposed = true;
                return;
            }

            // Flush and send an empty record!
            this.Flush();
            using (var emptyRecord = (StreamRecordBase)RecordFactory.CreateRecord(RequestId, RecordType))
            {
                Send(emptyRecord);
            }
            IsDisposed = true;
        }

        private bool IsDisposed;
        protected override void Dispose(bool disposing)
        {
            if (IsDisposed)
                return;

            this.Close();
        }

        public SocketStream(Socket sock, RecordType streamType, bool readMode)
            : base(readMode)
        {
            if (sock == null)
                throw new ArgumentNullException("sock");
            else if (!streamType.IsStreamType())
                throw new ArgumentException("streamType must be a stream record type");

            Socket = sock;
            RecordType = streamType;
            IsDisposed = false;
            LastFlushedStream = null;
        }
    }
}


text:
========================
How to create a product
========================

Creating a product in django SHOP is really easy, but requires you to write
python code.

Create a model
===============
The first step for you is to create a model to use as a product. We will create
an example Book model together::

	from shop.models.productmodel import Product
	from django.db import models

	class Book(Product):
		isbn = models.CharField(max_length=255)

The following fields are already defined in the Product superclass:

* name : The name/title of the product
* slug : The slug used to refer to this product in the URLs
* short_description : a short description of the product
* long_description : A longer, more in-depth description of the product
* active : Products flagged as not active will not show in the lists
* date_added : The date at which the product was first created
* last_modified : A timestamp of when the product was last modified
* unit_price : The base price for one item
* category : An optional category for the product

Create a template
==================

Like other objects in Django, you will need to create a template to display
your model's contents to the world.
By default, your Product subclass will use the "shop/product_detail.html"
template as a fallback, but will use your own template if you follow Django's
naming conventions: "appname/book_detail.html".

That's all there is to it :)

Using your newly created Product
=================================

Your product should behave like a normal Django model in all circumstances. You
should register it to admin (and create an admin class for it) like a normal
model.

Code wise, the following options are possible to retrieve your newly
created model::

    # This gets your model's instance the normal way, you get both your model's
    # fields and the Product fields
    o = MyProduct.objects.get(pk=...)

    # This is also possible - You retrieve a Product instance, with only the
    # fields defined in Product... but fear not! There is a way to get yours :)
    o = Product.objects.get(pk=...) # This gets a Product instance
    o = o.get_specific() # There, this is now an instance of MyProduct. Magic!

    # The opposite is of course possible as well:
    o = MyProduct.objects.get(pk=...) # a MyModel instance
    o = o.product # A Product instance
    o = o.get_specific() # Back to a MyModel instance

.. note:: This is possible thanks to using a Python __metaclass__, so the magic
          making it possible should be completely transparent to your Model.

Product variations
====================

By design, django SHOP does not include an out of the box solution to handling
product variations (colors, sizes...), in order to let implementors create their
own unrestricted.

If you want such a pre-made solution for simple cases, we suggest you take a
look at the `shop_simplevariations` "add-on" application, located at:

  https://github.com/chrisglass/django-shop-simplevariations


text:
package android.support.v4.view;

import android.os.Bundle;
import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
import android.support.v4.view.accessibility.AccessibilityNodeProviderCompat;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityEvent;

// Referenced classes of package android.support.v4.view:
//            AccessibilityDelegateCompat

class val.compat
    implements ellyBean
{

    final val.compat this$0;
    final AccessibilityDelegateCompat val$compat;

    public boolean dispatchPopulateAccessibilityEvent(View view, AccessibilityEvent accessibilityevent)
    {
        return val$compat.dispatchPopulateAccessibilityEvent(view, accessibilityevent);
    }

    public Object getAccessibilityNodeProvider(View view)
    {
        AccessibilityNodeProviderCompat accessibilitynodeprovidercompat = val$compat.getAccessibilityNodeProvider(view);
        if (accessibilitynodeprovidercompat != null)
        {
            return accessibilitynodeprovidercompat.getProvider();
        } else
        {
            return null;
        }
    }

    public void onInitializeAccessibilityEvent(View view, AccessibilityEvent accessibilityevent)
    {
        val$compat.onInitializeAccessibilityEvent(view, accessibilityevent);
    }

    public void onInitializeAccessibilityNodeInfo(View view, Object obj)
    {
        val$compat.onInitializeAccessibilityNodeInfo(view, new AccessibilityNodeInfoCompat(obj));
    }

    public void onPopulateAccessibilityEvent(View view, AccessibilityEvent accessibilityevent)
    {
        val$compat.onPopulateAccessibilityEvent(view, accessibilityevent);
    }

    public boolean onRequestSendAccessibilityEvent(ViewGroup viewgroup, View view, AccessibilityEvent accessibilityevent)
    {
        return val$compat.onRequestSendAccessibilityEvent(viewgroup, view, accessibilityevent);
    }

    public boolean performAccessibilityAction(View view, int i, Bundle bundle)
    {
        return val$compat.performAccessibilityAction(view, i, bundle);
    }

    public void sendAccessibilityEvent(View view, int i)
    {
        val$compat.sendAccessibilityEvent(view, i);
    }

    public void sendAccessibilityEventUnchecked(View view, AccessibilityEvent accessibilityevent)
    {
        val$compat.sendAccessibilityEventUnchecked(view, accessibilityevent);
    }

    ellyBean()
    {
        this$0 = final_ellybean;
        val$compat = AccessibilityDelegateCompat.this;
        super();
    }
}


text:
#include <errno.h>
#include <limits.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>

#include "cbfstool.h"
#include "file_type_bios.h"
#include "file_type.h"
#include "fmap.h"
#include "futility.h"
#include "futility_options.h"
#include "host_common.h"
#include "vb1_helper.h"

static void fmap_limit_area(FmapAreaHeader *ah, uint32_t len)
{
	uint32_t sum = ah->area_offset + ah->area_size;
	if (sum < ah->area_size || sum > len) {
		VB2_DEBUG("%.*s %#x + %#x > %#x\n", FMAP_NAMELEN,
			  ah->area_name, ah->area_offset, ah->area_size, len);
		ah->area_offset = 0;
		ah->area_size = 0;
	}
}

/** Show functions **/

static int show_gbb_buf(const char *name, uint8_t *buf, uint32_t len,
			void *data)
{
	struct vb2_gbb_header *gbb = (struct vb2_gbb_header *)buf;
	struct bios_state_s *state = (struct bios_state_s *)data;
	int retval = 0;
	uint32_t maxlen = 0;

	if (!len) {
		printf("GBB header:              %s <invalid>\n", name);
		return 1;
	}

	/* It looks like a GBB or we wouldn't be called. */
	if (!futil_valid_gbb_header(gbb, len, &maxlen))
		retval = 1;

	printf("GBB header:              %s\n", name);
	printf("  Version:               %d.%d\n",
	       gbb->major_version, gbb->minor_version);
	printf("  Flags:                 0x%08x\n", gbb->flags);
	printf("  Regions:                 offset       size\n");
	printf("    hwid                 0x%08x   0x%08x\n",
	       gbb->hwid_offset, gbb->hwid_size);
	printf("    bmpvf                0x%08x   0x%08x\n",
	       gbb->bmpfv_offset, gbb->bmpfv_size);
	printf("    rootkey              0x%08x   0x%08x\n",
	       gbb->rootkey_offset, gbb->rootkey_size);
	printf("    recovery_key         0x%08x   0x%08x\n",
	       gbb->recovery_key_offset, gbb->recovery_key_size);

	printf("  Size:                  0x%08x / 0x%08x%s\n",
	       maxlen, len, maxlen > len ? "  (not enough)" : "");

	if (retval) {
		printf("GBB header is invalid, ignoring content\n");
		return retval;
	}

	printf("GBB content:\n");
	printf("  HWID:                  %s\n", buf + gbb->hwid_offset);
	print_hwid_digest(gbb, "     digest:             ", "\n");

	struct vb2_packed_key *pubkey =
		(struct vb2_packed_key *)(buf + gbb->rootkey_offset);
	if (vb2_packed_key_looks_ok(pubkey, gbb->rootkey_size) == VB2_SUCCESS) {
		if (state) {
			state->rootkey.offset =
				state->area[BIOS_FMAP_GBB].offset +
				gbb->rootkey_offset;
			state->rootkey.buf = buf + gbb->rootkey_offset;
			state->rootkey.len = gbb->rootkey_size;
			state->rootkey.is_valid = 1;
		}
		printf("  Root Key:\n");
		show_pubkey(pubkey, "    ");
	} else {
		retval = 1;
		printf("  Root Key:              <invalid>\n");
	}

	pubkey = (struct vb2_packed_key *)(buf + gbb->recovery_key_offset);
	if (vb2_packed_key_looks_ok(pubkey, gbb->recovery_key_size)
	    == VB2_SUCCESS) {
		if (state) {
			state->recovery_key.offset =
				state->area[BIOS_FMAP_GBB].offset +
				gbb->recovery_key_offset;
			state->recovery_key.buf = buf +
				gbb->recovery_key_offset;
			state->recovery_key.len = gbb->recovery_key_size;
			state->recovery_key.is_valid = 1;
		}
		printf("  Recovery Key:\n");
		show_pubkey(pubkey, "    ");
	} else {
		retval = 1;
		printf("  Recovery Key:          <invalid>\n");
	}

	if (!retval && state)
		state->area[BIOS_FMAP_GBB].is_valid = 1;

	return retval;
}

int ft_show_gbb(const char *name, void *data)
{
	int retval = 0;
	int fd = -1;
	uint8_t *buf;
	uint32_t len;

	retval = futil_open_and_map_file(name, &fd, FILE_RO, &buf, &len);
	if (retval)
		return 1;

	retval = show_gbb_buf(name, buf, len, data);

	futil_unmap_and_close_file(fd, FILE_RO, buf, len);
	return retval;
}

/*
 * This handles FW_MAIN_A and FW_MAIN_B while processing a BIOS image.
 *
 * The data is just the RW firmware blob, so there's nothing useful to show
 * about it. We'll just mark it as present so when we encounter corresponding
 * VBLOCK area, we'll have this to verify.
 */
static int fmap_show_fw_main(const char *name, uint8_t *buf, uint32_t len,
			     void *data)
{
	struct bios_state_s *state = (struct bios_state_s *)data;

	if (!len) {
		printf("Firmware body:           %s <invalid>\n", name);
		return 1;
	}

	printf("Firmware body:           %s\n", name);
	printf("  Offset:                0x%08x\n",
	       state->area[state->c].offset);
	printf("  Size:                  0x%08x\n", len);

	state->area[state->c].is_valid = 1;

	return 0;
}

/* Functions to call to show the bios components */
static int (*fmap_show_fn[])(const char *name, uint8_t *buf, uint32_t len,
			       void *data) = {
	show_gbb_buf,
	fmap_show_fw_main,
	fmap_show_fw_main,
	show_fw_preamble_buf,
	show_fw_preamble_buf,
};
_Static_assert(ARRAY_SIZE(fmap_show_fn) == NUM_BIOS_COMPONENTS,
	       "Size of fmap_show_fn[] should match NUM_BIOS_COMPONENTS");

int ft_show_bios(const char *name, void *data)
{
	FmapHeader *fmap;
	FmapAreaHeader *ah = 0;
	char ah_name[FMAP_NAMELEN + 1];
	enum bios_component c;
	int retval = 0;
	struct bios_state_s state;
	int fd = -1;
	uint8_t *buf;
	uint32_t len;

	retval = futil_open_and_map_file(name, &fd, FILE_RO, &buf, &len);
	if (retval)
		return 1;

	memset(&state, 0, sizeof(state));

	printf("BIOS:                    %s\n", name);

	/* We've already checked, so we know this will work. */
	fmap = fmap_find(buf, len);
	for (c = 0; c < NUM_BIOS_COMPONENTS; c++) {
		/* We know one of these will work, too */
		if (fmap_find_by_name(buf, len, fmap, fmap_name[c], &ah)) {
			/* But the file might be truncated */
			fmap_limit_area(ah, len);
			/* The name is not necessarily null-terminated */
			snprintf(ah_name, sizeof(ah_name), "%s", ah->area_name);

			/* Update the state we're passing around */
			state.c = c;
			state.area[c].offset = ah->area_offset;
			state.area[c].buf = buf + ah->area_offset;
			state.area[c].len = ah->area_size;

			VB2_DEBUG("showing FMAP area %d (%s),"
				  " offset=0x%08x len=0x%08x\n",
				  c, ah_name, ah->area_offset, ah->area_size);

			/* Go look at it. */
			if (fmap_show_fn[c])
				retval += fmap_show_fn[c](ah_name,
							  state.area[c].buf,
							  state.area[c].len,
							  &state);
		}
	}

	futil_unmap_and_close_file(fd, FILE_RO, buf, len);
	return retval;
}

/** Sign functions **/

static int write_new_preamble(struct bios_area_s *vblock,
			      struct bios_area_s *fw_body,
			      struct vb2_private_key *signkey,
			      struct vb2_keyblock *keyblock)
{
	struct vb2_signature *body_sig = NULL;
	struct vb2_fw_preamble *preamble = NULL;
	int retval = 1;

	if (fw_body->metadata_hash.algo != VB2_HASH_INVALID)
		body_sig =
			vb2_create_signature_from_hash(&fw_body->metadata_hash);
	else
		body_sig = vb2_calculate_signature(fw_body->buf, fw_body->len,
						   signkey);

	if (!body_sig) {
		ERROR("Error calculating or creating body signature\n");
		goto end;
	}

	preamble = vb2_create_fw_preamble(vblock->version,
			(struct vb2_packed_key *)sign_option.kernel_subkey,
			body_sig,
			signkey,
			vblock->flags);
	if (!preamble) {
		ERROR("Error creating firmware preamble.\n");
		goto end;
	}

	if (keyblock->keyblock_size + preamble->preamble_size > vblock->len) {
		ERROR("Keyblock and preamble do not fit in VBLOCK.\n");
		goto end;
	}

	/* Write the new keyblock */
	uint32_t more = keyblock->keyblock_size;
	memcpy(vblock->buf, keyblock, more);
	/* and the new preamble */
	memcpy(vblock->buf + more, preamble, preamble->preamble_size);
	retval = 0;

end:
	free(preamble);
	free(body_sig);

	return retval;
}

static int write_loem(const char *ab, struct bios_area_s *vblock)
{
	char filename[PATH_MAX];
	int n;
	n = snprintf(filename, sizeof(filename), "%s/vblock_%s.%s",
		     sign_option.loemdir ? sign_option.loemdir : ".",
		     ab, sign_option.loemid);
	if (n >= sizeof(filename)) {
		fprintf(stderr, "LOEM args produce bogus filename\n");
		return 1;
	}

	FILE *fp = fopen(filename, "w");
	if (!fp) {
		fprintf(stderr, "Can't open %s for writing: %s\n",
			filename, strerror(errno));
		return 1;
	}

	if (1 != fwrite(vblock->buf, vblock->len, 1, fp)) {
		fprintf(stderr, "Can't write to %s: %s\n",
			filename, strerror(errno));
		fclose(fp);
		return 1;
	}
	if (fclose(fp)) {
		fprintf(stderr, "Failed closing loem output: %s\n",
			strerror(errno));
		return 1;
	}

	return 0;
}

/* This signs a full BIOS image after it's been traversed. */
static int sign_bios_at_end(struct bios_state_s *state)
{
	struct bios_area_s *vblock_a = &state->area[BIOS_FMAP_VBLOCK_A];
	struct bios_area_s *vblock_b = &state->area[BIOS_FMAP_VBLOCK_B];
	struct bios_area_s *fw_a = &state->area[BIOS_FMAP_FW_MAIN_A];
	struct bios_area_s *fw_b = &state->area[BIOS_FMAP_FW_MAIN_B];
	int retval = 0;

	if (!vblock_a->is_valid || !fw_a->is_valid) {
		fprintf(stderr, "Something's wrong. Not changing anything\n");
		return 1;
	}

	retval |= write_new_preamble(vblock_a, fw_a, sign_option.signprivate,
				     sign_option.keyblock);

	if (vblock_b->is_valid && fw_b->is_valid)
		retval |= write_new_preamble(vblock_b, fw_b,
					     sign_option.signprivate,
					     sign_option.keyblock);
	else
		INFO("BIOS image does not have %s. Signing only %s\n",
		     fmap_name[BIOS_FMAP_FW_MAIN_B],
		     fmap_name[BIOS_FMAP_FW_MAIN_A]);

	if (sign_option.loemid) {
		retval |= write_loem("A", vblock_a);
		if (vblock_b->is_valid)
			retval |= write_loem("B", vblock_b);
	}

	return retval;
}

/* Prepare firmware slot for signing.
   If fw_size is not zero, then it will be used as new length of signed area,
   for zero the length will be taken form FlashMap or preamble. */
static int prepare_slot(uint8_t *buf, uint32_t len, enum bios_component fw_c,
			enum bios_component vblock_c,
			struct bios_state_s *state)
{
	FmapHeader *fmap;
	FmapAreaHeader *ah;
	const char *fw_main_name = fmap_name[fw_c];
	const char *vblock_name = fmap_name[vblock_c];
	static uint8_t workbuf[VB2_FIRMWARE_WORKBUF_RECOMMENDED_SIZE]
		__attribute__((aligned(VB2_WORKBUF_ALIGN)));
	static struct vb2_workbuf wb;

	fmap = fmap_find(buf, len);
	vb2_workbuf_init(&wb, workbuf, sizeof(workbuf));

	VB2_DEBUG("Preparing areas: %s and %s\n", fw_main_name, vblock_name);

	/* FW_MAIN */
	if (!fmap_find_by_name(buf, len, fmap, fw_main_name, &ah)) {
		ERROR("%s area not found in FMAP\n", fw_main_name);
		return 1;
	}
	fmap_limit_area(ah, len);
	state->area[fw_c].buf = buf + ah->area_offset;
	state->area[fw_c].is_valid = 1;
	if (state->area[fw_c].fw_size > ah->area_size) {
		ERROR("%s size is incorrect.\n", fmap_name[fw_c]);
		return 1;
	} else if (state->area[fw_c].fw_size) {
		state->area[fw_c].len = state->area[fw_c].fw_size;
	} else {
		if (state->area[fw_c].metadata_hash.algo == VB2_HASH_INVALID)
			WARN("%s does not contain CBFS. Trying to sign entire "
			     "area.\n",
			     fmap_name[fw_c]);
		state->area[fw_c].len = ah->area_size;
	}

	/* Corresponding VBLOCK */
	if (!fmap_find_by_name(buf, len, fmap, vblock_name, &ah)) {
		ERROR("%s area not found in FMAP\n", vblock_name);
		return 1;
	}
	fmap_limit_area(ah, len);
	state->area[vblock_c].buf = buf + ah->area_offset;
	state->area[vblock_c].len = ah->area_size;

	struct vb2_keyblock *keyblock =
		(struct vb2_keyblock *)state->area[vblock_c].buf;
	int keyblock_valid = 0;

	if (vb2_verify_keyblock_hash(keyblock, state->area[vblock_c].len,
				     &wb) != VB2_SUCCESS) {
		WARN("%s keyblock is invalid.\n", vblock_name);
		goto end;
	}

	if (vb2_packed_key_looks_ok(&keyblock->data_key,
				    keyblock->data_key.key_offset +
					    keyblock->data_key.key_size)) {
		WARN("%s public key is invalid.\n", vblock_name);
		goto end;
	}

	struct vb2_public_key data_key;
	if (vb2_unpack_key(&data_key, &keyblock->data_key) != VB2_SUCCESS) {
		WARN("%s data key is invalid. Failed to parse.\n", vblock_name);
		goto end;
	}

	if (keyblock->keyblock_size + sizeof(struct vb2_fw_preamble) >
	    state->area[vblock_c].len) {
		ERROR("%s is invalid. Keyblock and preamble do not fit.\n",
		      vblock_name);
		goto end;
	}

	struct vb2_fw_preamble *preamble =
		(struct vb2_fw_preamble *)(state->area[vblock_c].buf +
					   keyblock->keyblock_size);
	if (vb2_verify_fw_preamble(preamble,
				   state->area[vblock_c].len -
					   keyblock->keyblock_size,
				   &data_key, &wb)) {
		WARN("%s preamble is invalid.\n", vblock_name);
		goto end;
	}

	if (state->area[fw_c].fw_size == 0) {
		if (preamble->body_signature.data_size >
		    state->area[fw_c].len) {
			ERROR("%s says the firmware is larger than we have.\n",
			      vblock_name);
			goto end;
		} else {
			state->area[fw_c].len =
				preamble->body_signature.data_size;
		}
	}

	keyblock_valid = 1;

end:
	if (sign_option.flags_specified)
		state->area[vblock_c].flags = sign_option.flags;
	else if (keyblock_valid)
		state->area[vblock_c].flags = preamble->flags;
	else
		state->area[vblock_c].flags = 0;

	if (sign_option.version_specified)
		state->area[vblock_c].version = sign_option.version;
	else if (keyblock_valid)
		state->area[vblock_c].version = preamble->firmware_version;
	else
		state->area[vblock_c].version = 1;

	state->area[vblock_c].is_valid = 1;

	return 0;
}

static bool image_uses_cbfs_integration(const char *file)
{
	char *value;
	bool rv = false;

	if (cbfstool_get_config_value(file, NULL,
				      "CONFIG_VBOOT_CBFS_INTEGRATION",
				      &value) != VB2_SUCCESS)
		return false;

	if (value && strcmp("y", value) == 0)
		rv = true;

	free(value);
	return rv;
}

static void image_check_and_prepare_cbfs(const char *file,
					 enum bios_component fw_c,
					 bool uses_cbfs_integration,
					 struct bios_state_s *state)
{
	if (!uses_cbfs_integration) {
		if (cbfstool_truncate(file, fmap_name[fw_c],
				      &state->area[fw_c].fw_size) !=
		    VB2_SUCCESS) {
			VB2_DEBUG("CBFS not found in area %s\n",
				  fmap_name[fw_c]);
			return;
		}
		VB2_DEBUG("CBFS found in area %s\n", fmap_name[fw_c]);
		return;
	}

	if (cbfstool_get_metadata_hash(file, fmap_name[fw_c],
				       &state->area[fw_c].metadata_hash) !=
	    VB2_SUCCESS)
		FATAL("CBFS metadata hash not found in area"
		      " %s. It is required for images with"
		      " VBOOT_CBFS_INTEGRATION",
		      fmap_name[fw_c]);

	VB2_DEBUG("CBFS metadata hash found in area %s\n", fmap_name[fw_c]);
}

static void check_slot_after_prepare(enum bios_component fw_c,
				     bool uses_cbfs_integration,
				     struct bios_state_s *state)
{
	if (state->area[fw_c].is_valid && uses_cbfs_integration &&
	    state->area[fw_c].metadata_hash.algo == VB2_HASH_INVALID)
		FATAL("CBFS with metadata hash not found in area %s."
		      " It is required for images with"
		      " VBOOT_CBFS_INTEGRATION",
		      fmap_name[fw_c]);
}

int ft_sign_bios(const char *name, void *data)
{
	int retval = 0;
	struct bios_state_s state;
	int fd = -1;
	uint8_t *buf = NULL;
	uint32_t len = 0;
	bool uses_cbfs_integration =
		image_uses_cbfs_integration(name);

	memset(&state, 0, sizeof(state));

	image_check_and_prepare_cbfs(name, BIOS_FMAP_FW_MAIN_A,
				     uses_cbfs_integration, &state);
	image_check_and_prepare_cbfs(name, BIOS_FMAP_FW_MAIN_B,
				     uses_cbfs_integration, &state);

	if (futil_open_and_map_file(name, &fd, FILE_MODE_SIGN(sign_option),
				    &buf, &len))
		return 1;

	retval = prepare_slot(buf, len, BIOS_FMAP_FW_MAIN_A, BIOS_FMAP_VBLOCK_A,
			      &state);
	if (retval)
		goto done;

	retval = prepare_slot(buf, len, BIOS_FMAP_FW_MAIN_B, BIOS_FMAP_VBLOCK_B,
			      &state);
	if (retval && state.area[BIOS_FMAP_FW_MAIN_B].is_valid)
		goto done;

	check_slot_after_prepare(BIOS_FMAP_FW_MAIN_A, uses_cbfs_integration,
				 &state);
	check_slot_after_prepare(BIOS_FMAP_FW_MAIN_B, uses_cbfs_integration,
				 &state);

	retval = sign_bios_at_end(&state);
done:
	futil_unmap_and_close_file(fd, FILE_MODE_SIGN(sign_option), buf, len);
	return retval;
}

enum futil_file_type ft_recognize_bios_image(uint8_t *buf, uint32_t len)
{
	FmapHeader *fmap;

	fmap = fmap_find(buf, len);
	if (!fmap)
		return FILE_TYPE_UNKNOWN;

	/* Correct BIOS image should contain at least GBB, FW_MAIN_A and
	   VBLOCK_A areas. FW_MAIN_B and VBLOCK_B are optional, but will be
	   signed or shown if present. */
	const int gbb_and_a_slot_ok =
		fmap_find_by_name(buf, len, fmap, fmap_name[BIOS_FMAP_GBB],
				  0) != NULL &&
		fmap_find_by_name(buf, len, fmap,
				  fmap_name[BIOS_FMAP_FW_MAIN_A], 0) != NULL &&
		fmap_find_by_name(buf, len, fmap, fmap_name[BIOS_FMAP_VBLOCK_A],
				  0) != NULL;

	if (gbb_and_a_slot_ok)
		return FILE_TYPE_BIOS_IMAGE;

	return FILE_TYPE_UNKNOWN;
}


text:
package com.fkeglevich.rawdumper.su;

import com.topjohnwu.superuser.Shell;

/**
 * TODO: add header comment
 * Created by Flávio Keglevich on 01/05/18.
 */
class ShellCreationThread extends Thread
{
    private Shell shell = null;

    ShellCreationThread()
    {
        super();
    }

    @Override
    public void run()
    {
        shell = Shell.newInstance();
    }

    public Shell getShell()
    {
        try
        {
            join();
        }
        catch (InterruptedException ignored)
        {   }
        return shell;
    }
}


text:
import * as widgets from '@jupyter-widgets/base';
import * as Backbone from 'backbone';

import { ManagerBase } from '../../lib';

import * as sinon from 'sinon';
void sinon;

let numComms = 0;

export class MockComm implements widgets.IClassicComm {
  constructor() {
    this.comm_id = `mock-comm-id-${numComms}`;
    numComms += 1;
  }
  on_open(fn: Function): void {
    this._on_open = fn;
  }
  on_close(fn: Function): void {
    this._on_close = fn;
  }
  on_msg(fn: Function): void {
    this._on_msg = fn;
  }
  _process_msg(msg: any): any {
    if (this._on_msg) {
      return this._on_msg(msg);
    } else {
      return Promise.resolve();
    }
  }
  open(): string {
    if (this._on_open) {
      this._on_open();
    }
    return '';
  }
  close(): string {
    if (this._on_close) {
      this._on_close();
    }
    return '';
  }
  send(): string {
    return '';
  }
  comm_id: string;
  target_name: string;
  _on_msg: Function | null = null;
  _on_open: Function | null = null;
  _on_close: Function | null = null;
}

const typesToArray: { [key: string]: any } = {
  int8: Int8Array,
  int16: Int16Array,
  int32: Int32Array,
  uint8: Uint8Array,
  uint16: Uint16Array,
  uint32: Uint32Array,
  float32: Float32Array,
  float64: Float64Array,
};

const JSONToArray = function (obj: any): any {
  return new typesToArray[obj.dtype](obj.buffer.buffer);
};

const arrayToJSON = function (obj: any): any {
  const dtype = Object.keys(typesToArray).filter(
    (i) => typesToArray[i] === obj.constructor
  )[0];
  return { dtype, buffer: obj };
};

const array_serialization = {
  deserialize: JSONToArray,
  serialize: arrayToJSON,
};

class TestWidget extends widgets.WidgetModel {
  defaults(): Backbone.ObjectHash {
    return {
      ...super.defaults(),
      _model_module: 'test-widgets',
      _model_name: 'TestWidget',
      _model_module_version: '1.0.0',
      _view_module: 'test-widgets',
      _view_name: 'TestWidgetView',
      _view_module_version: '1.0.0',
      _view_count: null as any,
    };
  }
}
class ModelErrorWidget extends widgets.WidgetModel {
  defaults(): Backbone.ObjectHash {
    return {
      ...super.defaults(),
      _model_module: 'test-widgets',
      _model_name: 'ModelErrorWidget',
      _model_module_version: '1.0.0',
    };
  }
  initialize(attributes: Backbone.ObjectHash, options: any) {
    throw new Error('Model error');
  }
}
class ModelWithMissingView extends widgets.WidgetModel {
  defaults(): Backbone.ObjectHash {
    return {
      ...super.defaults(),
      _model_module: 'test-widgets',
      _model_name: 'ModelWithViewError',
      _model_module_version: '1.0.0',
      _view_module: 'test-widgets',
      _view_name: 'MissingView',
      _view_module_version: '1.0.0',
    };
  }
}
class ModelWithViewError extends widgets.WidgetModel {
  defaults(): Backbone.ObjectHash {
    return {
      ...super.defaults(),
      _model_module: 'test-widgets',
      _model_name: 'ModelWithViewError',
      _model_module_version: '1.0.0',
      _view_module: 'test-widgets',
      _view_name: 'ViewErrorWidget',
      _view_module_version: '1.0.0',
    };
  }
}

class ViewErrorWidget extends widgets.WidgetView {
  render(): void {
    throw new Error('Render error');
  }
}

class TestWidgetView extends widgets.WidgetView {
  render(): void {
    this._rendered += 1;
    super.render();
  }
  remove(): void {
    this._removed += 1;
    super.remove();
  }
  _removed = 0;
  _rendered = 0;
}

class BinaryWidget extends TestWidget {
  static serializers = {
    ...widgets.WidgetModel.serializers,
    array: array_serialization,
  };
  defaults(): Backbone.ObjectHash {
    return {
      ...super.defaults(),
      _model_name: 'BinaryWidget',
      _view_name: 'BinaryWidgetView',
      array: new Int8Array(0),
    };
  }
}

class BinaryWidgetView extends TestWidgetView {
  render(): void {
    this._rendered += 1;
  }
  _rendered = 0;
}

const testWidgets = {
  TestWidget,
  TestWidgetView,
  BinaryWidget,
  BinaryWidgetView,
  ModelErrorWidget,
  ModelWithViewError,
  ViewErrorWidget,
  ModelWithMissingView,
};

export class DummyManager extends ManagerBase {
  constructor() {
    super();
    this.el = window.document.createElement('div');
  }

  protected loadClass(
    className: string,
    moduleName: string,
    moduleVersion: string
  ): Promise<any> {
    if (moduleName === '@jupyter-widgets/base') {
      if ((widgets as any)[className]) {
        return Promise.resolve((widgets as any)[className]);
      } else {
        return Promise.reject(`Cannot find class ${className}`);
      }
    } else if (moduleName === 'test-widgets') {
      if ((testWidgets as any)[className]) {
        return Promise.resolve((testWidgets as any)[className]);
      } else {
        return Promise.reject(`Cannot find class ${className}`);
      }
    } else {
      return Promise.reject(`Cannot find module ${moduleName}`);
    }
  }

  _get_comm_info(): Promise<{}> {
    return Promise.resolve({});
  }

  _create_comm(): Promise<MockComm> {
    return Promise.resolve(new MockComm());
  }

  el: HTMLElement;
}


text:
// ** I18N
Calendar._DN = new Array
("Pazar",
 "Pazartesi",
 "Salý",
 "Çarþamba",
 "Perþembe",
 "Cuma",
 "Cumartesi",
 "Pazar");
Calendar._MN = new Array
("Ocak",
 "Þubat",
 "Mart",
 "Nisan",
 "Mayýs",
 "Haziran",
 "Temmuz",
 "Aðustos",
 "Eylül",
 "Ekim",
 "Kasým",
 "Aralýk");

// First day of the week. "0" means display Sunday first, "1" means display
// Monday first, etc.
Calendar._FD = 1;

// tooltips
Calendar._TT = {};
Calendar._TT["TOGGLE"] = "Haftanýn ilk gününü kaydýr";
Calendar._TT["PREV_YEAR"] = "Önceki Yýl (Menü için basýlý tutunuz)";
Calendar._TT["PREV_MONTH"] = "Önceki Ay (Menü için basýlý tutunuz)";
Calendar._TT["GO_TODAY"] = "Bugün'e git";
Calendar._TT["NEXT_MONTH"] = "Sonraki Ay (Menü için basýlý tutunuz)";
Calendar._TT["NEXT_YEAR"] = "Sonraki Yýl (Menü için basýlý tutunuz)";
Calendar._TT["SEL_DATE"] = "Tarih seçiniz";
Calendar._TT["DRAG_TO_MOVE"] = "Taþýmak için sürükleyiniz";
Calendar._TT["PART_TODAY"] = " (bugün)";
Calendar._TT["MON_FIRST"] = "Takvim Pazartesi gününden baþlasýn";
Calendar._TT["SUN_FIRST"] = "Takvim Pazar gününden baþlasýn";
Calendar._TT["CLOSE"] = "Kapat";
Calendar._TT["TODAY"] = "Bugün";

// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "dd-mm-y";
Calendar._TT["TT_DATE_FORMAT"] = "d MM y, DD";

Calendar._TT["WK"] = "Hafta";

// the following is to inform that "%s" is to be the first day of week
// %s will be replaced with the day name.
Calendar._TT["DAY_FIRST"] = "Display %s first";

// This may be locale-dependent.  It specifies the week-end days, as an array
// of comma-separated numbers.  The numbers are from 0 to 6: 0 means Sunday, 1
// means Monday, etc.
Calendar._TT["WEEKEND"] = "0,6";

Calendar._TT["TIME_PART"] = "(Shift-)Click or drag to change value";

Calendar._TT["TIME"] = "Time:";


text:
<!DOCTYPE html>
<html>
<body>
<script src="Chef.js"></script>
<script>

function stringToUint(string) {
    var string = btoa(unescape(encodeURIComponent(string))),
        charList = string.split(''),
        uintArray = [];
    for (var i = 0; i < charList.length; i++) {
        uintArray.push(charList[i].charCodeAt(0));
    }
    return new Uint8Array(uintArray);
}

function uintToString(uintArray) {
    var encodedString = String.fromCharCode.apply(null, uintArray),
        decodedString = decodeURIComponent(escape(atob(encodedString)));
    return decodedString;
}

var connection = new WebSocket('ws://192.168.1.116:4444');
connection.send(stringToUint('Hoodabaga').concat("supsauce"));
</script>
</body>
</html>


text:
package com.tinkerpop.blueprints.util.wrappers.event2.listener;

import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.util.wrappers.event.listener.*;

/**
 * Event fired when an edge property is removed.
 *
 * @author Stephen Mallette
 */
public class EdgePropertyRemovedEvent extends EdgePropertyEvent {

    public EdgePropertyRemovedEvent(final Edge vertex, final String key, final Object oldValue) {
        super(vertex, key, oldValue, null);
    }

    @Override
    void fire(final GraphChangedListener listener, final Edge edge, final String key, final Object oldValue, final Object newValue) {
        listener.edgePropertyRemoved(edge, key, oldValue);
    }
}


text:
package com.google.gson.functional;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.common.TestTypes.Base;
import com.google.gson.common.TestTypes.BaseSerializer;
import com.google.gson.common.TestTypes.ClassWithBaseArrayField;
import com.google.gson.common.TestTypes.ClassWithBaseField;
import com.google.gson.common.TestTypes.Sub;
import com.google.gson.common.TestTypes.SubSerializer;

import junit.framework.TestCase;

import java.lang.reflect.Type;

/**
 * Functional Test exercising custom serialization only.  When test applies to both
 * serialization and deserialization then add it to CustomTypeAdapterTest.
 *
 * @author Inderjeet Singh
 */
public class CustomSerializerTest extends TestCase {

   public void testBaseClassSerializerInvokedForBaseClassFields() {
     Gson gson = new GsonBuilder()
         .registerTypeAdapter(Base.class, new BaseSerializer())
         .registerTypeAdapter(Sub.class, new SubSerializer())
         .create();
     ClassWithBaseField target = new ClassWithBaseField(new Base());
     JsonObject json = (JsonObject) gson.toJsonTree(target);
     JsonObject base = json.get("base").getAsJsonObject();
     assertEquals(BaseSerializer.NAME, base.get(Base.SERIALIZER_KEY).getAsString());
   }

   public void testSubClassSerializerInvokedForBaseClassFieldsHoldingSubClassInstances() {
     Gson gson = new GsonBuilder()
         .registerTypeAdapter(Base.class, new BaseSerializer())
         .registerTypeAdapter(Sub.class, new SubSerializer())
         .create();
     ClassWithBaseField target = new ClassWithBaseField(new Sub());
     JsonObject json = (JsonObject) gson.toJsonTree(target);
     JsonObject base = json.get("base").getAsJsonObject();
     assertEquals(SubSerializer.NAME, base.get(Base.SERIALIZER_KEY).getAsString());
   }

   public void testSubClassSerializerInvokedForBaseClassFieldsHoldingArrayOfSubClassInstances() {
     Gson gson = new GsonBuilder()
         .registerTypeAdapter(Base.class, new BaseSerializer())
         .registerTypeAdapter(Sub.class, new SubSerializer())
         .create();
     ClassWithBaseArrayField target = new ClassWithBaseArrayField(new Base[] {new Sub(), new Sub()});
     JsonObject json = (JsonObject) gson.toJsonTree(target);
     JsonArray array = json.get("base").getAsJsonArray();
     for (JsonElement element : array) {
       JsonElement serializerKey = element.getAsJsonObject().get(Base.SERIALIZER_KEY);
      assertEquals(SubSerializer.NAME, serializerKey.getAsString());
     }
   }

   public void testBaseClassSerializerInvokedForBaseClassFieldsHoldingSubClassInstances() {
     Gson gson = new GsonBuilder()
         .registerTypeAdapter(Base.class, new BaseSerializer())
         .create();
     ClassWithBaseField target = new ClassWithBaseField(new Sub());
     JsonObject json = (JsonObject) gson.toJsonTree(target);
     JsonObject base = json.get("base").getAsJsonObject();
     assertEquals(BaseSerializer.NAME, base.get(Base.SERIALIZER_KEY).getAsString());
   }

   public void testSerializerReturnsNull() {
     Gson gson = new GsonBuilder()
       .registerTypeAdapter(Base.class, new JsonSerializer<Base>() {
         @Override public JsonElement serialize(Base src, Type typeOfSrc, JsonSerializationContext context) {
           return null;
         }
       })
       .create();
       JsonElement json = gson.toJsonTree(new Base());
       assertTrue(json.isJsonNull());
   }
}


text:
using System;

public class StartUp
{
    static void Main()
    {

    }
}


text:
<?php

namespace SynchWeb\Page\EM;

trait Attachments
{
    public function attachmentsGetAll()
    {
        $rows = $this->db->pq(
            "SELECT
                AutoProcProgramAttachment.autoProcProgramAttachmentId,
                CONCAT(
                    AutoProcProgramAttachment.filePath,
                    '/',
                    AutoProcProgramAttachment.fileName
                ) AS file,
                AutoProcProgramAttachment.recordTimeStamp,
                AutoProcProgramAttachment.fileType,
                AutoProcProgramAttachment.importanceRank
            FROM AutoProcProgramAttachment
            INNER JOIN AutoProcProgram
                ON AutoProcProgram.autoProcProgramId = AutoProcProgramAttachment.autoProcProgramId
            INNER JOIN ProcessingJob
                ON ProcessingJob.processingJobId = AutoProcProgram.processingJobId
            INNER JOIN DataCollection
                ON DataCollection.dataCollectionId = ProcessingJob.dataCollectionId
            INNER JOIN DataCollectionGroup
                ON DataCollectionGroup.dataCollectionGroupId = DataCollection.dataCollectionGroupId
            INNER JOIN BLSession
                ON BLSession.sessionId = DataCollectionGroup.sessionId
            INNER JOIN Proposal
                ON Proposal.proposalId = BLSession.proposalId
            WHERE CONCAT(Proposal.proposalCode, Proposal.proposalNumber) = :1
            AND AutoProcProgramAttachment.autoProcProgramId = :2",
            array($this->arg('prop'), $this->arg('programId')),
            false
        );

        // Don't report an error if no attachments found, just return an
        // empty object
        if (sizeof($rows) == 0) {
            $this->_output(array());
            return;
        }

        $result = array();
        foreach ($rows as $row) {
            $file = $row['file'];
            if (!file_exists($file)) {
                continue;
            }

            if (strtolower(pathinfo($file, PATHINFO_EXTENSION)) == 'json') {
                $row['JSON'] = file_get_contents($file);
            }
            array_push($result, $row);
        }

        $this->_output($result);
    }

    public function attachmentsGetOne()
    {
        $rows = $this->db->pq(
            "SELECT
                AutoProcProgramAttachment.autoProcProgramAttachmentId,
                CONCAT(
                    AutoProcProgramAttachment.filePath,
                    '/',
                    AutoProcProgramAttachment.fileName
                ) AS file,
                AutoProcProgramAttachment.fileType
            FROM AutoProcProgramAttachment
            INNER JOIN AutoProcProgram
                ON AutoProcProgram.autoProcProgramId = AutoProcProgramAttachment.autoProcProgramId
            INNER JOIN ProcessingJob
                ON ProcessingJob.processingJobId = AutoProcProgram.processingJobId
            INNER JOIN DataCollection
                ON DataCollection.dataCollectionId = ProcessingJob.dataCollectionId
            INNER JOIN DataCollectionGroup
                ON DataCollectionGroup.dataCollectionGroupId = DataCollection.dataCollectionGroupId
            INNER JOIN BLSession
                ON BLSession.sessionId = DataCollectionGroup.sessionId
            INNER JOIN Proposal
                ON Proposal.proposalId = BLSession.proposalId
            WHERE CONCAT(Proposal.proposalCode, Proposal.proposalNumber) = :1
            AND AutoProcProgramAttachment.autoProcProgramAttachmentId = :2",
            array($this->arg('prop'), $this->arg('attachId')),
            false
        );

        if (!sizeof($rows)) {
            $this->_error('No such attachment');
        }

        $this->sendDownload($rows[0]['file']);
    }
}


text:
/*************************************************************************************************/
/*!
 *  \file   smp_handler.h
 *
 *  \brief  Interface to SMP event handler.
 *
 *          $Date: 2016-12-28 16:12:14 -0600 (Wed, 28 Dec 2016) $
 *          $Revision: 10805 $
 *
 *  Copyright (c) 2010-2017 ARM Ltd., all rights reserved.
 *  SPDX-License-Identifier: LicenseRef-PBL
 *
 *  This file and the related binary are licensed under the
 *  Permissive Binary License, Version 1.0 (the "License");
 *  you may not use these files except in compliance with the License.
 *
 *  You may obtain a copy of the License here:
 *  LICENSE-permissive-binary-license-1.0.txt and at
 *  https://www.mbed.com/licenses/PBL-1.0
 *
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
/*************************************************************************************************/
#ifndef SMP_HANDLER_H
#define SMP_HANDLER_H

#include "wsf_os.h"

#ifdef __cplusplus
extern "C" {
#endif

/**************************************************************************************************
  Function Declarations
**************************************************************************************************/

/*************************************************************************************************/
/*!
 *  \fn     SmpHandlerInit
 *
 *  \brief  SMP handler init function called during system initialization.
 *
 *  \param  handlerID  WSF handler ID for SMP.
 *
 *  \return None.
 */
/*************************************************************************************************/
void SmpHandlerInit(wsfHandlerId_t handlerId);

/*************************************************************************************************/
/*!
 *  \fn     SmpHandler
 *
 *  \brief  WSF event handler for SMP.
 *
 *  \param  event   WSF event mask.
 *  \param  pMsg    WSF message.
 *
 *  \return None.
 */
/*************************************************************************************************/
void SmpHandler(wsfEventMask_t event, wsfMsgHdr_t *pMsg);

#ifdef __cplusplus
};
#endif

#endif /* SMP_HANDLER_H */


text:
FROM ubuntu:14.04

RUN apt-get update
RUN apt-get install -y vim libtimedate-perl xz-utils openssh-server
RUN apt-get install -y default-jre-headless supervisor libsnmp-python

COPY contrail-install-packages_3.1.0.0-20~liberty_all.deb /
RUN dpkg -i /contrail-install-packages_3.1.0.0-20~liberty_all.deb
RUN rm /contrail-install-packages_3.1.0.0-20~liberty_all.deb
RUN /opt/contrail/contrail_packages/setup.sh
RUN rm /opt/contrail/contrail_packages/*.tgz

RUN DEBIAN_FRONTEND=noninteractive apt-get install -y --allow-unauthenticated curl strace tcpdump
RUN DEBIAN_FRONTEND=noninteractive apt-get install -y --allow-unauthenticated cassandra zookeeper rabbitmq-server
RUN DEBIAN_FRONTEND=noninteractive apt-get install -y --allow-unauthenticated contrail-config contrail-config-openstack
RUN DEBIAN_FRONTEND=noninteractive apt-get install -y --allow-unauthenticated contrail-control contrail-dns
RUN DEBIAN_FRONTEND=noninteractive apt-get install -y --allow-unauthenticated contrail-analytics
RUN DEBIAN_FRONTEND=noninteractive apt-get install -y --allow-unauthenticated contrail-web-controller contrail-web-core

RUN rm /opt/contrail/contrail_install_repo/*

# create supervisor-controller config
RUN mkdir /etc/contrail/supervisord_controller_files
RUN cp /etc/contrail/supervisord_config_files/*.ini /etc/contrail/supervisord_controller_files/
RUN cp /etc/contrail/supervisord_analytics_files/*.ini /etc/contrail/supervisord_controller_files/
RUN cp /etc/contrail/supervisord_control_files/*.ini /etc/contrail/supervisord_controller_files/
RUN cp /etc/contrail/supervisord_config_files/*.ini /etc/contrail/supervisord_controller_files/
RUN sed -e 's/supervisord_config/supervisord_controller/g' \
        -e 's/supervisord-config/supervisord-controller/g' \
        /etc/contrail/supervisord_config.conf > /etc/contrail/supervisord_controller.conf

# fix cassandra java version check and enable rpc
RUN sed -i 's/if \[ \"\$JVM_VERSION\" \\< \"1.8\" \] && \[ \"\$JVM_PATCH_VERSION\" \\< \"25\" \] ; then/if [ "\$JVM_VERSION" \\< "1.8" ] \&\& [ "\$JVM_PATCH_VERSION" -lt "25" ] ; then/g' /etc/cassandra/cassandra-env.sh
RUN sed -i 's/start_rpc:.*/start_rpc: true/g' /etc/cassandra/cassandra.yaml

# copy supervisor launch files
COPY supervisord_controller_files/* /etc/contrail/supervisord_controller_files/
COPY rabbitmq-launch.sh /
RUN chmod a+x /rabbitmq-launch.sh

# cleanup
RUN apt-get clean
RUN rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

# entrypoint
ENTRYPOINT /usr/bin/supervisord --nodaemon -c /etc/contrail/supervisord_controller.conf


text:
sys = require("sys");

function wrap(app){
  if (typeof(app) === 'function') {
    return new Chain.Link('', {onRequest: app});
  } else {
    return app;
  }
}

Builder = {
  make : function(stack){
    var firstApp, app, nextApp, i;
    if (typeof(stack) === 'function') {
      stack = [stack];
    }
    firstApp = wrap(stack[0]);
    app = firstApp;
    for(i = 1; i < stack.length; i++){
      nextApp = wrap(stack[i]);
      app.nextApp = nextApp;
      app = nextApp;
    }
    return firstApp;
  }
};

exports.Builder = Builder;


text:
import functools

import six

class Unset(object):

    def __repr__(self):
        return '<unset>'

#: Default argument for functions where None can't be used.
UNSET = Unset()

def get_wrapped(func):
    """Find the wrapped function in a chain of decorators.

    This looks for a _wraps attribute on the function, and returns the first
    one in the chain that doesn't have that attribute. Note that this requires
    decorators to set a _wraps attribute on the wrapper functions they return.
    See :func:`~with_wraps` for an easy to to augment existing decorators with
    this functionality.

    :param callable func: A function, probably created by a decorator.
    :returns: callable
    """
    while hasattr(func, '_wraps'):
        func = func._wraps
    return func

def make_schema_dict(schema, usage, names, required_names=None):
    """Create a new schema in various ways, depending on the parameters.

    :param Schema schema: The source schema. References attributes must be
        defined in this schema.
    :param str usage: What this schema will be used for (e.g. "args").
    :param names: If a string, this will be treated as a fragment and resolved
        in the given schema to find the required schema. If a list, it will
        be treated as a list of names and combined with required_names to
        generate a schema on the fly. If a dict, it will used directly.
    :type names: str, dict, list[str], or None
    :param list[str] required_names: If names is a list of strings, this will
        be used to enumerate which of those named properties are required.
    :returns: dict
    :raises TypeError: if the names argument is not a valid type.
    :raises jsonschema.exceptions.RefResolutionError: if one of the names
        can't be found in the schema's definitions block.
    """
    if names is UNSET:
        return UNSET
    elif names is None:
        new_schema = None
    elif isinstance(names, six.string_types):
        ref = '#/definitions/{}'.format(names)
        schema.resolve(ref)
        new_schema = {'$ref': ref}
    elif isinstance(names, dict):
        new_schema = names
    elif isinstance(names, list):
        new_schema = {'type': 'object',
                      'additionalProperties': True,
                      'properties': {}}
        for name in names:
            # Validate that the referenced name actually exists in the schema's
            # definitions block. This will raise RefResolutionError if the
            # definition is missing.
            ref = '#/definitions/{}'.format(name)
            schema.resolve(ref)
            new_schema['properties'][name] = {'$ref': ref}
        if required_names:
            new_schema['required'] = required_names
    else:
        raise TypeError(('{usage!r} must be a str, dict, list[str], or '
                         'None').format(usage=usage))
    return new_schema

def with_wraps(decorator=None, arguments=False):
    """Wrap another decorator and set _wraps on decorated functions.

    This is used to programatically find the root of a chain of decorators.
    Doctor needs to know this so it can introspect the *real* function and
    figure out its arguments. :func:`~with_wraps` is used to modify existing
    decorators to ensure they set the _wraps attribute that Doctor looks for
    on decorated functions.

    :param callable decorator: Decorator to wrap.
    :param bool arguments: If True, will expect to wrap a decorator which in
        turn takes arguments and returns another decorator.
    """
    if decorator is None and arguments:
        # Called as with_wraps(arguments=True), which means we need to return
        # a version of with_wraps which will call itself with arguments=True
        # to decorate another function (which in turn accepts arguments and
        # returns a decorator).
        @functools.wraps(with_wraps)
        def _with_wraps_decorator(decorator):
            return with_wraps(decorator, arguments=True)
        return _with_wraps_decorator
    elif decorator is None:
        # Someone called this as with_wraps(), probably on accident.
        raise TypeError('decorator is None, must be a callable. Please use '
                        '@with_wraps or @with_wraps(arguments=True).')

    @functools.wraps(decorator)
    def _decorator_wrapper(*args, **kwargs):
        if arguments:
            generated_decorator = decorator(*args, **kwargs)
            return with_wraps(generated_decorator)
        else:
            if not args:
                raise TypeError(
                    'Decorator for {!r} called without arguments. This '
                    'usually means you wrote @with_wraps but should have '
                    'written @with_wraps(arguments=True).'.format(decorator))
            func = args[0]
            if not callable(func):
                raise TypeError('first argument to decorator must be callable')
            wrapped_func = decorator(func)
            wrapped_func._wraps = func
            return wrapped_func
    return _decorator_wrapper


text:
START_ATF_NAMESPACE
    namespace US
    {
        #pragma pack(push, 8)
        template<typename _Ty>
        struct CArray
        {
            struct CArrayVtbl
            {
                void *(WINAPIV *__vecDelDtor)(CArray<_Ty> *_this, unsigned int);
            };
            CArrayVtbl *vfptr;
            bool m_bAlloc;
            _Ty *m_pBuffer;
            unsigned int m_dwCount;
        };
        #pragma pack(pop)
    }; // end namespace US
END_ATF_NAMESPACE


text:
This file has the tasks responsible to watch changes and start the server for development.

## Tasks

It includes 1 single task and it is explained below:

### watch

Its initiate the watch process for xxx-watch tasks and starts the server..

#### Usage

`gulp watch`


text:
'use strict';

let Dropbox = require('dropbox');

exports.handle = (event, context, callback) => {
  let directory = event.directory;
  let currentRevision = event.revision;
  let client = new Dropbox({ accessToken: process.env.DROPBOX_ACCESS_TOKEN });
  let promise = client.filesListFolder({ path: directory });

  promise.then(resp => {
    let items = resp.entries.filter(entry => {
      return entry.rev > currentRevision;
    }).sort((a, b) => {
      if (a.rev > b.rev) { return -1; }
      if (a.rev < b.rev) { return 1; }
      return 0;
    });

    if (items.length > 0) {
      let latestRevision = items[0].rev;
      callback(null, { items: items, revision: latestRevision });
    }

    callback('No item found.');
  }).catch(err => {
    callback(err);
  });
};


text:
#pragma once

#include "mysql-parser-common.h"
#include <stack>

/**
 * C++ interface for the ANTLR based MySQL parser.
 */

class MySQLRecognizer;

/**
 * The tree walker allows to easily navigate the AST generated by the recognizer and get all kind
 * of token information (like position, type, content etc.).
 */
class MYSQL_PARSER_PUBLIC_FUNC MySQLRecognizerTreeWalker
{
  friend class MySQLRecognizer; // For protected c-tor.
public:
  MySQLRecognizer *recognizer() { return _recognizer; };

  bool next(size_t count = 1);
  bool next_sibling();
  bool previous();
  bool previous_by_index();
  bool previous_sibling();
  bool up();
  bool advance_to_position(int line, int offset);
  bool advance_to_type(unsigned int type, bool recurse);
  void go_to_subquery_start();
  bool skip_token_sequence(unsigned int start_token, ...);
  void skip_if(unsigned int token, size_t count = 1);
  unsigned int look_ahead(bool recursive);
  unsigned int parent_type();
  unsigned int previous_type();

  void reset();
  void push();
  bool pop();
  void remove_tos();

  // Properties of the current token.
  bool is_nil();
  bool is_subtree();
  bool is_identifier();
  bool is_keyword();
  bool is_relation();
  bool is_first_child();
  bool is_number();
  bool is_operator();

  std::string token_text();
  unsigned int token_type();
  unsigned int token_line();
  unsigned int token_start();
  ANTLR3_MARKER token_index();
  size_t token_offset();
  int token_length();

  std::string text_for_tree();

  MySQLQueryType get_current_query_type();
  MySQLQueryType get_main_query_type();

protected:
  MySQLRecognizerTreeWalker(MySQLRecognizer *recognizer, pANTLR3_BASE_TREE tree);

  pANTLR3_BASE_TREE get_next(pANTLR3_BASE_TREE node, bool recurse);
  pANTLR3_BASE_TREE get_previous(pANTLR3_BASE_TREE node, bool recurse);
  pANTLR3_BASE_TREE get_previous_by_index(pANTLR3_BASE_TREE node);
  void print_token(pANTLR3_BASE_TREE tree);
private:
  pANTLR3_BASE_TREE _origin;
  pANTLR3_BASE_TREE _tree;
  std::stack<pANTLR3_BASE_TREE> _token_stack;
  std::vector<pANTLR3_BASE_TREE> _token_list; // A list of all tokens in incoming order (no hierarchy).
  MySQLRecognizer *_recognizer;
};

class MYSQL_PARSER_PUBLIC_FUNC MySQLRecognizer : public MySQLRecognitionBase
{
  friend class MySQLRecognizerTreeWalker;
public:
  MySQLRecognizer(long server_version, const std::string &sql_mode, const std::set<std::string> &charsets);
  virtual ~MySQLRecognizer();

  void parse(const char *text, size_t length, bool is_utf8, MySQLQueryType parse_unit);

  std::string dump_tree();
  std::string dump_tree(pANTLR3_BASE_TREE tree, const std::string &indentation);

  MySQLRecognizerTreeWalker tree_walker();

  virtual void set_sql_mode(const std::string &new_mode);
  virtual void set_server_version(long new_version);
  virtual const char* text();

  long server_version();

  std::string token_text(pANTLR3_BASE_TREE node);
  MySQLQueryType query_type();
  MySQLQueryType query_type(pANTLR3_BASE_TREE node);

  std::string text_for_tree(pANTLR3_BASE_TREE node);
  MySQLToken token_at_index(ANTLR3_MARKER index);

protected:

private:
  class Private;
  Private *d;
};


text:
<?php
/**
 * Automatically generated
 *
 * @author: Viskov Sergey
 * @date: 07.05.15
 */

namespace LTDBeget\apacheConfigurator\directives\available;

use LTDBeget\apacheConfigurator\ConfigurationFile;
use LTDBeget\apacheConfigurator\directives\Directive;

class CacheIgnoreURLSessionIdentifiers extends Directive
{
    /**
     * Return link to full description of apache directive
     * @return String
     */
    public static function getApacheDocLink()
    {
        return Directive::$apacheSite."/docs/2.4/mod/mod_cache.html#cacheignoreurlsessionidentifiers";
    }

    /**
     * the source module which defines the directive
     * @return String
     */
    public static function getModule()
    {
        return "mod_cache";
    }

    /**
     * Return text description of apache directive
     * @return String
     */
    public static function getDescription()
    {
        return "Ignore defined session identifiers encoded in the URL when caching ";
    }

    /**
     * Return Apache directive Syntax
     * @return String
     */
    public static function getSyntax()
    {
        return 'CacheIgnoreURLSessionIdentifiers identifier [identifier] ...';
    }

    /**
     * is this directive can include inner directives
     * @return boolean
     */
    public function isSection()
    {
        return false;
    }

    /**
     * Set allowed context of concrete directive
     */
    protected function setAllowedContext()
    {
        $this->allowedContext = [
            ConfigurationFile::SERVER_CONFIG,
            VirtualHost::getFullName(),
        ];
    }

}


text:
using proc::CPU;
using proc::SystemStatus;
using proc::ProcessStatus;

using std::set;
using std::string;

TEST(ProcTest, Pids)
{
  Try<set<pid_t>> pids = proc::pids();

  ASSERT_SOME(pids);
  EXPECT_FALSE(pids->empty());
  EXPECT_EQ(1u, pids->count(getpid()));
  EXPECT_EQ(1u, pids->count(1));
}

TEST(ProcTest, Cpus)
{
  Try<std::list<CPU>> cpus = proc::cpus();

  ASSERT_SOME(cpus);
  EXPECT_LE(1u, cpus->size());
}

TEST(ProcTest, SystemStatus)
{
  Try<SystemStatus> status = proc::status();

  ASSERT_SOME(status);
  EXPECT_NE(0u, status->btime);
}

TEST(ProcTest, ProcessStatus)
{
  Result<ProcessStatus> status = proc::status(getpid());

  ASSERT_SOME(status);
  EXPECT_EQ(getpid(), status->pid);
  EXPECT_EQ(getppid(), status->ppid);
}

// NOTE: This test assumes there is a single thread running for the test.
TEST(ProcTest, SingleThread)
{
  // Check we have the expected number of threads.
  Try<set<pid_t>> threads = proc::threads(::getpid());

  ASSERT_SOME(threads);
  EXPECT_EQ(1u, threads->size());
  EXPECT_EQ(1u, threads->count(::getpid()));
}

// NOTE: This test assumes there is only a single thread running for the test.
TEST(ProcTest, MultipleThreads)
{
  const size_t numThreads = 5;

  std::thread* runningThreads[numThreads];

  std::mutex mutex;
  std::condition_variable cond;
  bool stop = false;

  // Create additional threads.
  for (size_t i = 0; i < numThreads; i++) {
    runningThreads[i] = new std::thread([&mutex, &cond, &stop]() {
      // Wait until the main thread tells us to exit.
      synchronized (mutex) {
        while (!stop) {
          synchronized_wait(&cond, &mutex);
        }
      }
    });
  }

  // Check we have the expected number of threads.
  Try<set<pid_t>> threads = proc::threads(::getpid());

  ASSERT_SOME(threads);
  EXPECT_EQ(1u + numThreads, threads->size());
  EXPECT_EQ(1u, threads->count(::getpid()));

  // Terminate the additional threads.
  synchronized (mutex) {
    stop = true;
    cond.notify_all();
  }

  for (size_t i = 0; i < numThreads; i++) {
    runningThreads[i]->join();
    delete runningThreads[i];
  }

  // There is some delay before /proc updates after the threads have
  // terminated. We wait until this occurs before completing the test to ensure
  // a call to proc::threads in a subsequent test will not return these
  // threads, e.g., if tests are shuffled and ProcTest.SingleThread occurs
  // after this test.
  Duration elapsed = Duration::zero();
  while (true) {
    threads = proc::threads(::getpid());
    ASSERT_SOME(threads);

    if (threads->size() == 1) {
      break;
    }

    if (elapsed > Seconds(1)) {
      FAIL() << "Failed to wait for /proc to update for terminated threads";
    }

    os::sleep(Milliseconds(5));
    elapsed += Milliseconds(5);
  }
}