Best Python code snippet using autotest_python
hardware.py
Source:hardware.py  
...54        try:55            cmd = ['cat', '/proc/cpuinfo']56            process = subprocess.Popen(cmd, stdout=subprocess.PIPE)57            self._raw_output, _stderr = process.communicate()58            self._parse_output()59            self._load_data()60        except Exception as e:61            logger.error("Error reading cpu info.")62            logger.exception(e)63            self._cpus = {}  # Something went wrong, set to empty dict.64    def _load_data(self):65        self._physical_ids = {}66        self._cpus = {}67        for logical_cpu in self._logical_cpu_list:68            _id = logical_cpu["physical_id"]69            name = logical_cpu["name"]70            self._physical_ids[_id] = name71        self._number_of_cpus = len(self._physical_ids)72        for i in range(self._number_of_cpus):73            for logical_cpu in self._logical_cpu_list:74                p_id = logical_cpu["physical_id"]75                if p_id in self._cpus:76                    continue77                logical_dict = self._create_physical_dict(78                    str(i),79                    logical_cpu["name"],80                    logical_cpu["cores"],81                    logical_cpu["speed_mhz"],82                    logical_cpu["cache_kb"],83                    logical_cpu["bit_type"]84                )85                self._cpus[p_id] = logical_dict.copy()86    def _parse_output(self):87        self._cat_output = []88        for s in self._raw_output.splitlines():89            self._cat_output.append(s.replace("\t", ''))90        self._logical_cpu_list = []91        # Setting the physical id to zero in the event that there is92        # only one physical CPU. /proc/cpuinfo doesn't display 'physical id'93        # and 'core id' if there is only one.94        self._cpu_dict = {}95        self._cpu_dict["physical_id"] = '0'96        self._cpu_dict["cores"] = '0'97        for entry in self._cat_output:98            if entry.find('processor: ') == 0:99                logical_id = entry.partition(":")[2].strip()100                self._cpu_dict["processor"] = logical_id101                continue102            elif entry.find('physical id:') == 0:103                physical_id = entry.partition(":")[2].strip()104                self._cpu_dict["physical_id"] = physical_id105                continue106            elif entry.find('core id:') == 0:107                core_id = entry.partition(":")[2].strip()108                self._cpu_dict["core_id"] = core_id109                continue110            elif entry.find('cpu cores:') == 0:111                cores = entry.partition(":")[2].strip()112                self._cpu_dict["cores"] = cores113                continue114            elif entry.find('model name:') == 0:115                model_name = entry.partition(":")[2].strip()116                self._cpu_dict["name"] = model_name117                continue118            elif entry.find('cpu MHz:') == 0:119                speed = entry.partition(":")[2].strip()120                self._cpu_dict["speed_mhz"] = speed121                continue122            elif entry.find('cache size:') == 0:123                size = entry.partition(":")[2].strip()124                size_kb = settings.EmptyValue125                if "KB".lower() in size.lower():126                    # Some logic here!!127                    size_kb = size.lower().replace("KB".lower(), "").strip()128                self._cpu_dict["cache_kb"] = size_kb129                continue130            # 'flags' show a lot of options on one line separated by a space.131            elif entry.find('flags:') == 0:132                # lm is the flag set by linux to indicate 64bit133                # X86_FEATURE_LM (long mode)134                if " lm " in entry:135                    self._cpu_dict["bit_type"] = '64'136                else:137                    self._cpu_dict["bit_type"] = '32'138                continue139            # Empty line means the beginning of a new processor item. Save.140            elif entry == "":141                self._logical_cpu_list.append(self._cpu_dict.copy())142        # just some clean up.143        self._cpu_dict = None144    def _create_physical_dict(self, _id, name='', cores='', speed_mhz='',145                              cache_kb='', bit_type=''):146        logical_dict = {147            "cpu_id": _id,148            "name": name,149            "cores": cores,150            "speed_mhz": speed_mhz,151            "cache_kb": cache_kb,152            "bit_type": bit_type153        }154        return logical_dict155    def get_cpu_list(self):156        cpu_list = []157        for cpu in self._cpus:158            cpu_list.append(self._cpus[cpu])159        return cpu_list160class DisplayInfo():161    """Retrieve information about a computers display."""162    def _get_pci_device_info(self):163        """Retrieves all PCI device info from the lscpi command.164        Returns:165           str: Raw output from the 'lspci -v' command through subprocess.166        """167        cmd = ['lspci', '-v']168        process = subprocess.Popen(cmd, stdout=subprocess.PIPE)169        raw_output, _ = process.communicate()170        return raw_output171    def _parse_output(self, raw_output):172        """Parses output for 'VGA compatible controller' entry.173        Args:174            raw_output (str): Output in the format of what you get from175                'lspci -v'.176        Returns:177            Dictionary with 3 keys:178                name (str)179                speed_mhz (int)180                ram_kb (int)181            Example:182                {183                    'name': 'Parallels, Inc. Accelerated Virtual Video Adapter (prog-if 00 [VGA controller])',184                    'speed_mhz': 66,185                    'ram_kb': 32768186                }187        """188        tmp_list = []189        for s in raw_output.splitlines():190            tmp_list.append(s.replace("\t", ''))191        output = tmp_list192        display_dict = None193        display_list = []194        reading_vga = False195        for entry in output:196            if 'VGA compatible controller:' in entry:197                name = entry.partition('VGA compatible controller:')[2].strip()198                display_dict = {'name': name}199                reading_vga = True200                continue201            elif 'Flags:' in entry and reading_vga:202                flags = entry.partition(':')[2].strip()203                match = re.match(r'[0-9]+MHz', flags)204                speed_mhz = 0205                if match:206                    speed_mhz = int(match.group().split('MHz')[0])207                # TODO: string or int?208                display_dict['speed_mhz'] = speed_mhz209                continue210            elif 'Memory at' in entry and \211                 'prefetchable' in entry and \212                 reading_vga:213                size_string = entry.split("[size=")[1].replace(']', '')214                size_kb = 0215                # KB216                if 'K' in size_string:217                    size_kb = int(size_string.replace('K', ''))218                # MB219                elif 'M' in size_string:220                    size = int(size_string.replace('M', ''))221                    size_kb = size * 1024222                # GB223                elif 'G' in size_string:224                    size = int(size_string.replace('G', ''))225                    size_kb = (size * 1024) * 1024226                display_dict['ram_kb'] = \227                    display_dict.get('ram_kb', 0) + size_kb228                continue229            # Empty line means the beginning of a new processor item. Save.230            elif entry == "" and reading_vga:231                display_list.append(display_dict.copy())232                reading_vga = False233        return display_list234    def get_display_list(self):235        """Retrieves data corresponding to the computers display.236        Returns:237            Dictionary with 3 keys:238                name (str)239                speed_mhz (int)240                ram_kb (int)241            Example:242                {243                    'name': 'Parallels, Inc. Accelerated Virtual Video Adapter (prog-if 00 [VGA controller])',244                    'speed_mhz': 66,245                    'ram_kb': 32768246                }247            """248        raw_output = self._get_pci_device_info()249        try:250            display_list = self._parse_output(raw_output)251        except Exception:252            display_list = []253        return display_list254class HarddriveInfo():255    def __init__(self):256        self._hdd_list = []257        try:258            # df options:259            # 'h': print sizes in human readable format ('k' = KB)260            # 'l': local file systems. 'T': file system type (ext3/ext4/db)261            cmd = ['df', '-hklT']262            process = subprocess.Popen(cmd, stdout=subprocess.PIPE)263            self._raw_output, _stderr = process.communicate()264            self._parse_output()265        except Exception as e:266            logger.error("Error reading hard drive info.", 'error')267            logger.exception(e)268            self._hdd_list = []  # Something went wrong, set to empty list.269    def _parse_output(self):270        self._output = []271        for line in self._raw_output.splitlines():272            self._output.append([x for x in line.split(' ') if x != ''])273        _partition_blacklist = [274            'tmpfs',275            'rootfs',276            'none',277            'devtmpfs',278            'Filesystem'279        ]280        tmp_dict = {}281        for entry in self._output:282            if entry[0] in _partition_blacklist:283                continue284            # An ideal entry would consist of 7 items. It would look like:285            # ['/dev/sda1', 'ext4', '495844', '38218', '432026', '9%', '/boot']286            if len(entry) == 7:287                tmp_dict['name'] = entry[0]288                tmp_dict['size_kb'] = int(entry[3]) + int(entry[4])289                tmp_dict['free_size_kb'] = entry[4]290                tmp_dict['file_system'] = entry[1]291            else:292                # But less then 7 items means the name of the partition and its293                # data were split across two entries:294                # ['/dev/mapper/vg_centosmon-lv_root'],295                # ['ext4', '12004544', '3085772', '8796828', '26%', '/']296                # Taking that into consideration here.297                if len(entry) == 1:298                    tmp_dict['name'] = entry[0]299                    continue300                elif len(entry) == 6:301                    tmp_dict['size_kb'] = int(entry[2]) + int(entry[3])302                    tmp_dict['free_size_kb'] = entry[3]303                    tmp_dict['file_system'] = entry[0]304            self._hdd_list.append(tmp_dict.copy())305    def get_hdd_list(self):306        # return non-empty dictionaries307        return [info_dict for info_dict in self._hdd_list if info_dict]308class NicInfo():309    def __init__(self):310        self._nics = []311        try:312            cmd = ['ip', 'addr']313            process = subprocess.Popen(cmd, stdout=subprocess.PIPE)314            self._raw_output, _stderr = process.communicate()315            self._parse_output()316        except Exception as e:317            logger.error("Error reading nic info.", 'error')318            logger.exception(e)319            self._nics = []  # Something went wrong, set to empty dict.320    def _parse_output(self):321        self._output = [line.strip() for line in self._raw_output.splitlines()]322        #### Inserting a '\n' between interfaces. Easier to parse...323        indices = []324        for i in range(len(self._output)):325            match = re.match(r'[0-9]+:', self._output[i])326            if match:327                if i > 1:328                    indices.append(i)329        for i in indices:330            self._output.insert(i, '')331        self._output.insert(len(self._output), '')332        #######################################################333        reading_flag = False334        temp_dict = {}...nash.py
Source:nash.py  
...52            capture_output=True53        )54        p.check_returncode()55        return p.stdout56    def _parse_output(self, output: str, game, rational, extensive=False):57        profiles = []58        for line in output.splitlines():59            entries = line.strip().split(",")60            if entries[0] != "NE":61                continue62            if extensive:63                profile = game.mixed_behavior_profile(rational=rational)64            else:65                profile = game.mixed_strategy_profile(rational=rational)66            for (i, p) in enumerate(entries[1:]):67                if rational:68                    profile[i] = Fraction(p)69                else:70                    profile[i] = float(p)71            profiles.append(NashSolution(profile))72        return profiles73class ExternalEnumPureSolver(ExternalSolver):74    """75    Algorithm class to manage calls to external gambit-enumpure solver76    for computing pure-strategy equilibria.77    """78    def solve(self, game, use_strategic=False):79        if not game.is_perfect_recall:80            raise RuntimeError(81                "Computing equilibria of games with imperfect recall "82                "is not supported."83            )84        command_line = "gambit-enumpure"85        if use_strategic and game.is_tree:86            command_line += " -S"87        return self._parse_output(self._call(command_line, game),88                                  game, rational=True,89                                  extensive=game.is_tree and not use_strategic)90class ExternalLPSolver(ExternalSolver):91    """92    Algorithm class to manage calls to external gambit-lp solver93    for computing equilibria in two-player games using linear programming.94    """95    def solve(self, game, rational=False, use_strategic=False):96        if len(game.players) != 2:97            raise RuntimeError("Method only valid for two-player games.")98        if not game.is_const_sum:99            raise RuntimeError("Method only valid for constant-sum games.")100        if not game.is_perfect_recall:101            raise RuntimeError(102                "Computing equilibria of games with imperfect recall "103                "is not supported."104            )105        if rational:106            command_line = "gambit-lp"107        else:108            command_line = "gambit-lp -d 10"109        if use_strategic and game.is_tree:110            command_line += " -S"111        return self._parse_output(self._call(command_line, game),112                                  game, rational,113                                  extensive=game.is_tree and not use_strategic)114class ExternalLCPSolver(ExternalSolver):115    """116    Algorithm class to manage calls to external gambit-lcp solver117    for computing equilibria in two-player games using linear complementarity118    programming.119    """120    def solve(self, game, rational=False, use_strategic=False):121        if len(game.players) != 2:122            raise RuntimeError("Method only valid for two-player games.")123        if not game.is_perfect_recall:124            raise RuntimeError(125                "Computing equilibria of games with imperfect recall "126                "is not supported."127            )128        if rational:129            command_line = "gambit-lcp"130        else:131            command_line = "gambit-lcp -d 10"132        if use_strategic and game.is_tree:133            command_line += " -S"134        return self._parse_output(self._call(command_line, game),135                                  game, rational,136                                  extensive=game.is_tree and not use_strategic)137class ExternalEnumMixedSolver(ExternalSolver):138    """139    Algorithm class to manage calls to external gambit-enummixed solver140    for computing equilibria in two-player games using enumeration of141    extreme points.142    """143    def solve(self, game, rational=False):144        if not game.is_perfect_recall:145            raise RuntimeError(146                "Computing equilibria of games with imperfect recall "147                "is not supported."148            )149        if rational:150            command_line = "gambit-enummixed"151        else:152            command_line = "gambit-enummixed -d 10"153        return self._parse_output(self._call(command_line, game),154                                  game, rational)155class ExternalSimpdivSolver(ExternalSolver):156    """157    Algorithm class to manage calls to external gambit-simpdiv solver158    for computing equilibria in N-player games using simpicial subdivision.159    """160    def solve(self, game):161        if not game.is_perfect_recall:162            raise RuntimeError(163                "Computing equilibria of games with imperfect recall "164                "is not supported."165            )166        command_line = "gambit-simpdiv"167        return self._parse_output(self._call(command_line, game),168                                  game, rational=True)169class ExternalGlobalNewtonSolver(ExternalSolver):170    """171    Algorithm class to manage calls to external gambit-gnm solver172    for computing equilibria in N-player games using the global Newton method.173    """174    def solve(self, game):175        if not game.is_perfect_recall:176            raise RuntimeError(177                "Computing equilibria of games with imperfect recall "178                "is not supported."179            )180        command_line = "gambit-gnm -d 10"181        return self._parse_output(self._call(command_line, game),182                                  game, rational=False)183class ExternalEnumPolySolver(ExternalSolver):184    """185    Algorithm class to manage calls to external gambit-enumpoly solver186    for computing equilibria in N-player games systems of polynomial equations.187    """188    def solve(self, game, use_strategic=False):189        if not game.is_perfect_recall:190            raise RuntimeError(191                "Computing equilibria of games with imperfect recall "192                "is not supported."193            )194        command_line = "gambit-enumpoly -d 10"195        if use_strategic and game.is_tree:196            command_line += " -S"197        return self._parse_output(self._call(command_line, game),198                                  game, rational=False,199                                  extensive=game.is_tree and not use_strategic)200class ExternalLyapunovSolver(ExternalSolver):201    """202    Algorithm class to manage calls to external gambit-liap solver203    for computing equilibria in N-player games using Lyapunov function204    minimization.205    """206    def solve(self, game, use_strategic=False):207        if not game.is_perfect_recall:208            raise RuntimeError(209                "Computing equilibria of games with imperfect recall "210                "is not supported."211            )212        command_line = "gambit-liap -d 10"213        if use_strategic and game.is_tree:214            command_line += " -S"215        return self._parse_output(self._call(command_line, game),216                                  game, rational=False,217                                  extensive=game.is_tree and not use_strategic)218class ExternalIteratedPolymatrixSolver(ExternalSolver):219    """220    Algorithm class to manage calls to external gambit-ipa solver221    for computing equilibria in N-player games using iterated222    polymatrix approximation.223    """224    def solve(self, game):225        if not game.is_perfect_recall:226            raise RuntimeError(227                "Computing equilibria of games with imperfect recall "228                "is not supported."229            )230        command_line = "gambit-ipa -d 10"231        return self._parse_output(self._call(command_line, game),232                                  game, rational=False)233class ExternalLogitSolver(ExternalSolver):234    """235    Algorithm class to manage calls to external gambit-logit solver236    for computing equilibria in N-player games using quantal response237    equilibrium.238    """239    def solve(self, game, use_strategic=False):240        if not game.is_perfect_recall:241            raise RuntimeError(242                "Computing equilibria of games with imperfect recall "243                "is not supported."244            )245        command_line = "gambit-logit -d 20 -e"246        if use_strategic and game.is_tree:247            command_line += " -S"248        return self._parse_output(self._call(command_line, game),249                                  game, rational=False,250                                  extensive=game.is_tree and not use_strategic)251def enumpure_solve(game, use_strategic=True, external=False):252    """Convenience function to solve game to find pure-strategy Nash equilibria.253    """254    if external:255        return ExternalEnumPureSolver().solve(game, use_strategic=True)256    if not game.is_tree or use_strategic:257        alg = pygambit.lib.libgambit.EnumPureStrategySolver()258    else:259        alg = pygambit.lib.libgambit.EnumPureAgentSolver()260    return alg.solve(game)261def enummixed_solve(game, rational=True, external=False, use_lrs=False):262    """Convenience function to solve two-player game to find all...magic.py
Source:magic.py  
...37        if hasattr(self, 'cookie') and libmagic:38            self.close()39magic_none = Magic(mime=False)40magic_mime = Magic(mime=True)41def _parse_output(output):42    if output is None:43        return None44    return output.split(';')[0]45def check_magic_file(mime, magic_file=None):46    if mime:47        return _parse_output(magic_mime.from_file(magic_file))48    else:49        return magic_none.from_file(magic_file)50def check_magic_buffer(mime, buf=None):51    if mime:52        return _parse_output(magic_mime.from_buffer(buf))53    else:...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
