├── .gitignore ├── .travis.yml ├── LICENSE ├── Makefile ├── __init__.py ├── content ├── blog │ ├── 01_how_to_use_decorators.rst │ ├── 02_HDF5_python.rst │ ├── 03_Virtual_Environment.rst │ ├── 04_how_to_use_decorators_2.rst │ ├── 05_how_to_control_network.rst │ ├── 06_introducing_lantz.rst │ ├── 07_national_instruments_python.rst │ ├── 08_intro_to_classes.rst │ ├── 09_build_device_example.rst │ ├── 10_threads_or_processes.rst │ ├── 11_documenting.rst │ ├── 12_handling_exceptions.rst │ ├── 13_storing_data.rst │ ├── 14_Storing_data_2.rst │ ├── 15_Storing_data_3.rst │ ├── 16_context_manager.rst │ ├── 17_mutable_and_immutable.rst │ ├── 18_mutable_tuples.rst │ ├── 19_hashable_objects.rst │ ├── 20_deep_shallow_copies.rst │ ├── 21_Default_Attributes_Classes.rst │ ├── 22_Step_by_step_qt.rst │ ├── 23_accessing_raspberry.rst │ ├── 24_Releasing_PyNTA.rst │ ├── 25_ZMQ.rst │ ├── 26_ZMQ.rst │ ├── 27_Custom_CRM.rst │ ├── 28_using_fabric.rst │ ├── 29_args_kwargs.rst │ ├── 30_Lambda_Fuctions.rst │ ├── 31_Threads_Part_1.rst │ ├── 32_Threads_Part_2.rst │ ├── 33_duck_typing.rst │ ├── 34_monkey_patching.rst │ ├── 35_Threads_Part_3.rst │ ├── 36_threads_face_recognition.rst │ ├── 37_absolute_relative_imports.rst │ ├── alvaro-reyes-735660-unsplash.jpg │ ├── amirali-mirhashemian-brXPUp545NI-unsplash.jpg │ ├── amirali-mirhashemian-kiH-RBm08NQ-unsplash.jpg │ ├── chuttersnap-553860-unsplash.jpg │ ├── cody-davis-253928-unsplash.jpg │ ├── dan-gold-382057-unsplash.jpg │ ├── daniel-cheung-129841-unsplash.jpg │ ├── frank-mckenna-122867-unsplash.jpg │ ├── imports-blog-illustration.png │ ├── ivana-cajina-324103-unsplash.jpg │ ├── joshua-coleman-655076-unsplash.jpg │ ├── joshua-sortino-215039-unsplash.jpg │ ├── luca-bravo-217276-unsplash.jpg │ ├── michael-aleo-571965-unsplash.jpg │ ├── michael-browning-227688-unsplash.jpg │ ├── michal-pechardo-502908-unsplash.jpg │ ├── network_cables.jpg │ ├── pietro-jeng-266017-unsplash.jpg │ ├── pynta_screenshot.png │ ├── python1-01.png │ ├── rawpixel-274862-unsplash.jpg │ ├── rawpixel-760036-unsplash.jpg │ ├── rebecca-georgia-269933-unsplash.jpg │ ├── samuel-zeller-118195-unsplash.jpg │ ├── shashank-sahay-1659565-unsplash.jpg │ ├── thomas-jensen-592813-unsplash.jpg │ ├── tobias-fischer-185901-unsplash.jpg │ ├── tom-hermans-642319-unsplash.jpg │ ├── toolbox.jpg │ ├── victor-garcia-560967-unsplash.jpg │ ├── writing-machine.jpg │ └── yeo-khee-793533-unsplash.jpg ├── images │ ├── 10_images │ │ ├── 01_base_page.png │ │ ├── 02_base_module.png │ │ ├── RTL_advance_settings.png │ │ ├── RTL_advanced_settings.png │ │ ├── RTL_services.png │ │ ├── RTL_settings.png │ │ └── RTL_versions.png │ ├── 22_images │ │ ├── 01_main_window.png │ │ ├── 02_mainwindowlayout.png │ │ ├── 03_two_buttons.png │ │ ├── 04_two_buttons_layout.png │ │ └── 05_acquired_image.png │ ├── 27_images │ │ ├── 01_jupyter.jpg │ │ └── 02_jupyter.png │ ├── 35_images │ │ ├── 01_firefox.png │ │ └── 02_firefox.png │ ├── 37_images │ │ └── PyCharm_config.png │ └── new_picture.jpg ├── pages │ ├── about.rst │ ├── cookies.rst │ ├── new_picture.jpg │ └── privacy.rst └── static │ └── img │ └── compartments.jpg ├── deploy_rsa.enc ├── example_code ├── 04_how_to_use_decorators_2 │ ├── A_recap.py │ ├── BB_docstrings.py │ ├── B_docstrings.py │ ├── C_arguments.py │ ├── D_register.py │ ├── E_methods.py │ ├── F_classes.py │ └── G_decorating_classes.py ├── 10_threads_processes │ ├── A_base_class.py │ ├── BBB_Threads.py │ ├── BB_threads.py │ ├── B_threads.py │ ├── C_stopping_thread.py │ ├── DD_subclassing.py │ ├── D_subclassing.py │ ├── E_locks.py │ ├── F_limits.py │ ├── G_multiprocessing.py │ └── H_queues.py ├── 11_documenting │ ├── docs │ │ ├── conf_complete.py │ │ └── source │ │ │ ├── conf.py │ │ │ ├── factorial.rst │ │ │ ├── index.rst │ │ │ ├── people.rst │ │ │ └── teacher.rst │ └── my_module │ │ ├── __init__.py │ │ ├── factorial.py │ │ └── people.py ├── 12_exceptions │ ├── A_exeptions.py │ ├── B_exceptions.py │ ├── C_exceptions.py │ ├── D_exceptions.py │ ├── E_exceptions.py │ ├── F_exceptions.py │ ├── G_exceptions.py │ ├── H_exceptions.py │ ├── I_exceptions.py │ ├── JJ_exceptions.py │ ├── J_exceptions.py │ ├── K_exceptions.py │ ├── L_exceptions.py │ ├── M_warning.py │ ├── N_custom_exceptions.py │ ├── O_exceptions.py │ ├── P_traceback.py │ └── my_data.dat ├── 13_storing_data │ ├── AA_data.dat │ ├── AA_plain_text_two_columns.py │ ├── AB_data.dat │ ├── AB_plain_text_header.py │ ├── AC_plain_text_reading.py │ ├── AD_data.dat │ ├── AD_plain_text_incremental.py │ ├── AE_data.dat │ ├── AE_plain_text_with.py │ ├── A_data.dat │ ├── A_plain_text.py │ ├── BA_data.dat │ ├── BA_no_numpy.py │ ├── BB_data.dat │ ├── BB_no_numpy.py │ ├── BC_data.dat │ ├── BC_formatting.py │ ├── BD_data.dat │ ├── BD_two_columns.py │ ├── CA_reading_back.py │ ├── CB_reading_back.py │ ├── CC_reading_back.py │ ├── CD_reading_back.py │ ├── DA_data.dat │ ├── DA_non_numeric.py │ ├── DB_data.csv │ ├── DB_data.dat │ ├── DB_num_and_str.py │ ├── DC_reading_non_num.py │ └── __init__.py ├── 14_storing_data │ ├── AA_comparison.py │ ├── AA_data.dat │ ├── AB_unicode.dat │ ├── AB_unicode.py │ ├── AC_ascii.dat │ ├── AC_binary.py │ ├── AD_ascii.dat │ ├── AD_numpy_binary.py │ ├── AE_ascii.dat │ ├── AE_numpy_binary.py │ ├── AF_custom.dat │ ├── AF_custom_binary.dat │ ├── AF_custom_binary.py │ ├── AF_custom_binary2.dat │ ├── AG_pickle.dat │ ├── AG_pickle_numpy.py │ ├── AH_pickle_function.dat │ ├── AH_pickle_function.py │ ├── AII_load_object.py │ ├── AI_pickle_object.dat │ ├── AI_pickle_object.py │ ├── AJ_pickle_exploit.py │ ├── AK_json.dat │ ├── AK_json.py │ ├── ALL_read_numpy.py │ ├── AL_json_numpy.dat │ ├── AL_json_numpy.py │ ├── AM_data.yml │ ├── AM_example.yml │ ├── AM_read_yml.py │ └── AM_write.py ├── 15_databases │ ├── AA_create_db.py │ ├── AB_create_table.py │ ├── AC_add_data.py │ ├── AD_retrieve_data.py │ ├── AE_create_primary_key.py │ ├── AF_default_date.py │ ├── AG_limit_fields.py │ ├── AH_foreign_key.py │ ├── AI_numpy.py │ ├── AJ_join.py │ └── __init__.py ├── 16_context_managers │ ├── AA_save_list.dat │ ├── AA_save_list.py │ ├── AB_save_with.py │ ├── AC_custom_class.py │ ├── AD_constructor.py │ ├── AE_metaclass.py │ ├── My_File_With.txt │ ├── save_thread.txt │ └── test ├── 17_mutable_immutable │ ├── AA_default_arguments.py │ ├── AB_default_arguments.py │ ├── AC_mutable_arguments.py │ ├── AD_object_comparison.py │ └── AE_custom_objects.py ├── 18_mutable_tuples │ └── AA_tuples_dicts.py ├── 19_hashable_objects │ ├── AA_hashable_objects.py │ └── AB_hashable_objects_dicts.py ├── 20_deep_shallow_copies │ ├── AA_custom_objects.py │ ├── AB_custom_objects.py │ ├── AC_custom_copy.py │ ├── AD_custom_deep_copy.py │ └── AE_copying_functions.py ├── 21_Classes_Mutables │ ├── AA_defaults.py │ ├── AB_defaults.py │ └── AC_class_attributes.py ├── 22_Step_By_Step_Qt │ ├── AA_test_qt.py │ ├── AB_openCV_1.py │ ├── AC_video.py │ ├── AD_simple_qt.py │ ├── AE_qt_button.py │ ├── AF_qt_two_buttons.py │ ├── AG_layout.py │ ├── AH_acquire_frame.py │ └── AI_camera_model │ │ ├── __init__.py │ │ ├── models.py │ │ ├── start.py │ │ └── views.py ├── 25_ZMQ │ ├── 01_client_req_rep.py │ ├── 01_server_req_rep.py │ ├── 02_client_req_rep.py │ ├── 02_server_req_rep.py │ ├── 03_client_camera.py │ ├── 03_raspi_client_camera.py │ ├── 03_raspi_server_camera.py │ ├── 03_server_camera.py │ ├── 03_test_open_cv.py │ ├── 04_push_pull_simple_sink.py │ ├── 04_push_pull_sink.py │ ├── 04_push_pull_ventilator.py │ ├── 04_push_pull_worker.py │ ├── 05_pub_sub_publisher.py │ ├── 05_pub_sub_subscriber_1.py │ └── 05_pub_sub_subscriber_2.py ├── 26_ZMQ │ ├── camera.py │ ├── publisher.py │ ├── start.py │ └── subscribers.py ├── 27_CRM │ ├── Test_Notebook.ipynb │ ├── base_email.html │ ├── config_example.yml │ ├── simple_CRM_01.ipynb │ ├── simple_CRM_03_clean_db.ipynb │ ├── simple_CRM_04_send_all.ipynb │ ├── simple_CRM_05_clean_db_2.ipynb │ ├── simple_crm_02.ipynb │ └── test_email.txt ├── 28_fabric │ ├── configure_server.py │ └── test.test ├── 29_args_kwargs │ ├── AA_simple_test.py │ ├── AB_args_args.py │ ├── AC_args_function.py │ ├── AD_generator_args.py │ ├── AE_simple_kwargs.py │ ├── AF_kwargs_mix.py │ ├── AG_kwargs_unpack.py │ ├── AH_default_values.py │ └── AI_area.py ├── 30_lambdas │ ├── AA_pandas.py │ ├── AB_Qt.py │ └── example_data.csv ├── 31_threads │ ├── AA_simple.py │ ├── AB_multi_threads_simple.py │ ├── AC_concurrency.py │ ├── AC_concurrency.txt │ ├── AD_numpy_example.py │ ├── AE_numpy_thread.py │ ├── AF_numpy_multi_thread.py │ ├── AG_numpy_loops.py │ ├── AH_locks.py │ ├── AI_Two_locks.py │ ├── AJ_rlocks.py │ ├── AK_timeout.py │ ├── AL_event.py │ └── AM_stopping_threads.py ├── 32_threads_data │ ├── AA_shared_memory.py │ ├── AB_sync_data_access.py │ ├── AC_queue_simple.py │ ├── AD_queue_add.py │ ├── AE_queue_faster.py │ ├── AF_queues_sleep.py │ ├── AG_queues_no_wait.py │ ├── AH_queues_to_stop.py │ ├── AI_download_data.py │ └── AJ_threads_download_data.py ├── 33_duck_typing │ ├── AA_duck_typing.py │ ├── AB_duck_typing_numpy.py │ ├── AC_duck_typing.py │ ├── AD_custom_class.py │ ├── AE_Complex_data_structure.py │ └── config.yml ├── 34_monkey_patching │ ├── AAA_class_attributes.py │ ├── AA_custom_class.py │ ├── AB_custom_method.py │ ├── AC_attributes.py │ ├── AD_types.py │ ├── AE_module.py │ ├── AE_module2.py │ └── AE_script.py ├── 35_threads_crawler │ ├── AA_download_parse.py │ ├── AB_recursive_crawling.py │ └── AC_threading_download.py ├── 37_imports │ ├── AA_sys_argv.py │ ├── ABB_import_all.py │ ├── AB_sys_argv.py │ ├── AC_import_as.py │ ├── AD_import_as.py │ ├── AE_absolute_imports │ │ ├── first.py │ │ ├── module_a │ │ │ └── third.py │ │ ├── numpy │ │ │ ├── __init__.py │ │ │ └── sleep.py │ │ ├── second.py │ │ └── sys_append.py │ ├── AE_pckg │ │ ├── __init__.py │ │ ├── another.py │ │ ├── mod_a │ │ │ ├── __init__.py │ │ │ └── file_a.py │ │ ├── mod_b │ │ │ ├── __init__.py │ │ │ └── file_b.py │ │ └── start.py │ └── AF_relative │ │ ├── __init__.py │ │ ├── __init__.pyc │ │ ├── mod_a │ │ ├── __init__.py │ │ ├── __init__.pyc │ │ ├── file_a.py │ │ └── file_a.pyc │ │ ├── mod_b │ │ ├── __init__.py │ │ ├── __init__.pyc │ │ ├── file_b.py │ │ ├── file_b.pyc │ │ └── mod_a │ │ │ ├── __init__.py │ │ │ ├── __init__.pyc │ │ │ ├── file_c.py │ │ │ └── file_c.pyc │ │ └── start.py └── __init__.py ├── plugins ├── __init__.py ├── header_image │ ├── AmaticSC-Bold.ttf │ ├── FrederickatheGreat-Regular.ttf │ ├── IndieFlower.ttf │ ├── __init__.py │ └── header_image.py ├── new_pigment.py ├── newsletter_directive.py ├── sitemap │ ├── Readme.rst │ ├── __init__.py │ └── sitemap.py └── tipue_search │ ├── README.md │ ├── __init__.py │ └── tipue_search.py ├── requirements.txt ├── settings.py ├── settings_publish.py ├── static └── img │ └── compartments.jpg └── theme ├── static ├── css │ ├── IndiFlower.css │ ├── bootstrap.min.css │ ├── m8JVjfNVeKWVnh3QMuKkFcZVaUuH.woff2 │ ├── newsletter_signup.css │ ├── normalize.css │ ├── pftl.css │ ├── pygment.css │ └── tipuesearch.css ├── img │ ├── PFTL_Logo.png │ ├── Pacman_Spinner.svg │ ├── calendar.png │ ├── clock.png │ ├── cover_mockup.png │ ├── favicon.ico │ ├── general_header.jpg │ ├── square_logo.png │ └── tags.png └── js │ ├── bootstrap.bundle.js │ ├── bootstrap.bundle.js.map │ ├── bootstrap.bundle.min.js │ ├── bootstrap.bundle.min.js.map │ ├── bootstrap.js │ ├── bootstrap.js.map │ ├── bootstrap.min.js │ ├── bootstrap.min.js.map │ ├── comment_submit.js │ ├── comments_load.js │ ├── expired_storage.js │ ├── expired_storage.min.js │ ├── freechapter_subscribe.js │ ├── ie10-viewport-bug-workaround.js │ ├── jquery.min.js │ ├── jquery.toc.js │ ├── load_latest_articles.js │ ├── newsletter_capture.js │ ├── newsletter_popup.js │ ├── newsletter_subscribe.js │ ├── tether.js │ ├── tipuesearch.js │ ├── tipuesearch.min.js │ ├── tipuesearch_content.js │ └── tipuesearch_set.js └── templates ├── article.html ├── article_sidebar.html ├── author_info.html ├── base.html ├── comments.html ├── cookie_consent.html ├── footer.html ├── footer_javascript.html ├── free_chapter_form.html ├── head_scripts.html ├── index.html ├── macros └── article_thumbnail.html ├── nav.html ├── newsletter_card.html ├── newsletter_funnel.html ├── newsletter_popup.html ├── newsletter_sidebar.html ├── page.html ├── pagination.html ├── search.html ├── social_sharing.html ├── static_books.html ├── static_index.html └── support_us_card.html /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | __pycache__/ 3 | output 4 | *.npy 5 | *.hdf5 6 | *.db 7 | config.yml 8 | .ipynb_checkpoints/ 9 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | addons: 2 | ssh_known_hosts: pythonforthelab.com 3 | language: python 4 | python: 5 | - '3.6' 6 | sudo: disabled 7 | install: 8 | - pip install -r requirements.txt 9 | script: 10 | - make publish 11 | before_deploy: 12 | - openssl aes-256-cbc -K $encrypted_330e801a8bfb_key -iv $encrypted_330e801a8bfb_iv 13 | -in deploy_rsa.enc -out /tmp/deploy_rsa -d 14 | - eval "$(ssh-agent -s)" 15 | - chmod 600 /tmp/deploy_rsa 16 | - ssh-add /tmp/deploy_rsa 17 | deploy: 18 | provider: script 19 | skip_cleanup: true 20 | script: rsync -r --delete-after --quiet $TRAVIS_BUILD_DIR/output pftl_blog@pythonforthelab.com:~/ 21 | on: 22 | branch: master -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | run: 2 | pelican -t theme -s settings.py -o output/ content 3 | cp -r static/* output/static/ 4 | 5 | publish: 6 | pelican -t theme -s settings_publish.py -o output/ content 7 | cp -r static/* output/static/ 8 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/__init__.py -------------------------------------------------------------------------------- /content/blog/28_using_fabric.rst: -------------------------------------------------------------------------------- 1 | Using Fabric to Automate Remote Tasks 2 | ===================================== 3 | 4 | :status: draft 5 | :date: 2019-02-04 6 | :author: Aquiles Carattino 7 | :subtitle: Send and receive emails from Jupyter notebooks, keep track of people 8 | :header: {attach}rebecca-georgia-269933-unsplash.jpg 9 | :tags: CRM, Jupyter, Databases, Relational, SQLAlchemy, SQLite, Customers, email 10 | :description: Send and receive emails from Jupyter notebooks, keep track of people 11 | 12 | Configure a Server 13 | ------------------ 14 | 15 | Other Things 16 | ------------ 17 | -------------------------------------------------------------------------------- /content/blog/36_threads_face_recognition.rst: -------------------------------------------------------------------------------- 1 | Using Threads and Face Recognition 2 | ================================== 3 | 4 | :status: draft 5 | :date: 2019-07-25 6 | :author: Aquiles Carattino 7 | :subtitle: Using threads to acquire images from a camera and do face recognition 8 | :description: Using threads to acquire images from a camera and do face recognition 9 | :header: {attach}ivana-cajina-324103-unsplash.jpg 10 | :tags: functions, methods, arguments, packing, unpacking, args, kwargs 11 | 12 | We have seen in the previous articles how to set up threads to run different tasks simultaneously. -------------------------------------------------------------------------------- /content/blog/alvaro-reyes-735660-unsplash.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/alvaro-reyes-735660-unsplash.jpg -------------------------------------------------------------------------------- /content/blog/amirali-mirhashemian-brXPUp545NI-unsplash.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/amirali-mirhashemian-brXPUp545NI-unsplash.jpg -------------------------------------------------------------------------------- /content/blog/amirali-mirhashemian-kiH-RBm08NQ-unsplash.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/amirali-mirhashemian-kiH-RBm08NQ-unsplash.jpg -------------------------------------------------------------------------------- /content/blog/chuttersnap-553860-unsplash.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/chuttersnap-553860-unsplash.jpg -------------------------------------------------------------------------------- /content/blog/cody-davis-253928-unsplash.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/cody-davis-253928-unsplash.jpg -------------------------------------------------------------------------------- /content/blog/dan-gold-382057-unsplash.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/dan-gold-382057-unsplash.jpg -------------------------------------------------------------------------------- /content/blog/daniel-cheung-129841-unsplash.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/daniel-cheung-129841-unsplash.jpg -------------------------------------------------------------------------------- /content/blog/frank-mckenna-122867-unsplash.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/frank-mckenna-122867-unsplash.jpg -------------------------------------------------------------------------------- /content/blog/imports-blog-illustration.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/imports-blog-illustration.png -------------------------------------------------------------------------------- /content/blog/ivana-cajina-324103-unsplash.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/ivana-cajina-324103-unsplash.jpg -------------------------------------------------------------------------------- /content/blog/joshua-coleman-655076-unsplash.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/joshua-coleman-655076-unsplash.jpg -------------------------------------------------------------------------------- /content/blog/joshua-sortino-215039-unsplash.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/joshua-sortino-215039-unsplash.jpg -------------------------------------------------------------------------------- /content/blog/luca-bravo-217276-unsplash.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/luca-bravo-217276-unsplash.jpg -------------------------------------------------------------------------------- /content/blog/michael-aleo-571965-unsplash.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/michael-aleo-571965-unsplash.jpg -------------------------------------------------------------------------------- /content/blog/michael-browning-227688-unsplash.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/michael-browning-227688-unsplash.jpg -------------------------------------------------------------------------------- /content/blog/michal-pechardo-502908-unsplash.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/michal-pechardo-502908-unsplash.jpg -------------------------------------------------------------------------------- /content/blog/network_cables.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/network_cables.jpg -------------------------------------------------------------------------------- /content/blog/pietro-jeng-266017-unsplash.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/pietro-jeng-266017-unsplash.jpg -------------------------------------------------------------------------------- /content/blog/pynta_screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/pynta_screenshot.png -------------------------------------------------------------------------------- /content/blog/python1-01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/python1-01.png -------------------------------------------------------------------------------- /content/blog/rawpixel-274862-unsplash.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/rawpixel-274862-unsplash.jpg -------------------------------------------------------------------------------- /content/blog/rawpixel-760036-unsplash.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/rawpixel-760036-unsplash.jpg -------------------------------------------------------------------------------- /content/blog/rebecca-georgia-269933-unsplash.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/rebecca-georgia-269933-unsplash.jpg -------------------------------------------------------------------------------- /content/blog/samuel-zeller-118195-unsplash.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/samuel-zeller-118195-unsplash.jpg -------------------------------------------------------------------------------- /content/blog/shashank-sahay-1659565-unsplash.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/shashank-sahay-1659565-unsplash.jpg -------------------------------------------------------------------------------- /content/blog/thomas-jensen-592813-unsplash.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/thomas-jensen-592813-unsplash.jpg -------------------------------------------------------------------------------- /content/blog/tobias-fischer-185901-unsplash.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/tobias-fischer-185901-unsplash.jpg -------------------------------------------------------------------------------- /content/blog/tom-hermans-642319-unsplash.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/tom-hermans-642319-unsplash.jpg -------------------------------------------------------------------------------- /content/blog/toolbox.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/toolbox.jpg -------------------------------------------------------------------------------- /content/blog/victor-garcia-560967-unsplash.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/victor-garcia-560967-unsplash.jpg -------------------------------------------------------------------------------- /content/blog/writing-machine.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/writing-machine.jpg -------------------------------------------------------------------------------- /content/blog/yeo-khee-793533-unsplash.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/blog/yeo-khee-793533-unsplash.jpg -------------------------------------------------------------------------------- /content/images/10_images/01_base_page.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/images/10_images/01_base_page.png -------------------------------------------------------------------------------- /content/images/10_images/02_base_module.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/images/10_images/02_base_module.png -------------------------------------------------------------------------------- /content/images/10_images/RTL_advance_settings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/images/10_images/RTL_advance_settings.png -------------------------------------------------------------------------------- /content/images/10_images/RTL_advanced_settings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/images/10_images/RTL_advanced_settings.png -------------------------------------------------------------------------------- /content/images/10_images/RTL_services.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/images/10_images/RTL_services.png -------------------------------------------------------------------------------- /content/images/10_images/RTL_settings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/images/10_images/RTL_settings.png -------------------------------------------------------------------------------- /content/images/10_images/RTL_versions.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/images/10_images/RTL_versions.png -------------------------------------------------------------------------------- /content/images/22_images/01_main_window.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/images/22_images/01_main_window.png -------------------------------------------------------------------------------- /content/images/22_images/02_mainwindowlayout.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/images/22_images/02_mainwindowlayout.png -------------------------------------------------------------------------------- /content/images/22_images/03_two_buttons.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/images/22_images/03_two_buttons.png -------------------------------------------------------------------------------- /content/images/22_images/04_two_buttons_layout.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/images/22_images/04_two_buttons_layout.png -------------------------------------------------------------------------------- /content/images/22_images/05_acquired_image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/images/22_images/05_acquired_image.png -------------------------------------------------------------------------------- /content/images/27_images/01_jupyter.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/images/27_images/01_jupyter.jpg -------------------------------------------------------------------------------- /content/images/27_images/02_jupyter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/images/27_images/02_jupyter.png -------------------------------------------------------------------------------- /content/images/35_images/01_firefox.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/images/35_images/01_firefox.png -------------------------------------------------------------------------------- /content/images/35_images/02_firefox.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/images/35_images/02_firefox.png -------------------------------------------------------------------------------- /content/images/37_images/PyCharm_config.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/images/37_images/PyCharm_config.png -------------------------------------------------------------------------------- /content/images/new_picture.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/images/new_picture.jpg -------------------------------------------------------------------------------- /content/pages/about.rst: -------------------------------------------------------------------------------- 1 | About Us 2 | ======== 3 | :save_as: about/index.html 4 | 5 | Python for the Lab was born as a companion for the courses given by `Uetke `_. The idea is to provide a series of articles that can boost the readers in their Python endeavours. If you have any doubts, or are facing a problem to which there is no obvious solution, or are looking for an opinion, the best is to join the `forum `_, where you will meet a lot of like-minded people. 6 | 7 | 8 | Aquiles 9 | ------- 10 | .. image:: {attach}new_picture.jpg 11 | :alt: Aquiles Carattino 12 | 13 | My name is Aquiles and I am the guy behind Python for the Lab (or PFTL). If you would like to get in contact with me or check my projects, you can follow me on `Github `_ or just drop me a line at **aquiles@uetke.com**. I am always on the look out for great ideas and inspiration. -------------------------------------------------------------------------------- /content/pages/cookies.rst: -------------------------------------------------------------------------------- 1 | Cookie Policy for Python For The Lab 2 | ==================================== 3 | :save_as: cookie-policy/index.html 4 | 5 | **Python for the Lab** does not store cookies on your computer, neither from third parties. We use server access logs to monitor the most popular articles and detect possible problems or abuses of the website. 6 | 7 | 8 | However if you are still looking for more information then you can contact us through one of our preferred contact methods: 9 | 10 | - Email: aquiles@uetke.com -------------------------------------------------------------------------------- /content/pages/new_picture.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/pages/new_picture.jpg -------------------------------------------------------------------------------- /content/static/img/compartments.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/content/static/img/compartments.jpg -------------------------------------------------------------------------------- /deploy_rsa.enc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/deploy_rsa.enc -------------------------------------------------------------------------------- /example_code/04_how_to_use_decorators_2/A_recap.py: -------------------------------------------------------------------------------- 1 | def check_positive(func): 2 | """Checks that the inputs of a function are positive. 3 | """ 4 | def func_wrapper(x, y): 5 | """Function wrapper""" 6 | if x < 0 or y < 0: 7 | raise Exception("Both x and y have to be positive for function {} to work".format(func.__name__)) 8 | res = func(x, y) 9 | return res 10 | 11 | return func_wrapper 12 | 13 | 14 | @check_positive 15 | def average(x, y): 16 | """Calculates the average of two numbers. 17 | """ 18 | return (x + y) / 2 19 | 20 | a = average(1, 2) 21 | print(a) 22 | b = average(1, -1) 23 | print(b) 24 | 25 | -------------------------------------------------------------------------------- /example_code/04_how_to_use_decorators_2/BB_docstrings.py: -------------------------------------------------------------------------------- 1 | from functools import wraps 2 | 3 | 4 | def check_positive(func): 5 | @wraps(func) 6 | def func_wrapper(x, y): 7 | if x < 0 or y < 0: 8 | raise Exception("Both x and y have to be positive for function {} to work".format(func.__name__)) 9 | res = func(x, y) 10 | return res 11 | 12 | return func_wrapper 13 | 14 | 15 | @check_positive 16 | def average(x, y): 17 | """Calculates the average of two numbers. 18 | """ 19 | return (x + y) / 2 20 | -------------------------------------------------------------------------------- /example_code/04_how_to_use_decorators_2/B_docstrings.py: -------------------------------------------------------------------------------- 1 | def check_positive(func): 2 | """Decorator to check that input values are positive. 3 | """ 4 | def func_wrapper(x, y): 5 | if x < 0 or y < 0: 6 | raise Exception("Both x and y have to be positive for function {} to work".format(func.__name__)) 7 | res = func(x, y) 8 | return res 9 | 10 | func_wrapper.__name__ = func.__name__ 11 | func_wrapper.__doc__ = func.__doc__ 12 | return func_wrapper 13 | 14 | 15 | @check_positive 16 | def average(x, y): 17 | """Calculates the average of two numbers. 18 | """ 19 | return (x + y) / 2 -------------------------------------------------------------------------------- /example_code/04_how_to_use_decorators_2/C_arguments.py: -------------------------------------------------------------------------------- 1 | from functools import wraps 2 | 3 | 4 | def check_above(threshold): 5 | print('Threshold: ', threshold) 6 | def wrap(func): 7 | @wraps(func) 8 | def func_wrapper(x, y): 9 | if x < threshold or y < threshold: 10 | raise Exception("Both x and y have to be larger than {} for function {} to work".format(threshold, func.__name__)) 11 | res = func(x, y) 12 | return res 13 | return func_wrapper 14 | return wrap 15 | 16 | @check_above(2) 17 | def average(x, y): 18 | """Calculates the average of two numbers. 19 | """ 20 | return (x + y)/2 21 | 22 | 23 | # print(help(average)) 24 | # print(average(3, 4)) 25 | # print(average(1, 2)) 26 | -------------------------------------------------------------------------------- /example_code/04_how_to_use_decorators_2/D_register.py: -------------------------------------------------------------------------------- 1 | from functools import wraps 2 | 3 | func_registry = [] 4 | 5 | def register(func): 6 | func_registry.append(func.__name__) 7 | @wraps(func) 8 | def func_wrapper(*args, **kwargs): 9 | return func(*args, **kwargs) 10 | return func_wrapper 11 | 12 | @register 13 | def average(x, y): 14 | return (x + y)/2 15 | 16 | @register 17 | def geom_average(x, y): 18 | return (x*y)**0.5 19 | 20 | -------------------------------------------------------------------------------- /example_code/04_how_to_use_decorators_2/E_methods.py: -------------------------------------------------------------------------------- 1 | from functools import wraps 2 | 3 | 4 | def check_positive(func): 5 | @wraps(func) 6 | def func_wrapper(*args): 7 | for arg in args: 8 | if type(arg) is int or type(arg) is float: 9 | if arg < 0: 10 | raise Exception("Method {} takes only positive arguments".format(func.__name__)) 11 | return func(*args) 12 | 13 | return func_wrapper 14 | 15 | 16 | class Operations: 17 | @check_positive 18 | def average(self, x, y): 19 | return (x + y)/2 20 | 21 | 22 | op = Operations() 23 | res = op.average(1, 2) 24 | print(res) -------------------------------------------------------------------------------- /example_code/04_how_to_use_decorators_2/F_classes.py: -------------------------------------------------------------------------------- 1 | class Decorator: 2 | def __init__(self, func): 3 | print('Decorating {}'.format(func.__name__)) 4 | self.func = func 5 | 6 | def __call__(self, *args, **kwargs): 7 | return self.func(*args) 8 | 9 | @Decorator 10 | def average(x, y): 11 | return (x + y) / 2 12 | 13 | res = average(1, 2) 14 | print(res) 15 | 16 | print(type(average)) -------------------------------------------------------------------------------- /example_code/04_how_to_use_decorators_2/G_decorating_classes.py: -------------------------------------------------------------------------------- 1 | def Decorate(cls): 2 | print('Decorating {}'.format(cls)) 3 | def class_wrapper(*args): 4 | print('Arguments, ', args) 5 | def average(cls, x, y): 6 | return (x + y) / 2 7 | setattr(cls, 'average', average) 8 | return cls(*args) 9 | return class_wrapper 10 | 11 | @Decorate 12 | class MyClass: 13 | def __init__(self): 14 | print('MyClass') 15 | 16 | print(type(MyClass)) 17 | # op = Operations() 18 | # print(type(op)) 19 | # print(op.average(1, 2)) -------------------------------------------------------------------------------- /example_code/10_threads_processes/A_base_class.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from time import sleep 3 | 4 | class OhmLaw: 5 | def make_measurement(self, start, stop, num_points, delay): 6 | x_axis = np.linspace(start, stop, num_points) 7 | data = [] 8 | for i in x_axis: 9 | # Acquire fake data 10 | data.append(np.random.random()) 11 | sleep(delay) 12 | 13 | return data 14 | 15 | 16 | if __name__ == "__main__": 17 | ohm = OhmLaw() 18 | result = ohm.make_measurement(0,1,11,0.01) 19 | print(result) -------------------------------------------------------------------------------- /example_code/10_threads_processes/BBB_Threads.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from time import sleep 3 | 4 | 5 | class OhmLaw: 6 | def __init__(self): 7 | self.data = np.zeros(0) # To store the data of the measurement 8 | self.step = 0 # To keep track of the step 9 | self.running = False 10 | 11 | def make_measurement(self, start, stop, num_points, delay): 12 | if self.running: 13 | raise Exception("Can't trigger two measurements at the same time") 14 | 15 | self.running = True 16 | x_axis = np.linspace(start, stop, num_points) 17 | self.data = np.zeros(num_points) 18 | self.step = 0 19 | for i in x_axis: 20 | # Acquire fake data 21 | self.data[self.step] = np.random.random() 22 | self.step += 1 23 | sleep(delay) 24 | self.running = False 25 | return self.data 26 | 27 | 28 | if __name__ == "__main__": 29 | import threading 30 | 31 | ohm = OhmLaw() 32 | 33 | meas_1 = threading.Thread(target=ohm.make_measurement, args=(0, 1, 11, 1)) 34 | meas_1.start() 35 | meas_2 = threading.Thread(target=ohm.make_measurement, args=(0, 1, 21, 1)) 36 | meas_2.start() 37 | print('Triggered measurement') 38 | i = ohm.step 39 | while meas_1.is_alive() or meas_2.is_alive(): 40 | if i != ohm.step: 41 | print('Number of points acquired: {}'.format(ohm.step - 1)) 42 | i = ohm.step 43 | sleep(2) 44 | -------------------------------------------------------------------------------- /example_code/10_threads_processes/BB_threads.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from time import sleep 3 | 4 | class OhmLaw: 5 | def __init__(self): 6 | self.data = np.zeros(0) # To store the data of the measurement 7 | self.step = 0 # To keep track of the step 8 | 9 | def make_measurement(self, start, stop, num_points, delay): 10 | x_axis = np.linspace(start, stop, num_points) 11 | self.data = np.zeros(num_points) 12 | self.step = 0 13 | for i in x_axis: 14 | # Acquire fake data 15 | self.data[self.step] = np.random.random() 16 | self.step += 1 17 | sleep(delay) 18 | 19 | return self.data 20 | 21 | 22 | if __name__ == "__main__": 23 | import threading 24 | ohm = OhmLaw() 25 | 26 | t = threading.Thread(target=ohm.make_measurement, args=(0,1,11,1)) 27 | t.start() 28 | print('Triggered measurement') 29 | i = ohm.step 30 | while t.is_alive(): 31 | if i != ohm.step: 32 | print('Number of points acquired: {}'.format(ohm.step-1)) 33 | i = ohm.step 34 | sleep(2) 35 | -------------------------------------------------------------------------------- /example_code/10_threads_processes/B_threads.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from time import sleep 3 | 4 | class OhmLaw: 5 | def make_measurement(self, start, stop, num_points, delay): 6 | x_axis = np.linspace(start, stop, num_points) 7 | data = [] 8 | for i in x_axis: 9 | # Acquire fake data 10 | data.append(np.random.random()) 11 | print(i) 12 | sleep(delay) 13 | 14 | return data 15 | 16 | 17 | if __name__ == "__main__": 18 | import threading 19 | ohm = OhmLaw() 20 | 21 | t = threading.Thread(target=ohm.make_measurement, args=(0,1,11,1)) 22 | t.start() 23 | print('Triggered measurement') 24 | i = 0 25 | while t.is_alive(): 26 | i += 1 27 | print('Acquiring {}\r'.format('.'*i), end=' ') 28 | sleep(0.5) 29 | -------------------------------------------------------------------------------- /example_code/10_threads_processes/C_stopping_thread.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from time import sleep 3 | 4 | 5 | class OhmLaw: 6 | def __init__(self): 7 | self.data = np.zeros(0) # To store the data of the measurement 8 | self.step = 0 # To keep track of the step 9 | self.running = False 10 | self.stop = False 11 | 12 | def make_measurement(self, start, stop, num_points, delay): 13 | if self.running: 14 | raise Exception("Can't trigger two measurements at the same time") 15 | 16 | x_axis = np.linspace(start, stop, num_points) 17 | self.data = np.zeros(num_points) 18 | self.step = 0 19 | self.stop = False 20 | self.running = True 21 | for i in x_axis: 22 | if self.stop: 23 | print('Stopping') 24 | break 25 | # Acquire fake data 26 | self.data[self.step] = np.random.random() 27 | self.step += 1 28 | sleep(delay) 29 | self.running = False 30 | return self.data 31 | 32 | 33 | if __name__ == "__main__": 34 | import threading 35 | 36 | ohm = OhmLaw() 37 | 38 | meas_1 = threading.Thread(target=ohm.make_measurement, args=(0, 1, 11, 1)) 39 | meas_1.start() 40 | sleep(2) 41 | print('Finishing') 42 | ohm.stop = True 43 | meas_1.join() 44 | print('Finished') -------------------------------------------------------------------------------- /example_code/10_threads_processes/DD_subclassing.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from time import sleep 3 | from threading import Thread 4 | 5 | class Worker(Thread): 6 | def __init__(self): 7 | super().__init__() 8 | self.queue = [] 9 | self.keep_running = True 10 | 11 | def add_to_queue(self, target, args=None): 12 | print('Adding to queue') 13 | self.queue.append((target, args)) 14 | 15 | def stop_thread(self): 16 | self.keep_running = False 17 | 18 | def run(self): 19 | while self.keep_running: 20 | if self.queue: 21 | func, args = self.queue.pop(0) 22 | func(*args) 23 | 24 | class OhmLaw: 25 | def __init__(self): 26 | self.data = np.zeros(0) # To store the data of the measurement 27 | self.step = 0 # To keep track of the step 28 | self.running = False 29 | self.stop = False 30 | 31 | def make_measurement(self, start, stop, num_points, delay): 32 | if self.running: 33 | raise Exception("Can't trigger two measurements at the same time") 34 | 35 | x_axis = np.linspace(start, stop, num_points) 36 | self.data = np.zeros(num_points) 37 | self.step = 0 38 | self.stop = False 39 | self.running = True 40 | for i in x_axis: 41 | if self.stop: 42 | print('Stopping') 43 | break 44 | # Acquire fake data 45 | self.data[self.step] = np.random.random() 46 | self.step += 1 47 | sleep(delay) 48 | self.running = False 49 | return self.data 50 | 51 | 52 | if __name__ == "__main__": 53 | ohm = OhmLaw() 54 | 55 | worker = Worker() 56 | worker.start() 57 | worker.add_to_queue(ohm.make_measurement, args=(0, 1, 11, .1)) 58 | worker.add_to_queue(ohm.make_measurement, args=(0, 1, 11, .1)) 59 | worker.add_to_queue(ohm.make_measurement, args=(0, 1, 11, .1)) 60 | while worker.queue: 61 | print('Queue length: {}'.format(len(worker.queue))) 62 | sleep(1) 63 | worker.stop_thread() 64 | worker.join() 65 | print('Finishing') 66 | -------------------------------------------------------------------------------- /example_code/10_threads_processes/D_subclassing.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from time import sleep 3 | from threading import Thread 4 | 5 | class Worker(Thread): 6 | def __init__(self, target, args=None): 7 | super().__init__() 8 | self.target = target 9 | self.args = args 10 | 11 | def run(self): 12 | self.target(*self.args) 13 | 14 | class OhmLaw: 15 | def __init__(self): 16 | self.data = np.zeros(0) # To store the data of the measurement 17 | self.step = 0 # To keep track of the step 18 | self.running = False 19 | self.stop = False 20 | 21 | def make_measurement(self, start, stop, num_points, delay): 22 | if self.running: 23 | raise Exception("Can't trigger two measurements at the same time") 24 | 25 | x_axis = np.linspace(start, stop, num_points) 26 | self.data = np.zeros(num_points) 27 | self.step = 0 28 | self.stop = False 29 | self.running = True 30 | for i in x_axis: 31 | if self.stop: 32 | print('Stopping') 33 | break 34 | # Acquire fake data 35 | self.data[self.step] = np.random.random() 36 | self.step += 1 37 | sleep(delay) 38 | self.running = False 39 | return self.data 40 | 41 | 42 | if __name__ == "__main__": 43 | import threading 44 | 45 | ohm = OhmLaw() 46 | 47 | meas_1 = Worker(target=ohm.make_measurement, args=(0, 1, 11, 1)) 48 | meas_1.start() 49 | sleep(2) 50 | print('Finishing') 51 | ohm.stop = True 52 | meas_1.join() 53 | print('Finished') -------------------------------------------------------------------------------- /example_code/10_threads_processes/E_locks.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from time import sleep 3 | from threading import Thread, Lock 4 | 5 | lock = Lock() 6 | 7 | class Worker(Thread): 8 | def __init__(self, target, args=None): 9 | super().__init__() 10 | self.target = target 11 | self.args = args 12 | 13 | def run(self): 14 | lock.acquire() 15 | self.target(*self.args) 16 | lock.release() 17 | 18 | class OhmLaw: 19 | def __init__(self): 20 | self.data = np.zeros(0) # To store the data of the measurement 21 | self.step = 0 # To keep track of the step 22 | self.running = False 23 | self.stop = False 24 | 25 | def make_measurement(self, start, stop, num_points, delay): 26 | if self.running: 27 | raise Exception("Can't trigger two measurements at the same time") 28 | 29 | x_axis = np.linspace(start, stop, num_points) 30 | self.data = np.zeros(num_points) 31 | self.step = 0 32 | self.stop = False 33 | self.running = True 34 | for i in x_axis: 35 | if self.stop: 36 | print('Stopping') 37 | break 38 | # Acquire fake data 39 | self.data[self.step] = np.random.random() 40 | self.step += 1 41 | sleep(delay) 42 | self.running = False 43 | return self.data 44 | 45 | 46 | if __name__ == "__main__": 47 | import threading 48 | 49 | ohm = OhmLaw() 50 | 51 | meas_1 = Worker(target=ohm.make_measurement, args=(0, 1, 11, 1)) 52 | meas_1.start() 53 | meas_2 = Worker(target=ohm.make_measurement, args=(0, 1, 11, 1)) 54 | meas_2.start() 55 | i = ohm.step 56 | while meas_1.is_alive() or meas_2.is_alive(): 57 | if i != ohm.step: 58 | print('Number of points acquired: {}'.format(ohm.step - 1)) 59 | i = ohm.step 60 | sleep(2) 61 | 62 | print('Finishing') 63 | -------------------------------------------------------------------------------- /example_code/10_threads_processes/F_limits.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | class TestRand: 5 | def calculate_random(self, number_points): 6 | if number_points<=10: 7 | number_points = 10 8 | 9 | for i in range(10, number_points): 10 | data = np.random.random(i) 11 | fft = np.fft.fft(data) 12 | return fft 13 | 14 | if __name__ == "__main__": 15 | from time import time 16 | from threading import Thread 17 | 18 | t = TestRand() 19 | # t0 = time() 20 | # d = calculate_random(5000) 21 | # print('Total time: {:2.2f} seconds'.format(time() - t0)) 22 | 23 | t0 = time() 24 | t1 = Thread(target=t.calculate_random, args=(5000,)) 25 | t2 = Thread(target=t.calculate_random, args=(5000,)) 26 | t3 = Thread(target=t.calculate_random, args=(5000,)) 27 | t1.start() 28 | t2.start() 29 | t3.start() 30 | t1.join() 31 | t2.join() 32 | t3.join() 33 | print('Total time: {:2.2f} seconds'.format(time()-t0)) -------------------------------------------------------------------------------- /example_code/10_threads_processes/G_multiprocessing.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | def calculate_random(number_points): 5 | if number_points<=10: 6 | number_points = 10 7 | 8 | for i in range(10, number_points): 9 | data = np.random.random(i) 10 | fft = np.fft.fft(data) 11 | return fft 12 | 13 | if __name__ == "__main__": 14 | from time import time 15 | from multiprocessing import Process, Pool 16 | 17 | # t0 = time() 18 | # d = calculate_random(5000) 19 | # print('Total time: {:2.2f} seconds'.format(time() - t0)) 20 | 21 | t0 = time() 22 | t1 = Process(target=calculate_random, args=(5000,)) 23 | t2 = Process(target=calculate_random, args=(5000,)) 24 | t3 = Process(target=calculate_random, args=(5000,)) 25 | t1.start() 26 | t2.start() 27 | t3.start() 28 | t1.join() 29 | t2.join() 30 | t3.join() 31 | print('Total time: {:2.2f} seconds'.format(time()-t0)) 32 | 33 | t0 = time() 34 | with Pool(4) as p: 35 | print(p.map(calculate_random, [5000, 5000, 5000, 5000 ])) 36 | print('Total time: {:2.2f} seconds'.format(time() - t0)) -------------------------------------------------------------------------------- /example_code/10_threads_processes/H_queues.py: -------------------------------------------------------------------------------- 1 | from multiprocessing import Process, Queue 2 | import random 3 | from time import sleep 4 | 5 | def move_from_in_to_out(q_in, q_out): 6 | while not q_in.empty(): 7 | data = q_in.get() 8 | q_out.put(data) 9 | sleep(random.uniform(0,.01)) 10 | if data is None: 11 | break 12 | 13 | def print_len_queue(q_in, q_out): 14 | while not q_in.empty() or not q_out.empty(): 15 | space = int(q_in.qsize() / (q_in.qsize() + q_out.qsize()) * 50) 16 | output = str(q_in.qsize())+ '||' + space * ' '+ '|' + (50-space) * ' ' + '||' + str(q_out.qsize()) + '\r' 17 | print(output, end=' ') 18 | 19 | q_in = Queue() 20 | q_out = Queue() 21 | 22 | for i in range(50): 23 | q_in.put(i) 24 | q_out.put(i) 25 | 26 | p = Process(target=move_from_in_to_out, args=(q_in, q_out)) 27 | p2 = Process(target=move_from_in_to_out, args=(q_out, q_in)) 28 | p3 = Process(target=print_len_queue, args=(q_in, q_out)) 29 | p3.start() 30 | p2.start() 31 | p.start() 32 | p.join() 33 | p2.join() 34 | p3.join() -------------------------------------------------------------------------------- /example_code/11_documenting/docs/source/conf.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | sys.path.insert(0, os.path.abspath('../..')) 4 | sys.path.insert(0, os.path.abspath('.')) 5 | 6 | project = 'My Module' 7 | copyright = '2018, Aquiles Carattino' 8 | author = 'Aquiles Carattino' 9 | version = '' 10 | release = '0.1' 11 | templates_path = ['_templates'] 12 | source_suffix = '.rst' 13 | master_doc = 'index' 14 | pygments_style = 'sphinx' 15 | html_theme = 'alabaster' 16 | html_static_path = ['_static'] 17 | extensions = [ 18 | 'sphinx.ext.autodoc', 19 | 'sphinx.ext.doctest',] -------------------------------------------------------------------------------- /example_code/11_documenting/docs/source/factorial.rst: -------------------------------------------------------------------------------- 1 | How to calculate the factorial 2 | ============================== 3 | The factorial is a mathematical operation that calculates the product of all the numbers up to the specified integer. 4 | 5 | For example, the factorial of 5 would be 1*2*3*4*5 = 120. With our code we can do the following:: 6 | 7 | >>> from my_module.factorial import factorial 8 | >>> factorial(5) 9 | 120 10 | 11 | .. automodule:: my_module.factorial 12 | 13 | The function Factorial 14 | ====================== 15 | The function factorial is also well documented. 16 | 17 | .. autofunction:: my_module.factorial.factorial 18 | -------------------------------------------------------------------------------- /example_code/11_documenting/docs/source/index.rst: -------------------------------------------------------------------------------- 1 | Welcome to My Module's documentation! 2 | ===================================== 3 | This is going to become the future documentation of My Project 4 | 5 | .. toctree:: 6 | :maxdepth: 2 7 | :caption: Contents: 8 | 9 | factorial 10 | people -------------------------------------------------------------------------------- /example_code/11_documenting/docs/source/people.rst: -------------------------------------------------------------------------------- 1 | .. automodule:: my_module.people 2 | :members: 3 | 4 | .. toctree:: 5 | :maxdepth: 2 6 | :caption: Contents: 7 | 8 | teacher -------------------------------------------------------------------------------- /example_code/11_documenting/docs/source/teacher.rst: -------------------------------------------------------------------------------- 1 | Teacher Class 2 | ============= 3 | 4 | .. autoclass:: my_module.people.Teacher -------------------------------------------------------------------------------- /example_code/11_documenting/my_module/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/11_documenting/my_module/__init__.py -------------------------------------------------------------------------------- /example_code/11_documenting/my_module/factorial.py: -------------------------------------------------------------------------------- 1 | """ 2 | Module factorial 3 | ================ 4 | This module supplies one function, factorial() to calculate the factorial of an integer. 5 | You can imported like this: 6 | 7 | >>> from my_module.factorial import factorial 8 | """ 9 | import math 10 | 11 | 12 | def factorial(n): 13 | """Function to calculate the factorial of a number. 14 | First import, and then use, for example: 15 | 16 | 17 | >>> factorial(5) 18 | 120 19 | >>> factorial(-1) 20 | Traceback (most recent call last): 21 | ... 22 | ValueError: n must be >= 0 23 | 24 | :param n: Number to calculate the factorial 25 | :type n: int 26 | :return: The calculated factorial 27 | :rtype: int 28 | """ 29 | 30 | if not n >= 0: 31 | raise ValueError("n must be >= 0") 32 | if math.floor(n) != n: 33 | raise ValueError("n must be exact integer") 34 | if n + 1 == n: # catch a value like 1e300 35 | raise OverflowError("n too large") 36 | result = 1 37 | factor = 2 38 | while factor <= n: 39 | result *= factor 40 | factor += 1 41 | return result -------------------------------------------------------------------------------- /example_code/11_documenting/my_module/people.py: -------------------------------------------------------------------------------- 1 | """ 2 | Module People 3 | ============= 4 | Defines two classes, Person and Teacher. 5 | You define a person by supplying a name, for example: 6 | 7 | >>> from my_module.people import Person, Teacher 8 | >>> me = Person('My Name') 9 | >>> print(me.name) 10 | My Name 11 | >>> you = Teacher('Your Name', 'Math') 12 | >>> print(you.name) 13 | Your Name 14 | >>> print(you.course) 15 | Math 16 | """ 17 | class Person: 18 | """Class to store a general person information. For example the name.""" 19 | def __init__(self, name): 20 | """Create a person object by providing a name""" 21 | self.name = name 22 | 23 | 24 | class Teacher(Person): 25 | """Class to store a teacher's information. It subclasses :class:`Person`. 26 | You can create a teacher like this: 27 | """ 28 | def __init__(self, name, course): 29 | """Create a teacher object by providing a name and the course it teaches.""" 30 | super().__init__(name) 31 | self.course = course 32 | 33 | def get_course(self): 34 | """Get the course that the teacher teaches.""" 35 | return self.course 36 | 37 | def set_course(self, new_course): 38 | """Set the course that the teacher teaches""" 39 | self.course = new_course -------------------------------------------------------------------------------- /example_code/12_exceptions/A_exeptions.py: -------------------------------------------------------------------------------- 1 | f = open('my_file.dat') 2 | data = f.readfile() 3 | print('Loaded data') -------------------------------------------------------------------------------- /example_code/12_exceptions/B_exceptions.py: -------------------------------------------------------------------------------- 1 | try: 2 | f = open('my_file.dat') 3 | f.readfile() 4 | print('Loaded data') 5 | except: 6 | print('Data not loaded') 7 | 8 | f = open('my_data.dat') 9 | f.readfile() 10 | print('Loaded data') -------------------------------------------------------------------------------- /example_code/12_exceptions/C_exceptions.py: -------------------------------------------------------------------------------- 1 | try: 2 | file = open('my_data.dat') 3 | data = file.readfile() 4 | print('Data Loaded') 5 | except Exception as e: 6 | print(e) 7 | 8 | -------------------------------------------------------------------------------- /example_code/12_exceptions/D_exceptions.py: -------------------------------------------------------------------------------- 1 | try: 2 | file = open('my_file.dat') 3 | data = file.readfile() 4 | print('Data Loaded') 5 | except FileNotFoundError: 6 | file = open('my_file.dat', 'w') 7 | print('File created') 8 | file.close() -------------------------------------------------------------------------------- /example_code/12_exceptions/E_exceptions.py: -------------------------------------------------------------------------------- 1 | filename = 'my_data.dat' 2 | 3 | try: 4 | file = open(filename) 5 | data = file.readfile() 6 | except FileNotFoundError: 7 | file = open(filename, 'w') 8 | raise -------------------------------------------------------------------------------- /example_code/12_exceptions/F_exceptions.py: -------------------------------------------------------------------------------- 1 | filename = 'my_data.dat' 2 | 3 | try: 4 | file = open(filename) 5 | data = file.readfile() 6 | except FileNotFoundError: 7 | file = open(filename, 'w') 8 | print('Created file') 9 | except AttributeError: 10 | print('Attribute Error') 11 | -------------------------------------------------------------------------------- /example_code/12_exceptions/G_exceptions.py: -------------------------------------------------------------------------------- 1 | filename = 'my_data.dat' 2 | 3 | try: 4 | file = open(filename) 5 | data = file.read() 6 | important_data = data[0] 7 | except FileNotFoundError: 8 | file = open(filename, 'w') 9 | print('Created file') 10 | except AttributeError: 11 | print('Attribute Error') 12 | except Exception: 13 | print('Unhandled exception') -------------------------------------------------------------------------------- /example_code/12_exceptions/H_exceptions.py: -------------------------------------------------------------------------------- 1 | filename = 'my_data.dat' 2 | 3 | try: 4 | file = open(filename) 5 | data = file.read() 6 | important_data = data[0] 7 | except Exception as e: 8 | print('Unhandled exception') 9 | print(e) -------------------------------------------------------------------------------- /example_code/12_exceptions/I_exceptions.py: -------------------------------------------------------------------------------- 1 | filename = 'my_datas.dat' 2 | 3 | try: 4 | file = open(filename) 5 | data = file.read() 6 | important_data = data[0] 7 | except Exception as e: 8 | if isinstance(e, IndexError): 9 | print(e) 10 | data = 'Information' 11 | important_data = data[0] 12 | else: 13 | print('Unhandled exception') 14 | 15 | print(important_data) -------------------------------------------------------------------------------- /example_code/12_exceptions/JJ_exceptions.py: -------------------------------------------------------------------------------- 1 | filename = 'my_data.dat' 2 | 3 | try: 4 | print('In the try block') 5 | file = open(filename) 6 | data = file.read() 7 | important_data = data[0] 8 | except FileNotFoundError: 9 | print('File not found, creating one') 10 | file = open(filename, 'w') 11 | finally: 12 | print('Finally, closing the file') 13 | file.close() 14 | important_data = 'A' 15 | 16 | print(important_data) -------------------------------------------------------------------------------- /example_code/12_exceptions/J_exceptions.py: -------------------------------------------------------------------------------- 1 | filename = 'my_data.dat' 2 | 3 | try: 4 | file = open(filename) 5 | data = file.read() 6 | important_data = data[0] 7 | except Exception as e: 8 | if isinstance(e, IndexError): 9 | print(e) 10 | data = 'Information' 11 | important_data = data[0] 12 | else: 13 | print('Unhandled exception') 14 | finally: 15 | important_data = 'A' 16 | 17 | print(important_data) -------------------------------------------------------------------------------- /example_code/12_exceptions/K_exceptions.py: -------------------------------------------------------------------------------- 1 | def average(x, y): 2 | if x <= 0 or y <= 0: 3 | raise Exception('Both x and y should be positive') 4 | return (x + y) / 2 5 | 6 | print(average(1, 2)) 7 | print(average(2, -1)) -------------------------------------------------------------------------------- /example_code/12_exceptions/L_exceptions.py: -------------------------------------------------------------------------------- 1 | class NonPositiveError(Exception): 2 | pass 3 | 4 | def average(x, y): 5 | if x <= 0 or y <= 0: 6 | raise NonPositiveError('Both x and y should be positive') 7 | return (x + y) / 2 8 | 9 | print(average(1, 2)) 10 | print(average(2, -1)) -------------------------------------------------------------------------------- /example_code/12_exceptions/M_warning.py: -------------------------------------------------------------------------------- 1 | import warnings 2 | 3 | warnings.warn('Warning', category=UserWarning) 4 | 5 | -------------------------------------------------------------------------------- /example_code/12_exceptions/N_custom_exceptions.py: -------------------------------------------------------------------------------- 1 | class MyException(BaseException): 2 | pass 3 | 4 | class NonPositiveIntegerError(MyException): 5 | pass 6 | 7 | class TooBigIntegerError(MyException): 8 | pass 9 | 10 | def average(x, y): 11 | if x<=0 or y<=0: 12 | raise NonPositiveIntegerError('Either x or y is not positive') 13 | 14 | if x>=10 or y>=10: 15 | raise TooBigIntegerError('Either x or y is too large') 16 | return (x+y)/2 17 | 18 | try: 19 | average(1, -1) 20 | except MyException as e: 21 | print(e) 22 | 23 | try: 24 | average(11, 1) 25 | except MyException as e: 26 | print(e) 27 | 28 | try: 29 | average('a', 'b') 30 | except MyException as e: 31 | print(e) 32 | # print(dir(e)) 33 | 34 | print('Done') -------------------------------------------------------------------------------- /example_code/12_exceptions/O_exceptions.py: -------------------------------------------------------------------------------- 1 | class MyException(BaseException): 2 | pass 3 | 4 | class NonPositiveIntegerError(MyException): 5 | def __init__(self, x, y): 6 | super(NonPositiveIntegerError, self).__init__() 7 | if x<=0 and y<=0: 8 | self.msg = 'Both x and y are negative: x={}, y={}'.format(x, y) 9 | elif x<=0: 10 | self.msg = 'Only x is negative: x={}'.format(x) 11 | elif y<=0: 12 | self.msg = 'Only y is negative: y={}'.format(y) 13 | 14 | def __str__(self): 15 | msg = self.msg 16 | return msg 17 | 18 | 19 | def average(x, y): 20 | if x<=0 or y<=0: 21 | raise NonPositiveIntegerError(x, y) 22 | return (x+y)/2 23 | 24 | try: 25 | average(1, -1) 26 | except MyException as e: 27 | print(e) 28 | -------------------------------------------------------------------------------- /example_code/12_exceptions/P_traceback.py: -------------------------------------------------------------------------------- 1 | import traceback 2 | 3 | 4 | filename = 'my_datas.dat' 5 | 6 | try: 7 | file = open(filename) 8 | data = file.read() 9 | except FileNotFoundError: 10 | traceback.print_exc() -------------------------------------------------------------------------------- /example_code/12_exceptions/my_data.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/12_exceptions/my_data.dat -------------------------------------------------------------------------------- /example_code/13_storing_data/AA_plain_text_two_columns.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | x = np.linspace(0, 1, 201) 4 | y = np.random.random(201) 5 | 6 | data = np.column_stack((x, y)) 7 | 8 | np.savetxt('AA_data.dat', data) -------------------------------------------------------------------------------- /example_code/13_storing_data/AB_plain_text_header.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | x = np.linspace(0, 1, 201) 4 | y = np.random.random(201) 5 | 6 | data = np.column_stack((x, y)) 7 | header = "X-Column, Y-Column\n" 8 | header += "This is a second line" 9 | np.savetxt('AB_data.dat', data, header=header) -------------------------------------------------------------------------------- /example_code/13_storing_data/AC_plain_text_reading.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | data = np.loadtxt('AB_data.dat') 4 | x = data[:, 0] 5 | y = data[:, 1] 6 | -------------------------------------------------------------------------------- /example_code/13_storing_data/AD_plain_text_incremental.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from time import sleep 3 | 4 | x = np.linspace(0, 1, 201) 5 | y = np.random.random(201) 6 | 7 | 8 | header = "X-Column, Y-Column\n" 9 | header += "This is a second line" 10 | f = open('AD_data.dat', 'wb') 11 | np.savetxt(f, [], header=header) 12 | for i in range(201): 13 | data = np.column_stack((x[i], y[i])) 14 | np.savetxt(f, data) 15 | f.flush() 16 | sleep(0.1) 17 | 18 | f.close() -------------------------------------------------------------------------------- /example_code/13_storing_data/AE_plain_text_with.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from time import sleep 3 | 4 | x = np.linspace(0, 1, 201) 5 | y = np.random.random(201) 6 | 7 | 8 | header = "X-Column, Y-Column\n" 9 | header += "This is a second line" 10 | with open('AE_data.dat', 'wb') as f: 11 | np.savetxt(f, [], header=header) 12 | for i in range(201): 13 | data = np.column_stack((x[i], y[i])) 14 | np.savetxt(f, data) 15 | f.flush() 16 | -------------------------------------------------------------------------------- /example_code/13_storing_data/A_plain_text.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | data = np.linspace(0, 1, 201) 4 | 5 | np.savetxt('A_data.dat', data) -------------------------------------------------------------------------------- /example_code/13_storing_data/BA_data.dat: -------------------------------------------------------------------------------- 1 | # This is the header -------------------------------------------------------------------------------- /example_code/13_storing_data/BA_no_numpy.py: -------------------------------------------------------------------------------- 1 | f = open('BA_data.dat', 'w') 2 | f.write('# This is the header') 3 | f.close() -------------------------------------------------------------------------------- /example_code/13_storing_data/BB_data.dat: -------------------------------------------------------------------------------- 1 | # This is the header 2 | 0.0 3 | 0.005 4 | 0.01 5 | 0.015 6 | 0.02 7 | 0.025 8 | 0.03 9 | 0.035 10 | 0.04 11 | 0.045 12 | 0.05 13 | 0.055 14 | 0.06 15 | 0.065 16 | 0.07 17 | 0.075 18 | 0.08 19 | 0.085 20 | 0.09 21 | 0.095 22 | 0.1 23 | 0.105 24 | 0.11 25 | 0.115 26 | 0.12 27 | 0.125 28 | 0.13 29 | 0.135 30 | 0.14 31 | 0.145 32 | 0.15 33 | 0.155 34 | 0.16 35 | 0.165 36 | 0.17 37 | 0.17500000000000002 38 | 0.18 39 | 0.185 40 | 0.19 41 | 0.195 42 | 0.2 43 | 0.20500000000000002 44 | 0.21 45 | 0.215 46 | 0.22 47 | 0.225 48 | 0.23 49 | 0.23500000000000001 50 | 0.24 51 | 0.245 52 | 0.25 53 | 0.255 54 | 0.26 55 | 0.265 56 | 0.27 57 | 0.275 58 | 0.28 59 | 0.28500000000000003 60 | 0.29 61 | 0.295 62 | 0.3 63 | 0.305 64 | 0.31 65 | 0.315 66 | 0.32 67 | 0.325 68 | 0.33 69 | 0.335 70 | 0.34 71 | 0.34500000000000003 72 | 0.35000000000000003 73 | 0.355 74 | 0.36 75 | 0.365 76 | 0.37 77 | 0.375 78 | 0.38 79 | 0.385 80 | 0.39 81 | 0.395 82 | 0.4 83 | 0.405 84 | 0.41000000000000003 85 | 0.41500000000000004 86 | 0.42 87 | 0.425 88 | 0.43 89 | 0.435 90 | 0.44 91 | 0.445 92 | 0.45 93 | 0.455 94 | 0.46 95 | 0.465 96 | 0.47000000000000003 97 | 0.47500000000000003 98 | 0.48 99 | 0.485 100 | 0.49 101 | 0.495 102 | 0.5 103 | 0.505 104 | 0.51 105 | 0.515 106 | 0.52 107 | 0.525 108 | 0.53 109 | 0.535 110 | 0.54 111 | 0.545 112 | 0.55 113 | 0.555 114 | 0.56 115 | 0.5650000000000001 116 | 0.5700000000000001 117 | 0.5750000000000001 118 | 0.58 119 | 0.585 120 | 0.59 121 | 0.595 122 | 0.6 123 | 0.605 124 | 0.61 125 | 0.615 126 | 0.62 127 | 0.625 128 | 0.63 129 | 0.635 130 | 0.64 131 | 0.645 132 | 0.65 133 | 0.655 134 | 0.66 135 | 0.665 136 | 0.67 137 | 0.675 138 | 0.68 139 | 0.685 140 | 0.6900000000000001 141 | 0.6950000000000001 142 | 0.7000000000000001 143 | 0.705 144 | 0.71 145 | 0.715 146 | 0.72 147 | 0.725 148 | 0.73 149 | 0.735 150 | 0.74 151 | 0.745 152 | 0.75 153 | 0.755 154 | 0.76 155 | 0.765 156 | 0.77 157 | 0.775 158 | 0.78 159 | 0.785 160 | 0.79 161 | 0.795 162 | 0.8 163 | 0.805 164 | 0.81 165 | 0.8150000000000001 166 | 0.8200000000000001 167 | 0.8250000000000001 168 | 0.8300000000000001 169 | 0.835 170 | 0.84 171 | 0.845 172 | 0.85 173 | 0.855 174 | 0.86 175 | 0.865 176 | 0.87 177 | 0.875 178 | 0.88 179 | 0.885 180 | 0.89 181 | 0.895 182 | 0.9 183 | 0.905 184 | 0.91 185 | 0.915 186 | 0.92 187 | 0.925 188 | 0.93 189 | 0.935 190 | 0.9400000000000001 191 | 0.9450000000000001 192 | 0.9500000000000001 193 | 0.9550000000000001 194 | 0.96 195 | 0.965 196 | 0.97 197 | 0.975 198 | 0.98 199 | 0.985 200 | 0.99 201 | 0.995 202 | 1.0 203 | -------------------------------------------------------------------------------- /example_code/13_storing_data/BB_no_numpy.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | x = np.linspace(0,1,201) 4 | with open('BB_data.dat', 'w') as f: 5 | f.write('# This is the header\n') 6 | for data in x: 7 | f.write(str(data)+'\n') -------------------------------------------------------------------------------- /example_code/13_storing_data/BC_data.dat: -------------------------------------------------------------------------------- 1 | # This is the header 2 | 0.0 3 | 0.5 4 | 1.0 5 | 1.5 6 | 2.0 7 | 2.5 8 | 3.0 9 | 3.5 10 | 4.0 11 | 4.5 12 | 5.0 13 | 5.5 14 | 6.0 15 | 6.5 16 | 7.0 17 | 7.5 18 | 8.0 19 | 8.5 20 | 9.0 21 | 9.5 22 | 10.0 23 | 10.5 24 | 11.0 25 | 11.5 26 | 12.0 27 | 12.5 28 | 13.0 29 | 13.5 30 | 14.0 31 | 14.5 32 | 15.0 33 | 15.5 34 | 16.0 35 | 16.5 36 | 17.0 37 | 17.5 38 | 18.0 39 | 18.5 40 | 19.0 41 | 19.5 42 | 20.0 43 | 20.5 44 | 21.0 45 | 21.5 46 | 22.0 47 | 22.5 48 | 23.0 49 | 23.5 50 | 24.0 51 | 24.5 52 | 25.0 53 | 25.5 54 | 26.0 55 | 26.5 56 | 27.0 57 | 27.5 58 | 28.0 59 | 28.5 60 | 29.0 61 | 29.5 62 | 30.0 63 | 30.5 64 | 31.0 65 | 31.5 66 | 32.0 67 | 32.5 68 | 33.0 69 | 33.5 70 | 34.0 71 | 34.5 72 | 35.0 73 | 35.5 74 | 36.0 75 | 36.5 76 | 37.0 77 | 37.5 78 | 38.0 79 | 38.5 80 | 39.0 81 | 39.5 82 | 40.0 83 | 40.5 84 | 41.0 85 | 41.5 86 | 42.0 87 | 42.5 88 | 43.0 89 | 43.5 90 | 44.0 91 | 44.5 92 | 45.0 93 | 45.5 94 | 46.0 95 | 46.5 96 | 47.0 97 | 47.5 98 | 48.0 99 | 48.5 100 | 49.0 101 | 49.5 102 | 50.0 103 | 50.5 104 | 51.0 105 | 51.5 106 | 52.0 107 | 52.5 108 | 53.0 109 | 53.5 110 | 54.0 111 | 54.5 112 | 55.0 113 | 55.5 114 | 56.0 115 | 56.5 116 | 57.0 117 | 57.5 118 | 58.0 119 | 58.5 120 | 59.0 121 | 59.5 122 | 60.0 123 | 60.5 124 | 61.0 125 | 61.5 126 | 62.0 127 | 62.5 128 | 63.0 129 | 63.5 130 | 64.0 131 | 64.5 132 | 65.0 133 | 65.5 134 | 66.0 135 | 66.5 136 | 67.0 137 | 67.5 138 | 68.0 139 | 68.5 140 | 69.0 141 | 69.5 142 | 70.0 143 | 70.5 144 | 71.0 145 | 71.5 146 | 72.0 147 | 72.5 148 | 73.0 149 | 73.5 150 | 74.0 151 | 74.5 152 | 75.0 153 | 75.5 154 | 76.0 155 | 76.5 156 | 77.0 157 | 77.5 158 | 78.0 159 | 78.5 160 | 79.0 161 | 79.5 162 | 80.0 163 | 80.5 164 | 81.0 165 | 81.5 166 | 82.0 167 | 82.5 168 | 83.0 169 | 83.5 170 | 84.0 171 | 84.5 172 | 85.0 173 | 85.5 174 | 86.0 175 | 86.5 176 | 87.0 177 | 87.5 178 | 88.0 179 | 88.5 180 | 89.0 181 | 89.5 182 | 90.0 183 | 90.5 184 | 91.0 185 | 91.5 186 | 92.0 187 | 92.5 188 | 93.0 189 | 93.5 190 | 94.0 191 | 94.5 192 | 95.0 193 | 95.5 194 | 96.0 195 | 96.5 196 | 97.0 197 | 97.5 198 | 98.0 199 | 98.5 200 | 99.0 201 | 99.5 202 | 100.0 203 | -------------------------------------------------------------------------------- /example_code/13_storing_data/BC_formatting.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | x = np.linspace(0,100,201) 4 | with open('BC_data.dat', 'w') as f: 5 | f.write('# This is the header\n') 6 | for data in x: 7 | f.write('{:4.1f}\n'.format(data)) -------------------------------------------------------------------------------- /example_code/13_storing_data/BD_two_columns.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | x = np.linspace(0,100,201) 4 | y = np.random.random(201) 5 | 6 | with open('BD_data.dat', 'w') as f: 7 | f.write('# This is the header\n') 8 | for i in range(len(x)): 9 | f.write('{:4.1f}\t{:.4f}\n'.format(x[i], y[i])) -------------------------------------------------------------------------------- /example_code/13_storing_data/CA_reading_back.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | data = np.loadtxt('BD_data.dat') 4 | print(data) -------------------------------------------------------------------------------- /example_code/13_storing_data/CB_reading_back.py: -------------------------------------------------------------------------------- 1 | with open('BD_data.dat', 'r') as f: 2 | data = f.read() 3 | 4 | print(data) -------------------------------------------------------------------------------- /example_code/13_storing_data/CC_reading_back.py: -------------------------------------------------------------------------------- 1 | with open('BD_data.dat', 'r') as f: 2 | line = f.readline() 3 | header = [] 4 | data = [] 5 | while line: 6 | if line.startswith('#'): 7 | header.append(line) 8 | else: 9 | data.append(line) 10 | line = f.readline() 11 | 12 | print(header) 13 | print(data) -------------------------------------------------------------------------------- /example_code/13_storing_data/CD_reading_back.py: -------------------------------------------------------------------------------- 1 | with open('BD_data.dat', 'r') as f: 2 | line = f.readline() 3 | header = [] 4 | x = [] 5 | y = [] 6 | while line: 7 | if line.startswith('#'): 8 | header.append(line.strip()) 9 | else: 10 | data = line.split('\t') 11 | x.append(float(data[0])) 12 | y.append(float(data[1])) 13 | line = f.readline() 14 | 15 | print(header) 16 | print(x) 17 | print(y) -------------------------------------------------------------------------------- /example_code/13_storing_data/DA_data.dat: -------------------------------------------------------------------------------- 1 | Real Iris setosa 2 | Fake Iris versicolor 3 | Fake Iris versicolor 4 | Fake Iris versicolor 5 | Fake Iris virginica 6 | Real Iris setosa 7 | Fake Iris setosa 8 | Real Iris versicolor 9 | Fake Iris virginica 10 | Fake Iris setosa 11 | Real Iris versicolor 12 | Fake Iris virginica 13 | Fake Iris versicolor 14 | Fake Iris virginica 15 | Fake Iris virginica 16 | Fake Iris setosa 17 | Real Iris versicolor 18 | Real Iris virginica 19 | Real Iris setosa 20 | Fake Iris setosa 21 | -------------------------------------------------------------------------------- /example_code/13_storing_data/DA_non_numeric.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | observations = ['Real', 'Fake'] 4 | flowers = ['Iris setosa', 'Iris virginica', 'Iris versicolor'] 5 | 6 | with open('DA_data.dat', 'w') as f: 7 | for _ in range(20): 8 | observation = random.choice(observations) 9 | flower = random.choice(flowers) 10 | f.write('{} {}\n'.format(observation, flower)) 11 | -------------------------------------------------------------------------------- /example_code/13_storing_data/DB_data.csv: -------------------------------------------------------------------------------- 1 | Fake,Iris versicolor,0.740,0.538,0.088,0.103 2 | Fake,Iris setosa,0.191,0.182,0.743,0.685 3 | Fake,Iris setosa,0.870,0.226,0.144,0.831 4 | Real,Iris setosa,0.708,0.193,0.446,0.778 5 | Fake,Iris setosa,0.470,0.677,0.180,0.675 6 | Real,Iris virginica,0.145,0.516,0.756,0.367 7 | Fake,Iris versicolor,0.889,0.190,0.568,0.801 8 | Real,Iris virginica,0.072,0.259,0.283,0.044 9 | Fake,Iris virginica,0.740,0.652,0.498,0.236 10 | Fake,Iris setosa,0.117,0.209,0.136,0.673 11 | Fake,Iris versicolor,0.263,0.777,0.819,0.519 12 | Real,Iris virginica,0.007,0.860,0.412,0.874 13 | Real,Iris setosa,0.074,0.368,0.696,0.889 14 | Real,Iris setosa,0.189,0.588,0.103,0.218 15 | Fake,Iris versicolor,0.202,0.597,0.238,0.533 16 | Real,Iris versicolor,0.352,0.175,0.386,0.540 17 | Fake,Iris versicolor,0.707,0.962,0.734,0.031 18 | Fake,Iris versicolor,0.012,0.914,0.475,0.020 19 | Fake,Iris virginica,0.243,0.371,0.087,0.754 20 | Real,Iris setosa,0.091,0.206,0.487,0.416 21 | -------------------------------------------------------------------------------- /example_code/13_storing_data/DB_data.dat: -------------------------------------------------------------------------------- 1 | Fake Iris versicolor 0.625 0.542 0.918 0.602 2 | Fake Iris versicolor 0.119 0.870 0.851 0.639 3 | Fake Iris versicolor 0.941 0.976 0.332 0.253 4 | Fake Iris versicolor 0.515 0.227 0.463 0.743 5 | Real Iris virginica 0.992 0.327 0.317 0.051 6 | Real Iris versicolor 0.143 0.699 0.637 0.114 7 | Real Iris setosa 0.755 0.253 0.048 0.159 8 | Real Iris versicolor 0.386 0.327 0.152 0.454 9 | Fake Iris versicolor 0.600 0.855 0.921 0.061 10 | Real Iris setosa 0.985 0.663 0.848 0.008 11 | Fake Iris virginica 0.170 0.754 0.788 0.136 12 | Real Iris versicolor 0.127 0.915 0.475 0.680 13 | Real Iris setosa 0.641 0.625 0.984 0.392 14 | Fake Iris virginica 0.769 0.956 0.846 0.183 15 | Real Iris virginica 0.553 0.392 0.246 0.095 16 | Real Iris versicolor 0.490 0.811 0.927 0.184 17 | Fake Iris versicolor 0.672 0.129 0.799 0.373 18 | Real Iris setosa 0.250 0.968 0.452 0.026 19 | Real Iris setosa 0.322 0.351 0.133 0.165 20 | Fake Iris virginica 0.761 0.662 0.052 0.672 21 | -------------------------------------------------------------------------------- /example_code/13_storing_data/DB_num_and_str.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | observations = ['Real', 'Fake'] 4 | flowers = ['Iris setosa', 'Iris virginica', 'Iris versicolor'] 5 | 6 | with open('DB_data.csv', 'w') as f: 7 | for _ in range(20): 8 | observation = random.choice(observations) 9 | flower = random.choice(flowers) 10 | sepal_width = random.random() 11 | sepal_length = random.random() 12 | petal_width = random.random() 13 | petal_length = random.random() 14 | 15 | f.write('{},{},{:.3f},{:.3f},{:.3f},{:.3f}\n'.format( 16 | observation, 17 | flower, 18 | sepal_length, 19 | sepal_width, 20 | petal_length, 21 | petal_width)) 22 | -------------------------------------------------------------------------------- /example_code/13_storing_data/DC_reading_non_num.py: -------------------------------------------------------------------------------- 1 | with open('DB_data.dat', 'r') as f: 2 | line = f.readline() 3 | data = [] 4 | while line: 5 | data.append(line.split(' ')) 6 | line = f.readline() 7 | print(data) -------------------------------------------------------------------------------- /example_code/13_storing_data/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/13_storing_data/__init__.py -------------------------------------------------------------------------------- /example_code/14_storing_data/AA_comparison.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import numpy as np 3 | 4 | x = np.linspace(0, 255, 256, dtype=np.uint8) 5 | 6 | with open('AA_data.dat', 'w') as f: 7 | for data in x: 8 | f.write(str(data)+'\n') 9 | 10 | print(sys.getsizeof(x)) 11 | 12 | print(type(x[0])) -------------------------------------------------------------------------------- /example_code/14_storing_data/AA_data.dat: -------------------------------------------------------------------------------- 1 | 0 2 | 1 3 | 2 4 | 3 5 | 4 6 | 5 7 | 6 8 | 7 9 | 8 10 | 9 11 | 10 12 | 11 13 | 12 14 | 13 15 | 14 16 | 15 17 | 16 18 | 17 19 | 18 20 | 19 21 | 20 22 | 21 23 | 22 24 | 23 25 | 24 26 | 25 27 | 26 28 | 27 29 | 28 30 | 29 31 | 30 32 | 31 33 | 32 34 | 33 35 | 34 36 | 35 37 | 36 38 | 37 39 | 38 40 | 39 41 | 40 42 | 41 43 | 42 44 | 43 45 | 44 46 | 45 47 | 46 48 | 47 49 | 48 50 | 49 51 | 50 52 | 51 53 | 52 54 | 53 55 | 54 56 | 55 57 | 56 58 | 57 59 | 58 60 | 59 61 | 60 62 | 61 63 | 62 64 | 63 65 | 64 66 | 65 67 | 66 68 | 67 69 | 68 70 | 69 71 | 70 72 | 71 73 | 72 74 | 73 75 | 74 76 | 75 77 | 76 78 | 77 79 | 78 80 | 79 81 | 80 82 | 81 83 | 82 84 | 83 85 | 84 86 | 85 87 | 86 88 | 87 89 | 88 90 | 89 91 | 90 92 | 91 93 | 92 94 | 93 95 | 94 96 | 95 97 | 96 98 | 97 99 | 98 100 | 99 101 | 100 102 | 101 103 | 102 104 | 103 105 | 104 106 | 105 107 | 106 108 | 107 109 | 108 110 | 109 111 | 110 112 | 111 113 | 112 114 | 113 115 | 114 116 | 115 117 | 116 118 | 117 119 | 118 120 | 119 121 | 120 122 | 121 123 | 122 124 | 123 125 | 124 126 | 125 127 | 126 128 | 127 129 | 128 130 | 129 131 | 130 132 | 131 133 | 132 134 | 133 135 | 134 136 | 135 137 | 136 138 | 137 139 | 138 140 | 139 141 | 140 142 | 141 143 | 142 144 | 143 145 | 144 146 | 145 147 | 146 148 | 147 149 | 148 150 | 149 151 | 150 152 | 151 153 | 152 154 | 153 155 | 154 156 | 155 157 | 156 158 | 157 159 | 158 160 | 159 161 | 160 162 | 161 163 | 162 164 | 163 165 | 164 166 | 165 167 | 166 168 | 167 169 | 168 170 | 169 171 | 170 172 | 171 173 | 172 174 | 173 175 | 174 176 | 175 177 | 176 178 | 177 179 | 178 180 | 179 181 | 180 182 | 181 183 | 182 184 | 183 185 | 184 186 | 185 187 | 186 188 | 187 189 | 188 190 | 189 191 | 190 192 | 191 193 | 192 194 | 193 195 | 194 196 | 195 197 | 196 198 | 197 199 | 198 200 | 199 201 | 200 202 | 201 203 | 202 204 | 203 205 | 204 206 | 205 207 | 206 208 | 207 209 | 208 210 | 209 211 | 210 212 | 211 213 | 212 214 | 213 215 | 214 216 | 215 217 | 216 218 | 217 219 | 218 220 | 219 221 | 220 222 | 221 223 | 222 224 | 223 225 | 224 226 | 225 227 | 226 228 | 227 229 | 228 230 | 229 231 | 230 232 | 231 233 | 232 234 | 233 235 | 234 236 | 235 237 | 236 238 | 237 239 | 238 240 | 239 241 | 240 242 | 241 243 | 242 244 | 243 245 | 244 246 | 245 247 | 246 248 | 247 249 | 248 250 | 249 251 | 250 252 | 251 253 | 252 254 | 253 255 | 254 256 | 255 257 | -------------------------------------------------------------------------------- /example_code/14_storing_data/AB_unicode.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/14_storing_data/AB_unicode.dat -------------------------------------------------------------------------------- /example_code/14_storing_data/AB_unicode.py: -------------------------------------------------------------------------------- 1 | import codecs 2 | 3 | data_to_save = 'Data to Save' 4 | with codecs.open('AB_unicode.dat', 'w', 'utf-32') as f: 5 | f.write(data_to_save) -------------------------------------------------------------------------------- /example_code/14_storing_data/AC_binary.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | a = np.linspace(0, 1000, 1024, dtype=np.uint8) 5 | 6 | np.save('AC_binay', a) 7 | 8 | with open('AC_ascii.dat', 'w') as f: 9 | for i in a: 10 | f.write(str(i)+'\n') -------------------------------------------------------------------------------- /example_code/14_storing_data/AD_numpy_binary.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | a = np.ones((1024), dtype=np.uint32) 5 | 6 | np.save('AD_binay', a) 7 | 8 | with open('AD_ascii.dat', 'w') as f: 9 | for i in a: 10 | f.write(str(i)+'\n') -------------------------------------------------------------------------------- /example_code/14_storing_data/AE_numpy_binary.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | a = np.linspace(0,65535,65535, dtype=np.uint16) 5 | 6 | np.save('AE_binay', a) 7 | 8 | with open('AE_ascii.dat', 'w') as f: 9 | for i in a: 10 | f.write(str(i)+'\n') -------------------------------------------------------------------------------- /example_code/14_storing_data/AF_custom.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/14_storing_data/AF_custom.dat -------------------------------------------------------------------------------- /example_code/14_storing_data/AF_custom_binary.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/14_storing_data/AF_custom_binary.dat -------------------------------------------------------------------------------- /example_code/14_storing_data/AF_custom_binary.py: -------------------------------------------------------------------------------- 1 | import pickle 2 | 3 | data = [1, 1.2, 'a', 'b'] 4 | 5 | with open('AF_custom.dat', 'wb') as f: 6 | pickle.dump(data, f) 7 | 8 | with open('AF_custom.dat', 'rb') as f: 9 | new_data = pickle.load(f) 10 | 11 | print(new_data) -------------------------------------------------------------------------------- /example_code/14_storing_data/AF_custom_binary2.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/14_storing_data/AF_custom_binary2.dat -------------------------------------------------------------------------------- /example_code/14_storing_data/AG_pickle.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/14_storing_data/AG_pickle.dat -------------------------------------------------------------------------------- /example_code/14_storing_data/AG_pickle_numpy.py: -------------------------------------------------------------------------------- 1 | # import numpy as np 2 | import pickle 3 | 4 | # 5 | # data = np.linspace(0, 1023, 1000, dtype=np.uint8) 6 | # 7 | # np.save('AG_numpy', data) 8 | # 9 | # with open('AG_pickle.dat', 'wb') as f: 10 | # pickle.dump(data, f) 11 | # 12 | 13 | with open('AG_pickle.dat', 'rb') as f: 14 | new_data = pickle.load(f) 15 | 16 | print(new_data) -------------------------------------------------------------------------------- /example_code/14_storing_data/AH_pickle_function.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/14_storing_data/AH_pickle_function.dat -------------------------------------------------------------------------------- /example_code/14_storing_data/AH_pickle_function.py: -------------------------------------------------------------------------------- 1 | import pickle 2 | 3 | 4 | def my_function(var): 5 | new_str = '='*len(var) 6 | print(new_str+'\n'+var+'\n'+new_str) 7 | 8 | my_function('Testing') 9 | 10 | with open('AH_pickle_function.dat', 'wb') as f: 11 | pickle.dump(my_function, f) 12 | 13 | with open('AH_pickle_function.dat', 'rb') as f: 14 | new_function = pickle.load(f) 15 | 16 | new_function('New Test') -------------------------------------------------------------------------------- /example_code/14_storing_data/AII_load_object.py: -------------------------------------------------------------------------------- 1 | import pickle 2 | from AI_pickle_object import MyClass 3 | 4 | 5 | with open('AI_pickle_object.dat', 'rb') as f: 6 | new_class = pickle.load(f) 7 | 8 | print(new_class) -------------------------------------------------------------------------------- /example_code/14_storing_data/AI_pickle_object.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/14_storing_data/AI_pickle_object.dat -------------------------------------------------------------------------------- /example_code/14_storing_data/AI_pickle_object.py: -------------------------------------------------------------------------------- 1 | import pickle 2 | from time import time 3 | from datetime import datetime 4 | 5 | class MyClass: 6 | def __init__(self): 7 | self.init_time = time() 8 | 9 | def __str__(self): 10 | dt = datetime.fromtimestamp(self.init_time) 11 | return 'MyClass created at {:%H:%M:%S on %m-%d-%Y}'.\ 12 | format(dt) 13 | 14 | if __name__ == '__main__': 15 | my_class = MyClass() 16 | print(my_class) 17 | 18 | with open('AI_pickle_object.dat', 'wb') as f: 19 | pickle.dump(my_class, f) 20 | # 21 | # with open('AI_pickle_object.dat', 'rb') as f: 22 | # new_class = pickle.load(f) 23 | # 24 | # print(new_class) -------------------------------------------------------------------------------- /example_code/14_storing_data/AJ_pickle_exploit.py: -------------------------------------------------------------------------------- 1 | import os 2 | import pickle 3 | from time import time 4 | from datetime import datetime 5 | 6 | class MyClass: 7 | def __init__(self): 8 | self.init_time = time() 9 | 10 | def __str__(self): 11 | dt = datetime.fromtimestamp(self.init_time) 12 | return 'MyClass created at {:%H:%M:%S on %m-%d-%Y}'.\ 13 | format(dt) 14 | 15 | def __reduce__(self): 16 | return (os.system, ('ls',)) 17 | 18 | if __name__ == '__main__': 19 | my_class = MyClass() 20 | print(my_class) 21 | 22 | with open('AI_pickle_object.dat', 'wb') as f: 23 | pickle.dump(my_class, f) -------------------------------------------------------------------------------- /example_code/14_storing_data/AK_json.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/14_storing_data/AK_json.dat -------------------------------------------------------------------------------- /example_code/14_storing_data/AK_json.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | 4 | data = { 5 | 'first': [0, 1, 2, 3], 6 | 'second': 'A sample string' 7 | } 8 | 9 | data = [1, 2, data] 10 | 11 | with open('AK_json.dat', 'w') as f: 12 | json.dump(data, f) 13 | 14 | 15 | with open('AK_json.dat', 'r') as f: 16 | new_data = json.load(f) 17 | 18 | print(new_data) -------------------------------------------------------------------------------- /example_code/14_storing_data/ALL_read_numpy.py: -------------------------------------------------------------------------------- 1 | import pickle 2 | import base64 3 | import json 4 | 5 | with open('AL_json_numpy.dat', 'r') as f: 6 | data = json.load(f) 7 | 8 | 9 | array_bytes = base64.b64decode(data['array']) 10 | 11 | np_array = pickle.loads(array_bytes) 12 | print(data['time']) 13 | print(np_array) 14 | print(type(np_array)) -------------------------------------------------------------------------------- /example_code/14_storing_data/AL_json_numpy.py: -------------------------------------------------------------------------------- 1 | import pickle 2 | import json 3 | import numpy as np 4 | import time 5 | import base64 6 | 7 | np_array = np.ones((1000, 2), dtype=np.uint8) 8 | 9 | array_bytes = pickle.dumps(np_array) 10 | 11 | data = { 12 | 'array': base64.b64encode(array_bytes).decode('ascii'), 13 | 'time': time.time(), 14 | } 15 | 16 | with open('AL_json_numpy.dat', 'w') as f: 17 | json.dump(data, f) -------------------------------------------------------------------------------- /example_code/14_storing_data/AM_data.yml: -------------------------------------------------------------------------------- 1 | creation_date: 1533291680.31815 2 | values: [1, 2, 3, 4, 5] 3 | -------------------------------------------------------------------------------- /example_code/14_storing_data/AM_example.yml: -------------------------------------------------------------------------------- 1 | data: 2 | creation_date: 2018-08-08 3 | values: [1, 2, 3, 4] -------------------------------------------------------------------------------- /example_code/14_storing_data/AM_read_yml.py: -------------------------------------------------------------------------------- 1 | import yaml 2 | 3 | with open('AM_example.yml', 'r') as f: 4 | data = yaml.load(f) 5 | 6 | print(data) -------------------------------------------------------------------------------- /example_code/14_storing_data/AM_write.py: -------------------------------------------------------------------------------- 1 | import yaml 2 | from time import time 3 | 4 | data = { 5 | 'values': [1, 2, 3, 4, 5], 6 | 'creation_date': time(), 7 | } 8 | 9 | with open('AM_data.yml', 'w') as f: 10 | yaml.dump(data, f) -------------------------------------------------------------------------------- /example_code/15_databases/AA_create_db.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | conn = sqlite3.connect('AA_db.sqlite') 4 | conn.close() -------------------------------------------------------------------------------- /example_code/15_databases/AB_create_table.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | conn = sqlite3.connect('AA_db.sqlite') 4 | cur = conn.cursor() 5 | cur.execute('CREATE TABLE experiments (name VARCHAR, description VARCHAR)') 6 | conn.commit() 7 | 8 | conn.close() -------------------------------------------------------------------------------- /example_code/15_databases/AC_add_data.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | conn = sqlite3.connect('AA_db.sqlite') 4 | cur = conn.cursor() 5 | 6 | cur.execute('INSERT INTO experiments (name, description) values ("Aquiles", "My experiment description")') 7 | conn.commit() 8 | 9 | cur.execute('INSERT INTO experiments (name, description) VALUES (?, ?)', 10 | ('Another User', 'Another Experiment')) 11 | conn.commit() 12 | 13 | conn.close() -------------------------------------------------------------------------------- /example_code/15_databases/AD_retrieve_data.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | conn = sqlite3.connect('AA_db.sqlite') 4 | cur = conn.cursor() 5 | cur.execute('SELECT * FROM experiments') 6 | data = cur.fetchall() 7 | 8 | cur.execute('SELECT * FROM experiments') 9 | data_2 = cur.fetchone() 10 | 11 | cur.execute('SELECT * FROM experiments WHERE name="Aquiles"') 12 | data_3 = cur.fetchall() 13 | conn.close() 14 | 15 | print(data) 16 | print(data_2) 17 | print(data_3) 18 | 19 | -------------------------------------------------------------------------------- /example_code/15_databases/AE_create_primary_key.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | conn = sqlite3.connect('AA_db.sqlite') 4 | cur = conn.cursor() 5 | sql_command = """DROP TABLE IF EXISTS experiments; 6 | CREATE TABLE experiments ( 7 | id INTEGER, 8 | name STRING, 9 | description STRING, 10 | PRIMARY KEY (id)); 11 | INSERT INTO experiments (name, description) values ("Aquiles", "My experiment description"); 12 | INSERT INTO experiments (name, description) values ("Aquiles 2", "My experiment description 2"); 13 | """ 14 | 15 | cur.executescript(sql_command) 16 | conn.commit() 17 | cur.execute('SELECT * FROM experiments WHERE id=1') 18 | data = cur.fetchone() 19 | conn.close() 20 | 21 | print(data) 22 | -------------------------------------------------------------------------------- /example_code/15_databases/AF_default_date.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | conn = sqlite3.connect('AF_db.sqlite') 4 | cur = conn.cursor() 5 | sql_command = """DROP TABLE IF EXISTS experiments; 6 | CREATE TABLE experiments ( 7 | id INTEGER, 8 | name VARCHAR(20) DEFAULT "Aquiles", 9 | description VARCHAR , 10 | perfomed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, 11 | PRIMARY KEY (id)); 12 | INSERT INTO experiments (description) values ("My experiment description"); 13 | INSERT INTO experiments (name, description) values ("Aquiles 2", "My experiment description 2"); 14 | """ 15 | 16 | cur.executescript(sql_command) 17 | conn.commit() 18 | cur.execute('SELECT * FROM experiments WHERE id=1') 19 | data = cur.fetchone() 20 | conn.close() 21 | 22 | print(data) -------------------------------------------------------------------------------- /example_code/15_databases/AG_limit_fields.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | conn = sqlite3.connect('AG_db.sqlite') 4 | cur = conn.cursor() 5 | sql_command = """DROP TABLE IF EXISTS experiments; 6 | CREATE TABLE experiments ( 7 | id INTEGER, 8 | name VARCHAR DEFAULT "Aquiles", 9 | description VARCHAR , 10 | perfomed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, 11 | value INTEGER DEFAULT 0, 12 | PRIMARY KEY (id)); 13 | INSERT INTO experiments (description) values ("My experiment description"); 14 | INSERT INTO experiments (name, description) values ("Aquiles Very Long Name", "My experiment description 2"); 15 | INSERT INTO experiments (name, description, value) values ("Aquiles Very Long Name", "My experiment description 2", 1000); 16 | """ 17 | 18 | cur.executescript(sql_command) 19 | conn.commit() 20 | cur.execute('SELECT * FROM experiments') 21 | data = cur.fetchall() 22 | conn.close() 23 | 24 | for d in data: 25 | print(d) 26 | -------------------------------------------------------------------------------- /example_code/15_databases/AH_foreign_key.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | conn = sqlite3.connect('AH_db.sqlite') 4 | cur = conn.cursor() 5 | sql_command = """DROP TABLE IF EXISTS experiments; 6 | DROP TABLE IF EXISTS users; 7 | CREATE TABLE users( 8 | id INTEGER, 9 | name VARCHAR, 10 | email VARCHAR, 11 | phone VARCHAR, 12 | created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, 13 | PRIMARY KEY (id)); 14 | CREATE TABLE experiments ( 15 | id INTEGER, 16 | user_id INTEGER NOT NULL , 17 | description VARCHAR , 18 | perfomed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, 19 | PRIMARY KEY (id) 20 | FOREIGN KEY (user_id) REFERENCES users(id)); 21 | INSERT INTO users (name, email, phone) values ("Aquiles", "example@example.com", "123456789"); 22 | INSERT INTO users (name, email, phone) values ("Joseph", "joseph@example.com", "12345678"); 23 | INSERT INTO experiments (user_id, description) values (1, "My experiment description"); 24 | INSERT INTO experiments (user_id, description) values (2, "My experiment description 2"); 25 | """ 26 | 27 | cur.execute("PRAGMA foreign_keys = ON;") 28 | cur.executescript(sql_command) 29 | conn.commit() 30 | cur.execute('SELECT * FROM experiments') 31 | data = cur.fetchall() 32 | cur.execute('SELECT * FROM users') 33 | users = cur.fetchall() 34 | conn.close() 35 | print(30*'*' + 'Experiments' + 30*'*') 36 | for d in data: 37 | print(d) 38 | print(30*'*' + 'Users' + 30*'*') 39 | for u in users: 40 | print(u) -------------------------------------------------------------------------------- /example_code/15_databases/AI_numpy.py: -------------------------------------------------------------------------------- 1 | """https://stackoverflow.com/a/18622264/4467480""" 2 | 3 | import sqlite3 4 | import numpy as np 5 | import io 6 | 7 | def adapt_array(arr): 8 | out = io.BytesIO() 9 | np.save(out, arr) 10 | out.seek(0) 11 | return sqlite3.Binary(out.read()) 12 | 13 | def convert_array(text): 14 | out = io.BytesIO(text) 15 | out.seek(0) 16 | return np.load(out) 17 | 18 | sqlite3.register_adapter(np.ndarray, adapt_array) 19 | sqlite3.register_converter("array", convert_array) 20 | 21 | 22 | conn = sqlite3.connect('AI_db.sqlite', detect_types=sqlite3.PARSE_DECLTYPES) 23 | cur = conn.cursor() 24 | sql_command = """DROP TABLE IF EXISTS measurements; 25 | CREATE TABLE measurements ( 26 | id INTEGER PRIMARY KEY, 27 | description VARCHAR , 28 | arr array); 29 | """ 30 | cur.executescript(sql_command) 31 | conn.commit() 32 | 33 | 34 | 35 | x = np.random.rand(10,2) 36 | 37 | cur.execute('INSERT INTO measurements (arr) values (?)', (x,)) 38 | 39 | cur.execute('SELECT arr FROM measurements') 40 | data = cur.fetchone() 41 | conn.close() 42 | print(data) -------------------------------------------------------------------------------- /example_code/15_databases/AJ_join.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | conn = sqlite3.connect('AH_db.sqlite') 4 | cur = conn.cursor() 5 | 6 | sql_command = """ 7 | SELECT users.id, users.name, experiments.description 8 | FROM experiments 9 | INNER JOIN users ON experiments.user_id=users.id 10 | WHERE users.name="Aquiles"; 11 | """ 12 | cur.execute(sql_command) 13 | data = cur.fetchall() 14 | 15 | for d in data: 16 | print(d) 17 | -------------------------------------------------------------------------------- /example_code/15_databases/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/15_databases/__init__.py -------------------------------------------------------------------------------- /example_code/16_context_managers/AA_save_list.dat: -------------------------------------------------------------------------------- 1 | First line 2 | Second Line 3 | -------------------------------------------------------------------------------- /example_code/16_context_managers/AA_save_list.py: -------------------------------------------------------------------------------- 1 | from time import sleep 2 | 3 | file = open('My_File.txt', 'w') 4 | file.write('This is the first line\n') 5 | 6 | sleep(600) 7 | file.close() 8 | 9 | -------------------------------------------------------------------------------- /example_code/16_context_managers/AB_save_with.py: -------------------------------------------------------------------------------- 1 | f = open('my_file.txt', 'w') 2 | try: 3 | f.write('This is the first line\n') 4 | raise Exception('This is an exception') 5 | except Exception as e: 6 | pass 7 | f.close() 8 | raise e -------------------------------------------------------------------------------- /example_code/16_context_managers/AC_custom_class.py: -------------------------------------------------------------------------------- 1 | class SimpleClass: 2 | def simple_method(self): 3 | print('Simple Method') 4 | 5 | def finalize(self): 6 | print('Finalizing the Class') 7 | 8 | def __exit__(self, exc_type, exc_val, exc_tb): 9 | self.finalize() 10 | print(exc_type) 11 | print(exc_val) 12 | print(exc_tb) 13 | 14 | def __enter__(self): 15 | return self 16 | 17 | with SimpleClass() as sc: 18 | sc.simple_method() 19 | # raise Exception('This is an Exception') 20 | 21 | sc.simple_method() 22 | 23 | 24 | with open('test', 'w') as f: 25 | f.write('test') 26 | 27 | f.write('test') -------------------------------------------------------------------------------- /example_code/16_context_managers/AD_constructor.py: -------------------------------------------------------------------------------- 1 | class SimpleClass: 2 | def __init__(self): 3 | print('Init') 4 | 5 | def simple_method(self): 6 | print('Simple Method') 7 | 8 | def finalize(self): 9 | print('Finalizing the Class') 10 | 11 | def __exit__(self, exc_type, exc_val, exc_tb): 12 | print('Exit') 13 | self.finalize() 14 | 15 | def __enter__(self): 16 | print('enter') 17 | return self 18 | 19 | with SimpleClass() as sc: 20 | sc.simple_method() 21 | -------------------------------------------------------------------------------- /example_code/16_context_managers/AE_metaclass.py: -------------------------------------------------------------------------------- 1 | class PluginBase: 2 | subclasses = [] 3 | 4 | def __init_subclass__(cls, **kwargs): 5 | super().__init_subclass__(**kwargs) 6 | cls.subclasses.append(cls) 7 | 8 | 9 | class MyPlugin(PluginBase): 10 | pass 11 | 12 | 13 | print(PluginBase.subclasses) -------------------------------------------------------------------------------- /example_code/16_context_managers/My_File_With.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/16_context_managers/My_File_With.txt -------------------------------------------------------------------------------- /example_code/16_context_managers/save_thread.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/16_context_managers/save_thread.txt -------------------------------------------------------------------------------- /example_code/16_context_managers/test: -------------------------------------------------------------------------------- 1 | test -------------------------------------------------------------------------------- /example_code/17_mutable_immutable/AA_default_arguments.py: -------------------------------------------------------------------------------- 1 | def increase_values(var1=[1, 1], value=1): 2 | var1[0] += value 3 | var1[1] += value 4 | return var1 5 | 6 | print(increase_values()) 7 | print(increase_values()) 8 | 9 | var2 = [1, 2] 10 | var3 = increase_values(var2, 2) 11 | print(var3) 12 | print(var2) 13 | 14 | print(id(var2)) 15 | print(id(var3)) -------------------------------------------------------------------------------- /example_code/17_mutable_immutable/AB_default_arguments.py: -------------------------------------------------------------------------------- 1 | def increase_values(var1=[1, 1], value=0): 2 | value += 1 3 | var1[0] += value 4 | var1[1] += value 5 | return var1 6 | 7 | print(increase_values()) 8 | print(increase_values()) 9 | 10 | # var2 = [1, 2] 11 | # var3 = increase_values(var2) 12 | # print(var2) 13 | # print(var3) 14 | # 15 | # var2 = (1, 2) 16 | # var3 = increase_values(var2) 17 | # print(var2) 18 | # print(var3) -------------------------------------------------------------------------------- /example_code/17_mutable_immutable/AC_mutable_arguments.py: -------------------------------------------------------------------------------- 1 | def divide_and_average(var1): 2 | var = var1 3 | for i in range(len(var)): 4 | var[i] /= 2 5 | avg = sum(var)/len(var) 6 | return avg 7 | 8 | my_list = [1, 2, 3] 9 | print(divide_and_average(my_list)) 10 | print(my_list) 11 | 12 | import copy 13 | 14 | def divide_and_average(var1): 15 | var = copy.copy(var1) 16 | for i in range(len(var)): 17 | var[i] /= 2 18 | avg = sum(var)/len(var) 19 | return avg 20 | 21 | my_list = [1, 2, 3] 22 | print(divide_and_average(my_list)) 23 | print(my_list) -------------------------------------------------------------------------------- /example_code/17_mutable_immutable/AD_object_comparison.py: -------------------------------------------------------------------------------- 1 | class MyClass: 2 | def __init__(self): 3 | self.var = 1 4 | 5 | def __eq__(self, other): 6 | return True 7 | 8 | 9 | my_obj = MyClass() 10 | if my_obj == None: 11 | print('My object == None') 12 | 13 | if my_obj is None: 14 | print('My Object is None') -------------------------------------------------------------------------------- /example_code/17_mutable_immutable/AE_custom_objects.py: -------------------------------------------------------------------------------- 1 | class MyImmutable: 2 | def __init__(self, var1, var2): 3 | super().__setattr__('var1', var1) 4 | super().__setattr__('var2', var2) 5 | 6 | def __setattr__(self, key, value): 7 | raise TypeError('MyImmutable cannot be modified after instantiation') 8 | 9 | def __str__(self): 10 | return 'MyImmutable var1: {}, var2: {}'.format(self.var1, self.var2) 11 | 12 | my_immutable = MyImmutable(1, 2) 13 | print(my_immutable) 14 | my_immutable.var1 = 2 -------------------------------------------------------------------------------- /example_code/18_mutable_tuples/AA_tuples_dicts.py: -------------------------------------------------------------------------------- 1 | var1 = (1, 2) 2 | var2 = (4, 5) 3 | 4 | var3 = {var1: 'First Var', 5 | var2: 'Second Var'} 6 | 7 | print(var3.keys()) 8 | print(var3[1, 2]) 9 | 10 | var4 = (1, [1, 2]) 11 | var5 = {var4: 'Fourth Var', 12 | var2: 'Fifth Var'} -------------------------------------------------------------------------------- /example_code/19_hashable_objects/AA_hashable_objects.py: -------------------------------------------------------------------------------- 1 | class MyClass: 2 | def __init__(self, var): 3 | self.var = var 4 | 5 | def __hash__(self): 6 | return int(self.var) 7 | 8 | def __str__(self): 9 | return 'MyClass' 10 | 11 | def __repr__(self): 12 | return 'MyClass {}'.format(self.var) 13 | 14 | def __eq__(self, other): 15 | return other.var == self.var 16 | 17 | my_obj = MyClass(1) 18 | print(my_obj.__hash__()) 19 | my_new_obj = MyClass(1) 20 | print(my_new_obj.__hash__()) 21 | 22 | print(my_new_obj == my_obj) 23 | 24 | 25 | var = {my_obj: 'my_obj'} 26 | var[my_new_obj] = 'my_obj_2' 27 | print(var) 28 | 29 | print(my_obj == 1) -------------------------------------------------------------------------------- /example_code/19_hashable_objects/AB_hashable_objects_dicts.py: -------------------------------------------------------------------------------- 1 | class MyClass: 2 | def __init__(self, var): 3 | self.var = var 4 | 5 | def __hash__(self): 6 | return int(self.var) 7 | 8 | def __str__(self): 9 | return 'MyClass' 10 | 11 | def __repr__(self): 12 | return 'MyClass {}'.format(self.var) 13 | 14 | def __eq__(self, other): 15 | return True 16 | 17 | my_obj = MyClass(1) 18 | var = MyClass(2) 19 | print(var == my_obj) 20 | var2 = {my_obj: 'my_obj'} 21 | var2[var] = 'var' 22 | print(var2) -------------------------------------------------------------------------------- /example_code/20_deep_shallow_copies/AA_custom_objects.py: -------------------------------------------------------------------------------- 1 | class MyClass: 2 | def __init__(self, x, y): 3 | self.x = x 4 | self.y = y 5 | 6 | 7 | 8 | my_class = MyClass([1, 2], [3, 4]) 9 | my_new_class = my_class 10 | 11 | print(id(my_class)) 12 | print(id(my_new_class)) 13 | 14 | my_class.x[0] = 0 15 | print(my_new_class.x) 16 | 17 | -------------------------------------------------------------------------------- /example_code/20_deep_shallow_copies/AB_custom_objects.py: -------------------------------------------------------------------------------- 1 | import copy 2 | 3 | class MyClass: 4 | def __init__(self, x, y): 5 | self.x = x 6 | self.y = y 7 | 8 | 9 | 10 | my_class = MyClass([1, 2], [3, 4]) 11 | my_new_class = copy.copy(my_class) 12 | 13 | print(id(my_class)) 14 | print(id(my_new_class)) 15 | 16 | my_class.x[0] = 0 17 | print(my_new_class.x) -------------------------------------------------------------------------------- /example_code/20_deep_shallow_copies/AC_custom_copy.py: -------------------------------------------------------------------------------- 1 | import copy 2 | 3 | class MyClass: 4 | def __init__(self, x, y): 5 | self.x = x 6 | self.y = y 7 | self.other = [1, 2, 3] 8 | 9 | def __copy__(self): 10 | new_instance = MyClass(self.x, self.y) 11 | new_instance.__dict__.update(self.__dict__) 12 | new_instance.other = copy.deepcopy(self.other) 13 | return new_instance 14 | 15 | my_class = MyClass([1, 2], [3, 4]) 16 | my_new_class = copy.copy(my_class) 17 | 18 | print(id(my_class)) 19 | print(id(my_new_class)) 20 | 21 | my_class.x[0] = 0 22 | my_class.y[0] = 0 23 | my_class.other[0] = 0 24 | print(my_new_class.x) 25 | print(my_new_class.y) 26 | print(my_new_class.other) 27 | 28 | print(my_new_class.__dict__) 29 | my_new_class.__dict__['y'][0] = 20 30 | print(my_new_class.y) -------------------------------------------------------------------------------- /example_code/20_deep_shallow_copies/AD_custom_deep_copy.py: -------------------------------------------------------------------------------- 1 | import copy 2 | 3 | class MyClass: 4 | def __init__(self, x, y): 5 | self.x = x 6 | self.y = y 7 | self.other = [1, 2, 3] 8 | 9 | def __deepcopy__(self, memodict={}): 10 | new_instance = MyClass(self.x, self.y) 11 | new_instance.__dict__.update(self.__dict__) 12 | new_instance.x = copy.deepcopy(self.x, memodict) 13 | new_instance.y = copy.deepcopy(self.y, memodict) 14 | return new_instance 15 | 16 | my_class = MyClass([1, 2], [3, 4]) 17 | my_new_class = copy.deepcopy(my_class) 18 | 19 | print(id(my_class)) 20 | print(id(my_new_class)) 21 | 22 | my_class.x[0] = 0 23 | my_class.y[0] = 0 24 | my_class.other[0] = 0 25 | print(my_new_class.x) 26 | print(my_new_class.y) 27 | print(my_new_class.other) -------------------------------------------------------------------------------- /example_code/20_deep_shallow_copies/AE_copying_functions.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/20_deep_shallow_copies/AE_copying_functions.py -------------------------------------------------------------------------------- /example_code/21_Classes_Mutables/AA_defaults.py: -------------------------------------------------------------------------------- 1 | class MyClass: 2 | def __init__(self, var=[]): 3 | self.var = var 4 | 5 | def append(self, value): 6 | self.var.append(value) 7 | 8 | def __str__(self): 9 | return str(self.var) 10 | 11 | my_class = MyClass() 12 | print(my_class) 13 | my_class.append(1) 14 | print(my_class) 15 | my_class_2 = MyClass() 16 | print(my_class_2) 17 | 18 | my_class_2.append(2) 19 | print(my_class) 20 | 21 | print(id(my_class.var)) 22 | print(id(my_class_2.var)) 23 | 24 | print(id(my_class)) 25 | print(id(my_class_2)) 26 | 27 | my_list = [1, 2, 3] 28 | my_class = MyClass(my_list) 29 | my_class.append(4) 30 | print(my_list) -------------------------------------------------------------------------------- /example_code/21_Classes_Mutables/AB_defaults.py: -------------------------------------------------------------------------------- 1 | class MyClass: 2 | var = [] 3 | 4 | def append(self, value): 5 | self.var.append(value) 6 | 7 | def __str__(self): 8 | return str(self.var) 9 | 10 | my_class = MyClass() 11 | print(my_class) 12 | my_class.append(1) 13 | print(my_class) 14 | my_class_2 = MyClass() 15 | print(my_class_2) 16 | MyClass.var.append(2) 17 | print(my_class) 18 | print(my_class_2) 19 | 20 | my_class_2.var += [3] 21 | 22 | print(my_class) 23 | print(my_class_2) 24 | -------------------------------------------------------------------------------- /example_code/21_Classes_Mutables/AC_class_attributes.py: -------------------------------------------------------------------------------- 1 | class MyClass: 2 | var = 1 3 | 4 | def increase(self): 5 | self.var += 1 6 | 7 | def __str__(self): 8 | return str(self.var) 9 | 10 | my_class = MyClass() 11 | print(my_class) 12 | my_class_2 = MyClass() 13 | print(my_class_2) 14 | print(id(my_class_2.var)) 15 | print(id(my_class.var)) 16 | print(id(MyClass.var)) 17 | MyClass.var += 1 18 | print(my_class) 19 | print(my_class_2) 20 | print(id(my_class_2.var)) 21 | print(id(my_class.var)) 22 | print(id(MyClass.var)) 23 | 24 | my_class.var += 1 25 | print(id(my_class_2.var)) 26 | print(id(my_class.var)) 27 | print(id(MyClass.var)) 28 | 29 | my_class_2.var = 0 30 | print(my_class_2) 31 | print(my_class) 32 | 33 | my_class = MyClass() 34 | my_class_2 = MyClass() 35 | print(my_class) 36 | my_class.var += 1 37 | print(my_class) 38 | print(my_class_2) -------------------------------------------------------------------------------- /example_code/22_Step_By_Step_Qt/AA_test_qt.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtWidgets import QApplication, QMainWindow 2 | 3 | app = QApplication([]) 4 | win = QMainWindow() 5 | win.show() 6 | app.exit(app.exec_()) -------------------------------------------------------------------------------- /example_code/22_Step_By_Step_Qt/AB_openCV_1.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | 4 | 5 | cap = cv2.VideoCapture(0) 6 | ret, frame = cap.read() 7 | cap.release() 8 | 9 | print(np.min(frame)) 10 | print(np.max(frame)) -------------------------------------------------------------------------------- /example_code/22_Step_By_Step_Qt/AC_video.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import cv2 3 | 4 | cap = cv2.VideoCapture(0) 5 | cap.set(cv2.CAP_PROP_BRIGHTNESS, 0.5) 6 | 7 | while(True): 8 | # Capture frame-by-frame 9 | ret, frame = cap.read() 10 | 11 | # Our operations on the frame come here 12 | gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 13 | 14 | # Display the resulting frame 15 | cv2.imshow('frame',gray) 16 | if cv2.waitKey(1) & 0xFF == ord('q'): 17 | break 18 | 19 | # When everything done, release the capture 20 | cap.release() 21 | cv2.destroyAllWindows() 22 | -------------------------------------------------------------------------------- /example_code/22_Step_By_Step_Qt/AD_simple_qt.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtWidgets import QApplication, QMainWindow 2 | 3 | app = QApplication([]) 4 | win = QMainWindow() 5 | win.show() 6 | app.exit(app.exec_()) -------------------------------------------------------------------------------- /example_code/22_Step_By_Step_Qt/AE_qt_button.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton 2 | 3 | def button_pressed(): 4 | print('Button Pressed') 5 | 6 | app = QApplication([]) 7 | win = QMainWindow() 8 | button = QPushButton('&Test') 9 | button.clicked.connect(button_pressed) 10 | win.setCentralWidget(button) 11 | win.show() 12 | app.exit(app.exec_()) -------------------------------------------------------------------------------- /example_code/22_Step_By_Step_Qt/AF_qt_two_buttons.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtWidgets import QApplication, QMainWindow, \ 2 | QPushButton, QWidget 3 | 4 | def button_pressed(): 5 | print('Button Pressed') 6 | 7 | app = QApplication([]) 8 | win = QMainWindow() 9 | central_widget = QWidget() 10 | button2 = QPushButton('Second Test', central_widget) 11 | button = QPushButton('Test', central_widget) 12 | button.setGeometry(0,50,120,40) 13 | button.clicked.connect(button_pressed) 14 | button2.clicked.connect(button_pressed) 15 | win.setCentralWidget(central_widget) 16 | win.show() 17 | app.exit(app.exec_()) -------------------------------------------------------------------------------- /example_code/22_Step_By_Step_Qt/AG_layout.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtWidgets import QApplication, QMainWindow, \ 2 | QPushButton, QVBoxLayout, QWidget 3 | 4 | app = QApplication([]) 5 | win = QMainWindow() 6 | central_widget = QWidget() 7 | button2 = QPushButton('Second Test', central_widget) 8 | button = QPushButton('Test', central_widget) 9 | layout = QVBoxLayout(central_widget) 10 | layout.addWidget(button2) 11 | layout.addWidget(button) 12 | win.setCentralWidget(central_widget) 13 | win.show() 14 | app.exit(app.exec_()) -------------------------------------------------------------------------------- /example_code/22_Step_By_Step_Qt/AH_acquire_frame.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | from PyQt5.QtWidgets import QApplication, QMainWindow, \ 4 | QPushButton, QVBoxLayout, QWidget 5 | 6 | cap = cv2.VideoCapture(0) 7 | def button_min_pressed(): 8 | ret, frame = cap.read() 9 | print(np.min(frame)) 10 | 11 | def button_max_pressed(): 12 | ret, frame = cap.read() 13 | print(np.max(frame)) 14 | 15 | 16 | app = QApplication([]) 17 | win = QMainWindow() 18 | central_widget = QWidget() 19 | button_min = QPushButton('Get Minimum', central_widget) 20 | button_max = QPushButton('Get Maximum', central_widget) 21 | button_min.clicked.connect(button_min_pressed) 22 | button_max.clicked.connect(button_max_pressed) 23 | layout = QVBoxLayout(central_widget) 24 | layout.addWidget(button_min) 25 | layout.addWidget(button_max) 26 | win.setCentralWidget(central_widget) 27 | win.show() 28 | app.exit(app.exec_()) 29 | cap.release() 30 | -------------------------------------------------------------------------------- /example_code/22_Step_By_Step_Qt/AI_camera_model/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/22_Step_By_Step_Qt/AI_camera_model/__init__.py -------------------------------------------------------------------------------- /example_code/22_Step_By_Step_Qt/AI_camera_model/models.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | import cv2 4 | 5 | 6 | class Camera: 7 | def __init__(self, cam_num): 8 | self.cam_num = cam_num 9 | self.cap = None 10 | self.last_frame = np.zeros((1,1)) 11 | 12 | def initialize(self): 13 | self.cap = cv2.VideoCapture(self.cam_num) 14 | 15 | def get_frame(self): 16 | ret, self.last_frame = self.cap.read() 17 | return self.last_frame 18 | 19 | def acquire_movie(self, num_frames): 20 | movie = [] 21 | for _ in range(num_frames): 22 | movie.append(self.get_frame()) 23 | return movie 24 | 25 | def set_brightness(self, value): 26 | self.cap.set(cv2.CAP_PROP_BRIGHTNESS, value) 27 | 28 | def get_brightness(self): 29 | return self.cap.get(cv2.CAP_PROP_BRIGHTNESS) 30 | 31 | def close_camera(self): 32 | self.cap.release() 33 | 34 | def __str__(self): 35 | return 'OpenCV Camera {}'.format(self.cam_num) 36 | 37 | 38 | if __name__ == '__main__': 39 | cam = Camera(0) 40 | cam.initialize() 41 | print(cam) 42 | frame = cam.get_frame() 43 | print(frame) 44 | cam.set_brightness(1) 45 | print(cam.get_brightness()) 46 | cam.set_brightness(0.5) 47 | print(cam.get_brightness()) 48 | cam.close_camera() -------------------------------------------------------------------------------- /example_code/22_Step_By_Step_Qt/AI_camera_model/start.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtWidgets import QApplication 2 | 3 | from models import Camera 4 | from views import StartWindow 5 | 6 | camera = Camera(0) 7 | camera.initialize() 8 | 9 | app = QApplication([]) 10 | start_window = StartWindow(camera) 11 | start_window.show() 12 | app.exit(app.exec_()) -------------------------------------------------------------------------------- /example_code/22_Step_By_Step_Qt/AI_camera_model/views.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | from PyQt5.QtCore import Qt, QThread, QTimer 4 | from PyQt5.QtWidgets import QMainWindow, QWidget, QPushButton, QVBoxLayout, QApplication, QSlider 5 | from pyqtgraph import ImageView 6 | 7 | 8 | class StartWindow(QMainWindow): 9 | def __init__(self, camera = None): 10 | super().__init__() 11 | self.camera = camera 12 | 13 | self.central_widget = QWidget() 14 | self.button_frame = QPushButton('Acquire Frame', self.central_widget) 15 | self.button_movie = QPushButton('Start Movie', self.central_widget) 16 | self.image_view = ImageView() 17 | self.slider = QSlider(Qt.Horizontal) 18 | self.slider.setRange(0,10) 19 | 20 | self.layout = QVBoxLayout(self.central_widget) 21 | self.layout.addWidget(self.button_frame) 22 | self.layout.addWidget(self.button_movie) 23 | self.layout.addWidget(self.image_view) 24 | self.layout.addWidget(self.slider) 25 | self.setCentralWidget(self.central_widget) 26 | 27 | self.button_frame.clicked.connect(self.update_image) 28 | self.button_movie.clicked.connect(self.start_movie) 29 | self.slider.valueChanged.connect(self.update_brightness) 30 | 31 | self.update_timer = QTimer() 32 | self.update_timer.timeout.connect(self.update_movie) 33 | 34 | def update_image(self): 35 | frame = self.camera.get_frame() 36 | self.image_view.setImage(frame.T) 37 | 38 | def update_movie(self): 39 | self.image_view.setImage(self.camera.last_frame.T) 40 | 41 | def update_brightness(self, value): 42 | value /= 10 43 | self.camera.set_brightness(value) 44 | 45 | def start_movie(self): 46 | self.movie_thread = MovieThread(self.camera) 47 | self.movie_thread.start() 48 | self.update_timer.start(30) 49 | 50 | 51 | class MovieThread(QThread): 52 | def __init__(self, camera): 53 | super().__init__() 54 | self.camera = camera 55 | 56 | def run(self): 57 | self.camera.acquire_movie(200) 58 | 59 | if __name__ == '__main__': 60 | app = QApplication([]) 61 | window = StartWindow() 62 | window.show() 63 | app.exit(app.exec_()) -------------------------------------------------------------------------------- /example_code/25_ZMQ/01_client_req_rep.py: -------------------------------------------------------------------------------- 1 | import zmq 2 | 3 | context = zmq.Context() 4 | print("Connecting to Server on port 5555") 5 | socket = context.socket(zmq.REQ) 6 | socket.connect("tcp://localhost:5555") 7 | print('Sending Hello') 8 | socket.send(b"Hello") 9 | print('Waiting for answer') 10 | message = socket.recv() 11 | print(f"Received: {message}") -------------------------------------------------------------------------------- /example_code/25_ZMQ/01_server_req_rep.py: -------------------------------------------------------------------------------- 1 | from time import sleep 2 | import zmq 3 | 4 | context = zmq.Context() 5 | socket = context.socket(zmq.REP) 6 | socket.bind("tcp://*:5555") 7 | 8 | print('Binding to port 5555') 9 | message = socket.recv() 10 | print(f"Received request: {message}") 11 | sleep(1) 12 | socket.send(b"Message Received") -------------------------------------------------------------------------------- /example_code/25_ZMQ/02_client_req_rep.py: -------------------------------------------------------------------------------- 1 | import zmq 2 | from datetime import datetime 3 | 4 | context = zmq.Context() 5 | socket = context.socket(zmq.REQ) 6 | socket.connect("tcp://localhost:5555") 7 | msg = f"Now: {datetime.now()}" 8 | print(f"Sending: {msg}") 9 | socket.send(msg.encode('ascii')) 10 | message = socket.recv() 11 | print(f"Received: {message}") 12 | # socket.send(b"stop") 13 | # socket.recv() -------------------------------------------------------------------------------- /example_code/25_ZMQ/02_server_req_rep.py: -------------------------------------------------------------------------------- 1 | from time import sleep 2 | import zmq 3 | 4 | context = zmq.Context() 5 | socket = context.socket(zmq.REP) 6 | print('Binding to port 5555') 7 | socket.bind("tcp://*:5555") 8 | 9 | while True: 10 | message = socket.recv() 11 | print(f"Received request: {message}") 12 | sleep(1) 13 | socket.send(message) 14 | if message == b'stop': 15 | break -------------------------------------------------------------------------------- /example_code/25_ZMQ/03_client_camera.py: -------------------------------------------------------------------------------- 1 | import zmq 2 | import numpy as np 3 | import matplotlib.pyplot as plt 4 | import cv2 5 | 6 | context = zmq.Context() 7 | socket = context.socket(zmq.REQ) 8 | socket.connect("tcp://localhost:5555") 9 | socket.send_string('read') 10 | image = socket.recv_pyobj() 11 | print(np.min(image)) 12 | print(np.max(image)) 13 | plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) 14 | plt.show() 15 | socket.send_string('stop') 16 | print(socket.recv_string()) -------------------------------------------------------------------------------- /example_code/25_ZMQ/03_raspi_client_camera.py: -------------------------------------------------------------------------------- 1 | import zmq 2 | import numpy as np 3 | import matplotlib.pyplot as plt 4 | import cv2 5 | 6 | context = zmq.Context() 7 | socket = context.socket(zmq.REQ) 8 | socket.connect("tcp://192.168.0.3:5555") 9 | socket.send_string('read') 10 | image = socket.recv_pyobj() 11 | print(np.min(image)) 12 | print(np.max(image)) 13 | plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) 14 | plt.show() 15 | socket.send_string('stop') 16 | print(socket.recv_string()) -------------------------------------------------------------------------------- /example_code/25_ZMQ/03_raspi_server_camera.py: -------------------------------------------------------------------------------- 1 | from time import sleep 2 | import numpy as np 3 | import zmq 4 | import picamera 5 | from picamera import PiCamera 6 | 7 | context = zmq.Context() 8 | socket = context.socket(zmq.REP) 9 | print('Binding to port 5555') 10 | socket.bind("tcp://*:5555") 11 | camera = picamera.PiCamera() 12 | sleep(1) 13 | 14 | while True: 15 | message = socket.recv_string() 16 | if message == "read": 17 | camera.resolution = (320, 240) 18 | output = np.empty((240, 320, 3), dtype=np.uint8) 19 | camera.capture(output, 'rgb') 20 | socket.send_pyobj(output) 21 | if message == 'stop': 22 | socket.send_string('Stopping server') 23 | break -------------------------------------------------------------------------------- /example_code/25_ZMQ/03_server_camera.py: -------------------------------------------------------------------------------- 1 | from time import sleep 2 | import zmq 3 | import cv2 4 | 5 | context = zmq.Context() 6 | socket = context.socket(zmq.REP) 7 | print('Binding to port 5555') 8 | socket.bind("tcp://*:5555") 9 | cap = cv2.VideoCapture(0) 10 | sleep(1) 11 | 12 | while True: 13 | message = socket.recv_string() 14 | if message == "read": 15 | ret, frame = cap.read() 16 | socket.send_pyobj(frame) 17 | if message == 'stop': 18 | socket.send_string('Stopping server') 19 | break -------------------------------------------------------------------------------- /example_code/25_ZMQ/03_test_open_cv.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | import matplotlib.pyplot as plt 4 | 5 | 6 | cap = cv2.VideoCapture(0) 7 | 8 | ret, frame = cap.read() 9 | cap.release() 10 | 11 | print(np.min(frame)) 12 | print(np.max(frame)) 13 | 14 | plt.imshow(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) 15 | plt.show() -------------------------------------------------------------------------------- /example_code/25_ZMQ/04_push_pull_simple_sink.py: -------------------------------------------------------------------------------- 1 | import zmq 2 | 3 | context = zmq.Context() 4 | receiver = context.socket(zmq.PULL) 5 | receiver.bind("tcp://*:5556") 6 | 7 | ffts = [] 8 | for i in range(100): 9 | fft = receiver.recv_pyobj() 10 | ffts.append(fft) 11 | print('Received frame {}'.format(i)) 12 | 13 | print("Collected 100 FFT from the workers") -------------------------------------------------------------------------------- /example_code/25_ZMQ/04_push_pull_sink.py: -------------------------------------------------------------------------------- 1 | import zmq 2 | from time import time 3 | 4 | 5 | context = zmq.Context() 6 | receiver = context.socket(zmq.PULL) 7 | receiver.bind("tcp://*:5556") 8 | 9 | ventilator = context.socket(zmq.REP) 10 | ventilator.bind('tcp://*:5557') 11 | ventilator.recv() 12 | ventilator.send(b"") 13 | 14 | ffts = [] 15 | for i in range(100): 16 | fft = receiver.recv_pyobj() 17 | ffts.append(fft) 18 | print('Received frame {}'.format(i)) 19 | 20 | print(ffts) -------------------------------------------------------------------------------- /example_code/25_ZMQ/04_push_pull_ventilator.py: -------------------------------------------------------------------------------- 1 | from time import sleep 2 | import zmq 3 | import cv2 4 | 5 | context = zmq.Context() 6 | socket = context.socket(zmq.PUSH) 7 | socket.bind("tcp://*:5555") 8 | cap = cv2.VideoCapture(0) 9 | sleep(2) 10 | 11 | sink = context.socket(zmq.REQ) 12 | sink.connect('tcp://127.0.0.1:5557') 13 | sink.send(b'') 14 | s = sink.recv() 15 | 16 | for i in range(100): 17 | ret, frame = cap.read() 18 | socket.send_pyobj(frame) 19 | print('Sent frame {}'.format(i)) 20 | -------------------------------------------------------------------------------- /example_code/25_ZMQ/04_push_pull_worker.py: -------------------------------------------------------------------------------- 1 | import zmq 2 | import numpy as np 3 | from random import random 4 | 5 | worker_id = random() 6 | 7 | context = zmq.Context() 8 | receiver = context.socket(zmq.PULL) 9 | receiver.connect("tcp://localhost:5555") 10 | 11 | sender = context.socket(zmq.PUSH) 12 | sender.connect("tcp://localhost:5556") 13 | 14 | for i in range(100): 15 | print(i) 16 | image = receiver.recv_pyobj() 17 | fft = np.fft.fft2(image) 18 | sender.send_pyobj(fft) 19 | -------------------------------------------------------------------------------- /example_code/25_ZMQ/05_pub_sub_publisher.py: -------------------------------------------------------------------------------- 1 | from time import sleep 2 | import zmq 3 | import cv2 4 | 5 | context = zmq.Context() 6 | socket = context.socket(zmq.PUB) 7 | socket.bind("tcp://*:5555") 8 | cap = cv2.VideoCapture(0) 9 | sleep(2) 10 | 11 | i=0 12 | topic = 'camera_frame' 13 | while True: 14 | i += 1 15 | ret, frame = cap.read() 16 | socket.send_string(topic, zmq.SNDMORE) 17 | socket.send_pyobj(frame) 18 | print('Sent frame {}'.format(i)) 19 | -------------------------------------------------------------------------------- /example_code/25_ZMQ/05_pub_sub_subscriber_1.py: -------------------------------------------------------------------------------- 1 | from time import sleep 2 | import zmq 3 | 4 | context = zmq.Context() 5 | socket = context.socket(zmq.SUB) 6 | socket.connect("tcp://localhost:5555") 7 | socket.setsockopt(zmq.SUBSCRIBE, b'camera_frame') 8 | sleep(2) 9 | 10 | 11 | i=0 12 | while True: 13 | i += 1 14 | topic = socket.recv_string() 15 | frame = socket.recv_pyobj() 16 | print('Received frame number {}'.format(i)) 17 | -------------------------------------------------------------------------------- /example_code/25_ZMQ/05_pub_sub_subscriber_2.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | import h5py 3 | from time import sleep 4 | import zmq 5 | 6 | context = zmq.Context() 7 | socket = context.socket(zmq.SUB) 8 | socket.connect("tcp://localhost:5555") 9 | socket.setsockopt(zmq.SUBSCRIBE, b'camera_frame') 10 | sleep(2) 11 | 12 | 13 | with h5py.File('camera_data.hdf5', 'a') as file: 14 | now = str(datetime.now()) 15 | g = file.create_group(now) 16 | 17 | topic = socket.recv_string() 18 | frame = socket.recv_pyobj() 19 | 20 | x = frame.shape[0] 21 | y = frame.shape[1] 22 | z = frame.shape[2] 23 | 24 | dset = g.create_dataset('images', (x, y, z, 1), maxshape=(x, y, z, None)) 25 | dset[:, :, :, 0] = frame 26 | i=0 27 | while True: 28 | i += 1 29 | topic = socket.recv_string() 30 | frame = socket.recv_pyobj() 31 | dset.resize((x, y, z, i+1)) 32 | dset[:, :, :, i] = frame 33 | file.flush() 34 | print('Received frame number {}'.format(i)) 35 | if i == 50: 36 | break 37 | -------------------------------------------------------------------------------- /example_code/26_ZMQ/camera.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import cv2 3 | 4 | 5 | class Camera: 6 | def __init__(self, cam_num): 7 | self.cam_num = cam_num 8 | self.cap = None 9 | self.last_frame = np.zeros((1,1)) 10 | 11 | def initialize(self): 12 | self.cap = cv2.VideoCapture(self.cam_num) 13 | 14 | def get_frame(self, queue=None): 15 | ret, self.last_frame = self.cap.read() 16 | return self.last_frame 17 | 18 | def acquire_movie(self, queue): 19 | self.stop_movie = False 20 | while not self.stop_movie: 21 | queue.put({'topic': 'frame', 'data':self.get_frame()}) 22 | 23 | def set_brightness(self, value): 24 | self.cap.set(cv2.CAP_PROP_BRIGHTNESS, value) 25 | 26 | def get_brightness(self): 27 | return self.cap.get(cv2.CAP_PROP_BRIGHTNESS) 28 | 29 | def close_camera(self): 30 | self.cap.release() 31 | 32 | def __str__(self): 33 | return 'OpenCV Camera {}'.format(self.cam_num) 34 | 35 | 36 | if __name__ == '__main__': 37 | from time import sleep, time 38 | from multiprocessing import Process 39 | import multiprocessing as mp 40 | 41 | mp.set_start_method('spawn') 42 | 43 | cam = Camera(0) 44 | cam.initialize() 45 | movie_process = Process(target=cam.acquire_movie) 46 | movie_process.start() 47 | t0 = time() 48 | while time() - t0 < 10: 49 | # print(f'Total frames: {len(cam.movie)}') 50 | sleep(0.5) 51 | movie_process.terminate() 52 | cam.close_camera() -------------------------------------------------------------------------------- /example_code/26_ZMQ/publisher.py: -------------------------------------------------------------------------------- 1 | import zmq 2 | from time import sleep 3 | 4 | 5 | def publisher(queue, event, port): 6 | """ Simple method that starts a publisher on the port 5555. 7 | 8 | :param multiprocessing.Queue queue: Queue of messages to be broadcast 9 | :param multiprocessing.Event event: Event to stop the publisher 10 | :param int port: port in which to broadcast data 11 | .. TODO:: The publisher's port should be determined in a configuration file. 12 | """ 13 | port_pub = port 14 | context = zmq.Context() 15 | with context.socket(zmq.PUB) as socket: 16 | socket.bind("tcp://*:%s" % port_pub) 17 | while not event.is_set(): 18 | while not queue.empty(): 19 | data = queue.get() # Should be a dictionary {'topic': topic, 'data': data} 20 | socket.send_string(data['topic'], zmq.SNDMORE) 21 | socket.send_pyobj(data['data']) 22 | sleep(0.005) # Sleeps 5 milliseconds to be polite with the CPU 23 | sleep(1) # Gives enough time to the subscribers to update their status 24 | print('Finished publisher') 25 | -------------------------------------------------------------------------------- /example_code/26_ZMQ/start.py: -------------------------------------------------------------------------------- 1 | from multiprocessing import Queue, Process, Event 2 | from time import sleep, time 3 | 4 | from camera import Camera 5 | from publisher import publisher 6 | from subscribers import analyze_frames, save_movie, slow_subscriber 7 | from threading import Thread 8 | 9 | cam = Camera(0) 10 | cam.initialize() 11 | 12 | pub_queue = Queue() 13 | stop_event = Event() 14 | publisher_process = Process(target=publisher, args=(pub_queue, stop_event, 5555)) 15 | publisher_process.start() 16 | analyzer_process = Process(target=analyze_frames, args=(5555, 'frame', stop_event)) 17 | analyzer_process.start() 18 | frame = cam.get_frame() 19 | saver_process = Process(target=save_movie, args=(5555, 'frame', frame.shape, frame.dtype)) 20 | saver_process.start() 21 | 22 | slow_process = Process(target=slow_subscriber, args=(5555, 'frame')) 23 | slow_process.start() 24 | 25 | sleep(2) 26 | camera_thread = Thread(target=cam.acquire_movie, args=(pub_queue,)) 27 | camera_thread.start() 28 | t0 = time() 29 | while time()-t0<5: 30 | print('Still acquiring') 31 | sleep(1) 32 | cam.stop_movie = True 33 | cam.close_camera() 34 | pub_queue.put({'topic': 'frame', 'data': 'stop'}) 35 | camera_thread.join() 36 | analyzer_process.join() 37 | saver_process.join() 38 | slow_process.join() 39 | stop_event.set() 40 | publisher_process.join() 41 | print('Bye') -------------------------------------------------------------------------------- /example_code/27_CRM/Test_Notebook.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 3, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "name": "stdout", 10 | "output_type": "stream", 11 | "text": [ 12 | "Welcome!\n" 13 | ] 14 | } 15 | ], 16 | "source": [ 17 | "print('Welcome!')" 18 | ] 19 | }, 20 | { 21 | "cell_type": "code", 22 | "execution_count": 4, 23 | "metadata": {}, 24 | "outputs": [ 25 | { 26 | "name": "stdout", 27 | "output_type": "stream", 28 | "text": [ 29 | "Sleeping! 0\n", 30 | "Sleeping! 1\n", 31 | "Sleeping! 2\n", 32 | "Sleeping! 3\n", 33 | "Sleeping! 4\n", 34 | "Sleeping! 5\n", 35 | "Sleeping! 6\n", 36 | "Sleeping! 7\n", 37 | "Sleeping! 8\n", 38 | "Sleeping! 9\n" 39 | ] 40 | } 41 | ], 42 | "source": [ 43 | "from time import sleep\n", 44 | "for i in range(10):\n", 45 | " print('Sleeping! {}'.format(i))\n", 46 | " sleep(1)" 47 | ] 48 | }, 49 | { 50 | "cell_type": "markdown", 51 | "metadata": {}, 52 | "source": [ 53 | "# You can also embed markdown into your cells\n", 54 | "\n", 55 | "This is very useful for documenting what your are doing and not forgetting stuff." 56 | ] 57 | }, 58 | { 59 | "cell_type": "code", 60 | "execution_count": null, 61 | "metadata": {}, 62 | "outputs": [], 63 | "source": [] 64 | } 65 | ], 66 | "metadata": { 67 | "kernelspec": { 68 | "display_name": "Python 3", 69 | "language": "python", 70 | "name": "python3" 71 | }, 72 | "language_info": { 73 | "codemirror_mode": { 74 | "name": "ipython", 75 | "version": 3 76 | }, 77 | "file_extension": ".py", 78 | "mimetype": "text/x-python", 79 | "name": "python", 80 | "nbconvert_exporter": "python", 81 | "pygments_lexer": "ipython3", 82 | "version": "3.6.7" 83 | } 84 | }, 85 | "nbformat": 4, 86 | "nbformat_minor": 2 87 | } 88 | -------------------------------------------------------------------------------- /example_code/27_CRM/config_example.yml: -------------------------------------------------------------------------------- 1 | EMAIL: 2 | username: my_username 3 | password: my_password 4 | port: 1234 5 | smtp_server: smtp.server 6 | pop_server: pop.server -------------------------------------------------------------------------------- /example_code/27_CRM/test_email.txt: -------------------------------------------------------------------------------- 1 | Hello {name}, 2 | Welcome to the test CRM. 3 | Hope you are enjoying it! 4 | -------------------------------------------------------------------------------- /example_code/28_fabric/configure_server.py: -------------------------------------------------------------------------------- 1 | import os 2 | import click 3 | 4 | from fabric import Connection, Config 5 | 6 | 7 | @click.command() 8 | @click.option('--ip', help='IP address of the server to connect') 9 | @click.option('--user', '-u', help='New user name to create') 10 | def initial_server_setup(ip, user): 11 | # As soon as the server is created, we can log in as root 12 | c = Connection(ip, user='aquiles') 13 | 14 | # Lets create a user and add it to the sudoers group 15 | # c.run('adduser {}'.format(user)) 16 | # c.run('usermod -aG sudo {}'.format(user)) 17 | # c.run('su - {}'.format(user)) 18 | # c.run('mkdir ~/.ssh') 19 | # c.run('chmod 700 ~/.ssh') 20 | # Lets create an ssh-key pair if it does not exist: 21 | ssh_dir = os.path.join(os.environ.get('HOME'), '.ssh') 22 | ssh_filename = os.path.join(ssh_dir, 'id_rsa') 23 | if not os.path.exists(ssh_dir): 24 | os.makedirs(ssh_dir) 25 | make_ssh_key(c, ssh_filename) 26 | else: 27 | if not os.path.isfile(ssh_filename): 28 | make_ssh_key(c, ssh_filename) 29 | 30 | # Upload the file to the server 31 | ssh_filename_pub = ssh_filename+'.pub' 32 | c.put(ssh_filename_pub, remote='/home/{}/'.format(user)) 33 | c.run('cd /home/{}'.format(user)) 34 | c.run('cat {} >> .ssh/authorized_keys'.format('id_rsa.pub')) 35 | 36 | def make_ssh_key(c, ssh_file_path): 37 | c.local('ssh-keygen -f {}'.format(ssh_file_path)) 38 | 39 | 40 | if __name__ == '__main__': 41 | initial_server_setup() -------------------------------------------------------------------------------- /example_code/29_args_kwargs/AA_simple_test.py: -------------------------------------------------------------------------------- 1 | def test_function(*args): 2 | print(type(args)) 3 | for arg in args: 4 | print(arg) 5 | 6 | 7 | test_function('a', 'b', 1, 2) -------------------------------------------------------------------------------- /example_code/29_args_kwargs/AB_args_args.py: -------------------------------------------------------------------------------- 1 | def test_function(first, second, *args): 2 | print(first) 3 | print(second) 4 | for arg in args: 5 | print(arg) 6 | 7 | test_function('first', 2, 'a', 'b', 'c') 8 | test_function('first', 2) 9 | test_function('first') -------------------------------------------------------------------------------- /example_code/29_args_kwargs/AC_args_function.py: -------------------------------------------------------------------------------- 1 | def fixed_args(first, second): 2 | print(first) 3 | print(second) 4 | 5 | vars = ('First', 'Second') 6 | 7 | fixed_args(*vars) -------------------------------------------------------------------------------- /example_code/29_args_kwargs/AD_generator_args.py: -------------------------------------------------------------------------------- 1 | def test_function(first, second): 2 | print(first) 3 | print(second) 4 | 5 | a = range(1, 3) 6 | 7 | test_function(*a) -------------------------------------------------------------------------------- /example_code/29_args_kwargs/AE_simple_kwargs.py: -------------------------------------------------------------------------------- 1 | def test_kwargs(**kwargs): 2 | print(type(kwargs)) 3 | for key, value in kwargs.items(): 4 | print(key, '=>', value) 5 | 6 | 7 | test_kwargs(first=1, second=2) -------------------------------------------------------------------------------- /example_code/29_args_kwargs/AF_kwargs_mix.py: -------------------------------------------------------------------------------- 1 | def test_function(first, **kwargs): 2 | print(first) 3 | print('Number kwargs: ', len(kwargs)) 4 | 5 | test_function(1) 6 | test_function(1, second=2, third=3) -------------------------------------------------------------------------------- /example_code/29_args_kwargs/AG_kwargs_unpack.py: -------------------------------------------------------------------------------- 1 | def test_unpack(first, second, third): 2 | print(first) 3 | print(second) 4 | print(third) 5 | 6 | vars = {'second': 2, 7 | 'first': 1, 8 | 'third': 3} 9 | 10 | test_unpack(**vars) 11 | 12 | vars = (2, 1, 3) 13 | test_unpack(*vars) -------------------------------------------------------------------------------- /example_code/29_args_kwargs/AH_default_values.py: -------------------------------------------------------------------------------- 1 | def test_function(first, second, third=3, fourth=4): 2 | print(first) 3 | print(second) 4 | print(third) 5 | print(fourth) 6 | 7 | 8 | test_function(1, 2, 5) 9 | -------------------------------------------------------------------------------- /example_code/29_args_kwargs/AI_area.py: -------------------------------------------------------------------------------- 1 | def area(base, height): 2 | return base*height/2 3 | 4 | print(area(1,2)) 5 | 6 | print(area(-1, 2)) 7 | 8 | from functools import wraps 9 | 10 | 11 | def check_positive(func): 12 | @wraps(func) 13 | def func_wrapper(*args): 14 | for arg in args: 15 | if type(arg) is int or type(arg) is float: 16 | if arg < 0: 17 | raise Exception("Function {} takes only positive arguments".format(func.__name__)) 18 | else: 19 | raise Exception("Arguments of {} must be numbers".format(func.__name__)) 20 | return func(*args) 21 | 22 | return func_wrapper 23 | 24 | 25 | @check_positive 26 | def area_positive(base, height): 27 | return base*height/2 28 | 29 | print(area_positive(1, 2)) 30 | print(area_positive(-1, 2)) -------------------------------------------------------------------------------- /example_code/30_lambdas/AA_pandas.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | 3 | df = pd.read_csv('example_data.csv', delimiter = ',') 4 | print(df.head()) 5 | 6 | df['animal'] = df['animal'].apply(lambda x: x.capitalize()) 7 | print(df.head()) -------------------------------------------------------------------------------- /example_code/30_lambdas/AB_Qt.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtWidgets import QApplication, QPushButton 2 | 3 | app = QApplication([]) 4 | 5 | button = QPushButton('Press Me') 6 | button.show() 7 | button.clicked.connect(lambda x: print('Pressed!')) 8 | 9 | app.exit(app.exec()) 10 | 11 | -------------------------------------------------------------------------------- /example_code/30_lambdas/example_data.csv: -------------------------------------------------------------------------------- 1 | animal,uniq_id,water_need 2 | elephant,1001,500 3 | elephant,1002,600 4 | elephant,1003,550 5 | tiger,1004,300 6 | tiger,1005,320 7 | tiger,1006,330 8 | tiger,1007,290 9 | tiger,1008,310 10 | zebra,1009,200 11 | zebra,1010,220 12 | zebra,1011,240 13 | zebra,1012,230 14 | zebra,1013,220 15 | zebra,1014,100 16 | zebra,1015,80 17 | lion,1016,420 18 | lion,1017,600 19 | lion,1018,500 20 | lion,1019,390 21 | kangaroo,1020,410 22 | kangaroo,1021,430 23 | kangaroo,1022,410 -------------------------------------------------------------------------------- /example_code/31_threads/AA_simple.py: -------------------------------------------------------------------------------- 1 | from threading import Thread 2 | from time import sleep 3 | 4 | 5 | def print_numbers(number, delay=1): 6 | for i in range(number): 7 | print(i) 8 | sleep(delay) 9 | 10 | 11 | t = Thread(target=print_numbers, args=(10,), kwargs={'delay': .2}) 12 | t.start() 13 | print('Thread started') 14 | t.join() 15 | print('Thread finished') -------------------------------------------------------------------------------- /example_code/31_threads/AB_multi_threads_simple.py: -------------------------------------------------------------------------------- 1 | from threading import Thread, current_thread 2 | from time import sleep 3 | 4 | 5 | def print_numbers(number, delay=1): 6 | for i in range(number): 7 | print(current_thread(), i) 8 | sleep(delay) 9 | 10 | 11 | t1 = Thread(target=print_numbers, args=(10,), kwargs={'delay':.5}) 12 | t2 = Thread(target=print_numbers, args=(5,)) 13 | t1.start() 14 | t2.start() 15 | 16 | t1.join() 17 | t2.join() 18 | -------------------------------------------------------------------------------- /example_code/31_threads/AC_concurrency.py: -------------------------------------------------------------------------------- 1 | from threading import Thread, current_thread 2 | from time import sleep 3 | 4 | 5 | def save_strings(number, file): 6 | string = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum""" 7 | for i in range(number): 8 | file.write(string) 9 | # sleep(delay) 10 | 11 | 12 | f = open('AC_concurrency.txt', 'w') 13 | t1 = Thread(target=save_strings, args=(10, f)) #, kwargs={'delay':.5}) 14 | t2 = Thread(target=save_strings, args=(10, f)) 15 | t1.start() 16 | t2.start() 17 | 18 | t1.join() 19 | t2.join() 20 | -------------------------------------------------------------------------------- /example_code/31_threads/AD_numpy_example.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | def increase_by_one(array): 5 | array += 1 6 | 7 | data = np.ones((100,1)) 8 | increase_by_one(data) 9 | 10 | print(data[0]) -------------------------------------------------------------------------------- /example_code/31_threads/AE_numpy_thread.py: -------------------------------------------------------------------------------- 1 | from threading import Thread 2 | import numpy as np 3 | 4 | 5 | def increase_by_one(array): 6 | array += 1 7 | 8 | 9 | data = np.ones((100,1)) 10 | 11 | 12 | t = Thread(target=increase_by_one, args=(data,)) 13 | t.start() 14 | t.join() 15 | print(data[0]) 16 | -------------------------------------------------------------------------------- /example_code/31_threads/AF_numpy_multi_thread.py: -------------------------------------------------------------------------------- 1 | from threading import Thread 2 | import numpy as np 3 | 4 | 5 | def increase_by_one(array): 6 | for i in range(10000): 7 | array += 1 8 | 9 | 10 | def divide(array): 11 | for i in range(10000): 12 | array /= 1.1 13 | 14 | 15 | data = np.ones((100,1)) 16 | 17 | t = Thread(target=increase_by_one, args=(data,)) 18 | t2 = Thread(target=divide, args=(data,)) 19 | t.start() 20 | t2.start() 21 | t.join() 22 | t2.join() 23 | print(data[0]) 24 | print(np.mean(data)) 25 | -------------------------------------------------------------------------------- /example_code/31_threads/AG_numpy_loops.py: -------------------------------------------------------------------------------- 1 | from threading import Thread 2 | import numpy as np 3 | 4 | 5 | def increase_by_one(array): 6 | for i in range(len(array)): 7 | array[i] += 1 8 | 9 | 10 | def divide(array): 11 | for i in range(len(array)): 12 | array[i] /= 1.1 13 | 14 | 15 | data = np.ones((100000,1)) 16 | 17 | t = Thread(target=increase_by_one, args=(data,)) 18 | t2 = Thread(target=divide, args=(data,)) 19 | t.start() 20 | t2.start() 21 | t.join() 22 | t2.join() 23 | print(np.max(data)) 24 | print(np.min(data)) -------------------------------------------------------------------------------- /example_code/31_threads/AH_locks.py: -------------------------------------------------------------------------------- 1 | from threading import Thread, Lock 2 | import numpy as np 3 | 4 | lock = Lock() 5 | 6 | 7 | def increase_by_one(array): 8 | with lock: 9 | for i in range(len(array)): 10 | array[i] += 1 11 | 12 | def divide(array): 13 | with lock: 14 | for i in range(len(array)): 15 | array[i] /= 1.1 16 | 17 | data = np.ones((100000,1)) 18 | 19 | t = Thread(target=increase_by_one, args=(data,)) 20 | t2 = Thread(target=divide, args=(data,)) 21 | t2.start() 22 | t.start() 23 | t.join() 24 | t2.join() 25 | print(data[0]) 26 | print(np.mean(data)) 27 | -------------------------------------------------------------------------------- /example_code/31_threads/AI_Two_locks.py: -------------------------------------------------------------------------------- 1 | from threading import Thread, Lock 2 | import numpy as np 3 | 4 | lock = Lock() 5 | 6 | 7 | def increase_by_one(array): 8 | print('Increase') 9 | with lock: 10 | for i in range(len(array)): 11 | array[i] += 1 12 | 13 | def divide(array): 14 | print('Divide') 15 | with lock: 16 | for i in range(len(array)): 17 | array[i] /= 1.1 18 | 19 | lock.acquire() 20 | data = np.ones((100000,1)) 21 | t = Thread(target=increase_by_one, args=(data,)) 22 | t2 = Thread(target=divide, args=(data,)) 23 | t2.start() 24 | t.start() 25 | print('Threads are still not running') 26 | data += 10 27 | lock.release() 28 | t.join() 29 | t2.join() 30 | print(np.max(data)) 31 | print(np.min(data)) 32 | -------------------------------------------------------------------------------- /example_code/31_threads/AJ_rlocks.py: -------------------------------------------------------------------------------- 1 | from threading import Thread, Lock 2 | import numpy as np 3 | 4 | lock = Lock() 5 | 6 | 7 | def increase_by_one(array): 8 | with lock: 9 | for i in range(len(array)): 10 | array[i] += 1 11 | 12 | 13 | def divide(array): 14 | with lock: 15 | for i in range(len(array)): 16 | array[i] /= 1.1 17 | 18 | 19 | lock.acquire() 20 | data = np.ones((100000,1)) 21 | t = Thread(target=increase_by_one, args=(data,)) 22 | t2 = Thread(target=divide, args=(data,)) 23 | t2.start() 24 | t.start() 25 | increase_by_one(data) 26 | lock.release() 27 | t.join() 28 | t2.join() 29 | print(data[0]) 30 | print(np.mean(data)) 31 | -------------------------------------------------------------------------------- /example_code/31_threads/AK_timeout.py: -------------------------------------------------------------------------------- 1 | from threading import Thread, Lock 2 | from time import sleep 3 | 4 | import numpy as np 5 | 6 | lock = Lock() 7 | 8 | 9 | def increase_by_one(array): 10 | l = lock.acquire(timeout=1) 11 | print('Lock: ', l) 12 | for i in range(len(array)): 13 | array[i] += 1 14 | 15 | data = np.ones((100000,1)) 16 | 17 | t = Thread(target=increase_by_one, args=(data,)) 18 | lock.acquire() 19 | t.start() 20 | print('Before Sleeping') 21 | sleep(5) 22 | print('After sleeping') 23 | t.join() 24 | print(data[0]) 25 | print(np.mean(data)) 26 | -------------------------------------------------------------------------------- /example_code/31_threads/AL_event.py: -------------------------------------------------------------------------------- 1 | from threading import Thread, Event 2 | import numpy as np 3 | 4 | evnt = Event() 5 | 6 | def increase_by_one(array): 7 | print('Waiting for event') 8 | l = evnt.wait() 9 | print('Increasing by one') 10 | for i in range(len(array)): 11 | array[i] += 1 12 | 13 | data = np.zeros((100000,1)) 14 | 15 | t = Thread(target=increase_by_one, args=(data,)) 16 | t2 = Thread(target=increase_by_one, args=(data,)) 17 | t.start() 18 | t2.start() 19 | for i in range(len(data)): 20 | data[i] += 1 21 | print('Data Ready. Setting event') 22 | evnt.set() 23 | t.join() 24 | t2.join() 25 | print(data[0]) 26 | print(np.mean(data)) 27 | -------------------------------------------------------------------------------- /example_code/31_threads/AM_stopping_threads.py: -------------------------------------------------------------------------------- 1 | from threading import Thread, Event 2 | from time import sleep 3 | 4 | import numpy as np 5 | 6 | event = Event() 7 | 8 | 9 | def increase_by_one(array): 10 | print('Starting to increase by one') 11 | while True: 12 | if event.is_set(): 13 | break 14 | for i in range(len(array)): 15 | array[i] += 1 16 | sleep(0.1) 17 | print('Finishing') 18 | 19 | 20 | data = np.ones((10000, 1)) 21 | t = Thread(target=increase_by_one, args=(data,)) 22 | t.start() 23 | print('Going to sleep') 24 | sleep(1) 25 | print('Finished sleeping') 26 | event.set() 27 | t.join() 28 | print(data[0]) 29 | -------------------------------------------------------------------------------- /example_code/32_threads_data/AA_shared_memory.py: -------------------------------------------------------------------------------- 1 | from threading import Thread, Event 2 | from time import sleep, time 3 | 4 | event = Event() 5 | 6 | 7 | def modify_variable(var): 8 | while True: 9 | for i in range(len(var)): 10 | var[i] += 1 11 | if event.is_set(): 12 | break 13 | # sleep(.5) 14 | print('Stop printing') 15 | 16 | 17 | def modify_variable2(var): 18 | while True: 19 | for i in range(len(var)): 20 | var[i] -= 1 21 | if event.is_set(): 22 | break 23 | # sleep(.5) 24 | print('Stop printing') 25 | 26 | 27 | my_var = [1, 2, 3] 28 | t = Thread(target=modify_variable, args=(my_var, )) 29 | t2 = Thread(target=modify_variable2, args=(my_var, )) 30 | t.start() 31 | t2.start() 32 | t0 = time() 33 | while time()-t0 < 5: 34 | try: 35 | print(my_var) 36 | sleep(1) 37 | except KeyboardInterrupt: 38 | event.set() 39 | break 40 | event.set() 41 | t.join() 42 | t2.join() 43 | print(my_var) 44 | -------------------------------------------------------------------------------- /example_code/32_threads_data/AB_sync_data_access.py: -------------------------------------------------------------------------------- 1 | from threading import Thread, Event, Lock 2 | from time import sleep, time 3 | 4 | event = Event() 5 | data_lock = Lock() 6 | 7 | def modify_variable(var): 8 | while True: 9 | for i in range(len(var)): 10 | with data_lock: 11 | var[i] += 1 12 | if event.is_set(): 13 | break 14 | # sleep(.5) 15 | print('Stop printing') 16 | 17 | 18 | def modify_variable2(var): 19 | while True: 20 | for i in range(len(var)): 21 | with data_lock: 22 | var[i] -= 1 23 | if event.is_set(): 24 | break 25 | # sleep(.5) 26 | print('Stop printing') 27 | 28 | 29 | my_var = [1, 2, 3] 30 | t = Thread(target=modify_variable, args=(my_var, )) 31 | t2 = Thread(target=modify_variable, args=(my_var, )) 32 | t.start() 33 | t2.start() 34 | t0 = time() 35 | while time()-t0 < 5: 36 | try: 37 | print(my_var) 38 | sleep(1) 39 | except KeyboardInterrupt: 40 | event.set() 41 | break 42 | event.set() 43 | t.join() 44 | t2.join() 45 | print(my_var) 46 | -------------------------------------------------------------------------------- /example_code/32_threads_data/AC_queue_simple.py: -------------------------------------------------------------------------------- 1 | from queue import Queue 2 | 3 | queue = Queue() 4 | for i in range(20): 5 | queue.put(i) 6 | 7 | while not queue.empty(): 8 | data = queue.get() 9 | print(data) -------------------------------------------------------------------------------- /example_code/32_threads_data/AD_queue_add.py: -------------------------------------------------------------------------------- 1 | from threading import Thread, Event 2 | from queue import Queue 3 | from time import sleep, time 4 | 5 | event = Event() 6 | queue1 = Queue() 7 | queue2 = Queue() 8 | 9 | 10 | def modify_variable(queue_in: Queue, queue_out: Queue): 11 | internal_t = 0 12 | while True: 13 | if not queue_in.empty(): 14 | t0 = time() 15 | var = queue_in.get() 16 | for i in range(len(var)): 17 | var[i] += 1 18 | queue_out.put(var) 19 | internal_t += time()-t0 20 | if event.is_set(): 21 | break 22 | sleep(0.1) 23 | print(f'Running time: {internal_t} seconds\n') 24 | 25 | 26 | my_var = [1, 2, 3] 27 | queue1.put(my_var) 28 | t = Thread(target=modify_variable, args=(queue1, queue2)) 29 | t2 = Thread(target=modify_variable, args=(queue2, queue1)) 30 | t.start() 31 | t2.start() 32 | t0 = time() 33 | while time()-t0 < 5: 34 | try: 35 | sleep(1) 36 | except KeyboardInterrupt: 37 | break 38 | event.set() 39 | t.join() 40 | t2.join() 41 | if not queue1.empty(): 42 | print(queue1.get()) 43 | if not queue2.empty(): 44 | print(queue2.get()) -------------------------------------------------------------------------------- /example_code/32_threads_data/AE_queue_faster.py: -------------------------------------------------------------------------------- 1 | from threading import Thread, Event 2 | from queue import Queue 3 | from time import sleep, time 4 | 5 | event = Event() 6 | queue1 = Queue() 7 | queue2 = Queue() 8 | 9 | 10 | def modify_variable(queue_in: Queue, queue_out: Queue): 11 | internal_t = 0 12 | while True: 13 | t0 = time() 14 | var = queue_in.get() 15 | for i in range(len(var)): 16 | var[i] += 1 17 | queue_out.put(var) 18 | internal_t += time()-t0 19 | if event.is_set(): 20 | break 21 | sleep(0.1) 22 | print(f'Running time: {internal_t} seconds\n') 23 | 24 | 25 | my_var = [1, 2, 3] 26 | queue1.put(my_var) 27 | t = Thread(target=modify_variable, args=(queue1, queue2)) 28 | t2 = Thread(target=modify_variable, args=(queue2, queue1)) 29 | t.start() 30 | t2.start() 31 | t0 = time() 32 | while time()-t0 < 5: 33 | try: 34 | sleep(1) 35 | except KeyboardInterrupt: 36 | break 37 | event.set() 38 | t.join() 39 | t2.join() 40 | if not queue1.empty(): 41 | print(queue1.get()) 42 | if not queue2.empty(): 43 | print(queue2.get()) -------------------------------------------------------------------------------- /example_code/32_threads_data/AF_queues_sleep.py: -------------------------------------------------------------------------------- 1 | from threading import Thread, Event 2 | from queue import Queue 3 | from time import sleep, time 4 | 5 | event = Event() 6 | queue1 = Queue() 7 | queue2 = Queue() 8 | 9 | 10 | def modify_variable(queue_in: Queue, queue_out: Queue): 11 | internal_t = 0 12 | sleeping_t = 0 13 | while True: 14 | if not queue_in.empty(): 15 | var = queue_in.get() 16 | t0 = time() 17 | for i in range(len(var)): 18 | var[i] += 1 19 | queue_out.put(var) 20 | internal_t += time()-t0 21 | else: 22 | t0 = time() 23 | sleep(0.001) 24 | sleeping_t += time()-t0 25 | if event.is_set(): 26 | break 27 | sleep(0.1) 28 | print(f'Running time: {internal_t} seconds') 29 | print(f'Sleeping time: {sleeping_t} seconds') 30 | 31 | 32 | my_var = [1, 2, 3] 33 | queue1.put(my_var) 34 | t = Thread(target=modify_variable, args=(queue1, queue1)) 35 | t2 = Thread(target=modify_variable, args=(queue1, queue1)) 36 | t.start() 37 | t2.start() 38 | t0 = time() 39 | while time()-t0 < 5: 40 | try: 41 | sleep(1) 42 | except KeyboardInterrupt: 43 | break 44 | event.set() 45 | t.join() 46 | t2.join() 47 | if not queue1.empty(): 48 | print(queue1.get()) 49 | if not queue2.empty(): 50 | print(queue2.get()) -------------------------------------------------------------------------------- /example_code/32_threads_data/AG_queues_no_wait.py: -------------------------------------------------------------------------------- 1 | from threading import Thread, Event 2 | from queue import Queue, Empty 3 | from time import sleep, time 4 | 5 | event = Event() 6 | queue1 = Queue(1) 7 | queue2 = Queue(1) 8 | 9 | 10 | def modify_variable(queue_in: Queue, queue_out: Queue): 11 | internal_t = 0 12 | while True: 13 | try: 14 | var = queue_in.get(block=False) 15 | except Empty: 16 | continue 17 | t0 = time() 18 | for i in range(len(var)): 19 | var[i] += 1 20 | queue_out.put(var) 21 | internal_t += time()-t0 22 | if event.is_set(): 23 | break 24 | sleep(0.1) 25 | print(f'Running time: {internal_t} seconds\n') 26 | 27 | 28 | my_var = [1, 2, 3] 29 | queue1.put(my_var) 30 | t = Thread(target=modify_variable, args=(queue1, queue2)) 31 | t2 = Thread(target=modify_variable, args=(queue2, queue1)) 32 | t.start() 33 | t2.start() 34 | t0 = time() 35 | while time()-t0 < 5: 36 | try: 37 | sleep(1) 38 | except KeyboardInterrupt: 39 | break 40 | event.set() 41 | t.join() 42 | t2.join() 43 | if not queue1.empty(): 44 | print(queue1.get()) 45 | if not queue2.empty(): 46 | print(queue2.get()) -------------------------------------------------------------------------------- /example_code/32_threads_data/AH_queues_to_stop.py: -------------------------------------------------------------------------------- 1 | from threading import Thread, Event 2 | from queue import Queue 3 | from time import sleep, time 4 | 5 | event = Event() 6 | queue1 = Queue(1) 7 | queue2 = Queue(1) 8 | 9 | 10 | def modify_variable(queue_in: Queue, queue_out: Queue): 11 | internal_t = 0 12 | while True: 13 | var = queue_in.get() 14 | if var is None: 15 | break 16 | t0 = time() 17 | for i in range(len(var)): 18 | var[i] += 1 19 | queue_out.put(var) 20 | internal_t += time()-t0 21 | sleep(0.1) 22 | print(f'Running time: {internal_t} seconds\n') 23 | 24 | 25 | my_var = [1, 2, 3] 26 | queue1.put(my_var) 27 | t = Thread(target=modify_variable, args=(queue1, queue2)) 28 | t2 = Thread(target=modify_variable, args=(queue2, queue1)) 29 | t.start() 30 | t2.start() 31 | t0 = time() 32 | while time()-t0 < 5: 33 | try: 34 | sleep(1) 35 | except KeyboardInterrupt: 36 | break 37 | queue1.put(None) 38 | queue2.put(None) 39 | t.join() 40 | t2.join() 41 | if not queue1.empty(): 42 | print(queue1.get()) 43 | if not queue2.empty(): 44 | print(queue2.get()) -------------------------------------------------------------------------------- /example_code/32_threads_data/AI_download_data.py: -------------------------------------------------------------------------------- 1 | import os 2 | from time import time 3 | from urllib import request 4 | 5 | 6 | website_list = [ 7 | 'https://www.wikipedia.org/', 8 | 'https://nl.wikipedia.org/', 9 | 'https://de.wikipedia.org/', 10 | 'https://fr.wikipedia.org/', 11 | 'https://pt.wikipedia.org/', 12 | 'https://it.wikipedia.org', 13 | 'https://ru.wikipedia.org', 14 | 'https://es.wikipedia.org', 15 | 'https://en.wikipedia.org', 16 | 'https://ja.wikipedia.org', 17 | 'https://zh.wikipedia.org', 18 | ] 19 | 20 | def download_data(website): 21 | response = request.urlopen(website) 22 | data = response.read() 23 | save_data(data) 24 | 25 | def save_data(data): 26 | i = 0 27 | while os.path.exists(f'website_data_{i}.dat'): 28 | i += 1 29 | with open(f'website_data_{i}.dat', 'wb') as f: 30 | f.write(data) 31 | 32 | t0 = time() 33 | for ws in website_list: 34 | download_data(ws) 35 | 36 | print(f'Downloading {len(website_list)} websites took {time()-t0:2.2f} seconds') -------------------------------------------------------------------------------- /example_code/32_threads_data/AJ_threads_download_data.py: -------------------------------------------------------------------------------- 1 | import os 2 | from queue import Queue 3 | from threading import Lock, Thread 4 | from time import time 5 | from urllib import request 6 | 7 | 8 | website_queue = Queue() 9 | data_queue = Queue() 10 | file_lock = Lock() 11 | 12 | 13 | def download_data(): 14 | while True: 15 | var = website_queue.get() 16 | if var is None: 17 | break 18 | response = request.urlopen(var) 19 | data = response.read() 20 | data_queue.put(data) 21 | 22 | 23 | def save_data(): 24 | while True: 25 | var = data_queue.get() 26 | if var is None: 27 | break 28 | with file_lock: 29 | i = 0 30 | while os.path.exists(f'website_data_{i:03d}.dat'): 31 | i += 1 32 | open(f'website_data_{i:03d}.dat', 'w').close() 33 | with open(f'website_data_{i:03d}.dat', 'wb') as f: 34 | f.write(var) 35 | 36 | 37 | website_list = [ 38 | 'https://www.wikipedia.org/', 39 | 'https://nl.wikipedia.org/', 40 | 'https://de.wikipedia.org/', 41 | 'https://fr.wikipedia.org/', 42 | 'https://pt.wikipedia.org/', 43 | 'https://it.wikipedia.org', 44 | 'https://ru.wikipedia.org', 45 | 'https://es.wikipedia.org', 46 | 'https://en.wikipedia.org', 47 | 'https://ja.wikipedia.org', 48 | 'https://zh.wikipedia.org', 49 | ] 50 | 51 | for ws in website_list: 52 | website_queue.put(ws) 53 | 54 | 55 | t0 = time() 56 | threads_download = [] 57 | threads_save = [] 58 | for i in range(3): 59 | t = Thread(target=download_data) 60 | t.start() 61 | threads_download.append(t) 62 | t2 = Thread(target=save_data) 63 | t2.start() 64 | threads_save.append(t2) 65 | 66 | for i in range(3): 67 | website_queue.put(None) 68 | 69 | for t in threads_download: 70 | t.join() 71 | 72 | for i in range(3): 73 | data_queue.put(None) 74 | 75 | for t in threads_save: 76 | t.join() 77 | 78 | 79 | print(f'Downloading {len(website_list)} websites took {time()-t0:2.2f} seconds') -------------------------------------------------------------------------------- /example_code/33_duck_typing/AA_duck_typing.py: -------------------------------------------------------------------------------- 1 | def increase_by_one(value): 2 | if isinstance(value, int) or isinstance(value, float): 3 | return value + 1 4 | 5 | var1 = 'This is a string' 6 | 7 | increase_by_one(var1) 8 | 9 | -------------------------------------------------------------------------------- /example_code/33_duck_typing/AB_duck_typing_numpy.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | def increase_by_one(value): 4 | if isinstance(value, int) or isinstance(value, float): 5 | return value + 1 6 | 7 | var1 = np.array((0, 1, 2)) 8 | 9 | print(increase_by_one(var1)) 10 | 11 | 12 | def increase_by_one(value): 13 | return value + 1 14 | 15 | print(increase_by_one(var1)) -------------------------------------------------------------------------------- /example_code/33_duck_typing/AC_duck_typing.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | def increase_by_one(value): 5 | try: 6 | value += 1 7 | except TypeError: 8 | return None 9 | return value 10 | 11 | var1 = np.array((0, 1, 2)) 12 | print(increase_by_one(var1)) 13 | var1 = 2 14 | print(increase_by_one(var1)) 15 | var1 = 'This is a string' 16 | print(increase_by_one(var1)) 17 | -------------------------------------------------------------------------------- /example_code/33_duck_typing/AD_custom_class.py: -------------------------------------------------------------------------------- 1 | class AddOne: 2 | def __init__(self, value): 3 | self.value = str(value) 4 | 5 | def __add__(self, other): 6 | self.value += str(other) 7 | return self 8 | 9 | def __str__(self): 10 | return self.value 11 | 12 | def increase_by_one(value): 13 | try: 14 | value += 1 15 | except TypeError: 16 | return None 17 | return value 18 | 19 | var1 = AddOne('This is a string') 20 | print(increase_by_one(var1)) 21 | -------------------------------------------------------------------------------- /example_code/33_duck_typing/AE_Complex_data_structure.py: -------------------------------------------------------------------------------- 1 | import yaml 2 | 3 | configuration = { 4 | 'param1': 10, 5 | 'param2': 5 6 | } 7 | 8 | class Experiment: 9 | def __init__(self, config): 10 | self.configuration = config 11 | 12 | def check_config(self): 13 | if not {'param1', 'param2'} <= set(self.configuration.keys()): 14 | raise Exception('The configuration does not include the mandatory fields') 15 | print('Config looks OK') 16 | 17 | def check_config_range(self): 18 | if self.configuration['param1'] > 10: 19 | raise Exception('param1 cannot be larger than 10') 20 | if self.configuration['param2'] > 5: 21 | raise Exception('param2 cannot be larger than 5') 22 | print('Config ranges are OK') 23 | 24 | exp = Experiment(configuration) 25 | exp.check_config() 26 | exp.check_config_range() 27 | 28 | 29 | class Config: 30 | def __init__(self, filename): 31 | with open(filename, 'r') as f: 32 | self._config = yaml.load(f.read(), Loader=yaml.FullLoader) 33 | 34 | def keys(self): 35 | return self._config.keys() 36 | 37 | def __getitem__(self, item): 38 | return self._config[item] 39 | 40 | c = Config('config.yml') 41 | exp2 = Experiment(c) 42 | exp2.check_config() 43 | exp2.check_config_range() -------------------------------------------------------------------------------- /example_code/33_duck_typing/config.yml: -------------------------------------------------------------------------------- 1 | param1: 10 2 | param2: 5 -------------------------------------------------------------------------------- /example_code/34_monkey_patching/AAA_class_attributes.py: -------------------------------------------------------------------------------- 1 | class MyClass: 2 | def __init__(self): 3 | self.a = 1 4 | self.b = '2' 5 | 6 | 7 | var1 = MyClass() 8 | var2 = MyClass() 9 | MyClass.a = 3 10 | MyClass.b = '4' 11 | 12 | print(var1.a) 13 | print(var2.a) 14 | -------------------------------------------------------------------------------- /example_code/34_monkey_patching/AA_custom_class.py: -------------------------------------------------------------------------------- 1 | class MyClass: 2 | a = 1 3 | b = '2' 4 | 5 | 6 | var1 = MyClass() 7 | var2 = var1 8 | 9 | var1.a = 2 10 | var1.b = '3' 11 | 12 | print(var2.a) 13 | print(var2.b) 14 | 15 | var1 = MyClass() 16 | var2 = MyClass() 17 | MyClass.a = 3 18 | MyClass.b = '4' 19 | 20 | print(var1.a) 21 | print(var2.a) 22 | 23 | var1 = MyClass() 24 | var2 = var1 25 | 26 | var3 = var1.a 27 | 28 | var1.a = 2 29 | var1.b = '3' 30 | 31 | MyClass.a = 3 32 | 33 | print(var1.a) 34 | # 2 35 | print(var2.a) 36 | # 2 37 | print(var3) -------------------------------------------------------------------------------- /example_code/34_monkey_patching/AB_custom_method.py: -------------------------------------------------------------------------------- 1 | class MyClass: 2 | a = 1 3 | b = '2' 4 | 5 | def get_value(self): 6 | return self.a 7 | 8 | 9 | var1 = MyClass() 10 | print(var1.get_value()) 11 | 12 | 13 | def get_new_value(cls): 14 | return cls.b 15 | 16 | MyClass.get_value = get_new_value 17 | 18 | print(var1.get_value()) 19 | 20 | var2 = MyClass() 21 | print(var2.get_value()) -------------------------------------------------------------------------------- /example_code/34_monkey_patching/AC_attributes.py: -------------------------------------------------------------------------------- 1 | class MyClass: 2 | a = 1 3 | b = '2' 4 | 5 | def get_value(self): 6 | return self.a 7 | 8 | def get_new_value(cls): 9 | return cls.b 10 | 11 | var1 = MyClass() 12 | var2 = MyClass() 13 | 14 | MyClass.get_value = get_new_value 15 | MyClass.b = '3' 16 | print(var1.get_value()) 17 | print(var2.get_value()) -------------------------------------------------------------------------------- /example_code/34_monkey_patching/AD_types.py: -------------------------------------------------------------------------------- 1 | import types 2 | 3 | 4 | class MyClass: 5 | a = 1 6 | b = '2' 7 | 8 | def get_value(self): 9 | return self.a 10 | 11 | 12 | def get_new_value(cls): 13 | return cls.b 14 | 15 | 16 | var1 = MyClass() 17 | var2 = MyClass() 18 | var1.get_value = types.MethodType(get_new_value, var1) 19 | print(var1.get_value()) 20 | print(var2.get_value()) -------------------------------------------------------------------------------- /example_code/34_monkey_patching/AE_module.py: -------------------------------------------------------------------------------- 1 | def print_variable(var): 2 | print(var) -------------------------------------------------------------------------------- /example_code/34_monkey_patching/AE_module2.py: -------------------------------------------------------------------------------- 1 | import AE_module 2 | 3 | 4 | def another_print(var): 5 | AE_module.print_variable(var+1) -------------------------------------------------------------------------------- /example_code/34_monkey_patching/AE_script.py: -------------------------------------------------------------------------------- 1 | import AE_module 2 | import AE_module2 3 | 4 | var1 = 1 5 | 6 | AE_module.print_variable(var1) 7 | 8 | def print_plus_one(var): 9 | print(var+1) 10 | 11 | AE_module.print_variable = print_plus_one 12 | 13 | AE_module.print_variable(var1) 14 | AE_module2.another_print(var1) -------------------------------------------------------------------------------- /example_code/35_threads_crawler/AA_download_parse.py: -------------------------------------------------------------------------------- 1 | from urllib.request import Request 2 | 3 | from bs4 import BeautifulSoup 4 | from urllib import request 5 | 6 | 7 | headers = {'User-Agent': 'Mozilla/5.0 (compatible; PFTLBot/1.0)'} 8 | req = request.Request('https://en.wikipedia.org/wiki/Shergar', headers=headers) 9 | response = request.urlopen(req) 10 | data = response.read().decode('utf-8') 11 | 12 | soup = BeautifulSoup(data, 'html.parser') 13 | # print(soup.prettify()) 14 | body = soup.find('div', id='bodyContent') 15 | # for link in body.find_all('a'): 16 | # print(link.get('href')) 17 | 18 | links = [] 19 | for alink in body.find_all('a'): 20 | link = alink.get('href') 21 | if link and link.startswith('/wiki'): 22 | if not any(x in link for x in ('Category:', 'File:', 'Help:', 'Special:')): 23 | print(link) 24 | links.append(link) 25 | 26 | print(len(links)) -------------------------------------------------------------------------------- /example_code/35_threads_crawler/AB_recursive_crawling.py: -------------------------------------------------------------------------------- 1 | from bs4 import BeautifulSoup 2 | from urllib import request 3 | 4 | 5 | def get_pages(url, level=0, max_depth=1): 6 | print(f'{level} Getting pages for {url}') 7 | headers = {'User-Agent': 'Mozilla/5.0 (compatible; PFTLBot/1.0)'} 8 | req = request.Request('https://en.wikipedia.org'+url, headers=headers) 9 | response = request.urlopen(req) 10 | data = response.read().decode('utf-8') 11 | soup = BeautifulSoup(data, 'html.parser') 12 | body = soup.find('div', id='bodyContent') 13 | pages = [] 14 | for alink in body.find_all('a'): 15 | link = alink.get('href') 16 | if link and link.startswith('/wiki'): 17 | if not any(x in link for x in ('Category:', 'File:', 'Help:', 'Special:')): 18 | pages.append(link) 19 | if level < max_depth: 20 | pages += get_pages(link, level=level+1) 21 | return pages 22 | 23 | 24 | url = '/wiki/Shergar' 25 | pages = get_pages(url) 26 | print(len(pages)) -------------------------------------------------------------------------------- /example_code/37_imports/AA_sys_argv.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | print(sys.argv) -------------------------------------------------------------------------------- /example_code/37_imports/ABB_import_all.py: -------------------------------------------------------------------------------- 1 | from time import * 2 | from asyncio import * 3 | 4 | print('Here') 5 | sleep(1) 6 | print('After') -------------------------------------------------------------------------------- /example_code/37_imports/AB_sys_argv.py: -------------------------------------------------------------------------------- 1 | from sys import (api_version, 2 | argv, 3 | base_exec_prefix, 4 | exit, 5 | ) 6 | 7 | print(argv) 8 | print(api_version) 9 | print(base_exec_prefix) 10 | exit() 11 | -------------------------------------------------------------------------------- /example_code/37_imports/AC_import_as.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | 4 | data = np.linspace(0, 10, 11) 5 | other_data = np.arange(10, 20, 1) 6 | 7 | data_frame = pd.DataFrame(data=[data, other_data]) 8 | 9 | print(data_frame) -------------------------------------------------------------------------------- /example_code/37_imports/AD_import_as.py: -------------------------------------------------------------------------------- 1 | from asyncio import sleep as async_sleep 2 | from time import sleep as time_sleep 3 | 4 | print('1') 5 | async_sleep(1) 6 | print('2') 7 | time_sleep(1) 8 | print('3') -------------------------------------------------------------------------------- /example_code/37_imports/AE_absolute_imports/first.py: -------------------------------------------------------------------------------- 1 | def first_function(): 2 | print('This is the first function') -------------------------------------------------------------------------------- /example_code/37_imports/AE_absolute_imports/module_a/third.py: -------------------------------------------------------------------------------- 1 | def third_function(): 2 | print('This is the third function') -------------------------------------------------------------------------------- /example_code/37_imports/AE_absolute_imports/numpy/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/37_imports/AE_absolute_imports/numpy/__init__.py -------------------------------------------------------------------------------- /example_code/37_imports/AE_absolute_imports/numpy/sleep.py: -------------------------------------------------------------------------------- 1 | def sleep(): 2 | print('Sleep') -------------------------------------------------------------------------------- /example_code/37_imports/AE_absolute_imports/second.py: -------------------------------------------------------------------------------- 1 | from first import first_function 2 | from module_a.third import third_function 3 | from numpy.sleep import sleep 4 | 5 | 6 | first_function() 7 | third_function() 8 | sleep() 9 | -------------------------------------------------------------------------------- /example_code/37_imports/AE_absolute_imports/sys_append.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | 4 | 5 | CURR_DIR = os.path.dirname(os.path.abspath(__file__)) 6 | sys.path.append(CURR_DIR) 7 | for path in sys.path: 8 | print(path) -------------------------------------------------------------------------------- /example_code/37_imports/AE_pckg/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/37_imports/AE_pckg/__init__.py -------------------------------------------------------------------------------- /example_code/37_imports/AE_pckg/another.py: -------------------------------------------------------------------------------- 1 | from .mod_a import simple 2 | 3 | simple() -------------------------------------------------------------------------------- /example_code/37_imports/AE_pckg/mod_a/__init__.py: -------------------------------------------------------------------------------- 1 | from .file_a import simple -------------------------------------------------------------------------------- /example_code/37_imports/AE_pckg/mod_a/file_a.py: -------------------------------------------------------------------------------- 1 | def simple(): 2 | print('This is simple') -------------------------------------------------------------------------------- /example_code/37_imports/AE_pckg/mod_b/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/37_imports/AE_pckg/mod_b/__init__.py -------------------------------------------------------------------------------- /example_code/37_imports/AE_pckg/mod_b/file_b.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | 4 | BASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 5 | sys.path.append(BASE_PATH) 6 | 7 | from mod_a.file_a import simple 8 | 9 | 10 | def bsimple(): 11 | print('This is simple B') 12 | simple() -------------------------------------------------------------------------------- /example_code/37_imports/AE_pckg/start.py: -------------------------------------------------------------------------------- 1 | from mod_b import file_b 2 | 3 | file_b.bsimple() -------------------------------------------------------------------------------- /example_code/37_imports/AF_relative/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/37_imports/AF_relative/__init__.py -------------------------------------------------------------------------------- /example_code/37_imports/AF_relative/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/37_imports/AF_relative/__init__.pyc -------------------------------------------------------------------------------- /example_code/37_imports/AF_relative/mod_a/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/37_imports/AF_relative/mod_a/__init__.py -------------------------------------------------------------------------------- /example_code/37_imports/AF_relative/mod_a/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/37_imports/AF_relative/mod_a/__init__.pyc -------------------------------------------------------------------------------- /example_code/37_imports/AF_relative/mod_a/file_a.py: -------------------------------------------------------------------------------- 1 | def function_a(): 2 | print('This is function_a') -------------------------------------------------------------------------------- /example_code/37_imports/AF_relative/mod_a/file_a.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/37_imports/AF_relative/mod_a/file_a.pyc -------------------------------------------------------------------------------- /example_code/37_imports/AF_relative/mod_b/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/37_imports/AF_relative/mod_b/__init__.py -------------------------------------------------------------------------------- /example_code/37_imports/AF_relative/mod_b/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/37_imports/AF_relative/mod_b/__init__.pyc -------------------------------------------------------------------------------- /example_code/37_imports/AF_relative/mod_b/file_b.py: -------------------------------------------------------------------------------- 1 | from ..mod_a.file_a import function_a 2 | from AF_relative.mod_b.mod_a.file_c import function_c 3 | 4 | def function_b(): 5 | print('This is function_b') 6 | function_c() 7 | 8 | function_b() 9 | -------------------------------------------------------------------------------- /example_code/37_imports/AF_relative/mod_b/file_b.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/37_imports/AF_relative/mod_b/file_b.pyc -------------------------------------------------------------------------------- /example_code/37_imports/AF_relative/mod_b/mod_a/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/37_imports/AF_relative/mod_b/mod_a/__init__.py -------------------------------------------------------------------------------- /example_code/37_imports/AF_relative/mod_b/mod_a/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/37_imports/AF_relative/mod_b/mod_a/__init__.pyc -------------------------------------------------------------------------------- /example_code/37_imports/AF_relative/mod_b/mod_a/file_c.py: -------------------------------------------------------------------------------- 1 | from ...mod_a.file_a import function_a 2 | 3 | 4 | def function_c(): 5 | print('This is function c') 6 | function_a() 7 | 8 | function_c() -------------------------------------------------------------------------------- /example_code/37_imports/AF_relative/mod_b/mod_a/file_c.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/37_imports/AF_relative/mod_b/mod_a/file_c.pyc -------------------------------------------------------------------------------- /example_code/37_imports/AF_relative/start.py: -------------------------------------------------------------------------------- 1 | from mod_b.file_b import function_b 2 | 3 | function_b.bsimple() -------------------------------------------------------------------------------- /example_code/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/example_code/__init__.py -------------------------------------------------------------------------------- /plugins/__init__.py: -------------------------------------------------------------------------------- 1 | from .newsletter_directive import * -------------------------------------------------------------------------------- /plugins/header_image/AmaticSC-Bold.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/plugins/header_image/AmaticSC-Bold.ttf -------------------------------------------------------------------------------- /plugins/header_image/FrederickatheGreat-Regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/plugins/header_image/FrederickatheGreat-Regular.ttf -------------------------------------------------------------------------------- /plugins/header_image/IndieFlower.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/plugins/header_image/IndieFlower.ttf -------------------------------------------------------------------------------- /plugins/header_image/__init__.py: -------------------------------------------------------------------------------- 1 | from .header_image import * 2 | register() -------------------------------------------------------------------------------- /plugins/newsletter_directive.py: -------------------------------------------------------------------------------- 1 | from docutils.parsers.rst import directives, Directive 2 | from docutils import nodes 3 | 4 | 5 | newsletter_div = """ 6 |
7 |
Subscribe
8 |
9 |

Get all the information directly to your inbox

10 |
11 |
12 |
13 | 14 |
15 |
16 | 18 |
19 |
20 |

Get relevant information, unsubscribe at any time.

21 |
22 |
23 | """ 24 | 25 | 26 | class Newsletter(Directive): 27 | required_arguments = 0 28 | optional_arguments = 0 29 | has_content = False 30 | 31 | def run(self): 32 | return [nodes.raw('', newsletter_div, format='html'),] 33 | 34 | 35 | def register(): 36 | directives.register_directive('newsletter', Newsletter) 37 | -------------------------------------------------------------------------------- /plugins/sitemap/__init__.py: -------------------------------------------------------------------------------- 1 | from .sitemap import * -------------------------------------------------------------------------------- /plugins/tipue_search/__init__.py: -------------------------------------------------------------------------------- 1 | from .tipue_search import * 2 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | beautifulsoup4 2 | blinker 3 | bs4 4 | docutils 5 | feedgenerator 6 | Jinja2 7 | lxml 8 | MarkupSafe 9 | pelican 10 | Pillow 11 | Pygments 12 | python-dateutil 13 | pytz 14 | six 15 | soupsieve 16 | Unidecode 17 | -------------------------------------------------------------------------------- /settings.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | AUTHOR = u'Aquiles Carattino' 4 | SITENAME = u'Python For The Lab' 5 | SITEURL = u'https://www.pythonforthelab.com' 6 | TIMEZONE = 'Europe/Amsterdam' 7 | GITHUB_URL = 'https://github.com/PFTL' 8 | PDF_GENERATOR = False 9 | 10 | TEMPLATE_PAGES = {'static_index.html': 'index.html', 11 | 'search.html': 'search/index.html', 12 | 'static_books.html': 'books/index.html',} 13 | 14 | STATIC_PATHS = ['images', 'static', 'pages'] 15 | 16 | ARTICLE_URL = 'blog/{slug}' 17 | ARTICLE_SAVE_AS = 'blog/{slug}/index.html' 18 | 19 | 20 | 21 | SITEMAP_SAVE_AS = 'sitemap.xml' 22 | SITEMAP = { 23 | 'format': 'xml', 24 | 'priorities': { 25 | 'articles': 1, 26 | 'indexes': 0.5, 27 | 'pages': 0.5 28 | }, 29 | 'changefreqs': { 30 | 'articles': 'monthly', 31 | 'indexes': 'weekly', 32 | 'pages': 'monthly' 33 | }, 34 | 'exclude': ['tag/', 'category/', 'categories.html', 'tags.html', 'search/'], 35 | } 36 | 37 | 38 | FEED_DOMAIN = 'https://www.pythonforthelab.com' 39 | 40 | FEED_RSS = 'feed.rss' 41 | 42 | MARKUP = ('rst', 'markdown',) 43 | 44 | RELATIVE_URLS = True 45 | 46 | INDEX_SAVE_AS = 'blog/index.html' 47 | 48 | PLUGIN_PATHS = ['plugins',] 49 | PLUGINS = ['new_pigment', 'header_image', 'tipue_search', 'sitemap', 'newsletter_directive'] 50 | 51 | LOCALE = 'en_US.utf8' 52 | 53 | # Where to store the images 54 | HEADERS_FOLDER = 'static/img' 55 | # Force to re-generate the images even if they exist 56 | FORCE_IMG_REBUILD = False 57 | # Default image header for when one is missing 58 | DEFAULT_HEADER = 'static/img/compartments.jpg' 59 | 60 | DEFAULT_PAGINATION = 12 61 | -------------------------------------------------------------------------------- /settings_publish.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | AUTHOR = u'Aquiles Carattino' 4 | SITENAME = u'Python For The Lab' 5 | SITEURL = u'https://www.pythonforthelab.com' 6 | TIMEZONE = 'Europe/Amsterdam' 7 | GITHUB_URL = 'https://github.com/PFTL' 8 | PDF_GENERATOR = False 9 | 10 | TEMPLATE_PAGES = {'static_index.html': 'index.html', 11 | 'search.html': 'search/index.html', 12 | 'static_books.html': 'books/index.html',} 13 | 14 | STATIC_PATHS = ['images', 'static', 'pages'] 15 | 16 | ARTICLE_URL = 'blog/{slug}' 17 | ARTICLE_SAVE_AS = 'blog/{slug}/index.html' 18 | 19 | 20 | 21 | SITEMAP_SAVE_AS = 'sitemap.xml' 22 | SITEMAP = { 23 | 'format': 'xml', 24 | 'priorities': { 25 | 'articles': 1, 26 | 'indexes': 0.5, 27 | 'pages': 0.5 28 | }, 29 | 'changefreqs': { 30 | 'articles': 'monthly', 31 | 'indexes': 'weekly', 32 | 'pages': 'monthly' 33 | }, 34 | 'exclude': ['tag/', 'category/', 'categories.html', 'tags.html', 'search/'], 35 | } 36 | 37 | 38 | FEED_DOMAIN = 'https://www.pythonforthelab.com' 39 | 40 | FEED_RSS = 'feed.rss' 41 | 42 | MARKUP = ('rst', 'markdown',) 43 | 44 | RELATIVE_URLS = False 45 | 46 | INDEX_SAVE_AS = 'blog/index.html' 47 | 48 | PLUGIN_PATHS = ['plugins',] 49 | PLUGINS = ['new_pigment', 'header_image', 'tipue_search', 'sitemap', 'newsletter_directive'] 50 | 51 | LOCALE = 'en_US.utf8' 52 | 53 | # Where to store the images 54 | HEADERS_FOLDER = 'static/img' 55 | # Force to re-generate the images even if they exist 56 | FORCE_IMG_REBUILD = False 57 | # Default image header for when one is missing 58 | DEFAULT_HEADER = 'static/img/compartments.jpg' 59 | 60 | DEFAULT_PAGINATION = 12 61 | -------------------------------------------------------------------------------- /static/img/compartments.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/static/img/compartments.jpg -------------------------------------------------------------------------------- /theme/static/css/IndiFlower.css: -------------------------------------------------------------------------------- 1 | /* latin */ 2 | @font-face { 3 | font-family: 'Indie Flower'; 4 | font-style: normal; 5 | font-weight: 400; 6 | src: local('Indie Flower'), local('IndieFlower'), url(m8JVjfNVeKWVnh3QMuKkFcZVaUuH.woff2) format('woff2'); 7 | unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; 8 | } -------------------------------------------------------------------------------- /theme/static/css/m8JVjfNVeKWVnh3QMuKkFcZVaUuH.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/theme/static/css/m8JVjfNVeKWVnh3QMuKkFcZVaUuH.woff2 -------------------------------------------------------------------------------- /theme/static/img/PFTL_Logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/theme/static/img/PFTL_Logo.png -------------------------------------------------------------------------------- /theme/static/img/Pacman_Spinner.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /theme/static/img/calendar.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/theme/static/img/calendar.png -------------------------------------------------------------------------------- /theme/static/img/clock.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/theme/static/img/clock.png -------------------------------------------------------------------------------- /theme/static/img/cover_mockup.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/theme/static/img/cover_mockup.png -------------------------------------------------------------------------------- /theme/static/img/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/theme/static/img/favicon.ico -------------------------------------------------------------------------------- /theme/static/img/general_header.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/theme/static/img/general_header.jpg -------------------------------------------------------------------------------- /theme/static/img/square_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/theme/static/img/square_logo.png -------------------------------------------------------------------------------- /theme/static/img/tags.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/theme/static/img/tags.png -------------------------------------------------------------------------------- /theme/static/js/comment_submit.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function () { 2 | $('#comment-form').submit(function (event) { 3 | event.preventDefault(); 4 | data = $('#comment-form').serialize(); 5 | $.ajax({ 6 | type: "POST", 7 | url: "https://api.staticman.net/v2/entry/PFTL/website_comments/master/comments", 8 | data: data, 9 | beforeSend: function () { 10 | $("#submit").prop("disabled", true); 11 | $("#submit").html(''); 12 | $("#id").prop("disabled", true); 13 | }, 14 | success: function (data) { 15 | $(".comment").html(''); 16 | }, 17 | error: function () { 18 | $("#newsletter_feedback").html(''); 19 | } 20 | }); 21 | }); 22 | }); -------------------------------------------------------------------------------- /theme/static/js/comments_load.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function () { 2 | $.ajax({ 3 | type: 'GET', 4 | url: '/comments/{{ article.url }}comments.html', 5 | success: function (data) { 6 | $('#current-comments').html(data); 7 | }, 8 | error: function () { 9 | $('#current-comments').html('

No comments yet, be the first!

'); 10 | } 11 | }); 12 | }); -------------------------------------------------------------------------------- /theme/static/js/freechapter_subscribe.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function () { 2 | $('#free-chapter').submit(function (event) { 3 | event.preventDefault(); 4 | 5 | var email = {'email': $("#email").val()}; 6 | $.ajax({ 7 | type: "POST", 8 | dataType: 'json', 9 | contentType: 'application/json', 10 | url: "https://uetke.uetke.com/free-chapter", 11 | data: JSON.stringify(email), 12 | beforeSend: function () { 13 | $("#send").prop("disabled", true); 14 | $("#send").text("Sending"); 15 | }, 16 | success: function (data) { 17 | $("#newsletter_feedback").html(''); 18 | }, 19 | error: function (data) { 20 | $("#newsletter_feedback").html(''); 21 | } 22 | }); 23 | }); 24 | }); 25 | -------------------------------------------------------------------------------- /theme/static/js/ie10-viewport-bug-workaround.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * IE10 viewport hack for Surface/desktop Windows 8 bug 3 | * Copyright 2014-2017 The Bootstrap Authors 4 | * Copyright 2014-2017 Twitter, Inc. 5 | * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) 6 | */ 7 | 8 | // See the Getting Started docs for more information: 9 | // https://getbootstrap.com/getting-started/#support-ie10-width 10 | 11 | (function () { 12 | 'use strict' 13 | 14 | if (navigator.userAgent.match(/IEMobile\/10\.0/)) { 15 | var msViewportStyle = document.createElement('style') 16 | msViewportStyle.appendChild( 17 | document.createTextNode( 18 | '@-ms-viewport{width:auto!important}' 19 | ) 20 | ) 21 | document.head.appendChild(msViewportStyle) 22 | } 23 | 24 | }()) 25 | -------------------------------------------------------------------------------- /theme/static/js/jquery.toc.js: -------------------------------------------------------------------------------- 1 | /*! Table of Contents jQuery Plugin - jquery.toc * Copyright (c) 2013-2016 Nikhil Dabas * http://www.apache.org/licenses/LICENSE-2.0 */ 2 | !function (a) { 3 | "use strict"; 4 | var b = function (b) { 5 | return this.each(function () { 6 | var c, d, e = a(this), f = e.data(), g = [e], h = this.tagName, i = 0; 7 | c = a.extend({content: "body", headings: "h1,h2,h3"}, { 8 | content: f.toc || void 0, 9 | headings: f.tocHeadings || void 0 10 | }, b), d = c.headings.split(","), a(c.content).find(c.headings).attr("id", function (b, c) { 11 | var d = function (a) { 12 | 0 === a.length && (a = "?"); 13 | for (var b = a.replace(/\s+/g, "_"), c = "", d = 1; null !== document.getElementById(b + c);) c = "_" + d++; 14 | return b + c 15 | }; 16 | return c || d(a(this).text()) 17 | }).each(function () { 18 | var b = a(this), c = a.map(d, function (a, c) { 19 | return b.is(a) ? c : void 0 20 | })[0]; 21 | if (c > i) { 22 | var e = g[0].children("li:last")[0]; 23 | e && g.unshift(a("<" + h + "/>").appendTo(e)) 24 | } else g.splice(0, Math.min(i - c, Math.max(g.length - 1, 0))); 25 | a("
  • ").appendTo(g[0]).append(a("").text(b.text()).attr("href", "#" + b.attr("id"))), i = c 26 | }) 27 | }) 28 | }, c = a.fn.toc; 29 | a.fn.toc = b, a.fn.toc.noConflict = function () { 30 | return a.fn.toc = c, this 31 | }, a(function () { 32 | b.call(a("[data-toc]")) 33 | }) 34 | }(window.jQuery); -------------------------------------------------------------------------------- /theme/static/js/load_latest_articles.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function () { 2 | $.ajax({ 3 | dataType: "html", 4 | url: '/latest_articles.html', 5 | success: function(data) { 6 | $("#latest_articles").fadeOut(function () { 7 | $(this).html(data).slideDown(); 8 | }); 9 | } 10 | }); 11 | }); -------------------------------------------------------------------------------- /theme/static/js/newsletter_popup.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/theme/static/js/newsletter_popup.js -------------------------------------------------------------------------------- /theme/templates/author_info.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /theme/templates/base.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | {% block meta_header %}{% endblock %} 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | {% block title %}{% endblock %} | Python For The Lab 23 | {% include 'head_scripts.html' %} 24 | {% block head_scripts %}{% endblock %} 25 | 26 | 27 | 28 | {% include 'nav.html' %} 29 | {% block content %}{% endblock %} 30 | {% include 'footer.html' %} 31 | {% include 'footer_javascript.html' %} 32 | {% block footer_scripts %}{% endblock %} 33 | 34 | 35 | -------------------------------------------------------------------------------- /theme/templates/comments.html: -------------------------------------------------------------------------------- 1 |
    2 |
    3 |
    Comments
    4 |
    5 |
    6 |
    7 |
    9 | 10 | 11 |
    12 | 13 |
    14 | 15 |
    16 |
    17 |
    18 | 19 |
    20 | 21 |
    22 |
    23 |
    24 | 25 |
    26 | 27 |
    28 |
    29 |
    30 | 31 |
    32 | 34 |
    35 |
    36 | 37 |
    38 |
    39 |
    40 |
    -------------------------------------------------------------------------------- /theme/templates/cookie_consent.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /theme/templates/footer.html: -------------------------------------------------------------------------------- 1 |
    2 |
    3 | 6 |
    -------------------------------------------------------------------------------- /theme/templates/footer_javascript.html: -------------------------------------------------------------------------------- 1 | 2 | {##} 3 | 4 | {##} 5 | 6 | {##} 7 | {##} 8 | 9 | 10 | -------------------------------------------------------------------------------- /theme/templates/free_chapter_form.html: -------------------------------------------------------------------------------- 1 |
    2 |
    Get a free sample chapter
    3 |
    4 |

    Enter your e-mail and you will get a sample chapter in your inbox

    5 |
    6 |
    7 |
    8 | 9 |
    10 |
    11 | 13 |
    14 |
    15 |
    16 |
    17 | -------------------------------------------------------------------------------- /theme/templates/head_scripts.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PFTL/website/136aa3597b1afdba76c297691acf772628812948/theme/templates/head_scripts.html -------------------------------------------------------------------------------- /theme/templates/index.html: -------------------------------------------------------------------------------- 1 | {% import 'macros/article_thumbnail.html' as art_thum %} 2 | {% extends 'base.html' %} 3 | {% block title %}List of Articles{% endblock %} 4 | {% block content %} 5 |
    6 |
    7 |

    Our Latest Articles

    8 |
    9 |
    10 | {% for article in articles_page.object_list %} 11 |
    12 | {{ art_thum.article_thumb(article) }} 13 |
    14 | {% endfor %} 15 |
    16 | {% if articles_page.has_other_pages() %} 17 | {% include 'pagination.html' %} 18 | {% endif %} 19 | {% endblock %} 20 |
    -------------------------------------------------------------------------------- /theme/templates/macros/article_thumbnail.html: -------------------------------------------------------------------------------- 1 | {% macro article_thumb(article) -%} 2 |
    3 | {% if article.header_thumbnail %} 4 | 5 | {% else %} 6 | 7 | {% endif %} 8 |

    9 | 10 | {{ article.title }} 11 | 12 |

    13 |
    14 |
    15 | {{ article.summary }} 16 | read more 17 |
    18 | {%- endmacro %} -------------------------------------------------------------------------------- /theme/templates/nav.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /theme/templates/newsletter_card.html: -------------------------------------------------------------------------------- 1 |
    2 |
    Subscribe
    3 |
    4 |

    Get all the information directly to your inbox

    5 |
    6 |
    7 |
    8 | 9 |
    10 |
    11 | 13 |
    14 |
    15 |

    Get relevant information, unsubscribe at any time.

    16 |
    17 |
    -------------------------------------------------------------------------------- /theme/templates/newsletter_funnel.html: -------------------------------------------------------------------------------- 1 |
    2 |
    3 |
    4 | 5 |
    6 | Never stop learning 7 |
    8 | 9 |
    10 |

    11 | Join over 1000 Python developers and don't miss any updates! 12 |

    13 |
    14 | 15 | 16 |
    17 |

    Or check out our Books!

    18 | Our Privacy Policy. 19 |
    20 |
    -------------------------------------------------------------------------------- /theme/templates/newsletter_popup.html: -------------------------------------------------------------------------------- 1 |
    2 |
    3 |
    Subscribe ×
    4 |
    5 |

    Get all the information directly to your inbox

    6 |
    7 |
    8 |
    9 | 10 |
    11 |
    12 | 14 |
    15 |
    16 |

    Get relevant information, unsubscribe at any time.

    17 |

    Or check Our Books and Our 18 | Courses

    19 |
    20 |
    21 |
    -------------------------------------------------------------------------------- /theme/templates/newsletter_sidebar.html: -------------------------------------------------------------------------------- 1 |
    2 |
    Subscribe
    3 |
    4 |

    Get all the information directly to your inbox

    5 |
    6 |
    7 |
    8 | 9 |
    10 |
    11 | 13 |
    14 |
    15 |

    Get relevant information, unsubscribe at any time.

    16 |
    17 |
    -------------------------------------------------------------------------------- /theme/templates/page.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | 3 | {% block meta_header %}{% if page.meta %} 4 | 5 | 6 | {% endif %}{% endblock %} 7 | 8 | {% block title %}{{ page.title }}{% endblock %} 9 | 10 | {% block content %} 11 |
    12 |
    13 |

    {{ page.title }}

    14 |
    15 |
    16 |
    17 |
    18 | {{ page.content }} 19 |
    20 |
    21 |
    22 |
    23 | {% endblock %} -------------------------------------------------------------------------------- /theme/templates/pagination.html: -------------------------------------------------------------------------------- 1 | {% if DEFAULT_PAGINATION %} 2 | 3 |
    4 |
      5 |
    • 6 | « 7 |
    • 8 | {% for page_num in articles_paginator.page_range %} 9 |
    • 10 | {{ page_num }} 11 |
    • 12 | {% endfor %} 13 |
    • 14 | » 15 |
    • 16 |
    17 |
    18 | {% endif %} -------------------------------------------------------------------------------- /theme/templates/search.html: -------------------------------------------------------------------------------- 1 | {% extends 'base.html' %} 2 | 3 | {% block title %} 4 | Search - {{ SITENAME|striptags }} 5 | {% endblock title %} 6 | 7 | {% block custom_header_links %} 8 | 9 | 10 | 11 | 12 | 13 | {% endblock %} 14 | 15 | {% block content %} 16 |
    17 |
    18 |
    19 | {% endblock content %} 20 | 21 | {% block footer_scripts %} 22 | 23 | 24 | 25 | 33 | {% endblock %} -------------------------------------------------------------------------------- /theme/templates/social_sharing.html: -------------------------------------------------------------------------------- 1 | {% if article.share_post and article.status != 'draft' %} 2 | 14 | {% endif %} -------------------------------------------------------------------------------- /theme/templates/static_books.html: -------------------------------------------------------------------------------- 1 | {% import 'macros/article_thumbnail.html' as art_thum %} 2 | {% extends 'base.html' %} 3 | {% block title %}Books to Learn Python Programming{% endblock %} 4 | {% block meta_header %} 5 | 6 | 7 | {% endblock %} 8 | {% block head_scripts %} 9 | 15 | {% endblock %} 16 | {% block content %} 17 |
    18 |
    19 |
    20 |

    Python For The Lab

    21 |

    22 |

    Python For The Lab is a collection of resources to help you start using Python 23 | for developing solutions in your lab. 24 |

    25 |

    Learn by doing, with detailed, step-by-step instructions and exercises. More than 150 pages with complete examples and tutorials 26 |

    27 |
    28 |
    29 |
    30 | 33 |
    34 |
    35 | {% include 'free_chapter_form.html' %} 36 |
    37 |
    38 | 39 | {% endblock %} 40 | 41 | {% block footer_scripts %} 42 | 43 | {% endblock %} -------------------------------------------------------------------------------- /theme/templates/static_index.html: -------------------------------------------------------------------------------- 1 | {% import 'macros/article_thumbnail.html' as art_thum %} 2 | {% extends 'base.html' %} 3 | {% block title %}Learn Python Programming{% endblock %} 4 | {% block meta_header %} 5 | 6 | 7 | {% endblock %} 8 | {% block content %} 9 |
    10 |
    11 |
    12 |

    Learn how to use Python for your Lab

    13 |

    Python For The Lab is a collection of resources to help you start using Python 14 | for developing solutions in your lab.
    15 | From analyzing data collected with your experiments to writing software to control your setup. 16 |

    17 |
    18 |
    19 |
    20 |
    21 |

    Where to start

    22 | 29 |
    30 |
    31 |
    32 |
    33 | {% include 'newsletter_card.html' %} 34 |
    35 |
    36 |
    37 |

    Our Latest Articles

    38 |
    39 |
    40 |
    41 | {% for article in articles[:6] %} 42 |
    43 | {{ art_thum.article_thumb(article) }} 44 |
    45 | {% endfor %} 46 |
    47 |
    48 |
    49 | 50 | {% endblock %} 51 | 52 | {% block footer_scripts %} 53 | 54 | {% endblock %} -------------------------------------------------------------------------------- /theme/templates/support_us_card.html: -------------------------------------------------------------------------------- 1 |
    2 |
    3 |
    4 | Support us 5 |
    6 |
    7 | If you like the content of this website, consider buying a copy of the book Python 10 | For The Lab 11 |
    12 |
    13 |
    14 | --------------------------------------------------------------------------------