jiahuimbzuai/CoQuIR huggingface dataset:
// _add_chapsecret_to_host [python]
    def _add_chapsecret_to_host(self, host_name):
        """Generate and store a randomly-generated CHAP secret for the host."""

        chap_secret = utils.generate_password()
        ssh_cmd = ('svctask chhost -chapsecret "%(chap_secret)s" %(host_name)s'
                   % {'chap_secret': chap_secret, 'host_name': host_name})
        out, err = self._run_ssh(ssh_cmd)
        # No output should be returned from chhost
        self._assert_ssh_return(len(out.strip()) == 0,
                                '_add_chapsecret_to_host', ssh_cmd, out, err)
        return chap_secret
// _call_prepare_fc_map [python]
    def _call_prepare_fc_map(self, fc_map_id, source, target):
        try:
            out, err = self._run_ssh(['svctask', 'prestartfcmap', fc_map_id])
        except exception.ProcessExecutionError as e:
            with excutils.save_and_reraise_exception():
                LOG.error(_('_prepare_fc_map: Failed to prepare FlashCopy '
                            'from %(source)s to %(target)s.\n'
                            'stdout: %(out)s\n stderr: %(err)s')
                          % {'source': source,
                             'target': target,
                             'out': e.stdout,
                             'err': e.stderr})
// _call_prepare_fc_map [python]
    def _call_prepare_fc_map(self, fc_map_id, source, target):
        try:
            out, err = self._run_ssh('svctask prestartfcmap %s' % fc_map_id)
        except exception.ProcessExecutionError as e:
            with excutils.save_and_reraise_exception():
                LOG.error(_('_prepare_fc_map: Failed to prepare FlashCopy '
                            'from %(source)s to %(target)s.\n'
                            'stdout: %(out)s\n stderr: %(err)s')
                          % {'source': source,
                             'target': target,
                             'out': e.stdout,
                             'err': e.stderr})
// on_message [python]
    def on_message( self, profile_id, profile_name, level, message, timeout ):
        if 1 == level:
            cmd = ['notify-send']
            if timeout > 0:
                cmd.extend(['-t', str(1000 * timeout)])

            title = "Back In Time (%s) : %s" % (self.user, profile_name)
            message = message.replace("\n", ' ')
            message = message.replace("\r", '')

            cmd.append(title)
            cmd.append(message)
            subprocess.Popen(cmd).communicate()
        return
// on_message [python]
    def on_message( self, profile_id, profile_name, level, message, timeout ):
        if 1 == level:
            cmd = "notify-send "
            if timeout > 0:
                cmd = cmd + " -t %s" % (1000 * timeout)

            title = "Back In Time (%s) : %s" % (self.user, profile_name)
            message = message.replace("\n", ' ')
            message = message.replace("\r", '')

            cmd = cmd + " \"%s\" \"%s\"" % (title, message)
            print(cmd)
            os.system(cmd)
        return
// podbeuter::pb_controller::play_file [cpp]
void pb_controller::play_file(const std::string& file) {
	std::string cmdline;
	std::string player = cfg->get_configvalue("player");
	if (player == "")
		return;
	cmdline.append(player);
	cmdline.append(" '");
	cmdline.append(utils::replace_all(file,"'", "%27"));
	cmdline.append("'");
	stfl::reset();
	utils::run_interactively(cmdline, "pb_controller::play_file");
}
// podbeuter::pb_controller::play_file [cpp]
void pb_controller::play_file(const std::string& file) {
	std::string cmdline;
	std::string player = cfg->get_configvalue("player");
	if (player == "")
		return;
	cmdline.append(player);
	cmdline.append(" \"");
	cmdline.append(utils::replace_all(file,"\"", "\\\""));
	cmdline.append("\"");
	stfl::reset();
	utils::run_interactively(cmdline, "pb_controller::play_file");
}
// _find_host_exhaustive [python]
    def _find_host_exhaustive(self, connector, hosts):
        for host in hosts:
            ssh_cmd = ['svcinfo', 'lshost', '-delim', '!', host]
            out, err = self._run_ssh(ssh_cmd)
            self._assert_ssh_return(len(out.strip()),
                                    '_find_host_exhaustive',
                                    ssh_cmd, out, err)
            for attr_line in out.split('\n'):
                # If '!' not found, return the string and two empty strings
                attr_name, foo, attr_val = attr_line.partition('!')
                if (attr_name == 'iscsi_name' and
                        'initiator' in connector and
                        attr_val == connector['initiator']):
                    return host
                elif (attr_name == 'WWPN' and
                      'wwpns' in connector and
                      attr_val.lower() in
                      map(str.lower, map(str, connector['wwpns']))):
                        return host
        return None
// _find_host_exhaustive [python]
    def _find_host_exhaustive(self, connector, hosts):
        for host in hosts:
            ssh_cmd = 'svcinfo lshost -delim ! %s' % host
            out, err = self._run_ssh(ssh_cmd)
            self._assert_ssh_return(len(out.strip()),
                                    '_find_host_exhaustive',
                                    ssh_cmd, out, err)
            for attr_line in out.split('\n'):
                # If '!' not found, return the string and two empty strings
                attr_name, foo, attr_val = attr_line.partition('!')
                if (attr_name == 'iscsi_name' and
                        'initiator' in connector and
                        attr_val == connector['initiator']):
                    return host
                elif (attr_name == 'WWPN' and
                      'wwpns' in connector and
                      attr_val.lower() in
                      map(str.lower, map(str, connector['wwpns']))):
                        return host
        return None
