Browse Source

Added condensed and libraries markdown files

pull/1/head
Jure Šorn 7 years ago
parent
commit
8be850c556
3 changed files with 423 additions and 188 deletions
  1. 218
      CONDENSED.md
  2. 58
      LIBRARIES.md
  3. 335
      README.md

218
CONDENSED.md

@ -0,0 +1,218 @@
Python and Libraries Cheatsheet
===============================
Main
----
```
if __name__ == '__main__':
main()
```
Range
-----
```python
range(<from inclusive>, <to exclusive>, <step size>) # Negative step for backward.
```
List
----
```python
<list>[<inclusive from>:<exclusive to>:<step size>]
```
Dictionary
----------
```
<dict>.items()
<dict>.get(<key>, <default>)
<dict>.setdefault(<key>, <default>)
```
Enumerate
---------
```
for i, <el> in enumerate(<list/dict/set>)
```
Inline
------
### For
```pythonstub
[i+j for i in range(10) for j in range(10) if i+j > 5]
```
### Lambda
```
lambda <arg1>, <arg2>: <return value>
```
String
------
### Print
```
print(<el1>, <el2>, end='', sep='', file=<file>)
```
### Regex
```
import re
re.sub(<regex>, <new>, <text>)
re.search(<regex>, <text>)
```
### Format
```
{:<min width>} -> '<el> '
{:><min width>} -> ' <el>'
{:^<min width>} -> ' <el> '
{:_<min width>} -> '<el>____'
{:.<max width>} -> '<e>'
{:<max widht>.<min width>} -> ' <e>'
{:<max width>.<no of decimals>f} -> ' 3.14'
```
Infinity
--------
```
float("inf")
```
Class
-----
### Class
```
class <name>:
def __init__(self, <arg>):
self.a = <arg>
def __repr__(self):
return str({'a': self.a})
def __str__(self):
return str(self.a)
```
### Enum
```
import enum
class <name>(enum.Enum):
<value> = <index>
```
### Copy
```
import copy
copy.copy(<object>)
copy.deepcopy(<object>)
```
Random
------
```
import random
random.random()
random.randint(<from inclusive>, <to inclusive>)
random.shuffle(<list>)
```
Datetime
--------
```
import datetime
now = datetime.datetime.now()
now.strftime('%Y%m%d')
now.strftime('%Y%m%d%H%M%S')
```
System
------
### Arguments
```
import sys
sys.argv
```
### Read
```
with open(<filename>, encoding='utf-8') as file:
return file.readlines()
```
### Write
```
with open(<filename>, 'w', enconding='utf-8') as file:
file.write(<text>)
```
### Execute Command
```
import os
os.popen(<command>).read()
```
JSON
----
```
import json
```
### Read
```
with open(<filename>, encoding='utf-8') as file:
return json.load(file)
```
### Write
```
with open(<filename>, 'w', enconding='utf-8') as file:
file.write(json.dumps(<object>))
```
SQLite
------
```
import sqlite3
db = sqlite3.connect(<filename>)
```
### Read
```
cursor = db.execute(<query>)
if cursor:
cursor.<fetchone/fetchall>()
db.close()
```
### Write
```
db.execute(<query>)
db.commit()
```

58
LIBRARIES.md

@ -0,0 +1,58 @@
Libraries
=========
Plot
----
```
import matplotlib
matplotlib.pyplot.plot(<data>, ...)
matplotlib.pyplot.show()
matplotlib.pyplot.savefig(<filename>)
```
Web
---
```
import bottle
```
### Run
```
bottle.run(host='localhost', port=8080)
bottle.run(host='0.0.0.0', port=80, server='cherypy')
```
### Static request
### Dynamic request
### REST request
Curses
------
```
import curses
def main():
curses.wrapper(draw)
def draw(screen):
screen.clear()
screen.addstr(0, 0, "Press ESC to quit.")
while screen.getch() != 27:
pass
```
Profile
-------
```
import pycallgraph
graph = pycallgraph.output.GraphvizOutput()
graph.output_file = <filename>
whith pycallgraph.PyCallGraph(output=graph):
<code>
```

335
README.md

