Retrieve core and memory information for the current machine.
338028
def machine_info():
    
    import psutil
    BYTES_IN_GIG = 1073741824.0
    free_bytes = psutil.virtual_memory().total
    return [{"memory": float("%.1f" % (free_bytes / BYTES_IN_GIG)), "cores": multiprocessing.cpu_count(),
             "name": socket.gethostname()}]
1005952
def pretty_memory_info():
    '''
    
    '''
    process = psutil.Process(os.getpid())
    return '{}MB memory usage'.format(int(process.memory_info().rss / 2**20))
364319
def _get_vm_info(self):
        

        vm_info = {}
        results = yield from self.manager.execute("showvminfo", [self._vmname, "--machinereadable"])
        for info in results:
            try:
                name, value = info.split('=', 1)
            except ValueError:
                continue
            vm_info[name.strip('"')] = value.strip('"')
        return vm_info
1288622
def _get_cores_memory(data, downscale=2):
    
    resources = config_utils.get_resources("samtools", data["config"])
    num_cores = data["config"]["algorithm"].get("num_cores", 1)
    max_mem = config_utils.adjust_memory(resources.get("memory", "2G"),
                                         downscale, "decrease").upper()
    return num_cores, max_mem
107617
def _get_cpu_info_from_dmesg():
	'''
	
	'''
	# Just return {} if there is no dmesg
	if not DataSource.has_dmesg():
		return {}

	# If dmesg fails return {}
	returncode, output = DataSource.dmesg_a()
	if output == None or returncode != 0:
		return {}

	return _parse_dmesg_output(output)
513815
def _collect_cpu_info(run_info):
  """"""
  cpu_info = {}

  cpu_info["num_cores"] = multiprocessing.cpu_count()

  # Note: cpuinfo is not installed in the TensorFlow OSS tree.
  # It is installable via pip.
  import cpuinfo    # pylint: disable=g-import-not-at-top

  info = cpuinfo.get_cpu_info()
  cpu_info["cpu_info"] = info["brand"]
  cpu_info["mhz_per_cpu"] = info["hz_advertised_raw"][0] / 1.0e6

  run_info["machine_config"]["cpu_info"] = cpu_info
1173978
def _get_cpu_info_from_kstat():
	'''
	
	'''
	try:
		# Just return {} if there is no isainfo or kstat
		if not DataSource.has_isainfo() or not DataSource.has_kstat():
			return {}

		# If isainfo fails return {}
		returncode, flag_output = DataSource.isainfo_vb()
		if flag_output == None or returncode != 0:
			return {}

		# If kstat fails return {}
		returncode, kstat = DataSource.kstat_m_cpu_info()
		if kstat == None or returncode != 0:
			return {}

		# Various fields
		vendor_id = kstat.split('\tvendor_id ')[1].split('\n')[0].strip()
		processor_brand = kstat.split('\tbrand ')[1].split('\n')[0].strip()
		stepping = int(kstat.split('\tstepping ')[1].split('\n')[0].strip())
		model = int(kstat.split('\tmodel ')[1].split('\n')[0].strip())
		family = int(kstat.split('\tfamily ')[1].split('\n')[0].strip())

		# Flags
		flags = flag_output.strip().split('\n')[-1].strip().lower().split()
		flags.sort()

		# Convert from GHz/MHz string to Hz
		scale = 6
		hz_advertised = kstat.split('\tclock_MHz ')[1].split('\n')[0].strip()
		hz_advertised = _to_decimal_string(hz_advertised)

		# Convert from GHz/MHz string to Hz
		hz_actual = kstat.split('\tcurrent_clock_Hz ')[1].split('\n')[0].strip()
		hz_actual = _to_decimal_string(hz_actual)

		info = {
		'vendor_id_raw' : vendor_id,
		'brand_raw' : processor_brand,

		'hz_advertised_friendly' : _hz_short_to_friendly(hz_advertised, scale),
		'hz_actual_friendly' : _hz_short_to_friendly(hz_actual, 0),
		'hz_advertised' : _hz_short_to_full(hz_advertised, scale),
		'hz_actual' : _hz_short_to_full(hz_actual, 0),

		'stepping' : stepping,
		'model' : model,
		'family' : family,
		'flags' : flags
		}

		info = {k: v for k, v in info.items() if v}
		return info
	except:
		return {}
