text:
import mox
from oslo.config import cfg

from neutron.agent.linux import ip_lib
from neutron.agent.linux import ovs_lib
from neutron.openstack.common import log
from neutron.plugins.openvswitch.agent import ovs_neutron_agent
from neutron.plugins.openvswitch.common import constants
from neutron.tests import base

# Useful global dummy variables.
NET_UUID = '3faeebfe-5d37-11e1-a64b-000c29d5f0a7'
LS_ID = 42
LV_ID = 42
LV_IDS = [42, 43]
VIF_ID = '404deaec-5d37-11e1-a64b-000c29d5f0a8'
VIF_MAC = '3c:09:24:1e:78:23'
OFPORT_NUM = 1
VIF_PORT = ovs_lib.VifPort('port', OFPORT_NUM,
                           VIF_ID, VIF_MAC, 'switch')
VIF_PORTS = {LV_ID: VIF_PORT}
LVM = ovs_neutron_agent.LocalVLANMapping(LV_ID, 'gre', None, LS_ID, VIF_PORTS)
LVM_FLAT = ovs_neutron_agent.LocalVLANMapping(
    LV_ID, 'flat', 'net1', LS_ID, VIF_PORTS)
LVM_VLAN = ovs_neutron_agent.LocalVLANMapping(
    LV_ID, 'vlan', 'net1', LS_ID, VIF_PORTS)
BCAST_MAC = "01:00:00:00:00:00/01:00:00:00:00:00"

class DummyPort:
    def __init__(self, interface_id):
        self.interface_id = interface_id

class DummyVlanBinding:
    def __init__(self, network_id, vlan_id):
        self.network_id = network_id
        self.vlan_id = vlan_id

class TunnelTest(base.BaseTestCase):

    def setUp(self):
        super(TunnelTest, self).setUp()
        cfg.CONF.set_override('rpc_backend',
                              'neutron.openstack.common.rpc.impl_fake')
        cfg.CONF.set_override('report_interval', 0, 'AGENT')
        self.mox = mox.Mox()
        self.addCleanup(self.mox.UnsetStubs)

        self.INT_BRIDGE = 'integration_bridge'
        self.TUN_BRIDGE = 'tunnel_bridge'
        self.MAP_TUN_BRIDGE = 'tunnel_bridge_mapping'
        self.NET_MAPPING = {'net1': self.MAP_TUN_BRIDGE}
        self.INT_OFPORT = 11111
        self.TUN_OFPORT = 22222
        self.MAP_TUN_OFPORT = 33333
        self.inta = self.mox.CreateMock(ip_lib.IPDevice)
        self.intb = self.mox.CreateMock(ip_lib.IPDevice)
        self.inta.link = self.mox.CreateMock(ip_lib.IpLinkCommand)
        self.intb.link = self.mox.CreateMock(ip_lib.IpLinkCommand)

        self.mox.StubOutClassWithMocks(ovs_lib, 'OVSBridge')
        self.mock_int_bridge = ovs_lib.OVSBridge(self.INT_BRIDGE, 'sudo')
        self.mock_int_bridge.delete_port('patch-tun')
        self.mock_int_bridge.remove_all_flows()
        self.mock_int_bridge.add_flow(priority=1, actions='normal')

        self.mock_map_tun_bridge = ovs_lib.OVSBridge(
            self.MAP_TUN_BRIDGE, 'sudo')
        self.mock_map_tun_bridge.remove_all_flows()
        self.mock_map_tun_bridge.add_flow(priority=1, actions='normal')
        self.mock_int_bridge.delete_port('int-tunnel_bridge_mapping')
        self.mock_map_tun_bridge.delete_port('phy-tunnel_bridge_mapping')
        self.mock_int_bridge.add_port(self.inta)
        self.mock_map_tun_bridge.add_port(self.intb)
        self.inta.link.set_up()
        self.intb.link.set_up()

        self.mock_int_bridge.add_flow(priority=2, in_port=None, actions='drop')
        self.mock_map_tun_bridge.add_flow(
            priority=2, in_port=None, actions='drop')

        self.mock_tun_bridge = ovs_lib.OVSBridge(self.TUN_BRIDGE, 'sudo')
        self.mock_tun_bridge.reset_bridge()
        self.mock_int_bridge.add_patch_port(
            'patch-tun', 'patch-int').AndReturn(self.TUN_OFPORT)
        self.mock_tun_bridge.add_patch_port(
            'patch-int', 'patch-tun').AndReturn(self.INT_OFPORT)
        self.mock_tun_bridge.remove_all_flows()
        self.mock_tun_bridge.add_flow(priority=1, actions='drop')

        self.mox.StubOutWithMock(ip_lib, 'device_exists')
        ip_lib.device_exists('tunnel_bridge_mapping', 'sudo').AndReturn(True)
        ip_lib.device_exists(
            'int-tunnel_bridge_mapping', 'sudo').AndReturn(True)

        self.mox.StubOutWithMock(ip_lib.IpLinkCommand, 'delete')
        ip_lib.IPDevice('int-tunnel_bridge_mapping').link.delete()

        self.mox.StubOutClassWithMocks(ip_lib, 'IPWrapper')
        ip_lib.IPWrapper('sudo').add_veth(
            'int-tunnel_bridge_mapping',
            'phy-tunnel_bridge_mapping').AndReturn([self.inta, self.intb])

        self.mock_int_bridge.get_local_port_mac().AndReturn('000000000001')

    def testConstruct(self):
        self.mox.ReplayAll()
        ovs_neutron_agent.OVSNeutronAgent(self.INT_BRIDGE,
                                          self.TUN_BRIDGE,
                                          '10.0.0.1', self.NET_MAPPING,
                                          'sudo', 2, 'gre')
        self.mox.VerifyAll()

    def testConstructVXLAN(self):
        self.mox.StubOutWithMock(ovs_lib, 'get_installed_ovs_klm_version')
        ovs_lib.get_installed_ovs_klm_version().AndReturn("1.10")
        self.mox.StubOutWithMock(ovs_lib, 'get_installed_ovs_usr_version')
        ovs_lib.get_installed_ovs_usr_version('sudo').AndReturn("1.10")
        self.mox.ReplayAll()
        ovs_neutron_agent.OVSNeutronAgent(self.INT_BRIDGE,
                                          self.TUN_BRIDGE,
                                          '10.0.0.1', self.NET_MAPPING,
                                          'sudo', 2, 'vxlan')
        self.mox.VerifyAll()

    def testProvisionLocalVlan(self):
        action_string = 'set_tunnel:%s,normal' % LS_ID
        self.mock_tun_bridge.add_flow(priority=4, in_port=self.INT_OFPORT,
                                      dl_vlan=LV_ID, actions=action_string)

        action_string = 'mod_vlan_vid:%s,output:%s' % (LV_ID, self.INT_OFPORT)
        self.mock_tun_bridge.add_flow(priority=3, tun_id=LS_ID,
                                      dl_dst=BCAST_MAC, actions=action_string)

        self.mox.ReplayAll()

        a = ovs_neutron_agent.OVSNeutronAgent(self.INT_BRIDGE,
                                              self.TUN_BRIDGE,
                                              '10.0.0.1', self.NET_MAPPING,
                                              'sudo', 2, 'gre')
        a.available_local_vlans = set([LV_ID])
        a.provision_local_vlan(NET_UUID, constants.TYPE_GRE, None, LS_ID)
        self.mox.VerifyAll()

    def testProvisionLocalVlanFlat(self):
        action_string = 'strip_vlan,normal'
        self.mock_map_tun_bridge.add_flow(
            priority=4, in_port=self.MAP_TUN_OFPORT,
            dl_vlan=LV_ID, actions=action_string)

        action_string = 'mod_vlan_vid:%s,normal' % LV_ID
        self.mock_int_bridge.add_flow(priority=3, in_port=self.INT_OFPORT,
                                      dl_vlan=65535, actions=action_string)

        self.mox.ReplayAll()

        a = ovs_neutron_agent.OVSNeutronAgent(self.INT_BRIDGE,
                                              self.TUN_BRIDGE,
                                              '10.0.0.1', self.NET_MAPPING,
                                              'sudo', 2, 'gre')
        a.available_local_vlans = set([LV_ID])
        a.phys_brs['net1'] = self.mock_map_tun_bridge
        a.phys_ofports['net1'] = self.MAP_TUN_OFPORT
        a.int_ofports['net1'] = self.INT_OFPORT
        a.provision_local_vlan(NET_UUID, constants.TYPE_FLAT, 'net1', LS_ID)
        self.mox.VerifyAll()

    def testProvisionLocalVlanFlatFail(self):
        self.mox.ReplayAll()
        a = ovs_neutron_agent.OVSNeutronAgent(self.INT_BRIDGE,
                                              self.TUN_BRIDGE,
                                              '10.0.0.1', self.NET_MAPPING,
                                              'sudo', 2, 'gre')
        a.provision_local_vlan(NET_UUID, constants.TYPE_FLAT, 'net2', LS_ID)
        self.mox.VerifyAll()

    def testProvisionLocalVlanVlan(self):
        action_string = 'mod_vlan_vid:%s,normal' % LS_ID
        self.mock_map_tun_bridge.add_flow(
            priority=4, in_port=self.MAP_TUN_OFPORT,
            dl_vlan=LV_ID, actions=action_string)

        action_string = 'mod_vlan_vid:%s,normal' % LS_ID
        self.mock_int_bridge.add_flow(priority=3, in_port=self.INT_OFPORT,
                                      dl_vlan=LV_ID, actions=action_string)

        self.mox.ReplayAll()
        a = ovs_neutron_agent.OVSNeutronAgent(self.INT_BRIDGE,
                                              self.TUN_BRIDGE,
                                              '10.0.0.1', self.NET_MAPPING,
                                              'sudo', 2, 'gre')
        a.available_local_vlans = set([LV_ID])
        a.phys_brs['net1'] = self.mock_map_tun_bridge
        a.phys_ofports['net1'] = self.MAP_TUN_OFPORT
        a.int_ofports['net1'] = self.INT_OFPORT
        a.provision_local_vlan(NET_UUID, constants.TYPE_VLAN, 'net1', LS_ID)
        self.mox.VerifyAll()

    def testProvisionLocalVlanVlanFail(self):
        self.mox.ReplayAll()
        a = ovs_neutron_agent.OVSNeutronAgent(self.INT_BRIDGE,
                                              self.TUN_BRIDGE,
                                              '10.0.0.1', self.NET_MAPPING,
                                              'sudo', 2, 'gre')
        a.provision_local_vlan(NET_UUID, constants.TYPE_VLAN, 'net2', LS_ID)
        self.mox.VerifyAll()

    def testReclaimLocalVlan(self):
        self.mock_tun_bridge.delete_flows(tun_id=LVM.segmentation_id)

        self.mock_tun_bridge.delete_flows(dl_vlan=LVM.vlan)

        self.mox.ReplayAll()
        a = ovs_neutron_agent.OVSNeutronAgent(self.INT_BRIDGE,
                                              self.TUN_BRIDGE,
                                              '10.0.0.1', self.NET_MAPPING,
                                              'sudo', 2, 'gre')
        a.available_local_vlans = set()
        a.local_vlan_map[NET_UUID] = LVM
        a.reclaim_local_vlan(NET_UUID, LVM)
        self.assertTrue(LVM.vlan in a.available_local_vlans)
        self.mox.VerifyAll()

    def testReclaimLocalVlanFlat(self):
        self.mock_map_tun_bridge.delete_flows(
            in_port=self.MAP_TUN_OFPORT, dl_vlan=LVM_FLAT.vlan)

        self.mock_int_bridge.delete_flows(
            dl_vlan=65535, in_port=self.INT_OFPORT)

        self.mox.ReplayAll()
        a = ovs_neutron_agent.OVSNeutronAgent(self.INT_BRIDGE,
                                              self.TUN_BRIDGE,
                                              '10.0.0.1', self.NET_MAPPING,
                                              'sudo', 2, 'gre')
        a.phys_brs['net1'] = self.mock_map_tun_bridge
        a.phys_ofports['net1'] = self.MAP_TUN_OFPORT
        a.int_ofports['net1'] = self.INT_OFPORT

        a.available_local_vlans = set()
        a.local_vlan_map[NET_UUID] = LVM_FLAT
        a.reclaim_local_vlan(NET_UUID, LVM_FLAT)
        self.assertTrue(LVM_FLAT.vlan in a.available_local_vlans)
        self.mox.VerifyAll()

    def testReclaimLocalVlanVLAN(self):
        self.mock_map_tun_bridge.delete_flows(
            in_port=self.MAP_TUN_OFPORT, dl_vlan=LVM_VLAN.vlan)

        self.mock_int_bridge.delete_flows(
            dl_vlan=LV_ID, in_port=self.INT_OFPORT)

        self.mox.ReplayAll()
        a = ovs_neutron_agent.OVSNeutronAgent(self.INT_BRIDGE,
                                              self.TUN_BRIDGE,
                                              '10.0.0.1', self.NET_MAPPING,
                                              'sudo', 2, 'gre')
        a.phys_brs['net1'] = self.mock_map_tun_bridge
        a.phys_ofports['net1'] = self.MAP_TUN_OFPORT
        a.int_ofports['net1'] = self.INT_OFPORT

        a.available_local_vlans = set()
        a.local_vlan_map[NET_UUID] = LVM_VLAN
        a.reclaim_local_vlan(NET_UUID, LVM_VLAN)
        self.assertTrue(LVM_VLAN.vlan in a.available_local_vlans)
        self.mox.VerifyAll()

    def testPortBound(self):
        self.mock_int_bridge.set_db_attribute('Port', VIF_PORT.port_name,
                                              'tag', str(LVM.vlan))
        self.mock_int_bridge.delete_flows(in_port=VIF_PORT.ofport)

        action_string = 'mod_vlan_vid:%s,normal' % LV_ID
        self.mock_tun_bridge.add_flow(priority=3, tun_id=LS_ID,
                                      dl_dst=VIF_PORT.vif_mac,
                                      actions=action_string)

        self.mox.ReplayAll()
        a = ovs_neutron_agent.OVSNeutronAgent(self.INT_BRIDGE,
                                              self.TUN_BRIDGE,
                                              '10.0.0.1', self.NET_MAPPING,
                                              'sudo', 2, 'gre')
        a.local_vlan_map[NET_UUID] = LVM
        a.port_bound(VIF_PORT, NET_UUID, 'gre', None, LS_ID)
        self.mox.VerifyAll()

    def testPortUnbound(self):
        self.mock_int_bridge.set_db_attribute('Port', VIF_PORT.port_name,
                                              'tag', str(LVM.vlan))
        self.mock_int_bridge.delete_flows(in_port=VIF_PORT.ofport)

        action_string = 'mod_vlan_vid:%s,normal' % LV_ID
        self.mock_tun_bridge.add_flow(priority=3, tun_id=LS_ID,
                                      dl_dst=VIF_PORT.vif_mac,
                                      actions=action_string)
        self.mock_tun_bridge.delete_flows(dl_dst=VIF_MAC, tun_id=LS_ID)
        self.mox.ReplayAll()

        a = ovs_neutron_agent.OVSNeutronAgent(self.INT_BRIDGE,
                                              self.TUN_BRIDGE,
                                              '10.0.0.1', self.NET_MAPPING,
                                              'sudo', 2, 'gre')
        a.local_vlan_map[NET_UUID] = LVM
        a.port_bound(VIF_PORT, NET_UUID, 'gre', None, LS_ID)
        a.available_local_vlans = set([LV_ID])
        a.local_vlan_map[NET_UUID] = LVM
        a.port_unbound(VIF_ID, NET_UUID)
        self.mox.VerifyAll()

    def testPortDead(self):
        self.mock_int_bridge.set_db_attribute(
            'Port', VIF_PORT.port_name, 'tag', ovs_neutron_agent.DEAD_VLAN_TAG)

        self.mock_int_bridge.add_flow(priority=2, in_port=VIF_PORT.ofport,
                                      actions='drop')

        self.mox.ReplayAll()
        a = ovs_neutron_agent.OVSNeutronAgent(self.INT_BRIDGE,
                                              self.TUN_BRIDGE,
                                              '10.0.0.1', self.NET_MAPPING,
                                              'sudo', 2, 'gre')
        a.available_local_vlans = set([LV_ID])
        a.local_vlan_map[NET_UUID] = LVM
        a.port_dead(VIF_PORT)
        self.mox.VerifyAll()

    def testTunnelUpdate(self):
        self.mock_tun_bridge.add_tunnel_port('gre-1', '10.0.10.1', 'gre', 4789)
        self.mox.ReplayAll()
        a = ovs_neutron_agent.OVSNeutronAgent(self.INT_BRIDGE,
                                              self.TUN_BRIDGE,
                                              '10.0.0.1', self.NET_MAPPING,
                                              'sudo', 2, 'gre')
        a.tunnel_update(
            mox.MockAnything, tunnel_id='1', tunnel_ip='10.0.10.1')
        self.mox.VerifyAll()

    def testTunnelUpdateSelf(self):
        self.mox.ReplayAll()
        a = ovs_neutron_agent.OVSNeutronAgent(self.INT_BRIDGE,
                                              self.TUN_BRIDGE,
                                              '10.0.0.1', self.NET_MAPPING,
                                              'sudo', 2, 'gre')
        a.tunnel_update(
            mox.MockAnything, tunnel_id='1', tunnel_ip='10.0.0.1')
        self.mox.VerifyAll()

    def testDaemonLoop(self):
        reply2 = {'current': set(['tap0']),
                  'added': set([]),
                  'removed': set([])}

        reply3 = {'current': set(['tap2']),
                  'added': set([]),
                  'removed': set([])}

        self.mox.StubOutWithMock(log.ContextAdapter, 'exception')
        log.ContextAdapter.exception(
            _("Error in agent event loop")).AndRaise(
                Exception('Fake exception to get out of the loop'))

        self.mox.StubOutWithMock(
            ovs_neutron_agent.OVSNeutronAgent, 'update_ports')
        ovs_neutron_agent.OVSNeutronAgent.update_ports(set()).AndReturn(reply2)
        ovs_neutron_agent.OVSNeutronAgent.update_ports(
            set(['tap0'])).AndReturn(reply3)
        self.mox.StubOutWithMock(
            ovs_neutron_agent.OVSNeutronAgent, 'process_network_ports')
        ovs_neutron_agent.OVSNeutronAgent.process_network_ports(
            {'current': set(['tap0']),
             'removed': set([]),
             'added': set([])}).AndReturn(False)
        ovs_neutron_agent.OVSNeutronAgent.process_network_ports(
            {'current': set(['tap0']),
             'removed': set([]),
             'added': set([])}).AndRaise(
                 Exception('Fake exception to get out of the loop'))
        self.mox.ReplayAll()
        q_agent = ovs_neutron_agent.OVSNeutronAgent(self.INT_BRIDGE,
                                                    self.TUN_BRIDGE,
                                                    '10.0.0.1',
                                                    self.NET_MAPPING,
                                                    'sudo', 2, 'gre')

        # Hack to test loop
        # We start method and expect it will raise after 2nd loop
        # If something goes wrong, mox.VerifyAll() will catch it
        try:
            q_agent.daemon_loop()
        except Exception:
            pass

        self.mox.VerifyAll()


