text:
import collections

import mock

from oslotest import base

from networking_cisco.apps.saf.agent.vdp import ovs_vdp
from networking_cisco.apps.saf.agent.vdp import vdp_constants as vconstants
from networking_cisco.apps.saf.common import dfa_sys_lib as utils

try:
    OrderedDict = collections.OrderedDict
except AttributeError:
    import ordereddict
    OrderedDict = ordereddict.OrderedDict

class OvsVdpTest(base.BaseTestCase):
    """A test suite to exercise the OvsVdp Class.  """

    def setUp(self):
        '''Setup routine '''
        super(OvsVdpTest, self).setUp()
        self.root_helper = 'sudo'
        self.uplink = "eth2"
        self.integ_br = 'br-int1'
        self.ext_br = 'br-ethd1'

        self.port_name = "loc_veth"
        self.port_str = "loc_veth_eth2"
        self.rpc_client = mock.Mock()
        self.execute = mock.patch.object(
            utils, "execute", spec=utils.execute).start()
        self.addCleanup(mock.patch.stopall)
        self._test_ovs_vdp_init()
        phy_port_num = 5
        int_peer_port_num = 6
        self.port_uuid = '0000-1111-2222-3334'
        self.port_uuid_1 = '0000-1111-2222-3335'
        self.mac = '00:00:fa:11:22:34'
        self.net_uuid = '0000-aaaa-bbbb-cccc'
        self.segmentation_id = 10001
        self.lvid = 10
        self.exist_vdp_vlan = 3000
        self.oui = None
        self.ovs_vdp.phy_peer_port_num = phy_port_num
        self.ovs_vdp.int_peer_port_num = int_peer_port_num

    def _test_ovs_vdp_init(self):
        '''Test the init routine '''
        lldp_ovs_portnum = 14
        phy_port_num = 14
        get_br = mock.patch('networking_cisco.apps.saf.common.'
                            'dfa_sys_lib.get_bridges').start()
        is_patch = mock.patch('networking_cisco.apps.saf.common.'
                              'dfa_sys_lib.is_patch').start()
        get_peer = mock.patch('networking_cisco.apps.saf.common.'
                              'dfa_sys_lib.get_peer').start()
        self.ovs_br_add = mock.patch('networking_cisco.apps.saf.common.'
                                     'dfa_sys_lib.OVSBridge.add_flow').start()
        mock.patch('networking_cisco.apps.saf.common.'
                   'dfa_sys_lib.OVSBridge.add_port',
                   return_value=str(lldp_ovs_portnum)).start()
        mock.patch('networking_cisco.apps.saf.common.'
                   'dfa_sys_lib.OVSBridge.get_port_ofport',
                   return_value=str(phy_port_num)).start()
        port_name_list = mock.patch('networking_cisco.apps.saf.common.'
                                    'dfa_sys_lib.OVSBridge.'
                                    'get_port_name_list').start()
        dev_exist = mock.patch('neutron.agent.linux.ip_lib.'
                               'device_exists').start()
        add_veth = mock.patch('neutron.agent.linux.ip_lib.'
                              'IPWrapper.add_veth').start()
        mock.patch('networking_cisco.apps.saf.'
                   'agent.vdp.lldpad.LldpadDriver').start()
        mock.patch('networking_cisco.apps.saf.common.'
                   'utils.PeriodicTask').start()
        get_br.return_value = self.integ_br + ' ' + self.ext_br
        port_name_list.return_value = 'port_int1'
        is_patch.return_value = True
        get_peer.return_value = 'port_int1'
        dev_exist.return_value = False
        add_veth.return_value = mock.Mock(), mock.Mock()
        self.vdp_cb = mock.MagicMock()
        self.ovs_vdp = ovs_vdp.OVSNeutronVdp(self.uplink, self.integ_br,
                                             self.ext_br,
                                             self.root_helper, self.vdp_cb)
        self.ovs_br_add.reset_mock()

    def test_process_init(self):
        '''Wrapper for the init routine test '''
        pass

    def test_setup_lldpad_ports(self):
        """Test for setup lldpad ports. """
        lldp_ovs_portnum = 14
        phy_port_num = 14
        veth_str = vconstants.LLDPAD_LOC_VETH_PORT + self.uplink
        with mock.patch('networking_cisco.apps.saf.'
                        'agent.vdp.lldpad.LldpadDriver') as lldpad, \
            mock.patch('networking_cisco.apps.saf.common.dfa_sys_lib.'
                       'OVSBridge.delete_flows') as ovs_br_del:
            lldp_inst = lldpad.return_value
            parent = mock.MagicMock()
            parent.attach_mock(ovs_br_del, 'delete_flows')
            parent.attach_mock(self.ovs_br_add, 'add_flow')
            parent.attach_mock(lldp_inst.enable_evb, 'enable_evb')
            self.ovs_vdp.setup_lldpad_ports()
        expected_calls = [
            mock.call.delete_flows(dl_dst=vconstants.NCB_DMAC,
                                   dl_type=vconstants.LLDP_ETYPE),
            mock.call.delete_flows(dl_dst=vconstants.NCB_DMAC,
                                   dl_type=vconstants.VDP22_ETYPE),
            mock.call.add_flow(priority=vconstants.VDP_FLOW_PRIO,
                               in_port=str(lldp_ovs_portnum),
                               dl_dst=vconstants.NCB_DMAC,
                               dl_type=vconstants.LLDP_ETYPE,
                               actions="output:%s" % phy_port_num),
            mock.call.add_flow(priority=vconstants.VDP_FLOW_PRIO,
                               in_port=str(phy_port_num),
                               dl_dst=vconstants.NCB_DMAC,
                               dl_type=vconstants.LLDP_ETYPE,
                               actions="output:%s" % lldp_ovs_portnum),
            mock.call.add_flow(priority=vconstants.VDP_FLOW_PRIO,
                               in_port=str(lldp_ovs_portnum),
                               dl_dst=vconstants.NCB_DMAC,
                               dl_type=vconstants.VDP22_ETYPE,
                               actions="output:%s" % phy_port_num),
            mock.call.add_flow(priority=vconstants.VDP_FLOW_PRIO,
                               in_port=str(phy_port_num),
                               dl_dst=vconstants.NCB_DMAC,
                               dl_type=vconstants.VDP22_ETYPE,
                               actions="output:%s" % lldp_ovs_portnum),
            mock.call.enable_evb()]
        parent.assert_has_calls(expected_calls, any_order=False)
        lldpad.assert_called_with(veth_str, self.uplink, self.root_helper)

    def _test_vdp_port_event_new(self):
        '''Test the case for a new vnic port for a network '''
        port_uuid = '0000-1111-2222-3333'
        mac = '00:00:fa:11:22:33'
        net_uuid = '0000-aaaa-bbbb-cccc'
        segmentation_id = 10001
        status = 'up'
        oui = None
        with mock.patch('networking_cisco.apps.saf.common.'
                        'dfa_sys_lib.OVSBridge.get_ofport_name',
                        return_value='test_port'), \
            mock.patch('networking_cisco.apps.saf.common.'
                       'dfa_sys_lib.OVSBridge.get_port_vlan_tag',
                       return_value=10), \
            mock.patch.object(self.ovs_vdp.lldpad_info, 'send_vdp_vnic_up',
                              return_value=[500, None]):
            parent = mock.MagicMock()
            parent.attach_mock(self.ovs_br_add, 'add_flow')
            self.ovs_vdp.send_vdp_port_event(port_uuid, mac, net_uuid,
                                             segmentation_id, status, oui)
        expected_calls = [
            mock.call.add_flow(priority=4,
                               in_port=self.ovs_vdp.phy_peer_port_num,
                               dl_vlan=10,
                               actions="mod_vlan_vid:%s,normal" % 500),
            mock.call.add_flow(priority=3,
                               in_port=self.ovs_vdp.int_peer_port_num,
                               dl_vlan=500,
                               actions="mod_vlan_vid:%s,normal" % 10)]
        parent.assert_has_calls(expected_calls, any_order=False)

    def _test_vdp_port_event_exist(self):
        '''Test the case for a exist vnic port for a network '''
        port_uuid = '0000-1111-2222-3334'
        mac = '00:00:fa:11:22:34'
        net_uuid = '0000-aaaa-bbbb-cccc'
        segmentation_id = 10001
        status = 'up'
        oui = None
        ovs_cb_data = {'obj': self.ovs_vdp, 'mac': mac,
                       'port_uuid': port_uuid, 'net_uuid': net_uuid}
        with mock.patch('networking_cisco.apps.saf.common.'
                        'dfa_sys_lib.OVSBridge.get_ofport_name',
                        return_value='test_port'), \
                mock.patch.object(self.ovs_vdp.lldpad_info,
                                  'send_vdp_vnic_up') as vnic_up:
            parent = mock.MagicMock()
            parent.attach_mock(vnic_up, 'send_vdp_vnic_up')
            self.ovs_vdp.send_vdp_port_event(port_uuid, mac, net_uuid,
                                             segmentation_id, status, oui)
        expected_calls = [
            mock.call.send_vdp_vnic_up(port_uuid=port_uuid,
                                       vsiid=port_uuid,
                                       gid=segmentation_id,
                                       mac=mac, vlan=500,
                                       oui=oui,
                                       vsw_cb_fn=self.ovs_vdp.vdp_vlan_change,
                                       vsw_cb_data=ovs_cb_data)]
        parent.assert_has_calls(expected_calls, any_order=False)

    def _test_vdp_port_event_down(self):
        '''Test the case for a vnic port down for a network '''
        port_uuid = '0000-1111-2222-3334'
        mac = '00:00:fa:11:22:34'
        net_uuid = '0000-aaaa-bbbb-cccc'
        segmentation_id = 10001
        status = 'down'
        oui = None
        with mock.patch('networking_cisco.apps.saf.common.'
                        'dfa_sys_lib.OVSBridge.delete_flows') as (del_flow), \
            mock.patch('networking_cisco.apps.saf.common.'
                       'dfa_sys_lib.OVSBridge.get_ofport_name',
                       return_value='test_port'), \
            mock.patch.object(self.ovs_vdp.lldpad_info,
                              'send_vdp_vnic_down') as vnic_down:
            self.ovs_vdp.local_vlan_map[net_uuid] = ovs_vdp.LocalVlan(10, (
                segmentation_id))
            lvm = self.ovs_vdp.local_vlan_map[net_uuid]
            lvm.lvid = 10
            lvm.port_uuid_list[port_uuid] = port_uuid
            self.ovs_vdp.local_vlan_map[net_uuid].late_binding_vlan = 500
            parent = mock.MagicMock()
            parent.attach_mock(vnic_down, 'send_vdp_vnic_down')
            parent.attach_mock(del_flow, 'delete_flows')
            self.ovs_vdp.send_vdp_port_event(port_uuid, mac, net_uuid,
                                             segmentation_id, status, oui)
        expected_calls = [mock.call.send_vdp_vnic_down(port_uuid=port_uuid,
                                                       vsiid=port_uuid,
                                                       gid=segmentation_id,
                                                       mac=mac, vlan=500,
                                                       oui=oui),
                          mock.call.delete_flows(
                              in_port=self.ovs_vdp.phy_peer_port_num,
                              dl_vlan=10),
                          mock.call.delete_flows(
                              in_port=self.ovs_vdp.int_peer_port_num,
                              dl_vlan=500)]
        parent.assert_has_calls(expected_calls, any_order=False)

    def test_vdp_port_event(self):
        '''
        Routine the calls the other new port and existing port test routines
        '''
        self._test_vdp_port_event_new()
        self._test_vdp_port_event_exist()

    def test_vdp_port_event_down(self):
        '''Routine the calls the port down test '''
        self._test_vdp_port_event_down()

    def test_vdp_port_event_down_valid_vlan(self):
        """Test the case for a vnic port down for a network.

        This is to test the case when there are more than one vNic for a
        network with a valid VLAN. Flows should not be removed.
        """
        status = 'down'
        with mock.patch('networking_cisco.apps.saf.common.'
                        'dfa_sys_lib.OVSBridge.delete_flows') as (del_flow), \
            mock.patch('networking_cisco.apps.saf.common.'
                       'dfa_sys_lib.OVSBridge.get_ofport_name',
                       return_value='test_port'), \
            mock.patch.object(self.ovs_vdp.lldpad_info,
                              'send_vdp_vnic_down') as vnic_down:
            self.ovs_vdp.local_vlan_map[self.net_uuid] = ovs_vdp.LocalVlan(
                self.lvid, self.segmentation_id)
            lvm = self.ovs_vdp.local_vlan_map[self.net_uuid]
            lvm.lvid = self.lvid
            lvm.set_port_uuid(self.port_uuid, self.exist_vdp_vlan, None)
            lvm.set_port_uuid(self.port_uuid_1, self.exist_vdp_vlan, None)
            self.ovs_vdp.local_vlan_map[
                self.net_uuid].late_binding_vlan = self.exist_vdp_vlan
            parent = mock.MagicMock()
            parent.attach_mock(vnic_down, 'send_vdp_vnic_down')
            parent.attach_mock(del_flow, 'delete_flows')
            self.ovs_vdp.send_vdp_port_event(
                self.port_uuid, self.mac, self.net_uuid,
                self.segmentation_id, status, self.oui)
        expected_calls = [mock.call.send_vdp_vnic_down(
            port_uuid=self.port_uuid, vsiid=self.port_uuid,
            gid=self.segmentation_id, mac=self.mac, vlan=self.exist_vdp_vlan,
            oui=self.oui)]
        parent.assert_has_calls(expected_calls, any_order=False)
        del_flow.assert_not_called()

    def test_vdp_port_event_down_no_valid_vlan(self):
        """Test the case for a vnic port down for a network with no valid vlan.

       This is to test the case when there are more than one vNic for a
        network with no valid VLAN. Flows should be removed.
        """
        status = 'down'
        with mock.patch('networking_cisco.apps.saf.common.'
                        'dfa_sys_lib.OVSBridge.delete_flows') as (del_flow), \
            mock.patch('networking_cisco.apps.saf.common.'
                       'dfa_sys_lib.OVSBridge.get_ofport_name',
                       return_value='test_port'), \
            mock.patch.object(self.ovs_vdp.lldpad_info,
                              'send_vdp_vnic_down') as vnic_down:
            self.ovs_vdp.local_vlan_map[self.net_uuid] = ovs_vdp.LocalVlan(
                self.lvid, self.segmentation_id)
            lvm = self.ovs_vdp.local_vlan_map[self.net_uuid]
            lvm.lvid = self.lvid
            lvm.set_port_uuid(self.port_uuid, self.exist_vdp_vlan, None)
            lvm.set_port_uuid(self.port_uuid_1, 0, None)
            self.ovs_vdp.local_vlan_map[
                self.net_uuid].late_binding_vlan = self.exist_vdp_vlan
            parent = mock.MagicMock()
            parent.attach_mock(vnic_down, 'send_vdp_vnic_down')
            parent.attach_mock(del_flow, 'delete_flows')
            self.ovs_vdp.send_vdp_port_event(
                self.port_uuid, self.mac, self.net_uuid,
                self.segmentation_id, status, self.oui)
        expected_calls = [
            mock.call.send_vdp_vnic_down(
                port_uuid=self.port_uuid, vsiid=self.port_uuid,
                gid=self.segmentation_id, mac=self.mac,
                vlan=self.exist_vdp_vlan, oui=self.oui),
            mock.call.delete_flows(in_port=self.ovs_vdp.phy_peer_port_num,
                                   dl_vlan=self.lvid),
            mock.call.delete_flows(in_port=self.ovs_vdp.int_peer_port_num,
                                   dl_vlan=self.exist_vdp_vlan)]
        parent.assert_has_calls(expected_calls, any_order=False)

    def test_vdp_port_event_down_mismatched_vlans(self):
        """Test the case for a vnic port down for a network with mismatch vlan.

        This is to test the case when there are more than one vNic for a
        network with mismatched VLAN's. Stale Flows should be removed and new
        flows should be added.
        """
        old_vdp_vlan = 3001
        status = 'down'
        with mock.patch('networking_cisco.apps.saf.common.'
                        'dfa_sys_lib.OVSBridge.delete_flows') as (del_flow), \
            mock.patch('networking_cisco.apps.saf.common.'
                       'dfa_sys_lib.OVSBridge.add_flow') as (add_flow), \
            mock.patch('networking_cisco.apps.saf.common.'
                       'dfa_sys_lib.OVSBridge.get_ofport_name',
                       return_value='test_port'), \
            mock.patch.object(self.ovs_vdp.lldpad_info,
                              'send_vdp_vnic_down') as vnic_down:
            self.ovs_vdp.local_vlan_map[self.net_uuid] = ovs_vdp.LocalVlan(
                self.lvid, self.segmentation_id)
            lvm = self.ovs_vdp.local_vlan_map[self.net_uuid]
            lvm.lvid = self.lvid
            lvm.set_port_uuid(self.port_uuid, self.exist_vdp_vlan, None)
            lvm.set_port_uuid(self.port_uuid_1, old_vdp_vlan, None)
            self.ovs_vdp.local_vlan_map[
                self.net_uuid].late_binding_vlan = self.exist_vdp_vlan
            parent = mock.MagicMock()
            parent.attach_mock(vnic_down, 'send_vdp_vnic_down')
            parent.attach_mock(del_flow, 'delete_flows')
            parent.attach_mock(add_flow, 'add_flow')
            self.ovs_vdp.send_vdp_port_event(
                self.port_uuid, self.mac, self.net_uuid,
                self.segmentation_id, status, self.oui)
        expected_calls = [
            mock.call.send_vdp_vnic_down(
                port_uuid=self.port_uuid, vsiid=self.port_uuid,
                gid=self.segmentation_id, mac=self.mac,
                vlan=self.exist_vdp_vlan, oui=self.oui),
            mock.call.delete_flows(in_port=self.ovs_vdp.phy_peer_port_num,
                                   dl_vlan=self.lvid),
            mock.call.delete_flows(in_port=self.ovs_vdp.int_peer_port_num,
                                   dl_vlan=self.exist_vdp_vlan),
            mock.call.add_flow(
                priority=4, in_port=self.ovs_vdp.phy_peer_port_num,
                dl_vlan=self.lvid,
                actions="mod_vlan_vid:%s,normal" % old_vdp_vlan),
            mock.call.add_flow(
                priority=3, in_port=self.ovs_vdp.int_peer_port_num,
                dl_vlan=old_vdp_vlan,
                actions="mod_vlan_vid:%s,normal" % self.lvid)]
        parent.assert_has_calls(expected_calls, any_order=False)

    def test_vdp_vlan_change_rem_add(self):
        """Testing the VDP VLAN change for a remove/add flow case. """
        new_vdp_vlan = 3006
        ovs_cb_data = {'port_uuid': self.port_uuid, 'net_uuid': self.net_uuid}
        with mock.patch('networking_cisco.apps.saf.common.'
                        'dfa_sys_lib.OVSBridge.delete_flows') as (ovs_br_del):
            parent = mock.MagicMock()
            parent.attach_mock(ovs_br_del, 'delete_flows')
            parent.attach_mock(self.ovs_br_add, 'add_flow')
            self.ovs_vdp.local_vlan_map[
                self.net_uuid] = ovs_vdp.LocalVlan(self.lvid,
                                                   self.segmentation_id)
            lvm = self.ovs_vdp.local_vlan_map[self.net_uuid]
            lvm.late_binding_vlan = self.exist_vdp_vlan
            lvm.set_port_uuid(self.port_uuid, self.exist_vdp_vlan, None)
            self.ovs_vdp.vdp_vlan_change(ovs_cb_data, new_vdp_vlan, None)
        expected_calls = [
            mock.call.delete_flows(
                in_port=self.ovs_vdp.phy_peer_port_num, dl_vlan=self.lvid),
            mock.call.delete_flows(
                in_port=self.ovs_vdp.int_peer_port_num,
                dl_vlan=self.exist_vdp_vlan),
            mock.call.add_flow(
                priority=4, in_port=self.ovs_vdp.phy_peer_port_num,
                dl_vlan=self.lvid,
                actions="mod_vlan_vid:%s,normal" % new_vdp_vlan),
            mock.call.add_flow(
                priority=3, in_port=self.ovs_vdp.int_peer_port_num,
                dl_vlan=new_vdp_vlan,
                actions="mod_vlan_vid:%s,normal" % self.lvid)]
        parent.assert_has_calls(expected_calls, any_order=False)

    def test_vdp_vlan_change_rem(self):
        """Testing the VDP VLAN change for a remove flow case. """
        new_vdp_vlan = 0
        ovs_cb_data = {'port_uuid': self.port_uuid, 'net_uuid': self.net_uuid}
        with mock.patch('networking_cisco.apps.saf.common.'
                        'dfa_sys_lib.OVSBridge.delete_flows') as (ovs_br_del):
            parent = mock.MagicMock()
            parent.reset_mock(self.ovs_br_add)
            parent.attach_mock(ovs_br_del, 'delete_flows')
            self.ovs_vdp.local_vlan_map[
                self.net_uuid] = ovs_vdp.LocalVlan(self.lvid,
                                                   self.segmentation_id)
            lvm = self.ovs_vdp.local_vlan_map[self.net_uuid]
            lvm.late_binding_vlan = self.exist_vdp_vlan
            lvm.set_port_uuid(self.port_uuid, self.exist_vdp_vlan, None)
            self.ovs_vdp.vdp_vlan_change(ovs_cb_data, new_vdp_vlan, None)
        expected_calls = [
            mock.call.delete_flows(
                in_port=self.ovs_vdp.phy_peer_port_num, dl_vlan=self.lvid),
            mock.call.delete_flows(
                in_port=self.ovs_vdp.int_peer_port_num,
                dl_vlan=self.exist_vdp_vlan)]
        parent.assert_has_calls(expected_calls, any_order=False)
        self.ovs_br_add.assert_not_called()

    def test_vdp_vlan_change_multiple_vnics_norem(self):
        """Testing the VDP VLAN change for multiple vnic's.

        This is for the case when there are multiple vNics for the same
        network and for one vNic a VDP VLAN of 0, is returned. So flow
        should not be deleted.
        """
        new_vdp_vlan = 0
        ovs_cb_data = {'port_uuid': self.port_uuid, 'net_uuid': self.net_uuid}
        with mock.patch('networking_cisco.apps.saf.common.'
                        'dfa_sys_lib.OVSBridge.add_flow') as (ovs_br_add), \
            mock.patch('networking_cisco.apps.saf.common.'
                       'dfa_sys_lib.OVSBridge.delete_flows') as (ovs_br_del):
            parent = mock.MagicMock()
            parent.attach_mock(ovs_br_del, 'delete_flows')
            parent.attach_mock(ovs_br_add, 'add_flow')
            self.ovs_vdp.local_vlan_map[
                self.net_uuid] = ovs_vdp.LocalVlan(self.lvid,
                                                   self.segmentation_id)
            lvm = self.ovs_vdp.local_vlan_map[self.net_uuid]
            lvm.late_binding_vlan = self.exist_vdp_vlan
            lvm.set_port_uuid(self.port_uuid, self.exist_vdp_vlan, None)
            lvm.set_port_uuid(self.port_uuid_1, self.exist_vdp_vlan, None)
            self.ovs_vdp.vdp_vlan_change(ovs_cb_data, new_vdp_vlan, None)
        ovs_br_add.assert_not_called()
        ovs_br_del.assert_not_called()

    def test_flow_check_handler_ext_flows_missing(self):
        """Testing the flow check handler for external bridge.

        Flow is missing for external bridge.
        """
        integ_flow = "NXST_FLOW reply (xid=0x4):\n" \
                     "cookie=0x0, duration=460654.804s, table=0, "\
                     "n_packets=3885, n_bytes=248632, idle_age=71, "\
                     "hard_age=65534, priority=3,in_port=1,dl_vlan=10 "\
                     "actions=mod_vlan_vid:3005,NORMAL\n" \
                     "cookie=0x9feb720beeec4ab9, duration=777857.315s, "\
                     "table=0, n_packets=32387, n_bytes=2186200, idle_age=4,"\
                     " hard_age=65534, priority=2,in_port=1 actions=drop"
        ext_flow = "NXST_FLOW reply (xid=0x4):"
        with mock.patch('networking_cisco.apps.saf.common.'
                        'dfa_sys_lib.OVSBridge.add_flow') as (ovs_br_add), \
            mock.patch.object(self.ovs_vdp.integ_br_obj, 'dump_flows_for',
                              return_value=integ_flow), \
            mock.patch.object(self.ovs_vdp.ext_br_obj, 'dump_flows_for',
                              return_value=ext_flow):
            parent = mock.MagicMock()
            parent.attach_mock(ovs_br_add, 'add_flow')
            self.ovs_vdp.local_vlan_map[
                self.net_uuid] = ovs_vdp.LocalVlan(self.lvid,
                                                   self.segmentation_id)
            lvm = self.ovs_vdp.local_vlan_map[self.net_uuid]
            lvm.late_binding_vlan = self.exist_vdp_vlan
            lvm.lvid = self.lvid
            lvm.set_port_uuid(self.port_uuid, self.exist_vdp_vlan, None)
            self.ovs_vdp._flow_check_handler()
        expected_calls = [
            mock.call.add_flow(
                priority=4, in_port=self.ovs_vdp.phy_peer_port_num,
                dl_vlan=self.lvid,
                actions="mod_vlan_vid:%s,normal" % self.exist_vdp_vlan),
            mock.call.add_flow(
                priority=3, in_port=self.ovs_vdp.int_peer_port_num,
                dl_vlan=self.exist_vdp_vlan,
                actions="mod_vlan_vid:%s,normal" % self.lvid)]
        parent.assert_has_calls(expected_calls, any_order=False)

    def test_flow_check_handler_integ_flows_missing(self):
        """Testing the flow check handler for integ bridge.

        Flow is missing for integration bridge.
        """
        ext_flow = "NXST_FLOW reply (xid=0x4):\n" \
                   "cookie=0x0, duration=460654.804s, table=0, "\
                   "n_packets=3885, n_bytes=248632, idle_age=71, "\
                   "hard_age=65534, priority=3,in_port=1,dl_vlan=3005 "\
                   "actions=mod_vlan_vid:10,NORMAL\n" \
                   "cookie=0x9feb720beeec4ab9, duration=777857.315s, "\
                   "table=0, n_packets=32387, n_bytes=2186200, idle_age=4,"\
                   " hard_age=65534, priority=2,in_port=1 actions=drop"
        integ_flow = "NXST_FLOW reply (xid=0x4):"
        with mock.patch('networking_cisco.apps.saf.common.'
                        'dfa_sys_lib.OVSBridge.add_flow') as (ovs_br_add), \
            mock.patch.object(self.ovs_vdp.integ_br_obj, 'dump_flows_for',
                              return_value=integ_flow), \
            mock.patch.object(self.ovs_vdp.ext_br_obj, 'dump_flows_for',
                              return_value=ext_flow):
            parent = mock.MagicMock()
            parent.attach_mock(ovs_br_add, 'add_flow')
            self.ovs_vdp.local_vlan_map[
                self.net_uuid] = ovs_vdp.LocalVlan(self.lvid,
                                                   self.segmentation_id)
            lvm = self.ovs_vdp.local_vlan_map[self.net_uuid]
            lvm.late_binding_vlan = self.exist_vdp_vlan
            lvm.lvid = self.lvid
            lvm.set_port_uuid(self.port_uuid, self.exist_vdp_vlan, None)
            self.ovs_vdp._flow_check_handler()
        expected_calls = [
            mock.call.add_flow(
                priority=4, in_port=self.ovs_vdp.phy_peer_port_num,
                dl_vlan=self.lvid,
                actions="mod_vlan_vid:%s,normal" % self.exist_vdp_vlan),
            mock.call.add_flow(
                priority=3, in_port=self.ovs_vdp.int_peer_port_num,
                dl_vlan=self.exist_vdp_vlan,
                actions="mod_vlan_vid:%s,normal" % self.lvid)]
        parent.assert_has_calls(expected_calls, any_order=False)

    def test_flow_check_handler_both_flows_missing(self):
        """Testing the flow check handler for both bridges.

        Flow is missing for both bridges.
        """
        ext_flow = "NXST_FLOW reply (xid=0x4):"
        integ_flow = "NXST_FLOW reply (xid=0x4):"
        with mock.patch('networking_cisco.apps.saf.common.'
                        'dfa_sys_lib.OVSBridge.add_flow') as (ovs_br_add), \
            mock.patch.object(self.ovs_vdp.integ_br_obj, 'dump_flows_for',
                              return_value=integ_flow), \
            mock.patch.object(self.ovs_vdp.ext_br_obj, 'dump_flows_for',
                              return_value=ext_flow):
            parent = mock.MagicMock()
            parent.attach_mock(ovs_br_add, 'add_flow')
            self.ovs_vdp.local_vlan_map[
                self.net_uuid] = ovs_vdp.LocalVlan(self.lvid,
                                                   self.segmentation_id)
            lvm = self.ovs_vdp.local_vlan_map[self.net_uuid]
            lvm.late_binding_vlan = self.exist_vdp_vlan
            lvm.lvid = self.lvid
            lvm.set_port_uuid(self.port_uuid, self.exist_vdp_vlan, None)
            self.ovs_vdp._flow_check_handler()
        expected_calls = [
            mock.call.add_flow(
                priority=4, in_port=self.ovs_vdp.phy_peer_port_num,
                dl_vlan=self.lvid,
                actions="mod_vlan_vid:%s,normal" % self.exist_vdp_vlan),
            mock.call.add_flow(
                priority=3, in_port=self.ovs_vdp.int_peer_port_num,
                dl_vlan=self.exist_vdp_vlan,
                actions="mod_vlan_vid:%s,normal" % self.lvid)]
        parent.assert_has_calls(expected_calls, any_order=False)

    def test_flow_check_handler_no_flows_missing(self):
        """Testing the flow check handler for both bridges.

        No flows are missing in both the bridges.
        """
        new_vdp_vlan = 3005
        ext_flow = "NXST_FLOW reply (xid=0x4):\n" \
                   "cookie=0x0, duration=460654.804s, table=0, "\
                   "n_packets=3885, n_bytes=248632, idle_age=71, "\
                   "hard_age=65534, priority=3,in_port=1,dl_vlan=10 "\
                   "actions=mod_vlan_vid:3005,NORMAL\n" \
                   "cookie=0x9feb720beeec4ab9, duration=777857.315s, "\
                   "table=0, n_packets=32387, n_bytes=2186200, idle_age=4,"\
                   " hard_age=65534, priority=2,in_port=1 actions=drop"
        integ_flow = "NXST_FLOW reply (xid=0x4):\n" \
                     "cookie=0x0, duration=460654.804s, table=0, "\
                     "n_packets=3885, n_bytes=248632, idle_age=71, "\
                     "hard_age=65534, priority=3,in_port=1,dl_vlan=3005 "\
                     "actions=mod_vlan_vid:10,NORMAL\n" \
                     "cookie=0x9feb720beeec4ab9, duration=777857.315s, "\
                     "table=0, n_packets=32387, n_bytes=2186200, idle_age=4,"\
                     " hard_age=65534, priority=2,in_port=1 actions=drop"
        with mock.patch('networking_cisco.apps.saf.common.'
                        'dfa_sys_lib.OVSBridge.add_flow') as (ovs_br_add), \
            mock.patch.object(self.ovs_vdp.integ_br_obj, 'dump_flows_for',
                              return_value=integ_flow), \
            mock.patch.object(self.ovs_vdp.ext_br_obj, 'dump_flows_for',
                              return_value=ext_flow):
            parent = mock.MagicMock()
            parent.attach_mock(ovs_br_add, 'add_flow')
            self.ovs_vdp.local_vlan_map[
                self.net_uuid] = ovs_vdp.LocalVlan(self.lvid,
                                                   self.segmentation_id)
            lvm = self.ovs_vdp.local_vlan_map[self.net_uuid]
            lvm.late_binding_vlan = new_vdp_vlan
            lvm.lvid = self.lvid
            lvm.set_port_uuid(self.port_uuid, new_vdp_vlan, None)
            self.ovs_vdp._flow_check_handler()
        ovs_br_add.assert_not_called()

    def test_populate_cache(self):
        """Test the populate cache function. """
        self.ovs_vdp.pop_local_cache(
            self.port_uuid, self.mac, self.net_uuid, self.lvid,
            self.exist_vdp_vlan, self.segmentation_id)
        rvlan = self.ovs_vdp.local_vlan_map[self.net_uuid].get_portid_vlan(
            self.port_uuid)
        fail_reason = self.ovs_vdp.local_vlan_map[
            self.net_uuid].get_portid_fail_reason(self.port_uuid)
        valid_vlan = self.ovs_vdp.local_vlan_map[
            self.net_uuid].any_valid_vlan()
        self.assertEqual(
            self.lvid, self.ovs_vdp.local_vlan_map[self.net_uuid].lvid)
        self.assertEqual(
            self.exist_vdp_vlan,
            self.ovs_vdp.local_vlan_map[self.net_uuid].late_binding_vlan)
        self.assertEqual(
            False, self.ovs_vdp.local_vlan_map[self.net_uuid].vdp_nego_req)
        self.assertEqual(self.exist_vdp_vlan, rvlan)
        self.assertIsNone(fail_reason)
        self.assertTrue(valid_vlan)


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ChainList = exports.ChainExists = exports.ChainStrictModeEnabled = exports.ChainCacheEnabled = exports.ExecuteChain = exports.ChainMiddleware = exports.Chain = exports.ChainAction = undefined;

