Internal variant of freecpu taking a libvirt connection as parameter
977619
def _freecpu(conn):
    '''
    
    '''
    cpus = conn.getInfo()[2]
    for dom in _get_domain(conn, iterable=True):
        if dom.ID() > 0:
            cpus -= dom.info()[3]
    return cpus
243536
def create_virtualenv(srcdir, datadir, preload_image, get_container_name):
    
    try:
        if docker.is_boot2docker():
            docker.data_only_container(
                get_container_name('venv'),
                ['/usr/lib/ckan'],
                )
            img_id = docker.web_command(
                '/bin/mv /usr/lib/ckan/ /usr/lib/ckan_original',
                image=preload_image,
                commit=True,
                )
            docker.web_command(
                command='/bin/cp -a /usr/lib/ckan_original/. /usr/lib/ckan/.',
                volumes_from=get_container_name('venv'),
                image=img_id,
                )
            docker.remove_image(img_id)
            return

        docker.web_command(
            command='/bin/cp -a /usr/lib/ckan/. /usr/lib/ckan_target/.',
            rw={datadir + '/venv': '/usr/lib/ckan_target'},
            image=preload_image,
            )
    finally:
        rw = {datadir + '/venv': '/usr/lib/ckan'} if not docker.is_boot2docker() else {}
        volumes_from = get_container_name('venv') if docker.is_boot2docker() else None
        # fix venv permissions
        docker.web_command(
            command='/bin/chown -R --reference=/project /usr/lib/ckan',
            rw=rw,
            volumes_from=volumes_from,
            ro={srcdir: '/project'},
            )
1355898
function FindFreePortSync(options = {}) {
    this.defaultOptions = {
        // port start for scan
        start: 1,
        // port end for scan
        end: 65534,
        // ports number for scan
        num: 1,
        // specify ip for scan
        ip: '0.0.0.0|127.0.0.1',
        // for inner usage, some platforms like darkwin shows commom address 0.0.0.0:10000 as *.10000
        _ipSpecial: '\\*|127.0.0.1',
        // scan this port
        port: null
    };

    this.msg = {
        error: 'Cannot find free port'
    }

    this.adjustOptions(options);
}
1110917
def startup_capabilities(cls, rcfile=False, norc=False, stdin=False,
                             command=False):
        
        raise NotImplementedError
168975
private synchronized VirtualMachine getAttachedVirtualMachine() throws VirtualMachineException {
        if (PID == null) {
            // Java Attach requires a PID.
            return null;
        }

        if (vm == null) {
            vm = createVirtualMachine();
        }
        return vm.isAttached() ? vm : null;
    }
1243983
def _load_nvrtc_lib(self, lib_path):
        
        if sizeof(c_void_p) == 8:
            if system() == 'Windows':
                def_lib_name = 'nvrtc64_92.dll'
            elif system() == 'Darwin':
                def_lib_name = 'libnvrtc.dylib'
            else:
                def_lib_name = 'libnvrtc.so'
        else:
            raise NVRTCException('NVRTC is not supported on 32-bit platforms.')

        if len(lib_path) == 0:
            name = def_lib_name
        else:
            name = lib_path

        self._lib = cdll.LoadLibrary(name)

        self._lib.nvrtcCreateProgram.argtypes = [
            POINTER(c_void_p),  # prog
            c_char_p,           # src
            c_char_p,           # name
            c_int,              # numHeaders
            POINTER(c_char_p),  # headers
            POINTER(c_char_p)   # include_names
        ]
        self._lib.nvrtcCreateProgram.restype = c_int

        self._lib.nvrtcDestroyProgram.argtypes = [
            POINTER(c_void_p)   # prog
        ]
        self._lib.nvrtcDestroyProgram.restype = c_int

        self._lib.nvrtcCompileProgram.argtypes = [
            c_void_p,           # prog
            c_int,              # numOptions
            POINTER(c_char_p)   # options
        ]
        self._lib.nvrtcCompileProgram.restype = c_int

        self._lib.nvrtcGetPTXSize.argtypes = [
            c_void_p,           # prog
            POINTER(c_size_t)   # ptxSizeRet
        ]
        self._lib.nvrtcGetPTXSize.restype = c_int

        self._lib.nvrtcGetPTX.argtypes = [
            c_void_p,           # prog
            c_char_p            # ptx
        ]
        self._lib.nvrtcGetPTX.restype = c_int

        self._lib.nvrtcGetProgramLogSize.argtypes = [
            c_void_p,           # prog
            POINTER(c_size_t)   # logSizeRet
        ]
        self._lib.nvrtcGetProgramLogSize.restype = c_int

        self._lib.nvrtcGetProgramLog.argtypes = [
            c_void_p,           # prog
            c_char_p            # log
        ]
        self._lib.nvrtcGetProgramLog.restype = c_int

        self._lib.nvrtcAddNameExpression.argtypes = [
            c_void_p,           # prog
            c_char_p            # nameExpression
        ]
        self._lib.nvrtcAddNameExpression.restype = c_int

        self._lib.nvrtcGetLoweredName.argtypes = [
            c_void_p,           # prog
            c_char_p,           # nameExpression
            POINTER(c_char_p)   # loweredName
        ]
        self._lib.nvrtcGetLoweredName.restype = c_int

        self._lib.nvrtcGetErrorString.argtypes = [
            c_int               # result
        ]
        self._lib.nvrtcGetErrorString.restype = c_char_p

        self._lib.nvrtcVersion.argtypes = [
            POINTER(c_int),     # major
            POINTER(c_int)      # minor
        ]
        self._lib.nvrtcVersion.restype = c_int