text:
string::size_type pos = 0;
while ((pos = form.find("Daisy", pos)) != string::npos) {
  form.replace(pos, 5, lastname);
  pos += lastname.size();
 }

//replace 'Ms'

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Croogo\Install\Shell;

use App\Console\Installer;
use App\Controller\Component\AuthComponent;
use Cake\Controller\ComponentRegistry;
use Cake\Console\Shell;
use Cake\Datasource\ConnectionManager;
use Cake\ORM\TableRegistry;
use Croogo\Acl\AclGenerator;
use Croogo\Core\Plugin;
use Croogo\Install\InstallManager;
use Croogo\Install\Model\Table\InstallTable;
use Composer\IO\BufferIO;

/**
 * Install Shell
 *
 * @category Shell
 * @package  Croogo.Install.Console.Command
 * @version  1.0
 * @author   Fahad Ibnay Heylaal <contact@fahad19.com>
 * @license  http://www.opensource.org/licenses/mit-license.php The MIT License
 * @link     http://www.croogo.org
 */
class InstallShell extends Shell
{

    public function startup()
    {
        $options = ['bootstrap' => true, 'routes' => true];
        $plugins = array_merge(Plugin::$corePlugins, Plugin::$bundledPlugins);
        foreach ($plugins as $plugin) {
            if (!Plugin::loaded($plugin)) {
                Plugin::load($plugin, $options);
            }
        }
    }

/**
 * Display help/options
 */
    public function getOptionParser()
    {
        $drivers = ['Mysql', 'Postgres', 'Sqlite', 'Sqlserver'];
        $parser = parent::getOptionParser();
        $parser->description(__d('croogo', 'Install Utilities'))
            ->addSubcommand('main', [
                'help' => 'Generate database.php and create admin user.',
                'parser' => [
                    'description' => 'Generate database.php and create admin user.',
                ]
            ])
            ->addSubcommand('setup_grants', [
                'help' => 'Setup default grants (ACOs) for roles',
                'parser' => [
                    'description' => 'Generate default role settings during release',
                ]
            ])
            ->addOption('datasource', [
                'help' => 'Database Driver',
                'short' => 'd',
                'required' => true,
                'options' => $drivers,
            ])
            ->addOption('host', [
                'help' => 'Database Host',
                'short' => 'h',
                'required' => true,
            ])
            ->addOption('username', [
                'help' => 'Database User',
                'short' => 'u',
                'required' => true,
            ])
            ->addOption('password', [
                'help' => 'Database Password',
                'short' => 'p',
                'required' => true,
            ])
            ->addOption('database-name', [
                'help' => 'Database Name',
                'short' => 'n',
                'required' => true,
            ])
            ->addOption('port', [
                'help' => 'Database Port',
                'short' => 't',
                'required' => true,
            ])
            //->addOption('prefix', [
                //'help' => 'Table Prefix',
                //'short' => 'x',
                //'required' => true,
            //])
            ->addArgument('admin-user', [
                'help' => 'Admin username',
            ])
            ->addArgument('admin-password', [
                'help' => 'Admin password',
            ]);
        return $parser;
    }

/**
 * Convenient wrapper for Shell::in() that gets the default from CLI options
 */
    protected function _in($prompt, $options = null, $default = null, $argument = null)
    {
        if (isset($this->params[$argument])) {
            return $this->params[$argument];
        }
        return $this->in($prompt, $options, $default);
    }

/**
 * Convenient wrapper for Shell::in() that gets the default from CLI argument
 */
    protected function _args($prompt, $options = null, $default = null, $index = null)
    {
        if (!empty($this->args[$index])) {
            return $this->args[$index];
        }
        return $this->in($prompt, $options, $default);
    }

    public function main()
    {
        Installer::setSecuritySalt(ROOT, new BufferIO());
        $this->out();
        $this->out('Database settings:');
        $install['datasource'] = $this->_in(__d('croogo', 'DataSource'), [
            'Mysql',
            'Sqlite',
            'Postgres',
            'Sqlserver'
        ], 'Mysql', 'datasource');
        $install['driver'] = 'Cake\Database\Driver\\' . $install['datasource'];
        $install['host'] = $this->_in(__d('croogo', 'Host'), null, 'localhost', 'host');
        $install['username'] = $this->_in(__d('croogo', 'Login'), null, 'root', 'username');
        $install['password'] = $this->_in(__d('croogo', 'Password'), null, '', 'password');
        $install['database'] = $this->_in(__d('croogo', 'Database'), null, 'croogo', 'database-name');
        //$install['prefix'] = $this->_in(__d('croogo', 'Prefix'), null, '', 'prefix');
        $install['port'] = $this->_in(__d('croogo', 'Port'), null, null, 'port');

        $InstallManager = new InstallManager();
        $InstallManager->createDatabaseFile($install);

        $this->out('Setting up database objects. Please wait...');
        $Install = TableRegistry::get('Croogo/Install.Install');
        try {
            $result = $InstallManager->setupDatabase();
            if ($result !== true) {
                $this->err($result);
                return $this->_stop();
            }
        } catch (\Exception $e) {
            $this->err($e->getMessage());
            $this->err('Please verify you have the correct credentials');
            return $this->_stop();
        }

        try {
            $this->out('Setting up access control objects. Please wait...');
            $generator = new AclGenerator();
            $generator->Shell = $this;
            $generator->insertAcos(ConnectionManager::get('default'));
            $InstallManager->setupGrants();
        } catch (\Exception $e) {
            $this->err('Error installing access control objects');
            $this->err($e->getMessage());
            return $this->_stop();
        }

        if (empty($this->args)) {
            $this->out();
            $this->out('Create Admin user:');
        }

        do {
            $username = $this->_args(__d('croogo', 'Username'), null, null, 0);
            if (empty($username)) {
                $this->err('Username must not be empty');
            }
        } while (empty($username));

        do {
            $password = $this->_args(__d('croogo', 'Password'), null, null, 1);
            if (empty($this->args)) {
                $verify = $this->_in(__d('croogo', 'Verify Password'), null, null, 1);
                $passwordsMatched = $password == $verify;

                if (!$passwordsMatched) {
                    $this->err('Passwords do not match');
                }
            } else {
                $passwordsMatched = true;
            }
            if (empty($password)) {
                $this->err('Password must not be empty');
            }
        } while (empty($password) || !$passwordsMatched);

        $user = ['username' => $username, 'password' => $password];

        try {
            $this->out('Setting up admin user. Please wait...');
            $Install->addAdminUser($user);
            $InstallManager->installCompleted();
        } catch (\Exception $e) {
            $this->err('Error creating admin user: ' . $e->getMessage());
        }

        $this->out();
        $this->success('Congratulations, Croogo has been installed successfully.');
    }
}


