Compare commits

...

2 Commits

  1. 21
      Python/Argparse/ArgparseExample.py
  2. 29
      Python/Decorators/Decorators.py
  3. 38
      Python/Decorators/decoratortest.py
  4. 31
      Python/Decorators/successful_decorator.py
  5. 77
      Python/EmailandText/serverStatusTest.py
  6. 17
      Python/Epub/makeepub.py
  7. 65
      Python/KeypressDetect/KeyPressDetector_Multiplatform.py
  8. 13
      Python/Requests/wordpress_login.py
  9. 4
      Python/TextMessagingandEmail/mailinfo.py
  10. 43
      Python/TextMessagingandEmail/pythonTextMessage.py
  11. 10
      Python/Unicode_conversion/unicoder.py
  12. 19
      Python/mvc/controller.py
  13. 15
      Python/mvc/model.py
  14. 11
      Python/mvc/mvc.py
  15. 21
      Python/mvc/view.py
  16. 31
      Python/svg/RegularPolygons.py
  17. 16
      Python/svg/RegularPolygonsFormula.txt
  18. 46
      Python/svg/svger.py
  19. 8
      README.md

21
Python/Argparse/ArgparseExample.py

@ -0,0 +1,21 @@ @@ -0,0 +1,21 @@
import argparse,os
arguments=argparse.ArgumentParser(description="GeoBC unzipper/sorter/renamer")
arguments.add_argument("required", help="Required elements", nargs="*") #nargs=number of arguments
arguments.add_argument("-o", help="Optional elements")
arguments.add_argument("--alternate", help="This is supposedly a flag", action="store_true")
arguments.add_argument("-f", "--file", help="Which files to process instead")
#Don't forget to pass the arguments into another variable
test=arguments.parse_args()
print(test.required)
if test.o:
print(test.o)
if test.alternate:
print(test.alternate)
if test.file:
print(test.file)

29
Python/Decorators/Decorators.py

@ -0,0 +1,29 @@ @@ -0,0 +1,29 @@
def deco(func):
def wrapper(*args, **kwargs):
func(*args, **kwargs)
wrapper.count+=1
wrapper.count=0
return wrapper
def deco2(func):
def wrapper(*args, **kwargs):
print(args)
def fname(*args):
print('args',args)
return fname
@deco2
def fname(arg):
print(arg)
@deco
def main(arg):
print(arg)
for item in range(3):
main(item)
print('count', main.count)
fname('test')

38
Python/Decorators/decoratortest.py

@ -0,0 +1,38 @@ @@ -0,0 +1,38 @@
from random import randint
#this is the decorator
def decor(func): #takes a function as an argument
def x(z): # z = arguments passed from function that was decorated
print('now with decoration') #extra shit from the decorator
func(z) #run that function
return x #return the decorator function
@decor #invoke the decorator
def z(number):
print(number)
z(3)
#this is the functional equivalent
def decor2(func):
def x(z):
print('also with decoration')
func(z)
return x
def q(number):
print(number)
zz=decor2(q)
zz(3)
##another example
@decor
def othershite(thing):
x=randint(1,100)
print(f'here is some other shite and a random number({x}) plus {thing}')
othershite('piztak')

31
Python/Decorators/successful_decorator.py

@ -0,0 +1,31 @@ @@ -0,0 +1,31 @@
#import numpy as np
#import time
import math
from math import tan as qe
def deco(func):
def wrapper(y):
ang = y *2 *math.pi/360
return func(ang)
return wrapper #You need two returns! So confusing!
def test(number):
return number
@deco
def test2(number):
return number
print('undecorated')
print(test(45))
print('decorated')
print(test2(45))
print('math.tan')
print(qe(45))
print('math.tan decorated')
test3=deco(qe)
print(type(test3))
print(test3(45))
print(math.tan(45))

77
Python/EmailandText/serverStatusTest.py

