get monitor info from the plugin `pe` and return a hash object
487265
def get_monitor_info(pe, opts={})
      obj = {}

      # Common plugin information
      obj['plugin_id'] = pe.plugin_id
      obj['plugin_category'] = plugin_category(pe)
      obj['type'] = pe.config['@type']
      obj['config'] = pe.config if opts[:with_config]

      # run MONITOR_INFO in plugins' instance context and store the info to obj
      MONITOR_INFO.each_pair {|key,code|
        begin
          catch(:skip) do
            obj[key] = pe.instance_exec(&code)
          end
        rescue NoMethodError => e
          unless @first_warn
            log.error "NoMethodError in monitoring plugins", key: key, plugin: pe.class, error: e
            log.error_backtrace
            @first_warn = true
          end
        rescue => e
          log.warn "unexpected error in monitoring plugins", key: key, plugin: pe.class, error: e
        end
      }

      obj['retry'] = get_retry_info(pe.retry) if opts[:with_retry] and pe.instance_variable_defined?(:@retry)

      # include all instance variables if :with_debug_info is set
      if opts[:with_debug_info]
        iv = {}
        pe.instance_eval do
          instance_variables.each {|sym|
            next if IGNORE_ATTRIBUTES.include?(sym)
            key = sym.to_s[1..-1]  # removes first '@'
            iv[key] = instance_variable_get(sym)
          }
        end
        obj['instance_variables'] = iv
      elsif ivars = opts[:ivars]
        iv = {}
        ivars.each {|name|
          iname = "@#{name}"
          iv[name] = pe.instance_variable_get(iname) if pe.instance_variable_defined?(iname)
        }
        obj['instance_variables'] = iv
      end

      obj
    end
213188
def _getspnam(name, root=None):
    '''
    
    '''
    root = '/' if not root else root
    passwd = os.path.join(root, 'etc/shadow')
    with salt.utils.files.fopen(passwd) as fp_:
        for line in fp_:
            line = salt.utils.stringutils.to_unicode(line)
            comps = line.strip().split(':')
            if comps[0] == name:
                # Generate a getspnam compatible output
                for i in range(2, 9):
                    comps[i] = int(comps[i]) if comps[i] else -1
                return spwd.struct_spwd(comps)
    raise KeyError
546682
def _extract_device_name_from_event(event):
  """"""
  plugin_data_content = json.loads(
      tf.compat.as_str(event.summary.value[0].metadata.plugin_data.content))
  return plugin_data_content['device']
1298063
def show_health_monitor(self, health_monitor, **_params):
        """"""
        return self.get(self.health_monitor_path % (health_monitor),
                        params=_params)
1208644
def groestlHash(data):
    """"""
    try:
        import groestlcoin_hash
    except ImportError:
        t = 'Groestlcoin requires the groestlcoin_hash package ("pip install groestlcoin_hash").'
        print(t)
        raise ImportError(t)

    return bytes_as_revhex(groestlcoin_hash.getHash(data, len(data)))
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 {}
645699
def get_pe(self):
        
        return PE(self.rest_client.make_request(self.pe), self.rest_client)
739282
def getMonitorById(self, monitorId):
        
        url = self.baseUrl
        url += "getMonitors?apiKey=%s&monitors=%s" % (self.apiKey, monitorId)
        url += "&noJsonCallback=1&format=json"
        success, response = self.requestApi(url)
        if success:
            status = response.get('monitors').get('monitor')[0].get('status')
            alltimeuptimeratio = response.get('monitors').get('monitor')[0].get('alltimeuptimeratio')
            return status, alltimeuptimeratio
        return None, None
769288
def host_info(host=None):
    '''
    
    '''
    data = query(host, quiet=True)
    for id_ in data:
        if 'vm_info' in data[id_]:
            data[id_].pop('vm_info')
    __jid_event__.fire_event({'data': data, 'outputter': 'nested'}, 'progress')
    return data
368871
def get_port_monitor(self):
        
        uri = "{}{}".format(self.data["uri"], self.PORT_MONITOR_PATH)
        return self._helper.do_get(uri)