// _create_vdisk [python]
    def _create_vdisk(self, name, size, units, opts):
        """Create a new vdisk."""

        LOG.debug(_('enter: _create_vdisk: vdisk %s ') % name)

        model_update = None
        easytier = 'on' if opts['easytier'] else 'off'

        # Set space-efficient options
        if opts['rsize'] == -1:
            ssh_cmd_se_opt = []
        else:
            ssh_cmd_se_opt = ['-rsize', '%s%%' % str(opts['rsize']),
                              '-autoexpand', '-warning',
                              '%s%%' % str(opts['warning'])]
            if not opts['autoexpand']:
                ssh_cmd_se_opt.remove('-autoexpand')

            if opts['compression']:
                ssh_cmd_se_opt.append('-compressed')
            else:
                ssh_cmd_se_opt.extend(['-grainsize', str(opts['grainsize'])])

        ssh_cmd = ['svctask', 'mkvdisk', '-name', name, '-mdiskgrp',
                   self.configuration.storwize_svc_volpool_name,
                   '-iogrp', '0', '-size', size, '-unit',
                   units, '-easytier', easytier] + ssh_cmd_se_opt
        out, err = self._run_ssh(ssh_cmd)
        self._assert_ssh_return(len(out.strip()), '_create_vdisk',
                                ssh_cmd, out, err)

        # Ensure that the output is as expected
        match_obj = re.search('Virtual Disk, id \[([0-9]+)\], '
                              'successfully created', out)
        # Make sure we got a "successfully created" message with vdisk id
        self._driver_assert(
            match_obj is not None,
            _('_create_vdisk %(name)s - did not find '
              'success message in CLI output.\n '
              'stdout: %(out)s\n stderr: %(err)s')
            % {'name': name, 'out': str(out), 'err': str(err)})

        LOG.debug(_('leave: _create_vdisk: volume %s ') % name)
// _create_vdisk [python]
    def _create_vdisk(self, name, size, units, opts):
        """Create a new vdisk."""

        LOG.debug(_('enter: _create_vdisk: vdisk %s ') % name)

        model_update = None
        autoex = '-autoexpand' if opts['autoexpand'] else ''
        easytier = '-easytier on' if opts['easytier'] else '-easytier off'

        # Set space-efficient options
        if opts['rsize'] == -1:
            ssh_cmd_se_opt = ''
        else:
            ssh_cmd_se_opt = (
                '-rsize %(rsize)d%% %(autoex)s -warning %(warn)d%%' %
                {'rsize': opts['rsize'],
                 'autoex': autoex,
                 'warn': opts['warning']})
            if opts['compression']:
                ssh_cmd_se_opt = ssh_cmd_se_opt + ' -compressed'
            else:
                ssh_cmd_se_opt = ssh_cmd_se_opt + (
                    ' -grainsize %d' % opts['grainsize'])

        ssh_cmd = ('svctask mkvdisk -name %(name)s -mdiskgrp %(mdiskgrp)s '
                   '-iogrp 0 -size %(size)s -unit '
                   '%(unit)s %(easytier)s %(ssh_cmd_se_opt)s'
                   % {'name': name,
                   'mdiskgrp': self.configuration.storwize_svc_volpool_name,
                   'size': size, 'unit': units, 'easytier': easytier,
                   'ssh_cmd_se_opt': ssh_cmd_se_opt})
        out, err = self._run_ssh(ssh_cmd)
        self._assert_ssh_return(len(out.strip()), '_create_vdisk',
                                ssh_cmd, out, err)

        # Ensure that the output is as expected
        match_obj = re.search('Virtual Disk, id \[([0-9]+)\], '
                              'successfully created', out)
        # Make sure we got a "successfully created" message with vdisk id
        self._driver_assert(
            match_obj is not None,
            _('_create_vdisk %(name)s - did not find '
              'success message in CLI output.\n '
              'stdout: %(out)s\n stderr: %(err)s')
            % {'name': name, 'out': str(out), 'err': str(err)})

        LOG.debug(_('leave: _create_vdisk: volume %s ') % name)
// test_invalid_iscsi_ip [python]
    def test_invalid_iscsi_ip(self):
        self.flags(lock_path=self.tempdir)

        #record driver set up
        self.clear_mox()
        _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)
        self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "_run_ssh", _run_ssh)

        show_port_cmd = ['showport']
        _run_ssh(show_port_cmd, False).AndReturn([pack(PORT_RET), ''])

        show_port_i_cmd = ['showport', '-iscsi']
        _run_ssh(show_port_i_cmd, False).AndReturn([pack(READY_ISCSI_PORT_RET),
                                                    ''])

        show_port_i_cmd = ['showport', '-iscsiname']
        _run_ssh(show_port_i_cmd, False).AndReturn([pack(SHOW_PORT_ISCSI), ''])

        config = self.setup_configuration()
        config.hp3par_iscsi_ips = ['10.10.220.250', '10.10.220.251']
        config.iscsi_ip_address = '10.10.10.10'
        self.mox.ReplayAll()

        # no valid ip addr should be configured.
        self.assertRaises(exception.InvalidInput,
                          self.setup_driver,
                          config,
                          set_up_fakes=False)