text:
<?php
namespace beatrix\tests\mock;
class CModule extends BaseMock{
    public static function includeModule($id){}
}


text:
from iris_sdk.models.maps.base_map import BaseMap

class RoleMap(BaseMap):

    permissions = None
    role_name = None


text:
using JustLogic.Core;
using System.Collections.Generic;
using UnityEngine;

[UnitMenu("GUI/Event/Get Type For Control")]
[UnitFriendlyName("GUIEvent.Get Type For Control")]
[UnitUsage(typeof(EventType), HideExpressionInActionsList = true)]
public class JLGUIEventGetTypeForControl : JLExpression
{
    [Parameter(ExpressionType = typeof(Event))]
    public JLExpression OperandValue;

    [Parameter(ExpressionType = typeof(System.Int32))]
    public JLExpression ControlID;

    public override object GetAnyResult(IExecutionContext context)
    {
        Event opValue = OperandValue.GetResult<Event>(context);
        return opValue.GetTypeForControl(ControlID.GetResult<System.Int32>(context));
    }
}


text:
import { Injectable } from '@angular/core';
import { ToastController, Platform } from 'ionic-angular';
import { Toast as NativeToast } from '@ionic-native/toast';

import { Config } from './config';

/*
  Generated class for the Toast provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/
const TOAST_DURATION = 3000;
const TOAST_POSITION = 'bottom';

@Injectable()
export class Toast {

  constructor(
    public toastCtrl: ToastController,
    public config: Config,
    public platform: Platform,
    public toastNative: NativeToast,
  ) { }

  show(message = '') {
    if (this.platform.is('cordova')) {
      this.toastNative.show(message, `${TOAST_DURATION}`, this.config.getToast('position', TOAST_POSITION)).subscribe();
    } else {
      this.toastCtrl.create({
        message,
        duration: this.config.getToast('duration', TOAST_DURATION)
      }).present();
    }
  }

}


text:
#pragma once

namespace BumbleRumble
{

class Manager;

class ContentManager : public Manager
{
public:
    ContentManager();
    ~ContentManager();

    std::shared_ptr<DX::Texture> LoadTexture(const std::string &path);
    std::shared_ptr<DirectX::SpriteFont> LoadFont(const std::string &path);

private:
    std::map<std::string, std::shared_ptr<DX::Texture>> m_textures;
    std::map<std::string, std::shared_ptr<DirectX::SpriteFont>> m_fonts;
};

}


text:
/* globals QUnit, test, asyncTest */
(function (global) {

    'use strict';

    // block QUnit to try autostart without being ready
    global.QUnit.config.autostart = false;

    var APP = global._MonkeyTestJS = global._MonkeyTestJS || {}, // APP namespace
        $$ = global.$$ = global.jQuery.noConflict(true); // jquery no conflict

    $$(function() {
        // MonkeyTestJS can be configured by assigning the configuration object to a global variable monkeytestjs
        // before this script loads. If no such variable has been defined, this script will attempt to load config.json
        // (via ajax) from the server.
        function configured(config) {
            var monkeytestjs = global.monkeytestjs = new APP.MonkeyTestJS(); // create our singleton
            monkeytestjs.start($$.extend({}, {
                workspace: window.frames[0],
                jQuery: $$
            }, config));
        }
        if (typeof global.monkeytestjs === 'object') {
            var config = global.monkeytestjs;
            configured(config);
        } else {
            $$.getJSON('config.json', function (data) {
                configured(data);
            })
                .fail(function () {
                    global.alert(
                        'Failed to load config.json. Please make sure this file exists and it is correctly formatted.\n\n' +
                        'Alternatively, configure MonkeyTestJS by defining a global variable before including the monkeytestjs script:\n\n' +
                        '    var monkeytestjs = <contents of config.json>;'
                    );
                });
        }

    });

}(this));


text:
package filodb.coordinator.queryplanner

import filodb.prometheus.ast.Vectors.PromMetricLabel
import filodb.query._
import filodb.query.AggregationOperator.CountValues
import filodb.query.InstantFunctionId.{ClampMax, ClampMin}
import filodb.query.RangeFunctionId.QuantileOverTime

object QueryConstants {
  val Quotes = "\""
  val OpeningCurlyBraces = "{"
  val ClosingCurlyBraces = "}"
  val Space = " "
  val Offset = "offset"
  val OpeningRoundBracket = "("
  val ClosingRoundBracket = ")"
  val OpeningSquareBracket = "["
  val ClosingSquareBracket = "]"
  val Comma = ","
}

object LogicalPlanParser {
  import QueryConstants._

  private def getFiltersFromRawSeries(lp: RawSeries)= lp.filters.map(f => (f.column, f.filter.operatorString,
    Quotes + f.filter.valuesStrings.head.toString + Quotes))

  private def filtersToQuery(filters: Seq[(String, String, String)], columns: Seq[String]): String = {
    val columnString = if (columns.isEmpty) "" else s"::${columns.head}"
    // Get metric name from filters and remove quotes from start and end
    val name = s"${filters.find(x => x._1.equals(PromMetricLabel)).head._3.
      replaceAll("^\"|\"$", "")}$columnString"
    // When only metric name is present
    if (filters.size == 1) name
    else s"$name$OpeningCurlyBraces${filters.filterNot(x => x._1.equals(PromMetricLabel)).
      map(f => f._1 + f._2 + f._3).mkString(Comma)}$ClosingCurlyBraces"
  }

  private def rawSeriesLikeToQuery(lp: RawSeriesLikePlan): String = {
    lp match {
      case r: RawSeries               => filtersToQuery(getFiltersFromRawSeries(r), r.columns)
      case a: ApplyInstantFunctionRaw => val filters = getFiltersFromRawSeries(a.vectors)
        val bucketFilter = ("_bucket_", "=", s"$Quotes${functionArgsToQuery(a.functionArgs.head)}$Quotes")
        filtersToQuery(filters :+ bucketFilter, a.vectors.columns)
      case _            => throw new UnsupportedOperationException(s"$lp can't be converted to Query")
    }
  }

  private def periodicSeriesToQuery(periodicSeries: PeriodicSeries): String = {
    s"${rawSeriesLikeToQuery(periodicSeries.rawSeries)}${periodicSeries.offsetMs.map(o => Space + Offset + Space +
      (o / 1000).toString + "s" ).getOrElse("")}"
  }

  private def aggregateToQuery(lp: Aggregate): String = {
    val periodicSeriesQuery = convertToQuery(lp.vectors)
    val byString = if (lp.by.isEmpty) "" else s"${Space}by${Space}$OpeningRoundBracket${lp.by.mkString(Comma)}" +
      ClosingRoundBracket
    val withoutString = if (lp.without.isEmpty) "" else s"${Space}without$Space$OpeningRoundBracket" +
      s"${lp.without.mkString(Comma)}$ClosingRoundBracket"
    val params = if (lp.params.isEmpty) "" else s"${lp.params.mkString(",")},"

    val function = if (lp.operator.equals(CountValues)) "count_values" else lp.operator.toString.toLowerCase
    s"$function$OpeningRoundBracket$params$periodicSeriesQuery$ClosingRoundBracket$byString$withoutString"
  }

  private def absentFnToQuery(lp: ApplyAbsentFunction): String = {
    val periodicSeriesQuery = convertToQuery(lp.vectors)
    s"absent$OpeningRoundBracket$periodicSeriesQuery$ClosingRoundBracket"
  }

  private def functionArgsToQuery(f: FunctionArgsPlan): String = {
    f match {
      case d: ScalarFixedDoublePlan   => d.scalar.toString
      case t: ScalarTimeBasedPlan     => s"${t.function.entryName}$OpeningRoundBracket$ClosingRoundBracket"
      case s: ScalarVaryingDoublePlan => convertToQuery(s.vectors)
      case s: ScalarBinaryOperation   => scalarBinaryOperationToQuery(s)
    }
  }

  private def instantFnToQuery(lp: ApplyInstantFunction): String = {
    val periodicSeriesQuery = convertToQuery(lp.vectors)
    val prefix = lp.function.entryName + OpeningRoundBracket
    if (lp.functionArgs.isEmpty) s"$prefix$periodicSeriesQuery$ClosingRoundBracket"
    else {
      if (lp.function.equals(ClampMax) || lp.function.equals(ClampMin))
        s"$prefix$periodicSeriesQuery$Comma${functionArgsToQuery(lp.functionArgs.head)}$ClosingRoundBracket"
      else s"$prefix${functionArgsToQuery(lp.functionArgs.head)}$Comma$periodicSeriesQuery$ClosingRoundBracket"
    }
  }

  private def scalarBinaryOperationToQuery(lp: ScalarBinaryOperation): String = {
    val rhs = if (lp.rhs.isLeft) lp.rhs.left.get.toString else convertToQuery(lp.rhs.right.get)
    val lhs = if (lp.lhs.isLeft) lp.lhs.left.get.toString else convertToQuery(lp.lhs.right.get)
    s"$lhs$Space${lp.operator.operatorString}$Space$rhs"
  }

  private def scalarVectorBinaryOperationToQuery(lp: ScalarVectorBinaryOperation): String = {
    val periodicSeriesQuery = convertToQuery(lp.vector)
    if (lp.scalarIsLhs) s"${functionArgsToQuery(lp.scalarArg)}$Space${lp.operator.operatorString}$Space" +
      s"$periodicSeriesQuery"
    else s"$periodicSeriesQuery ${lp.operator.operatorString} ${functionArgsToQuery(lp.scalarArg)}"
  }

  private def periodicSeriesWithWindowingToQuery(lp: PeriodicSeriesWithWindowing): String = {
    val rawSeries = rawSeriesLikeToQuery(lp.series)
    val rawSeriesQueryWithWindow = if (lp.window == 0) rawSeries else s"${rawSeries}$OpeningSquareBracket" +
      s"${lp.window/1000}s$ClosingSquareBracket${lp.offsetMs.map(o => s"$Space$Offset$Space${(o / 1000).toString}s")
        .getOrElse("")}"
    val prefix = lp.function.entryName + OpeningRoundBracket
    if (lp.functionArgs.isEmpty) s"$prefix$rawSeriesQueryWithWindow$ClosingRoundBracket"
    else {
      if (lp.function.equals(QuantileOverTime))
        s"$prefix${functionArgsToQuery(lp.functionArgs.head)}$Comma$rawSeriesQueryWithWindow$ClosingRoundBracket"
      else
        s"$prefix$rawSeriesQueryWithWindow$Comma${lp.functionArgs.map(functionArgsToQuery(_)).mkString(Comma)}" +
          s"$ClosingRoundBracket"
    }
  }

  private def sortToQuery(lp: ApplySortFunction): String = {
    val vector = convertToQuery(lp.vectors)
    s"${lp.function.entryName}$OpeningRoundBracket$vector$ClosingRoundBracket"
  }

  private def binaryJoinToQuery(lp: BinaryJoin): String = {
    val lhs = convertToQuery(lp.lhs)
    val rhs = convertToQuery(lp.rhs)
    val on = if (lp.on.isEmpty) "" else s"${Space}on$OpeningRoundBracket${lp.on.mkString(Comma)}$ClosingRoundBracket"
    val ignoring = if (lp.ignoring.isEmpty) "" else s"${Space}ignoring$OpeningRoundBracket" +
      s"${lp.ignoring.mkString(Comma)}$ClosingRoundBracket"

    val groupingType = lp.cardinality match {
      case Cardinality.OneToMany  => s"${Space}group_right"
      case Cardinality.ManyToOne  => s"${Space}group_left"
      case _                      => ""
    }
    val grouping = if (lp.include.isEmpty) groupingType else s"$groupingType$OpeningRoundBracket" +
      s"${lp.include.mkString(Comma)}$ClosingRoundBracket"
    s"$lhs$Space${lp.operator.operatorString}$on$ignoring$grouping$Space$rhs"
  }

  def miscellaneousFnToQuery(lp: ApplyMiscellaneousFunction): String = {
    val prefix = s"${lp.function.entryName}$OpeningRoundBracket${convertToQuery(lp.vectors)}"
    if(lp.stringArgs.isEmpty) s"$prefix$ClosingRoundBracket"
    else s"$prefix$Comma${lp.stringArgs.map(Quotes + _ + Quotes).mkString(Comma)}$ClosingRoundBracket"
  }

  def scalarVaryingDoubleToQuery(lp: ScalarVaryingDoublePlan): String = {
    s"${lp.function.entryName}$OpeningRoundBracket${convertToQuery(lp.vectors)}$ClosingRoundBracket"
  }

  def scalarTimeToQuery(lp: ScalarTimeBasedPlan): String = s"${lp.function.entryName}$OpeningRoundBracket" +
    ClosingRoundBracket

  def vectorToQuery(lp: VectorPlan): String = s"vector$OpeningRoundBracket${convertToQuery(lp.scalars)}" +
    ClosingRoundBracket

  def convertToQuery(logicalPlan: LogicalPlan): String = {
    logicalPlan match {
      case lp: RawSeries                   => rawSeriesLikeToQuery(lp)
      case lp: PeriodicSeries              => periodicSeriesToQuery(lp)
      case lp: Aggregate                   => aggregateToQuery(lp)
      case lp: ApplyAbsentFunction         => absentFnToQuery(lp)
      case lp: ApplyInstantFunction        => instantFnToQuery(lp)
      case lp: ScalarVectorBinaryOperation => scalarVectorBinaryOperationToQuery(lp)
      case lp: ScalarBinaryOperation       => scalarBinaryOperationToQuery(lp)
      case lp: PeriodicSeriesWithWindowing => periodicSeriesWithWindowingToQuery(lp)
      case lp: ApplySortFunction           => sortToQuery(lp)
      case lp: BinaryJoin                  => binaryJoinToQuery(lp)
      case lp: ApplyMiscellaneousFunction  => miscellaneousFnToQuery(lp)
      case lp: ScalarVaryingDoublePlan     => scalarVaryingDoubleToQuery(lp)
      case lp: ScalarTimeBasedPlan         => scalarTimeToQuery(lp)
      case lp: ScalarFixedDoublePlan       => lp.scalar.toString
      case lp: VectorPlan                  => vectorToQuery(lp)
      case _                               => throw new UnsupportedOperationException(s"Logical plan to query not " +
        s"supported for ${logicalPlan}")
    }
  }
}


