code
stringlengths 20
13.2k
| label
stringlengths 21
6.26k
|
---|---|
1 import sys
2 import ssl
3 import urllib
4 import matplotlib.pyplot as plt
5
6
7
8 def Parse_File(link):
9 context = ssl._create_unverified_context()
10 f = urllib.request.urlopen(link, context=context)
11 data = f.read().decode('utf-8').split('\n')
12 e = [i.split(',') for i in data[2:7]]
13 a = [i.split(',') for i in data[8:11]]
14 w = [i.split(',') for i in data[12:15]]
15
16 E = ['Education level']
17 A = ['Average monthly income']
18 W = ['Working environment']
19 lst = [E, A, W]
20
21 for index, cl in enumerate([e, a, w]):
22 total_pop = 0.0
23 x_tick = []
24 M = []
25 F = []
26 T = []
27 Non_smoke = []
28
29 for row in cl:
30 x_tick.append(row[0])
31 temp = list(map(float, row[1:]))
32 M.append(temp[1])
33 F.append(temp[3])
34 T.append(float("{0:.1f}".format((temp[0]*temp[1]+temp[2]*temp[3])/(temp[0]+temp[2]))))
35 Non_smoke.append(temp[0]*(1-temp[1]/100)+temp[2]*(1-temp[3]/100))
36 total_pop += (temp[0]*(1-temp[1]/100)+temp[2]*(1-temp[3]/100))
37 Non_smoke = [float("{0:.1f}".format(i/total_pop)) for i in Non_smoke]
38 lst[index].extend([x_tick, M, F, T, Non_smoke])
39
40 return E, A, W
41
42
43 def Data_Class(s):
44 assert s in ['E', 'A', 'W'], "Cannot find class type {} !".format(s)
45 data = []
46
47 if s == 'E':
48 data = E
49 elif s == 'A':
50 data = A
51 else:
52 data = W
53
54 return data
55
56
57 def Chart(s, data):
58 assert s in ['l', 'b', 'p'], "Cannot find chart type {} !".format(s)
59 n = len(data[1])
60 fig, ax = plt.subplots(figsize=(15, 8))
61 ax.set_xticks(range(n))
62 ax.set_xticklabels(data[1], ha='center')
63 ax.tick_params(labelsize=9)
64
65 if s == 'l':
66 ax.plot(range(n), data[2], marker='s', label='Male')
67 ax.plot(range(n), data[3], marker='o', label='Female')
68 ax.plot(range(n), data[4], marker='^', label='Total')
69 for pop in data[2:5]:
70 for i, j in zip(range(n), pop):
71 ax.text(i+0.1, j+0.1, str(j), ha='center', va='bottom', fontsize=10)
72 ax.set_title("Smoking Percentage vs {}".format(data[0]), fontsize=11)
73 ax.set_xlabel(data[0], fontsize=9)
74 ax.set_ylabel('Smoking Percentage (%)', fontsize=9)
75 ax.set_xlim([-0.5, n-0.5])
76 plt.legend(loc='upper right', prop={"size":10})
77 plt.show()
78
79 elif s == 'b':
80 width=0.15
81 rects1 = ax.bar([i-1.5*width for i in range(n)], data[2], width=width, label='Male', color='b')
82 rects2 = ax.bar([i-0.5*width for i in range(n)], data[3], width=width, label='Female', color='r')
83 rects3 = ax.bar([i+0.5*width for i in range(n)], data[4], width=width, label='Total', color='y')
84 for rects in [rects1, rects2, rects3]:
85 for rect in rects:
86 h = rect.get_height()
87 ax.text(rect.get_x()+rect.get_width()/2., 1.01*h, h,
88 ha='center', va='bottom', fontsize=10)
89 ax.set_title("Smoking Percentage vs {}".format(data[0]), fontsize=11)
90 ax.set_xlabel(data[0], fontsize=9)
91 ax.set_ylabel('Smoking Percentage (%)', fontsize=9)
92 ax.set_xlim([-0.5, n-0.5])
93 plt.legend(loc='upper right', prop={"size":10})
94 plt.show()
95
96 else:
97 ax.pie(data[5], labels=data[1], autopct='%1.1f%%',)
98 ax.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
99 ax.set_title("Proportion of different {} in non-smoking population".format(data[0]), fontsize=11, y=1.08)
100 plt.show()
101
102
103
104 if __name__ == '__main__':
105 link = "https://ceiba.ntu.edu.tw/course/481ea4/hw1_data.csv"
106 E, A, W = Parse_File(link)
107
108 for arg in sys.argv[1:]:
109 if arg.startswith('-'):
110 arg = arg[1:]
111 cl = Data_Class(arg[0])
112 Chart(arg[1], cl)
113
| 86 - warning: bad-indentation
87 - warning: bad-indentation
8 - refactor: too-many-locals
8 - warning: redefined-outer-name
16 - warning: redefined-outer-name
17 - warning: redefined-outer-name
18 - warning: redefined-outer-name
21 - warning: redefined-outer-name
9 - warning: protected-access
10 - refactor: consider-using-with
48 - error: possibly-used-before-assignment
50 - error: possibly-used-before-assignment
52 - error: possibly-used-before-assignment
60 - warning: unused-variable
|
1 #! /usr/bin/env python3
2 import psycopg2
3 import time
4 def connects():
5 return psycopg2.connect("dbname=news")
6
7 data1="select title,views from article_view limit 3"
8 data2="select * from author_view"
9 data3="select to_char(date,'Mon DD,YYYY') as date,err_prc from err_perc where err_prc>1.0"
10
11 def popular_article(data1):
12 db=connects()
13 c=db.cursor()
14 c.execute(data1)
15 results=c.fetchall()
16 for result in range(len(results)):
17 title=results[result][0]
18 views=results[result][1]
19 print("%s--%d" % (title,views))
20 db.close()
21
22 def popular_authors(data2):
23 db=connects()
24 c=db.cursor()
25 c.execute(data2)
26 results=c.fetchall()
27 for result in range(len(results)):
28 name=results[result][0]
29 views=results[result][1]
30 print("%s--%d" % (name,views))
31 db.close()
32
33 def error_percent(query3):
34 db=connects()
35 c=db.cursor()
36 c.execute(data3)
37 results=c.fetchall()
38 for result in range(len(results)):
39 date=results[result][0]
40 err_prc=results[result][1]
41 print("%s--%.1f %%" %(date,err_prc))
42
43 if __name__ == "__main__":
44 print("THE LIST OF POPULAR ARTICLES ARE:")
45 popular_article(data1)
46 print("\n")
47 print("THE LIST OF POPULAR AUTHORS ARE:")
48 popular_authors(data2)
49 print("\n")
50 print("PERC ERROR MORE THAN 1.0:")
51 error_percent(data3)
52
| 44 - warning: bad-indentation
45 - warning: bad-indentation
46 - warning: bad-indentation
47 - warning: bad-indentation
48 - warning: bad-indentation
49 - warning: bad-indentation
50 - warning: bad-indentation
51 - warning: bad-indentation
11 - warning: redefined-outer-name
22 - warning: redefined-outer-name
33 - warning: unused-argument
3 - warning: unused-import
|
1 import requests
2 from bs4 import BeautifulSoup
3
4 response = requests.get(
5 url="https://en.wikipedia.org/wiki/Toronto_Stock_Exchange",
6 )
7 soup = BeautifulSoup(response.content, 'html.parser')
8
9 table = soup.find_all('table')
10 print(table) | 4 - warning: missing-timeout
|
1 from tkinter import ttk
2 from tkinter import *
3
4 import sqlite3
5
6 class Product:
7
8 db_name = 'matricula.db'
9
10 def __init__(self, box):
11 self.box=box
12 self.box.title('Registro De Estudiante')
13
14 frame = LabelFrame(self.box, text='Datos del estudiante')
15 frame.grid(row = 0, column = 0, columnspan= 3, pady= 20)
16
17 #Espacio nombres
18
19 Label(frame, text= 'Nombres y apellidos: ').grid(row = 1, column = 0)
20 self.nombre = Entry (frame)
21 self.nombre.focus()
22 self.nombre.grid(row = 1, column = 1)
23
24 #Espacio edad
25 Label(frame, text='NuCedula: ').grid(row=2,column=0)
26 self.edad=Entry (frame)
27 self.edad.grid(row=2,column=1)
28
29 #Espacio Cedula
30 Label(frame, text='Direccion: ').grid(row=3, column= 0)
31 self.cedula = Entry(frame)
32 self.cedula.grid(row=3, column=1)
33
34 #Espacio Celular
35 Label(frame, text='NuTelular: ').grid(row=4, column=0)
36 self.celular = Entry(frame)
37 self.celular.grid(row=4, column=1)
38
39 #Boton agregar
40 ttk.Button(frame,text='Registrar').grid(row = 5,column = 0, columnspan=3, sticky = W+E)
41 #mensaje
42
43 self.menssage = Label(text='',fg='red')
44 self.menssage.grid(row=3,column=0,columnspan=2,sticky=W+E)
45
46 #Tabla
47 self.tree = ttk.Treeview(height = 10,column= ('#1', '#2', '#3'))
48 self.tree.grid(row= 4, column= 0, columnspan=3)
49 self.tree.heading("#0", text = 'Nombre y Apellido', anchor = CENTER)
50 self.tree.heading("#1", text= 'NUmero de Cedula', anchor= CENTER)
51 self.tree.heading("#2", text= 'Direccion', anchor= CENTER)
52 self.tree.heading("#3", text= 'Numero de Telefono', anchor= CENTER)
53 #botones
54 ttk.Button(text='Eliminar').grid(row=5,column=0,sticky=W+E)
55 ttk.Button(text='Editar').grid(row=5, column=2,sticky=W+E)
56
57 self.get_Estudiante()
58
59 #conecto la base de datos
60 def run_query(self, query, parameters=()):
61 with sqlite3.connect(self.db_name) as conn:
62 cursor = conn.cursor()
63 result = cursor.execute(query, parameters)
64 conn.commit()
65 return result
66
67 #Metodo Onbtner estudiante
68 def get_estudiante(self):
69 #limpiar
70 records = self.tree.get_children()
71 for element in records:
72 self.tree.delete(element)
73
74 #consultar datos
75 query = 'SELC * FROM Estudiante ORDER BY name DESC'
76 db_rows = self.run_query(query)
77 #Rellenar datos
78 for row in db_rows:
79 self.tree.insert('',0,txt= row[1], values= row[3])
80
81
82
83
84
85
86 if __name__ == '__main__':
87 box = Tk()
88 sistema = Product(box)
89 box.mainloop() | 2 - warning: wildcard-import
10 - warning: redefined-outer-name
57 - error: no-member
2 - warning: unused-wildcard-import
|
1 import tweepy
2 from tweepy import OAuthHandler
3 import re
4
5 class TwitterClient(object):
6 '''
7 Twitter Class for grabbing Tweets
8 '''
9 def __init__(self):
10 '''
11 Initialization Method
12 '''
13 #Keys and Tokens from the Twitter Dev Console
14 consumer_key = 'osoPe1vbrjL6hi83pPaT99JcZ'
15 consumer_secret = '72ePjiWIu8YGRFSTXJdUiww12J6UcR0bJL556VSx73hfd7dwW0'
16 access_token = '1038587928967098368-uX8QbeIua1pXU33gzB5Tcy89qMPrgt'
17 access_token_secret = 'AohvvdBfkYILiwEouMpAfyVDP2TBX6xdLcmfyvAJqojcj'
18
19 #Attempt Authentication
20 try:
21 #Create OAuthhandler object
22 self.auth = OAuthHandler(consumer_key,consumer_secret)
23 #Set access token and secret
24 self.auth.set_access_token(access_token,access_token_secret)
25 #Create tweepy API object to fetch tweets
26 self.api = tweepy.API(self.auth)
27 except:
28 print("Error Authentication Failed")
29
30 def clean_tweet(self, tweet):
31 '''
32 Utility function to clean tweet text by removing links, special characters
33 using simple regex statements
34 '''
35 return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", tweet).split())
36
37 def get_tweets(self, query, count = 1):
38 '''
39 Main Function to fetch tweets and parse them
40 '''
41 #Empty list to store parsed tweets
42 tweets = []
43
44 try:
45 #call twitter api to fetch tweets
46 fetch_tweets = self.api.search(q=query,count = count)
47
48 #parsing tweets one by one
49 for tweet in fetch_tweets:
50 print(tweet)
51 #empty dictionary to store required params of tweet
52 parsed_tweet = {}
53
54 #saving text of tweet
55 parsed_tweet['text'] = tweet.text
56
57 #appending parsed tweet to tweets list
58 if tweet.retweet_count > 0:
59 #if tweet has a retweet, ensure that is is append only once.
60 if parsed_tweet not in tweets:
61 tweets.append(parsed_tweet)
62 else:
63 tweets.append(parsed_tweet)
64
65 #return parsed tweet
66 return tweets
67 except tweepy.TweepError as e:
68 #print error
69 print("Error : " + str(e))
70
71 def main():
72 #Creating Object of twitter client class
73 api = TwitterClient()
74 #calling function to get tweets
75 tweets = api.get_tweets(query = 'Cryptocurrency', count = 1)
76
77 #print tweets
78 print(tweets)
79
80 #running program
81 main() | 35 - warning: anomalous-backslash-in-string
35 - warning: anomalous-backslash-in-string
35 - warning: anomalous-backslash-in-string
35 - warning: anomalous-backslash-in-string
5 - refactor: useless-object-inheritance
27 - warning: bare-except
37 - refactor: inconsistent-return-statements
|
1 import torch
2 import pytest
3 import numpy as np
4 import torch.nn as nn
5 from torch.utils.data import TensorDataset, DataLoader
6
7 from torchensemble import FastGeometricClassifier as clf
8 from torchensemble import FastGeometricRegressor as reg
9 from torchensemble.utils.logging import set_logger
10
11
12 set_logger("pytest_fast_geometric")
13
14
15 # Testing data
16 X_test = torch.Tensor(np.array(([0.5, 0.5], [0.6, 0.6])))
17
18 y_test_clf = torch.LongTensor(np.array(([1, 0])))
19 y_test_reg = torch.FloatTensor(np.array(([0.5, 0.6])))
20 y_test_reg = y_test_reg.view(-1, 1)
21
22
23 # Base estimator
24 class MLP_clf(nn.Module):
25 def __init__(self):
26 super(MLP_clf, self).__init__()
27 self.linear1 = nn.Linear(2, 2)
28 self.linear2 = nn.Linear(2, 2)
29
30 def forward(self, X):
31 X = X.view(X.size()[0], -1)
32 output = self.linear1(X)
33 output = self.linear2(output)
34 return output
35
36
37 class MLP_reg(nn.Module):
38 def __init__(self):
39 super(MLP_reg, self).__init__()
40 self.linear1 = nn.Linear(2, 2)
41 self.linear2 = nn.Linear(2, 1)
42
43 def forward(self, X):
44 X = X.view(X.size()[0], -1)
45 output = self.linear1(X)
46 output = self.linear2(output)
47 return output
48
49
50 def test_fast_geometric_workflow_clf():
51 """
52 This unit test checks the error message when calling `predict` before
53 calling `ensemble`.
54 """
55 model = clf(estimator=MLP_clf, n_estimators=2, cuda=False)
56
57 model.set_optimizer("Adam")
58
59 # Prepare data
60 test = TensorDataset(X_test, y_test_clf)
61 test_loader = DataLoader(test, batch_size=2, shuffle=False)
62
63 # Training
64 with pytest.raises(RuntimeError) as excinfo:
65 model.evaluate(test_loader)
66 assert "Please call the `ensemble` method to build" in str(excinfo.value)
67
68
69 def test_fast_geometric_workflow_reg():
70 """
71 This unit test checks the error message when calling `predict` before
72 calling `ensemble`.
73 """
74 model = reg(estimator=MLP_reg, n_estimators=2, cuda=False)
75
76 model.set_optimizer("Adam")
77
78 # Prepare data
79 test = TensorDataset(X_test, y_test_reg)
80 test_loader = DataLoader(test, batch_size=2, shuffle=False)
81
82 # Training
83 with pytest.raises(RuntimeError) as excinfo:
84 model.evaluate(test_loader)
85 assert "Please call the `ensemble` method to build" in str(excinfo.value)
| 4 - refactor: consider-using-from-import
26 - refactor: super-with-arguments
39 - refactor: super-with-arguments
|
1 import os
2 import time
3 import logging
4
5
6 def set_logger(log_file=None, log_console_level="info", log_file_level=None):
7 """Bind the default logger with console and file stream output."""
8
9 def _get_level(level):
10 if level.lower() == 'debug':
11 return logging.DEBUG
12 elif level.lower() == 'info':
13 return logging.INFO
14 elif level.lower() == 'warning':
15 return logging.WARN
16 elif level.lower() == 'error':
17 return logging.ERROR
18 elif level.lower() == 'critical':
19 return logging.CRITICAL
20 else:
21 msg = (
22 "`log_console_level` must be one of {{DEBUG, INFO,"
23 " WARNING, ERROR, CRITICAL}}, but got {} instead."
24 )
25 raise ValueError(msg.format(level.upper()))
26
27 _logger = logging.getLogger()
28
29 # Reset
30 for h in _logger.handlers:
31 _logger.removeHandler(h)
32
33 rq = time.strftime('%Y_%m_%d_%H_%M', time.localtime(time.time()))
34 log_path = os.path.join(os.getcwd(), 'logs')
35
36 ch_formatter = logging.Formatter(
37 "%(asctime)s - %(levelname)s: %(message)s"
38 )
39 ch = logging.StreamHandler()
40 ch.setLevel(_get_level(log_console_level))
41 ch.setFormatter(ch_formatter)
42 _logger.addHandler(ch)
43
44 if log_file is not None:
45 print('Log will be saved in \'{}\'.'.format(log_path))
46 if not os.path.exists(log_path):
47 os.mkdir(log_path)
48 print('Create folder \'logs/\'')
49 log_name = os.path.join(log_path, log_file + '-' + rq + '.log')
50 print('Start logging into file {}...'.format(log_name))
51 fh = logging.FileHandler(log_name, mode='w')
52 fh.setLevel(
53 logging.DEBUG
54 if log_file_level is None
55 else _get_level(log_file_level)
56 )
57 fh_formatter = logging.Formatter(
58 "%(asctime)s - %(filename)s[line:%(lineno)d] - "
59 "%(levelname)s: %(message)s"
60 )
61 fh.setFormatter(fh_formatter)
62 _logger.addHandler(fh)
63 _logger.setLevel("DEBUG")
64
65 return _logger
| 10 - refactor: no-else-return
|
1 #!/usr/bin/env python
2 from distutils.core import setup
3
4 setup(name='fv-sectools',
5 description='A set of IP-based security checks for websites and applications',
6 long_description=open('README.rst').read(),
7 version='0.1dev',
8 author='F Vicaria',
9 author_email='fvicaria@hotmail.com',
10 url='http://www.vicaria.org/',
11 packages=['fv-sectools', ],
12 python_requires='>=3.6',
13 license='MIT License',
14 platforms=['Windows']
15 )
| 2 - warning: deprecated-module
6 - refactor: consider-using-with
6 - warning: unspecified-encoding
|
1 class Murphy():
2 '''The Murphy Object represents a bed assembly at a particular angle'''
3 learning_rate = -.2
4 threshold = .001
5 def __init__(self, bedframe, A_link, B_link):
6 ''' Basic structure'''
7 self.bedframe = bedframe
8 self.A = A_link
9 self.B = B_link
10
11 @property
12 def ikea_error(self):
13 '''The total difference between actual positions and intended positions for fixed, rigid components.'''
14 return sum([component.ikea_error for component in [self.A, self.B]])
15
16 def plot(self):
17 ax = plt.figure().add_subplot(111)
18 ax.set_aspect('equal')
19 for component in [self.bedframe, self.A, self.B]:
20 ax = component.plot(ax)
21 ax.set_title(round(self.ikea_error,2))
22 plt.show()
23
24 def assemble(self, plot_here = False):
25 ''' For a given structure and bed angle, adjust link angles and bed (x,y) to minimize ikea error.'''
26 # loop over the following variables, making small adjustments until ikea error is minimized (ideally zero):
27 # [bedframe.x, bedframe.y, A_link.angle, B_link.angle, C_link.angle]
28 # Note: it is necessary to reposition C_link (x,y) to B_link.distal after B_link.angle is adjusted.
29 # while True:
30 for i in range(1000):
31 for variable in ['A.angle', 'B.angle', 'bedframe.x', 'bedframe.y']:
32 errors = []
33 for step in ['+=0.5', '-=1']:
34 exec('self.{variable} {step}'.format(variable = variable, step = step))
35 errors.append(self.ikea_error)
36 partial_derivative = errors[0]-errors[1]
37 adjustment = self.learning_rate*partial_derivative + .5
38 exec('self.{variable} += {adjustment}'.format(variable = variable, adjustment = adjustment))
39 if (i%5000==0) and plot_here:
40 self.plot()
41 if self.ikea_error < 0.125: break
42 # print('Assembled in {} steps with Ikea error {}'.format(i,round(self.ikea_error,3)))
43 if plot_here: self.plot()
| 14 - refactor: consider-using-generator
17 - error: undefined-variable
22 - error: undefined-variable
34 - warning: exec-used
38 - warning: exec-used
|
1 import numpy as np
2 from math import radians, sin, cos
3 import matplotlib.pyplot as plt
4 from sklearn.linear_model import LinearRegression as LR
5
6 class Bedframe():
7 def __init__(self, x,y, thickness, length, margin, angle):
8 '''Design elements'''
9 self.t = thickness
10 self.l = length
11 self.margin = margin # the distance from the edges to the point where a link can be connected
12
13 '''Current Position'''
14 self.x, self.y = x,y
15 '''Angle in degrees, 0 is deployed, 90 is stowed'''
16 self.angle = angle
17
18 @property
19 def lower_foot(self):
20 theta = radians(self.angle)
21 return self.x + self.l*cos(theta), self.y + self.l*sin(theta)
22
23 @property
24 def upper_foot(self):
25 theta = radians(self.angle)
26 x = self.x + self.l*cos(theta) - self.t*sin(theta)
27 y = self.y + self.l*sin(theta) + self.t*cos(theta)
28 return x, y
29
30 @property
31 def lower_head(self):
32 return self.x, self.y
33
34 @property
35 def upper_head(self):
36 theta = radians(self.angle)
37 x = self.x - self.t*sin(theta)
38 y = self.y + self.t*cos(theta)
39 return x,y
40
41 @property
42 def left_edge(self):
43 return min(self.lower_foot[0], self.lower_head[0], self.upper_foot[0], self.upper_head[0])
44
45 @property
46 def right_edge(self):
47 return max(self.lower_foot[0], self.lower_head[0], self.upper_foot[0], self.upper_head[0])
48
49 @property
50 def top(self):
51 return max(self.lower_foot[1], self.lower_head[1], self.upper_foot[1], self.upper_head[1])
52
53 @property
54 def bottom(self):
55 return min(self.lower_foot[1], self.lower_head[1], self.upper_foot[1], self.upper_head[1])
56
57 def _offset_point(self, p, p1, p2, offset):
58 x, y = p
59 x1, y1, = p1
60 x2, y2 = p2
61
62 #vector1
63 d1 = (((x1-x)**2 + (y1-y)**2)**.5)/offset
64 v1 = (x1-x)/d1, (y1-y)/d1
65
66 #vector from (x,y) to (x2,y2)
67 d2 = (((x2-x)**2 + (y2-y)**2)**.5)/offset
68 v2 = (x2-x)/d2, (y2-y)/d2
69
70 return x + v1[0] + v2[0], y + v1[1] + v2[1]
71
72
73 @property
74 def head_lower_margin(self):
75 return self._offset_point(self.lower_head, self.lower_foot, self.upper_head, self.margin)
76
77 @property
78 def head_upper_margin(self):
79 return self._offset_point(self.upper_head, self.lower_head, self.upper_foot, self.margin)
80
81 @property
82 def foot_lower_margin(self):
83 return self._offset_point(self.lower_foot, self.upper_foot, self.lower_head, self.margin)
84
85 @property
86 def foot_upper_margin(self):
87 return self._offset_point(self.upper_foot, self.upper_head, self.lower_foot, self.margin)
88
89
90
91 # @property
92 # def floor_opening(self):
93 # if (self.bottom >= 0) or (self.top <= 0):
94 # return 0
95
96 # #topside
97 # if np.sign(self.upper_head[1]) == np.sign(self.upper_foot[1]):
98 # topside = 0
99 # else:
100 # ys = np.array([[self.upper_head[1]], [self.upper_head[1]])
101 # xs = np.array([[self.upper_head[0]],[self.lower_head[0]]])
102 # topside = LR().fit(ys, xs).predict([[0]])[0]
103
104
105 def plot(self, ax = None):
106 color = 'k'
107 plot_here = False
108 if not ax:
109 ax = plt.figure().add_subplot(111)
110 ax.set_aspect('equal')
111 plot_here = True
112
113 xs = [self.lower_head[0], self.lower_foot[0], self.upper_foot[0], self.upper_head[0], self.lower_head[0]]
114 ys = [self.lower_head[1], self.lower_foot[1], self.upper_foot[1], self.upper_head[1], self.lower_head[1]]
115 ax.plot(xs, ys, color = color)
116
117 bounding_xs = [self.left_edge, self.right_edge, self.right_edge, self.left_edge, self.left_edge]
118 bounding_ys = [self.bottom, self.bottom, self.top, self.top, self.bottom]
119
120 ax.plot(bounding_xs, bounding_ys, color = 'gray')
121
122 ax.scatter(self.head_lower_margin[0], self.head_lower_margin[1])
123 ax.scatter(self.head_upper_margin[0], self.head_upper_margin[1])
124 ax.scatter(self.foot_upper_margin[0], self.foot_upper_margin[1])
125 ax.scatter(self.foot_lower_margin[0], self.foot_lower_margin[1])
126 # # ax.scatter(self.CoG[0], self.CoG[1], marker = 'X', color = color)
127 # # ax.scatter(self.floor_opening, 0, marker = 'o', color = color)
128 # ax.plot([self.extents['left'], self.extents['right'], self.extents['right'], self.extents['left'], self.extents['left']],
129 # [self.extents['bottom'], self.extents['bottom'], self.extents['top'], self.extents['top'], self.extents['bottom']],
130 # alpha = .1, color = color)
131 if plot_here: plt.show()
132 return ax
133
134
135 if __name__ == '__main__':
136 b = Bedframe(0,0, 15, 80, 2, 10)
137 b.plot()
138 plt.show()
139
| 7 - refactor: too-many-arguments
7 - refactor: too-many-positional-arguments
1 - warning: unused-import
4 - warning: unused-import
|
1
2 from math import sin, cos, radians, atan
3 import numpy as np
4 import matplotlib.pyplot as plt
5
6 class Link():
7 def __init__(self, x, y, length, width, angle, color, bedframe, attachment = None):
8 self.x, self.y = x, y
9 self.length, self.width = length, width
10 self.angle = angle
11 self.color = color
12 self.bedframe = bedframe
13 # Attachment point relative to the bedframe
14 self.attachment = {'x':attachment[0],'y':attachment[1]}
15
16 @property
17 def room_attachment(self):
18 # attachment point relative to the room
19 if self.attachment:
20 theta = radians(self.bedframe.angle)
21 l = ((self.attachment['x']**2)+(self.attachment['y']**2))**0.5
22 phi = atan(self.attachment['y']/self.attachment['x'])
23 x = self.bedframe.x + l*cos(theta + phi)
24 y = self.bedframe.y + l*sin(theta + phi)
25 return {'x':x, 'y':y}
26 else: return None
27
28 @property
29 def distal(self):
30 x, y, l, theta = self.x, self.y, self.length, radians(self.angle)
31 X = x + l * cos(theta)
32 Y = y + l * sin(theta)
33 return X,Y
34
35 @property
36 def edges(self):
37 x,y,w, theta = self.x, self.y, self.width/2, radians(self.angle)
38 X,Y = self.distal
39 x0 = x - w*sin(theta)
40 x1 = X - w*sin(theta)
41 y0 = y + w*cos(theta)
42 y1 = Y + w*cos(theta)
43
44 X0 = x + w*sin(theta)
45 X1 = X + w*sin(theta)
46 Y0 = y - w*cos(theta)
47 Y1 = Y - w*cos(theta)
48 return [((x0, y0), (x1, y1)), ((X0, Y0), (X1, Y1))]
49
50 @property
51 def extents(self):
52 left = min(self.x, self.distal[0]) - self.width/2
53 right = max(self.x, self.distal[0]) + self.width/2
54 top = max(self.y, self.distal[1]) + self.width/2
55 bottom = min(self.y, self.distal[1]) - self.width/2
56 return {'left':left, 'right':right, 'top':top, 'bottom':bottom}
57
58 @property
59 def floor_opening(self):
60 w = r = self.width/2
61 theta = radians(self.angle)
62 x,y = self.x, self.y
63 X,Y = self.distal
64
65 if abs(self.y) < r:
66 a0 = self.x + ((r**2)-(self.y)**2)**0.5
67 else:
68 a0 = 0
69 if abs(self.distal[1]) < w:
70 a1 = self.distal[0] + ((r**2)-self.distal[1]**2)**0.5
71 else:
72 a1 = 0
73 if y * Y < 0:
74 a2 = x - y*(X-x)/(Y-y) + abs(w/sin(theta))
75 else: a2 = 0
76
77 return max(a0,a1,a2)
78
79 @property
80 def CoG(self):
81 return (self.x+self.distal[0])/2, (self.y+self.distal[1])/2
82
83 @property
84 def ikea_error(self):
85 '''Ikea error is the assembly error, or the distance from the distal point of a link to its intended attachment point'''
86 if self.attachment:
87 fit_error = ((self.distal[0]-self.room_attachment['x'])**2+(self.distal[1]-self.room_attachment['y'])**2)
88 else: fit_error = 0
89 return fit_error
90
91 def plot(self, ax = None):
92 plot_here = False
93 if not ax:
94 ax = plt.figure().add_subplot(111)
95 ax.set_aspect('equal')
96 plot_here = True
97
98 r = self.width/2
99 for edge in self.edges:
100 ax.plot([edge[0][0],edge[1][0]], [edge[0][1], edge[1][1]], c = self.color)
101
102 for x,y in zip([self.x,self.distal[0]], [self.y,self.distal[1]]):
103 phi = np.radians(np.linspace(0,360,37))
104 ax.plot(r*np.cos(phi)+x, r*np.sin(phi)+y, c = self.color )
105
106 # Extents Box
107 ax.plot([self.extents['left'], self.extents['right'], self.extents['right'], self.extents['left'], self.extents['left']],
108 [self.extents['bottom'], self.extents['bottom'], self.extents['top'], self.extents['top'], self.extents['bottom']],
109 alpha = .1, c = self.color)
110
111 # Floor Opening Point
112 ax.scatter(self.floor_opening, 0, c=self.color)
113
114 # Attachment Point
115 if self.attachment:
116 ax.scatter(self.room_attachment['x'], self.room_attachment['y'], marker = 'x', c = self.color)
117 ax.plot([self.distal[0], self.room_attachment['x']], [self.distal[1], self.room_attachment['y']], c = self.color, linestyle = 'dashed')
118
119 if plot_here: plt.show()
120 return ax
| 6 - refactor: too-many-instance-attributes
7 - refactor: too-many-arguments
7 - refactor: too-many-positional-arguments
19 - refactor: no-else-return
|
1 class Point:
2 def __init__(self, x, y):
3 self.x = x
4 self.y = y
5
6 def distance(self, other):
7 if isinstance(other, Point):
8 return self._distance_to_point(other)
9 elif isinstance(other, LineSegment):
10 return self._distance_to_line(other)
11 else:
12 raise Exception
13
14 def _distance_to_point(self, other):
15 return ((self.x-other.x)**2+(self.y-other.y)**2)**.5
16
17 def _distance_to_line(self, line):
18 x,y = self.x, self.y
19 x1, y1 = line.point1.x, line.point1.y
20 x2, y2 = line.point2.x, line.point2.y
21
22 numerator = abs((y2-y1)*x-(x2-x1)*y + x2*y1 - y2*x1)
23 denominator = ((y2-y1)**2 + (x2-x1)**2)**.5
24
25 return numerator/denominator
26
27 def __sub__(self, other):
28 x = self.x - other.x
29 y = self.y - other.y
30 return Point(x,y)
31
32 def __add__(self, other):
33 x = self.x + other.x
34 y = self.y + other.y
35 return Point(x,y)
36
37 def __isub__(self, other):
38 self.x -= other.x
39 self.y -= other.y
40 return self
41
42 def __iadd__(self, other):
43 self.x += other.x
44 self.y += other.y
45 return self
46
47 def __repr__(self):
48 return f'{self.x},{self.y}'
49
50
51 def is_between_lines(self, line1, line2):
52 '''Yields true if the point is in the interior of the rectangle
53 defined by the two parallel, flush, lines'''
54 pass
55
56
57 class LineSegment:
58 def __init__(self, p0, p1):
59 points = list(set([p0, p1]))
60
61 self.p0 = points[0]
62 self.p1 = points[1]
63
64 @property
65 def length(self):
66 return self.p0.distance(self.p1)
67
68 def distance_to_point(self, point):
69 return point.distance(self)
70
71 def __add__(self, point):
72 p0 = self.p0 + point
73 p1 = self.p1 + point
74 return LineSegment(p0, p1)
75
76 def __sub__(self, point):
77 p0 = self.p0 - point
78 p1 = self.p1 - point
79 return LineSegment(p0, p1)
80
81 def __iadd__(self, point):
82 self.p0, self.p1 = self.p0 + point, self.p1 + point
83
84 def __isub__(self, point):
85 self.p0, self.p1 = self.p0 - point, self.p1 - point
86
87 def __repr__(self):
88 return f'({self.p0})<-->({self.p1})'
89
| 7 - refactor: no-else-return
12 - warning: broad-exception-raised
54 - warning: unnecessary-pass
|
1 from math import cos, sin, tan, atan, radians
2 import matplotlib.pyplot as plt
3 import numpy as np
4 from copy import deepcopy
5 from Murphy.link import Link
6 from Murphy.bedframe import Bedframe
7 from Murphy.murphy import Murphy
8 import sys
9 import pickle
10
11 class MurphyBed():
12 '''The MurphyBed Class represents a collection of Murphy objects, all of the same design, solved over the full range of angles from deployed (0) to stowed (90)'''
13 def __init__(self, bed, desired_deployed_height, desired_stowed_height):
14 self.bed = bed
15 self.desired_deployed_height, self.desired_stowed_height = desired_deployed_height, desired_stowed_height
16 self.collected_solutions = {}
17
18 def solve_over_full_range(self, steps):
19 for angle in np.linspace(0,90, steps):
20 self.bed.bedframe.angle = angle
21 self.bed.assemble()
22 self.collected_solutions[angle] = deepcopy(self.bed)
23
24 @property
25 def murphy_error(self):
26 '''murphy_error is the sum of all differences between current design and optimal design. Used to optimize fixed, positions and rigid components.
27 Calculation of Murphy Error requires collected_solutions for all angles between 0 and 90'''
28 deployed = self.collected_solutions[0]
29 stowed = self.collected_solutions[90]
30 errors = []
31
32 balance = np.array([5, 7, 2, 1, 1, 1, 50, 50, 1, 1,1])
33
34 # When deployed, the bed should be at desired height
35 errors.append((deployed.bedframe.y+deployed.bedframe.t-self.desired_deployed_height)**2)
36
37 # When deployed, the head of the bed should be close to the wall
38 errors.append(deployed.bedframe.x**2)
39
40 # When stowed, the bed should be flat up against the wall
41 errors.append((stowed.bedframe.x-stowed.bedframe.h_headboard)**2)
42
43 # When stowed, the foot of the bed should be at desired height below the window
44 errors.append((stowed.bedframe.y+stowed.bedframe.l - self.desired_stowed_height)**2)
45
46 # No part of the assembly should ever extend outside of the house
47 left_most = 0
48 for murphy in self.collected_solutions.values():
49 for component in [murphy.bedframe, murphy.A, murphy.B]:
50 left_most = min(left_most, component.extents['left'])
51
52 errors.append(left_most**2)
53
54 # when stowed, no part of the links should extend forward of the bedframe if it is above the floor
55 def stowed_encroachment(link):
56 if (link.extents['top'] > 0) and (link.extents['right'] > stowed.bedframe.x):
57 return (link.extents['right']-stowed.bedframe.x)**2
58 else: return 0
59
60 errors.append(max([stowed_encroachment(link) for link in [stowed.A, stowed.B]]))
61
62 # when deployed, no part of the links should extend above/forward of the bedframe
63 def deployed_encroachment(link):
64 if (link.extents['right'] > deployed.bedframe.x) and (link.extents['top'] > (deployed.bedframe.y+deployed.bedframe.t)):
65 return (link.extents['top'] - deployed.bedframe.y+deployed.bedframe.t)**2
66 else: return 0
67
68 errors.append(max([deployed_encroachment(link) for link in [deployed.A, deployed.B]]))
69
70 # the floor opening should not be much larger than the thickness of the beframe
71 floor_opening = 0
72 for murphy in self.collected_solutions.values():
73 for component in [murphy.bedframe, murphy.A, murphy.B]:
74 floor_opening = max(floor_opening, component.floor_opening)
75
76 if floor_opening > stowed.bedframe.x:
77 error = floor_opening**2
78 else:
79 error = 0
80 errors.append(error)
81
82 #the bed should be buildable
83 errors.append(max([i.ikea_error for i in self.collected_solutions.values()])**2)
84
85 # Link A,B Attachment point must be on the bedframe
86 for i in [self.bed.A, self.bed.B]:
87 x = i.attachment['x']
88 y = i.attachment['y']
89 if (0 < x < self.bed.bedframe.l) and (0 < y < self.bed.bedframe.t):
90 errors.append(0)
91 elif (0 < x < self.bed.bedframe.depth_of_headboard) and (0 < y < self.bed.bedframe.h_headboard):
92 errors.append(0)
93 else:
94 X,Y = self.bed.bedframe.CoG
95 errors.append((X-x)**2 + (Y-y)**2)
96
97 errors = (np.array(errors)/balance)
98
99 return errors.sum(), errors
100
101 def plot_all(murphy_bed):
102 ax = plt.figure().add_subplot(111)
103 for i in murphy_bed.collected_solutions.values():
104 for j in [i.bedframe, i.A, i.B]:
105 j.plot(ax)
106 plt.show()
107
108 def cycles(n=10):
109 if len(sys.argv) > 1:
110 try:
111 return int(sys.argv[1])
112 except:
113 pass
114 return n
115
116 def plot():
117 plt.plot(adjustments)
118 plt.show()
119 plt.plot(murphy_errors_history)
120 plt.show()
121 plot_all(murphy_bed)
122
123 if __name__ == '__main__':
124 angle_steps = 5
125 learning_rate = -.08
126 # The basic components of a bed
127 bedframe = Bedframe(10,4,10, 72, 12, 8)
128 A_link = Link(x=0,y=0,length=10,width=4,angle=80, color = 'r', bedframe = bedframe, attachment = (5,2))
129 B_link = Link(x=20, y = -1, length = 10, width = 4, angle = 110, color ='g', bedframe = bedframe, attachment = (18,2))
130
131 # A bed assembled at a single position
132 assembly = Murphy(bedframe, A_link, B_link)
133
134 # The complete solution of a bed from deployed to stowed
135 murphy_bed = MurphyBed(assembly, 15, 40)
136 # with open('murphy.pkl','rb') as f:
137 # murphy_bed = pickle.load(f)
138 murphy_bed.solve_over_full_range(angle_steps)
139 print('Initial Murphy Error: ', murphy_bed.murphy_error[0])
140
141 # initial_design = deepcopy(murphy_bed)
142
143 murphy_error_history = []
144 murphy_errors_history = []
145 adjustments = []
146
147 for i in range(cycles()):
148 print('#'*20+'\n'+str(i)+'\n'+'#'*20)
149 murphy_bed.bed = murphy_bed.collected_solutions[0]
150 variable = np.random.choice(np.array(['A.x','A.y', "A.attachment['x']", "A.attachment['y']", 'A.length', 'B.x','B.y','B.length', "B.attachment['x']", "B.attachment['y']"]))
151 print(variable)
152 errors = []
153 for step in ['+=0.5', '-=1']:
154 exec('murphy_bed.bed.{variable}{step}'.format(variable = variable, step=step))
155 murphy_bed.solve_over_full_range(angle_steps)
156 errors.append(murphy_bed.murphy_error[0])
157 partial_derivative = errors[0]-errors[1]
158 adjustment = partial_derivative*learning_rate + 0.5
159 exec('murphy_bed.bed.{variable}+={adjustment}'.format(variable = variable, adjustment = adjustment))
160 adjustments.append(adjustment)
161 murphy_bed.solve_over_full_range(angle_steps)
162 print('Adjusted Murphy Error: ', murphy_bed.murphy_error[0])
163 murphy_error_history.append(murphy_bed.murphy_error[0])
164 murphy_errors_history.append(murphy_bed.murphy_error[1])
165
166 if i%100==0:
167 with open('murphy.pkl', 'wb') as f:
168 pickle.dump(murphy_bed, f)
169
170 with open('murphy.pkl', 'wb') as f:
171 pickle.dump(murphy_bed, f)
172
173 plot() | 171 - warning: bad-indentation
25 - refactor: too-many-locals
30 - warning: redefined-outer-name
86 - warning: redefined-outer-name
56 - refactor: no-else-return
60 - refactor: consider-using-generator
64 - refactor: no-else-return
68 - refactor: consider-using-generator
83 - refactor: consider-using-generator
101 - warning: redefined-outer-name
103 - warning: redefined-outer-name
112 - warning: bare-except
117 - error: possibly-used-before-assignment
119 - error: possibly-used-before-assignment
121 - error: possibly-used-before-assignment
154 - warning: exec-used
159 - warning: exec-used
1 - warning: unused-import
1 - warning: unused-import
1 - warning: unused-import
1 - warning: unused-import
1 - warning: unused-import
|
1 str = input("Enter a string: ")
2
3 def Dictionary(i):
4 dictionary = {}
5 for letter in i:
6 dictionary[letter] = 1 + dictionary.get(letter, 0)
7 return dictionary
8
9
10 def most_frequent(str):
11 alphabets = [letter.lower() for letter in str if letter.isalpha()]
12 dictionary = Dictionary(alphabets)
13 result = []
14 for key in dictionary:
15 result.append((dictionary[key], key))
16 result.sort(reverse=True)
17 for frequency, letter in result:
18 print (letter, frequency)
19
20 most_frequent(str)
21
| 1 - warning: redefined-builtin
10 - warning: redefined-outer-name
|
1 from argparse import Namespace
2 import co2_dataset
3 import os
4 import time
5
6
7
8 # Settings
9 data_path = 'CO2/monthly_in_situ_co2_mlo.csv'
10 save_path = 'reg_params/params3'
11 epochs = 10000
12 minibatch_size = 100
13 mc_samples = 50
14 optimizer = 'adam'
15 learning_rate = 1e-1
16 momentum = 0.9
17 l2_weight = 1e-6
18 drop_p = 0.1
19 tau_rc = 0.07
20 tau_ref = 0.0005
21 amplitude = 0.01
22 train = False
23 continue_training = True
24 spiking = True
25 plot = True
26 comment = 'test run'
27
28 args = Namespace(data_path=data_path, epochs=epochs, minibatch_size=minibatch_size,
29 optimizer=optimizer, learning_rate=learning_rate, l2_weight=l2_weight, momentum=momentum,
30 mc_samples=mc_samples, tau_ref=tau_ref, tau_rc=tau_rc, train=train, continue_training=continue_training,
31 save_path=save_path, amplitude=amplitude, drop_p=drop_p, spiking=spiking, plot=plot)
32
33 print('########################')
34 print(comment) # a comment that will be printed in the log file
35 print(args) # print all args in the log file so we know what we were running
36 print('########################')
37
38
39 start = time.time()
40 loss = co2_dataset.main(args)
41 print("The training took {:.1f} minutes with a loss of {:.3f}".format((time.time()-start)/60,loss)) # measure time
| 3 - warning: unused-import
|
1 #!/usr/bin/python
2 '''
3 Apache log analysis script for Amazon Code challenge.
4 July 2nd 2016 by Fred McLain.
5 Copyright (C) 2016 Fred McLain, all rights reserved.
6
7 high level language of your choice (e.g. Python/Ruby/Perl)
8
9 The right fit language appears to be Python, so I'm going with that even though I'm a Java developer.
10
11 required:
12 * Top 10 requested pages and the number of requests made for each
13 * Percentage of successful requests (anything in the 200s and 300s range)
14 * Percentage of unsuccessful requests (anything that is not in the 200s or 300s range)
15 * Top 10 unsuccessful page requests
16 * The top 10 IPs making the most requests, displaying the IP address and number of requests made.
17 * Option parsing to produce only the report for one of the previous points (e.g. only the top 10 urls, only the percentage of successful requests and so on)
18 * A README file explaining how to use the tool, what its dependencies and any assumptions you made while writing it
19
20 optional:
21 * Unit tests for your code.
22 * The total number of requests made every minute in the entire time period covered by the file provided.
23 * For each of the top 10 IPs, show the top 5 pages requested and the number of requests for each.
24
25 Assumptions:
26 * Statistics for the number of pages and requesting IPs does not exceed available memory.
27 * Log file lines are of a uniform format
28 * Log records are in time order
29
30 Sample log lines:
31 10.0.68.207 - - [31/Oct/1994:14:00:17 +0000] "POST /finance/request.php?id=39319 HTTP/1.1" 200 56193
32 10.0.173.204 - - [31/Oct/1994:14:00:20 +0000] "GET /kernel/get.php?name=ndCLVHvbDM HTTP/1.1" 403 759
33
34 Records are new line separated.
35
36 Fields in record are whitespace separated:
37 IP - - [timestamp] "request path status ?
38 '''
39 from __future__ import division
40 import sys
41 from optparse import OptionParser
42
43 parser = OptionParser()
44 parser.add_option("-f", "--file", dest="fileName", help="file to parse, default=%default", metavar="FILE", default="apache.log")
45 parser.add_option("-a", "--reportAll", action="store_true", dest="reportAll", help="show all reports", default=False)
46 parser.add_option("-t", "--top10", action="store_true", dest="reportTop10", help="Top 10 requested pages and the number of requests made for each", default=False)
47 parser.add_option("-s", "--success", action="store_true", dest="reportSucccessPercentReq", help="Percentage of successful requests (anything in the 200s and 300s range)", default=False)
48 parser.add_option("-u", "--unsuccess", action="store_true", dest="reportUnsucccessPercentReq", help="Percentage of unsuccessful requests (anything that is not in the 200s or 300s range)", default=False)
49 parser.add_option("-r", "--top10Unsuccess", action="store_true", dest="reportTop10Unsuccess", help="Top 10 unsuccessful page requests", default=False)
50 parser.add_option("-i", "--top10IpPages", action="store_true", dest="reportTop10IpPages", help="The top 10 IPs making the most requests, displaying the IP address and number of requests made", default=False)
51 #parser.add_option("-m", "--numReqPerMinute", action="store_true", dest="reportReqPerMinute", help="The total number of requests made every minute in the entire time period covered by the file provided.", default=False)
52
53 (options, args) = parser.parse_args()
54
55 # accumulators for report stats
56 #totalRequests = 0
57 #requestMap = 0
58 #successCount = 0
59 #failCount = 0
60 errorList = []
61
62 totalPages = {}
63 failPages = {}
64 successPages = {}
65 ipPages={}
66
67 def analizeFile(fileName):
68 print "Parsing file:", fileName
69 try:
70 f = open(fileName)
71 except IOError:
72 errorList.append("Can not read " + fileName)
73 return
74 lineno = 0
75 for line in f:
76 lineno += 1
77 try:
78 analizeLine(line)
79 except:
80 errorList.append("Error in " + fileName + " on line " + str(lineno))
81 return
82
83 def analizeLine(logLine):
84 '''
85 Fields in record are whitespace separated:
86 IP - - [timestamp] "request path status ?
87 '''
88 # print logLine
89 r = logLine.split()
90 #print r
91 '''
92 0 = IP 3 = timestamp 4 = TZ 5 = method 6 = page 7 = protocol 8 = status 9 = ?
93 ['10.0.16.208', '-', '-', '[31/Oct/1994:23:59:50', '+0000]', '"GET', '/finance/list.php?value=60549', 'HTTP/1.0"', '404', '1595']
94 '''
95 ip = r[0]
96 timestamp = r[3].lstrip('[')
97 #timestamp = time.strptime(r[3].lstrip('['),"%d/%b/%Y:%H:%M:%S")
98 method = r[5].lstrip('"')
99 #page = r[6].split("?")[0]
100 page = r[6]
101 stat = int(r[8])
102
103 if page in totalPages:
104 totalPages[page] = totalPages[page] + 1
105 else:
106 totalPages.update({page:1})
107
108 if ip in ipPages:
109 ipPages[ip] = ipPages[ip] +1
110 else:
111 ipPages.update({ip:1})
112
113 if (stat >= 200) and (stat < 400):
114 # success
115 if page in successPages:
116 successPages[page] = successPages[page] + 1
117 else:
118 successPages.update({page:1})
119 else:
120 # failure
121 if page in failPages:
122 failPages[page] = failPages[page] + 1
123 else:
124 failPages.update({page:1})
125
126 return
127
128 def reportTop10(dict):
129 s=sorted(dict,key=dict.__getitem__,reverse=True)
130 i = 1
131 for k in s:
132 print i,k,dict[k]
133 if i == 10:
134 break
135 i += 1
136
137 def report():
138 if options.reportAll or options.reportTop10:
139 print "Most requested pages:"
140 reportTop10(totalPages)
141 ''' not in spec but useful?
142 print "Most successful pages (page, count):"
143 reportTop10(successPages)
144 '''
145 if options.reportAll or options.reportSucccessPercentReq:
146 # print len(successPages),"/",len(totalPages),len(failPages)
147 print "Percentage of successful requests: ",str(len(successPages)/len(totalPages)*100.),"%"
148
149 if options.reportAll or options.reportUnsucccessPercentReq:
150 print "Most failed pages (page, count):"
151 reportTop10(failPages)
152
153 if options.reportAll or options.reportTop10IpPages:
154 print "The top 10 IPs making the most requests, (IP, count)"
155 reportTop10(ipPages)
156 return
157
158 def usage():
159 parser.print_help()
160 exit(-1)
161 return
162
163 def go():
164 print "Apache log file parser demonstration by Fred McLain, July 2nd 2016"
165 if 1 == len(sys.argv):
166 usage() # require command line arguments or show usage and bail out
167 analizeFile(options.fileName)
168 report()
169 if len(errorList) > 0:
170 print "Errors in input",errorList
171 return
172
173 go()
| 68 - error: syntax-error
|
1 #!/usr/local/bin/python
2
3 from os.path import expanduser
4
5 execfile(expanduser('~/python/evm2003/brp/wizard.py')) | 5 - error: undefined-variable
|
1 basic.show_string("Think of a number between 1 to 10")
2 basic.show_string("Input your answer here")
3 input.button_is_pressed(Button.A)
4 basic.show_string("The answer was...")
5 basic.show_number(randint(1, 10))
| 1 - error: undefined-variable
2 - error: undefined-variable
3 - error: undefined-variable
4 - error: undefined-variable
5 - error: undefined-variable
5 - error: undefined-variable
|
1 import json
2 import codecs
3 import random
4 from sklearn.feature_extraction.text import CountVectorizer
5 from nltk.stem.snowball import SnowballStemmer
6 from sklearn.naive_bayes import MultinomialNB
7 import numpy as np
8 from sklearn import metrics
9 import numpy as np
10 from sklearn import svm
11 from sklearn.feature_extraction.text import TfidfVectorizer
12 from scipy.sparse import hstack
13 from nltk.tokenize import RegexpTokenizer
14 import pickle
15 import sys
16
17 def getclassmore(a):
18 if a>3: return a-2
19 elif a<3: return 0
20 else: return 1
21
22 def getclass(a):
23 if a>3:
24 return 2
25 elif a<3:
26 return 0
27 else:
28 return 1
29
30 def allupper(word):
31 for c in word:
32 if not(c.isupper()):
33 return False
34 return True
35
36 def cleandoc(doc):
37 global imp
38 unclean = doc.split()
39 words = []
40 for word in unclean:
41 if len(word)>2:
42 words.append(word)
43 if word in imp:
44 for i in range(0, 3):
45 words.append(word)
46 lng = len(words)
47 for i in range(0, lng):
48 word = words[i]
49 if allupper(word):
50 words.append(word)
51 if word=="not":
52 for j in range(1, 5):
53 if(i+j<lng):
54 words[i+j]="NOT_" + words[i+j]
55 lower_words = [word.lower() for word in words]
56 return ' '.join(lower_words)
57
58 print("Reading side files")
59 imp = set()
60
61 file = open('adjectives.txt', 'r')
62 for adj_en in file.readlines():
63 imp.add(adj_en.split()[0])
64
65 file = open('adverbs.txt', 'r')
66 for adj_en in file.readlines():
67 imp.add(adj_en.split()[0])
68
69 file = open('verbs.txt', 'r')
70 for adj_en in file.readlines():
71 imp.add(adj_en.split()[0])
72
73
74 print("Reading test json file")
75 test_data = []
76 test_it = 0
77 with codecs.open(sys.argv[1],'rU','utf-8') as f:
78 for line in f:
79 test_it = test_it + 1
80 test_data.append(json.loads(line))
81
82 print("Cleaning test sentences")
83
84 test_sentences = []
85 end = test_it
86 i = 0
87 while(i<end):
88 sent = test_data[i]['reviewText']
89 temp = ""
90 for j in range(0, 3):
91 temp = temp + test_data[i]['summary']
92 sent = sent + temp
93 test_sentences.append(cleandoc(sent))
94 i = i+1
95
96 with open('vect_uni.pkl', 'rb') as f:
97 vect_uni = pickle.load(f)
98
99 with open('vect_bi.pkl', 'rb') as f:
100 vect_bi = pickle.load(f)
101
102 print("Making Test matrix - Unigrams")
103 test_matrix_uni = vect_uni.transform(test_sentences)
104
105 print("Making Test matrix - Unigrams")
106 test_matrix_bi = vect_bi.transform(test_sentences)
107
108 test_matrix = hstack((test_matrix_uni, test_matrix_bi))
109
110 print("Predicting")
111 with open('model.pkl', 'rb') as f:
112 model = pickle.load(f)
113 y_pred = model.predict(test_matrix)
114 y_pred_class = []
115 for ele in y_pred:
116 if(ele==3):
117 y_pred_class.append(2)
118 else:
119 y_pred_class.append(ele)
120
121
122 file = open(sys.argv[2],'w')
123 for ele in y_pred_class:
124 if(ele==0):
125 file.write("1\n")
126 elif(ele==1):
127 file.write("3\n")
128 elif(ele==2):
129 file.write("5\n") | 52 - warning: bad-indentation
53 - warning: bad-indentation
54 - warning: bad-indentation
78 - warning: bad-indentation
79 - warning: bad-indentation
80 - warning: bad-indentation
9 - warning: reimported
18 - refactor: no-else-return
23 - refactor: no-else-return
44 - warning: redefined-outer-name
52 - warning: redefined-outer-name
37 - warning: global-variable-not-assigned
61 - warning: unspecified-encoding
61 - refactor: consider-using-with
65 - warning: unspecified-encoding
65 - refactor: consider-using-with
69 - warning: unspecified-encoding
69 - refactor: consider-using-with
122 - warning: unspecified-encoding
122 - refactor: consider-using-with
3 - warning: unused-import
4 - warning: unused-import
5 - warning: unused-import
6 - warning: unused-import
7 - warning: unused-import
8 - warning: unused-import
10 - warning: unused-import
11 - warning: unused-import
13 - warning: unused-import
|
1 from shop.models import Article
2 from shop.serializers import ArticleSerializer
3 from rest_framework.viewsets import ModelViewSet
4
5
6 class ArticleViewSet(ModelViewSet):
7 queryset = Article.objects.all()
8 serializer_class = ArticleSerializer
| 6 - refactor: too-few-public-methods
|
1 from json import loads
2 from django.http import JsonResponse
3 from django.http import HttpResponseNotAllowed
4 from django.http import HttpResponseNotFound
5 from shop.models import Article
6
7
8 def view_articles(request):
9 """ Handles GET and POST requests for a collection of articles.
10
11 curl --include \
12 http://localhost:8000/shop/articles/
13
14 curl --include \
15 --request POST \
16 --header "Content-Type: application/json" \
17 --data '{"name":"test"}' \
18 http://localhost:8000/shop/articles/
19
20 """
21
22 if request.method == 'GET':
23 articles = []
24 for article in Article.objects.all():
25 articles.append({
26 'id': article.id,
27 'name': article.name
28 })
29 articles = Article.objects.all()
30 return JsonResponse({'articles': articles})
31
32 if request.method == 'POST':
33 data = loads(request.body)
34 name = data.get('name')
35 article = Article.objects.create(name=name)
36 return JsonResponse({
37 'id': article.id,
38 'name': article.name
39 })
40
41 return HttpResponseNotAllowed(['GET', 'POST'])
42
43
44 def view_article(request, id):
45 """ Handles GET, PATCH and DELETE requests for a single article.
46
47 curl --include \
48 http://localhost:8000/shop/articles/1/
49
50 curl --include \
51 --request PATCH \
52 --header "Content-Type: application/json" \
53 --data '{"name":"foo"}' \
54 http://localhost:8000/shop/articles/1/
55
56 curl --include \
57 --request DELETE \
58 http://localhost:8000/shop/articles/1/
59
60 """
61 article = Article.objects.filter(id=id).first()
62 if not article:
63 return HttpResponseNotFound()
64
65 if request.method == 'GET':
66 return JsonResponse({
67 'id': article.id,
68 'name': article.name
69 })
70
71 if request.method == 'PATCH':
72 data = loads(request.body)
73 name = data.get('name')
74 article.name = name
75 article.save()
76 return JsonResponse({
77 'id': article.id,
78 'name': article.name
79 })
80
81 if request.method == 'DELETE':
82 article.delete()
83 return JsonResponse({'id': id})
84
85 return HttpResponseNotAllowed(['GET', 'PATCH', 'DELETE'])
| 44 - warning: redefined-builtin
|
1 from django.urls import path
2 from shop.views import view_article
3 from shop.views import view_articles
4
5
6 urlpatterns = [
7 path('articles/', view_articles),
8 path('articles/<int:id>/', view_article),
9 ]
| Clean Code: No Issues Detected
|
1 from shop.views import ArticleViewSet
2 from rest_framework.routers import DefaultRouter
3
4
5 router = DefaultRouter()
6 router.register('articles', ArticleViewSet)
7 urlpatterns = router.urls
| Clean Code: No Issues Detected
|
1 from django.db.models import Model
2 from django.db.models import CharField
3
4
5 class Article(Model):
6 name = CharField(max_length=50)
| 5 - refactor: too-few-public-methods
|
1 from django_filters import FilterSet
2 from shop.models import Article
3
4
5 class ArticleFilter(FilterSet):
6
7 class Meta:
8 model = Article
9 fields = ['category']
| 7 - refactor: too-few-public-methods
5 - refactor: too-few-public-methods
|
1 from django.contrib.admin import ModelAdmin, register
2 from shop.models import Article
3
4
5 @register(Article)
6 class ArticelAdmin(ModelAdmin):
7 pass
| 6 - refactor: too-few-public-methods
|
1 from shop.models import Article
2 from rest_framework.serializers import HyperlinkedModelSerializer
3
4
5 class ArticleSerializer(HyperlinkedModelSerializer):
6
7 class Meta:
8 model = Article
9 fields = ['id', 'name', 'category']
10 read_only_fields = ['id']
| 7 - refactor: too-few-public-methods
5 - refactor: too-few-public-methods
|
1 from json import loads
2 from django.http import JsonResponse
3 from django.http import HttpResponseNotAllowed
4
5
6 def view_articles(request):
7 """ Handles GET and POST requests for a collection of articles.
8
9 curl --include \
10 http://localhost:8000/shop/articles/
11
12 curl --include \
13 --request POST \
14 --header "Content-Type: application/json" \
15 --data '{"name":"test"}' \
16 http://localhost:8000/shop/articles/
17
18 """
19
20 if request.method == 'GET':
21 return JsonResponse({'ids': [id for id in range(10)]})
22
23 if request.method == 'POST':
24 data = loads(request.body)
25 data['id'] = 1
26 return JsonResponse(data)
27
28 return HttpResponseNotAllowed(['GET', 'POST'])
29
30
31 def view_article(request, id):
32 """ Handles GET, PATCH and DELETE requests for a single article.
33
34 curl --include \
35 http://localhost:8000/shop/articles/1/
36
37 curl --include \
38 --request PATCH \
39 --header "Content-Type: application/json" \
40 --data '{"name":"test"}' \
41 http://localhost:8000/shop/articles/1/
42
43 curl --include \
44 --request DELETE \
45 http://localhost:8000/shop/articles/1/
46
47 """
48
49 if request.method == 'GET':
50 return JsonResponse({'id': id})
51
52 if request.method == 'PATCH':
53 data = loads(request.body)
54 data['id'] = id
55 return JsonResponse(data)
56
57 if request.method == 'DELETE':
58 return JsonResponse({'id': id})
59
60 return HttpResponseNotAllowed(['GET', 'PATCH', 'DELETE'])
| 21 - refactor: unnecessary-comprehension
31 - warning: redefined-builtin
|
1 def add(x, y):
2 """Add function"""
3 return x+y
4 def subtract(x,y):
5 """Subtract function"""
6 return x-y
7 def multiply(x,y):
8 """Multiply function"""
9 return x*y
| Clean Code: No Issues Detected
|
1 # Generated by Django 3.1 on 2021-09-13 16:42
2
3 import datetime
4 from django.db import migrations, models
5
6
7 class Migration(migrations.Migration):
8
9 dependencies = [
10 ('charitydonation', '0002_auto_20210909_1554'),
11 ]
12
13 operations = [
14 migrations.AddField(
15 model_name='donation',
16 name='pick_up_time',
17 field=models.TimeField(default=datetime.time),
18 ),
19 migrations.AlterField(
20 model_name='donation',
21 name='pick_up_date',
22 field=models.DateField(),
23 ),
24 ]
| 7 - refactor: too-few-public-methods
|
1 from django.contrib import admin
2 from .models import Category, Institution, Donation
3
4 admin.site.register(Category)
5 admin.site.register(Institution)
6 admin.site.register(Donation) | 2 - error: relative-beyond-top-level
|
1 from django.db import models
2 from django.contrib.auth.models import (
3 BaseUserManager, AbstractBaseUser, UserManager
4 )
5 #
6 # class UserManager(BaseUserManager):
7 # def create_user(self, email, password=None):
8 # """
9 # Creates and saves a User with the given email and password.
10 # """
11 # if not email:
12 # raise ValueError('Users must have an email address')
13 #
14 # if not password:
15 # raise ValueError("Users must have a password!!! ")
16 # user = self.model(
17 # email=self.normalize_email(email),
18 # )
19 #
20 # user.set_password(password)
21 # user.staff = is_staff
22 # user.admin = is_admin
23 # user.active = is_active
24 # # user.save(using=self._db)
25 # return user
26 #
27 # def create_staffuser(self, email, password):
28 # """
29 # Creates and saves a staff user with the given email and password.
30 # """
31 # user = self.create_user(
32 # email,
33 # password=password,
34 # )
35 # user.staff = True
36 # # user.save(using=self._db)
37 # return user
38 #
39 # def create_superuser(self, email, password):
40 # """
41 # Creates and saves a superuser with the given email and password.
42 # """
43 # user = self.create_user(
44 # email,
45 # password=password,
46 # )
47 # user.staff = True
48 # user.admin = True
49 # # user.save(using=self._db)
50 # return user
51 #
52 # class User(AbstractBaseUser):
53 # email = models.EmailField(
54 # verbose_name='email address',
55 # max_length=255,
56 # unique=True,
57 # )
58 # # full_name = models.CharField(max_length=255, blank=True, null=True)
59 # is_active = models.BooleanField(default=True)
60 # staff = models.BooleanField(default=False) # a admin user; non super-user
61 # admin = models.BooleanField(default=False) # a superuser
62 # timestamp = models.DateTimeField(auto_now_add=True)
63 # # notice the absence of a "Password field", that is built in.
64 #
65 # USERNAME_FIELD = 'email'
66 # REQUIRED_FIELDS = [] # Email & Password are required by default.
67 # objects = UserManager()
68 #
69 # def get_full_name(self):
70 # # The user is identified by their email address
71 # return self.email
72 #
73 # def get_short_name(self):
74 # # The user is identified by their email address
75 # return self.email
76 #
77 # def __str__(self):
78 # return self.email
79 #
80 # def has_perm(self, perm, obj=None):
81 # "Does the user have a specific permission?"
82 # # Simplest possible answer: Yes, always
83 # return True
84 #
85 # def has_module_perms(self, app_label):
86 # "Does the user have permissions to view the app `app_label`?"
87 # # Simplest possible answer: Yes, always
88 # return True
89 #
90 # @property
91 # def is_staff(self):
92 # "Is the user a member of staff?"
93 # return self.staff
94 #
95 # @property
96 # def is_active(self):
97 # "Is the user a admin member?"
98 # return self.active
99 #
100 # @property
101 # def is_admin(self):
102 # "Is the user a admin member?"
103 # return self.admin
104 #
105 #
106 #
107 #
108 #
109 # class GuestEmail(models.Model):
110 # email = models.EmailField()
111 # active = models.BooleanField(default=True)
112 # update = models.DateTimeField(auto_now=True)
113 # timestamp = models.DateTimeField(auto_now_add=True)
114 #
115 # def __str__(self):
116 # return self.email
117
118 from django.db import models
119 from django.contrib.auth.models import AbstractUser
120 from django.utils.translation import gettext_lazy as _
121
122
123 class UserManager(BaseUserManager):
124 def create_user(self, email, password=None, **extra_fields):
125
126 if not email:
127 raise ValueError('Users must have an email address')
128
129 if not password:
130 raise ValueError("Users must have a password!!! ")
131
132 extra_fields.setdefault('is_staff', False)
133 extra_fields.setdefault('is_superuser', False)
134 extra_fields.setdefault('is_active', True)
135
136 email = self.normalize_email(email)
137 user = self.model(email=email, **extra_fields)
138 user.set_password(password)
139 user.save()
140 return user
141
142 def create_superuser(self, email, password, **extra_fields):
143
144 extra_fields.setdefault('is_staff', True)
145 extra_fields.setdefault('is_superuser', True)
146 extra_fields.setdefault('is_active', True)
147
148 if extra_fields.get('is_staff') is not True:
149 raise ValueError(_('Superuser must have is_staff=True.'))
150 if extra_fields.get('is_superuser') is not True:
151 raise ValueError(_('Superuser must have is_superuser=True.'))
152 return self.create_user(email, password, **extra_fields)
153
154
155 class CustomUser(AbstractUser):
156 username = None
157 email = models.EmailField(_('email address'), max_length=255, unique=True)
158 USERNAME_FIELD = 'email'
159 REQUIRED_FIELDS = []
160 objects = UserManager()
161
162 def __str__(self):
163 return self.email
| 118 - warning: reimported
123 - error: function-redefined
155 - refactor: too-few-public-methods
2 - warning: unused-import
|
1 from django.shortcuts import render
2 from django.views import View, generic
3 from django.contrib.auth import views
4 # from .forms import RegisterForm
5 from django.shortcuts import render
6 from django.views import View, generic
7 # from charitydonation.models import Donation, Institution
8 from .forms import CreateUserForm, LoginForm, CustomUserCreationForm
9 from django.contrib.auth import login, logout, authenticate, views
10 from django.shortcuts import redirect
11 from django.urls import reverse_lazy
12
13
14 class LoginView(View):
15 def get(self, request):
16 form = LoginForm()
17 return render(request, 'login.html', {'form': form})
18
19 def post(self, request, *args, **kwargs):
20 form = LoginForm(request.POST)
21 if form.is_valid():
22 user = authenticate(email=form.cleaned_data['email'], password=form.cleaned_data['password'])
23 # breakpoint()
24 if user is not None:
25
26 login(request, user)
27 return redirect('landing-page')
28 else:
29 return render(request, 'login.html', {'form': form})
30 else:
31 return render(request, 'login.html', {'form': form})
32
33
34 class RegisterView(View):
35 def get(self, request):
36 form = CustomUserCreationForm()
37 return render(request, 'register.html', {'form': form})
38
39 def post(self, request):
40 form = CustomUserCreationForm(request.POST)
41 if form.is_valid():
42 form.save()
43 # instance = form.save(commit=False)
44 # instance.set_password(instance.password)
45 # # form.clean_password2()
46 # instance.save()
47 # # email = form.cleaned_data['email']
48 # raw_password = form.cleaned_data['password']
49 # user = authenticate(email=email, password=raw_password)
50 # user.save()
51 # login(request, user)
52 return redirect('landing-page')
53 return render(request, 'register.html', {'form': form})
54
55
56 class LogoutView(View):
57 def get(self, request):
58 logout(request)
59 return redirect('landing-page')
| 5 - warning: reimported
6 - warning: reimported
6 - warning: reimported
8 - error: relative-beyond-top-level
9 - warning: reimported
24 - refactor: no-else-return
19 - warning: unused-argument
19 - warning: unused-argument
56 - refactor: too-few-public-methods
2 - warning: unused-import
3 - warning: unused-import
8 - warning: unused-import
11 - warning: unused-import
|
1 from django.shortcuts import render
2 from django.views import View, generic
3 from .models import Donation, Institution, Category
4 from .forms import AddDonationForm
5 from django.contrib.auth import login, logout, authenticate, views
6 from django.shortcuts import redirect
7 from django.urls import reverse_lazy
8 from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin
9 from django.views.generic.edit import CreateView
10 from django.db.models import Avg, Count
11 from django.core.paginator import Paginator
12 from django.contrib.auth.views import PasswordChangeView, PasswordChangeDoneView
13 from django.http import HttpResponse
14 from django.db.models import Q, Sum
15
16
17 class LandingPage(View):
18 def get(self, request):
19 count_bags = Donation.objects.all()
20 count_b = count_bags.aggregate(Sum('quantity'))['quantity__sum']
21 count_institutions = Donation.objects.distinct("institution").count()
22
23
24 #
25 all_institution_fund = Institution.objects.filter(type='1')
26 all_institution_org = Institution.objects.filter(type='2')
27 all_institution_lok = Institution.objects.filter(type='3')
28
29 return render(request, 'index.html', {'count_b': count_b, 'count_institutions': count_institutions,
30 'all_institution_fund': all_institution_fund,
31 'all_institution_org': all_institution_org,
32 'all_institution_lok': all_institution_lok}
33 )
34
35
36 class AddDonation(LoginRequiredMixin, View):
37 login_url = '/'
38 # raise_exception = True
39
40 def get(self, request):
41 categories_all = Category.objects.all()
42 institutions_all = Institution.objects.all()
43 form = AddDonationForm()
44
45 # redirect_field_name = 'landing-page'
46 return render(request, 'form.html',
47 {'categories_all': categories_all,
48 'institutions_all': institutions_all, 'form': form})
49
50 def post(self, request):
51 form = AddDonationForm(request.POST)
52
53 if form.is_valid():
54
55 # categories_all = Category.objects.all()
56 categories = form.cleaned_data['categories']
57 # institutions_all = Institution.objects.all()
58 quantity = form.cleaned_data['bags']
59 # category_id = request.POST.get('category.id')
60 # catogeria = Institution.objects.filter(id=category_id)
61 institution = form.cleaned_data['organization']
62 # if request.POST.get(
63 # catego = Category.objects.get(id=category_id)
64 address = form.cleaned_data['address']
65 city = form.cleaned_data['city']
66 zip_code = form.cleaned_data['postcode']
67 phone_number = form.cleaned_data['phone']
68 pick_up_date = form.cleaned_data['data']
69 pick_up_time = form.cleaned_data['time']
70 pick_up_comment = form.cleaned_data['more_info']
71 user = request.user
72 donat = Donation.objects.create(
73 quantity=quantity, categories=categories, institution=institution,
74 address=address, phone_number=phone_number, city=city, zip_code=zip_code,
75 pick_up_date=pick_up_date, pick_up_comment=pick_up_comment, pick_up_time=pick_up_time,
76 user=user)
77 donat.save()
78 # redirect_field_name = 'landing-page'
79 return render(request, 'form-confirmation.html', {'form': form})
80
81 return render(request, 'form.html', {'form': form})
82 # return HttpResponse("Źle")
83 # class LoginView(views.LoginView):
84 # form_class = LoginForm
85 # template_name = 'login.html'
86 #
87 #
88 # class RegisterView(generic.CreateView):
89 # form_class = CreateUserForm
90 # template_name = 'register.html'
91 # success_url = reverse_lazy('login')
92
93
94 class UserView(LoginRequiredMixin, View):
95 login_url = '/'
96
97 def get(self, request):
98 donation_user = Donation.objects.filter(user=request.user)
99 return render(request, 'user-view.html', {'donation_user': donation_user})
100
101
102 class PasswordChangeView(PasswordChangeView):
103 template_name = 'change-password.html'
104 success_url = 'done/'
105
106
107 class PasswordChangeDoneView(PasswordChangeDoneView):
108 template_name = 'change-password-done.html'
109
110
111 class DonationReady(View):
112 def get(self, request):
113 return render(request, 'form-confirmation.html')
| 3 - error: relative-beyond-top-level
4 - error: relative-beyond-top-level
17 - refactor: too-few-public-methods
94 - refactor: too-few-public-methods
102 - error: function-redefined
102 - refactor: too-few-public-methods
107 - error: function-redefined
107 - refactor: too-few-public-methods
111 - refactor: too-few-public-methods
2 - warning: unused-import
5 - warning: unused-import
5 - warning: unused-import
5 - warning: unused-import
5 - warning: unused-import
6 - warning: unused-import
7 - warning: unused-import
8 - warning: unused-import
9 - warning: unused-import
10 - warning: unused-import
10 - warning: unused-import
11 - warning: unused-import
13 - warning: unused-import
14 - warning: unused-import
|
1 from django.contrib.auth.forms import UserCreationForm, UserChangeForm
2 from .models import Donation
3 from django import forms
4 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
5 from django.contrib.auth.models import User
6 from django.core.exceptions import ValidationError
7 from django.contrib.auth import get_user_model
8
9
10 # class CreateUserForm(UserCreationForm):
11 # class Meta:
12 # model = get_user_model()
13 # fields = ('email', 'username', 'password1', 'password2')
14
15
16 class AddDonationForm(forms.Form):
17 class Meta:
18 model = Donation
19 fields = ('quantity', 'categories', 'institution', 'address', 'phone_number',
20 'city', 'zip_code', 'pick_up_date', 'pick_up_time', 'pick_up_comment', 'user')
| 2 - error: relative-beyond-top-level
4 - warning: reimported
17 - refactor: too-few-public-methods
16 - refactor: too-few-public-methods
1 - warning: unused-import
1 - warning: unused-import
4 - warning: unused-import
5 - warning: unused-import
6 - warning: unused-import
7 - warning: unused-import
|
1 """donation URL Configuration
2
3 The `urlpatterns` list routes URLs to views. For more information please see:
4 https://docs.djangoproject.com/en/3.2/topics/http/urls/
5 Examples:
6 Function views
7 1. Add an import: from my_app import views
8 2. Add a URL to urlpatterns: path('', views.home, name='home')
9 Class-based views
10 1. Add an import: from other_app.views import Home
11 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
12 Including another URLconf
13 1. Import the include() function: from django.urls import include, path
14 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
15 """
16 from django.contrib import admin
17 from django.urls import path
18 from charitydonation.views import LandingPage, AddDonation, UserView, PasswordChangeView, PasswordChangeDoneView, DonationReady
19 from accounts.views import RegisterView, LoginView, LogoutView
20
21
22 urlpatterns = [
23 path('admin/', admin.site.urls),
24 path('', LandingPage.as_view(), name='landing-page'),
25 path('add_donation/', AddDonation.as_view(), name='add-donation'),
26 path('login/', LoginView.as_view(), name='login'),
27 path('register/', RegisterView.as_view(), name='register'),
28 path('logout/', LogoutView.as_view(), name='logout'),
29 path('user_view/', UserView.as_view(), name='user-view'),
30 path('password_change/', PasswordChangeView.as_view(), name='user-change'),
31 path('password_change/done/', PasswordChangeDoneView.as_view(), name='user-change-done'),
32 path('add_donation/form-confirmation/', DonationReady.as_view(), name='form-ready'),
33
34
35 ]
| Clean Code: No Issues Detected
|
1 # Generated by Django 3.1 on 2021-09-09 15:54
2
3 import datetime
4 from django.db import migrations, models
5
6
7 class Migration(migrations.Migration):
8
9 dependencies = [
10 ('charitydonation', '0001_initial'),
11 ]
12
13 operations = [
14 migrations.RemoveField(
15 model_name='donation',
16 name='pick_up_time',
17 ),
18 migrations.AlterField(
19 model_name='donation',
20 name='pick_up_date',
21 field=models.DateTimeField(verbose_name=datetime.datetime),
22 ),
23 migrations.AlterField(
24 model_name='institution',
25 name='type',
26 field=models.CharField(choices=[('1', 'Fundacja'), ('2', 'Organizacja pozarządowa'), ('3', 'Zbiórka lokalna')], default='1', max_length=2),
27 ),
28 ]
| 7 - refactor: too-few-public-methods
|
1 import datetime
2 from django.contrib.auth.models import User
3 from django.contrib.auth.models import AbstractUser
4 from django.db import models
5 from django.utils.translation import gettext_lazy as _
6 # from ProjektPortfolioLab.donation import settings
7 from django.conf import settings
8
9 User = settings.AUTH_USER_MODEL
10
11
12 class Category(models.Model):
13 name = models.CharField(max_length=64)
14
15 def __str__(self):
16 return self.name
17
18 INSTITUTIONS = (
19 ('1', "Fundacja"),
20 ('2', "Organizacja pozarządowa"),
21 ('3', "Zbiórka lokalna"),
22 )
23
24
25 class Institution(models.Model):
26
27 istitution_name = models.CharField(max_length=128)
28 description = models.TextField()
29 type = models.CharField(max_length=2, choices=INSTITUTIONS, default='1')
30 categories = models.ManyToManyField(Category)
31
32 def __str__(self):
33 return self.istitution_name
34
35
36 class Donation(models.Model):
37 quantity = models.IntegerField()
38 categories = models.ManyToManyField(Category)
39 institution = models.ForeignKey(Institution, on_delete=models.CASCADE)
40 address = models.TextField()
41 phone_number = models.CharField(max_length=12)
42 city = models.CharField(max_length=64)
43 zip_code = models.TextField()
44 pick_up_date = models.DateField()
45 pick_up_time = models.TimeField(default=datetime.time)
46 pick_up_comment = models.TextField()
47 user = models.ForeignKey(User, on_delete=models.CASCADE)
48
49 #
50 # class CustomUser(AbstractUser):
51 # email = models.EmailField(_('email address'), unique=True)
52
| 12 - refactor: too-few-public-methods
25 - refactor: too-few-public-methods
36 - refactor: too-few-public-methods
3 - warning: unused-import
|
1 from bs4 import BeautifulSoup
2 from pprint import pprint
3 from functools import reduce
4 import sys
5
6
7 def scrape(html_file_path):
8
9 soup = BeautifulSoup(open(html_file_path), 'html.parser')
10
11 rows = soup.find_all('tr')
12
13 commands = list()
14
15 for row in rows[1:]:
16 cols = row.find_all('td')
17
18 lure_string = list(cols[0].descendants)[0]
19 lure = lure_string.text
20
21 body_of_water = cols[1].string
22
23 location = cols[2].string
24
25 fish_string = cols[3]
26 fish_type = fish_string.font.string
27 fish_level = fish_string.find('font').text
28
29 size_strings = list(map(lambda x: x.string, cols[4].find_all('font')))
30 weight_idx = -1
31 for idx in range(len(size_strings)):
32 if 'lb' in size_strings[idx]:
33 weight_idx = idx
34 break
35 weight = size_strings[weight_idx].split()[0]
36 fish_class = reduce(lambda x, y: "%s %s" % (x, y), size_strings[weight_idx+1:])
37 if 'L e g e n d a r y' in fish_class:
38 fish_class = 'Legendary'
39 elif 'B R U I S E R' in fish_class:
40 fish_class = 'Bruiser'
41
42 # size not stored for now
43 # size = reduce(lambda x, y: "%s %s" % (x, y), size_strings[:-3])
44
45 command = "'%s', '%s', '%s', '%s', '%s', '%s', '%s'" % (lure, body_of_water, location, fish_type, fish_level,
46 weight, fish_class)
47 commands.append(command)
48
49 return commands
50
51
52 if __name__ == '__main__':
53
54 if len(sys.argv) != 2:
55 print("Need one argument: path to html_file", file=sys.stderr)
56 sys.exit(1)
57
58 scrape_data = scrape(sys.argv[1])
59 pprint(scrape_data)
| 7 - refactor: too-many-locals
9 - refactor: consider-using-with
9 - warning: unspecified-encoding
13 - refactor: use-list-literal
|
1 import os.path
2 import sqlite3
3 import Scraper
4 import sys
5
6
7 def create_db():
8 conn = sqlite3.connect('reellog.db')
9 c = conn.cursor()
10
11 c.execute('''CREATE TABLE reellog
12 (lure text, body text, location text, species text, level integer, weight real, class text,
13 unique(lure, body, location, species, level, weight, class))''')
14
15 conn.commit()
16 conn.close()
17
18
19 def sample_db_entry():
20 scrape_data = "'Culprit Worm', 'Amazon River', 'Baia de Santa Rosa', 'Matrincha', '6', '0.062', 'Wimpy III'"
21 command = "INSERT INTO reellog VALUES (%s)" % scrape_data
22
23 conn = sqlite3.connect('reellog.db')
24 c = conn.cursor()
25
26 c.execute(command)
27
28 conn.commit()
29 conn.close()
30
31
32 def parse_and_store(html_file_path):
33 conn = sqlite3.connect('reellog.db')
34 c = conn.cursor()
35
36 c.execute("SELECT COUNT(*) from reellog")
37 (old_entry_count, ) = c.fetchone()
38
39 to_write = Scraper.scrape(html_file_path)
40
41 for row in to_write:
42 command = "INSERT INTO reellog VALUES (%s)" % row
43 try:
44 c.execute(command)
45 print('+ %s' % row)
46 except sqlite3.IntegrityError:
47 print('= %s' % row)
48
49 conn.commit()
50
51 c.execute("SELECT COUNT(*) from reellog")
52 (new_entry_count,) = c.fetchone()
53
54 conn.close()
55
56 print("%i new entries added" % (int(new_entry_count) - int(old_entry_count)))
57
58
59 if __name__ == '__main__':
60
61 if len(sys.argv) != 2:
62 print("Need one argument: path to html_file", file=sys.stderr)
63 sys.exit(1)
64
65 if not os.path.isfile('reellog.db'):
66 print('No reellog.db found, creating')
67 create_db()
68 parse_and_store(sys.argv[1])
69 # sample_db_entry()
70
71 print('Done')
| Clean Code: No Issues Detected
|
1 Numero1 = int (input ('Primeiro numero = ' ))
2 Numero2 = int (input ('Segundo numero = '))
3 print (Numero1 + Numero2)
4
5
6
| Clean Code: No Issues Detected
|
1 n = input('Digite algo:')
2 print ('Esse número é', (type (n)))
3 print ('Ele é númerico ? ', n.isnumeric ())
4 print (' Ele é alfabético? ', n.isalpha ())
5 print (' Ele é um decimal? ', n.isdecimal ())
6 print (' Ele é minúsculo? ', n .islower ())
7 print ('Ele é maiúsculo?', n.isupper ())
8 print ('Ele é um dígito?', n.isdigit ())
9 print ('Verificação concluída') | Clean Code: No Issues Detected
|
1 Nome = input('Digite seu nome:')
2 print('Seja bem vindo,',format(Nome))
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| Clean Code: No Issues Detected
|
1 n1 = input('Digite um valor: ')
2 print(type (n1))
| Clean Code: No Issues Detected
|
1 n = input('Digite algo: ')
2 print(n .isnumeric())
| Clean Code: No Issues Detected
|
1 import sys, os
2 import fileinput
3
4 funcString = "function ("
5 openBracket = '('
6 closingBracket = ') {'
7 closingBracket2 = '){'
8 arrowSyntax = ') => {'
9
10 def main():
11
12 if (len(sys.argv) < 2 or len(sys.argv) > 3):
13 print 'ERROR:'
14 print 'Please supply either a directory to a folder containing JavaScript files, or a JavaScript file and an optional output file name in the following formats:'
15 print '----------------------------------------'
16 print 'To convert all files in a directory:'
17 print 'python func-to-arrow.py "directory-to-folder"'
18 print 'To convert a single file with optional output file:'
19 print 'python func-to-arrow.py "JavaScript-file.js" "output-file.js"'
20
21 elif (len(sys.argv) == 2):
22 input1 = sys.argv[1]
23 jsFileExt = '.js'
24 # newFileName = sys.argv[1].split('.')[0] + '-new.' + sys.argv[1].split('.')[1]
25 if (jsFileExt in input1):
26 parseFile(input1, False, False)
27 else:
28 parseDir(input1)
29 # for f in os.listdir(input1):
30 # if (jsFileExt in f):
31 # parseFile(f, False, input1)
32
33 elif (len(sys.argv) == 3):
34 fileIn = sys.argv[1]
35 fileOut = sys.argv[2]
36
37 if ((jsFileExt in sys.argv[1]) and (jsFileExt in sys.argv[2])):
38 parseFile(open(fileIn), fileOut, False)
39 else:
40 print 'Please check your file types'
41
42 exit()
43
44 def parseDir(folder):
45 for f in os.listdir(folder):
46 if (('.js' in f) and ('.min.' not in f)):
47 parseFile(f, False, folder)
48 elif (os.path.isdir(os.path.join(folder, f)) and (f != 'node_modules')):
49 parseDir(os.path.join(folder, f))
50
51 return
52
53 def parseFile(fileIn, fileOut, directory):
54 if (fileOut):
55 newFileName = fileOut
56
57 else:
58 newFileName = str(fileIn).split('.')[0] + '-new.' + fileIn.split('.')[1]
59
60 if (directory):
61 fileIn = os.path.join(directory, fileIn)
62 newFile = open(os.path.join(directory, newFileName), 'a+')
63
64 else:
65 newFile = open(newFileName, 'a+')
66
67 isSame = True
68
69 for line in open(fileIn):
70 toWrite = arrowStyle(line)
71 newFile.write(toWrite)
72 if (line != toWrite):
73 isSame = False
74
75 newFile.close();
76
77 if isSame:
78 os.remove(os.path.join(directory, newFileName))
79 print 'No changes were made to ' + fileIn
80 else:
81 print 'Changes were made to ' + fileIn
82 oldFile = os.path.join(directory, newFileName.replace('-new', '-old'))
83 os.rename(fileIn, oldFile)
84 # print fileIn + ' has been renamed to ' + oldFile
85 # print newFileName + ' has been renamed to ' + fileIn
86 os.rename(os.path.join(directory, newFileName), fileIn)
87
88
89 def arrowStyle(line):
90 if (funcString in line):
91 newLine = line.replace(funcString, openBracket)
92 newLine = newLine.replace(closingBracket, arrowSyntax)
93 newLine = newLine.replace(closingBracket2, arrowSyntax)
94 return newLine
95 else:
96 return line
97
98 main()
| 13 - error: syntax-error
|
1 import os, sys
2
3 def main():
4 if (len(sys.argv) == 2):
5 if os.path.isdir(sys.argv[1]):
6 parseDir(sys.argv[1])
7
8 def parseDir(folder):
9 for f in os.listdir(folder):
10 if ('-old.' in f):
11 os.remove(os.path.join(folder, f))
12 elif (os.path.isdir(os.path.join(folder, f)) and (f != 'node_modules')):
13 parseDir(os.path.join(folder, f))
14
15 main()
| Clean Code: No Issues Detected
|
1 import requests
2 from bs4 import BeautifulSoup
3 import discord
4 import os
5 from tabulate import tabulate
6 import handlers
7 import pandas as pd
8 from helpers import get_url, get_problems, trim,load_problems
9 from handlers import start_contest, update_leaderboard,add_cf_user,users,get_recommendations_topics, set_handle, recommendations_handle
10
11 from keep_alive import keep_alive
12
13 import weasyprint as wsp
14 import PIL as pil
15
16 # global running
17 # running = contest_running
18
19
20
21 client = discord.Client()
22
23 @client.event
24 async def on_ready():
25 print('We have logged in as {0.user}'.format(client))
26
27
28 @client.event
29 async def on_message(message):
30 global contest_running
31
32 if message.author == client.user:
33 return
34
35 msg = message.content
36 #params = msg.lower().split(' ')
37 params = msg.split(' ')
38 if params[0][0] != '!':
39 return
40
41 if params[0] == '!setrc':
42 handle = params[1]
43 rc = set_handle(handle)
44 if rc < 0:
45 await message.channel.send('Invalid codeforces handle')
46 else:
47 await message.channel.send('Done! Getting recommandations from: '+handle+".")
48
49
50 if params[0] == '!topics':
51 msg = get_recommendations_topics(recommendations_handle)
52 await message.channel.send(msg)
53
54 if params[0] == '!add':
55 username = params[1]
56 rc = add_cf_user(username)
57 if rc == -1:
58 await message.channel.send('User already registered!')
59 elif rc == -2:
60 await message.channel.send('Not a valid user on CodeForces!')
61 else:
62 await message.channel.send(f"Sucessfully added {username}")
63
64 elif params[0] == '!all':
65 await message.channel.send(users)
66
67 elif params[0] == '!start':
68 if handlers.contest_running:
69 await message.channel.send("A contest is already Active !")
70 return
71 task = "_".join(word for word in params[1:])
72 #img_filepath = 'table.png'
73 #print(task)
74 msg = start_contest(task)
75
76 if msg == "error":
77 await message.channel.send("Please Try Again!")
78 else:
79 e = discord.Embed(
80 title=f"Problem Set {handlers.ID}\n",
81 description=msg,
82 color=0xFF5733)
83 await message.channel.send(embed=e)
84
85 elif params[0] == '!lb':
86 id = params[1] if len(params) > 1 else handlers.ID
87 df_lead = update_leaderboard(id)
88 df_lead['Total'] = df_lead[list(df_lead.columns)[1:]].sum(axis=1)
89 df_lead.sort_values(by='Total',ascending=False, inplace=True)
90 await message.channel.send("```"+tabulate(df_lead, headers='keys', tablefmt='psql', showindex=False)+"```")
91 # f = discord.File('table.png', filename="image.png")
92 # e = discord.Embed(title='Leaderboard', color=0xFF5733)
93 # e.set_image(url="attachment://image.png")
94 # await message.channel.send(file=f, embed=e)
95
96 elif params[0] == "!prob":
97 id = params[1] if len(params) > 1 else handlers.ID
98 msg = load_problems(id)
99 e = discord.Embed(
100 title=f"Problem Set {handlers.ID}\n",
101 description=msg,
102 color=0xFF5733)
103 await message.channel.send(embed=e)
104
105 elif params[0] == "!end":
106 if handlers.contest_running == 0:
107 await message.channel.send("No contest is running !")
108 else:
109 handlers.contest_running = 0
110 await message.channel.send("Contest Abandoned !")
111
112 keep_alive()
113 client.run(os.getenv('TOKEN'))
| 30 - warning: bad-indentation
32 - warning: bad-indentation
33 - warning: bad-indentation
35 - warning: bad-indentation
37 - warning: bad-indentation
38 - warning: bad-indentation
39 - warning: bad-indentation
41 - warning: bad-indentation
42 - warning: bad-indentation
43 - warning: bad-indentation
44 - warning: bad-indentation
45 - warning: bad-indentation
46 - warning: bad-indentation
47 - warning: bad-indentation
50 - warning: bad-indentation
51 - warning: bad-indentation
52 - warning: bad-indentation
54 - warning: bad-indentation
55 - warning: bad-indentation
56 - warning: bad-indentation
57 - warning: bad-indentation
58 - warning: bad-indentation
59 - warning: bad-indentation
60 - warning: bad-indentation
61 - warning: bad-indentation
62 - warning: bad-indentation
64 - warning: bad-indentation
65 - warning: bad-indentation
67 - warning: bad-indentation
68 - warning: bad-indentation
69 - warning: bad-indentation
70 - warning: bad-indentation
71 - warning: bad-indentation
74 - warning: bad-indentation
76 - warning: bad-indentation
77 - warning: bad-indentation
78 - warning: bad-indentation
79 - warning: bad-indentation
83 - warning: bad-indentation
85 - warning: bad-indentation
86 - warning: bad-indentation
87 - warning: bad-indentation
88 - warning: bad-indentation
89 - warning: bad-indentation
90 - warning: bad-indentation
96 - warning: bad-indentation
97 - warning: bad-indentation
98 - warning: bad-indentation
99 - warning: bad-indentation
103 - warning: bad-indentation
105 - warning: bad-indentation
106 - warning: bad-indentation
107 - warning: bad-indentation
108 - warning: bad-indentation
109 - warning: bad-indentation
110 - warning: bad-indentation
86 - warning: redefined-builtin
30 - warning: global-variable-not-assigned
29 - refactor: too-many-branches
29 - refactor: too-many-statements
1 - warning: unused-import
2 - warning: unused-import
7 - warning: unused-import
8 - warning: unused-import
8 - warning: unused-import
8 - warning: unused-import
13 - warning: unused-import
14 - warning: unused-import
|
1 import requests
2 from bs4 import BeautifulSoup
3 import discord
4 import os
5 import pandas as pd
6
7 import weasyprint as wsp
8 import PIL as pil
9
10
11 def get_url(task,handle):
12 URL = 'https://recommender.codedrills.io/profile?handles=cf%2Fjatinmunjal2k'
13 page = requests.get(URL)
14
15 soup = BeautifulSoup(page.content, 'html.parser')
16
17 # print(task)
18
19 result = soup.find(id=task)
20
21 url = result.find(title='An url for sharing and keeping track of solved problems for this recommendation list')
22 link = "https://recommender.codedrills.io"+url['href']
23 return link
24
25 def get_problems(task, ID,handle):
26 # print(ID)
27 items = [[],[]]
28 buffer = ""
29 URL = get_url(task,handle)
30 page = requests.get(URL)
31 soup = BeautifulSoup(page.content, 'html.parser')
32 elems = soup.find_all('tr')
33 idx = 1
34 for e in elems:
35 a_tag = e.find('a')
36 buffer = buffer +"["+str(idx)+"](" + a_tag['href'] + ") " + a_tag.text + "\n"
37 items[0].append(a_tag.text)
38 items[1].append(a_tag['href'])
39 idx += 1
40
41 df = pd.DataFrame(list(zip(items[0],items[1])), columns = ['name', 'link'])
42 df.to_csv('contests/problems-contest'+str(ID)+'.csv' , index = False)
43 #print(df.head(3))
44
45 return buffer
46
47 def load_problems(id):
48 df = pd.read_csv('contests/problems-contest'+str(id)+'.csv')
49 buffer = ""
50 for idx, row in df.iterrows():
51 buffer = buffer + row['name'] + " [Link](" + row['link'] + ")\n"
52 return buffer
53
54
55 def trim(source_filepath, target_filepath=None, background=None):
56 if not target_filepath:
57 target_filepath = source_filepath
58 img = pil.Image.open(source_filepath)
59 if background is None:
60 background = img.getpixel((0, 0))
61 border = pil.Image.new(img.mode, img.size, background)
62 diff = pil.ImageChops.difference(img, border)
63 bbox = diff.getbbox()
64 img = img.crop(bbox) if bbox else img
65 img.save(target_filepath)
66
| 12 - warning: bad-indentation
13 - warning: bad-indentation
15 - warning: bad-indentation
19 - warning: bad-indentation
21 - warning: bad-indentation
22 - warning: bad-indentation
23 - warning: bad-indentation
27 - warning: bad-indentation
28 - warning: bad-indentation
29 - warning: bad-indentation
30 - warning: bad-indentation
31 - warning: bad-indentation
32 - warning: bad-indentation
33 - warning: bad-indentation
34 - warning: bad-indentation
35 - warning: bad-indentation
36 - warning: bad-indentation
37 - warning: bad-indentation
38 - warning: bad-indentation
39 - warning: bad-indentation
41 - warning: bad-indentation
42 - warning: bad-indentation
45 - warning: bad-indentation
48 - warning: bad-indentation
49 - warning: bad-indentation
50 - warning: bad-indentation
51 - warning: bad-indentation
52 - warning: bad-indentation
13 - warning: missing-timeout
11 - warning: unused-argument
30 - warning: missing-timeout
47 - warning: redefined-builtin
50 - warning: unused-variable
3 - warning: unused-import
4 - warning: unused-import
7 - warning: unused-import
|
1 import requests
2 from bs4 import BeautifulSoup
3 import discord
4 import os
5 from tabulate import tabulate
6 import pandas as pd
7 from helpers import get_url, get_problems, trim,load_problems
8 from keep_alive import keep_alive
9
10 import weasyprint as wsp
11 import PIL as pil
12
13 global ID, contest_running, users, recommendations_handle
14 ID = 0
15 contest_running = 0
16 users = []
17 recommendations_handle = 'jatinmunjal2k'
18
19
20
21 def get_recommendations_topics(handle='jatinmunjal2k'):
22 topics = "Available Topics:\n"
23 URL = 'https://recommender.codedrills.io/profile?handles=cf%2F' + handle
24 page = requests.get(URL)
25 soup = BeautifulSoup(page.content, 'html.parser')
26 ul = soup.find("ul", class_="nav nav-pills")
27 tags = ul.find_all('li')
28 for e in tags:
29 topics = topics + e.text.strip() + ", "
30 return topics[:-2]
31
32
33 def set_handle(handle):
34 global recommendations_handle
35 r = requests.head('https://codeforces.com/profile/'+handle)
36 if r.status_code != 200:
37 return -1
38 recommendations_handle = handle
39 return 0
40
41 def start_contest(task):
42 global ID, contest_running
43 try:
44 ID += 1
45 problems_str = get_problems(task, ID,recommendations_handle)
46 init_leaderboard(ID)
47 contest_running = 1
48 return problems_str
49 except:
50 ID -= 1
51 return "error"
52
53 def add_cf_user(cf_handle):
54 global users
55
56 if cf_handle in users:
57 return -1
58
59 r = requests.head('https://codeforces.com/profile/'+cf_handle)
60 if r.status_code != 200:
61 return -2
62
63 users.append(cf_handle)
64 if contest_running == 1:
65 df = pd.read_csv('contests/leaderboard'+str(ID)+'.csv')
66 entry = [cf_handle] + [0]*(df.shape[1]-1)
67 df.loc[len(df)] = entry
68 df.to_csv('contests/leaderboard'+str(ID)+'.csv',index = False)
69
70 return 1
71
72 # def print_leaderboard(id, img_filepath):
73 # df_leaderboard = pd.read_csv('contests/leaderboard'+str(id)+'.csv')
74 # css = wsp.CSS(string='''
75 # @page { size: 2048px 2048px; padding: 0px; margin: 0px; }
76 # table, td, tr, th { border: 1px solid black; }
77 # td, th { padding: 4px 8px; }
78 # ''')
79 # html = wsp.HTML(string=df_leaderboard.to_html(index=False))
80 # html.write_png(img_filepath, stylesheets=[css])
81 # trim(img_filepath)
82
83 def init_leaderboard(id):
84 df = pd.read_csv('contests/problems-contest'+str(id)+'.csv')
85 problems = df['name']
86 zeros = [ [0]*len(users) for i in range(len(problems))]
87 df_scoreboard = pd.DataFrame(data=list(zip(users,*zeros)), columns=['User']+list(range(1,len(problems)+1)))
88 df_scoreboard.to_csv('contests/leaderboard'+str(id)+'.csv',index=False)
89
90 # print_leaderboard(id, img_filepath)
91
92
93 def update_leaderboard(id):
94 global users
95 df_prob = pd.read_csv('contests/problems-contest'+str(id)+'.csv')
96 df_lead = pd.read_csv('contests/leaderboard'+str(id)+'.csv')
97
98 for idxu, ru in df_lead.iterrows():
99 user = ru['User']
100 URL = 'https://codeforces.com/submissions/' + user
101 page = requests.get(URL)
102 soup = BeautifulSoup(page.content, 'html.parser')
103 submissions = soup.find_all('tr')
104 ac = []
105 for submission in submissions:
106 data = submission.find_all('td')
107 try:
108 url = data[3].find('a')['href'].split('/')
109 verdict = data[5].text
110 #print(url, repr(verdict))
111 if 'Accepted' in verdict:
112 ac.append('/'+url[2]+'/'+url[-1])
113 except:
114 continue
115
116 j = 0
117 for idx, row in df_prob.iterrows():
118 j += 1
119 link = row['link']
120 for pid in ac:
121 if pid in link:
122 df_lead.at[idxu,str(j)] = 1
123
124 df_lead.to_csv('contests/leaderboard'+str(id)+'.csv',index = False)
125 # print_leaderboard(id, 'table.png')
126 return df_lead
127
128
129
| 22 - warning: bad-indentation
23 - warning: bad-indentation
24 - warning: bad-indentation
25 - warning: bad-indentation
26 - warning: bad-indentation
27 - warning: bad-indentation
28 - warning: bad-indentation
29 - warning: bad-indentation
30 - warning: bad-indentation
34 - warning: bad-indentation
35 - warning: bad-indentation
36 - warning: bad-indentation
37 - warning: bad-indentation
38 - warning: bad-indentation
39 - warning: bad-indentation
42 - warning: bad-indentation
43 - warning: bad-indentation
44 - warning: bad-indentation
45 - warning: bad-indentation
46 - warning: bad-indentation
47 - warning: bad-indentation
48 - warning: bad-indentation
49 - warning: bad-indentation
50 - warning: bad-indentation
51 - warning: bad-indentation
54 - warning: bad-indentation
56 - warning: bad-indentation
57 - warning: bad-indentation
59 - warning: bad-indentation
60 - warning: bad-indentation
61 - warning: bad-indentation
63 - warning: bad-indentation
64 - warning: bad-indentation
65 - warning: bad-indentation
66 - warning: bad-indentation
67 - warning: bad-indentation
68 - warning: bad-indentation
70 - warning: bad-indentation
84 - warning: bad-indentation
85 - warning: bad-indentation
86 - warning: bad-indentation
87 - warning: bad-indentation
88 - warning: bad-indentation
94 - warning: bad-indentation
95 - warning: bad-indentation
96 - warning: bad-indentation
98 - warning: bad-indentation
99 - warning: bad-indentation
100 - warning: bad-indentation
101 - warning: bad-indentation
102 - warning: bad-indentation
103 - warning: bad-indentation
104 - warning: bad-indentation
105 - warning: bad-indentation
106 - warning: bad-indentation
107 - warning: bad-indentation
108 - warning: bad-indentation
109 - warning: bad-indentation
111 - warning: bad-indentation
112 - warning: bad-indentation
113 - warning: bad-indentation
114 - warning: bad-indentation
116 - warning: bad-indentation
117 - warning: bad-indentation
118 - warning: bad-indentation
119 - warning: bad-indentation
120 - warning: bad-indentation
121 - warning: bad-indentation
122 - warning: bad-indentation
124 - warning: bad-indentation
126 - warning: bad-indentation
13 - warning: global-at-module-level
24 - warning: missing-timeout
34 - warning: global-statement
35 - warning: missing-timeout
42 - warning: global-statement
49 - warning: bare-except
54 - warning: global-variable-not-assigned
59 - warning: missing-timeout
83 - warning: redefined-builtin
93 - refactor: too-many-locals
93 - warning: redefined-builtin
94 - warning: global-variable-not-assigned
101 - warning: missing-timeout
113 - warning: bare-except
117 - warning: unused-variable
3 - warning: unused-import
4 - warning: unused-import
5 - warning: unused-import
7 - warning: unused-import
7 - warning: unused-import
7 - warning: unused-import
8 - warning: unused-import
10 - warning: unused-import
11 - warning: unused-import
|
1 import ie_classifier as ic
2 import argparse
3 import logging as log
4 import sys
5 import cv2
6
7 def build_argparser():
8 parser = argparse.ArgumentParser()
9 parser.add_argument('-m', '--model', help='Path to an .xml \
10 file with a trained model.', required=True, type=str)
11 parser.add_argument('-w', '--weights', help='Path to an .bin file \
12 with a trained weights.', required=True, type=str)
13 parser.add_argument('-i', '--input', help='Path to \
14 image file', required=True, type=str)
15 parser.add_argument('-c', '--classes', help='File containing \
16 classnames', type=str, default=None)
17 parser.add_argument('-d', '--device', help='Device name',
18 default = "CPU", type = str)
19 parser.add_argument('-e', '--cpu_extension', help='For custom',
20 default = None, type = str)
21 return parser
22
23 def main():
24 log.basicConfig(format="[ %(levelname)s ] %(message)s",
25 level=log.INFO, stream=sys.stdout)
26 args = build_argparser().parse_args()
27 log.info("Start IE classification sample")
28 ie_classifier = ic.InferenceEngineClassifier(configPath=args.model,
29 weightsPath=args.weights, device=args.device, extension=args.cpu_extension,
30 classesPath=args.classes)
31 img = cv2.imread(args.input)
32 prob = ie_classifier.classify(img)
33 predictions = ie_classifier.get_top(prob, 5)
34 log.info("Predictions: " + str(predictions))
35 return
36
37 if __name__ == '__main__':
38 sys.exit(main()) | 38 - warning: bad-indentation
34 - warning: logging-not-lazy
23 - refactor: useless-return
|
1 from openvino.inference_engine import IECore
2 import cv2
3 import numpy as np
4
5 class InferenceEngineDetector:
6 def __init__(self, configPath = None, weightsPath = None,
7 device = None, extension = None, classesPath = None):
8 IEc = IECore()
9 if (extension and device == 'CPU'):
10 IEc.add_extension(extension, device)
11 self.net = IEc.read_network(configPath, weightsPath)
12 self.exec_net = IEc.load_network(self.net, device_name = device)
13 with open(classesPath, 'r') as f:
14 self.classes = [i.strip() for i in f]
15 def _prepare_image(self, image, h, w):
16 image = cv2.resize(image, (w, h))
17 image = image.transpose((2, 0, 1))
18 return image
19 def detect(self, image):
20 input_blob = next(iter(self.net.inputs))
21 output_blob = next(iter(self.net.outputs))
22 n, c, h, w = self.net.inputs[input_blob].shape
23 image = self._prepare_image(image, h, w)
24 output = self.exec_net.infer(inputs={input_blob: image})
25 output = output[output_blob]
26 return output
27 def draw_detection(self, detections, image, confidence = 0.5, draw_text = True):
28 detections = np.squeeze(detections)
29 h, w, c = image.shape
30 for classdet in detections:
31 if (classdet[2] > confidence):
32 image = cv2.rectangle(image, (int(classdet[3] * w), int(classdet[4] * h)),
33 (int(classdet[5] * w), int(classdet[6] * h)),
34 (0, 255, 0), 1)
35 if (draw_text):
36 image = cv2.putText(image,
37 self.classes[int(classdet[1])]
38 + ' ' + str('{:.2f}'.format(classdet[2] * 100)) + '%',
39 (int(classdet[3] * w - 5), int(classdet[4] * h - 5)),
40 cv2.FONT_HERSHEY_SIMPLEX, 0.45,
41 (0, 0, 255), 1)
42 return image | 6 - refactor: too-many-arguments
6 - refactor: too-many-positional-arguments
13 - warning: unspecified-encoding
22 - warning: unused-variable
22 - warning: unused-variable
29 - warning: unused-variable
|
1 from openvino.inference_engine import IECore
2 import cv2
3 import numpy as np
4
5 class InferenceEngineClassifier:
6 def __init__(self, configPath = None, weightsPath = None, device = None, extension = None, classesPath = None):
7 IEc = IECore()
8 if (extension and device == "CPU"):
9 IEc.add_extension(extension, device)
10 self.net = IEc.read_network(configPath, weightsPath)
11 self.exec_net = IEc.load_network(self.net, device_name=device)
12 with open(classesPath, 'r') as f:
13 self.classes = [i.strip() for i in f]
14 def _prepare_image(self, image, h, w):
15 image = cv2.resize(image, (w, h))
16 image = image.transpose((2, 0, 1))
17 return image
18 def classify(self, image):
19 input_blob = next(iter(self.net.inputs))
20 out_blob = next(iter(self.net.outputs))
21 n, c, h, w = self.net.inputs[input_blob].shape
22 image = self._prepare_image(image, h, w)
23 output = self.exec_net.infer(inputs={input_blob: image})
24 output = output[out_blob]
25 return output
26 def get_top(self, prob, topN = 1):
27 prob = np.squeeze(prob)
28 top = np.argsort(prob)
29 out = []
30 for i in top[1000 - topN:1000]:
31 out.append([self.classes[i], '{:.15f}'.format(prob[i])])
32 out.reverse()
33 return out | 6 - refactor: too-many-arguments
6 - refactor: too-many-positional-arguments
12 - warning: unspecified-encoding
21 - warning: unused-variable
21 - warning: unused-variable
|
1 import ie_detector as id
2 import logging as log
3 import cv2
4 import argparse
5 import sys
6
7 def build_argparser():
8 parser = argparse.ArgumentParser()
9 parser.add_argument('-m', '--model', help = 'Path to an .xml \
10 file with a trained model.', required = True, type = str)
11 parser.add_argument('-w', '--weights', help = 'Path to an .bin file \
12 with a trained weights.', required = True, type = str)
13 parser.add_argument('-i', '--input', help = 'Path to \
14 image file.', required = True, type = str)
15 parser.add_argument('-d', '--device', help = 'Device name',
16 default='CPU', type = str)
17 parser.add_argument('-l', '--cpu_extension',
18 help = 'MKLDNN (CPU)-targeted custom layers. \
19 Absolute path to a shared library with the kernels implementation',
20 type = str, default=None)
21 parser.add_argument('-c', '--classes', help = 'File containing \
22 classnames', type = str, default=None)
23 return parser
24
25 def main():
26 log.basicConfig(format="[ %(levelname)s ] %(message)s",
27 level=log.INFO, stream=sys.stdout)
28 args = build_argparser().parse_args()
29 log.info("Start IE detection sample")
30 ie_detector = id.InferenceEngineDetector(configPath=args.model,
31 weightsPath=args.weights,
32 device=args.device,
33 extension=args.cpu_extension,
34 classesPath=args.classes)
35 img = cv2.imread(args.input)
36 detections = ie_detector.detect(img)
37 image_detected = ie_detector.draw_detection(detections, img)
38 cv2.imshow('Image with detections', image_detected)
39 cv2.waitKey(0)
40 cv2.destroyAllWindows()
41 return
42
43 if (__name__ == '__main__'):
44 sys.exit(main()) | 1 - warning: redefined-builtin
25 - refactor: useless-return
|
1 import kivy
2 kivy.require('1.11.1')
3 from kivy.app import App
4 from kivy.lang import Builder
5 from kivy.uix.screenmanager import ScreenManager, Screen
6 from kivy.properties import ObjectProperty
7 from collections import Counter
8 import bot
9 import time
10 import tensorflow as tf
11 import facialrecognition as fr
12 import cv2
13
14 class Home(Screen):
15 pass
16
17
18 class Questions(Screen):
19
20
21 ques_path='Personality Test(base)\Questions.txt'
22 personalities={'isfj':'Defender','esfj':'Cousellor','istj':'Logistician','estp':'Entrepreneur','esfp':'Entertainer','istp':'Virtuoso','isfp':'Adventurer','entj':'Commander','entp':'Debator','intj':'Architect','intp':'Logician','enfj':'Protagonist','enfp':'Campaigner','infj':'Advocate','infp':'Mediator','estj':'Executive'}
23 personality=''
24 questions=[]
25 question_1 = ObjectProperty(None)
26 question_2 = ObjectProperty(None)
27 counter=1
28 answers=[0]*20
29 with open(ques_path) as quest_file:
30 questions=[r.split('SPLIT') for r in quest_file.readlines()]
31
32 def personality_exam(self,answers):
33 e,s,j,t=['e','i'],['s','n'],['j','p'],['t','f']
34 e.extend([answers[r] for r in range(0,20,4)])
35 s.extend([answers[r] for r in range(1,20,4)])
36 t.extend([answers[r] for r in range(2,20,4)])
37 j.extend([answers[r] for r in range(3,20,4)])
38 personality=''
39 for option in e,s,t,j:
40 temp=Counter(option)
41 personality+=option[0] if temp['a']>temp['b'] else option[1]
42 Report.personality=personality
43
44 def on_enter(self, *args):
45 self.question_1.text=self.questions[0][0]
46 self.question_2.text=self.questions[0][1]
47
48 def ask_question1(self):
49 if(self.counter==20):
50 self.answers[self.counter-1]='a'
51 self.personality_exam(self.answers)
52 self.counter=1
53 sm.current = 'rep'
54
55 else:
56 self.question_1.text=self.questions[self.counter][0]
57 self.question_2.text=self.questions[self.counter][1]
58 self.answers[self.counter-1]='a'
59 self.counter+=1
60
61 def ask_question2(self):
62 if(self.counter==20):
63 self.answers[self.counter-1]='b'
64 self.personality_exam(self.answers)
65 self.counter=1
66 sm.current = 'rep'
67
68 else:
69 self.question_1.text=self.questions[self.counter][0]
70 self.question_2.text=self.questions[self.counter][1]
71 self.answers[self.counter-1]='b'
72 self.counter+=1
73
74
75
76 class Report(Screen):
77 personality=''
78 def on_enter(self, *args):
79 self.per.text=Questions.personalities[self.personality]+'\n'+'('+self.personality+')'
80 self.image.source= Report.personality+'\INTRODUCTION\Image.png'
81 class Description(Screen):
82 def on_enter(self, *args):
83 self.persona.text=Questions.personalities[Report.personality]
84 file_path=Report.personality+'\INTRODUCTION\Introduction.txt'
85 with open(file_path) as file:
86 self.detail.text=file.read()
87
88 class CareerOptions(Screen):
89 def on_enter(self, *args):
90 self.persona.text=Questions.personalities[Report.personality]
91 file_path=Report.personality+'\career.txt'
92 with open(file_path) as file:
93 self.detail.text=file.read()
94
95 class Strengths(Screen):
96 def on_enter(self, *args):
97 self.persona.text=Questions.personalities[Report.personality]
98 file_path=Report.personality+'\STRENGTHS\Strengths.txt'
99 with open(file_path) as file:
100 self.detail.text=file.read()
101
102 class CameraClick(Screen):
103
104 emo = ['Angry', 'Fear', 'Happy',
105 'Sad', 'Surprise', 'Neutral']
106 model = tf.keras.models.load_model("facial_1 (1)")
107 buddy=''
108 mood=''
109
110
111 def prepare(self, filepath):
112 IMG_SIZE = 48
113 img_array = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE)
114 new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
115 return new_array.reshape(-1, IMG_SIZE, IMG_SIZE, 1)
116
117 def capture(self):
118
119 camera = self.ids['camera']
120 timestr = time.strftime("%Y%m%d_%H%M%S")
121 name="IMG_{}.png".format(timestr)
122 camera.export_to_png(name)
123 print("Captured")
124 fc=fr.FaceCropper().generate(name,True)
125 try:
126 prediction = self.model.predict([self.prepare(fc)])
127 prediction=list(map(float,prediction[0]))
128 except:
129 prediction="prepare function could not run(0 faces detected)"
130 self.mood='Neutral'
131 print(prediction)
132 try:
133 self.mood=self.emo[prediction.index(max(prediction))] # self.emo[list(prediction[0]).index(1)]
134 except:
135 print("Exception handled..!! Picture could not be cleared properly. Please check lighting")
136 self.mood='Neutral'
137 bot.setname(self.textforcamera.text)
138 print(bot.getname())
139 ChatWindow.mood=self.mood
140
141
142 class ChatWindow(Screen):
143 mood=''
144 bot.pre_processing()
145 #bot.chatcode()
146 def on_enter(self, *args):
147 self.chat_history.text="Hey "+bot.getname()+", what brings you here today!!\n Current Mood: "+self.mood+" !! "
148 def send_message(self):
149 message=self.text.text
150 self.text.text=''
151 #self.history.update_chat_history(f'[color=dd2020]{chat_app.connect_page.username.text}[/color] > {message}')
152 self.chat_history.text += '\n' +"User: "+message
153
154 # Set layout height to whatever height of chat history text is + 15 pixels
155 # (adds a bit of space at teh bottom)
156 # Set chat history label to whatever height of chat history text is
157 # Set width of chat history text to 98 of the label width (adds small margins)
158 #self.layout.height = self.chat_history.texture_size[1] + 15
159 self.chat_history.text_size = (self.chat_history.width * 0.98, None)
160
161 class WindowManager(ScreenManager):
162 pass
163
164 kv=Builder.load_file('design.kv')
165
166 sm = WindowManager()
167 screens=[Home(name="home"), Questions(name="quest"), Report(name="rep"), Description(name='description'), CareerOptions(name='career'), Strengths(name='strengths'), ChatWindow(name='chat'),CameraClick(name='camera')]
168 for screen in screens:
169 sm.add_widget(screen)
170 sm.current = "home"
171
172 class CafeApp(App):
173 def build(self):
174 return sm
175
176 if __name__=='__main__':
177 CafeApp().run() | 21 - warning: anomalous-backslash-in-string
80 - warning: anomalous-backslash-in-string
80 - warning: anomalous-backslash-in-string
84 - warning: anomalous-backslash-in-string
84 - warning: anomalous-backslash-in-string
91 - warning: anomalous-backslash-in-string
98 - warning: anomalous-backslash-in-string
98 - warning: anomalous-backslash-in-string
14 - refactor: too-few-public-methods
29 - warning: unspecified-encoding
44 - warning: unused-argument
78 - warning: unused-argument
76 - refactor: too-few-public-methods
85 - warning: unspecified-encoding
82 - warning: unused-argument
81 - refactor: too-few-public-methods
92 - warning: unspecified-encoding
89 - warning: unused-argument
88 - refactor: too-few-public-methods
99 - warning: unspecified-encoding
96 - warning: unused-argument
95 - refactor: too-few-public-methods
128 - warning: bare-except
134 - warning: bare-except
146 - warning: unused-argument
53 - warning: attribute-defined-outside-init
66 - warning: attribute-defined-outside-init
170 - warning: attribute-defined-outside-init
161 - refactor: too-few-public-methods
172 - refactor: too-few-public-methods
|
1 lst=sorted(list(map(int,input().split())))[::-1]
2 temp=lst[0]
3 for i in range(1,len(lst)):
4 if temp==lst[i]:
5 continue
6 else:
7 print(lst[i])
8 break
9
10
| 4 - refactor: no-else-continue
|
1 """
2 import tensorflow as tf
3 modeltest=tf.keras.models.load_model("facial_1 (1)")
4 print("--model loaded successfully--")
5 """
6 import cv2
7 import sys
8 import os
9
10 class FaceCropper(object):
11 cascades_path = 'haarcascade_frontalface_default.xml'
12
13 def __init__(self):
14 self.face_cascade = cv2.CascadeClassifier(self.cascades_path)
15
16 def generate(self, image_path, show_result):
17 name=""
18 img = cv2.imread(image_path)
19 if (img is None):
20 print("Can't open image file")
21 return 0
22
23 #img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
24 faces = self.face_cascade.detectMultiScale(img, 1.1, 3, minSize=(100, 100))
25 if (faces is None):
26 print('Failed to detect face')
27 return 0
28
29 if (show_result):
30 for (x, y, w, h) in faces:
31
32 cv2.rectangle(img, (x,y), (x+w, y+h), (255,0,0), 2)
33 roi_color = img[y:y + h, x:x + w]
34 print("[INFO] Object found. Saving locally.")
35 name= str(w) + str(h) + '_faces.jpg'
36 cv2.imwrite(str(w) + str(h) + '_faces.jpg', roi_color)
37 #cv2.imshow('cropped image',roi_color)
38 #cv2.imshow('marked image',img)
39 cv2.waitKey(0)
40 cv2.destroyAllWindows()
41
42 facecnt = len(faces)
43 print("Detected faces: %d" % facecnt)
44 i = 0
45 height, width = img.shape[:2]
46
47 for (x, y, w, h) in faces:
48 r = max(w, h) / 2
49 centerx = x + w / 2
50 centery = y + h / 2
51 nx = int(centerx - r)
52 ny = int(centery - r)
53 nr = int(r * 2)
54
55 faceimg = img[ny:ny+nr, nx:nx+nr]
56 lastimg = cv2.resize(faceimg, (32, 32))
57 i += 1
58 cv2.imwrite("image%d.jpg" % i, lastimg)
59 return name
60
61 #fc=FaceCropper().generate("IMG_20200226_000431.png",True)
62
| 10 - refactor: useless-object-inheritance
16 - refactor: too-many-locals
45 - warning: unused-variable
45 - warning: unused-variable
10 - refactor: too-few-public-methods
7 - warning: unused-import
8 - warning: unused-import
|
1 import kivy
2 kivy.require('1.11.1')
3 from kivy.app import App
4 from kivy.lang import Builder
5 from kivy.uix.screenmanager import ScreenManager, Screen
6 from kivy.properties import ObjectProperty
7 import time
8
9 class Home(Screen):
10 def animation_begins(self):
11 textvalue=self.labelvalue.text.split()
12 var=" "
13 for i in textvalue:
14 var+=i
15 self.labelvalue.text=var
16 time.sleep(3)
17
18 class WindowManager(ScreenManager):
19 pass
20
21 kv=Builder.load_file('designing.kv')
22
23 sm = WindowManager()
24 screens=[Home(name="home")]
25 for screen in screens:
26 sm.add_widget(screen)
27 sm.current = "home"
28
29 class CafeApp(App):
30 def build(self):
31 return sm
32
33 if __name__=='__main__':
34 CafeApp().run() | 9 - refactor: too-few-public-methods
27 - warning: attribute-defined-outside-init
18 - refactor: too-few-public-methods
29 - refactor: too-few-public-methods
6 - warning: unused-import
|
1 import kivy
2 kivy.require('1.11.1')
3 from kivy.app import App
4 from kivy.lang import Builder
5 from kivy.uix.screenmanager import ScreenManager, Screen
6 from kivy.properties import ObjectProperty
7 from collections import Counter
8 import time
9
10
11 class Home(Screen):
12 pass
13
14
15 class Questions(Screen):
16
17
18 ques_path='Personality Test(base)\Questions.txt'
19 personalities={'isfj':'Defender','esfj':'Cousellor','istj':'Logistician','estp':'Entrepreneur','esfp':'Entertainer','istp':'Virtuoso','isfp':'Adventurer','entj':'Commander','entp':'Debator','intj':'Architect','intp':'Logician','enfj':'Protagonist','enfp':'Campaigner','infj':'Advocate','infp':'Mediator','estj':'Executive'}
20 personality=''
21 questions=[]
22 question_1 = ObjectProperty(None)
23 question_2 = ObjectProperty(None)
24 counter=1
25 answers=[0]*20
26 with open(ques_path) as quest_file:
27 questions=[r.split('SPLIT') for r in quest_file.readlines()]
28
29 def personality_exam(self,answers):
30 e,s,j,t=['e','i'],['s','n'],['j','p'],['t','f']
31 e.extend([answers[r] for r in range(0,20,4)])
32 s.extend([answers[r] for r in range(1,20,4)])
33 t.extend([answers[r] for r in range(2,20,4)])
34 j.extend([answers[r] for r in range(3,20,4)])
35 personality=''
36 for option in e,s,t,j:
37 temp=Counter(option)
38 personality+=option[0] if temp['a']>temp['b'] else option[1]
39 Report.personality=personality
40
41 def on_enter(self, *args):
42 self.question_1.text=self.questions[0][0]
43 self.question_2.text=self.questions[0][1]
44
45 def ask_question1(self):
46 if(self.counter==20):
47 self.answers[self.counter-1]='a'
48 self.personality_exam(self.answers)
49 self.counter=1
50 sm.current = 'rep'
51
52 else:
53 self.question_1.text=self.questions[self.counter][0]
54 self.question_2.text=self.questions[self.counter][1]
55 self.answers[self.counter-1]='a'
56 self.counter+=1
57
58 def ask_question2(self):
59 if(self.counter==20):
60 self.answers[self.counter-1]='b'
61 self.personality_exam(self.answers)
62 self.counter=1
63 sm.current = 'rep'
64
65 else:
66 self.question_1.text=self.questions[self.counter][0]
67 self.question_2.text=self.questions[self.counter][1]
68 self.answers[self.counter-1]='b'
69 self.counter+=1
70
71
72
73 class Report(Screen):
74 personality=''
75 def on_enter(self, *args):
76 self.per.text=Questions.personalities[self.personality]+'\n'+'('+self.personality+')'
77 self.image.source= Report.personality+'\INTRODUCTION\Image.png'
78 class Description(Screen):
79 def on_enter(self, *args):
80 self.persona.text=Questions.personalities[Report.personality]
81 file_path=Report.personality+'\INTRODUCTION\Introduction.txt'
82 with open(file_path) as file:
83 self.detail.text=file.read()
84
85 class CareerOptions(Screen):
86 def on_enter(self, *args):
87 self.persona.text=Questions.personalities[Report.personality]
88 file_path=Report.personality+'\career.txt'
89 with open(file_path) as file:
90 self.detail.text=file.read()
91
92 class Strengths(Screen):
93 def on_enter(self, *args):
94 self.persona.text=Questions.personalities[Report.personality]
95 file_path=Report.personality+'\STRENGTHS\Strengths.txt'
96 with open(file_path) as file:
97 self.detail.text=file.read()
98
99 class CameraClick(Screen):
100 pass
101
102 class ChatWindow(Screen):
103 pass
104
105 class WindowManager(ScreenManager):
106 pass
107
108 kv=Builder.load_file('design_edit.kv')
109
110 sm = WindowManager()
111 screens=[Home(name="home"), Questions(name="quest"), Report(name="rep"), Description(name='description'), CareerOptions(name='career'), Strengths(name='strengths'), ChatWindow(name='chat'),CameraClick(name='camera')]
112 for screen in screens:
113 sm.add_widget(screen)
114 sm.current = "home"
115
116 class CafeApp(App):
117 def build(self):
118 return sm
119
120 if __name__=='__main__':
121 CafeApp().run() | 18 - warning: anomalous-backslash-in-string
77 - warning: anomalous-backslash-in-string
77 - warning: anomalous-backslash-in-string
81 - warning: anomalous-backslash-in-string
81 - warning: anomalous-backslash-in-string
88 - warning: anomalous-backslash-in-string
95 - warning: anomalous-backslash-in-string
95 - warning: anomalous-backslash-in-string
11 - refactor: too-few-public-methods
26 - warning: unspecified-encoding
41 - warning: unused-argument
75 - warning: unused-argument
73 - refactor: too-few-public-methods
82 - warning: unspecified-encoding
79 - warning: unused-argument
78 - refactor: too-few-public-methods
89 - warning: unspecified-encoding
86 - warning: unused-argument
85 - refactor: too-few-public-methods
96 - warning: unspecified-encoding
93 - warning: unused-argument
92 - refactor: too-few-public-methods
99 - refactor: too-few-public-methods
102 - refactor: too-few-public-methods
50 - warning: attribute-defined-outside-init
63 - warning: attribute-defined-outside-init
114 - warning: attribute-defined-outside-init
105 - refactor: too-few-public-methods
116 - refactor: too-few-public-methods
8 - warning: unused-import
|
1 # -*- coding: utf-8 -*-
2 """
3 Created on Mon Jul 26 15:20:48 2021
4
5 @author: Grant Isaacs
6 """
7
8 #IMPORT LIBRARIES------------------------------------------------------------->
9 import numpy as np
10 import pandas as pd
11 import tensorflow as tf
12 from sklearn.preprocessing import LabelEncoder
13 from sklearn.compose import ColumnTransformer
14 from sklearn.preprocessing import OneHotEncoder
15 from sklearn.model_selection import train_test_split
16 from sklearn.preprocessing import StandardScaler
17 from sklearn.metrics import confusion_matrix, accuracy_score
18
19
20
21
22 #PREPROCESS DATA-------------------------------------------------------------->
23 #load data
24 dataset = pd.read_csv("_")
25 X = dataset.iloc[:, 3:-1].values
26 y = dataset.iloc[:, -1].values
27
28 #check for missing values
29 print(sum(np.equal(X, None)))
30
31 #encode categorical variables
32 lencoder = LabelEncoder()
33 X[: , 2] = lencoder.fit_transform(X[:, 2])
34
35 ctransform = ColumnTransformer(transformers=[('encoder', OneHotEncoder(), [1])], remainder='passthrough')
36 X = np.array(ctransform.fit_transform(X))
37
38 #split dataset into training and test sets
39 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state=361981)
40
41 #scale the features
42 scaler = StandardScaler()
43 X_train = scaler.fit_transform(X_train)
44 X_test = scaler.transform(X_test)
45
46
47
48
49 #STRUCTURE THE ANN------------------------------------------------------------>
50 #initialize the neural network
51 neural_net = tf.keras.models.Sequential()
52
53 #create the input layer and first hidden layer to form a shallow learning model.
54 """Layer quantity is determined by experimentation and expertise."""
55 neural_net.add(tf.keras.layers.Dense(units=6, activation='relu'))
56
57 #create the second hidden layer to form a deep learning model.
58 neural_net.add(tf.keras.layers.Dense(units=6, activation='relu'))
59
60 #add the output layer
61 """Output units equals the output dimensions minus 1.
62 This model generates a probability between 0 and 1 (Sigmoid)"""
63 neural_net.add(tf.keras.layers.Dense(units=1, activation='sigmoid'))
64
65
66
67
68 #TRAIN THE ANN---------------------------------------------------------------->
69 #compile the neural network
70 """In this example the adam optimizer is used for stochastic gradient desecent.
71 The output is binary so binary cross entropy is selected for the loss function."""
72 neural_net.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
73
74 #train the neural network
75 """Batch and Epoch arguments were chose based on previous training data.
76 Modify accordingly."""
77 neural_net.fit(X_train, y_train, batch_size=32, epochs=100)
78
79
80
81
82 #GENERATE PREDICTIONS--------------------------------------------------------->
83 #predict test set
84 y_pred = neural_net.predict(X_test)
85 y_pred = (y_pred > 0.5)
86 y_test = y_test.reshape(len(y_test), 1)
87 y_pred = y_pred.reshape(len(y_pred), 1)
88 print(np.concatenate((y_pred, y_test), 1))
89
90 #build confusion matrix
91 cmatrix = confusion_matrix(y_test, y_pred)
92 print(cmatrix)
93 print(accuracy_score(y_test, y_pred))
94
95 #individual prediction
96 """Apply the transform method to scale the variables to the same distribution as the training data."""
97 pred = neural_net.predict(scaler.transform([[1.0, 0.0, 0.0, 600, 1, 40, 3, 60000, 2, 1, 1, 50000]]))
98 print("Predicted Probabilty the Customer will leave: {}".format(pred))
99
100 pred = neural_net.predict(scaler.transform([[1.0, 0.0, 0.0, 600, 1, 40, 3, 60000, 2, 1, 1, 50000]])) > 0.5
101 print("Binary statement will the customer leave: {}".format(pred)) | 61 - warning: pointless-string-statement
70 - warning: pointless-string-statement
75 - warning: pointless-string-statement
96 - warning: pointless-string-statement
|
1 import gzip
2 import json
3 import csv
4
5
6 class Dataset:
7 def __init__(self, filename):
8 self.filename = filename
9
10 def read_json(self, useful_keys=(), required_keys=(), is_gzip=False, encoding='utf8'):
11 """
12 :param useful_keys: (tuple): Keys to return for each dataset record. Pass empty to return all keys.
13 :param required_keys: (tuple): Required keys for each record. If one of these keys does not exist, this function ignores the dataset record.
14 :param is_gzip: (boolean): Whether the file is a compressed file or not.
15 :param encoding: (string): The default is 'utf8'.
16 :return: (list of dictionary): For each JSON record, return a dictionary inside a list.
17 """
18 dataset = list()
19 if is_gzip:
20 open_function = gzip.GzipFile
21 else:
22 open_function = open
23 # Load dataset file
24 with open_function(self.filename, 'rb') as file:
25 # For each record in dataset
26 for line in file:
27 data = json.loads(line, encoding=encoding)
28 # By default get the dataset record
29 append_record = True
30 # If required keys does not exist do not get the record otherwise
31 for key in required_keys:
32 if not data.get(key):
33 append_record = False
34 break
35 # get useful reviews
36 if append_record:
37 # Determine useful keys
38 useful = ()
39 if 0 == len(useful_keys):
40 useful = data.keys()
41 else:
42 useful = useful_keys
43 temp = {}
44 for key in useful:
45 temp[key] = data.get(key)
46 dataset.append(temp)
47 return dataset
48
49 def read_csv(self, useful_keys=(), required_keys=(), delimiter=',', is_gzip=False, encoding='utf8'):
50 """
51 :param useful_keys: (tuple or string): Keys to return for each dataset record. Pass empty to return all keys.
52 :param required_keys: (tuple): Required keys for each record. If one of these keys does not exist, this function ignores the dataset record.
53 :param delimiter: (string): CSV delimiter
54 :param is_gzip: (boolean): Whether the file is a compressed file or not.
55 :param encoding: (string): The default is 'utf8'.
56 :return: (list of list | list): For each CSV row, return a list inside another list and a list of headers.
57 """
58 dataset = list()
59 if is_gzip:
60 open_function = gzip.open
61 else:
62 open_function = open
63 # Load dataset file
64 with open_function(self.filename, mode='rt', encoding=encoding) as file:
65 content = csv.reader((line.replace('\0', '') for line in file), delimiter=delimiter)
66 # Get keys of dataset
67
68 headers = next(content)
69 # Transform keys to index
70 useful = []
71 required = []
72 if 0 == len(useful_keys):
73 iteration = headers
74 else:
75 iteration = useful_keys
76 for key in iteration:
77 useful.append(headers.index(key))
78 for key in required_keys:
79 required.append(headers.index(key))
80 # For each record in dataset
81 for row in content:
82 if not row:
83 continue
84 # By default get the record from dataset
85 append_record = True
86 # If one of required keys does not exists ignore this dataset record otherwise get the record
87 for i in required:
88 if row[i] == '':
89 append_record = False
90 break
91 if append_record:
92 dataset.append(list(row[index] for index in useful))
93 return dataset, headers
94
| 7 - warning: bad-indentation
8 - warning: bad-indentation
10 - warning: bad-indentation
11 - warning: bad-indentation
18 - warning: bad-indentation
19 - warning: bad-indentation
20 - warning: bad-indentation
21 - warning: bad-indentation
22 - warning: bad-indentation
24 - warning: bad-indentation
26 - warning: bad-indentation
27 - warning: bad-indentation
29 - warning: bad-indentation
31 - warning: bad-indentation
32 - warning: bad-indentation
33 - warning: bad-indentation
34 - warning: bad-indentation
36 - warning: bad-indentation
38 - warning: bad-indentation
39 - warning: bad-indentation
40 - warning: bad-indentation
41 - warning: bad-indentation
42 - warning: bad-indentation
43 - warning: bad-indentation
44 - warning: bad-indentation
45 - warning: bad-indentation
46 - warning: bad-indentation
47 - warning: bad-indentation
49 - warning: bad-indentation
50 - warning: bad-indentation
58 - warning: bad-indentation
59 - warning: bad-indentation
60 - warning: bad-indentation
61 - warning: bad-indentation
62 - warning: bad-indentation
64 - warning: bad-indentation
65 - warning: bad-indentation
68 - warning: bad-indentation
70 - warning: bad-indentation
71 - warning: bad-indentation
72 - warning: bad-indentation
73 - warning: bad-indentation
74 - warning: bad-indentation
75 - warning: bad-indentation
76 - warning: bad-indentation
77 - warning: bad-indentation
78 - warning: bad-indentation
79 - warning: bad-indentation
81 - warning: bad-indentation
82 - warning: bad-indentation
83 - warning: bad-indentation
85 - warning: bad-indentation
87 - warning: bad-indentation
88 - warning: bad-indentation
89 - warning: bad-indentation
90 - warning: bad-indentation
91 - warning: bad-indentation
92 - warning: bad-indentation
93 - warning: bad-indentation
18 - refactor: use-list-literal
49 - refactor: too-many-arguments
49 - refactor: too-many-positional-arguments
49 - refactor: too-many-locals
58 - refactor: use-list-literal
|
1 import pandas as pd
2 import os
3 THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
4 my_file_estate = os.path.join(THIS_FOLDER,'csv\\Real estate.csv')
5
6 def Write_Csv(list_data):
7 df = pd.read_csv(my_file_estate)
8 file = open(my_file_estate,"a")
9 number=df['No'].values[-1]
10 number+=1
11 file.write(str(number)+",")
12 for i in list_data:
13 if i != list_data[6]:
14 file.write(str(i)+",")
15 else :file.write(str(i)+"\n")
16 file.close()
17 df.reset_index(drop = True,inplace=True)
| 8 - warning: unspecified-encoding
8 - refactor: consider-using-with
|
1 from flask import Flask,request
2 import scikit_learn
3 import Write_Csv
4 app = Flask(__name__)
5 #append data(from url) to list
6 def Data_append(x1,x2,x3,x4,x5,x6):
7 list_data=[]
8 list_data.append(x1)
9 list_data.append(x2)
10 list_data.append(x3)
11 list_data.append(x4)
12 list_data.append(x5)
13 list_data.append(x6)
14 return list_data
15
16 #route /
17 #take data from url then send them to scikit_learn of Calculate price from scikit
18 #return information
19 @app.route('/')
20 def hello_world():
21 transaction_date=float(request.args.get('transaction_date'))
22 house_age=float(request.args.get('house_age'))
23 distance_to_the__nearest_MRT_station=float(request.args.get('distance_to_the__nearest_MRT_station'))
24 number_of_convenience_stores=float(request.args.get('number_of_convenience_stores'))
25 latitude=float(request.args.get('latitude'))
26 longitude=float(request.args.get('longitude'))
27 list_data=[]
28 list_data=Data_append(transaction_date,house_age,distance_to_the__nearest_MRT_station,number_of_convenience_stores,latitude,longitude)
29 price=scikit_learn.path(list_data)
30 list_data.append(price)
31 Write_Csv.Write_Csv(list_data)
32 return '''<h3>
33 transaction date : {}<br>
34 house age= {}<br>
35 distance to the nearest MRT station= {}<br>
36 number of convenience stores= {}<br>
37 latitude= {}<br>
38 longitude= {}<br>
39 price ={}
40 </h3>'''.format(transaction_date,house_age,distance_to_the__nearest_MRT_station,number_of_convenience_stores,latitude,longitude,price)
41
42 #to run servier => py app.py -path ./model.pickle
43 if __name__ == '__main__':
44 app.run(port=5060,debug=False,use_reloader=False)
45 # http://127.0.0.1:5060/?transaction_date=2017.917&house_age=10&distance_to_the__nearest_MRT_station=306.59470&number_of_convenience_stores=15&latitude=24.98034&longitude=121.53951
| 21 - warning: bad-indentation
22 - warning: bad-indentation
23 - warning: bad-indentation
24 - warning: bad-indentation
25 - warning: bad-indentation
26 - warning: bad-indentation
27 - warning: bad-indentation
28 - warning: bad-indentation
29 - warning: bad-indentation
30 - warning: bad-indentation
31 - warning: bad-indentation
32 - warning: bad-indentation
6 - refactor: too-many-arguments
6 - refactor: too-many-positional-arguments
|
1 import pickle
2 import argparse
3 import numpy as np
4
5
6 #take model
7 #Calculate price from scikit
8 def path(list_data):
9 parser = argparse.ArgumentParser()
10 parser.add_argument("-path","--path",type = str)
11 args = parser.parse_args()
12 # './model.pickle'
13 loaded_model = pickle.load(open(args.path, 'rb'))
14 x = np.array(list_data).reshape(1,6)
15 result = loaded_model.predict(x)
16 if x.shape[0] == 1:
17 result = result[0]
18 return result
| 13 - refactor: consider-using-with
|
1 # Menu-Driven program
2
3 import string
4 import random
5
6 # just for reference purposes.
7 from Part_1 import all_prime
8 from Part_2 import even_odd
9 from Part_3 import prime_composite
10 from Part_4 import vowel_consonant
11 from Part_5 import check_in_group
12
13 while True:
14 print('\nChoose your Option - ')
15 print('0. Exit')
16 print('1. Print Prime Numbers between 1 to 1000.')
17 print('2. To Find whether Number is ODD or EVEN.')
18 print('3. To Find whether Number is PRIME or COMPOSITE.')
19 print('4. To Find whether Alphabet is VOWEL or NOT.')
20 print('5. To Check specified Value n Group of Values')
21 option = input('Enter - ')
22 try:
23 option = int(option)
24 except:
25 print('\tINVALID CHOICE.\n\tTRY AGAIN.\n')
26 continue
27
28 if (option < 0 or option > 5):
29 print('\tINVALID CHOICE.\n\tTRY AGAIN.\n')
30 continue
31
32 if option == 0:
33 print('\n\tTHANK YOU FOR JOINING US!')
34 exit(-1)
35 elif option == 1:
36 all_prime()
37 elif option == 2:
38 even_odd()
39 elif option == 3:
40 prime_composite()
41 elif option == 4:
42 vowel_consonant()
43 elif option == 5:
44 check_in_group()
| 24 - warning: bare-except
34 - refactor: consider-using-sys-exit
3 - warning: unused-import
4 - warning: unused-import
|
1 # Write a Python program to check whether a
2 # specified value is contained in a group of values.
3
4 # 3 -> [1, 5, 8, 3] : True -1 -> [1, 5, 8, 3] : False
5
6 import random
7
8 def check_in_group():
9 while True:
10 test_case = [1, 5, 8, 3]
11 print('\nEnter \'-1\' to QUIT.')
12 value = input('Enter - ')
13 try:
14 value = int(value)
15 except:
16 print('\tINVALID CHOICE.\n\tTRY AGAIN.\n')
17 continue
18 if value == -1:
19 print('\tTHANK YOU.\n\tRETURNING TO MAIN MENU.\n')
20 break
21 if value in test_case:
22 print('True')
23 break
24 else:
25 print('False')
26 continue
27
28
29 # in case needed.
30 def check_random():
31 while True:
32 test_case = list()
33 length = input('\nEnter Length of the test_case - ')
34 try:
35 length = int(length)
36 except:
37 print('\tINVALID CHOICE.\n\tTRY AGAIN.\n')
38 continue
39 for _ in range(length):
40 test_case.append(random.choice(range(10)))
41 break
42 # print(test_case)
43 while True:
44 print('\nEnter \'-1\' to QUIT.')
45 value = input('Enter - ')
46 try:
47 value = int(value)
48 except:
49 print('\tINVALID CHOICE.\n\tTRY AGAIN.\n')
50 continue
51 if value == -1:
52 print('\tTHANK YOU.\n\tRETURNING TO MAIN MENU.\n')
53 break
54 if value in test_case:
55 print('True')
56 break
57 else:
58 print('False')
59 continue
| 15 - warning: bare-except
21 - refactor: no-else-break
32 - refactor: use-list-literal
36 - warning: bare-except
48 - warning: bare-except
54 - refactor: no-else-break
|
1 # Realizar un programa que utilizando una estructura repetitiva (bucle) presente por pantalla
2 # los números del 1 al 10 separados por un guión.
3 # El resultado debe ser similar a esto:
4
5 # 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10
6
7
8 for i in range(1,11):
9 print(i, end="-")
| 9 - warning: bad-indentation
|
1 import string
2
3
4 def open_file():
5 fname = input('Type the filename: ')
6 fhandler = open(fname, encoding='utf-8')
7 return fhandler
8
9
10 def count_characters(filehandler, text):
11 # print('------Printin filehandler: ', filehandler)
12
13 char_count = dict()
14 for line in filehandler:
15 line = line.strip().lower()
16 line = line.translate(line.maketrans('', '', string.punctuation))
17 # print('--After doing strip each char, Character: ', line)
18 text = text + line
19 print('')
20 print('____________________________________________')
21 print('The text after concatenate lines: ', text)
22 print('|')
23 print('|___Type of the text variable: ', type(text))
24 print('____________________________________________')
25 # tratar de no hacer un for anidado aca, eso es lo que hay que mejorar de este codio
26
27 for character in text:
28 # print('')
29 # print('Char in text:', character)
30 if character.isalpha():
31 if character in char_count:
32 char_count[str(character)] += 1
33 else:
34 char_count[str(character)] = 1
35 # char_count[character] = char_count.get(character)
36 else:
37 continue
38 return char_count
39
40
41 def order_by_decreasing(counter):
42 inverse_counter_lst = list()
43 for element in counter:
44 inverse_counter_lst.append((counter[element], element))
45
46 inverse_counter_lst.sort(reverse=True)
47
48 for number, element in inverse_counter_lst:
49 print(f'{element} -> {number}')
50
51
52 first_text = ""
53 # order_by_decreasing(count_characters(open_file(), first_text))
54 print(count_characters(open_file(), first_text))
| 6 - refactor: consider-using-with
13 - refactor: use-dict-literal
42 - refactor: use-list-literal
|
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 """
5
6 Alejandro Valeriano Fernandez - GITT
7 Ejercicio 13.6
8 Calculadora
9
10 """
11
12 import sys
13
14 def suma(operando1, operando2):
15 try:
16 return int(operando1) + int(operando2)
17 except NameError:
18 print ("Invalid arguments")
19
20 def rest(operando1, operando2):
21 try:
22 return int(operando1) - int(operando2)
23 except NameError:
24 print ("Invalid arguments")
25
26 def mult(operando1, operando2):
27 try:
28 return int(operando1) * int(operando2)
29 except NameError:
30 print ("Invalid arguments")
31
32 def div(operando1, operando2):
33 try:
34 return float(operando1) / float(operando2)
35 except NameError:
36 print ("Invalid arguments")
37
38
39 if __name__ == "__main__":
40
41 if len(sys.argv) != 4:
42 print
43 sys.exit("Usage: $ python calculadora.py funcion operando1 operando2")
44
45 if sys.argv[1] == 'add':
46 print sys.argv[2] + ' mas ' + sys.argv[3] + ' = ' + str(suma (sys.argv[2], sys.argv[3]))
47
48 if sys.argv[1] == 'substract':
49 print sys.argv[2] + ' menos ' + sys.argv[3] + ' = ' + str(rest (sys.argv[2], sys.argv[3]))
50
51 if sys.argv[1] == 'multiply':
52 print sys.argv[2] + ' por ' + sys.argv[3] + ' = ' + str(mult (sys.argv[2], sys.argv[3]))
53
54 if sys.argv[1] == 'divide':
55 try:
56 print sys.argv[2] + ' entre ' + sys.argv[3] + ' = ' + str(div (sys.argv[2], sys.argv[3]))
57
58 except:
59 print 'error al dividir'
60 else:
61 print 'Las posibles operaciones son "add", "substract", "multiply" y "divide"'
| 46 - error: syntax-error
|
1 from re import findall
2 from subprocess import check_output
3 from pwd import getpwall
4
5 d = {}
6 filesearch = open("/etc/login.defs","r")
7
8 for line in filesearch:
9 if findall("^UID_(MIN|MAX)",line):
10 a = line.strip().split()
11 d[str(a[0])] = str(a[1])
12
13 filesearch.close()
14
15 for p in getpwall():
16 if int(p[2]) >= int(d['UID_MIN']) and int(p[2]) <= int(d['UID_MAX']):
17 print p[0] | 17 - error: syntax-error
|
1 #!/usr/bin/python
2 import pyrax, time, sys, multiprocessing, argparse, os, __builtin__
3
4 parser = argparse.ArgumentParser(description='Remove Cloud Files Fast')
5 parser.add_argument('--container', nargs='?', dest='cont', required=True, help="The Cloud Contain To Remove Objects From")
6 parser.add_argument('--username', nargs='?', dest='username', help="Your Cloud Username")
7 parser.add_argument('--password', nargs='?', dest='password', help="Your Cloud API Key")
8 parser.add_argument('--file', nargs='?', dest='file', help="Your Cloud API Key File")
9 parser.add_argument('--region', nargs='?', dest='region', help="Set the Cloud File region")
10 args = parser.parse_args()
11
12 def authenticate(username='', passwd='', path=''):
13 if username or passwd:
14 pyrax.set_credentials(username,passwd)
15 elif path:
16 pyrax.set_credential_file(os.path.expanduser(path))
17 else:
18 print "Authentication Failed... please use username/password or file to authenticate"
19 sys.exit()
20
21 def worker(num):
22 try:
23 global obj
24 print "Deleting:", obj[num].name
25 obj[num].delete()
26 #time.sleep(1 + random.random()*5)
27 #print num
28 except:
29 print "Unexpected error in worker:", sys.exc_info()
30 raise
31
32 def pooling(length):
33 try:
34 pool = multiprocessing.Pool(processes=20)
35 for num in xrange(length):
36 pool.apply_async(worker, [num])
37 #pool.apply(worker,[num])
38 pool.apply_async(time.sleep, 5)
39 pool.close()
40 pool.join()
41 except:
42 print "Unexpected error in pooling:", sys.exc_info()[0]
43 raise
44
45 if __name__ == "__main__":
46 authenticate(username=args.username,passwd=args.password,path=args.file)
47 cf = pyrax.connect_to_cloudfiles(region=args.region)
48 limit = 10000
49 marker = ""
50 obj = cf.get_container(args.cont).get_objects(limit=limit, marker=marker)
51 while obj:
52 try:
53 marker = obj.pop()
54 length = len(obj)
55 pooling(length)
56 obj = cf.get_container(args.cont).get_objects(limit=limit, marker=marker.name)
57 except:
58 print "Unexpected error:", sys.exc_info()[0]
59 raise | 18 - error: syntax-error
|
1 import sqlite3 as lite
2 import sys
3 import argparse
4 from time import strftime
5 from subprocess import check_output
6
7
8 def collect():
9 # Grab information from mtr
10 output = check_output(["mtr","-nr","-c5","50.56.142.146"])
11 date = strftime('%Y%m%d %H%M')
12
13 # split the data into an array and clean up array a bit
14 a = output.split("\n")
15 del a[0]
16 del a[-1]
17
18 # Connect to the sqlite3 server to place the information into it
19 con = lite.connect('/root/icmp/data.db')
20 cur = con.cursor()
21
22 # loop through the data and store information into sqlite
23 for i in a:
24 array = i.replace("%","").split()
25 del array[0]
26 cur.execute("insert into netreport values ('%s','%s',%0.1f,%i,%0.1f,%0.1f,%0.1f,%0.1f,%0.1f);" %
27 (str(date), str(array[0]), float(array[1]), int(array[2]), float(array[3]), float(array[4]), float(array[5]), float(array[6]), float(array[7]),))
28 con.commit()
29 if con:
30 con.close()
31
32 if __name__ == '__main__':
33 collect() | 10 - warning: bad-indentation
11 - warning: bad-indentation
14 - warning: bad-indentation
15 - warning: bad-indentation
16 - warning: bad-indentation
19 - warning: bad-indentation
20 - warning: bad-indentation
23 - warning: bad-indentation
24 - warning: bad-indentation
25 - warning: bad-indentation
26 - warning: bad-indentation
28 - warning: bad-indentation
29 - warning: bad-indentation
30 - warning: bad-indentation
33 - warning: bad-indentation
2 - warning: unused-import
3 - warning: unused-import
|
1 #!/usr/bin/python
2 import pyinotify
3
4 class MyEventHandler(pyinotify.ProcessEvent):
5 def process_IN_CREATE(self, event):
6 print "CREATE event:", event.pathname
7 def process_IN_DELETE(self, event):
8
9 def main():
10 wm = pyinotify.WatchManager()
11 wm.add_watch('/home/brya5376/test'), pyinotify.ALL_EVENTS, rec=True)
12
13 if __name__ == '__main__':
14 main()
15
16 # http://www.saltycrane.com/blog/2010/04/monitoring-filesystem-python-and-pyinotify/ | 11 - error: syntax-error
|
1 import os, re
2 def filePop(top):
3 sizeList = []
4 #exclude = "^/proc.*|^/sys.*|^/boot.*|^/tmp.*|^/mnt.*"
5 exclude = "^/proc.*|^/sys.*|^/boot.*|/tmp.*|/home.*|/var.*|/data.*"
6 # Skip any files that are located in /proc, /sys or /boot
7 for root,dirs,files in os.walk(top):
8 if re.findall(exclude,root):
9 continue
10 for f in files:
11 fullpath = os.path.join(root,f)
12 if (os.path.isfile(fullpath) or os.path.isdir(fullpath)) and not os.path.islink(fullpath):
13 sizeList.append((os.path.getsize(fullpath),fullpath))
14 return sizeList
15
16 def fileSort(fileList,top=15):
17 sList = sorted(fileList, key=lambda a: a[0], reverse=True)
18 for i in xrange(0,15):
19 size = ((sList[i][0] / 1024) / 1024)
20 directory = sList[i][1]
21 print '%s MB --> %s' % (size,directory)
22
23 fileSort(filePop("/")) | 21 - error: syntax-error
|
1 # import tensorflow as tf
2 import cv2
3 import sys
4 sys.path.append("..")
5 import utils
6 import numpy as np
7
8 model_path = "./models/train_mnist1_model3.h5"
9 img_path = "../img/seven.png"
10 # img_path = "../img/one.png"
11 # img_path = "../img/six.png"
12
13 mnist_model = utils.load_model(model_path)
14
15 ## Way 1
16 print("Way 1")
17 digit_img = utils.standarize_digit_img_to_model_input(img_path, 28)
18 bin_digit_img = utils.binarize_img(digit_img)
19 img = utils.prepare_to_predict(bin_digit_img)
20
21 cv2.imshow("Digit", digit_img)
22 cv2.imshow("Binary digit", bin_digit_img)
23 cv2.waitKey(50)
24
25 prob_predictions = mnist_model.predict(img)
26 prediction = [(np.where(item == np.amax(item)))[0][0] for item in prob_predictions]
27 print("Prediction: {}".format(prediction[0]))
28
29
30 ## Way 2
31 print("Way 2")
32 prediction = utils.predict_digit(mnist_model, img_path)
33 print("Prediction: {}".format(prediction))
| Clean Code: No Issues Detected
|
1 import numpy as np
2 from random import randint
3 from copy import deepcopy
4 import cv2
5 import utils
6 import grid
7 import paho.mqtt.client as mqtt
8 import io
9 from PIL import Image
10
11 # Global variables
12 BROKER_ADRESS = "192.168.9.201"
13 sudoku_grid = [[5, 3, 0, 0, 7, 0, 0, 0, 0],
14 [6, 0, 0, 1, 9, 5, 0, 0, 0],
15 [0, 9, 8, 0, 0, 0, 0, 6, 0],
16 [8, 0, 0, 0, 6, 0, 0, 0, 3],
17 [4, 0, 0, 8, 0, 3, 0, 0, 1],
18 [7, 0, 0, 0, 2, 0, 0, 0, 6],
19 [0, 6, 0, 0, 0, 0, 2, 8, 0],
20 [0, 0, 0, 4, 1, 9, 0, 0, 5],
21 [0, 0, 0, 0, 8, 0, 0, 0, 9]]
22 counter = 0
23 solutions = []
24 recur_cnt = 0
25 IMG_NAME = 'puzzle1.jpg'
26
27
28 def on_connect(client, userdata, flags, rc):
29 print("Connected to broker with result code " + str(rc))
30 client.subscribe("sudoku/#")
31
32
33 def on_message(client, userdata, msg):
34 global counter
35 counter = 0
36 if msg.topic == "sudoku/photo":
37 try:
38 stream = io.BytesIO(msg.payload)
39 open_cv_image = np.array(Image.open(stream).convert('RGB'))
40 # Convert RGB to BGR
41 open_cv_image = open_cv_image[:, :, ::-1].copy()
42 cv2.imwrite('./mqtt_com/' + IMG_NAME, open_cv_image)
43 except Exception as e:
44 print("Exception: ")
45 print(e)
46 solve_sudoku()
47 send_solution(client)
48 if msg.payload.decode() == "End":
49 print("Okey! I'm disconnecting :)")
50 client.disconnect()
51
52
53 def send_message(client, topic, msg):
54 client.publish(topic, msg)
55
56
57 def is_possible(y, x, n):
58 global sudoku_grid
59 for i in range(0, 9):
60 if sudoku_grid[y][i] == n:
61 return False
62 for j in range(0, 9):
63 if sudoku_grid[j][x] == n:
64 return False
65 x0 = (x//3)*3
66 y0 = (y//3)*3
67 for k in range(0, 3):
68 for l in range(0, 3):
69 if sudoku_grid[y0+k][x0+l] == n:
70 return False
71 return True
72
73
74 def solve_recursion():
75 global sudoku_grid, counter, solutions, recur_cnt
76 recur_cnt += 1
77 if recur_cnt > 10**5:
78 return
79 for y in range(9):
80 for x in range(9):
81 if sudoku_grid[y][x] == 0:
82 for n in range(1, 10):
83 if is_possible(y, x, n):
84 sudoku_grid[y][x] = n
85 solve_recursion()
86 sudoku_grid[y][x] = 0
87 return
88 counter += 1
89 solutions.append(deepcopy(sudoku_grid))
90
91
92 def solve_sudoku():
93 global sudoku_grid, counter, solutions
94 model = utils.load_mnist_model()
95 img = cv2.imread("./mqtt_com/" + IMG_NAME)
96 sudoku_grid = grid.recognize_grid(model, img)
97
98 solve_recursion()
99 print("Number or recurrent function invocations: {}".format(recur_cnt))
100 print("There are {} possible solutions".format(counter))
101 if len(solutions) > 0:
102 print("Random solution:")
103 solved_grid = solutions[randint(0, counter - 1)]
104 print(np.matrix(solved_grid))
105
106 img_solved = grid.draw_solved_grid(model, img, solved_grid)
107 cv2.imwrite("./results/" + IMG_NAME, img_solved)
108 # cv2.imshow("Solved sudoku", img_solved)
109 # cv2.waitKey(0)
110
111
112 def send_solution(client):
113 global solutions, counter
114 with open("./results/" + IMG_NAME, "rb") as f:
115 fileContent = f.read()
116 byteArrayPhoto = bytearray(fileContent)
117 client.publish("sudoku/solution/photo", byteArrayPhoto)
118 # client.publish("sudoku/solution/grid", str(solutions[randint(0, counter - 1)]))
119
120
121 def main():
122 client = mqtt.Client()
123 client.connect(BROKER_ADRESS, 1883, 60)
124 client.on_connect = on_connect
125 client.on_message = on_message
126 client.loop_forever()
127
128
129 if __name__ == "__main__":
130 main()
131
| 28 - warning: unused-argument
28 - warning: unused-argument
34 - warning: global-statement
43 - warning: broad-exception-caught
33 - warning: unused-argument
58 - warning: global-variable-not-assigned
75 - warning: global-variable-not-assigned
75 - warning: global-variable-not-assigned
93 - warning: global-variable-not-assigned
93 - warning: global-variable-not-assigned
113 - warning: global-variable-not-assigned
113 - warning: global-variable-not-assigned
|
1 import cv2
2 from copy import deepcopy
3 import numpy as np
4 import utils
5
6 RESCALE = 3
7
8 def find_cell_param(joints):
9 # Set up the detector with default parameters.
10 params = cv2.SimpleBlobDetector_Params()
11 # filter by area
12 params.filterByArea = True
13 params.minArea = 1
14 params.maxArea = 50
15 detector = cv2.SimpleBlobDetector_create(params)
16 # Detect blobs
17 keypoints = detector.detect(~joints)
18 sorted_keypoints = sorted(keypoints, key=lambda x: (x.pt[0], x.pt[1]))
19 min_keypoint = sorted_keypoints[0]
20 max_keypoint = sorted_keypoints[-1]
21 # for it, keypoint in enumerate(keypoints):
22 # img_contours = deepcopy(img)
23 # Draw detected blobs as red circles.
24 # cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures the size of the circle corresponds to the size of blob
25 # im_with_keypoints = cv2.drawKeypoints(img_contours, [min_keypoint, max_keypoint], np.array([]), (0, 0, 255),
26 # cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
27 # cv2.imshow("Keypoints", im_with_keypoints)
28 # cv2.waitKey(0)
29 return (max_keypoint.pt[0] - min_keypoint.pt[0]) / 7, (max_keypoint.pt[1] - min_keypoint.pt[1]) / 7, min_keypoint.pt, max_keypoint.pt
30
31
32 def get_joints(img):
33 img = cv2.resize(img, (int(img.shape[1]/RESCALE), int(img.shape[0]/RESCALE)))
34 # retval = cv2.getPerspectiveTransform(img) TO DO https://blog.ayoungprogrammer.com/2013/03/tutorial-creating-multiple-choice.html/
35 img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
36 bin_img = cv2.adaptiveThreshold(cv2.bitwise_not(img_gray), 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 15, -2)
37 # cv2.imshow("Bin: ", bin_img)
38 # cv2.waitKey(0)
39 scale = 20
40 horizontal_size = bin_img.shape[0] // scale
41 horizontal_structure = cv2.getStructuringElement(cv2.MORPH_RECT, (horizontal_size, 1))
42 img_eroded_horizontal = cv2.erode(bin_img, horizontal_structure, anchor=(-1, -1))
43 img_dilated_horizontal = cv2.erode(img_eroded_horizontal, horizontal_structure, anchor=(-1, -1))
44
45 vertical_size = bin_img.shape[1] // scale
46 vertical_structure = cv2.getStructuringElement(cv2.MORPH_RECT, (1, vertical_size))
47 img_eroded_vertical = cv2.erode(bin_img, vertical_structure, anchor=(-1, -1))
48 img_dilated_vertical = cv2.erode(img_eroded_vertical, vertical_structure, anchor=(-1, -1))
49
50 # mask = img_dilated_vertical + img_dilated_horizontal
51 joints = cv2.bitwise_and(img_dilated_horizontal, img_dilated_vertical)
52 # cv2.imshow("joints: ", joints)
53 # cv2.waitKey(0)
54 return bin_img, joints
55
56
57 def recognize_grid(model, img):
58 bin_img, joints = get_joints(img)
59 cell_height, cell_width, min_pt, max_pt = find_cell_param(joints)
60 grid = []
61 for x in range(-1, 8):
62 row = []
63 for y in range(-1, 8):
64 roi = bin_img[int(min_pt[1]+cell_width*x):int(min_pt[1]+cell_width*(x+1)),
65 int(min_pt[0]+cell_height*y):int(min_pt[0]+cell_height*(y+1))]
66 alpha = 0.1
67 roi = roi[int(roi.shape[1]*alpha):int(roi.shape[1]*(1-alpha)), int(roi.shape[0]*alpha):int(roi.shape[0]*(1-alpha))]
68 row.append(utils.predict_digit(model, roi))
69 # cv2.imshow("ROI: ", roi)
70 # cv2.waitKey(0)
71 grid.append(row)
72 return grid
73
74
75 def draw_solved_grid(model, img, solved_sudoku):
76 solved_img = deepcopy(cv2.resize(img, (int(img.shape[1] / RESCALE), int(img.shape[0] / RESCALE))))
77 bin_img, joints = get_joints(img)
78 cell_height, cell_width, min_pt, max_pt = find_cell_param(joints)
79 for x in range(-1, 8):
80 for y in range(-1, 8):
81 roi = bin_img[int(min_pt[1]+cell_width*x):int(min_pt[1]+cell_width*(x+1)),
82 int(min_pt[0]+cell_height*y):int(min_pt[0]+cell_height*(y+1))]
83 alpha = 0.1
84 roi = roi[int(roi.shape[1]*alpha):int(roi.shape[1]*(1-alpha)), int(roi.shape[0]*alpha):int(roi.shape[0]*(1-alpha))]
85 if utils.predict_digit(model, roi) == 0:
86 pt = (int((min_pt[0] + cell_height * y + min_pt[0] + cell_height * (y + 1))/2) - 5, int((min_pt[1] + cell_width * x + min_pt[1] + cell_width * (x + 1))/2)+8)
87 cv2.putText(solved_img, str(solved_sudoku[x+1][y+1]), pt, cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2)
88 return solved_img
89
90
91 def main():
92 model = utils.load_mnist_model()
93 img = cv2.imread("./SudokuOnline/puzzle1.jpg")
94
95 sudoku_grid = recognize_grid(model, img)
96 print(np.matrix(sudoku_grid))
97
98 img = cv2.resize(img, (int(img.shape[1]/RESCALE), int(img.shape[0]/RESCALE)))
99 cv2.imshow("Img: ", img)
100 # cv2.imshow("Gray: ", img_gray)
101 # cv2.imshow("Bin: ", bin_img)
102 # cv2.imshow("Dilated horizontal: ", img_dilated_horizontal)
103 # cv2.imshow("Dilated vertical: ", img_dilated_vertical)
104 # cv2.imshow("Joints: ", joints)
105 # cv2.imshow("Mask: ", mask)
106 cv2.waitKey(0)
107
108
109 if __name__ == "__main__":
110 main()
| 59 - warning: unused-variable
78 - warning: unused-variable
|
1 import cv2
2 import numpy as np
3 import tensorflow
4
5
6 def standarize_digit_img_to_model_input(img, size):
7 if isinstance(img, str):
8 img = cv2.imread(img)
9 img_resized = cv2.resize(img, (size, size))
10 return img_resized
11
12
13 def binarize_img(img):
14 gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
15 blur = cv2.GaussianBlur(gray_img, (5, 5), 0)
16 ret, th = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
17 return cv2.bitwise_not(th)
18
19
20 def prepare_to_predict(img):
21 return img.reshape(1, 28, 28, 1) / 255.0
22
23
24 def predict_digit(model, img):
25 digit_img = standarize_digit_img_to_model_input(img, 28)
26 if len(img.shape) == 3:
27 bin_digit_img = binarize_img(digit_img)
28 else:
29 bin_digit_img = digit_img
30 img = prepare_to_predict(bin_digit_img)
31 prob_predictions = model.predict(img)
32 if np.any(prob_predictions > 0.7):
33 prediction = [(np.where(item == np.amax(item)))[0][0] for item in prob_predictions]
34 return prediction[0]
35 else:
36 return 0
37
38
39 def load_model(model_path):
40 return tensorflow.keras.models.load_model(model_path)
41
42
43 def load_mnist_model():
44 model_path = "./MNISTmodel/models/train_mnist1_model3.h5"
45 return tensorflow.keras.models.load_model(model_path)
46
| 16 - warning: unused-variable
32 - refactor: no-else-return
|
1 import numpy as np
2 from random import randint
3 from copy import deepcopy
4 import cv2
5 import utils
6 import grid
7
8 # Global variables
9 sudoku_grid = [[5, 3, 0, 0, 7, 0, 0, 0, 0],
10 [6, 0, 0, 1, 9, 5, 0, 0, 0],
11 [0, 9, 8, 0, 0, 0, 0, 6, 0],
12 [8, 0, 0, 0, 6, 0, 0, 0, 3],
13 [4, 0, 0, 8, 0, 3, 0, 0, 1],
14 [7, 0, 0, 0, 2, 0, 0, 0, 6],
15 [0, 6, 0, 0, 0, 0, 2, 8, 0],
16 [0, 0, 0, 4, 1, 9, 0, 0, 5],
17 [0, 0, 0, 0, 8, 0, 0, 0, 9]]
18 counter = 0
19 solutions = []
20 recur_cnt = 0
21
22
23 def is_possible(y, x, n):
24 global sudoku_grid
25 for i in range(0, 9):
26 if sudoku_grid[y][i] == n:
27 return False
28 for j in range(0, 9):
29 if sudoku_grid[j][x] == n:
30 return False
31 x0 = (x//3)*3
32 y0 = (y//3)*3
33 for k in range(0, 3):
34 for l in range(0, 3):
35 if sudoku_grid[y0+k][x0+l] == n:
36 return False
37 return True
38
39
40 def solve_recursion():
41 global sudoku_grid, counter, solutions, recur_cnt
42 recur_cnt += 1
43 if recur_cnt > 10**5:
44 return
45 for y in range(9):
46 for x in range(9):
47 if sudoku_grid[y][x] == 0:
48 for n in range(1, 10):
49 if is_possible(y, x, n):
50 sudoku_grid[y][x] = n
51 solve_recursion()
52 sudoku_grid[y][x] = 0
53 return
54 counter += 1
55 solutions.append(deepcopy(sudoku_grid))
56
57
58 def main():
59 global sudoku_grid, counter, solutions
60 model = utils.load_mnist_model()
61 img = cv2.imread("./SudokuOnline/puzzle1.jpg")
62
63 sudoku_grid = grid.recognize_grid(model, img)
64
65 solve_recursion()
66 print("Number or recurrent function invocations: {}".format(recur_cnt))
67 print("There are {} possible solutions".format(counter))
68 if len(solutions) > 0:
69 print("Random solution:")
70 solved_grid = solutions[randint(0, counter - 1)]
71 print(np.matrix(solved_grid))
72
73 img_solved = grid.draw_solved_grid(model, img, solved_grid)
74 cv2.imwrite("./results/result1.jpg", img_solved)
75 cv2.imshow("Solved sudoku", img_solved)
76 cv2.waitKey(0)
77
78
79 if __name__ == "__main__":
80 main()
81
| 24 - warning: global-variable-not-assigned
41 - warning: global-variable-not-assigned
41 - warning: global-variable-not-assigned
59 - warning: global-variable-not-assigned
59 - warning: global-variable-not-assigned
|
1 import tensorflow as tf
2 import datetime
3 import os
4 import numpy as np
5 from tensorflow.python.keras.callbacks import TensorBoard
6
7 mnist = tf.keras.datasets.mnist
8 (training_images, training_labels), (test_images, test_labels) = mnist.load_data()
9
10 # print(training_images.shape)
11 # print(test_images.shape)
12 training_images = training_images / 255.0
13 test_images = test_images / 255.0
14 training_images = training_images.reshape(training_images.shape[0], 28, 28, 1)
15 test_images = test_images.reshape(test_images.shape[0], 28, 28, 1)
16
17 test_images, validation_images = np.split(test_images, [int(test_images.shape[0]*0.4)])
18 test_labels, validation_labels = np.split(test_labels, [int(test_labels.shape[0]*0.4)])
19
20 model = tf.keras.models.Sequential([
21 tf.keras.layers.Conv2D(64, (3, 3), activation='relu', input_shape=(28, 28, 1)),
22 tf.keras.layers.MaxPooling2D(2, 2),
23 tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
24 tf.keras.layers.MaxPooling2D(2, 2),
25 tf.keras.layers.Flatten(),
26 tf.keras.layers.Dense(64, activation='relu'),
27 tf.keras.layers.Dense(10, activation='softmax')
28 ])
29
30
31 ## Designing callbacks
32 class myCallback(tf.keras.callbacks.Callback):
33 def on_epoch_end(self, epoch, logs={}):
34 print("\nReached {} epoch".format(epoch + 1))
35 if logs.get('accuracy') > 0.997:
36 print("Reached 99.99% accuracy so cancelling training!")
37 self.model.stop_training = True
38
39
40 log_dir = os.path.join(
41 "logs",
42 "fit",
43 datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))
44 tensorboard_callback = TensorBoard(log_dir=log_dir, histogram_freq=1)
45
46 model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
47 model.fit(training_images,
48 training_labels,
49 validation_data=(validation_images, validation_labels),
50 epochs=20,
51 callbacks=[myCallback(), tensorboard_callback],
52 verbose=2)
53
54 # model.summary()
55 metrics = model.evaluate(test_images, test_labels)
56 print("[Loss, Accuracy]")
57 print(metrics)
58 model.save("./models/train_mnist1_model3.h5")
59
| 17 - warning: unbalanced-tuple-unpacking
18 - warning: unbalanced-tuple-unpacking
33 - warning: dangerous-default-value
32 - refactor: too-few-public-methods
|
1 import os
2 import time
3
4 from selenium.common.exceptions import TimeoutException
5 from selenium.webdriver.common.by import By
6 from selenium.webdriver.common.keys import Keys
7 from selenium.webdriver.support.expected_conditions import presence_of_element_located
8 from selenium.webdriver.support.wait import WebDriverWait
9
10 from helpers import print_timestamp
11
12
13 class Mei:
14 def __init__(self, driver, files_path, uf):
15 self.driver = driver
16 self.files_path = os.path.join(os.getcwd(), files_path)
17 # print(self.files_path)
18 self.uf = uf
19
20 def _retorna_xpath(self, driver, timeout, freq, xpath):
21 wbw = WebDriverWait(driver=driver,
22 timeout=timeout,
23 poll_frequency=freq)
24 wbw.until(presence_of_element_located((By.XPATH, xpath)),
25 "Elemento não encontrado.")
26 xpath = driver.find_element_by_xpath(xpath)
27 return xpath
28
29 def retorna_tabela(self, xpath_btn_consulta, xpath_tab_completa):
30 time.sleep(2)
31 print('Extraindo tabela.', print_timestamp())
32 tentativas = [1, 2, 3]
33 for i in tentativas:
34 print(f"Tentativa {i} de 3...")
35 self.driver.find_element_by_xpath(xpath_btn_consulta).click()
36 try:
37 self._retorna_xpath(self.driver, 150, 5, xpath_tab_completa)
38 print('Tabela carregada.', print_timestamp())
39 return True
40 except TimeoutException:
41 print('Tabela não foi carregada.')
42 return False
43
44 def del_arquivos_inuteis(self):
45 files_path = self.files_path
46 for file in os.listdir(files_path):
47 if file[:13] == 'relatorio_mei':
48 os.remove(os.path.join(files_path, file))
49
50 def renomeia_arquivo(self):
51 files_path = self.files_path
52 uf = self.uf
53 file = r'relatorio_mei.csv'
54 if file in os.listdir(files_path):
55 old_file = os.path.join(files_path, file)
56 new_file = self.nome_arquivo(uf)
57 new_file = os.path.join(files_path, new_file)
58 try:
59 os.rename(old_file, new_file)
60 print(f"Arquivo renomeado para {new_file} " + print_timestamp())
61 except FileExistsError:
62 print("Arquivo já existe.")
63
64 def verifica_arquivo(self):
65 files_path = self.files_path
66 if not os.path.exists(files_path):
67 os.mkdir(files_path)
68 print(f"Arquivos baixados ficarão na pasta {files_path}.")
69 uf = self.uf
70 name = self.nome_arquivo(uf)
71 if name in os.listdir(files_path):
72 return name
73 else:
74 return False
75
76 def nome_arquivo(self, uf):
77 data = print_timestamp(now=False)
78 return f"{uf}_cnae_e_municipios_{data}.csv"
79
80 def exporta_csv(self):
81 driver = self.driver
82 xpath_btn_exportar = '//*[@id="form:botaoExportarCsv"]'
83 driver.find_element_by_xpath(xpath_btn_exportar).click()
84 time.sleep(10)
85 print('Download concluído.', print_timestamp())
86
87 def abre_browser(self):
88 url = 'http://www22.receita.fazenda.gov.br/inscricaomei/private/pages/relatorios/opcoesRelatorio.jsf#'
89 xpath = '/html/body/table/tbody/tr[2]/td/form/div/div/div[1]/p'
90
91 while True:
92 driver = self.driver
93 try:
94 driver.get(url)
95 print('Browser iniciado. ' + print_timestamp())
96 print('Extraindo ' + self.uf + '...')
97 self._retorna_xpath(driver, 15, 5, xpath)
98 break
99 except TimeoutException as e:
100 driver.quit()
101 print(e)
102
103 def carrega_pagina_relatorio(self, xpath_page):
104 driver = self.driver
105 page = driver.find_element_by_xpath(xpath_page)
106 page.click()
107
108 def uf_listbox(self, xpath_listbox):
109 time.sleep(5)
110 driver = self.driver
111 uf = self.uf
112 el = driver.find_element_by_xpath(xpath_listbox)
113 for option in el.find_elements_by_tag_name('option'):
114 if option.text == uf:
115 option.click()
116 break
117
118
119 class MeiCnaeMunicipio(Mei):
120 xpath_page = '/html/body/table/tbody/tr[2]/td/form/div/div/div[1]/ul/li[6]/a'
121 xpath_listbox = '//*[@id="form:uf"]'
122 xpath_municipios = '//*[@id="form:listaMunicipiosUF"]'
123 xpath_relatorio = '//*[@id="form:listaMunicipiosRelatorio"]'
124 xpath_btn_inserir = '//*[@id="form:btnInserir"]'
125 xpath_btn_consulta = '//*[@id="form:botaoConsultar"]'
126 xpath_tab_completa = '//*[@id="form:j_id62"]'
127
128 def __init__(self, driver, files_path, uf):
129 super().__init__(driver, files_path, uf)
130
131 def verifica_listbox_municipios(self):
132 driver = self.driver
133 for tries in [1, 2, 3]:
134 print(f"Carregando municípios. Tentativa {tries}/3.", print_timestamp())
135 time.sleep(5)
136 # verifica se a 1a listbox está preenchida
137 cities = driver.find_element_by_xpath(self.xpath_municipios)
138 n_cities = len(cities.text.split('\n'))
139 if n_cities > 1 or cities.text == 'BRASILIA':
140 cities.find_elements_by_tag_name('option')[0].click()
141 cities.send_keys(Keys.SHIFT, Keys.END)
142 driver.find_element_by_xpath(self.xpath_btn_inserir).click()
143 time.sleep(5)
144 # verifica se a 2a listbox está preenchida
145 rel = driver.find_element_by_xpath(self.xpath_relatorio)
146 n_rel = len(rel.text.split('\n'))
147 if n_rel > 1 or rel.text == 'BRASILIA':
148 print("Municipíos carregados.")
149 break
150 # se nao atenderem as condições
151 if n_cities <= 1 and tries == 3:
152 print("Não foi possível carregar os municípios.")
153 return False
154 return True
155
156
157 class MeiCnaeSexoUF(Mei):
158 xpath_page = '/html/body/table/tbody/tr[2]/td/form/div/div/div[1]/ul/li[7]/a'
159 xpath_listbox = '//*[@id="form:uf"]'
160 xpath_municipios = '//*[@id="form:municipioUF"]'
161 xpath_btn_consulta = '//*[@id="form:botaoConsultar"]'
162 xpath_tab_completa = '//*[@id="form:botaoExportarCsv"]'
163
164 def __init__(self, driver, files_path, uf):
165 super().__init__(driver, files_path, uf)
166
167 def nome_arquivo(self, uf):
168 data = print_timestamp(now=False)
169 return f"{uf}_cnae_e_sexo_{data}.csv"
| 71 - refactor: no-else-return
128 - warning: useless-parent-delegation
164 - warning: useless-parent-delegation
|
1 from selenium import webdriver
2
3
4 def config(path_folder: str, headless: bool):
5 fp = webdriver.FirefoxProfile()
6 fp.set_preference("browser.download.folderList", 2)
7 fp.set_preference("browser.download.manager.showWhenStarting", False)
8 fp.set_preference("browser.download.dir", path_folder)
9 fp.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/csv")
10 fp.set_preference("dom.disable_beforeunload", True)
11 fp.set_preference("browser.download.manager.closeWhenDone", True)
12
13 options = webdriver.FirefoxOptions()
14 if headless:
15 options.add_argument('-headless')
16
17 driver = webdriver.Firefox(fp, options=options)
18
19 return driver
| Clean Code: No Issues Detected
|
1 import time
2
3
4 def print_timestamp(now=True):
5 timestamp = time.localtime(time.time())
6 if now:
7 print_time = '{}/{}/{} {}:{}:{}'.format(timestamp.tm_mday, timestamp.tm_mon, timestamp.tm_year,
8 timestamp.tm_hour, timestamp.tm_min, timestamp.tm_sec)
9 return print_time
10 print_time = '{:04d}{:02d}{:02d}'.format(timestamp.tm_year, timestamp.tm_mon, timestamp.tm_mday)
11 return print_time
12
13
14 def retorna_ufs():
15 with open('lista de uf.txt', 'r', encoding='latin-1') as f:
16 file = f.readlines()
17 ufs = [uf[:-1] for uf in file]
18 return ufs
| Clean Code: No Issues Detected
|
1 import os
2 import fire
3
4 from selenium.common.exceptions import NoSuchElementException, \
5 WebDriverException, NoSuchWindowException
6
7 from init import config
8 from mei import MeiCnaeMunicipio, MeiCnaeSexoUF
9 from helpers import retorna_ufs
10
11
12 def ufs_por_municipio_cnae(pasta="arquivos", invisivel=True):
13 ufs = retorna_ufs()
14 for uf in ufs:
15 uf_por_municipio_cnae(uf=uf, pasta=pasta, invisivel=invisivel)
16
17
18 def uf_por_municipio_cnae(uf="PERNAMBUCO", pasta="arquivos", invisivel=True):
19 path_file = os.path.join(os.getcwd(), pasta)
20 driver = config(path_file, headless=invisivel)
21 mei = MeiCnaeMunicipio(driver, path_file, uf)
22 file = mei.verifica_arquivo()
23 if not file:
24 mei.del_arquivos_inuteis()
25 try:
26 mei.abre_browser()
27 mei.carrega_pagina_relatorio(mei.xpath_page)
28 mei.uf_listbox(mei.xpath_listbox)
29 checkbox = mei.verifica_listbox_municipios()
30 if checkbox:
31 table = mei.retorna_tabela(mei.xpath_btn_consulta,
32 mei.xpath_tab_completa)
33 if table:
34 mei.exporta_csv()
35 mei.renomeia_arquivo()
36 else:
37 print(f"Não foi possível exportar o arquivo")
38 else:
39 print(f"Não foi possível exportar o arquivo.")
40 driver.quit()
41 except (NoSuchElementException, WebDriverException,
42 NoSuchWindowException) as e:
43 print(e)
44 driver.quit()
45 print("Não foi possível exportar o arquivo.")
46 else:
47 print(f"O arquivo {file} já existe.")
48
49
50 def ufs_por_sexo_cnae(pasta="arquivos", invisivel=True):
51 ufs = retorna_ufs()
52 for uf in ufs:
53 uf_por_sexo_cnae(uf=uf, pasta=pasta, invisivel=invisivel)
54
55
56 def uf_por_sexo_cnae(uf="PERNAMBUCO", pasta="arquivos", invisivel=True):
57 path_file = os.path.join(os.getcwd(), pasta)
58 driver = config(path_file, headless=invisivel)
59 mei = MeiCnaeSexoUF(driver, path_file, uf)
60 file = mei.verifica_arquivo()
61 if not file:
62 mei.del_arquivos_inuteis()
63 try:
64 mei.abre_browser()
65 mei.carrega_pagina_relatorio(mei.xpath_page)
66 mei.uf_listbox(mei.xpath_listbox)
67 table = mei.retorna_tabela(mei.xpath_btn_consulta,
68 mei.xpath_tab_completa)
69 if table:
70 mei.exporta_csv()
71 mei.renomeia_arquivo()
72 else:
73 print(f"Não foi possível exportar o arquivo")
74 driver.quit()
75 except (NoSuchElementException, WebDriverException,
76 NoSuchWindowException) as e:
77 print(e)
78 driver.quit()
79 print("Não foi possível exportar o arquivo.")
80 else:
81 print(f"O arquivo {file} já existe.")
82
83
84 if __name__ == '__main__':
85 fire.Fire()
| 37 - warning: f-string-without-interpolation
39 - warning: f-string-without-interpolation
73 - warning: f-string-without-interpolation
|
1 from sqlalchemy import create_engine
2 from sqlalchemy.orm import scoped_session, sessionmaker
3 import csv
4
5 database_url = "postgres://ioovleludzhxle:a966a7d36f9e61edd437415d538afd38b89ab723d71177647d3766c32e0b2106@ec2-54-221-243-211.compute-1.amazonaws.com:5432/d3a4ekarkutr2s"
6 engine = create_engine(database_url)
7 db = scoped_session(sessionmaker(bind=engine))
8
9 def import_books():
10 csv_file = open('books.csv', 'r')
11 rows = csv.reader(csv_file, delimiter=',')
12 cur_row = 0
13 db.execute("""CREATE TABLE books (
14 id SERIAL PRIMARY KEY,
15 isbn varchar NOT NULL,
16 title varchar NOT NULL,
17 author varchar NOT NULL,
18 year INTEGER NOT NULL)""")
19 for row in rows:
20 if cur_row != 0:
21 db.execute("INSERT INTO books (isbn, title, author, year) VALUES (:isbn, :title, :author, :year)",
22 {"isbn": row[0], "title": row[1], "author": row[2], "year": int(row[3])})
23 cur_row += 1
24 db.commit()
25
26
27
28
29
30
31 if __name__ == '__main__':
32 import_books() | 10 - warning: unspecified-encoding
10 - refactor: consider-using-with
|
1 #IF a table has an already defined relationship:
2 # Build a statement to join census and state_fact tables: stmt
3 stmt = select([census.columns.pop2000, state_fact.columns.abbreviation])
4
5 # Execute the statement and get the first result: result
6 result = connection.execute(stmt).first()
7
8 # Loop over the keys in the result object and print the key and value
9 for key in result.keys():
10 print(key, getattr(result, key))
11
12
13 # Build a statement to select the census and state_fact tables: stmt
14 stmt = select([census, state_fact])
15
16 # Add a select_from clause that wraps a join for the census and state_fact
17 # tables where the census state column and state_fact name column match
18 stmt = stmt.select_from(
19 census.join(state_fact, census.columns.state == state_fact.columns.name))
20
21 # Execute the statement and get the first result: result
22 result = connection.execute(stmt).first()
23
24 # Loop over the keys in the result object and print the key and value
25 for key in result.keys():
26 print(key, getattr(result, key))
27
28
29 # Build a statement to select the state, sum of 2008 population and census
30 # division name: stmt
31 stmt = select([
32 census.columns.state,
33 func.sum(census.columns.pop2008),
34 state_fact.columns.census_division_name
35 ])
36
37 # Append select_from to join the census and state_fact tables by the census state and state_fact name columns
38 stmt = stmt.select_from(
39 census.join(state_fact, census.columns.state == state_fact.columns.name)
40 )
41
42 # Append a group by for the state_fact name column
43 stmt = stmt.group_by(state_fact.columns.name)
44
45 # Execute the statement and get the results: results
46 results = connection.execute(stmt).fetchall() | 3 - error: undefined-variable
3 - error: undefined-variable
3 - error: undefined-variable
6 - error: undefined-variable
14 - error: undefined-variable
14 - error: undefined-variable
14 - error: undefined-variable
19 - error: undefined-variable
19 - error: undefined-variable
19 - error: undefined-variable
19 - error: undefined-variable
22 - error: undefined-variable
31 - error: undefined-variable
32 - error: undefined-variable
33 - error: undefined-variable
33 - error: undefined-variable
34 - error: undefined-variable
39 - error: undefined-variable
39 - error: undefined-variable
39 - error: undefined-variable
39 - error: undefined-variable
43 - error: undefined-variable
46 - error: undefined-variable
|
1 # Import create_engine
2 from sqlalchemy import create_engine
3
4 # Create an engine that connects to the census.sqlite file: engine
5 engine = create_engine('sqlite:///census.sqlite')
6
7 connection = engine.connect()
8
9 # Build select statement for census table: stmt
10 stmt = "SELECT * FROM census"
11
12 # Execute the statement and fetch the results: results
13 results = connection.execute(stmt).fetchall()
14
15 # Print results
16 print(results)
17
18 #ALTERNATIVELY
19 # Import select
20 from sqlalchemy import select
21
22 # Reflect census table via engine: census
23 census = Table('census', metadata, autoload=True, autoload_with=engine)
24
25 # Build select statement for census table: stmt
26 stmt = select([census])
27
28 # Print the emitted statement to see the SQL emitted
29 print(stmt)
30
31 # Execute the statement and print the results
32 print(connection.execute(stmt).fetchall())
33
34 #
35 #Recall the differences between a ResultProxy and a ResultSet:
36 #
37 # ResultProxy: The object returned by the .execute() method. It can be used in a variety of ways to get the data returned by the query.
38 # ResultSet: The actual data asked for in the query when using a fetch method such as .fetchall() on a ResultProxy.
39
40 #This separation between the ResultSet and ResultProxy allows us to fetch as much or as little data as we desire.
41
42 results = connection.execute(stmt).fetchall()
43
44 # Get the first row of the results by using an index: first_row
45 first_row = results[0]
46
47 # Print the first row of the results
48 print(first_row)
49
50 # Print the first column of the first row by using an index
51 print(first_row[0])
52
53 # Print the 'state' column of the first row by using its name
54 print(first_row['state']) | 23 - error: undefined-variable
23 - error: undefined-variable
|
1 #Basics of reading in:
2 filename = 'file.txt'
3 file = open(filename, mode = 'r') #'r' is top read, 'w' is to write
4 text = file.read()
5 file.close()
6
7 with open('huck_finn.txt', 'r') as file: #with is referred to as the context manager
8 print(file.read())
9
10
11 #Using NumPy - for numeric arrays
12 #This allows use of sci-kit learn
13 import numpy as np
14
15 #Can use:
16 data = np.loadtxt(filename, delimiter = "'", skiprows = 1, usecols=[0, 2], dtype=str)
17
18 #Alternatively, use Pandas (this is preferable)
19
20 import pandas as pd
21
22 data = pd.read_csv(filename, sep = '\t', comment='#', na_values='Nothing') #comment drops everything after '#', na_values are user specified nulls
23 #header=0 and names=new_names will label the rows
24 #parse_date does something
25 #index_col specifies which col should be the index
26
27
28 data.head() #prints first 5 rows .head(10) displays 10 rows
29
30 data_array = data.values #converts to numpy array
31
32 #Other types of import files:
33
34 #Pickled file: files containing python data structures that don't traslate to an obvious readible form (i.e. dicts, lists, tuples)
35 # Import pickle package
36 import pickle
37
38 # Open pickle file and load data: d
39 with open('data.pkl', 'rb') as file:
40 d = pickle.load(file)
41
42 #Excel
43 file = "excel.xlsx"
44 data = pd.ExcelFile(file)
45
46 print(data.sheet_names)
47
48 df1 = data.parse('name_of_sheet')
49 df2 = data.parse(1) #index of sheet
50 df1 = data.parse(0, skiprows=[1], names=['Country', 'AAM due to War (2002)'])
51
52 #SAS
53 # Import sas7bdat package
54 from sas7bdat import SAS7BDAT
55
56 # Save file to a DataFrame: df_sas
57 with SAS7BDAT('sales.sas7bdat') as file:
58 df_sas = file.to_data_frame()
59
60 #Stata
61 # Import pandas
62 import pandas as pd
63
64 # Load Stata file into a pandas DataFrame: df
65 df = pd.read_stata('disarea.dta')
66
67 #HDF5 (Hierarchical Data Format version 5)
68 import h5py
69
70 # Assign filename: file
71 file = 'LIGO_data.hdf5'
72
73 # Load file: data
74 data = h5py.File(file, 'r')
75
76 # Print the datatype of the loaded file
77 print(type(data))
78
79 # Print the keys of the file. HDF5 files have a heirarchical structure that can be drilled down using the keys
80 for key in data.keys():
81 print(key)
82
83 group = data['strain']
84
85 # Check out keys of group
86 for key in group.keys():
87 print(key)
88
89 # Set variable equal to time series data: strain
90 strain = data['strain']['Strain'].value
91
92
93 #MATLAB
94 # Import package
95 import scipy.io
96
97 # Load MATLAB file: mat
98 mat = scipy.io.loadmat('albeck_gene_expression.mat') #loads a dict with the variables : values of thingfs that were saved in the MATLAB workspace
99
| 8 - warning: bad-indentation
58 - warning: bad-indentation
3 - warning: unspecified-encoding
7 - warning: unspecified-encoding
62 - warning: reimported
3 - refactor: consider-using-with
|
1 #Row concatenation
2 row_concat = pd.concat([uber1, uber2, uber3])
3 #where each is a df
4 #Note though that the original row indices will be maintained
5 #Use the ignore_index = True to reset the indices in sequential order
6
7 #Use the axis =1 to do column concatenation
8
9 #If we have many files to concatenate:
10 # Import necessary modules
11 import glob
12 import pandas as pd
13
14 # Write the pattern: pattern
15 pattern = '*.csv'
16 # * = all strings
17 # ? = single character
18
19 # Save all file matches: csv_files
20 csv_files = glob.glob(pattern)
21 #this gives a list of files that match the pattern
22
23 # Create an empty list: frames
24 frames = []
25
26 # Iterate over csv_files
27 for csv in csv_files:
28
29 # Read csv into a DataFrame: df
30 df = pd.read_csv(csv)
31
32 # Append df to frames
33 frames.append(df)
34
35 # Concatenate frames into a single DataFrame: uber
36 uber = pd.concat(frames) | 2 - error: used-before-assignment
2 - error: undefined-variable
2 - error: undefined-variable
2 - error: undefined-variable
|
1 #EG:
2 id treatment gender response
3 0 1 A F 5
4 1 2 A M 3
5 2 3 B F 8
6 3 4 B M 9
7
8 df.pivot(index = "treatment", columns = "gender", values = "response")
9 #pivot
10 gender F M
11 treatment
12 A 5 3
13 B 8 9
14
15 #Not specifying the values will pivot all columns | 2 - error: syntax-error
|
1 # Import plotting modules
2 import matplotlib.pyplot as plt
3 import seaborn as sns
4
5 # Plot a linear regression between 'weight' and 'hp'
6 sns.lmplot(x='weight', y='hp', data=auto)
7
8 # Display the plot
9 plt.show()
10
11 #RESIDUALS
12 # Import plotting modules
13 import matplotlib.pyplot as plt
14 import seaborn as sns
15
16 # Generate a green residual plot of the regression between 'hp' and 'mpg'
17 sns.residplot(x='hp', y='mpg', data=auto, color='green')
18
19 # Display the plot
20 plt.show()
21
22 #HIGHER ORDER
23 # Generate a scatter plot of 'weight' and 'mpg' using red circles
24 plt.scatter(auto['weight'], auto['mpg'], label='data', color='red', marker='o')
25
26 # Plot in blue a linear regression of order 1 between 'weight' and 'mpg'
27 sns.regplot(x='weight', y='mpg', data=auto, label='order 1', color='blue', order=1, scatter=None)
28
29 # Plot in green a linear regression of order 2 between 'weight' and 'mpg'
30 sns.regplot(x='weight', y='mpg', data=auto, label='order 2', color='green', order=2, scatter=None)
31
32 # Add a legend and display the plot
33 plt.legend(loc='upper right')
34 plt.show()
35
36
37 # Plot a linear regression between 'weight' and 'hp', with a hue (specifies categories) of 'origin' and palette of 'Set1'
38 sns.lmplot('weight', 'hp', data=auto, hue='origin', palette='Set1')
39
40 # Display the plot
41 plt.show()
42
43 # Plot linear regressions between 'weight' and 'hp' grouped row-wise by 'origin'
44 sns.lmplot('weight', 'hp', data=auto, row='origin')
45
46 # Display the plot
47 plt.show() | 6 - error: undefined-variable
13 - warning: reimported
14 - warning: reimported
17 - error: undefined-variable
24 - error: undefined-variable
24 - error: undefined-variable
27 - error: undefined-variable
30 - error: undefined-variable
38 - error: undefined-variable
44 - error: undefined-variable
|
1 '''This was created after installing virtualenv. This allows use to create a virtual environment that mimics
2 a fresh Python install. This ensures that any updates to packages don't affect previous applications built on previous package versions.
3
4 Run: conda create -n venv python=3.5.0 anaconda
5 to create a virtual env called venv with python 3.5.0
6
7 conda activate venv
8 conda deactivate'''
9
10 from flask import Flask, request
11 from flask_restful import Resource, Api
12
13 app = Flask(__name__)
14 api = Api(app)
15
16 items = []
17
18 class Item(Resource):
19 def get(self, name):
20 item = next(filter(lambda x: x['name'] == name, items), None) #if next produces nothing, return None
21 return {"item" : item}, 200 if item is not None else 404
22
23 def post(self, name):
24 #Note that the 'Header' and 'Body' need to be set
25 if next(filter(lambda x: x['name'] == name, items), None) is not None:
26 return {"message" : "an item with name '{}' already exists.".format(name)}, 400 #400 = bad request
27
28 data = request.get_json() #args: force:Forces the content header, silent: returns None (generally don't use)
29 item = {'name' : name, 'price' : data['price']}
30 items.append(item)
31
32 return item, 201 #201 is code for created
33
34 class ItemList(Resource):
35 def get(self):
36 return{"items" : items}
37
38 api.add_resource(Item, '/item/<string:name>') #http://127.0.0.1:5000/item/item_name
39 api.add_resource(ItemList, '/items')
40 app.run(port=5000, debug=True) #debug gives better error messages | 19 - warning: bad-indentation
20 - warning: bad-indentation
21 - warning: bad-indentation
23 - warning: bad-indentation
25 - warning: bad-indentation
26 - warning: bad-indentation
28 - warning: bad-indentation
29 - warning: bad-indentation
30 - warning: bad-indentation
32 - warning: bad-indentation
35 - warning: bad-indentation
36 - warning: bad-indentation
34 - refactor: too-few-public-methods
|
1 import sqlite3
2
3 connection = sqlite3.connect('data.db')
4
5 cursor = connection.cursor() #similar to a screen cursor, it allows us to selct and start thinigs. It executes the queries
6
7 create_table = "CREATE TABLE users (id int, username text, password text)"
8 cursor.execute(create_table)
9
10
11 user = (1, "damien", "bitches")
12 insert_query = "INSERT INTO users VALUES (?, ?, ?)"
13 cursor.execute(insert_query, user)
14
15 users = [
16 (2, "not damien", "notbitches"),
17 (3, "other", "otherps")
18 ]
19 cursor.executemany(insert_query, users)
20
21 select_query = "SELECT * from users"
22 a = cursor.execute(select_query)
23 res = connection.execute("SELECT name FROM sqlite_master WHERE type='table';")
24 for name in res:
25 print (name[0])
26 print(next(a))
27
28 connection.commit()
29
30 connection.close() | Clean Code: No Issues Detected
|
1 # Create a select query: stmt
2 stmt = select([census])
3
4 # Add a where clause to filter the results to only those for New York
5 stmt = stmt.where(census.columns.state == 'New York')
6
7 # Execute the query to retrieve all the data returned: results
8 results = connection.execute(stmt).fetchall()
9
10 # Loop over the results and print the age, sex, and pop2008
11 for result in results:
12 print(result.age, result.sex, result.pop2008)
13
14 # Create a query for the census table: stmt
15 stmt = select([census])
16
17 # Append a where clause to match all the states in_ the list states
18 stmt = stmt.where(census.columns.state.in_(states))
19
20 # Loop over the ResultProxy and print the state and its population in 2000
21 for i in connection.execute(stmt).fetchall():
22 print(i.state, i.pop2000)
23
24 # Import and_
25 from sqlalchemy import and_
26
27 # Build a query for the census table: stmt
28 stmt = select([census])
29
30 # Append a where clause to select only non-male records from California using and_
31 stmt = stmt.where(
32 # The state of California with a non-male sex
33 and_(census.columns.state == 'California',
34 census.columns.sex != 'M'
35 )
36 )
37
38 # Loop over the ResultProxy printing the age and sex
39 for result in connection.execute(stmt).fetchall():
40 print(result.age, result.sex)
41
42 # Build a query to select the state column: stmt
43 stmt = select([census.columns.state])
44
45 # Order stmt by the state column
46 stmt = stmt.order_by(census.columns.state) #desc(census.columns.state)
47
48 ## Build a query to select state and age: stmt
49 #stmt = select([census.columns.state, census.columns.age])
50 #
51 ## Append order by to ascend by state and descend by age
52 #stmt = stmt.order_by(census.columns.state, desc(census.columns.age))
53
54 # Execute the query and store the results: results
55 results = connection.execute(stmt).fetchall()
56
57 # Print the first 10 results
58 print(results[:10]) | 2 - error: undefined-variable
2 - error: undefined-variable
5 - error: undefined-variable
8 - error: undefined-variable
15 - error: undefined-variable
15 - error: undefined-variable
18 - error: undefined-variable
18 - error: undefined-variable
21 - error: undefined-variable
28 - error: undefined-variable
28 - error: undefined-variable
33 - error: undefined-variable
34 - error: undefined-variable
39 - error: undefined-variable
43 - error: undefined-variable
43 - error: undefined-variable
46 - error: undefined-variable
55 - error: undefined-variable
|
1 # Import pandas
2 import pandas as pd
3
4 # Read 'monthly_max_temp.csv' into a DataFrame: weather1
5 weather1 = pd.read_csv('monthly_max_temp.csv', index_col='Month')
6
7 # Print the head of weather1
8 print(weather1.head())
9
10 # Sort the index of weather1 in alphabetical order: weather2
11 weather2 = weather1.sort_index()
12
13 # Print the head of weather2
14 print(weather2.head())
15
16 # Sort the index of weather1 in reverse alphabetical order: weather3
17 weather3 = weather1.sort_index(ascending=False)
18
19 # Print the head of weather3
20 print(weather3.head())
21
22 # Sort weather1 numerically using the values of 'Max TemperatureF': weather4
23 weather4 = weather1.sort_values('Max TemperatureF')
24
25 # Print the head of weather4
26 print(weather4.head())
27
28 # Import pandas
29 import pandas as pd
30
31 # Reindex weather1 using the list year: weather2
32 weather2 = weather1.reindex(year)
33
34 # Print weather2
35 print(weather2)
36
37 # Reindex weather1 using the list year with forward-fill: weather3
38 weather3 = weather1.reindex(year).ffill()
39
40 # Print weather3
41 print(weather3)
42
43 Mean TemperatureF
44 Month
45 Jan 32.133333
46 Feb NaN
47 Mar NaN
48 Apr 61.956044
49 May NaN
50 Jun NaN
51 Jul 68.934783
52 Aug NaN
53 Sep NaN
54 Oct 43.434783
55 Nov NaN
56 Dec NaN
57 Mean TemperatureF
58 Month
59 Jan 32.133333
60 Feb 32.133333
61 Mar 32.133333
62 Apr 61.956044
63 May 61.956044
64 Jun 61.956044
65 Jul 68.934783
66 Aug 68.934783
67 Sep 68.934783
68 Oct 43.434783
69 Nov 43.434783
70 Dec 43.434783
71
72 # Import pandas
73 import pandas as pd
74
75 # Reindex names_1981 with index of names_1881: common_names
76 common_names = names_1981.reindex(names_1881.index)
77
78 # Print shape of common_names
79 print(common_names.shape)
80
81 # Drop rows with null counts: common_names
82 common_names = common_names.dropna()
83
84 # Print shape of new common_names
85 print(common_names.shape) | 43 - error: syntax-error
|
1 from models.user import UserModel
2 from werkzeug.security import safe_str_cmp
3
4
5 def authenticate(username, password):
6 user = UserModel.find_by_username(username)
7 if user is not None and safe_str_cmp(user.password, password): #safe_str_cmp() alleviates issues with string comparison
8 return user
9
10 #identity function is unique to flask JWT
11 #payload is the contents on the JWT Token
12 def identity(payload):
13 user_id = payload['identity']
14 return UserModel.find_by_id(user_id)
15
16
17
18
19
20 | 6 - warning: bad-indentation
7 - warning: bad-indentation
8 - warning: bad-indentation
13 - warning: bad-indentation
14 - warning: bad-indentation
5 - refactor: inconsistent-return-statements
|
1 # Make an array of translated impact forces: translated_force_b
2 translated_force_b = force_b - np.mean(force_b) + 0.55
3
4 # Take bootstrap replicates of Frog B's translated impact forces: bs_replicates
5 bs_replicates = draw_bs_reps(translated_force_b, np.mean, 10000)
6
7 # Compute fraction of replicates that are less than the observed Frog B force: p
8 p = np.sum(bs_replicates <= np.mean(force_b)) / 10000
9
10 # Print the p-value
11 print('p = ', p)
12
13
14
15 # Compute mean of all forces: mean_force
16 mean_force = np.mean(forces_concat)
17
18 # Generate shifted arrays
19 force_a_shifted = force_a - np.mean(force_a) + mean_force
20 force_b_shifted = force_b - np.mean(force_b) + mean_force
21
22 # Compute 10,000 bootstrap replicates from shifted arrays
23 bs_replicates_a = draw_bs_reps(force_a_shifted, np.mean, 10000)
24 bs_replicates_b = draw_bs_reps(force_b_shifted, np.mean, 10000)
25
26 # Get replicates of difference of means: bs_replicates
27 bs_replicates = bs_replicates_a-bs_replicates_b
28
29 # Compute and print p-value: p
30 p = np.sum(bs_replicates >= (np.mean(force_a)-np.mean(force_b))) / 10000
31 print('p-value =', p) | 2 - error: undefined-variable
2 - error: undefined-variable
2 - error: undefined-variable
5 - error: undefined-variable
5 - error: undefined-variable
8 - error: undefined-variable
8 - error: undefined-variable
8 - error: undefined-variable
16 - error: undefined-variable
16 - error: undefined-variable
19 - error: undefined-variable
19 - error: undefined-variable
19 - error: undefined-variable
20 - error: undefined-variable
20 - error: undefined-variable
20 - error: undefined-variable
23 - error: undefined-variable
23 - error: undefined-variable
24 - error: undefined-variable
24 - error: undefined-variable
30 - error: undefined-variable
30 - error: undefined-variable
30 - error: undefined-variable
30 - error: undefined-variable
30 - error: undefined-variable
|
1 # Create the pivot table: medals_won_by_country
2 medals_won_by_country = medals.pivot_table(index = 'Edition', columns='NOC', values= "Athlete", aggfunc='count')
3
4 # Slice medals_won_by_country: cold_war_usa_urs_medals
5 cold_war_usa_urs_medals = medals_won_by_country.loc[1952:1988, ['USA','URS']]
6 NOC USA URS
7 Edition
8 1952 130.0 117.0
9 1956 118.0 169.0
10 1960 112.0 169.0
11 1964 150.0 174.0
12 1968 149.0 188.0
13 1972 155.0 211.0
14 1976 155.0 285.0
15 1980 NaN 442.0
16 1984 333.0 NaN
17 1988 193.0 294.0
18
19 # If .max() returns the maximum value of Series or 1D array, .idxmax() returns the index of the maximizing element.
20 # Create most_medals
21 most_medals = cold_war_usa_urs_medals.idxmax(axis='columns')
22 Edition
23 1952 USA
24 1956 URS
25 1960 URS
26 1964 URS
27 1968 URS
28 1972 URS
29 1976 URS
30 1980 URS
31 1984 USA
32 1988 URS
33 dtype: object
34 # Print most_medals.value_counts()
35 print(most_medals.value_counts())
36
37
38 In [5]: cold_war_usa_urs_medals.idxmax()
39 Out[5]:
40 NOC
41 USA 1984
42 URS 1980
43 dtype: int64 | 6 - error: syntax-error
|
1 from user import User
2 from werkzeug.security import safe_str_cmp
3
4 #some database
5 users = [
6 User(1, "bob", "asdf"),
7 User(2, "Damien", "bitches")
8 ]
9
10
11 #below allows us to find the user by username or ID without having to iterate over the above list
12 username_mapping = {u.username : u for u in users} #list comprehension where the function is a key:value pair
13 userid_mapping = {u.id : u for u in users}
14
15 def authenticate(username, password):
16 user = username_mapping.get(username, None) #note that this is the same as the [] notation, but allows a default value
17 if user is not None and safe_str_cmp(user.password, password): #safe_str_cmp() alleviates issues with string comparison
18 return user
19
20 #identity function is unique to flask JWT
21 #payload is the contents on the JWT Token
22 def identity(payload):
23 user_id = payload['identity']
24 return userid_mapping.get(user_id, None)
25
26
27
28
29
30 | 16 - warning: bad-indentation
17 - warning: bad-indentation
18 - warning: bad-indentation
23 - warning: bad-indentation
24 - warning: bad-indentation
15 - refactor: inconsistent-return-statements
|
1 np.random.binomial(trails, probablity_of_success, size=number_of_reps)
2
3 np.random.poisson(average_rate, size=number_of_reps)
4
5 np.random.normal(mean, std, size=)
6 # Draw 100000 samples from Normal distribution with stds of interest: samples_std1, samples_std3, samples_std10
7 samples_std1 = np.random.normal(20,1,size=100000)
8 samples_std3 = np.random.normal(20,3,size=100000)
9 samples_std10 = np.random.normal(20,10,size=100000)
10
11 # Make histograms
12 _ = plt.hist(samples_std1, normed=True, histtype='step', bins=100)
13 _ = plt.hist(samples_std3, normed=True, histtype='step', bins=100)
14 _ = plt.hist(samples_std10, normed=True, histtype='step', bins=100)
15
16 # Make a legend, set limits and show plot
17 _ = plt.legend(('std = 1', 'std = 3', 'std = 10'))
18 plt.ylim(-0.01, 0.42)
19 plt.show()
20
21
22 # Compute mean and standard deviation: mu, sigma
23 mu = np.mean(belmont_no_outliers)
24 sigma = np.std(belmont_no_outliers)
25
26 # Sample out of a normal distribution with this mu and sigma: samples
27 samples = np.random.normal(mu, sigma, size=10000)
28
29 # Get the CDF of the samples and of the data
30 x_theor, y_theor = ecdf(samples)
31 x, y = ecdf(belmont_no_outliers)
32
33 # Plot the CDFs and show the plot
34 _ = plt.plot(x_theor, y_theor)
35 _ = plt.plot(x, y, marker='.', linestyle='none')
36 _ = plt.xlabel('Belmont winning time (sec.)')
37 _ = plt.ylabel('CDF')
38 plt.show()
39
40
41 np.randm.exponential(mean, size=)
42 def successive_poisson(tau1, tau2, size=1):
43 """Compute time for arrival of 2 successive Poisson processes."""
44 # Draw samples out of first exponential distribution: t1
45 t1 = np.random.exponential(tau1, size=size)
46
47 # Draw samples out of second exponential distribution: t2
48 t2 = np.random.exponential(tau2, size=size)
49
50 return t1 + t2 | 5 - error: syntax-error
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.