1096546
def _get_cpu_info_from_cpuid():
	'''
	
	'''
	from multiprocessing import Process, Queue

	# Return {} if can't cpuid
	if not DataSource.can_cpuid:
		return {}

	# Get the CPU arch and bits
	arch, bits = _parse_arch(DataSource.arch_string_raw)

	# Return {} if this is not an X86 CPU
	if not arch in ['X86_32', 'X86_64']:
		return {}

	try:
		# Start running the function in a subprocess
		queue = Queue()
		p = Process(target=_actual_get_cpu_info_from_cpuid, args=(queue,))
		p.start()

		# Wait for the process to end, while it is still alive
		while p.is_alive():
			p.join(0)

		# Return {} if it failed
		if p.exitcode != 0:
			return {}

		# Return the result, only if there is something to read
		if not queue.empty():
			output = queue.get()
			return _b64_to_obj(output)
	except:
		pass

	# Return {} if everything failed
	return {}
148533
def memory():
    

    mem_info = {}

    if platform.linux_distribution()[0]:
        with open('/proc/meminfo') as file:
            c = 0
            for line in file:
                lst = line.split()
                if str(lst[0]) == 'MemTotal:':
                    mem_info['total'] = int(lst[1])
                elif str(lst[0]) in ('MemFree:', 'Buffers:', 'Cached:'):
                    c += int(lst[1])
            mem_info['free'] = c
            mem_info['used'] = (mem_info['total']) - c
    elif platform.mac_ver()[0]:
        ps = subprocess.Popen(['ps', '-caxm', '-orss,comm'], stdout=subprocess.PIPE).communicate()[0]
        vm = subprocess.Popen(['vm_stat'], stdout=subprocess.PIPE).communicate()[0]

        # Iterate processes
        process_lines = ps.split('\n')
        sep = re.compile('[\s]+')
        rss_total = 0  # kB
        for row in range(1, len(process_lines)):
            row_text = process_lines[row].strip()
            row_elements = sep.split(row_text)
            try:
                rss = float(row_elements[0]) * 1024
            except:
                rss = 0  # ignore...
            rss_total += rss

        # Process vm_stat
        vm_lines = vm.split('\n')
        sep = re.compile(':[\s]+')
        vm_stats = {}
        for row in range(1, len(vm_lines) - 2):
            row_text = vm_lines[row].strip()
            row_elements = sep.split(row_text)
            vm_stats[(row_elements[0])] = int(row_elements[1].strip('\.')) * 4096

        mem_info['total'] = rss_total
        mem_info['used'] = vm_stats["Pages active"]
        mem_info['free'] = vm_stats["Pages free"]
    else:
        raise('Unsupported Operating System.\n')
        exit(1)

    return mem_info
437074
def _windows_cpudata():
    '''
    
    '''
    # Provides:
    #   num_cpus
    #   cpu_model
    grains = {}
    if 'NUMBER_OF_PROCESSORS' in os.environ:
        # Cast to int so that the logic isn't broken when used as a
        # conditional in templating. Also follows _linux_cpudata()
        try:
            grains['num_cpus'] = int(os.environ['NUMBER_OF_PROCESSORS'])
        except ValueError:
            grains['num_cpus'] = 1
    grains['cpu_model'] = salt.utils.win_reg.read_value(
        hive="HKEY_LOCAL_MACHINE",
        key="HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
        vname="ProcessorNameString").get('vdata')
    return grains
1098322
def _get_cpu_info_from_cpufreq_info():
	'''
	
	'''
	try:
		hz_brand, scale = '0.0', 0

		if not DataSource.has_cpufreq_info():
			return {}

		returncode, output = DataSource.cpufreq_info()
		if returncode != 0:
			return {}

		hz_brand = output.split('current CPU frequency is')[1].split('\n')[0]
		i = hz_brand.find('Hz')
		assert(i != -1)
		hz_brand = hz_brand[0 : i+2].strip().lower()

		if hz_brand.endswith('mhz'):
			scale = 6
		elif hz_brand.endswith('ghz'):
			scale = 9
		hz_brand = hz_brand.rstrip('mhz').rstrip('ghz').strip()
		hz_brand = _to_decimal_string(hz_brand)

		info = {
			'hz_advertised_friendly' : _hz_short_to_friendly(hz_brand, scale),
			'hz_actual_friendly' : _hz_short_to_friendly(hz_brand, scale),
			'hz_advertised' : _hz_short_to_full(hz_brand, scale),
			'hz_actual' : _hz_short_to_full(hz_brand, scale),
		}

		info = {k: v for k, v in info.items() if v}
		return info
	except:
		#raise # NOTE: To have this throw on error, uncomment this line
		return {}