var _Chain = require('./chain/Chain');

var _ChainSettings = require('./chain/ChainSettings');

var _ChainStorage = require('./chain/ChainStorage');

var _middleware = require('./middleware');

var _ChainExecuter = require('./chain/ChainExecuter');

var ChainAction = exports.ChainAction = _Chain.Action;
var Chain = exports.Chain = _Chain.Chain;
var ChainMiddleware = exports.ChainMiddleware = _middleware.ChainMiddleware;
var ExecuteChain = exports.ExecuteChain = _ChainExecuter.Execute;
var ChainCacheEnabled = exports.ChainCacheEnabled = _ChainSettings.CacheEnabled;
var ChainStrictModeEnabled = exports.ChainStrictModeEnabled = _ChainSettings.StrictModeEnabled;
var ChainExists = exports.ChainExists = _ChainStorage.exists;
var ChainList = exports.ChainList = _ChainStorage.getChains;

redpajama_set_name: RedPajamaGithub


text:
/**
 * @author mrdoob / http://mrdoob.com/
 */
/*
///BufferAttribute类用来存储于bufferGeometry相关联的属性数据,更多细节可以参考官方的样例http://threejs.org/
/// 这个类用来存储内置属性例如顶点位置,法线,颜色,等,但也可以用于存储bufferGeometry对象的自定义属性.
///BufferAttribute对象的功能函数采用定义构造的函数原型对象来实现.
/// TODO:增加一个基类setAttr(index,item,itemSize)根据跟多不同的属性相长度设置属性
///
*/
///BufferAttribute
///<param name ="array" type="Array">属性数组</param>
///<param name ="itemSize" type="number">属性相长度</param>
///<returns type="BufferAttribute">返回新的属性数组</returns>
THREE.BufferAttribute = function ( array, itemSize ) {

	this.array = array;		//BufferAttribute的array属性
	this.itemSize = itemSize;	//BufferAttribute的itemSize属性

};

