Best Python code snippet using Testify_python
game.py
Source:game.py  
...22HAND_RELEASED = 723CONCENTRATION_ENDS = 824VOTED_FOR_SHURIKEN = 925SHURIKEN_THROWN = 1026def throw_warning(text):27    print("WARNING: " + text)28class Game:29    # initialized on init30    # initialized on start31    # initialized on compilation32    rewards = [0, 2, 1, 0, 2, 1, 0, 2, 1, 0, 0, 0]33    def __init__(self, game_id):34        self.game_id = game_id35        self.n_levels = None36        self.hp = None37        self.n_players = 038        self.player_hands = dict()39        self.player_status = dict()40        self.level = 041        self.status = 042        self.n_shurikens = 143        self.top_card = 044    # add a player to the unstarted game session45    def add_player(self, player_id):46        response = PLAYER_ADDED47        if self.status == NOT_STARTED:48            if player_id in self.player_hands.keys():49                response = WARNING50                throw_warning(51                    "The player has been already added to the game. "52                    "This call is ignored."53                )54            else:55                self.player_hands[player_id] = list()56                self.player_status[player_id] = NORMAL57                self.n_players += 158        else:59            response = WARNING60            throw_warning(61                "A player was added after the game was started. "62                "This player will not take part in this game."63            )64        return self.__get_status(response)65    def start_game(self):66        response = GAME_STARTED67        if self.status == NOT_STARTED:68            if self.n_players == 2:69                self.n_levels = 1270                self.hp = 271            elif self.n_players == 3:72                self.n_levels = 1073                self.hp = 374            elif self.n_players == 4:75                self.n_levels = 876                self.hp = 477            else:78                response = WARNING79                throw_warning(80                    "n_levels should be either 2, 3, or 4. "81                    "This call is ignored."82                )83            if response != WARNING:84                self.status = FREE_CHAT85        else:86            response = WARNING87            throw_warning(88                "It was tried to start the game when "89                "it had already been started. "90                "This call is ignored."91            )92        return self.__get_status(response)93    # proceed to the next level94    def start_level(self):95        response = LEVEL_STARTED96        if self.status == FREE_CHAT:97            self.level += 198            self.status = ACTION99            self.__pass_cards(self.level)100            # everyone places their hand on the table101            for player_id in self.player_status.keys():102                self.place_hand(player_id)103        else:104            response = WARNING105            throw_warning(106                "It was tried to start a level when"107                "other level is not finished. "108                "This call is ignored."109            )110        return self.__get_status(response)111    # place a card to the stack112    def act(self, player_id):113        response = CARD_PLAYED114        discarded = {player_id: list()115                     for player_id in self.player_status.keys()}116        if (117            self.status == ACTION118            and player_id in self.player_hands.keys()119            and self.player_hands[player_id]120        ):121            card = min(self.player_hands[player_id])122            self.player_hands[player_id].remove(card)123            self.top_card = card124            flag = False125            for player_id in self.player_hands.keys():126                new_hand = list(127                    dropwhile(lambda x: x < card, self.player_hands[player_id])128                )129                if new_hand != self.player_hands[player_id]:130                    flag = True131                    discarded[player_id] = [132                        item133                        for item in self.player_hands[player_id]134                        if item not in new_hand135                    ]136                    self.player_hands[player_id] = new_hand137            if flag:138                self.hp -= 1139                if self.hp < 0:140                    self.status = LOSE141            if sum(map(sum, self.player_hands.values())) == 0 and self.hp >= 0:142                self.__finish_level()143        else:144            response = WARNING145            throw_warning(146                "Something went wrong when playing a card. "147                "This call is ignored."148            )149        return self.__get_status(response, discarded=discarded)150    def place_hand(self, player_id):151        "Places down all players' hands "152        "(this behavior may be changed in future)"153        response = HAND_PLACED154        if (155            self.status in [CONCENTRATION, ACTION]156            and player_id in self.player_hands.keys()157        ):158            for item in self.player_status:159                self.player_status[item] = STOP160            # self.player_status[player_id] = STOP161            if self.status != CONCENTRATION:162                response = CONCENTRATION_BEGINS163            self.status = CONCENTRATION164        else:165            response = WARNING166            throw_warning(167                "Hand was placed during wrong game phase. "168                "This call is ignored."169            )170        return self.__get_status(response)171    # change hand state to NORMAL172    # called when unvoting for shuriken or being ready to end concentration173    def release_hand(self, player_id):174        response = HAND_RELEASED175        if (176            player_id in self.player_hands.keys()177            and self.player_status[player_id] == STOP178        ):179            self.player_status[player_id] = NORMAL180            if STOP not in self.player_status.values():181                self.status = ACTION182                response = CONCENTRATION_ENDS183        elif (184            player_id in self.player_hands.keys()185            and self.player_status[player_id] == SHURIKEN186        ):187            self.player_status[player_id] = NORMAL188        else:189            response = WARNING190            throw_warning(191                "Player s hand had been already released. "192                "This call is ignored."193            )194        return self.__get_status(response)195    def vote_shuriken(self, player_id):196        response = VOTED_FOR_SHURIKEN197        discarded = {player_id: list()198                     for player_id in self.player_status.keys()}199        if (200            player_id in self.player_hands.keys()201            and self.status == ACTION202            and self.n_shurikens > 0203        ):204            self.player_status[player_id] = SHURIKEN205            if list(self.player_status.values()).count(SHURIKEN) == len(206                self.player_status.values()207            ):208                response = SHURIKEN_THROWN209                self.n_shurikens -= 1210                for player_id in self.player_hands.keys():211                    if self.player_hands[player_id]:212                        discarded[player_id] = [213                            min(self.player_hands[player_id])]214                        self.player_hands[player_id].remove(215                            min(self.player_hands[player_id])216                        )217                    self.player_status[player_id] = NORMAL218            if sum(map(sum, self.player_hands.values())) == 0:219                self.__finish_level()220        else:221            response = WARNING222            throw_warning(223                "Something went wrong during voting for shuriken. "224                "This call is ignored."225            )226        return self.__get_status(response, discarded=discarded)227    def load_status(self, status_dict):228        self.game_id = status_dict["game_id"]229        self.n_players = len(status_dict["player_hands"].keys())230        # calculate n_levels231        self.status = NOT_STARTED232        self.start_game()233        self.hp = status_dict["hp"]234        self.player_hands = status_dict["player_hands"]235        self.player_status = status_dict["player_status"]236        self.level = status_dict["level"]...utils.py
Source:utils.py  
1import csv2import time3import math4import numpy as np5import warnings6from rdkit import Chem7from rdkit import DataStructs8from h2o4gpu.model_selection import KFold, StratifiedKFold9def get_fp(smiles):10    fp = []11    processed_indices = []12    invalid_indices = []13    for i in range(len(smiles)):14        mol = smiles[i]15        tmp = np.array(mol2image(mol, n=2048))16        if np.isnan(tmp[0]):17            invalid_indices.append(i)18        else:19            fp.append(tmp)20            processed_indices.append(i)21    return np.array(fp), processed_indices, invalid_indices22def get_desc(smiles, calc):23    desc = []24    processed_indices = []25    invalid_indices = []26    for i in range(len(smiles)):27        sm = smiles[i]28        try:29            mol = Chem.MolFromSmiles(sm)30            tmp = np.array(calc(mol))31            desc.append(tmp)32            processed_indices.append(i)33        except:34            invalid_indices.append(i)35    desc_array = np.array(desc)36    return desc_array, processed_indices, invalid_indices37def normalize_desc(desc_array, desc_mean=None):38    desc_array = np.array(desc_array).reshape(len(desc_array), -1)39    ind = np.zeros(desc_array.shape)40    for i in range(desc_array.shape[0]):41        for j in range(desc_array.shape[1]):42            try:43                if np.isfinite(desc_array[i, j]):44                    ind[i, j] = 145            except:46                pass47    for i in range(desc_array.shape[0]):48        for j in range(desc_array.shape[1]):49            if ind[i, j] == 0:50                desc_array[i, j] = 051    if desc_mean is None:52        desc_mean = np.mean(desc_array, axis=0)53    for i in range(desc_array.shape[0]):54        for j in range(desc_array.shape[1]):55            if ind[i, j] == 0:56                desc_array[i, j] = desc_mean[j]57    return desc_array, desc_mean58def mol2image(x, n=2048):59    try:60        m = Chem.MolFromSmiles(x)61        fp = Chem.RDKFingerprint(m, maxPath=4, fpSize=n)62        res = np.zeros(len(fp))63        DataStructs.ConvertToNumpyArray(fp, res)64        return res65    except:66        return [np.nan]67def sanitize_smiles(smiles, canonical=True, throw_warning=False):68    """69    Takes list of SMILES strings and returns list of their sanitized versions.70    For definition of sanitized SMILES check71    http://www.rdkit.org/docs/api/rdkit.Chem.rdmolops-module.html#SanitizeMol72    Parameters73    ----------74    smiles: list75        list of SMILES strings76    canonical: bool (default True)77        parameter specifying whether SMILES will be converted to canonical78        format79    throw_warning: bool (default False)80        parameter specifying whether warnings will be thrown if a SMILES is81        invalid82    Returns83    -------84    new_smiles: list85        list of SMILES and NaNs if SMILES string is invalid or unsanitized.86        If canonical is True, returns list of canonical SMILES.87    When canonical is True this function is analogous to:88        canonical_smiles(smiles, sanitize=True).89    """90    new_smiles = []91    for sm in smiles:92        try:93            if canonical:94                new_smiles.append(Chem.MolToSmiles(Chem.MolFromSmiles(sm, sanitize=True)))95            else:96                new_smiles.append(sm)97        except:98            if throw_warning:99                warnings.warn('Unsanitized SMILES string: ' + sm, UserWarning)100            new_smiles.append('')101    return new_smiles102def canonical_smiles(smiles, sanitize=True, throw_warning=False):103    """104    Takes list of SMILES strings and returns list of their canonical SMILES.105    Parameters106    ----------107    smiles: list108        list of SMILES strings to convert into canonical format109    sanitize: bool (default True)110        parameter specifying whether to sanitize SMILES or not.111            For definition of sanitized SMILES check112            http://www.rdkit.org/docs/api/rdkit.Chem.rdmolops-module.html#SanitizeMol113    throw_warning: bool (default False)114        parameter specifying whether warnings will be thrown if a SMILES is115        invalid116    Returns117    -------118    new_smiles: list119        list of canonical SMILES and NaNs if SMILES string is invalid or120        unsanitized (when sanitize is True)121    When sanitize is True the function is analogous to:122        sanitize_smiles(smiles, canonical=True).123    """124    new_smiles = []125    for sm in smiles:126        try:127            mol = Chem.MolFromSmiles(sm, sanitize=sanitize)128            new_smiles.append(Chem.MolToSmiles(mol))129        except:130            if throw_warning:131                warnings.warn(sm + ' can not be canonized: invalid '132                                   'SMILES string!', UserWarning)133            new_smiles.append('')134    return new_smiles135def save_smi_to_file(filename, smiles, unique=True):136    """137    Takes path to file and list of SMILES strings and writes SMILES to the specified file.138        Args:139            filename (str): path to the file140            smiles (list): list of SMILES strings141            unique (bool): parameter specifying whether to write only unique copies or not.142        Output:143            success (bool): defines whether operation was successfully completed or not.144       """145    if unique:146        smiles = list(set(smiles))147    else:148        smiles = list(smiles)149    f = open(filename, 'w')150    for mol in smiles:151        f.writelines([mol, '\n'])152    f.close()153    return f.closed154def read_smi_file(filename, unique=True, add_start_end_tokens=False):155    """156    Reads SMILES from file. File must contain one SMILES string per line157    with \n token in the end of the line.158    Args:159        filename (str): path to the file160        unique (bool): return only unique SMILES161    Returns:162        smiles (list): list of SMILES strings from specified file.163        success (bool): defines whether operation was successfully completed or not.164    If 'unique=True' this list contains only unique copies.165    """166    f = open(filename, 'r')167    molecules = []168    for line in f:169        if add_start_end_tokens:170            molecules.append('<' + line[:-1] + '>')171        else:172            molecules.append(line[:-1])173    if unique:174        molecules = list(set(molecules))175    else:176        molecules = list(molecules)177    f.close()178    return molecules, f.closed179def tokenize(smiles, tokens=None):180    """181    Returns list of unique tokens, token-2-index dictionary and number of182    unique tokens from the list of SMILES183    Parameters184    ----------185        smiles: list186            list of SMILES strings to tokenize.187        tokens: list, str (default None)188            list of unique tokens189    Returns190    -------191        tokens: list192            list of unique tokens/SMILES alphabet.193        token2idx: dict194            dictionary mapping token to its index.195        num_tokens: int196            number of unique tokens.197    """198    if tokens is None:199        tokens = list(set(''.join(smiles)))200        tokens = list(np.sort(tokens))201        tokens = ''.join(tokens)202    token2idx = dict((token, i) for i, token in enumerate(tokens))203    num_tokens = len(tokens)204    return tokens, token2idx, num_tokens205def time_since(since):206    s = time.time() - since207    m = math.floor(s / 60)208    s -= m * 60209    return '%dm %ds' % (m, s)210def cross_validation_split(x, y, n_folds=5, split='random', folds=None):211    assert(len(x) == len(y))212    x = np.array(x)213    y = np.array(y)214    if split not in ['random', 'stratified', 'fixed']:215        raise ValueError('Invalid value for argument \'split\': '216                         'must be either \'random\', \'stratified\' '217                         'or \'fixed\'')218    if split == 'random':219        cv_split = KFold(n_splits=n_folds, shuffle=True)220        folds = list(cv_split.split(x, y))221    elif split == 'stratified':222        cv_split = StratifiedKFold(n_splits=n_folds, shuffle=True)223        folds = list(cv_split.split(x, y))224    elif split == 'fixed' and folds is None:225        raise TypeError(226            'Invalid type for argument \'folds\': found None, but must be list')227    cross_val_data = []228    cross_val_labels = []229    if len(folds) == n_folds:230        for fold in folds:231            cross_val_data.append(x[fold[1]])232            cross_val_labels.append(y[fold[1]])233    elif len(folds) == len(x) and np.max(folds) == n_folds:234        for f in range(n_folds):235            left = np.where(folds == f)[0].min()236            right = np.where(folds == f)[0].max()237            cross_val_data.append(x[left:right + 1])238            cross_val_labels.append(y[left:right + 1])239    return cross_val_data, cross_val_labels240def read_object_property_file(path, delimiter=',', cols_to_read=[0, 1],241                              keep_header=False):242    f = open(path, 'r')243    reader = csv.reader(f, delimiter=delimiter)244    data_full = np.array(list(reader))245    if keep_header:246        start_position = 0247    else:248        start_position = 1249    assert len(data_full) > start_position250    data = [[] for _ in range(len(cols_to_read))]251    for i in range(len(cols_to_read)):252        col = cols_to_read[i]253        data[i] = data_full[start_position:, col]254    f.close()255    if len(cols_to_read) == 1:256        data = data[0]...test_logger.py
Source:test_logger.py  
...9            "Filtered IamDataFrame is empty!",  # message10        )11    ]12def test_adjusting_logger_level(test_df, caplog):13    def throw_warning():14        logging.warning("This is a root warning")15    with caplog.at_level(logging.INFO, logger="pyam.core"):16        test_df.filter(model="junk")17        throw_warning()18    assert caplog.record_tuples == [19        ("pyam.core", logging.WARNING, "Filtered IamDataFrame is empty!"),20        ("root", logging.WARNING, "This is a root warning"),21    ]22    caplog.clear()23    with caplog.at_level(logging.ERROR, logger="pyam.core"):24        test_df.filter(model="junk")25        throw_warning()26    # only the root warning should come through now i.e. we can silence pyam27    # without silencing everything28    # TODO this test fails with pytest>=6.0.1, deactivated for now29    # assert caplog.record_tuples == [30    #     ("root", logging.WARNING, "This is a root warning"),...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!!
