Python Snippets

Python Setup

Basic setup code

Setup Snippets

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$ sudo apt-get install python
sudo apt-get install python3
sudo apt-get install python-pip
sudo apt-get install python3-pip
 
# PIP with easy install (sudo)
# Suitable for PI's, but not Ardunio Yun.
apt-get install curl
curl -O http://peak.telecommunity.com/dist/ez_setup.py
python ez_setup.py
easy_install pip
 
# Database Package
pip install tinydb
pip3 install tinydb
 
# Six Package
pip install six

Raspberry PI Setup Snippets

1
2
3
# Raspberry Pi
pip install unicornhat
pip3 install unicornhat
;

Python 3

Below are Python3 snippets

Simple Snippets

1
2
#!/usr/bin/python3
print("Hello world!")
1
2
3
#!/usr/bin/python3
name = input('What is your name?n')
print('Hi, %s.' % name)

Main() Example

1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/python3
# main-shell.py by Stuart Eske [http://stuarteske.io]
# This file is from the "Python Snippets" project.
# Copyright 2016 Stuart Eske
 
def main():
    print("This is the main-shell.py file.")
 
# Allows for function to be called in any order
if __name__ == '__main__': main()
 
# Test suits here...

Fun Functions

Custom functions that do stuff.

Prime Number Search

10 mins of work produced a the prime of 36536041 with this function.

Join the Biggest Ever Prime Search

This is a cloud processing inititive to find the largest ever primes. Download the software and lend your processing power to the search.
Visit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/usr/bin/python3
import math
 
 
def main():
    count = 2
 
    while True:
        isprime = True
 
        for x in range(2, int(math.sqrt(count) + 1)):
            if count % x == 0:
                isprime = False
                break
 
        if isprime:
            print(count)
 
        count += 1
 
if __name__ == '__main__': main()

Sieve Prime Number Search

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/usr/bin/python3
# Sieve of Eratosthenes
# Code by David Eppstein, UC Irvine, 28 Feb 2002
# http://code.activestate.com/recipes/117119/
 
def main():
    """ Generate an infinite sequence of prime numbers.
    """
    # Maps composites to primes witnessing their compositeness.
    # This is memory efficient, as the sieve is not "run forward"
    # indefinitely, but only as long as required by the current
    # number being tested.
    #
    D = {}
 
    # The running integer that's checked for primeness
    q = 2
 
    while True:
        if q not in D:
            # q is a new prime.
            # Yield it and mark its first multiple that isn't
            # already marked in previous iterations
            #
            yield q
            D[q * q] = [q]
        else:
            # q is composite. D[q] is the list of primes that
            # divide it. Since we've reached q, we no longer
            # need it in the map, but we'll mark the next
            # multiples of its witnesses to prepare for larger
            # numbers
            #
            for p in D[q]:
                D.setdefault(p + q, []).append(p)
            del D[q]
 
        q += 1
t

Function List

This is a list of common functions

1
2
print( string ) 
type( variable )
1
raise TypeError('Needs arguments!')
1
2
*args # As function input
**kwargs # As dictionary

Validation Snippets

A collection of validation snippets

Email Validation
1
2
3
4
5
6
# validator [^@][email protected][^@]+\.[^@]+
import re
if not re.match(r"... regex here ...", email):
# or
EMAIL_REGEX = re.compile(r"... regex here ...")
if not EMAIL_REGEX.match(email):

Sendgrid Snippets

Send mail with a Yun and Iduino

Send a Simple Email

1
2
3
4
5
curl --request POST \
  --url https://api.sendgrid.com/v3/mail/send \
  --header 'Authorization: Bearer *************THE_LARGE_API_KEY*************' \
  --header 'Content-Type: application/json' \
  --data '{"personalizations": [{"to": [{"email": "[email protected]"}]}],"from": {"email": "[email protected]"},"subject": "Hello, World!","content": [{"type": "text/plain", "value": "Heya!"}]}'

Sending a Basic Email to Multiple Recipients

1
2
3
4
5
curl --request POST \
  --url https://api.sendgrid.com/v3/mail/send \
  --header 'authorization: Bearer YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{"personalizations": [{"to": [{"email": "[email protected]"}],"cc": [{"email":"[email protected]"}, {"email": "[email protected]"}, {"email":"[email protected]"}]}], "from": {"email": "[email protected]"},"subject":"Hello, World!", "content": [{"type": "text/plain", "value": "Heya!"}]}'

Sending a Basic Email Using a Template

1
2
3
4
5
curl --request POST \
  --url https://api.sendgrid.com/v3/mail/send \
  --header 'authorization: Bearer YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{"personalizations": [{"to": [{"email": "[email protected]"}]}],"from": {"email": "[email protected]"},"subject":"Hello, World!","content": [{"type": "text/plain","value": "Heya!"}], "template_id" : "YOUR_TEMPLATE_ID"}'

