mirror of
https://github.com/m-lamonaca/dev-notes.git
synced 2025-06-08 10:47:13 +00:00
Fix typos
This commit is contained in:
parent
76550dfa3c
commit
5c0799df7f
118 changed files with 1150 additions and 1602 deletions
|
@ -45,7 +45,7 @@ ArgumentParser.add_argument("name_or_flags", nargs="...", action="...")
|
|||
|
||||
### Actions
|
||||
|
||||
`store`: This just stores the argument’s value. This is the default action.
|
||||
`store`: This just stores the argument's value. This is the default action.
|
||||
|
||||
```py
|
||||
>>> parser = argparse.ArgumentParser()
|
||||
|
@ -159,7 +159,7 @@ Namespace(bar='XX', foo='c')
|
|||
Namespace(bar='d', foo='d')
|
||||
```
|
||||
|
||||
`*`: All command-line arguments present are gathered into a list. Note that it generally doesn’t make much sense to have more than one positional argument with `nargs='*'`, but multiple optional arguments with `nargs='*'` is possible.
|
||||
`*`: All command-line arguments present are gathered into a list. Note that it generally doesn't make much sense to have more than one positional argument with `nargs='*'`, but multiple optional arguments with `nargs='*'` is possible.
|
||||
|
||||
```py
|
||||
>>> parser = argparse.ArgumentParser()
|
||||
|
@ -170,7 +170,7 @@ Namespace(bar='d', foo='d')
|
|||
Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
|
||||
```
|
||||
|
||||
`+`: All command-line args present are gathered into a list. Additionally, an error message will be generated if there wasn’t at least one command-line argument present.
|
||||
`+`: All command-line args present are gathered into a list. Additionally, an error message will be generated if there wasn't at least one command-line argument present.
|
||||
|
||||
```py
|
||||
>>> parser = argparse.ArgumentParser(prog='PROG')
|
||||
|
|
|
@ -6,7 +6,7 @@
|
|||
# sottoclasse dizionario per contare oggetti hash-abili
|
||||
from collections import Counter
|
||||
Counter(sequenza) # -> oggetto Counter
|
||||
# {item: num comparese in sequenza, ...}
|
||||
# {item: num comprese in sequenza, ...}
|
||||
|
||||
var = Counter(sequenza)
|
||||
var.most_common(n) # produce lista degli elementi più comuni (n più comuni)
|
||||
|
|
|
@ -29,10 +29,10 @@ fieldnames
|
|||
# elimina il dialect associato a name
|
||||
.unregister_dialect()
|
||||
|
||||
# restituisce il dialet associato a name
|
||||
# restituisce il dialetto associato a name
|
||||
.get_dialect(name)
|
||||
|
||||
# elenco dialec associati a name
|
||||
# elenco dialetti associati a name
|
||||
.list_dialect(name)
|
||||
|
||||
# restituisce (se vuoto) o setta il limite del campo del csv
|
||||
|
@ -75,8 +75,8 @@ class csv.Sniffer
|
|||
.has_header(campione) --> bool # True se prima riga è una serie di intestazioni di colonna
|
||||
|
||||
#COSTANTI
|
||||
csv.QUOTE_ALL # indica a writer di citere (" ") tutti i campi
|
||||
csv.QUOTE_MINIMAL # indica a write di citare solo i campi contenenti caratteri speciali come delimiter, quotechar ...
|
||||
csv.QUOTE_NONNUMERIC # indica al vriter di citare tutti i campi non numerici
|
||||
csv.QUOTE_ALL # indica a writer di citare (" ") tutti i campi
|
||||
csv.QUOTE_MINIMAL # indica a write di citare solo i campi contenenti caratteri speciali come delimiter, quote char ...
|
||||
csv.QUOTE_NONNUMERIC # indica al writer di citare tutti i campi non numerici
|
||||
csv.QUOTE_NONE # indica a write di non citare mai i campi
|
||||
```
|
||||
|
|
|
@ -1,14 +1,13 @@
|
|||
# Ftplib Module Cheat Sheet
|
||||
# Ftplib Module
|
||||
|
||||
## FTP CLASSES
|
||||
|
||||
```py
|
||||
# restiuisce istanza classe FTP
|
||||
ftplib.FTP(host="", user="", password="", acct="")
|
||||
# se HOST fornito esegue connect(host)
|
||||
# SE USER fornito esegue login(user, password, acct)
|
||||
# if HOST => connect(host)
|
||||
# if USER => login(user, password, acct)
|
||||
|
||||
|
||||
# sottoclasse FTP con TLS
|
||||
ftplib.FTP_TLS(host="", user="", password="", acct="")
|
||||
```
|
||||
|
||||
|
@ -18,7 +17,7 @@ ftplib.FTP_TLS(host="", user="", password="", acct="")
|
|||
ftplib.error_reply # unexpected error from server
|
||||
ftplib.error_temp # temporary error (response codes 400-499)
|
||||
ftplib.error_perm # permanent error (response codes 500-599)
|
||||
ftplib.error_proto # error not in ftp specs
|
||||
ftplib.error_proto # error not in ftp specs
|
||||
ftplib.all_errors # tuple of all exceptions
|
||||
```
|
||||
|
||||
|
@ -29,43 +28,43 @@ ftplib.all_errors # tuple of all exceptions
|
|||
# method on binary files: -binary
|
||||
|
||||
# CONNECTION
|
||||
FTP.connect(host="", port=0) # used unce per instance
|
||||
# DONT CALL if host was supplied at instance creation
|
||||
FTP.connect(host="", port=0) # used once per instance
|
||||
# DON'T CALL if host was supplied at instance creation
|
||||
|
||||
FTP.getwelcome() # return welcome message
|
||||
|
||||
FTP.login(user='anonymous', password='', acct='')
|
||||
# called unce per instance after connection is established
|
||||
# DEAFAULT PASSWORD: anonymous@
|
||||
# DONT CALL if host was supplied at instance creation
|
||||
# called once per instance after connection is established
|
||||
# DEFAULT PASSWORD: anonymous@
|
||||
# DON'T CALL if host was supplied at instance creation
|
||||
FTP.sendcmd(cmd) # send command string and return response
|
||||
FTP.voidcmd(cmd) # send command string and return nothing if successful
|
||||
# FILE TRANSFER
|
||||
FTP.abort() # abort in progress file transfer (can fail)
|
||||
|
||||
FTTP.transfercmd(cmd, rest=None) # returns socket for connection
|
||||
# CMD avtive mode: send EPRT or PORT command and CMD and accept connection
|
||||
# CMD active mode: send EPRT or PORT command and CMD and accept connection
|
||||
# CMD passive mode: send EPSV or PASV and start transfer command
|
||||
|
||||
FTP.retrbinary(cmd, callback, blocksize=8192, rest=None) # retrieve file in binary mode
|
||||
# CMD: appropriate RETR comkmand ('RETR filename')
|
||||
# CMD: appropriate RETR command ('RETR filename')
|
||||
# CALLBACK: func called on every block of data received
|
||||
|
||||
FTP.rertlines(cmd, callback=None)
|
||||
# retrieve file or dir list in ASCII transfer mode
|
||||
# CMD: appropriate RETR, LSIT (list and info of files), NLST ( list of file names)
|
||||
# CMD: appropriate RETR, LSIT (list and info of files), NLST (list of file names)
|
||||
# DEFAULT CALLBACK: sys.stdout
|
||||
|
||||
FTP.set_pasv(value) # set passive mode if value is true, otherwise disable it
|
||||
# passive mode on by deafultù
|
||||
# passive mode on by default
|
||||
|
||||
FTP.storbinary(cmd, fp, blocksize=8192, callback=None, rest=None) # store file in binary mode
|
||||
# CMD: appropriate STOR command ('STOR filename')
|
||||
# FP: {file object in binary mode} read until EOF in blocks of blocksize
|
||||
# CLABBACK: func called on each bloak after sending
|
||||
# CALLBACK: func called on each block after sending
|
||||
|
||||
FTP.storlines(cmd, fp, callback=None) # store file in ASCII transfer mode
|
||||
# CMD: appropriate STOR command ('STOR filename')
|
||||
# FP: {file object} read until EOF
|
||||
# CLABBACK: func called on each bloak after sending
|
||||
# CALLBACK: func called on each block after sending
|
||||
```
|
||||
|
|
|
@ -1,42 +0,0 @@
|
|||
# Functools Module Cheat Sheet
|
||||
|
||||
Hiegher-order functions and operations on callable objects.
|
||||
|
||||
```py
|
||||
# crea nuova funzione con argomenti (*args, **kwarg) parzialmente fissati
|
||||
new_func = partial(func, *args, **kwargs)
|
||||
|
||||
# crea nuovo metodo con argomenti (*args, **kwarg) parzialmente fissati
|
||||
new_method = partialmethod(func, *args, **kwargs)
|
||||
|
||||
# applica ripetutamente funzione( , ) all'iterabile per creare un output singolo
|
||||
# funzione applicata ai primi due elementi
|
||||
# restituisce inizzializzatore se l'iterabile è vuoto (dipendente dalla funzione)
|
||||
reduce(funzione((arg_1, arg_2), iterabile, inizzializzatore) # -> singolo output
|
||||
|
||||
# decoratore che salva maxsixe:int chiamate recenti in cache
|
||||
# utilizza dizionario per memorizzazione, argomenti (posizionali e keyworded devono essere hashabili)
|
||||
# se maxsixe=None cache cresce indefinitivamente e feature LRU è disattivata
|
||||
# LRU --> Least Recent Used. Elementi poco usati rimossi dalla cache
|
||||
# per efficienza maxsize=2**n
|
||||
@lru_cache(maxsize=128, typed=False)
|
||||
|
||||
# decoratore che trasforma la funzione in una single-dispatch generic function
|
||||
# generic function --> singola funzione implementa la stessa operazione per tipi diversi (ALTERNATIVA A METHOD OVERLOAD)
|
||||
# single dispatch --> forma di generic function in cui l'implementazione è decissa in base ad un singolo argomento
|
||||
# ATTENZIONE: single dispatch deciso dal primo argomento
|
||||
@singledispatch # crea decorated_func.register per raggruppare funzioni in una generic function
|
||||
@decorated_func.register() # decide implementazione basandosi su type annotation
|
||||
@decorated_func.register(type) # decide implementazione secondo argomento type (da usare se non è presente type annotation)
|
||||
# il nome di decorated_func è irrilevante
|
||||
# è utile usare register(type) su ABC per supportare classi più generiche e classi future
|
||||
|
||||
# decoratore per aggiornare wrapper function per apparire come wrapperd function
|
||||
# funz_decoratrice mantiene argomenti e docstring della funzione decorata
|
||||
def decorator(funzione):
|
||||
@wraps(funzione)
|
||||
def wrapper(): #funz_decoratrice dentro decorator
|
||||
|
||||
# crea operatori uguaglianza se classe ne implementa almeno uno e __eq__()
|
||||
@total_ordering
|
||||
```
|
|
@ -1,56 +1,51 @@
|
|||
# Itertools Module
|
||||
|
||||
```py
|
||||
# iteratore restituisce somma cumulativa, se presente viene applicata func( , )
|
||||
# accumulate([1,2,3,4,5]) -> 1, 3(1+2), 6(1+2+3), 10(1+2+3+6), 15(1+2+3+4+5)
|
||||
# accumulate(iter, func( , )) -> iter[0], func(iter[0] + iter[1]) + func(ris_prec + iter[2]), ...
|
||||
accumulate(iterabile, func(_, _))
|
||||
# accumulate(iter, func( , )) -> iter[0], func(iter[0] + iter[1]) + func(prev + iter[2]), ...
|
||||
accumulate(iterable, func(_, _))
|
||||
|
||||
# iteratore restituisce elemenmti dal primo iterabile,
|
||||
# iteratore restituisce elementi dal primo iterable,
|
||||
# poi procede al successivo fino alla fine degli iterabili
|
||||
# non funziona se l'iterabile è uno solo
|
||||
# non funziona se l'iterable è uno solo
|
||||
chain(*iterabili)
|
||||
|
||||
ChainMap(*maps) # A ChainMap groups multiple dicts or other mappings together to create a single, updateable view. Lookups search the underlying mappings successively until a key is found. A ChainMap incorporates the underlying mappings by reference. So, if one of the underlying mappings gets updated, those changes will be reflected in ChainMap
|
||||
# concatena elementi del singolo iterable anche se contiene sequenze
|
||||
chain.from_iterable(iterable)
|
||||
|
||||
# concatena elementi del singolo iterabile anche se contiene sequenze
|
||||
chain.from_iterable(iterabile)
|
||||
|
||||
# restituisce sequenze di lunghezza r a partire dall'iterabile
|
||||
# restituisce sequenze di lunghezza r a partire dall'iterable
|
||||
# elementi trattati come unici in base al loro valore
|
||||
combinations(iterabile, r)
|
||||
combinations(iterable, r)
|
||||
|
||||
# # restituisce sequenze di lunghezza r a partire dall'iterabile permettendo la ripetizione degli elementi
|
||||
combinations_with_replacement(iterabile, r)
|
||||
# # restituisce sequenze di lunghezza r a partire dall'iterable permettendo la ripetizione degli elementi
|
||||
combinations_with_replacement(iterable, r)
|
||||
|
||||
# iteratore filtra elementi di data restituenso solo quelli che hanno
|
||||
# iteratore filtra elementi di data restituendo solo quelli che hanno
|
||||
# un corrispondente elemento in selectors che ha valore vero
|
||||
compress(data, selectors)
|
||||
|
||||
# iteratore restituiente valori equidistanti a partire da start
|
||||
#! ATTENZIONE: sequenza numerica infinita
|
||||
count(start, step)
|
||||
|
||||
# iteratore restituiente valori in sequenza infinita
|
||||
cycle(iterabile)
|
||||
# iteratore restituente valori in sequenza infinita
|
||||
cycle(iterable)
|
||||
|
||||
# iteratore droppa elementi dell'iterabile finchè il predicato è vero
|
||||
dropwhile(predicato, iterabile)
|
||||
# iteratore scarta elementi dell'iterable finché il predicato è vero
|
||||
dropwhile(predicato, iterable)
|
||||
|
||||
# iteratore restituiente valori se il predicato è falso
|
||||
filterfalse(predicato, iterabile)
|
||||
# iteratore restituente valori se il predicato è falso
|
||||
filterfalse(predicato, iterable)
|
||||
|
||||
# iteratore restituisce tuple (key, group)
|
||||
# key è il criterio di raggruppamento
|
||||
# group è un generatore restituiente i membri del gruppo
|
||||
groupby(iterabile, key=None)
|
||||
# group è un generatore restituente i membri del gruppo
|
||||
groupby(iterable, key=None)
|
||||
|
||||
# iteratore restituisce slice dell'iterabile
|
||||
# iteratore restituisce slice dell'iterable
|
||||
isslice(iterable, stop)
|
||||
isslice(iterable, start, stop, step)
|
||||
|
||||
# restituisce tutte le permutazioni di lunghezza r dell'iterabile
|
||||
permutations(iterabile, r=None)
|
||||
# restituisce tutte le permutazioni di lunghezza r dell'iterable
|
||||
permutations(iterable, r=None)
|
||||
|
||||
# prodotto cartesiano degli iterabili
|
||||
# cicla iterabili in ordine di input
|
||||
|
@ -61,17 +56,17 @@ product(*iterabili, ripetizioni=1)
|
|||
# restituisce un oggetto infinite volte se ripetizioni non viene specificato
|
||||
repeat(oggetto, ripetizioni)
|
||||
|
||||
# iteratore computa func(iterabile)
|
||||
# usato se iterabile è sequenza pre-zipped (seq di tuple raggruppanti elementi)
|
||||
starmap(func, iterabile)
|
||||
# iteratore computa func(iterable)
|
||||
# usato se iterable è sequenza pre-zipped (seq di tuple raggruppanti elementi)
|
||||
starmap(func, iterable)
|
||||
|
||||
# iteratore restituiente valori da iterabile finchè predicato è vero
|
||||
takewhile(predicato, iterabile)
|
||||
# iteratore restituente valori da iterable finché predicato è vero
|
||||
takewhile(predicato, iterable)
|
||||
|
||||
# restituisce n iteratori indipendenti dal singolo iterabile
|
||||
tee(iterabile, n=2)
|
||||
# restituisce n iteratori indipendenti dal singolo iterable
|
||||
tee(iterable, n=2)
|
||||
|
||||
# produce un iteratore che aggrega elementi da ogni iterabile
|
||||
# produce un iteratore che aggrega elementi da ogni iterable
|
||||
# se gli iterabili hanno lunghezze differenti i valori mancanti sono riempiti secondo fillervalue
|
||||
zip_longest(*iterabile, fillvalue=None)
|
||||
zip_longest(*iterable, fillvalue=None)
|
||||
```
|
||||
|
|
|
@ -65,7 +65,7 @@ json.loads(s, cls=None)
|
|||
|
||||
## Default Decoder (`json.JSONDecoder()`)
|
||||
|
||||
Convertions (JSON -> Python):
|
||||
Conversions (JSON -> Python):
|
||||
|
||||
- object -> dict
|
||||
- array -> list
|
||||
|
@ -78,7 +78,7 @@ Convertions (JSON -> Python):
|
|||
|
||||
## Default Encoder (`json.JSONEncoder()`)
|
||||
|
||||
Convertions (Python -> Json):
|
||||
Conversions (Python -> Json):
|
||||
|
||||
- dict -> object
|
||||
- list, tuple -> array
|
||||
|
@ -96,7 +96,7 @@ import json
|
|||
class ComplexEncoder(json.JSONEncoder):
|
||||
def default(self, obj):
|
||||
if isinstance(obj, complex):
|
||||
return [obj.real, obj.imag]
|
||||
return [obj.real, obj.image]
|
||||
# Let the base class default method raise the TypeError
|
||||
return json.JSONEncoder.default(self, obj)
|
||||
```
|
||||
|
@ -105,6 +105,6 @@ class ComplexEncoder(json.JSONEncoder):
|
|||
|
||||
```python
|
||||
data = json.loads(json)
|
||||
data["key"] # retieve the value associated with the key
|
||||
data["outer key"]["nested key"] # nested key value retireval
|
||||
data["key"] # retrieve the value associated with the key
|
||||
data["outer key"]["nested key"] # nested key value retrieval
|
||||
```
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
# Logging Module Cheat Sheet
|
||||
# Logging Module
|
||||
|
||||
## Configuration
|
||||
|
||||
|
@ -41,24 +41,24 @@ logging.disable(level=LOG_LEVEL)
|
|||
|
||||
| Directive | Meaning |
|
||||
|-----------|------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `%a` | Locale’s abbreviated weekday name. |
|
||||
| `%A` | Locale’s full weekday name. |
|
||||
| `%b` | Locale’s abbreviated month name. |
|
||||
| `%B` | Locale’s full month name. |
|
||||
| `%c` | Locale’s appropriate date and time representation. |
|
||||
| `%a` | Locale's abbreviated weekday name. |
|
||||
| `%A` | Locale's full weekday name. |
|
||||
| `%b` | Locale's abbreviated month name. |
|
||||
| `%B` | Locale's full month name. |
|
||||
| `%c` | Locale's appropriate date and time representation. |
|
||||
| `%d` | Day of the month as a decimal number [01,31]. |
|
||||
| `%H` | Hour (24-hour clock) as a decimal number [00,23]. |
|
||||
| `%I` | Hour (12-hour clock) as a decimal number [01,12]. |
|
||||
| `%j` | Day of the year as a decimal number [001,366]. |
|
||||
| `%m` | Month as a decimal number [01,12]. |
|
||||
| `%M` | Minute as a decimal number [00,59]. |
|
||||
| `%p` | Locale’s equivalent of either AM or PM. |
|
||||
| `%p` | Locale's equivalent of either AM or PM. |
|
||||
| `%S` | Second as a decimal number [00,61]. |
|
||||
| `%U` | Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. |
|
||||
| `%w` | Weekday as a decimal number [0(Sunday),6]. |
|
||||
| `%W` | Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. |
|
||||
| `%x` | Locale’s appropriate date representation. |
|
||||
| `%X` | Locale’s appropriate time representation. |
|
||||
| `%x` | Locale's appropriate date representation. |
|
||||
| `%X` | Locale's appropriate time representation. |
|
||||
| `%y` | Year without century as a decimal number [00,99]. |
|
||||
| `%Y` | Year with century as a decimal number. |
|
||||
| `%z` | Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM [-23:59, +23:59]. |
|
||||
|
|
|
@ -9,14 +9,14 @@ __ne__(a, b), ne(a, b) # a != b
|
|||
__ge__(a, b), ge(a, b) # a >= b
|
||||
__gt__(a, b), gt(a, b) # a > b
|
||||
|
||||
# OPERATOTI LOGICI
|
||||
not_(obj) # not obj
|
||||
truth(obj) # True o Flase ini base a valore verità oggetto (come costruttore bool)
|
||||
is_(a, b) # return a is b
|
||||
is_not(a, b) # return a is not b
|
||||
|
||||
# OPARATORI BINARI E MATEMATICI
|
||||
__abs__(a, b), abs(obj) # valore assoluto di obj
|
||||
not_(obj)
|
||||
truth(obj)
|
||||
is_(a, b)
|
||||
is_not(a, b)
|
||||
|
||||
|
||||
__abs__(a, b), abs(obj)
|
||||
__add__(a, b), add(a, b) # a + b
|
||||
__sub__(a, b), sub(a, b) # a - b
|
||||
__mul__(a,b), mul(a,b) # a * b
|
||||
|
@ -25,37 +25,20 @@ __truediv__(a, b), truediv(a, b) # a / b
|
|||
__floordiv__(a, b), floordiv(a, b) # return a // b
|
||||
__mod__(a, b), mod(a, b) # a % b
|
||||
__neg__(obj), neg(obj) # -obj
|
||||
__index__(a), index(a) # converte a in intero
|
||||
__index__(a), index(a)
|
||||
|
||||
__and__(a, b), and_(a, b) # a and b binario (a & b)
|
||||
__or__(a, b), or_(a, b) # a or b binario (a | b)
|
||||
__xor__(a, b), xor(a, b) # a xor b binario (a ^ b)
|
||||
__and__(a, b), and_(a, b) # a & b
|
||||
__or__(a, b), or_(a, b) # a | b
|
||||
__xor__(a, b), xor(a, b) # a ^ b
|
||||
|
||||
__inv__(obj), inv(obj), __inverse__(obj), inverse(obj) # inverso binario di obj, ~obj
|
||||
__lshift__(obj), lshift(a, b) # restituisce a spostato a sinistra di b
|
||||
__inv__(obj), inv(obj), __inverse__(obj), inverse(obj) # ~obj
|
||||
__lshift__(obj), lshift(a, b)
|
||||
|
||||
__concat__(a, b), concat(a, b) # a + b per sequenze (CONCATENZIONE)
|
||||
__contains__(a, b), contains(a, b) # return b in a
|
||||
countOf(a, b) # numero occorrenze b in a
|
||||
indexOF(a, b) # restituisce prima occorrenza di b in a
|
||||
__concat__(a, b), concat(a, b)
|
||||
__contains__(a, b), contains(a, b)
|
||||
countOf(a, b)
|
||||
indexOf(a, b)
|
||||
|
||||
__delitem__(a, b), delitem(a, b) # rimuove valore a in posizione b
|
||||
__getitem__(a, b), getitem(a, b) # restituisce valore a in posizione b
|
||||
__setitem__(a, b), setitem(a, b) # setta valore a in psoizione b
|
||||
|
||||
# ATTRGETTER
|
||||
# restituisce oggetto chiamabile che recupera attributo attr da oggetto
|
||||
funz = attrgetter(*attr)
|
||||
funz(var) # restituisce var.attr
|
||||
|
||||
# ITEMGETTER
|
||||
# restituisce oggetto chiamabile che recupera item dall'oggetto
|
||||
# implementa __getitem__
|
||||
funz = itemgetter(*item)
|
||||
funz(var) # restituisce var[item]
|
||||
|
||||
# METHODCALLER
|
||||
# restutiusce oggetto che chiama metodo method sull'oggetto
|
||||
var = methodcaller(method, args)
|
||||
var(obj) # return obj.method()
|
||||
```
|
||||
__delitem__(a, b), delitem(a, b)
|
||||
__getitem__(a, b), getitem(a, b)
|
||||
__setitem__(a, b), setitem(a, b)
|
||||
|
|
|
@ -1,60 +0,0 @@
|
|||
# OS Cheat Sheet
|
||||
|
||||
```python
|
||||
os.curdir # stringa identificante cartella corrente ("." per WIN)
|
||||
os.pardir # stringa identificante cartella genitore (".." per WIN)
|
||||
os.sep # carattere separatore in path (\\ per WIN, / per POSIX)
|
||||
os.extsep # carattere separatore estensione file (".")
|
||||
os.pathsep # carattere separatore in ENVVAR PATH (";" per WIN, ":" per POSIX)
|
||||
os.linesp # stringa usata per separare linee (\r\n per WIN, \n per POSIX)
|
||||
|
||||
os.system("command") # execute command in shell
|
||||
|
||||
os.remove(path) # cancella il file indicato da path
|
||||
os.rmdir(path) # cancella cartella indicata da path
|
||||
|
||||
os.listdir(path) # restituisce lista nomi dei contenuti cartella
|
||||
|
||||
os.path.exists(path) # True se path si riferisce ad elemento esistente
|
||||
os.path.split() # divide path in (head, tail), head + tail == path
|
||||
os.path.splitdrive(path) # divide path in (drive, tail), drive + tail == path
|
||||
os.path.splitext() # divide path in (root, ext), root + ext == path
|
||||
os.path.dirname(path) # restituisce nome cartella (path head)
|
||||
|
||||
os.path.getatime(path) # restituisce data ultimo accesso
|
||||
os.path.getmtime(path) # restituisce data ultima modifica
|
||||
|
||||
os.path.getsize(path) # restituisce dimesione in bytes (OSError se file inaccessibile o inesistente)
|
||||
|
||||
os.path.isfile(path) # True se path è file esistente
|
||||
os.path.isdir(path) # True se path è cartella esistente
|
||||
|
||||
os.path.join(path, *paths) # concatena vari path
|
||||
os.path.realpath(path) # Return the canonical path of the specified filename, eliminating symbolic links
|
||||
os.path.relpath(path, start=os.curdir) # restituisce path relativo (start opzionale, default os.curdir)
|
||||
os.path.abspath(path) # return a normalized absolutized version of the pathname path
|
||||
# collapses redundant separators and up-level references so that A//B, A/B/, A/./B and A/foo/../B all become A/B
|
||||
|
||||
os.walk(top)
|
||||
# Generate the file names in a directory tree by walking the tree either top-down or bottom-up.
|
||||
# For each directory in the tree rooted at directory top (including), it yields a 3-tuple (dirpath, dirnames, filenames).
|
||||
# dirpath is a string, the path to the directory.
|
||||
# dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..').
|
||||
# filenames is a list of the names of the non-directory files in dirpath.
|
||||
```
|
||||
|
||||
## Folder Operations
|
||||
|
||||
```python
|
||||
os.getcwd() # Return a string representing the current working directory
|
||||
os.chdir(path) # change the current working directory to path
|
||||
os.mkdir(path, mode=0o777) # Create a directory named path with numeric mode MODE.
|
||||
os.makedirs(name, mode=0o777) # Recursive directory creation
|
||||
```
|
||||
|
||||
## Exceptions
|
||||
|
||||
```python
|
||||
IsADirectoryError # file operation requested on directory
|
||||
NotADirectoryError # directory operation requested on file
|
||||
```
|
|
@ -1,55 +0,0 @@
|
|||
# Regex Module Cheat Sheet
|
||||
|
||||
Compile a regular expression pattern into a regular expression object, which can be used for matching.
|
||||
|
||||
```py
|
||||
regex_obj = re.compile(r"") # raw string doesn't escapes special caracters
|
||||
|
||||
# cerca la corrispondenza con REGEX_OBJ nella stringa
|
||||
match_obj = regex_obj.search(stringa) # -> oggetto Match
|
||||
|
||||
# cerca la corrispondenza con REGEX_OBJ all'inizio della stringa
|
||||
# se non vi sono corrispondenze l'oggetto match ha valore NONE
|
||||
match_obj = regex_obj.match(stringa) # -> oggetto Match
|
||||
|
||||
# l'intera stringa eve corrispondere a REGEX_OBJ
|
||||
# se non vi sono corrispondenze l'oggetto match ha valore NONE
|
||||
match_obj = regex_obj.fullmatch(stringa) # -> oggetto Match
|
||||
|
||||
# restituisce tutte le sottostringhe corrispondenti a REGEX_OBJ in una lista.
|
||||
# In caso non ve ne siano la lista è vuota
|
||||
# se nel pattern sono presenti due o più gruppi verrà restituita una lista di tuple.
|
||||
# Solo il contenuto dei gruppi vine restituito.
|
||||
regex_obj.findall(stringa)
|
||||
|
||||
# suddivide le stringhe in base a REGEX_OBJ, caratteri cercati non riportati nella lista
|
||||
regex_obj.split(pattern, stringa)
|
||||
|
||||
# sostituisce ogni sottostringa corrispondente a REGEX_OBJ con substringa
|
||||
regex_obj.sub(substringa, stringa)
|
||||
```
|
||||
|
||||
## Match Objects
|
||||
|
||||
L'oggetto match contiene True/None, info sul match, info su string, REGEX usata e posizione della corrispondenza
|
||||
|
||||
```python
|
||||
match_obj.group([number]) # restituisce la stringa individuata, [number] selezione il sottogurppo della REGEX
|
||||
match_obj.groups() # Return a tuple containing all the subgroups of the match
|
||||
match_obj.start() # posizione inizio corrispondenza
|
||||
match_obj.end() # posizione fine corrispondenza
|
||||
```
|
||||
|
||||
## Regex Configuration
|
||||
|
||||
```python
|
||||
re.compile(r"", re.OPTION_1 | re.OPTION_2 | ...) # specify options
|
||||
|
||||
# Allows regex that are more readable by allowing visually separate logical sections of the pattern and add comments.
|
||||
re.VERBOSE
|
||||
|
||||
# Make the '.' special character match any character at all, including a newline. Corresponds to the inline flag (?s).
|
||||
re.DOTALL
|
||||
re.IGNORECASE
|
||||
re.MULTILINE
|
||||
```
|
|
@ -1,32 +0,0 @@
|
|||
# Shelve Module Cheat Sheet
|
||||
|
||||
```python
|
||||
import shelve
|
||||
|
||||
# open a persistent dictionary, returns a shelf object
|
||||
shelf = shelve.open("filename", flag="c", writeback=False)
|
||||
```
|
||||
|
||||
FLAG:
|
||||
|
||||
- r = read
|
||||
- w = read & write
|
||||
- c = read, wite & create (if doesen't exist)
|
||||
- n = always create new
|
||||
|
||||
If `writeback` is `True` all entries accessed are also cached in memory, and written back on `sync()` and `close()`.
|
||||
This makes it handier to mutate mutable entries in the persistent dictionary, but, if many entries are accessed, it can consume vast amounts of memory for the cache, and it can make the close operation very slow since all accessed entries are written back.
|
||||
|
||||
```python
|
||||
# key is a string, data is an arbitrary object
|
||||
shelf[key] = data # store data at key
|
||||
data = shelf[key] # retrieve a COPY of data at key
|
||||
|
||||
shelf.keys() # list of all existing keys (slow!)
|
||||
shelf.values() # lsit of all existing values
|
||||
|
||||
del shelf[key] # selete data stored at key
|
||||
|
||||
shelf.close() # Synchronize and close the persistent dict object.
|
||||
# Operations on a closed shelf will fail with a ValueError.
|
||||
```
|
|
@ -1,4 +1,4 @@
|
|||
# Shutil Module Cheat Sheet
|
||||
# Shutil Module
|
||||
|
||||
High-level file operations
|
||||
|
||||
|
@ -18,7 +18,7 @@ shutil.copytree(src, dst, dirs_exist_ok=False)
|
|||
# or any missing parent directory already exists
|
||||
|
||||
# delete an entire directory tree
|
||||
shutil.rmtree(apth, ignore_errors=False, onerror=None)
|
||||
shutil.rmtree(path, ignore_errors=False, onerror=None)
|
||||
# IGNORE_ERROR: {bool} -- if true errors (failed removals) will be ignored
|
||||
# ON_ERROR: handler for removal errors (if ignore_errors=False or omitted)
|
||||
|
||||
|
@ -37,15 +37,15 @@ shutil.chown(path, user=None, group=None)
|
|||
# create archive file and return its name
|
||||
shutil.make_archive(base_name, format, [root_dir, base_dir])
|
||||
# BASE_NAME: {string} -- name of the archive, including path, excluding extension
|
||||
# FROMAT: {zip, tar, gztar, bztar, xztar} -- archive fromat
|
||||
# FROMAT: {zip, tar, gztar, bztar, xztar} -- archive format
|
||||
# ROOT_DIR: {path} -- root directory of archive (location of archive)
|
||||
# BASE_DIR: {path} -- directory where the archivation starts
|
||||
# BASE_DIR: {path} -- directory where the archiviation starts
|
||||
|
||||
# unpack an archive
|
||||
shutil.unpack_archive(filename, [extarct_dir, format])
|
||||
shutil.unpack_archive(filename, [extract_dir, format])
|
||||
# FILENAME: full path of archive
|
||||
# EXTRACT_DIR: {path} -- directory to unpack into
|
||||
# FROMAT: {zip, tar, gztar, bztar, xztar} -- archive fromat
|
||||
# FORMAT: {zip, tar, gztar, bztar, xztar} -- archive format
|
||||
|
||||
# return disk usage statistics as Namedtuple w/ attributes total, used, free
|
||||
shutil.disk_usage(path)
|
||||
|
|
|
@ -21,8 +21,8 @@ SMTP.verify(address) # Check the validity of an address on this server using SM
|
|||
|
||||
SMTP.login(user="full_user_mail", password="user_password") # Log-in on an SMTP server that requires authentication
|
||||
|
||||
SMTP.SMTPHeloError # The server didn’t reply properly to the HELO greeting
|
||||
SMTP.SMTPAuthenticationError # The server didn’t accept the username/password combination.
|
||||
SMTP.SMTPHeloError # The server didn't reply properly to the HELO greeting
|
||||
SMTP.SMTPAuthenticationError # The server didn't accept the username/password combination.
|
||||
SMTP.SMTPNotSupportedError # The AUTH command is not supported by the server.
|
||||
SMTP.SMTPException # No suitable authentication method was found.
|
||||
|
||||
|
@ -41,6 +41,3 @@ SMTP.send_message(msg, from_addr=None, to_addrs=None, **kwargs)
|
|||
# msg: {email.message.Message object} -- message string
|
||||
SMTP.quit() # Terminate the SMTP session and close the connection. Return the result of the SMTP QUIT command
|
||||
```
|
||||
|
||||
In general, use the email package’s features to construct an {email.message.EmailMEssage} message to send via send_message()
|
||||
EMAIL EXAMPLES --> {https:\\docs.python.org\3\library\email.examples.html#email-examples}
|
||||
|
|
|
@ -12,7 +12,7 @@ In this context, sockets are assumed to be associated with a specific socket add
|
|||
```python
|
||||
import socket
|
||||
|
||||
# socket ovet the intenet, socket is a stream of data
|
||||
# socket over the internet, socket is a stream of data
|
||||
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
|
||||
socket.connect = (("URL", port: int)) # connect to socket
|
||||
|
@ -23,9 +23,9 @@ socket.close() # close connection
|
|||
|
||||
```python
|
||||
import socket
|
||||
HTTP_Method = "GET hhtp://url/resource HTTP/version\n\n".encode() # set HTTP request (encoded string from UTF-8 to bytes)
|
||||
HTTP_Method = "GET http://url/resource HTTP/version\n\n".encode() # set HTTP request (encoded string from UTF-8 to bytes)
|
||||
socket.send(HTTP_Method) # make HTTP request
|
||||
|
||||
data = socket.recv(buffer_size) # recieve data from socket
|
||||
data = socket.recv(buffer_size) # receive data from socket
|
||||
decoded = data.decode() # decode data (from bytes to UTF-8)
|
||||
```
|
||||
|
|
|
@ -26,9 +26,10 @@ The data saved is persistent and is available in subsequent sessions.
|
|||
### Query Construction
|
||||
|
||||
Usually your SQL operations will need to use values from Python variables.
|
||||
You shouldn’t assemble your query using Python’s string operations because doing so is insecure: it makes your program vulnerable to an [SQL injection attack](https://en.wikipedia.org/wiki/SQL_injection)
|
||||
You shouldn't assemble your query using Python's string operations because doing so is insecure:
|
||||
it makes your program vulnerable to an [SQL injection attack](https://en.wikipedia.org/wiki/SQL_injection)
|
||||
|
||||
Put `?` as a placeholder wherever you want to use a value, and then provide a _tuple of values_ as the second argument to the cursor’s `execute()` method.
|
||||
Put `?` as a placeholder wherever you want to use a value, and then provide a _tuple of values_ as the second argument to the cursor's `execute()` method.
|
||||
|
||||
```python
|
||||
# Never do this -- insecure!
|
||||
|
@ -58,7 +59,7 @@ connection.commit()
|
|||
### Multiple SQL Instructions
|
||||
|
||||
```python
|
||||
conection = sqlite3.connect("file.db")
|
||||
connection = sqlite3.connect("file.db")
|
||||
cur = con.cursor()
|
||||
cur.executescript("""
|
||||
QUERY_1;
|
||||
|
@ -74,7 +75,7 @@ con.close()
|
|||
|
||||
```python
|
||||
# Fetches the next row of a query result set, returning a single sequence.
|
||||
# Reruens None when no more data is available.
|
||||
# Returns None when no more data is available.
|
||||
cursor.fetchone()
|
||||
|
||||
# Fetches all (remaining) rows of a query result, returning a list.
|
||||
|
@ -86,7 +87,7 @@ cursor.fetchall()
|
|||
fetchmany(size=cursor.arraysize)
|
||||
```
|
||||
|
||||
The number of rows to fetch per call is specified by the `size` parameter. If it is not given, the cursor’s `arraysize` determines the number of rows to be fetched.
|
||||
The number of rows to fetch per call is specified by the `size` parameter. If it is not given, the cursor's `arraysize` determines the number of rows to be fetched.
|
||||
The method should try to fetch as many rows as indicated by the size parameter.
|
||||
If this is not possible due to the specified number of rows not being available, fewer rows may be returned.
|
||||
|
||||
|
|
|
@ -1,36 +0,0 @@
|
|||
# String Module Cheat Sheet
|
||||
|
||||
## TEMPLATE STRINGS
|
||||
|
||||
Template strings support $-based substitutions, using the following rules:
|
||||
|
||||
`$$` is an escape; it is replaced with a single `$`.
|
||||
|
||||
`$identifier` names a substitution placeholder matching a mapping key of "identifier".
|
||||
By default, "identifier" is restricted to any case-insensitive ASCII alphanumeric string (including underscores) that starts with an underscore or ASCII letter.
|
||||
The first non-identifier character after the $ character terminates this placeholder specification.
|
||||
|
||||
`${identifier}` is equivalent to `$identifier`.
|
||||
It is required when valid identifier characters follow the placeholder but are not part of the placeholder.
|
||||
Any other appearance of `$` in the string will result in a `ValueError` being raised.
|
||||
The string module provides a Template class that implements these rules.
|
||||
|
||||
```python
|
||||
from string import Template
|
||||
|
||||
# The methods of Template are:
|
||||
string.Template(template) # The constructor takes a single argument which is the template string.
|
||||
|
||||
substitute(mapping={}, **kwargs)
|
||||
# Performs the template substitution, returning a new string.
|
||||
# mapping is any dictionary-like object with keys that match the placeholders in the template.
|
||||
# Alternatively, you can provide keyword arguments, where the keywords are the placeholders.
|
||||
# When both mapping and kwds are given and there are duplicates, the placeholders from kwds take precedence.
|
||||
|
||||
safe_substitute(mapping={}, **kwargs)
|
||||
# Like substitute(), except that if placeholders are missing from mapping and kwds,
|
||||
# instead of raising a KeyError exception, the original placeholder will appear in the resulting string intact.
|
||||
# Also, unlike with substitute(), any other appearances of the $ will simply return $ instead of raising ValueError.
|
||||
# While other exceptions may still occur, this method is called “safe” because it always tries to return a usable string instead of raising an exception.
|
||||
# In another sense, safe_substitute() may be anything other than safe, since it will silently ignore malformed templates containing dangling delimiters, unmatched braces, or placeholders that are not valid Python identifiers.
|
||||
```
|
|
@ -1,4 +1,4 @@
|
|||
# Time & Datetime Modules Cheatsheet
|
||||
# Time & Datetime
|
||||
|
||||
## Time
|
||||
|
||||
|
@ -6,7 +6,7 @@
|
|||
# epoch: tempo in secondi trascorso (in UNIX parte da 01-010-1970)
|
||||
import time # UNIX time
|
||||
variabile = time.time() # restituisce il tempo (In secondi) trascorso da 01-01-1970
|
||||
variabile = time.ctime(epochseconds) # traforma l'epoca in data
|
||||
variabile = time.ctime(epochseconds) # trasforma l'epoca in data
|
||||
|
||||
var = time.perf_counter() # ritorna il tempo di esecuzione attuale
|
||||
# tempo di esecuzione = tempo inizio - tempo fine
|
||||
|
@ -16,24 +16,24 @@ var = time.perf_counter() # ritorna il tempo di esecuzione attuale
|
|||
|
||||
| Format | Data |
|
||||
|--------|------------------------------------------------------------------------------------------------------------|
|
||||
| `%a` | Locale’s abbreviated weekday name. |
|
||||
| `%A` | Locale’s full weekday name. |
|
||||
| `%b` | Locale’s abbreviated month name. |
|
||||
| `%B` | Locale’s full month name. |
|
||||
| `%c` | Locale’s appropriate date and time representation. |
|
||||
| `%a` | Locale's abbreviated weekday name. |
|
||||
| `%A` | Locale's full weekday name. |
|
||||
| `%b` | Locale's abbreviated month name. |
|
||||
| `%B` | Locale's full month name. |
|
||||
| `%c` | Locale's appropriate date and time representation. |
|
||||
| `%d` | Day of the month as a decimal number `[01,31]`. |
|
||||
| `%H` | Hour (24-hour clock) as a decimal number `[00,23]`. |
|
||||
| `%I` | Hour (12-hour clock) as a decimal number `[01,12]`. |
|
||||
| `%j` | Day of the year as a decimal number `[001,366]`. |
|
||||
| `%m` | Month as a decimal number `[01,12]`. |
|
||||
| `%M` | Minute as a decimal number `[00,59]`. |
|
||||
| `%p` | Locale’s equivalent of either AM or PM. |
|
||||
| `%p` | Locale's equivalent of either AM or PM. |
|
||||
| `%S` | Second as a decimal number `[00,61]`. |
|
||||
| `%U` | Week number of the year (Sunday as the first day of the week) as a decimal number `[00,53]`. |
|
||||
| `%w` | Weekday as a decimal number `[0(Sunday),6]`. |
|
||||
| `%W` | Week number of the year (Monday as the first day of the week) as a decimal number `[00,53]`. |
|
||||
| `%x` | Locale’s appropriate date representation. |
|
||||
| `%X` | Locale’s appropriate time representation. |
|
||||
| `%x` | Locale's appropriate date representation. |
|
||||
| `%X` | Locale's appropriate time representation. |
|
||||
| `%y` | Year without century as a decimal number `[00,99]`. |
|
||||
| `%Y` | Year with century as a decimal number. |
|
||||
| `%z` | Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM |
|
||||
|
@ -48,14 +48,14 @@ today = datetime.date.today() # restituisce data corrente
|
|||
today = datetime.datetime.today() # restituisce la data e l'ora corrente
|
||||
|
||||
# esempio di formattazione
|
||||
print('Curent Date: {}-{}-{}' .format(today.day, today.month, today.year))
|
||||
print('Current Date: {}-{}-{}' .format(today.day, today.month, today.year))
|
||||
print('Current Time: {}:{}.{}' .format(today.hour, today.minute, today.second))
|
||||
|
||||
var_1 = datetime.date(anno, mese, giorno) # crea oggetto data
|
||||
var_2 = datetime.time(ora, minuti, secondi, micro-secondi) # crea oggetto tempo
|
||||
dt = datetime.combine(var_1, var_2) # combina gli oggetti data e tempo in un unico oggetto
|
||||
|
||||
date_1 = datetieme.date('year', 'month', 'day')
|
||||
date_1 = datetime.date('year', 'month', 'day')
|
||||
date_2 = date_1.replace(year = 'new_year')
|
||||
|
||||
#DATETIME ARITHMETIC
|
||||
|
|
|
@ -1,16 +1,12 @@
|
|||
# Unittest Module
|
||||
|
||||
Permette di testare il propio codice e controllare se l'output corrisponde a quello desiderato.
|
||||
|
||||
```py
|
||||
import unittest
|
||||
import modulo_da_testare
|
||||
import module_under_test
|
||||
|
||||
class Test(unittest.TestCase): # eredita da unittest.TestCase
|
||||
class Test(unittest.TestCase):
|
||||
|
||||
# testa se l'output è corretto con un asserzione
|
||||
def test_1(self):
|
||||
# code here
|
||||
self.assert*(output, expected_output)
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
|
|
@ -1,43 +0,0 @@
|
|||
# Urllib Module Cheatsheet
|
||||
|
||||
## Module Structure
|
||||
|
||||
`urllib` is a package that collects several modules for working with URLs:
|
||||
|
||||
- `urllib.request` for opening and reading URLs
|
||||
- `urllib.error` containing the exceptions raised by urllib.request
|
||||
- `urllib.parse` for parsing URLs
|
||||
- `urllib.robotparser` for parsing robots.txt files
|
||||
|
||||
## urllib.request
|
||||
|
||||
### Opening an URL
|
||||
|
||||
```python
|
||||
import urllib.request
|
||||
|
||||
# HTTP request header are not returned
|
||||
response = urllib.request.urlopen(url)
|
||||
data = response.read().decode()
|
||||
```
|
||||
|
||||
### Readign Headers
|
||||
|
||||
```python
|
||||
response = urllib.request.urlopen(url)
|
||||
|
||||
headers = dict(response.getheaders()) # store headers as a dict
|
||||
```
|
||||
|
||||
## urllib.parse
|
||||
|
||||
### URL Encoding
|
||||
|
||||
Encode a query in a URL
|
||||
|
||||
```python
|
||||
url = "http://www.addres.x/_?"
|
||||
|
||||
# encode an url with passed key-value pairs
|
||||
encoded = url + urllib.parse.encode( {"key": value} )
|
||||
```
|
|
@ -1,26 +0,0 @@
|
|||
# XML Module CheatSheet
|
||||
|
||||
## Submodules
|
||||
|
||||
The XML handling submodules are:
|
||||
|
||||
- `xml.etree.ElementTree`: the ElementTree API, a simple and lightweight XML processor
|
||||
- `xml.dom`: the DOM API definition
|
||||
- `xml.dom.minidom`: a minimal DOM implementation
|
||||
- `xml.dom.pulldom`: support for building partial DOM trees
|
||||
- `xml.sax`: SAX2 base classes and convenience functions
|
||||
- `xml.parsers.expat`: the Expat parser binding
|
||||
|
||||
## xml.etree.ElementTree
|
||||
|
||||
```python
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
data = "<xml/>"
|
||||
|
||||
tree = ET.fromstring(data) # parse string containing XML
|
||||
|
||||
tree.find("tag").text # return data contained between <tag></tag>
|
||||
tree.find("tag").get("attribute") # return value of <tag attrubute="value">
|
||||
tree.findall("tag1/tag2") # list of tag2 inside tag1
|
||||
```
|
Loading…
Add table
Add a link
Reference in a new issue