// test_invalid_iscsi_ip [python]
    def test_invalid_iscsi_ip(self):
        self.flags(lock_path=self.tempdir)

        #record driver set up
        self.clear_mox()
        _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)
        self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "_run_ssh", _run_ssh)

        show_port_cmd = 'showport'
        _run_ssh(show_port_cmd, False).AndReturn([pack(PORT_RET), ''])

        show_port_i_cmd = 'showport -iscsi'
        _run_ssh(show_port_i_cmd, False).AndReturn([pack(READY_ISCSI_PORT_RET),
                                                    ''])

        show_port_i_cmd = 'showport -iscsiname'
        _run_ssh(show_port_i_cmd, False).AndReturn([pack(SHOW_PORT_ISCSI), ''])

        config = self.setup_configuration()
        config.hp3par_iscsi_ips = ['10.10.220.250', '10.10.220.251']
        config.iscsi_ip_address = '10.10.10.10'
        self.mox.ReplayAll()

        # no valid ip addr should be configured.
        self.assertRaises(exception.InvalidInput,
                          self.setup_driver,
                          config,
                          set_up_fakes=False)
// get_output [python]
def get_output(command: List[str]) -> str:
    """
    Run a command and return raw output

    :param str command: the command to run
    :returns: the stdout output of the command
    """
    result = subprocess.run(command, stdout=subprocess.PIPE, check=True)
    return result.stdout.decode()
// get_output [python]
def get_output(command: str) -> bytes:
    """
    Run a command and return raw output

    :param str command: the command to run
    :returns: the stdout output of the command
    """
    return subprocess.check_output(command.split())
// openscript [c]
openscript(
    char_u	*name,
    int		directly)	/* when TRUE execute directly */
{
    if (curscript + 1 == NSCRIPT)
    {
	emsg(_(e_nesting));
	return;
    }

    // Disallow sourcing a file in the sandbox, the commands would be executed
    // later, possibly outside of the sandbox.
    if (check_secure())
	return;

#ifdef FEAT_EVAL
    if (ignore_script)
	/* Not reading from script, also don't open one.  Warning message? */
	return;
#endif

    if (scriptin[curscript] != NULL)	/* already reading script */
	++curscript;
				/* use NameBuff for expanded name */
    expand_env(name, NameBuff, MAXPATHL);
    if ((scriptin[curscript] = mch_fopen((char *)NameBuff, READBIN)) == NULL)
    {
	semsg(_(e_notopen), name);
	if (curscript)
	    --curscript;
	return;
    }
    if (save_typebuf() == FAIL)
	return;

    /*
     * Execute the commands from the file right now when using ":source!"
     * after ":global" or ":argdo" or in a loop.  Also when another command
     * follows.  This means the display won't be updated.  Don't do this
     * always, "make test" would fail.
     */
    if (directly)
    {
	oparg_T	oa;
	int	oldcurscript;
	int	save_State = State;
	int	save_restart_edit = restart_edit;
	int	save_insertmode = p_im;
	int	save_finish_op = finish_op;
	int	save_msg_scroll = msg_scroll;

	State = NORMAL;
	msg_scroll = FALSE;	/* no msg scrolling in Normal mode */
	restart_edit = 0;	/* don't go to Insert mode */
	p_im = FALSE;		/* don't use 'insertmode' */
	clear_oparg(&oa);
	finish_op = FALSE;

	oldcurscript = curscript;
	do
	{
	    update_topline_cursor();	// update cursor position and topline
	    normal_cmd(&oa, FALSE);	// execute one command
	    vpeekc();			// check for end of file
	}
	while (scriptin[oldcurscript] != NULL);

	State = save_State;
	msg_scroll = save_msg_scroll;
	restart_edit = save_restart_edit;
	p_im = save_insertmode;
	finish_op = save_finish_op;
    }
}
// openscript [c]
openscript(
    char_u	*name,
    int		directly)	/* when TRUE execute directly */
{
    if (curscript + 1 == NSCRIPT)
    {
	emsg(_(e_nesting));
	return;
    }
#ifdef FEAT_EVAL
    if (ignore_script)
	/* Not reading from script, also don't open one.  Warning message? */
	return;
#endif

    if (scriptin[curscript] != NULL)	/* already reading script */
	++curscript;
				/* use NameBuff for expanded name */
    expand_env(name, NameBuff, MAXPATHL);
    if ((scriptin[curscript] = mch_fopen((char *)NameBuff, READBIN)) == NULL)
    {
	semsg(_(e_notopen), name);
	if (curscript)
	    --curscript;
	return;
    }
    if (save_typebuf() == FAIL)
	return;

    /*
     * Execute the commands from the file right now when using ":source!"
     * after ":global" or ":argdo" or in a loop.  Also when another command
     * follows.  This means the display won't be updated.  Don't do this
     * always, "make test" would fail.
     */
    if (directly)
    {
	oparg_T	oa;
	int	oldcurscript;
	int	save_State = State;
	int	save_restart_edit = restart_edit;
	int	save_insertmode = p_im;
	int	save_finish_op = finish_op;
	int	save_msg_scroll = msg_scroll;

	State = NORMAL;
	msg_scroll = FALSE;	/* no msg scrolling in Normal mode */
	restart_edit = 0;	/* don't go to Insert mode */
	p_im = FALSE;		/* don't use 'insertmode' */
	clear_oparg(&oa);
	finish_op = FALSE;

	oldcurscript = curscript;
	do
	{
	    update_topline_cursor();	// update cursor position and topline
	    normal_cmd(&oa, FALSE);	// execute one command
	    vpeekc();			// check for end of file
	}
	while (scriptin[oldcurscript] != NULL);

	State = save_State;
	msg_scroll = save_msg_scroll;
	restart_edit = save_restart_edit;
	p_im = save_insertmode;
	finish_op = save_finish_op;
    }
}
// add_user [python]
def add_user(username, password):
    encPass = crypt.crypt(password,"22")
    #subprocess escapes the username stopping code injection
    subprocess.call(['useradd','-G','docker,wheel','-p',encPass,username])
