Skip to content

Commit b0c0c03

Browse files
committed
cool commit
1 parent c91f44d commit b0c0c03

20 files changed

+604
-21
lines changed
+16-4
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,10 @@
1+
import datetime
2+
import getpass
3+
import math
4+
import os
5+
6+
import requests
7+
18

29
class Employee:
310
"""A sample Employee class"""
@@ -6,15 +13,20 @@ def __init__(self, first, last):
613
self.first = first
714
self.last = last
815

9-
print('Created Employee: {} - {}'.format(self.fullname, self.email))
16+
print("Created Employee: {} - {}".format(self.fullname, self.email))
1017

1118
@property
1219
def email(self):
13-
return '{}.{}@email.com'.format(self.first, self.last)
20+
return "{}.{}@email.com".format(self.first, self.last)
1421

1522
@property
1623
def fullname(self):
17-
return '{} {}'.format(self.first, self.last)
24+
return "{} {}".format(self.first, self.last)
25+
26+
27+
emp_1 = Employee("John", "Smith")
1828

29+
name = input("your name?")
30+
password = getpass.getpass("your password?")
1931

20-
emp_1 = Employee('John', 'Smith')
32+
print(name, password)

Better_Python/bp.py

+87
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
x = 1 if True else 2
2+
3+
num1 = 1_000_000_000_000_000
4+
num2 = 100_000_000_000
5+
6+
total = num1 + num2
7+
8+
print(f"{total:,}")
9+
10+
11+
from pathlib import Path
12+
13+
script_location = Path(__file__).absolute().parent
14+
file_location = script_location / "bp.py"
15+
16+
with open(file_location, "r") as f:
17+
f_contents = f.read()
18+
19+
words = f_contents.split(" ")
20+
word_count = len(words)
21+
print(word_count)
22+
23+
name = ["John", "Doe"]
24+
25+
for i, n in enumerate(name, start=1):
26+
print(i, n)
27+
28+
29+
name = ["John", "Doe", "Jane", "Smith", "David"]
30+
heros = ["Spiderman", "Superman", "Batman", "Wonder Womna"]
31+
universe = ["Marvel", "DC", "DC", "DC"]
32+
for n, h, u in zip(name, heros, universe):
33+
print(f"{n} is actually {h} from {u}")
34+
35+
# unpacking
36+
a, b, *c = (1, 2, 3, 4, 5)
37+
print(a)
38+
print(b)
39+
print(c, type(c))
40+
41+
# if you dont care the rest
42+
a, _ = (1, 2)
43+
print(a)
44+
45+
# this will throw exception
46+
# a, b, c = (1, 2)
47+
48+
a, b, *c, d = (1, 2, 3)
49+
print(a, b, c, d)
50+
51+
52+
class Person:
53+
pass
54+
55+
56+
person = Person()
57+
58+
person.firstname = "zhang"
59+
person.lastname = "san"
60+
61+
first_key = "first"
62+
first_val = "li 4"
63+
64+
setattr(person, first_key, first_val)
65+
66+
first = getattr(person, first_key)
67+
68+
print(first)
69+
70+
print(person)
71+
72+
73+
person_info = {"age": 20, "address": "shanghai"}
74+
75+
for key, value in person_info.items():
76+
setattr(person, key, value)
77+
78+
for key in person_info.keys():
79+
print(getattr(person, key))
80+
81+
from datetime import datetime
82+
83+
print(dir(datetime))
84+
85+
print(dir(datetime.today))
86+
87+
print(datetime.today)

Better_Python/bp_getpass.py

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
from getpass import getpass
2+
3+
username = input("username: ")
4+
password = getpass("password: ")
5+
6+
print(username, password)

Better_Python/math.py

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
from math import radians, sin
2+
3+
rads = radians(90)
4+
5+
print(sin(rads))
6+
7+
8+
# radians = radians(45)
9+
# rad45 = radians(45)

Better_Python/mistakes_1.py

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
nums = [11, 30, 44, 54]
2+
3+
for num in nums:
4+
square = num**2
5+
print(square)
+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument
2+
3+
4+
# https://web.archive.org/web/20200221224620id_/http://effbot.org/zone/default-values.htm
5+
# list is mutable
6+
# Default parameter values are always evaluated when, and only when, the “def” statement they belong to is executed; see:
7+
def function(data=[]):
8+
data.append(1)
9+
print(data)
10+
11+
12+
function()
13+
print(id(function))
14+
function()
15+
print(id(function))
16+
17+
18+
def myfunc(value=None):
19+
if value is None:
20+
value = []
21+
value.append(5)
22+
print(value)
23+
24+
25+
myfunc()
26+
myfunc()
+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument
2+
3+
4+
# https://web.archive.org/web/20200221224620id_/http://effbot.org/zone/default-values.htm
5+
# list is mutable
6+
# Default parameter values are always evaluated when, and only when, the “def” statement they belong to is executed; see:
7+
def add_emp(emp, emp_list=[]):
8+
emp_list.append(emp)
9+
print(emp_list)
10+
11+
12+
print(add_emp.__defaults__)
13+
14+
emps = ["john", "jane"]
15+
add_emp("tom", emps)
16+
print(emps)
17+
18+
add_emp("tim")
19+
print(add_emp.__defaults__)
20+
add_emp("dave")
21+
print(add_emp.__defaults__)
22+
23+
print("*" * 50)
24+
25+
26+
def add_emp_safe(emp, emp_list=None):
27+
if emp_list is None:
28+
emp_list = []
29+
emp_list.append(emp)
30+
print(emp_list)
31+
32+
33+
print(add_emp_safe.__defaults__) # (None,)
34+
add_emp_safe("john")
35+
print(add_emp_safe.__defaults__) # (None,)
36+
add_emp_safe("jane")
37+
print(add_emp_safe.__defaults__) # (None,)
38+
39+
import time
40+
from datetime import datetime
41+
42+
print(datetime.now())
43+
time.sleep(1)
44+
print(datetime.now())