@ -0,0 +1,77 @@ @@ -0,0 +1,77 @@
#! /Library/Frameworks/Python.framework/Versions/3.6/bin/python3
import smtplib
from email.message import EmailMessage as Em
#https://stackoverflow.com/questions/16683732/python-smtplib-security
import requests
from bs4 import BeautifulSoup as bs
def emailer(usr, pwd, mailserv, port, msg):
server = smtplib.SMTP(mailserv, port)
server.ehlo()
server.starttls()
server.ehlo()
server.login(usr,pwd)
server.sendmail(msg['From'], msg['To'], msg.as_string())
server.close()
def tester(url):
try:
s=requests.Session()
checker=s.get(url)
if not checker.ok:
returncode = checker.status_code
#returns integer of server status code https://www.w3.org/Protocols/HTTP/HTRESP.html
print(returncode)
soup = bs(page.text, 'html.parser')
if returncode != 200 and str(returncode).startswith('2'):
content = '{} returned status which is not code 200 (OK): {}'.format(URL, returncode)
elif str(returncode).startswith('3'):
content = '{} returned a redirect status: {}/'.format(URL, returncode)
elif str(returncode).startswith('4'):
content = '{} returned a not found status: {}.'.format(URL, returncode)
elif str(returncode).startswith('5'):
content = '{} returned an internal error: {}.'.format(URL, returncode)
elif str(soup.title) != titletest:
content = '{} title string has changed. Possible hacking attempt.'.format(URL)
else:
content = 'OK'
return content
except:
content = 'Server {} appears to be down.'.format(URL)
return content
if __name__ == '__main__':
USER = 'user@example.invalid'
PASS = 'passwordabc123notreally'
MAILSERVER = 'smtp.example.invalid'
PORT = 587
URL='https://example.invalid'
message = Em()
message['Subject'] = '{} status warning'.format(URL)
message['From'] = user
message['To'] = 'recipient1@example.invalid, recipient2@example.invalid'
titletest='<title>Website Title</title>'
try:
content=tester(URL)
except:
content = 'Server {} appears to be down.'.format(URL)
#pass
message.set_content(content)
if content !='OK':
emailer(USER, PASS, MAILSERVER, PORT, message)

17
Python/Epub/makeepub.py

@ -0,0 +1,17 @@ @@ -0,0 +1,17 @@
import requests as r
from bs4 import BeautifulSoup as bs
import pypub
import os
#page = r.get('http://gutenberg.net.au/ebooks06/0600811h.html')
#pagetext=page.text
#cleanpage=pypub.clean( pagetext )
book= pypub.Epub('Book Title', creator="Robert E Howard", publisher='Project Gutenberg Australia')
#xchapterone = pypub.ChapterFactory(cleanpage)
z= pypub.create_chapter_from_url('http://gutenberg.net.au/ebooks06/0600811h.html')
book.add_chapter(z)
book.create_epub( os.getcwd() )

65
Python/KeypressDetect/KeyPressDetector_Multiplatform.py