680660
def _nic_profile(profile_name, hypervisor, dmac=None):
    '''
    
    '''

    default = [{'eth0': {}}]

    # support old location
    config_data = __salt__['config.option']('virt.nic', {}).get(
        profile_name, None
    )

    if config_data is not None:
        salt.utils.versions.warn_until(
            'Sodium',
            '\'virt.nic\' has been deprecated in favor of \'virt:nic\'. '
            '\'virt.nic\' will stop being used in {version}.'
        )
    else:
        config_data = __salt__['config.get']('virt:nic', {}).get(
            profile_name, default
        )

    interfaces = []

    # pylint: disable=invalid-name
    def append_dict_profile_to_interface_list(profile_dict):
        '''
        Append dictionary profile data to interfaces list
        '''
        for interface_name, attributes in six.iteritems(profile_dict):
            attributes['name'] = interface_name
            interfaces.append(attributes)

    # old style dicts (top-level dicts)
    #
    # virt:
    #    nic:
    #        eth0:
    #            bridge: br0
    #        eth1:
    #            network: test_net
    if isinstance(config_data, dict):
        append_dict_profile_to_interface_list(config_data)

    # new style lists (may contain dicts)
    #
    # virt:
    #   nic:
    #     - eth0:
    #         bridge: br0
    #     - eth1:
    #         network: test_net
    #
    # virt:
    #   nic:
    #     - name: eth0
    #       bridge: br0
    #     - name: eth1
    #       network: test_net
    elif isinstance(config_data, list):
        for interface in config_data:
            if isinstance(interface, dict):
                if len(interface) == 1:
                    append_dict_profile_to_interface_list(interface)
                else:
                    interfaces.append(interface)

    # dmac can only be used from init()
    return _complete_nics(interfaces, hypervisor, dmac=dmac)
1062276
def InternalPlatformSwitch(funcname, *args, **kwargs):
  """"""
  # pylint: disable=g-import-not-at-top
  clz = None
  if sys.platform.startswith('linux'):
    from pyu2f.hid import linux
    clz = linux.LinuxHidDevice
  elif sys.platform.startswith('win32'):
    from pyu2f.hid import windows
    clz = windows.WindowsHidDevice
  elif sys.platform.startswith('darwin'):
    from pyu2f.hid import macos
    clz = macos.MacOsHidDevice

  if not clz:
    raise Exception('Unsupported platform: ' + sys.platform)

  if funcname == '__init__':
    return clz(*args, **kwargs)
  return getattr(clz, funcname)(*args, **kwargs)
618522
def libvlc_vlm_set_enabled(p_instance, psz_name, b_enabled):
    '''
    '''
    f = _Cfunctions.get('libvlc_vlm_set_enabled', None) or \
        _Cfunction('libvlc_vlm_set_enabled', ((1,), (1,), (1,),), None,
                    ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_int)
    return f(p_instance, psz_name, b_enabled)
1133714
def pool_lookup(hypervisor, disk_path):
    
    try:
        volume = hypervisor.storageVolLookupByPath(disk_path)

        return volume.storagePoolLookupByVolume()
    except libvirt.libvirtError:
        return None
684146
def _virtual_hv(osdata):
    '''
    
    '''
    grains = {}

    # Bail early if we're not running on Xen
    try:
        if 'xen' not in osdata['virtual']:
            return grains
    except KeyError:
        return grains

    # Try to get the exact hypervisor version from sysfs
    try:
        version = {}
        for fn in ('major', 'minor', 'extra'):
            with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
                version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
        grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
        grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
    except (IOError, OSError, KeyError):
        pass

    # Try to read and decode the supported feature set of the hypervisor
    # Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
    # Table data from include/xen/interface/features.h
    xen_feature_table = {0: 'writable_page_tables',
                         1: 'writable_descriptor_tables',
                         2: 'auto_translated_physmap',
                         3: 'supervisor_mode_kernel',
                         4: 'pae_pgdir_above_4gb',
                         5: 'mmu_pt_update_preserve_ad',
                         7: 'gnttab_map_avail_bits',
                         8: 'hvm_callback_vector',
                         9: 'hvm_safe_pvclock',
                        10: 'hvm_pirqs',
                        11: 'dom0',
                        12: 'grant_map_identity',
                        13: 'memory_op_vnode_supported',
                        14: 'ARM_SMCCC_supported'}
    try:
        with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
            features = salt.utils.stringutils.to_unicode(fhr.read().strip())
        enabled_features = []
        for bit, feat in six.iteritems(xen_feature_table):
            if int(features, 16) & (1 << bit):
                enabled_features.append(feat)
        grains['virtual_hv_features'] = features
        grains['virtual_hv_features_list'] = enabled_features
    except (IOError, OSError, KeyError):
        pass

    return grains