Sending a Basic Email at a Scheduled Time

1
2
3
4
5
curl --request POST \
  --url https://api.sendgrid.com/v3/mail/send \
  --header 'authorization: Bearer YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{"personalizations": [{"to": [{"email": "[email protected]"}]}],"from": {"email": "[email protected]"},"subject":"Hello, World!","content": [{"type": "text/plain","value": "Heya!"}], "send_at" : "UNIX_TIMESTAMP_HERE"}'

TinyDB Snippets

This is example TinyDB code

Example 7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/usr/bin/python
import sys
import os
# print os.sep
# os.path.join(pathfile,"output","log.txt")
 
# Globals
ROOTPATH = os.getcwd()
 
# Custom Class Paths
# Import the directory above the from statements
sys.path.insert(0, os.path.join("..", ROOTPATH, "vendor", "tinydb"))
 
from tinydb import TinyDB, where
 
print(ROOTPATH)
 
db = TinyDB(os.path.join(ROOTPATH, 'db.json'))
db.insert({'int': 1, 'char': 'a'})
db.insert({'int': 1, 'char': 'b'})
print(db.all())
b

Serial Connect Notes

Sketch Code.

1
2
3
4
5
6
Serial USB Connect
$ python
import serial
ser = serial.Serial('/dev/ttyACM0', 9600)
while 1 :
    ser.readline()

API's with Flask Notes

Super easy and fast API code (port 5000).

PIP install flask, then screen to run the new app script.

1
2
3
4
5
6
7
8
pip install flask
cd ~/
touch app.py
chmod a+x app.py
nano app.py
screen -S python
cd /to/script/folder
python app.py
Script Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!flask/bin/python
from flask import Flask, jsonify
 
app = Flask(__name__)
 
tasks = [{
'id': 1,
'title': 'Buy groceries',
'description': 'Milk, Cheese, Pizza, Fruit, Tylenol',
'done': False
},
{
'id': 2,
'title': 'Learn Python',
'description': 'Need to find a good Python tutorial on the web',
'done': False
}]
 
@app.route('/', methods=['GET'])
def index():
  return jsonify({'tasks': tasks})
 
@app.route('/api/v1.0/tasks/', methods=['GET'])
def get_tasks():
  return jsonify({'tasks': tasks})
 
if __name__ == '__main__':
  app.run(debug=True, host='0.0.0.0')
i

TCL/Tkinter Notes

Muliti Platform GUI Constructoor, Example Code..

# Python3
>>> import tkinter
>>> import _tkinter
>>> tkinter._test()
>>> tkinter._test()
>>> from tklinter import *
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named 'tklinter'
>>> from tkinter import *
>>> from tkinter import ttk
>>> root = Tk()
>>> button = ttk.Button(root, text = 'Click Me')
>>> botton.pack()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'botton' is not defined
>>> button.pack()
>>> button['text']
'Click Me'
>>> button['text'] = 'Hey'
>>> button.config(text = 'Config function')
>>> button.config()
{'style': ('style', 'style', 'Style', '', ''), 'text': ('text', 'text', 'Text', '', 'Config function'), 'class': ('class', '', '', '', ''), 'image': ('image', 'image', 'Image', '', ''), 'takefocus': ('takefocus', 'takeFocus', 'TakeFocus', '', 'ttk::takefocus'), 'underline': ('underline', 'underline', 'Underline', -1, -1), 'textvariable': ('textvariable', 'textVariable', 'Variable', '', ''), 'command': ('command', 'command', 'Command', <bytecode object: ''>, <bytecode object: ''>), 'compound': ('compound', 'compound', 'Compound', <index object: 'none'>, <index object: 'none'>), 'default': ('default', 'default', 'Default', <index object: 'normal'>, <index object: 'normal'>), 'width': ('width', 'width', 'Width', '', ''), 'cursor': ('cursor', 'cursor', 'Cursor', '', ''), 'state': ('state', 'state', 'State', <index object: 'normal'>, <index object: 'normal'>), 'padding': ('padding', 'padding', 'Pad', '', '')}
b

Notes

A collection of useful pages

Send mail with CURL and Sendgrid – https://sendgrid.com/docs/Classroom/Send/v3_Mail_Send/curl_examples.html
Yun Useful information – http://playground.arduino.cc/Hardware/Yun#sharing_data_with_custom_python_script
Yun disk Expansion – https://www.arduino.cc/en/Tutorial/ExpandingYunDiskSpace
Expand Root OpenWrt – http://wiki.openwrt.org/doc/howto/extroot
b

Unit and Abbreviations

A collection of useful things for electronics

Prefix Name Abbreviation Weight Equivalent Farads
Picofarad pH 10-12 0.000000000001 F
Nanofarad nH 10-9 0.000000001 F
Microfarad uH 10-6 0.000001 F
Milifarad mH 10-3 0.001 F
Kliofarad kH 10+3 1,000 F
Share This