/****************************************
****下面是BufferAttribute对象提供的功能函数.
****************************************/
THREE.BufferAttribute.prototype = {

	constructor: THREE.BufferAttribute,		//构造器,返回对创建此对象BufferAttribute函数的引用.

	/*
	///get length 方法用来获取BufferAttribute的数组长度
	///NOTE: get length()BufferAttribute.prototype.length(),这种用法在除ie浏览器以外的浏览器上可以使用.
	*/
	///get length
	///<returns type="number">返回BufferAttribute的数组长度</returns>
	get length () {

		return this.array.length;	//返回BufferAttribute的数组长度

	},

	/*
	///set方法用来重新设置BufferAttribute的属性数组
	*/
	///set
	///<param name ="value" type="Array">属性数组</param>
	///<returns type="BufferAttribute">返回新的BufferAttribute属性对象</returns>
	set: function ( value ) {

		this.array.set( value );

		return this;	//返回新的BufferAttribute属性对象

	},

	/*
	///setX方法用来重新设置含有3个属性相的BufferAttribute属性数组的第一个分量
	/// NOTE:setX方法中,属性数组的长度是属性相的长度乘以属性的个数.比如要存放100个点的坐标,坐标有3个属性相,那么属性数组的长度是300,如果想改变第30个点的x坐标就将index设为30
	*/
	///setX
	///<param name ="index" type="Number">属性数组的索引</param>
	///<param name ="x" type="Number">属性数组的第一个分量</param>
	///<returns type="BufferAttribute">返回新的BufferAttribute属性对象</returns>
	setX: function ( index, x ) {

		this.array[ index * this.itemSize ] = x;

		return this;	//返回新的BufferAttribute属性对象

	},

	/*
	///setY方法用来重新设置含有3个属性相的BufferAttribute属性数组的第二个分量
	/// NOTE:setY方法中,属性数组的长度是属性相的长度乘以属性的个数.比如要存放100个点的坐标,坐标有3个属性相,那么属性数组的长度是300,如果想改变第30个点的Y坐标就将index设为30
	*/
	///setY
	///<param name ="index" type="Number">属性数组的索引</param>
	///<param name ="y" type="Number">属性数组的第一个分量</param>
	///<returns type="BufferAttribute">返回新的BufferAttribute属性对象</returns>
	setY: function ( index, y ) {

		this.array[ index * this.itemSize + 1 ] = y;

		return this;	//返回新的BufferAttribute属性对象

	},

	/*
	///setZ方法用来重新设置含有3个属性相的BufferAttribute属性数组的第三个分量
	/// NOTE:setY方法中,属性数组的长度是属性相的长度乘以属性的个数.比如要存放100个点的坐标,坐标有3个属性相,那么属性数组的长度是300,如果想改变第30个点的Z坐标就将index设为30
	*/
	///setZ
	///<param name ="index" type="Number">属性数组的索引</param>
	///<param name ="z" type="Number">属性数组的第一个分量</param>
	///<returns type="BufferAttribute">返回新的BufferAttribute属性对象</returns>
	setZ: function ( index, z ) {

		this.array[ index * this.itemSize + 2 ] = z;

		return this;	//返回新的BufferAttribute属性对象

	},

	/*
	///setXY方法用来重新设置含有3个属性相的BufferAttribute属性数组的第一个和第二个分量
	/// NOTE:setXY方法中,属性数组的长度是属性相的长度乘以属性的个数.比如要存放100个点的坐标,坐标有3个属性相,那么属性数组的长度是300,如果想改变第30个点的x,y坐标就将index设为30
	*/
	///setXY
	///<param name ="index" type="Number">属性数组的索引</param>
	///<param name ="x" type="Number">属性数组的第一个分量</param>
	///<param name ="y" type="Number">属性数组的第二个分量</param>
	///<returns type="BufferAttribute">返回新的BufferAttribute属性对象</returns>
	setXY: function ( index, x, y ) {

		index *= this.itemSize;

		this.array[ index     ] = x;
		this.array[ index + 1 ] = y;

		return this;	//返回新的BufferAttribute属性对象

	},

	/*
	///setXYZ方法用来重新设置含有3个属性相的BufferAttribute属性数组的第一个,第二个和第三个分量
	/// NOTE:setXY方法中,属性数组的长度是属性相的长度乘以属性的个数.比如要存放100个点的坐标,坐标有3个属性相,那么属性数组的长度是300,如果想改变第30个点的x,y,z坐标就将index设为30
	*/
	///setXYZ
	///<param name ="index" type="Number">属性数组的索引</param>
	///<param name ="x" type="Number">属性数组的第一个分量</param>
	///<param name ="y" type="Number">属性数组的第二个分量</param>
	///<param name ="z" type="Number">属性数组的第三个分量</param>
	///<returns type="BufferAttribute">返回新的BufferAttribute属性对象</returns>
	setXYZ: function ( index, x, y, z ) {

		index *= this.itemSize;

		this.array[ index     ] = x;
		this.array[ index + 1 ] = y;
		this.array[ index + 2 ] = z;

		return this;	//返回新的BufferAttribute属性对象

	},

	/*
	///setXYZW方法用来重新设置含有3个属性相的BufferAttribute属性数组的第一个,第二个和第三个,第四个分量
	/// NOTE:setXYZW方法中,属性数组的长度是属性相的长度乘以属性的个数.比如要存放100个点的坐标,坐标有4个属性相,那么属性数组的长度是400,如果想改变第30个点的x,y,z,w坐标就将index设为30
	*/
	///setXYZW
	///<param name ="index" type="Number">属性数组的索引</param>
	///<param name ="x" type="Number">属性数组的第一个分量</param>
	///<param name ="y" type="Number">属性数组的第二个分量</param>
	///<param name ="z" type="Number">属性数组的第三个分量</param>
	///<param name ="w" type="Number">属性数组的第四个分量</param>
	///<returns type="BufferAttribute">返回新的BufferAttribute属性对象</returns>
	setXYZW: function ( index, x, y, z, w ) {

		index *= this.itemSize;

		this.array[ index     ] = x;
		this.array[ index + 1 ] = y;
		this.array[ index + 2 ] = z;
		this.array[ index + 3 ] = w;

		return this;	//返回新的BufferAttribute属性对象

	}

};

