Read entropy from YubiHSM and feed it to Linux as entropy using ioctl() syscall.
547234
def get_entropy(hsm, iterations, entropy_ratio):
    
    fd = os.open("/dev/random", os.O_WRONLY)
    # struct rand_pool_info {
    #    int     entropy_count;
    #    int     buf_size;
    #    __u32   buf[0];
    # };
    fmt = 'ii%is' % (pyhsm.defines.YSM_MAX_PKT_SIZE - 1)
    for _ in xrange(iterations):
        rnd = hsm.random(pyhsm.defines.YSM_MAX_PKT_SIZE - 1)
        this = struct.pack(fmt, entropy_ratio * len(rnd), len(rnd), rnd)
        fcntl.ioctl(fd, RNDADDENTROPY, this)
    os.close(fd)
480750
def _get_cpu(self):
        '''
        
        '''
        # CPU data in grains is OK-ish, but lscpu is still better in this case
        out = __salt__['cmd.run_all']("lscpu")
        salt.utils.fsutils._verify_run(out)
        data = dict()
        for descr, value in [elm.split(":", 1) for elm in out['stdout'].split(os.linesep)]:
            data[descr.strip()] = value.strip()

        return data
681222
def _raw_pack(key_handle, flags, data):
    
    # #define YHSM_HMAC_RESET          0x01    // Flag to indicate reset at first packet
    # #define YHSM_HMAC_FINAL          0x02    // Flag to indicate that the hash shall be calculated
    # typedef struct {
    #   uint32_t keyHandle;                 // Key handle
    #   uint8_t flags;                      // Flags
    #   uint8_t numBytes;                   // Number of bytes in data packet
    #   uint8_t data[YHSM_MAX_PKT_SIZE - 6]; // Data to be written
    # } YHSM_HMAC_SHA1_GENERATE_REQ;
    return struct.pack('<IBB', key_handle, flags, len(data)) + data
71264
def entropy_H(self, data):
        """"""
        
        if len(data) == 0:
            return 0.0
        
        occurences = array.array('L', [0]*256)
        
        for x in data:
            occurences[ord(x)] += 1
        
        entropy = 0
        for x in occurences:
            if x:
                p_x = float(x) / len(data)
                entropy -= p_x*math.log(p_x, 2)
        
        return entropy