text:
package flow.netbeans.markdown.highlighter;

import flow.netbeans.markdown.csl.MarkdownLanguageConfig;
import java.util.Collection;
import java.util.EnumSet;
import org.netbeans.api.lexer.InputAttributes;
import org.netbeans.api.lexer.Language;
import org.netbeans.api.lexer.LanguagePath;
import org.netbeans.api.lexer.Token;
import org.netbeans.api.lexer.TokenId;
import org.netbeans.spi.lexer.LanguageEmbedding;
import org.netbeans.spi.lexer.LanguageHierarchy;
import org.netbeans.spi.lexer.Lexer;
import org.netbeans.spi.lexer.LexerRestartInfo;

public enum MarkdownTokenId implements TokenId {

    ABBREVIATION,
    ANCHORLINK,
    AUTOLINK,
    BLOCKQUOTE,
    BULLETLIST,
    CODE,
    EMPH,
    EXPIMAGE,
    EXPLINK,
    HEADER1,
    HEADER2,
    HEADER3,
    HEADER4,
    HEADER5,
    HEADER6,
    HORIZONTALRULE,
    HTMLBLOCK,
    INLINEHTML,
    LISTITEM,
    MAILLINK,
    ORDEREDLIST,
    PLAIN,
    STRONG,
    TABLE,
    VERBATIM,
    WIKILINK,
    DEFINITION,
    DEFINITION_LIST,
    DEFINITION_TERM,
    REFERENCE,
    QUOTED,
    REF_IMAGE,
    REF_LINK,
    WHITESPACE,
    STRIKETHROUGH;

    private static final Language<MarkdownTokenId> LANGUAGE = new LanguageHierarchy<MarkdownTokenId>() {

        @Override
        protected Collection<MarkdownTokenId> createTokenIds() {
            return EnumSet.allOf(MarkdownTokenId.class);
        }

        @Override
        protected Lexer<MarkdownTokenId> createLexer(LexerRestartInfo<MarkdownTokenId> info) {
            return MarkdownLexer.create(info);
        }

        @Override
        protected String mimeType() {
            return MarkdownLanguageConfig.MIME_TYPE;
        }

        @Override
        protected LanguageEmbedding<?> embedding(Token<MarkdownTokenId> token, LanguagePath languagePath, InputAttributes inputAttributes) {
          if ((token.id() == MarkdownTokenId.HTMLBLOCK) || (token.id() == MarkdownTokenId.INLINEHTML)) {
            Language<?> htmlLanguage = Language.find("text/html");
            if (htmlLanguage != null) {
              return LanguageEmbedding.create(htmlLanguage, 0, 0);
            }
          }
          return null;
        }
    }.language();

    @Override
    public String primaryCategory() {
        return this.name().toLowerCase();
    }

    public static Language<MarkdownTokenId> language() {
        return LANGUAGE;
    }
}


text:
var _ = require('lodash');
var logger = require('winston'); // application log file
var what3words = require('../what3words');

/**
 * [description]
 * @param  {[type]} req             [description]
 * @param  {[type]} res             [description]
 * @param  {[type]} promiseThrottle [description]
 * @return {[type]}                 [description]
 */
module.exports = function (req, res, promiseThrottle) {
  var query = req.query;
  // var partial = false;
  if (typeof query.addr === 'undefined') {
    res.send({
      code: 400,
      message: 'missing required parameter \'addr\''
    });
  }
  var n = query.addr.split('.').length - 1;
  logger.log('debug', 'n dot is', n);
  var nstop = 2 - n;
  logger.log('debug', 'nstop to add', nstop);
  if (nstop === 2) {
    query.addr = query.addr + '.a.a';
    query.count = 12;
  } else if (nstop === 1) {
    query.addr = query.addr + '.a';
    query.count = 9;
  }
  var promises = [];
  var p;
  if (typeof promiseThrottle === 'undefined') {
    p = what3words.autosuggest(query);
  } else {
    p = promiseThrottle.add(what3words.autosuggest.bind(this, query));
  }
  promises.push(p);

  var result = null;
  p.then(function (value) {
    logger.log('debug', 'return value is', value);
    if (nstop === 0) {
      result = JSON.parse(value);
    } else {
      result = {
        status: {
          reason: 'OK',
          status: 200
        },
        suggestions: [],
        thanks: 'thanks for using what3words extended API'
      };
      var suggestions = [];
      _.forEach(JSON.parse(value).suggestions, function (suggestion) {
        if (nstop === 1) {
          suggestions.push({
            words: suggestion.words.substr(0, suggestion.words.lastIndexOf('.'))
          });
        } else if (nstop === 2) {
          suggestions.push({
            words: suggestion.words.substr(0, suggestion.words.indexOf('.'))
          });
        }
      });
      result.suggestions = _.uniqWith(suggestions, _.isEqual);
    }
    res.send(result);
  });
};


text:
package org.wyona.yanel.core.attributes.annotatable;

import org.apache.log4j.Logger;

/**
 * Utility class to read, write annotations, etc.
 */
public class Util {

    private static Logger log = Logger.getLogger(Util.class);

    private static final String ANNOTATIONS_PROP_NAME = "annotations";

    /**
     * Read annotations
     * @param repo Repository containing annotations
     * @param path Path for which annotations are associated with
     * @return annotations, whereas return empty list if there are no annotations yet
     */
    public static java.util.Set<String> readAnnotations(org.wyona.yarep.core.Repository repo, String path) throws Exception {
        java.util.Set<String> annotations  = new java.util.HashSet<String>();
        if (repo.existsNode(path) && repo.getNode(path).hasProperty(ANNOTATIONS_PROP_NAME)) {
            String aString = repo.getNode(path).getProperty(ANNOTATIONS_PROP_NAME).getString();
            String[] aArray = aString.split(", ");
            for(int i = 0; i < aArray.length; i++) {
                annotations.add(aArray[i]);
            }
        } else {
           log.info("No annotations yet: " + path);
        }
        return annotations;
    }

    /**
     * Save one particular annotation
     * @param annotation Annotation to be set/saved
     * @param repo Repository containing annotation
     * @param path Path for which annotation is associated with
     */
    public static void saveAnnotation(String annotation, org.wyona.yarep.core.Repository repo, String path) throws Exception {
        java.util.Set<String> existingAnnotations = readAnnotations(repo, path);
        if(annotation != null && !existingAnnotations.contains(annotation)){
            existingAnnotations.add(annotation);
            saveAnnotations(existingAnnotations, repo, path);
        } else {
            log.warn("Either no annotation or annotation already exists: " + annotation + " (Repository node path: " + path + ")");
        }
    }

    /**
     * Save annotations
     * @param annotations Annotations to be set/saved
     * @param repo Repository containing annotations
     * @param path Path for which annotations are associated with
     */
    public static void saveAnnotations(java.util.Set<String> annotations, org.wyona.yarep.core.Repository repo, String path) throws Exception {
        String[] aArray = annotations.toArray(new String[0]);
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < aArray.length; i++) {
            sb.append(aArray[i]);
            if (i < aArray.length - 1) {
                sb.append(", ");
            }
        }
        log.debug("Save annotations: " + sb);
        repo.getNode(path).setProperty(ANNOTATIONS_PROP_NAME, sb.toString());
    }
}


text:
package edu.nyu.classes.popup.api;

import java.io.IOException;

public interface Popup {
    public boolean isActive();
    public String getCampaign();
    public String getTemplate() throws IOException;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
	"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.lachesis.mnis.core.mybatis.mapper.NurseWhiteBoardMapper">
	<resultMap id="nurseWhiteBoardMetadataMap" type="NurseWhiteBoardMetadata">
		<id property="id" column="id" />
		<result property="code" column="code" />
		<result property="name" column="name" />
		<result property="parentId" column="parent_id" />
		<result property="level" column="level" />
		<result property="inputType" column="input_type" />
		<result property="showType" column="show_type" />
		<result property="deptCode" column="dept_code" />
		<result property="isAuto" column="is_auto" />
		<result property="isBedCode" column="is_bed_code"/>
		<result property="isEdit" column="is_edit" />
		<result property="isExec" column="is_exec" />
		<result property="isDosage" column="is_dosage" />
		<result property="columnNo" column="column_no" />
		<result property="rowNo" column="row_no" />
		<result property="columnType" column="column_type" />
		<result property="backgroundColor" column="background_color" />
		<result property="width" column="width" />
		<result property="titleWidth" column="title_width" />
		<result property="height" column="height" />
		<result property="isColspan" column="is_colspan"></result>
		<result property="templateId" column="template_id" />
		<result property="isShowTitle" column="is_show_title" />
		<result property="isShowData" column="is_show_data" />
		<result property="isShowLineR" column="is_show_line_r" />
		<result property="isShowLineB" column="is_show_line_b" />
		<result property="isShowLineT" column="is_show_line_t" />
		<result property="includeRow" column="include_row" />
		<result property="titleFontSize" column="title_font_size" />
		<result property="contentFontSize" column="content_font_size" />
		<collection property="nurseWhiteBoardEditTypes" resultMap="nurseWhiteBoardEditTypeMap"></collection>
	</resultMap>

	<resultMap id="nurseWhiteBoardMetadataTVMap" type="com.lachesis.mnis.core.whiteBoard.entity.NurseWhiteBoardMetadataTV">
		<id property="id" column="id" />
		<result property="code" column="code" />
		<result property="name" column="name" />
		<result property="deptCode" column="dept_code" />
		<result property="columnNo" column="column_no" />
		<result property="rowNo" column="row_no" />
		<result property="width" column="width" />
		<result property="titleWidth" column="title_width" />
		<result property="templateId" column="template_id" />
		<result property="isShowTitle" column="is_show_title" />
		<result property="isShowData" column="is_show_data" />
		<result property="isShowLineR" column="is_show_line_r" />
		<result property="isShowLineB" column="is_show_line_b" />
		<result property="isShowLineT" column="is_show_line_t" />
		<result property="isDosage" column="is_dosage" />
		<result property="isBedCode" column="is_bed_code" />
		<result property="includeRow" column="include_row" />
		<result property="titleFontSize" column="title_font_size" />
		<result property="contentFontSize" column="content_font_size" />
	</resultMap>

	<resultMap id="nurseWhiteBoardEditTypeMap" type="com.lachesis.mnis.core.whiteBoard.entity.NurseWhiteBoardEditType">
		<id property="id" column="et_id"></id>
		<result property="type" column="et_type"></result>
		<result property="code" column="et_code"></result>
		<result property="isMulti" column="et_is_multi"></result>
		<result property="isInner" column="et_is_inner"></result>
		<result property="isBedCode" column="is_bed_code"></result>
		<result property="templateId" column="et_template_id"></result>
	</resultMap>

