Best Python code snippet using lemoncheesecake
Candy_Hierarchy.py
Source:Candy_Hierarchy.py
1#!/usr/bin/env python2# coding: utf-83# In[1]:4#Import modules5import pandas as pd6import numpy as np7from fuzzywuzzy import fuzz8from fuzzywuzzy import process9# In[2]:10# read the DataFrame11candy_hierarchy = pd.read_csv('E:/hazem/Technology/Data science/CAT/Data Cleaning/task/candyhierarchy2017.csv')12pd.set_option('display.max_columns',120)13# In[3]:14#chaning the names of the columns15candy_hierarchy.columns=['ID','Going_Out','Gender','Age','Country','State' ,'Grand_Bar','Brown_Globs','Candy_bar','Black_jacks',16 'Bonkers_Candy','Bonkers_Game','Bottle_caps','Raisins_Box','Broken_stick','Butterfinger',17 'Cadbury_CremeEggs' , 'Candy_Corn','Resturant_FreeCandy','Caramellos','Cash','Chardonnay','Chick-O-Sticks',18 'Chiclets','Coffee Crisp','Creepy_Religious_comics','paraphenalia','Dots','Dove_Bars','Fuzzy_Peaches',19 'Generic_Brand_Acetaminophen' ,'Glow_Sticks',' GooGoo_Clusters','GoodN_Plenty', 'Gum_cards','Gummy_Bears',20 'Hard_Candy','Healthy_Fruit','Health_Bar','Hersheys_DarkChocolate','Hersheys_MilkChocolate',21 'Hersheys_Kisses','Hugs','Bad_JollyRancher','Good_JollyRancher','JoyJoy' ,'Junior_Mints' ,'senior Mints',22 'Kale_smoothie','Kinder','KitKat','LaffyTaffy','LemonHeads','NotBlack_Licorice','Black_Licorice',23 'Lindt_Truffle','Lollipops','Mars','Maynards','Mike&Ike','Milk_Duds','Milky Way','Regular-M&M',24 'Peanut_M&M','Blue_M&M','Red_M&M','Green_M&M','Independant_M&M','Abstained_M&M','Minibags_Chips','Mint_Kisses',25 'Mint_Juleps','Mr.Goodbar','NeccoWafers','Nerds','NestleCrunch',"Now'n'Laters",'Peeps','Pencils','Pixy_Stix',26 'Housewives','ReeseâsButter',"Reese'sPieces",'JacksonBar','Rolos','BooBerry_Sandwich','Skittles','American_Smarties',27 'CommonWealth_Smarties','Snickers','Sourpatch_Kids','Spotted_Dick','Starburst','Sweet_Tarts','Swedish Fish',28 'Sweetums','Take5','TicTacs','Marshmallow','Musketeers','Tolberone','Trail-Mix','Twix','fructose corn syrup',29 'Vicodin','Whatchamacallit_Bars','White_Bread','Whole Wheat anything','Peppermint Patties','JOY OTHER',30 'DESPAIR OTHER','OTHER COMMENTS','Dress','Unnamed:113','Day',"Media DailyDish","Media Science",'Media ESPN',31 'Media Yahoo',"Click Coordinates (x, y)"]32# In[4]:33#Show some general properties of the DataFrame34candy_hierarchy.head()35candy_hierarchy.info()36candy_hierarchy.dtypes37# In[5]:38#chanind the datatypes of some columns39candy_hierarchy['ID'] = candy_hierarchy['ID'].astype('O')40assert candy_hierarchy['ID'].dtype == 'O'41#Making Sure there isnot dupliacted values42duplicates=candy_hierarchy.duplicated(subset=['ID'],keep=False)43candy_hierarchy[duplicates] #No duplicated Value44# In[6]:45#Droping the usless columns 46candy_hierarchy.drop(columns=['ID','Unnamed:113'],inplace=True)47# In[7]:48#Droping the rows which have Nan values for all columns49candy_hierarchy.dropna(axis='index',how='all',inplace=True)50#drop the rows which have Nan values for all Q6 Column 51columns_name=[ 'Grand_Bar','Brown_Globs','Candy_bar','Black_jacks','Bonkers_Candy','Bonkers_Game','Bottle_caps','Raisins_Box','Broken_stick','Butterfinger',52 'Cadbury_CremeEggs' , 'Candy_Corn','Resturant_FreeCandy','Caramellos','Cash','Chardonnay','Chick-O-Sticks',53 'Chiclets','Coffee Crisp','Creepy_Religious_comics','paraphenalia','Dots','Dove_Bars','Fuzzy_Peaches',54 'Generic_Brand_Acetaminophen' ,'Glow_Sticks',' GooGoo_Clusters','GoodN_Plenty', 'Gum_cards','Gummy_Bears',55 'Hard_Candy','Healthy_Fruit','Health_Bar','Hersheys_DarkChocolate','Hersheys_MilkChocolate',56 'Hersheys_Kisses','Hugs','Bad_JollyRancher','Good_JollyRancher','JoyJoy' ,'Junior_Mints' ,'senior Mints',57 'Kale_smoothie','Kinder','KitKat','LaffyTaffy','LemonHeads','NotBlack_Licorice','Black_Licorice',58 'Lindt_Truffle','Lollipops','Mars','Maynards','Mike&Ike','Milk_Duds','Milky Way','Regular-M&M',59 'Peanut_M&M','Blue_M&M','Red_M&M','Green_M&M','Independant_M&M','Abstained_M&M','Minibags_Chips','Mint_Kisses',60 'Mint_Juleps','Mr.Goodbar','NeccoWafers','Nerds','NestleCrunch',"Now'n'Laters",'Peeps','Pencils','Pixy_Stix',61 'Housewives','ReeseâsButter',"Reese'sPieces",'JacksonBar','Rolos','BooBerry_Sandwich','Skittles','American_Smarties',62 'CommonWealth_Smarties','Snickers','Sourpatch_Kids','Spotted_Dick','Starburst','Sweet_Tarts','Swedish Fish',63 'Sweetums','Take5','TicTacs','Marshmallow','Musketeers','Tolberone','Trail-Mix','Twix','fructose corn syrup',64 'Vicodin','Whatchamacallit_Bars','White_Bread','Whole Wheat anything','Peppermint Patties']65candy_hierarchy.dropna(axis='index',how='all',subset=columns_name,inplace=True)66# In[8]:67candy_hierarchy68# In[9]:69#Cleaning the Going_out Column70#1-Knowing the unique values of the column71candy_hierarchy['Going_Out'].unique()72#2-Replace the Nan values73candy_hierarchy.fillna({'Going_Out' : 'No'},inplace=True)74# In[10]:75#Cleaning the Gender Column76#1-Knowing the unique values of the column77candy_hierarchy['Gender'].unique()78#2-Replace the Nan values79candy_hierarchy.fillna({'Gender' :"I'd rather not say"},inplace=True)80candy_hierarchy['Gender'].value_counts()81# In[11]:82#Cleaning the Age column83#1-Knowing the dtype of the column84candy_hierarchy['Age'].dtype85#2-Knowing the unique values of the column86candy_hierarchy['Age'].unique()87#3-Replace some values88NonSense_values= ['I can remember when Java was a cool new language', 'MY NAME JEFF','ancient','1000','See question 2','older than dirt',89 'Enough','312','hahahahaha','?', 'no', 'Many','4']90Old_People = ['old enough','old','OLD','Old enough','Over 50']91for state in NonSense_values:92 candy_hierarchy['Age'].replace(state,np.nan,inplace=True)93for person in Old_People:94 candy_hierarchy['Age'].replace(person,55,inplace=True)95 96candy_hierarchy['Age'].replace('45-55',50,inplace=True)97candy_hierarchy['Age'].replace('24-50',37,inplace=True)98candy_hierarchy['Age'].replace('46 Halloweens.',46,inplace=True)99candy_hierarchy['Age'].replace('59 on the day after Halloween',59,inplace=True)100#4-Parsing the age column101candy_hierarchy['Age']=candy_hierarchy['Age'].astype('float')102#5-Using the more suitable way103candy_hierarchy['Age'].describe()104Age_Median = candy_hierarchy['Age'].median()105#6-Replace the Non values106candy_hierarchy.fillna({'Age':Age_Median},inplace=True)107candy_hierarchy['Age'].unique()108# In[12]:109#Cleaning the Country column110#1-Knowing the unique values of the column111candy_hierarchy['Country']=candy_hierarchy['Country'].str.lower()112candy_hierarchy['Country'].unique()113#2-Replace some values114Missed_Countries=["i don't know anymore",'fear and loathing','subscribe to dm4uz3 on youtube','a','insanity lately','earth',115 'atlantis',]116USA_Country = ['usa usa usa!!!!','u s a', 'united statea','u.s. ','ussa', 'united stated','united statss','united sates',117 'i pretend to be from canada, but i am really from the united states.','usa? hard to tell anymore..',118 'the united states of america', 'the united states', 'unites states', 'united states of america ',119 'u.s.a.', 'usausausa','united states ','united states of america','united states', 'united staes',120 'usa ', 'us', 'usa','united states','us of a','u s', 'u.s.']121Canda_Country =['canada','canada ','canae','canada`']122America_Country =['america',"'merica",'ahem....amerca','n. america', 'murrika']123France_Country =['france', 'france ']124Uk =['uk','united kingdom']125England = ['england','endland']126for country in Missed_Countries:127 candy_hierarchy['Country'].replace(country,'Unknown',inplace=True)128for country in USA_Country:129 candy_hierarchy['Country'].replace( country,'United States',inplace=True)130 131for country in Canda_Country:132 candy_hierarchy['Country'].replace( country,'Canda',inplace=True)133for country in America_Country:134 candy_hierarchy['Country'].replace( country,'America',inplace=True)135for country in France_Country:136 candy_hierarchy['Country'].replace( country,'France',inplace=True)137for country in Uk:138 candy_hierarchy['Country'].replace( country,'United kingdom',inplace=True)139 140for country in England:141 candy_hierarchy['Country'].replace( country,'England',inplace=True)142 143#3-Fill the Nan Value144candy_hierarchy.fillna({'Country':'Unknown'},inplace=True)145candy_hierarchy['Country']=candy_hierarchy['Country'].str.capitalize()146candy_hierarchy['Country'].value_counts().sort_values()147# In[13]:148#Cleaning Q6 Column149for Column in columns_name:150 candy_hierarchy.fillna({Column :'Other'} ,inplace=Tru151# In[ ]:152#Cleaning the JOY OTHER Column153#1-Knowing the unique values of the column154candy_hierarchy['JOY OTHER'].unique()155#2-Replace the Nan values156candy_hierarchy.fillna({'JOY OTHER' : 'No'},inplace=True)157 158 159# In[ ]:160#Cleaning the DESPAIR OTHER Column161#1-Knowing the unique values of the column162candy_hierarchy['DESPAIR OTHER'].unique()163#2-Replace the Nan values164candy_hierarchy.fillna({'DESPAIR OTHER' : 'No'},inplace=True)165# In[ ]:166#Cleaning the OTHER COMMENTS Column167#1-Knowing the unique values of the column168candy_hierarchy['OTHER COMMENTS'].unique()169#2-Replace the Nan values170candy_hierarchy.fillna({'OTHER COMMENTS' : 'No'},inplace=True)171# In[ ]:172#Cleaning the Day Column173#1-Knowing the unique values of the column174candy_hierarchy['Day'].unique()175#2-Replace the Nan values176candy_hierarchy.fillna({'Day' : 'Other'},inplace=True)177# In[ ]:178#Cleaning the Dress Column179#1-Knowing the unique values of the column180candy_hierarchy['Dress'].unique()181#2-Replace the Nan values182candy_hierarchy.fillna({'Dress' : 'Other'},inplace=True)...
test_pressuresolve.py
Source:test_pressuresolve.py
1from firedrake import *2from pressuresolver.operators import *3from pressuresolver.hierarchy import *4from pressuresolver.mu_tilde import *5from pressuresolver.smoothers import *6from pressuresolver.preconditioners import *7from pressuresolver.solvers import *8from pressuresolver.ksp_monitor import *9from mixedoperators import *10import numpy as np11import pytest12from fixtures import *13op2.init(log_level="WARNING")14from ffc import log15log.set_level(log.ERROR)16def test_pressuresolve(R_earth,17 W3,18 W2,19 W2_horiz,20 W2_vert,21 Wb,22 W3_hierarchy,23 W2_hierarchy,24 W2_horiz_hierarchy,25 W2_vert_hierarchy,26 Wb_hierarchy,27 pressure_expression):28 '''Test pressure solver at next-to-lowest order. This tests29 the hp-multigrid preconditioner.30 :arg R_earth: Earth radius31 :arg W3: (Higher order) pressure space32 :arg W2: (Higher order) velocity space33 :arg W2_horiz: Horizontal component of (higher order) velocity space34 :arg W2_vert: Vertical component of (higher order) velocity space35 :arg Wb: (Higher order) buoyancy space36 :arg W3_hierarchy: Pressure space hierarchy37 :arg W2_hierarchy: Velocity space hierarchy38 :arg W2_horiz_hierarchy: Horizontal velocity component hierarchy39 :arg W2_vert_hierarchy: Vertical velocity component hierarchy40 :arg Wb_hierarchy: Buoyancy space hierarchy41 :arg pressure_expression: analytical expression for RHS42 '''43 mesh = W3.mesh()44 ncells = mesh.cell_set.size45 print 'Number of cells on finest grid = '+str(ncells)46 if (mesh.geometric_dimension == 3):47 dx = 2./math.sqrt(3.)*math.sqrt(4.*math.pi/(ncells))*R_earth48 else:49 dx = 2.*math.pi/float(ncells)*R_earth50 51 c = 300.52 N = 0.0153 nu_cfl = 8.54 dt = nu_cfl/c*dx55 omega_c = 0.5*c*dt56 omega_N = 0.5*N*dt57 mixed_operator = MixedOperator(W2,W3,dt,c,N)58 # Construct h-multigrid preconditioner59 operator_Hhat_hierarchy = HierarchyContainer(Operator_Hhat,60 zip(W3_hierarchy,61 W2_horiz_hierarchy,62 W2_vert_hierarchy),63 omega_c,64 omega_N)65 presmoother_hierarchy = HierarchyContainer(Jacobi,66 zip(operator_Hhat_hierarchy))67 postsmoother_hierarchy = HierarchyContainer(Jacobi,68 zip(operator_Hhat_hierarchy))69 coarsegrid_solver = postsmoother_hierarchy[0]70 hmultigrid = hMultigrid(W3_hierarchy,71 operator_Hhat_hierarchy,72 presmoother_hierarchy,73 postsmoother_hierarchy,74 coarsegrid_solver)75 # Higher order operator \hat{H} and smoothers76 operator_Hhat = Operator_Hhat(W3,W2_horiz,W2_vert,77 omega_c,omega_N)78 presmoother = Jacobi(operator_Hhat)79 postsmoother = Jacobi(operator_Hhat)80 # hp-multigrid preconditioner81 preconditioner = hpMultigrid(hmultigrid,82 operator_Hhat,83 presmoother,84 postsmoother)85 # Higher order operator H86 mutilde = Mutilde(mixed_operator,lumped=False,tolerance_u=1.E-1)87 operator_H = Operator_H(W3,W2,mutilde,omega_c)88 ksp_monitor = KSPMonitor()89 ksp_type = 'cg'90 solver = PETScSolver(operator_H,91 preconditioner,92 ksp_type,93 ksp_monitor,94 tolerance=1.E-5,95 maxiter=30)96 b = Function(W3).project(pressure_expression)97 phi = Function(W3)98 solver.solve(b,phi)99 assert (ksp_monitor.its < 25)100def test_pressuresolve_lowestorder(R_earth,101 W3_hierarchy,102 W2_hierarchy,103 W2_horiz_hierarchy,104 W2_vert_hierarchy,105 Wb_hierarchy,106 pressure_expression):107 '''Test pressure solver at lowest order. This mainly tests the108 h-multigrid preconditioner.109 :arg R_earth: Earth radius110 :arg W3_hierarchy: Pressure space hierarchy111 :arg W2_hierarchy: Velocity space hierarchy112 :arg W2_horiz_hierarchy: Horizontal velocity component hierarchy113 :arg W2_vert_hierarchy: Vertical velocity component hierarchy114 :arg Wb_hierarchy: Buoyancy space hierarchy115 :arg pressure_expression: analytical expression for RHS116 '''117 W3 = W3_hierarchy[-1]118 W2 = W2_hierarchy[-1]119 Wb = Wb_hierarchy[-1]120 mesh = W3.mesh()121 ncells = mesh.cell_set.size122 print 'Number of cells on finest grid = '+str(ncells)123 if (mesh.geometric_dimension == 3):124 dx = 2./math.sqrt(3.)*math.sqrt(4.*math.pi/(ncells))*R_earth125 else:126 dx = 2.*math.pi/float(ncells)*R_earth127 128 c = 300.129 N = 0.01130 nu_cfl = 8.0131 dt = nu_cfl/c*dx132 omega_c = 0.5*c*dt133 omega_N = 0.5*N*dt134 mixed_operator = MixedOperator(W2,W3,dt,c,N)135 mutilde = Mutilde(mixed_operator,lumped=True,tolerance_u=1.E-1)136 operator_H = Operator_H(W3,W2,mutilde,omega_c)137 operator_Hhat_hierarchy = HierarchyContainer(Operator_Hhat,138 zip(W3_hierarchy,139 W2_horiz_hierarchy,140 W2_vert_hierarchy),141 omega_c,142 omega_N)143 presmoother_hierarchy = HierarchyContainer(Jacobi,144 zip(operator_Hhat_hierarchy))145 postsmoother_hierarchy = HierarchyContainer(Jacobi,146 zip(operator_Hhat_hierarchy))147 coarsegrid_solver = postsmoother_hierarchy[0]148 preconditioner = hMultigrid(W3_hierarchy,149 operator_Hhat_hierarchy,150 presmoother_hierarchy,151 postsmoother_hierarchy,152 coarsegrid_solver)153 ksp_monitor = KSPMonitor()154 ksp_type = 'cg'155 solver = PETScSolver(operator_H,156 preconditioner,157 ksp_type,158 ksp_monitor,159 tolerance=1.E-5,160 maxiter=30)161 b = Function(W3).project(pressure_expression)162 phi = Function(W3)163 solver.solve(b,phi)164 assert (ksp_monitor.its < 25)165##############################################################166# M A I N167##############################################################168if __name__ == '__main__':169 import os...
part2.py
Source:part2.py
1from _utils import get_packet2from _utils import get_lims3from _utils import get_type4def _evaluate_0(packet, hierarchy, lims):5 subpacket_lims = hierarchy[lims]6 sum_ = 07 for subpacket_lim in subpacket_lims:8 sum_ += evaluate(packet, hierarchy, subpacket_lim)9 return sum_10def _evaluate_1(packet, hierarchy, lims):11 subpacket_lims = hierarchy[lims]12 prod = 113 for subpacket_lim in subpacket_lims:14 prod *= evaluate(packet, hierarchy, subpacket_lim)15 return prod16def _evaluate_2(packet, hierarchy, lims):17 subpacket_lims = hierarchy[lims]18 min_ = 1e619 for subpacket_lim in subpacket_lims:20 val = evaluate(packet, hierarchy, subpacket_lim)21 if val < min_:22 min_ = val23 return min_24def _evaluate_3(packet, hierarchy, lims):25 subpacket_lims = hierarchy[lims]26 max_ = 027 for subpacket_lim in subpacket_lims:28 val = evaluate(packet, hierarchy, subpacket_lim)29 if val > max_:30 max_ = val31 return max_32def _evaluate_4(packet, hierarchy, lims):33 # args for consistency34 # assumes it has no children35 start, end = lims36 pointer = start + 637 bin_str = ''38 while True:39 val = packet[pointer]40 pointer += 141 bin_str += packet[pointer:pointer + 4]42 pointer += 443 if val == '0':44 break45 return int(bin_str, 2)46def _evaluate_logical(packet, hierarchy, lims, fnc):47 subpacket_lims = hierarchy[lims]48 value_0 = evaluate(packet, hierarchy, subpacket_lims[0])49 value_1 = evaluate(packet, hierarchy, subpacket_lims[1])50 if fnc(value_0, value_1):51 return 152 return 053def _evaluate_5(packet, hierarchy, lims):54 return _evaluate_logical(packet, hierarchy, lims,55 lambda x, y: x > y)56def _evaluate_6(packet, hierarchy, lims):57 return _evaluate_logical(packet, hierarchy, lims,58 lambda x, y: x < y)59def _evaluate_7(packet, hierarchy, lims):60 return _evaluate_logical(packet, hierarchy, lims,61 lambda x, y: x == y)62def evaluate(packet, hierarchy, lims):63 type_ = get_type(packet, lims[0])64 fnc = eval(f'_evaluate_{type_}')65 val = fnc(packet, hierarchy, lims)66 return val67def hierarchize(lims):68 hierarchy = {}69 children_pool = lims.copy()70 for lim in reversed(lims):71 start, end = lim72 hierarchy[lim] = []73 for cmp_lim in children_pool.copy():74 if start <= cmp_lim[0] <= end and start <= cmp_lim[1] <= end:75 if lim == cmp_lim:76 continue77 hierarchy[lim].append(cmp_lim)78 children_pool.remove(cmp_lim)79 return hierarchy80def get_root_key(lims):81 for lim in lims:82 if lim[0] == 0:83 return lim84if __name__ == '__main__':85 from input import MAIN as HEXA_STR86 packet = get_packet(HEXA_STR)87 n = len(packet)88 lims = get_lims(packet, 0, n)89 hierarchy = hierarchize(lims)90 root_lims = get_root_key(hierarchy)91 value = evaluate(packet, hierarchy, root_lims)...
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!!