715928
def init_not_msvc(self):
        
        # find_library() does not search automatically LD_LIBRARY_PATH
        paths = os.environ.get('LD_LIBRARY_PATH', '').split(':')
        for gomp in ('libgomp.so', 'libgomp.dylib'):
            if cxx is None:
                continue
            cmd = [cxx, '-print-file-name=' + gomp]
            # the subprocess can fail in various ways
            # in that case just give up that path
            try:
                path = os.path.dirname(check_output(cmd).strip())
                if path:
                    paths.append(path)
            except OSError:
                pass

        # Try to load find libgomp shared library using loader search dirs
        libgomp_path = find_library("gomp")

        # Try to use custom paths if lookup failed
        for path in paths:
            if libgomp_path:
                break
            path = path.strip()
            if os.path.isdir(path):
                libgomp_path = find_library(os.path.join(str(path), "libgomp"))

        if not libgomp_path:
            raise ImportError("I can't find a shared library for libgomp,"
                              " you may need to install it or adjust the "
                              "LD_LIBRARY_PATH environment variable.")
        else:
            # Load the library (shouldn't fail with an absolute path right?)
            self.libomp = ctypes.CDLL(libgomp_path)
            self.version = 45
1155121
def GetCpuShares(self):
        ''''''
        counter = c_uint()
        ret = vmGuestLib.VMGuestLib_GetCpuShares(self.handle.value, byref(counter))
        if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret)
        return counter.value
921940
def _init_virtual_io(self, file):
        """"""
        @_ffi.callback("sf_vio_get_filelen")
        def vio_get_filelen(user_data):
            curr = file.tell()
            file.seek(0, SEEK_END)
            size = file.tell()
            file.seek(curr, SEEK_SET)
            return size

        @_ffi.callback("sf_vio_seek")
        def vio_seek(offset, whence, user_data):
            file.seek(offset, whence)
            return file.tell()

        @_ffi.callback("sf_vio_read")
        def vio_read(ptr, count, user_data):
            # first try readinto(), if not available fall back to read()
            try:
                buf = _ffi.buffer(ptr, count)
                data_read = file.readinto(buf)
            except AttributeError:
                data = file.read(count)
                data_read = len(data)
                buf = _ffi.buffer(ptr, data_read)
                buf[0:data_read] = data
            return data_read

        @_ffi.callback("sf_vio_write")
        def vio_write(ptr, count, user_data):
            buf = _ffi.buffer(ptr, count)
            data = buf[:]
            written = file.write(data)
            # write() returns None for file objects in Python <= 2.7:
            if written is None:
                written = count
            return written

        @_ffi.callback("sf_vio_tell")
        def vio_tell(user_data):
            return file.tell()

        # Note: the callback functions must be kept alive!
        self._virtual_io = {'get_filelen': vio_get_filelen,
                            'seek': vio_seek,
                            'read': vio_read,
                            'write': vio_write,
                            'tell': vio_tell}

        return _ffi.new("SF_VIRTUAL_IO*", self._virtual_io)
988091
def enable_vt_mode(filehandle=None):
    

    if filehandle is None:
        filehandle = msvcrt.get_osfhandle(sys.__stdout__.fileno())

    current_mode = wintypes.DWORD()
    KERNEL32.GetConsoleMode(filehandle, ctypes.byref(current_mode))
    new_mode = 0x0004 | current_mode.value
    KERNEL32.SetConsoleMode(filehandle, new_mode)
261716
def tunnel_to_kernel(self, connection_info, hostname, sshkey=None,
                         password=None, timeout=10):
        
        lports = zmqtunnel.select_random_ports(4)
        rports = (connection_info['shell_port'], connection_info['iopub_port'],
                  connection_info['stdin_port'], connection_info['hb_port'])
        remote_ip = connection_info['ip']
        for lp, rp in zip(lports, rports):
            self.ssh_tunnel(lp, rp, hostname, remote_ip, sshkey, password,
                            timeout)
        return tuple(lports)
124477
function updateCpu (cpu, next) {
  if (cpu !== null) {
    getRealUptime(function (err, uptime) {
      if (err) return next(err)
      cpu.uptime = uptime
      next(null, cpu)
    })
    return
  }

  parallel([
    getClockAndPageSize,
    getRealUptime
  ], function (err, data) {
    if (err) return next(err)

    cpu = {
      clockTick: data[0].clockTick,
      pageSize: data[0].pageSize,
      uptime: data[1]
    }

    next(null, cpu)
  })
}