1289302
def generate_entropy(strength, internal_entropy, external_entropy):
    '''
    
    '''
    if strength not in (128, 192, 256):
        raise Exception("Invalid strength")

    if not internal_entropy:
        raise Exception("Internal entropy is not provided")

    if len(internal_entropy) < 32:
        raise Exception("Internal entropy too short")

    if not external_entropy:
        raise Exception("External entropy is not provided")

    if len(external_entropy) < 32:
        raise Exception("External entropy too short")

    entropy = hashlib.sha256(internal_entropy + external_entropy).digest()
    entropy_stripped = entropy[:strength // 8]

    if len(entropy_stripped) * 8 != strength:
        raise Exception("Entropy length mismatch")

    return entropy_stripped
162483
def get_free_memory_linux():
    
    try:
        p = Popen('free -m', shell=True, stdout=PIPE, encoding='utf8')
        stdout_string = p.communicate()[0].split('\n')[2]
    except OSError:
        raise OSError
    stdout_list = stdout_string.split(' ')
    stdout_list = [x for x in stdout_list if x != '']
    return int(stdout_list[3])
607746
def shannon(self, data):
        '''
        
        '''
        entropy = 0

        if data:
            length = len(data)

            seen = dict(((chr(x), 0) for x in range(0, 256)))
            for byte in data:
                seen[byte] += 1

            for x in range(0, 256):
                p_x = float(seen[chr(x)]) / length
                if p_x > 0:
                    entropy -= p_x * math.log(p_x, 2)

        return (entropy / 8)
1308049
def sysinfo2magic(version_info=sys.version_info):
    

    # FIXME: DRY with sysinfo2float()
    vers_str = '.'.join([str(v) for v in version_info[0:3]])
    if version_info[3] != 'final':
        vers_str += ''.join([str(v) for v in version_info[3:]])

    if IS_PYPY:
        vers_str += 'pypy'
    else:
        try:
            import platform
            platform = platform.python_implementation()
            if platform in ('Jython', 'Pyston'):
                vers_str += platform
                pass
        except ImportError:
            # Python may be too old, e.g. < 2.6 or implementation may
            # just not have platform
            pass

    return magics[vers_str]
425810
def entropy(data):
    

    if len(data) == 0:
        return None

    n = sum(data)

    _op = lambda f: f * math.log(f)
    return - sum(_op(float(i) / n) for i in data)
50566
def spectral_entropy(data, numOfShortBlocks=10):
    """"""
    data = np.mean(data, axis=1)

    nFFT = len(data) // 2
    X = FFT(data, nFFT)
    L = len(X)                         # number of frame data
    Eol = np.sum(X ** 2)            # total spectral energy

    subWinLength = int(np.floor(L / numOfShortBlocks))   # length of sub-frame
    if L != subWinLength * numOfShortBlocks:
        X = X[0:subWinLength * numOfShortBlocks]

    # define sub-frames (using matrix reshape)
    subWindows = X.reshape(subWinLength, numOfShortBlocks, order='F').copy()

    # compute spectral sub-energies
    s = np.sum(subWindows ** 2, axis=0) / (Eol + EPSILON)

    # compute spectral entropy
    return -np.sum(s * np.log2(s + EPSILON))
773443
def _linux_memdata():
    '''
    
    '''
    grains = {'mem_total': 0, 'swap_total': 0}

    meminfo = '/proc/meminfo'
    if os.path.isfile(meminfo):
        with salt.utils.files.fopen(meminfo, 'r') as ifile:
            for line in ifile:
                comps = line.rstrip('\n').split(':')
                if not len(comps) > 1:
                    continue
                if comps[0].strip() == 'MemTotal':
                    # Use floor division to force output to be an integer
                    grains['mem_total'] = int(comps[1].split()[0]) // 1024
                if comps[0].strip() == 'SwapTotal':
                    # Use floor division to force output to be an integer
                    grains['swap_total'] = int(comps[1].split()[0]) // 1024
    return grains
823904
def _parse_sid_iter(data):
    """"""
    limit = len(data)
    buf = BytesIO(data)
    while buf.tell() < limit:
        sid = _parse_var_int(buf, signed=False)
        yield SymbolToken(None, sid)
1310363
def _ioctl (self, func, args):
        """"""
        import fcntl
        return fcntl.ioctl(self.sockfd.fileno(), func, args)
234179
def _osx_memdata():
    '''
    
    '''
    grains = {'mem_total': 0, 'swap_total': 0}

    sysctl = salt.utils.path.which('sysctl')
    if sysctl:
        mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl))
        swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.')
        if swap_total.endswith('K'):
            _power = 2**10
        elif swap_total.endswith('M'):
            _power = 2**20
        elif swap_total.endswith('G'):
            _power = 2**30
        swap_total = float(swap_total[:-1]) * _power

        grains['mem_total'] = int(mem) // 1024 // 1024
        grains['swap_total'] = int(swap_total) // 1024 // 1024
    return grains
115928
def image_entropy(im):
    
    if not isinstance(im, Image.Image):
        # Can only deal with PIL images. Fall back to a constant entropy.
        return 0
    hist = im.histogram()
    hist_size = float(sum(hist))
    hist = [h / hist_size for h in hist]
    return -sum([p * math.log(p, 2) for p in hist if p != 0])
477648
private static String fromSystemPropOrEnv(String prop) {
		String resolvedProp = System.getProperty(prop);
		if (StringUtils.hasText(resolvedProp)) {
			return resolvedProp;
		}
		return System.getenv(prop);
	}
132572
def read_iter(use_fpi):
    '''
    '''
    filename_rhosuffix = 'exe/inv.lastmod_rho'
    filename = 'exe/inv.lastmod'
    # filename HAS to exist. Otherwise the inversion was not finished
    if(not os.path.isfile(filename)):
        print('Inversion was not finished! No last iteration found.')

    if(use_fpi is True):
        if(os.path.isfile(filename_rhosuffix)):
            filename = filename_rhosuffix

    linestring = open(filename, 'r').readline().strip()
    linestring = linestring.replace('\n', '')
    linestring = linestring.replace('../', '')
    return linestring