Best Python code snippet using pytest-django_python
randomForest.py
Source:randomForest.py  
1"""2__author__ : SRK3"""4import numpy as np5import pandas as pd6from sklearn import preprocessing, ensemble7# columns to be used as features #8feature_cols = ["ind_empleado","pais_residencia","sexo","age", "ind_nuevo", "antiguedad", "nomprov", "segmento"]9dtype_list = {'ind_cco_fin_ult1': 'float16', 'ind_deme_fin_ult1': 'float16', 'ind_aval_fin_ult1': 'float16', 'ind_valo_fin_ult1': 'float16', 'ind_reca_fin_ult1': 'float16', 'ind_ctju_fin_ult1': 'float16', 'ind_cder_fin_ult1': 'float16', 'ind_plan_fin_ult1': 'float16', 'ind_fond_fin_ult1': 'float16', 'ind_hip_fin_ult1': 'float16', 'ind_pres_fin_ult1': 'float16', 'ind_nomina_ult1': 'float16', 'ind_cno_fin_ult1': 'float16', 'ncodpers': 'int64', 'ind_ctpp_fin_ult1': 'float16', 'ind_ahor_fin_ult1': 'float16', 'ind_dela_fin_ult1': 'float16', 'ind_ecue_fin_ult1': 'float16', 'ind_nom_pens_ult1': 'float16', 'ind_recibo_ult1': 'float16', 'ind_deco_fin_ult1': 'float16', 'ind_tjcr_fin_ult1': 'float16', 'ind_ctop_fin_ult1': 'float16', 'ind_viv_fin_ult1': 'float16', 'ind_ctma_fin_ult1': 'float16'}10target_cols = ['ind_ahor_fin_ult1','ind_aval_fin_ult1','ind_cco_fin_ult1','ind_cder_fin_ult1','ind_cno_fin_ult1','ind_ctju_fin_ult1','ind_ctma_fin_ult1','ind_ctop_fin_ult1','ind_ctpp_fin_ult1','ind_deco_fin_ult1','ind_deme_fin_ult1','ind_dela_fin_ult1','ind_ecue_fin_ult1','ind_fond_fin_ult1','ind_hip_fin_ult1','ind_plan_fin_ult1','ind_pres_fin_ult1','ind_reca_fin_ult1','ind_tjcr_fin_ult1','ind_valo_fin_ult1','ind_viv_fin_ult1','ind_nomina_ult1','ind_nom_pens_ult1','ind_recibo_ult1'] 11if __name__ == "__main__":12    data_path = "../input/"13    train_file = data_path + "train_ver2.csv"14    test_file = data_path + "test_ver2.csv"15    train_file = data_path + "small_train.csv"16    test_file = data_path + "small_test.csv"17    train_size = 1364730918    nrows = 1000000 # change this value to read more rows from train19    start_index = train_size - nrows20    for ind, col in enumerate(feature_cols):21        print(col)22        train = pd.read_csv(train_file, usecols=[col])23        test = pd.read_csv(test_file, usecols=[col])24        train.fillna(-99, inplace=True)25        test.fillna(-99, inplace=True)26        if train[col].dtype == "object":27            le = preprocessing.LabelEncoder()28            le.fit(list(train[col].values) + list(test[col].values))29            temp_train_X = le.transform(list(train[col].values)).reshape(-1,1)[start_index:,:]30            temp_test_X = le.transform(list(test[col].values)).reshape(-1,1)31        else:32            temp_train_X = np.array(train[col]).reshape(-1,1)[start_index:,:]33            temp_test_X = np.array(test[col]).reshape(-1,1)34        if ind == 0:35            train_X = temp_train_X.copy()36            test_X = temp_test_X.copy()37        else:38            train_X = np.hstack([train_X, temp_train_X])39            test_X = np.hstack([test_X, temp_test_X])40        print(train_X.shape, test_X.shape)41    del train42    del test43    train_y = pd.read_csv(train_file, usecols=['ncodpers']+target_cols, dtype=dtype_list)44    last_instance_df = train_y.drop_duplicates('ncodpers', keep='last')45    train_y = np.array(train_y.fillna(0)).astype('int')[start_index:,1:]46    print(train_X.shape, train_y.shape)47    print(test_X.shape)48    print("Running Model..")49    model = ensemble.RandomForestClassifier(n_estimators=10, max_depth=10, min_samples_leaf=10, n_jobs=4, random_state=2016)50    model.fit(train_X, train_y)51    del train_X, train_y52    print("Predicting..")53    preds = np.array(model.predict_proba(test_X))[:,:,1].T54    del test_X55    print("Getting last instance dict..")56    last_instance_df = last_instance_df.fillna(0).astype('int')57    cust_dict = {}58    target_cols = np.array(target_cols)59    for ind, row in last_instance_df.iterrows():60        cust = row['ncodpers']61        used_products = set(target_cols[np.array(row[1:])==1])62        cust_dict[cust] = used_products63    del last_instance_df64    print("Creating submission..")65    preds = np.argsort(preds, axis=1)66    preds = np.fliplr(preds)67    test_id = np.array(pd.read_csv(test_file, usecols=['ncodpers'])['ncodpers'])68    final_preds = []69    for ind, pred in enumerate(preds):70        cust = test_id[ind]71        top_products = target_cols[pred]72        used_products = cust_dict.get(cust,[])73        new_top_products = []74        for product in top_products:75            if product not in used_products:76                new_top_products.append(product)77            if len(new_top_products) == 7:78                break79        final_preds.append(" ".join(new_top_products))80    out_df = pd.DataFrame({'ncodpers':test_id, 'added_products':final_preds})...accparse2.py
Source:accparse2.py  
1# -*- mode: python; coding: utf-8 -*-2# Copyright (C) 2015, 2017  Laboratoire de Recherche et Développement3# de l'Epita4#5# This file is part of Spot, a model checking library.6#7# Spot is free software; you can redistribute it and/or modify it8# under the terms of the GNU General Public License as published by9# the Free Software Foundation; either version 3 of the License, or10# (at your option) any later version.11#12# Spot is distributed in the hope that it will be useful, but WITHOUT13# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY14# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public15# License for more details.16#17# You should have received a copy of the GNU General Public License18# along with this program.  If not, see <http://www.gnu.org/licenses/>.19import spot20a = spot.acc_cond(5)21a.set_acceptance(spot.acc_code('parity min odd 5'))22assert(a.is_parity() == [True, False, True])23a.set_acceptance('parity max even 5')24assert(a.is_parity() == [True, True, False])25a.set_acceptance('generalized-Buchi 5')26assert(a.is_parity()[0] == False)27assert(a.is_parity(True)[0] == False)28a.set_acceptance('Inf(4) | (Fin(3)&Inf(2)) | (Fin(3)&Fin(1)&Inf(0))')29assert(a.is_parity()[0] == False)30assert(a.is_parity(True) == [True, True, False])31assert a.maybe_accepting([1, 2, 3], [0, 4]).is_true()32assert a.maybe_accepting([0], []).is_true()33assert a.maybe_accepting([0], [3]).is_false()34assert a.maybe_accepting([0, 3], []).is_maybe()35assert a.maybe_accepting([2, 3], [3]).is_false()36assert a.maybe_accepting([2, 3], []).is_maybe()37assert a.maybe_accepting([2], []).is_true()38assert a.maybe_accepting([0, 1], []).is_maybe()39assert a.maybe_accepting([0, 1], [1]).is_false()40a.set_acceptance('Fin(0)|Fin(1)')41assert a.maybe_accepting([0, 1], [1]).is_maybe()42assert a.maybe_accepting([0, 1], [0, 1]).is_false()43assert a.maybe_accepting([0], []).is_true()44assert a.maybe_accepting([], [0]).is_true()45a = spot.acc_cond(0)46a.set_acceptance('all')47assert(a.is_rabin() == -1)48assert(a.is_streett() == 0)49assert(a.is_parity() == [True, True, True])50a.set_acceptance('none')51assert(a.is_rabin() == 0)52assert(a.is_streett() == -1)53assert(a.is_parity() == [True, True, False])54a = spot.acc_cond('(Fin(0)&Inf(1))')55assert(a.is_rabin() == 1)56assert(a.is_streett() == -1)57a.set_acceptance('Inf(1)&Fin(0)')58assert(a.is_rabin() == 1)59assert(a.is_streett() == -1)60a.set_acceptance('(Fin(0)|Inf(1))')61assert(a.is_rabin() == -1)62assert(a.is_streett() == 1)63a.set_acceptance('Inf(1)|Fin(0)')64assert(a.is_rabin() == -1)65assert(a.is_streett() == 1)66a = spot.acc_cond('(Fin(0)&Inf(1))|(Fin(2)&Inf(3))')67assert(a.is_rabin() == 2)68assert(a.is_streett() == -1)69a.set_acceptance(spot.acc_code('(Inf(3)&Fin(2))|(Fin(0)&Inf(1))'))70assert(a.is_rabin() == 2)71assert(a.is_streett() == -1)72a.set_acceptance(spot.acc_code('(Inf(2)&Fin(3))|(Fin(0)&Inf(1))'))73assert(a.is_rabin() == -1)74assert(a.is_streett() == -1)75a.set_acceptance(spot.acc_code('(Inf(3)&Fin(2))|(Fin(2)&Inf(1))'))76assert(a.is_rabin() == -1)77assert(a.is_streett() == -1)78a.set_acceptance(spot.acc_code('(Inf(1)&Fin(0))|(Fin(0)&Inf(1))'))79assert(a.is_rabin() == -1)80assert(a.is_streett() == -1)81a.set_acceptance('(Fin(0)&Inf(1))|(Inf(1)&Fin(0))|(Inf(3)&Fin(2))')82assert(a.is_rabin() == 2)83assert(a.is_streett() == -1)84a.set_acceptance('(Fin(0)|Inf(1))&(Fin(2)|Inf(3))')85assert(a.is_rabin() == -1)86assert(a.is_streett() == 2)87a.set_acceptance('(Inf(3)|Fin(2))&(Fin(0)|Inf(1))')88assert(a.is_rabin() == -1)89assert(a.is_streett() == 2)90a.set_acceptance('(Inf(2)|Fin(3))&(Fin(0)|Inf(1))')91assert(a.is_rabin() == -1)92assert(a.is_streett() == -1)93a.set_acceptance('(Inf(3)|Fin(2))&(Fin(2)|Inf(1))')94assert(a.is_rabin() == -1)95assert(a.is_streett() == -1)96a.set_acceptance('(Inf(1)|Fin(0))&(Fin(0)|Inf(1))')97assert(a.is_rabin() == -1)98assert(a.is_streett() == -1)99a.set_acceptance('(Fin(0)|Inf(1))&(Inf(1)|Fin(0))&(Inf(3)|Fin(2))')100assert(a.is_rabin() == -1)...Chef and Hamming Distance.py
Source:Chef and Hamming Distance.py  
1t=int(input())2for I in range(t):3    count=04    n=int(input())5    a=list(map(int,input().split(" ")))6    b=[]7    for i in a:8        b.append(i)9    #print(b)10    if(n==1):11        print(0)12        print(a[0])13    elif(n==2):14        if(a[0]==a[1]):15            print(0)16            print(a[0],a[1])17        else:18            print(2)19            print(a[1],a[0])20    else:21        if(n%2==0):22            ini=023            fin=n-124            if(b[0]==b[n-1]):25                b[0],b[1]=b[1],b[0]26                b[n-1],b[n-2]=b[n-2],b[n-1]27                ini=228                fin=n-329            while(ini+2<fin):30                #print('ini',ini)31                #print('fin',fin)32                #print(b)33                if(b[ini]==b[fin]):34                    #print('hello')35                    b[ini],b[ini+1]=b[ini+1],b[ini]36                    b[fin],b[fin-1]=b[fin-1],b[fin]37                    ini+=238                    fin-=239                else:40                    b[ini],b[fin]=b[fin],b[ini]41                    ini+=142                    fin-=143            a1=n//244            if(b[a1]==b[a1-1] and (a[a1]==b[a1] and a[a1-1]==b[a1-1])):45                b[a1-1],b[a1-2]=b[a1-2],b[a1-1]46                b[a1],b[a1+1]=b[a1+1],b[a1]47            else:48                b[a1],b[a1-1]=b[a1-1],b[a1]49            print(n)50            for i in b:51                print(i,end=' ')52        else:53            if(n==3):54                if(b[0]==b[2]):55                    #print('hola')56                    b[1],b[2]=b[2],b[1]57                elif(b[0]!=b[1] and b[0]!=b[2]):58                    #print('hola')59                    o1=b[0]60                    o2=b[1]61                    o3=b[2]62                    b[0]=o263                    b[1]=o364                    b[2]=o165                elif(b[1]==b[2]):66                    #print('hola')67                    b[0],b[1]=b[1],b[0]68                elif(b[0]==b[1]):69                    #print('hola')70                    b[1],b[2]=b[2],b[1]71            else:72                ini=073                fin=n-174                if(b[0]==b[n-1]):75                    b[0],b[1]=b[1],b[0]76                    b[n-1],b[n-2]=b[n-2],b[n-1]77                    ini=278                    fin=n-379                while(ini+1<fin):80                    if(b[ini]==b[fin] and ini!=(n//2-1)):81                    #print('hello')82                        b[ini],b[ini+1]=b[ini+1],b[ini]83                        b[fin],b[fin-1]=b[fin-1],b[fin]84                        ini+=285                        fin-=286                    elif(b[ini]==b[fin] and ini==(n//2-1)):87                        b[ini],b[ini-1]=b[ini-1],b[ini]88                        b[fin],b[fin+1]=b[fin+1],b[fin]89                        ini+=290                        fin-=291                    else:92                        b[ini],b[fin]=b[fin],b[ini]93                        ini+=194                        fin-=195                #b[(n//2)],b[(n//2)+1]=b[(n//2)+1],b[(n//2)]96                #print(b)97                num11=b[n//2]98                for i in range((n//2)+1,n):99                    if(num11!=a[i] and num11!=b[i]):100                        b[n//2],b[i]=b[i],b[n//2]101                        break102                        103            #print(a)104            #print(b)105            for i in range(len(b)):106                if(a[i]!=b[i]):107                    count+=1108            print(count)109            for i in b:110                print(i,end=' ')
...readStark.py
Source:readStark.py  
1#!/usr/bin/env python2from __future__ import print_function3#from builtins import str4#from builtins import range5#from builtins import object6import numpy as np7import re8import ast9import matplotlib.pylab as plt10import os11def run():12    shotnr = 2986513    nevin   = readDivData(getDivFname(shotnr,'nev','in'))14    nevout  = readDivData(getDivFname(shotnr,'nev','out'))15    jsatin  = readDivData(getDivFname(shotnr,'jsat','in'))16    jsatout = readDivData(getDivFname(shotnr,'jsat','out'))17def getDivFname(shotnr,what,pos):18    19    homedir = str(os.environ["HOME"])20    ##Expects data to be saved in "$HOME/Divertor"21    fin = homedir + '/Divertor/' + str(shotnr) + '/3D_'+ str(shotnr) + '_'22    if what == 'nev':23        fin = fin + 'nev'24    elif what == 'jsat':25        fin = fin + 'jsat'26    elif what == 'net':27        fin = fin + 'net'28    elif what == 'te':29        fin = fin + 'te'30    else:31        print("Item not recognized, defaulting to jsat")32        fin = fin + 'jsat'33    if pos == 'in':34        fin = fin+'_in.dat'35    else:36        fin = fin+'_out.dat'37    return fin38def readDivData(filename):39    """Reads contour-plot DIVERTOR data from an ascii file40    Parameters41    ----------42    filename:43         String with the filename outputted from DIVERTOR, ususally "3D_..."44    Returns45    ----------46    An object with three fields:47    obj.time: ndarray48         The times of the contour49    obj.deltas: ndarray50         The y axis of the contour, usually Delta S, but rho is also possible51    obj.data: matrix52        The matrix with the jsat, density, etc., data.53    54    """55    class objview(object):56        def __init__(self, d):57            self.__dict__=d58            59    try:60        fin = open(filename, 'r')61    except:62        print("No such file " + filename)63        print("Returning dummy data")64        data = np.array([[0.0, 0.0],[0.0,0.0]])65        #return dummy data66        #Return ranges that will always be covered by the times ELM analysis are performed67        return objview({'time': np.array([-21.0, 21.0]),68                        'deltas': np.array([-17.0, 57.0]),69                        'data': data})70    #Read dumb line71    fin.readline()72    #Time points73    tpts = int(fin.readline())74    #Read dumb lines75    fin.readline()76    fin.readline()77    #DS coordinate points78    spts = int(fin.readline())79    #Read dumb lines80    fin.readline()81    fin.readline()82    #Density scale83    nes = float(fin.readline())84    nesc = np.array(nes)85    #Read dumb lines86    fin.readline()87    fin.readline()88    #Read time vector89    time = []90    for i in range(0, tpts):91        time.append(float(fin.readline()))92    #Read dumb lines93    fin.readline()94    fin.readline()95    #Read Delta S vector96    deltas = []97    for i in range(0, spts):98        deltas.append(float(fin.readline()))99    #Read dumb lines100    fin.readline()101    fin.readline()102    #Read Density data103    data = []104    for i in range(0, tpts):105        string = fin.readline()106        string = re.sub(r"\s+",",",string)107        string = "[" + string[1:-1] + "]"108        vec = ast.literal_eval(string)109        data.append(vec)110    #Close shotfile111    fin.close()112    113    return objview({'time': np.array(time),114                    'deltas': np.array(deltas),115                    'data': np.array(data).T})116#a = readDivData(getDivFname(29865, "nev", "in"))...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!!