185140
def getMemoryStats(self):
        
        if self._statusxml is None:
            self.initStats()
        node = self._statusxml.find('jvm/memory')
        memstats = {}
        if node is not None:
            for (key,val) in node.items():
                memstats[key] = util.parse_value(val)
        return memstats
574030
def get_bios(self):
        
        uri = "{}/bios".format(self.data["uri"])
        return self._helper.do_get(uri)
1069718
def _linux_cpudata():
    '''
    
    '''
    # Provides:
    #   num_cpus
    #   cpu_model
    #   cpu_flags
    grains = {}
    cpuinfo = '/proc/cpuinfo'
    # Parse over the cpuinfo file
    if os.path.isfile(cpuinfo):
        with salt.utils.files.fopen(cpuinfo, 'r') as _fp:
            grains['num_cpus'] = 0
            for line in _fp:
                comps = line.split(':')
                if not len(comps) > 1:
                    continue
                key = comps[0].strip()
                val = comps[1].strip()
                if key == 'processor':
                    grains['num_cpus'] += 1
                elif key == 'model name':
                    grains['cpu_model'] = val
                elif key == 'flags':
                    grains['cpu_flags'] = val.split()
                elif key == 'Features':
                    grains['cpu_flags'] = val.split()
                # ARM support - /proc/cpuinfo
                #
                # Processor       : ARMv6-compatible processor rev 7 (v6l)
                # BogoMIPS        : 697.95
                # Features        : swp half thumb fastmult vfp edsp java tls
                # CPU implementer : 0x41
                # CPU architecture: 7
                # CPU variant     : 0x0
                # CPU part        : 0xb76
                # CPU revision    : 7
                #
                # Hardware        : BCM2708
                # Revision        : 0002
                # Serial          : 00000000
                elif key == 'Processor':
                    grains['cpu_model'] = val.split('-')[0]
                    grains['num_cpus'] = 1
    if 'num_cpus' not in grains:
        grains['num_cpus'] = 0
    if 'cpu_model' not in grains:
        grains['cpu_model'] = 'Unknown'
    if 'cpu_flags' not in grains:
        grains['cpu_flags'] = []
    return grains
418531
def _sge_info(queue):
    
    qhost_out = subprocess.check_output(["qhost", "-q", "-xml"]).decode()
    qstat_queue = ["-q", queue] if queue and "," not in queue else []
    qstat_out = subprocess.check_output(["qstat", "-f", "-xml"] + qstat_queue).decode()
    slot_info = _sge_get_slots(qstat_out)
    mem_info = _sge_get_mem(qhost_out, queue)
    machine_keys = slot_info.keys()
    #num_cpus_vec = [slot_info[x]["slots_total"] for x in machine_keys]
    #mem_vec = [mem_info[x]["mem_total"] for x in machine_keys]
    mem_per_slot = [mem_info[x]["mem_total"] / float(slot_info[x]["slots_total"]) for x in machine_keys]
    min_ratio_index = mem_per_slot.index(median_left(mem_per_slot))
    mem_info[machine_keys[min_ratio_index]]["mem_total"]
    return [{"cores": slot_info[machine_keys[min_ratio_index]]["slots_total"],
             "memory": mem_info[machine_keys[min_ratio_index]]["mem_total"],
             "name": "sge_machine"}]