Better_Python/mistakes_generator.py

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
names = ["John", "Doe", "Jane", "Smith", "David"]
2+
heros = ["Spiderman", "Superman", "Batman", "Wonder Womna"]
3+
4+
identities = zip(names, heros)
5+
6+
7+
print(identities)
8+
9+
for id in identities:
10+
print(id)

Better_Python/mistakes_import.py

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# this is bad
2+
from os import *
3+
from html import *
4+
from glob import *
5+
6+
# both html and glob has escape function
7+
# people does not where this come from
8+
print(help(escape)) # Help on function escape in module glob:

Python/Site-Monitor/monitor.py

+14-17
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,33 @@
11
import os
22
import smtplib
33
import requests
4+
45
# import logging
56
from linode_api4 import LinodeClient, Instance
67

7-
EMAIL_ADDRESS = os.environ.get('EMAIL_USER')
8-
EMAIL_PASSWORD = os.environ.get('EMAIL_PASS')
9-
LINODE_TOKEN = os.environ.get('LINODE_TOKEN')
8+
EMAIL_ADDRESS = os.environ.get("EMAIL_USER")
9+
EMAIL_PASSWORD = os.environ.get("EMAIL_PASS")
10+
LINODE_TOKEN = os.environ.get("LINODE_TOKEN")
1011

1112
# logging.basicConfig(filename='PATH_TO_DESIRED_LOG_FILE',
1213
# level=logging.INFO,
1314
# format='%(asctime)s:%(levelname)s:%(message)s')
1415

1516

1617
def notify_user():
17-
with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
18+
with smtplib.SMTP("smtp.gmail.com", 587) as smtp:
1819
smtp.ehlo()
1920
smtp.starttls()
2021
smtp.ehlo()
2122

2223
smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
2324

24-
subject = 'YOUR SITE IS DOWN!'
25-
body = 'Make sure the server restarted and it is back up'
26-
msg = f'Subject: {subject}\n\n{body}'
25+
subject = "YOUR SITE IS DOWN!"
26+
body = "Make sure the server restarted and it is back up"
27+
msg = f"Subject: {subject}\n\n{body}"
2728

2829
# logging.info('Sending Email...')
29-
smtp.sendmail(EMAIL_ADDRESS, 'INSERT_RECEIVER_ADDRESS', msg)
30+
smtp.sendmail(EMAIL_ADDRESS, "INSERT_RECEIVER_ADDRESS", msg)
3031

3132

3233
def reboot_server():
@@ -36,16 +37,12 @@ def reboot_server():
3637
# logging.info('Attempting to reboot server...')
3738

3839

39-
try:
40-
r = requests.get('https://example.com', timeout=5)
40+
r = requests.get("https://example.com", timeout=5)
4141

42-
if r.status_code != 200:
43-
# logging.info('Website is DOWN!')
44-
notify_user()
45-
reboot_server()
46-
else:
47-
# logging.info('Website is UP')
48-
except Exception as e:
42+
if r.status_code != 200:
4943
# logging.info('Website is DOWN!')
5044
notify_user()
5145
reboot_server()
46+
else:
47+
# logging.info('Website is UP')
48+
pass

Requests-HTML/rh_1.py

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import os
2+
from pathlib import Path
3+
from requests_html import HTML
4+
5+
6+
script_location = Path(__file__).absolute().parent
7+
file_location = script_location / "simple.html"
8+
9+
10+
with open(file_location, "r") as html_file:
11+
source = html_file.read()
12+
html = HTML(html=source)
13+
14+
print(html.html)
15+
print(html.text)
16+
17+
match = html.find("title")
18+
print(match[0].text, match[0].html)
19+
20+
match = html.find("#footer", first=True)
21+
print(match.text)
22+
23+
24+
article = html.find("div.article", first=True)
25+
headline = article.find("h2", first=True)
26+
summary = article.find("p", first=True)
27+
print(headline.text, summary.text)

Requests-HTML/rh_web.py

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import os
2+
from pathlib import Path
3+
from requests_html import HTML, HTMLSession
4+
5+
6+
session = HTMLSession()
7+
r = session.get("https://google.ca")
8+
9+
print(r.html.html)

Requests-HTML/simple.html

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<!doctype html>
2+
<html class="no-js" lang="">
3+
<head>
4+
<title>Test - A Sample Website</title>
5+
<meta charset="utf-8">
6+
<link rel="stylesheet" href="css/normalize.css">
7+
<link rel="stylesheet" href="css/main.css">
8+
</head>
9+
<body>
10+
<h1 id='site_title'>Test Website</h1>
11+
<hr></hr>
12+
<div class="article">
13+
<h2><a href="article_1.html">Article 1 Headline</a></h2>
14+
<p>This is a summary of article 1</p>
15+
</div>
16+
<hr></hr>
17+
<div class="article">
18+
<h2><a href="article_2.html">Article 2 Headline</a></h2>
19+
<p>This is a summary of article 2</p>
20+
</div>
21+
<hr></hr>
22+
<div id='footer'>
23+
<p>Footer Information</p>
24+
</div>
25+
<script>
26+
var para = document.createElement("p");
27+
var node = document.createTextNode("This is text generated by JavaScript.");
28+
para.appendChild(node);
29+
var element = document.getElementById("footer");
30+
element.appendChild(para);
31+
</script>
32+
</body>
33+
</html>

Requests/python.png

88.7 KB
Loading

0 commit comments

Comments
 (0)