	<resultMap id="nurseWhiteBoardRecordMap" type="NurseWhiteBoardRecord">
		<id property="recordCode" column="record_code" />
		<result property="recordName" column="record_name" />
		<result property="deptCode" column="dept_code" />
		<result property="isExec" column="is_exec" />
		<collection property="nurseWhiteBoardRecordFreqInfos"
			resultMap="nurseWhiteBoardRecordFreqInfoMap"></collection>
	</resultMap>
	<resultMap id="nurseWhiteBoardRecordInfoMap" type="NurseWhiteBoardRecordInfo">
		<id property="recordId" column="record_id" />
		<result property="recordValue" column="record_value" />
		<result property="orderNo" column="order_no" />
		<result property="recordNurseCode" column="record_user_code" />
		<result property="recordNurseName" column="record_user_name" />
		<result property="recordDate" column="record_date" />
		<result property="patInfo" column="pat_info" />
		<result property="patId" column="pat_id" />
		<result property="performSchedule" column="perform_schedule" />
		<collection property="nurseWhiteBoardRecordItemInfos"
			resultMap="nurseWhiteBoardRecordItemInfoMap"></collection>
	</resultMap>

	<resultMap id="nurseWhiteBoardRecordItemMap" type="NurseWhiteBoardRecordItem">
		<id property="recordCode" column="record_code" />
		<result property="recordName" column="record_name" />
		<result property="deptCode" column="dept_code" />
		<collection property="nurseWhiteBoardRecordItemInfos"
			resultMap="nurseWhiteBoardRecordItemInfoMap"></collection>
	</resultMap>
	<resultMap id="nurseWhiteBoardRecordItemInfoMap" type="NurseWhiteBoardRecordItemInfo">
		<id property="recordItemId" column="item_id" />
		<result property="recordId" column="record_id" />
		<result property="recordItemCode" column="item_code" />
		<result property="recordItemName" column="item_name" />
		<result property="recordItemValue" column="item_value" />
		<result property="recordItemDate" column="item_date" />
		<result property="status" column="is_finish" />
	</resultMap>

	<resultMap id="nurseWhiteBoardRecordFreqInfoMap" type="com.lachesis.mnis.core.whiteBoard.entity.NurseWhiteBoardRecordFreqInfo">
		<id property="randomId" column="random_id" />
		<result property="performSchedule" column="perform_schedule" />
		<result property="recordValue" column="record_value" />
		<result property="orderNo" column="order_no" />
		<collection property="nurseWhiteBoardRecordFreqPatInfos" ofType="com.lachesis.mnis.core.whiteBoard.entity.NurseWhiteBoardRecordFreqPatInfo">
			<id property="patId" column="pat_id" />
			<result property="recordId" column="record_id" />
			<result property="patInfo" column="pat_info" />
		</collection>
		<collection property="nurseWhiteBoardRecordFreqItems" ofType="com.lachesis.mnis.core.whiteBoard.entity.NurseWhiteBoardRecordFreqItem">
			<id property="recordItemCode" column="item_code" />
			<result property="recordItemName" column="item_name" />
			<result property="simpleRecordItemName" column="item_name" />
		</collection>
	</resultMap>

	<!-- 获取元数据的编号和名称对应 -->
	<resultMap type="java.util.Map" id="metadataCodeName">
		<result property="code" column="code"/>
		<result property="name" column="name"/>
	</resultMap>

	<!-- 小白板项目配置表 -->
	<resultMap id="nwbMetadataDic" type="com.lachesis.mnis.core.whiteBoard.entity.NurseWhiteBoardMetadataDic" >
		<id property="code" column="code"/>
		<result property="name" column="name"/>
		<result property="isSelected" column="is_selected" />
	</resultMap>

	<!-- 小白板项目配置表 -->
	<resultMap id="nwbTemplateMap" type="com.lachesis.mnis.core.whiteBoard.entity.NurseWhiteBoardTemplate" >
		<id property="id" column="id"/>
		<result property="deptCode" column="dept_code"/>
		<result property="title" column="title" />
		<result property="titleFontSize" column="title_font_size"/>
		<result property="background" column="background"/>
		<result property="rowCount" column="row_count"/>
	</resultMap>

	<!-- 元数据 -->
	<sql id="nwbMetadataSql">
		nm.code,
		nm.name,
		nm.parent_id,
		nm.dept_code,
		nm.level,
		nm.input_type,
		nm.is_auto,
		nm.is_exec,
		nm.is_dosage,
		nm.column_no,
		nm.row_no,
		nm.show_type,
		nm.is_edit,
		nm.column_type,
		nm.background_color,
		nm.is_bed_code,
		nm.is_colspan,
		nm.width,
		nm.title_width,
		nm.height,
		nm.template_id,
		nm.is_show_title,
		nm.is_show_data,
		nm.is_show_line_r,
		nm.is_show_line_b,
		nm.is_show_line_t,
		nm.include_row,
		nm.title_font_size,
		nm.content_font_size
	</sql>

	<sql id="editTypeSql">
		et.id et_id,
		et.code et_code,
		et.type et_type,
		et.is_inner et_is_inner,
		et.template_id et_template_id,
		et.is_multi et_is_multi
	</sql>

	<select id="getNwbMetadataDics" parameterType="String" resultMap="nwbMetadataDic">
		SELECT wbt.item_code code,wbt.item_name name,
		case when (nm.id is null or nm.id=0) then 0
		else 1 end is_selected
		FROM WHITE_BOARD_ITEM wbt
		left join NURSE_WHITE_BOARD_METADATA nm on nm.code=wbt.item_code
		and nm.is_valid = '1' and nm.dept_code=#{param1}
	</select>