176347
private function _cpuinfo()
    {
        $allCpus = $this->_get_Win32_Processor();
        if (!$allCpus) {
            if (CommonFunctions::executeProgram('reg', 'query HKEY_LOCAL_MACHINE\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor /s', $strBuf, false) && (strlen($strBuf) > 0)) {
                $lines = preg_split('/\n/', $strBuf);
                $coreCount = -1;
                foreach ($lines as $line) {
                    if (preg_match('/^HKEY_LOCAL_MACHINE\\\\HARDWARE\\\\DESCRIPTION\\\\System\\\\CentralProcessor\\\\\d+/i', $line)) {
                        $coreCount++;
                    } elseif ($coreCount >= 0) {
                        if (preg_match("/^\s*ProcessorNameString\s+REG_SZ\s+(.+)\s*$/i", $line, $buffer2)) {
                            $allCpus[$coreCount]['Name'] = $buffer2[1];
                        } elseif (preg_match("/^\s*~MHz\s+REG_DWORD\s+(0x.+)\s*$/i", $line, $buffer2)) {
                            $allCpus[$coreCount]['CurrentClockSpeed'] = hexdec($buffer2[1]);
                        }
                    }
                }
            }
        }

        $globalcpus = 0;
        foreach ($allCpus as $oneCpu) {
            $cpuCount = 1;
            if (isset($oneCpu['NumberOfLogicalProcessors'])) {
                $cpuCount = $oneCpu['NumberOfLogicalProcessors'];
            } elseif (isset($oneCpu['NumberOfCores'])) {
                $cpuCount = $oneCpu['NumberOfCores'];
            }
            $globalcpus+=$cpuCount;
        }

        foreach ($allCpus as $oneCpu) {
            $cpuCount = 1;
            if (isset($oneCpu['NumberOfLogicalProcessors'])) {
                $cpuCount = $oneCpu['NumberOfLogicalProcessors'];
            } elseif (isset($oneCpu['NumberOfCores'])) {
                $cpuCount = $oneCpu['NumberOfCores'];
            }
            for ($i = 0; $i < $cpuCount; $i++) {
                $cpu = new CpuDevice();
                if (isset($oneCpu['Name'])) $cpu->setModel($oneCpu['Name']);
                if (isset($oneCpu['L3CacheSize']) && ($oneCpu['L3CacheSize'] > 0)) {
                    $cpu->setCache($oneCpu['L3CacheSize'] * 1024);
                } elseif (isset($oneCpu['L2CacheSize'])) {
                    $cpu->setCache($oneCpu['L2CacheSize'] * 1024);
                }
                if (isset($oneCpu['CurrentClockSpeed'])) {
                    $cpu->setCpuSpeed($oneCpu['CurrentClockSpeed']);
                    if (isset($oneCpu['MaxClockSpeed']) && ($oneCpu['CurrentClockSpeed'] < $oneCpu['MaxClockSpeed'])) $cpu->setCpuSpeedMax($oneCpu['MaxClockSpeed']);
                }
                if (isset($oneCpu['ExtClock'])) $cpu->setBusSpeed($oneCpu['ExtClock']);
                if (PSI_LOAD_BAR) {
                    if ((count($allCpus) == 1) && ($globalcpus > 1)) {
                        if (($cpubuffer = $this->_get_Win32_PerfFormattedData_PerfOS_Processor()) && (count($cpubuffer) == ($cpuCount+1)) && isset($cpubuffer['cpu'.$i])) {
                            $cpu->setLoad($cpubuffer['cpu'.$i]);
                        }
                    } elseif (count($allCpus) == $globalcpus) {
                        if (isset($oneCpu['LoadPercentage'])) $cpu->setLoad($oneCpu['LoadPercentage']);
                    }
                }
                $this->sys->setCpus($cpu);
            }
        }
    }
92694
def _check_bios_resource(self, properties=[]):
        """"""

        system = self._get_host_details()
        if ('links' in system['Oem']['Hp'] and
                'BIOS' in system['Oem']['Hp']['links']):
            # Get the BIOS URI and Settings
            bios_uri = system['Oem']['Hp']['links']['BIOS']['href']
            status, headers, bios_settings = self._rest_get(bios_uri)

            if status >= 300:
                msg = self._get_extended_error(bios_settings)
                raise exception.IloError(msg)

            # If property is not None, check if the bios_property is supported
            for property in properties:
                if property not in bios_settings:
                    # not supported on this platform
                    msg = ('BIOS Property "' + property + '" is not'
                           ' supported on this system.')
                    raise exception.IloCommandNotSupportedError(msg)

            return headers, bios_uri, bios_settings

        else:
            msg = ('"links/BIOS" section in ComputerSystem/Oem/Hp'
                   ' does not exist')
            raise exception.IloCommandNotSupportedError(msg)