/**********************************************************************************
****下面这些方法是定义不同数据类型的属性,已经在新版本中删除,这里保留是为了向后兼容.
***********************************************************************************/
THREE.Int8Attribute = function ( data, itemSize ) {

	console.warn( 'THREE.Int8Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
	return new THREE.BufferAttribute( data, itemSize );

};

THREE.Uint8Attribute = function ( data, itemSize ) {

	console.warn( 'THREE.Uint8Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
	return new THREE.BufferAttribute( data, itemSize );

};

THREE.Uint8ClampedAttribute = function ( data, itemSize ) {

	console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
	return new THREE.BufferAttribute( data, itemSize );

};

THREE.Int16Attribute = function ( data, itemSize ) {

	console.warn( 'THREE.Int16Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
	return new THREE.BufferAttribute( data, itemSize );

};

THREE.Uint16Attribute = function ( data, itemSize ) {

	console.warn( 'THREE.Uint16Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
	return new THREE.BufferAttribute( data, itemSize );

};

THREE.Int32Attribute = function ( data, itemSize ) {

	console.warn( 'THREE.Int32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
	return new THREE.BufferAttribute( data, itemSize );

};

THREE.Uint32Attribute = function ( data, itemSize ) {

	console.warn( 'THREE.Uint32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
	return new THREE.BufferAttribute( data, itemSize );

};

THREE.Float32Attribute = function ( data, itemSize ) {

	console.warn( 'THREE.Float32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
	return new THREE.BufferAttribute( data, itemSize );

};

THREE.Float64Attribute = function ( data, itemSize ) {

	console.warn( 'THREE.Float64Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
	return new THREE.BufferAttribute( data, itemSize );

};


text:
package com.google.javascript.refactoring;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.javascript.jscomp.Compiler;
import com.google.javascript.jscomp.CompilerOptions;
import com.google.javascript.jscomp.SourceFile;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.util.List;

/**
 * Unit tests for {RefasterJsScanner}.
 *
 * The RefasterJsScanner must be initialized with the compiler used to compile the
 * test code so that the types from the template and the test code match.
 * Therefore, it is important to compile the test code first before creating the
 * scanner, and to reuse the same compiler object for both the test code and the
 * scanner.
 *
 * @author mknichel@google.com (Mark Knichel)
 */
// TODO(mknichel): Make this a SmallTest by disabling threads in the JS Compiler.

@RunWith(JUnit4.class)
public class RefasterJsScannerTest {

  @Test
  public void testInitialize_missingTemplates() throws Exception {
    try {
      Compiler compiler = createCompiler();
      compileTestCode(compiler, "", "");
      createScanner(compiler, "");
      fail("An exception should have been thrown for missing templates.");
    } catch (IllegalStateException expected) {}

    try {
      Compiler compiler = createCompiler();
      compileTestCode(compiler, "", "");
      createScanner(compiler, "function notATemplate() {}");
      fail("An exception should have been thrown for missing templates.");
    } catch (IllegalStateException expected) {}

    try {
      Compiler compiler = createCompiler();
      compileTestCode(compiler, "", "");
      createScanner(compiler, "function after_foo() {}");
      fail("An exception should have been thrown for missing templates.");
    } catch (IllegalStateException expected) {}
  }

  @Test
  public void testInitialize_missingAfterTemplate() throws Exception {
    try {
      Compiler compiler = createCompiler();
      compileTestCode(compiler, "", "");
      createScanner(compiler, "function before_foo() {'bar'};");
      fail("An exception should have been thrown for missing the after template.");
    } catch (IllegalStateException expected) {}
  }

  @Test
  public void testInitialize_duplicateTemplateName() throws Exception {
    try {
      Compiler compiler = createCompiler();
      compileTestCode(compiler, "", "");
      createScanner(compiler, "function before_foo() {}; function before_foo() {};");
      fail("RefasterJS templates are not allowed to have the same name.");
    } catch (IllegalStateException expected) {}
  }

  @Test
  public void testInitialize_emptyBeforeTemplates() throws Exception {
    try {
      Compiler compiler = createCompiler();
      compileTestCode(compiler, "", "");
      createScanner(compiler, "function before_foo() {}; function after_foo() {};");
      fail("RefasterJS templates are not allowed to be empty!.");
    } catch (IllegalStateException expected) {}
  }

  @Test
  public void testInitialize_success() throws Exception {
    Compiler compiler = createCompiler();
    compileTestCode(compiler, "", "");
    createScanner(compiler, "function before_foo() {'str';}; function after_foo() {};");
  }

  @Test
  public void test_simple() throws Exception {
    String originalCode = "var loc = 'str';";
    String expectedCode = "'bar';";
    String template = ""
        + "function before_foo() {\n"
        + "  var a = 'str';\n"
        + "};\n"
        + "function after_foo() {\n"
        + "  'bar';\n"
        + "}\n";
    assertChanges("", originalCode, expectedCode, template);
  }

  @Test
  public void test_semicolonCorrect() throws Exception {
    String externs = ""
        + "/** @constructor */\n"
        + "function Location() {};\n"
        + "/** @type {string} */\n"
        + "Location.prototype.href;\n"
        + "function foo() {}\n"
        + "/** @type {Location} */ var loc;";
    String originalCode = "loc.href = 'str';";
    String expectedCode = "foo();";
    String template = ""
        + "/** @param {Location} loc */"
        + "function before_foo(loc) {\n"
        + "  loc.href = 'str';\n"
        + "};\n"
        + "function after_foo() {\n"
        + "  foo();\n"
        + "}\n";
    assertChanges(externs, originalCode, expectedCode, template);
  }

  @Test
  public void test_withTypes() throws Exception {
    String externs = ""
        + "/** @constructor */\n"
        + "function FooType() {}\n"
        + "FooType.prototype.bar = function() {};\n"
        + "/** @type {FooType} */ var obj;";
    String originalCode = "obj.bar();";
    String expectedCode = "obj.baz();";
    String template = ""
        + "/**\n"
        + " * @param {FooType} foo\n"
        + " */\n"
        + "function before_foo(foo) {\n"
        + "  foo.bar();\n"
        + "};\n"
        + "/**\n"
        + " * @param {FooType} foo\n"
        + " */\n"
        + "function after_foo(foo) {\n"
        + "  foo.baz();\n"
        + "}\n";
    assertChanges(externs, originalCode, expectedCode, template);
  }

  @Test
  public void test_multiLines() throws Exception {
    String externs = ""
        + "/** @constructor */\n"
        + "function FooType() {}\n"
        + "FooType.prototype.bar = function() {};\n"
        + "FooType.prototype.baz = function() {};";
    String preamble = "var obj = new FooType();\n";
    String postamble = "var someOtherCode = 3;\n";
    String originalCode = ""
        + preamble
        + "obj.bar();\n"
        + "obj.baz();\n"
        + postamble;
    String expectedCode = preamble + postamble;
    String template = ""
        + "/**\n"
        + " * @param {FooType} foo\n"
        + " */\n"
        + "function before_foo(foo) {\n"
        + "  foo.bar();\n"
        + "  foo.baz();\n"
        + "};\n"
        + "/**\n"
        + " * @param {FooType} foo\n"
        + " */\n"
        + "function after_foo(foo) {\n"
        + "}\n";
    assertChanges(externs, originalCode, expectedCode, template);
  }

  @Test
  public void test_replaceFunctionArgument() throws Exception {
    String externs = ""
        + "/** @constructor */\n"
        + "function MyClass() {};\n"
        + "MyClass.prototype.foo = function() {};\n"
        + "MyClass.prototype.bar = function() {};\n"
        + "/** @type {MyClass} */ var clazz;";
    String originalCode = "alert(clazz.foo());";
    String expectedCode = "alert(clazz.bar());";
    String template = ""
        + "/** @param {MyClass} clazz */"
        + "function before_foo(clazz) {\n"
        + "  clazz.foo();\n"
        + "};\n"
        + "/** @param {MyClass} clazz */"
        + "function after_foo(clazz) {\n"
        + "  clazz.bar();\n"
        + "}\n";
    assertChanges(externs, originalCode, expectedCode, template);
  }

  @Test
  public void test_replaceLeftHandSideOfAssignment() throws Exception {
    String externs = ""
        + "/** @constructor */\n"
        + "function MyClass() {};\n";
    String originalCode = "MyClass.prototype.foo = function() {};\n";
    String expectedCode = "MyClass.prototype.bar = function() {};\n";
    String template = ""
        + "function before_foo() {\n"
        + "  MyClass.prototype.foo\n"
        + "};\n"
        + "function after_foo() {\n"
        + "  MyClass.prototype.bar\n"
        + "}\n";
    assertChanges(externs, originalCode, expectedCode, template);
  }

  @Test
  public void test_replaceRightHandSideOfAssignment() throws Exception {
    String externs = ""
        + "/** @constructor */\n"
        + "function MyClass() {};\n"
        + "MyClass.prototype.foo = function() {};\n"
        + "MyClass.prototype.bar = function() {};\n";
    String originalCode = "var x = MyClass.prototype.foo;";
    String expectedCode = "var x = MyClass.prototype.bar;";
    String template = ""
        + "function before_foo() {\n"
        + "  MyClass.prototype.foo\n"
        + "};\n"
        + "function after_foo() {\n"
        + "  MyClass.prototype.bar\n"
        + "}\n";
    assertChanges(externs, originalCode, expectedCode, template);
  }

  @Test
  public void test_doesNotAddSpuriousNewline() throws Exception {
    String externs = ""
        + "/** @constructor */\n"
        + "function MyClass() {};\n"
        + "MyClass.prototype.foo = function() {};\n"
        + "MyClass.prototype.bar = function() {};\n"
        + "/** @type {MyClass} */ var clazz;\n";
    String originalCode = "clazz.foo();";
    String expectedCode = "clazz.bar();";
    String template = ""
        + "/** @param {MyClass} clazz */"
        + "function before_foo(clazz) {\n"
        + "  clazz.foo();\n"
        + "};\n"
        + "/** @param {MyClass} clazz */"
        + "function after_foo(clazz) {\n"
        + "  clazz.bar();\n"
        + "}\n";
    assertChanges(externs, originalCode, expectedCode, template);
  }

  @Test
  public void test_throwStatements() throws Exception {
    String externs = "";
    String originalCode = "throw Error('foo');";
    String expectedCode = "throw getError();";
    String template = ""
        + "/** @param {string} msg */\n"
        + "function before_template(msg) {\n"
        + "  throw Error(msg);\n"
        + "}\n"
        + "/** @param {string} msg */\n"
        + "function after_template(msg) {\n"
        + "  throw getError();\n"
        + "}\n";
    assertChanges(externs, originalCode, expectedCode, template);

    originalCode = "function f() {throw Error('foo');}";
    expectedCode = "function f() {throw getError();}";
    assertChanges(externs, originalCode, expectedCode, template);

    originalCode = ""
        + "if (true) {\n"
        + "  throw Error('foo');\n"
        + "}";
    expectedCode = ""
        + "if (true) {\n"
        + "  throw getError();\n"
        + "}";
    assertChanges(externs, originalCode, expectedCode, template);
}

  @Test
  public void test_whileStatements() throws Exception {
    String externs = "/** @return {string} */ function getFoo() {return 'foo';}";
    String originalCode = "while(getFoo()) {}";
    String expectedCode = "while(getBar()) {}";
    String template = ""
        + "function before_template() {\n"
        + "  getFoo();\n"
        + "}\n"
        + "function after_template() {\n"
        + "  getBar();\n"
        + "}\n";
    assertChanges(externs, originalCode, expectedCode, template);
  }

  @Test
  public void test_doWhileStatements() throws Exception {
    String externs = "/** @return {string} */ function getFoo() {return 'foo';}";
    String originalCode = "do {} while(getFoo());";
    String expectedCode = "do {} while(getBar());";
    String template = ""
        + "function before_template() {\n"
        + "  getFoo();\n"
        + "}\n"
        + "function after_template() {\n"
        + "  getBar();\n"
        + "}\n";
    assertChanges(externs, originalCode, expectedCode, template);
  }

  @Test
  public void test_returnStatement() throws Exception {
    String externs = "/** @return {string} */ function getFoo() {return 'foo';}";
    String originalCode = "function() { return getFoo(); }";
    String expectedCode = "function() { return getBar(); }";
    String template = ""
        + "function before_template() {\n"
        + "  getFoo();\n"
        + "}\n"
        + "function after_template() {\n"
        + "  getBar();\n"
        + "}\n";
    assertChanges(externs, originalCode, expectedCode, template);

    originalCode = "function() { return getFoo() == 'foo'; }";
    expectedCode = "function() { return getBar() == 'foo'; }";
    assertChanges(externs, originalCode, expectedCode, template);
  }

  @Test
  public void test_switchStatement() throws Exception {
    String externs = "/** @return {string} */ function getFoo() {return 'foo';}";
    String originalCode = ""
        + "switch(getFoo()) {\n"
        + "  default:\n"
        + "    break;\n"
        + "}";
    String expectedCode = ""
        + "switch(getBar()) {\n"
        + "  default:\n"
        + "    break;\n"
        + "}";
    String template = ""
        + "function before_template() {\n"
        + "  getFoo();\n"
        + "}\n"
        + "function after_template() {\n"
        + "  getBar();\n"
        + "}\n";
    assertChanges(externs, originalCode, expectedCode, template);
  }

  @Test
  public void test_caseStatement() throws Exception {
    String externs = ""
        + "var str = 'foo';\n"
        + "var CONSTANT = 'bar';\n";
    String originalCode = ""
        + "switch(str) {\n"
        + "  case CONSTANT:\n"
        + "    break;\n"
        + "}";
    String expectedCode = ""
        + "switch(str) {\n"
        + "  case getValue():\n"
        + "    break;\n"
        + "}";
    String template = ""
        + "function before_template() {\n"
        + "  CONSTANT\n"
        + "}\n"
        + "function after_template() {\n"
        + "  getValue()\n"
        + "}\n";
    assertChanges(externs, originalCode, expectedCode, template);
  }

  @Test
  public void test_forStatement() throws Exception {
    String externs = ""
        + "var obj = {};\n"
        + "obj.prop = 6;"
        + "var CONSTANT = 3;\n";
    String originalCode = "for (var i = CONSTANT; i < 5; i++) {}";
    String expectedCode = "for (var i = CONSTANT2; i < 5; i++) {}";
    String template = ""
        + "function before_template() {\n"
        + "  CONSTANT\n"
        + "}\n"
        + "function after_template() {\n"
        + "  CONSTANT2\n"
        + "}\n";
    assertChanges(externs, originalCode, expectedCode, template);

    originalCode = "for (var i = 0; i < CONSTANT; i++) {}";
    expectedCode = "for (var i = 0; i < CONSTANT2; i++) {}";
    assertChanges(externs, originalCode, expectedCode, template);

    originalCode = "for (var i = 0; i < CONSTANT; i++) {}";
    expectedCode = "for (var i = 0; i < obj.prop; i++) {}";
    template = ""
        + "function before_template() {\n"
        + "  CONSTANT\n"
        + "}\n"
        + "function after_template() {\n"
        + "  obj.prop\n"
        + "}\n";
    assertChanges(externs, originalCode, expectedCode, template);

    originalCode = "for (var prop in obj) {}";
    expectedCode = "for (var prop in getObj()) {}";
    template = ""
        + "function before_template() {\n"
        + "  obj\n"
        + "}\n"
        + "function after_template() {\n"
        + "  getObj()\n"
        + "}\n";
    assertChanges(externs, originalCode, expectedCode, template);
  }

  @Test
  public void test_comparisons() throws Exception {
    String externs = ""
        + "var obj = {};\n"
        + "obj.prop = 5;";
    String originalCode = "if (obj.prop == 5) {}";
    String expectedCode = "if (3 == 5) {}";
    String template = ""
        + "function before_template() {\n"
        + "  obj.prop;\n"
        + "}\n"
        + "function after_template() {\n"
        + "  3;\n"
        + "}\n";
    assertChanges(externs, originalCode, expectedCode, template);
  }

  @Test
  public void test_arrayAccess() throws Exception {
    String externs = ""
        + "var arr = [];\n"
        + "var i = 0;\n"
        + "/** @return {number} */ function getNewIndex() {}";
    String originalCode = "arr[i];";
    String expectedCode = "arr[getNewIndex()];";
    String template = ""
        + "function before_template() {\n"
        + "  i;\n"
        + "}\n"
        + "function after_template() {\n"
        + "  getNewIndex();\n"
        + "}\n";
    assertChanges(externs, originalCode, expectedCode, template);
  }

  @Test
  public void test_functionCalls() throws Exception {
    // Assigning the function as a property of an object is important to this test since it
    // tracks a corner case in the TemplateAstMatcher code.
    String externs = "var foo = {}; /** @return {number} */ foo.someFn = function() {}";
    String originalCode = "foo.someFn();";
    String expectedCode = "foo.someFn().someOtherFn();";
    String template = ""
        + "/** @param {function():number} fn */\n"
        + "function before_template(fn) {\n"
        + "  fn();\n"
        + "}\n"
        + "/** @param {function():number} fn */\n"
        + "function after_template(fn) {\n"
        + "  fn().someOtherFn();\n"
        + "}\n";
    assertChanges(externs, originalCode, expectedCode, template);
  }

  @Test
  public void test_strictSubtypeMatching() throws Exception {
    String externs = ""
        + "/** @constructor */\n"
        + "function T() {};\n"
        + "/** @type {string} */\n"
        + "T.prototype.p;\n"
        + "/** @constructor @extends {T} */\n"
        + "function S() {};\n"
        + "/** @param {!T} someT */\n"
        + "function setP(someT) {};\n";
    String template = ""
        + "/** @param {!T} t */\n"
        + "function before_template(t) {\n"
        + "  t.p = 'foo';\n"
        + "}\n"
        + "/** @param {!T} t */\n"
        + "function after_template(t) {\n"
        + "  setP(t);\n"
        + "}\n";
    String originalCode = "theT.p = 'foo';";
    String expectedCode = "setP(theT);";

    // {!T} matches {!T}
    assertChanges(
        externs + "/** @type {!T} */ var theT;",
        originalCode,
        expectedCode,
        template);

    // {?T} in the code does not match {!T} in the template.
    assertChanges(
        externs + "/** @type {?T} */ var theT;",
        originalCode,
        null, // No changes.
        template);

    // {unknown} does not match {!T}
    assertChanges(
        externs + "var theT;",
        originalCode,
        null, // No changes.
        template);

    // {!S} matches {!T}
    assertChanges(
        externs + "/** @type {!S} */ var theT;",
        originalCode,
        expectedCode,
        template);

    // {?S} does not match {!T}
    assertChanges(
        externs + "/** @type {?S} */ var theT;",
        originalCode,
        null, // No changes.
        template);
  }

  @Test
  public void test_templatesEvaluatedInOrder() throws Exception {
    String externs = ""
        + "/** @constructor */\n"
        + "function T() {};\n"
        + "/** @type {string} */\n"
        + "T.prototype.p;\n"
        + "/** @constructor @extends {T} */\n"
        + "function S() {};\n"
        + "/** @param {!T} someT */\n"
        + "function setP(someT) {};\n"
        + "/** @param {!S} someS */\n"
        + "function setPonS(someS) {};\n"
        + "/** @type {!T} */ var theT;"
        + "/** @type {!S} */ var theS;";
    String template = ""
        + "/** @param {!S} s */\n"
        + "function before_template_S(s) {\n"
        + "  s.p = 'foo';\n"
        + "}\n"
        + "/** @param {!S} s */\n"
        + "function after_template_S(t) {\n"
        + "  setPonS(s);\n"
        + "}\n"
        + "\n"
        + "/** @param {!T} t */\n"
        + "function before_template_T(t) {\n"
        + "  t.p = 'foo';\n"
        + "}\n"
        + "/** @param {!T} t */\n"
        + "function after_template_T(t) {\n"
        + "  setP(t);\n"
        + "}\n";
    String originalCode = "theT.p = 'foo'; theS.p = 'foo';";
    // Templates are evaluated in order:
    //  - theT.p does not match before_template_S but matches before_template_T
    //  - theS.p would match either template (see {@link #test_strictSubtypeMatching}),
    //    but since before_template_S comes first it takes precedence.
    String expectedCode = "setP(theT); setPonS(theS);";
    assertChanges(externs, originalCode, expectedCode, template);
  }

  private Compiler createCompiler() {
    return new Compiler();
  }

  private RefasterJsScanner createScanner(Compiler compiler, String template) throws Exception {
    RefasterJsScanner scanner = new RefasterJsScanner();
    scanner.loadRefasterJsTemplateFromCode(template);
    scanner.initialize(compiler);
    return scanner;
  }

  private void compileTestCode(Compiler compiler, String testCode, String externs) {
    CompilerOptions options = RefactoringDriver.getCompilerOptions();
    compiler.compile(
        ImmutableList.of(SourceFile.fromCode("externs", externs)),
        ImmutableList.of(SourceFile.fromCode("test", testCode)),
        options);
  }

  private void assertChanges(
      String externs, String originalCode, String expectedCode, String refasterJsTemplate)
      throws Exception {
    RefasterJsScanner scanner = new RefasterJsScanner();
    scanner.loadRefasterJsTemplateFromCode(refasterJsTemplate);

    RefactoringDriver driver = new RefactoringDriver.Builder(scanner)
        .addExternsFromCode(externs)
        .addInputsFromCode(originalCode)
        .build();
    List<SuggestedFix> fixes = driver.drive();
    String newCode = ApplySuggestedFixes.applySuggestedFixesToCode(
        fixes, ImmutableMap.of("input", originalCode)).get("input");
    assertEquals(expectedCode, newCode);
  }
}


text:
postgres extension with fun

![](http://img1.wikia.nocookie.net/__cb20091210033559/disney/images/7/76/Dumbo-HQ.JPG)

## Installation

Add this line to your application's Gemfile:

    gem 'dumbo'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install dumbo

## Getting Started

At the command prompt, create a new extension:

  dumbo new myextention

where "myextention" is the extension name.

Change directory to myextention to start hacking:

    cd myapp

As a stating point take a look at the sample function in

    sql/sample.sql

and the corresponding test file

    spec/sample_spec.rb

build the extension and run the specs

    rake

if you start working on a new version run

    rake dumbo:new_version [level]

where level is new version level (major, minor patch)

when you are done you can create the migration files with

    rake dumbo:migrations

## Contributing

1. Fork it ( http://github.com/adeven/dumbo/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>D-Index</title>
<meta name="date" content="2016-11-17">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I J K L M N O P Q R S T U V W

D

date - Variable in class de.qaware.chronix.client.benchmark.resultpresenter.TimeSeriesStatistics

dbName - Variable in class InfluxDB

dbName - Variable in class KairosDB

dbName - Variable in class OpenTsdbInterface

de.qaware.chronix.client - package de.qaware.chronix.client

de.qaware.chronix.client.benchmark - package de.qaware.chronix.client.benchmark

de.qaware.chronix.client.benchmark.benchmarkrunner - package de.qaware.chronix.client.benchmark.benchmarkrunner

de.qaware.chronix.client.benchmark.benchmarkrunner.util - package de.qaware.chronix.client.benchmark.benchmarkrunner.util

de.qaware.chronix.client.benchmark.configurator - package de.qaware.chronix.client.benchmark.configurator

de.qaware.chronix.client.benchmark.configurator.util - package de.qaware.chronix.client.benchmark.configurator.util

de.qaware.chronix.client.benchmark.queryhandler - package de.qaware.chronix.client.benchmark.queryhandler

de.qaware.chronix.client.benchmark.resultpresenter - package de.qaware.chronix.client.benchmark.resultpresenter

de.qaware.chronix.client.benchmark.resultpresenter.plot - package de.qaware.chronix.client.benchmark.resultpresenter.plot

de.qaware.chronix.client.benchmark.util - package de.qaware.chronix.client.benchmark.util

de.qaware.chronix.common.DataModels - package de.qaware.chronix.common.DataModels

de.qaware.chronix.common.dockerUtil - package de.qaware.chronix.common.dockerUtil

de.qaware.chronix.common.math - package de.qaware.chronix.common.math

de.qaware.chronix.common.QueryUtil - package de.qaware.chronix.common.QueryUtil

de.qaware.chronix.common.ServerConfig - package de.qaware.chronix.common.ServerConfig

de.qaware.chronix.database - package de.qaware.chronix.database

de.qaware.chronix.database.util - package de.qaware.chronix.database.util

de.qaware.chronix.server - package de.qaware.chronix.server

de.qaware.chronix.server.benchmark.collector - package de.qaware.chronix.server.benchmark.collector

de.qaware.chronix.server.benchmark.configurator - package de.qaware.chronix.server.benchmark.configurator

de.qaware.chronix.server.benchmark.queryrunner - package de.qaware.chronix.server.benchmark.queryrunner

de.qaware.chronix.server.util - package de.qaware.chronix.server.util

DEFAULT_BATCH_SIZE_LIMIT - Static variable in class OpenTsdb

deleteBenchmarkRecords() - Method in class de.qaware.chronix.server.benchmark.collector.StatsCollector

deleteBenchmarkRecords() - Method in class de.qaware.chronix.server.benchmark.collector.StatsCollectorResource

deleteBenchmarkRecordsOnServer(String) - Method in class de.qaware.chronix.client.benchmark.benchmarkrunner.BenchmarkRunner

Deletes the benchmark records on given server.

deleteBenchmarkTimeSeriesMetaDataJson() - Method in class de.qaware.chronix.common.QueryUtil.JsonTimeSeriesHandler

deleteContainer(List<String>) - Static method in class de.qaware.chronix.server.util.DockerCommandLineUtil

Delete container with given container id

deleteDirectory(Path) - Static method in class de.qaware.chronix.server.util.ServerSystemUtil

deleteTimeSeriesMetaDataJsonFile(String) - Method in class de.qaware.chronix.common.QueryUtil.JsonTimeSeriesHandler

Deletes the previously saved meta data for a given measurement name.

dimensionsSet - Variable in class OpenTsdbInterface

dirPath - Variable in class de.qaware.chronix.common.QueryUtil.JsonTimeSeriesHandler.TimesSeriesWriter

diskUsage - Variable in class de.qaware.chronix.common.QueryUtil.BenchmarkRecord

diskUsageTotal - Variable in class de.qaware.chronix.common.QueryUtil.BenchmarkRecord

doBenchmarkQuery(String, List<String>) - Method in class de.qaware.chronix.client.benchmark.benchmarkrunner.BenchmarkRunner

This method is used to actually benchmark the given TSDBs on a given server.

doBenchmarkRecordsAnalysis() - Method in class de.qaware.chronix.client.benchmark.resultpresenter.ResultPresenter

Analyzes and prints the benchmark records download from benchmark server.

DOCKER_STATS_REACTION_MILLISECONDS - Variable in class de.qaware.chronix.server.util.DockerStatsUtil

DockerBuild - Class in de.qaware.chronix.client.benchmark.util

Created by mcqueen666 on 07.10.16.

DockerBuild() - Constructor for class de.qaware.chronix.client.benchmark.util.DockerBuild

DockerBuildOptions - Class in de.qaware.chronix.common.dockerUtil

Created by mcqueen666 on 03.08.16.

DockerBuildOptions() - Constructor for class de.qaware.chronix.common.dockerUtil.DockerBuildOptions

DockerBuildOptions(String, String) - Constructor for class de.qaware.chronix.common.dockerUtil.DockerBuildOptions

DockerCommandLineUtil - Class in de.qaware.chronix.server.util

Created by mcqueen666 on 21.06.16.

DockerCommandLineUtil() - Constructor for class de.qaware.chronix.server.util.DockerCommandLineUtil

DockerRunOptions - Class in de.qaware.chronix.common.dockerUtil

Created by mcqueen666 on 03.08.16.

DockerRunOptions() - Constructor for class de.qaware.chronix.common.dockerUtil.DockerRunOptions

DockerRunOptions(String, int, int, String) - Constructor for class de.qaware.chronix.common.dockerUtil.DockerRunOptions

DockerStart - Class in de.qaware.chronix.client.benchmark.util

Created by mcqueen666 on 07.10.16.

DockerStart() - Constructor for class de.qaware.chronix.client.benchmark.util.DockerStart

DockerStatsRecord - Class in de.qaware.chronix.server.util

Created by mcqueen666 on 11.09.16.

DockerStatsRecord(Double, Double, Long, Long, Long, Long) - Constructor for class de.qaware.chronix.server.util.DockerStatsRecord

DockerStatsUtil - Class in de.qaware.chronix.server.util

Created by mcqueen666 on 19.08.16.

DockerStatsUtil() - Constructor for class de.qaware.chronix.server.util.DockerStatsUtil

DockerStatsUtil.MeasureRunner - Class in de.qaware.chronix.server.util

DockerStop - Class in de.qaware.chronix.client.benchmark.util

Created by mcqueen666 on 07.10.16.

DockerStop() - Constructor for class de.qaware.chronix.client.benchmark.util.DockerStop

DockerUtil - Class in de.qaware.chronix.database.util

Created by mcqueen666 on 13.09.16.

DockerUtil() - Constructor for class de.qaware.chronix.database.util.DockerUtil

doImportOnServer(String, ImportRecordWrapper) - Method in class de.qaware.chronix.client.benchmark.queryhandler.QueryHandler

Imports time series on given server.

doImportOnServerWithUploadedFiles(String, FormDataMultiPart) - Method in class de.qaware.chronix.client.benchmark.queryhandler.QueryHandler

Uploads time series and wrapped import record as multipart to server for import.

doQueryOnServer(String, QueryRecord) - Method in class de.qaware.chronix.client.benchmark.queryhandler.QueryHandler

Transmits the given queryRecord to given server on which the query should be performed.

DropWizardServerApplication - Class in de.qaware.chronix.server

Created by mcqueen666 on 15.06.16.

DropWizardServerApplication() - Constructor for class de.qaware.chronix.server.DropWizardServerApplication

DropWizardServerConfiguration - Class in de.qaware.chronix.server

Created by mcqueen666 on 15.06.16.

DropWizardServerConfiguration() - Constructor for class de.qaware.chronix.server.DropWizardServerConfiguration

DropWizardServerHealthCheck - Class in de.qaware.chronix.server

Created by mcqueen666 on 15.06.16.

DropWizardServerHealthCheck() - Constructor for class de.qaware.chronix.server.DropWizardServerHealthCheck

A B C D E F G H I J K L M N O P Q R S T U V W

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Containers;
using osu.Framework.Testing;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Online.Chat;
using osu.Game.Tests.Visual;

namespace osu.Game.Tests.Chat
{
    [HeadlessTest]
    public class TestSceneChannelManager : OsuTestScene
    {
        private ChannelManager channelManager;
        private int currentMessageId;
        private List<Message> sentMessages;

        [SetUp]
        public void Setup() => Schedule(() =>
        {
            var container = new ChannelManagerContainer();
            Child = container;
            channelManager = container.ChannelManager;
        });

        [SetUpSteps]
        public void SetUpSteps()
        {
            AddStep("register request handling", () =>
            {
                currentMessageId = 0;
                sentMessages = new List<Message>();

                ((DummyAPIAccess)API).HandleRequest = req =>
                {
                    switch (req)
                    {
                        case JoinChannelRequest joinChannel:
                            joinChannel.TriggerSuccess();
                            return true;

                        case PostMessageRequest postMessage:
                            handlePostMessageRequest(postMessage);
                            return true;

                        case MarkChannelAsReadRequest markRead:
                            handleMarkChannelAsReadRequest(markRead);
                            return true;
                    }

                    return false;
                };
            });
        }

        [Test]
        public void TestCommandsPostedToCorrectChannelWhenNotCurrent()
        {
            Channel channel1 = null;
            Channel channel2 = null;

            AddStep("join 2 rooms", () =>
            {
                channelManager.JoinChannel(channel1 = createChannel(1, ChannelType.Public));
                channelManager.JoinChannel(channel2 = createChannel(2, ChannelType.Public));
            });

            AddStep("select channel 1", () => channelManager.CurrentChannel.Value = channel1);

            AddStep("post /me command to channel 2", () => channelManager.PostCommand("me dances", channel2));
            AddAssert("/me command received by channel 2", () => channel2.Messages.Last().Content == "dances");

            AddStep("post /np command to channel 2", () => channelManager.PostCommand("np", channel2));
            AddAssert("/np command received by channel 2", () => channel2.Messages.Last().Content.Contains("is listening to"));
        }

        [Test]
        public void TestMarkAsReadIgnoringLocalMessages()
        {
            Channel channel = null;

            AddStep("join channel and select it", () =>
            {
                channelManager.JoinChannel(channel = createChannel(1, ChannelType.Public));
                channelManager.CurrentChannel.Value = channel;
            });

            AddStep("post message", () => channelManager.PostMessage("Something interesting"));

            AddStep("post /help command", () => channelManager.PostCommand("help", channel));
            AddStep("post /me command with no action", () => channelManager.PostCommand("me", channel));
            AddStep("post /join command with no channel", () => channelManager.PostCommand("join", channel));
            AddStep("post /join command with non-existent channel", () => channelManager.PostCommand("join i-dont-exist", channel));
            AddStep("post non-existent command", () => channelManager.PostCommand("non-existent-cmd arg", channel));

            AddStep("mark channel as read", () => channelManager.MarkChannelAsRead(channel));
            AddAssert("channel's last read ID is set to the latest message", () => channel.LastReadId == sentMessages.Last().Id);
        }

        private void handlePostMessageRequest(PostMessageRequest request)
        {
            var message = new Message(++currentMessageId)
            {
                IsAction = request.Message.IsAction,
                ChannelId = request.Message.ChannelId,
                Content = request.Message.Content,
                Links = request.Message.Links,
                Timestamp = request.Message.Timestamp,
                Sender = request.Message.Sender
            };

            sentMessages.Add(message);
            request.TriggerSuccess(message);
        }

        private void handleMarkChannelAsReadRequest(MarkChannelAsReadRequest request)
        {
            // only accept messages that were sent through the API
            if (sentMessages.Contains(request.Message))
            {
                request.TriggerSuccess();
            }
            else
            {
                request.TriggerFailure(new APIException("unknown message!", null));
            }
        }

        private Channel createChannel(int id, ChannelType type) => new Channel(new APIUser())
        {
            Id = id,
            Name = $"Channel {id}",
            Topic = $"Topic of channel {id} with type {type}",
            Type = type,
            LastMessageId = 0,
        };

        private class ChannelManagerContainer : CompositeDrawable
        {
            [Cached]
            public ChannelManager ChannelManager { get; } = new ChannelManager();

            public ChannelManagerContainer()
            {
                InternalChild = ChannelManager;
            }
        }
    }
}


text:
var LocalStrategy = require('passport-local').Strategy;

var User = require('../models/users');

module.exports = function(passport) {

    passport.serializeUser(function(user, done) {
        done(null, user.id);
    });

    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
            done(err, user);
        });
    });

    passport.use('local-signup', new LocalStrategy({
        usernameField: 'email',
        passwordField: 'password',
        passReqToCallback: true
    },
        function (req, email, password, done) {

            process.nextTick(function() {

            User.findOne({'local.email': email}, function(err, user) {
                if (err) {
                    console.log(err+"err");
                    return done(err, false, {message: "thas an issue"});
                }
                if (user) {
                    console.log(user+"user");
                    return done(null, false, {message: "Sorry, a user already exists with that name."});
                } else {
                    var newUser = User();
                    newUser.local.email = email;
                    newUser.local.password = newUser.generateHash(password);
                    newUser.save(function(err) {
                        if (err) {
                            throw err;
                        }
                        else {
                            return done(null, newUser, {message: "Sweet, you are now registered!"});
                        }
                    });
                }
        });

        });

    }));

    passport.use('local-login', new LocalStrategy({
        usernameField: 'email',
        passwordField: 'password',
        passReqToCallback: true},

        function(req, email, password, done) {

        console.log(email);

        User.findOne({'local.email': email}, function(err, user) {

            if (err) {
                return done(err);
            }

            if (!user) {
                return done(null, false, {'message': 'This isnt a correct username'});

            }
            if (!user.validPassword(password)) {
                return done(null, false, {'message': 'Wrong password bud'});
            }

                return done (null, user);

        });
    }));
}


text:
#ifndef _HIERARCHICAL_H__
#define _HIERARCHICAL_H__

#include <stdio.h>
#include <shogun/lib/common.h>
#include <shogun/io/SGIO.h>
#include <shogun/distance/Distance.h>
#include <shogun/machine/DistanceMachine.h>

namespace shogun
{
class CDistanceMachine;

/** @brief Agglomerative hierarchical single linkage clustering.
 *
 * Starting with each object being assigned to its own cluster clusters are
 * iteratively merged.  Here the clusters are merged whose elements have
 * minimum distance, i.e.  the clusters A and B that obtain
 *
 * \f[
 * \min\{d({\bf x},{\bf x'}): {\bf x}\in {\cal A},{\bf x'}\in {\cal B}\}
 * \f]
 *
 * are merged.
 *
 * cf e.g. http://en.wikipedia.org/wiki/Data_clustering*/
class CHierarchical : public CDistanceMachine
{
	public:
		/** default constructor */
		CHierarchical();

		/** constructor
		 *
		 * @param merges the merges
		 * @param d distance
		 */
		CHierarchical(int32_t merges, CDistance* d);
		virtual ~CHierarchical();

		/** get classifier type
		 *
		 * @return classifier type HIERARCHICAL
		 */
		virtual EClassifierType get_classifier_type();

		/** load distance machine from file
		 *
		 * @param srcfile file to load from
		 * @return if loading was successful
		 */
		virtual bool load(FILE* srcfile);

		/** save distance machine to file
		 *
		 * @param dstfile file to save to
		 * @return if saving was successful
		 */
		virtual bool save(FILE* dstfile);

		/** set merges
		 *
		 * @param m new merges
		 */
		inline void set_merges(int32_t m)
		{
			ASSERT(m>0);
			merges=m;
		}

		/** get merges
		 *
		 * @return merges
		 */
		int32_t get_merges();

		/** get assignment
		 *
		 */
		SGVector<int32_t> get_assignment();

		/** get merge distance
		 *
		 */
		SGVector<float64_t> get_merge_distances();

		/** get cluster pairs
		 *
		 */
		SGMatrix<int32_t> get_cluster_pairs();

		/** @return object name */
		inline virtual const char* get_name() const { return "Hierarchical"; }

	protected:
		/** estimate hierarchical clustering
		 *
		 * @param data training data (parameter can be avoided if distance or
		 * kernel-based classifiers are used and distance/kernels are
		 * initialized with train data)
		 *
		 * @return whether training was successful
		 */
		virtual bool train_machine(CFeatures* data=NULL);

		/** TODO: Ensures cluster centers are in lhs of underlying distance
		 * Currently: does nothing.
		 * */
		virtual void store_model_features();

		/** NOT IMPLEMENTED */
		virtual CLabels* apply();

		/** NOT IMPLEMENTED */
		virtual CLabels* apply(CFeatures* data);

		/** NOT IMPLEMENTED */
		virtual float64_t apply(int32_t num);

	protected:
		/// the number of merges in hierarchical clustering
		int32_t merges;

		/// number of dimensions
		int32_t dimensions;

		/// size of assignment table
		int32_t assignment_size;

		/// cluster assignment for the num_points
		int32_t* assignment;

		/// size of the below tables
		int32_t table_size;

		/// tuples of i/j
		int32_t* pairs;

		/// distance at which pair i/j was added
		float64_t* merge_distance;
};
}
#endif


text:
/* socket.h
   ========
   Author: R.J.Barnes
*/

/*
 LICENSE AND DISCLAIMER

 Copyright (c) 2012 The Johns Hopkins University/Applied Physics Laboratory

 This file is part of the Radar Software Toolkit (RST).

 RST is free software: you can redistribute it and/or modify
 it under the terms of the GNU Lesser General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 any later version.

 RST is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Lesser General Public License for more details.

 You should have received a copy of the GNU Lesser General Public License
 along with RST.  If not, see <http://www.gnu.org/licenses/>.

*/

#define CLIENT_MAX 16
#define BUF_SIZE 10*1024

struct client {
  int sock;
  int in_sze;
  int out_sze;
  char host[256];
  char in_buf[BUF_SIZE]; /* data from client */
  char out_buf[BUF_SIZE]; /* data to client */
};

int createsocket(int *port);
int procsocket(int sock,int inpipe);


text:
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}

module HipBot.HipLambda.Pointfree
  ( pointfreeResource
  , pointfulResource
  ) where

import Control.Monad.Reader
import Data.Foldable
import Data.List (isPrefixOf, isSuffixOf)
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as T
import Lambdabot.Pointful (pointful)
import Pointfree (pointfree')
import Prelude hiding (any)
import Webcrank.Wai

import HipBot.Webhooks

pointfreeResource :: WaiResource IO
pointfreeResource =
  simpleWebhookResource "pointfree" ["/pf", "/pointfree"] (massage pointfree')

pointfulResource :: WaiResource IO
pointfulResource =
  simpleWebhookResource "pointful" ["/unpf", "/pointful"] (massage unpf)

unpf :: String -> Maybe String
unpf input =
  let output = pointful input
  in if any (`isPrefixOf` output) ["Error:", "<unknown>.hs:"]
    then Nothing
    else if ";" `isSuffixOf` output && not (";" `isSuffixOf` input)
      then Just (init output)
      else Just output

massage :: (String -> Maybe String) -> Text -> Maybe Text
massage f = fmap (T.pack . mappend "/code "). f . T.unpack


text:
/*$T boole/Boole2/uSimulacion.h GC! 1.116 05/02/01 18:53:25 */

/*$6
 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 */

#ifndef uSimulacionH
#define uSimulacionH

#define MAX_PASOS	(32)
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include <Grids.hpp>
#include "CSPIN.h"
#include <Menus.hpp>
#include <ExtCtrls.hpp>
#include <Buttons.hpp>
class TfSimulacion : public TForm
{
__published:	// IDE-managed Components
	TMainMenu		*MainMenu1;
	TMenuItem		*Cerrar1;
	TMenuItem		*Log1;
	TMenuItem		*VerLog1;
	TMenuItem		*Ayuda1;
	TPanel			*Panel1;
	TStringGrid		*gridSimulacion;
	TPanel			*Panel2;
	TBitBtn			*btIniciarSim;
	TBitBtn			*btPausarSim;
	TBitBtn			*btSiguiente;
	TBitBtn			*btPararSim;
	TBitBtn			*btRapido;
	TPanel			*Panel3;
	TLabel			*Label1;
	TComboBox		*comboInicial;
	TLabel			*Label2;
	TCSpinEdit		*spinFilas;
  TPopupMenu *PopupTabla;
  TMenuItem *menuInsertarfila;
  TMenuItem *menuEliminarfila;
	void __fastcall gridSimulacionMouseDown(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y);
	void __fastcall spinFilasChange(TObject *Sender);
	void __fastcall btIniciarSimClick(TObject *Sender);
	void __fastcall comboInicialChange(TObject *Sender);
	void __fastcall Cerrar1Click(TObject *Sender);
	void __fastcall FormClose(TObject *Sender, TCloseAction &Action);
	void __fastcall btSiguienteClick(TObject *Sender);
	void __fastcall btPararSimClick(TObject *Sender);
	void __fastcall btPausarSimClick(TObject *Sender);
	void __fastcall gridSimulacionSelectCell(TObject *Sender, int ACol, int ARow, bool &CanSelect);
	void __fastcall FormShow(TObject *Sender);
	void __fastcall gridSimulacionMouseMove(TObject *Sender, TShiftState Shift, int X, int Y);
	void __fastcall btRapidoClick(TObject *Sender);
	void __fastcall VerLog1Click(TObject *Sender);
  void __fastcall menuInsertarfilaClick(TObject *Sender);
  void __fastcall menuEliminarfilaClick(TObject *Sender);
  void __fastcall PopupTablaPopup(TObject *Sender);
  void __fastcall Ayuda1Click(TObject *Sender);

/*
 -----------------------------------------------------------------------------------------------------------------------
 -----------------------------------------------------------------------------------------------------------------------
 */
private:	// User declarations

/*
 -----------------------------------------------------------------------------------------------------------------------
 -----------------------------------------------------------------------------------------------------------------------
 */
public: // User declarations
	__fastcall		TfSimulacion(TComponent *Owner);
	void			PosicionarPaso(int paso);
	int				indiceEntInicial;
	int				indiceEntFinal;
	int				indiceCLK;
	int				indiceRESET;
	int				indiceEstado;
	int				indiceEstadoSig;
	int				indiceSalInicial;
	int				indiceSalFinal;
	int				indiceActual;
	bool			pausado;
	void			BorrarTabla(void);
  void      ActualizarTablaYLog();
  void      AnyadirFila(int fila);
  void      SuprimirFila(int fila);
  void      AnyadirPaso(int fila);
  void      SuprimirPaso(int fila);
  void      Renumerar();

        };
extern PACKAGE TfSimulacion *fSimulacion;
#endif