983666
def _get_interface_info(interface):
    '''
    
    '''
    adapter_mode = _get_adapter_mode_info(interface.name)
    if adapter_mode == 'disabled':
        return _get_base_interface_info(interface)
    elif adapter_mode == 'ethercat':
        return _get_ethercat_interface_info(interface)
    return _get_tcpip_interface_info(interface)
1116300
function getPsInfo(param, callback) { 
	if (process.platform === 'windows') return;
	var pid = param.pid;
	var cmd = "ps auxw | grep " + pid + " | grep -v 'grep'";
	//var cmd = "ps auxw | grep -E '.+?\\s+" + pid + "\\s+'"  ;
	exec(cmd, function(err, output) {
		if (!!err) {
			if (err.code === 1) {
				console.log('the content is null!');
			} else {
				console.error('getPsInfo failed! ' + err.stack);
			}
			callback(err, null);
			return;
		} 
    format(param, output, callback);
	});
}
767458
def _getMonitorInfo(self):
        
        monitors = []
        CCHDEVICENAME = 32
        def _MonitorEnumProcCallback(hMonitor, hdcMonitor, lprcMonitor, dwData):
            class MONITORINFOEX(ctypes.Structure):
                _fields_ = [("cbSize", ctypes.wintypes.DWORD),
                            ("rcMonitor", ctypes.wintypes.RECT),
                            ("rcWork", ctypes.wintypes.RECT),
                            ("dwFlags", ctypes.wintypes.DWORD),
                            ("szDevice", ctypes.wintypes.WCHAR*CCHDEVICENAME)]
            lpmi = MONITORINFOEX()
            lpmi.cbSize = ctypes.sizeof(MONITORINFOEX)
            self._user32.GetMonitorInfoW(hMonitor, ctypes.byref(lpmi))
            #hdc = self._gdi32.CreateDCA(ctypes.c_char_p(lpmi.szDevice), 0, 0, 0)
            monitors.append({
                "hmon": hMonitor,
                #"hdc":  hdc,
                "rect": (lprcMonitor.contents.left,
                         lprcMonitor.contents.top,
                         lprcMonitor.contents.right,
                         lprcMonitor.contents.bottom),
                "name": lpmi.szDevice
                })
            return True
        MonitorEnumProc = ctypes.WINFUNCTYPE(
            ctypes.c_bool,
            ctypes.c_ulong,
            ctypes.c_ulong,
            ctypes.POINTER(ctypes.wintypes.RECT),
            ctypes.c_int)
        callback = MonitorEnumProc(_MonitorEnumProcCallback)
        if self._user32.EnumDisplayMonitors(0, 0, callback, 0) == 0:
            raise WindowsError("Unable to enumerate monitors")
        # Clever magic to make the screen with origin of (0,0) [the primary monitor]
        # the first in the list
        # Sort by device ID - 0 is primary, 1 is next, etc.
        monitors.sort(key=lambda x: (not (x["rect"][0] == 0 and x["rect"][1] == 0), x["name"]))

        return monitors
1121234
def _get_certificate_obj(cert):
    '''
    
    '''
    if isinstance(cert, M2Crypto.X509.X509):
        return cert

    text = _text_or_file(cert)
    text = get_pem_entry(text, pem_type='CERTIFICATE')
    return M2Crypto.X509.load_cert_string(text)
