Best Python code snippet using autotest_python
fpl_api.py
Source:fpl_api.py
1# -*- coding: utf-8 -*-2"""3Created on Wed Oct 29 20:09:42 20144@author: Prathmesh5"""6#Importing Various Python modules 7import pandas as pd8import statsmodels.formula.api as smf9import statsmodels.api as sm10import matplotlib.pyplot as plt11import numpy as np12import requests13from pprint import pprint14import csv15from time import sleep16from sklearn.cross_validation import cross_val_score17from sklearn.linear_model import LinearRegression18from sklearn.cross_validation import train_test_split19from sklearn.metrics import mean_squared_error20#Sample API for one Player21r = requests.get('http://fantasy.premierleague.com/web/api/elements/266/')22top = r.text # unicode text string23top = r.json() # dictionary24pprint(top)25#for loop for scrapping api for all the players26#Reviewers Don't need to Run this Step as I've already got the data in CSV27#This is a time consuming process as this step is accessing web api28s1='http://fantasy.premierleague.com/web/api/elements/'29players = []30for player_link in range(1,624,1):31 link = s1+""+str(player_link)32 r = requests.get(link)33 player =r.json() 34 players.append(player)35 sleep(1)36#Writing the Data from the API into a CSV file37with open('/Users/Prathmesh/Documents/Data-Science-Course/Project/dict_output1.csv', 'wb') as f: # Just use 'w' mode in 3.x38 w = csv.DictWriter(f,player.keys())39 w.writeheader()40 for player in players: 41 w.writerow(player)42# Reading CSV into Pandas DataFrame43# dict_output Refers to Player data from a November Week44players_df = pd.read_csv('/Users/Prathmesh/Documents/Data-Science-Course/Project/dict_output1.csv',index_col='web_name', na_filter=False)45#Observing the Data for Exploration46players_df.head()47players_df.tail()48players_df.dtypes49players_df.iloc[0,:]50#Some random plotting to determine which attributes to use in the final model51# I did this step for various variables but it didn't reveal much to me.52plt.scatter(players_df.value_form, players_df.points_per_game, alpha=0.3)53plt.scatter(players_df.value_season, players_df.points_per_game, alpha=0.3) 54plt.scatter(forwards_df.bps, forwards_df.points_per_game, alpha=0.3) 55plt.xlabel("BPS")56plt.ylabel("Points Per Game")57#Filtering the data only for Forwards58players_df[players_df.type_name=='Forward'].to_csv('../data/players_updated.csv')59forwards_df = pd.read_csv('/Users/Prathmesh/Documents/Data-Science-Course/Project/players_updated.csv',index_col='web_name', na_filter=False)60#Exploring the data in the forwards data frame61forwards_df.describe()62forwards_df.head()63forwards_df.tail()64forwards_df.dtypes65forwards_df.points_per_game.describe()66forwards_df.points_per_game.value_counts()67forwards_df.isnull()68#Creating Initial Linear Model for Forwards69forwards_model = smf.ols(formula='event_total ~ selected_by + value_form + value_season + form + ea_index + bps', data=forwards_df).fit()70forwards_model.summary()71# Exploring Multi-collinearity between Variables72columns = ['event_total', 'selected_by', 'value_form', 'value_season', 'form','ea_index','bps']73pd.scatter_matrix(forwards_df[columns])74corr_matrix = np.corrcoef(forwards_df[columns].T)75sm.graphics.plot_corr(corr_matrix, xnames=columns)76# Its obvious from the Correlation Matrix that there is correlation between bps - ea_index & form - value_form77# Hence removing bps & value_from model and exploring78forwards_model = smf.ols(formula='event_total ~ selected_by + form + value_season + ea_index', data=forwards_df).fit()79forwards_model.summary()80#Trying Interaction terms to handle Correlation81# Interaction using * between form & value_form ; form and value_season82interaction_model = smf.ols(formula='event_total ~ selected_by + value_form*form + value_season*form + ea_index', data=forwards_df).fit()83interaction_model.summary()84# Removing players who have played 0 minutes till now85forwards_df[forwards_df.minutes> 0].to_csv('/Users/Prathmesh/Documents/Data-Science-Course/Project/regular_forwards.csv')86regular_forwards_df = pd.read_csv('/Users/Prathmesh/Documents/Data-Science-Course/Project/regular_forwards.csv',index_col='web_name', na_filter=False)87# Running all features models for data set without fringe players88# This inculdes all the possible features, just to study the importance of each feature89all_features_model = smf.ols(formula='event_total ~ selected_by + total_points+ chance_of_playing_this_round + value_form + value_season + form + transfers_out_event+ transfers_in_event + points_per_game + minutes +ea_index + bps', data=regular_forwards_df).fit()90all_features_model.summary()91# Performing Cross Evaluation of the Model92# Creating two interaction terms based on what we learned from multi-collinearity matrix93regular_forwards_df['interaction_term1'] = regular_forwards_df.value_form * regular_forwards_df.form94regular_forwards_df['interaction_term2'] = regular_forwards_df.value_season * regular_forwards_df.form95cols = ['points_per_game','now_cost','selected_by', 'interaction_term1','interaction_term2', 'ea_index']96X = regular_forwards_df[cols]97y = regular_forwards_df.event_total98lm = LinearRegression()99# Also tried RandomForestClassifier but it didn't produce better model as compared to Linear Regression100#rf = RandomForestClassifier(n_estimators=100) 101scores = cross_val_score(lm, X, y, cv=5, scoring='mean_squared_error')102#Calculating Root Mean Squared Error103np.sqrt(-scores)104np.mean(np.sqrt(-scores)) #RMSE for Nov Model 2.0596105# Creating the Same Model for Dec 1 Data Set106players_dec1_df = pd.read_csv('/Users/Prathmesh/Documents/Data-Science-Course/Project/dec1_players.csv',index_col='web_name', na_filter=False)107players_dec1_df[players_dec1_df.type_name=='Forward'].to_csv('/Users/Prathmesh/Documents/Data-Science-Course/Project/forwardplayers_dec1.csv')108forwards_dec1_df = pd.read_csv('/Users/Prathmesh/Documents/Data-Science-Course/Project/forwardplayers_dec1.csv',index_col='web_name', na_filter=False)109forwards_dec1_df[forwards_dec1_df.minutes> 0].to_csv('/Users/Prathmesh/Documents/Data-Science-Course/Project/regular_forwards_dec1.csv')110regular_forwards_dec1_df = pd.read_csv('/Users/Prathmesh/Documents/Data-Science-Course/Project/regular_forwards_dec1.csv',index_col='web_name', na_filter=False)111regular_forwards_dec1_df['interaction_term1'] = regular_forwards_dec1_df.value_form * regular_forwards_dec1_df.form112regular_forwards_dec1_df['interaction_term2'] = regular_forwards_dec1_df.value_season * regular_forwards_dec1_df.form113cols = ['points_per_game','now_cost','selected_by', 'interaction_term1','interaction_term2', 'ea_index']114X2 = regular_forwards_dec1_df[cols]115y2 = regular_forwards_dec1_df.event_total116lm = LinearRegression()117scores = cross_val_score(lm, X2, y2, cv=5, scoring='mean_squared_error')118np.sqrt(-scores)119np.mean(np.sqrt(-scores)) #RMSE for Dec1 Model 1.6575120# Creating the Same Model for Dec 4 Data Set121players_dec4_df = pd.read_csv('/Users/Prathmesh/Documents/Data-Science-Course/Project/dec4_players.csv',index_col='web_name', na_filter=False)122players_dec4_df[players_df.type_name=='Forward'].to_csv('/Users/Prathmesh/Documents/Data-Science-Course/Project/forwardplayers_dec4.csv')123forwards_dec4_df = pd.read_csv('/Users/Prathmesh/Documents/Data-Science-Course/Project/forwardplayers_dec4.csv',index_col='web_name', na_filter=False)124forwards_dec4_df[forwards_dec4_df.minutes> 0].to_csv('/Users/Prathmesh/Documents/Data-Science-Course/Project/regular_forwards_dec4.csv')125regular_forwards_dec4_df = pd.read_csv('/Users/Prathmesh/Documents/Data-Science-Course/Project/regular_forwards_dec4.csv',index_col='web_name', na_filter=False)126regular_forwards_dec4_df['interaction_term1'] = regular_forwards_dec4_df.value_form * regular_forwards_dec4_df.form127regular_forwards_dec4_df['interaction_term2'] = regular_forwards_dec4_df.value_season * regular_forwards_dec4_df.form128cols = ['points_per_game','now_cost','selected_by', 'interaction_term1','interaction_term2', 'ea_index']129X3 = regular_forwards_dec4_df[cols]130y3 = regular_forwards_dec4_df.event_total131lm = LinearRegression()132scores = cross_val_score(lm, X3, y3, cv=5, scoring='mean_squared_error')133np.sqrt(-scores)134np.mean(np.sqrt(-scores)) #RMSE for Dec4 Model 2.4378135# Creating the Same Model for Dec 9 Data Set136players_dec9_df = pd.read_csv('/Users/Prathmesh/Documents/Data-Science-Course/Project/dec9_players.csv',index_col='web_name', na_filter=False)137players_dec9_df[players_df.type_name=='Forward'].to_csv('/Users/Prathmesh/Documents/Data-Science-Course/Project/forwardplayers_dec9.csv')138forwards_dec9_df = pd.read_csv('/Users/Prathmesh/Documents/Data-Science-Course/Project/forwardplayers_dec9.csv',index_col='web_name', na_filter=False)139forwards_dec9_df[forwards_dec9_df.minutes> 0].to_csv('/Users/Prathmesh/Documents/Data-Science-Course/Project/regular_forwards_dec9.csv')140regular_forwards_dec9_df = pd.read_csv('/Users/Prathmesh/Documents/Data-Science-Course/Project/regular_forwards_dec9.csv',index_col='web_name', na_filter=False)141regular_forwards_dec9_df['interaction_term1'] = regular_forwards_dec9_df.value_form * regular_forwards_dec9_df.form142regular_forwards_dec9_df['interaction_term2'] = regular_forwards_dec9_df.value_season * regular_forwards_dec9_df.form143cols = ['points_per_game','now_cost','selected_by', 'interaction_term1','interaction_term2', 'ea_index']144X4 = regular_forwards_dec9_df[cols]145y4 = regular_forwards_dec9_df.event_total146lm = LinearRegression()147scores = cross_val_score(lm, X4, y4, cv=5, scoring='mean_squared_error')148np.sqrt(-scores)149np.mean(np.sqrt(-scores)) #RMSE for Dec9 Model 3.14755150# Training the model on the November Data Set & Testing for Dec 1, Dec4 & Dec 9 Data 151cols = ['points_per_game','now_cost','selected_by', 'interaction_term1','interaction_term2', 'ea_index']152X = regular_forwards_df[cols]153y = regular_forwards_df.event_total154lm = LinearRegression()155#rf = RandomForestClassifier(n_estimators=100)156#rf.fit(X,y)157lm.fit(X, y) # fitting the linear regression on Nov values of X & Y158# Testing and Predicting for Dec 1 Data set159preds = lm.predict(X2) #X for Dec 1160# calc RMSE to compare preds vs y for Dec 1161rms = np.sqrt(mean_squared_error(y2, preds))162rms # RMSE for preds for Dec1 data set 2.3746163# Testing and Predicting for Dec 4 Data set164preds = lm.predict(X3) #X for Dec 4165# calc RMSE to compare preds vs y for Dec 4166rms = np.sqrt(mean_squared_error(y3, preds))167rms # RMSE for preds for Dec4 data set 2.8351168# Testing and Predicting for Dec 9 Data set169preds = lm.predict(X4) #X for Dec 9170# calc RMSE to compare preds vs y for Dec 9171rms = np.sqrt(mean_squared_error(y4, preds))...
dirgui.py
Source:dirgui.py
...56 except IndexError:57 pass58 main.robot_stop()59 self.forwards_left()60 def call_forwards(self):61 try:62 self.after_cancel(self._job)63 except IndexError:64 pass65 main.robot_stop()66 self.forwards()67 def call_forwards_right(self):68 try:69 self.after_cancel(self._job)70 except IndexError:71 pass72 main.robot_stop()73 self.forwards_right()74 def call_left(self):75 try:76 self.after_cancel(self._job)77 except IndexError:78 pass79 main.robot_stop()80 self.left()81 def call_right(self):82 try:83 self.after_cancel(self._job)84 except IndexError:85 pass86 main.robot_stop()87 self.right()88 def call_backwards_right(self):89 try:90 self.after_cancel(self._job)91 except IndexError:92 pass93 main.robot_stop()94 self.backwards_right()95 def call_backwards(self):96 try:97 self.after_cancel(self._job)98 except IndexError:99 pass100 main.robot_stop()101 self.backwards()102 def call_backwards_left(self):103 try:104 self.after_cancel(self._job)105 except IndexError:106 pass107 main.robot_stop()108 self.backwards_left()109 def forwards_left(self):110 arduino_data = self._get_arduino()111 if arduino_data is not None:112 compass = arduino_data[3]113 switch = arduino_data[-2]114 main.robot_forwards_left(compass, switch)115 self._job = self.after(64, self.forwards_left)116 def forwards(self):117 arduino_data = self._get_arduino()118 if arduino_data is not None:119 compass = arduino_data[3]120 switch = arduino_data[-2]121 main.robot_forwards(compass, switch)122 self._job = self.after(64, self.forwards)123 def forwards_right(self):124 arduino_data = self._get_arduino()125 if arduino_data is not None:126 compass = arduino_data[3]127 switch = arduino_data[-2]128 main.robot_forwards_right(compass, switch)129 self._job = self.after(64, self.forwards_right)130 def right(self):131 arduino_data = self._get_arduino()132 if arduino_data is not None:133 compass = arduino_data[3]134 switch = arduino_data[-2]135 main.robot_right(compass, switch)...
skip_list.py
Source:skip_list.py
1"""2 An implementation of skip list.3 The list stores positive integers without duplicates.4 跳表çä¸ç§å®ç°æ¹æ³ã5 跳表ä¸å¨åçæ¯æ£æ´æ°ï¼å¹¶ä¸å¨åçæ¯ä¸éå¤çã6 Author: Wenru7"""8from typing import Optional9import random10class ListNode:11 def __init__(self, data: Optional[int] = None):12 self._data = data13 self._forwards = [] # Forward pointers14class SkipList:15 _MAX_LEVEL = 1616 def __init__(self):17 self._level_count = 118 self._head = ListNode()19 self._head._forwards = [None] * type(self)._MAX_LEVEL20 def find(self, value: int) -> Optional[ListNode]:21 p = self._head22 for i in range(self._level_count - 1, -1, -1): # Move down a level23 while p._forwards[i] and p._forwards[i]._data < value:24 p = p._forwards[i] # Move along level25 26 return p._forwards[0] if p._forwards[0] and p._forwards[0]._data == value else None27 def insert(self, value: int):28 level = self._random_level()29 if self._level_count < level: self._level_count = level30 new_node = ListNode(value)31 new_node._forwards = [None] * level32 update = [self._head] * level # update is like a list of prevs33 p = self._head34 for i in range(level - 1, -1, -1):35 while p._forwards[i] and p._forwards[i]._data < value:36 p = p._forwards[i]37 38 update[i] = p # Found a prev39 for i in range(level):40 new_node._forwards[i] = update[i]._forwards[i] # new_node.next = prev.next41 update[i]._forwards[i] = new_node # prev.next = new_node42 43 def delete(self, value):44 update = [None] * self._level_count45 p = self._head46 for i in range(self._level_count - 1, -1, -1):47 while p._forwards[i] and p._forwards[i]._data < value:48 p = p._forwards[i]49 update[i] = p50 51 if p._forwards[0] and p._forwards[0]._data == value:52 for i in range(self._level_count - 1, -1, -1):53 if update[i]._forwards[i] and update[i]._forwards[i]._data == value:54 update[i]._forwards[i] = update[i]._forwards[i]._forwards[i] # Similar to prev.next = prev.next.next55 def _random_level(self, p: float = 0.5) -> int:56 level = 157 while random.random() < p and level < type(self)._MAX_LEVEL:58 level += 159 return level60 def __repr__(self) -> str:61 values = []62 p = self._head63 while p._forwards[0]:64 values.append(str(p._forwards[0]._data))65 p = p._forwards[0]66 return "->".join(values)67if __name__ == "__main__":68 l = SkipList()69 for i in range(10):70 l.insert(i)71 print(l)72 p = l.find(7)73 print(p._data)74 l.delete(3)...
跳表.py
Source:跳表.py
1from typing import Optional2import random3class ListNode:4 def __init__(self, data: Optional[int] = None):5 self._data = data6 self._forwards = [] # Forward pointers7class SkipList:8 _MAX_LEVEL = 169 def __init__(self):10 self._level_count = 111 self._head = ListNode()12 self._head._forwards = [None] * type(self)._MAX_LEVEL13 def find(self, value: int) -> Optional[ListNode]:14 p = self._head15 for i in range(self._level_count - 1, -1, -1): # Move down a level16 while p._forwards[i] and p._forwards[i]._data < value:17 p = p._forwards[i] # Move along level18 return p._forwards[0] if p._forwards[0] and p._forwards[0]._data == value else None19 def insert(self, value: int):20 level = self._random_level()21 if self._level_count < level: self._level_count = level22 new_node = ListNode(value)23 new_node._forwards = [None] * level24 update = [self._head] * level # update is like a list of prevs25 p = self._head26 for i in range(level - 1, -1, -1):27 while p._forwards[i] and p._forwards[i]._data < value:28 p = p._forwards[i]29 update[i] = p # Found a prev30 for i in range(level):31 new_node._forwards[i] = update[i]._forwards[i] # new_node.next = prev.next32 update[i]._forwards[i] = new_node # prev.next = new_node33 def delete(self, value):34 update = [None] * self._level_count35 p = self._head36 for i in range(self._level_count - 1, -1, -1):37 while p._forwards[i] and p._forwards[i]._data < value:38 p = p._forwards[i]39 update[i] = p40 if p._forwards[0] and p._forwards[0]._data == value:41 for i in range(self._level_count - 1, -1, -1):42 if update[i]._forwards[i] and update[i]._forwards[i]._data == value:43 update[i]._forwards[i] = update[i]._forwards[i]._forwards[44 i] # Similar to prev.next = prev.next.next45 def _random_level(self, p: float = 0.5) -> int:46 level = 147 while random.random() < p and level < type(self)._MAX_LEVEL:48 level += 149 return level50 def __repr__(self) -> str:51 values = []52 p = self._head53 while p._forwards[0]:54 values.append(str(p._forwards[0]._data))55 p = p._forwards[0]56 return "->".join(values)57if __name__ == "__main__":58 l = SkipList()59 for i in range(10):60 l.insert(i)61 print(l)62 p = l.find(7)63 print(p._data)64 l.delete(3)...
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!!