// add_user [python]
def add_user(username, password):
    encPass = crypt.crypt(password,"22")
    os.system("useradd -G docker,wheel -p "+encPass+" "+username)
// write_section [python]
    def write_section(self, section_name, section_data):
        self.write_line("")
        self.write_line("define %s {" % section_name)
        sorted_keys = section_data.keys()
        sorted_keys.sort()
        for key in sorted_keys:
            value = self.value_to_icinga(section_data[key])
            icinga_line = "%s%-45s%s" % (self.indent, key, value)

            if "\n" in icinga_line or "}" in icinga_line:
                msg = "Found forbidden newline or '}' character in section %r."
                raise Exception(msg % section_name)

            self.icinga_lines.append(icinga_line)
        self.write_line("}")
// write_section [python]
    def write_section(self, section_name, section_data):
        self.write_line("")
        self.write_line("define %s {" % section_name)
        sorted_keys = section_data.keys()
        sorted_keys.sort()
        for key in sorted_keys:
            value = section_data[key]
            self.icinga_lines.append(("%s%-45s%s" % (self.indent, key, self.value_to_icinga(value))))
        self.write_line("}")
// _update_volume_stats [python]
    def _update_volume_stats(self):
        """Retrieve stats info from volume group."""

        LOG.debug(_("Updating volume stats"))
        data = {}

        data['vendor_name'] = 'IBM'
        data['driver_version'] = '1.1'
        data['storage_protocol'] = list(self._enabled_protocols)

        data['total_capacity_gb'] = 0  # To be overwritten
        data['free_capacity_gb'] = 0   # To be overwritten
        data['reserved_percentage'] = 0
        data['QoS_support'] = False

        pool = self.configuration.storwize_svc_volpool_name
        #Get storage system name
        ssh_cmd = ['svcinfo', 'lssystem', '-delim', '!']
        attributes = self._execute_command_and_parse_attributes(ssh_cmd)
        if not attributes or not attributes['name']:
            exception_message = (_('_update_volume_stats: '
                                   'Could not get system name'))
            raise exception.VolumeBackendAPIException(data=exception_message)

        backend_name = self.configuration.safe_get('volume_backend_name')
        if not backend_name:
            backend_name = '%s_%s' % (attributes['name'], pool)
        data['volume_backend_name'] = backend_name

        ssh_cmd = ['svcinfo', 'lsmdiskgrp', '-bytes', '-delim', '!', pool]
        attributes = self._execute_command_and_parse_attributes(ssh_cmd)
        if not attributes:
            LOG.error(_('Could not get pool data from the storage'))
            exception_message = (_('_update_volume_stats: '
                                   'Could not get storage pool data'))
            raise exception.VolumeBackendAPIException(data=exception_message)

        data['total_capacity_gb'] = (float(attributes['capacity']) /
                                    (1024 ** 3))
        data['free_capacity_gb'] = (float(attributes['free_capacity']) /
                                    (1024 ** 3))
        data['easytier_support'] = attributes['easy_tier'] in ['on', 'auto']
        data['compression_support'] = self._compression_enabled

        self._stats = data
// _update_volume_stats [python]
    def _update_volume_stats(self):
        """Retrieve stats info from volume group."""

        LOG.debug(_("Updating volume stats"))
        data = {}

        data['vendor_name'] = 'IBM'
        data['driver_version'] = '1.1'
        data['storage_protocol'] = list(self._enabled_protocols)

        data['total_capacity_gb'] = 0  # To be overwritten
        data['free_capacity_gb'] = 0   # To be overwritten
        data['reserved_percentage'] = 0
        data['QoS_support'] = False

        pool = self.configuration.storwize_svc_volpool_name
        #Get storage system name
        ssh_cmd = 'svcinfo lssystem -delim !'
        attributes = self._execute_command_and_parse_attributes(ssh_cmd)
        if not attributes or not attributes['name']:
            exception_message = (_('_update_volume_stats: '
                                   'Could not get system name'))
            raise exception.VolumeBackendAPIException(data=exception_message)

        backend_name = self.configuration.safe_get('volume_backend_name')
        if not backend_name:
            backend_name = '%s_%s' % (attributes['name'], pool)
        data['volume_backend_name'] = backend_name

        ssh_cmd = 'svcinfo lsmdiskgrp -bytes -delim ! %s' % pool
        attributes = self._execute_command_and_parse_attributes(ssh_cmd)
        if not attributes:
            LOG.error(_('Could not get pool data from the storage'))
            exception_message = (_('_update_volume_stats: '
                                   'Could not get storage pool data'))
            raise exception.VolumeBackendAPIException(data=exception_message)

        data['total_capacity_gb'] = (float(attributes['capacity']) /
                                    (1024 ** 3))
        data['free_capacity_gb'] = (float(attributes['free_capacity']) /
                                    (1024 ** 3))
        data['easytier_support'] = attributes['easy_tier'] in ['on', 'auto']
        data['compression_support'] = self._compression_enabled

        self._stats = data
// test_create_modify_host [python]
    def test_create_modify_host(self):
        self.flags(lock_path=self.tempdir)

        #record
        self.clear_mox()
        self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "get_cpg",
                       self.fake_get_cpg)
        self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "get_domain",
                       self.fake_get_domain)
        _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)
        self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "_run_ssh", _run_ssh)

        show_host_cmd = ['showhost', '-verbose', 'fakehost']
        _run_ssh(show_host_cmd, False).AndReturn([pack(NO_FC_HOST_RET), ''])

        create_host_cmd = ['createhost', '-add', 'fakehost', '123456789012345',
                           '123456789054321']
        _run_ssh(create_host_cmd, False).AndReturn([CLI_CR, ''])

        show_host_cmd = ['showhost', '-verbose', 'fakehost']
        _run_ssh(show_host_cmd, False).AndReturn([pack(FC_HOST_RET), ''])
        self.mox.ReplayAll()

        host = self.driver._create_host(self.volume, self.connector)
        self.assertEqual(host['name'], self.FAKE_HOST)