979278
def cli(env, identifier, passwords, price):
    """"""

    hardware = SoftLayer.HardwareManager(env.client)

    table = formatting.KeyValueTable(['name', 'value'])
    table.align['name'] = 'r'
    table.align['value'] = 'l'

    hardware_id = helpers.resolve_id(hardware.resolve_ids, identifier, 'hardware')
    result = hardware.get_hardware(hardware_id)
    result = utils.NestedDict(result)

    operating_system = utils.lookup(result, 'operatingSystem', 'softwareLicense', 'softwareDescription') or {}
    memory = formatting.gb(result.get('memoryCapacity', 0))
    owner = None
    if utils.lookup(result, 'billingItem') != []:
        owner = utils.lookup(result, 'billingItem', 'orderItem', 'order', 'userRecord', 'username')

    table.add_row(['id', result['id']])
    table.add_row(['guid', result['globalIdentifier'] or formatting.blank()])
    table.add_row(['hostname', result['hostname']])
    table.add_row(['domain', result['domain']])
    table.add_row(['fqdn', result['fullyQualifiedDomainName']])
    table.add_row(['status', result['hardwareStatus']['status']])
    table.add_row(['datacenter', result['datacenter']['name'] or formatting.blank()])
    table.add_row(['cores', result['processorPhysicalCoreAmount']])
    table.add_row(['memory', memory])
    table.add_row(['public_ip', result['primaryIpAddress'] or formatting.blank()])
    table.add_row(['private_ip', result['primaryBackendIpAddress'] or formatting.blank()])
    table.add_row(['ipmi_ip', result['networkManagementIpAddress'] or formatting.blank()])
    table.add_row(['os', operating_system.get('name') or formatting.blank()])
    table.add_row(['os_version', operating_system.get('version') or formatting.blank()])
    table.add_row(['created', result['provisionDate'] or formatting.blank()])
    table.add_row(['owner', owner or formatting.blank()])

    vlan_table = formatting.Table(['type', 'number', 'id'])
    for vlan in result['networkVlans']:
        vlan_table.add_row([vlan['networkSpace'], vlan['vlanNumber'], vlan['id']])

    table.add_row(['vlans', vlan_table])

    if result.get('notes'):
        table.add_row(['notes', result['notes']])

    if price:
        total_price = utils.lookup(result, 'billingItem', 'nextInvoiceTotalRecurringAmount') or 0

        price_table = formatting.Table(['Item', 'Recurring Price'])
        price_table.add_row(['Total', total_price])

        for item in utils.lookup(result, 'billingItem', 'children') or []:
            price_table.add_row([item['description'], item['nextInvoiceTotalRecurringAmount']])

        table.add_row(['prices', price_table])

    if passwords:
        pass_table = formatting.Table(['username', 'password'])
        for item in result['operatingSystem']['passwords']:
            pass_table.add_row([item['username'], item['password']])
        table.add_row(['users', pass_table])

        pass_table = formatting.Table(['ipmi_username', 'password'])
        for item in result['remoteManagementAccounts']:
            pass_table.add_row([item['username'], item['password']])
        table.add_row(['remote users', pass_table])

    table.add_row(['tags', formatting.tags(result['tagReferences'])])

    env.fout(table)
917
def GetWindowsInfo(self):
        '''
        '''
        result, ui = chmlib.chm_resolve_object(self.file, '/#WINDOWS')
        if (result != chmlib.CHM_RESOLVE_SUCCESS):
            return -1

        size, text = chmlib.chm_retrieve_object(self.file, ui, 0l, 8)
        if (size < 8):
            return -2

        buff = array.array('B', text)
        num_entries = self.GetDWORD(buff, 0)
        entry_size = self.GetDWORD(buff, 4)

        if num_entries < 1:
            return -3

        size, text = chmlib.chm_retrieve_object(self.file, ui, 8l, entry_size)
        if (size < entry_size):
            return -4

        buff = array.array('B', text)
        toc_index = self.GetDWORD(buff, 0x60)
        idx_index = self.GetDWORD(buff, 0x64)
        dft_index = self.GetDWORD(buff, 0x68)

        result, ui = chmlib.chm_resolve_object(self.file, '/#STRINGS')
        if (result != chmlib.CHM_RESOLVE_SUCCESS):
            return -5

        size, text = chmlib.chm_retrieve_object(self.file, ui, 0l, ui.length)
        if (size == 0):
            return -6

        if (not self.topics):
            self.topics = self.GetString(text, toc_index)
            if not self.topics.startswith("/"):
                self.topics = "/" + self.topics

        if (not self.index):
            self.index = self.GetString(text, idx_index)
            if not self.index.startswith("/"):
                self.index = "/" + self.index

        if (dft_index != 0):
            self.home = self.GetString(text, dft_index)
            if not self.home.startswith("/"):
                self.home = "/" + self.home
840723
def get_section_data(self, name):
        """"""
        logging.debug(_('Obtaining PE section: %s'), name)
        for section in self.binary.sections:
            if section.Name.rstrip(b'\x00') == name:
                return section.get_data()
        return b''