├── lectures ├── Makefile ├── python │ ├── 02_symbols │ │ ├── my_package │ │ │ ├── bar_module.py │ │ │ ├── foo_module.py │ │ │ └── __init__.py │ │ ├── my_module.py │ │ ├── 04_global_local.ipynb │ │ ├── 05_closures.ipynb │ │ ├── 03_copy_deepcopy.ipynb │ │ ├── 06_nasty_bugs.ipynb │ │ └── 07_classes.ipynb │ ├── 03_advanced_topics │ │ ├── sequence.py │ │ ├── my_module.py │ │ ├── test_sequence.py │ │ ├── 08_testing.ipynb │ │ ├── 07_context_manager.ipynb │ │ ├── 02_property.ipynb │ │ └── 06_generators.ipynb │ └── 01_intro │ │ └── 06_sets.ipynb └── c++ │ ├── 08_STL │ └── presentation │ │ ├── img │ │ ├── alex.jpg │ │ ├── list.png │ │ ├── map.png │ │ ├── alex.jpeg │ │ ├── alex2.jpeg │ │ ├── array.png │ │ ├── head_01.png │ │ ├── head_02.png │ │ ├── head_03.png │ │ ├── head_04.png │ │ ├── head_05.png │ │ ├── head_06.png │ │ ├── head_07.png │ │ ├── head_08.png │ │ ├── head_09.png │ │ ├── head_10.png │ │ ├── head_11.png │ │ ├── head_12.png │ │ ├── members.png │ │ ├── ordered.png │ │ ├── summary.png │ │ ├── vector.png │ │ ├── alexfest.jpg │ │ ├── iterators.png │ │ ├── unordered.png │ │ ├── arithmetic.png │ │ ├── blackboard.png │ │ ├── complexity.png │ │ ├── forward_list.png │ │ ├── mhpc-logo2.pdf │ │ ├── predicates.png │ │ ├── sissa_logo.jpg │ │ ├── sissa_logo.png │ │ ├── stroustrup.jpg │ │ ├── unordered_map.png │ │ └── sequence_containers.png │ │ ├── stl_intro.pdf │ │ ├── tex_files │ │ ├── Makefile │ │ ├── function_objects.tex │ │ ├── iterators.tex │ │ ├── algorithms.tex │ │ ├── containers.tex │ │ └── summary.tex │ │ ├── Makefile │ │ ├── beamerthemenasatalk.sty │ │ ├── beamerouterthemenasalines.sty │ │ └── stl_intro.tex │ ├── 07_inheritance │ ├── iostream_hierarchy.png │ ├── exceptions_hierarchy.png │ ├── organized │ │ ├── src │ │ │ ├── helper_functions.cpp │ │ │ ├── dog.cpp │ │ │ ├── animal.cpp │ │ │ └── snake.cpp │ │ ├── include │ │ │ ├── helper_functions.h │ │ │ ├── dog.h │ │ │ ├── animal.h │ │ │ └── snake.h │ │ ├── main.cpp │ │ └── Makefile │ ├── 06_template.cpp │ ├── 07_using.cpp │ ├── 03_virtual_destructor.cpp │ ├── Makefile │ ├── 02_virtual.cpp │ ├── 00_first_trial.cpp │ ├── 01_inheritance.cpp │ ├── 05_dynamic_cast.cpp │ ├── 04_private.cpp │ └── readme.md │ ├── 04_custom_types │ ├── 04_why_scoped.cpp │ ├── 01_enum.cpp │ ├── 06_operator_overloading.cpp │ ├── Makefile │ ├── 02_scoped_enum.cpp │ ├── 03_namespace.cpp │ ├── 05_struct_class.cpp │ ├── 08_template_class.cpp │ ├── 07_constructor_destructor.cpp │ └── readme.md │ ├── Makefile │ ├── 01_intro │ ├── 02_hello_name.cc │ ├── 06_watch_out.cc │ ├── Makefile │ ├── 04_vars_pointers_refs.cc │ ├── 05_functions.cc │ ├── 03_loops.cc │ ├── readme.md │ └── 01_variables.cc │ ├── 06_error_handling │ ├── 00_errno.cpp │ ├── Makefile │ ├── 04_assert.cpp │ ├── 02_exceptions.cpp │ ├── 01_exceptions.cpp │ ├── 06_smart_pointers.cpp │ ├── 03_error.cpp │ ├── 05_stack_unwinding.cpp │ └── readme.md │ ├── 03_more_on_pointers_and_vectors │ ├── 03_command_line_args.cpp │ ├── 01_const_and_pointers.cpp │ ├── Makefile │ ├── 06_std_vectors.cpp │ ├── 04_matrices.cpp │ ├── 05_std_arrays.cpp │ ├── readme.md │ └── 02_special_pointers.cpp │ ├── 02_functions_and_arrays │ ├── 06_dynamic_arrays.cpp │ ├── 04_templates.cpp │ ├── 02_functions.cpp │ ├── 01_auto.cpp │ ├── Makefile │ ├── 03_overloading.cpp │ ├── 05_static_arrays.cpp │ └── readme.md │ └── 05_copy_move_semantics │ ├── 01_surprise.cpp │ ├── Makefile │ ├── 05_buggy_vector.cpp │ ├── 02_default.cpp │ ├── 03_default.cpp │ ├── 04_buggy_vector.cpp │ ├── readme.md │ └── 06_copy_move.cpp ├── exam ├── .aux │ └── binary.png ├── test_exam.py └── python_exam.ipynb ├── exercises ├── c++ │ ├── 05_copy_move │ │ ├── .aux │ │ │ └── list2.png │ │ └── readme.md │ ├── 03_arrays_and_vectors │ │ ├── temperatures.txt │ │ └── readme.md │ ├── 01_intro │ │ └── readme.md │ ├── 04_custom_types │ │ ├── multiple_flags.cpp │ │ └── readme.md │ ├── 02_arrays │ │ └── readme.md │ └── vector │ │ ├── as_vector.cpp │ │ ├── as_vector_malloc.cpp │ │ └── as_vector_allocator.cpp └── python │ ├── 03_advanced │ └── readme.md │ └── 02_symbols │ └── readme.md ├── .travis.yml ├── Makefile └── readme.md /lectures/Makefile: -------------------------------------------------------------------------------- 1 | %: 2 | +$(MAKE) $@ -C c++ 3 | -------------------------------------------------------------------------------- /lectures/python/02_symbols/my_package/bar_module.py: -------------------------------------------------------------------------------- 1 | def bar(): 2 | print('Barring from a package') 3 | -------------------------------------------------------------------------------- /lectures/python/02_symbols/my_package/foo_module.py: -------------------------------------------------------------------------------- 1 | def foo(): 2 | print('Fooing from a package') 3 | -------------------------------------------------------------------------------- /exam/.aux/binary.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/exam/.aux/binary.png -------------------------------------------------------------------------------- /lectures/python/02_symbols/my_module.py: -------------------------------------------------------------------------------- 1 | def foo(): 2 | print('Fooing') 3 | 4 | def bar(): 5 | print('Barring') 6 | -------------------------------------------------------------------------------- /exercises/c++/05_copy_move/.aux/list2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/exercises/c++/05_copy_move/.aux/list2.png -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/alex.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/alex.jpg -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/list.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/list.png -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/map.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/map.png -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/alex.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/alex.jpeg -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/alex2.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/alex2.jpeg -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/array.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/array.png -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/head_01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/head_01.png -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/head_02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/head_02.png -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/head_03.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/head_03.png -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/head_04.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/head_04.png -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/head_05.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/head_05.png -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/head_06.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/head_06.png -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/head_07.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/head_07.png -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/head_08.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/head_08.png -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/head_09.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/head_09.png -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/head_10.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/head_10.png -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/head_11.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/head_11.png -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/head_12.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/head_12.png -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/members.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/members.png -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/ordered.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/ordered.png -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/summary.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/summary.png -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/vector.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/vector.png -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/stl_intro.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/stl_intro.pdf -------------------------------------------------------------------------------- /lectures/c++/07_inheritance/iostream_hierarchy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/07_inheritance/iostream_hierarchy.png -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/alexfest.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/alexfest.jpg -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/iterators.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/iterators.png -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/unordered.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/unordered.png -------------------------------------------------------------------------------- /lectures/c++/07_inheritance/exceptions_hierarchy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/07_inheritance/exceptions_hierarchy.png -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/arithmetic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/arithmetic.png -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/blackboard.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/blackboard.png -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/complexity.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/complexity.png -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/forward_list.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/forward_list.png -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/mhpc-logo2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/mhpc-logo2.pdf -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/predicates.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/predicates.png -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/sissa_logo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/sissa_logo.jpg -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/sissa_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/sissa_logo.png -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/stroustrup.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/stroustrup.jpg -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/unordered_map.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/unordered_map.png -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/tex_files/Makefile: -------------------------------------------------------------------------------- 1 | all: 2 | +$(MAKE) $@ -C ../ 3 | 4 | clean: 5 | rm -f *~ 6 | 7 | %: 8 | +$(MAKE) $@ -C ../ 9 | 10 | .PHONY: all clean 11 | -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/img/sequence_containers.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asartori86/advanced_programming_2020/HEAD/lectures/c++/08_STL/presentation/img/sequence_containers.png -------------------------------------------------------------------------------- /lectures/c++/07_inheritance/organized/src/helper_functions.cpp: -------------------------------------------------------------------------------- 1 | #include "helper_functions.h" 2 | 3 | void print_animal(const Animal& a) noexcept { 4 | std::cout << "throught ref\n"; 5 | a.info(); 6 | a.speak(); 7 | } 8 | -------------------------------------------------------------------------------- /lectures/c++/04_custom_types/04_why_scoped.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | enum month { jan = 1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec }; 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | cout << nov << endl; 9 | // cout << dec << endl; 10 | 11 | return 0; 12 | } 13 | -------------------------------------------------------------------------------- /lectures/c++/Makefile: -------------------------------------------------------------------------------- 1 | %: 2 | +$(MAKE) $@ -C 01_intro 3 | +$(MAKE) $@ -C 02_functions_and_arrays 4 | +$(MAKE) $@ -C 03_more_on_pointers_and_vectors 5 | +$(MAKE) $@ -C 04_custom_types 6 | +$(MAKE) $@ -C 05_copy_move_semantics 7 | +$(MAKE) $@ -C 06_error_handling 8 | +$(MAKE) $@ -C 07_inheritance 9 | 10 | -------------------------------------------------------------------------------- /lectures/c++/01_intro/02_hello_name.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | std::cout << "Insert your name and age:\n"; 6 | std::string name; 7 | unsigned int age; 8 | std::cin >> name >> age; 9 | std::cout << "Hello, " << name << " [" << age << "]\n"; 10 | return 0; 11 | } 12 | -------------------------------------------------------------------------------- /lectures/c++/07_inheritance/organized/src/dog.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // void Dog::speak() const noexcept override{ don't repeat override 5 | void Dog::speak() const noexcept { 6 | std::cout << "Bau\n"; 7 | } 8 | 9 | Dog::Dog(const unsigned int a, const double d) : Animal{a, d} {} 10 | -------------------------------------------------------------------------------- /lectures/c++/07_inheritance/organized/include/helper_functions.h: -------------------------------------------------------------------------------- 1 | #ifndef __ap_helper 2 | #define __ap_helper 3 | 4 | #include 5 | #include 6 | 7 | /** 8 | * print Animal's details. It calls Animal::info() and Animal::speak() 9 | */ 10 | void print_animal(const Animal& a) noexcept; 11 | 12 | #endif 13 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: cpp 3 | 4 | addons: 5 | apt: 6 | sources: 7 | - llvm-toolchain-precise-3.8 8 | - ubuntu-toolchain-r-test 9 | packages: 10 | - g++-6 11 | - clang-3.8 12 | 13 | env: 14 | - COMPILER=g++-6 15 | - COMPILER=clang++-3.8 16 | 17 | script: 18 | - make CXX=$COMPILER 19 | -------------------------------------------------------------------------------- /lectures/c++/06_error_handling/00_errno.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | double d = std::sqrt(4); 6 | std::cout << d << " " << errno << std::endl; 7 | 8 | d = std::sqrt(-4); 9 | std::cout << d << " " << errno << std::endl; 10 | 11 | d = 0; 12 | 13 | errno = 0; 14 | 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /lectures/c++/07_inheritance/06_template.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | template 4 | struct Base { 5 | void foo() const { std::cout << "base foo" << std::endl; } 6 | }; 7 | 8 | template 9 | struct Derived : public Base { 10 | void bar() const { this->foo(); } 11 | }; 12 | 13 | int main() { 14 | Derived d; 15 | d.bar(); 16 | } 17 | -------------------------------------------------------------------------------- /lectures/c++/07_inheritance/07_using.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct foo { 4 | void f(int x) { std::cout << "int " << x << std::endl; } 5 | }; 6 | 7 | struct bar : public foo { 8 | using foo::f; // brings all foo::f to this scope 9 | void f(char x) { std::cout << "char " << x << std::endl; } 10 | }; 11 | 12 | int main() { 13 | bar b; 14 | b.f(33); 15 | } 16 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Simple Makefile to compile, clean and format all the sample codes 2 | # provided during the course of Advanced Programming 3 | 4 | default: all 5 | 6 | all: 7 | +$(MAKE) $@ -C lectures 8 | 9 | clean: 10 | +$(MAKE) $@ -C lectures 11 | @find . -type f \( -name '*~' -o -name 'a.out' \) -exec rm '{}' \; 12 | 13 | format: 14 | +$(MAKE) $@ -C lectures 15 | 16 | .PHONY: all clean format default 17 | -------------------------------------------------------------------------------- /lectures/c++/03_more_on_pointers_and_vectors/03_command_line_args.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(int argc, char* argv[]) { 5 | for (auto i = 0; i < argc; ++i) 6 | std::cout << "argv[" << i << "] = " << argv[i] << std::endl; 7 | 8 | unsigned int a; 9 | { 10 | std::istringstream s{argv[1]}; 11 | s >> a; 12 | } 13 | std::cout << "a is " << a << std::endl; 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /lectures/python/02_symbols/my_package/__init__.py: -------------------------------------------------------------------------------- 1 | # it must be present 2 | 3 | # can be empty 4 | 5 | # or set the __all__ variable, which overrides * 6 | 7 | # __all__=['foo_module','bar_module'] 8 | # __all__=['foo_module'] 9 | 10 | # if the __all__ variable contains all the modules 11 | # do not define it 12 | 13 | 14 | # import my_package.bar_module 15 | 16 | # # from .bar_module import bar 17 | # from my_package.foo_module import foo -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/Makefile: -------------------------------------------------------------------------------- 1 | TARGET = stl_intro 2 | 3 | all: compile clean 4 | 5 | compile: 6 | pdflatex $(TARGET) 7 | pdflatex $(TARGET) 8 | 9 | clean: 10 | rm -f *.bbl *.log *.lot *.toc *.out *.blg *.aux *.lof *.nav *.snm *.vrb *~ 11 | +$(MAKE) $@ -C tex_files 12 | 13 | quick: 14 | pdflatex $(TARGET) 15 | 16 | open: 17 | xdg-open $(TARGET).pdf & 18 | 19 | distclean: clean 20 | rm -f $(TARGET).pdf 21 | 22 | .PHONY: all compile clean quick open distclean 23 | 24 | -------------------------------------------------------------------------------- /lectures/c++/02_functions_and_arrays/06_dynamic_arrays.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | std::cout << "Please insert array lenght: "; 5 | std::size_t n; 6 | std::cin >> n; 7 | int* da{new int[n]}; // allocated on the HEAP, or free-store 8 | 9 | for (std::size_t i{0}; i < n; ++i) 10 | da[i] = i * 10; 11 | 12 | for (std::size_t i{0}; i < n; ++i) 13 | std::cout << "da[" << i << "] = " << da[i] << std::endl; 14 | 15 | delete[] da; 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /lectures/c++/07_inheritance/03_virtual_destructor.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct Base { 4 | Base() { std::cout << "Base\n"; } 5 | ~Base() { std::cout << "~Base\n"; } 6 | }; 7 | 8 | struct Derived : public Base { 9 | Derived() { std::cout << "Derived\n"; } 10 | ~Derived() { std::cout << "~Derived\n"; } 11 | }; 12 | 13 | int main() { 14 | { Derived d; } 15 | 16 | std::cout << "\n\npointers\n"; 17 | Base* p = new Derived; 18 | delete p; 19 | 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /lectures/c++/07_inheritance/organized/src/animal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | Animal::Animal() : Animal{0, 0} {} 5 | 6 | Animal::Animal(const unsigned int a, const double w) : age{a}, weight{w} { 7 | AP_ERROR_GE(w, 0) << "invalid weight"; 8 | } 9 | 10 | // virtual Animal::info() const noexcept{ would be error: do not repeat 11 | // virtual 12 | void Animal::info() const noexcept { 13 | std::cout << "age:\t" << age << '\n' << "weight:\t" << weight << '\n'; 14 | } 15 | -------------------------------------------------------------------------------- /lectures/c++/07_inheritance/organized/src/snake.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | Snake::Snake(const unsigned int a, const double w, const bool b) 5 | : Animal{a, w}, dangerous{b} {} 6 | 7 | // do not repeat explicit here 8 | Snake::Snake(const bool b) : Animal{}, dangerous{b} {} 9 | 10 | void Snake::info() const noexcept { 11 | Animal::info(); 12 | std::cout << "dangerous:\t" << (dangerous ? "true" : "false") << std::endl; 13 | } 14 | 15 | void Snake::speak() const noexcept { 16 | std::cout << "ssss\n"; 17 | } 18 | -------------------------------------------------------------------------------- /exercises/python/03_advanced/readme.md: -------------------------------------------------------------------------------- 1 | # Exercises 03 2 | 3 | ### myrange 4 | 5 | - implement `myrange` that acts like `range` 6 | - define a function `myrange` 7 | - define a class `MyRange` 8 | 9 | 10 | Remember to `raise` the right exception if too few (or too many) arguments are passed. 11 | 12 | 13 | ### Context Manager 14 | 15 | - Implement a Timer that exploiting `__enter__` and `__exit__` is able to measure the time spent in a portion of python code. 16 | 17 | ### Unittest 18 | 19 | - write several tests to test `range` and `MyRange` 20 | 21 | -------------------------------------------------------------------------------- /lectures/c++/02_functions_and_arrays/04_templates.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | template 4 | T dwim(const T a, const T b); 5 | 6 | int main() { 7 | int a{5}, b{7}; 8 | double c{3.332}, d{7.7}; 9 | float e{23.4}, f{3.34e2}; 10 | char g{'0'}, h{'6'}; 11 | 12 | std::cout << dwim(a, b) << '\n' 13 | << dwim(c, d) << '\n' 14 | << dwim(e, f) << '\n' 15 | << dwim(g, h) << std::endl; 16 | return 0; 17 | } 18 | 19 | template 20 | T dwim(const T a, const T b) { 21 | return a + b; 22 | } 23 | -------------------------------------------------------------------------------- /lectures/c++/05_copy_move_semantics/01_surprise.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct X { 4 | char member; 5 | }; 6 | 7 | int main() { 8 | X x1; // default ctor 9 | X x2{x1}; // copy ctor 10 | X x3{std::move(x2)}; // move ctor 11 | X x4{}; // default ctor calling {} to each member 12 | x4 = x3; // copy assignment 13 | X x5; // default ctor 14 | x5 = std::move(x4); // move assignment 15 | std::cout << x5.member << std::endl; // what do you expect?? 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /lectures/c++/01_intro/06_watch_out.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | // size matters! 6 | int a = 1; 7 | for (int i = 0; i < 33; ++i) { 8 | a *= 2; 9 | std::cout << a << std::endl; 10 | } 11 | 12 | // never ever use == (or !=) with floating point numbers 13 | 14 | // for (double d = 0.1; d != 1.0; d += 0.1) 15 | // std::cout << d << std::endl; 16 | 17 | // std::cout << std::setprecision(50); 18 | // double d = 0; 19 | // for (int i = 0; i < 10; ++i) { 20 | // d += 0.1; 21 | // std::cout << d << std::endl; 22 | // } 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /lectures/c++/07_inheritance/organized/include/dog.h: -------------------------------------------------------------------------------- 1 | #ifndef __ap_dog 2 | #define __ap_dog 3 | 4 | #include 5 | 6 | /** 7 | * Specialization of class Animal. It simply overrides the function speak. 8 | */ 9 | class Dog : public Animal { 10 | public: 11 | /** 12 | * A dog usually says "Bau" 13 | */ 14 | void speak() const noexcept override; 15 | /** 16 | * Default constructor is fine. It will call the default constructor 17 | * of Animal. 18 | */ 19 | Dog() = default; 20 | 21 | /** 22 | * Delegating constructor to build an Animal{a,b} 23 | */ 24 | Dog(const unsigned int a, const double d); 25 | }; 26 | 27 | #endif 28 | -------------------------------------------------------------------------------- /lectures/c++/02_functions_and_arrays/02_functions.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | auto factorial(unsigned int n) { 4 | unsigned int ret{1}; 5 | while (n > 1) { 6 | ret *= n; 7 | --n; 8 | 9 | // or "simply" 10 | // ret *= n--; 11 | } 12 | return ret; 13 | } 14 | 15 | int main() { 16 | unsigned int f5{factorial(5)}; 17 | 18 | auto f6 = factorial(6); 19 | 20 | std::cout << "factorial of 5 is " << f5 << '\n' 21 | << "factorial of 6 is " << f6 << std::endl; 22 | 23 | // errors 24 | // factorial(); // too few args 25 | // factorial(3,4,5,5); // too many args 26 | // factorial("byobu"); // wrong type 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /lectures/c++/02_functions_and_arrays/01_auto.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | auto b = true; // a bool 6 | auto ch = 'x'; // a char 7 | auto i = 123; // an int 8 | auto d = 1.2; // a double 9 | auto z = std::sqrt(d); // z has the type of whatever sqrt(d) returns 10 | auto ui = 0u; // unsigned int 11 | auto llui = 0llu; // long long unsigned int 12 | 13 | auto& j = i; // int& 14 | 15 | for (auto i = 0; i < 7; ++i) 16 | std::cout << i << std::endl; 17 | 18 | auto pb = &b; // guess what.. How can I know? 19 | 20 | auto s = "hello"; // watch out! 21 | 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /lectures/c++/07_inheritance/organized/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main() { 7 | try { 8 | Python s; 9 | s.info(); 10 | s.speak(); 11 | 12 | std::cout << std::endl; 13 | 14 | // Animal* p = new DangerousSnake{1, 2.3}; 15 | Animal* p = new Anaconda{1, 2.3}; 16 | 17 | std::cout << "through pointer\n"; 18 | p->info(); 19 | p->speak(); 20 | 21 | delete p; 22 | 23 | std::cout << std::endl; 24 | 25 | print_animal(s); 26 | 27 | return 0; 28 | } catch (std::runtime_error& e) { 29 | std::cerr << e.what() << std::endl; 30 | return 1; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /exercises/c++/03_arrays_and_vectors/temperatures.txt: -------------------------------------------------------------------------------- 1 | 49.49 2 | 43.29478 3 | 9.18310 4 | 1.25426 5 | 31.11884 6 | 17.17143 7 | 25.32008 8 | 28.18118 9 | 18.32374 10 | 28.30987 11 | 15.20080 12 | 34.22997 13 | 42.22004 14 | 8.5524 15 | 36.17551 16 | 22.10146 17 | 20.13939 18 | 37.14999 19 | 17.19778 20 | 41.26524 21 | 32.10188 22 | 40.2751 23 | 19.10367 24 | 9.28040 25 | 9.25547 26 | 11.31013 27 | 25.3343 28 | 13.6814 29 | 17.13339 30 | 36.11118 31 | 17.3957 32 | 26.31245 33 | 30.15994 34 | 40.31343 35 | 16.20671 36 | 25.549 37 | 16.3368 38 | 40.5604 39 | 42.30077 40 | 2.4097 41 | 14.30421 42 | 6.14514 43 | 38.1082 44 | 43.18149 45 | 36.11233 46 | 18.24570 47 | 15.23786 48 | 26.22972 49 | 35.29985 50 | 20.9195 51 | -------------------------------------------------------------------------------- /lectures/c++/01_intro/Makefile: -------------------------------------------------------------------------------- 1 | CXX = c++ 2 | CXXFLAGS = -Wall -Wextra -g -std=c++11 3 | 4 | SRC = 01_variables.cc \ 5 | 02_hello_name.cc \ 6 | 03_loops.cc \ 7 | 04_vars_pointers_refs.cc \ 8 | 05_functions.cc \ 9 | 06_watch_out.cc 10 | 11 | EXE = $(SRC:.cc=.x) 12 | 13 | # eliminate default suffixes 14 | .SUFFIXES: 15 | SUFFIXES = 16 | 17 | # just consider our own suffixes 18 | .SUFFIXES: .cc .x 19 | 20 | all: $(EXE) 21 | 22 | .PHONY: all 23 | 24 | %.x: %.cc 25 | $(CXX) $< -o $@ $(CXXFLAGS) 26 | 27 | format: $(SRC) 28 | @clang-format -i $^ 2>/dev/null || echo "Please install clang-format to run this command" 29 | 30 | .PHONY: format 31 | 32 | clean: 33 | rm -f $(EXE) *~ 34 | 35 | .PHONY: clean 36 | -------------------------------------------------------------------------------- /lectures/c++/01_intro/04_vars_pointers_refs.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | double d = 9.9; 5 | double& ref = d; 6 | double* ptr = &d; 7 | std::cout << "value of d: " << d << std::endl; 8 | std::cout << "value of ref: " << ref << std::endl; 9 | std::cout << "value of ptr: " << ptr << std::endl << std::endl; 10 | 11 | std::cout << "address of d: " << &d << std::endl; 12 | std::cout << "address of ref: " << &ref << std::endl; 13 | std::cout << "address of ptr: " << &ptr << std::endl << std::endl; 14 | 15 | // the value of variable d can be changed through either ref or 16 | // ptr as follows 17 | ref = 7.7; 18 | std::cout << "value of d: " << d << std::endl; 19 | 20 | *ptr = 5.5; 21 | std::cout << "value of d: " << d << std::endl; 22 | } 23 | -------------------------------------------------------------------------------- /lectures/c++/05_copy_move_semantics/Makefile: -------------------------------------------------------------------------------- 1 | SRC = 01_surprise.cpp \ 2 | 02_default.cpp \ 3 | 03_default.cpp \ 4 | 04_buggy_vector.cpp \ 5 | 05_buggy_vector.cpp \ 6 | 06_copy_move.cpp 7 | 8 | CXX = c++ 9 | CXXFLAGS = -Wall -Wextra -g -std=c++14 10 | 11 | EXE = $(SRC:.cpp=.x) 12 | 13 | # eliminate default suffixes 14 | .SUFFIXES: 15 | SUFFIXES = 16 | 17 | # just consider our own suffixes 18 | .SUFFIXES: .cpp .x 19 | 20 | all: $(EXE) 21 | 22 | .PHONY: all 23 | 24 | %.x: %.cpp 25 | $(CXX) $< -o $@ $(CXXFLAGS) 26 | 27 | format: $(SRC) 28 | @clang-format -i $^ -verbose || echo "Please install clang-format to run this command" 29 | 30 | .PHONY: format 31 | 32 | clean: 33 | rm -f $(EXE) *~ 34 | 35 | .PHONY: clean 36 | 37 | 01_surprise.x: CXXFLAGS += -Wno-uninitialized 38 | -------------------------------------------------------------------------------- /lectures/c++/02_functions_and_arrays/Makefile: -------------------------------------------------------------------------------- 1 | SRC = 01_auto.cpp \ 2 | 02_functions.cpp \ 3 | 03_overloading.cpp \ 4 | 04_templates.cpp \ 5 | 05_static_arrays.cpp \ 6 | 06_dynamic_arrays.cpp 7 | 8 | CXX = c++ 9 | CXXFLAGS = -Wall -Wextra -g -std=c++14 10 | 11 | EXE = $(SRC:.cpp=.x) 12 | 13 | # eliminate default suffixes 14 | .SUFFIXES: 15 | SUFFIXES = 16 | 17 | # just consider our own suffixes 18 | .SUFFIXES: .cpp .x 19 | 20 | all: $(EXE) 21 | 22 | .PHONY: all 23 | 24 | %.x: %.cpp 25 | $(CXX) $< -o $@ $(CXXFLAGS) 26 | 27 | format: $(SRC) 28 | @clang-format -i $^ -verbose || echo "Please install clang-format to run this command" 29 | 30 | .PHONY: format 31 | 32 | clean: 33 | rm -f $(EXE) *~ 34 | 35 | .PHONY: clean 36 | 37 | 01_auto.x : CXXFLAGS+=-Wno-unused-variable 38 | -------------------------------------------------------------------------------- /lectures/c++/03_more_on_pointers_and_vectors/01_const_and_pointers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | template 4 | void print_sentinel(const T* a, const std::size_t l); 5 | 6 | int main() { 7 | int a{8}, b{7}; 8 | int* pi{&a}; 9 | 10 | const int* pc{&a}; 11 | // *pc = 7; // error 12 | a = 15; // I can obviously change a 13 | 14 | int* const cp{&a}; 15 | a = b; 16 | *cp = 33; 17 | // cp = &b; // error 18 | 19 | const int* const cpc{&a}; 20 | 21 | // *cpc = 0; // error 22 | // cpc = &n; // error 23 | a = 99; 24 | 25 | int aa[4]{}; 26 | print_sentinel(aa, 4); 27 | 28 | return 0; 29 | } 30 | 31 | template 32 | void print_sentinel(const T* a, const std::size_t l) { 33 | const T* const end{a + l}; 34 | for (; a != end; ++a) 35 | std::cout << *a << std::endl; 36 | } 37 | -------------------------------------------------------------------------------- /lectures/c++/02_functions_and_arrays/03_overloading.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // forward declaration 4 | int dwim(const int a, const int b); 5 | double dwim(const double a, const double b); 6 | float dwim(const float a, const float b); 7 | 8 | int main() { 9 | int a{5}, b{7}; 10 | double c{3.332}, d{7.7}; 11 | float e{23.4}, f{3.34e2}; 12 | 13 | std::cout << dwim(a, b) << '\n' 14 | << dwim(c, d) << '\n' 15 | << dwim(e, f) << std::endl; 16 | return 0; 17 | } 18 | 19 | int dwim(const int a, const int b) { 20 | std::cout << "int ------ "; 21 | return a + b; 22 | } 23 | 24 | double dwim(const double a, const double b) { 25 | std::cout << "double --- "; 26 | return a + b; 27 | } 28 | 29 | float dwim(const float a, const float b) { 30 | std::cout << "float ---- "; 31 | return a + b; 32 | } 33 | -------------------------------------------------------------------------------- /lectures/c++/01_intro/05_functions.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void buggy_swap(int a, int b); 4 | void swap_c(int* a, int* b); 5 | void swap_cxx(int& a, int& b); 6 | 7 | int main() { 8 | int a = 3; 9 | int b = {7}; 10 | buggy_swap(a, b); 11 | std::cout << "buggy:\texpected 7 3 --> " << a << " " << b << "\n"; 12 | 13 | a = 3; 14 | b = 7; 15 | swap_c(&a, &b); 16 | std::cout << "c:\texpected 7 3 --> " << a << " " << b << "\n"; 17 | 18 | a = 3; 19 | b = 7; 20 | swap_cxx(a, b); 21 | std::cout << "cxx:\texpected 7 3 --> " << a << " " << b << "\n"; 22 | } 23 | 24 | void buggy_swap(int a, int b) { 25 | int tmp = b; 26 | b = a; 27 | a = tmp; 28 | } 29 | 30 | void swap_c(int* a, int* b) { 31 | int tmp = *b; 32 | *b = *a; 33 | *a = tmp; 34 | } 35 | 36 | void swap_cxx(int& a, int& b) { 37 | int tmp = b; 38 | b = a; 39 | a = tmp; 40 | } 41 | -------------------------------------------------------------------------------- /lectures/python/03_advanced_topics/sequence.py: -------------------------------------------------------------------------------- 1 | 2 | class Sequence(): 3 | 4 | def __init__(self, an_iterable): 5 | self.l = list(an_iterable) 6 | 7 | def __repr__(self): 8 | return f'{self.__class__.__name__}({self.l!r})' 9 | 10 | def __len__(self): 11 | return len(self.l) 12 | 13 | def __eq__(self,other): 14 | return self.l == other.l 15 | 16 | def __getitem__(self,key): 17 | return self.l[key] 18 | 19 | def __setitem__(self,key,item): 20 | self.l[key] = item 21 | 22 | def __delitem__(self,key): 23 | del self.l[key] 24 | 25 | def __iter__(self): 26 | return iter(self.l) 27 | 28 | def insert(self,position,value): 29 | return self.l.insert(position,value) 30 | 31 | def append(self,value): 32 | return self.l.append(value) 33 | -------------------------------------------------------------------------------- /lectures/c++/05_copy_move_semantics/05_buggy_vector.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | template 5 | class Vector { 6 | std::unique_ptr elem; 7 | std::size_t _size; 8 | 9 | public: 10 | explicit Vector(const std::size_t length) 11 | : elem{new T[length]{}}, _size{length} {} 12 | 13 | const T& operator[](const std::size_t& i) const { return elem[i]; } 14 | T& operator[](const std::size_t& i) { return elem[i]; } 15 | 16 | std::size_t size() const { return _size; } 17 | 18 | // range-for 19 | const T* begin() const { return elem.get(); } 20 | T* begin() { return elem.get(); } 21 | 22 | const T* end() const { return elem.get() + _size; } 23 | T* end() { return elem.get() + _size; } 24 | }; 25 | 26 | int main() { 27 | Vector v1{7}; 28 | // Vector v2{v1}; // default copy ctor calls a deleted function by 29 | // std::unique_ptr 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /lectures/c++/04_custom_types/01_enum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | enum color { red, yellow, green }; 4 | // enum color{red=0, yellow=1, green=2}; // equivalent 5 | 6 | void dwim(const color c) { 7 | switch (c) { 8 | case red: 9 | std::cout << "option 1: red\n"; 10 | break; 11 | case yellow: 12 | std::cout << "option 2: yellow\n"; 13 | break; 14 | case green: 15 | std::cout << "option 3: green\n"; 16 | break; 17 | default: 18 | std::cout << "unknown option\n"; // should I exit the program? 19 | break; 20 | } 21 | } 22 | 23 | int main() { 24 | color opt{red}; 25 | // opt = 3; // cannot assign int to enum 26 | int a{opt}; // but they implicitly convert to integers 27 | 28 | dwim(opt); 29 | 30 | dwim(yellow); 31 | 32 | // dwim(2); // error 33 | dwim(color(2)); // works but why you may want to write this? 34 | 35 | dwim(color(6)); // ??? 36 | 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /lectures/c++/05_copy_move_semantics/02_default.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct S { 5 | int a; 6 | double b; 7 | std::string s; // default ctor of string set s to empty string 8 | }; 9 | 10 | int main() { 11 | S s1; // calls default constructor 12 | 13 | S s2{1, 2.3, "alberto"}; // if there are no custom ctors I can 14 | // directly initialize the members. Note 15 | // that I need access (i.e. they must be 16 | // public) 17 | // it is called aggregate initialization (see 18 | // https://en.cppreference.com/w/cpp/language/aggregate_initialization) 19 | 20 | S s3{}; // calls {} on each member: S s3 { {}, {}, {} }; 21 | 22 | std::cout << s1.a << "--" << s1.b << "--" << s1.s << "\n"; 23 | std::cout << s2.a << "--" << s2.b << "--" << s2.s << "\n"; 24 | std::cout << s3.a << "--" << s3.b << "--" << s3.s << "\n"; 25 | 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /lectures/c++/04_custom_types/06_operator_overloading.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | struct Point_s { 6 | double x; 7 | double y; 8 | }; // note ; at the end 9 | 10 | std::ostream& operator<<(std::ostream& os, const Point_s& p) { 11 | os << "Struct. x = " << p.x << "; y = " << p.y << std::endl; 12 | return os; 13 | } 14 | 15 | class Point_c { 16 | double x; 17 | double y; 18 | 19 | friend std::ostream& operator<<(std::ostream& os, const Point_c& p) { 20 | os << "Class. x = " << p.x << "; y = " << p.y << std::endl; 21 | return os; 22 | } 23 | 24 | }; // note ; at the end 25 | 26 | int main() { 27 | Point_s ps; 28 | ps.x = 9.9; 29 | ps.y = 3. / 7; 30 | 31 | std::cout << ps; 32 | 33 | Point_c pc; 34 | // pc.x =7.6; // error 35 | std::cout << pc; 36 | 37 | Point_s* p = &ps; 38 | p->x = 0.0; 39 | std::cout << *p; // operator overloading does not work with pointers 40 | 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /lectures/c++/06_error_handling/Makefile: -------------------------------------------------------------------------------- 1 | SRC = 00_errno.cpp \ 2 | 01_exceptions.cpp \ 3 | 02_exceptions.cpp \ 4 | 03_error.cpp \ 5 | 04_assert.cpp \ 6 | 05_stack_unwinding.cpp \ 7 | 06_smart_pointers.cpp 8 | 9 | CXX = c++ 10 | CXXFLAGS = -Wall -Wextra -g -std=c++11 11 | 12 | EXE = $(SRC:.cpp=.x) 13 | 14 | # eliminate default suffixes 15 | .SUFFIXES: 16 | SUFFIXES = 17 | 18 | # just consider our own suffixes 19 | .SUFFIXES: .cpp .x 20 | 21 | all: $(EXE) 22 | 23 | .PHONY: all 24 | 25 | %.x: %.cpp 26 | $(CXX) $< -o $@ $(CXXFLAGS) 27 | 28 | format: $(SRC) 29 | @clang-format -i $^ -verbose || echo "Please install clang-format to run this command" 30 | 31 | .PHONY: format 32 | 33 | clean: 34 | rm -f $(EXE) *~ 35 | 36 | .PHONY: clean 37 | 38 | 03_error.x: ap_error.h 39 | 04_assert.x: ap_error.h 40 | 05_stack_unwinding.x: ap_error.h 41 | 06_smart_pointers.x: ap_error.h 42 | 43 | format: ap_error.h 44 | -------------------------------------------------------------------------------- /lectures/c++/01_intro/03_loops.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | for (int i = 0; i < 10; ++i) { 5 | std::cout << i << " "; // if the action is just one line, {} can be omitted 6 | } 7 | 8 | // std::cout << i << '\n'; // error, i is out of scope 9 | 10 | std::cout << std::endl; 11 | 12 | int i{}; 13 | 14 | while (i < 10) 15 | std::cout << i++ << " "; 16 | 17 | std::cout << "\n after while i is " << i << "\n"; 18 | 19 | std::cout << std::endl; 20 | 21 | do { 22 | std::cout << "inside do \n"; 23 | } while (i < 2); // note ; at the end 24 | 25 | std::cout << "\n break at i=2" << std::endl; 26 | 27 | for (i = 0; i < 5; ++i) { 28 | if (i == 2) 29 | break; 30 | std::cout << i << std::endl; 31 | } 32 | 33 | std::cout << "\n continue at i=2" << std::endl; 34 | 35 | for (i = 0; i < 5; ++i) { 36 | if (i == 2) 37 | continue; 38 | std::cout << i << std::endl; 39 | } 40 | 41 | std::cout << std::endl; 42 | } 43 | -------------------------------------------------------------------------------- /lectures/c++/03_more_on_pointers_and_vectors/Makefile: -------------------------------------------------------------------------------- 1 | SRC = 01_const_and_pointers.cpp \ 2 | 02_special_pointers.cpp \ 3 | 03_command_line_args.cpp \ 4 | 04_matrices.cpp \ 5 | 05_std_arrays.cpp \ 6 | 06_std_vectors.cpp 7 | 8 | CXX = c++ 9 | CXXFLAGS = -Wall -Wextra -g -std=c++14 10 | 11 | EXE = $(SRC:.cpp=.x) 12 | 13 | # eliminate default suffixes 14 | .SUFFIXES: 15 | SUFFIXES = 16 | 17 | # just consider our own suffixes 18 | .SUFFIXES: .cpp .x 19 | 20 | all: $(EXE) 21 | 22 | .PHONY: all 23 | 24 | %.x: %.cpp 25 | $(CXX) $< -o $@ $(CXXFLAGS) 26 | 27 | format: $(SRC) 28 | @clang-format -i $^ -verbose || echo "Please install clang-format to run this command" 29 | 30 | .PHONY: format 31 | 32 | clean: 33 | rm -f $(EXE) *~ 34 | 35 | .PHONY: clean 36 | 37 | 01_const_and_pointers.x : CXXFLAGS += -Wno-unused-variable -Wno-unused-but-set-variable 38 | 02_special_pointers.x : CXXFLAGS += -Wno-unused-variable -Wno-unused-but-set-variable -Wno-uninitialized 39 | -------------------------------------------------------------------------------- /exercises/python/02_symbols/readme.md: -------------------------------------------------------------------------------- 1 | # Exercises 02 2 | 3 | ### Lambda 4 | 5 | - Given a list of words (`str`), construct a new **ordered** list from the former where words are sorted by their reversed spelling using a `lambda` function. 6 | 7 | *Hint*: use `sorted` and its keyword argument `key` 8 | 9 | 10 | 11 | ### Sequence 12 | 13 | - Write a class `Sequence`. 14 | - Constructor takes an iterable. Internally, use a `list` 15 | - Find the way to support the following syntax 16 | 1. `s = Sequence(range(10))` 17 | 2. `print(s)` prints all the elements (hint: `__str__`) 18 | 3. `len(s)` (hint: `__len__`) 19 | 4. `s == other_s` (hint: `__eq__`, `all`) 20 | 5. `print(s[-1])` (hint: `__getitem__`) 21 | 6. `s[0] = 1` (hint: `__setitem__`) 22 | 7. `del s[1:4:2]` (hint: `__delitem__`) 23 | 8. `for x in s` (hints: `__iter__`, `iter`) 24 | 9. `s.insert(position, value)` 25 | 10. `s.append(value)` 26 | 11. `s2 = copy.copy(s1)` is a **deepcopy ** (hint: `__copy__`) 27 | -------------------------------------------------------------------------------- /lectures/c++/05_copy_move_semantics/03_default.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct X { 4 | int a = 5; // in-class initialization 5 | double b; 6 | char c = 'a'; 7 | X() = default; // in-class initializers are used by the constructors 8 | }; 9 | 10 | struct Y { 11 | int a = 77; 12 | double b; 13 | char c = 'a'; 14 | Y() : a{5} {} // what it is written here wins the in-class initialization 15 | Y(const Y&) = delete; 16 | }; 17 | 18 | int main() { 19 | X x1; // compiler-generated default ctor 20 | X x2{}; // compiler-generated default ctor calls {} on uninitialized vars 21 | std::cout << x1.a << "--" << x1.b << "--" << x1.c << "\n"; 22 | std::cout << x2.a << "--" << x2.b << "--" << x2.c << "\n\n"; 23 | 24 | Y y1; // default ctor 25 | Y y2{}; // default ctor 26 | std::cout << y1.a << "--" << y1.b << "--" << y1.c << "\n"; 27 | std::cout << y2.a << "--" << y2.b << "--" << y2.c << "\n"; 28 | 29 | // Y y3{y2}; // error: call to a deleted function 30 | 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /lectures/c++/07_inheritance/organized/include/animal.h: -------------------------------------------------------------------------------- 1 | #ifndef __ap__animal 2 | #define __ap__animal 3 | 4 | /** 5 | * Base class for animals. Each new animal should derive from this 6 | * class and override \p speak() which is pure virtual. 7 | */ 8 | class Animal { 9 | /** animal's age */ 10 | unsigned int age; 11 | 12 | /** animal's weight */ 13 | double weight; 14 | 15 | public: 16 | /** 17 | * Animal Constructor. Takes \p a for the age and \p w for the 18 | * weight. 19 | */ 20 | Animal(const unsigned int a, const double w); 21 | 22 | /** 23 | * Deafult constructor. Set all attributes to zero. 24 | */ 25 | Animal(); 26 | 27 | /** 28 | * print on stdout the animal's call 29 | */ 30 | virtual void speak() const = 0; 31 | 32 | /** 33 | * print animal's details 34 | */ 35 | virtual void info() const noexcept; 36 | 37 | /** 38 | * Destructor. It does anything but is set virtual to ensure proper 39 | * cleanup of the data that will be defined in the derived classes. 40 | */ 41 | virtual ~Animal() {} 42 | }; 43 | 44 | #endif 45 | -------------------------------------------------------------------------------- /lectures/c++/04_custom_types/Makefile: -------------------------------------------------------------------------------- 1 | SRC = 01_enum.cpp \ 2 | 02_scoped_enum.cpp \ 3 | 03_namespace.cpp \ 4 | 04_why_scoped.cpp \ 5 | 05_struct_class.cpp \ 6 | 06_operator_overloading.cpp \ 7 | 07_constructor_destructor.cpp \ 8 | 08_template_class.cpp 9 | 10 | CXX = c++ 11 | CXXFLAGS = -Wall -Wextra -g -std=c++14 12 | 13 | EXE = $(SRC:.cpp=.x) 14 | 15 | # eliminate default suffixes 16 | .SUFFIXES: 17 | SUFFIXES = 18 | 19 | # just consider our own suffixes 20 | .SUFFIXES: .cpp .x 21 | 22 | all: $(EXE) 23 | 24 | .PHONY: all 25 | 26 | %.x: %.cpp 27 | $(CXX) $< -o $@ $(CXXFLAGS) 28 | 29 | format: $(SRC) 30 | @clang-format -i $^ -verbose || echo "Please install clang-format to run this command" 31 | 32 | .PHONY: format 33 | 34 | clean: 35 | rm -f $(EXE) *~ 36 | 37 | .PHONY: clean 38 | 39 | 01_enum.x : CXXFLAGS += -Wno-unused-variable 40 | 02_scoped_enum.x : CXXFLAGS += -Wno-unused-variable 41 | 05_struct_class.x : CXXFLAGS += -Wno-unused-but-set-variable -Wno-unknown-warning-option 42 | -------------------------------------------------------------------------------- /lectures/c++/07_inheritance/Makefile: -------------------------------------------------------------------------------- 1 | SRC = 00_first_trial.cpp \ 2 | 01_inheritance.cpp \ 3 | 02_virtual.cpp \ 4 | 03_virtual_destructor.cpp \ 5 | 04_private.cpp \ 6 | 05_dynamic_cast.cpp \ 7 | 06_template.cpp \ 8 | 07_using.cpp 9 | 10 | 11 | CXX = c++ 12 | CXXFLAGS = -W -Wall -Wextra -g -std=c++11 13 | 14 | CXXFLAGS += -I ../06_error_handling # needed by the compiler to find the header 15 | 16 | VPATH = ../06_error_handling # needed by makefile to look for files 17 | 18 | EXE = $(SRC:.cpp=.x) 19 | 20 | # eliminate default suffixes 21 | .SUFFIXES: 22 | SUFFIXES = 23 | 24 | # just consider our own suffixes 25 | .SUFFIXES: .cpp .x 26 | 27 | all: $(EXE) 28 | 29 | .PHONY: all 30 | 31 | %.x: %.cpp ap_error.h 32 | $(CXX) $< -o $@ $(CXXFLAGS) 33 | 34 | format: $(SRC) 35 | @clang-format -i $^ -verbose || echo "Please install clang-format to run this command" 36 | +$(MAKE) $@ -C organized 37 | 38 | .PHONY: format 39 | 40 | clean: 41 | rm -f $(EXE) *~ 42 | +$(MAKE) $@ -C organized 43 | 44 | .PHONY: clean 45 | 46 | -------------------------------------------------------------------------------- /lectures/c++/06_error_handling/04_assert.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "ap_error.h" 6 | 7 | // implment a square root function that "deals with" negative 8 | // numbers. Moreover according to the logic of the program, d should 9 | // never be greater than 50 10 | double square_root(const double d); 11 | 12 | int main() { 13 | try { 14 | std::cout << "please insert a number\n"; 15 | double number; 16 | std::cin >> number; 17 | double d = square_root(number); 18 | std::cout << "square root of " << number << " is " << d << '\n'; 19 | return 0; 20 | } catch (const std::exception& e) { 21 | std::cerr << e.what() << '\n'; 22 | return 1; 23 | } catch (...) { 24 | std::cerr << "Unknown exception. Aborting.\n"; 25 | return 3; 26 | } 27 | } 28 | 29 | double square_root(const double d) { 30 | // test the pre-conditions 31 | // assert(d >= 0 && d <= 50); // provided by C, no execeptions 32 | 33 | AP_ASSERT(d >= 0 && d <= 50) << "d should be in the range [0,50]"; 34 | 35 | // AP_ASSERT_IN_RANGE(d,0,50); 36 | return sqrt(d); 37 | } 38 | -------------------------------------------------------------------------------- /lectures/c++/04_custom_types/02_scoped_enum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | enum class color { red, yellow, green }; 4 | // enum class color{red=0, yellow=1, green=2}; // equivalent 5 | 6 | void dwim(const color c) { 7 | switch (c) { 8 | case color::red: 9 | std::cout << "option 1: red\n"; 10 | break; 11 | case color::yellow: 12 | std::cout << "option 2: yellow\n"; 13 | break; 14 | case color::green: 15 | std::cout << "option 3: green\n"; 16 | break; 17 | default: 18 | std::cout << "unknown option\n"; // should I exit the program? 19 | break; 20 | } 21 | } 22 | 23 | int main() { 24 | color opt{color::red}; 25 | // opt = 3; // cannot assign int to enum 26 | // int a = opt; // and they don't implicitly convert to integers 27 | int a{static_cast(opt)}; // cast 28 | // int a {int(opt)}; // 29 | // int a {(int)opt}; // C-style cast 30 | 31 | dwim(opt); 32 | 33 | dwim(color::yellow); 34 | 35 | // dwim(2); // error 36 | dwim(color(2)); // works but what why you may want to write this? 37 | 38 | dwim(color(6)); // ??? 39 | 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /lectures/c++/04_custom_types/03_namespace.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | namespace choose_a_name { 4 | 5 | int variable; 6 | 7 | namespace nested { 8 | 9 | void hello1(); 10 | void hello2(); 11 | void hello3(); 12 | 13 | } // namespace nested 14 | } // namespace choose_a_name 15 | 16 | int main() { 17 | // variable = 42; // error 18 | choose_a_name::variable = 42; 19 | // hello1(); // error 20 | choose_a_name::nested::hello1(); 21 | choose_a_name::nested::hello2(); 22 | choose_a_name::nested::hello3(); 23 | return 0; 24 | } 25 | 26 | void choose_a_name::nested::hello1() { 27 | std::cout << "hello1 from nested\n" 28 | << "variable is " << choose_a_name::variable << std::endl; 29 | } 30 | 31 | namespace choose_a_name { 32 | namespace nested { 33 | void hello2() { 34 | std::cout << "hello2 from nested\n" 35 | << "variable is " << variable << std::endl; 36 | } 37 | } // namespace nested 38 | } // namespace choose_a_name 39 | 40 | using namespace choose_a_name; 41 | 42 | void nested::hello3() { 43 | std::cout << "hello3 from nested\n" 44 | << "variable is " << variable << std::endl; 45 | } 46 | -------------------------------------------------------------------------------- /lectures/c++/03_more_on_pointers_and_vectors/06_std_vectors.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // template> 6 | // class vector; 7 | 8 | template 9 | void print_vector(const std::vector& v, const std::string& s); 10 | 11 | int main() { 12 | std::vector v0{1, 2, 4}; 13 | std::vector v1(4, 4); 14 | 15 | print_vector(v0, "v0"); 16 | print_vector(v1, "v1"); 17 | 18 | v1 = v0; 19 | 20 | print_vector(v1, "v1 after copy"); 21 | 22 | for (auto x : {7, 8, 9}) 23 | v1.push_back(x); // or v1.emplace_back(x); 24 | 25 | print_vector(v1, "v1 after push_back"); 26 | 27 | for (auto i = 0u; i < v1.size(); ++i) 28 | std::cout << "v[" << i << "] = " << v1[i] << std::endl; 29 | 30 | std::cout << v1[3] << " " << v1[78] << std::endl; // no bounds checking 31 | std::cout << v1.at(3) << " " << v1.at(78) << std::endl; // bounds checking 32 | 33 | return 0; 34 | } 35 | 36 | template 37 | void print_vector(const std::vector& v, const std::string& s) { 38 | std::cout << s << ": "; 39 | for (const auto& x : v) 40 | std::cout << x << " "; 41 | std::cout << std::endl; 42 | } 43 | -------------------------------------------------------------------------------- /lectures/c++/04_custom_types/05_struct_class.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | struct Point_s { 6 | double x; 7 | double y; 8 | void print(); 9 | }; // note ; at the end 10 | 11 | void Point_s::print() { 12 | std::cout << "Structure. x = " << x << "; y = " << y << std::endl; 13 | } 14 | 15 | class Point_c { 16 | double x; 17 | double y; 18 | 19 | public: 20 | void print() { 21 | std::cout << "Class. x = " << x << "; y = " << y << std::endl; 22 | } // note no ; at the end 23 | }; // note ; at the end 24 | 25 | int main() { 26 | Point_s ps; 27 | ps.x = 9.9; 28 | ps.y = 3. / 7; 29 | 30 | ps.print(); 31 | 32 | Point_c pc; 33 | // pc.x =7.6; // error 34 | pc.print(); // I can access private data through public functions 35 | 36 | Point_s* p = &ps; 37 | p->x = 0.0; 38 | p->print(); 39 | 40 | auto& pr = ps; 41 | ++pr.x; 42 | pr.print(); 43 | 44 | Point_s array_of_structs[8]; // built-in array 45 | array_of_structs[0].x = 1; 46 | array_of_structs[0].y = 2; 47 | 48 | std::array as; 49 | as[3].x = 3; 50 | 51 | std::vector vs; 52 | vs.push_back(ps); 53 | vs[0].x = 999; 54 | ps.x = 11; 55 | ps.print(); 56 | vs[0].print(); 57 | 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /lectures/python/03_advanced_topics/my_module.py: -------------------------------------------------------------------------------- 1 | __all__ = ['my_sum', 'Point'] 2 | 3 | def my_sum(a,b): 4 | '''return the sum of two objects 5 | >>> my_sum(3,5) 6 | 8 7 | >>> my_sum("a","b") 8 | 'ab' 9 | >>> my_sum([1,2],[3,4]) 10 | [1, 2, 3, 4] 11 | ''' 12 | return a+b 13 | 14 | class Point: 15 | '''simple 2D point''' 16 | def __init__(self,x,y): 17 | '''ctor 18 | >>> p = Point(3,4) 19 | >>> p.x 20 | 3 21 | >>> p.y 22 | 4 23 | ''' 24 | self.x = x 25 | self.y = y 26 | 27 | def __abs__(self): 28 | ''' 29 | >>> p = Point(3,4) 30 | >>> abs(p) 31 | 5.0 32 | ''' 33 | import math 34 | return math.hypot(self.x,self.y) 35 | 36 | 37 | import unittest 38 | class TestMyModule(unittest.TestCase): 39 | def test_my_sum(self): 40 | self.assertEqual(my_sum(3,4), 7) 41 | 42 | def test_point_ctor(self): 43 | p = Point(3,4) 44 | self.assertEqual(p.x,3) 45 | self.assertEqual(p.y,4) 46 | 47 | def test_point_abs(self): 48 | p = Point(3,4) 49 | self.assertEqual(abs(p),5) 50 | 51 | if __name__ == '__main__': 52 | import doctest 53 | doctest.testmod() 54 | unittest.main() 55 | 56 | 57 | -------------------------------------------------------------------------------- /lectures/c++/07_inheritance/organized/Makefile: -------------------------------------------------------------------------------- 1 | EXE = exe.x 2 | CXX = c++ 3 | CXXFLAGS = -I include -g -std=c++11 -Wall -Wextra -I ../../06_error_handling/ 4 | 5 | SRC= main.cpp src/dog.cpp src/animal.cpp src/snake.cpp src/helper_functions.cpp 6 | OBJ=$(SRC:.cpp=.o) 7 | INC = include/animal.h include/dog.h include/helper_functions.h include/snake.h 8 | 9 | VPATH = ../../06_error_handling 10 | 11 | # eliminate default suffixes 12 | .SUFFIXES: 13 | SUFFIXES = 14 | 15 | # just consider our own suffixes 16 | .SUFFIXES: .cpp .o 17 | 18 | all: $(EXE) 19 | 20 | .PHONY: all 21 | 22 | clean: 23 | rm -rf $(OBJ) $(EXE) src/*~ include/*~ *~ html latex 24 | 25 | .PHONY: clean 26 | 27 | %.o: %.cpp ap_error.h 28 | $(CXX) -c $< -o $@ $(CXXFLAGS) 29 | 30 | $(EXE): $(OBJ) 31 | $(CXX) $^ -o $(EXE) 32 | 33 | documentation: Doxygen/doxy.in 34 | doxygen $^ 35 | 36 | .PHONY: documentation 37 | 38 | main.o: include/dog.h include/animal.h include/snake.h \ 39 | include/helper_functions.h 40 | 41 | src/animal.o: include/animal.h 42 | 43 | src/dog.o: include/animal.h include/dog.h 44 | src/snake.o: include/animal.h include/snake.h 45 | src/helper_functions.o: include/animal.h include/helper_functions.h 46 | 47 | format: $(SRC) $(INC) 48 | @clang-format -i $^ -verbose || echo "Please install clang-format to run this commands" 49 | 50 | .PHONY: format 51 | -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/beamerthemenasatalk.sty: -------------------------------------------------------------------------------- 1 | % Copyright 2004 by Manuel Carro 2 | % 3 | % This file may be distributed and/or modified 4 | % 5 | % 1. under the LaTeX Project Public License and/or 6 | % 2. under the GNU Public License. 7 | % 8 | % See the file doc/licenses/LICENSE for more details. 9 | 10 | \mode 11 | 12 | \newif\ifbeamer@secheader 13 | \beamer@secheaderfalse 14 | 15 | \DeclareOptionBeamer{secheader}{\beamer@secheadertrue} 16 | \ProcessOptionsBeamer 17 | 18 | 19 | \usecolortheme{rose} 20 | \useinnertheme[shadow]{rounded} 21 | \usecolortheme{dolphin} 22 | \useoutertheme{nasalines} 23 | 24 | 25 | 26 | 27 | \usepackage[scaled]{helvet} 28 | %\usepackage{eulervm} 29 | \usepackage{amsmath} 30 | \usepackage{amsfonts} 31 | \usepackage{amssymb} 32 | \setbeamertemplate{items}[circle] 33 | \setbeamertemplate{itemize subitem}[triangle] 34 | 35 | \definecolor{nasablue}{RGB}{0,96,169} 36 | \definecolor{nasared}{RGB}{239,61,66} 37 | \definecolor{orionblue}{RGB}{15,16,64} 38 | \setbeamercolor{itemize item}{fg=nasablue} 39 | \setbeamercolor{itemize subitem}{fg=nasablue} 40 | \setbeamercolor{itemize subsubitem}{fg=nasablue} 41 | 42 | \usecolortheme[named=nasablue]{structure} 43 | 44 | \newcommand{\zapspace}{\topsep=0pt\partopsep=0pt\itemsep=0pt\parskip=0pt} 45 | 46 | \setbeamertemplate{navigation symbols}{} 47 | \mode 48 | 49 | -------------------------------------------------------------------------------- /lectures/c++/06_error_handling/02_exceptions.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | // implment a square root function that "deals with" negative 7 | // numbers. Moreover according to the logic of the program, d should 8 | // never be greater than 50 9 | double square_root(const double d); 10 | 11 | struct Square_root_invalid { 12 | std::string message; 13 | Square_root_invalid(std::string s) : message{std::move(s)} {} 14 | }; 15 | 16 | int main() { 17 | try { 18 | std::cout << "please insert a number\n"; 19 | double number; 20 | std::cin >> number; 21 | auto d = square_root(number); 22 | std::cout << "square root of " << number << " is " << d << '\n'; 23 | return 0; 24 | } catch (const Square_root_invalid& s) { 25 | std::cerr << s.message << std::endl; 26 | return 1; 27 | } catch (...) { 28 | std::cerr << "Unknown exception. Aborting.\n"; 29 | return 3; 30 | } 31 | } 32 | 33 | double square_root(const double d) { 34 | // test the pre-conditions 35 | if (d < 0) 36 | throw Square_root_invalid{"Cannot handle negative numbers. You gave me " + 37 | std::to_string(d)}; 38 | if (d > 50) 39 | throw Square_root_invalid{ 40 | "The argument of square_root must be lower than 50. You gave me " + 41 | std::to_string(d)}; 42 | return sqrt(d); 43 | } 44 | -------------------------------------------------------------------------------- /lectures/c++/02_functions_and_arrays/05_static_arrays.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void surprise(double a[], const std::size_t n) { 4 | for (auto i = 0llu; i < n; ++i) { 5 | a[i] = 77; 6 | } 7 | } 8 | 9 | int main() { 10 | int ai[4]; 11 | float af[9]; 12 | ai[0] = 9; // first element 13 | af[8] = 3.3; // last element 14 | ai[88] = 7; // undefined behavior, no range checking 15 | 16 | for (std::size_t k{0}; k < 4; ++k) 17 | std::cout << "ai[" << k << "] = " << ai[k] << '\n'; 18 | 19 | std::cout << "\n-------------------------------\n\n"; 20 | 21 | for (std::size_t k{0}; k < 9; ++k) 22 | std::cout << "af[" << k << "] = " << af[k] << '\n'; 23 | 24 | std::cout << "\n how is an array in memory?\n\n"; 25 | 26 | for (std::size_t k{0}; k < 9; ++k) 27 | std::cout << "&af[" << k << "] = " << &af[k] << '\n'; 28 | 29 | std::cout << "\n-------------------------------\n\n"; 30 | 31 | double ad[7]{1.1, 2.2, 3.3}; // the rest is set to 0 32 | 33 | *ad = 9.9; // an array is implicitly converted to 34 | // a pointer to its first element; 35 | for (std::size_t k{0}; k < 7; ++k) 36 | std::cout << ad[k] << std::endl; 37 | 38 | // double ad2[2] {1,2,3,4}; // error 39 | 40 | surprise(ad, 7); 41 | std::cout << "after surprise()" << std::endl; 42 | for (std::size_t k{0}; k < 7; ++k) 43 | std::cout << ad[k] << std::endl; 44 | 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /lectures/c++/04_custom_types/08_template_class.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | template 5 | class Vector { 6 | T* elem; 7 | std::size_t _size; 8 | 9 | public: 10 | Vector(const std::size_t size) : elem{new T[size]}, _size{size} {} 11 | 12 | // automatically release the acquired memory 13 | ~Vector() { delete[] elem; } 14 | 15 | // try to remove the const and recompile 16 | std::size_t size() const { return _size; } 17 | 18 | T& operator[](const std::size_t i) { return elem[i]; } 19 | 20 | // try to comment this line and recompile 21 | const T& operator[](const std::size_t i) const { return elem[i]; } 22 | }; 23 | 24 | template 25 | std::ostream& operator<<(std::ostream& os, const Vector& v) { 26 | for (auto i = 0u; i < v.size(); ++i) 27 | os << "v[" << i << "] = " << v[i] << std::endl; 28 | return os; 29 | } 30 | 31 | int main() { 32 | Vector v{10}; 33 | 34 | for (auto i = 0u; i < v.size(); ++i) 35 | v[i] = i; 36 | 37 | std::cout << v << std::endl; 38 | 39 | Vector* pv{&v}; 40 | 41 | // first dereference the pointer, then I can use the defined operators 42 | (*pv)[0] = -99.999; 43 | 44 | pv->operator[](1) = 77777.3333; // or I call the function by name 45 | 46 | std::cout << *pv << std::endl; 47 | 48 | Vector& rv{v}; 49 | 50 | rv[5] = 555; 51 | 52 | std::cout << v << std::endl; 53 | 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /lectures/c++/03_more_on_pointers_and_vectors/04_matrices.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void print_ma(int m[][5], int dim1); // ugly and not flexible 5 | // void print_ma(int m[][], int dim1, int dim2); // error second 6 | // dimension must be 7 | // knwon at compile time 8 | 9 | void print_ma(int* p, int row, int col); // the only possible solution 10 | 11 | int main() { 12 | int ma[6][5]; // matrix: 6 rows, 5 columns each 13 | 14 | for (int i = 0; i < 6; ++i) 15 | for (int j = 0; j < 5; ++j) 16 | ma[i][j] = 10 * i + j; 17 | 18 | for (int i = 0; i < 6; ++i) { 19 | for (int j = 0; j < 5; ++j) 20 | std::cout << std::setw(3) << ma[i][j]; 21 | std::cout << std::endl; 22 | } 23 | 24 | for (int i = 0; i < 6; ++i) { 25 | for (int j = 0; j < 5; ++j) 26 | std::cout << &ma[i][j] << " "; 27 | std::cout << std::endl; 28 | } 29 | 30 | // int *pma {ma}; // error 31 | // int *pma[5] {ma}; // error 32 | int* p{reinterpret_cast(ma)}; 33 | // int* p {&ma[0][0]}; 34 | 35 | // print_ma(ma, 6, 5); // error 36 | print_ma(p, 6, 5); 37 | 38 | auto d_ma = new int[6 * 5]{}; 39 | 40 | std::cout << std::endl; 41 | 42 | print_ma(d_ma, 6, 5); 43 | delete[] d_ma; 44 | 45 | return 0; 46 | } 47 | 48 | void print_ma(int* p, int row, int col) { 49 | for (int i = 0; i < row; ++i) { 50 | for (int j = 0; j < col; ++j) 51 | std::cout << std::setw(2) << p[i * col + j] << " "; 52 | std::cout << std::endl; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /exam/test_exam.py: -------------------------------------------------------------------------------- 1 | def reverse_dict(d): 2 | pass 3 | 4 | 5 | def test_reverse_small_dict(): 6 | d = {"a": [1, 2, 3], "b": [45, 6], "c": [2, 45]} 7 | 8 | rd = {1: ["a"], 2: ["a", "c"], 3: ["a"], 6: ["b"], 45: ["b", "c"]} 9 | 10 | rd = reverse_dict(d) 11 | 12 | assert len(rd) == 5 13 | 14 | assert 'a' in rd[1] 15 | assert len(rd[1]) == 1 16 | 17 | assert 99 not in rd 18 | 19 | assert 'a' in rd[2] 20 | assert 'c' in rd[2] 21 | assert len(rd[2]) == 2 22 | 23 | assert 'a' in rd[3] 24 | assert len(rd[3]) == 1 25 | 26 | assert 'b' in rd[6] 27 | assert len(rd[6]) == 1 28 | 29 | assert 'b' in rd[45] 30 | assert 'c' in rd[45] 31 | assert len(rd[45]) == 2 32 | 33 | 34 | import pytest 35 | 36 | @pytest.fixture 37 | def big_dict(): 38 | chars = "qwertyuiopasdfghjklzxcvbnm" 39 | chars = sorted(chars.upper() + chars) 40 | 41 | keys = [c + str(n) for c in chars for n in range(100)] 42 | 43 | import random 44 | 45 | random.seed(42) 46 | 47 | d = {k: [random.randint(1, 200) for _ in range(random.randint(1, 10))] for k in keys} 48 | return d 49 | 50 | 51 | def test_reverse_big_dict(big_dict): 52 | 53 | rd = reverse_dict(big_dict) 54 | 55 | assert 'A24' in rd[1] 56 | assert 'A25' not in rd[1] 57 | assert 'K10' in rd[77] 58 | assert len(rd) == 200 59 | assert len(rd[42]) == 150 60 | assert len(rd[147]) == 173 61 | assert len(rd[149]) == 115 62 | assert min([len(x) for x in rd.values()]) == 106 63 | -------------------------------------------------------------------------------- /lectures/c++/06_error_handling/01_exceptions.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // implment a square root function that "deals with" negative 5 | // numbers. Moreover according to the logic of the program, d should 6 | // never be greater than 50 7 | double square_root(const double d); 8 | 9 | struct Negative_number {}; 10 | 11 | struct Bigger_than_expected {}; 12 | 13 | int main() { 14 | try { 15 | std::cout << "please insert a number\n"; 16 | double number; 17 | std::cin >> number; 18 | auto d = square_root(number); 19 | std::cout << "square root of " << number << " is " << d << '\n'; 20 | return 0; 21 | } catch (const Negative_number) { 22 | std::cerr << "The square root of a negative number is a complex number.\n" 23 | "square_root() is " 24 | << "limited to handle positive double numbers.\n"; 25 | return 1; 26 | } catch (const Bigger_than_expected) { 27 | std::cerr << "The function square_root has been called with a parameter " 28 | "greater than 50.\n" 29 | << "This means there is a bug in the algorithm that generated " 30 | "this number.\n"; 31 | return 2; 32 | } catch (...) { 33 | std::cerr << "Unknown exception. Aborting.\n"; 34 | return 3; 35 | } 36 | } 37 | 38 | double square_root(const double d) { 39 | // test the pre-conditions 40 | if (d < 0) 41 | throw Negative_number{}; 42 | if (d > 50) 43 | throw Bigger_than_expected{}; 44 | return std::sqrt(d); 45 | } 46 | -------------------------------------------------------------------------------- /lectures/c++/05_copy_move_semantics/04_buggy_vector.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | template 4 | class Vector { 5 | T* elem; 6 | std::size_t _size; 7 | 8 | public: 9 | explicit Vector(const std::size_t length) 10 | : elem{new T[length]{}}, _size{length} {} 11 | 12 | ~Vector() { delete[] elem; } 13 | 14 | const T& operator[](const std::size_t& i) const { return elem[i]; } 15 | T& operator[](const std::size_t& i) { return elem[i]; } 16 | 17 | std::size_t size() const { return _size; } 18 | 19 | // range-for 20 | const T* begin() const { return elem; } 21 | T* begin() { return elem; } 22 | 23 | const T* end() const { return elem + size(); } 24 | T* end() { return elem + size(); } 25 | }; 26 | 27 | int main() { 28 | Vector v1{3}; 29 | v1[0] = 1; 30 | v1[1] = 2; 31 | v1[2] = 3; 32 | 33 | std::cout << "v1: "; 34 | for (const auto x : v1) 35 | std::cout << x << " "; 36 | std::cout << std::endl; 37 | 38 | Vector v2{v1}; // default copy constructor 39 | 40 | std::cout << "v2 after default copy ctor: "; 41 | for (const auto x : v2) 42 | std::cout << x << " "; 43 | std::cout << std::endl; 44 | 45 | v1[0] = 99; 46 | 47 | std::cout << "v2 after v1 has been changed: "; 48 | for (const auto x : v2) 49 | std::cout << x << " "; 50 | std::cout << std::endl; 51 | 52 | v2[1] = -999; 53 | 54 | std::cout << "v1 after v2 has been changed: "; 55 | for (const auto x : v1) 56 | std::cout << x << " "; 57 | std::cout << std::endl; 58 | 59 | return 0; 60 | } 61 | -------------------------------------------------------------------------------- /lectures/c++/04_custom_types/07_constructor_destructor.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Foo { 5 | int _i; 6 | double _d; 7 | std::string _s; 8 | 9 | Foo(const int i, const double d, 10 | const std::string& s); // custom constructor 11 | 12 | Foo(); // default constructor 13 | 14 | ~Foo(); // destructor 15 | }; 16 | 17 | Foo::Foo(const int i, const double d, const std::string& s) 18 | : _i{i}, 19 | _d{d}, 20 | _s{s} 21 | // _i, _d, _s must be initialized in the same order they have been declared 22 | 23 | { 24 | std::cout << "custom ctor\n"; 25 | // if you want/need you can use _i, _d, _s and change their value 26 | // with the usual notation +,-,=,*, call a function.. 27 | // don't use {} because this notation is reserved for the 28 | // construction of the variables and at this point they have already 29 | // been constructed 30 | } 31 | 32 | Foo::Foo() { 33 | std::cout << "default ctor\n"; // what happens to our member variables? 34 | } 35 | 36 | Foo::~Foo() { 37 | std::cout << "dtor\n"; 38 | } 39 | 40 | std::ostream& operator<<(std::ostream& os, const Foo& f) { 41 | os << f._i << " " << f._d << " " << f._s << std::endl; 42 | return os; 43 | } 44 | 45 | int main() { 46 | Foo f0; // call default ctor 47 | Foo f1{}; // call default ctor 48 | // Foo f2(); // compiler error 49 | 50 | Foo f2{8, 2.2, "hello"}; 51 | std::cout << "f0: " << f0 << "f1: " << f1 << "f2: " << f2 << std::endl; 52 | 53 | // the destructor is called when the variable goes out of scope 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /lectures/c++/03_more_on_pointers_and_vectors/05_std_arrays.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // template 5 | // struct array; 6 | 7 | template 8 | void print_array_two(const std::array& a); 9 | 10 | template 11 | void print_array_one(const T& a); 12 | 13 | int main() { 14 | std::array a{1, 2, 3, 4}; 15 | std::array b{a}; // I can copy element-wise from another std::array 16 | // this is not possible with plain built-in arrays 17 | b = a; 18 | for (auto x : a) 19 | std::cout << x << " "; 20 | std::cout << std::endl; 21 | 22 | for (auto x : b) 23 | std::cout << x << " "; 24 | std::cout << std::endl; 25 | 26 | a[0] = 0; // same subscripting operator without bound checking 27 | 28 | for (const auto x : a) 29 | std::cout << x << " "; 30 | std::cout << std::endl; 31 | 32 | for (const auto x : b) 33 | std::cout << x << " "; 34 | std::cout << std::endl; 35 | 36 | for (auto& x : a) 37 | x *= 10; 38 | 39 | for (auto i = 0u; i < a.size(); ++i) 40 | std::cout << "a[" << i << "] = " << a[i] << std::endl; 41 | 42 | b.at(90); // bound checking at run-time 43 | 44 | return 0; 45 | } 46 | 47 | template 48 | void print_array_two(const std::array& a) { 49 | for (const auto& x : a) 50 | std::cout << x << " "; 51 | std::cout << std::endl; 52 | } 53 | 54 | template 55 | void print_array_one(const T& a) { 56 | for (const auto& x : a) 57 | std::cout << x << " "; 58 | std::cout << std::endl; 59 | } 60 | -------------------------------------------------------------------------------- /lectures/c++/06_error_handling/06_smart_pointers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include // std::uniqe_ptr 3 | 4 | #include "ap_error.h" 5 | 6 | class Vector { 7 | std::unique_ptr elem; 8 | 9 | public: 10 | Vector(const unsigned int l) : elem{new double[l]} { 11 | // std::cout << "Vector ctor\n"; 12 | } 13 | 14 | Vector(Vector&&) noexcept = default; 15 | Vector& operator=(Vector&&) noexcept = default; 16 | 17 | double& operator[](const unsigned int i) noexcept { // noexcept ---> better 18 | // code, faster code 19 | return elem[i]; 20 | } // you can use smart pointers almost like raw pointers 21 | 22 | const double& operator[](const unsigned int i) 23 | const noexcept { // noexcept ---> better code, faster code 24 | return elem[i]; 25 | } // you can use smart pointers almost like raw pointers 26 | 27 | ~Vector() noexcept { std::cout << "~Vector\n"; } 28 | }; 29 | 30 | class ManyResources { 31 | std::unique_ptr ptr; 32 | Vector v; 33 | 34 | public: 35 | ManyResources() : ptr{new double[5]}, v{3} { 36 | std::cout << "ManyResources ctor\n"; 37 | AP_ERROR(false) << "I am simulating something wrong.\n"; 38 | } 39 | ~ManyResources() noexcept { std::cout << "~ManyResources\n"; } 40 | }; 41 | 42 | int main() { 43 | try { 44 | std::unique_ptr up{new int[7]}; // RAII 45 | ManyResources mr; 46 | 47 | } catch (const std::exception& e) { 48 | std::cerr << e.what() << std::endl; 49 | return 1; 50 | 51 | } catch (...) { 52 | std::cerr << "Unknown exception. Aborting.\n" << std::endl; 53 | return 2; 54 | } 55 | 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /lectures/c++/06_error_handling/03_error.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "ap_error.h" 5 | 6 | // implment a square root function that "deals with" negative 7 | // numbers. Moreover according to the logic of the program, d should 8 | // never be greater than 50 9 | double square_root(const double d); 10 | 11 | struct Square_root_invalid { 12 | std::string message; 13 | Square_root_invalid(std::string s) : message{std::move(s)} {} 14 | const char* what() const { return message.c_str(); } 15 | }; 16 | 17 | int main() { 18 | try { 19 | std::cout << "please insert a number\n"; 20 | double number; 21 | std::cin >> number; 22 | double d = square_root(number); 23 | std::cout << "square root of " << number << " is " << d << '\n'; 24 | return 0; 25 | } catch (const Square_root_invalid& e) { 26 | std::cerr << e.what() << std::endl; 27 | return 2; 28 | } catch (const std::exception& e) { 29 | std::cerr << e.what() << std::endl; 30 | return 1; 31 | } catch (...) { 32 | std::cerr << "Unknown exception. Aborting.\n"; 33 | return 3; 34 | } 35 | } 36 | 37 | double square_root(const double d) { 38 | // test the pre-conditions 39 | 40 | AP_ERROR(d >= 0 && d <= 50, Square_root_invalid) 41 | << "In our library the argument must be positive and less or equal than " 42 | "50.\n\nYou passed " 43 | << d << ".\n"; 44 | 45 | // AP_ERROR(d >= 0 && d <= 50) << "In our library the argument must be 46 | // positive " 47 | // "and less or equal than 50.\n"; 48 | 49 | // AP_ERROR_GE(d, 0) << "Cannot handle negative numbers.\n"; 50 | 51 | // AP_ERROR_LE(d, 50) << "According to the implemented algorithm, the argument 52 | // " 53 | // "must be less than 50.\n"; 54 | 55 | // AP_ERROR_IN_RANGE(d,0,50); 56 | 57 | return sqrt(d); 58 | } 59 | -------------------------------------------------------------------------------- /lectures/c++/07_inheritance/organized/include/snake.h: -------------------------------------------------------------------------------- 1 | #ifndef __ap_snake 2 | #define __ap_snake 3 | 4 | #include 5 | 6 | /** 7 | * Base class for snakes. It specializes into DangerousSnake and 8 | * NonDangerousSnake. It is derived from class Animal and add a 9 | * boolean Snake#dangerous to specify if a type of snake is dangerous or 10 | * not. 11 | */ 12 | class Snake : public Animal { 13 | /** Is dangerous */ 14 | bool dangerous; 15 | 16 | public: 17 | /** 18 | * Constructor. Takes all the arguments to construct an Animal plus 19 | * the additional boolean 20 | */ 21 | Snake(const unsigned int a, const double w, const bool b); 22 | 23 | /** 24 | * Calls the default constructor for Animal, and the \p dangerous is 25 | * set to \p b 26 | */ 27 | explicit Snake(const bool b); 28 | 29 | /** 30 | * Print details. 31 | */ 32 | void info() const noexcept override; 33 | 34 | /** 35 | * Snake's call 36 | */ 37 | void speak() const noexcept override; 38 | }; 39 | 40 | /** 41 | * Specialization of class Snake. It specialize the constructors such 42 | * that the attribute \p dangerous is set to true 43 | */ 44 | class DangerousSnake : public Snake { 45 | public: 46 | DangerousSnake(const unsigned int a, const double w) : Snake{a, w, true} {} 47 | DangerousSnake() : Snake{true} {} 48 | }; 49 | 50 | /** 51 | * Specialization of class Snake. It specialize the constructors such 52 | * that the attribute \p dangerous is set to false. 53 | */ 54 | class NonDangerousSnake : public Snake { 55 | public: 56 | NonDangerousSnake(const unsigned int a, const double w) 57 | : Snake{a, w, false} {} 58 | NonDangerousSnake() : Snake{false} {} 59 | }; 60 | 61 | /** 62 | * Define the type Python 63 | */ 64 | struct Python : public NonDangerousSnake {}; 65 | 66 | /** 67 | * Aliasing Anaconda as DangerousSnake 68 | */ 69 | using Anaconda = DangerousSnake; 70 | 71 | #endif 72 | -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/tex_files/function_objects.tex: -------------------------------------------------------------------------------- 1 | \section{Function objects} 2 | \subsection{Introduction} 3 | \begin{frame} 4 | \frametitle{Function objects} 5 | \begin{itemize} 6 | \item defined in \texttt{} 7 | \item[] 8 | \item comparison criteria 9 | \item[] 10 | \item predicates (functions returning \texttt{bool}) 11 | \item[] 12 | \item arithmetic operations 13 | \end{itemize} 14 | \end{frame} 15 | \begin{frame} 16 | \frametitle{Predicates} 17 | \centering 18 | \includegraphics[width=0.8\textwidth]{img/predicates.png} 19 | \end{frame} 20 | \begin{frame} 21 | \frametitle{Arithmetic operations} 22 | \centering 23 | \includegraphics[width=0.8\textwidth]{img/arithmetic.png} 24 | \end{frame} 25 | 26 | \subsection{Examples} 27 | \begin{frame}[fragile] 28 | \frametitle{Decreasing sort} 29 | \begin{lstlisting} 30 | #include 31 | #include 32 | #include 33 | 34 | int main(){ 35 | std::vector v1; 36 | ... 37 | std::sort(v1.begin(), v1.end(), 38 | std::greater{}); 39 | } 40 | \end{lstlisting} 41 | \end{frame} 42 | 43 | \begin{frame}[fragile] 44 | \frametitle{My comparison} 45 | \begin{lstlisting} 46 | #include 47 | #include 48 | 49 | template 50 | struct my_comparison{ 51 | bool operator()(const num& a, const num& b) { return a > b;} 52 | }; 53 | 54 | int main(){ 55 | std::vector v1; 56 | ... 57 | std::sort(v1.begin(), v1.end(), 58 | my_comparison{}); 59 | } 60 | \end{lstlisting} 61 | \end{frame} 62 | 63 | \begin{frame}[fragile] 64 | \frametitle{Lambda} 65 | \begin{lstlisting} 66 | #include 67 | #include 68 | 69 | int main(){ 70 | std::vector v1; 71 | ... 72 | std::sort(v1.begin(), v1.end(), 73 | [](const auto& a, const auto& b) 74 | { return a>b; } ); 75 | } 76 | \end{lstlisting} 77 | \end{frame} 78 | -------------------------------------------------------------------------------- /lectures/python/03_advanced_topics/test_sequence.py: -------------------------------------------------------------------------------- 1 | from sequence import Sequence 2 | 3 | def test_ctor(): 4 | s = Sequence(range(3)) 5 | assert s.l == [0,1,2] 6 | 7 | s = Sequence([4,1,2]) 8 | assert s.l == [4,1,2] 9 | 10 | s = Sequence((1,2,3)) 11 | assert s.l == [1,2,3] 12 | 13 | def test_equality(): 14 | s = Sequence(range(3)) 15 | o = Sequence([0,1,2]) 16 | assert s == o 17 | assert not s != o 18 | 19 | 20 | def test_repr(): 21 | assert str(Sequence(range(4))) == 'Sequence([0, 1, 2, 3])' 22 | 23 | 24 | import pytest 25 | 26 | @pytest.fixture 27 | def default_sequence(): 28 | return Sequence(range(3)) 29 | 30 | def test_len(default_sequence): 31 | assert len(default_sequence) == 3 32 | 33 | def test_get(default_sequence): 34 | assert default_sequence[-1] == 2 35 | 36 | def test_set(default_sequence): 37 | default_sequence[0] = 0.1 38 | assert default_sequence[0] == pytest.approx(0.09999999999) 39 | assert default_sequence[0] == pytest.approx(0.09999999999,1e-3) 40 | 41 | def test_del(default_sequence): 42 | assert len(default_sequence) == 3 43 | del default_sequence[0] 44 | assert len(default_sequence) == 2 45 | assert str(default_sequence) == 'Sequence([1, 2])' 46 | 47 | def test_insert(default_sequence): 48 | assert default_sequence.l == [0,1,2] 49 | 50 | default_sequence.insert(0,9) 51 | assert default_sequence.l == [9,0,1,2] 52 | 53 | default_sequence.insert(1,10) 54 | assert default_sequence.l == [9,10,0,1,2] 55 | 56 | def append(default_sequence): 57 | assert default_sequence[-1] != 10 58 | default_sequence.append(10) 59 | assert default_sequence[-1] == 10 60 | 61 | 62 | def test_iter(default_sequence): 63 | i = iter(default_sequence) 64 | assert next(i) == 0 65 | assert next(i) == 1 66 | assert next(i) == 2 67 | 68 | ## now we expect an exception 69 | with pytest.raises(StopIteration): 70 | next(i) 71 | 72 | -------------------------------------------------------------------------------- /lectures/c++/07_inheritance/02_virtual.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Animal { 5 | unsigned int age; 6 | double weight; 7 | 8 | Animal(const unsigned int a, const double w) : age{a}, weight{w} { 9 | AP_ERROR(!(weight < 0)) << "invalid weight!\n"; 10 | } 11 | 12 | Animal() : Animal{0, 0} {} // delegating constructor 13 | 14 | virtual void speak() const = 0; // pure virtual function ==> abstract class 15 | virtual void info() const noexcept { 16 | std::cout << "age:\t" << age << '\n' << "weight:\t" << weight << '\n'; 17 | } 18 | 19 | virtual ~Animal() {} // why? see file 03_virtual_destructor.cc 20 | }; 21 | 22 | struct Dog : public Animal { 23 | void speak() const noexcept override { std::cout << "Bau\n"; } 24 | Dog() = default; 25 | Dog(const unsigned int a, const double d) : Animal{a, d} {} 26 | }; 27 | 28 | struct Snake : public Animal { 29 | bool dangerous; 30 | Snake(const unsigned int a, const double w, const bool b) 31 | : Animal{a, w}, dangerous{b} {} 32 | explicit Snake(const bool b) : Animal{}, dangerous{b} {} 33 | void info() const noexcept override { 34 | Animal::info(); 35 | std::cout << "dangerous:\t" << (dangerous ? "true" : "false") << std::endl; 36 | } 37 | void speak() const noexcept override { std::cout << "ssss\n"; } 38 | }; 39 | 40 | void print_animal(const Animal& a) noexcept { 41 | std::cout << "throught ref\n"; 42 | a.info(); 43 | a.speak(); 44 | } 45 | 46 | int main() { 47 | try { 48 | Snake s{true}; 49 | s.info(); 50 | s.speak(); 51 | 52 | std::cout << std::endl; 53 | 54 | Animal* p = new Snake{1, 2.3, false}; 55 | 56 | std::cout << "through pointer\n"; 57 | p->info(); 58 | p->speak(); 59 | 60 | delete p; 61 | 62 | std::cout << std::endl; 63 | 64 | print_animal(s); 65 | 66 | return 0; 67 | } catch (std::runtime_error& e) { 68 | std::cerr << e.what() << std::endl; 69 | return 1; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /lectures/c++/07_inheritance/00_first_trial.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // each animal has an age and a weight and must implement 4 | // void info() 5 | // void speak() 6 | 7 | struct Animal { 8 | unsigned int age; 9 | double weight; 10 | void info() const noexcept { 11 | std::cout << "age: " << age << std::endl 12 | << "weight: " << weight << std::endl; 13 | } 14 | }; 15 | 16 | struct Dog { 17 | Animal _animal; 18 | void speak() const noexcept { std::cout << "Bau\n"; } 19 | void info() const noexcept { _animal.info(); } 20 | Dog() noexcept : _animal{} {} 21 | Dog(const unsigned int a, const double d) noexcept : _animal{a, d} {} 22 | }; 23 | 24 | struct Snake { 25 | Animal _animal; 26 | bool dangerous; 27 | Snake(const unsigned int a, const double w, const bool b) noexcept 28 | : _animal{a, w}, dangerous{b} {} 29 | Snake(const bool b) noexcept : _animal{}, dangerous{b} {} 30 | void info() const noexcept { 31 | _animal.info(); 32 | std::cout << "dangerous:\t" << (dangerous ? "true" : "false") << std::endl; 33 | } 34 | void speak() const noexcept { std::cout << "ssss\n"; } 35 | }; 36 | 37 | template 38 | void print_animal(const AT& a) noexcept { 39 | std::cout << "through ref\n"; 40 | a.info(); 41 | a.speak(); 42 | } 43 | 44 | int main() { 45 | try { 46 | Dog d; 47 | d.info(); 48 | d.speak(); 49 | 50 | std::cout << std::endl; 51 | 52 | Dog d1{0, 0.6}; 53 | d1.info(); 54 | d1.speak(); 55 | 56 | std::cout << std::endl; 57 | 58 | Snake s{true}; 59 | s.info(); 60 | s.speak(); 61 | 62 | std::cout << std::endl; 63 | 64 | Snake* p = new Snake{1, 2.3, false}; 65 | std::cout << "through pointer\n"; 66 | p->info(); 67 | p->speak(); 68 | 69 | delete p; 70 | 71 | std::cout << std::endl; 72 | 73 | print_animal(s); 74 | 75 | return 0; 76 | } catch (std::runtime_error& e) { 77 | std::cerr << e.what() << std::endl; 78 | return 1; 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /lectures/c++/06_error_handling/05_stack_unwinding.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "ap_error.h" 5 | 6 | class Foo { 7 | public: 8 | Foo() { std::cout << "Foo" << std::endl; } 9 | ~Foo() { std::cout << "~Foo" << std::endl; } 10 | }; 11 | 12 | class Bar { 13 | public: 14 | Bar() { std::cout << "Bar" << std::endl; } 15 | ~Bar() { std::cout << "~Bar" << std::endl; } 16 | }; 17 | 18 | class Vector { 19 | double* elem; 20 | 21 | public: 22 | Vector(const unsigned int l) : elem{new double[l]} { 23 | std::cout << "Vector" << std::endl; 24 | } 25 | ~Vector() { 26 | delete[] elem; 27 | std::cout << "~Vector" << std::endl; 28 | } 29 | }; 30 | 31 | class ManyResources { 32 | double* ptr; 33 | Vector v; 34 | 35 | public: 36 | ManyResources() : ptr{nullptr}, v{3} { 37 | std::cout << "Manyresources" << std::endl; 38 | try { 39 | ptr = new double[5]; // new(std::nothrow) double[5] could be better 40 | AP_ERROR(false) << "Error in ManyResources ctor." << std::endl; 41 | } catch (...) { 42 | delete[] ptr; // <---- 43 | throw; // re-throw 44 | } 45 | } 46 | 47 | ~ManyResources() { 48 | std::cout << "~Manyresources" << std::endl; 49 | delete[] ptr; // <---- 50 | } 51 | }; 52 | 53 | int main() { 54 | Foo f; 55 | int* raw_ptr = new int[7]; // do not use raw ptr 56 | try { 57 | // int * raw_ptr=new int[7]; // wrong because raw_ptr would not be visible 58 | // inside the catch-clause 59 | ManyResources mr; 60 | Bar b; 61 | 62 | } catch (const std::exception& e) { 63 | std::cerr << e.what() << std::endl; 64 | 65 | delete[] raw_ptr; // <--- try to comment this and run valgrind or use the 66 | // sanitize library 67 | return 1; 68 | 69 | } catch (...) { 70 | std::cerr << "Unknown exception. Aborting.\n" << std::endl; 71 | 72 | delete[] raw_ptr; // <--- 73 | return 2; 74 | } 75 | 76 | delete[] raw_ptr; // <--- 77 | return 0; 78 | } 79 | -------------------------------------------------------------------------------- /lectures/c++/02_functions_and_arrays/readme.md: -------------------------------------------------------------------------------- 1 | # Lecture 02_functions_and_arrays 2 | 3 | ## 01_auto.cc 4 | 5 | [link to file](./01_auto.cpp) 6 | 7 | This program introduces the `auto` specifier. When you declare a 8 | variable with this keyword its type will be automatically deduced by 9 | the compiler. 10 | 11 | PPP: chap 20.5.2 12 | CPL: chap 2.2.2, chap 6.3.6 13 | 14 | 15 | ## 02_functions.cpp 16 | [link to file](./02_functions.cpp) 17 | 18 | A function is a named sequence of statements. A function can return a result (return value), and since c++14 can be declared as `auto`. 19 | 20 | PPP: 4.5 21 | 22 | 23 | ## 03_overloading.cpp 24 | 25 | [link to file](./03_overloading.cpp) 26 | 27 | This program contains an example of *function overloading*. You can give two 28 | functions the same name provided that they differ by the types and/or the 29 | number of arguments. 30 | 31 | CPL: 12.3 32 | 33 | 34 | 35 | ## 04_templates.cpp 36 | 37 | [link to file](./04_templates) 38 | 39 | This program introduces the usage of *templates* for the function of the previous 40 | example. The template allows the function to work with different kinds of types, thus 41 | avoiding code repetitions (from the programmer). 42 | 43 | PPP: 19.3 44 | CPL: 3.4.1, 3.4.2 45 | 46 | 47 | ## 05_static_arrays.cpp 48 | 49 | [link to file](./05_static_arrays.cpp) 50 | 51 | Brief introduction to arrays in C++, examples of declaration and various initializations. 52 | There is also a demonstration of their consecutive representation in memory. 53 | The `std::string` class is a good alternative for `char` arrays. 54 | 55 | PPP: 17.2 arrays, 18.6 array and pointers 56 | CPL: 7.3 arrays 57 | 58 | 59 | 60 | ## 06_dynamic_arrays.cpp 61 | 62 | [link to file](./06_dynamic_arrays.cpp) 63 | 64 | Usage of the `new` function to allocate memory on the *heap* (also called free-store or dynamic memory) 65 | and consequent usage of `delete` to free it. 66 | 67 | PPP: 17.4 68 | CPL: 11.2 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | ### References: 78 | 79 | [PPP] Programming: Principles and Practice using C++ (Second Edition), Bjarne Stroustrup, Addison-Wesley 2014, ISBN 978-0-321-99278-9 80 | 81 | [CPL] The C++ Programming Language, Bjarne Stroustrup, Addison-Wesley 2013, ISBN 978-0321563842 82 | -------------------------------------------------------------------------------- /lectures/c++/03_more_on_pointers_and_vectors/readme.md: -------------------------------------------------------------------------------- 1 | # Lecture 03_more_on_pointers_and_vectors 2 | 3 | ## 01_const_and_pointers.cpp 4 | 5 | [link to file](./02_const_and_pointers.cpp) 6 | 7 | This example teaches you how to declare a `const` pointer or a pointer 8 | to a `const` object. It also introduces the usage of the *sentinel* 9 | method to loop over arrays. 10 | 11 | CPL: chap 7.5 12 | 13 | 14 | 15 | ## 02_special_pointers.cpp 16 | 17 | [link to file](./03_special_pointers.cpp) 18 | 19 | Here you can find more about pointers, like the `nullptr` keyword, the 20 | `static_cast` function, that can be used to perform conversions at 21 | compile time between compatible types, and the pointers to 22 | functions. `decltype()` is a function that returns the type of its 23 | argument. 24 | 25 | PPP: chap 17.4.5 nullptr, appendix A.5.7 static_cast, chap 27.2.5 pointer to func 26 | CPL: chap 2.2.5 nullptr, chap 6.3.6.3 decltype, chap 11.5.2 static_cast, chap 12.5 pointer to func 27 | 28 | 29 | 30 | 31 | ## 03_command_line_args.cpp 32 | 33 | [link to file](./04_command_line_args.cpp) 34 | 35 | This is a small example on how you can pass arguments to a program 36 | from the command line. 37 | 38 | CPL: chap 10.2.7 39 | 40 | 41 | 42 | 43 | ## 04_matrices.cpp 44 | 45 | [link to file](./05_matrices.cpp) 46 | 47 | This example shows the basics of how to implement the mathematical 48 | concept of matrix. 49 | 50 | CPL: chap 7.4.2 and 7.4.3 multidimensional arrays and passing arrays 51 | 52 | 53 | 54 | ## 05_std_arrays.cpp 55 | 56 | [link to file](./06_std_arrays.cpp) 57 | 58 | Introduction to the usage of `std::array` defined in the *array* 59 | header, together with *the range-for loop*. 60 | 61 | PPP: chap 20.9 62 | CPL: chap 2.2.5 and 9.5.1 range-for loop, chap 34.2.1 array 63 | 64 | 65 | 66 | ## 06_std_vectors.cpp 67 | 68 | [link to file](./07_std_vectors.cpp) 69 | 70 | Introduction to the `std::vector` class defined in the *vector* 71 | header. 72 | 73 | CPL: chap 31.4.1 74 | 75 | 76 | 77 | 78 | ### References: 79 | 80 | [PPP] Programming: Principles and Practice using C++ (Second Edition), Bjarne Stroustrup, Addison-Wesley 2014, ISBN 978-0-321-99278-9 81 | 82 | [CPL] The C++ Programming Language, Bjarne Stroustrup, Addison-Wesley 2013, ISBN 978-0321563842 83 | -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/beamerouterthemenasalines.sty: -------------------------------------------------------------------------------- 1 | % Copyright 2007 by Till Tantau 2 | % 3 | % This file may be distributed and/or modified 4 | % 5 | % 1. under the LaTeX Project Public License and/or 6 | % 2. under the GNU Public License. 7 | % 8 | % See the file doc/licenses/LICENSE for more details. 9 | 10 | \ProvidesPackageRCS $Header: /cvsroot/latex-beamer/latex-beamer/themes/outer/beamerouterthemenasalines.sty,v 1.9 2007/01/28 20:48:30 tantau Exp $ 11 | 12 | 13 | \mode 14 | 15 | \setbeamercolor*{author in head/foot}{parent=palette tertiary} 16 | \setbeamercolor*{title in head/foot}{parent=palette secondary} 17 | \setbeamercolor*{date in head/foot}{parent=palette primary} 18 | 19 | \setbeamercolor*{section in head/foot}{parent=palette tertiary} 20 | \setbeamercolor*{subsection in head/foot}{parent=palette primary} 21 | 22 | \defbeamertemplate*{footline}{infolines theme} 23 | { 24 | \leavevmode% 25 | \hbox{% 26 | \begin{beamercolorbox}[wd=.333333\paperwidth,ht=2.25ex,dp=1ex,center]{author in head/foot}% 27 | %\usebeamerfont{author in head/foot}\insertshortauthor 28 | \usebeamerfont{author in head/foot}\insertshortauthor~~\insertshortinstitute 29 | \end{beamercolorbox}% 30 | \begin{beamercolorbox}[wd=.333333\paperwidth,ht=2.25ex,dp=1ex,center]{title in head/foot}% 31 | \usebeamerfont{title in head/foot}\insertshorttitle 32 | \end{beamercolorbox}% 33 | \begin{beamercolorbox}[wd=.333333\paperwidth,ht=2.25ex,dp=1ex,right]{date in head/foot}% 34 | \usebeamerfont{date in head/foot}\insertshortdate{}\hspace*{2em} 35 | \insertframenumber{} / \inserttotalframenumber\hspace*{2ex} 36 | \end{beamercolorbox}}% 37 | \vskip0pt% 38 | } 39 | 40 | \defbeamertemplate*{headline}{infolines theme} 41 | { 42 | \leavevmode% 43 | \hbox{% 44 | \begin{beamercolorbox}[wd=.5\paperwidth,ht=2.25ex,dp=1ex,right]{section in head/foot}% 45 | \usebeamerfont{section in head/foot}\insertsectionhead\hspace*{2ex} 46 | \end{beamercolorbox}% 47 | \begin{beamercolorbox}[wd=.5\paperwidth,ht=2.25ex,dp=1ex,left]{subsection in head/foot}% 48 | \usebeamerfont{subsection in head/foot}\hspace*{2ex}\insertsubsectionhead 49 | \end{beamercolorbox}}% 50 | \vskip0pt% 51 | } 52 | 53 | \setbeamersize{text margin left=1em,text margin right=1em} 54 | 55 | \mode 56 | 57 | -------------------------------------------------------------------------------- /lectures/c++/07_inheritance/01_inheritance.cpp: -------------------------------------------------------------------------------- 1 | #include "ap_error.h" 2 | #include 3 | 4 | struct Animal { 5 | unsigned int age; 6 | double weight; 7 | 8 | Animal(const unsigned int a, const double w) : age{a}, weight{w} { 9 | AP_ERROR(weight >= 0) << "invalid weight: " << weight << std::endl; 10 | } 11 | 12 | Animal() noexcept : Animal{0, 0} {} // delegating constructor 13 | 14 | void speak() const noexcept { std::cout << "Unknown\n"; } 15 | void info() const noexcept { 16 | std::cout << "age:\t" << age << '\n' << "weight:\t" << weight << '\n'; 17 | } 18 | }; 19 | 20 | struct Dog : public Animal { 21 | void speak() const noexcept { std::cout << "Bau\n"; } 22 | Dog() noexcept = default; 23 | Dog(const unsigned int a, const double d) : Animal{a, d} {} 24 | }; 25 | 26 | struct Snake : public Animal { 27 | bool dangerous; 28 | Snake(const unsigned int a, const double w, const bool b) 29 | : Animal{a, w}, dangerous{b} {} 30 | explicit Snake(const bool b) noexcept : Animal{}, dangerous{b} {} 31 | void info() const noexcept { 32 | Animal::info(); 33 | std::cout << "dangerous:\t" << (dangerous ? "true" : "false") << std::endl; 34 | } 35 | void speak() const noexcept { std::cout << "ssss\n"; } 36 | }; 37 | 38 | // run-time (dynamic) polymorphism 39 | void print_animal(const Animal& a) noexcept { 40 | std::cout << "through ref\n"; 41 | a.info(); 42 | a.speak(); 43 | } 44 | 45 | // compile-time (static) polymorphism 46 | template 47 | void print_animal_template(const T& a) noexcept { 48 | std::cout << "through template\n"; 49 | a.info(); 50 | a.speak(); 51 | } 52 | 53 | int main() { 54 | try { 55 | Dog d; 56 | d.info(); 57 | d.speak(); 58 | 59 | std::cout << std::endl; 60 | 61 | Dog d1{0, 0.6}; 62 | d1.info(); 63 | d1.speak(); 64 | 65 | std::cout << std::endl; 66 | 67 | Snake s{true}; 68 | s.info(); 69 | s.speak(); 70 | 71 | std::cout << std::endl; 72 | 73 | Animal* p = new Snake{1, 2.3, false}; 74 | std::cout << "through pointer\n"; 75 | p->info(); 76 | p->speak(); 77 | 78 | delete p; 79 | 80 | std::cout << std::endl; 81 | 82 | print_animal(s); 83 | 84 | std::cout << std::endl; 85 | 86 | print_animal_template(s); 87 | 88 | return 0; 89 | } catch (std::runtime_error& e) { 90 | std::cerr << e.what() << std::endl; 91 | return 1; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /lectures/c++/03_more_on_pointers_and_vectors/02_special_pointers.cpp: -------------------------------------------------------------------------------- 1 | #include // strcmp 2 | #include 3 | 4 | int func1(const char* a); 5 | int func2(const char* a); 6 | void func3(const char* a); 7 | 8 | int main() { 9 | int a{8}; 10 | int* pi{&a}; 11 | 12 | char** ppc; 13 | 14 | int* ap[7]; 15 | 16 | void* pv{pi}; 17 | // *pv; // we cannot dereference void* 18 | // ++pv; // we cannot increment. Why? 19 | int* pi2{static_cast(pv)}; 20 | 21 | pv = ppc; 22 | pv = ap; 23 | pv = pi; 24 | 25 | pi = nullptr; 26 | ppc = nullptr; 27 | // ap = nullptr; // error, why? 28 | ap[0] = nullptr; 29 | int** bbb; 30 | bbb = ap; 31 | pv = nullptr; 32 | pi2 = 0; // older codes. gets the nullptr 33 | 34 | // pi = NULL; // please don't do this 35 | 36 | double* da{new double[5]{}}; 37 | delete[] da; // dangling pointer 38 | da = nullptr; 39 | 40 | if (pi != nullptr) 41 | std::cout << "pi is not nullptr and I can dereference it " << *pi 42 | << std::endl; 43 | 44 | if (pi) 45 | std::cout << "pi is not nullptr and I can dereference it " << *pi 46 | << std::endl; 47 | 48 | if (pi == nullptr) 49 | std::cout << "pi is nullptr and I CANNOT dereference it \n"; 50 | 51 | if (!pi) 52 | std::cout << "pi is nullptr and I CANNOT dereference it \n"; 53 | 54 | // strings are special type of char[] 55 | char word[]{"Hello"}; 56 | char word2[]{'H', 'e', 'l', 'l', 'o', 0}; 57 | if (strcmp(word, word2) == 0) // word == word2 is 58 | // implementation-dependent (it might 59 | // compare the two pointers, i.e. the 60 | // two addresses of word and word2) 61 | std::cout << "same\n"; 62 | else 63 | std::cout << "different\n"; 64 | 65 | int (*fp)(const char*); 66 | fp = func1; 67 | 68 | fp("hello"); 69 | 70 | fp = &func2; 71 | fp("world"); 72 | 73 | // fp = func3; // error: wrong signature 74 | auto xx = func3; 75 | 76 | xx("auto"); 77 | 78 | decltype(&func3) x = func3; 79 | x("decltype"); 80 | 81 | return 0; 82 | } 83 | 84 | int func1(const char* a) { 85 | std::cout << "1111: " << a << std::endl; 86 | return 1; 87 | } 88 | 89 | int func2(const char* a) { 90 | std::cout << "2222: " << a << std::endl; 91 | return 2; 92 | } 93 | 94 | void func3(const char* a) { 95 | std::cout << "3333: " << a << std::endl; 96 | } 97 | -------------------------------------------------------------------------------- /lectures/c++/07_inheritance/05_dynamic_cast.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | class Animal { 5 | unsigned int age; 6 | double weight; 7 | 8 | public: 9 | Animal(const unsigned int a, const double w) : age{a}, weight{w} { 10 | AP_ERROR_GE(weight, 0) << "invalid weight!\n"; 11 | } 12 | 13 | Animal() : Animal{0, 0} {} // delegating constructor 14 | 15 | virtual void speak() const = 0; 16 | virtual void info() const noexcept { 17 | std::cout << "age:\t" << age << '\n' << "weight:\t" << weight << '\n'; 18 | } 19 | 20 | virtual ~Animal() {} 21 | }; 22 | 23 | class Dog : public Animal { 24 | public: 25 | void speak() const noexcept override { std::cout << "Bau\n"; } 26 | Dog() = default; 27 | Dog(const unsigned int a, const double d) : Animal{a, d} {} 28 | }; 29 | 30 | class Snake : public Animal { 31 | bool dangerous; 32 | 33 | public: 34 | Snake(const unsigned int a, const double w, const bool b) 35 | : Animal{a, w}, dangerous{b} {} 36 | explicit Snake(const bool b) : Animal{}, dangerous{b} {} 37 | void info() const noexcept override { 38 | Animal::info(); 39 | std::cout << "dangerous:\t" << (dangerous ? "true" : "false") << std::endl; 40 | } 41 | void speak() const noexcept override { std::cout << "ssss\n"; } 42 | }; 43 | 44 | class DangerousSnake : public Snake { 45 | public: 46 | DangerousSnake(const unsigned int a, const double w) : Snake{a, w, true} {} 47 | DangerousSnake() : Snake{true} {} 48 | }; 49 | 50 | class NonDangerousSnake : public Snake { 51 | public: 52 | NonDangerousSnake(const unsigned int a, const double w) 53 | : Snake{a, w, false} {} 54 | NonDangerousSnake() : Snake{false} {} 55 | }; 56 | 57 | struct Python : public NonDangerousSnake {}; 58 | 59 | using Anaconda = DangerousSnake; 60 | 61 | void print_animal(const Animal& a) noexcept { 62 | a.info(); 63 | a.speak(); 64 | 65 | // dynamic_cast is used to know the real type of the object 66 | if (dynamic_cast(&a)) 67 | std::cout << "call 911...\n"; 68 | } 69 | 70 | int main() { 71 | try { 72 | Python s; 73 | print_animal(s); 74 | 75 | std::cout << std::endl; 76 | 77 | // Animal* p = new DangerousSnake{1, 2.3}; 78 | Animal* p = new Anaconda{1, 2.3}; 79 | 80 | print_animal(*p); 81 | delete p; 82 | 83 | return 0; 84 | } catch (std::runtime_error& e) { 85 | std::cerr << e.what() << std::endl; 86 | return 1; 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /lectures/c++/07_inheritance/04_private.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | class Animal { 5 | unsigned int age; 6 | double weight; 7 | 8 | public: 9 | Animal(const unsigned int a, const double w) : age{a}, weight{w} { 10 | AP_ERROR_GE(weight, 0) << "invalid weight!\n"; 11 | } 12 | 13 | Animal() : Animal{0, 0} {} // delegating constructor 14 | 15 | virtual void speak() const = 0; 16 | virtual void info() const noexcept { 17 | std::cout << "age:\t" << age << '\n' << "weight:\t" << weight << '\n'; 18 | } 19 | 20 | virtual ~Animal() {} 21 | }; 22 | 23 | class Dog : public Animal { 24 | public: 25 | void speak() const noexcept override { std::cout << "Bau\n"; } 26 | Dog() = default; 27 | Dog(const unsigned int a, const double d) : Animal{a, d} {} 28 | }; 29 | 30 | class Snake : public Animal { 31 | bool dangerous; 32 | 33 | public: 34 | Snake(const unsigned int a, const double w, const bool b) 35 | : Animal{a, w}, dangerous{b} {} 36 | explicit Snake(const bool b) : Animal{}, dangerous{b} {} 37 | void info() const noexcept override { 38 | Animal::info(); 39 | std::cout << "dangerous:\t" << (dangerous ? "true" : "false") << std::endl; 40 | } 41 | void speak() const noexcept override { std::cout << "ssss\n"; } 42 | }; 43 | 44 | class DangerousSnake : public Snake { 45 | public: 46 | DangerousSnake(const unsigned int a, const double w) : Snake{a, w, true} {} 47 | DangerousSnake() : Snake{true} {} 48 | }; 49 | 50 | class NonDangerousSnake : public Snake { 51 | public: 52 | NonDangerousSnake(const unsigned int a, const double w) 53 | : Snake{a, w, false} {} 54 | NonDangerousSnake() : Snake{false} {} 55 | }; 56 | 57 | struct Python : public NonDangerousSnake {}; 58 | 59 | using Anaconda = DangerousSnake; 60 | 61 | void print_animal(const Animal& a) noexcept { 62 | std::cout << "throught ref\n"; 63 | a.info(); 64 | a.speak(); 65 | } 66 | 67 | int main() { 68 | try { 69 | Python s; 70 | s.info(); 71 | s.speak(); 72 | 73 | std::cout << std::endl; 74 | 75 | // Animal* p = new DangerousSnake{1, 2.3}; 76 | Animal* p = new Anaconda{1, 2.3}; 77 | 78 | std::cout << "through pointer\n"; 79 | p->info(); 80 | p->speak(); 81 | 82 | delete p; 83 | 84 | std::cout << std::endl; 85 | 86 | print_animal(s); 87 | 88 | return 0; 89 | } catch (std::runtime_error& e) { 90 | std::cerr << e.what() << std::endl; 91 | return 1; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /exercises/c++/01_intro/readme.md: -------------------------------------------------------------------------------- 1 | # Exercises - session 01 2 | 3 | ## Understanding compiler messages 4 | - Take a simple program (e.g., the hello world one) and put one at a time the following errors. Compile it and try to understand the error messages. If you have different compilers compare the messages from the two compilers. 5 | - do not put the `main` function 6 | - typos in function name (e.g., `c0ut`) 7 | - typos in variable name 8 | - forget to put `;` 9 | - forget to `#include ` 10 | - declare a variable with illegal name like `int double {0};` 11 | 12 | 13 | ## uniq 14 | - Write a simple version of the Unix program `uniq -c`, which, when fed with a text, outputs the same text with **consecutive** identical lines collapsed into one prepended with the number of repetitions. 15 | 16 | You can scan the stdin as follows 17 | ``` 18 | std::string line; 19 | while(std::getline(std::cin,line)) 20 | {...} 21 | ``` 22 | or 23 | ``` 24 | for(std::string line; std::getline(std::cin,line);) 25 | {...} 26 | ``` 27 | What do you think it is better? Why? 28 | 29 | Remember that if you type directly from stdin, you should press `Ctr+D` to close the stdin without interrupting the program. Moreover, you can redirect the content of a text to stdin trough the `<` operator 30 | ``` 31 | ./a.out `, so, remember to include it! 44 | 45 | ## Getters 46 | - write a function `get_int` that reads from stdin until a valid number is fed 47 | - write a function `get_double` that reads from stdin until a valid number is fed. 48 | 49 | *Hints*: 50 | You can keep reading from stdin using one of two statements 51 | ``` 52 | while(std::cin >> i) 53 | ``` 54 | or 55 | ``` 56 | while(!(std::cin >> i)) 57 | ``` 58 | what is the difference? 59 | 60 | After that a wrong input has been parsed, you have to clear the error flag from `std::cin` calling 61 | ``` 62 | std::cin.clear(); 63 | ``` 64 | and ignore what just read 65 | ``` 66 | std::cin.ignore(); 67 | ``` 68 | 69 | ## Units of measure 70 | 71 | - Write a code that reads a number with its proper unit of measure, and prints back that number according to the SI units, e.g. 72 | 73 | ``` 74 | 1 inch 75 | 0.0254 m 76 | ``` 77 | 78 | ## **Optional**: Text formatter 79 | - Write a simple text formatter that breaks the lines longer than a given number of characters. This formatter does not break words and leaves unmodified the lines shorter than the given threshold. 80 | -------------------------------------------------------------------------------- /exam/python_exam.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Reverse dictionary\n", 8 | "\n", 9 | "Given the following `dict` `d` compute the reverse dictionary `rd`. Let `k_d` and `v_d` be the keys and values of `d`, respectively. The keys of `rd` `k_rd` are all the integer numbers contained in all the `v_d`. The values of `rd` are lists containing all the keys `k_d` where `k_rd` is inside the corresponding `v_d`. For example\n", 10 | "```python\n", 11 | "d = {\"a\": [1, 2, 3], \"b\": [45, 6], \"c\": [2, 45]}\n", 12 | "\n", 13 | "rd = {1: [\"a\"], 2: [\"a\", \"c\"], 3: [\"a\"], 6: [\"b\"], 45: [\"b\", \"c\"]}\n", 14 | "```\n", 15 | "\n", 16 | "If you do not write the proper code, the computational time might exceed the time given for the exam! Numpy is not required.\n", 17 | "\n", 18 | "Hints: \n", 19 | "- comprehensions are your friend.\n", 20 | "- work on a small dictionay, once you are satisfied with your code, apply it to the big `d`\n", 21 | "- you can use the `test_exam.py` to test your implementation running `pytest test_exam.py` " 22 | ] 23 | }, 24 | { 25 | "cell_type": "code", 26 | "execution_count": null, 27 | "metadata": {}, 28 | "outputs": [], 29 | "source": [ 30 | "chars = \"qwertyuiopasdfghjklzxcvbnm\"\n", 31 | "chars = sorted(chars.upper() + chars)\n", 32 | "\n", 33 | "keys = [c + str(n) for c in chars for n in range(100)]\n", 34 | "\n", 35 | "import random\n", 36 | "\n", 37 | "random.seed(42)\n", 38 | "\n", 39 | "d = {k: [random.randint(1, 200) for _ in range(random.randint(1, 10))] for k in keys}\n", 40 | "\n", 41 | "for i, (k, v) in enumerate(d.items()):\n", 42 | " print(k, \":\", v)\n", 43 | " if i == 10:\n", 44 | " break" 45 | ] 46 | }, 47 | { 48 | "cell_type": "code", 49 | "execution_count": null, 50 | "metadata": {}, 51 | "outputs": [], 52 | "source": [ 53 | "def reverse_dict(d):\n", 54 | " pass\n", 55 | "\n", 56 | "rd = reverse_dict(d)" 57 | ] 58 | } 59 | ], 60 | "metadata": { 61 | "kernelspec": { 62 | "display_name": "Python 3", 63 | "language": "python", 64 | "name": "python3" 65 | }, 66 | "language_info": { 67 | "codemirror_mode": { 68 | "name": "ipython", 69 | "version": 3 70 | }, 71 | "file_extension": ".py", 72 | "mimetype": "text/x-python", 73 | "name": "python", 74 | "nbconvert_exporter": "python", 75 | "pygments_lexer": "ipython3", 76 | "version": "3.7.6" 77 | } 78 | }, 79 | "nbformat": 4, 80 | "nbformat_minor": 4 81 | } 82 | -------------------------------------------------------------------------------- /lectures/c++/05_copy_move_semantics/readme.md: -------------------------------------------------------------------------------- 1 | # 06_copy_move_semantics 2 | 3 | 4 | ## 01_surprise.cpp 5 | 6 | [link to file](./01_surprise.cpp) 7 | 8 | This program highlights that a compiler is able to generate a default 9 | constructor, copy constructor, copy assignment, move constructor and 10 | move assignment, and illustrates their syntax. The function 11 | `std::move()` is used to get a r-value reference. 12 | 13 | 14 | PPP: chap 18.3 copying 15 | CPL: chap 17.5 copy and move 16 | 17 | 18 | 19 | 20 | ## 02_default.cpp 21 | 22 | [link to file](./02_default.cpp) 23 | 24 | The compiler-generated default ctor behave very differntly if invoked 25 | with or without `{}`. The aggregate initialization is addressed as 26 | well. 27 | 28 | PPP: chap 9.7.3 default constructors 29 | CPL: chap 17.6.1 default 30 | 31 | 32 | 33 | 34 | ## 03_default.cpp 35 | 36 | [link to file](./03_default.cpp) 37 | Shows how to use the `default` keyword to explicitly ask the compiler 38 | to create a default constructor (or assignment operator) even if other 39 | constructors are present. The keyword `delete`, instead, is used to 40 | eliminate a particular function. 41 | Shows the usage of *in-class* initialization and aggregate initialization and their relationships with the constructors. 42 | 43 | PPP: chap 9.7.3 44 | CPL: chap 17.6.1 default, chap 17.6.4 delete 45 | 46 | 47 | ## 04_buggy_vector.cpp 48 | 49 | [link to file](./04_buggy_vector.cpp) 50 | 51 | This program illustrates the behavior of the class Vector, that 52 | handles some **allocated** memory, when a proper copy constructor is 53 | not defined, and the one provided by the compiler is used (**shallow 54 | copy**). The constructor for this class is defined `explicit`. 55 | 56 | 57 | PPP: chap 18.4.1 explicit constructor 58 | CPL: chap 16.2.6 explicit constructor 59 | 60 | 61 | 62 | ## 05_buggy_vector.cpp 63 | 64 | [link to file](./05_buggy_vector.cpp) 65 | 66 | Same as the previous one, but this time the elements are stored using a `std::unique_ptr`. No copy semantic can be defined by the compiler because it has been `delete`d in the `std::unique_ptr` class 67 | 68 | 69 | 70 | 71 | ## 06_copy_move.cpp 72 | 73 | [link to file](./06_copy_move.cpp) 74 | 75 | Implements the copy and move semantics for the Vector class and shows some examples. 76 | 77 | PPP: chap 18.3 copying 78 | CPL: chap 17.5 copy and move 79 | 80 | 81 | 82 | ### References: 83 | 84 | [PPP] = Programming: Principles and Practice using C++ (Second Edition), Bjarne Stroustrup, Addison-Wesley 2014, ISBN 978-0-321-99278-9 85 | 86 | [CPL] = The C++ Programming Language, Bjarne Stroustrup, Addison-Wesley 2013, ISBN 978-0321563842 87 | -------------------------------------------------------------------------------- /exercises/c++/04_custom_types/multiple_flags.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | enum class flags : unsigned int { 4 | flag1 = 1, 5 | flag2 = 2, 6 | flag3 = 4, 7 | // flag4 = 8 | flag1 | flag2, // imply flag1 and flag2 easy to implement, but 8 | // difficult to compare.. 9 | flag4 = 8, // additional functions needed 10 | flag5 = 16, // imply flag3 11 | 12 | // useful combinations 13 | comb1 = flag1 | flag2, 14 | comb2 = flag1 | flag3, 15 | comb3 = comb1 | flag3, 16 | }; 17 | 18 | void do_complicated_stuff(flags flags); 19 | 20 | flags operator|(const flags f1, const flags f2); 21 | 22 | unsigned int operator&(const flags f1, const flags f2); 23 | 24 | flags& operator|=(flags& f1, const flags f2); 25 | 26 | int main() { 27 | std::cout << "testing flag1 and flag3\n" 28 | << "expected flag1 and flag3 \n\n"; 29 | do_complicated_stuff(flags::flag1 | flags::flag3 | flags::flag1 | 30 | flags::flag1); 31 | 32 | std::cout << "--------------\n\n" 33 | << "testing comb3\n" 34 | << "expected flag1, flag2 and flag3 \n\n"; 35 | do_complicated_stuff(flags::comb3); 36 | 37 | std::cout << "--------------\n\n" 38 | << "testing flag4\n" 39 | << "expected flag1, flag2 and flag4 \n\n"; 40 | do_complicated_stuff(flags::flag4); 41 | 42 | std::cout << "--------------\n\n" 43 | << "testing flag5\n" 44 | << "expected flag3 and flag5 \n\n"; 45 | do_complicated_stuff(flags::flag5); 46 | 47 | return 0; 48 | } 49 | 50 | flags operator|(const flags f1, const flags f2) { 51 | return static_cast(static_cast(f1) | 52 | static_cast(f2)); 53 | } 54 | 55 | unsigned int operator&(const flags f1, const flags f2) { 56 | return static_cast(static_cast(f1) & 57 | static_cast(f2)); 58 | } 59 | 60 | flags& operator|=(flags& f1, const flags f2) { 61 | f1 = f1 | f2; 62 | return f1; 63 | } 64 | 65 | void compute_multiple_flags(flags& f) { 66 | if (f & flags::flag4) 67 | f |= (flags::flag1 | flags::flag2); 68 | if (f & flags::flag5) 69 | f |= flags::flag3; 70 | } 71 | 72 | void do_complicated_stuff(flags flags) { 73 | // update flags correctly 74 | compute_multiple_flags(flags); 75 | 76 | if (flags & flags::flag1) 77 | std::cout << "flag 1 selected\n"; 78 | if (flags & flags::flag2) 79 | std::cout << "flag 2 selected\n"; 80 | if (flags & flags::flag3) 81 | std::cout << "flag 3 selected\n"; 82 | if (flags & flags::flag4) 83 | std::cout << "flag 4 selected\n"; 84 | if (flags & flags::flag5) 85 | std::cout << "flag 5 selected\n"; 86 | } 87 | -------------------------------------------------------------------------------- /lectures/c++/01_intro/readme.md: -------------------------------------------------------------------------------- 1 | # Lecture 01_intro 2 | 3 | 4 | ## 01_variables.cc 5 | 6 | [link to file](./01_variables.cc) 7 | 8 | Introduces many built-in types (such as int, double, char and bool), and 9 | also some basic operations defined on them (like +, -, +=, -=, ==, <=, and %). 10 | The *universal and uniform initializer ({})* is introduced, together with the *const* 11 | declaration for variables. 12 | 13 | 14 | PPP: basically all chapter 3 15 | CPL: all chapter 6 is dedicated to types but is too technical, 6.3.5 explains 16 | in detail why the universal and uniform initializer is better. 17 | 18 | 19 | 20 | ## 02_hello_name.cc 21 | 22 | [link to file](./02_hello_name.cc) 23 | 24 | Introductory program that says hello to the user, after this one has 25 | inserted his name and age. You can see the usage of `std::cout` and `std::cin`, and 26 | an example of the class string. 27 | 28 | PPP: chapter 2, take a look also at chapter 1 29 | 30 | 31 | 32 | 33 | ## 03_loops.cc 34 | 35 | [link to file](./03_loops.cc) 36 | 37 | Example with the most common types of loops in C++: the `for` loop, the `while` and 38 | the `do while` loop. 39 | 40 | 41 | PPP: chapter 4.4 42 | 43 | 44 | 45 | 46 | 47 | 48 | ## 04_vars_pointers_refs.cc 49 | 50 | [link to file](./04_vars_pointers_refs.cc) 51 | 52 | Small introduction to the usage of *pointers* and *references*. 53 | 54 | PPP: chap 17.9 for pointers and references 55 | CPL: chap 7.2 for pointers, 7.7 for references 56 | 57 | 58 | 59 | 60 | 61 | ## 05_functions.cc 62 | 63 | [link to file](./05_functions.cc) 64 | 65 | Three different implementations of a function that swaps two integers, one of them is used to 66 | introduce the concept of *pass by reference*. 67 | 68 | PPP: chap 4.5 for introduction to functions, chap 8.5 for a more detailed discussion, with 69 | also the *pass by value*, *pass by const-reference* and *pass by reference* principles and 70 | practices. 71 | 72 | CPL: all chap 12 is dedicated to functions, but maybe is too detailed for the moment 73 | 74 | 75 | 76 | 77 | ## 06_watch_out.cc 78 | 79 | [link to file](./06_watch_out.cc) 80 | 81 | 82 | This program shows two typical problems one can encounter in programming: the integer 83 | overflow and the uncorrect representation of certain floating point numbers. The function 84 | `std::setprecision()` allows the user to set the decimal precision for the output operations. 85 | 86 | 87 | PPP: chapter 24.2 88 | 89 | 90 | 91 | 92 | 93 | 94 | ### References: 95 | 96 | [PPP] Programming: Principles and Practice using C++ (Second Edition), Bjarne Stroustrup, Addison-Wesley 2014, ISBN 978-0-321-99278-9 97 | 98 | [CPL] The C++ Programming Language, Bjarne Stroustrup, Addison-Wesley 2013, ISBN 978-0321563842 99 | -------------------------------------------------------------------------------- /lectures/c++/07_inheritance/readme.md: -------------------------------------------------------------------------------- 1 | # 07_inheritance 2 | 3 | 4 | 5 | ## 00_first_trial.cpp 6 | 7 | [link to file](./00_first_trial.cpp) 8 | 9 | A naive and conceptually wrong implementation of a series of classes that share data. 10 | 11 | PPP: chap 14.3 12 | CPL: chap 20.1, 20.2 13 | 14 | 15 | 16 | ## 01_inheritance.cpp 17 | 18 | [link to file](./01_inheritance.cpp) 19 | 20 | A wrong implementation with *inheritance*. In particular, the run-time polymorphism is not working. 21 | 22 | PPP: chap 14.3 23 | CPL: chap 20.1, 20.2 24 | 25 | 26 | 27 | ## 02_virtual.cpp 28 | 29 | [link to file](./02_virtual.cpp) 30 | 31 | This program shows the usage of the `virtual` keyword when working with derived classes methods. 32 | The specifier `override` is used to force the compiler to check that we are actually overriding a function of the base class. 33 | 34 | PPP: chap 14.3.2 35 | CPL: chap 3.2.2, 3.2.3, 3.2.4 for an introduction, chap 20 for more details 36 | 37 | 38 | 39 | 40 | ## 03_virtual_destructor.cpp 41 | 42 | [link to file](./03_virtual_destructor.cpp) 43 | 44 | Shows the order in which the constructors and the destructors for derived objects are 45 | called. Using run-time polymorphism, to call the proper destructor (and not always and only the destructor of the base class), the destructor of the base class must be *virtual*. 46 | 47 | PPP: chap 17.5.2 48 | CPL: chap 17.2.5 49 | 50 | 51 | 52 | ## 04_private.cpp 53 | 54 | [link to file](./04_private.cpp) 55 | 56 | Trivial example to demonstrate how to deal with parents with private data. 57 | 58 | PPP: chap 14.3.5 59 | CPL: chap 20.4 60 | 61 | 62 | 63 | ## 05_dynamic_cast.cpp 64 | 65 | [link to file](./05_dynamic_cast.cpp) 66 | 67 | This example illustrates the usage of dynamic casting to perform a type conversion at run-time. 68 | 69 | PPP: appendix A.5.7 70 | CPL: chap 22.2.1 71 | 72 | 73 | 74 | ## 06_template.cpp 75 | 76 | [link to file](./06_template.cpp) 77 | 78 | When we inherit from a templated class, we need to use `this->` to acppess parent's member. 79 | 80 | CPL: chap 26.3.7 81 | 82 | 83 | 84 | ## 07_using.cpp 85 | 86 | [link to file](./07_using.cpp) 87 | 88 | Functions do not overload across scopes. 89 | 90 | CPL: chap 12.3.3, 20.3.5 91 | 92 | 93 | 94 | ## example of structured library 95 | [link_to_folder](./organized) 96 | 97 | Example of how to document and organized a simple library. 98 | 99 | 100 | ### References: 101 | 102 | [PPP] = Programming: Principles and Practice using C++ (Second Edition), Bjarne Stroustrup, Addison-Wesley 2014, ISBN 978-0-321-99278-9 103 | 104 | [CPL] = The C++ Programming Language, Bjarne Stroustrup, Addison-Wesley 2013, ISBN 978-0321563842 105 | -------------------------------------------------------------------------------- /lectures/c++/04_custom_types/readme.md: -------------------------------------------------------------------------------- 1 | # Lecture 04_custom_types 2 | 3 | 4 | ## 01_enum.cpp 5 | 6 | [link to file](./01_enum.cpp) 7 | 8 | The idea behind enumeration is to create a new type whose values are restricted to a specific range or set of values. This example illustrates the plain `enum` syntax and usage. 9 | 10 | PPP: chap 9.5 11 | CPL: chap 8.4 12 | 13 | 14 | 15 | ## 02_scoped_enum.cpp 16 | 17 | [link to file](./02_scoped_enum.cpp) 18 | 19 | Introduces the *scoped enum*, extension of the "plain enum" described before. Now the enumerator name must be qualified by the enum type name and the scope resolution operator. They are not implicitly converted to integers. 20 | 21 | PPP: chap 9.5 22 | CPL: chap 8.4 23 | 24 | 25 | 26 | ## 03_namespace.cpp 27 | 28 | [link to file](./04_namespace.cpp) 29 | 30 | `namespace` allows to group variables, functions and classes into a proper set. Examples on the usage of the `namespace` keyword are given. 31 | 32 | PPP: 8.7 and 8.7.1 33 | CPL: chapter 14 34 | 35 | 36 | 37 | ## 04_why_scoped.cpp 38 | 39 | [link to file](./03_why_scoped.cpp) 40 | 41 | This program demonstrates how the plain enum can lead to name clashing, which can be avoided through scoped enum. 42 | 43 | 44 | 45 | 46 | ## 05_struct_class.cpp 47 | 48 | [link to file](./05_struct_class.cpp) 49 | 50 | The program implements a very simple `struct` and a very simple `class` to show the different *default* visibility of their members. 51 | 52 | 53 | PPP: 9.2, 9.3 and 9.4 54 | CPL: chap 16 for classes, in particular chap 16.2.4 (class and struct) 55 | 56 | 57 | ## 06_operator_overloading.cpp 58 | 59 | [link to file](./06_operator_overloading.cpp) 60 | 61 | A simple example about **operator overloading**. The `friend` keyword is addressed as well. 62 | 63 | PPP: 9.6 64 | CPL: 3.2.1.1 (for a quick example), chap 18 for all the details 65 | 66 | 67 | ## 07_constructor_destructor.cpp 68 | 69 | [link to file](./07_constructor_destructor.cpp) 70 | 71 | This example introduces you to the concepts of *constructor* and *destructor* of a class. Here you can also find the first example of *operator overloading*. 72 | 73 | PPP: chap 9.4.2 constructors, chap 17.5 destructors, chap 9.6 operator overloading 74 | CPL: chap 16.2.5 constructors, chap 17.2 constructors and destructors, chap 18 operator overloading 75 | 76 | 77 | 78 | ## 08_template_class.cpp 79 | 80 | [link to file](./08_template_class.cpp) 81 | 82 | A naive implementation of a vector class, using the template for the type stored in the vector. 83 | 84 | 85 | 86 | 87 | ###References: 88 | 89 | [PPP] = Programming: Principles and Practice using C++ (Second Edition), Bjarne Stroustrup, Addison-Wesley 2014, ISBN 978-0-321-99278-9 90 | 91 | [CPL] = The C++ Programming Language, Bjarne Stroustrup, Addison-Wesley 2013, ISBN 978-0321563842 92 | -------------------------------------------------------------------------------- /exercises/c++/02_arrays/readme.md: -------------------------------------------------------------------------------- 1 | # Exercises - session 02 2 | 3 | ## Reverse order 4 | 5 | - Write a program that reads from stdin the length of an array and then stores in it the numbers given from stdin. The program should then print the numbers in **reverse order**. Remember to free the used memory properly. Divide the problem into two parts: 6 | 7 | 1. Write one **template** function that allocates on the *heap* one array of a given size, initializes its elements, and returns the pointer to the first element. 8 | 9 | 2. Write a **template** function that prints the elements of an array in the reverse order. 10 | 11 | - Test with integers and doubles. 12 | 13 | - Use `std::size_t`. 14 | 15 | ​ 16 | 17 | *Hints*: 18 | 19 | - If you have to pass an array to a function, pass the pointer to its first element and the size of the array itself. 20 | 21 | 22 | - Remember to check your code with `valgrind`. If you have a MAC, you might have nasty surprises. Run `valgrind` on a **Linux** system. Alternatively, compile and link your code with the following flags 23 | 24 | `-g -fsanitize=address` and then run your executable. If it runs fine, you have no memory leaks. If it doesn't, you have some. 25 | 26 | ​ 27 | 28 | ## Prime numbers 29 | 30 | - Populate an array named `primes` containing the first prime numbers smaller than 100. Consider 2 as the first prime (i.e. `primes[0] == 2`). 31 | 32 | - you are free to choose the design and the implementation. 33 | 34 | - please comment and motivate your choices (e.g., allocate one big 35 | array, or every time I find a new prime number I increase the size of 36 | the previous `primes` array, etc.) 37 | 38 | *Hints*: 39 | 40 | - The remainder of a division between two integers is computed as follows: 41 | ```c++ 42 | unsigned int remainder = 6%3; 43 | ``` 44 | - Inside a for loop, you can use `continue` to immediately go to the next iteration, `break` to exit the loop. Note that if you have two or more nested loops, the statements affect only the innermost loop. 45 | 46 | 47 | 48 | ## Sieve of Eratosthenes 49 | 50 | - Implement the Sieve of Eratosthenes algorithm. Write a code that prints on screen the first prime numbers up to `N` **included**, where `N` is read from stdin. The first printed number is `2`. 51 | 52 | ```shell 53 | $ ./a.out 54 | insert number: 5 55 | 2 56 | 3 57 | 5 58 | 59 | $ ./a.out 60 | insert number: 10 61 | 2 62 | 3 63 | 5 64 | 7 65 | ``` 66 | 67 | *Hints*: 68 | - https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes :) 69 | 70 | - the function `std::sqrt`, which computes the square root of a number, is defined in `` 71 | ```c++ 72 | #include 73 | ... 74 | std::cout << std::sqrt(4) << std::endl; 75 | ``` 76 | 77 | ## **Optional**: Use `std::vector` 78 | Re-implement the exercises *Prime numbers* and *Sieve of Eratosthenes* using `std::vector` instead of built-in arrays. `std::vector` is defined in the header ``. 79 | -------------------------------------------------------------------------------- /lectures/c++/01_intro/01_variables.cc: -------------------------------------------------------------------------------- 1 | #include // M_PI 2 | #include // std::setprecision 3 | #include 4 | #include 5 | 6 | int main() { 7 | // built-in types 8 | int a{-1}; // long long int, unsigned int 9 | // int a = -1; // is fine 10 | std::cout << a << std::endl; 11 | 12 | double b{2.2}; // long double, float 13 | std::cout << b << std::endl; 14 | 15 | char c{'r'}; // unsigned char, signed char, wchar_t 16 | std::cout << c << std::endl; 17 | 18 | bool t{true}; // false,0,1,... 19 | std::cout << t << std::endl; 20 | 21 | // check the size of a variable type 22 | std::cout << "on my machine the size of an int is " << sizeof(int) 23 | << " bytes\n"; 24 | std::cout << "on my machine the size of an double is " << sizeof(double) 25 | << " bytes\n"; 26 | std::cout << "on my machine the size of a char is " << sizeof(char) 27 | << " bytes\n"; 28 | std::cout << "on my machine the size of a bool is " << sizeof(bool) 29 | << " bytes\n"; 30 | 31 | // if you want to make sure an int is e.g. 2 bytes use special 32 | // variables names 33 | int16_t small_int{}; 34 | std::cout << "on every machine the size of variable small_int is " 35 | << sizeof(small_int) << " bytes\n"; 36 | 37 | // not built-in but useful :) 38 | std::string s{"Hello, World!\n"}; 39 | std::cout << s; 40 | 41 | // narrowing effect 42 | int var = 6.9; // try to initialize var with the universal and 43 | // uniform initialization 44 | // int v_narrow {6.9}; // compiler error or warning with variables 45 | // int v_narrow_w {int(a+b)}; // suppress error/warning with a cast 46 | 47 | std::cout << var << "\n"; 48 | 49 | var += 7; 50 | var -= 7; 51 | var *= 7; 52 | var /= 7; 53 | var %= 7; 54 | var++; 55 | ++var; 56 | 57 | var = a + b; // works also for strings 58 | var = a - b; 59 | var = a * b; 60 | var = a % var; // modulus operator just between integers 61 | 62 | bool test; 63 | test = a == b; 64 | test = a < b; 65 | test = a > b; 66 | test = a <= b; 67 | test = a >= b; 68 | test = a != b; 69 | 70 | if (test) { 71 | std::cout << "test is true\n"; 72 | } else { 73 | std::cout << "test is false\n"; 74 | } 75 | 76 | // constants 77 | 78 | const int cc{7}; 79 | // cc = 9; // error 80 | 81 | constexpr double ce{cc * 8.1234 / M_PI}; // evaluated at compile-time 82 | 83 | int ve{int(ce * a)}; // ok create a variable from constexpr 84 | 85 | // constexpr int n_ce {ve*8.1234/M_PI}; // error 86 | 87 | // cast to void to suppress warning of unused variable 88 | (void)ve; 89 | long double lpi = 3.141592653589793238462L; 90 | std::cout << std::setprecision(50) << M_PI << std::endl; 91 | std::cout << std::hex << 43 << std::endl; 92 | std::cout << std::oct << 43 << std::endl; 93 | std::cout << std::dec << 43 << std::endl; 94 | 95 | (void)lpi; 96 | 97 | return 0; 98 | } 99 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Advanced Programming [![Build Status](https://api.travis-ci.org/asartori86/advanced_programming_2020.svg?branch=master)](https://travis-ci.org/asartori86/advanced_programming_2020) 2 | 3 | [SISSA webpage](http://www.math.sissa.it/course/phd-course-master-course/advanced-programming-2) 4 | 5 | The course aims to provide advanced knowledge of both theoretical and practical programming in C++14 and Python3, with particular regard to the principles of object-oriented programming and best practices of software development. 6 | 7 | Syllabus: 8 | 9 | - Introduction to C++11. You will learn the logic and the basics of C++11, the built-in data types and how to effectively use them. Best practices in programming will be addressed. 10 | - Object orientation in C++11. The principles of Object-Oriented programming will be presented with particular attention to their implementations in C++11. Some of the most important Design Patterns will be discussed. 11 | - Advanced features of C++14/17. Some of the new features of standard C++/14/17 will be introduced and explained. 12 | - Python3. After a recap of the basics of Python3, you will learn how to program in object-oriented fashion in the Python3 programming language. 13 | - How to combine the two languages. Several methods to combine the two languages will be presented. 14 | 15 | 16 | ## Prerequisites 17 | - Familiarity with linux terminal and a text editor (e.g., emacs, vim) 18 | - A bit of knowledge of git 19 | 20 | ## References 21 | 22 | - Programming: Principles and Practice using C++ (Second Edition), 23 | Bjarne Stroustrup, Addison-Wesley 2014, ISBN 978-0-321-99278-9 24 | 25 | - The C++ Programming Language, Bjarne Stroustrup, Addison-Wesley 26 | 2013, ISBN 978-0321563842 27 | 28 | - Fluent Pyhton. Clear, concise, and effective programming, Luciano Ramalho, O'Reilly 2015, ISBN 978-1-491-946000-8 29 | 30 | 31 | 32 | ## How to get the material 33 | ### Non-experienced git users 34 | - Very first time `(N==0)` 35 | - open a terminal 36 | - `cd` in a suitable folder 37 | - `git clone https://github.com/asartori86/advanced_programming_2020.git` 38 | - `cd advanced-programming_2020` 39 | - take a look at [software carpentry lecture](http://swcarpentry.github.io/git-novice/) and [pro git book](https://git-scm.com/book/en/v2) 40 | - `N > 0` 41 | - open a terminal 42 | - `cd` to the folder `advanced-programming_2020` 43 | - `git pull origin master` 44 | - if(conflict) 45 | - ask 46 | 47 | ### Experienced git users 48 | - Very first time `(N==0)` 49 | - fork the repository 50 | - clone either your fork or this repository 51 | - add the other remote 52 | - `N >= 0` 53 | - use branches 54 | - rebase on the correct master branch 55 | - merge the branches in your local master 56 | - push on the master of your fork 57 | - if(conflict) 58 | - if(rebase) 59 | - `git add` 60 | - `git rebase --continue` 61 | - if(bigger mess) 62 | - `git rebase --abort` 63 | - if(merge) 64 | - `git add` 65 | - `git commit` 66 | - `git merge --continue` 67 | - if(bigger mess) 68 | - `git merge --abort` 69 | -------------------------------------------------------------------------------- /exercises/c++/03_arrays_and_vectors/readme.md: -------------------------------------------------------------------------------- 1 | # Exercises - session 03 2 | 3 | ## Matrix transpose 4 | 5 | - Write a function that computes the transpose of a matrix. The matrix is represented by a simple `std::array` where N is the total size of the matrix (i.e., number of rows times number of columns). The original array must be modified inside the function `transpose`. 6 | 7 | *Hints*: 8 | 9 | - In C/C++, the matrices are accessed row-wise 10 | - You are not required to do the transpose *in place* 11 | - Test with both square and rectangular matrices. 12 | - Use `std::swap` defined in header `` 13 | 14 | ## Convert `argv` to types 15 | 16 | - Modify the above program such that the number of rows and columns are read from command line arguments. 17 | 18 | *Hints*: 19 | - Use `std::istringstream` defined in the header `` 20 | 21 | ```c++ 22 | #include 23 | 24 | std::size_t rows; 25 | { 26 | std::istringstream is{argv[1]}; 27 | is >> rows; 28 | } 29 | ``` 30 | 31 | 32 | ## Mean and Median 33 | 34 | - Store the numbers contained in file `temperatures.txt` into a `std::vector` and compute: 35 | - the mean 36 | - the median 37 | 38 | *Hints*: 39 | 40 | - use `push_back()` 41 | - you can increment a variable using `+=` operator 42 | - you can **sort** the elements of a vector `v` as follows 43 | ```c++ 44 | #include 45 | 46 | std::vector v; 47 | ... 48 | std::sort( v.begin(), v.end() ); 49 | ``` 50 | 51 | 52 | ## Avoid repeated words 53 | 54 | - Read from stdin a sequence of words. Store each word in a `std::vector`. Then, print the words without repetitions. 55 | 56 | *Hints*: 57 | 58 | - you can print the words in any order you want (i.e., you are not required to print the words in the order you have read them) 59 | 60 | ## **Optional**: Use `std::map` and `std::unordered_map` 61 | 62 | - Read the `LittleWomen.txt` and then print all the read words (without repetitions) followed by the number of repetitions of that word. Compare the time to do the same using `std::vector`, `std::map`, `std::unordered_map`. The order in which the words are printed is **not** relevant. 63 | 64 | - You can measure the elapsed time as follows: 65 | ```c++ 66 | #include 67 | 68 | auto t0 = std::chrono::high_resolution_clock::now(); 69 | ... 70 | auto t1 = std::chrono::high_resolution_clock::now(); 71 | 72 | auto elapsed = std::chrono::duration_cast(t1-t0); 73 | std::cout << "Elapsed " << elapsed.count() << " [milliseconds]" << std::endl; 74 | ``` 75 | 76 | - You can avoid to repeat `std::chrono::` if you write 77 | ```c++ 78 | 79 | using namespace std::chrono; 80 | 81 | auto t0 = high_resolution_clock::now(); 82 | ``` 83 | 84 | - Compile with the flag `-O3` (is a capital O, not a zero) 85 | 86 | 87 | ## **Optional**: Conway's Game of Life 88 | - Implement the [Game of Life](https://www.wikidata.org/wiki/Q244615#sitelinks-wikipedia) 89 | - You can slow down your code by forcing a "nap". 90 | ```c++ 91 | #include 92 | #include 93 | ... 94 | std::this_thread::sleep_for (std::chrono::milliseconds(50)); 95 | ``` 96 | -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/tex_files/iterators.tex: -------------------------------------------------------------------------------- 1 | \section{Iterators} 2 | \subsection{What they are} 3 | \begin{frame} 4 | \frametitle{What is an Iterator?} 5 | \begin{block}{Design pattern [GoF]} 6 | Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation. 7 | \end{block} 8 | \vfill 9 | \begin{block}{Stepanov} 10 | Iterator is a coordinate. 11 | \end{block} 12 | \vfill 13 | \begin{block}{A generalization of a pointer} 14 | \begin{itemize} 15 | \item indirect access (\texttt{operator*()}, \texttt{operator->()}) 16 | \item operations for moving to point to a new element (\texttt{operator++()}, \texttt{operator--()}) 17 | \end{itemize} 18 | \end{block} 19 | \end{frame} 20 | 21 | \subsection{Iterators in the STL} 22 | 23 | \begin{frame} 24 | \frametitle{Iterators in the STL} 25 | \begin{block}{Their role} 26 | \begin{itemize} 27 | \item Iterators are the glue that ties the standard-library alogorithms to their data 28 | \item Iterators are the mechanism used to minimize an algorithm's dependence on the data structures on which it operates. 29 | \end{itemize} 30 | \end{block} 31 | \vfill 32 | \begin{block}{Alex Stepanov} 33 | The reason that STL containers and algorithms work so well together is that they know nothing of each other. 34 | \end{block} 35 | \end{frame} 36 | 37 | \begin{frame}[fragile] 38 | %% \frametitle{How to use iterators} 39 | \vfill 40 | \begin{lstlisting} 41 | while( first != last ) 42 | \end{lstlisting} 43 | \vfill 44 | \end{frame} 45 | 46 | 47 | \subsection{Iterator categories} 48 | \begin{frame} 49 | \frametitle{Iterator categories} 50 | \centering 51 | \includegraphics[height=0.8\textheight]{img/iterators.png} 52 | \end{frame} 53 | 54 | \begin{frame}[fragile] 55 | \frametitle{How to implement our own iterator?} 56 | \begin{lstlisting} 57 | template 58 | class List::Iterator { 59 | ... 60 | }; 61 | \end{lstlisting} 62 | \end{frame} 63 | 64 | \subsection{Our List iterator} 65 | \begin{frame}[fragile] 66 | \frametitle{How to implement our own iterator?} 67 | \begin{lstlisting} 68 | #include 69 | ... 70 | template 71 | class List::Iterator{ 72 | typename List::node* current; 73 | public: 74 | using value_type = T; 75 | using difference_type = std::ptrdiff_t; 76 | using iterator_category = 77 | std::forward_iterator_tag; 78 | using reference = value_type&; 79 | using pointer = value_type*; 80 | ... 81 | \end{lstlisting} 82 | \end{frame} 83 | 84 | \begin{frame}[fragile] 85 | \frametitle{How to implement our own iterator?} 86 | \begin{lstlisting} 87 | ... 88 | reference operator*() { 89 | return current->value; } 90 | pointer operator->() { return &**this; } 91 | Iterator& operator++() { 92 | current = current->next; 93 | return *this; 94 | } 95 | friend 96 | bool operator==(const Iterator&, const Iterator&); 97 | friend 98 | bool operator!=(const Iterator&, const Iterator&); 99 | }; 100 | \end{lstlisting} 101 | \end{frame} 102 | 103 | -------------------------------------------------------------------------------- /exercises/c++/05_copy_move/readme.md: -------------------------------------------------------------------------------- 1 | # Exercises - session 05 2 | 3 | ## Linked list 4 | Implement a linked list with the following design. You are free to add more functions. 5 | 6 | ```c++ 7 | enum class Insertion_method { push_back, push_front }; 8 | 9 | template 10 | class List { 11 | public: 12 | // insert a new node with the value v according to the method m 13 | // this method should be used to fill the list 14 | void insert(const value_type& v, const Insertion_method m); 15 | 16 | // return the size of the list 17 | std::size_t size() const; 18 | 19 | // delete all the nodes of the list 20 | void reset(); 21 | 22 | // constructor(s) for List 23 | 24 | // copy semantics (deep copy) 25 | // move semantics 26 | 27 | // destructor 28 | 29 | private: 30 | 31 | // private struct node with the proper value_type 32 | struct node { 33 | value_type value; 34 | std::unique_ptr next; 35 | 36 | // implement suitable constructor(s) for node 37 | 38 | // copy and move semantics if needed 39 | 40 | // destructor 41 | }; 42 | 43 | // append the newly created node at the end of the list 44 | void push_back(const value_type& v); 45 | 46 | // insert the newly created node in front of the list 47 | void push_front(const value_type& v); 48 | 49 | std::unique_ptr head; 50 | std::size_t _size; 51 | }; 52 | 53 | template 54 | std::ostream& operator<<(std::ostream& os, const List& l); 55 | 56 | ``` 57 | 58 | #### *Hints*: 59 | 60 | - `std::move` is defined in header `utility` 61 | 62 | - `std::unique_ptr` is defined in header `memory` 63 | 64 | - A `std::unique_ptr p` has the following functions 65 | - `T* get() const` Returns a pointer to the managed object or `nullptr` if no object is owned. 66 | - `T* release()` Releases the ownership of the managed object if any. `get()` returns `nullptr` after the call. 67 | - `void reset(T* ptr=nullptr)` Delete `current_ptr` (if any) and set `current_ptr = ptr`. 68 | - To check if a `std::unique_ptr p` is different from `nullptr` you can simply use `if(p)` (there is no need to write `if (p.get())`). 69 | 70 | - For a class `Foo` 71 | 72 | ```C++ 73 | class Foo{ 74 | Foo(); // default ctor 75 | Foo(const Foo& f); // copy ctor 76 | Foo(Foo&& f); // move ctor 77 | 78 | Foo& operator=(const Foo& f); // copy assignment 79 | Foo& operator=(Foo&& f); // move assignment 80 | }; 81 | ``` 82 | 83 | 84 | 85 | You are required to use blocks of memory (*heap*) locations which are linked together. Each of these blocks contains one component that may refer to another block. If each block (except the final one) contains a pointer to the next block, so that they form a chain, then the entire collection of linked blocks is called a **linked list**. The blocks of memory locations of a linked list are usually called *nodes*. 86 | 87 | Every node of a linked list, except the final one, contains a pointer to its immediate *successor*, and every node except the first one is pointed to by its immediate *predecessor*. The pointer member of the last node has the value `nullptr`. 88 | 89 | The private member `head` points to the first element of the list. 90 | 91 | ![linked_list.png](./.aux/list2.png) 92 | 93 | -------------------------------------------------------------------------------- /lectures/c++/06_error_handling/readme.md: -------------------------------------------------------------------------------- 1 | # Lecture 05_error_handling 2 | 3 | 4 | 5 | ## 00_errno.cpp 6 | 7 | [link to file](./00_errno.cpp) 8 | 9 | The example shows one of the common problem with the error handling in 10 | the C language. The `errno` macro can be used by any function to 11 | signal a particular error. 12 | 13 | PPP: chap 5.5 14 | CPL: 13.1.2 traditional error handling 15 | 16 | 17 | 18 | 19 | ## 01_exceptions.cpp 20 | 21 | [link to file](./01_exceptions.cpp) 22 | 23 | A simple square root function is implemented. In particular, it `throw`s exceptions defined by the user, in 24 | particular these are simple `struct`s with a name that represent the kind of error. 25 | The function is then tested using the `try`-block and `catch`-clause. 26 | 27 | PPP: chap 5.6 exceptions 28 | CPL: 13.5 throwing and catching exceptions 29 | 30 | 31 | 32 | 33 | ## 02_exceptions.cpp 34 | 35 | [link to file](./02_exceptions.cpp) 36 | 37 | Same example as before, but now the exception is a `struct` that contains the message to be 38 | printed. 39 | 40 | 41 | 42 | 43 | ## 03_error.cpp 44 | 45 | [link to file](./03_error.cpp) 46 | 47 | Again the same example of the square root function, but this time the [ap_error.h](./ap_error.h) 48 | header file is used. 49 | We can see the behaviour of the `AP_ERROR()` macro, and that of several other macros defined there. 50 | 51 | 52 | 53 | ## 04_assert.cpp 54 | 55 | [link to file](./04_assert.cpp) 56 | 57 | The `assert` is a macro derived from the C language and it's contained in *assert.h*. 58 | It calls the `abort()` function, thus terminating the program, if the condition is false. The main feature of the `assert`s with respect to an hard-coded `if` statement is that the `assert`s can be "turned off" through the compile flag `-DNDEBUG`. 59 | 60 | CPL: chap 13.4 assert macro 61 | 62 | 63 | 64 | 65 | ## 05_stack_unwinding.cpp 66 | 67 | [link to file](./05_stack_unwinding.cpp) 68 | 69 | The program demonstrates how the *stack unwinding* is performed. In particular, is worth noting that the destructor of an object is called if and only if its constructor ended sucppessfully. 70 | 71 | CPL: chap 13.5 72 | 73 | 74 | 75 | 76 | 77 | 78 | ## 06_smart_pointers.cpp 79 | 80 | [link to file](./06_smart_pointers.cpp) 81 | 82 | This program introduces you to the usage of *smart pointers*, defined in the 83 | *memory* header. The `unique_ptr` is able to manage by himself the memory he holds, 84 | thus avoiding memory leaks. 85 | 86 | PPP: chap 19.5.4 unique_ptr, appendix B.6.5 87 | CPL: 5.2.1 unique_ptr and shared_ptr 88 | 89 | 90 | 91 | 92 | 93 | ## ap_error.h 94 | 95 | In this header file there are the implementations of the macros used in the previous programs. 96 | You can find a description of its main features and some examples of its usage at the beginning 97 | of the file. 98 | 99 | PPP: chap 27.8 macros 100 | CPL: chap 12.6 macros 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | ### References: 110 | 111 | [PPP] = Programming: Principles and Practice using C++ (Second Edition), Bjarne Stroustrup, Addison-Wesley 2014, ISBN 978-0-321-99278-9 112 | 113 | [CPL] = The C++ Programming Language, Bjarne Stroustrup, Addison-Wesley 2013, ISBN 978-0321563842 114 | -------------------------------------------------------------------------------- /exercises/c++/04_custom_types/readme.md: -------------------------------------------------------------------------------- 1 | # Exercises - session 04 2 | 3 | ## Class Date 4 | Implement a class `Date`. This class must meet the following requirements: 5 | - it has three **private** attributes to represent day, month and year 6 | - use a scoped enum for month 7 | - it has the following **public** functions: 8 | - constructor that takes as arguments a day, a month and a year. (Forget about the validation for now) 9 | - `day()` function that returns the day 10 | - `month()` function that returns the month 11 | - `year()` function that returns the year 12 | - `add_days(const unsigned int n)` which adds `n` days. You have to take care to increment months and years accordingly (neglect leap years) 13 | 14 | *Hints*: 15 | - you can add more functions, maybe private, to simplify the implementation of the above (e.g., you can implement a function that adds 1 single day) 16 | - remember to properly mark the member functions that do not modify the class as `const` 17 | - you should think where to implement the member functions, i.e. inside the class declaration or outside 18 | ```c++ 19 | class Foo{ 20 | public: 21 | 22 | int foo() const {return an_int;} // note no ; at the end 23 | 24 | int bar(); 25 | 26 | private: 27 | int an_int; 28 | }; // note the ; at the end of class declaration 29 | 30 | int Foo::bar(){ 31 | ... 32 | } // note no ; at the end of function implementation 33 | 34 | ``` 35 | 36 | Member functions that are *defined* inside the class are **inlined** 37 | meaning that the compiler will replace the function call to its 38 | implementation (thus the executable becomes bigger). A good rule of 39 | thumb is that functions that are simple (e.g. a simple return or few 40 | lines of code) should be inlined. Bigger functions are recommended to 41 | be implemented outside the class. Remember that the name of the 42 | function is prefixed with the class name (see the implementation of 43 | `bar()` above). 44 | 45 | - In a switch-case statement you can use several `case` labels for a single case 46 | ```c++ 47 | int a; 48 | ... 49 | switch (a){ 50 | case 0: case 2: case 4: 51 | case 6: case 8: case 10: 52 | std::cout << "a is even\n"; 53 | break; 54 | 55 | case 1: case 3: case 5: 56 | case 7: case 9: 57 | std::cout << "a is odd\n"; 58 | break; 59 | default: 60 | std::cout << "a > 10\n"; 61 | break; 62 | } 63 | ``` 64 | 65 | ## Helper functions 66 | Implement the following external helper functions (i.e., they are not part of the class): 67 | - `bool operator==(const Date& lhs, const Date& rhs);` 68 | - `bool operator!=(const Date& lhs, const Date& rhs);` 69 | - `std::ostream& operator<<(std::ostream& os, const Date& d);` 70 | - **optional** `bool is_leap(const int y);` 71 | 72 | *Hints*: 73 | - a year is a leap year if it is divisible by 4. If it is also divisible by 100 is not a leap year. However, it is a leap year if it is divisible by 400. 74 | - try to avoid code duplication 75 | 76 | 77 | 78 | 79 | ## C++14 80 | 81 | Modify the class `Vector` presented during the lecture exploiting all the of C++14 features you know. Can you see any benefit? 82 | 83 | *Hints*: 84 | 85 | - remember to compile with `-std=c++14` 86 | 87 | 88 | 89 | ## Smart usage of `enums` 90 | Study and try to understand the file [multiple_flags.cpp](./multiple_flags.cpp) 91 | 92 | 93 | 94 | ## Optional: range-for-loop 95 | 96 | Implement the range-for-loop for the class `Vector` we have written. 97 | 98 | -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/tex_files/algorithms.tex: -------------------------------------------------------------------------------- 1 | \section{Algorithms} 2 | \subsection{Introduction} 3 | \begin{frame} 4 | \frametitle{STL algorithms} 5 | \begin{itemize} 6 | \item about 80 algorithms in \texttt{ and } 7 | \item[] 8 | \item operate on \emph{sequences} 9 | \begin{itemize} 10 | \item pair of iterators for inputs $[b:e)$ 11 | \item single iterator for output $[b2: b2+(e-b))$ 12 | \end{itemize} 13 | \item[] 14 | \item can take functions or function objects 15 | \item[] 16 | \item report failure (e.g. not found) by returning the end of the sequence 17 | \end{itemize} 18 | \end{frame} 19 | \subsection{Quick examples} 20 | \begin{frame}[fragile] 21 | \frametitle{Examples} 22 | \framesubtitle{Sequences} 23 | \begin{lstlisting} 24 | #include 25 | #include 26 | 27 | int main(){ 28 | std::vector v1; 29 | ... 30 | std::vector v2(v1.size()); 31 | std::sort(v1.begin(), v1.end()); 32 | std::copy(v1.begin(), v1.end(), v2.begin()); 33 | } 34 | \end{lstlisting} 35 | \end{frame} 36 | 37 | \begin{frame}[fragile] 38 | \frametitle{Examples} 39 | \framesubtitle{Sequences} 40 | \begin{lstlisting} 41 | #include 42 | #include 43 | 44 | int main(){ 45 | std::vector v1; 46 | ... 47 | double sum{0}; 48 | sum = std::accumulate(v1.begin(),v1.end(),sum); 49 | } 50 | \end{lstlisting} 51 | \end{frame} 52 | 53 | \begin{frame}[fragile] 54 | \frametitle{Examples} 55 | \framesubtitle{User-defined functions} 56 | \begin{lstlisting} 57 | #include 58 | #include 59 | 60 | double my_f(const double& a, const double& b){ 61 | if(std::abs(b - 2.2) < 1e-12) 62 | return a; 63 | return a+b; 64 | } 65 | int main(){ 66 | std::vector v1; 67 | ... 68 | double sum{0}; 69 | sum = std::accumulate(first,last,sum,my_f); 70 | } 71 | \end{lstlisting} 72 | 73 | \end{frame} 74 | 75 | 76 | \begin{frame}[fragile] 77 | \frametitle{Examples} 78 | \framesubtitle{Lambda functions} 79 | \begin{lstlisting} 80 | #include 81 | #include 82 | int main(){ 83 | std::vector v1; 84 | ... 85 | auto my_f = [](const double& a, const double &b) -> double { 86 | return ( (std::abs(b-2.2) < 1e-12) ? a : a+b); 87 | }; 88 | double sum{0}; 89 | sum = std::accumulate(first,last,sum,my_f); 90 | } 91 | \end{lstlisting} 92 | \end{frame} 93 | 94 | \begin{frame}[fragile] 95 | \frametitle{Examples} 96 | \framesubtitle{Generic lambdas (since C++14)} 97 | \begin{lstlisting} 98 | #include 99 | #include 100 | int main(){ 101 | std::vector v1; 102 | ... 103 | auto my_f = [](const auto& a, const auto& b) { 104 | return ( (std::abs(b-2.2) < 1e-12) ? a : a+b); 105 | }; 106 | double sum{0}; 107 | sum = std::accumulate(first,last,sum,my_f); 108 | } 109 | \end{lstlisting} 110 | 111 | \end{frame} 112 | 113 | \begin{frame}[fragile] 114 | \frametitle{Examples} 115 | \framesubtitle{Failure check} 116 | \begin{lstlisting} 117 | #include 118 | #include 119 | 120 | int main(){ 121 | std::vector v1; 122 | ... 123 | auto it = std::find(v1.begin(), v1.end(), 2.2); 124 | 125 | if(it != v1.end()) 126 | std::cout << "found " << *it << std::endl; 127 | else 128 | std::cout << "not found\n"; 129 | } 130 | 131 | \end{lstlisting} 132 | \end{frame} 133 | -------------------------------------------------------------------------------- /lectures/python/03_advanced_topics/08_testing.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Simple testing\n", 8 | "- `unittest`\n", 9 | "- `doctest`\n", 10 | "- `assert`\n", 11 | "- `if __name__ == '__main__':`\n", 12 | "- `__all__`\n", 13 | "- RTFM \n", 14 | " - https://docs.python.org/3/library/unittest.html\n", 15 | " - https://docs.python.org/3/library/doctest.html" 16 | ] 17 | }, 18 | { 19 | "cell_type": "markdown", 20 | "metadata": {}, 21 | "source": [ 22 | " - take a look at file `my_module.py`\n", 23 | " - `python my_module.py`\n", 24 | " - `pyhton my_module.py -v`" 25 | ] 26 | }, 27 | { 28 | "cell_type": "code", 29 | "execution_count": null, 30 | "metadata": {}, 31 | "outputs": [], 32 | "source": [ 33 | "!python my_module.py" 34 | ] 35 | }, 36 | { 37 | "cell_type": "code", 38 | "execution_count": null, 39 | "metadata": {}, 40 | "outputs": [], 41 | "source": [ 42 | "!python my_module.py -v" 43 | ] 44 | }, 45 | { 46 | "cell_type": "markdown", 47 | "metadata": {}, 48 | "source": [ 49 | "## Python `assert`" 50 | ] 51 | }, 52 | { 53 | "cell_type": "code", 54 | "execution_count": null, 55 | "metadata": {}, 56 | "outputs": [], 57 | "source": [ 58 | "x = 1\n", 59 | "assert x < 0, 'x is supposed to be negative'" 60 | ] 61 | }, 62 | { 63 | "cell_type": "code", 64 | "execution_count": null, 65 | "metadata": {}, 66 | "outputs": [], 67 | "source": [ 68 | "assert x > 0, 'x is supposed to be positive'" 69 | ] 70 | }, 71 | { 72 | "cell_type": "markdown", 73 | "metadata": {}, 74 | "source": [ 75 | "### Do not use parenthesis with `assert`s" 76 | ] 77 | }, 78 | { 79 | "cell_type": "code", 80 | "execution_count": null, 81 | "metadata": {}, 82 | "outputs": [], 83 | "source": [ 84 | "assert (x < 0, 'x is supposed to be negative')" 85 | ] 86 | }, 87 | { 88 | "cell_type": "markdown", 89 | "metadata": {}, 90 | "source": [ 91 | "## Pytest\n", 92 | " - install with `conda` or `pip`\n", 93 | " - simple `assert`\n", 94 | " - recursive searching for `test_*` or `*_test.py` files\n", 95 | "\n", 96 | "#### How to use it\n", 97 | "- run `pytest`\n", 98 | "- with `doctest`, run `pytest --doctest-modules` \n" 99 | ] 100 | }, 101 | { 102 | "cell_type": "code", 103 | "execution_count": null, 104 | "metadata": {}, 105 | "outputs": [], 106 | "source": [ 107 | "!pytest" 108 | ] 109 | }, 110 | { 111 | "cell_type": "code", 112 | "execution_count": null, 113 | "metadata": {}, 114 | "outputs": [], 115 | "source": [ 116 | "!pytest --doctest-modules" 117 | ] 118 | } 119 | ], 120 | "metadata": { 121 | "kernelspec": { 122 | "display_name": "Python 3", 123 | "language": "python", 124 | "name": "python3" 125 | }, 126 | "language_info": { 127 | "codemirror_mode": { 128 | "name": "ipython", 129 | "version": 3 130 | }, 131 | "file_extension": ".py", 132 | "mimetype": "text/x-python", 133 | "name": "python", 134 | "nbconvert_exporter": "python", 135 | "pygments_lexer": "ipython3", 136 | "version": "3.7.6" 137 | } 138 | }, 139 | "nbformat": 4, 140 | "nbformat_minor": 4 141 | } 142 | -------------------------------------------------------------------------------- /exercises/c++/vector/as_vector.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | template 8 | class Vector{ 9 | std::unique_ptr elem; 10 | std::size_t _size{}; 11 | std::size_t _capacity{}; 12 | 13 | void check_and_increase_capacity(){ 14 | if(_capacity == 0) 15 | reserve(12); // reserve 8 elements 16 | else if (_size == _capacity) 17 | reserve(2*_capacity); 18 | } 19 | 20 | template 21 | void _push_back(O&& x){ 22 | check_and_increase_capacity(); 23 | elem[_size] = std::forward(x); 24 | ++_size; 25 | } 26 | 27 | 28 | public: 29 | 30 | auto size() const { return _size; } 31 | auto capacity() const { return _capacity; } 32 | 33 | Vector() = default; 34 | ~Vector() = default; 35 | 36 | Vector(std::initializer_list list): // pass by value 37 | elem{new T[list.size()]}, 38 | _size{list.size()}, 39 | _capacity{list.size()}{ 40 | 41 | std::copy(list.begin(), list.end(), elem.get()); 42 | 43 | // for(std::size_t i=0; i // variadic templates; packing 79 | void emplace_back(Types&&... args){ // unpack 80 | check_and_increase_capacity(); 81 | elem[_size] = T{std::forward(args)...}; // T{} 82 | ++_size; 83 | } 84 | 85 | 86 | 87 | }; 88 | 89 | template 90 | std::ostream& operator<<(std::ostream& os, const Vector& x){ 91 | os <<"capacity: " << x.capacity() << ", size: " << x.size() << "\n"; 92 | for(auto i =0u; i < x.size(); ++i) 93 | os << x[i] << " "; 94 | os << std::endl; 95 | return os; 96 | 97 | } 98 | 99 | struct Foo{ 100 | Foo(){std::cout << "foo ctor" << std::endl;} 101 | }; 102 | 103 | 104 | int main(){ 105 | 106 | Vector vf{{},{}}; 107 | // std::vector vf{{},{}}; 108 | vf.emplace_back(); 109 | std::cout << vf.capacity() << std::endl; 110 | 111 | return 0; 112 | 113 | Vector x{1,2,3,4}; 114 | 115 | std::cout << x; 116 | 117 | x.push_back(3); 118 | 119 | std::cout << x; 120 | 121 | 122 | std::vector> vs; 123 | 124 | vs.push_back({4,"hello"}); // push_back takes 1 arg 125 | 126 | vs.emplace_back(4,"hello"); // 2 args 127 | 128 | // std::vector v; // default ctor 129 | // v.reserve(128); 130 | // std::vector v1(4,2); // custom ctor 131 | // std::vector v2{4,2,4,5,6}; // std::initializer_list // higher priority 132 | 133 | // for (const auto x : v1) 134 | // std::cout << x << " "; 135 | // std::cout << std::endl; 136 | 137 | 138 | // for (const auto x : v2) 139 | // std::cout << x << " "; 140 | // std::cout << std::endl; 141 | 142 | } 143 | -------------------------------------------------------------------------------- /lectures/python/02_symbols/04_global_local.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "### Global " 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "b = 9\n", 17 | "\n", 18 | "\n", 19 | "def foo():\n", 20 | " print(\"inside foo\", b)\n", 21 | "\n", 22 | "\n", 23 | "foo()\n", 24 | "print(\"main\", b)" 25 | ] 26 | }, 27 | { 28 | "cell_type": "markdown", 29 | "metadata": {}, 30 | "source": [ 31 | "### Local" 32 | ] 33 | }, 34 | { 35 | "cell_type": "code", 36 | "execution_count": null, 37 | "metadata": {}, 38 | "outputs": [], 39 | "source": [ 40 | "def bar():\n", 41 | " y = 7\n", 42 | " print(\"inside bar\", y)\n", 43 | "\n", 44 | "\n", 45 | "bar()\n", 46 | "print(\"main\", y) # expect error" 47 | ] 48 | }, 49 | { 50 | "cell_type": "markdown", 51 | "metadata": {}, 52 | "source": [ 53 | "### Pay attention!" 54 | ] 55 | }, 56 | { 57 | "cell_type": "code", 58 | "execution_count": null, 59 | "metadata": {}, 60 | "outputs": [], 61 | "source": [ 62 | "b = 9\n", 63 | "\n", 64 | "\n", 65 | "def magic():\n", 66 | " y = 7\n", 67 | " print(\"inside magic\", y, b)\n", 68 | " b = 6\n", 69 | "\n", 70 | "\n", 71 | "print(\"main\", b)\n", 72 | "magic()" 73 | ] 74 | }, 75 | { 76 | "cell_type": "code", 77 | "execution_count": null, 78 | "metadata": {}, 79 | "outputs": [], 80 | "source": [ 81 | "b = 9\n", 82 | "\n", 83 | "\n", 84 | "def magic_local():\n", 85 | " y = 7\n", 86 | " b = 6\n", 87 | " print(\"inside magic_local\", y, b)\n", 88 | "\n", 89 | "\n", 90 | "magic_local()\n", 91 | "print(\"main\", b)" 92 | ] 93 | }, 94 | { 95 | "cell_type": "markdown", 96 | "metadata": {}, 97 | "source": [ 98 | "### `global` keyword" 99 | ] 100 | }, 101 | { 102 | "cell_type": "code", 103 | "execution_count": null, 104 | "metadata": {}, 105 | "outputs": [], 106 | "source": [ 107 | "b = 9\n", 108 | "\n", 109 | "\n", 110 | "def magic_global():\n", 111 | " global b # <----\n", 112 | " y = 7\n", 113 | " print(\"inside magic_local\", y, b)\n", 114 | " b = 6\n", 115 | "\n", 116 | "\n", 117 | "magic_global()\n", 118 | "print(\"main\", b)" 119 | ] 120 | }, 121 | { 122 | "cell_type": "code", 123 | "execution_count": null, 124 | "metadata": {}, 125 | "outputs": [], 126 | "source": [ 127 | "lst = [1, 2, 3, [4, 5, 6]]\n", 128 | "\n", 129 | "\n", 130 | "def mutables():\n", 131 | " print(\"inside\", lst)\n", 132 | " lst[0] = 99\n", 133 | "\n", 134 | "\n", 135 | "mutables()\n", 136 | "print(\"main\", lst)" 137 | ] 138 | } 139 | ], 140 | "metadata": { 141 | "kernelspec": { 142 | "display_name": "Python 3", 143 | "language": "python", 144 | "name": "python3" 145 | }, 146 | "language_info": { 147 | "codemirror_mode": { 148 | "name": "ipython", 149 | "version": 3 150 | }, 151 | "file_extension": ".py", 152 | "mimetype": "text/x-python", 153 | "name": "python", 154 | "nbconvert_exporter": "python", 155 | "pygments_lexer": "ipython3", 156 | "version": "3.7.6" 157 | } 158 | }, 159 | "nbformat": 4, 160 | "nbformat_minor": 4 161 | } 162 | -------------------------------------------------------------------------------- /lectures/python/02_symbols/05_closures.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "### free variables (aka nonlocal variables)" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "def inspect_vars(o):\n", 17 | " for i in (\"co_varnames\", \"co_freevars\"):\n", 18 | " print(i, eval(\"o.__code__.\" + i))" 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": null, 24 | "metadata": {}, 25 | "outputs": [], 26 | "source": [ 27 | "def maker():\n", 28 | " so_far = []\n", 29 | "\n", 30 | " def avg(new_value):\n", 31 | " so_far.append(new_value)\n", 32 | " return sum(so_far) / len(so_far)\n", 33 | "\n", 34 | " return avg\n", 35 | "\n", 36 | "\n", 37 | "av = maker()\n", 38 | "print(av(9))\n", 39 | "print(av(11))\n", 40 | "print(av(40))" 41 | ] 42 | }, 43 | { 44 | "cell_type": "code", 45 | "execution_count": null, 46 | "metadata": {}, 47 | "outputs": [], 48 | "source": [ 49 | "inspect_vars(av)" 50 | ] 51 | }, 52 | { 53 | "cell_type": "code", 54 | "execution_count": null, 55 | "metadata": {}, 56 | "outputs": [], 57 | "source": [ 58 | "def maker_buggy():\n", 59 | " _sum = 0\n", 60 | " _count = 0\n", 61 | "\n", 62 | " def avg(new_value):\n", 63 | " _sum += new_value\n", 64 | " _count += 1\n", 65 | " return _sum / _count\n", 66 | "\n", 67 | " return avg\n", 68 | "\n", 69 | "\n", 70 | "av = maker_buggy()\n", 71 | "av(9)" 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "execution_count": null, 77 | "metadata": {}, 78 | "outputs": [], 79 | "source": [ 80 | "inspect_vars(av)" 81 | ] 82 | }, 83 | { 84 | "cell_type": "code", 85 | "execution_count": null, 86 | "metadata": {}, 87 | "outputs": [], 88 | "source": [ 89 | "def maker_right():\n", 90 | " _sum = 0\n", 91 | " _count = 0\n", 92 | "\n", 93 | " def avg(new_value):\n", 94 | " nonlocal _sum, _count\n", 95 | " _sum += new_value\n", 96 | " _count += 1\n", 97 | " return _sum / _count\n", 98 | "\n", 99 | " return avg\n", 100 | "\n", 101 | "\n", 102 | "av = maker_right()\n", 103 | "print(av(9))\n", 104 | "print(av(11))\n", 105 | "print(av(40))" 106 | ] 107 | }, 108 | { 109 | "cell_type": "code", 110 | "execution_count": null, 111 | "metadata": {}, 112 | "outputs": [], 113 | "source": [ 114 | "inspect_vars(av)" 115 | ] 116 | }, 117 | { 118 | "cell_type": "markdown", 119 | "metadata": {}, 120 | "source": [ 121 | "### closure\n", 122 | "A closure is a function that retains the bindings of the free variables that exist when the function is defined, so that they can be used later when the function is invoked and the **defining scope** is no longer available." 123 | ] 124 | } 125 | ], 126 | "metadata": { 127 | "kernelspec": { 128 | "display_name": "Python 3", 129 | "language": "python", 130 | "name": "python3" 131 | }, 132 | "language_info": { 133 | "codemirror_mode": { 134 | "name": "ipython", 135 | "version": 3 136 | }, 137 | "file_extension": ".py", 138 | "mimetype": "text/x-python", 139 | "name": "python", 140 | "nbconvert_exporter": "python", 141 | "pygments_lexer": "ipython3", 142 | "version": "3.7.6" 143 | } 144 | }, 145 | "nbformat": 4, 146 | "nbformat_minor": 4 147 | } 148 | -------------------------------------------------------------------------------- /exercises/c++/vector/as_vector_malloc.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | template 9 | class Vector{ 10 | std::unique_ptr elem{nullptr,free}; // free(ptr) instead of delete[] ptr 11 | std::size_t _size{}; 12 | std::size_t _capacity{}; 13 | 14 | void check_and_increase_capacity(){ 15 | if(_capacity == 0) 16 | reserve(12); // reserve 8 elements 17 | else if (_size == _capacity) 18 | reserve(2*_capacity); 19 | } 20 | 21 | template 22 | void _push_back(O&& x){ 23 | check_and_increase_capacity(); 24 | new(elem.get()+_size) T{std::forward(x)}; 25 | ++_size; 26 | } 27 | 28 | 29 | public: 30 | 31 | auto size() const { return _size; } 32 | auto capacity() const { return _capacity; } 33 | 34 | Vector() = default; 35 | ~Vector(){ 36 | for(auto i = 0; i <_size; ++i){ 37 | // invoke the destructor 38 | } 39 | 40 | } 41 | 42 | Vector(std::initializer_list list): // pass by value 43 | elem{static_cast(malloc(list.size()*sizeof(T))), free}, 44 | _size{list.size()}, 45 | _capacity{list.size()}{ 46 | 47 | std::uninitialized_copy(list.begin(), list.end(), elem.get()); 48 | 49 | // for(std::size_t i=0; i(malloc(n*sizeof(T))}; 56 | 57 | for(std::size_t i = 0; i < _size; ++i) 58 | new(tmp+i) T{std::move(elem[i])}; // placement new 59 | elem.reset(tmp); 60 | _capacity = n; 61 | } 62 | 63 | } 64 | 65 | void push_back(const T& x){ 66 | _push_back(x); 67 | } 68 | 69 | void push_back(T&& x){ 70 | _push_back(std::move(x)); 71 | } 72 | 73 | auto& operator[](const std::size_t i){ 74 | // pre-conditions: good point for assert 75 | return elem[i]; 76 | } 77 | 78 | const auto& operator[](const std::size_t i) const{ 79 | // pre-conditions: good point for assert 80 | return elem[i]; 81 | } 82 | 83 | 84 | template // variadic templates; packing 85 | void emplace_back(Types&&... args){ // unpack 86 | check_and_increase_capacity(); 87 | new(elem.get() + _size) T{std::forward(args)...}; // T{} 88 | ++_size; 89 | } 90 | 91 | 92 | 93 | }; 94 | 95 | template 96 | std::ostream& operator<<(std::ostream& os, const Vector& x){ 97 | os <<"capacity: " << x.capacity() << ", size: " << x.size() << "\n"; 98 | for(auto i =0u; i < x.size(); ++i) 99 | os << x[i] << " "; 100 | os << std::endl; 101 | return os; 102 | 103 | } 104 | 105 | struct Foo{ 106 | Foo(){std::cout << "foo ctor" << std::endl;} 107 | }; 108 | 109 | 110 | int main(){ 111 | 112 | Vector vf{{},{}}; 113 | // std::vector vf{{},{}}; 114 | vf.emplace_back(); 115 | std::cout << vf.capacity() << std::endl; 116 | 117 | return 0; 118 | 119 | Vector x{1,2,3,4}; 120 | 121 | std::cout << x; 122 | 123 | x.push_back(3); 124 | 125 | std::cout << x; 126 | 127 | 128 | std::vector> vs; 129 | 130 | vs.push_back({4,"hello"}); // push_back takes 1 arg 131 | 132 | vs.emplace_back(4,"hello"); // 2 args 133 | 134 | // std::vector v; // default ctor 135 | // v.reserve(128); 136 | // std::vector v1(4,2); // custom ctor 137 | // std::vector v2{4,2,4,5,6}; // std::initializer_list // higher priority 138 | 139 | // for (const auto x : v1) 140 | // std::cout << x << " "; 141 | // std::cout << std::endl; 142 | 143 | 144 | // for (const auto x : v2) 145 | // std::cout << x << " "; 146 | // std::cout << std::endl; 147 | 148 | } 149 | -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/tex_files/containers.tex: -------------------------------------------------------------------------------- 1 | \section{Containers} 2 | \subsection{Introduction} 3 | \begin{frame} 4 | \frametitle{Containers} 5 | \begin{block}{Definition} 6 | A container holds a sequence of objects 7 | \end{block} 8 | \vfill 9 | \begin{block}{Two categories} 10 | \begin{itemize} 11 | \item Sequence containers: provide access to sequences of elements 12 | \item Associative containers: provide associative lookup based on a key 13 | \end{itemize} 14 | \end{block} 15 | \vfill 16 | \begin{block}{Associative containers} 17 | \begin{itemize} 18 | \item Ordered 19 | \item Unordered 20 | \end{itemize} 21 | \end{block} 22 | \end{frame} 23 | 24 | \subsection{Sequence containers} 25 | \begin{frame} 26 | \frametitle{Sequence containers} 27 | \centering 28 | \includegraphics[width=\textwidth]{img/sequence_containers.png} 29 | \end{frame} 30 | 31 | \subsection{Associative containers} 32 | \begin{frame} 33 | \frametitle{Ordered associative containers} 34 | \centering 35 | \includegraphics[width=\textwidth]{img/ordered.png} 36 | \end{frame} 37 | \begin{frame} 38 | \frametitle{Unordered associative containers} 39 | \centering 40 | \includegraphics[width=\textwidth]{img/unordered.png} 41 | \end{frame} 42 | 43 | \subsection{Container representation} 44 | \begin{frame} 45 | \frametitle{Array} 46 | \centering 47 | \includegraphics[width=0.5\textwidth]{img/array.png} 48 | \end{frame} 49 | 50 | \begin{frame} 51 | \frametitle{Vector} 52 | \centering 53 | \includegraphics[width=\textwidth]{img/vector.png} 54 | \end{frame} 55 | 56 | \begin{frame} 57 | \frametitle{Forward list} 58 | \centering 59 | \includegraphics[width=\textwidth]{img/forward_list.png} 60 | \end{frame} 61 | 62 | \begin{frame} 63 | \frametitle{List} 64 | \centering 65 | \includegraphics[width=\textwidth]{img/list.png} 66 | \end{frame} 67 | 68 | \begin{frame} 69 | \frametitle{Map} 70 | \centering 71 | \includegraphics[width=\textwidth]{img/map.png} 72 | \end{frame} 73 | 74 | \begin{frame} 75 | \frametitle{Unordered map} 76 | \centering 77 | \includegraphics[width=\textwidth]{img/unordered_map.png} 78 | \end{frame} 79 | 80 | \subsection{Overview} 81 | \begin{frame} 82 | \frametitle{Operations and types} 83 | \centering 84 | \includegraphics[height=0.95\textheight]{img/members.png} 85 | \end{frame} 86 | 87 | \begin{frame} 88 | \frametitle{Operation complexity} 89 | \centering 90 | \includegraphics[height=0.9\textheight]{img/complexity.png} 91 | \end{frame} 92 | 93 | \subsection{Examples} 94 | \begin{frame}[fragile] 95 | \frametitle{Prime numbers} 96 | \begin{lstlisting} 97 | #include 98 | 99 | int main(){ 100 | std::vector primes; 101 | 102 | primes.emplace_back(2); 103 | 104 | for (int i=3; i<=max; ++i) 105 | if (is_prime(i)) 106 | primes.emplace_back(i); 107 | 108 | for (const auto& x: primes) 109 | std::cout << x << std::endl; 110 | } 111 | \end{lstlisting} 112 | \end{frame} 113 | 114 | \begin{frame}[fragile] 115 | \frametitle{Word count} 116 | \begin{lstlisting} 117 | #include 118 | 119 | int main(){ 120 | std::map words; 121 | 122 | for (std::string s; std::cin>>s;) 123 | ++words[s]; 124 | 125 | for (const auto& x: words) 126 | std::cout << x.first << ": " 127 | << x.second << std::endl; 128 | } 129 | \end{lstlisting} 130 | \end{frame} 131 | 132 | \begin{frame}[fragile] 133 | \frametitle{Word count} 134 | \begin{lstlisting} 135 | #include 136 | 137 | int main(){ 138 | std::unordered_map words; 139 | 140 | for (std::string s; std::cin>>s;) 141 | ++words[s]; 142 | 143 | for (const auto& x: words) 144 | std::cout << x.first << ": " 145 | << x.second << std::endl; 146 | } 147 | \end{lstlisting} 148 | \end{frame} 149 | -------------------------------------------------------------------------------- /lectures/python/03_advanced_topics/07_context_manager.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Context manager" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "with open(\"new_file.txt\", \"w\") as f:\n", 17 | " for i in range(10):\n", 18 | " print(i, file=f)\n", 19 | " # f.write(str(i)+'\\n')" 20 | ] 21 | }, 22 | { 23 | "cell_type": "code", 24 | "execution_count": null, 25 | "metadata": {}, 26 | "outputs": [], 27 | "source": [ 28 | "f.closed" 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "execution_count": null, 34 | "metadata": {}, 35 | "outputs": [], 36 | "source": [ 37 | "i" 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": null, 43 | "metadata": {}, 44 | "outputs": [], 45 | "source": [ 46 | "%%timeit\n", 47 | "\n", 48 | "a = []\n", 49 | "with open(\"new_file.txt\", \"r\") as f:\n", 50 | " for i in f:\n", 51 | " a.append(int(i))\n", 52 | "a" 53 | ] 54 | }, 55 | { 56 | "cell_type": "code", 57 | "execution_count": null, 58 | "metadata": {}, 59 | "outputs": [], 60 | "source": [ 61 | "%%timeit\n", 62 | "with open(\"new_file.txt\") as f:\n", 63 | " a = [int(i) for i in f]\n", 64 | "a" 65 | ] 66 | }, 67 | { 68 | "cell_type": "code", 69 | "execution_count": null, 70 | "metadata": {}, 71 | "outputs": [], 72 | "source": [ 73 | "%%timeit \n", 74 | "a = []\n", 75 | "for i in range(10):\n", 76 | " a.append(i)" 77 | ] 78 | }, 79 | { 80 | "cell_type": "code", 81 | "execution_count": null, 82 | "metadata": {}, 83 | "outputs": [], 84 | "source": [ 85 | "%%timeit\n", 86 | "a = [i for i in range(10)]" 87 | ] 88 | }, 89 | { 90 | "cell_type": "code", 91 | "execution_count": null, 92 | "metadata": {}, 93 | "outputs": [], 94 | "source": [ 95 | "# adapted from Fluent Python\n", 96 | "class LookingGlass:\n", 97 | " def __enter__(self): # no other arguments\n", 98 | " print(\"__enter__\")\n", 99 | " import sys\n", 100 | "\n", 101 | " self.original_write = sys.stdout.write\n", 102 | " sys.stdout.write = self.reverse_write\n", 103 | "\n", 104 | " def reverse_write(self, text):\n", 105 | " self.original_write(text[::-1])\n", 106 | "\n", 107 | " def __exit__(self, exc_type, exc_value, traceback):\n", 108 | " import sys\n", 109 | "\n", 110 | " sys.stdout.write = self.original_write # restore original\n", 111 | " # handling of exception, if any\n", 112 | " print(\"__exit__\")\n", 113 | " return True # everything has been managed\n", 114 | "\n", 115 | "\n", 116 | "with LookingGlass():\n", 117 | " print(\"What is going on?\")\n", 118 | " print(\"I cannot read this\")\n", 119 | "\n", 120 | "print(\"back to work\")" 121 | ] 122 | }, 123 | { 124 | "cell_type": "code", 125 | "execution_count": null, 126 | "metadata": {}, 127 | "outputs": [], 128 | "source": [] 129 | } 130 | ], 131 | "metadata": { 132 | "kernelspec": { 133 | "display_name": "Python 3", 134 | "language": "python", 135 | "name": "python3" 136 | }, 137 | "language_info": { 138 | "codemirror_mode": { 139 | "name": "ipython", 140 | "version": 3 141 | }, 142 | "file_extension": ".py", 143 | "mimetype": "text/x-python", 144 | "name": "python", 145 | "nbconvert_exporter": "python", 146 | "pygments_lexer": "ipython3", 147 | "version": "3.7.6" 148 | } 149 | }, 150 | "nbformat": 4, 151 | "nbformat_minor": 4 152 | } 153 | -------------------------------------------------------------------------------- /lectures/python/01_intro/06_sets.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## `set`s\n", 8 | "- like `dict`s but without values (they are **unordered**)\n", 9 | "- used to know if something exists (is present) avoiding repetitions\n", 10 | "- optimized for mathematical set operations (union, intersect" 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": null, 16 | "metadata": {}, 17 | "outputs": [], 18 | "source": [ 19 | "empty_set = set() # no other symbols can be used for an empty set\n", 20 | "even_numbers = {0, 2, 4, 6, 8, 10} # {} can be used if it is not empty\n", 21 | "print(type(even_numbers), even_numbers)" 22 | ] 23 | }, 24 | { 25 | "cell_type": "code", 26 | "execution_count": null, 27 | "metadata": {}, 28 | "outputs": [], 29 | "source": [ 30 | "even_numbers = {0, 0, 0, 2, 2, 4, 6, 8, 8, 8, 128}\n", 31 | "print(even_numbers)" 32 | ] 33 | }, 34 | { 35 | "cell_type": "code", 36 | "execution_count": null, 37 | "metadata": {}, 38 | "outputs": [], 39 | "source": [ 40 | "odd_numbers = {n for n in range(10) if n % 2}\n", 41 | "print(odd_numbers, type(odd_numbers))" 42 | ] 43 | }, 44 | { 45 | "cell_type": "code", 46 | "execution_count": null, 47 | "metadata": {}, 48 | "outputs": [], 49 | "source": [ 50 | "2 in odd_numbers" 51 | ] 52 | }, 53 | { 54 | "cell_type": "code", 55 | "execution_count": null, 56 | "metadata": {}, 57 | "outputs": [], 58 | "source": [ 59 | "2 in even_numbers" 60 | ] 61 | }, 62 | { 63 | "cell_type": "markdown", 64 | "metadata": {}, 65 | "source": [ 66 | "### union" 67 | ] 68 | }, 69 | { 70 | "cell_type": "code", 71 | "execution_count": null, 72 | "metadata": {}, 73 | "outputs": [], 74 | "source": [ 75 | "all_numbers = odd_numbers.union(even_numbers)\n", 76 | "print(all_numbers)\n", 77 | "all_numbers = odd_numbers | even_numbers\n", 78 | "print(all_numbers)" 79 | ] 80 | }, 81 | { 82 | "cell_type": "markdown", 83 | "metadata": {}, 84 | "source": [ 85 | "### intersect" 86 | ] 87 | }, 88 | { 89 | "cell_type": "code", 90 | "execution_count": null, 91 | "metadata": {}, 92 | "outputs": [], 93 | "source": [ 94 | "empty = odd_numbers.intersection(even_numbers)\n", 95 | "print(empty)\n", 96 | "empty = odd_numbers & even_numbers" 97 | ] 98 | }, 99 | { 100 | "cell_type": "markdown", 101 | "metadata": {}, 102 | "source": [ 103 | "### difference" 104 | ] 105 | }, 106 | { 107 | "cell_type": "code", 108 | "execution_count": null, 109 | "metadata": {}, 110 | "outputs": [], 111 | "source": [ 112 | "set1 = {1, 2, 3, 4, 5}\n", 113 | "set2 = {1, 2, 3}\n", 114 | "print(\"set1 - set2 -->\", set1 - set2)\n", 115 | "print(\"set2 - set1 -->\", set2 - set1)" 116 | ] 117 | }, 118 | { 119 | "cell_type": "markdown", 120 | "metadata": {}, 121 | "source": [ 122 | "### Iterability" 123 | ] 124 | }, 125 | { 126 | "cell_type": "code", 127 | "execution_count": null, 128 | "metadata": {}, 129 | "outputs": [], 130 | "source": [ 131 | "for x in set1 - set2:\n", 132 | " print(x)" 133 | ] 134 | } 135 | ], 136 | "metadata": { 137 | "kernelspec": { 138 | "display_name": "Python 3", 139 | "language": "python", 140 | "name": "python3" 141 | }, 142 | "language_info": { 143 | "codemirror_mode": { 144 | "name": "ipython", 145 | "version": 3 146 | }, 147 | "file_extension": ".py", 148 | "mimetype": "text/x-python", 149 | "name": "python", 150 | "nbconvert_exporter": "python", 151 | "pygments_lexer": "ipython3", 152 | "version": "3.7.6" 153 | } 154 | }, 155 | "nbformat": 4, 156 | "nbformat_minor": 4 157 | } 158 | -------------------------------------------------------------------------------- /lectures/python/02_symbols/03_copy_deepcopy.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "### Shallow is the default" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "l = [1, 2, [4, 5, 6], 8]\n", 17 | "o = l" 18 | ] 19 | }, 20 | { 21 | "cell_type": "code", 22 | "execution_count": null, 23 | "metadata": {}, 24 | "outputs": [], 25 | "source": [ 26 | "o == l" 27 | ] 28 | }, 29 | { 30 | "cell_type": "code", 31 | "execution_count": null, 32 | "metadata": {}, 33 | "outputs": [], 34 | "source": [ 35 | "o is l" 36 | ] 37 | }, 38 | { 39 | "cell_type": "code", 40 | "execution_count": null, 41 | "metadata": {}, 42 | "outputs": [], 43 | "source": [ 44 | "id(o), id(l)" 45 | ] 46 | }, 47 | { 48 | "cell_type": "code", 49 | "execution_count": null, 50 | "metadata": {}, 51 | "outputs": [], 52 | "source": [ 53 | "o = list(l)" 54 | ] 55 | }, 56 | { 57 | "cell_type": "code", 58 | "execution_count": null, 59 | "metadata": {}, 60 | "outputs": [], 61 | "source": [ 62 | "o == l" 63 | ] 64 | }, 65 | { 66 | "cell_type": "code", 67 | "execution_count": null, 68 | "metadata": {}, 69 | "outputs": [], 70 | "source": [ 71 | "o is l" 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "execution_count": null, 77 | "metadata": {}, 78 | "outputs": [], 79 | "source": [ 80 | "l.append(9)\n", 81 | "print(l)\n", 82 | "print(o)" 83 | ] 84 | }, 85 | { 86 | "cell_type": "code", 87 | "execution_count": null, 88 | "metadata": {}, 89 | "outputs": [], 90 | "source": [ 91 | "l[2].append(7)\n", 92 | "print(l)\n", 93 | "print(o)" 94 | ] 95 | }, 96 | { 97 | "cell_type": "code", 98 | "execution_count": null, 99 | "metadata": {}, 100 | "outputs": [], 101 | "source": [ 102 | "import copy" 103 | ] 104 | }, 105 | { 106 | "cell_type": "code", 107 | "execution_count": null, 108 | "metadata": {}, 109 | "outputs": [], 110 | "source": [ 111 | "o = copy.copy(l)\n", 112 | "l[2].append(888)\n", 113 | "print(l)\n", 114 | "print(o)" 115 | ] 116 | }, 117 | { 118 | "cell_type": "code", 119 | "execution_count": null, 120 | "metadata": {}, 121 | "outputs": [], 122 | "source": [ 123 | "o = copy.deepcopy(l)\n", 124 | "l[2].append(3333)\n", 125 | "print(l)\n", 126 | "print(o)" 127 | ] 128 | }, 129 | { 130 | "cell_type": "code", 131 | "execution_count": null, 132 | "metadata": {}, 133 | "outputs": [], 134 | "source": [ 135 | "def augmented(ll):\n", 136 | " ll += [99]\n", 137 | "\n", 138 | "\n", 139 | "augmented(l)\n", 140 | "print(l)" 141 | ] 142 | }, 143 | { 144 | "cell_type": "code", 145 | "execution_count": null, 146 | "metadata": {}, 147 | "outputs": [], 148 | "source": [ 149 | "def assignment(ll):\n", 150 | " ll = [99]\n", 151 | "\n", 152 | "\n", 153 | "assignment(l)\n", 154 | "print(l)" 155 | ] 156 | }, 157 | { 158 | "cell_type": "code", 159 | "execution_count": null, 160 | "metadata": {}, 161 | "outputs": [], 162 | "source": [] 163 | } 164 | ], 165 | "metadata": { 166 | "kernelspec": { 167 | "display_name": "Python 3", 168 | "language": "python", 169 | "name": "python3" 170 | }, 171 | "language_info": { 172 | "codemirror_mode": { 173 | "name": "ipython", 174 | "version": 3 175 | }, 176 | "file_extension": ".py", 177 | "mimetype": "text/x-python", 178 | "name": "python", 179 | "nbconvert_exporter": "python", 180 | "pygments_lexer": "ipython3", 181 | "version": "3.7.6" 182 | } 183 | }, 184 | "nbformat": 4, 185 | "nbformat_minor": 4 186 | } 187 | -------------------------------------------------------------------------------- /lectures/python/02_symbols/06_nasty_bugs.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Nasty bugs" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "### free vars" 15 | ] 16 | }, 17 | { 18 | "cell_type": "code", 19 | "execution_count": null, 20 | "metadata": {}, 21 | "outputs": [], 22 | "source": [ 23 | "def define_methods(number):\n", 24 | " methods = []\n", 25 | " for i in range(number):\n", 26 | " methods.append(lambda var: 2 * var + i)\n", 27 | " return methods\n", 28 | "\n", 29 | "\n", 30 | "funcs = define_methods(10)\n", 31 | "\n", 32 | "funcs[2](20) # expect 2*20 + 2 = 42" 33 | ] 34 | }, 35 | { 36 | "cell_type": "code", 37 | "execution_count": null, 38 | "metadata": {}, 39 | "outputs": [], 40 | "source": [ 41 | "def define_methods(number):\n", 42 | " methods = []\n", 43 | " for i in range(number):\n", 44 | " methods.append(lambda var, i=i: 2 * var + i)\n", 45 | " return methods\n", 46 | "\n", 47 | "\n", 48 | "funcs = define_methods(10)\n", 49 | "\n", 50 | "funcs[2](20) # expect 2*20 + 2 = 42" 51 | ] 52 | }, 53 | { 54 | "cell_type": "markdown", 55 | "metadata": {}, 56 | "source": [ 57 | "### (mutable) default values\n", 58 | "The only mode pf parameter passing in Python is **call by sharing**." 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "execution_count": null, 64 | "metadata": {}, 65 | "outputs": [], 66 | "source": [ 67 | "def func(a=[]):\n", 68 | " a += [\"you visited func function\"]\n", 69 | " return a\n", 70 | "\n", 71 | "\n", 72 | "l_default = func()\n", 73 | "print(l_default)" 74 | ] 75 | }, 76 | { 77 | "cell_type": "code", 78 | "execution_count": null, 79 | "metadata": {}, 80 | "outputs": [], 81 | "source": [ 82 | "l_custom = func([\"under control\"])\n", 83 | "print(l_custom)" 84 | ] 85 | }, 86 | { 87 | "cell_type": "code", 88 | "execution_count": null, 89 | "metadata": {}, 90 | "outputs": [], 91 | "source": [ 92 | "OMG = func()\n", 93 | "print(OMG)" 94 | ] 95 | }, 96 | { 97 | "cell_type": "code", 98 | "execution_count": null, 99 | "metadata": {}, 100 | "outputs": [], 101 | "source": [ 102 | "l_default" 103 | ] 104 | }, 105 | { 106 | "cell_type": "markdown", 107 | "metadata": {}, 108 | "source": [ 109 | "### None" 110 | ] 111 | }, 112 | { 113 | "cell_type": "code", 114 | "execution_count": null, 115 | "metadata": {}, 116 | "outputs": [], 117 | "source": [ 118 | "def func(a=None):\n", 119 | " \"\"\"returns a list\"\"\"\n", 120 | " if a:\n", 121 | " return list(a) + [\"you visited func function\"]\n", 122 | " return [\"you visited func function\"]" 123 | ] 124 | }, 125 | { 126 | "cell_type": "code", 127 | "execution_count": null, 128 | "metadata": {}, 129 | "outputs": [], 130 | "source": [ 131 | "a = func((\"first\", 2))\n", 132 | "a" 133 | ] 134 | }, 135 | { 136 | "cell_type": "code", 137 | "execution_count": null, 138 | "metadata": {}, 139 | "outputs": [], 140 | "source": [ 141 | "func()" 142 | ] 143 | } 144 | ], 145 | "metadata": { 146 | "kernelspec": { 147 | "display_name": "Python 3", 148 | "language": "python", 149 | "name": "python3" 150 | }, 151 | "language_info": { 152 | "codemirror_mode": { 153 | "name": "ipython", 154 | "version": 3 155 | }, 156 | "file_extension": ".py", 157 | "mimetype": "text/x-python", 158 | "name": "python", 159 | "nbconvert_exporter": "python", 160 | "pygments_lexer": "ipython3", 161 | "version": "3.7.6" 162 | } 163 | }, 164 | "nbformat": 4, 165 | "nbformat_minor": 4 166 | } 167 | -------------------------------------------------------------------------------- /lectures/python/03_advanced_topics/02_property.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Property\n", 8 | "- make an attribute **constant** (read only)\n", 9 | "- perform specific actions (e.g., error checking, pre/post-conditions) when an attribute is **set** " 10 | ] 11 | }, 12 | { 13 | "cell_type": "markdown", 14 | "metadata": {}, 15 | "source": [ 16 | "### const" 17 | ] 18 | }, 19 | { 20 | "cell_type": "code", 21 | "execution_count": null, 22 | "metadata": {}, 23 | "outputs": [], 24 | "source": [ 25 | "class Point:\n", 26 | " def __init__(self, x, y):\n", 27 | " self.x = x\n", 28 | " self.y = y\n", 29 | "\n", 30 | " # other methods are omitted\n", 31 | "\n", 32 | "\n", 33 | "def use_point(p):\n", 34 | " # complicated stuff\n", 35 | " p.x = 0 # bug, I would like to have p.x, p.y const\n", 36 | "\n", 37 | "\n", 38 | "p = Point(3, 4)\n", 39 | "\n", 40 | "use_point(p)\n", 41 | "\n", 42 | "print(p.x, p.y)" 43 | ] 44 | }, 45 | { 46 | "cell_type": "code", 47 | "execution_count": null, 48 | "metadata": {}, 49 | "outputs": [], 50 | "source": [ 51 | "class Point:\n", 52 | " def __init__(self, x, y):\n", 53 | " self._x = x\n", 54 | " self._y = y\n", 55 | "\n", 56 | " @property\n", 57 | " def x(self):\n", 58 | " return self._x\n", 59 | "\n", 60 | " @property\n", 61 | " def y(self):\n", 62 | " return self._y\n", 63 | "\n", 64 | " # other methods are omitted\n", 65 | "\n", 66 | "\n", 67 | "def use_point(p):\n", 68 | " # complicated stuff\n", 69 | " p.x = 0 # I expect an error\n", 70 | "\n", 71 | "\n", 72 | "p = Point(3, 4)\n", 73 | "\n", 74 | "use_point(p)\n", 75 | "\n", 76 | "print(p.x, p.y)" 77 | ] 78 | }, 79 | { 80 | "cell_type": "markdown", 81 | "metadata": {}, 82 | "source": [ 83 | "### Perform some checks" 84 | ] 85 | }, 86 | { 87 | "cell_type": "code", 88 | "execution_count": null, 89 | "metadata": {}, 90 | "outputs": [], 91 | "source": [ 92 | "class Date:\n", 93 | " def __init__(self, day, month, year):\n", 94 | " self._day = day\n", 95 | " self._month = month\n", 96 | " self._year = year\n", 97 | "\n", 98 | " def check_validity(self, day, month, year):\n", 99 | " # should check if the date is valid\n", 100 | " print(\"validating date...\", end=\"\")\n", 101 | " # what should I do if the date is not good?\n", 102 | " print(\"Done\")\n", 103 | "\n", 104 | " @property\n", 105 | " def day(self):\n", 106 | " return self._day\n", 107 | "\n", 108 | " @day.setter\n", 109 | " def day(self, new_day):\n", 110 | " self.check_validity(new_day, self._month, self._year)\n", 111 | " self._day = new_day\n", 112 | "\n", 113 | "\n", 114 | "d = Date(5, 8, 1986)\n", 115 | "\n", 116 | "print(d.day)\n", 117 | "d.day = 67" 118 | ] 119 | }, 120 | { 121 | "cell_type": "code", 122 | "execution_count": null, 123 | "metadata": {}, 124 | "outputs": [], 125 | "source": [ 126 | "help(property)" 127 | ] 128 | } 129 | ], 130 | "metadata": { 131 | "kernelspec": { 132 | "display_name": "Python 3", 133 | "language": "python", 134 | "name": "python3" 135 | }, 136 | "language_info": { 137 | "codemirror_mode": { 138 | "name": "ipython", 139 | "version": 3 140 | }, 141 | "file_extension": ".py", 142 | "mimetype": "text/x-python", 143 | "name": "python", 144 | "nbconvert_exporter": "python", 145 | "pygments_lexer": "ipython3", 146 | "version": "3.7.6" 147 | } 148 | }, 149 | "nbformat": 4, 150 | "nbformat_minor": 4 151 | } 152 | -------------------------------------------------------------------------------- /exercises/c++/vector/as_vector_allocator.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | template> 8 | class Vector{ 9 | Allocator allocator; 10 | T* elem; 11 | std::size_t _size{}; 12 | std::size_t _capacity{}; 13 | 14 | void check_and_increase_capacity(){ 15 | if(_capacity == 0) 16 | reserve(12); // reserve 8 elements 17 | else if (_size == _capacity) 18 | reserve(2*_capacity); 19 | } 20 | 21 | template 22 | void _push_back(O&& x){ 23 | check_and_increase_capacity(); 24 | elem[_size] = std::forward(x); 25 | ++_size; 26 | } 27 | 28 | 29 | public: 30 | 31 | auto size() const { return _size; } 32 | auto capacity() const { return _capacity; } 33 | 34 | Vector() = default; 35 | ~Vector() { 36 | for(std::size_t i = 0; i < _size; ++i) 37 | allocator.destroy(elem+i); 38 | 39 | allocator.deallocate(elem,_capacity); 40 | 41 | } 42 | 43 | Vector(std::initializer_list list): // pass by value 44 | elem{allocator.allocate(list.size())}, 45 | _size{list.size()}, 46 | _capacity{list.size()}{ 47 | 48 | std::uninitialized_copy(list.begin(), list.end(), elem); 49 | 50 | // for(std::size_t i=0; i::allocate(n) 57 | 58 | for(std::size_t i = 0; i < _size; ++i) 59 | allocator.construct(tmp+i, std::move(elem[i])); 60 | 61 | for(std::size_t i = 0; i < _size; ++i) 62 | allocator.destroy(elem+i); 63 | 64 | allocator.deallocate(elem,_capacity); 65 | 66 | elem = tmp; 67 | _capacity = n; 68 | } 69 | 70 | } 71 | 72 | void push_back(const T& x){ 73 | _push_back(x); 74 | } 75 | 76 | void push_back(T&& x){ 77 | _push_back(std::move(x)); 78 | } 79 | 80 | auto& operator[](const std::size_t i){ 81 | // pre-conditions: good point for assert 82 | return elem[i]; 83 | } 84 | 85 | const auto& operator[](const std::size_t i) const{ 86 | // pre-conditions: good point for assert 87 | return elem[i]; 88 | } 89 | 90 | 91 | template // variadic templates; packing 92 | void emplace_back(Types&&... args){ // unpack 93 | check_and_increase_capacity(); 94 | allocator.construct(elem + _size, T{std::forward(args)...}); // T{} // please update 95 | ++_size; 96 | } 97 | 98 | 99 | 100 | }; 101 | 102 | template 103 | std::ostream& operator<<(std::ostream& os, const Vector& x){ 104 | os <<"capacity: " << x.capacity() << ", size: " << x.size() << "\n"; 105 | for(auto i =0u; i < x.size(); ++i) 106 | os << x[i] << " "; 107 | os << std::endl; 108 | return os; 109 | 110 | } 111 | 112 | struct Foo{ 113 | Foo(){std::cout << "foo ctor" << std::endl;} 114 | }; 115 | 116 | 117 | int main(){ 118 | 119 | Vector vf{{},{}}; 120 | // std::vector vf{{},{}}; 121 | vf.emplace_back(); 122 | std::cout << vf.capacity() << std::endl; 123 | 124 | return 0; 125 | 126 | Vector x{1,2,3,4}; 127 | 128 | std::cout << x; 129 | 130 | x.push_back(3); 131 | 132 | std::cout << x; 133 | 134 | 135 | std::vector> vs; 136 | 137 | vs.push_back({4,"hello"}); // push_back takes 1 arg 138 | 139 | vs.emplace_back(4,"hello"); // 2 args 140 | 141 | // std::vector v; // default ctor 142 | // v.reserve(128); 143 | // std::vector v1(4,2); // custom ctor 144 | // std::vector v2{4,2,4,5,6}; // std::initializer_list // higher priority 145 | 146 | // for (const auto x : v1) 147 | // std::cout << x << " "; 148 | // std::cout << std::endl; 149 | 150 | 151 | // for (const auto x : v2) 152 | // std::cout << x << " "; 153 | // std::cout << std::endl; 154 | 155 | } 156 | -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/tex_files/summary.tex: -------------------------------------------------------------------------------- 1 | \section{The C++ standard library} 2 | \begin{frame} 3 | \frametitle{What is the standard library?} 4 | The standard library is the set of components specified by the ISO C++ standard ($\sim 1600$ dense pages for C++17) and shipped with identical behavior (modulo performance) by every C++ implementation. 5 | \vfill 6 | \url{https://github.com/cplusplus/draft} 7 | \end{frame} 8 | \subsection{Summary} 9 | \begin{frame} 10 | \frametitle{The C++ Programming Language} 11 | \centering 12 | \includegraphics[height=0.7\textheight]{img/summary.png} 13 | \end{frame} 14 | 15 | \subsection{Headers} 16 | \begin{frame} 17 | \frametitle{The header files} 18 | \centering 19 | \includegraphics[width=0.7\textwidth]{img/head_01.png} 20 | \end{frame} 21 | \begin{frame} 22 | \frametitle{The header files} 23 | \centering 24 | \includegraphics[width=0.7\textwidth]{img/head_02.png} 25 | \end{frame} 26 | \begin{frame} 27 | \frametitle{The header files} 28 | \centering 29 | \includegraphics[width=0.7\textwidth]{img/head_03.png} 30 | \end{frame} 31 | \begin{frame} 32 | \frametitle{The header files} 33 | \centering 34 | \includegraphics[width=0.7\textwidth]{img/head_04.png} 35 | \end{frame} 36 | \begin{frame} 37 | \frametitle{The header files} 38 | \centering 39 | \includegraphics[width=0.7\textwidth]{img/head_05.png} 40 | \end{frame} 41 | \begin{frame} 42 | \frametitle{The header files} 43 | \centering 44 | \includegraphics[width=0.7\textwidth]{img/head_06.png} 45 | \end{frame} 46 | \begin{frame} 47 | \frametitle{The header files} 48 | \centering 49 | \includegraphics[width=0.7\textwidth]{img/head_07.png} 50 | \end{frame} 51 | \begin{frame} 52 | \frametitle{The header files} 53 | \centering 54 | \includegraphics[width=0.7\textwidth]{img/head_08.png} 55 | \end{frame} 56 | \begin{frame} 57 | \frametitle{The header files} 58 | \centering 59 | \includegraphics[width=0.7\textwidth]{img/head_09.png} 60 | \end{frame} 61 | \begin{frame} 62 | \frametitle{The header files} 63 | \centering 64 | \includegraphics[width=0.7\textwidth]{img/head_10.png} 65 | \end{frame} 66 | \begin{frame} 67 | \frametitle{The header files} 68 | \centering 69 | \includegraphics[width=0.7\textwidth]{img/head_11.png} 70 | \end{frame} 71 | \begin{frame} 72 | \frametitle{The header files} 73 | \centering 74 | \includegraphics[width=0.7\textwidth]{img/head_12.png} 75 | \end{frame} 76 | \subsection{STL} 77 | \begin{frame} 78 | \frametitle{We will focus on the STL \smiley} 79 | \centering 80 | \includegraphics[width=0.6\textwidth]{img/alex.jpeg} 81 | \hfill 82 | \includegraphics[width=0.35\textwidth]{img/alex2.jpeg} 83 | \hfill 84 | \end{frame} 85 | \subsection{Concurrency} 86 | \begin{frame}[fragile] 87 | \frametitle{We will not see the concurrency library \frownie } 88 | \begin{lstlisting} 89 | int main(){ 90 | // f and g are independent 91 | f(); 92 | g(); 93 | } 94 | \end{lstlisting} 95 | \end{frame} 96 | 97 | \begin{frame}[fragile] 98 | \frametitle{We will not see the concurrency library \frownie } 99 | \begin{lstlisting} 100 | #include 101 | 102 | int main(){ 103 | // f and g are independent 104 | std::thread t{ f }; 105 | g(); 106 | t.join(); 107 | } 108 | \end{lstlisting} 109 | 110 | \end{frame} 111 | 112 | 113 | 114 | \begin{frame}[fragile] 115 | \frametitle{We will not see the concurrency library \frownie } 116 | \begin{lstlisting} 117 | #include 118 | 119 | int main(){ 120 | // f and g are independent 121 | auto from_f = std::async( f ); 122 | auto from_g = g(); 123 | ... 124 | complicated( from_g, from_f.get() ); 125 | } 126 | \end{lstlisting} 127 | \end{frame} 128 | 129 | \begin{frame}[fragile] 130 | \frametitle{We will not see the concurrency library \frownie } 131 | \framesubtitle{Link against \texttt{pthread}} 132 | %% \lstset{language=bash} 133 | \begin{lstlisting} 134 | $ c++ test.cpp -pthread 135 | \end{lstlisting} 136 | \vfill 137 | \begin{lstlisting} 138 | $ c++ test.cpp -c 139 | $ c++ test.o -pthread 140 | \end{lstlisting} 141 | 142 | \end{frame} 143 | -------------------------------------------------------------------------------- /lectures/c++/08_STL/presentation/stl_intro.tex: -------------------------------------------------------------------------------- 1 | % GMGFP 2 | \documentclass{beamer} 3 | \usepackage{caption} 4 | \captionsetup[table]{name=, labelformat = empty, labelsep=newline} 5 | 6 | %\usepackage{beamerthemeblackboard} 7 | \usepackage{natbib} 8 | \usepackage{calc} 9 | \usepackage{empheq} 10 | \usepackage{subfig} 11 | \usepackage{siunitx} 12 | \usepackage{fontenc} 13 | \usepackage{amsmath} 14 | \usepackage{array} 15 | \usepackage{wasysym} 16 | \newcolumntype{C}[1]{>{\centering\let\newline\\\arraybackslash\hspace{0pt}}m{#1}} 17 | \newcolumntype{L}[1]{>{\raggedright\let\newline\\\arraybackslash\hspace{0pt}}m{#1}} 18 | \newcolumntype{R}[1]{>{\raggedleft\let\newline\\\arraybackslash\hspace{0pt}}m{#1}} 19 | \usepackage{multirow} 20 | \usepackage[absolute,overlay]{textpos} 21 | %% \usepackage{bbding} 22 | \definecolor{links}{HTML}{2A1B81} 23 | \hypersetup{colorlinks,linkcolor=,urlcolor=links} 24 | \usepackage{listings} 25 | \lstloadlanguages{Matlab} 26 | \lstloadlanguages{C++} 27 | \definecolor{MyDarkGreen}{rgb}{0.0,0.4,0.0} 28 | \lstset{language=C++, 29 | %frame=single, 30 | basicstyle=\small, 31 | tabsize=4, 32 | showstringspaces=false, 33 | numbers=none, 34 | numberstyle=\tiny, 35 | breaklines=true, 36 | firstnumber=1, 37 | language=C++, 38 | basicstyle=\ttfamily, 39 | keywordstyle=\color{blue}\ttfamily, 40 | stringstyle=\color{red}\ttfamily, 41 | commentstyle=\color{gray}\ttfamily, 42 | morecomment=[l][\color{blue}]{\#} 43 | } 44 | \usepackage{tikz} 45 | \usetikzlibrary{arrows,automata} 46 | \usetikzlibrary{positioning} 47 | 48 | \newcommand{\ped}[1]{_{\mathrm{#1}}} 49 | \newcommand{\up}[1]{^{\mathrm{#1}}} 50 | \renewcommand{\r}{\mathbf{r}} 51 | \renewcommand{\d}{\mathrm{d}} 52 | \newcommand{\dund}[1]{\underline{\underline{#1}}} 53 | \newcommand{\und}[1]{\underline{#1}} 54 | \newcommand{\mmu}{\boldsymbol\mu} 55 | 56 | 57 | \usetheme{nasatalk} 58 | 59 | \AtBeginSection[]{\frame{\tableofcontents[currentsection,hideallsubsections]}} 60 | \begin{document} 61 | \title[STL]{A quick overview of the C++ Standard (Template) Library} 62 | \subtitle{Advanced Programming} 63 | 64 | 65 | \logo{% 66 | \makebox[0.99\paperwidth]{% 67 | \includegraphics[height=0.7cm,keepaspectratio]{img/mhpc-logo2.pdf}% 68 | \hfill% 69 | \includegraphics[height=1cm,keepaspectratio]{img/sissa_logo.jpg}% 70 | }% 71 | }% 72 | 73 | 74 | \author[Alberto Sartori]{Alberto Sartori} 75 | 76 | 77 | \date[December 10, 2020]{December 10, 2020} 78 | 79 | \setbeamercolor{caption name}{fg=white} 80 | 81 | \begin{frame}%[noframenumbering] 82 | \maketitle 83 | \end{frame} 84 | 85 | \usebackgroundtemplate{% 86 | % 87 | } 88 | 89 | \logo{% 90 | \vspace*{-0.2cm} 91 | \makebox[0.99\paperwidth]{% 92 | \includegraphics[height=0.4cm,keepaspectratio]{img/mhpc-logo2.pdf}% 93 | \hfill% 94 | \includegraphics[height=0.7cm,keepaspectratio]{img/sissa_logo.png}% 95 | }% 96 | }% 97 | 98 | \begin{frame}%[noframenumbering] 99 | \frametitle{Outline} 100 | \tableofcontents[hideallsubsections] 101 | \end{frame} 102 | \input{tex_files/summary.tex} 103 | \input{tex_files/containers.tex} 104 | \input{tex_files/iterators.tex} 105 | \input{tex_files/algorithms.tex} 106 | \input{tex_files/function_objects.tex} 107 | \section*{} 108 | \begin{frame} 109 | \centering 110 | \includegraphics[width=0.8\textwidth]{img/alexfest.jpg} 111 | \end{frame} 112 | 113 | \defbeamertemplate*{footline}{for appendix} 114 | { 115 | \leavevmode% 116 | \hbox{% 117 | \begin{beamercolorbox}[wd=.333333\paperwidth,ht=2.25ex,dp=1ex,center]{author in head/foot}% 118 | %\usebeamerfont{author in head/foot}\insertshortauthor 119 | \usebeamerfont{author in head/foot}\insertshortauthor~~\insertshortinstitute 120 | \end{beamercolorbox}% 121 | \begin{beamercolorbox}[wd=.333333\paperwidth,ht=2.25ex,dp=1ex,center]{title in head/foot}% 122 | \usebeamerfont{title in head/foot}\insertshorttitle 123 | \end{beamercolorbox}% 124 | \begin{beamercolorbox}[wd=.333333\paperwidth,ht=2.25ex,dp=1ex,right]{date in head/foot}% 125 | \usebeamerfont{date in head/foot}\insertshortdate{}\hspace*{2em} 126 | % \insertframenumber{} / \inserttotalframenumber\hspace*{2ex} 127 | \end{beamercolorbox}}% 128 | \vskip0pt% 129 | } 130 | \usebackgroundtemplate{} 131 | %% \input{tex_files/bckup_slides.tex} 132 | 133 | \end{document} 134 | -------------------------------------------------------------------------------- /lectures/python/03_advanced_topics/06_generators.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Generators, iterables, and iterators" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "# taken from Python documentation\n", 17 | "class Reverse:\n", 18 | " \"\"\"Iterator for looping over a sequence backwards.\"\"\"\n", 19 | "\n", 20 | " def __init__(self, data):\n", 21 | " self.data = data\n", 22 | " self.index = len(data)\n", 23 | "\n", 24 | " def __iter__(self):\n", 25 | " return self\n", 26 | "\n", 27 | " def __next__(self):\n", 28 | " if self.index == 0:\n", 29 | " raise StopIteration\n", 30 | " self.index = self.index - 1\n", 31 | " return self.data[self.index]\n", 32 | "\n", 33 | "\n", 34 | "for i in Reverse( (\"first\", \"second\", 3, \"IV\") ):\n", 35 | " print(i)" 36 | ] 37 | }, 38 | { 39 | "cell_type": "code", 40 | "execution_count": null, 41 | "metadata": {}, 42 | "outputs": [], 43 | "source": [ 44 | "rev = Reverse((\"first\", \"second\", 3, \"IV\"))\n", 45 | "print(next(rev))\n", 46 | "print(next(rev))\n", 47 | "print(next(rev))\n", 48 | "print(next(rev))\n", 49 | "\n", 50 | "print(\"let's loop again...\")\n", 51 | "for i in rev:\n", 52 | " print(i)" 53 | ] 54 | }, 55 | { 56 | "cell_type": "code", 57 | "execution_count": null, 58 | "metadata": {}, 59 | "outputs": [], 60 | "source": [ 61 | "def reverse(data):\n", 62 | " for x in data[::-1]:\n", 63 | " yield x\n", 64 | "\n", 65 | "\n", 66 | "for i in reverse((\"first\", \"second\", 3, \"IV\")):\n", 67 | " print(i)" 68 | ] 69 | }, 70 | { 71 | "cell_type": "code", 72 | "execution_count": null, 73 | "metadata": {}, 74 | "outputs": [], 75 | "source": [ 76 | "type(reverse((1,2)))" 77 | ] 78 | }, 79 | { 80 | "cell_type": "markdown", 81 | "metadata": {}, 82 | "source": [ 83 | "### Generator expressions" 84 | ] 85 | }, 86 | { 87 | "cell_type": "code", 88 | "execution_count": null, 89 | "metadata": {}, 90 | "outputs": [], 91 | "source": [ 92 | "for i in (n for n in range(10) if n % 2 == 0):\n", 93 | " print(i)" 94 | ] 95 | }, 96 | { 97 | "cell_type": "code", 98 | "execution_count": null, 99 | "metadata": {}, 100 | "outputs": [], 101 | "source": [ 102 | "g = (n for n in range(10) if n % 2 == 0)" 103 | ] 104 | }, 105 | { 106 | "cell_type": "code", 107 | "execution_count": null, 108 | "metadata": {}, 109 | "outputs": [], 110 | "source": [ 111 | "g" 112 | ] 113 | }, 114 | { 115 | "cell_type": "code", 116 | "execution_count": null, 117 | "metadata": {}, 118 | "outputs": [], 119 | "source": [ 120 | "next(g)" 121 | ] 122 | }, 123 | { 124 | "cell_type": "markdown", 125 | "metadata": {}, 126 | "source": [ 127 | "## Generators can be chained" 128 | ] 129 | }, 130 | { 131 | "cell_type": "code", 132 | "execution_count": null, 133 | "metadata": {}, 134 | "outputs": [], 135 | "source": [ 136 | "even_integers = (n for n in range(10) if not n % 2)\n", 137 | "squared = (n * n for n in even_integers)\n", 138 | "negated = (-n for n in squared)\n", 139 | "\n", 140 | "for i in negated:\n", 141 | " print(i)" 142 | ] 143 | }, 144 | { 145 | "cell_type": "code", 146 | "execution_count": null, 147 | "metadata": {}, 148 | "outputs": [], 149 | "source": [ 150 | "type(negated)" 151 | ] 152 | } 153 | ], 154 | "metadata": { 155 | "kernelspec": { 156 | "display_name": "Python 3", 157 | "language": "python", 158 | "name": "python3" 159 | }, 160 | "language_info": { 161 | "codemirror_mode": { 162 | "name": "ipython", 163 | "version": 3 164 | }, 165 | "file_extension": ".py", 166 | "mimetype": "text/x-python", 167 | "name": "python", 168 | "nbconvert_exporter": "python", 169 | "pygments_lexer": "ipython3", 170 | "version": "3.7.6" 171 | } 172 | }, 173 | "nbformat": 4, 174 | "nbformat_minor": 4 175 | } 176 | -------------------------------------------------------------------------------- /lectures/python/02_symbols/07_classes.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "### Class\n", 8 | "- `class`\n", 9 | "- `self` (even though you can use whatever)" 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": null, 15 | "metadata": {}, 16 | "outputs": [], 17 | "source": [ 18 | "class Point:\n", 19 | " def __init__(self, x, y):\n", 20 | " self.x = x\n", 21 | " self.y = y\n", 22 | "\n", 23 | " def method_with_no_arg(self): # if you remove self --> error\n", 24 | " print(\"no args!\")\n", 25 | "\n", 26 | " def update(self, x, y): # do I really need this?\n", 27 | " self.x = x\n", 28 | " self.y = y\n", 29 | "\n", 30 | " def print(self): # is this pythonic?\n", 31 | " print(self.x, self.y)\n", 32 | "\n", 33 | " def equal(self, other): # is this pythonic?\n", 34 | " return (self.x, self.y) == (other.x, other.y)\n", 35 | "\n", 36 | "\n", 37 | "p = Point(1, 2)\n", 38 | "print(p.x, p.y)" 39 | ] 40 | }, 41 | { 42 | "cell_type": "code", 43 | "execution_count": null, 44 | "metadata": {}, 45 | "outputs": [], 46 | "source": [ 47 | "p.update(7, 8)\n", 48 | "p.print()\n", 49 | "\n", 50 | "p.x, p.y = 0, 0\n", 51 | "p.print()" 52 | ] 53 | }, 54 | { 55 | "cell_type": "code", 56 | "execution_count": null, 57 | "metadata": {}, 58 | "outputs": [], 59 | "source": [ 60 | "p.method_with_no_arg()" 61 | ] 62 | }, 63 | { 64 | "cell_type": "code", 65 | "execution_count": null, 66 | "metadata": {}, 67 | "outputs": [], 68 | "source": [ 69 | "p2 = Point(1, 0)\n", 70 | "p.equal(p2)" 71 | ] 72 | }, 73 | { 74 | "cell_type": "markdown", 75 | "metadata": {}, 76 | "source": [ 77 | "### Better" 78 | ] 79 | }, 80 | { 81 | "cell_type": "code", 82 | "execution_count": null, 83 | "metadata": {}, 84 | "outputs": [], 85 | "source": [ 86 | "class Point:\n", 87 | " \"\"\"Documention of class Point\"\"\"\n", 88 | "\n", 89 | " def __init__(self, x, y):\n", 90 | " self.x = x\n", 91 | " self.y = y\n", 92 | "\n", 93 | " def __repr__(self):\n", 94 | " return f\"{self.__class__.__name__}({self.x!r}, {self.y!r})\"\n", 95 | "\n", 96 | " # don't need to define __str__ beacause if falls back to __repr__\n", 97 | "\n", 98 | " def __eq__(self, other):\n", 99 | " # return self.x == other.x and self.y == other.y\n", 100 | " return (self.x, self.y) == (other.x, other.y)\n", 101 | "\n", 102 | " def __abs__(self):\n", 103 | " \"\"\"return absolute value\"\"\"\n", 104 | " import math\n", 105 | "\n", 106 | " return math.hypot(self.x, self.y)\n", 107 | "\n", 108 | "\n", 109 | "p = Point(3, 4)\n", 110 | "print(p)" 111 | ] 112 | }, 113 | { 114 | "cell_type": "code", 115 | "execution_count": null, 116 | "metadata": {}, 117 | "outputs": [], 118 | "source": [ 119 | "p2 = Point(4, 5)\n", 120 | "p == p2" 121 | ] 122 | }, 123 | { 124 | "cell_type": "code", 125 | "execution_count": null, 126 | "metadata": {}, 127 | "outputs": [], 128 | "source": [ 129 | "p2.x, p2.y = 3, 4\n", 130 | "p == p2" 131 | ] 132 | }, 133 | { 134 | "cell_type": "code", 135 | "execution_count": null, 136 | "metadata": {}, 137 | "outputs": [], 138 | "source": [ 139 | "abs(p)" 140 | ] 141 | }, 142 | { 143 | "cell_type": "code", 144 | "execution_count": null, 145 | "metadata": {}, 146 | "outputs": [], 147 | "source": [ 148 | "help(p)" 149 | ] 150 | }, 151 | { 152 | "cell_type": "code", 153 | "execution_count": null, 154 | "metadata": {}, 155 | "outputs": [], 156 | "source": [] 157 | } 158 | ], 159 | "metadata": { 160 | "kernelspec": { 161 | "display_name": "Python 3", 162 | "language": "python", 163 | "name": "python3" 164 | }, 165 | "language_info": { 166 | "codemirror_mode": { 167 | "name": "ipython", 168 | "version": 3 169 | }, 170 | "file_extension": ".py", 171 | "mimetype": "text/x-python", 172 | "name": "python", 173 | "nbconvert_exporter": "python", 174 | "pygments_lexer": "ipython3", 175 | "version": "3.7.6" 176 | } 177 | }, 178 | "nbformat": 4, 179 | "nbformat_minor": 4 180 | } 181 | -------------------------------------------------------------------------------- /lectures/c++/05_copy_move_semantics/06_copy_move.cpp: -------------------------------------------------------------------------------- 1 | #include // std::copy 2 | #include 3 | #include 4 | 5 | template 6 | class Vector { 7 | std::size_t _size; 8 | std::unique_ptr elem; 9 | 10 | public: 11 | // custom ctor 12 | explicit Vector(const std::size_t length) 13 | : _size{length}, elem{new T[length]{}} { 14 | std::cout << "custom ctor\n"; 15 | } 16 | 17 | // Vector(const std::initializer_list args) 18 | // : _size{args.size()}, elem{new T[_size]} { 19 | // std::cout << "list ctor\n"; 20 | // std::copy(args.begin(), args.end(), begin()); 21 | // } 22 | 23 | // default ctor 24 | Vector() { std::cout << "default ctor\n"; } // _size uninitialized 25 | // Vector() : _size{}, elem{} { std::cout << "default ctor\n"; } // this could 26 | // be better Vector() = default; 27 | 28 | ~Vector() = default; 29 | 30 | ///////////////////////// 31 | // copy semantics 32 | 33 | // copy ctor -- deep copy 34 | Vector(const Vector& v); 35 | 36 | // copy assignment -- deep copy 37 | Vector& operator=(const Vector& v); 38 | // end of copy semantics 39 | ///////////////////////// 40 | 41 | ///////////////////////// 42 | // move semantics 43 | 44 | // move ctor 45 | Vector(Vector&& v) : _size{std::move(v._size)}, elem{std::move(v.elem)} { 46 | std::cout << "move ctor\n"; 47 | } 48 | 49 | // Vector(Vector&& v) = default; // ok 50 | 51 | // move assignment 52 | Vector& operator=(Vector&& v) { 53 | std::cout << "move assignment\n"; 54 | _size = std::move(v._size); 55 | elem = std::move(v.elem); 56 | return *this; 57 | } 58 | 59 | // Vector& operator=(Vector&& v) = default; // ok 60 | 61 | // end move semantics 62 | ///////////////////////// 63 | 64 | const T& operator[](const std::size_t& i) const { return elem[i]; } 65 | T& operator[](const std::size_t& i) { return elem[i]; } 66 | 67 | std::size_t size() const { return _size; } 68 | 69 | // range-for 70 | const T* begin() const { return &elem[0]; } 71 | T* begin() { return &elem[0]; } 72 | 73 | const T* end() const { return &elem[_size]; } 74 | T* end() { return &elem[_size]; } 75 | }; 76 | 77 | // copy ctor 78 | template 79 | Vector::Vector(const Vector& v) : _size{v._size}, elem{new T[_size]} { 80 | std::cout << "copy ctor\n"; 81 | std::copy(v.begin(), v.end(), begin()); 82 | } 83 | 84 | // copy assignment 85 | template 86 | Vector& Vector::operator=(const Vector& v) { 87 | std::cout << "copy assignment (\n"; 88 | 89 | // we could decide that this operation is allowed if and only if 90 | // _size == v._size 91 | // 92 | 93 | elem.reset(); // first of all clean my memory 94 | auto tmp = v; // then use copy ctor 95 | (*this) = std::move(tmp); // finally move assignment 96 | 97 | // or we do everything by hand.. 98 | // and we can do not reset and call new again if the sizes are suitable 99 | 100 | std::cout << ")\n"; 101 | return *this; 102 | 103 | // is this approach consistent with self-assignment vx=vx? 104 | } 105 | 106 | template 107 | // why we return by value? 108 | Vector operator+(const Vector& lhs, const Vector& rhs) { 109 | const auto size = lhs.size(); 110 | 111 | // how we should check that the two vectors have the same size? 112 | 113 | Vector res(size); 114 | for (std::size_t i = 0; i < size; ++i) 115 | res[i] = lhs[i] + rhs[i]; 116 | 117 | return res; 118 | } 119 | 120 | template 121 | std::ostream& operator<<(std::ostream& os, const Vector& v) { 122 | for (const auto& x : v) 123 | os << x << " "; 124 | os << std::endl; 125 | return os; 126 | } 127 | 128 | int main() { 129 | std::cout << "Vector v0; calls\n"; 130 | Vector v0; 131 | std::cout << v0.size() << "\n"; 132 | std::cout << "Vector v00{}; calls\n"; 133 | Vector v00{}; 134 | std::cout << v00.size() << "\n"; 135 | 136 | std::cout << "\nVector v1{5}; calls\n"; 137 | Vector v1{5}; 138 | 139 | std::cout << "\nVector v2 = v1; calls\n"; 140 | Vector v2 = v1; 141 | std::cout << "\nv2 = Vector{7}; calls\n"; 142 | v2 = Vector{7}; 143 | std::cout << "\nVector v3{std::move(v1)}; calls\n"; 144 | Vector v3{std::move(v1)}; // now v1 should not be used 145 | std::cout << "\nv3 = v2; calls\n"; 146 | v3 = v2; 147 | std::cout << "\nv2 = " << v2; 148 | std::cout << "v3 = " << v3; 149 | 150 | std::cout << "\nassign some values to v3\n"; 151 | { 152 | // auto i = v3.size(); 153 | // while (i--) 154 | // v3[i] = i; 155 | 156 | int c = 0; 157 | for (auto& x : v3) 158 | x = c++; 159 | } 160 | // v3=v3; 161 | std::cout << "\nv2 = " << v2; 162 | std::cout << "v3 = " << v3; 163 | 164 | std::cout << "\nVector v4{v3 + v3}; calls\n"; 165 | Vector v4{v3 + v3}; 166 | 167 | std::cout << "v4 = " << v4; 168 | 169 | std::cout << "\nNRVO: Named Return Value Optimization\n"; 170 | 171 | std::cout << "\nv4 = v3 + v3 + v2 + v3; calls\n"; 172 | v4 = v3 + v3 + v2 + v3; 173 | std::cout << "v4 = " << v4; 174 | 175 | return 0; 176 | } 177 | --------------------------------------------------------------------------------