	<select id="getNurseWhiteBoardTopMetadatas" parameterType="String"
		resultMap="nurseWhiteBoardMetadataMap">
		SELECT
		nm.id,
		<include refid="nwbMetadataSql"></include>,
		<include refid="editTypeSql"/>
		FROM NURSE_WHITE_BOARD_METADATA nm
		left join NURSE_WHITE_BOARD_EDIT_TYPE_DIC et on et.metadata_code=nm.code
		and et.template_id = nm.template_id and et.is_valid='1'
		WHERE
		nm.is_valid = '1' and
		(nm.parent_id is null or nm.parent_id = '') and
		(nm.dept_code=#{param1} or nm.dept_code is null)

		<if test="param2 != null">
			and nm.code = #{param2}
		</if>
		order by nm.level,nm.row_no,nm.column_no, nm.column_type
	</select>

	<select id="getNurseWhiteBoardMetadatasByIds" parameterType="String"
		resultMap="nurseWhiteBoardMetadataMap">
		SELECT
		nm.id,
		<include refid="nwbMetadataSql"/>
		FROM NURSE_WHITE_BOARD_METADATA nm
		WHERE
		nm.is_valid = '1'
		<if test="param1 != null">
			AND nm.id = #{param1}
		</if>
		<if test="param2 != null">
			AND nm.parent_id = #{param2}
		</if>
		ORDER BY nm.level
	</select>

	<select id="getNurseWhiteBoardTVMetadatas" parameterType="String"
		resultMap="nurseWhiteBoardMetadataTVMap">
		SELECT
			nm.id,
			nm.code,
			nm.name,
			nm.dept_code,
			nm.template_id,
			nm.is_bed_code,
			nm.is_show_title,
			nm.is_show_data,
			nm.is_show_line_r,
			nm.is_show_line_b,
			nm.is_show_line_t,
			nm.column_no,
			nm.row_no,
			nm.include_row,
			nm.width,
			nm.title_width,
			nm.title_font_size,
			nm.is_dosage,
			nm.content_font_size
			FROM NURSE_WHITE_BOARD_METADATA nm
		WHERE
		nm.is_valid = '1' and
		(nm.dept_code=#{param1} or nm.dept_code is null)
		order by nm.level,nm.row_no,nm.column_no, nm.column_type
	</select>

	<!-- 获取所有元数据的编号和名称 -->
	<select id="selectMetadataName" parameterType="String" resultMap="metadataCodeName">
		select distinct code,name
		from NURSE_WHITE_BOARD_METADATA
		WHERE is_valid = '1'
		and dept_code = #{param1}
		<if test="param2 != null">
			and parent_id=#{param2}
		</if>
	</select>

	<select id="getMetadataNameValue" parameterType="String" resultMap="metadataCodeName">
		select mv_value as name,mv_code as code
		from NURSE_WHITE_BOARD_METADATA_VALUE
		WHERE is_valid='1'
		and mv_type = #{param1}
	</select>

	<select id="getFreqTypes" resultType="String">
		select distinct mv_type
		from NURSE_WHITE_BOARD_METADATA_VALUE
		WHERE is_valid='1'
	</select>

	<select id="getParentMetadatas" parameterType="String" resultType="String">
		select m.parent_id from NURSE_WHITE_BOARD_METADATA m
		where m.is_valid='1' and m.dept_code=#{param1} and m.parent_id is not null
	</select>

	<!-- 获取所有元数据的编号和名称 -->
	<select id="getSubMetadatas" parameterType="String" resultMap="metadataCodeName">
		select m.code as code,m.name as name
		from NURSE_WHITE_BOARD_METADATA m
		where
		m.is_valid = '1'
		and m.dept_code=#{param1}
		and m.parent_id is not null
		and m.parent_id = #{param2}
	</select>

	<select id="getFreqMetadataCodes" parameterType="String" resultType="String">
		select m.code as code
		from NURSE_WHITE_BOARD_METADATA m
		where
		m.is_valid = '1'
		and m.is_include_freq = '1'
		and m.dept_code=#{deptCode}
	</select>
	<select id="getNwbMetadataCount" parameterType="String" resultType="int">
		select count(1) from NURSE_WHITE_BOARD_METADATA
		where is_valid = '1'
		and dept_code = #{param1}
		<choose>
			<when test="param2 != null">
				and code = #{param2}
			</when>
			<otherwise>
				and row_no = #{param3}
			</otherwise>
		</choose>
	</select>
	<select id="getNwbMetadataRowNo" parameterType="String" resultType="String">
		select top 1 row_no from NURSE_WHITE_BOARD_METADATA
		where is_valid = '1'
		and dept_code = #{param1}
		and code = #{param2}
	</select>

	<select id="getNwbEditTypeCount" parameterType="String" resultType="int">
		select count(1) from NURSE_WHITE_BOARD_EDIT_TYPE_DIC
		where is_valid = '1'
		and type = #{param1}
		<choose>
			<when test="param2 != null ">
				and code = #{param2}
			</when>
			<otherwise>
				and (code = '' or code is null)
			</otherwise>
		</choose>

		and metadata_code = #{param3}
		and template_id = #{param4}
	</select>

	<select id="getMetadataCodes" parameterType="String" resultType="String">
		select distinct code from NURSE_WHITE_BOARD_METADATA nm
		where nm.is_valid = '1'
		and nm.dept_code = #{param1}
		<choose>
			<when test="param2 == 'edit'">
				and nm.is_edit = '1'
			</when>
			<otherwise>
				and nm.is_dosage = '1'
			</otherwise>
		</choose>
	</select>

	 <insert id="saveNwbMetadata" parameterType="NurseWhiteBoardMetadata">
		INSERT INTO NURSE_WHITE_BOARD_METADATA(
		code,name,parent_id,dept_code,
		level,input_type,is_auto,
		column_no,row_no,show_type,is_edit,is_exec,is_dosage,
		column_type,background_color,
		is_bed_code,is_colspan,height,width,title_width,create_date,is_valid,
		template_id,is_show_title,is_show_data,is_show_line_r,is_show_line_b,
		is_show_line_t,include_row,title_font_size,content_font_size)
		VALUES
		(#{code},#{name},#{parentId},#{deptCode},
		#{level},#{inputType},#{isAuto},
		#{columnNo},#{rowNo},#{showType},#{isEdit},#{isExec},#{isDosage},
		#{columnType},#{backgroundColor},
		#{isBedCode},#{isColspan},#{height},#{width},#{titleWidth},GETDATE(),'1',
		#{templateId},#{isShowTitle},#{isShowData},#{isShowLineR},#{isShowLineB},
		#{isShowLineT},#{includeRow},#{titleFontSize},#{contentFontSize})
	</insert>

	<update  id="updateNwbMetadata" parameterType="NurseWhiteBoardMetadata">
		UPDATE NURSE_WHITE_BOARD_METADATA
		<set>
			<if test="code != null">
				code = #{code},
			</if>
			<if test="name != null">
				name = #{name},
			</if>
			<if test="parentId != null">
				parent_id = #{parentId},
			</if>
			<if test="deptCode != null">
				dept_code = #{deptCode},
			</if>
			<if test="level != null">
				level = #{level},
			</if>
			<if test="inputType != null">
				input_type = #{inputType},
			</if>
			<if test="isAuto != null">
				is_auto = #{isAuto},
			</if>
			<if test="isEdit != null">
				is_edit = #{isEdit},
			</if>
			<if test="isExec != null">
				is_exec = #{isExec},
			</if>
			<if test="isDosage != null">
				is_dosage = #{isDosage},
			</if>
			<if test="isBedCode != null">
				is_bed_code = #{isBedCode},
			</if>
			<if test="columnNo != null">
				column_no = #{columnNo},
			</if>
			<if test="rowNo != null">
				row_no = #{rowNo},
			</if>
			<if test="showType != null">
				show_type = #{showType},
			</if>
			<if test="columnType != null">
				column_type = #{columnType},
			</if>
			<if test="backgroundColor != null">
				background_color = #{backgroundColor},
			</if>
			<if test="isColspan != null">
				is_colspan = #{isColspan},
			</if>
			<if test="height != null">
				height = #{height},
			</if>
			<if test="width != null">
				width = #{width},
			</if>
			<if test="titleWidth != null ">
				title_width = #{titleWidth},
			</if>
			<if test="templateId != null">
				template_id = #{templateId},
			</if>
			<if test="isShowData != null">
				is_show_data = #{isShowData},
			</if>
			<if test="isShowTitle != null">
				is_show_title = #{isShowTitle},
			</if>
			<if test="isShowLineR != null">
				is_show_line_r = #{isShowLineR},
			</if>
			<if test="isShowLineB != null">
				is_show_line_b = #{isShowLineB},
			</if>
			<if test="isShowLineT != null">
				is_show_line_t = #{isShowLineT},
			</if>
			<if test="includeRow != null">
				include_row = #{includeRow},
			</if>
			<if test="contentFontSize != null">
				content_font_size = #{contentFontSize},
			</if>
			<if test="titleFontSize != null">
				title_font_size = #{titleFontSize},
			</if>

		</set>
		WHERE
			IS_VALID = '1' and id = #{id}
	</update>

	<update  id="updateNwbMetadataByRowNo" parameterType="java.util.HashMap">
		UPDATE NURSE_WHITE_BOARD_METADATA
		SET
			<choose>
				<when test="oldRowNo > 0">
					row_no = #{newRowNo}
				</when>
				<otherwise>
					row_no = row_no + 1
				</otherwise>
			</choose>

		WHERE
			is_valid = '1'
			and dept_code = #{deptCode}
			<choose>
				<when test="oldRowNo > 0">
					and row_no = #{oldRowNo}
				</when>
				<otherwise>
					and row_no >= #{newRowNo}
				</otherwise>
			</choose>

	</update>

	<update  id="deleteNwbMetadata" parameterType="String">
		UPDATE NURSE_WHITE_BOARD_METADATA SET IS_VALID = '0'
		WHERE IS_VALID = '1'
		<choose>
			<when test="param2 != null and param2 != ''">
				and code = #{param2}
				and dept_code = #{param3}
			</when>
			<otherwise>
				and id = #{param1}
			</otherwise>
		</choose>

	</update>

	<insert id="saveNwbEditType" parameterType="com.lachesis.mnis.core.whiteBoard.entity.NurseWhiteBoardEditType">
		INSERT INTO NURSE_WHITE_BOARD_EDIT_TYPE_DIC(type,code,is_multi,is_inner,metadata_code,is_valid,template_id)
		VALUES(
			#{type},#{code},#{isMulti},#{isInner},#{metadataCode},'1',#{templateId}
		)
	</insert>

	<update id="updateNwbEditType" parameterType="com.lachesis.mnis.core.whiteBoard.entity.NurseWhiteBoardEditType">
		UPDATE NURSE_WHITE_BOARD_EDIT_TYPE_DIC
		<set>
			<if test="type != null">
				type = #{type},
			</if>
			<if test="code != null">
				code = #{code},
			</if>
			<if test="isMulti != null">
				is_multi = #{isMulti},
			</if>
			<if test="isInner != null">
				is_inner = #{isInner},
			</if>
			<if test="templateId != null">
				template_id = #{templateId},
			</if>
			<if test="metadataCode != null">
				metadata_code = #{metadataCode}
			</if>
		</set>
		WHERE is_valid = '1' and id = #{id}
	</update>

	<update  id="deleteNwbEditType" parameterType="String">
		UPDATE NURSE_WHITE_BOARD_EDIT_TYPE_DIC SET IS_VALID = '0'
		WHERE IS_VALID = '1'
		and metadata_code = #{param1}
		and template_id = #{param2}
	</update>

	<select id="getNwbTemplates" parameterType="String" resultMap="nwbTemplateMap">
		select * from NURSE_WHITE_BOARD_TEMPLATE m
		where m.is_valid = '1' and m.dept_code = #{param1}
		<if test="param2 != null">
			and id=#{param2}
		</if>
	</select>

	<insert id="saveNwbTemplate" parameterType="com.lachesis.mnis.core.whiteBoard.entity.NurseWhiteBoardTemplate"
		useGeneratedKeys="true" keyProperty="id">
		insert into NURSE_WHITE_BOARD_TEMPLATE(dept_code,title,title_font_size,row_count,background,is_valid)
		values(#{deptCode},#{title},#{titleFontSize},#{rowCount},#{background},'1')
	</insert>

	<update id="updateNwbTemplate" parameterType="com.lachesis.mnis.core.whiteBoard.entity.NurseWhiteBoardTemplate" >
		update NURSE_WHITE_BOARD_TEMPLATE
		<set>
			<if test="deptCode != null">
				dept_code=#{deptCode},
			</if>
			<if test="title != null">
				title=#{title},
			</if>
			<if test="titleFontSize != null">
				title_font_size=#{titleFontSize},
			</if>
			<if test="rowCount != null">
				row_count=#{rowCount},
			</if>
			<if test="background != null">
				background=#{background},
			</if>
		</set>
		WHERE
			is_valid = '1' and id=#{id}
	</update>

	<update id="deleteNwbTemplate" parameterType="String" >
		update NURSE_WHITE_BOARD_TEMPLATE set is_valid='0'
		where m.is_valid = '1' and m.dept_code = #{param1}
		<if test="param2 != null">
			and id=#{param2}
		</if>
	</update>

	<!--************************ 小白板记录************************** -->
	<sql id="nwbRecordSql">
		nr.record_code,
		nr.record_name,
		nr.record_value,
		nr.dept_code,
		nr.order_no,
		nr.record_user_code,
		nr.record_user_name,
		nr.record_date,
		nr.pat_id,
		nr.pat_info,
		nr.is_valid,
		nr.perform_schedule,
		nr.random_id
	</sql>

	<sql id="nwbRecordItemSql">
		nri.item_code,
		nri.item_name,
		nri.item_value,
		nri.item_date,
		nri.exec_date,
		nri.item_pat_id,
		nri.item_pat_info,
		nri.start_item_date,
		nri.end_item_date,
		nri.is_finish,
		nri.is_valid
	</sql>

	<sql id="insertNwbRecordSql">
		insert into
		NURSE_WHITE_BOARD_RECORD(
		<include refid="nwbRecordSql" />
		)
		values(#{recordCode}, #{recordName}, #{recordValue},
		#{deptCode},#{orderNo},#{recordNurseCode},#{recordNurseName},
		#{recordDate},#{patId},#{patInfo},#{isValid},#{performSchedule},#{randomId})
	</sql>
 	<select id="getNurseWhiteBoardRecords" parameterType="String"
		resultMap="nurseWhiteBoardRecordMap">
		SELECT
		nr.random_id,
		nr.record_id,
		nr.record_code,
		nr.record_name,
		nr.record_value,
		nr.dept_code,
		nr.order_no,
		nr.record_user_code,
		nr.record_user_name,
		nr.record_date,
		nr.pat_id,
		nr.pat_info,
		nr.perform_schedule,
		nri.item_id,
		nri.item_code,
		nri.item_name,
		nri.item_value,
		nri.item_date,
		nri.is_finish,
		m.is_exec
		FROM NURSE_WHITE_BOARD_RECORD nr
		inner join NURSE_WHITE_BOARD_METADATA m on nr.record_code = m.code
		LEFT JOIN
		NURSE_WHITE_BOARD_RECORD_ITEM nri ON nr.record_id = nri.record_id
		and nri.is_finish = 1 and nri.is_valid = 1
		WHERE
		nr.is_valid = 1
		AND
		nr.dept_code = #{deptCode}
		<if test="code != null">
			AND nr.record_code = #{code}
		</if>
		<if test="patIds != null and patIds.size() >0">
			AND nr.pat_id IN (
			<foreach collection="patIds" item="patientId" separator=",">
				#{patientId}
			</foreach>
			)
		</if>
		<if test="param4 != null and param5 != null">
			AND nr.record_date BETWEEN #{param4} AND #{param5}
		</if>
		ORDER BY nr.record_date
	</select>

	<select id="isExistNwbRecord" parameterType="String" resultType="Integer">
		select count(*) from NURSE_WHITE_BOARD_RECORD nr
		where nr.record_code = #{param1}
		and nr.is_valid = '1'
		and nr.dept_code=#{param3}
		<choose>
			<when test="param2 != null">
				and nr.pat_id = #{param2}
			</when>
			<otherwise>
				and nr.record_value is not null
			</otherwise>
		</choose>
	</select>

	<select id="getExistNwbRecordCodes" parameterType="String" resultType="String">
		SELECT DISTINCT
			CASE WHEN nr.pat_id is null THEN nr.record_code
			ELSE nr.record_code + '-' + nr.pat_id
			END record_code
		FROM NURSE_WHITE_BOARD_RECORD nr
		INNER JOIN NURSE_WHITE_BOARD_METADATA nm
		ON nr.record_code = nm.code and nr.DEPT_CODE = nm.DEPT_CODE and nm.is_valid = '1'
		WHERE nr.dept_code = #{param1}
	</select>

	<select id="getExistNwbViewRecordCodes" parameterType="String" resultType="String">
		SELECT DISTINCT
			CASE WHEN nr.pat_id is null THEN nr.record_code
			ELSE nr.record_code + '-' + nr.pat_id
			END record_code
		FROM VIEW_NURSE_WHITE_BOARD_RECORD nr
		INNER JOIN NURSE_WHITE_BOARD_METADATA nm
		ON nr.record_code = nm.code and nr.DEPT_CODE = nm.DEPT_CODE and nm.is_valid = '1'
		WHERE nr.dept_code = #{param1}
		AND nr.record_date <= #{param2}
		AND nr.is_valid = '1' and nr.is_stop = '0'
	</select>

	<select id="getNurseWhiteBoardDynamicRecords" parameterType="String"
		resultMap="nurseWhiteBoardRecordMap">
		select *
  			from (select RANDOM_ID,
               RECORD_ID,
               RECORD_CODE,
               RECORD_NAME,
               RECORD_VALUE,
               RECORD_DATE,
               PERFORM_SCHEDULE,
               DEPT_CODE,
               BED_CODE,
               PAT_ID,
               PAT_INFO,
               ITEM_ID,
               ITEM_CODE,
               ITEM_NAME,
               ITEM_VALUE,
               ITEM_DATE,
               IS_FINISH,
               IS_EXEC,
               IS_VALID,
               IS_STOP,
               row_number() over(partition by random_id,pat_id,item_code order by record_date desc) as cn
          from VIEW_NURSE_WHITE_BOARD_RECORD vr
	      where vr.dept_code = #{param1}
			<if test="param2 != null">
				and vr.record_code = #{param2}
			</if> ) v_record
 		  where v_record.cn = 1
		  and (v_record.IS_VALID = '1' and v_record.IS_STOP = '0')
 		  order by LEN(v_record.BED_CODE), v_record.BED_CODE

	</select>

	<select id="getNwbRecordLastRecordDate" resultType="String" parameterType="String">
		select top 1 record_date from NURSE_WHITE_BOARD_RECORD
		where dept_code=#{param1}
		order by record_date desc
	</select>

	<select id="getNwbOrderDataMap" resultMap="metadataCodeName" parameterType="String">
	select distinct tab.item_code name, tab.item_code + '-' + tab.pat_id code  from
	   (select d.ITEM_CODE,d.PAT_ID,d.IS_STOP ,
			row_number() over(partition by d.pat_id,d.item_code order by d.item_date desc,d.is_stop ) cn
			from WHITE_BOARD_DATA d
			inner join NURSE_WHITE_BOARD_METADATA m on d.item_code = m.code
			inner join PAT_CURE_INFO p on p.pat_id = d.pat_id
			where m.dept_code=#{param1} and
			p.ward_code = #{param1}
			and (d.item_date >= #{param2}
				or d.stop_date >= #{param2})
		) tab where tab.cn=1
		and tab.IS_STOP='1'

	</select>

	<insert id="insertNurseWhiteBoardRecordInfo" parameterType="NurseWhiteBoardRecordInfo"
		useGeneratedKeys="true" keyProperty="recordId">
		<include refid="insertNwbRecordSql"></include>
	</insert>

	<insert id="insertNurseWhiteBoardRecordInfoAndItems"
		parameterType="NurseWhiteBoardRecordInfo">
		<selectKey resultType="int" keyProperty="recordId" order="BEFORE">
			<include refid="insertNwbRecordSql" />
			select @@IDENTITY as id
		</selectKey>
		<if
			test="nurseWhiteBoardRecordItemInfos!=null and nurseWhiteBoardRecordItemInfos.size!=0">
			insert into
			NURSE_WHITE_BOARD_RECORD_ITEM(
			<include refid="nwbRecordItemSql" />
			,nri.record_id
			)
			(
			<foreach collection="nurseWhiteBoardRecordItemInfos" item="item"
				index="index" separator="union all">
				select
				#{item.recordItemCode},#{item.recordItemName},#{item.recordItemValue},GETDATE(),#{item.execItemDate},
				#{item.itemPatId},#{item.itemPatInfo},#{item.startRecordItemDate},#{item.endRecordItemDate},#{item.status},
				1,#{recordId}

			</foreach>
			)
		</if>
	</insert>

	<update id="updateNurseWhiteBoardRecordInfo" parameterType="NurseWhiteBoardRecordInfo">
		update NURSE_WHITE_BOARD_RECORD
		<set>
			<if test="recordCode != null">
				record_code = #{recordCode},
			</if>
			<if test="recordName != null">
				record_name = #{recordName},
			</if>
			<if test="recordValue != null">
				record_value = #{recordValue},
			</if>
			<if test="deptCode != null">
				dept_code = #{deptCode},
			</if>
			<if test="orderNo != null">
				order_no = #{orderNo},
			</if>
			<if test="recordNurseCode != null">
				record_user_code = #{recordNurseCode},
			</if>
			<if test="recordNurseName != null">
				record_user_name = #{recordNurseName},
			</if>
			<if test="recordDate != null">
				record_date = #{recordDate},
			</if>
			<if test="patId != null">
				pat_id = #{patId},
			</if>
			<if test="patInfo != null">
				pat_info = #{patInfo},
			</if>
		</set>
		where record_code = #{recordCode}
		and dept_code = #{deptCode}
		<if test="patId != null">
			and pat_id = #{patId}
		</if>
		and is_valid = '1'
	</update>

	<delete id="deleteNurseWhiteBoardRecordInfoById" parameterType="String">
		DELETE FROM NURSE_WHITE_BOARD_RECORD_ITEM WHERE RECORD_ID = #{param1}
		DELETE FROM NURSE_WHITE_BOARD_RECORD WHERE RECORD_ID = #{param1}
	</delete>

	<select id="getNurseWhiteBoardRecordItems" parameterType="String"
		resultMap="nurseWhiteBoardRecordItemMap">
		SELECT
		nr.record_id,
		<include refid="nwbRecordSql"></include>
		,
		nri.item_id,
		<include refid="nwbRecordItemSql"></include>
		FROM NURSE_WHITE_BOARD_RECORD nr
		INNER JOIN
		NURSE_WHITE_BOARD_RECORD_ITEM nri ON nr.record_id = nri.record_id
		WHERE
		nr.dept_code = #{param1}
		<if test="param2 != null">
			AND nr.code = #{param2}
		</if>
		<!-- <if test="param3 != null and param4 != null">
			AND nr.record_date BETWEEN #{param3} AND #{param4}
		</if> -->
	</select>

	<insert id="insertNurseWhiteBoardRecordItemInfo" parameterType="NurseWhiteBoardRecordItemInfo"
		useGeneratedKeys="true" keyProperty="recordItemId">
		insert into
		NURSE_WHITE_BOARD_RECORD_ITEM(
		<include refid="nwbRecordItemSql" />
		,
		nri.record_id,nri.is_valid
		)
		VALUES(
		#{recordItemCode},#{recordItemName},#{recordItemValue},#{recordItemDate},#{execItemDate}
		#{itemPatId},#{itemPatInfo},#{startRecordItemDate},#{endRecordItemDate},#{status},#{recordId},1)
	</insert>

	<update id="updateNurseWhiteBoardRecordItemInfo" parameterType="NurseWhiteBoardRecordItemInfo">
		update NURSE_WHITE_BOARD_RECORD_ITEM
		<set>
			<if test="recordItemCode != null">
				item_code = #{recordItemCode},
			</if>
			<if test="recordItemName != null">
				item_name = #{recordItemName},
			</if>
			<if test="recordItemValue != null">
				item_value = #{recordItemValue},
			</if>
			<if test="recordItemDate != null">
				item_date = #{recordItemDate},
			</if>
			<if test="execItemDate != null">
				exec_date = #{execItemDate},
			</if>
			<if test="recordId != null">
				record_id = #{recordId}
			</if>
			<if test="itemPatId != null">
				item_pat_id = #{itemPatId}
			</if>
			<if test="itemPatInfo != null">
				item_pat_info = #{itemPatInfo}
			</if>
			<if test="startRecordItemDate != null">
				start_item_date = #{startRecordItemDate}
			</if>
			<if test="endRecordItemDate != null">
				end_item_date = #{endRecordItemDate}
			</if>
		</set>
		where item_id = #{recordItemId}
	</update>

	<delete id="deleteNurseWhiteBoardRecordItemInfoById"
		parameterType="String">
		DELETE FROM NURSE_WHITE_BOARD_RECORD_ITEM WHERE ITEM_ID
		= #{param1}
	</delete>

	<update id="delete" parameterType="String">
		update NURSE_WHITE_BOARD_RECORD set is_valid = '0',
		record_date = GETDATE()
		where is_valid=1 and record_code=#{param1}
		and dept_code = #{param3}
		<choose>
			<when test="param2 != null">
				and pat_id = #{param2}
			</when>
			<otherwise>
				and record_value is not null
			</otherwise>
		</choose>
	</update>

	<!-- 更新小白板明细记录-根据患者-->
	<update id="updateNurseWhiteBoardRecordItem" parameterType="NurseWhiteBoardRecordItemInfo">
		update NURSE_WHITE_BOARD_RECORD_ITEM set
			is_finish = #{status},
			END_ITEM_DATE = GETDATE()
		where item_pat_id = #{itemPatId}
			and	  exec_date = #{execItemDate}
			and   item_code = #{recordItemCode}
	</update>

	<update id="execWhiteBoardItem" parameterType="String">
		update NURSE_WHITE_BOARD_RECORD set
			is_valid='0'
		where record_id=#{param1}
	</update>

	<select id="getDosageByData" parameterType="String" resultType="String">
		select top 1
		case when w.dosage_unit is null then convert(varchar,cast(w.dosage as numeric(20,1)))
		else convert(varchar,cast(w.dosage as numeric(20,1)))+w.dosage_unit
		end dosage
		from WHITE_BOARD_DATA w
		inner join NURSE_WHITE_BOARD_METADATA nm
		on nm.code = w.item_code and nm.is_valid = '1'
		where w.is_stop = '0' and nm.dept_code = #{param1}
		and w.pat_id = #{param2} and w.item_code = #{param3}
		order by w.item_date desc
	</select>

	<select id="getQueryOrderCodes" resultType="String">
		select distinct item_code from WHITE_BOARD_ITEM
		where query_order=1
	</select>
</mapper>


text:
import React, { useState, useReducer } from 'react';

import services from 'web/libs/services';
import { EmailPrefData } from 'jslib/operations/types';
import Button from '../../Common/Button';
import { receiveEmailPreference } from '../../../store/auth';
import { useDispatch } from '../../../store';
import styles from './Form.scss';

enum Action {
  setInactiveReminder,
  setProductUpdate
}

function formReducer(state, action): EmailPrefData {
  switch (action.type) {
    case Action.setInactiveReminder:
      return {
        ...state,
        inactiveReminder: action.data
      };
    case Action.setProductUpdate:
      return {
        ...state,
        productUpdate: action.data
      };
    default:
      return state;
  }
}

interface Props {
  emailPreference: EmailPrefData;
  setSuccessMsg: (string) => void;
  setFailureMsg: (string) => void;
  token?: string;
}

const Form: React.FunctionComponent<Props> = ({
  emailPreference,
  setSuccessMsg,
  setFailureMsg,
  token
}) => {
  const [inProgress, setInProgress] = useState(false);
  const dispatch = useDispatch();

  const [formState, formDispatch] = useReducer(formReducer, emailPreference);

  function handleSubmit(e) {
    e.preventDefault();

    setSuccessMsg('');
    setFailureMsg('');
    setInProgress(true);

    services.users
      .updateEmailPreference({
        inactiveReminder: formState.inactiveReminder,
        productUpdate: formState.productUpdate,
        token
      })
      .then(updatedPreference => {
        dispatch(receiveEmailPreference(updatedPreference));

        setSuccessMsg('Updated email preference');
        setInProgress(false);
      })
      .catch(err => {
        setFailureMsg(`Failed to update. Error: ${err.message}`);
        setInProgress(false);
      });
  }

  return (
    <form id="T-notifications-form" onSubmit={handleSubmit}>

Alerts

Email me when:

            <input
              type="checkbox"
              id="inactive-reminder"
              checked={formState.inactiveReminder}
              onChange={e => {
                const { checked } = e.target;

                formDispatch({
                  type: Action.setInactiveReminder,
                  data: checked
                });
              }}
            />

              I stop learning new things

News

Email me about:

            <input
              type="checkbox"
              id="product-update"
              checked={formState.productUpdate}
              onChange={e => {
                const { checked } = e.target;

                formDispatch({
                  type: Action.setProductUpdate,
                  data: checked
                });
              }}
            />

              New features and updates

        <Button type="submit" kind="first" size="normal" isBusy={inProgress}>
          Update
        </Button>

    </form>
  );
};

export default Form;


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2010-2013 Evolveum
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:activiti="http://activiti.org/bpmn"
             xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI"
             xmlns:omgdc="http://www.omg.org/spec/DD/20100524/DC" xmlns:omgdi="http://www.omg.org/spec/DD/20100524/DI"
             typeLanguage="http://www.w3.org/2001/XMLSchema" expressionLanguage="http://www.w3.org/1999/XPath"
             targetNamespace="http://evolveum.com/midpoint" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <process id="ItemApproval" name="General multi-level item approval process" isExecutable="true">
        <extensionElements>
            <activiti:executionListener event="end" class="com.evolveum.midpoint.wf.impl.processes.common.MidPointProcessListener" />
        </extensionElements>

        <!-- This process takes care of approving "something" - an item to approve.

           Input variables:
             - approvalRequest (ApprovalRequest): data structure describing the item to be approved and (possibly multi-level) schema of the approval process
             - approvalTaskName (String): name of the approval task (e.g. "Approve adding role R to user U")

           Output variables:
             - wfAnswer (Soolean: __APPROVED__ / __REJECTED__-or-null): whether the item was approved or not
             (in the future we may accept a set of deltas to be directly applied)
        -->

        <startEvent id="start" name="Start" />
        <sequenceFlow sourceRef="start" targetRef="start.1" />

        <serviceTask id="start.1" activiti:class="com.evolveum.midpoint.wf.impl.processes.common.DumpVariables" />
        <sequenceFlow sourceRef="start.1" targetRef="initializeLoopThroughLevels" />

        <serviceTask id="initializeLoopThroughLevels" activiti:class="com.evolveum.midpoint.wf.impl.processes.itemApproval.InitializeLoopThroughLevels" />
        <sequenceFlow sourceRef="initializeLoopThroughLevels" targetRef="loopLevels" />

        <!-- New variable:
              - loopLevels_stop: whether to stop looping through levels (i.e. when the request is rejected at a particular level)
              - allDecisions (List<Decision>): here all the decisions are recorded
        -->

        <subProcess id="loopLevels">
            <multiInstanceLoopCharacteristics isSequential="true"
                    activiti:collection="${approvalRequest.approvalSchema.levels}" activiti:elementVariable="level">
                <completionCondition>${loopLevels_stop}</completionCondition>
            </multiInstanceLoopCharacteristics>

            <!-- variables:
                  - level: information about particular level of approval (e.g. list of approvers)
            -->

            <startEvent id="loopLevels.start" />
            <sequenceFlow sourceRef="loopLevels.start" targetRef="loopLevels.start.1" />

            <serviceTask id="loopLevels.start.1" activiti:class="com.evolveum.midpoint.wf.impl.processes.common.DumpVariables" />
            <sequenceFlow sourceRef="loopLevels.start.1" targetRef="loopLevels.initializeLoopThroughApprovers" />

            <!-- here we (besides other things) evaluate expressions describing approvers at this level and fill-in approversInLevel - list of references -->
            <serviceTask id="loopLevels.initializeLoopThroughApprovers" activiti:class="com.evolveum.midpoint.wf.impl.processes.itemApproval.InitializeLoopThroughApproversInLevel" />
            <sequenceFlow sourceRef="loopLevels.initializeLoopThroughApprovers" targetRef="loopLevels.shouldBeLevelExecutedQ" />

            <!-- variables:
                  - approversInLevel: list of LightweightObjectRef's for individual approvers
                  - loopApproversInLevel_stop: whether to stop looping through approvers at this level
                  - decisionList: list of decisions done at this level
            -->

            <exclusiveGateway id="loopLevels.shouldBeLevelExecutedQ"/>

            <sequenceFlow sourceRef='loopLevels.shouldBeLevelExecutedQ' targetRef='loopLevels.loopApprovers' >
                <conditionExpression xsi:type="tFormalExpression">
                    ${!loopApproversInLevel_stop}</conditionExpression>
            </sequenceFlow>
            <sequenceFlow sourceRef='loopLevels.shouldBeLevelExecutedQ' targetRef='loopLevels.before.summarizeDecisions' >
                <conditionExpression xsi:type="tFormalExpression">
                    ${loopApproversInLevel_stop}</conditionExpression>
            </sequenceFlow>

            <subProcess id="loopLevels.loopApprovers">
                <multiInstanceLoopCharacteristics isSequential="false"
                                                  activiti:collection="${approversInLevel}" activiti:elementVariable="approverRef">
                    <completionCondition>${loopApproversInLevel_stop}</completionCondition>
                </multiInstanceLoopCharacteristics>

                <!-- variables:
                      - approverRef: reference to an approver
                -->

                <startEvent id="loopLevels.loopApprovers.start" />
                <sequenceFlow sourceRef="loopLevels.loopApprovers.start" targetRef="loopLevels.loopApprovers.start.1" />

                <serviceTask id="loopLevels.loopApprovers.start.1" activiti:class="com.evolveum.midpoint.wf.impl.processes.common.DumpVariables" />
                <sequenceFlow sourceRef="loopLevels.loopApprovers.start.1" targetRef="loopLevels.loopApprovers.prepareApprover" />

                <serviceTask id="loopLevels.loopApprovers.prepareApprover" activiti:class="com.evolveum.midpoint.wf.impl.processes.itemApproval.PrepareApprover" />
                <sequenceFlow sourceRef="loopLevels.loopApprovers.prepareApprover" targetRef="loopLevels.loopApprovers.approve" />

                <exclusiveGateway id="loopLevels.loopApprovers.approve" />

                <sequenceFlow sourceRef='loopLevels.loopApprovers.approve' targetRef='loopLevels.loopApprovers.approve.withGroups' >
                    <conditionExpression xsi:type="tFormalExpression">
                        ${candidateGroups != null}</conditionExpression>
                </sequenceFlow>

                <sequenceFlow sourceRef='loopLevels.loopApprovers.approve' targetRef='loopLevels.loopApprovers.approve.withoutGroups' >
                    <conditionExpression xsi:type="tFormalExpression">
                        ${candidateGroups == null}</conditionExpression>
                </sequenceFlow>

                <userTask id="loopLevels.loopApprovers.approve.withGroups" name="${approvalTaskName}"
                          activiti:candidateGroups="${candidateGroups}">
                    <extensionElements>
                        <activiti:formProperty id="comment" name="01: Your comment" type="string" required="false" readable="true" writable="true"></activiti:formProperty>
                        <activiti:formProperty id="[H]decision" name="decision to be filled-in automatically" type="string" required="false" readable="true" writable="true"></activiti:formProperty>
                        <activiti:taskListener event="create" class="com.evolveum.midpoint.wf.impl.processes.common.MidPointTaskListener" />
                        <activiti:taskListener event="complete" class="com.evolveum.midpoint.wf.impl.processes.common.MidPointTaskListener" />
                    </extensionElements>
                </userTask>

                <userTask id="loopLevels.loopApprovers.approve.withoutGroups" name="${approvalTaskName}"
                          activiti:assignee="${assignee}">
                    <extensionElements>
                        <activiti:formProperty id="comment" name="01: Your comment" type="string" required="false" readable="true" writable="true"></activiti:formProperty>
                        <activiti:formProperty id="[H]decision" name="decision to be filled-in automatically" type="string" required="false" readable="true" writable="true"></activiti:formProperty>
                        <activiti:taskListener event="create" class="com.evolveum.midpoint.wf.impl.processes.common.MidPointTaskListener" />
                        <activiti:taskListener event="complete" class="com.evolveum.midpoint.wf.impl.processes.common.MidPointTaskListener" />
                    </extensionElements>
                </userTask>

                <sequenceFlow sourceRef="loopLevels.loopApprovers.approve.withGroups" targetRef="loopLevels.loopApprovers.recordDecision" />
                <sequenceFlow sourceRef="loopLevels.loopApprovers.approve.withoutGroups" targetRef="loopLevels.loopApprovers.recordDecision" />

                <!-- modifies decisionList, allDecisions, and loopApproversInLevel_stop (if necessary) -->
                <serviceTask id="loopLevels.loopApprovers.recordDecision" activiti:class="com.evolveum.midpoint.wf.impl.processes.itemApproval.RecordIndividualDecision" />
                <sequenceFlow sourceRef="loopLevels.loopApprovers.recordDecision" targetRef="loopLevels.loopApprovers.before.end" />

                <serviceTask id="loopLevels.loopApprovers.before.end" activiti:class="com.evolveum.midpoint.wf.impl.processes.common.DumpVariables" />
                <sequenceFlow sourceRef="loopLevels.loopApprovers.before.end" targetRef="loopLevels.loopApprovers.end" />

                <endEvent id="loopLevels.loopApprovers.end" />
            </subProcess>
            <sequenceFlow sourceRef="loopLevels.loopApprovers" targetRef="loopLevels.before.summarizeDecisions" />

            <serviceTask id="loopLevels.before.summarizeDecisions" activiti:class="com.evolveum.midpoint.wf.impl.processes.common.DumpVariables" />
            <sequenceFlow sourceRef="loopLevels.before.summarizeDecisions" targetRef="loopLevels.summarizeDecisions" />

            <!-- modifies loopLevels_stop, if necessary -->
            <serviceTask id="loopLevels.summarizeDecisions" activiti:class="com.evolveum.midpoint.wf.impl.processes.itemApproval.SummarizeDecisionsInLevel" />
            <sequenceFlow sourceRef="loopLevels.summarizeDecisions" targetRef="loopLevels.end" />

            <endEvent id="loopLevels.end" />
        </subProcess>
        <sequenceFlow sourceRef="loopLevels" targetRef="before.prepareResult"></sequenceFlow>

        <serviceTask id="before.prepareResult" activiti:class="com.evolveum.midpoint.wf.impl.processes.common.DumpVariables" />
        <sequenceFlow sourceRef="before.prepareResult" targetRef="prepareResult"></sequenceFlow>

        <!-- prepares wfAnswer -->
        <serviceTask id="prepareResult" activiti:class="com.evolveum.midpoint.wf.impl.processes.itemApproval.PrepareResult" />
        <sequenceFlow sourceRef="prepareResult" targetRef="end"></sequenceFlow>

        <endEvent id="end" />
    </process>

</definitions>


text:
using System.Reflection.Emit;
using JetBrains.Annotations;

namespace ILGeneratorExtensions
{
    /// <summary>
    /// Contains extension methods for comparing objects on the stack
    /// </summary>
    public static partial class CompareAndBranch
    {
        /// <summary>
        /// Pops a reference from the evaluation stack and branches to the given label if it is the null reference
        /// </summary>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        /// <param name="label">The label to branch to</param>
        [PublicAPI]
        public static ILGenerator BranchIfNull(this ILGenerator generator, Label label)
        {
            return generator.LoadNull()
                            .BranchIfEqual(label);
        }

        /// <summary>
        /// Pops a reference from the evaluation stack and branches to the given label if it is the null reference
        /// </summary>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        /// <param name="labelName">The name of the fluently-specified label</param>
        [PublicAPI]
        public static ILGenerator BranchIfNull(this ILGenerator generator, string labelName)
            => generator.BranchIfNull(generator.GetOrCreateLabel(labelName));

        /// <summary>
        /// Pops a reference from the evaluation stack and branches to the given label if it is the null reference
        /// </summary>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        /// <param name="label">The label to branch to</param>
        [PublicAPI]
        public static ILGenerator BranchIfNullShortForm(this ILGenerator generator, Label label)
        {
            return generator.LoadNull()
                            .BranchIfEqualShortForm(label);
        }

        /// <summary>
        /// Pops a reference from the evaluation stack and branches to the given label if it is the null reference
        /// </summary>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        /// <param name="labelName">The name of the fluently-specified label</param>
        [PublicAPI]
        public static ILGenerator BranchIfNullShortForm(this ILGenerator generator, string labelName)
            => generator.BranchIfNullShortForm(generator.GetOrCreateLabel(labelName));

        /// <summary>
        /// Pops an integer value from the evaluation stack and branches to the given label if it interprets as true
        /// </summary>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        /// <param name="label">The label to branch to</param>
        [PublicAPI]
        public static ILGenerator BranchIfTrue(this ILGenerator generator, Label label) => generator.FluentEmit(OpCodes.Brtrue, label);

        /// <summary>
        /// Pops an integer value from the evaluation stack and branches to the given label if it interprets as true
        /// </summary>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        /// <param name="labelName">The name of the fluently-specified label</param>
        [PublicAPI]
        public static ILGenerator BranchIfTrue(this ILGenerator generator, string labelName)
            => generator.BranchIfTrue(generator.GetOrCreateLabel(labelName));

        /// <summary>
        /// Pops an integer value from the evaluation stack and branches to the given label if it interprets as true
        /// </summary>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        /// <param name="label">The label to branch to</param>
        [PublicAPI]
        public static ILGenerator BranchIfTrueShortForm(this ILGenerator generator, Label label) => generator.FluentEmit(OpCodes.Brtrue_S, label);

        /// <summary>
        /// Pops an integer value from the evaluation stack and branches to the given label if it interprets as true
        /// </summary>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        /// <param name="labelName">The name of the fluently-specified label</param>
        [PublicAPI]
        public static ILGenerator BranchIfTrueShortForm(this ILGenerator generator, string labelName)
            => generator.BranchIfTrueShortForm(generator.GetOrCreateLabel(labelName));

        /// <summary>
        /// Pops an integer value from the evaluation stack and branches to the given label if it interprets as false
        /// </summary>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        /// <param name="label">The label to branch to</param>
        [PublicAPI]
        public static ILGenerator BranchIfFalse(this ILGenerator generator, Label label) => generator.FluentEmit(OpCodes.Brfalse, label);

        /// <summary>
        /// Pops an integer value from the evaluation stack and branches to the given label if it interprets as false
        /// </summary>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        /// <param name="labelName">The name of the fluently-specified label</param>
        [PublicAPI]
        public static ILGenerator BranchIfFalse(this ILGenerator generator, string labelName)
            => generator.BranchIfFalse(generator.GetOrCreateLabel(labelName));

        /// <summary>
        /// Pops an integer value from the evaluation stack and branches to the given label if it interprets as false
        /// </summary>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        /// <param name="label">The label to branch to</param>
        [PublicAPI]
        public static ILGenerator BranchIfFalseShortForm(this ILGenerator generator, Label label) => generator.FluentEmit(OpCodes.Brfalse_S, label);

        /// <summary>
        /// Pops an integer value from the evaluation stack and branches to the given label if it interprets as false
        /// </summary>
        /// <param name="generator">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
        /// <param name="labelName">The name of the fluently-specified label</param>
        [PublicAPI]
        public static ILGenerator BranchIfFalseShortForm(this ILGenerator generator, string labelName)
            => generator.BranchIfFalseShortForm(generator.GetOrCreateLabel(labelName));
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Didymopanax glaziovii Taub.

### Remarks
null


text:
layout: tag
title: "PyIlmbase"
slug: pyilmbase
permalink: /tag/pyilmbase/
---


text:
==========
User Guide
==========

.. contents::

{{ cookiecutter.package_name }} user guide
----------------------------------------------------

This is probably the most important section but follows no standard layout.