@ -0,0 +1,65 @@ @@ -0,0 +1,65 @@
class _GetCh:
def __init__(self):
try:
self.impl = _GetChWindows()
except ImportError:
try:
self.impl = _GetChMacCarbon()
except ImportError:
self.impl = _GetChUnix()
def __call__(self):
return self.impl()
class _GetChWindows:
def __init__(self):
import msvcrt
def __call__(self):
import msvcrt
if msvcrt.kbhit():
while msvcrt.kbhit():
ch = msvcrt.getch()
while ch in b'\x00\xe0':
msvcrt.getch()
ch = msvcrt.getch()
return ord( ch.decode() )
else:
return -1
class _GetChMacCarbon:
def __init__(self):
import Carbon
Carbon.Evt
def __call__(self):
import Carbon
if Carbon.Evt.EventAvail(0x0008)[0]==0: # 0x0008 is the keyDownMask
return ""
else:
(what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1]
return msg & 0x000000FF
class _GetChUnix:
def __init__(self):
import tty, sys, termios # import termios now or else you'll get the Unix
# version on the Mac
def __call__(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ord(ch)
if __name__ == '__main__':
InKey = _GetCh()
print( "Press Ctrl-C to exit" )
c = InKey()
while c != 3:
if c >= 0:
print( c )
c = InKey()

13
Python/Requests/wordpress_login.py

@ -0,0 +1,13 @@ @@ -0,0 +1,13 @@
import requests
from bs4 import BeautifulSoup
import urllib.parse
''' From https://stackoverflow.com/questions/42002336/using-python-requests-module-to-login-on-an-wordpress-based-website'''
if __name__=="__main__":
s=requests.Session()
link="http://example.invalid/wp-login"
initial=s.get(link)
login_data={"log":"individual@example.invalid","pwd":"passwordgoeshere",'rememberme':'forever','redirect_to':'http://example.invalid/dash/', 'redirect_to_automatic': '1'}
page_login=s.post(link, data=login_data)
print(page_login)

4
Python/TextMessagingandEmail/mailinfo.py

@ -0,0 +1,4 @@ @@ -0,0 +1,4 @@
hostname="smtp.example.invalid"
portno=465
username='user@example.invalid'
password=''

43
Python/TextMessagingandEmail/pythonTextMessage.py

@ -0,0 +1,43 @@ @@ -0,0 +1,43 @@
import smtplib
from mailinfo import *
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
print(username, hostname, portno)
server=smtplib.SMTP_SSL(host=hostname,port=portno)
server.set_debuglevel(1)
#server.starttls()
server.ehlo()
server.login(username,password)
message=MIMEMultipart()
message['From']=username
message['To']='6045618656@sms.rogers.com'
message['Subject']="I can python"
body="Sending a text message via command script."
message.attach(MIMEText(body,'plain'))
server.send_message(message)
server.quit()
'''
Bell: [10-digit phone number]@txt.bell.ca
Chatr: [10-digit phone number]@sms.rogers.com (rogers was PCS, now SMS)
Eastlink: [10-digit phone number]@txt.eastlink.ca
Fido: [10-digit phone number]@fido.ca
Freedom: [10-digit phone number]@txt.freedommobile.ca
Koodo Mobile: [10-digit phone number]@msg.koodomobile.com
MTS: [10-digit phone number]@text.mtsmobility.com
PC Mobile: [10-digit phone number]@mobiletxt.ca
Public Mobile: [10-digit phone number]@msg.telus.com
Rogers: [10-digit phone number]@pcs.rogers.com
Sasktel: [10-digit phone number]@sms.sasktel.com
Solo Mobile: [10-digit phone number]@txt.bell.ca
TBayTel: [10-digit phone number]@pcs.rogers.com
TELUS: [10-digit phone number]@msg.telus.com
Virgin Mobile: [10-digit phone number]@vmobile.ca
'''

10
Python/Unicode_conversion/unicoder.py

@ -0,0 +1,10 @@ @@ -0,0 +1,10 @@
from sys import argv
import codecs
name, codec=argv
#f = codecs.open("example.html", 'r', 'cp1140')
f = codecs.open("example.html", 'r', codec)
u = f.read() # now the contents have been transformed to a Unicode string
out = codecs.open("example_u.html", 'w', 'utf-8')
out.write(u) # and now the contents have been output as UTF-8

19
Python/mvc/controller.py

@ -0,0 +1,19 @@ @@ -0,0 +1,19 @@
import model, view
class Controller(object):
"""docstring for Controller."""
def __init__(self, model, view):
super(Controller, self).__init__()
self.model = model
self.view = view
def update(self, *args):
self.model.added(*args)
self.view.updated(args)
def expunge(self, *args):
self.model.removed(*args)
self.view.deleted(list(args))
def display(self):
self.view.displayed(self.model.var)

15
Python/mvc/model.py

@ -0,0 +1,15 @@ @@ -0,0 +1,15 @@
class Model(object):
"""docstring for Model."""
def __init__(self, *args):
self.var = list(args)
def added(self, *args):
self.var = self.var+ list(args)
def removed(self, *args):
for item in args:
self.var.remove(item)
if __name__ == '__main__':
x=Model('paulasda')

11
Python/mvc/mvc.py

@ -0,0 +1,11 @@ @@ -0,0 +1,11 @@
import model, view, controller
bp=['alpha', 'gamma', 'Deutschland', 'failure']
v=view.View()
m=model.Model('initial','population')
c=controller.Controller(m,v)
c.update(bp)
c.expunge(bp)
c.update('This', 'works')
c.display()

21
Python/mvc/view.py

@ -0,0 +1,21 @@ @@ -0,0 +1,21 @@
class View(object):
"""docstring for View."""
__instance = None
def __init__(self):
super(View, self).__init__()
if View.__instance !=None:
raise Exception('not a thing')
else:
View.__instance = self
@staticmethod
def updated(ls):
print(f'added {list(*ls)}')
@staticmethod
def deleted(ls):
print(f'deleted {list(ls)}')
@staticmethod
def displayed(ls):
print(f'contents {list(ls)}')

31
Python/svg/RegularPolygons.py

@ -0,0 +1,31 @@ @@ -0,0 +1,31 @@
import svgwrite
from svgwrite import cm,mm
from math import cos,sin,pi
'''
https://stackoverflow.com/questions/13006601/setting-default-units-in-svg-python-svgwrite
'''
drawring = svgwrite.Drawing('test.svg', profile='tiny', size=('30cm', '30cm'), viewBox=('0 0 30 30'))
''' You need size and viewBox. Why I don't know, also formatting is insane'''
def polycoord(sides,radius,cenx=0,ceny=0,unit='cm',angle=0, *args, **kwargs):
x=[]
y=[]
for n in range(sides):
x.append( str((radius *cos(2*pi*n/sides + 2*pi*angle) + cenx)))
y.append( str((radius *sin(2*pi*n/sides + 2*pi*angle) + ceny)))
z=list(zip(x,y))
return z
coords=polycoord(sides=4, radius=2, angle=45, cenx=7, ceny=7)
if __name__ == '__main__':
hex=drawring.polygon( points=polycoord(sides=6, radius=1, cenx=2, ceny=3), fill="blue", id="hex")
square=drawring.polygon(points=polycoord(sides=4, radius=3, cenx=10, ceny=10, angle=30), fill="yellow", id="square")
pentagon=drawring.polygon(points=polycoord(sides=5, radius=7, cenx=15, ceny=15, angle=20), fill="none", stroke="black", stroke_width="0.2 ", id="pentagon")
drawring.add(square)
drawring.add(hex)
drawring.add(pentagon)
drawring.save()

16
Python/svg/RegularPolygonsFormula.txt

@ -0,0 +1,16 @@ @@ -0,0 +1,16 @@
Cartesian coordinates for regular polygons:
https://stackoverflow.com/questions/7198144/how-to-draw-a-n-sided-regular-polygon-in-cartesian-coordinates
Let's assume you want to draw an N-sided polygon of radius r, centred at (0,0). Then the n vertices are given by:
x[n] = r * cos(2*pi*n/N)
y[n] = r * sin(2*pi*n/N)
where 0 <= n < N. Note that cos and sin here are working in radians, not degrees (this is pretty common in most programming languages).
If you want a different centre, then just add the coordinates of the centre point to each (x[n], y[n]). If you want a different orientation, you just need to add a constant angle. So the general form is:
x[n] = r * cos(2*pi*n/N + theta) + x_centre
y[n] = r * sin(2*pi*n/N + theta) + y_centre

46
Python/svg/svger.py

@ -0,0 +1,46 @@ @@ -0,0 +1,46 @@
import svgwrite
from svgwrite import cm,mm
from math import cos,sin,pi
'''
https://stackoverflow.com/questions/13006601/setting-default-units-in-svg-python-svgwrite
'''
drawring = svgwrite.Drawing('test.svg', profile='tiny', size=('17cm', '13cm'), viewBox=('0 0 17 13'))
''' You need size and viewBox. Why I don't know, also formatting is insane'''
x=[]
y=[]
N=6
r=2
print(cm)
for n in range(N):
x.append( (r * cos(2*pi*n/N)+7) )
y.append( (r * sin(2*pi*n/N)+7) )
z=list(zip(x,y))
def polycoord(sides,radius,cenx=0,ceny=0,unit='cm'):
x=[]
y=[]
for n in range(sides):
x.append( str((r *cos(2*pi*n/sides)+(sides+1))) + cenx)
y.append( str((r *sin(2*pi*n/sides)+(sides+1))) + ceny)
z=list(zip(x,y))
return z
'''
print(x,y)
print(z)
point=list(zip([xp*cm for xp in x],[yp*cm for yp in y]))
print(point)
'''
hex=drawring.polygon(points=z, stroke='green',fill='yellow', id='hex1',stroke_width='.1')
'''
hex=drawring.polygon(points=[(9,7),(8, 8.732050807568877),(6,8.732050807568879),(5, 7),(6, 5.267949192431123),(8, 5.267949192431123)] ,stroke='green',id='hex1',stroke_width=3)
'''
drawring.add(hex)
drawring.save()

8
README.md

@ -1,3 +1,7 @@ @@ -1,3 +1,7 @@
# gist
##Useful code snippets
Potentially useful code snippets
These are some potentially useful code snippets. Some may be out of date, but there you are.
Mostly for Python and C++/Arduino. I'm not a very good programmer, so don't be expecting miracles here.
Also, **remember to anonymize**

Loading…
Cancel
Save