// test_create_modify_host [python]
    def test_create_modify_host(self):
        self.flags(lock_path=self.tempdir)

        #record
        self.clear_mox()
        self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "get_cpg",
                       self.fake_get_cpg)
        self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "get_domain",
                       self.fake_get_domain)
        _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)
        self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "_run_ssh", _run_ssh)

        show_host_cmd = 'showhost -verbose fakehost'
        _run_ssh(show_host_cmd, False).AndReturn([pack(NO_FC_HOST_RET), ''])

        create_host_cmd = ('createhost -add fakehost '
                           '123456789012345 123456789054321')
        _run_ssh(create_host_cmd, False).AndReturn([CLI_CR, ''])

        show_host_cmd = 'showhost -verbose fakehost'
        _run_ssh(show_host_cmd, False).AndReturn([pack(FC_HOST_RET), ''])
        self.mox.ReplayAll()

        host = self.driver._create_host(self.volume, self.connector)
        self.assertEqual(host['name'], self.FAKE_HOST)
// install [python]
def install(filename, target):
  '''Run a package's installer script against the given target directory.'''
  print(' Unpacking %s...' % filename)
  subprocess.check_call(['tar', 'xf', filename])
  basename = filename.split('.tar')[0]
  print(' Installing %s...' % basename)
  install_cmd = [os.path.join(basename, 'install.sh')]
  install_cmd += ['--prefix=' + os.path.abspath(target)]
  install_cmd += ['--disable-ldconfig']
  subprocess.check_call(install_cmd)
  print(' Cleaning %s...' % basename)
  subprocess.check_call(['rm', '-rf', basename])
// install [python]
def install(filename, target):
  '''Run a package's installer script against the given target directory.'''
  print(' Unpacking %s...' % filename)
  os.system('tar xf ' + filename)
  basename = filename.split('.tar')[0]
  print(' Installing %s...' % basename)
  install_opts = '--prefix=${PWD}/%s --disable-ldconfig' % target
  os.system('%s/install.sh %s' % (basename, install_opts))
  print(' Cleaning %s...' % basename)
  os.system('rm -rf %s' % basename)
// _get_least_used_nsp [python]
    def _get_least_used_nsp(self, nspss):
        """"Return the nsp that has the fewest active vluns."""
        # return only the nsp (node:server:port)
        result = self.common._cli_run(['showvlun', '-a', '-showcols', 'Port'])

        # count the number of nsps (there is 1 for each active vlun)
        nsp_counts = {}
        for nsp in nspss:
            # initialize counts to zero
            nsp_counts[nsp] = 0

        current_least_used_nsp = None
        if result:
            # first line is header
            result = result[1:]
            for line in result:
                nsp = line.strip()
                if nsp in nsp_counts:
                    nsp_counts[nsp] = nsp_counts[nsp] + 1

            # identify key (nsp) of least used nsp
            current_smallest_count = sys.maxint
            for (nsp, count) in nsp_counts.iteritems():
                if count < current_smallest_count:
                    current_least_used_nsp = nsp
                    current_smallest_count = count

        return current_least_used_nsp
// _get_least_used_nsp [python]
    def _get_least_used_nsp(self, nspss):
        """"Return the nsp that has the fewest active vluns."""
        # return only the nsp (node:server:port)
        result = self.common._cli_run('showvlun -a -showcols Port', None)

        # count the number of nsps (there is 1 for each active vlun)
        nsp_counts = {}
        for nsp in nspss:
            # initialize counts to zero
            nsp_counts[nsp] = 0

        current_least_used_nsp = None
        if result:
            # first line is header
            result = result[1:]
            for line in result:
                nsp = line.strip()
                if nsp in nsp_counts:
                    nsp_counts[nsp] = nsp_counts[nsp] + 1

            # identify key (nsp) of least used nsp
            current_smallest_count = sys.maxint
            for (nsp, count) in nsp_counts.iteritems():
                if count < current_smallest_count:
                    current_least_used_nsp = nsp
                    current_smallest_count = count

        return current_least_used_nsp
// _start_fc_map [python]
    def _start_fc_map(self, fc_map_id, source, target):
        try:
            out, err = self._run_ssh(['svctask', 'startfcmap', fc_map_id])
        except exception.ProcessExecutionError as e:
            with excutils.save_and_reraise_exception():
                LOG.error(_('_start_fc_map: Failed to start FlashCopy '
                            'from %(source)s to %(target)s.\n'
                            'stdout: %(out)s\n stderr: %(err)s')
                          % {'source': source,
                             'target': target,
                             'out': e.stdout,
                             'err': e.stderr})
// _start_fc_map [python]
    def _start_fc_map(self, fc_map_id, source, target):
        try:
            out, err = self._run_ssh('svctask startfcmap %s' % fc_map_id)
        except exception.ProcessExecutionError as e:
            with excutils.save_and_reraise_exception():
                LOG.error(_('_start_fc_map: Failed to start FlashCopy '
                            'from %(source)s to %(target)s.\n'
                            'stdout: %(out)s\n stderr: %(err)s')
                          % {'source': source,
                             'target': target,
                             'out': e.stdout,
                             'err': e.stderr})
