mirror of
https://github.com/m-lamonaca/dev-notes.git
synced 2025-04-08 11:56:41 +00:00
Merge branch 'main' into NET-6
This commit is contained in:
commit
3734f966ca
35 changed files with 394 additions and 729 deletions
|
@ -27,7 +27,7 @@ namespace <Namespace>
|
||||||
{
|
{
|
||||||
services.AddControllers(); // controllers w/o views
|
services.AddControllers(); // controllers w/o views
|
||||||
//or
|
//or
|
||||||
sevices.AddControllersWithViews(); // MVC Controllers
|
services.AddControllersWithViews(); // MVC Controllers
|
||||||
}
|
}
|
||||||
|
|
||||||
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
|
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
|
||||||
|
@ -117,7 +117,7 @@ public void ConfigureServices(IServiceCollection services)
|
||||||
- Mirroring of model in the DB.
|
- Mirroring of model in the DB.
|
||||||
- Will create & update DB Schema if necessary
|
- Will create & update DB Schema if necessary
|
||||||
|
|
||||||
In Packge Manager Shell:
|
In Package Manager Shell:
|
||||||
|
|
||||||
```ps1
|
```ps1
|
||||||
add-migrations <migration_name>
|
add-migrations <migration_name>
|
||||||
|
@ -294,7 +294,7 @@ namespace <App>.Controllers
|
||||||
|
|
||||||
if(result != null)
|
if(result != null)
|
||||||
{
|
{
|
||||||
return Ok(_mapper.Map<EntityCrudOp>(result)); // transfrom entity to it's DTO
|
return Ok(_mapper.Map<EntityCrudOp>(result)); // transform entity to it's DTO
|
||||||
}
|
}
|
||||||
|
|
||||||
return NotFound(); // ActionResult NOT FOUND (404)
|
return NotFound(); // ActionResult NOT FOUND (404)
|
||||||
|
|
|
@ -4,7 +4,7 @@
|
||||||
|
|
||||||
`%quickref` Display the IPython Quick Reference Card
|
`%quickref` Display the IPython Quick Reference Card
|
||||||
`%magic` Display detailed documentation for all of the available magic commands
|
`%magic` Display detailed documentation for all of the available magic commands
|
||||||
`%debug` Enter the interactive debugger at the bottom of the last exception traceback
|
`%debug` Enter the interactive debugger at the bottom of the last exception trace-back
|
||||||
`%hist` Print command input (and optionally output) history
|
`%hist` Print command input (and optionally output) history
|
||||||
`%pdb` Automatically enter debugger after any exception
|
`%pdb` Automatically enter debugger after any exception
|
||||||
`%paste` Execute pre-formatted Python code from clipboard
|
`%paste` Execute pre-formatted Python code from clipboard
|
||||||
|
@ -14,7 +14,7 @@
|
||||||
`%run` script.py Run a Python script inside IPython
|
`%run` script.py Run a Python script inside IPython
|
||||||
`%prun` statement Execute statement with cProfile and report the profiler output
|
`%prun` statement Execute statement with cProfile and report the profiler output
|
||||||
`%time` statement Report the execution time of single statement
|
`%time` statement Report the execution time of single statement
|
||||||
`%timeit` statement Run a statement multiple times to compute an emsemble average execution time. Useful for timing code with very short execution time
|
`%timeit` statement Run a statement multiple times to compute an ensemble average execution time. Useful for timing code with very short execution time
|
||||||
`%who`, `%who_ls`, `%whos` Display variables defined in interactive namespace, with varying levels of information / verbosity
|
`%who`, `%who_ls`, `%whos` Display variables defined in interactive namespace, with varying levels of information / verbosity
|
||||||
`%xdel` variable Delete a variable and attempt to clear any references to the object in the IPython internals
|
`%xdel` variable Delete a variable and attempt to clear any references to the object in the IPython internals
|
||||||
|
|
||||||
|
@ -23,7 +23,7 @@
|
||||||
`!cmd` Execute cmd in the system shell
|
`!cmd` Execute cmd in the system shell
|
||||||
`output = !cmd args` Run cmd and store the stdout in output
|
`output = !cmd args` Run cmd and store the stdout in output
|
||||||
`%alias alias_name cmd` Define an alias for a system (shell) command
|
`%alias alias_name cmd` Define an alias for a system (shell) command
|
||||||
`%bookmark` Utilize IPython’s directory bookmarking system
|
`%bookmark` Utilize IPython's directory bookmarking system
|
||||||
`%cd` directory Change system working directory to passed directory
|
`%cd` directory Change system working directory to passed directory
|
||||||
`%pwd` Return the current system working directory
|
`%pwd` Return the current system working directory
|
||||||
`%pushd` directory Place current directory on stack and change to target directory
|
`%pushd` directory Place current directory on stack and change to target directory
|
||||||
|
|
|
@ -37,7 +37,7 @@ cli.add_command(dropdb)
|
||||||
|
|
||||||
The `group()` decorator works like the `command()` decorator, but creates a Group object instead which can be given multiple subcommands that can be attached with `Group.add_command()`.
|
The `group()` decorator works like the `command()` decorator, but creates a Group object instead which can be given multiple subcommands that can be attached with `Group.add_command()`.
|
||||||
|
|
||||||
For simple scripts, it’s also possible to automatically attach and create a command by using the `Group.command()` decorator instead.
|
For simple scripts, it's also possible to automatically attach and create a command by using the `Group.command()` decorator instead.
|
||||||
The above script can instead be written like this:
|
The above script can instead be written like this:
|
||||||
|
|
||||||
```py
|
```py
|
||||||
|
@ -54,7 +54,7 @@ def dropdb():
|
||||||
click.echo('Dropped the database')
|
click.echo('Dropped the database')
|
||||||
```
|
```
|
||||||
|
|
||||||
You would then invoke the Group in your setuptools entry points or other invocations:
|
You would then invoke the Group in your setup-tools entry points or other invocations:
|
||||||
|
|
||||||
```py
|
```py
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
|
|
@ -10,27 +10,27 @@ from tkinter import ttk # import Themed Widgets
|
||||||
## GEOMETRY MANAGEMENT
|
## GEOMETRY MANAGEMENT
|
||||||
|
|
||||||
Putting widgets on screen
|
Putting widgets on screen
|
||||||
master widget --> toplevel window, frame
|
master widget --> top-level window, frame
|
||||||
slave widget --> widgets contained in master widget
|
slave widget --> widgets contained in master widget
|
||||||
geometry managers determine size and oder widget drawing properties
|
geometry managers determine size and oder widget drawing properties
|
||||||
|
|
||||||
## EVENT HANDLING
|
## EVENT HANDLING
|
||||||
|
|
||||||
event loop recives events from the OS
|
event loop receives events from the OS
|
||||||
customizable events provide a callback as a widget configuration
|
customizable events provide a callback as a widget configuration
|
||||||
|
|
||||||
```py
|
```py
|
||||||
widget.bind('event', function) # method to capture any event and than execute an arbitrary piece of code (generally a functio or lambda)
|
widget.bind('event', function) # method to capture any event and than execute an arbitrary piece of code (generally a function or lambda)
|
||||||
```
|
```
|
||||||
|
|
||||||
VIRTUAL EVENT --> hig level event genearted by widget (listed in widget docs)
|
VIRTUAL EVENT --> hig level event generated by widget (listed in widget docs)
|
||||||
|
|
||||||
## WIDGETS
|
## WIDGETS
|
||||||
|
|
||||||
"idgets are objects and all things on screen. All widgets are children of a window.
|
Widgets are objects and all things on screen. All widgets are children of a window.
|
||||||
|
|
||||||
```py
|
```py
|
||||||
widget_name = tk_object(parent_window) # widget is insetred into widget hierarchy
|
widget_name = tk_object(parent_window) # widget is inserted into widget hierarchy
|
||||||
```
|
```
|
||||||
|
|
||||||
## FRAME WIDGET
|
## FRAME WIDGET
|
||||||
|
@ -40,7 +40,7 @@ Displays a single rectangle, used as container for other widgets
|
||||||
```py
|
```py
|
||||||
frame = ttk.Frame(parent, width=None, height=None, borderwidth=num:int)
|
frame = ttk.Frame(parent, width=None, height=None, borderwidth=num:int)
|
||||||
# BORDERWIDTH: sets frame border width (default: 0)
|
# BORDERWIDTH: sets frame border width (default: 0)
|
||||||
# width, height MUST be specified if frame is empty, otherwise determinded by parent geometry manager
|
# width, height MUST be specified if frame is empty, otherwise determined by parent geometry manager
|
||||||
```
|
```
|
||||||
|
|
||||||
### FRAME PADDING
|
### FRAME PADDING
|
||||||
|
@ -49,7 +49,7 @@ Extra space inside widget (margin).
|
||||||
|
|
||||||
```py
|
```py
|
||||||
frame['padding'] = num # same padding for every border
|
frame['padding'] = num # same padding for every border
|
||||||
frame['padding'] = (horizzontal, vertical) # set horizontal THEN vertical padding
|
frame['padding'] = (horizontal, vertical) # set horizontal THEN vertical padding
|
||||||
frame['padding'] = (left, top, right, bottom) # set left, top, right, bottom padding
|
frame['padding'] = (left, top, right, bottom) # set left, top, right, bottom padding
|
||||||
|
|
||||||
# RELIEF: set border style, [flat (default), raised, sunken, solid, ridge, groove]
|
# RELIEF: set border style, [flat (default), raised, sunken, solid, ridge, groove]
|
||||||
|
@ -58,7 +58,7 @@ frame['relief'] = border_style
|
||||||
|
|
||||||
## LABEL WIDGET
|
## LABEL WIDGET
|
||||||
|
|
||||||
Display tetx or image without interactivity.
|
Display text or image without interactivity.
|
||||||
|
|
||||||
```py
|
```py
|
||||||
label = ttk.Label(parent, text='label text')
|
label = ttk.Label(parent, text='label text')
|
||||||
|
@ -67,7 +67,7 @@ label = ttk.Label(parent, text='label text')
|
||||||
### DEFINING UPDATING LABEL
|
### DEFINING UPDATING LABEL
|
||||||
|
|
||||||
```py
|
```py
|
||||||
var = StringVar() # variable containing text, watchs for changes. Use get, set methods to interact with the value
|
var = StringVar() # variable containing text, watches for changes. Use get, set methods to interact with the value
|
||||||
label['textvariable'] = var # attach var to label (only of type StringVar)
|
label['textvariable'] = var # attach var to label (only of type StringVar)
|
||||||
var.set("new text label") # change label text
|
var.set("new text label") # change label text
|
||||||
```
|
```
|
||||||
|
@ -105,7 +105,7 @@ label['anchor'] = compass_direction #compass_direction: n, ne, e, se, s, sw, w,
|
||||||
|
|
||||||
```py
|
```py
|
||||||
# use \n for multi line text
|
# use \n for multi line text
|
||||||
label['wraplength'] = size # max line lenght
|
label['wraplength'] = size # max line length
|
||||||
```
|
```
|
||||||
|
|
||||||
### CONTROL TEXT JUSTIFICATION
|
### CONTROL TEXT JUSTIFICATION
|
||||||
|
@ -114,8 +114,8 @@ label['wraplength'] = size # max line lenght
|
||||||
label['justify'] = value #value: left, center, right
|
label['justify'] = value #value: left, center, right
|
||||||
|
|
||||||
label['relief'] = label_style
|
label['relief'] = label_style
|
||||||
label['foreground'] = color # color pased with name or HEX RGB codes
|
label['foreground'] = color # color passed with name or HEX RGB codes
|
||||||
label['background'] = color # color pased with name or HEX RGB codes
|
label['background'] = color # color passed with name or HEX RGB codes
|
||||||
```
|
```
|
||||||
|
|
||||||
### FONT STYLE (use with caution)
|
### FONT STYLE (use with caution)
|
||||||
|
@ -129,7 +129,7 @@ Fonts:
|
||||||
|
|
||||||
- TkDefaultFont -- default for all GUI items
|
- TkDefaultFont -- default for all GUI items
|
||||||
- TkTextFont -- used for entry widgets, listboxes, etc
|
- TkTextFont -- used for entry widgets, listboxes, etc
|
||||||
- TkFixedFont -- standar fixed-width font
|
- TkFixedFont -- standard fixed-width font
|
||||||
- TkMenuFont -- used for menu items
|
- TkMenuFont -- used for menu items
|
||||||
- TkHeadingFont -- for column headings in lists and tables
|
- TkHeadingFont -- for column headings in lists and tables
|
||||||
- TkCaptionFont -- for window and dialog caption bars
|
- TkCaptionFont -- for window and dialog caption bars
|
||||||
|
@ -159,7 +159,7 @@ button.invoke() # button activation in the program
|
||||||
|
|
||||||
### BUTTON STATE
|
### BUTTON STATE
|
||||||
|
|
||||||
Activate (interagible) or deactivate (not interagible) the widget.
|
Activate or deactivate the widget.
|
||||||
|
|
||||||
```py
|
```py
|
||||||
button.state(['disabled']) # set the disabled flag, disabling the button
|
button.state(['disabled']) # set the disabled flag, disabling the button
|
||||||
|
@ -172,7 +172,7 @@ button.instate(['!disabled'], cmd) # execute 'cmd' if the button is not disable
|
||||||
|
|
||||||
## CHECKBUTTON
|
## CHECKBUTTON
|
||||||
|
|
||||||
Button with binary value of some kind (e.g a toggle) and also invokes a comman callback
|
Button with binary value of some kind (e.g a toggle) and also invokes a command callback
|
||||||
|
|
||||||
```py
|
```py
|
||||||
checkbutton_var = TkVarType
|
checkbutton_var = TkVarType
|
||||||
|
@ -182,9 +182,9 @@ check = ttk.Checkbutton(parent, text='button text', command=action_performed, va
|
||||||
### WIDGET VALUE
|
### WIDGET VALUE
|
||||||
|
|
||||||
Variable option holds value of button, updated by widget toggle.
|
Variable option holds value of button, updated by widget toggle.
|
||||||
EFAULT: 1 (while checked), 0 (while unchecked)
|
DEFAULT: 1 (while checked), 0 (while unchecked)
|
||||||
`onvalue`, `offvalue` are used to personalize cheched and uncheched values
|
`onvalue`, `offvalue` are used to personalize checked and unchecked values
|
||||||
if linked variable is empry or different from on-offvalue the state flag is set to alternate
|
if linked variable is empty or different from on-off value the state flag is set to alternate
|
||||||
checkbutton won't set the linked variable (MUST be done in the program)
|
checkbutton won't set the linked variable (MUST be done in the program)
|
||||||
|
|
||||||
### CONFIG OPTIONS
|
### CONFIG OPTIONS
|
||||||
|
@ -245,7 +245,7 @@ radio.instate(['flag'])
|
||||||
|
|
||||||
## COMBOBOX
|
## COMBOBOX
|
||||||
|
|
||||||
Drop-down list of avaiable options.
|
Drop-down list of available options.
|
||||||
|
|
||||||
```py
|
```py
|
||||||
combobox_var = StringVar()
|
combobox_var = StringVar()
|
||||||
|
@ -253,7 +253,7 @@ combo = ttk.Combobox(parent, textvariable=combobox_var)
|
||||||
combobox.get() # return combobox current value
|
combobox.get() # return combobox current value
|
||||||
combobox.set(value) # set combobox new value
|
combobox.set(value) # set combobox new value
|
||||||
combobox.current() # returns which item in the predefined values list is selected (0-based index of the provided list, -1 if not in the list)
|
combobox.current() # returns which item in the predefined values list is selected (0-based index of the provided list, -1 if not in the list)
|
||||||
#combobox will generate a bind-able <ComboxboSelected> virtual event whenever the value changes
|
#combobox will generate a bind-able <ComboboxSelected> virtual event whenever the value changes
|
||||||
combobox.bind('<<ComboboxSelected>>', function)
|
combobox.bind('<<ComboboxSelected>>', function)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -271,7 +271,7 @@ Display list of single-line items, allows browsing and multiple selection (part
|
||||||
|
|
||||||
```py
|
```py
|
||||||
lstbx = Listbox(parent, height=num, listvariable=item_list:list)
|
lstbx = Listbox(parent, height=num, listvariable=item_list:list)
|
||||||
# listvariable links a variable (MUST BE a list) to the listbox, each elemenmt is a item of the listbox
|
# listvariable links a variable (MUST BE a list) to the listbox, each element is a item of the listbox
|
||||||
# manipulation of the list changes the listbox
|
# manipulation of the list changes the listbox
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -292,7 +292,7 @@ lstbx.curselection() # returns list of indices of selected items
|
||||||
scroll = ttk.Scrollbar(parent, orient=direction, command=widget.view)
|
scroll = ttk.Scrollbar(parent, orient=direction, command=widget.view)
|
||||||
# ORIENT: VERTICAL, HORIZONTAL
|
# ORIENT: VERTICAL, HORIZONTAL
|
||||||
# WIDGET.VIEW: .xview, .yview
|
# WIDGET.VIEW: .xview, .yview
|
||||||
# NEEDS ASSOCITED WIDGET SCROLL CONFIG
|
# NEEDS ASSOCIATED WIDGET SCROLL CONFIG
|
||||||
widget.configure(xscrollcommand=scroll.set)
|
widget.configure(xscrollcommand=scroll.set)
|
||||||
widget.configure(yscrollcommand=scroll.set)
|
widget.configure(yscrollcommand=scroll.set)
|
||||||
```
|
```
|
||||||
|
@ -324,10 +324,10 @@ txt.delete(start, end) # delete range of text
|
||||||
Feedback about progress of lenghty operation.
|
Feedback about progress of lenghty operation.
|
||||||
|
|
||||||
```py
|
```py
|
||||||
progbar = ttk.Progressbar(parent, orient=direction, lenght=num:int, value=num, maximum=num:float mode=mode)
|
progbar = ttk.Progressbar(parent, orient=direction, length=num:int, value=num, maximum=num:float mode=mode)
|
||||||
# DIRECTION: VERTICAL, HORIZONTAL
|
# DIRECTION: VERTICAL, HORIZONTAL
|
||||||
# MODE: determinate (relative progress of completion), indeterminate (no estimate of completion)
|
# MODE: determinate (relative progress of completion), indeterminate (no estimate of completion)
|
||||||
# LENGHT: dimension in pixel
|
# LENGTH: dimension in pixel
|
||||||
# VALUE: sets the progress, updates the bar as it changes
|
# VALUE: sets the progress, updates the bar as it changes
|
||||||
# MAXIMUM: total number of steps (DEFAULT: 100)
|
# MAXIMUM: total number of steps (DEFAULT: 100)
|
||||||
```
|
```
|
||||||
|
@ -342,7 +342,7 @@ progbar.step(amount) # increment value of given amount (DEFAULT: 1.0)
|
||||||
|
|
||||||
```py
|
```py
|
||||||
progbar.start() # starts progressbar
|
progbar.start() # starts progressbar
|
||||||
progbar.stop() #stopos progressbar
|
progbar.stop() #stoops progressbar
|
||||||
```
|
```
|
||||||
|
|
||||||
## SCALE
|
## SCALE
|
||||||
|
@ -350,7 +350,7 @@ progbar.stop() #stopos progressbar
|
||||||
Provide a numeric value through direct manipulation.
|
Provide a numeric value through direct manipulation.
|
||||||
|
|
||||||
```py
|
```py
|
||||||
scale = ttk.Scale(parent, orient=DIR, lenght=num:int, from_=num:float, to=num:float, command=cmd)
|
scale = ttk.Scale(parent, orient=DIR, length=num:int, from_=num:float, to=num:float, command=cmd)
|
||||||
# COMMAND: calls cmd at every scale change, appends current value to func call
|
# COMMAND: calls cmd at every scale change, appends current value to func call
|
||||||
scale['value'] # set or read current value
|
scale['value'] # set or read current value
|
||||||
scale.set(value) # set current value
|
scale.set(value) # set current value
|
||||||
|
@ -364,9 +364,9 @@ Choose numbers. The spinbox choses item from a list, arrows permit cycling lits
|
||||||
```py
|
```py
|
||||||
spinval = StringVar()
|
spinval = StringVar()
|
||||||
spin = Spinbox(parent, from_=num, to=num, textvariable=spinval, increment=num, value=lst, wrap=boolean)
|
spin = Spinbox(parent, from_=num, to=num, textvariable=spinval, increment=num, value=lst, wrap=boolean)
|
||||||
# INCREMENT specifies incremend\decremenment by arrow button
|
# INCREMENT specifies increment\decrement by arrow button
|
||||||
# VALUE: list of items associated with the spinbox
|
# VALUE: list of items associated with the spinbox
|
||||||
# WRAP: boolean value determining if value shuld wrap around if beyond start-end value
|
# WRAP: boolean value determining if value should wrap around if beyond start-end value
|
||||||
```
|
```
|
||||||
|
|
||||||
## GRID GEOMETRY MANAGER
|
## GRID GEOMETRY MANAGER
|
||||||
|
@ -424,7 +424,7 @@ tlw = Toplevel(parent) # parent of root window, no need to grid it
|
||||||
|
|
||||||
window.destroy()
|
window.destroy()
|
||||||
# can destroy every widget
|
# can destroy every widget
|
||||||
# destroing parent also destroys it's children
|
# destroying parent also destroys it's children
|
||||||
```
|
```
|
||||||
|
|
||||||
### CHANGING BEHAVIOR AND STYLE
|
### CHANGING BEHAVIOR AND STYLE
|
||||||
|
@ -436,7 +436,7 @@ window.title('new title') # sets title
|
||||||
|
|
||||||
# SIZE AND LOCATION
|
# SIZE AND LOCATION
|
||||||
window.geometry(geo_specs)
|
window.geometry(geo_specs)
|
||||||
'''full geomtry specification: width * height +- x +- y (actual coordinates of screen)
|
'''full geometry specification: width * height +- x +- y (actual coordinates of screen)
|
||||||
+x --> x pixels from left edge
|
+x --> x pixels from left edge
|
||||||
-x --> x pixels from right edge
|
-x --> x pixels from right edge
|
||||||
+y --> y pixels from top edge
|
+y --> y pixels from top edge
|
||||||
|
@ -454,7 +454,7 @@ window.lift(otherwin) # relative to other window
|
||||||
window.lower() # absolute position
|
window.lower() # absolute position
|
||||||
window.lower(otherwin) # relative to other window
|
window.lower(otherwin) # relative to other window
|
||||||
|
|
||||||
# RESIZION BEHAVIOR
|
# RESIZE BEHAVIOR
|
||||||
window.resizable(boolean, boolean) # sets if resizable in width (1st param) and width (2nd param)
|
window.resizable(boolean, boolean) # sets if resizable in width (1st param) and width (2nd param)
|
||||||
window.minsize(num, num) # sets min width and height
|
window.minsize(num, num) # sets min width and height
|
||||||
window.maxsize(num, num) # sets max width and height
|
window.maxsize(num, num) # sets max width and height
|
||||||
|
@ -470,7 +470,7 @@ window.deiconify() # deiconifies window
|
||||||
### STANDARD DIALOGS
|
### STANDARD DIALOGS
|
||||||
|
|
||||||
```py
|
```py
|
||||||
# SLECTING FILE AND DIRECTORIES
|
# SLEETING FILE AND DIRECTORIES
|
||||||
# on Windows and Mac invokes underlying OS dialogs directly
|
# on Windows and Mac invokes underlying OS dialogs directly
|
||||||
from tkinter import filedialog
|
from tkinter import filedialog
|
||||||
filename = filedialog.askopenfilename()
|
filename = filedialog.askopenfilename()
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
# Pillow Library Cheat Sheet
|
# Pillow
|
||||||
|
|
||||||
## Standard Imports
|
## Standard Imports
|
||||||
|
|
||||||
|
@ -16,7 +16,7 @@ image = Image.open(filepath, mode) # open image file (returns Image object)
|
||||||
|
|
||||||
image.format # image file extension
|
image.format # image file extension
|
||||||
image.size # 2-tuple (width, height) in pixels
|
image.size # 2-tuple (width, height) in pixels
|
||||||
image.mode # defines number and name of bands in image, pixeld type and depth
|
image.mode # defines number and name of bands in image, pixel type and depth
|
||||||
```
|
```
|
||||||
|
|
||||||
## SAVING IMAGE FILE
|
## SAVING IMAGE FILE
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
# PyCarto Cheat Sheet
|
# PyCairo
|
||||||
|
|
||||||
## Definitions
|
## Definitions
|
||||||
|
|
||||||
|
@ -11,7 +11,7 @@ A `Path` is a collection of points used to create primitive shapes such as lines
|
||||||
In a closed path, starting and ending points meet. In an open path, starting and ending point do not meet. In PyCairo, we start with an empty path.
|
In a closed path, starting and ending points meet. In an open path, starting and ending point do not meet. In PyCairo, we start with an empty path.
|
||||||
First, we define a path and then we make them visible by stroking and/or filling them. After each `stroke()` or `fill()` method call, the path is emptied.
|
First, we define a path and then we make them visible by stroking and/or filling them. After each `stroke()` or `fill()` method call, the path is emptied.
|
||||||
We have to define a new path. If we want to keep the existing path for later drawing, we can use the `stroke_preserve()` and `fill_preserve()` methods.
|
We have to define a new path. If we want to keep the existing path for later drawing, we can use the `stroke_preserve()` and `fill_preserve()` methods.
|
||||||
A path is made of subpaths.
|
A path is made of sub-paths.
|
||||||
|
|
||||||
A `Source` is the paint we use in drawing. We can compare the source to a pen or ink that we use to draw the outlines and fill the shapes.
|
A `Source` is the paint we use in drawing. We can compare the source to a pen or ink that we use to draw the outlines and fill the shapes.
|
||||||
There are four kinds of basic sources: colors, gradients, patterns, and images.
|
There are four kinds of basic sources: colors, gradients, patterns, and images.
|
||||||
|
@ -83,7 +83,7 @@ context.set_source_rgb(red, green, blue)
|
||||||
`context.new_sub_path()` begins a new sub-path. Note that the existing path is not affected. After this call there will be no current point.
|
`context.new_sub_path()` begins a new sub-path. Note that the existing path is not affected. After this call there will be no current point.
|
||||||
In many cases, this call is not needed since new sub-paths are frequently started with `Context.move_to()`.
|
In many cases, this call is not needed since new sub-paths are frequently started with `Context.move_to()`.
|
||||||
A call to `new_sub_path()` is particularly useful when beginning a new sub-path with one of the `Context.arc()` calls.
|
A call to `new_sub_path()` is particularly useful when beginning a new sub-path with one of the `Context.arc()` calls.
|
||||||
This makes things easier as it is no longer necessary to manually compute the arc’s initial coordinates for a call to `Context.move_to()`.
|
This makes things easier as it is no longer necessary to manually compute the arc's initial coordinates for a call to `Context.move_to()`.
|
||||||
|
|
||||||
### Stroke
|
### Stroke
|
||||||
|
|
||||||
|
@ -99,7 +99,7 @@ After `fill()`, the current path will be cleared from the Context.
|
||||||
`context.set_fill_rule(fill_rule)` set a FILL RULE to the cairo context.
|
`context.set_fill_rule(fill_rule)` set a FILL RULE to the cairo context.
|
||||||
|
|
||||||
For both fill rules, whether or not a point is included in the fill is determined by taking a ray from that point to infinity and looking at intersections with the path.
|
For both fill rules, whether or not a point is included in the fill is determined by taking a ray from that point to infinity and looking at intersections with the path.
|
||||||
The ray can be in any direction, as long as it doesn’t pass through the end point of a segment or have a tricky intersection such as intersecting tangent to the path.
|
The ray can be in any direction, as long as it doesn't pass through the end point of a segment or have a tricky intersection such as intersecting tangent to the path.
|
||||||
(Note that filling is not actually implemented in this way. This is just a description of the rule that is applied.)
|
(Note that filling is not actually implemented in this way. This is just a description of the rule that is applied.)
|
||||||
|
|
||||||
* `cairo.FILL_RULE_WINDING` (default):
|
* `cairo.FILL_RULE_WINDING` (default):
|
||||||
|
@ -138,9 +138,9 @@ Font Weights:
|
||||||
## Creating the image
|
## Creating the image
|
||||||
|
|
||||||
```py
|
```py
|
||||||
surface.show_page() # Emits and clears the current page for backends that support multiple pages. Use copy_page() if you don’t want to clear the page.
|
surface.show_page() # Emits and clears the current page for backends that support multiple pages. Use copy_page() if you don't want to clear the page.
|
||||||
|
|
||||||
surface.copy_page() # Emits the current page for backends that support multiple pages, but doesn’t clear it, so that the contents of the current page will be retained for the next page. Use show_page() if you want to get an empty page after the emission.
|
surface.copy_page() # Emits the current page for backends that support multiple pages, but doesn't clear it, so that the contents of the current page will be retained for the next page. Use show_page() if you want to get an empty page after the emission.
|
||||||
|
|
||||||
surface.write_to_png("filename") # Writes the contents of Surface to filename as a PNG image
|
surface.write_to_png("filename") # Writes the contents of Surface to filename as a PNG image
|
||||||
```
|
```
|
||||||
|
|
|
@ -16,7 +16,7 @@ Unless explicitly specified `np.array` tries to infer a good data type for the a
|
||||||
The data type is stored in a special dtype object.
|
The data type is stored in a special dtype object.
|
||||||
|
|
||||||
```py
|
```py
|
||||||
var = np.array(sequence) # createa array
|
var = np.array(sequence) # creates array
|
||||||
var = np.asarray(sequence) # convert input to array
|
var = np.asarray(sequence) # convert input to array
|
||||||
var = np.ndarray(*sequence) # creates multidimensional array
|
var = np.ndarray(*sequence) # creates multidimensional array
|
||||||
var = np.asanyarray(*sequence) # convert the input to an ndarray
|
var = np.asanyarray(*sequence) # convert the input to an ndarray
|
||||||
|
@ -53,12 +53,12 @@ The numerical `dtypes` are named the same way: a type name followed by a number
|
||||||
| complex64, complex128, complex256 | c8, c16, c32 | Complex numbers represented by two 32, 64, or 128 floats, respectively |
|
| complex64, complex128, complex256 | c8, c16, c32 | Complex numbers represented by two 32, 64, or 128 floats, respectively |
|
||||||
| bool | ? | Boolean type storing True and False values |
|
| bool | ? | Boolean type storing True and False values |
|
||||||
| object | O | Python object type |
|
| object | O | Python object type |
|
||||||
| string_ | `S<num>` | Fixed-length string type (1 byte per character), `<num>` is string lenght |
|
| string_ | `S<num>` | Fixed-length string type (1 byte per character), `<num>` is string length |
|
||||||
| unicode_ | `U<num>` | Fixed-length unicode type, `<num>` is lenght |
|
| unicode_ | `U<num>` | Fixed-length unicode type, `<num>` is length |
|
||||||
|
|
||||||
## OPERATIONS BETWEEN ARRAYS AND SCALARS
|
## OPERATIONS BETWEEN ARRAYS AND SCALARS
|
||||||
|
|
||||||
Any arithmetic operations between equal-size arrays applies the operation elementwise.
|
Any arithmetic operations between equal-size arrays applies the operation element-wise.
|
||||||
|
|
||||||
array `+` scalar --> element-wise addition (`[1, 2, 3] + 2 = [3, 4, 5]`)
|
array `+` scalar --> element-wise addition (`[1, 2, 3] + 2 = [3, 4, 5]`)
|
||||||
array `-` scalar --> element-wise subtraction (`[1 , 2, 3] - 2 = [-2, 0, 1]`)
|
array `-` scalar --> element-wise subtraction (`[1 , 2, 3] - 2 = [-2, 0, 1]`)
|
||||||
|
@ -73,7 +73,7 @@ array_1 `/` array_2 --> element-wise division (`[1, 2, 3] / [3, 2, 1] = [0.33, 1
|
||||||
## SHAPE MANIPULATION
|
## SHAPE MANIPULATION
|
||||||
|
|
||||||
```py
|
```py
|
||||||
np.reshape(array, newshape) # changes the shape of the array
|
np.reshape(array, new_shape) # changes the shape of the array
|
||||||
np.ravel(array) # returns the array flattened
|
np.ravel(array) # returns the array flattened
|
||||||
array.resize(shape) # modifies the array itself
|
array.resize(shape) # modifies the array itself
|
||||||
array.T # returns the array transposed
|
array.T # returns the array transposed
|
||||||
|
@ -87,7 +87,7 @@ np.swapaxes(array, first_axis, second_axis) # interchange two axes of an array
|
||||||
```py
|
```py
|
||||||
np.vstack((array1, array2)) # takes tuple, vertical stack of arrays (column wise)
|
np.vstack((array1, array2)) # takes tuple, vertical stack of arrays (column wise)
|
||||||
np.hstack((array1, array2)) # takes a tuple, horizontal stack of arrays (row wise)
|
np.hstack((array1, array2)) # takes a tuple, horizontal stack of arrays (row wise)
|
||||||
np.dstack((array1, array2)) # takes a tuple, depth wise stack of arrays (3rd dimesion)
|
np.dstack((array1, array2)) # takes a tuple, depth wise stack of arrays (3rd dimension)
|
||||||
np.stack(*arrays, axis) # joins a sequence of arrays along a new axis (axis is an int)
|
np.stack(*arrays, axis) # joins a sequence of arrays along a new axis (axis is an int)
|
||||||
np.concatenate((array1, array2, ...), axis) # joins a sequence of arrays along an existing axis (axis is an int)
|
np.concatenate((array1, array2, ...), axis) # joins a sequence of arrays along an existing axis (axis is an int)
|
||||||
```
|
```
|
||||||
|
@ -95,32 +95,32 @@ np.concatenate((array1, array2, ...), axis) # joins a sequence of arrays along a
|
||||||
## SPLITTING ARRAYS
|
## SPLITTING ARRAYS
|
||||||
|
|
||||||
```py
|
```py
|
||||||
np.split(array, indices) # splits an array into equalli long sub-arrays (indices is int), if not possible raises error
|
np.split(array, indices) # splits an array into equall7 long sub-arrays (indices is int), if not possible raises error
|
||||||
np.vsplit(array, indices) # splits an array equally into sub-arrays vertically (row wise) if not possible raises error
|
np.vsplit(array, indices) # splits an array equally into sub-arrays vertically (row wise) if not possible raises error
|
||||||
np.hsplit(array, indices) # splits an array equally into sub-arrays horizontally (column wise) if not possible raises error
|
np.hsplit(array, indices) # splits an array equally into sub-arrays horizontally (column wise) if not possible raises error
|
||||||
np.dsplit(array, indices) # splits an array into equally sub-arrays along the 3rd axis (depth) if not possible raises error
|
np.dsplit(array, indices) # splits an array into equally sub-arrays along the 3rd axis (depth) if not possible raises error
|
||||||
np.array_split(array, indices) # splits an array into sub-arrays, arrays can be of different lenghts
|
np.array_split(array, indices) # splits an array into sub-arrays, arrays can be of different lengths
|
||||||
```
|
```
|
||||||
|
|
||||||
## VIEW()
|
## VIEW()
|
||||||
|
|
||||||
```py
|
```py
|
||||||
var = array.view() # creates a new array that looks at the same data
|
var = array.view() # creates a new array that looks at the same data
|
||||||
# slicinga returnas a view
|
# slicing returns a view
|
||||||
# view shapes are separated but assignement changes all arrays
|
# view shapes are separated but assignment changes all arrays
|
||||||
```
|
```
|
||||||
|
|
||||||
## COPY()
|
## COPY()
|
||||||
|
|
||||||
```py
|
```py
|
||||||
var = array.copy() # creates a deepcopy of the array
|
var = array.copy() # creates a deep copy of the array
|
||||||
```
|
```
|
||||||
|
|
||||||
## INDEXING, SLICING, ITERATING
|
## INDEXING, SLICING, ITERATING
|
||||||
|
|
||||||
1-dimensional --> sliced, iterated and indexed as standard
|
1-dimensional --> sliced, iterated and indexed as standard
|
||||||
n-dimensinal --> one index per axis, index given in tuple separated by commas `[i, j] (i, j)`
|
n-dimensional --> one index per axis, index given in tuple separated by commas `[i, j] (i, j)`
|
||||||
dots (`...`) represent as meny colons as needed to produce complete indexing tuple
|
dots (`...`) represent as many colons as needed to produce complete indexing tuple
|
||||||
|
|
||||||
- `x[1, 2, ...] == [1, 2, :, :, :]`
|
- `x[1, 2, ...] == [1, 2, :, :, :]`
|
||||||
- `x[..., 3] == [:, :, :, :, 3]`
|
- `x[..., 3] == [:, :, :, :, 3]`
|
||||||
|
@ -134,7 +134,7 @@ iteration on first index, use .flat() to iterate over each element
|
||||||
|
|
||||||
## UNIVERSAL FUNCTIONS (ufunc)
|
## UNIVERSAL FUNCTIONS (ufunc)
|
||||||
|
|
||||||
Functions that performs elemen-wise operations (vectorization).
|
Functions that performs element-wise operations (vectorization).
|
||||||
|
|
||||||
```py
|
```py
|
||||||
np.abs(array) # vectorized abs(), return element absolute value
|
np.abs(array) # vectorized abs(), return element absolute value
|
||||||
|
@ -151,7 +151,7 @@ np.ceil(array) # vectorized ceil()
|
||||||
np.floor(array) # vectorized floor()
|
np.floor(array) # vectorized floor()
|
||||||
np.rint(array) # vectorized round() to nearest int
|
np.rint(array) # vectorized round() to nearest int
|
||||||
np.modf(array) # vectorized divmod(), returns the fractional and integral parts of element
|
np.modf(array) # vectorized divmod(), returns the fractional and integral parts of element
|
||||||
np.isnan(array) # vectorized x == NaN, return bollean array
|
np.isnan(array) # vectorized x == NaN, return boolean array
|
||||||
np.isinf(array) # vectorized test for positive or negative infinity, return boolean array
|
np.isinf(array) # vectorized test for positive or negative infinity, return boolean array
|
||||||
np.isfineite(array) # vectorized test fo finiteness, returns boolean array
|
np.isfineite(array) # vectorized test fo finiteness, returns boolean array
|
||||||
np.cos(array) # vectorized cos(x)
|
np.cos(array) # vectorized cos(x)
|
||||||
|
@ -163,7 +163,7 @@ np.tanh(array) # vectorized tanh(x)
|
||||||
np.arccos(array) # vectorized arccos(x)
|
np.arccos(array) # vectorized arccos(x)
|
||||||
np.arcsinh(array) # vectorized arcsinh(x)
|
np.arcsinh(array) # vectorized arcsinh(x)
|
||||||
np.arctan(array) # vectorized arctan(x)
|
np.arctan(array) # vectorized arctan(x)
|
||||||
np.arccosh(array) # vectorized arccos(x)
|
np.arccosh(array) # vectorized arccosh(x)
|
||||||
np.arcsinh(array) # vectorized arcsin(x)
|
np.arcsinh(array) # vectorized arcsin(x)
|
||||||
np.arctanh(array) # vectorized arctanh(x)
|
np.arctanh(array) # vectorized arctanh(x)
|
||||||
np.logical_not(array) # vectorized not(x), equivalent to -array
|
np.logical_not(array) # vectorized not(x), equivalent to -array
|
||||||
|
@ -246,13 +246,13 @@ np.setxor1d() # Set symmetric differences; elements that are in either of the a
|
||||||
## FILE I/O WITH ARRAYS
|
## FILE I/O WITH ARRAYS
|
||||||
|
|
||||||
```py
|
```py
|
||||||
np.save(file, array) # save array to binary file in .npy fromat
|
np.save(file, array) # save array to binary file in .npy format
|
||||||
np.savez(file, *array) # saveseveral arrays into a single file in uncompressed .npz format
|
np.savez(file, *array) # save several arrays into a single file in uncompressed .npz format
|
||||||
np.savez_compressed(file, *args, *kwargs) # save several arrays into a single file in compressed .npz format
|
np.savez_compressed(file, *args, *kwargs) # save several arrays into a single file in compressed .npz format
|
||||||
# *ARGS: arrays to save to the file. arrays will be saved with names “arr_0”, “arr_1”, and so on
|
# *ARGS: arrays to save to the file. arrays will be saved with names "arr_0", "arr_1", and so on
|
||||||
# **KWARGS: arrays to save to the file. arrays will be saved in the file with the keyword names
|
# **KWARGS: arrays to save to the file. arrays will be saved in the file with the keyword names
|
||||||
|
|
||||||
np.savetxt(file, X, fmt="%.18e", delimiter=" ") # save arry to text file
|
np.savetxt(file, X, fmt="%.18e", delimiter=" ") # save array to text file
|
||||||
# X: 1D or 2D
|
# X: 1D or 2D
|
||||||
# FMT: Python Format Specification Mini-Language
|
# FMT: Python Format Specification Mini-Language
|
||||||
# DELIMITER: {str} -- string used to separate values
|
# DELIMITER: {str} -- string used to separate values
|
||||||
|
@ -272,14 +272,14 @@ np.diag(array, k=0) # extract a diagonal or construct a diagonal array
|
||||||
|
|
||||||
np.dot(x ,y) # matrix dot product
|
np.dot(x ,y) # matrix dot product
|
||||||
np.trace(array, offset=0, dtype=None, out=None) # return the sum along diagonals of the array
|
np.trace(array, offset=0, dtype=None, out=None) # return the sum along diagonals of the array
|
||||||
# OFFSET: {int} -- offest of the diagonal from the main diagonal
|
# OFFSET: {int} -- offset of the diagonal from the main diagonal
|
||||||
# dtype: {dtype} -- determines the data-type of the returned array
|
# dtype: {dtype} -- determines the data-type of the returned array
|
||||||
# OUT: {ndarray} -- array into which the output is placed
|
# OUT: {ndarray} -- array into which the output is placed
|
||||||
|
|
||||||
np.linalg.det(A) # compute the determinant of an array
|
np.linalg.det(A) # compute the determinant of an array
|
||||||
np.linalg.eig(A) # compute the eigenvalues and right eigenvectors of a square array
|
np.linalg.eig(A) # compute the eigenvalues and right eigenvectors of a square array
|
||||||
np.linalg.inv(A) # compute the (multiplicative) inverse of a matrix
|
np.linalg.inv(A) # compute the (multiplicative) inverse of a matrix
|
||||||
# Ainv satisfies dot(A, Ainv) = dor(Ainv, A) = eye(A.shape[0])
|
# A_inv satisfies dot(A, A_inv) = dor(A_inv, A) = eye(A.shape[0])
|
||||||
|
|
||||||
np.linalg.pinv(A) # compute the (Moore-Penrose) pseudo-inverse of a matrix
|
np.linalg.pinv(A) # compute the (Moore-Penrose) pseudo-inverse of a matrix
|
||||||
np.linalg.qr() # factor the matrix a as qr, where q is orthonormal and r is upper-triangular
|
np.linalg.qr() # factor the matrix a as qr, where q is orthonormal and r is upper-triangular
|
||||||
|
@ -304,13 +304,13 @@ np.random.Generator.beta(a, b, size=None) # draw samples from a Beta distributi
|
||||||
|
|
||||||
np.random.Generator.binomial(n, p, size=None) # draw samples from a binomial distribution
|
np.random.Generator.binomial(n, p, size=None) # draw samples from a binomial distribution
|
||||||
# N: {int, array ints} -- parameter of the distribution, >= 0
|
# N: {int, array ints} -- parameter of the distribution, >= 0
|
||||||
# P: {float, attay floats} -- Parameter of the distribution, >= 0 and <= 1
|
# P: {float, arrey floats} -- Parameter of the distribution, >= 0 and <= 1
|
||||||
|
|
||||||
np.random.Generator.chisquare(df, size=None)
|
np.random.Generator.chisquare(df, size=None)
|
||||||
# DF: {float, array floats} -- degrees of freedom, > 0
|
# DF: {float, array floats} -- degrees of freedom, > 0
|
||||||
|
|
||||||
np.random.Generator.gamma(shape, scale=1.0, size=None) # draw samples from a Gamma distribution
|
np.random.Generator.gamma(shape, scale=1.0, size=None) # draw samples from a Gamma distribution
|
||||||
# SHAPE: {flaot, array floats} -- shape of the gamma distribution, != 0
|
# SHAPE: {float, array floats} -- shape of the gamma distribution, != 0
|
||||||
|
|
||||||
np.random.Generator.normal(loc=0.0, scale=1.0, Size=None) # draw random samples from a normal (Gaussian) distribution
|
np.random.Generator.normal(loc=0.0, scale=1.0, Size=None) # draw random samples from a normal (Gaussian) distribution
|
||||||
# LOC: {float, all floats} -- mean ("centre") of distribution
|
# LOC: {float, all floats} -- mean ("centre") of distribution
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
# Pandas Lib
|
# Pandas
|
||||||
|
|
||||||
## Basic Pandas Imports
|
## Basic Pandas Imports
|
||||||
|
|
||||||
|
@ -25,8 +25,8 @@ s = Series(dict) # Series created from python dict, dict keys become index valu
|
||||||
```py
|
```py
|
||||||
s['index'] # selection by index label
|
s['index'] # selection by index label
|
||||||
s[condition] # return slice selected by condition
|
s[condition] # return slice selected by condition
|
||||||
s[ : ] # slice endpoin included
|
s[ : ] # slice endpoint included
|
||||||
s[ : ] = *value # modifi value of entire slice
|
s[ : ] = *value # modify value of entire slice
|
||||||
s[condition] = *value # modify slice by condition
|
s[condition] = *value # modify slice by condition
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -35,8 +35,8 @@ s[condition] = *value # modify slice by condition
|
||||||
Missing data appears as NaN (Not a Number).
|
Missing data appears as NaN (Not a Number).
|
||||||
|
|
||||||
```py
|
```py
|
||||||
pd.isnull(array) # retunn a Series index-bool indicating wich indexes dont have data
|
pd.isnull(array) # return a Series index-bool indicating which indexes don't have data
|
||||||
pd.notnull(array) # retunn a Series index-bool indicating wich indexes have data
|
pd.notnull(array) # return a Series index-bool indicating which indexes have data
|
||||||
array.isnull()
|
array.isnull()
|
||||||
array.notnull()
|
array.notnull()
|
||||||
```
|
```
|
||||||
|
@ -53,18 +53,18 @@ s.index.name = "index name" # renames index
|
||||||
### SERIES METHODS
|
### SERIES METHODS
|
||||||
|
|
||||||
```py
|
```py
|
||||||
pd.Series.isin(self, values) # boolean Series showing whether elements in Series matcheselements in values exactly
|
pd.Series.isin(self, values) # boolean Series showing whether elements in Series matches elements in values exactly
|
||||||
|
|
||||||
# Conform Series to new index, new object produced unless the new index is equivalent to current one and copy=False
|
# Conform Series to new index, new object produced unless the new index is equivalent to current one and copy=False
|
||||||
pd.Series.reindex(delf, index=None, **kwargs)
|
pd.Series.reindex(self, index=None, **kwargs)
|
||||||
# INDEX: {array} -- new labels / index
|
# INDEX: {array} -- new labels / index
|
||||||
# METHOD: {none (dont fill gaps), pad (fill or carry values forward), backfill (fill or carry values backward)}-- hole filling method
|
# METHOD: {none (don't fill gaps), pad (fill or carry values forward), backfill (fill or carry values backward)}-- hole filling method
|
||||||
# COPY: {bool} -- return new object even if index is same -- DEFAULT True
|
# COPY: {bool} -- return new object even if index is same -- DEFAULT True
|
||||||
# FILLVALUE: {scalar} --value to use for missing values. DEFAULT NaN
|
# FILLVALUE: {scalar} --value to use for missing values. DEFAULT NaN
|
||||||
|
|
||||||
pd.Series.drop(self, index=None, **kwargs) # return Series with specified index labels removed
|
pd.Series.drop(self, index=None, **kwargs) # return Series with specified index labels removed
|
||||||
# INPLACE: {bool} -- if true do operation in place and return None -- DEFAULT False
|
# INPLACE: {bool} -- if true do operation in place and return None -- DEFAULT False
|
||||||
# ERRORS: {ignore, raise} -- If ‘ignore’, suppress error and existing labels are dropped
|
# ERRORS: {ignore, raise} -- If "ignore", suppress error and existing labels are dropped
|
||||||
# KeyError raised if not all of the labels are found in the selected axis
|
# KeyError raised if not all of the labels are found in the selected axis
|
||||||
|
|
||||||
pd.Series.value_counts(self, normalize=False, sort=True, ascending=False, bins=None, dropna=True)
|
pd.Series.value_counts(self, normalize=False, sort=True, ascending=False, bins=None, dropna=True)
|
||||||
|
@ -72,7 +72,7 @@ pd.Series.value_counts(self, normalize=False, sort=True, ascending=False, bins=N
|
||||||
# SORT: {bool} -- sort by frequency -- DEFAULT True
|
# SORT: {bool} -- sort by frequency -- DEFAULT True
|
||||||
# ASCENDING: {bool} -- sort in ascending order -- DEFAULT False
|
# ASCENDING: {bool} -- sort in ascending order -- DEFAULT False
|
||||||
# BINS: {int} -- group values into half-open bins, only works with numeric data
|
# BINS: {int} -- group values into half-open bins, only works with numeric data
|
||||||
# DROPNA: {bool} -- dont include counts of NaN
|
# DROPNA: {bool} -- don't include counts of NaN
|
||||||
```
|
```
|
||||||
|
|
||||||
## DATAFRAME
|
## DATAFRAME
|
||||||
|
@ -124,19 +124,19 @@ df.T # transpose
|
||||||
### DATAFRAME METHODS
|
### DATAFRAME METHODS
|
||||||
|
|
||||||
```py
|
```py
|
||||||
pd.DataFrame.isin(self , values) # boolean DataFrame showing whether elements in DataFrame matcheselements in values exactly
|
pd.DataFrame.isin(self , values) # boolean DataFrame showing whether elements in DataFrame matches elements in values exactly
|
||||||
|
|
||||||
# Conform DataFrame to new index, new object produced unless the new index is equivalent to current one and copy=False
|
# Conform DataFrame to new index, new object produced unless the new index is equivalent to current one and copy=False
|
||||||
pd.DataFrame.reindex(self, index=None, columns=None, **kwargs)
|
pd.DataFrame.reindex(self, index=None, columns=None, **kwargs)
|
||||||
# INDEX: {array} -- new labels / index
|
# INDEX: {array} -- new labels / index
|
||||||
# COLUMNS: {array} -- new labels / columns
|
# COLUMNS: {array} -- new labels / columns
|
||||||
# METHOD: {none (dont fill gaps), pad (fill or carry values forward), backfill (fill or carry values backward)}-- hole filling method
|
# METHOD: {none (don't fill gaps), pad (fill or carry values forward), backfill (fill or carry values backward)}-- hole filling method
|
||||||
# COPY: {bool} -- return new object even if index is same -- DEFAULT True
|
# COPY: {bool} -- return new object even if index is same -- DEFAULT True
|
||||||
# FILLVALUE: {scalar} --value to use for missing values. DEFAULT NaN
|
# FILLVALUE: {scalar} --value to use for missing values. DEFAULT NaN
|
||||||
|
|
||||||
pd.DataFrame.drop(self, index=None, columns=None, **kwargs) # Remove rows or columns by specifying label names
|
pd.DataFrame.drop(self, index=None, columns=None, **kwargs) # Remove rows or columns by specifying label names
|
||||||
# INPLACE: {bool} -- if true do operation in place and return None -- DEFAULT False
|
# INPLACE: {bool} -- if true do operation in place and return None -- DEFAULT False
|
||||||
# ERRORS: {ignore, raise} -- If ‘ignore’, suppress error and existing labels are dropped
|
# ERRORS: {ignore, raise} -- If "ignore", suppress error and existing labels are dropped
|
||||||
# KeyError raised if not all of the labels are found in the selected axis
|
# KeyError raised if not all of the labels are found in the selected axis
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -147,7 +147,7 @@ Holds axis labels and metadata, immutable.
|
||||||
### INDEX TYPES
|
### INDEX TYPES
|
||||||
|
|
||||||
```py
|
```py
|
||||||
pd.Index # immutable ordered ndarray, sliceable. stortes axis labels
|
pd.Index # immutable ordered ndarray, sliceable. stores axis labels
|
||||||
pd.Int64Index # special case of Index with purely integer labels
|
pd.Int64Index # special case of Index with purely integer labels
|
||||||
pd.MultiIndex # multi-level (hierarchical) index object for pandas objects
|
pd.MultiIndex # multi-level (hierarchical) index object for pandas objects
|
||||||
pd.PeriodINdex # immutable ndarray holding ordinal values indicating regular periods in time
|
pd.PeriodINdex # immutable ndarray holding ordinal values indicating regular periods in time
|
||||||
|
@ -169,27 +169,27 @@ pd.Index.hasnans # Return True if the index has NaNs
|
||||||
pd.Index.append(self, other) # append a collection of Index options together
|
pd.Index.append(self, other) # append a collection of Index options together
|
||||||
|
|
||||||
pd.Index.difference(self, other, sort=None) # set difference of two Index objects
|
pd.Index.difference(self, other, sort=None) # set difference of two Index objects
|
||||||
# SORT: {None (attempt sorting), False (dont sort)}
|
# SORT: {None (attempt sorting), False (don't sort)}
|
||||||
|
|
||||||
pd.Index.intersection(self, other, sort=None) # set intersection of two Index objects
|
pd.Index.intersection(self, other, sort=None) # set intersection of two Index objects
|
||||||
# SORT: {None (attempt sorting), False (dont sort)}
|
# SORT: {None (attempt sorting), False (don't sort)}
|
||||||
|
|
||||||
pd.Index.union(self, other, sort=None) # set union of two Index objects
|
pd.Index.union(self, other, sort=None) # set union of two Index objects
|
||||||
# SORT: {None (attempt sorting), False (dont sort)}
|
# SORT: {None (attempt sorting), False (don't sort)}
|
||||||
|
|
||||||
pd.Index.isin(self, values, level=None) # boolean array indicating where the index values are in values
|
pd.Index.isin(self, values, level=None) # boolean array indicating where the index values are in values
|
||||||
pd.Index.insert(self, loc, item) # make new Index inserting new item at location
|
pd.Index.insert(self, loc, item) # make new Index inserting new item at location
|
||||||
pd.Index.delete(self, loc) # make new Index with passed location(-s) deleted
|
pd.Index.delete(self, loc) # make new Index with passed location(-s) deleted
|
||||||
|
|
||||||
pd.Index.drop(self, labels, errors='raise') # Make new Index with passed list of labels deleted
|
pd.Index.drop(self, labels, errors='raise') # Make new Index with passed list of labels deleted
|
||||||
# ERRORS: {ignore, raise} -- If ‘ignore’, suppress error and existing labels are dropped
|
# ERRORS: {ignore, raise} -- If 'ignore', suppress error and existing labels are dropped
|
||||||
# KeyError raised if not all of the labels are found in the selected axis
|
# KeyError raised if not all of the labels are found in the selected axis
|
||||||
|
|
||||||
pd.Index.reindex(self, target, **kwargs) # create index with target’s values (move/add/delete values as necessary)
|
pd.Index.reindex(self, target, **kwargs) # create index with target's values (move/add/delete values as necessary)
|
||||||
# METHOD: {none (dont fill gaps), pad (fill or carry values forward), backfill (fill or carry values backward)}-- hole filling method
|
# METHOD: {none (don't fill gaps), pad (fill or carry values forward), backfill (fill or carry values backward)}-- hole filling method
|
||||||
```
|
```
|
||||||
|
|
||||||
## ARITMETHIC OPERATIONS
|
## ARITHMETIC OPERATIONS
|
||||||
|
|
||||||
NumPy arrays operations preserve labels-value link.
|
NumPy arrays operations preserve labels-value link.
|
||||||
Arithmetic operations automatically align differently indexed data.
|
Arithmetic operations automatically align differently indexed data.
|
||||||
|
@ -199,10 +199,10 @@ Missing values propagate in arithmetic computations (NaN `<operator>` value = Na
|
||||||
|
|
||||||
```py
|
```py
|
||||||
self + other
|
self + other
|
||||||
pd.Series.add(self, other, fill_value=None) # add(), supports substituion of NaNs
|
pd.Series.add(self, other, fill_value=None) # add(), supports substitution of NaNs
|
||||||
pd,Series.radd(self, other, fill_value=None) # radd(), supports substituion of NaNs
|
pd,Series.radd(self, other, fill_value=None) # radd(), supports substitution of NaNs
|
||||||
pd.DataFrame.add(self, other, axis=columns, fill_value=None) # add(), supports substituion of NaNs
|
pd.DataFrame.add(self, other, axis=columns, fill_value=None) # add(), supports substitution of NaNs
|
||||||
pd.DataFrame.radd(self, other, axis=columns, fill_value=None) # radd(), supports substituion of NaNs
|
pd.DataFrame.radd(self, other, axis=columns, fill_value=None) # radd(), supports substitution of NaNs
|
||||||
# OTHER: {scalar, sequence, Series, DataFrame}
|
# OTHER: {scalar, sequence, Series, DataFrame}
|
||||||
# AXIS: {0, 1, index, columns} -- whether to compare by the index or columns
|
# AXIS: {0, 1, index, columns} -- whether to compare by the index or columns
|
||||||
# FILLVALUE: {None, float} -- fill missing value
|
# FILLVALUE: {None, float} -- fill missing value
|
||||||
|
@ -212,10 +212,10 @@ pd.DataFrame.radd(self, other, axis=columns, fill_value=None) # radd(), support
|
||||||
|
|
||||||
```py
|
```py
|
||||||
self - other
|
self - other
|
||||||
pd.Series.sub(self, other, fill_value=None) # sub(), supports substituion of NaNs
|
pd.Series.sub(self, other, fill_value=None) # sub(), supports substitution of NaNs
|
||||||
pd.Series.radd(self, other, fill_value=None) # radd(), supports substituion of NaNs
|
pd.Series.radd(self, other, fill_value=None) # radd(), supports substitution of NaNs
|
||||||
ps.DataFrame.sub(self, other, axis=columns, fill_value=None) # sub(), supports substituion of NaNs
|
ps.DataFrame.sub(self, other, axis=columns, fill_value=None) # sub(), supports substitution of NaNs
|
||||||
pd.DataFrame.rsub(self, other, axis=columns, fill_value=None) # rsub(), supports substituion of NaNs
|
pd.DataFrame.rsub(self, other, axis=columns, fill_value=None) # rsub(), supports substitution of NaNs
|
||||||
# OTHER: {scalar, sequence, Series, DataFrame}
|
# OTHER: {scalar, sequence, Series, DataFrame}
|
||||||
# AXIS: {0, 1, index, columns} -- whether to compare by the index or columns
|
# AXIS: {0, 1, index, columns} -- whether to compare by the index or columns
|
||||||
# FILLVALUE: {None, float} -- fill missing value
|
# FILLVALUE: {None, float} -- fill missing value
|
||||||
|
@ -225,10 +225,10 @@ pd.DataFrame.rsub(self, other, axis=columns, fill_value=None) # rsub(), support
|
||||||
|
|
||||||
```py
|
```py
|
||||||
self * other
|
self * other
|
||||||
pd.Series.mul(self, other, fill_value=None) # mul(), supports substituion of NaNs
|
pd.Series.mul(self, other, fill_value=None) # mul(), supports substitution of NaNs
|
||||||
pd.Series.rmul(self, other, fill_value=None) # rmul(), supports substituion of NaNs
|
pd.Series.rmul(self, other, fill_value=None) # rmul(), supports substitution of NaNs
|
||||||
ps.DataFrame.mul(self, other, axis=columns, fill_value=None) # mul(), supports substituion of NaNs
|
ps.DataFrame.mul(self, other, axis=columns, fill_value=None) # mul(), supports substitution of NaNs
|
||||||
pd.DataFrame.rmul(self, other, axis=columns, fill_value=None) # rmul(), supports substituion of NaNs
|
pd.DataFrame.rmul(self, other, axis=columns, fill_value=None) # rmul(), supports substitution of NaNs
|
||||||
# OTHER: {scalar, sequence, Series, DataFrame}
|
# OTHER: {scalar, sequence, Series, DataFrame}
|
||||||
# AXIS: {0, 1, index, columns} -- whether to compare by the index or columns
|
# AXIS: {0, 1, index, columns} -- whether to compare by the index or columns
|
||||||
# FILLVALUE: {None, float} -- fill missing value
|
# FILLVALUE: {None, float} -- fill missing value
|
||||||
|
@ -238,14 +238,14 @@ pd.DataFrame.rmul(self, other, axis=columns, fill_value=None) # rmul(), support
|
||||||
|
|
||||||
```py
|
```py
|
||||||
self / other
|
self / other
|
||||||
pd.Series.div(self, other, fill_value=None) # div(), supports substituion of NaNs
|
pd.Series.div(self, other, fill_value=None) # div(), supports substitution of NaNs
|
||||||
pd.Series.rdiv(self, other, fill_value=None) # rdiv(), supports substituion of NaNs
|
pd.Series.rdiv(self, other, fill_value=None) # rdiv(), supports substitution of NaNs
|
||||||
pd.Series.truediv(self, other, fill_value=None) # truediv(), supports substituion of NaNs
|
pd.Series.truediv(self, other, fill_value=None) # truediv(), supports substitution of NaNs
|
||||||
pd.Series.rtruediv(self, other, fill_value=None) # rtruediv(), supports substituion of NaNs
|
pd.Series.rtruediv(self, other, fill_value=None) # rtruediv(), supports substitution of NaNs
|
||||||
ps.DataFrame.div(self, other, axis=columns, fill_value=None) # div(), supports substituion of NaNs
|
ps.DataFrame.div(self, other, axis=columns, fill_value=None) # div(), supports substitution of NaNs
|
||||||
pd.DataFrame.rdiv(self, other, axis=columns, fill_value=None) # rdiv(), supports substituion of NaNs
|
pd.DataFrame.rdiv(self, other, axis=columns, fill_value=None) # rdiv(), supports substitution of NaNs
|
||||||
ps.DataFrame.truediv(self, other, axis=columns, fill_value=None) # truediv(), supports substituion of NaNs
|
ps.DataFrame.truediv(self, other, axis=columns, fill_value=None) # truediv(), supports substitution of NaNs
|
||||||
pd.DataFrame.rtruediv(self, other, axis=columns, fill_value=None) # rtruediv(), supports substituion of NaNs
|
pd.DataFrame.rtruediv(self, other, axis=columns, fill_value=None) # rtruediv(), supports substitution of NaNs
|
||||||
# OTHER: {scalar, sequence, Series, DataFrame}
|
# OTHER: {scalar, sequence, Series, DataFrame}
|
||||||
# AXIS: {0, 1, index, columns} -- whether to compare by the index or columns
|
# AXIS: {0, 1, index, columns} -- whether to compare by the index or columns
|
||||||
# FILLVALUE: {None, float} -- fill missing value
|
# FILLVALUE: {None, float} -- fill missing value
|
||||||
|
@ -255,10 +255,10 @@ pd.DataFrame.rtruediv(self, other, axis=columns, fill_value=None) # rtruediv(),
|
||||||
|
|
||||||
```py
|
```py
|
||||||
self // other
|
self // other
|
||||||
pd.Series.floordiv(self, other, fill_value=None) # floordiv(), supports substituion of NaNs
|
pd.Series.floordiv(self, other, fill_value=None) # floordiv(), supports substitution of NaNs
|
||||||
pd.Series.rfloordiv(self, other, fill_value=None) # rfloordiv(), supports substituion of NaNs
|
pd.Series.rfloordiv(self, other, fill_value=None) # rfloordiv(), supports substitution of NaNs
|
||||||
ps.DataFrame.floordiv(self, other, axis=columns, fill_value=None) # floordiv(), supports substituion of NaNs
|
ps.DataFrame.floordiv(self, other, axis=columns, fill_value=None) # floordiv(), supports substitution of NaNs
|
||||||
pd.DataFrame.rfloordiv(self, other, axis=columns, fill_value=None) # rfloordiv(), supports substituion of NaNs
|
pd.DataFrame.rfloordiv(self, other, axis=columns, fill_value=None) # rfloordiv(), supports substitution of NaNs
|
||||||
# OTHER: {scalar, sequence, Series, DataFrame}
|
# OTHER: {scalar, sequence, Series, DataFrame}
|
||||||
# AXIS: {0, 1, index, columns} -- whether to compare by the index or columns
|
# AXIS: {0, 1, index, columns} -- whether to compare by the index or columns
|
||||||
# FILLVALUE: {None, float} -- fill missing value
|
# FILLVALUE: {None, float} -- fill missing value
|
||||||
|
@ -268,10 +268,10 @@ pd.DataFrame.rfloordiv(self, other, axis=columns, fill_value=None) # rfloordiv(
|
||||||
|
|
||||||
```py
|
```py
|
||||||
self % other
|
self % other
|
||||||
pd.Series.mod(self, other, fill_value=None) # mod(), supports substituion of NaNs
|
pd.Series.mod(self, other, fill_value=None) # mod(), supports substitution of NaNs
|
||||||
pd.Series.rmod(self, other, fill_value=None) # rmod(), supports substituion of NaNs
|
pd.Series.rmod(self, other, fill_value=None) # rmod(), supports substitution of NaNs
|
||||||
ps.DataFrame.mod(self, other, axis=columns, fill_value=None) # mod(), supports substituion of NaNs
|
ps.DataFrame.mod(self, other, axis=columns, fill_value=None) # mod(), supports substitution of NaNs
|
||||||
pd.DataFrame.rmod(self, other, axis=columns, fill_value=None) # rmod(), supports substituion of NaNs
|
pd.DataFrame.rmod(self, other, axis=columns, fill_value=None) # rmod(), supports substitution of NaNs
|
||||||
# OTHER: {scalar, sequence, Series, DataFrame}
|
# OTHER: {scalar, sequence, Series, DataFrame}
|
||||||
# AXIS: {0, 1, index, columns} -- whether to compare by the index or columns
|
# AXIS: {0, 1, index, columns} -- whether to compare by the index or columns
|
||||||
# FILLVALUE: {None, float} -- fill missing value
|
# FILLVALUE: {None, float} -- fill missing value
|
||||||
|
@ -281,10 +281,10 @@ pd.DataFrame.rmod(self, other, axis=columns, fill_value=None) # rmod(), support
|
||||||
|
|
||||||
```py
|
```py
|
||||||
other ** self
|
other ** self
|
||||||
pd.Series.pow(self, other, fill_value=None) # pow(), supports substituion of NaNs
|
pd.Series.pow(self, other, fill_value=None) # pow(), supports substitution of NaNs
|
||||||
pd.Series.rpow(self, other, fill_value=None) # rpow(), supports substituion of NaNs
|
pd.Series.rpow(self, other, fill_value=None) # rpow(), supports substitution of NaNs
|
||||||
ps.DataFrame.pow(self, other, axis=columns, fill_value=None) # pow(), supports substituion of NaNs
|
ps.DataFrame.pow(self, other, axis=columns, fill_value=None) # pow(), supports substitution of NaNs
|
||||||
pd.DataFrame.rpow(self, other, axis=columns, fill_value=None) # rpow(), supports substituion of NaNs
|
pd.DataFrame.rpow(self, other, axis=columns, fill_value=None) # rpow(), supports substitution of NaNs
|
||||||
# OTHER: {scalar, sequence, Series, DataFrame}
|
# OTHER: {scalar, sequence, Series, DataFrame}
|
||||||
# AXIS: {0, 1, index, columns} -- whether to compare by the index or columns
|
# AXIS: {0, 1, index, columns} -- whether to compare by the index or columns
|
||||||
# FILLVALUE: {None, float} -- fill missing value
|
# FILLVALUE: {None, float} -- fill missing value
|
||||||
|
@ -299,7 +299,7 @@ NumPy ufuncs work fine with pandas objects.
|
||||||
```py
|
```py
|
||||||
pd.DataFrame.applymap(self, func) # apply function element-wise
|
pd.DataFrame.applymap(self, func) # apply function element-wise
|
||||||
|
|
||||||
pd.DataFrame.apply(self, func, axis=0, args=()) # apllay a function along an axis of a DataFrame
|
pd.DataFrame.apply(self, func, axis=0, args=()) # apply a function along an axis of a DataFrame
|
||||||
# FUNC: {function} -- function to apply
|
# FUNC: {function} -- function to apply
|
||||||
# AXIS: {O, 1, index, columns} -- axis along which the function is applied
|
# AXIS: {O, 1, index, columns} -- axis along which the function is applied
|
||||||
# ARGS: {tuple} -- positional arguments to pass to func in addition to the array/series
|
# ARGS: {tuple} -- positional arguments to pass to func in addition to the array/series
|
||||||
|
@ -309,7 +309,7 @@ pd.Series.sort_values(self, ascending=True, **kwargs) # sort series by the valu
|
||||||
# ASCENDING: {bool} -- if True, sort values in ascending order, otherwise descending -- DEFAULT True
|
# ASCENDING: {bool} -- if True, sort values in ascending order, otherwise descending -- DEFAULT True
|
||||||
# INPALCE: {bool} -- if True, perform operation in-place
|
# INPALCE: {bool} -- if True, perform operation in-place
|
||||||
# KIND: {quicksort, mergesort, heapsort} -- sorting algorithm
|
# KIND: {quicksort, mergesort, heapsort} -- sorting algorithm
|
||||||
# NA_POSITION {first, last} -- ‘first’ puts NaNs at the beginning, ‘last’ puts NaNs at the end
|
# NA_POSITION {first, last} -- 'first' puts NaNs at the beginning, 'last' puts NaNs at the end
|
||||||
|
|
||||||
pd.DataFrame.sort_index(self, axis=0, ascending=True, **kwargs) # sort object by labels along an axis
|
pd.DataFrame.sort_index(self, axis=0, ascending=True, **kwargs) # sort object by labels along an axis
|
||||||
pd.DataFrame.sort_values(self, axis=0, ascending=True, **kwargs) # sort object by values along an axis
|
pd.DataFrame.sort_values(self, axis=0, ascending=True, **kwargs) # sort object by values along an axis
|
||||||
|
@ -317,7 +317,7 @@ pd.DataFrame.sort_values(self, axis=0, ascending=True, **kwargs) # sort object
|
||||||
# ASCENDING: {bool} -- if True, sort values in ascending order, otherwise descending -- DEFAULT True
|
# ASCENDING: {bool} -- if True, sort values in ascending order, otherwise descending -- DEFAULT True
|
||||||
# INPALCE: {bool} -- if True, perform operation in-place
|
# INPALCE: {bool} -- if True, perform operation in-place
|
||||||
# KIND: {quicksort, mergesort, heapsort} -- sorting algorithm
|
# KIND: {quicksort, mergesort, heapsort} -- sorting algorithm
|
||||||
# NA_POSITION {first, last} -- ‘first’ puts NaNs at the beginning, ‘last’ puts NaNs at the end
|
# NA_POSITION {first, last} -- 'first' puts NaNs at the beginning, 'last' puts NaNs at the end
|
||||||
```
|
```
|
||||||
|
|
||||||
## DESCRIPTIVE AND SUMMARY STATISTICS
|
## DESCRIPTIVE AND SUMMARY STATISTICS
|
||||||
|
@ -332,7 +332,7 @@ pd.DataFrame.count(self, numeric_only=False) # count non-NA cells for each colu
|
||||||
|
|
||||||
### DESCRIBE
|
### DESCRIBE
|
||||||
|
|
||||||
Generate descriptive statistics summarizing central tendency, dispersion and shape of dataset’s distribution (exclude NaN).
|
Generate descriptive statistics summarizing central tendency, dispersion and shape of dataset's distribution (exclude NaN).
|
||||||
|
|
||||||
```py
|
```py
|
||||||
pd.Series.describe(self, percentiles=None, include=None, exclude=None)
|
pd.Series.describe(self, percentiles=None, include=None, exclude=None)
|
||||||
|
@ -350,7 +350,7 @@ pd.Series.min(self, skipna=None, numeric_only=None) # minimum of the values for
|
||||||
pd.DataFrame.max(self, axis=None, skipna=None, numeric_only=None) # maximum of the values for the requested axis
|
pd.DataFrame.max(self, axis=None, skipna=None, numeric_only=None) # maximum of the values for the requested axis
|
||||||
pd.DataFrame.min(self, axis=None, skipna=None, numeric_only=None) # minimum of the values for the requested axis
|
pd.DataFrame.min(self, axis=None, skipna=None, numeric_only=None) # minimum of the values for the requested axis
|
||||||
# SKIPNA: {bool} -- exclude NA/null values when computing the result
|
# SKIPNA: {bool} -- exclude NA/null values when computing the result
|
||||||
# NUMERIC_ONLY: {bool} -- include only float, int, boolean columns, not immplemented for Series
|
# NUMERIC_ONLY: {bool} -- include only float, int, boolean columns, not implemented for Series
|
||||||
```
|
```
|
||||||
|
|
||||||
### IDXMAX - IDXMIN
|
### IDXMAX - IDXMIN
|
||||||
|
@ -381,7 +381,7 @@ pd.Series.sum(self, skipna=None, numeric_only=None, min_count=0) # sum of the v
|
||||||
pd.DataFrame.sum(self, axis=None, skipna=None, numeric_only=None, min_count=0) # sum of the values for the requested axis
|
pd.DataFrame.sum(self, axis=None, skipna=None, numeric_only=None, min_count=0) # sum of the values for the requested axis
|
||||||
# AXIS: {0, 1, index, columns} -- axis for the function to be applied on
|
# AXIS: {0, 1, index, columns} -- axis for the function to be applied on
|
||||||
# SKIPNA: {bool} -- exclude NA/null values when computing the result
|
# SKIPNA: {bool} -- exclude NA/null values when computing the result
|
||||||
# NUMERIC_ONLY: {bool} -- include only float, int, boolean columns, not immplemented for Series
|
# NUMERIC_ONLY: {bool} -- include only float, int, boolean columns, not implemented for Series
|
||||||
# MIN_COUNT: {int} -- required number of valid values to perform the operation. if fewer than min_count non-NA values are present the result will be NA
|
# MIN_COUNT: {int} -- required number of valid values to perform the operation. if fewer than min_count non-NA values are present the result will be NA
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -392,7 +392,7 @@ pd.Series.mean(self, skipna=None, numeric_only=None) # mean of the values
|
||||||
pd.DataFrame.mean(self, axis=None, skipna=None, numeric_only=None) # mean of the values for the requested axis
|
pd.DataFrame.mean(self, axis=None, skipna=None, numeric_only=None) # mean of the values for the requested axis
|
||||||
# AXIS: {0, 1, index, columns} -- axis for the function to be applied on
|
# AXIS: {0, 1, index, columns} -- axis for the function to be applied on
|
||||||
# SKIPNA: {bool} -- exclude NA/null values when computing the result
|
# SKIPNA: {bool} -- exclude NA/null values when computing the result
|
||||||
# NUMERIC_ONLY: {bool} -- include only float, int, boolean columns, not immplemented for Series
|
# NUMERIC_ONLY: {bool} -- include only float, int, boolean columns, not implemented for Series
|
||||||
```
|
```
|
||||||
|
|
||||||
### MEDIAN
|
### MEDIAN
|
||||||
|
@ -402,7 +402,7 @@ pd.Series.median(self, skipna=None, numeric_only=None) # median of the values
|
||||||
pd.DataFrame.median(self, axis=None, skipna=None, numeric_only=None) # median of the values for the requested axis
|
pd.DataFrame.median(self, axis=None, skipna=None, numeric_only=None) # median of the values for the requested axis
|
||||||
# AXIS: {0, 1, index, columns} -- axis for the function to be applied on
|
# AXIS: {0, 1, index, columns} -- axis for the function to be applied on
|
||||||
# SKIPNA: {bool} -- exclude NA/null values when computing the result
|
# SKIPNA: {bool} -- exclude NA/null values when computing the result
|
||||||
# NUMERIC_ONLY: {bool} -- include only float, int, boolean columns, not immplemented for Series
|
# NUMERIC_ONLY: {bool} -- include only float, int, boolean columns, not implemented for Series
|
||||||
```
|
```
|
||||||
|
|
||||||
### MAD (mean absolute deviation)
|
### MAD (mean absolute deviation)
|
||||||
|
@ -422,7 +422,7 @@ pd.DataFrame.var(self, axis=None, skipna=None, ddof=1, numeric_only=None) # un
|
||||||
# AXIS: {0, 1, index, columns} -- axis for the function to be applied on
|
# AXIS: {0, 1, index, columns} -- axis for the function to be applied on
|
||||||
# SKIPNA: {bool} -- exclude NA/null values. if an entire row/column is NA, the result will be NA
|
# SKIPNA: {bool} -- exclude NA/null values. if an entire row/column is NA, the result will be NA
|
||||||
# DDOF: {int} -- Delta Degrees of Freedom. divisor used in calculations is N - ddof (N represents the number of elements) -- DEFAULT 1
|
# DDOF: {int} -- Delta Degrees of Freedom. divisor used in calculations is N - ddof (N represents the number of elements) -- DEFAULT 1
|
||||||
# NUMERIC_ONLY: {bool} -- include only float, int, boolean columns, not immplemented for Series
|
# NUMERIC_ONLY: {bool} -- include only float, int, boolean columns, not implemented for Series
|
||||||
```
|
```
|
||||||
|
|
||||||
### STD (standard deviation)
|
### STD (standard deviation)
|
||||||
|
@ -433,7 +433,7 @@ pd.Dataframe.std(self, axis=None, skipna=None, ddof=1, numeric_only=None) # sam
|
||||||
# AXIS: {0, 1, index, columns} -- axis for the function to be applied on
|
# AXIS: {0, 1, index, columns} -- axis for the function to be applied on
|
||||||
# SKIPNA: {bool} -- exclude NA/null values. if an entire row/column is NA, the result will be NA
|
# SKIPNA: {bool} -- exclude NA/null values. if an entire row/column is NA, the result will be NA
|
||||||
# DDOF: {int} -- Delta Degrees of Freedom. divisor used in calculations is N - ddof (N represents the number of elements) -- DEFAULT 1
|
# DDOF: {int} -- Delta Degrees of Freedom. divisor used in calculations is N - ddof (N represents the number of elements) -- DEFAULT 1
|
||||||
# NUMERIC_ONLY: {bool} -- include only float, int, boolean columns, not immplemented for Series
|
# NUMERIC_ONLY: {bool} -- include only float, int, boolean columns, not implemented for Series
|
||||||
```
|
```
|
||||||
|
|
||||||
### SKEW
|
### SKEW
|
||||||
|
@ -443,19 +443,19 @@ pd.Series.skew(self, skipna=None, numeric_only=None) # unbiased skew Normalized
|
||||||
pd.DataFrame.skew(self, axis=None, skipna=None, numeric_only=None) # unbiased skew over requested axis Normalized by N-1
|
pd.DataFrame.skew(self, axis=None, skipna=None, numeric_only=None) # unbiased skew over requested axis Normalized by N-1
|
||||||
# AXIS: {0, 1, index, columns} -- axis for the function to be applied on
|
# AXIS: {0, 1, index, columns} -- axis for the function to be applied on
|
||||||
# SKIPNA: {bool} -- exclude NA/null values when computing the result
|
# SKIPNA: {bool} -- exclude NA/null values when computing the result
|
||||||
# NUMERIC_ONLY: {bool} -- include only float, int, boolean columns, not immplemented for Series
|
# NUMERIC_ONLY: {bool} -- include only float, int, boolean columns, not implemented for Series
|
||||||
```
|
```
|
||||||
|
|
||||||
### KURT
|
### KURT
|
||||||
|
|
||||||
Unbiased kurtosis over requested axis using Fisher’s definition of kurtosis (kurtosis of normal == 0.0). Normalized by N-1.
|
Unbiased kurtosis over requested axis using Fisher's definition of kurtosis (kurtosis of normal == 0.0). Normalized by N-1.
|
||||||
|
|
||||||
```py
|
```py
|
||||||
pd.Series.kurt(self, skipna=None, numeric_only=None)
|
pd.Series.kurt(self, skipna=None, numeric_only=None)
|
||||||
pd.Dataframe.kurt(self, axis=None, skipna=None, numeric_only=None)
|
pd.Dataframe.kurt(self, axis=None, skipna=None, numeric_only=None)
|
||||||
# AXIS: {0, 1, index, columns} -- axis for the function to be applied on
|
# AXIS: {0, 1, index, columns} -- axis for the function to be applied on
|
||||||
# SKIPNA: {bool} -- exclude NA/null values when computing the result
|
# SKIPNA: {bool} -- exclude NA/null values when computing the result
|
||||||
# NUMERIC_ONLY: {bool} -- include only float, int, boolean columns, not immplemented for Series
|
# NUMERIC_ONLY: {bool} -- include only float, int, boolean columns, not implemented for Series
|
||||||
```
|
```
|
||||||
|
|
||||||
### CUMSUM (cumulative sum)
|
### CUMSUM (cumulative sum)
|
||||||
|
@ -471,7 +471,7 @@ pd.Dataframe.cumsum(self, axis=None, skipna=True) # cumulative sum over request
|
||||||
|
|
||||||
```py
|
```py
|
||||||
pd.Series.cummax(self, skipna=True) # cumulative maximum
|
pd.Series.cummax(self, skipna=True) # cumulative maximum
|
||||||
pd.Series.cummin(self, skipna=True) # cumulative minimumm
|
pd.Series.cummin(self, skipna=True) # cumulative minimum
|
||||||
pd.Dataframe.cummax(self, axis=None, skipna=True) # cumulative maximum over requested axis
|
pd.Dataframe.cummax(self, axis=None, skipna=True) # cumulative maximum over requested axis
|
||||||
pd.Dataframe.cummin(self, axis=None, skipna=True) # cumulative minimum over requested axis
|
pd.Dataframe.cummin(self, axis=None, skipna=True) # cumulative minimum over requested axis
|
||||||
# AXIS: {0, 1, index, columns} -- axis for the function to be applied on
|
# AXIS: {0, 1, index, columns} -- axis for the function to be applied on
|
||||||
|
@ -499,7 +499,7 @@ pd.DataFrame.diff(self, periods=1, axis=0)
|
||||||
# AXIS: {0, 1, index, columns} -- Take difference over rows or columns
|
# AXIS: {0, 1, index, columns} -- Take difference over rows or columns
|
||||||
```
|
```
|
||||||
|
|
||||||
### PCT_CAHNGE
|
### PCT_CHANGE
|
||||||
|
|
||||||
Percentage change between the current and a prior element.
|
Percentage change between the current and a prior element.
|
||||||
|
|
||||||
|
@ -541,7 +541,7 @@ pd.DataFrame.fillna(self, value=None, method=None, axis=None, inplace=False, lim
|
||||||
|
|
||||||
## HIERARCHICAL INDEXING (MultiIndex)
|
## HIERARCHICAL INDEXING (MultiIndex)
|
||||||
|
|
||||||
Enables storing and manupulation of data with an arbitrary number of dimensions.
|
Enables storing and manipulation of data with an arbitrary number of dimensions.
|
||||||
In lower dimensional data structures like Series (1d) and DataFrame (2d).
|
In lower dimensional data structures like Series (1d) and DataFrame (2d).
|
||||||
|
|
||||||
### MULTIIINDEX CREATION
|
### MULTIIINDEX CREATION
|
||||||
|
@ -565,7 +565,7 @@ pd.MultiIndex.get_level_values(self, level)
|
||||||
|
|
||||||
### PARTIAL AND CROSS-SECTION SELECTION
|
### PARTIAL AND CROSS-SECTION SELECTION
|
||||||
|
|
||||||
Partial selection “drops” levels of the hierarchical index in the result in a completely analogous way to selecting a column in a regular DataFrame.
|
Partial selection "drops" levels of the hierarchical index in the result in a completely analogous way to selecting a column in a regular DataFrame.
|
||||||
|
|
||||||
```py
|
```py
|
||||||
pd.Series.xs(self, key, axis=0, level=None, drop_level=True) # cross-section from Series
|
pd.Series.xs(self, key, axis=0, level=None, drop_level=True) # cross-section from Series
|
||||||
|
@ -608,7 +608,7 @@ pd.MultiIndex.sortlevel(self, level=0, ascending=True, sort_remaining=True) # s
|
||||||
pd.read_fwf(filepath, colspecs='infer', widths=None, infer_nrows=100) # read a table of fixed-width formatted lines into DataFrame
|
pd.read_fwf(filepath, colspecs='infer', widths=None, infer_nrows=100) # read a table of fixed-width formatted lines into DataFrame
|
||||||
# FILEPATH: {str, path object} -- any valid string path is acceptable, could be a URL. Valid URLs: http, ftp, s3, and file
|
# FILEPATH: {str, path object} -- any valid string path is acceptable, could be a URL. Valid URLs: http, ftp, s3, and file
|
||||||
# COLSPECS: {list of tuple (int, int), 'infer'} -- list of tuples giving extents of fixed-width fields of each line as half-open intervals { [from, to) }
|
# COLSPECS: {list of tuple (int, int), 'infer'} -- list of tuples giving extents of fixed-width fields of each line as half-open intervals { [from, to) }
|
||||||
# WIDTHS: {list of int} -- list of field widths which can be used instead of ‘colspecs’ if intervals are contiguous
|
# WIDTHS: {list of int} -- list of field widths which can be used instead of "colspecs" if intervals are contiguous
|
||||||
# INFER_ROWS: {int} -- number of rows to consider when letting parser determine colspecs -- DEFAULT 100
|
# INFER_ROWS: {int} -- number of rows to consider when letting parser determine colspecs -- DEFAULT 100
|
||||||
|
|
||||||
pd.read_excel() # read an Excel file into a pandas DataFrame
|
pd.read_excel() # read an Excel file into a pandas DataFrame
|
||||||
|
@ -635,7 +635,7 @@ pd.DataFrame.to_csv(self, path_or_buf, sep=',', na_rep='', columns=None, header=
|
||||||
# COLUMNS: {sequence} -- colums to write
|
# COLUMNS: {sequence} -- colums to write
|
||||||
# HEADER: {bool, list of str} -- write out column names. if list of strings is given its assumed to be aliases for column names
|
# HEADER: {bool, list of str} -- write out column names. if list of strings is given its assumed to be aliases for column names
|
||||||
# INDEX: {bool, list of str} -- write out row names (index)
|
# INDEX: {bool, list of str} -- write out row names (index)
|
||||||
# ENCODING: {str} -- string representing encoding to use -- DEFAULT ‘utf-8’
|
# ENCODING: {str} -- string representing encoding to use -- DEFAULT "utf-8"
|
||||||
# LINE_TERMINATOR: {str} -- newline character or character sequence to use in the output file -- DEFAULT os.linesep
|
# LINE_TERMINATOR: {str} -- newline character or character sequence to use in the output file -- DEFAULT os.linesep
|
||||||
# DECIMAL: {str} -- character recognized as decimal separator (in EU ,)
|
# DECIMAL: {str} -- character recognized as decimal separator (in EU ,)
|
||||||
|
|
||||||
|
|
|
@ -17,18 +17,18 @@ sns.set(style='darkgrid')
|
||||||
|
|
||||||
```python
|
```python
|
||||||
sns.replot(x='name_in_data', y='name_in_data', hue='point_color', size='point_size', style='point_shape', data=data)
|
sns.replot(x='name_in_data', y='name_in_data', hue='point_color', size='point_size', style='point_shape', data=data)
|
||||||
# HUE, SIZE and STYLE: {name in data} -- used to differenciate points, a sort-of 3rd dimention
|
# HUE, SIZE and STYLE: {name in data} -- used to differentiate points, a sort-of 3rd dimension
|
||||||
# hue behaves differently if the data is categorical or numerical, numerical uses a color gradient
|
# hue behaves differently if the data is categorical or numerical, numerical uses a color gradient
|
||||||
# SORT: {False, True} -- avoid sorting data in function of x
|
# SORT: {False, True} -- avoid sorting data in function of x
|
||||||
# CI: {None, sd} -- avoid comuting confidence intervals or plot standard deviation
|
# CI: {None, sd} -- avoid computing confidence intervals or plot standard deviation
|
||||||
# (aggregate multiple measurements at each x value by plotting the mean and the 95% confidence interval around the mean)
|
# (aggregate multiple measurements at each x value by plotting the mean and the 95% confidence interval around the mean)
|
||||||
# ESTIMATOR: {None} -- turn off aggregation of multiple observations
|
# ESTIMATOR: {None} -- turn off aggregation of multiple observations
|
||||||
# MARKERS: {True, False} -- evidetiate observations with dots
|
# MARKERS: {True, False} -- evidenziate observations with dots
|
||||||
# DASHES: {True, False} -- evidetiate observations with dashes
|
# DASHES: {True, False} -- evidenziate observations with dashes
|
||||||
# COL, ROW: {name in data} -- categorical variables that will determine the grid of plots
|
# COL, ROW: {name in data} -- categorical variables that will determine the grid of plots
|
||||||
# COL_WRAP: {int} -- “Wrap” the column variable at this width, so that the column facets span multiple rows. Incompatible with a row facet.
|
# COL_WRAP: {int} -- "Wrap" the column variable at this width, so that the column facets span multiple rows. Incompatible with a row facet.
|
||||||
# SCATTERPLOT
|
# SCATTERPLOT
|
||||||
# depicts the joint distibution of two variables usinga a cloud of points
|
# depicts the joint distribution of two variables using a cloud of points
|
||||||
# kind can be omitted since scatterplot is the default for replot
|
# kind can be omitted since scatterplot is the default for replot
|
||||||
sns.replot(kind='scatter') # calls scatterplot()
|
sns.replot(kind='scatter') # calls scatterplot()
|
||||||
sns.scatterplot() # underlying axis-level function of replot()
|
sns.scatterplot() # underlying axis-level function of replot()
|
||||||
|
@ -45,16 +45,16 @@ sns.lineplot() # underlying axis-level function of replot()
|
||||||
|
|
||||||
## CATPLOT (categorical)
|
## CATPLOT (categorical)
|
||||||
|
|
||||||
Categorical: dicided into discrete groups.
|
Categorical: divided into discrete groups.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
sns.catplot(x='name_in_data', y='name_in_data', data=data)
|
sns.catplot(x='name_in_data', y='name_in_data', data=data)
|
||||||
# HUE: {name in data} -- used to differenciate points, a sort-of 3rd dimention
|
# HUE: {name in data} -- used to differenziate points, a sort-of 3rd dimension
|
||||||
# COL, ROW: {name in data} -- categorical variables that will determine the grid of plots
|
# COL, ROW: {name in data} -- categorical variables that will determine the grid of plots
|
||||||
# COL_WRAP: {int} -- “Wrap” the column variable at this width, so that the column facets span multiple rows. Incompatible with a row facet.
|
# COL_WRAP: {int} -- "Wrap" the column variable at this width, so that the column facets span multiple rows. Incompatible with a row facet.
|
||||||
# ORDER, HUE_ORDER: {list of strings} -- oreder of categorical levels of the plot
|
# ORDER, HUE_ORDER: {list of strings} -- order of categorical levels of the plot
|
||||||
# ROW_ORDER, COL_ORDER: {list of strings} -- order to organize the rows and/or columns of the grid in
|
# ROW_ORDER, COL_ORDER: {list of strings} -- order to organize the rows and/or columns of the grid in
|
||||||
# ORIENT: {'v', 'h'} -- Orientation of the plot (can also swap x&y assignement)
|
# ORIENT: {'v', 'h'} -- Orientation of the plot (can also swap x&y assignment)
|
||||||
# COLOR: {matplotlib color} -- Color for all of the elements, or seed for a gradient palette
|
# COLOR: {matplotlib color} -- Color for all of the elements, or seed for a gradient palette
|
||||||
# CATEGORICAL SCATTERPLOT - STRIPPLOT
|
# CATEGORICAL SCATTERPLOT - STRIPPLOT
|
||||||
# adjust the positions of points on the categorical axis with a small amount of random “jitter”
|
# adjust the positions of points on the categorical axis with a small amount of random “jitter”
|
||||||
|
@ -85,7 +85,7 @@ sns.boxplot()
|
||||||
Combines a boxplot with the kernel density estimation procedure.
|
Combines a boxplot with the kernel density estimation procedure.
|
||||||
|
|
||||||
```py
|
```py
|
||||||
sns.catplot(kind='violon')
|
sns.catplot(kind='violin')
|
||||||
sns.violonplot()
|
sns.violonplot()
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -113,7 +113,7 @@ sns.pointplot()
|
||||||
# JOIN: {bool} -- if True, lines will be drawn between point estimates at the same hue level
|
# JOIN: {bool} -- if True, lines will be drawn between point estimates at the same hue level
|
||||||
# SCALE: {float} -- scale factor for the plot elements
|
# SCALE: {float} -- scale factor for the plot elements
|
||||||
# ERRWIDTH: {float} -- thickness of error bar lines (and caps)
|
# ERRWIDTH: {float} -- thickness of error bar lines (and caps)
|
||||||
# CAPSIZE: {float} -- width of the “caps” on error bars
|
# CAPSIZE: {float} -- width of the "caps" on error bars
|
||||||
```
|
```
|
||||||
|
|
||||||
### CATEGORICAL ESTIMATE - BARPLOT
|
### CATEGORICAL ESTIMATE - BARPLOT
|
||||||
|
@ -126,7 +126,7 @@ sns.barplot()
|
||||||
# CI: {float, sd} -- size of confidence intervals to draw around estimated values, sd -> standard deviation
|
# CI: {float, sd} -- size of confidence intervals to draw around estimated values, sd -> standard deviation
|
||||||
# ERRCOLOR: {matplotlib color} -- color for the lines that represent the confidence interval
|
# ERRCOLOR: {matplotlib color} -- color for the lines that represent the confidence interval
|
||||||
# ERRWIDTH: {float} -- thickness of error bar lines (and caps)
|
# ERRWIDTH: {float} -- thickness of error bar lines (and caps)
|
||||||
# CAPSIZE: {float} -- width of the “caps” on error bars
|
# CAPSIZE: {float} -- width of the "caps" on error bars
|
||||||
# DODGE: {bool} -- whether elements should be shifted along the categorical axis if hue is used
|
# DODGE: {bool} -- whether elements should be shifted along the categorical axis if hue is used
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -173,7 +173,7 @@ sns.rugplot(a=data) # -> axes obj with plot on it
|
||||||
Fit and plot a univariate or bivariate kernel density estimate.
|
Fit and plot a univariate or bivariate kernel density estimate.
|
||||||
|
|
||||||
```py
|
```py
|
||||||
# DATA: {1D array-like} -- inpoy data
|
# DATA: {1D array-like} -- input data
|
||||||
sns.kdeplot(data=data)
|
sns.kdeplot(data=data)
|
||||||
# DATA2 {1D array-like} -- second input data. if present, a bivariate KDE will be estimated.
|
# DATA2 {1D array-like} -- second input data. if present, a bivariate KDE will be estimated.
|
||||||
# SHADE: {bool} -- if True, shade-in the area under KDE curve (or draw with filled contours is bivariate)
|
# SHADE: {bool} -- if True, shade-in the area under KDE curve (or draw with filled contours is bivariate)
|
||||||
|
|
|
@ -8,7 +8,7 @@ from bs4 import BeautifulSoup
|
||||||
import requests
|
import requests
|
||||||
import lxml # better html parser than built-in
|
import lxml # better html parser than built-in
|
||||||
|
|
||||||
response = requests.get("url") # retuire a web page
|
response = requests.get("url") # retrieve a web page
|
||||||
|
|
||||||
soup = BeautifulSoup(response.text, "html.parser") # parse HTML from response w/ python default HTML parser
|
soup = BeautifulSoup(response.text, "html.parser") # parse HTML from response w/ python default HTML parser
|
||||||
soup = BeautifulSoup(response.text, "lxml") # parse HTML from response w/ lxml parser
|
soup = BeautifulSoup(response.text, "lxml") # parse HTML from response w/ lxml parser
|
||||||
|
@ -32,7 +32,7 @@ type(tag) # <class 'bs4.element.Tag'>
|
||||||
print(tag) # <b class="boldest">Extremely bold</b>
|
print(tag) # <b class="boldest">Extremely bold</b>
|
||||||
|
|
||||||
tag.name # tag name
|
tag.name # tag name
|
||||||
tag["attribute"] # access to ttag attribute values
|
tag["attribute"] # access to tag attribute values
|
||||||
tag.attrs # dict of attribue-value pairs
|
tag.attrs # dict of attribue-value pairs
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -48,21 +48,21 @@ A string corresponds to a bit of text within a tag. Beautiful Soup uses the `Nav
|
||||||
soup.<tag>.<child_tag> # navigate using tag names
|
soup.<tag>.<child_tag> # navigate using tag names
|
||||||
|
|
||||||
<tag>.contents # direct children as a list
|
<tag>.contents # direct children as a list
|
||||||
<tag>.children # direct children as a genrator for iteration
|
<tag>.children # direct children as a generator for iteration
|
||||||
<tag>.descendats # iterator over all childered, recusive
|
<tag>.descendants # iterator over all children, recursive
|
||||||
|
|
||||||
<tag>.string # tag contents, does not have further children
|
<tag>.string # tag contents, does not have further children
|
||||||
# If a tag’s only child is another tag, and that tag has a .string, then the parenttag is considered to have the same .string as its child
|
# If a tag's only child is another tag, and that tag has a .string, then the parent tag is considered to have the same .string as its child
|
||||||
# If a tag contains more than one thing, then it’s not clear what .string should refer to, so .string is defined to be None
|
# If a tag contains more than one thing, then it's not clear what .string should refer to, so .string is defined to be None
|
||||||
|
|
||||||
<tag>.strings # generattor to iterate over all children's strings (will list white space)
|
<tag>.strings # generator to iterate over all children's strings (will list white space)
|
||||||
<tag>.stripped_strings # generattor to iterate over all children's strings (will NOT list white space)
|
<tag>.stripped_strings # generator to iterate over all children's strings (will NOT list white space)
|
||||||
```
|
```
|
||||||
|
|
||||||
### Going Up
|
### Going Up
|
||||||
|
|
||||||
```py
|
```py
|
||||||
<tag>.parent # tags direct parent (BeautifleSoup has parent None, html has parent BeautifulSoup)
|
<tag>.parent # tags direct parent (BeautifulSoup has parent None, html has parent BeautifulSoup)
|
||||||
<tag>.parents # iterable over all parents
|
<tag>.parents # iterable over all parents
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -94,7 +94,7 @@ soup.<tag>.<child_tag> # navigate using tag names
|
||||||
soup.find_all("tag") # by name
|
soup.find_all("tag") # by name
|
||||||
soup.find_all(["tag1", "tag2"]) # multiple tags in a list
|
soup.find_all(["tag1", "tag2"]) # multiple tags in a list
|
||||||
soup.find_all(function) # based on a bool function
|
soup.find_all(function) # based on a bool function
|
||||||
sopu.find_all(True) # Match everyting
|
soup.find_all(True) # Match everything
|
||||||
```
|
```
|
||||||
|
|
||||||
## Methods
|
## Methods
|
||||||
|
@ -102,10 +102,10 @@ sopu.find_all(True) # Match everyting
|
||||||
Methods arguments:
|
Methods arguments:
|
||||||
|
|
||||||
- `name` (string): tag to search for
|
- `name` (string): tag to search for
|
||||||
- `attrs` (dict): attributte-value pai to search for
|
- `attrs` (dict): attribute-value pai to search for
|
||||||
- `string` (string): search by string contents rather than by tag
|
- `string` (string): search by string contents rather than by tag
|
||||||
- `limit` (int). limit number of results
|
- `limit` (int). limit number of results
|
||||||
- `**kwargs`: be turned into a filter on one of a tag’s attributes.
|
- `**kwargs`: be turned into a filter on one of a tag's attributes.
|
||||||
|
|
||||||
```py
|
```py
|
||||||
find_all(name, attrs, recursive, string, limit, **kwargs) # several results
|
find_all(name, attrs, recursive, string, limit, **kwargs) # several results
|
||||||
|
@ -140,7 +140,7 @@ soup.select("css_selector") # search for CSS selectors of HTML tags
|
||||||
<tag>["attribute"] = "value" # modify the attribute value
|
<tag>["attribute"] = "value" # modify the attribute value
|
||||||
del <tag>["attribute"] # remove the attribute
|
del <tag>["attribute"] # remove the attribute
|
||||||
|
|
||||||
soup.new_tag("name", <attribute> = "value") # creat a new tag with specified name and attributes
|
soup.new_tag("name", <attribute> = "value") # create a new tag with specified name and attributes
|
||||||
|
|
||||||
<tag>.string = "new content" # modify tag text content
|
<tag>.string = "new content" # modify tag text content
|
||||||
<tag>.append(item) # append to Tag content
|
<tag>.append(item) # append to Tag content
|
||||||
|
@ -161,7 +161,7 @@ soup.new_tag("name", <attribute> = "value") # creat a new tag with specified na
|
||||||
<tag>.replace_with(item) # remove a tag or string from the tree, and replaces it with the tag or string of choice
|
<tag>.replace_with(item) # remove a tag or string from the tree, and replaces it with the tag or string of choice
|
||||||
|
|
||||||
<tag>.wrap(other_tag) # wrap an element in the tag you specify, return the new wrapper
|
<tag>.wrap(other_tag) # wrap an element in the tag you specify, return the new wrapper
|
||||||
<tag>.unwrap() # replace a tag with whatever’s inside, good for stripping out markup
|
<tag>.unwrap() # replace a tag with whatever's inside, good for stripping out markup
|
||||||
|
|
||||||
<tag>.smooth() # clean up the parse tree by consolidating adjacent strings
|
<tag>.smooth() # clean up the parse tree by consolidating adjacent strings
|
||||||
```
|
```
|
||||||
|
|
|
@ -34,14 +34,14 @@ Converter Type | Accepts
|
||||||
`uuid` | UUID strings
|
`uuid` | UUID strings
|
||||||
|
|
||||||
```python
|
```python
|
||||||
@app.route("/user/<string:username>") # hanle URL at runtime
|
@app.route("/user/<string:username>") # handle URL at runtime
|
||||||
def profile(username):
|
def profile(username):
|
||||||
return f"{escape(username)}'s profile'"
|
return f"{escape(username)}'s profile'"
|
||||||
```
|
```
|
||||||
|
|
||||||
## Redirection
|
## Redirection
|
||||||
|
|
||||||
`url_for(endpoint, **values)` is used to redirect passing keyeworderd arguments. It can be used in combination with `@app.route("/<value>")` to accept the paassed arguments.
|
`url_for(endpoint, **values)` is used to redirect passing keyworded arguments. It can be used in combination with `@app.route("/<value>")` to accept the passed arguments.
|
||||||
|
|
||||||
```py
|
```py
|
||||||
from flask import Flask, redirect, url_for
|
from flask import Flask, redirect, url_for
|
||||||
|
@ -137,7 +137,7 @@ In `parent_template.html`:
|
||||||
|
|
||||||
The content of the block will be filled by the child class.
|
The content of the block will be filled by the child class.
|
||||||
|
|
||||||
In `child_template.hmtl`:
|
In `child_template.html`:
|
||||||
|
|
||||||
```html
|
```html
|
||||||
{% extends "parent_template.html" %}
|
{% extends "parent_template.html" %}
|
||||||
|
|
|
@ -27,7 +27,7 @@ In `login.html`:
|
||||||
|
|
||||||
```html
|
```html
|
||||||
<html>
|
<html>
|
||||||
<!-- action="#" goes to page itsef but with # at the end of the URL -->
|
<!-- action="#" goes to page itself but with # at the end of the URL -->
|
||||||
<form action="#" method="post">
|
<form action="#" method="post">
|
||||||
<input type="text" name="field name">
|
<input type="text" name="field name">
|
||||||
</html>
|
</html>
|
||||||
|
|
|
@ -21,7 +21,7 @@ The response message consists of:
|
||||||
```text
|
```text
|
||||||
1xx -> INFORMATIONAL RESPONSE
|
1xx -> INFORMATIONAL RESPONSE
|
||||||
2xx -> SUCCESS
|
2xx -> SUCCESS
|
||||||
200 OK -> request succesful
|
200 OK -> request successful
|
||||||
3xx -> REDIRECTION
|
3xx -> REDIRECTION
|
||||||
4xx -> CLIENT ERRORS
|
4xx -> CLIENT ERRORS
|
||||||
404 NOT FOUND -> resource not found
|
404 NOT FOUND -> resource not found
|
||||||
|
@ -85,7 +85,7 @@ requests.post('URL', json={'key': 'value'})
|
||||||
### INSPECTING THE REQUEST
|
### INSPECTING THE REQUEST
|
||||||
|
|
||||||
```py
|
```py
|
||||||
# requests lib prepares the requests nefore sending it
|
# requests lib prepares the requests before sending it
|
||||||
response = requests.post('URL', data={'key':'value'})
|
response = requests.post('URL', data={'key':'value'})
|
||||||
response.request.something # inspect request field
|
response.request.something # inspect request field
|
||||||
```
|
```
|
||||||
|
@ -93,7 +93,7 @@ response.request.something # inspect request field
|
||||||
## AUTHENTICATION
|
## AUTHENTICATION
|
||||||
|
|
||||||
```py
|
```py
|
||||||
requests.get('URL', auth=('uesrname', 'password')) # use implicit HTTP Basic Authorization
|
requests.get('URL', auth=('username', 'password')) # use implicit HTTP Basic Authorization
|
||||||
|
|
||||||
# explicit HTTP Basic Authorization and other
|
# explicit HTTP Basic Authorization and other
|
||||||
from requests.auth import HTTPBasicAuth, HTTPDigestAuth, HTTPProxyAuth
|
from requests.auth import HTTPBasicAuth, HTTPDigestAuth, HTTPProxyAuth
|
||||||
|
@ -101,7 +101,7 @@ from getpass import getpass
|
||||||
requests.get('URL', auth=HTTPBasicAuth('username', getpass()))
|
requests.get('URL', auth=HTTPBasicAuth('username', getpass()))
|
||||||
```
|
```
|
||||||
|
|
||||||
### PERSOANLIZED AUTH
|
### PERSONALIZED AUTH
|
||||||
|
|
||||||
```py
|
```py
|
||||||
from requests.auth import AuthBase
|
from requests.auth import AuthBase
|
||||||
|
|
194
Python/Python.md
194
Python/Python.md
|
@ -21,12 +21,12 @@ dir(object) # return an alphabetized list of names comprising (some of) the att
|
||||||
|
|
||||||
import sys # importa modulo
|
import sys # importa modulo
|
||||||
from sys import argv # importa singolo elemento da un modulo
|
from sys import argv # importa singolo elemento da un modulo
|
||||||
from sys import * # importa tutti gli elementi di un modulo (non cecessaria sintassi modulo.metodo)
|
from sys import * # importa tutti gli elementi di un modulo (non necessaria sintassi modulo.metodo)
|
||||||
import sys as alias # importa il modulo con un alias, utilizzo alias.metodo
|
import sys as alias # importa il modulo con un alias, utilizzo alias.metodo
|
||||||
|
|
||||||
# SET CARATTERI
|
# SET CARATTERI
|
||||||
import string
|
import string
|
||||||
string.ascii_lowecase = 'abcdefghijklmnopqrstuvwxyz'
|
string.ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
|
||||||
string.asci_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
string.asci_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
||||||
string.asci_letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
string.asci_letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
||||||
string.digits = '0123456789'
|
string.digits = '0123456789'
|
||||||
|
@ -43,14 +43,14 @@ string.whitespace
|
||||||
|
|
||||||
```py
|
```py
|
||||||
"""istruzioni a dx di = eseguite prima di istruzioni a sx di ="""
|
"""istruzioni a dx di = eseguite prima di istruzioni a sx di ="""
|
||||||
variabile = espressione # il tipo della variabile viene deciso dianmicamente da python in base al contenuto
|
variabile = espressione # il tipo della variabile viene deciso dinamicamente da python in base al contenuto
|
||||||
var_1, var_2 = valore1, valore2 # assegnamento parallelo
|
var_1, var_2 = valore1, valore2 # assegnamento parallelo
|
||||||
var_1, var_2 = var_2, var_1 # swap valori
|
var_1, var_2 = var_2, var_1 # swap valori
|
||||||
|
|
||||||
# conditional assignement
|
# conditional assignment
|
||||||
x = a if condition else b
|
x = a if condition else b
|
||||||
x = a or b # If bool(a) returns False, then x is assigned the value of b
|
x = a or b # If bool(a) returns False, then x is assigned the value of b
|
||||||
# a series of OR expressions has the effect of returning the first item that evaluates True, or the last item (last item sould be a literal).
|
# a series of OR expressions has the effect of returning the first item that evaluates True, or the last item (last item should be a literal).
|
||||||
```
|
```
|
||||||
|
|
||||||
### Conversione Tipo Variabile
|
### Conversione Tipo Variabile
|
||||||
|
@ -60,7 +60,7 @@ x = a or b # If bool(a) returns False, then x is assigned the value of b
|
||||||
### Assegnamento Espressioni
|
### Assegnamento Espressioni
|
||||||
|
|
||||||
```py
|
```py
|
||||||
(var := expressione) # assegna ad una variabile un espressione per evitare di ripetere l'espressione
|
(var := expression) # assegna ad una variabile un espressione per evitare di ripetere l'espressione
|
||||||
```
|
```
|
||||||
|
|
||||||
### Confronto Variabili (`==` vs `is`)
|
### Confronto Variabili (`==` vs `is`)
|
||||||
|
@ -88,19 +88,19 @@ print(f'{name=}, {marks=}') # OUTPUT: name=Alex, marks=94.5
|
||||||
# USO DEI PLACEHOLDER
|
# USO DEI PLACEHOLDER
|
||||||
print('Name is %s, Marks are %3.2f' % (name, marks)) # metodo ereditato da C. La variabile viene sostituita al posto di %..
|
print('Name is %s, Marks are %3.2f' % (name, marks)) # metodo ereditato da C. La variabile viene sostituita al posto di %..
|
||||||
print("Name is {}, Marks are {}".format(name, marks))
|
print("Name is {}, Marks are {}".format(name, marks))
|
||||||
print("Name is {1}, Marks are {2}".format(marks, name)) # indici in parentesi odrinano elementi in .format
|
print("Name is {1}, Marks are {2}".format(marks, name)) # indici in parentesi ordinano elementi in .format
|
||||||
print("Name is {n}, Marks are {m}".format(m = '94.5', n = 'Alex')) # indici in parentesi odrinano elementi in .format
|
print("Name is {n}, Marks are {m}".format(m = '94.5', n = 'Alex')) # indici in parentesi ordinano elementi in .format
|
||||||
print(f'Name is {name}, Marks are {marks}') # formattazione con f-strings
|
print(f'Name is {name}, Marks are {marks}') # formattazione con f-strings
|
||||||
```
|
```
|
||||||
|
|
||||||
### Format Specification Mini-Language
|
### Format Specification Mini-Language
|
||||||
|
|
||||||
`{value:width.precision symbol}`
|
`{value:width.precision symbol}`
|
||||||
`width.precision` => numeroCifreTottali.numeroCifreDecimali
|
`width.precision` => numeroCifreTotali.numeroCifreDecimali
|
||||||
|
|
||||||
Format: `[[fill]align] [sign] [#] [width] [grouping] [.precidion] [type]`
|
Format: `[[fill]align] [sign] [#] [width] [grouping] [.precision] [type]`
|
||||||
|
|
||||||
OVVERRIDE __format__()
|
OVERRIDE __format__()
|
||||||
{!a} | chiama ascii() sulla variabile
|
{!a} | chiama ascii() sulla variabile
|
||||||
{!r} | chiama repr() sulla variabile
|
{!r} | chiama repr() sulla variabile
|
||||||
{!s} | chiama str() sulla variabile
|
{!s} | chiama str() sulla variabile
|
||||||
|
@ -108,10 +108,10 @@ OVVERRIDE __format__()
|
||||||
RIEMPIMENTO [fill]
|
RIEMPIMENTO [fill]
|
||||||
{<qualsiasi_carattere>}
|
{<qualsiasi_carattere>}
|
||||||
|
|
||||||
| `[align]` | Allinemanto |
|
| `[align]` | Allineamento |
|
||||||
| --------- | ---------------------- |
|
| --------- | ---------------------- |
|
||||||
| `:<` | allinemaneto sininstra |
|
| `:<` | allineamento sinistra |
|
||||||
| `:>` | allinemento destra |
|
| `:>` | allineamento destra |
|
||||||
| `:=` | padding dopo il segno |
|
| `:=` | padding dopo il segno |
|
||||||
| `:^` | centrato |
|
| `:^` | centrato |
|
||||||
|
|
||||||
|
@ -139,14 +139,14 @@ RIEMPIMENTO [fill]
|
||||||
| `:e` | output è notazione esponenziale (precisione base 6 cifre) |
|
| `:e` | output è notazione esponenziale (precisione base 6 cifre) |
|
||||||
| `:E` | output è notazione esponenziale (precisione base 6 cifre) separatore maiuscolo |
|
| `:E` | output è notazione esponenziale (precisione base 6 cifre) separatore maiuscolo |
|
||||||
| `:f` | output è float (precisione base 6 cifre) |
|
| `:f` | output è float (precisione base 6 cifre) |
|
||||||
| `:%` | output è percentuale (moltiplica * 100, diplay come :f) |
|
| `:%` | output è percentuale (moltiplica * 100, display come :f) |
|
||||||
|
|
||||||
### Input Da Tastiera
|
### Input Da Tastiera
|
||||||
|
|
||||||
```py
|
```py
|
||||||
# input ritorna sempre una STRINGA
|
# input ritorna sempre una STRINGA
|
||||||
s = input() # richiesta input senza messaggio
|
s = input() # richiesta input senza messaggio
|
||||||
s = input('Prompt') # richiesta imput
|
s = input('Prompt') # richiesta input
|
||||||
i = int(input('prompt')) # richiesta input con conversione di tipo
|
i = int(input('prompt')) # richiesta input con conversione di tipo
|
||||||
|
|
||||||
# INPUT MULTIPLI
|
# INPUT MULTIPLI
|
||||||
|
@ -158,7 +158,7 @@ lista = [int(x) for x in input('prompt').split('separatore')]
|
||||||
|
|
||||||
```py
|
```py
|
||||||
a = 77
|
a = 77
|
||||||
b = 1_000_000 # underscore può essere usato per seoarare gruppi di cifre
|
b = 1_000_000 # underscore può essere usato per separare gruppi di cifre
|
||||||
c = -69
|
c = -69
|
||||||
|
|
||||||
# float numbers
|
# float numbers
|
||||||
|
@ -184,7 +184,7 @@ bin(3616544)
|
||||||
hex(589)
|
hex(589)
|
||||||
oct(265846)
|
oct(265846)
|
||||||
|
|
||||||
# COVERSIONE UNICODE
|
# CONVERSIONE UNICODE
|
||||||
ord(c) # Given a string representing one Unicode character, return an integer representing the Unicode code point of that character
|
ord(c) # Given a string representing one Unicode character, return an integer representing the Unicode code point of that character
|
||||||
chr(i) # Return the string representing a character whose Unicode code point is the integer i
|
chr(i) # Return the string representing a character whose Unicode code point is the integer i
|
||||||
|
|
||||||
|
@ -196,21 +196,21 @@ round(num, precisione) # arrotonda il numero alla data precisione, non converte
|
||||||
|
|
||||||
### Confronto Numeri Decimali
|
### Confronto Numeri Decimali
|
||||||
|
|
||||||
Non usare `==` o `!=` per confrontare numeri in virgola mobile. Essi sono approssiamazioni o hanno parecchie cifre.
|
Non usare `==` o `!=` per confrontare numeri in virgola mobile. Essi sono approssimazioni o hanno parecchie cifre.
|
||||||
Conviene verificare se la differenza tra i numeri è sufficientemente piccola.
|
Conviene verificare se la differenza tra i numeri è sufficientemente piccola.
|
||||||
|
|
||||||
## Stringhe
|
## Stringhe
|
||||||
|
|
||||||
```py
|
```py
|
||||||
|
|
||||||
stringa = 'contenuto stringa' # asegnazione e creazione variabile stringa
|
stringa = 'contenuto stringa' # assegnazione e creazione variabile stringa
|
||||||
stringa = '''multi
|
stringa = '''multi
|
||||||
line
|
line
|
||||||
string'''
|
string'''
|
||||||
|
|
||||||
stringa3 = stringa1 + stringa2 # concatenazione stringhe (polimorfismo operatore +)
|
stringa3 = stringa1 + stringa2 # concatenazione stringhe (polimorfismo operatore +)
|
||||||
|
|
||||||
# INDEXING (selezione di un carattere nella srtinga)
|
# INDEXING (selezione di un carattere nella stringa)
|
||||||
stringa[0]
|
stringa[0]
|
||||||
stringa[2]
|
stringa[2]
|
||||||
stringa[-3] # selezione partendo dal fondo (indice negativo)
|
stringa[-3] # selezione partendo dal fondo (indice negativo)
|
||||||
|
@ -220,7 +220,7 @@ print(stringa * n)
|
||||||
|
|
||||||
len(stringa) # mostra la lunghezza di una stringa
|
len(stringa) # mostra la lunghezza di una stringa
|
||||||
|
|
||||||
# SLICING (estrazione di sottostringhe, non include la posizione dell'ultimo indice)
|
# SLICING (estrazione di sotto-stringhe, non include la posizione dell'ultimo indice)
|
||||||
stringa[0:5]
|
stringa[0:5]
|
||||||
stringa[:6]
|
stringa[:6]
|
||||||
stringa[-3:-1]
|
stringa[-3:-1]
|
||||||
|
@ -257,7 +257,7 @@ stringa.capitalize()
|
||||||
# SEPARAZIONE IN ELEMENTI LISTA
|
# SEPARAZIONE IN ELEMENTI LISTA
|
||||||
stringa.split()
|
stringa.split()
|
||||||
stringa.split('separatore') # separa usando il separatore (separatore omesso nella lista)
|
stringa.split('separatore') # separa usando il separatore (separatore omesso nella lista)
|
||||||
stringa.partition('char') # -> tuple # sepra la stringa i 3 parti alla prima occorrenza di separatore
|
stringa.partition('char') # -> tuple # separa la stringa i 3 parti alla prima occorrenza di separatore
|
||||||
|
|
||||||
# METODI IS_CHECK --> bool
|
# METODI IS_CHECK --> bool
|
||||||
stringa.isalnum()
|
stringa.isalnum()
|
||||||
|
@ -284,18 +284,18 @@ lista = [9, 11, 'WTC', -5.6, True] # le liste possono contenere dati di tipo div
|
||||||
lista[3] # indexing
|
lista[3] # indexing
|
||||||
lista[3:5] # slicing
|
lista[3:5] # slicing
|
||||||
lista * 3 # repetition
|
lista * 3 # repetition
|
||||||
len(lista) # lenght
|
len(lista) # length
|
||||||
lista3 = lista1 + lista2 # concatenazione liste (polimorfismo operatore +)
|
lista3 = lista1 + lista2 # concatenazione liste (polimorfismo operatore +)
|
||||||
lista[indice] = valore # modifica elemento lista
|
lista[indice] = valore # modifica elemento lista
|
||||||
del(lista[1]) # rimozione per indice (INBUILT IN PYTHON)
|
del(lista[1]) # rimozione per indice (INBUILT IN PYTHON)
|
||||||
# modifica la lista tra gli indici start e stop riasegnando gli elementi dell'iterabile
|
# modifica la lista tra gli indici start e stop riassegnando gli elementi dell'iterabile
|
||||||
lista[start:stop] = iterabile
|
lista[start:stop] = iterabile
|
||||||
|
|
||||||
# METODI LISTE
|
# METODI LISTE
|
||||||
lista.append(oggetto) # aggiunge oggetto al fondo
|
lista.append(oggetto) # aggiunge oggetto al fondo
|
||||||
lista.count(item) # conta il numero di occorrenze di item
|
lista.count(item) # conta il numero di occorrenze di item
|
||||||
lista.extend(sequenza) # aggiunge gli elementi di sequenza alla lista
|
lista.extend(sequenza) # aggiunge gli elementi di sequenza alla lista
|
||||||
lista.insert(posizione, oggetto) # inserise oggetto in lista[posizione]
|
lista.insert(posizione, oggetto) # inserisce oggetto in lista[posizione]
|
||||||
lista.index(item) # restituisce l'indice di item
|
lista.index(item) # restituisce l'indice di item
|
||||||
lista.remove(item) # rimuove item
|
lista.remove(item) # rimuove item
|
||||||
lista.pop(item) # elimina item e lo restituisce
|
lista.pop(item) # elimina item e lo restituisce
|
||||||
|
@ -354,7 +354,7 @@ var = [(exp_1, exp_2) for item_1 in seq_1 for item_2 in seq_2] # --> [(..., ...
|
||||||
```py
|
```py
|
||||||
# LE TUPLE NON POSSONO ESSERE MODIFICATE
|
# LE TUPLE NON POSSONO ESSERE MODIFICATE
|
||||||
tuple = (69, 420, 69, 'abc') # assegnazione tuple
|
tuple = (69, 420, 69, 'abc') # assegnazione tuple
|
||||||
tuple = (44, ) # tuple di signolo elemento necessitano di una virgola
|
tuple = (44, ) # tuple di singolo elemento necessitano di una virgola
|
||||||
|
|
||||||
tuple[3] # indexing
|
tuple[3] # indexing
|
||||||
tuple * 3 # repetition
|
tuple * 3 # repetition
|
||||||
|
@ -376,7 +376,7 @@ var_1, (var_2, var_3) = tup
|
||||||
|
|
||||||
#OPERATORE *VAR (tuple unpacking)
|
#OPERATORE *VAR (tuple unpacking)
|
||||||
var_1, var_2, *rest = sequenza # var_1 = seq[0], var_2 = seq[1], rest = seq[2:]
|
var_1, var_2, *rest = sequenza # var_1 = seq[0], var_2 = seq[1], rest = seq[2:]
|
||||||
var_1, *body, var_2, var_3 = sequeza # var_1 = seq[0], body = seq[1:-2], var_2 = sequenza[-2], var_3 = seq[-1]
|
var_1, *body, var_2, var_3 = sequenza # var_1 = seq[0], body = seq[1:-2], var_2 = sequenza[-2], var_3 = seq[-1]
|
||||||
# *var recupera gli item in eccesso, se in assegnamento parallelo usabile max una volta ma in posizione qualsiasi
|
# *var recupera gli item in eccesso, se in assegnamento parallelo usabile max una volta ma in posizione qualsiasi
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -411,14 +411,14 @@ set.remove(item) # rimuove item dal set se presente, altrimenti solleva KeyErro
|
||||||
set.discard(item) #rimuove item dal set se presente, altrimenti fa nulla
|
set.discard(item) #rimuove item dal set se presente, altrimenti fa nulla
|
||||||
set.difference(*sets) # -> set # restituisce elementi in set che sono assenti in *sets
|
set.difference(*sets) # -> set # restituisce elementi in set che sono assenti in *sets
|
||||||
set.difference_update(*sets) # rimuove le differenze dal set_2
|
set.difference_update(*sets) # rimuove le differenze dal set_2
|
||||||
set.union(*sets) # -> set # restituisce tutti gli elemnti dei set
|
set.union(*sets) # -> set # restituisce tutti gli elementi dei set
|
||||||
set.update(*sets) # aggiunge elementi *sets a set
|
set.update(*sets) # aggiunge elementi *sets a set
|
||||||
set.intersection(*sets) # -> set # restituisce gli elementi comuni ai set
|
set.intersection(*sets) # -> set # restituisce gli elementi comuni ai set
|
||||||
set.intersection_update(*sets) # rimuove tutti gli elementi tranne quelli comuni ai set
|
set.intersection_update(*sets) # rimuove tutti gli elementi tranne quelli comuni ai set
|
||||||
set.symmetric_difference(*sets) # -> set # restituisce gli elementi non comuni ai set
|
set.symmetric_difference(*sets) # -> set # restituisce gli elementi non comuni ai set
|
||||||
set.symmetric_difference_update(*sets) # rimuove tutti gli elementi comuni ai set (lasci solo gli elementi non comuni)
|
set.symmetric_difference_update(*sets) # rimuove tutti gli elementi comuni ai set (lasci solo gli elementi non comuni)
|
||||||
|
|
||||||
set_1.isdisjoint(set_2) # -> bool # True se non ci sono elementi comunni (intersezione è vuota)
|
set_1.isdisjoint(set_2) # -> bool # True se non ci sono elementi comuni (intersezione è vuota)
|
||||||
set_1.issubset(set_2) # -> bool # True se ogni elemento di set_1 è anche in set_2
|
set_1.issubset(set_2) # -> bool # True se ogni elemento di set_1 è anche in set_2
|
||||||
set_1.issuperset(set_2) # -> bool # True se ogni elemento di set_2 è anche in set_1
|
set_1.issuperset(set_2) # -> bool # True se ogni elemento di set_2 è anche in set_1
|
||||||
|
|
||||||
|
@ -461,7 +461,7 @@ bytearray.count(subseq, start, end) # restituisce conteggio apparizioni subseq
|
||||||
BYTE LITERALS
|
BYTE LITERALS
|
||||||
ASCII --> stesso carattere
|
ASCII --> stesso carattere
|
||||||
tab, newline, carriage return, escape sequence --> \t, \n, \r, \\
|
tab, newline, carriage return, escape sequence --> \t, \n, \r, \\
|
||||||
altro --> escape sequence exadeciamle (null byte --> \x00)
|
altro --> escape sequence esadecimale (null byte --> \x00)
|
||||||
|
|
||||||
Unicode Literals:
|
Unicode Literals:
|
||||||
|
|
||||||
|
@ -485,11 +485,11 @@ stringa.encode('utf-8', errors='replace') # -> b'byte literals'
|
||||||
|
|
||||||
# DECODING
|
# DECODING
|
||||||
# trasforma byte literal in stringa
|
# trasforma byte literal in stringa
|
||||||
# error='replace' sostituisce gli errori (byte literal non appartenentia formato di decodifica) con U+FFFD "REPLACEMENT CHARARCTER"
|
# error='replace' sostituisce gli errori (byte literal non appartenenti a formato di decodifica) con U+FFFD "REPLACEMENT CHARACTER"
|
||||||
bytes.decode('utf-8', errors='replace') # -> str
|
bytes.decode('utf-8', errors='replace') # -> str
|
||||||
|
|
||||||
# NORMALIZZAZIONE UNICODE
|
# NORMALIZZAZIONE UNICODE
|
||||||
# gestione equivalenti canconici unicode (e.g. é, e\u0301 sono equivalenti per unicode)
|
# gestione equivalenti canonici unicode (e.g. é, e\u0301 sono equivalenti per unicode)
|
||||||
import unicodedata
|
import unicodedata
|
||||||
unicodedata.normalize(form, unicode_string) # FORM: NFC,NFD, NFCK, NFDK
|
unicodedata.normalize(form, unicode_string) # FORM: NFC,NFD, NFCK, NFDK
|
||||||
# NFC --> "Normalization Form C" --> produce la stringa equivalente più corta
|
# NFC --> "Normalization Form C" --> produce la stringa equivalente più corta
|
||||||
|
@ -588,9 +588,9 @@ d | e # {'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}
|
||||||
e | d # {'aardvark': 'Ethel', 'spam': 1, 'eggs': 2, 'cheese': 3}
|
e | d # {'aardvark': 'Ethel', 'spam': 1, 'eggs': 2, 'cheese': 3}
|
||||||
d |= e # {'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}
|
d |= e # {'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}
|
||||||
|
|
||||||
# DIZIONARI ANNIDATI (possibile annidare dizioanari all'interno di dizionari)
|
# DIZIONARI ANNIDATI (possibile annidare dizionari all'interno di dizionari)
|
||||||
my_dict = {'key_1':123, 'key_2':[12, 23, 33], 'key_3':['item_0', 'item_1', 'item_2']}
|
my_dict = {'key_1':123, 'key_2':[12, 23, 33], 'key_3':['item_0', 'item_1', 'item_2']}
|
||||||
my_dict['key'][0] # restituisce elemento annnidato
|
my_dict['key'][0] # restituisce elemento annidato
|
||||||
|
|
||||||
# DICT COMPREHENSIONS
|
# DICT COMPREHENSIONS
|
||||||
var = {key : value for elemento in sequenza}
|
var = {key : value for elemento in sequenza}
|
||||||
|
@ -598,7 +598,7 @@ var = {key : value for elemento in sequenza}
|
||||||
|
|
||||||
## Operators
|
## Operators
|
||||||
|
|
||||||
### Methematical Operators
|
### Mathematical Operators
|
||||||
|
|
||||||
| Operator | Operation |
|
| Operator | Operation |
|
||||||
| -------- | ------------------------------ |
|
| -------- | ------------------------------ |
|
||||||
|
@ -621,7 +621,7 @@ var = {key : value for elemento in sequenza}
|
||||||
| x `==` y | equality |
|
| x `==` y | equality |
|
||||||
| x `!=` y | inequality |
|
| x `!=` y | inequality |
|
||||||
|
|
||||||
### Assignement
|
### Assignment
|
||||||
|
|
||||||
| Operator | Operation |
|
| Operator | Operation |
|
||||||
| --------- | ---------- |
|
| --------- | ---------- |
|
||||||
|
@ -646,7 +646,7 @@ var = {key : value for elemento in sequenza}
|
||||||
| x `^` y | bitwise XOR |
|
| x `^` y | bitwise XOR |
|
||||||
| x `|` y | bitwise OR |
|
| x `|` y | bitwise OR |
|
||||||
| x `<<` y | left bit shift |
|
| x `<<` y | left bit shift |
|
||||||
| x `>>` y | rigth bit shift |
|
| x `>>` y | right bit shift |
|
||||||
|
|
||||||
### Logical Operators
|
### Logical Operators
|
||||||
|
|
||||||
|
@ -667,7 +667,7 @@ var = {key : value for elemento in sequenza}
|
||||||
|
|
||||||
| Operator | Operation |
|
| Operator | Operation |
|
||||||
| -------- | ---------------------- |
|
| -------- | ---------------------- |
|
||||||
| `in` | item in cooection |
|
| `in` | item in collection |
|
||||||
| `not in` | item not in collection |
|
| `not in` | item not in collection |
|
||||||
|
|
||||||
### Precedenza Operatori
|
### Precedenza Operatori
|
||||||
|
@ -691,16 +691,7 @@ built-in objects considered *false*:
|
||||||
- zero of any numeric type: `0`, `0.0`, `0j`, `Decimal(0)`, `Fraction(0, 1)`
|
- zero of any numeric type: `0`, `0.0`, `0j`, `Decimal(0)`, `Fraction(0, 1)`
|
||||||
- empty sequences and collections: `''`, `()`, `[]`, `{}`, `set()`, `range(0)`
|
- empty sequences and collections: `''`, `()`, `[]`, `{}`, `set()`, `range(0)`
|
||||||
|
|
||||||
### `if-else` semplice
|
### `if-else`
|
||||||
|
|
||||||
```py
|
|
||||||
if (condizione):
|
|
||||||
# code here
|
|
||||||
else:
|
|
||||||
# code here
|
|
||||||
```
|
|
||||||
|
|
||||||
### `if-else` multiramo
|
|
||||||
|
|
||||||
```py
|
```py
|
||||||
if (condizione):
|
if (condizione):
|
||||||
|
@ -726,7 +717,7 @@ contextmanager.__enter__(self)
|
||||||
# restituisce exc_type, exc_value, traceback
|
# restituisce exc_type, exc_value, traceback
|
||||||
contextmanager.__exit__(self, exc_type, exc_value, traceback)
|
contextmanager.__exit__(self, exc_type, exc_value, traceback)
|
||||||
# exc_type: exception class
|
# exc_type: exception class
|
||||||
# exc_value: exception istance
|
# exc_value: exception instance
|
||||||
# traceback: traceback object
|
# traceback: traceback object
|
||||||
# NO EXCEPTION -> restituisce None, None, None
|
# NO EXCEPTION -> restituisce None, None, None
|
||||||
# SOPPRESSIONE ECCEZIONE: necessario restituire valore True
|
# SOPPRESSIONE ECCEZIONE: necessario restituire valore True
|
||||||
|
@ -765,7 +756,7 @@ for key, value in dict.items():
|
||||||
### Istruzioni `break` & `continue`
|
### Istruzioni `break` & `continue`
|
||||||
|
|
||||||
`break`: causa l'uscita immediata dal ciclo senza l'esecuzione delle successive iterazioni
|
`break`: causa l'uscita immediata dal ciclo senza l'esecuzione delle successive iterazioni
|
||||||
`continue`: salte le restanti istruzioni del'iterazione e prosegue il ciclo
|
`continue`: salta le restanti istruzioni del'iterazione e prosegue il ciclo
|
||||||
|
|
||||||
### Istruzione `range`
|
### Istruzione `range`
|
||||||
|
|
||||||
|
@ -785,7 +776,7 @@ list(enumerate(iterabile)) # restituisce lista di tuple [(1, iterabile[0]), (2,
|
||||||
|
|
||||||
```py
|
```py
|
||||||
list_1 = [1, 2, 3, 4, 5]
|
list_1 = [1, 2, 3, 4, 5]
|
||||||
lsit_2 = ['a', 'b', 'c', 'd', 'e']
|
list_2 = ['a', 'b', 'c', 'd', 'e']
|
||||||
|
|
||||||
zip(list_1, list_2) # restituisce oggetto zip
|
zip(list_1, list_2) # restituisce oggetto zip
|
||||||
list(zip(list_1, list_2)) # restituisce lista di tuple fondendo la lista [(list_1[0], list_2[0]), (list_1[1], list_2[1]), ...]
|
list(zip(list_1, list_2)) # restituisce lista di tuple fondendo la lista [(list_1[0], list_2[0]), (list_1[1], list_2[1]), ...]
|
||||||
|
@ -802,12 +793,12 @@ randint(inizio, fine) # restituisce un intero random compreso tra inizio e fine
|
||||||
### Istruzione `in`
|
### Istruzione `in`
|
||||||
|
|
||||||
```py
|
```py
|
||||||
item in iterabile # controlla presenza di intem in iterabile (restituisce True o False)
|
item in iterabile # controlla presenza di item in iterabile (restituisce True o False)
|
||||||
```
|
```
|
||||||
|
|
||||||
## Funzioni
|
## Funzioni
|
||||||
|
|
||||||
### Definizone Funzione
|
### Definizione Funzione
|
||||||
|
|
||||||
```py
|
```py
|
||||||
def nome_funzione (parametri):
|
def nome_funzione (parametri):
|
||||||
|
@ -820,14 +811,14 @@ def nome_funzione (parametri):
|
||||||
|
|
||||||
`nome_funzione(parametri)`
|
`nome_funzione(parametri)`
|
||||||
|
|
||||||
### Specificare Tipo Paremetri In Funzioni
|
### Specificare Tipo Parametri In Funzioni
|
||||||
|
|
||||||
- parametri prima di `/` possono essere solo *posizionali*
|
- parametri prima di `/` possono essere solo *posizionali*
|
||||||
- parametri tra `/` e `*` possono essere *posizionali* o *keyworded*
|
- parametri tra `/` e `*` possono essere *posizionali* o *keyworded*
|
||||||
- parametri dopo `*` possono essere solo *keyworded*
|
- parametri dopo `*` possono essere solo *keyworded*
|
||||||
|
|
||||||
```py
|
```py
|
||||||
def funz(a, b, /, c, d, *, e, f):
|
def func(a, b, /, c, d, *, e, f):
|
||||||
# code here
|
# code here
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -865,17 +856,17 @@ def funzione (parametro1 = valore1, parametro2 = valore3): # valori di default i
|
||||||
# code here
|
# code here
|
||||||
return espressione
|
return espressione
|
||||||
|
|
||||||
funzione(parametro2 = valore2, parametro1 = valore1) # argometi passati con keyword per imporre l'ordine di riferimento
|
funzione(parametro2 = valore2, parametro1 = valore1) # argomenti passati con keyword per imporre l'ordine di riferimento
|
||||||
```
|
```
|
||||||
|
|
||||||
### VARIABILI GLOBALI E LOCALI
|
### VARIABILI GLOBALI E LOCALI
|
||||||
|
|
||||||
```py
|
```py
|
||||||
# global scope
|
# global scope
|
||||||
def funz_esterna():
|
def func_esterna():
|
||||||
# enclosing local scope
|
# enclosing local scope
|
||||||
# code here
|
# code here
|
||||||
def funz_interna():
|
def func_interna():
|
||||||
# local scope
|
# local scope
|
||||||
# code here
|
# code here
|
||||||
```
|
```
|
||||||
|
@ -898,11 +889,11 @@ def funzione():
|
||||||
# code here
|
# code here
|
||||||
```
|
```
|
||||||
|
|
||||||
### Iteratabili, Iteratori E Generatori
|
### Iterabili, Iteratori E Generatori
|
||||||
|
|
||||||
**Iterabile**: oggetto implementante `__iter__()`, sequenze e oggetti supportanti `__getitem__` con index `0`
|
**Iterabile**: oggetto implementante `__iter__()`, sequenze e oggetti supportanti `__getitem__` con index `0`
|
||||||
|
|
||||||
**Iteratore**: oggetto implementante `__next__` e `__iter__` (**protocollo iteratore**), quando interamente consumato da next() diventa inutilizablie.
|
**Iteratore**: oggetto implementante `__next__` e `__iter__` (**protocollo iteratore**), quando interamente consumato da next() diventa inutilizzabili.
|
||||||
Gli iteratori sono iterabili, viceversa non vero. Restituisce `StopIteration` quando `next()` ha restituito tutti gli elementi.
|
Gli iteratori sono iterabili, viceversa non vero. Restituisce `StopIteration` quando `next()` ha restituito tutti gli elementi.
|
||||||
|
|
||||||
**Funzione Generatore**: funzione con keyword `yield` (se presente anche `return` causa `StopIteration`), restituisce un generatore che produce i valori uno alla volta.
|
**Funzione Generatore**: funzione con keyword `yield` (se presente anche `return` causa `StopIteration`), restituisce un generatore che produce i valori uno alla volta.
|
||||||
|
@ -913,7 +904,7 @@ Funzionamento `iter()`:
|
||||||
|
|
||||||
- chiama __iter__()
|
- chiama __iter__()
|
||||||
- in assenza di esso python sfrutta __getitem__() (se presente) per creare un iteratore che tenta di recuperare gli item in ordine, partendo dall'indice `0`
|
- in assenza di esso python sfrutta __getitem__() (se presente) per creare un iteratore che tenta di recuperare gli item in ordine, partendo dall'indice `0`
|
||||||
- in caso di fallimento resituisce `TypeError "obj_cls is not iterable"`
|
- in caso di fallimento restituisce `TypeError "obj_cls is not iterable"`
|
||||||
|
|
||||||
**Note**: `abc.Iterable` non controlla la presenza di `__getitem__` per decidere se un sotto-oggetto è membro conseguentemente il miglior test per l'iterabilità è usare `iter()` e gestirne le eccezioni.
|
**Note**: `abc.Iterable` non controlla la presenza di `__getitem__` per decidere se un sotto-oggetto è membro conseguentemente il miglior test per l'iterabilità è usare `iter()` e gestirne le eccezioni.
|
||||||
|
|
||||||
|
@ -923,7 +914,7 @@ Funzionamento `iter()`:
|
||||||
next(iterabile) # prossimo item dell'iterabile o errore StopIteration
|
next(iterabile) # prossimo item dell'iterabile o errore StopIteration
|
||||||
|
|
||||||
iter(oggetto) # ottiene un iteratore a partire da un oggetto
|
iter(oggetto) # ottiene un iteratore a partire da un oggetto
|
||||||
# chiama callable_onj.next() senza argomenti finche esso restituisce valori diversi da sentinella
|
# chiama callable_onj.next() senza argomenti finché esso restituisce valori diversi da sentinella
|
||||||
|
|
||||||
iter(callable_obj, sentinella)
|
iter(callable_obj, sentinella)
|
||||||
```
|
```
|
||||||
|
@ -948,7 +939,7 @@ for item in custom_generator(parametri):
|
||||||
# solleva eccezione al punto di sospensione e restituisce valore del generatore
|
# solleva eccezione al punto di sospensione e restituisce valore del generatore
|
||||||
# se il generatore termina senza restituire valori solleva StopIteration
|
# se il generatore termina senza restituire valori solleva StopIteration
|
||||||
# se un eccezione non viene gestita viene propagata al chiamante
|
# se un eccezione non viene gestita viene propagata al chiamante
|
||||||
generator.throw(ExceptionType, exceptio_value, traceback)
|
generator.throw(ExceptionType, exception_value, traceback)
|
||||||
|
|
||||||
# solleva GeneratorExit al punto si sospensione
|
# solleva GeneratorExit al punto si sospensione
|
||||||
# se generatore restituisce un valore -> RuntimeError
|
# se generatore restituisce un valore -> RuntimeError
|
||||||
|
@ -962,7 +953,7 @@ generator.close()
|
||||||
# sequenza di lunghezza zero (valori generati sul momento)
|
# sequenza di lunghezza zero (valori generati sul momento)
|
||||||
var = (espressione for iterabile in sequenza if condizione)
|
var = (espressione for iterabile in sequenza if condizione)
|
||||||
# ISTRUZIONE ENUMERATE()
|
# ISTRUZIONE ENUMERATE()
|
||||||
# restituisce una lista di tuple associando ad ogni elemendo della sequenza un indice di posizione
|
# restituisce una lista di tuple associando ad ogni elemento della sequenza un indice di posizione
|
||||||
# [(0, sequenza[0]), (1, sequenza[1]), (2, sequenza[2]), ...)
|
# [(0, sequenza[0]), (1, sequenza[1]), (2, sequenza[2]), ...)
|
||||||
enumerate(sequenza) # -> oggetto enumerate
|
enumerate(sequenza) # -> oggetto enumerate
|
||||||
```
|
```
|
||||||
|
@ -1004,7 +995,7 @@ def coroutine(func):
|
||||||
|
|
||||||
# TERMINAZIONE COROUTINE E EXCEPTION HANDLING
|
# TERMINAZIONE COROUTINE E EXCEPTION HANDLING
|
||||||
# eccezioni in coroutine non gestite si propagano alle iterazioni successive
|
# eccezioni in coroutine non gestite si propagano alle iterazioni successive
|
||||||
# un eccezione causa la tarminazione della coroutine che non puo riprendere
|
# un eccezione causa la terminazione della coroutine che non puo riprendere
|
||||||
|
|
||||||
# yield solleva eccezione, se gestita ciclo continua
|
# yield solleva eccezione, se gestita ciclo continua
|
||||||
# throw() restituisce valore del generatore
|
# throw() restituisce valore del generatore
|
||||||
|
@ -1019,7 +1010,7 @@ coroutine.close()
|
||||||
|
|
||||||
### `yield from <iterabile>`
|
### `yield from <iterabile>`
|
||||||
|
|
||||||
**Note**: auto-priming generators incomplatible with `yield from`
|
**Note**: auto-priming generators incompatible with `yield from`
|
||||||
|
|
||||||
**DELEGATING GENERATOR**: funzione generatore contenente yield from
|
**DELEGATING GENERATOR**: funzione generatore contenente yield from
|
||||||
**SUBGENERATOR**: generatore ottenuto da `yield from <iterabile>`
|
**SUBGENERATOR**: generatore ottenuto da `yield from <iterabile>`
|
||||||
|
@ -1034,8 +1025,8 @@ La funzione principale di `yield from` è aprire una canale bidirezionale tra il
|
||||||
- Any values that the subgenerator yields are passed directly to the caller of the delegating generator (i.e., the client code).
|
- Any values that the subgenerator yields are passed directly to the caller of the delegating generator (i.e., the client code).
|
||||||
|
|
||||||
- Any values sent to the delegating generator using `send()` are passed directly to the subgenerator.
|
- Any values sent to the delegating generator using `send()` are passed directly to the subgenerator.
|
||||||
- If the sent value is `None`, the subgenerator’s `__next__()` method is called.
|
- If the sent value is `None`, the subgenerator's `__next__()` method is called.
|
||||||
- If the sent value is not `None`, the subgenerator’s `send()` method is called.
|
- If the sent value is not `None`, the subgenerator's `send()` method is called.
|
||||||
- If the call raises `StopIteration`, the delegating generator is resumed.
|
- If the call raises `StopIteration`, the delegating generator is resumed.
|
||||||
- Any other exception is propagated to the delegating generator.
|
- Any other exception is propagated to the delegating generator.
|
||||||
|
|
||||||
|
@ -1067,7 +1058,7 @@ def delegating_gen(var):
|
||||||
def client():
|
def client():
|
||||||
# code here
|
# code here
|
||||||
result = delegating_gen() # use delegating_gen
|
result = delegating_gen() # use delegating_gen
|
||||||
result.send(None) # termina istanza sub_gen (IMPORATNTE)
|
result.send(None) # termina istanza sub_gen (IMPORTANTE)
|
||||||
```
|
```
|
||||||
|
|
||||||
## Ricorsione
|
## Ricorsione
|
||||||
|
@ -1085,9 +1076,6 @@ def factorial(n):
|
||||||
else:
|
else:
|
||||||
result = (n*factorial(n-1))
|
result = (n*factorial(n-1))
|
||||||
return result
|
return result
|
||||||
|
|
||||||
num = int(input('Enther a number to calculate it\'s factorial:'))
|
|
||||||
print(factorial(num))
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Funzioni Avanzate
|
## Funzioni Avanzate
|
||||||
|
@ -1103,31 +1091,31 @@ def funzione(parametri):
|
||||||
# chiamata funzione senza parentesi
|
# chiamata funzione senza parentesi
|
||||||
funzione # restituisce oggetto funzione
|
funzione # restituisce oggetto funzione
|
||||||
var = funzione # assegna (per riferimento) la funzione ad una variabile.
|
var = funzione # assegna (per riferimento) la funzione ad una variabile.
|
||||||
# la chiamata funziona anche se la funz originale viene eliminata (del funzione)
|
# la chiamata funziona anche se la func originale viene eliminata (del funzione)
|
||||||
var() # chiama la funzione tramite la variabile (usando le parentesi tonde)
|
var() # chiama la funzione tramite la variabile (usando le parentesi tonde)
|
||||||
```
|
```
|
||||||
|
|
||||||
### Funzioni Annidate
|
### Funzioni Annidate
|
||||||
|
|
||||||
```py
|
```py
|
||||||
# funz_interna locale viene ritornata per riferimento
|
# func_interna locale viene ritornata per riferimento
|
||||||
def funz_esterna(args):
|
def func_esterna(args):
|
||||||
|
|
||||||
def funz_interna(): # funz_interna ha accesso a scope funzione esterna (aka Closure)
|
def func_interna(): # func_interna ha accesso a scope funzione esterna (aka Closure)
|
||||||
# code here
|
# code here
|
||||||
return funz_interna # restituisce funz_interna
|
return func_interna # restituisce func_interna
|
||||||
|
|
||||||
funz_esterna() # chiamata funz_esterna che chiama funz_interna (risultato funz_esterna è riferimento funz_interna)
|
func_esterna() # chiamata func_esterna che chiama func_interna (risultato func_esterna è riferimento func_interna)
|
||||||
```
|
```
|
||||||
|
|
||||||
### Funzioni Passate Per Argomento
|
### Funzioni Passate Per Argomento
|
||||||
|
|
||||||
```py
|
```py
|
||||||
# funzione passata come argomento viene eseguita (chiamata) all'esecuzione della funzione a cui viene passata
|
# funzione passata come argomento viene eseguita (chiamata) all'esecuzione della funzione a cui viene passata
|
||||||
def funz_esterna(funzione):
|
def func_esterna(funzione):
|
||||||
funzione() # chiama funzione passata come argomento
|
funzione() # chiama funzione passata come argomento
|
||||||
|
|
||||||
funz_esterna() # esecuzione funz_esterna chiama funz_interna
|
func_esterna() # esecuzione func_esterna chiama func_interna
|
||||||
```
|
```
|
||||||
|
|
||||||
### Funzioni Incapsulanti Funzioni (Argomenti Wrapper = Argomenti Wrapped)
|
### Funzioni Incapsulanti Funzioni (Argomenti Wrapper = Argomenti Wrapped)
|
||||||
|
@ -1138,7 +1126,7 @@ def wrapped(*args):
|
||||||
|
|
||||||
def wrapper(*args):
|
def wrapper(*args):
|
||||||
# instructions
|
# instructions
|
||||||
wrapped(*args) # wrapped chiamata con gli argomeni passati a wrapper AS-IS (args = tupla) senza incapsulamento in una tupla
|
wrapped(*args) # wrapped chiamata con gli argomenti passati a wrapper AS-IS (args = tuple) senza incapsulamento in una tuple
|
||||||
```
|
```
|
||||||
|
|
||||||
## LAMBDA Functions
|
## LAMBDA Functions
|
||||||
|
@ -1154,28 +1142,28 @@ var(args) # invocazione lambda
|
||||||
|
|
||||||
## Decoratori
|
## Decoratori
|
||||||
|
|
||||||
Entita' chiamabile che prende in input una funzione (come argomento).
|
Entità' chiamabile che prende in input una funzione (come argomento).
|
||||||
Eventualmente effettua operazioni con la funzione decorata e la restituisce o sostituisce.
|
Eventualmente effettua operazioni con la funzione decorata e la restituisce o sostituisce.
|
||||||
vengono eseguiti all'importazione, prima di ogni altra istruzione.
|
vengono eseguiti all'importazione, prima di ogni altra istruzione.
|
||||||
|
|
||||||
```py
|
```py
|
||||||
# STRUTTURA DECORATORE PARZIALE (SOSTITUISCE FUNZIONE IMPUT)
|
# STRUTTURA DECORATORE PARZIALE (SOSTITUISCE FUNZIONE INPUT)
|
||||||
def decorator(funzione): # prende in input una funzione
|
def decorator(funzione): # prende in input una funzione
|
||||||
def wrapper(): # funzione decoratrice
|
def wrapper(): # funzione decoratrice
|
||||||
# code here
|
# code here
|
||||||
|
|
||||||
return wrapper # restituisce wrapper (chiamata a funz_decorata chiama wrapper)
|
return wrapper # restituisce wrapper (chiamata a func_decorata chiama wrapper)
|
||||||
|
|
||||||
# STRUTTURA DECORATORE COMPLETA (MODOFICA FUNZIONE INPUT)
|
# STRUTTURA DECORATORE COMPLETA (MODIFICA FUNZIONE INPUT)
|
||||||
def decorator(funzione): # prende in input una funzione da decorare
|
def decorator(funzione): # prende in input una funzione da decorare
|
||||||
@functools.wraps(funzione) # keep code inspection avaiable
|
@functools.wraps(funzione) # keep code inspection available
|
||||||
def wrapper(*args, **kwargs): # funzione decoratrice (args, kwargs sono argomenti della funzione decorata)
|
def wrapper(*args, **kwargs): # funzione decoratrice (args, kwargs sono argomenti della funzione decorata)
|
||||||
# do something before
|
# do something before
|
||||||
var_funz = funzione(*args, **kwargs)
|
var_func = funzione(*args, **kwargs)
|
||||||
# do something after
|
# do something after
|
||||||
return var_funz # restituisce il risultato della decorazione della funzione
|
return var_func # restituisce il risultato della decorazione della funzione
|
||||||
|
|
||||||
return wrapper # restituisce wrapper (chiamata a funz_decorata chiama wrapper)
|
return wrapper # restituisce wrapper (chiamata a func_decorata chiama wrapper)
|
||||||
|
|
||||||
@decorator # applicazione del decoratore alla funzione
|
@decorator # applicazione del decoratore alla funzione
|
||||||
def funzione(): # funzione da decorare
|
def funzione(): # funzione da decorare
|
||||||
|
@ -1190,9 +1178,9 @@ def decorator(*dec_args, **dec_kwargs): # prende in input argomenti del decorat
|
||||||
|
|
||||||
def inner_wrapper(*args, **kwargs):
|
def inner_wrapper(*args, **kwargs):
|
||||||
# do something before
|
# do something before
|
||||||
var_funz = funzione(*args, **kwargs)
|
var_func = funzione(*args, **kwargs)
|
||||||
# do something after
|
# do something after
|
||||||
return var_funz
|
return var_func
|
||||||
|
|
||||||
return inner_wrapper
|
return inner_wrapper
|
||||||
|
|
||||||
|
@ -1213,14 +1201,14 @@ def funzione(): # funzione da decorare
|
||||||
class NomeClasse:
|
class NomeClasse:
|
||||||
|
|
||||||
# creazione variabile statica (o di classe; condivisa da tutte le istanze)
|
# creazione variabile statica (o di classe; condivisa da tutte le istanze)
|
||||||
# ovverride possinile tramite subclassing o assegnazine diretta (oggetto.static_var =)
|
# override possibile tramite subclassing o assegnazione diretta (oggetto.static_var =)
|
||||||
# NomeClasse.static_var = cambia l'attributo di classe in tutte le istanze
|
# NomeClasse.static_var = cambia l'attributo di classe in tutte le istanze
|
||||||
static_var = espressione
|
static_var = espressione
|
||||||
|
|
||||||
def __init__(self, valore_1, valore_2): # costruttore di default parametrizzato
|
def __init__(self, valore_1, valore_2): # costruttore di default parametrizzato
|
||||||
# attributi sono alias degli argomenti (modifiche in-place cambiano argomenti)
|
# attributi sono alias degli argomenti (modifiche in-place cambiano argomenti)
|
||||||
self.variabile = valore_1 # creazione variabili di istanza
|
self.variabile = valore_1 # creazione variabili di istanza
|
||||||
self.__variabile = valore_2 # variabile appartenente ad oggetti della classe e non ai figli, accesso tarmite NAME MANGLING
|
self.__variabile = valore_2 # variabile appartenente ad oggetti della classe e non ai figli, accesso tramite NAME MANGLING
|
||||||
|
|
||||||
|
|
||||||
@classmethod # metodo agente sulla classe e non sull'oggetto (utile x costruttori alternativi)
|
@classmethod # metodo agente sulla classe e non sull'oggetto (utile x costruttori alternativi)
|
||||||
|
@ -1234,14 +1222,14 @@ class NomeClasse:
|
||||||
return espressione
|
return espressione
|
||||||
|
|
||||||
@staticmethod # indica un metodo statico (NECESSARIO)
|
@staticmethod # indica un metodo statico (NECESSARIO)
|
||||||
def metodo_statico(parametri): # metodi statici non influenzano variabili di istanza (SELF non necessatio)
|
def metodo_statico(parametri): # metodi statici non influenzano variabili di istanza (SELF non necessario)
|
||||||
instruction
|
instruction
|
||||||
return espressione
|
return espressione
|
||||||
|
|
||||||
oggetto = NomeClasse(parametri) # creazione di un oggetto
|
oggetto = NomeClasse(parametri) # creazione di un oggetto
|
||||||
oggetto.variabile = espressione # modifica variabile pubblica
|
oggetto.variabile = espressione # modifica variabile pubblica
|
||||||
oggetto.metodo(parametri) # invocazione metodo di istanza
|
oggetto.metodo(parametri) # invocazione metodo di istanza
|
||||||
NomeClasse.metodo(parametri) #ivocazione metodo statico
|
NomeClasse.metodo(parametri) # invocazione metodo statico
|
||||||
oggetto._NomeClasse__var_privata # accesso a variabile specificando la classe di appartenenza (NAME MANGLING)
|
oggetto._NomeClasse__var_privata # accesso a variabile specificando la classe di appartenenza (NAME MANGLING)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -1260,7 +1248,7 @@ class NomeClasse:
|
||||||
return self.__parametro
|
return self.__parametro
|
||||||
|
|
||||||
@parametro.setter
|
@parametro.setter
|
||||||
def parameto(self, valore):
|
def parametro(self, valore):
|
||||||
self.__parametro = valore
|
self.__parametro = valore
|
||||||
|
|
||||||
@parametro.deleter # metodo deleter
|
@parametro.deleter # metodo deleter
|
||||||
|
@ -1271,12 +1259,12 @@ class NomeClasse:
|
||||||
### `__slots__`
|
### `__slots__`
|
||||||
|
|
||||||
L'attributo `__slots__` implementa **Flyweight Design Pattern**:
|
L'attributo `__slots__` implementa **Flyweight Design Pattern**:
|
||||||
salva gli attributi d'istanza in una tupla e può essere usato per diminuire il costo in memoria inserendovi solo le variabili di istanza (sopprime il dizionario dell'istanza).
|
salva gli attributi d'istanza in una tuple e può essere usato per diminuire il costo in memoria inserendovi solo le variabili di istanza (sopprime il dizionario dell'istanza).
|
||||||
|
|
||||||
**Default**: attributi salvati in un dizionario (`oggetto.__dict__`)
|
**Default**: attributi salvati in un dizionario (`oggetto.__dict__`)
|
||||||
**Uso**: `__slots_ = [attributi]`
|
**Uso**: `__slots_ = [attributi]`
|
||||||
|
|
||||||
`__slots__` non viene ereditato dalle sottoclassi, impedisce l'aggiunta dinamica delgi attributi.
|
`__slots__` non viene ereditato dalle sottoclassi, impedisce l'aggiunta dinamica degli attributi.
|
||||||
|
|
||||||
### Fluent Interface
|
### Fluent Interface
|
||||||
|
|
||||||
|
@ -1324,7 +1312,7 @@ I metodi speciali sono definiti dall'uso di doppi underscore; essi permettono l'
|
||||||
class NomeClasse():
|
class NomeClasse():
|
||||||
|
|
||||||
def __init__(self, parametri):
|
def __init__(self, parametri):
|
||||||
istuzioni
|
istruzioni
|
||||||
|
|
||||||
# usato da metodo str() e print()
|
# usato da metodo str() e print()
|
||||||
# gestisce le richieste di rappresentazione come stringa
|
# gestisce le richieste di rappresentazione come stringa
|
||||||
|
@ -1334,8 +1322,8 @@ class NomeClasse():
|
||||||
def __len__(self):
|
def __len__(self):
|
||||||
return espressione # necessario return in quanto len richiede una lunghezza/dimensione
|
return espressione # necessario return in quanto len richiede una lunghezza/dimensione
|
||||||
|
|
||||||
def __del__(self): # elimina l'istanda della classe
|
def __del__(self): # elimina l'istanza della classe
|
||||||
instruction # eventuali istruzionni che avvengono all'eliminazione
|
instruction # eventuali istruzioni che avvengono all'eliminazione
|
||||||
|
|
||||||
oggetto = NomeClasse()
|
oggetto = NomeClasse()
|
||||||
len(oggetto) # funzione speciale applicata ad un oggetto
|
len(oggetto) # funzione speciale applicata ad un oggetto
|
||||||
|
@ -1363,7 +1351,7 @@ __xor__(self, other) # ^
|
||||||
__or__(self, other) # |
|
__or__(self, other) # |
|
||||||
|
|
||||||
# operatori aritmetici riflessi
|
# operatori aritmetici riflessi
|
||||||
# [se self.__dunde__(other) fallisce viene chiamato other.__dunder__(self)]
|
# [se self.__dunder__(other) fallisce viene chiamato other.__dunder__(self)]
|
||||||
__radd__(self, other) # reverse +
|
__radd__(self, other) # reverse +
|
||||||
__rsub__(self, other) # reverse -
|
__rsub__(self, other) # reverse -
|
||||||
__rmul__(self, other) # reverse *
|
__rmul__(self, other) # reverse *
|
||||||
|
|
|
@ -45,7 +45,7 @@ ArgumentParser.add_argument("name_or_flags", nargs="...", action="...")
|
||||||
|
|
||||||
### Actions
|
### 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
|
```py
|
||||||
>>> parser = argparse.ArgumentParser()
|
>>> parser = argparse.ArgumentParser()
|
||||||
|
@ -159,7 +159,7 @@ Namespace(bar='XX', foo='c')
|
||||||
Namespace(bar='d', foo='d')
|
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
|
```py
|
||||||
>>> parser = argparse.ArgumentParser()
|
>>> parser = argparse.ArgumentParser()
|
||||||
|
@ -170,7 +170,7 @@ Namespace(bar='d', foo='d')
|
||||||
Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
|
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
|
```py
|
||||||
>>> parser = argparse.ArgumentParser(prog='PROG')
|
>>> parser = argparse.ArgumentParser(prog='PROG')
|
||||||
|
|
|
@ -6,7 +6,7 @@
|
||||||
# sottoclasse dizionario per contare oggetti hash-abili
|
# sottoclasse dizionario per contare oggetti hash-abili
|
||||||
from collections import Counter
|
from collections import Counter
|
||||||
Counter(sequenza) # -> oggetto Counter
|
Counter(sequenza) # -> oggetto Counter
|
||||||
# {item: num comparese in sequenza, ...}
|
# {item: num comprese in sequenza, ...}
|
||||||
|
|
||||||
var = Counter(sequenza)
|
var = Counter(sequenza)
|
||||||
var.most_common(n) # produce lista degli elementi più comuni (n più comuni)
|
var.most_common(n) # produce lista degli elementi più comuni (n più comuni)
|
||||||
|
|
|
@ -29,10 +29,10 @@ fieldnames
|
||||||
# elimina il dialect associato a name
|
# elimina il dialect associato a name
|
||||||
.unregister_dialect()
|
.unregister_dialect()
|
||||||
|
|
||||||
# restituisce il dialet associato a name
|
# restituisce il dialetto associato a name
|
||||||
.get_dialect(name)
|
.get_dialect(name)
|
||||||
|
|
||||||
# elenco dialec associati a name
|
# elenco dialetti associati a name
|
||||||
.list_dialect(name)
|
.list_dialect(name)
|
||||||
|
|
||||||
# restituisce (se vuoto) o setta il limite del campo del csv
|
# 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
|
.has_header(campione) --> bool # True se prima riga è una serie di intestazioni di colonna
|
||||||
|
|
||||||
#COSTANTI
|
#COSTANTI
|
||||||
csv.QUOTE_ALL # indica a writer di citere (" ") tutti i campi
|
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, quotechar ...
|
csv.QUOTE_MINIMAL # indica a write di citare solo i campi contenenti caratteri speciali come delimiter, quote char ...
|
||||||
csv.QUOTE_NONNUMERIC # indica al vriter di citare tutti i campi non numerici
|
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
|
csv.QUOTE_NONE # indica a write di non citare mai i campi
|
||||||
```
|
```
|
||||||
|
|
|
@ -1,14 +1,13 @@
|
||||||
# Ftplib Module Cheat Sheet
|
# Ftplib Module
|
||||||
|
|
||||||
## FTP CLASSES
|
## FTP CLASSES
|
||||||
|
|
||||||
```py
|
```py
|
||||||
# restiuisce istanza classe FTP
|
|
||||||
ftplib.FTP(host="", user="", password="", acct="")
|
ftplib.FTP(host="", user="", password="", acct="")
|
||||||
# se HOST fornito esegue connect(host)
|
# if HOST => connect(host)
|
||||||
# SE USER fornito esegue login(user, password, acct)
|
# if USER => login(user, password, acct)
|
||||||
|
|
||||||
|
|
||||||
# sottoclasse FTP con TLS
|
|
||||||
ftplib.FTP_TLS(host="", user="", password="", acct="")
|
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_reply # unexpected error from server
|
||||||
ftplib.error_temp # temporary error (response codes 400-499)
|
ftplib.error_temp # temporary error (response codes 400-499)
|
||||||
ftplib.error_perm # permanent error (response codes 500-599)
|
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
|
ftplib.all_errors # tuple of all exceptions
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -29,43 +28,43 @@ ftplib.all_errors # tuple of all exceptions
|
||||||
# method on binary files: -binary
|
# method on binary files: -binary
|
||||||
|
|
||||||
# CONNECTION
|
# CONNECTION
|
||||||
FTP.connect(host="", port=0) # used unce per instance
|
FTP.connect(host="", port=0) # used once per instance
|
||||||
# DONT CALL if host was supplied at instance creation
|
# DON'T CALL if host was supplied at instance creation
|
||||||
|
|
||||||
FTP.getwelcome() # return welcome message
|
FTP.getwelcome() # return welcome message
|
||||||
|
|
||||||
FTP.login(user='anonymous', password='', acct='')
|
FTP.login(user='anonymous', password='', acct='')
|
||||||
# called unce per instance after connection is established
|
# called once per instance after connection is established
|
||||||
# DEAFAULT PASSWORD: anonymous@
|
# DEFAULT PASSWORD: anonymous@
|
||||||
# DONT CALL if host was supplied at instance creation
|
# DON'T CALL if host was supplied at instance creation
|
||||||
FTP.sendcmd(cmd) # send command string and return response
|
FTP.sendcmd(cmd) # send command string and return response
|
||||||
FTP.voidcmd(cmd) # send command string and return nothing if successful
|
FTP.voidcmd(cmd) # send command string and return nothing if successful
|
||||||
# FILE TRANSFER
|
# FILE TRANSFER
|
||||||
FTP.abort() # abort in progress file transfer (can fail)
|
FTP.abort() # abort in progress file transfer (can fail)
|
||||||
|
|
||||||
FTTP.transfercmd(cmd, rest=None) # returns socket for connection
|
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
|
# CMD passive mode: send EPSV or PASV and start transfer command
|
||||||
|
|
||||||
FTP.retrbinary(cmd, callback, blocksize=8192, rest=None) # retrieve file in binary mode
|
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
|
# CALLBACK: func called on every block of data received
|
||||||
|
|
||||||
FTP.rertlines(cmd, callback=None)
|
FTP.rertlines(cmd, callback=None)
|
||||||
# retrieve file or dir list in ASCII transfer mode
|
# 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
|
# DEFAULT CALLBACK: sys.stdout
|
||||||
|
|
||||||
FTP.set_pasv(value) # set passive mode if value is true, otherwise disable it
|
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
|
FTP.storbinary(cmd, fp, blocksize=8192, callback=None, rest=None) # store file in binary mode
|
||||||
# CMD: appropriate STOR command ('STOR filename')
|
# CMD: appropriate STOR command ('STOR filename')
|
||||||
# FP: {file object in binary mode} read until EOF in blocks of blocksize
|
# 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
|
FTP.storlines(cmd, fp, callback=None) # store file in ASCII transfer mode
|
||||||
# CMD: appropriate STOR command ('STOR filename')
|
# CMD: appropriate STOR command ('STOR filename')
|
||||||
# FP: {file object} read until EOF
|
# 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
|
# Itertools Module
|
||||||
|
|
||||||
```py
|
```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([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(iter, func( , )) -> iter[0], func(iter[0] + iter[1]) + func(prev + iter[2]), ...
|
||||||
accumulate(iterabile, func(_, _))
|
accumulate(iterable, func(_, _))
|
||||||
|
|
||||||
# iteratore restituisce elemenmti dal primo iterabile,
|
# iteratore restituisce elementi dal primo iterable,
|
||||||
# poi procede al successivo fino alla fine degli iterabili
|
# 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)
|
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
|
# restituisce sequenze di lunghezza r a partire dall'iterable
|
||||||
chain.from_iterable(iterabile)
|
|
||||||
|
|
||||||
# restituisce sequenze di lunghezza r a partire dall'iterabile
|
|
||||||
# elementi trattati come unici in base al loro valore
|
# 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
|
# # restituisce sequenze di lunghezza r a partire dall'iterable permettendo la ripetizione degli elementi
|
||||||
combinations_with_replacement(iterabile, r)
|
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
|
# un corrispondente elemento in selectors che ha valore vero
|
||||||
compress(data, selectors)
|
compress(data, selectors)
|
||||||
|
|
||||||
# iteratore restituiente valori equidistanti a partire da start
|
|
||||||
#! ATTENZIONE: sequenza numerica infinita
|
|
||||||
count(start, step)
|
count(start, step)
|
||||||
|
|
||||||
# iteratore restituiente valori in sequenza infinita
|
# iteratore restituente valori in sequenza infinita
|
||||||
cycle(iterabile)
|
cycle(iterable)
|
||||||
|
|
||||||
# iteratore droppa elementi dell'iterabile finchè il predicato è vero
|
# iteratore scarta elementi dell'iterable finché il predicato è vero
|
||||||
dropwhile(predicato, iterabile)
|
dropwhile(predicato, iterable)
|
||||||
|
|
||||||
# iteratore restituiente valori se il predicato è falso
|
# iteratore restituente valori se il predicato è falso
|
||||||
filterfalse(predicato, iterabile)
|
filterfalse(predicato, iterable)
|
||||||
|
|
||||||
# iteratore restituisce tuple (key, group)
|
# iteratore restituisce tuple (key, group)
|
||||||
# key è il criterio di raggruppamento
|
# key è il criterio di raggruppamento
|
||||||
# group è un generatore restituiente i membri del gruppo
|
# group è un generatore restituente i membri del gruppo
|
||||||
groupby(iterabile, key=None)
|
groupby(iterable, key=None)
|
||||||
|
|
||||||
# iteratore restituisce slice dell'iterabile
|
# iteratore restituisce slice dell'iterable
|
||||||
isslice(iterable, stop)
|
isslice(iterable, stop)
|
||||||
isslice(iterable, start, stop, step)
|
isslice(iterable, start, stop, step)
|
||||||
|
|
||||||
# restituisce tutte le permutazioni di lunghezza r dell'iterabile
|
# restituisce tutte le permutazioni di lunghezza r dell'iterable
|
||||||
permutations(iterabile, r=None)
|
permutations(iterable, r=None)
|
||||||
|
|
||||||
# prodotto cartesiano degli iterabili
|
# prodotto cartesiano degli iterabili
|
||||||
# cicla iterabili in ordine di input
|
# cicla iterabili in ordine di input
|
||||||
|
@ -61,17 +56,17 @@ product(*iterabili, ripetizioni=1)
|
||||||
# restituisce un oggetto infinite volte se ripetizioni non viene specificato
|
# restituisce un oggetto infinite volte se ripetizioni non viene specificato
|
||||||
repeat(oggetto, ripetizioni)
|
repeat(oggetto, ripetizioni)
|
||||||
|
|
||||||
# iteratore computa func(iterabile)
|
# iteratore computa func(iterable)
|
||||||
# usato se iterabile è sequenza pre-zipped (seq di tuple raggruppanti elementi)
|
# usato se iterable è sequenza pre-zipped (seq di tuple raggruppanti elementi)
|
||||||
starmap(func, iterabile)
|
starmap(func, iterable)
|
||||||
|
|
||||||
# iteratore restituiente valori da iterabile finchè predicato è vero
|
# iteratore restituente valori da iterable finché predicato è vero
|
||||||
takewhile(predicato, iterabile)
|
takewhile(predicato, iterable)
|
||||||
|
|
||||||
# restituisce n iteratori indipendenti dal singolo iterabile
|
# restituisce n iteratori indipendenti dal singolo iterable
|
||||||
tee(iterabile, n=2)
|
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
|
# 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()`)
|
## Default Decoder (`json.JSONDecoder()`)
|
||||||
|
|
||||||
Convertions (JSON -> Python):
|
Conversions (JSON -> Python):
|
||||||
|
|
||||||
- object -> dict
|
- object -> dict
|
||||||
- array -> list
|
- array -> list
|
||||||
|
@ -78,7 +78,7 @@ Convertions (JSON -> Python):
|
||||||
|
|
||||||
## Default Encoder (`json.JSONEncoder()`)
|
## Default Encoder (`json.JSONEncoder()`)
|
||||||
|
|
||||||
Convertions (Python -> Json):
|
Conversions (Python -> Json):
|
||||||
|
|
||||||
- dict -> object
|
- dict -> object
|
||||||
- list, tuple -> array
|
- list, tuple -> array
|
||||||
|
@ -96,7 +96,7 @@ import json
|
||||||
class ComplexEncoder(json.JSONEncoder):
|
class ComplexEncoder(json.JSONEncoder):
|
||||||
def default(self, obj):
|
def default(self, obj):
|
||||||
if isinstance(obj, complex):
|
if isinstance(obj, complex):
|
||||||
return [obj.real, obj.imag]
|
return [obj.real, obj.image]
|
||||||
# Let the base class default method raise the TypeError
|
# Let the base class default method raise the TypeError
|
||||||
return json.JSONEncoder.default(self, obj)
|
return json.JSONEncoder.default(self, obj)
|
||||||
```
|
```
|
||||||
|
@ -105,6 +105,6 @@ class ComplexEncoder(json.JSONEncoder):
|
||||||
|
|
||||||
```python
|
```python
|
||||||
data = json.loads(json)
|
data = json.loads(json)
|
||||||
data["key"] # retieve the value associated with the key
|
data["key"] # retrieve the value associated with the key
|
||||||
data["outer key"]["nested key"] # nested key value retireval
|
data["outer key"]["nested key"] # nested key value retrieval
|
||||||
```
|
```
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
# Logging Module Cheat Sheet
|
# Logging Module
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
|
@ -41,24 +41,24 @@ logging.disable(level=LOG_LEVEL)
|
||||||
|
|
||||||
| Directive | Meaning |
|
| Directive | Meaning |
|
||||||
|-----------|------------------------------------------------------------------------------------------------------------------------------|
|
|-----------|------------------------------------------------------------------------------------------------------------------------------|
|
||||||
| `%a` | Locale’s abbreviated weekday name. |
|
| `%a` | Locale's abbreviated weekday name. |
|
||||||
| `%A` | Locale’s full weekday name. |
|
| `%A` | Locale's full weekday name. |
|
||||||
| `%b` | Locale’s abbreviated month name. |
|
| `%b` | Locale's abbreviated month name. |
|
||||||
| `%B` | Locale’s full month name. |
|
| `%B` | Locale's full month name. |
|
||||||
| `%c` | Locale’s appropriate date and time representation. |
|
| `%c` | Locale's appropriate date and time representation. |
|
||||||
| `%d` | Day of the month as a decimal number [01,31]. |
|
| `%d` | Day of the month as a decimal number [01,31]. |
|
||||||
| `%H` | Hour (24-hour clock) as a decimal number [00,23]. |
|
| `%H` | Hour (24-hour clock) as a decimal number [00,23]. |
|
||||||
| `%I` | Hour (12-hour clock) as a decimal number [01,12]. |
|
| `%I` | Hour (12-hour clock) as a decimal number [01,12]. |
|
||||||
| `%j` | Day of the year as a decimal number [001,366]. |
|
| `%j` | Day of the year as a decimal number [001,366]. |
|
||||||
| `%m` | Month as a decimal number [01,12]. |
|
| `%m` | Month as a decimal number [01,12]. |
|
||||||
| `%M` | Minute as a decimal number [00,59]. |
|
| `%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]. |
|
| `%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]. |
|
| `%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` | 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]. |
|
| `%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 date representation. |
|
||||||
| `%X` | Locale’s appropriate time representation. |
|
| `%X` | Locale's appropriate time representation. |
|
||||||
| `%y` | Year without century as a decimal number [00,99]. |
|
| `%y` | Year without century as a decimal number [00,99]. |
|
||||||
| `%Y` | Year with century as a decimal number. |
|
| `%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]. |
|
| `%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
|
__ge__(a, b), ge(a, b) # a >= b
|
||||||
__gt__(a, b), gt(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
|
not_(obj)
|
||||||
__abs__(a, b), abs(obj) # valore assoluto di obj
|
truth(obj)
|
||||||
|
is_(a, b)
|
||||||
|
is_not(a, b)
|
||||||
|
|
||||||
|
|
||||||
|
__abs__(a, b), abs(obj)
|
||||||
__add__(a, b), add(a, b) # a + b
|
__add__(a, b), add(a, b) # a + b
|
||||||
__sub__(a, b), sub(a, b) # a - b
|
__sub__(a, b), sub(a, b) # a - b
|
||||||
__mul__(a,b), mul(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
|
__floordiv__(a, b), floordiv(a, b) # return a // b
|
||||||
__mod__(a, b), mod(a, b) # a % b
|
__mod__(a, b), mod(a, b) # a % b
|
||||||
__neg__(obj), neg(obj) # -obj
|
__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)
|
__and__(a, b), and_(a, b) # a & b
|
||||||
__or__(a, b), or_(a, b) # a or b binario (a | b)
|
__or__(a, b), or_(a, b) # a | b
|
||||||
__xor__(a, b), xor(a, b) # a xor b binario (a ^ b)
|
__xor__(a, b), xor(a, b) # a ^ b
|
||||||
|
|
||||||
__inv__(obj), inv(obj), __inverse__(obj), inverse(obj) # inverso binario di obj, ~obj
|
__inv__(obj), inv(obj), __inverse__(obj), inverse(obj) # ~obj
|
||||||
__lshift__(obj), lshift(a, b) # restituisce a spostato a sinistra di b
|
__lshift__(obj), lshift(a, b)
|
||||||
|
|
||||||
__concat__(a, b), concat(a, b) # a + b per sequenze (CONCATENZIONE)
|
__concat__(a, b), concat(a, b)
|
||||||
__contains__(a, b), contains(a, b) # return b in a
|
__contains__(a, b), contains(a, b)
|
||||||
countOf(a, b) # numero occorrenze b in a
|
countOf(a, b)
|
||||||
indexOF(a, b) # restituisce prima occorrenza di b in a
|
indexOf(a, b)
|
||||||
|
|
||||||
__delitem__(a, b), delitem(a, b) # rimuove valore a in posizione b
|
__delitem__(a, b), delitem(a, b)
|
||||||
__getitem__(a, b), getitem(a, b) # restituisce valore a in posizione b
|
__getitem__(a, b), getitem(a, b)
|
||||||
__setitem__(a, b), setitem(a, b) # setta valore a in psoizione b
|
__setitem__(a, b), setitem(a, 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()
|
|
||||||
```
|
|
||||||
|
|
|
@ -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
|
High-level file operations
|
||||||
|
|
||||||
|
@ -18,7 +18,7 @@ shutil.copytree(src, dst, dirs_exist_ok=False)
|
||||||
# or any missing parent directory already exists
|
# or any missing parent directory already exists
|
||||||
|
|
||||||
# delete an entire directory tree
|
# 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
|
# IGNORE_ERROR: {bool} -- if true errors (failed removals) will be ignored
|
||||||
# ON_ERROR: handler for removal errors (if ignore_errors=False or omitted)
|
# 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
|
# create archive file and return its name
|
||||||
shutil.make_archive(base_name, format, [root_dir, base_dir])
|
shutil.make_archive(base_name, format, [root_dir, base_dir])
|
||||||
# BASE_NAME: {string} -- name of the archive, including path, excluding extension
|
# 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)
|
# 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
|
# unpack an archive
|
||||||
shutil.unpack_archive(filename, [extarct_dir, format])
|
shutil.unpack_archive(filename, [extract_dir, format])
|
||||||
# FILENAME: full path of archive
|
# FILENAME: full path of archive
|
||||||
# EXTRACT_DIR: {path} -- directory to unpack into
|
# 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
|
# return disk usage statistics as Namedtuple w/ attributes total, used, free
|
||||||
shutil.disk_usage(path)
|
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.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.SMTPHeloError # The server didn't reply properly to the HELO greeting
|
||||||
SMTP.SMTPAuthenticationError # The server didn’t accept the username/password combination.
|
SMTP.SMTPAuthenticationError # The server didn't accept the username/password combination.
|
||||||
SMTP.SMTPNotSupportedError # The AUTH command is not supported by the server.
|
SMTP.SMTPNotSupportedError # The AUTH command is not supported by the server.
|
||||||
SMTP.SMTPException # No suitable authentication method was found.
|
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
|
# 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
|
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
|
```python
|
||||||
import socket
|
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 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
|
|
||||||
socket.connect = (("URL", port: int)) # connect to socket
|
socket.connect = (("URL", port: int)) # connect to socket
|
||||||
|
@ -23,9 +23,9 @@ socket.close() # close connection
|
||||||
|
|
||||||
```python
|
```python
|
||||||
import socket
|
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
|
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)
|
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
|
### Query Construction
|
||||||
|
|
||||||
Usually your SQL operations will need to use values from Python variables.
|
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
|
```python
|
||||||
# Never do this -- insecure!
|
# Never do this -- insecure!
|
||||||
|
@ -58,7 +59,7 @@ connection.commit()
|
||||||
### Multiple SQL Instructions
|
### Multiple SQL Instructions
|
||||||
|
|
||||||
```python
|
```python
|
||||||
conection = sqlite3.connect("file.db")
|
connection = sqlite3.connect("file.db")
|
||||||
cur = con.cursor()
|
cur = con.cursor()
|
||||||
cur.executescript("""
|
cur.executescript("""
|
||||||
QUERY_1;
|
QUERY_1;
|
||||||
|
@ -74,7 +75,7 @@ con.close()
|
||||||
|
|
||||||
```python
|
```python
|
||||||
# Fetches the next row of a query result set, returning a single sequence.
|
# 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()
|
cursor.fetchone()
|
||||||
|
|
||||||
# Fetches all (remaining) rows of a query result, returning a list.
|
# Fetches all (remaining) rows of a query result, returning a list.
|
||||||
|
@ -86,7 +87,7 @@ cursor.fetchall()
|
||||||
fetchmany(size=cursor.arraysize)
|
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.
|
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.
|
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
|
## Time
|
||||||
|
|
||||||
|
@ -6,7 +6,7 @@
|
||||||
# epoch: tempo in secondi trascorso (in UNIX parte da 01-010-1970)
|
# epoch: tempo in secondi trascorso (in UNIX parte da 01-010-1970)
|
||||||
import time # UNIX time
|
import time # UNIX time
|
||||||
variabile = time.time() # restituisce il tempo (In secondi) trascorso da 01-01-1970
|
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
|
var = time.perf_counter() # ritorna il tempo di esecuzione attuale
|
||||||
# tempo di esecuzione = tempo inizio - tempo fine
|
# tempo di esecuzione = tempo inizio - tempo fine
|
||||||
|
@ -16,24 +16,24 @@ var = time.perf_counter() # ritorna il tempo di esecuzione attuale
|
||||||
|
|
||||||
| Format | Data |
|
| Format | Data |
|
||||||
|--------|------------------------------------------------------------------------------------------------------------|
|
|--------|------------------------------------------------------------------------------------------------------------|
|
||||||
| `%a` | Locale’s abbreviated weekday name. |
|
| `%a` | Locale's abbreviated weekday name. |
|
||||||
| `%A` | Locale’s full weekday name. |
|
| `%A` | Locale's full weekday name. |
|
||||||
| `%b` | Locale’s abbreviated month name. |
|
| `%b` | Locale's abbreviated month name. |
|
||||||
| `%B` | Locale’s full month name. |
|
| `%B` | Locale's full month name. |
|
||||||
| `%c` | Locale’s appropriate date and time representation. |
|
| `%c` | Locale's appropriate date and time representation. |
|
||||||
| `%d` | Day of the month as a decimal number `[01,31]`. |
|
| `%d` | Day of the month as a decimal number `[01,31]`. |
|
||||||
| `%H` | Hour (24-hour clock) as a decimal number `[00,23]`. |
|
| `%H` | Hour (24-hour clock) as a decimal number `[00,23]`. |
|
||||||
| `%I` | Hour (12-hour clock) as a decimal number `[01,12]`. |
|
| `%I` | Hour (12-hour clock) as a decimal number `[01,12]`. |
|
||||||
| `%j` | Day of the year as a decimal number `[001,366]`. |
|
| `%j` | Day of the year as a decimal number `[001,366]`. |
|
||||||
| `%m` | Month as a decimal number `[01,12]`. |
|
| `%m` | Month as a decimal number `[01,12]`. |
|
||||||
| `%M` | Minute as a decimal number `[00,59]`. |
|
| `%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]`. |
|
| `%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]`. |
|
| `%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` | 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]`. |
|
| `%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 date representation. |
|
||||||
| `%X` | Locale’s appropriate time representation. |
|
| `%X` | Locale's appropriate time representation. |
|
||||||
| `%y` | Year without century as a decimal number `[00,99]`. |
|
| `%y` | Year without century as a decimal number `[00,99]`. |
|
||||||
| `%Y` | Year with century as a decimal number. |
|
| `%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 |
|
| `%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
|
today = datetime.datetime.today() # restituisce la data e l'ora corrente
|
||||||
|
|
||||||
# esempio di formattazione
|
# 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))
|
print('Current Time: {}:{}.{}' .format(today.hour, today.minute, today.second))
|
||||||
|
|
||||||
var_1 = datetime.date(anno, mese, giorno) # crea oggetto data
|
var_1 = datetime.date(anno, mese, giorno) # crea oggetto data
|
||||||
var_2 = datetime.time(ora, minuti, secondi, micro-secondi) # crea oggetto tempo
|
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
|
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')
|
date_2 = date_1.replace(year = 'new_year')
|
||||||
|
|
||||||
#DATETIME ARITHMETIC
|
#DATETIME ARITHMETIC
|
||||||
|
|
|
@ -1,16 +1,12 @@
|
||||||
# Unittest Module
|
# Unittest Module
|
||||||
|
|
||||||
Permette di testare il propio codice e controllare se l'output corrisponde a quello desiderato.
|
|
||||||
|
|
||||||
```py
|
```py
|
||||||
import unittest
|
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):
|
def test_1(self):
|
||||||
# code here
|
|
||||||
self.assert*(output, expected_output)
|
self.assert*(output, expected_output)
|
||||||
|
|
||||||
if __name__ == '__main__':
|
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
Reference in a new issue