@ -1,101 +1,56 @@
Python and Libraries Cheatsheet Python and Libraries Cheatsheet
=============================== ===============================
Sum Main
--- ----
```
sum(<list>)
```
Profile
-------
```
import pycallgraph
graph = pycallgraph.output.GraphvizOutput()
graph.output_file = <filename>
whith pycallgraph.PyCallGraph(output=graph):
<code>
```
SQLite
------
```
import sqlite3
db = sqlite3.connect(<filename>)
```
### Read
```
cursor = db.execute(<query>)
if cursor:
cursor.<fetchone/fetchall>()
db.close()
```
### Write
```
db.execute(<query>)
db.commit()
```
Curses
------
``` ```
import curses if __name__ == '__main__':
def main(): main()
curses.wrapper(draw)
def draw(screen):
screen.clear()
screen.addstr(0, 0, "Press ESC to quit.")
while screen.getch() != 27:
pass
``` ```
Regex Range
----- -----
``` ```
import re range(<to exclusive>)
re.sub(<regex>, <new>, <text>) range(<from inclusive>, <to exclusive>)
re.search(<regex>, <text>) range(<from inclusive>, <to exclusive>, <step size>) # Negative step for backward
```
Threading
---------
```
import threading
``` ```
### Thread List
----
``` ```
thread = threading.Thread(target=<function>, args=(<first arg>, )) <list>[<inclusive from>:<exclusive to>:<step size>]
thread.start() <list>.extend(<list>)
thread.join() <list>.sort()
<list>.reverse()
sum(<list>)
``` ```
### Lock Dictionary
``` ----------
lock = threading.Rlock() <dict>.items()
lock.acquire() <dict>.get(<key>, <default>)
lock.release() <dict>.setdefault(<key>, <default>)
``` ```
Bottle Set
------ ---
``` ```
import bottle <set> = set()
<set>.add(<el>)
<set>.update(<set>)
<set>.union(<set>)
<set>.intersection(<set>)
<set>.difference(<set>)
``` ```
### Run Enumerate
---------
``` ```
bottle.run(host='localhost', port=8080) for i, <el> in enumerate(<list>)
bottle.run(host='0.0.0.0', port=80, server='cherypy')
``` ```
### Static request
### Dynamic request
### REST request
Type Type
---- ----
@ -107,60 +62,64 @@ import numbers
isinstance(<el>, numbers.Number) isinstance(<el>, numbers.Number)
``` ```
Arguments String
--------- ------
``` ```
import sys str.replace(<text>, <old>, <new>)
sys.argv <str>.isnumeric()
``` ```
Enumerate ### Print
---------
``` ```
for i, <el> in enumerate(<list>) print(<el1>, <el2>, end='', sep='', file=<file>)
``` ```
### Regex
System Commands
---------------
### Read File
``` ```
with open(<filename>, encoding='utf-8') as file: import re
return file.readlines() re.sub(<regex>, <new>, <text>)
re.search(<regex>, <text>)
``` ```
### Write to File ### Format
``` ```
with open(<filename>, 'w', enconding='utf-8') as file: '{}'.format(<el>)
file.write(<text>)
``` ```
### Execute Command
``` ```
import os {:<min width>} -> '<el> '
os.popen(<command>).read() {:><min width>} -> ' <el>'
{:^<min width>} -> ' <el> '
{:_<min width>} -> '<el>____'
{:.<max width>} -> '<e>'
{:<max widht>.<min width>} -> ' <e>'
{:<max width>.<no of decimals>f} -> ' 3.14'
``` ```
### Text Wrap
JSON
----
``` ```
import json import textwrap
textwrap.wrap(<text>, <width>)
``` ```
### Read File Random
------
``` ```
with open(<filename>, encoding='utf-8') as file: import random
return json.load(file) random.random()
random.randint(<from inclusive>, <to inclusive>)
random.shuffle(<list>)
``` ```
### Write to File Infinity
--------
``` ```
with open(<filename>, 'w', enconding='utf-8') as file: float("inf")
file.write(json.dumps(<object>))
``` ```
Datetime Datetime
-------- --------
``` ```
@ -170,14 +129,39 @@ now.strftime('%Y%m%d')
now.strftime('%Y%m%d%H%M%S') now.strftime('%Y%m%d%H%M%S')
``` ```
String Inline
------ ------
### For
``` ```
str.replace(<text>, <old>, <new>) [i+1 for i in range(10)]
<str>.isnumeric() [i+1 for i in range(10) if i > 5]
[i+j for i in range(10) for j in range(10)]
```
### Lambda
```
lambda <arg1>, <arg2>: <return value>
lambda: <return value>
```
Class
-----
### Class
```
class <name>:
def __init__(self, <arg>):
self.a = <arg>
def __repr__(self):
return str({'a': self.a})
def __str__(self):
return str(self.a)
``` ```
Enum ### Enum
---- ----
``` ```
import enum import enum
@ -185,128 +169,103 @@ class <name>(enum.Enum):
<value> = <index> <value> = <index>
``` ```
Copy ### Copy
----
``` ```
import copy import copy
copy.copy(<object>) copy.copy(<object>)
copy.deepcopy(<object>) copy.deepcopy(<object>)
``` ```
Infinity
--------
```
float("inf")
```
Plot System
---- ------
```
import matplotlib
matplotlib.pyplot.plot(<data>, ...)
matplotlib.pyplot.show()
matplotlib.pyplot.savefig(<filename>)
```
List ### Arguments
----
``` ```
<list>[<inclusive from>:<exclusive to>:<step size>] import sys
sys.argv
``` ```
Lambda ### Read File
------
``` ```
lambda <arg1>, <arg2>: <return value> with open(<filename>, encoding='utf-8') as file:
lambda: <return value> return file.readlines()
``` ```
[For] ### Write to File
-----
``` ```
[i+1 for i in range(10)] with open(<filename>, 'w', enconding='utf-8') as file:
[i+1 for i in range(10) if i > 5] file.write(<text>)
[i+j for i in range(10) for j in range(10)]
``` ```
Class ### Execute Command
-----
``` ```
class <name>: import os
def __init__(self, <arg>): os.popen(<command>).read()
self.a = <arg>
def __repr__(self):
return str({'a': self.a})
def __str__(self):
return str(self.a)
``` ```
Random JSON
------ ----
``` ```
import random import json
random.random()
random.randint(<from inclusive>, <to inclusive>)
random.shuffle(<list>)
``` ```
Range ### Read File
-----
``` ```
range(<to exclusive>) with open(<filename>, encoding='utf-8') as file:
range(<from inclusive>, <to exclusive>) return json.load(file)
range(<from inclusive>, <to exclusive>, <step size>) # Negative step for backward
``` ```
List ### Write to File
----
``` ```
<list>.sort() with open(<filename>, 'w', enconding='utf-8') as file:
<list>.reverse() file.write(json.dumps(<object>))
<list>.extend(<list>)
``` ```
Print SQLite
----- ------
``` ```
print(<el1>, <el2>, end='', sep='', file=<file>) import sqlite3
db = sqlite3.connect(<filename>)
``` ```
Format ### Read
------
``` ```
'{}'.format(<el>) cursor = db.execute(<query>)
if cursor:
cursor.<fetchone/fetchall>()
db.close()
``` ```
### Write
``` ```
{:<min width>} -> '<el> ' db.execute(<query>)
{:><min width>} -> ' <el>' db.commit()
{:^<min width>} -> ' <el> '
{:_<min width>} -> '<el>____'
{:.<max width>} -> '<e>'
{:<max widht>.<min width>} -> ' <e>'
{:<max width>.<no of decimals>f} -> ' 3.14'
``` ```
Text Wrap Threading
--------- ---------
``` ```
import textwrap import threading
textwrap.wrap(<text>, <width>)
``` ```
Dictionary ### Thread
---------- ```
<dict>.items() thread = threading.Thread(target=<function>, args=(<first arg>, ))
<dict>.get(<key>, <default>) thread.start()
<dict>.setdefault(<key>, <default>) thread.join()
``` ```
### Lock
```
lock = threading.Rlock()
lock.acquire()
lock.release()
```

|||||||
100:0
Loading…
Cancel
Save