// resolve_hostname [python]
@then(parsers.parse("the hostname '{hostname}' should be resolved"))
def resolve_hostname(busybox_pod, host, hostname):
    with host.sudo():
        # test dns resolve
        result = host.run(
            "kubectl --kubeconfig=/etc/kubernetes/admin.conf "
            "exec -ti %s nslookup %s",
            busybox_pod,
            hostname,
        )

        assert result.rc == 0, "Cannot resolve {}".format(hostname)
// resolve_hostname [python]
@then(parsers.parse("the hostname '{hostname}' should be resolved"))
def resolve_hostname(busybox_pod, host, hostname):
        with host.sudo():
            # test dns resolve
            cmd_nslookup = ("kubectl --kubeconfig=/etc/kubernetes/admin.conf"
                            " exec -ti {0} nslookup {1}".format(
                                pod_name,
                                hostname))
            res = host.run(cmd_nslookup)
            assert res.rc == 0, "Cannot resolve {}".format(hostname)
// _modify_3par_fibrechan_host [python]
    def _modify_3par_fibrechan_host(self, hostname, wwns):
        # when using -add, you can not send the persona or domain options
        command = ['createhost', '-add', hostname]
        for wwn in wwns:
            command.append(wwn)

        out = self.common._cli_run(command)
// _modify_3par_fibrechan_host [python]
    def _modify_3par_fibrechan_host(self, hostname, wwn):
        # when using -add, you can not send the persona or domain options
        out = self.common._cli_run('createhost -add %s %s'
                                   % (hostname, " ".join(wwn)), None)
// test_settings_path_skip_issue_909 [python]
def test_settings_path_skip_issue_909(tmpdir):
    base_dir = tmpdir.mkdir('project')
    config_dir = base_dir.mkdir('conf')
    config_dir.join('.isort.cfg').write('[isort]\n'
                                        'skip =\n'
                                        '    file_to_be_skipped.py\n'
                                        'skip_glob =\n'
                                        '    *glob_skip*\n')

    base_dir.join('file_glob_skip.py').write('import os\n'
                                             '\n'
                                             'print("Hello World")\n'
                                             '\n'
                                             'import sys\n')
    base_dir.join('file_to_be_skipped.py').write('import os\n'
                                                 '\n'
                                                 'print("Hello World")'
                                                 '\n'
                                                 'import sys\n')

    test_run_directory = os.getcwd()
    os.chdir(str(base_dir))
    with pytest.raises(Exception):  # without the settings path provided: the command should not skip & identify errors
        subprocess.run(['isort', '--check-only'], check=True)
    result = subprocess.run(
        ['isort', '--check-only', '--settings-path=conf/.isort.cfg'],
        stdout=subprocess.PIPE,
        check=True
    )
    os.chdir(str(test_run_directory))

    assert b'skipped 2' in result.stdout.lower()
// test_settings_path_skip_issue_909 [python]
def test_settings_path_skip_issue_909(tmpdir):
    base_dir = tmpdir.mkdir('project')
    config_dir = base_dir.mkdir('conf')
    config_dir.join('.isort.cfg').write('[isort]\n'
                                        'skip =\n'
                                        '    file_to_be_skipped.py\n'
                                        'skip_glob =\n'
                                        '    *glob_skip*\n')

    base_dir.join('file_glob_skip.py').write('import os\n'
                                             '\n'
                                             'print("Hello World")\n'
                                             '\n'
                                             'import sys\n')
    base_dir.join('file_to_be_skipped.py').write('import os\n'
                                                 '\n'
                                                 'print("Hello World")'
                                                 '\n'
                                                 'import sys\n')

    test_run_directory = os.getcwd()
    os.chdir(str(base_dir))
    with pytest.raises(Exception):  # without the settings path provided: the command should not skip & identify errors
        check_output(['isort', '--check-only'])
    results = check_output(['isort', '--check-only', '--settings-path=conf/.isort.cfg'])
    os.chdir(str(test_run_directory))

    assert b'skipped 2' in results.lower()
// _create_3par_fibrechan_host [python]
    def _create_3par_fibrechan_host(self, hostname, wwns, domain, persona_id):
        """Create a 3PAR host.

        Create a 3PAR host, if there is already a host on the 3par using
        the same wwn but with a different hostname, return the hostname
        used by 3PAR.
        """
        command = ['createhost', '-persona', persona_id, '-domain', domain,
                   hostname]
        for wwn in wwns:
            command.append(wwn)

        out = self.common._cli_run(command)
        if out and len(out) > 1:
            return self.common.parse_create_host_error(hostname, out)

        return hostname
// _create_3par_fibrechan_host [python]
    def _create_3par_fibrechan_host(self, hostname, wwn, domain, persona_id):
        """Create a 3PAR host.

        Create a 3PAR host, if there is already a host on the 3par using
        the same wwn but with a different hostname, return the hostname
        used by 3PAR.
        """
        out = self.common._cli_run('createhost -persona %s -domain %s %s %s'
                                   % (persona_id, domain,
                                      hostname, " ".join(wwn)), None)
        if out and len(out) > 1:
            return self.common.parse_create_host_error(hostname, out)

        return hostname
// take_bug_report [python]
    def take_bug_report(self, test_name, begin_time):
        """Takes a bug report on the device and stores it in a file.

        Args:
            test_name: Name of the test case that triggered this bug report.
            begin_time: Logline format timestamp taken when the test started.
        """
        new_br = True
        try:
            stdout = self.adb.shell('bugreportz -v').decode('utf-8')
            # This check is necessary for builds before N, where adb shell's ret
            # code and stderr are not propagated properly.
            if 'not found' in stdout:
                new_br = False
        except adb.AdbError:
            new_br = False
        br_path = os.path.join(self.log_path, 'BugReports')
        utils.create_dir(br_path)
        base_name = ',%s,%s.txt' % (begin_time, self.serial)
        if new_br:
            base_name = base_name.replace('.txt', '.zip')
        test_name_len = utils.MAX_FILENAME_LEN - len(base_name)
        out_name = test_name[:test_name_len] + base_name
        full_out_path = os.path.join(br_path, out_name.replace(' ', r'\ '))
        # in case device restarted, wait for adb interface to return
        self.wait_for_boot_completion()
        self.log.info('Taking bugreport for %s.', test_name)
        if new_br:
            out = self.adb.shell('bugreportz').decode('utf-8')
            if not out.startswith('OK'):
                raise DeviceError(self, 'Failed to take bugreport: %s' % out)
            br_out_path = out.split(':')[1].strip()
            self.adb.pull([br_out_path, full_out_path])
        else:
            # shell=True as this command redirects the stdout to a local file
            # using shell redirection.
            self.adb.bugreport(' > %s' % full_out_path, shell=True)
        self.log.info('Bugreport for %s taken at %s.', test_name,
                      full_out_path)
// take_bug_report [python]
    def take_bug_report(self, test_name, begin_time):
        """Takes a bug report on the device and stores it in a file.

        Args:
            test_name: Name of the test case that triggered this bug report.
            begin_time: Logline format timestamp taken when the test started.
        """
        new_br = True
        try:
            stdout = self.adb.shell('bugreportz -v').decode('utf-8')
            # This check is necessary for builds before N, where adb shell's ret
            # code and stderr are not propagated properly.
            if 'not found' in stdout:
                new_br = False
        except adb.AdbError:
            new_br = False
        br_path = os.path.join(self.log_path, 'BugReports')
        utils.create_dir(br_path)
        base_name = ',%s,%s.txt' % (begin_time, self.serial)
        if new_br:
            base_name = base_name.replace('.txt', '.zip')
        test_name_len = utils.MAX_FILENAME_LEN - len(base_name)
        out_name = test_name[:test_name_len] + base_name
        full_out_path = os.path.join(br_path, out_name.replace(' ', r'\ '))
        # in case device restarted, wait for adb interface to return
        self.wait_for_boot_completion()
        self.log.info('Taking bugreport for %s.', test_name)
        if new_br:
            out = self.adb.shell('bugreportz').decode('utf-8')
            if not out.startswith('OK'):
                raise DeviceError(self, 'Failed to take bugreport: %s' % out)
            br_out_path = out.split(':')[1].strip()
            self.adb.pull('%s %s' % (br_out_path, full_out_path))
        else:
            self.adb.bugreport(' > %s' % full_out_path)
        self.log.info('Bugreport for %s taken at %s.', test_name,
                      full_out_path)
// test_create_invalid_host [python]
    def test_create_invalid_host(self):
        self.flags(lock_path=self.tempdir)

        #record
        self.clear_mox()
        self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "get_cpg",
                       self.fake_get_cpg)
        self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "get_domain",
                       self.fake_get_domain)
        _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)
        self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "_run_ssh", _run_ssh)

        show_host_cmd = ['showhost', '-verbose', 'fakehost']
        _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), ''])

        create_host_cmd = (['createhost', '-iscsi', '-persona', '1', '-domain',
                           ('OpenStack',), 'fakehost',
                            'iqn.1993-08.org.debian:01:222'])
        in_use_ret = pack('\r\nalready used by host fakehost.foo ')
        _run_ssh(create_host_cmd, False).AndReturn([in_use_ret, ''])

        show_3par_cmd = ['showhost', '-verbose', 'fakehost.foo']
        _run_ssh(show_3par_cmd, False).AndReturn([pack(ISCSI_3PAR_RET), ''])
        self.mox.ReplayAll()

        host = self.driver._create_host(self.volume, self.connector)

        self.assertEquals(host['name'], 'fakehost.foo')
// test_create_invalid_host [python]
    def test_create_invalid_host(self):
        self.flags(lock_path=self.tempdir)

        #record
        self.clear_mox()
        self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "get_cpg",
                       self.fake_get_cpg)
        self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "get_domain",
                       self.fake_get_domain)
        _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)
        self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "_run_ssh", _run_ssh)

        show_host_cmd = 'showhost -verbose fakehost'
        _run_ssh(show_host_cmd, False).AndReturn([pack('no hosts listed'), ''])

        create_host_cmd = ('createhost -iscsi -persona 1 -domain '
                           '(\'OpenStack\',) '
                           'fakehost iqn.1993-08.org.debian:01:222')
        in_use_ret = pack('\r\nalready used by host fakehost.foo ')
        _run_ssh(create_host_cmd, False).AndReturn([in_use_ret, ''])

        show_3par_cmd = 'showhost -verbose fakehost.foo'
        _run_ssh(show_3par_cmd, False).AndReturn([pack(ISCSI_3PAR_RET), ''])
        self.mox.ReplayAll()

        host = self.driver._create_host(self.volume, self.connector)

        self.assertEquals(host['name'], 'fakehost.foo')
// __getattr__.adb_call [python]
        def adb_call(args=None, shell=False):
            """Wrapper for an ADB command.

            Args:
                args: string or list of strings, arguments to the adb command.
                    See subprocess.Proc() documentation.
                shell: bool, True to run this command through the system shell,
                    False to invoke it directly. See subprocess.Proc() docs.

            Returns:
                The output of the adb command run if exit code is 0.
            """
            args = args or ''
            clean_name = name.replace('_', '-')
            return self._exec_adb_cmd(clean_name, args, shell=shell)
// __getattr__.adb_call [python]
        def adb_call(*args):
            clean_name = name.replace('_', '-')
            arg_str = ' '.join(str(elem) for elem in args)
            return self._exec_adb_cmd(clean_name, arg_str)
// test_skip_paths_issue_938 [python]
def test_skip_paths_issue_938(tmpdir):
    base_dir = tmpdir.mkdir('project')
    config_dir = base_dir.mkdir('conf')
    config_dir.join('.isort.cfg').write('[isort]\n'
                                        'line_length = 88\n'
                                        'multi_line_output = 4\n'
                                        'lines_after_imports = 2\n'
                                        'skip_glob =\n'
                                        '    migrations/**.py\n')
    base_dir.join('dont_skip.py').write('import os\n'
                                        '\n'
                                        'print("Hello World")'
                                        '\n'
                                        'import sys\n')

    migrations_dir = base_dir.mkdir('migrations')
    migrations_dir.join('file_glob_skip.py').write('import os\n'
                                                   '\n'
                                                   'print("Hello World")\n'
                                                   '\n'
                                                   'import sys\n')

    test_run_directory = os.getcwd()
    os.chdir(str(base_dir))
    result = subprocess.run(
        ['isort', 'dont_skip.py', 'migrations/file_glob_skip.py'],
        stdout=subprocess.PIPE,
        check=True,
    )
    os.chdir(str(test_run_directory))

    assert b'skipped' not in result.stdout.lower()

    os.chdir(str(base_dir))
    result = subprocess.run(
        ['isort', '--filter-files', '--settings-path=conf/.isort.cfg', 'dont_skip.py', 'migrations/file_glob_skip.py'],
        stdout=subprocess.PIPE,
        check=True,
    )
    os.chdir(str(test_run_directory))

    assert b'skipped 1' in result.stdout.lower()
// test_skip_paths_issue_938 [python]
def test_skip_paths_issue_938(tmpdir):
    base_dir = tmpdir.mkdir('project')
    config_dir = base_dir.mkdir('conf')
    config_dir.join('.isort.cfg').write('[isort]\n'
                                        'line_length = 88\n'
                                        'multi_line_output = 4\n'
                                        'lines_after_imports = 2\n'
                                        'skip_glob =\n'
                                        '    migrations/**.py\n')
    base_dir.join('dont_skip.py').write('import os\n'
                                        '\n'
                                        'print("Hello World")'
                                        '\n'
                                        'import sys\n')

    migrations_dir = base_dir.mkdir('migrations')
    migrations_dir.join('file_glob_skip.py').write('import os\n'
                                                   '\n'
                                                   'print("Hello World")\n'
                                                   '\n'
                                                   'import sys\n')

    test_run_directory = os.getcwd()
    os.chdir(str(base_dir))
    results = check_output(['isort', 'dont_skip.py', 'migrations/file_glob_skip.py'])
    os.chdir(str(test_run_directory))

    assert b'skipped' not in results.lower()

    os.chdir(str(base_dir))
    results = check_output(['isort', '--filter-files', '--settings-path=conf/.isort.cfg', 'dont_skip.py', 'migrations/file_glob_skip.py'])
    os.chdir(str(test_run_directory))

    assert b'skipped 1' in results.lower()
// _ensure_vdisk_no_fc_mappings [python]
    def _ensure_vdisk_no_fc_mappings(self, name, allow_snaps=True):
        # Ensure vdisk has no FlashCopy mappings
        mapping_ids = self._get_vdisk_fc_mappings(name)
        while len(mapping_ids):
            wait_for_copy = False
            for map_id in mapping_ids:
                attrs = self._get_flashcopy_mapping_attributes(map_id)
                if not attrs:
                    continue
                source = attrs['source_vdisk_name']
                target = attrs['target_vdisk_name']
                copy_rate = attrs['copy_rate']
                status = attrs['status']

                if copy_rate == '0':
                    # Case #2: A vdisk that has snapshots
                    if source == name:
                        if not allow_snaps:
                            return False
                        ssh_cmd = ['svctask', 'chfcmap', '-copyrate', '50',
                                   '-autodelete', 'on', map_id]
                        out, err = self._run_ssh(ssh_cmd)
                        wait_for_copy = True
                    # Case #3: A snapshot
                    else:
                        msg = (_('Vdisk %(name)s not involved in '
                                 'mapping %(src)s -> %(tgt)s') %
                               {'name': name, 'src': source, 'tgt': target})
                        self._driver_assert(target == name, msg)
                        if status in ['copying', 'prepared']:
                            self._run_ssh(['svctask', 'stopfcmap', map_id])
                        elif status in ['stopping', 'preparing']:
                            wait_for_copy = True
                        else:
                            self._run_ssh(['svctask', 'rmfcmap', '-force',
                                           map_id])
                # Case 4: Copy in progress - wait and will autodelete
                else:
                    if status == 'prepared':
                        self._run_ssh(['svctask', 'stopfcmap', map_id])
                        self._run_ssh(['svctask', 'rmfcmap', '-force', map_id])
                    elif status == 'idle_or_copied':
                        # Prepare failed
                        self._run_ssh(['svctask', 'rmfcmap', '-force', map_id])
                    else:
                        wait_for_copy = True
            if wait_for_copy:
                time.sleep(5)
            mapping_ids = self._get_vdisk_fc_mappings(name)
        return True