├── university_counselor ├── a8754_SafetyCriticalSystems │ ├── note.md │ ├── COM4506.pdf │ └── answers │ │ ├── 1a.jpeg │ │ ├── 1b.jpeg │ │ ├── 1c.jpeg │ │ ├── 1d.jpeg │ │ ├── 2ab.jpeg │ │ ├── 2cd.jpeg │ │ ├── 3ab.jpeg │ │ └── 3cd.jpeg ├── b9365_ProgrammingQs │ ├── day1_2end │ │ ├── my_db.sql │ │ ├── requirements.txt │ │ ├── manage.py │ │ └── config.py │ ├── day3_5end │ │ ├── my_db.sql │ │ ├── requirements.txt │ │ ├── static │ │ │ ├── fonts │ │ │ │ ├── glyphicons-halflings-regular.eot │ │ │ │ ├── glyphicons-halflings-regular.ttf │ │ │ │ ├── glyphicons-halflings-regular.woff │ │ │ │ └── glyphicons-halflings-regular.woff2 │ │ │ └── js │ │ │ │ └── npm.js │ │ ├── manage.py │ │ ├── config.py │ │ └── templates │ │ │ ├── home.html │ │ │ ├── tag.html │ │ │ └── user.html │ ├── day1_2start │ │ ├── requirements.txt │ │ ├── config.py │ │ ├── main.py │ │ └── manage.py │ ├── b9365.docx │ ├── b9365.pages │ ├── requirement_docs │ │ └── 要求.docx │ └── day3_5static │ │ └── static │ │ ├── fonts │ │ ├── glyphicons-halflings-regular.eot │ │ ├── glyphicons-halflings-regular.ttf │ │ ├── glyphicons-halflings-regular.woff │ │ └── glyphicons-halflings-regular.woff2 │ │ └── js │ │ └── npm.js └── b9158_SoftwareEngineeringTopic │ ├── 软件维护.docx │ ├── 软件维护.pages │ └── requirement_docs │ ├── 面向对象设计案例题目.pdf │ ├── 结构化设计-教学案例及题目设计.docx │ ├── 软件工程实践课程教学目标2021.1.15.docx │ └── requirement.md ├── 02Modular-Programming-with-Python ├── ch1modular_program_with_py │ ├── i1animals │ │ ├── __init__.py │ │ ├── cat.py │ │ ├── cow.py │ │ ├── dog.py │ │ ├── sheep.py │ │ └── horse.py │ ├── i2shaghetti │ │ ├── config.ini │ │ └── spaghetti.py │ ├── i0stats │ │ ├── stats.py │ │ └── test_stats.py │ ├── i0animals_test.py │ ├── i1animals_test.py │ └── i3cache │ │ ├── test_cache.py │ │ └── cache.py ├── ch3Modules_and_Packages │ ├── i10 │ │ ├── __init__.py │ │ └── i10__all__.py │ ├── i9relative_import │ │ ├── gui │ │ │ └── widgets │ │ │ │ ├── editor │ │ │ │ ├── __init__.py │ │ │ │ ├── slider │ │ │ │ │ ├── __init__.py │ │ │ │ │ └── test.py │ │ │ │ └── utils.py │ │ │ │ └── controls.py │ │ └── i9client.py │ ├── i8import_as │ │ ├── package1 │ │ │ └── utils.py │ │ ├── package2 │ │ │ └── utils.py │ │ └── i8import_as.py │ ├── i12 │ │ ├── module_2.py │ │ ├── module_3.py │ │ ├── module_1.py │ │ └── __init__.py │ ├── i2initialization.py │ ├── i4test_package │ │ ├── __init__.py │ │ └── test_module.py │ ├── i5client_of_i4.py │ ├── i11client_of_i10.py │ ├── i6import.py │ ├── i3test_i2.py │ ├── i13client_of_i12.py │ ├── i0test_module.py │ ├── i1clientOf_i0.py │ └── i7import_globals.py ├── ch4Using Modules for Real-World │ ├── charter │ │ ├── renderers │ │ │ ├── __init__.py │ │ │ ├── png │ │ │ │ ├── __init__.py │ │ │ │ ├── title.py │ │ │ │ ├── line_series.py │ │ │ │ ├── bar_series.py │ │ │ │ ├── y_axis.py │ │ │ │ └── x_axis.py │ │ │ ├── pdf │ │ │ │ ├── __init__.py │ │ │ │ ├── title.py │ │ │ │ ├── line_series.py │ │ │ │ ├── bar_series.py │ │ │ │ ├── y_axis.py │ │ │ │ └── x_axis.py │ │ │ └── renderer.py │ │ ├── __init__.py │ │ ├── constants.py │ │ ├── chart.py │ │ └── generator.py │ └── test_charter.py ├── ch2inventoryControl │ └── items.json ├── ch6Creating_Reusable_Modules │ ├── quantities │ │ ├── __init__.py │ │ └── quantity.py │ └── test_quantities.py ├── ch7Advanced Module Techniques │ ├── i4package globals │ │ ├── globalspackage │ │ │ ├── __init__.py │ │ │ ├── globals.py │ │ │ └── test.py │ │ └── runner.py │ ├── i1add_to_path_gotcha │ │ ├── package │ │ │ ├── __init__.py │ │ │ └── module.py │ │ ├── good_imports.py │ │ └── bad_imports.py │ ├── i3package data │ │ ├── datapackage │ │ │ ├── __init__.py │ │ │ ├── data │ │ │ │ └── phone_numbers.txt │ │ │ └── interface.py │ │ └── runner.py │ ├── i2package configuration │ │ ├── configpackage │ │ │ ├── __init__.py │ │ │ └── interface.py │ │ └── runner.py │ ├── i5script as module gotcha │ │ ├── helpers.py │ │ └── test.py │ └── i6stringutils │ │ └── stringutils.py ├── ch5Working with Module Patterns │ ├── i4dynamic imports │ │ ├── module_a.py │ │ ├── module_b.py │ │ ├── module_c.py │ │ └── load_module.py │ ├── i5plugins │ │ ├── plugins │ │ │ ├── plugin_a.py │ │ │ └── plugin_b.py │ │ └── load_plugin.py │ ├── i3wrappers │ │ └── numpy_wrapper.py │ ├── i6hook_client.py │ ├── i2encapsulation │ │ └── test_recipes.py │ ├── i6hook_login_module.py │ └── i1abstraction │ │ └── happy_hour.py ├── ch8Testing and Deploying Modules │ ├── i2test-package │ │ ├── erikwestra_test_package │ │ │ ├── __init__.py │ │ │ └── test.py │ │ ├── MANIFEST │ │ ├── README.rst │ │ └── setup.py │ └── i1test_quantities │ │ ├── quantities │ │ ├── __init__.py │ │ └── quantity.py │ │ └── test_quantities.py └── ch9Modular Programming as a Foundation for Good Programming Technique │ ├── i1counter │ ├── counter │ │ ├── __init__.py │ │ └── interface.py │ └── tests.py │ └── i2counter-ranges │ ├── counter │ └── __init__.py │ └── tests.py ├── a13814_uml ├── desgin.docx ├── desgin.pages └── note.md ├── 00RefactoringPython ├── ch4Build Test System │ ├── i0unnecessary_math.py │ ├── i1data.txt │ ├── build_test_system.md │ ├── test_i0unnecessary_math.py │ └── test_i1file_reader.py ├── ch15Summary │ ├── path.png │ └── i0summary.md ├── ch2Principles │ ├── 2hats.jpeg │ ├── modao.jpg │ ├── clean_window.jpg │ └── i01what_why_when.md ├── ch8Reorganize_Data │ ├── mycolor.py │ ├── d2itools_cycle.py │ ├── d0singleton.py │ ├── i3replace_array_with_object.py │ ├── i1replace_data_with_obj.py │ ├── i6magicnumber_to_symbolic_constant.py │ ├── i0self_encapsulate_field.py │ ├── i2change_value_to_reference.py │ ├── i7typecode_to_subclass.py │ ├── d4factory_pattern.py │ ├── i5change_unidirect_to_bidirect.py │ ├── d1oberver_pattern.py │ ├── d3state_pattern.py │ ├── i4duplicate_observed_data.py │ └── i9subclass_to_field.py ├── ch10Simplify_Function_Call │ ├── mycolor.py │ ├── i8exception_under_control.py │ ├── i0rename_method.py │ ├── i6introd_parameter_obj.py │ ├── i3parameter_to_explicit_method.py │ ├── i9replace_exception_with_test.py │ ├── i4perserve_whole_object.py │ ├── i2parameterize_method.py │ ├── i7errorcode_to_exception.py │ ├── i5parameter_to_method.py │ └── i1seperate_query_from_modifier.py ├── ch11Handle_Generalization │ ├── mycolor.py │ ├── i1pull_up_constructor_body.py │ ├── i4inheritance_to_delegation.py │ ├── i3template_method.py │ ├── i0pull_up.py │ └── i2push_down.py ├── ch7Move_attribute_between_Objects │ ├── mycolor.py │ ├── i6introd_local_extension.py │ ├── i4hide_delegate.py │ ├── i5introduce_foreign_method.py │ ├── i1move_field.py │ ├── i2extract_class.py │ └── i3inline_class.py ├── ch9Simplify_Conditional_Expression │ ├── mycolor.py │ ├── i3consolidate_duplicate_conditional.py │ ├── i8introd_assertion.py │ ├── i2consolidate_conditional_expression.py │ ├── i4remove_control_flag.py │ ├── i7introd_null_object.py │ ├── i1decompose_conditonal.py │ ├── i5nested_conditiaon_to_guard_clause.py │ └── i6conditional_to_polymorphism.py ├── ch13Refactory_Reuse_Reality │ └── i0refactory_reuse_reality.md ├── ch5Refactory_List │ └── i0record_style.md ├── ch12Big_Refactory │ └── i01big_refactory.md ├── ch3Bad Smell │ └── i01bad_smell.md └── ch6Reorganize_Functions │ ├── i1inline_method.py │ ├── myfinal.py │ ├── i2inline_temp_var.py │ ├── i0extract_method.py │ ├── i5split_temp_var.py │ ├── i3introduce_explain_var.py │ ├── i4introduce_explain_var.py │ ├── i9substitue_algorithm.py │ ├── i7remove_assignment_to_parameter.py │ ├── i6split_temp_var.py │ └── i8replace_method_with_method_obj.py ├── tip.md ├── 01Python_Tricks ├── ch5Common Data Structures in Python │ ├── i11multiprocessing_Queue.py │ ├── i9Immutable Groups of Objects.py │ ├── i1OrderedDict.py │ ├── i0dict.py │ ├── i7bytes.py │ ├── i6str.py │ ├── i3ChainMap.py │ ├── i10LifoQueue.py │ ├── i2defaultdict.py │ ├── i8records_structs_transfer.py │ ├── i4MappingProxyType.py │ └── i5array.py ├── ch3Effective Functions │ ├── i4objects_behave_funcs.py │ ├── i6decorator.py │ ├── i7decorator_modify_behavior.py │ ├── i8multiple_decorators.py │ ├── i15default_return.py │ ├── i13args_decorator.py │ ├── i11args.py │ ├── i12optional_args.py │ ├── i5lambdas.py │ ├── i0function_are_firstclass.py │ ├── i3func_capture_localstate.py │ ├── i2nested_func.py │ ├── i14arg_unpack.py │ ├── i9decorator_with_arg.py │ ├── i1func_in_datastructure.py │ └── i10debuggable_decorator.py ├── ch4Classes&OOP │ ├── i0object_compare.py │ ├── i6class_vs_instance.py │ ├── i4namedtuple.py │ ├── i3clone.py │ ├── i5subclass_namedtuple.py │ ├── i1repr.py │ ├── i2own_exception.py │ ├── i3copying_arbitary_obj.py │ └── i7staticmethod.py ├── ch6Looping & Iteration │ └── i0Pythonic_Loops.py └── ch2Patterns_for_Cleaner_Python │ ├── i5template_string.py │ ├── i1complacent_comma.py │ ├── i0assert.py │ ├── i4string_format.py │ ├── i2with.py │ └── i3with_contextlib.py ├── Software Architecture with Python ├── 4Performance │ ├── mem_profile_example.py │ ├── Listings.txt │ ├── chainmap_example.py │ ├── named.py │ ├── rotate.py │ ├── i1plot.py │ ├── objgraph_example.py │ ├── hound_words.py │ ├── bloomtest.py │ ├── primes.py │ ├── big_o.py │ ├── defaultdict_example.py │ ├── i0common_items.py │ └── ordered.py ├── 2Writing Modifiable and Readable Code │ ├── i4_b_text_better.py │ ├── i0readability_loop.py │ ├── i1_a1.py │ ├── i2_a1_better.py │ ├── i3_b_text_bad.py │ ├── i3_a_text_bad.py │ ├── i1_b1.py │ ├── i5urlrank.py │ ├── i4_a_text_better.py │ ├── i5textrank.py │ └── i5rankbase_improve.py └── 3Testability │ ├── Listings.txt │ ├── test_datetimehelper_object.py │ ├── palindrome1.py │ ├── palindrome2.py │ ├── test_palindrome1.py │ ├── factorial.py │ ├── palindrome3.py │ ├── test_datetimehelper1.py │ ├── test_palindrome2.py │ ├── selenium_testcase.py │ ├── datetimehelper.py │ ├── test_textsearch.py │ ├── url_data.py │ ├── textsearcher.py │ ├── fakelogger.py │ ├── test_palindrome3.py │ └── test_datetimehelper2.py ├── README.md └── .gitignore /university_counselor/a8754_SafetyCriticalSystems/note.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch1modular_program_with_py/i1animals/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /university_counselor/b9365_ProgrammingQs/day1_2end/my_db.sql: -------------------------------------------------------------------------------- 1 | create database blog_db; -------------------------------------------------------------------------------- /university_counselor/b9365_ProgrammingQs/day3_5end/my_db.sql: -------------------------------------------------------------------------------- 1 | create database blog_db; -------------------------------------------------------------------------------- /university_counselor/b9365_ProgrammingQs/day1_2start/requirements.txt: -------------------------------------------------------------------------------- 1 | flake8 2 | 3 | 4 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch3Modules_and_Packages/i10/__init__.py: -------------------------------------------------------------------------------- 1 | from .i10__all__ import * -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch4Using Modules for Real-World/charter/renderers/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /a13814_uml/desgin.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/a13814_uml/desgin.docx -------------------------------------------------------------------------------- /00RefactoringPython/ch4Build Test System/i0unnecessary_math.py: -------------------------------------------------------------------------------- 1 | def multiply(x, y): 2 | return x * y 3 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch2inventoryControl/items.json: -------------------------------------------------------------------------------- 1 | [["SKU123", "S1A1"], ["SKU123", "S2A1"]] -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch3Modules_and_Packages/i9relative_import/gui/widgets/editor/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /a13814_uml/desgin.pages: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/a13814_uml/desgin.pages -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch1modular_program_with_py/i1animals/cat.py: -------------------------------------------------------------------------------- 1 | def speak(): 2 | print("meow") -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch1modular_program_with_py/i1animals/cow.py: -------------------------------------------------------------------------------- 1 | def speak(): 2 | print("moo") -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch1modular_program_with_py/i1animals/dog.py: -------------------------------------------------------------------------------- 1 | def speak(): 2 | print("woof") -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch1modular_program_with_py/i1animals/sheep.py: -------------------------------------------------------------------------------- 1 | def speak(): 2 | print("baa") -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch6Creating_Reusable_Modules/quantities/__init__.py: -------------------------------------------------------------------------------- 1 | from .interface import * -------------------------------------------------------------------------------- /university_counselor/b9365_ProgrammingQs/day1_2start/config.py: -------------------------------------------------------------------------------- 1 | class DevConfig(object): 2 | DEBUG = True 3 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch1modular_program_with_py/i1animals/horse.py: -------------------------------------------------------------------------------- 1 | def speak(): 2 | print("neigh") -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch3Modules_and_Packages/i8import_as/package1/utils.py: -------------------------------------------------------------------------------- 1 | print('import package1 utils') -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch3Modules_and_Packages/i8import_as/package2/utils.py: -------------------------------------------------------------------------------- 1 | print('import package2 utils') -------------------------------------------------------------------------------- /00RefactoringPython/ch4Build Test System/i1data.txt: -------------------------------------------------------------------------------- 1 | Bradman 99.9 52 80 10 6996 334 29 2 | Pollock 60.9 23 41 4 2256 274 7 -------------------------------------------------------------------------------- /tip.md: -------------------------------------------------------------------------------- 1 | grip 真是好东西,举例子,预览readme: 2 | grip ch2Principles/i01what_why_when.md -b 3 | 4 | shift + option + 9 可以打出 · -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch3Modules_and_Packages/i10/i10__all__.py: -------------------------------------------------------------------------------- 1 | A = 1 2 | B = 2 3 | C = 3 4 | 5 | __all__ = ["A", "B"] -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch3Modules_and_Packages/i12/module_2.py: -------------------------------------------------------------------------------- 1 | print('module 2') 2 | 3 | def m2(): 4 | print('m2') -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch3Modules_and_Packages/i12/module_3.py: -------------------------------------------------------------------------------- 1 | print('module 3') 2 | 3 | def m3(): 4 | print('m3') -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch3Modules_and_Packages/i2initialization.py: -------------------------------------------------------------------------------- 1 | def init(): 2 | global my_var 3 | my_var = 10 -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch3Modules_and_Packages/i4test_package/__init__.py: -------------------------------------------------------------------------------- 1 | from i4test_package.test_module import say_hello -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch3Modules_and_Packages/i4test_package/test_module.py: -------------------------------------------------------------------------------- 1 | def say_hello(): 2 | print("hello world!") -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch3Modules_and_Packages/i5client_of_i4.py: -------------------------------------------------------------------------------- 1 | import i4test_package 2 | 3 | i4test_package.say_hello() -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch3Modules_and_Packages/i12/module_1.py: -------------------------------------------------------------------------------- 1 | print('module 1') 2 | 3 | def m1(): 4 | print('m1') 5 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch4Using Modules for Real-World/charter/__init__.py: -------------------------------------------------------------------------------- 1 | from .chart import * 2 | from .generator import * -------------------------------------------------------------------------------- /university_counselor/b9365_ProgrammingQs/day1_2end/requirements.txt: -------------------------------------------------------------------------------- 1 | flake8 2 | flask_sqlalchemy 3 | Flask-Migrate 4 | PyMySQL 5 | 6 | -------------------------------------------------------------------------------- /university_counselor/b9365_ProgrammingQs/day3_5end/requirements.txt: -------------------------------------------------------------------------------- 1 | flake8 2 | flask_sqlalchemy 3 | Flask-Migrate 4 | PyMySQL 5 | 6 | -------------------------------------------------------------------------------- /00RefactoringPython/ch15Summary/path.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/00RefactoringPython/ch15Summary/path.png -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch3Modules_and_Packages/i11client_of_i10.py: -------------------------------------------------------------------------------- 1 | import i10 2 | 3 | print(i10.A) 4 | print(i10.B) 5 | print(i10.C) -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch3Modules_and_Packages/i9relative_import/gui/widgets/editor/slider/__init__.py: -------------------------------------------------------------------------------- 1 | from .test import test_func -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch3Modules_and_Packages/i9relative_import/i9client.py: -------------------------------------------------------------------------------- 1 | # 绝对路径方式 2 | from gui.widgets.editor import slider 3 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch7Advanced Module Techniques/i4package globals/globalspackage/__init__.py: -------------------------------------------------------------------------------- 1 | # Package initialization file. 2 | -------------------------------------------------------------------------------- /00RefactoringPython/ch2Principles/2hats.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/00RefactoringPython/ch2Principles/2hats.jpeg -------------------------------------------------------------------------------- /00RefactoringPython/ch2Principles/modao.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/00RefactoringPython/ch2Principles/modao.jpg -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch3Modules_and_Packages/i6import.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | print(math.pi) 4 | 5 | from math import e 6 | print(e) 7 | 8 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch5Working with Module Patterns/i4dynamic imports/module_a.py: -------------------------------------------------------------------------------- 1 | def say_hello(): 2 | print("Hello from module_a") 3 | 4 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch5Working with Module Patterns/i4dynamic imports/module_b.py: -------------------------------------------------------------------------------- 1 | def say_hello(): 2 | print("Hello from module_b") 3 | 4 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch5Working with Module Patterns/i4dynamic imports/module_c.py: -------------------------------------------------------------------------------- 1 | def say_hello(): 2 | print("Hello from module_c") 3 | 4 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch5Working with Module Patterns/i5plugins/plugins/plugin_a.py: -------------------------------------------------------------------------------- 1 | def say_hello(): 2 | print("Hello from plugin_a") 3 | 4 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch5Working with Module Patterns/i5plugins/plugins/plugin_b.py: -------------------------------------------------------------------------------- 1 | def say_hello(): 2 | print("Hello from plugin_b") 3 | 4 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch7Advanced Module Techniques/i1add_to_path_gotcha/package/__init__.py: -------------------------------------------------------------------------------- 1 | # This is an empty package initialization file. 2 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch8Testing and Deploying Modules/i2test-package/erikwestra_test_package/__init__.py: -------------------------------------------------------------------------------- 1 | # Empty package initialization file. 2 | -------------------------------------------------------------------------------- /00RefactoringPython/ch2Principles/clean_window.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/00RefactoringPython/ch2Principles/clean_window.jpg -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch3Modules_and_Packages/i8import_as/i8import_as.py: -------------------------------------------------------------------------------- 1 | from package1 import utils as utils1 2 | from package2 import utils as utils2 -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch3Modules_and_Packages/i9relative_import/gui/widgets/editor/slider/test.py: -------------------------------------------------------------------------------- 1 | def test_func(): 2 | print("import silder.py") -------------------------------------------------------------------------------- /university_counselor/b9365_ProgrammingQs/b9365.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/university_counselor/b9365_ProgrammingQs/b9365.docx -------------------------------------------------------------------------------- /university_counselor/b9365_ProgrammingQs/b9365.pages: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/university_counselor/b9365_ProgrammingQs/b9365.pages -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch3Modules_and_Packages/i3test_i2.py: -------------------------------------------------------------------------------- 1 | import i2initialization 2 | 3 | i2initialization.init() 4 | 5 | print(i2initialization.my_var) -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch7Advanced Module Techniques/i3package data/datapackage/__init__.py: -------------------------------------------------------------------------------- 1 | # Package initialization file. 2 | 3 | from .interface import * 4 | -------------------------------------------------------------------------------- /00RefactoringPython/ch4Build Test System/build_test_system.md: -------------------------------------------------------------------------------- 1 | - 一套测试就是一个强大的bug侦测机器,能够大大缩减查找bug所需时间 2 | - XP编程者都是十分专注的测试者,他们希望尽可能快速开发, 3 |  而且也知道测试让他们尽可能快速前进 4 | 5 | 6 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch3Modules_and_Packages/i13client_of_i12.py: -------------------------------------------------------------------------------- 1 | from i12 import * 2 | 3 | print('#'*10) 4 | module_1.m1() 5 | module_2.m2() 6 | module_3.m3() 7 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch4Using Modules for Real-World/charter/renderers/png/__init__.py: -------------------------------------------------------------------------------- 1 | """ __init__.py 2 | 3 | Empty package initialization file. 4 | """ 5 | -------------------------------------------------------------------------------- /00RefactoringPython/ch8Reorganize_Data/mycolor.py: -------------------------------------------------------------------------------- 1 | from termcolor import colored 2 | 3 | 4 | def show(s,color='green'): 5 | return colored(s, color, attrs=['reverse', 'blink']) -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch1modular_program_with_py/i2shaghetti/config.ini: -------------------------------------------------------------------------------- 1 | # Configuration file for the spaghetti.py program. 2 | 3 | [config] 4 | 5 | num_data_points=10 -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch4Using Modules for Real-World/charter/renderers/pdf/__init__.py: -------------------------------------------------------------------------------- 1 | """ __init__.py 2 | 3 | Empty package initialization file. 4 | """ 5 | 6 | -------------------------------------------------------------------------------- /university_counselor/a8754_SafetyCriticalSystems/COM4506.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/university_counselor/a8754_SafetyCriticalSystems/COM4506.pdf -------------------------------------------------------------------------------- /university_counselor/b9158_SoftwareEngineeringTopic/软件维护.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/university_counselor/b9158_SoftwareEngineeringTopic/软件维护.docx -------------------------------------------------------------------------------- /university_counselor/b9158_SoftwareEngineeringTopic/软件维护.pages: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/university_counselor/b9158_SoftwareEngineeringTopic/软件维护.pages -------------------------------------------------------------------------------- /00RefactoringPython/ch10Simplify_Function_Call/mycolor.py: -------------------------------------------------------------------------------- 1 | from termcolor import colored 2 | 3 | 4 | def show(s,color='green'): 5 | return colored(s, color, attrs=['reverse', 'blink']) -------------------------------------------------------------------------------- /00RefactoringPython/ch11Handle_Generalization/mycolor.py: -------------------------------------------------------------------------------- 1 | from termcolor import colored 2 | 3 | 4 | def show(s,color='green'): 5 | return colored(s, color, attrs=['reverse', 'blink']) -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch6Creating_Reusable_Modules/test_quantities.py: -------------------------------------------------------------------------------- 1 | import quantities 2 | 3 | quantities.init("us") 4 | 5 | 6 | 7 | print(quantities.parse("15 liters")) -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch7Advanced Module Techniques/i2package configuration/configpackage/__init__.py: -------------------------------------------------------------------------------- 1 | # Package initialization file. 2 | 3 | from .interface import * 4 | 5 | -------------------------------------------------------------------------------- /university_counselor/a8754_SafetyCriticalSystems/answers/1a.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/university_counselor/a8754_SafetyCriticalSystems/answers/1a.jpeg -------------------------------------------------------------------------------- /university_counselor/a8754_SafetyCriticalSystems/answers/1b.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/university_counselor/a8754_SafetyCriticalSystems/answers/1b.jpeg -------------------------------------------------------------------------------- /university_counselor/a8754_SafetyCriticalSystems/answers/1c.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/university_counselor/a8754_SafetyCriticalSystems/answers/1c.jpeg -------------------------------------------------------------------------------- /university_counselor/a8754_SafetyCriticalSystems/answers/1d.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/university_counselor/a8754_SafetyCriticalSystems/answers/1d.jpeg -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch7Advanced Module Techniques/i2package configuration/runner.py: -------------------------------------------------------------------------------- 1 | import configpackage 2 | 3 | configpackage.init({'log_errors': True}) 4 | configpackage.test() -------------------------------------------------------------------------------- /university_counselor/a8754_SafetyCriticalSystems/answers/2ab.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/university_counselor/a8754_SafetyCriticalSystems/answers/2ab.jpeg -------------------------------------------------------------------------------- /university_counselor/a8754_SafetyCriticalSystems/answers/2cd.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/university_counselor/a8754_SafetyCriticalSystems/answers/2cd.jpeg -------------------------------------------------------------------------------- /university_counselor/a8754_SafetyCriticalSystems/answers/3ab.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/university_counselor/a8754_SafetyCriticalSystems/answers/3ab.jpeg -------------------------------------------------------------------------------- /university_counselor/a8754_SafetyCriticalSystems/answers/3cd.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/university_counselor/a8754_SafetyCriticalSystems/answers/3cd.jpeg -------------------------------------------------------------------------------- /university_counselor/b9365_ProgrammingQs/requirement_docs/要求.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/university_counselor/b9365_ProgrammingQs/requirement_docs/要求.docx -------------------------------------------------------------------------------- /00RefactoringPython/ch7Move_attribute_between_Objects/mycolor.py: -------------------------------------------------------------------------------- 1 | from termcolor import colored 2 | 3 | 4 | def show(s,color='green'): 5 | return colored(s, color, attrs=['reverse', 'blink']) -------------------------------------------------------------------------------- /00RefactoringPython/ch9Simplify_Conditional_Expression/mycolor.py: -------------------------------------------------------------------------------- 1 | from termcolor import colored 2 | 3 | 4 | def show(s,color='green'): 5 | return colored(s, color, attrs=['reverse', 'blink']) -------------------------------------------------------------------------------- /01Python_Tricks/ch5Common Data Structures in Python/i11multiprocessing_Queue.py: -------------------------------------------------------------------------------- 1 | from multiprocessing import Queue 2 | 3 | q = Queue() 4 | q.put('eat') 5 | q.put('sleep') 6 | q.put('code') 7 | print(q) -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch3Modules_and_Packages/i12/__init__.py: -------------------------------------------------------------------------------- 1 | # from .module_1 import * 2 | # from .module_2 import * 3 | # from .module_3 import * 4 | 5 | __all__ = ["module_1", "module_2"] 6 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch7Advanced Module Techniques/i3package data/datapackage/data/phone_numbers.txt: -------------------------------------------------------------------------------- 1 | (123) 456-7890 2 | (123) 921-0487 3 | (167) 201-4494 4 | (192) 549-2024 5 | (502) 772-9903 6 | -------------------------------------------------------------------------------- /01Python_Tricks/ch5Common Data Structures in Python/i9Immutable Groups of Objects.py: -------------------------------------------------------------------------------- 1 | import dis 2 | 3 | dis.dis(compile("(23, 'a', 'b', 'c')", '', 'eval')) 4 | dis.dis(compile("[23, 'a', 'b', 'c']", '', 'eval')) -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch7Advanced Module Techniques/i4package globals/runner.py: -------------------------------------------------------------------------------- 1 | # Simple script to load and run globalspackage.test.test() function. 2 | 3 | from globalspackage import test 4 | test.test() 5 | 6 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch8Testing and Deploying Modules/i2test-package/MANIFEST: -------------------------------------------------------------------------------- 1 | # file GENERATED by distutils, do NOT edit 2 | setup.py 3 | erikwestra_test_package/__init__.py 4 | erikwestra_test_package/test.py 5 | -------------------------------------------------------------------------------- /university_counselor/b9158_SoftwareEngineeringTopic/requirement_docs/面向对象设计案例题目.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/university_counselor/b9158_SoftwareEngineeringTopic/requirement_docs/面向对象设计案例题目.pdf -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch3Modules_and_Packages/i0test_module.py: -------------------------------------------------------------------------------- 1 | def foo(): 2 | print("in foo") 3 | 4 | def bar(): 5 | print("in bar") 6 | 7 | my_var = 0 8 | 9 | print("importing test module") 10 | 11 | -------------------------------------------------------------------------------- /university_counselor/b9158_SoftwareEngineeringTopic/requirement_docs/结构化设计-教学案例及题目设计.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/university_counselor/b9158_SoftwareEngineeringTopic/requirement_docs/结构化设计-教学案例及题目设计.docx -------------------------------------------------------------------------------- /00RefactoringPython/ch13Refactory_Reuse_Reality/i0refactory_reuse_reality.md: -------------------------------------------------------------------------------- 1 | - 对员工进行培训
2 | - 尽量获取短期利益
3 | - 减少开销
4 | - 安全引入新技术
5 |
6 | 如果你正试图说服别人充哦股(或者采用其他技术实践),请注意保证自己时刻关注这些问题, 7 | 这样才能深入人心,技术传播是很困难的,但不是做不到。 -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch7Advanced Module Techniques/i3package data/runner.py: -------------------------------------------------------------------------------- 1 | # Simple script to load and run datapackage.get_phone_numbers() function. 2 | 3 | import datapackage 4 | print(datapackage.get_phone_numbers()) 5 | 6 | -------------------------------------------------------------------------------- /01Python_Tricks/ch5Common Data Structures in Python/i1OrderedDict.py: -------------------------------------------------------------------------------- 1 | import collections 2 | 3 | d = collections.OrderedDict(one=1, two=2, three=3) 4 | 5 | print(d) 6 | 7 | d['four'] = 4 8 | print(d) 9 | 10 | print('d.keys()=', d.keys()) -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch9Modular Programming as a Foundation for Good Programming Technique/i1counter/counter/__init__.py: -------------------------------------------------------------------------------- 1 | # This is the package initialization file for the "counter" package. 2 | 3 | from .interface import * 4 | 5 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch8Testing and Deploying Modules/i1test_quantities/quantities/__init__.py: -------------------------------------------------------------------------------- 1 | """ __init__.py 2 | 3 | This is the package initialization file for the `quantities` package. 4 | """ 5 | from .interface import * 6 | 7 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch9Modular Programming as a Foundation for Good Programming Technique/i2counter-ranges/counter/__init__.py: -------------------------------------------------------------------------------- 1 | # This is the package initialization file for the "counter" package. 2 | 3 | from .interface import * 4 | 5 | -------------------------------------------------------------------------------- /university_counselor/b9158_SoftwareEngineeringTopic/requirement_docs/软件工程实践课程教学目标2021.1.15.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/university_counselor/b9158_SoftwareEngineeringTopic/requirement_docs/软件工程实践课程教学目标2021.1.15.docx -------------------------------------------------------------------------------- /university_counselor/b9365_ProgrammingQs/day3_5end/static/fonts/glyphicons-halflings-regular.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/university_counselor/b9365_ProgrammingQs/day3_5end/static/fonts/glyphicons-halflings-regular.eot -------------------------------------------------------------------------------- /university_counselor/b9365_ProgrammingQs/day3_5end/static/fonts/glyphicons-halflings-regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/university_counselor/b9365_ProgrammingQs/day3_5end/static/fonts/glyphicons-halflings-regular.ttf -------------------------------------------------------------------------------- /university_counselor/b9365_ProgrammingQs/day3_5end/static/fonts/glyphicons-halflings-regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/university_counselor/b9365_ProgrammingQs/day3_5end/static/fonts/glyphicons-halflings-regular.woff -------------------------------------------------------------------------------- /01Python_Tricks/ch5Common Data Structures in Python/i0dict.py: -------------------------------------------------------------------------------- 1 | phonebook = { 'bob': 7387, 2 | 'alice': 3719, 3 | 'jack': 7052, 4 | } 5 | 6 | squares = {x: x*x for x in range(6)} 7 | 8 | print(phonebook['alice']) 9 | print(squares) -------------------------------------------------------------------------------- /01Python_Tricks/ch5Common Data Structures in Python/i7bytes.py: -------------------------------------------------------------------------------- 1 | arr = bytes((0, 1, 2, 3)) 2 | print(arr[1], arr) 3 | 4 | arr = b'xx00x01x02x03' 5 | try: 6 | bytes((0, 300)) 7 | except: 8 | print('An error occured: integers in the rangeof0<=x<=255') -------------------------------------------------------------------------------- /university_counselor/b9365_ProgrammingQs/day3_5end/static/fonts/glyphicons-halflings-regular.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/university_counselor/b9365_ProgrammingQs/day3_5end/static/fonts/glyphicons-halflings-regular.woff2 -------------------------------------------------------------------------------- /university_counselor/b9365_ProgrammingQs/day3_5static/static/fonts/glyphicons-halflings-regular.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/university_counselor/b9365_ProgrammingQs/day3_5static/static/fonts/glyphicons-halflings-regular.eot -------------------------------------------------------------------------------- /university_counselor/b9365_ProgrammingQs/day3_5static/static/fonts/glyphicons-halflings-regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/university_counselor/b9365_ProgrammingQs/day3_5static/static/fonts/glyphicons-halflings-regular.ttf -------------------------------------------------------------------------------- /01Python_Tricks/ch5Common Data Structures in Python/i6str.py: -------------------------------------------------------------------------------- 1 | arr = 'abcd' 2 | 3 | print(arr[1]) 4 | 5 | try: 6 | arr[1] = 'e' 7 | del arr[1] 8 | except: 9 | print('An error occured.') 10 | 11 | print("list('abcd')=", list('abcd')) 12 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch4Using Modules for Real-World/charter/constants.py: -------------------------------------------------------------------------------- 1 | 2 | CHART_WIDTH = 600 3 | CHART_HEIGHT = 400 4 | TITLE_HEIGHT = 50 5 | X_AXIS_HEIGHT = 50 6 | Y_AXIS_WIDTH = 50 7 | MARGIN = 20 8 | TICKMARK_HEIGHT = 8 -------------------------------------------------------------------------------- /university_counselor/b9365_ProgrammingQs/day3_5static/static/fonts/glyphicons-halflings-regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/university_counselor/b9365_ProgrammingQs/day3_5static/static/fonts/glyphicons-halflings-regular.woff -------------------------------------------------------------------------------- /university_counselor/b9365_ProgrammingQs/day3_5static/static/fonts/glyphicons-halflings-regular.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/greatabel/ImprovePython/HEAD/university_counselor/b9365_ProgrammingQs/day3_5static/static/fonts/glyphicons-halflings-regular.woff2 -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch3Modules_and_Packages/i1clientOf_i0.py: -------------------------------------------------------------------------------- 1 | import i0test_module 2 | 3 | print('-'*10) 4 | i0test_module.foo() 5 | i0test_module.bar() 6 | 7 | print(i0test_module.my_var) 8 | i0test_module.my_var = 111 9 | print(i0test_module.my_var) -------------------------------------------------------------------------------- /Software Architecture with Python/4Performance/mem_profile_example.py: -------------------------------------------------------------------------------- 1 | # Code Listing #4 2 | """ 3 | 4 | Memory profiler example 5 | 6 | """ 7 | 8 | @profile 9 | def squares(n): 10 | return [x*x for x in range(1, n+1)] 11 | 12 | squares(1000000) 13 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch5Working with Module Patterns/i4dynamic imports/load_module.py: -------------------------------------------------------------------------------- 1 | import importlib 2 | 3 | module_name = input("Load module: ") 4 | 5 | if module_name != "": 6 | module = importlib.import_module(module_name) 7 | module.say_hello() -------------------------------------------------------------------------------- /01Python_Tricks/ch3Effective Functions/i4objects_behave_funcs.py: -------------------------------------------------------------------------------- 1 | class Adder: 2 | def __init__(self, n): 3 | self.n = n 4 | 5 | def __call__(self, x): 6 | return self.n + x 7 | 8 | 9 | plus_3 = Adder(3) 10 | r = plus_3(4) 11 | print(r) 12 | -------------------------------------------------------------------------------- /01Python_Tricks/ch5Common Data Structures in Python/i3ChainMap.py: -------------------------------------------------------------------------------- 1 | from collections import ChainMap 2 | 3 | dict1 = {'one': 1, 'two': 2} 4 | dict2 = {'three': 3, 'four': 4} 5 | 6 | chain = ChainMap(dict1, dict2) 7 | print(chain) 8 | print(chain['three']) 9 | print(chain['one']) -------------------------------------------------------------------------------- /00RefactoringPython/ch5Refactory_List/i0record_style.md: -------------------------------------------------------------------------------- 1 | # 介绍时候我才用标准格式,每个重构首发有5个部分 2 | - name 3 | - summary 4 | - motivation 5 | ···why需要这个重构 什么情况下不该使用这个重构 6 | - mechanics(做法) 7 | - examples 8 | 9 | # 重构基本技巧:小步前进,频繁测试 10 | 运用重构时候,请记住:它们仅仅是起点,发表它们,是因为我相信 11 | 尽管它们还不完美,但的确有用。 -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch7Advanced Module Techniques/i5script as module gotcha/helpers.py: -------------------------------------------------------------------------------- 1 | # Helper module for the test.py script. 2 | 3 | 4 | import test 5 | print('helper: ', '@^@ '*5) 6 | 7 | def run_test(): 8 | print(test.do_something(10)) 9 | 10 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch8Testing and Deploying Modules/i2test-package/README.rst: -------------------------------------------------------------------------------- 1 | erikwestra-test-package 2 | ----------------------- 3 | 4 | This is a simple test package. To use it, type:: 5 | 6 | from erikwestra_test_package import test 7 | test.run() 8 | 9 | -------------------------------------------------------------------------------- /00RefactoringPython/ch15Summary/i0summary.md: -------------------------------------------------------------------------------- 1 | - 如果代码比重构之前好,那么就把它集成到系统中,发布你的成果。 2 | - 如果代码并没有变好,就放弃无用的工作,回到起始点。 3 |
这就像在悬崖峭壁的小路上走,有光就前进,虽然谨慎但是自信,但是一旦太阳下山, 4 | 你就应该停止前进,晚上睡觉,并且相信太阳仍然会出来。 5 | ![](https://raw.githubusercontent.com/greatabel/RefactoringPython/master/ch15Summary/path.png) -------------------------------------------------------------------------------- /01Python_Tricks/ch4Classes&OOP/i0object_compare.py: -------------------------------------------------------------------------------- 1 | a = [1, 2, 3] 2 | b = a 3 | 4 | assert a == b 5 | assert a is b 6 | 7 | print('We can do that by calling list() on the existing list to create a copy we’ll name c') 8 | c = list(a) 9 | 10 | assert a == c 11 | assert a is c 12 | -------------------------------------------------------------------------------- /00RefactoringPython/ch10Simplify_Function_Call/i8exception_under_control.py: -------------------------------------------------------------------------------- 1 | from mycolor import show 2 | 3 | while True: 4 | try: 5 | x = int(input("Please enter a number: ")) 6 | break 7 | except ValueError: 8 | print("Oops! That was no valid number. Try again...") -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch6Creating_Reusable_Modules/quantities/quantity.py: -------------------------------------------------------------------------------- 1 | class Quantity(object): 2 | def __init__(self, value, units): 3 | self.value = value 4 | self.units = units 5 | 6 | def __str__(self): 7 | return "{} {}".format(self.value, self.units) -------------------------------------------------------------------------------- /00RefactoringPython/ch10Simplify_Function_Call/i0rename_method.py: -------------------------------------------------------------------------------- 1 | from mycolor import show 2 | 3 | print('函数名称应该准确表达它的用途') 4 | print('取名:首先考虑给函数写一个注释,然后想办法将注释变成函数名称') 5 | 6 | def get_invoiceable_credit_limit(): 7 | print(show(' I am batter than getinvcdlimt')) 8 | 9 | get_invoiceable_credit_limit() -------------------------------------------------------------------------------- /01Python_Tricks/ch4Classes&OOP/i6class_vs_instance.py: -------------------------------------------------------------------------------- 1 | class Dog: 2 | num_legs = 4 # <- class var 3 | 4 | def __init__(self, name): 5 | self.name = name # instance var 6 | 7 | jack = Dog('Jack') 8 | jill = Dog('Jill') 9 | print(jack.num_legs, jill.num_legs) 10 | print(jack.name, jill.name) -------------------------------------------------------------------------------- /01Python_Tricks/ch5Common Data Structures in Python/i10LifoQueue.py: -------------------------------------------------------------------------------- 1 | from queue import LifoQueue 2 | 3 | s = LifoQueue() 4 | s.put('eat') 5 | s.put('sleep') 6 | s.put('code') 7 | 8 | print(s) 9 | 10 | print(s.get()) 11 | print(s.get()) 12 | print(s.get()) 13 | 14 | print(s.get_nowait()) 15 | print(s.get()) -------------------------------------------------------------------------------- /00RefactoringPython/ch12Big_Refactory/i01big_refactory.md: -------------------------------------------------------------------------------- 1 | 大型重构,有一件事需要注意:它会耗费相当长时间 2 | - 你只能一点点做你的工作,今天一点点,明天一点点
3 | - 过程中,你需要安排自己工作,只在需要添加新功能或者修改错误时候重构
4 | - 你不必要一开始就完成整个系统的重构,重构程度之需要满足其他任务的需要就行了
5 | - 大型重构可能话费相当长时间,他们并不像简单重构,能够立刻满意。
6 |   你必须有些信仰: 你每天都在使你自己的程序更加安全 7 | 8 | 9 | -------------------------------------------------------------------------------- /01Python_Tricks/ch6Looping & Iteration/i0Pythonic_Loops.py: -------------------------------------------------------------------------------- 1 | my_items = ['a', 'b', 'c'] 2 | 3 | i=0 4 | while i < len(my_items): 5 | print(my_items[i]) 6 | i += 1 7 | 8 | for i in range(len(my_items)): 9 | print(my_items[i]) 10 | 11 | for i, item in enumerate(my_items): 12 | print(f'{i}: {item}') -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch7Advanced Module Techniques/i1add_to_path_gotcha/good_imports.py: -------------------------------------------------------------------------------- 1 | print("Calling import package.module...") 2 | import package.module 3 | print("Calling import package.module as module...") 4 | import package.module as module 5 | print("Calling from package import module...") 6 | from package import module -------------------------------------------------------------------------------- /university_counselor/b9365_ProgrammingQs/day1_2start/main.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | from config import DevConfig 3 | 4 | app = Flask(__name__) 5 | app.config.from_object(DevConfig) 6 | 7 | 8 | @app.route('/') 9 | def home(): 10 | return '

Hello World!

' 11 | 12 | if __name__ == '__main__': 13 | app.run() 14 | -------------------------------------------------------------------------------- /00RefactoringPython/ch8Reorganize_Data/d2itools_cycle.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | 3 | 4 | shape_list = ["square", "triangle", "circle", "pentagon", "star", "octagon"] 5 | g = itertools.cycle(shape_list) 6 | for i in range(18): 7 | if i % len(shape_list) == 0: 8 | print('') 9 | shape = next(g) 10 | print("Drawing",shape) -------------------------------------------------------------------------------- /01Python_Tricks/ch2Patterns_for_Cleaner_Python/i5template_string.py: -------------------------------------------------------------------------------- 1 | from string import Template 2 | 3 | name = 'bob' 4 | errno = 123434 5 | t = Template('Hey, $name!') 6 | print(t.substitute(name=name)) 7 | 8 | teml_string = "Hey $name, ther is $error error!" 9 | t = Template(teml_string).substitute(name=name, error=hex(errno)) 10 | print(t) -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch7Advanced Module Techniques/i4package globals/globalspackage/globals.py: -------------------------------------------------------------------------------- 1 | # This module defines various global variables which can be shared any module 2 | # within the current package. 3 | 4 | # Define our package globals, giving them a suitable default value. 5 | 6 | language = None 7 | currency = None 8 | 9 | -------------------------------------------------------------------------------- /01Python_Tricks/ch3Effective Functions/i6decorator.py: -------------------------------------------------------------------------------- 1 | def null_decorator(func): 2 | return func 3 | 4 | def greet(): 5 | return "Hello!" 6 | 7 | a_greet = null_decorator(greet) 8 | r = a_greet() 9 | print(r) 10 | 11 | 12 | @null_decorator 13 | def greetA(): 14 | return "Hello A" 15 | 16 | 17 | ra = greetA() 18 | print(ra) 19 | -------------------------------------------------------------------------------- /01Python_Tricks/ch4Classes&OOP/i4namedtuple.py: -------------------------------------------------------------------------------- 1 | from collections import namedtuple 2 | 3 | print('namedtuples are a memory- efficient shortcut to defining \ 4 | an immutable class in Python manually.') 5 | 6 | Car = namedtuple('Car', [ 7 | 'color', 'mileage']) 8 | 9 | my_car = Car('red', 3456.7) 10 | print(my_car.color, my_car.mileage) -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch3Modules_and_Packages/i7import_globals.py: -------------------------------------------------------------------------------- 1 | print(globals()) 2 | 3 | def test(): 4 | print("hello") 5 | 6 | print(globals()) 7 | 8 | import string 9 | print(string.capwords("this is a test")) 10 | 11 | from string import capwords 12 | print(globals()) 13 | 14 | import math as math_ops 15 | print(math_ops.pi) -------------------------------------------------------------------------------- /Software Architecture with Python/2Writing Modifiable and Readable Code/i4_b_text_better.py: -------------------------------------------------------------------------------- 1 | import i4_a_text_better as a 2 | 3 | def common_words(filename1, filename2): 4 | """ Return common words across two input files """ 5 | 6 | lines1 = open(filename1).read() 7 | lines2 = open(filename2).read() 8 | 9 | return a.common_words(lines1, lines2) -------------------------------------------------------------------------------- /university_counselor/b9365_ProgrammingQs/day1_2start/manage.py: -------------------------------------------------------------------------------- 1 | from flask.ext.script import Manager, Server 2 | from main import app 3 | 4 | manager = Manager(app) 5 | manager.add_command("server", Server()) 6 | 7 | @manager.shell 8 | def make_shell_context(): 9 | return dict(app=app) 10 | 11 | if __name__ == "__main__": 12 | manager.run() 13 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch7Advanced Module Techniques/i4package globals/globalspackage/test.py: -------------------------------------------------------------------------------- 1 | # This module shows how to access and change global variables within a package. 2 | 3 | from . import globals 4 | 5 | def test(): 6 | globals.language = "EN" 7 | globals.currency = "NZD" 8 | print(globals.language, globals.currency) 9 | 10 | -------------------------------------------------------------------------------- /01Python_Tricks/ch3Effective Functions/i7decorator_modify_behavior.py: -------------------------------------------------------------------------------- 1 | def uppercase(func): 2 | def wrapper(): 3 | original_result = func() 4 | modified_result = original_result.upper() 5 | return modified_result 6 | return wrapper 7 | 8 | @uppercase 9 | def greet(): 10 | return 'Hello world!' 11 | 12 | r = greet() 13 | print(r) -------------------------------------------------------------------------------- /01Python_Tricks/ch5Common Data Structures in Python/i2defaultdict.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | dd = defaultdict(list) 4 | 5 | dd['dogs'].append('Rufus0') 6 | dd['dogs'].append('Rufus1') 7 | dd['dogs'].append('Rufus2') 8 | 9 | dd['cats'].append('cat0') 10 | dd['cats'].append('cat1') 11 | dd['cats'].append('cat2') 12 | print(dd['dogs'], dd['cats']) -------------------------------------------------------------------------------- /Software Architecture with Python/4Performance/Listings.txt: -------------------------------------------------------------------------------- 1 | 1. common_items.py 2 | 2. plot.py 3 | 3. primes.py 4 | 4. mem_profile_example.py 5 | 5. sub_string.py 6 | 6. objgraph_example.py 7 | 7. rotate.py 8 | 8. sub_string2.py 9 | 9. defaultdict_example.py 10 | 10. ordered.py 11 | 11. hound_words.py 12 | 12. chainmap_example.py 13 | 13. named.py 14 | 14. bloomtest.py 15 | -------------------------------------------------------------------------------- /01Python_Tricks/ch4Classes&OOP/i3clone.py: -------------------------------------------------------------------------------- 1 | print('shallow copy') 2 | 3 | xs = [[1, 2, 3], [4, 5, 6]] 4 | ys = list(xs) 5 | print(xs, ys) 6 | 7 | xs.append(['new sublist']) 8 | print(xs, ys) 9 | 10 | xs[1][0] = 'X' 11 | print(xs, ys) 12 | 13 | print('Making Deep Copies') 14 | import copy 15 | zs = copy.deepcopy(xs) 16 | print(xs, zs) 17 | 18 | xs[1][0] = 'XX' 19 | print(xs, zs) -------------------------------------------------------------------------------- /01Python_Tricks/ch5Common Data Structures in Python/i8records_structs_transfer.py: -------------------------------------------------------------------------------- 1 | car1 = { 2 | 'color': 'red', 3 | 'mileage': 3812.4, 4 | 'automatic': True, 5 | } 6 | 7 | car2 = { 8 | 'color': 'blue', 9 | 'mileage': 40231, 10 | 'automatic': False, 11 | } 12 | 13 | print(car2) 14 | 15 | car2['mileage'] = 12 16 | car2['windshield'] = 'broken' 17 | 18 | print(car2) -------------------------------------------------------------------------------- /university_counselor/b9158_SoftwareEngineeringTopic/requirement_docs/requirement.md: -------------------------------------------------------------------------------- 1 | 专业方向:软件工程 2 | 研究生/本科:研究生 3 | 课程编号及课程名称:软件工程 4 | 编程语言:不限 5 | 需求详细描述:出5道软件维护的题,按照教学要求和其他知识点的例题出题, 6 | 每道题要有典型人物(相关论点得科学家),所有题可以放在一个案例(也可以分开),每晚九点前有进度,老板要求没办法 7 | 8 | 需要出更复杂的,这边有和其他知识结合的东西 9 | 全部都按分析题来做 10 | 然后画不画uml图由老师们自己定 11 | 12 | 增加1道实践题(编程题,一个实际项目的部署维护的交互类题目, 13 | 然后把以前的知识点融合当材料给学生) -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch3Modules_and_Packages/i9relative_import/gui/widgets/editor/utils.py: -------------------------------------------------------------------------------- 1 | # from . import slider 2 | print('python3 package relative import is shit!!!') 3 | print(__package__) 4 | 5 | if __package__ is None or __package__ == '': 6 | #uses current directory visibility 7 | import slider 8 | else: 9 | #uses current package visibility 10 | from . import slider -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch7Advanced Module Techniques/i1add_to_path_gotcha/package/module.py: -------------------------------------------------------------------------------- 1 | # This is a test module to demonstrate why you should never add a package (or a 2 | # sub-directory of a package) directly to sys.path. 3 | # 4 | # When imported, this module prints out a message. This shows that the module 5 | # has been initialized. 6 | 7 | print("### Initializing module.py ###") 8 | -------------------------------------------------------------------------------- /01Python_Tricks/ch2Patterns_for_Cleaner_Python/i1complacent_comma.py: -------------------------------------------------------------------------------- 1 | names = ['Alice', 'Bob', 'Dilbert'] 2 | 3 | # following is better 4 | names = [ 5 | 'Alice', 6 | 'Bob', 7 | 'Dilbert' 8 | ] 9 | 10 | my_str = ('This is a super long string constant ' 11 | 'spread out across multiple lines. ' 12 | 'And look, no backslash characters needed!') 13 | print(my_str) -------------------------------------------------------------------------------- /01Python_Tricks/ch5Common Data Structures in Python/i4MappingProxyType.py: -------------------------------------------------------------------------------- 1 | from types import MappingProxyType 2 | 3 | writable = {'one': 1, 'two': 2} 4 | read_only = MappingProxyType(writable) 5 | 6 | writable['one'] = 10 7 | print('writable=', writable) 8 | 9 | print(read_only['one']) 10 | try: 11 | read_only['one'] = 23 12 | except Exception: 13 | print('Exception happened') 14 | pass -------------------------------------------------------------------------------- /01Python_Tricks/ch5Common Data Structures in Python/i5array.py: -------------------------------------------------------------------------------- 1 | import array 2 | 3 | arr = array.array('f', (1.0, 1.5, 2.0, 2.5)) 4 | 5 | print('arr[1], arr[2]=', arr[1], arr[2]) 6 | print(arr) 7 | arr[1] = 111 8 | print(arr) 9 | 10 | del arr[1] 11 | print(arr) 12 | 13 | arr.append(333) 14 | print(arr) 15 | 16 | try: 17 | arr[1] = 'hello' 18 | except: 19 | print('An error occured.') 20 | -------------------------------------------------------------------------------- /00RefactoringPython/ch7Move_attribute_between_Objects/i6introd_local_extension.py: -------------------------------------------------------------------------------- 1 | from dateutil import parser 2 | import datetime 3 | from mycolor import show 4 | 5 | class MyDate(datetime.datetime): 6 | def next_day(self): 7 | newstart = self + datetime.timedelta(days=1) 8 | return newstart 9 | 10 | d = MyDate(2018, 2, 24, 14, 37) 11 | print('new way:', show(d.next_day(), 'red')) -------------------------------------------------------------------------------- /01Python_Tricks/ch2Patterns_for_Cleaner_Python/i0assert.py: -------------------------------------------------------------------------------- 1 | def apply_discount(product, discount): 2 | price = int(product['price'] * (1.0 - discount)) 3 | assert 0 <= price <= product['price'] 4 | return price 5 | 6 | if __name__ == "__main__": 7 | shoes = {'name': 'Fancy shoes', 'price': 14900} 8 | r = apply_discount(shoes, 0.25) 9 | print(r) 10 | apply_discount(shoes, 2.0) -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch5Working with Module Patterns/i3wrappers/numpy_wrapper.py: -------------------------------------------------------------------------------- 1 | import numpy 2 | 3 | def new(num_rows, num_cols): 4 | return numpy.zeros((num_rows, num_cols), dtype=numpy.int32) 5 | 6 | def average(arrays_to_average): 7 | return numpy.mean(numpy.array(arrays_to_average), axis=0) 8 | 9 | def get_indices(array): 10 | return numpy.transpose(array.nonzero()) 11 | -------------------------------------------------------------------------------- /01Python_Tricks/ch3Effective Functions/i8multiple_decorators.py: -------------------------------------------------------------------------------- 1 | def strong(func): 2 | def wrapper(): 3 | return '' + func() + '' 4 | return wrapper 5 | 6 | def emphasis(func): 7 | def wrapper(): 8 | return '' + func() + '' 9 | return wrapper 10 | 11 | @strong 12 | @emphasis 13 | def greet(): 14 | return 'Hello!' 15 | 16 | r = greet() 17 | print(r) -------------------------------------------------------------------------------- /01Python_Tricks/ch4Classes&OOP/i5subclass_namedtuple.py: -------------------------------------------------------------------------------- 1 | from collections import namedtuple 2 | 3 | 4 | Car = namedtuple('Car', [ 5 | 'color', 'mileage']) 6 | 7 | class MyCarWithMethod(Car): 8 | def hexcolor(self): 9 | if self.color == 'red': 10 | return '#ff0000' 11 | else: 12 | return '#000000' 13 | 14 | c = MyCarWithMethod('red', 3456.7) 15 | print(c.hexcolor()) -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch3Modules_and_Packages/i9relative_import/gui/widgets/controls.py: -------------------------------------------------------------------------------- 1 | print('python3 package relative import is shit!!!') 2 | print(__package__) 3 | 4 | if __package__ is None or __package__ == '': 5 | #uses current directory visibility 6 | from editor import slider 7 | else: 8 | #uses current package visibility 9 | from .editor import slider 10 | 11 | 12 | 13 | slider.test_func() -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch1modular_program_with_py/i0stats/stats.py: -------------------------------------------------------------------------------- 1 | def init(): 2 | global _stats 3 | _stats = {} 4 | 5 | def event_occurred(event): 6 | global _stats 7 | try: 8 | _stats[event] =_stats[event] + 1 9 | except KeyError: 10 | _stats[event] = 1 11 | 12 | def get_stats(): 13 | global _stats 14 | # after py3.6 dict perserve order 15 | return _stats.items() -------------------------------------------------------------------------------- /00RefactoringPython/ch8Reorganize_Data/d0singleton.py: -------------------------------------------------------------------------------- 1 | class Customer_afterRF: 2 | instance = None 3 | 4 | def __init__(self, name): 5 | self.name = name 6 | 7 | @staticmethod 8 | def get_instnace(name): 9 | if Customer_afterRF.instance is None: 10 | Customer_afterRF.instance = Customer_afterRF(name) 11 | return Customer_afterRF.instance 12 | 13 | c2 = Customer_afterRF.get_instnace('c') -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch1modular_program_with_py/i0animals_test.py: -------------------------------------------------------------------------------- 1 | import i1animals.cow 2 | import i1animals.cat 3 | import i1animals.dog 4 | import i1animals.horse 5 | import i1animals.sheep 6 | 7 | 8 | def main(): 9 | i1animals.cow.speak() 10 | i1animals.cat.speak() 11 | i1animals.dog.speak() 12 | i1animals.horse.speak() 13 | i1animals.sheep.speak() 14 | 15 | if __name__ == "__main__": 16 | main() -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch1modular_program_with_py/i1animals_test.py: -------------------------------------------------------------------------------- 1 | import i1animals.cow 2 | import i1animals.cat 3 | import i1animals.dog 4 | import i1animals.horse 5 | import i1animals.sheep 6 | 7 | 8 | def main(): 9 | i1animals.cow.speak() 10 | i1animals.cat.speak() 11 | i1animals.dog.speak() 12 | i1animals.horse.speak() 13 | i1animals.sheep.speak() 14 | 15 | if __name__ == "__main__": 16 | main() -------------------------------------------------------------------------------- /01Python_Tricks/ch3Effective Functions/i15default_return.py: -------------------------------------------------------------------------------- 1 | def foo1(value): 2 | if value: 3 | return value 4 | else: 5 | return None 6 | 7 | def foo2(value): 8 | if value: 9 | return value 10 | else: 11 | return 12 | 13 | def foo3(value): 14 | if value: 15 | return value 16 | 17 | print(foo1(0), type(foo1(0)) ) 18 | print(foo2(0), type(foo2(0)) ) 19 | print(foo3(0), type(foo3(0)) ) -------------------------------------------------------------------------------- /01Python_Tricks/ch3Effective Functions/i13args_decorator.py: -------------------------------------------------------------------------------- 1 | import functools 2 | 3 | def trace(f): 4 | @functools.wraps(f) 5 | def decorated_function(*args, **kwargs): 6 | print(f,'#'*3, args, '@'*3, kwargs) 7 | result = f(*args, **kwargs) 8 | print(result) 9 | return decorated_function 10 | 11 | @trace 12 | def greet(greeting, name): 13 | return '{}, {}!'.format(greeting, name) 14 | 15 | greet('Hello', 'Bob') -------------------------------------------------------------------------------- /01Python_Tricks/ch3Effective Functions/i11args.py: -------------------------------------------------------------------------------- 1 | def foo(requried, *args, **kwargs): 2 | print('0 requried=', requried) 3 | if args: 4 | print('1 args=', args) 5 | if kwargs: 6 | print('2 kwargs=', kwargs) 7 | 8 | print(f'kwargs will collect extra keyword arguments as a \ 9 | dictionary because the parameter name has a ** prefix.') 10 | 11 | foo('hello') 12 | foo('hello', 1, 2, 3) 13 | foo('hello', 1, 2, 3, key1='value1', key2=999) -------------------------------------------------------------------------------- /01Python_Tricks/ch3Effective Functions/i12optional_args.py: -------------------------------------------------------------------------------- 1 | def bar(requried, *args, **kwargs): 2 | print('0 requried=', requried) 3 | if args: 4 | print('1 args=', args) 5 | if kwargs: 6 | print('2 kwargs=', kwargs) 7 | 8 | 9 | def foo(x, *args, **kwargs): 10 | kwargs['name'] = 'Alice' 11 | new_args = args + ('extra',) 12 | bar(x, *new_args , **kwargs) 13 | 14 | 15 | foo('hello', 1, 2, 3, key1='value1', key2=999, name='test') -------------------------------------------------------------------------------- /00RefactoringPython/ch3Bad Smell/i01bad_smell.md: -------------------------------------------------------------------------------- 1 | 如果尿布臭了,就换掉它 2 | - 重复代码 3 | - 过长函数 4 | - 过大的类 5 | - 过长的参数列表 6 | ···有了对象,你不必把函数需要的所有东西都参数传递给它了 7 | 只需要传给足够的,让函数能从中获取自己所须就行了。
8 | ···这里有个重要例外,就是明显不希望‘被调用对象’和‘较大对象’之间某种依赖关系 9 | - 发散式变化 10 | ···我们希望软件一代需要修改,能够跳到系统某一点,只在该处修改。 11 | - 霰弹式修改 12 | ···和发散式相反,你需要在不同类做许多小修改,不但很难找,也很容易忘记某个修改。 13 | - 依恋情结 14 | ···将总是一起变化的东西放在一块。保持变化只在一地发生 15 | - 数据泥团 16 | ···删掉众多数据中的一项,其他数据没有因而失去意义? 如果它们不在有意义,就是一个明确 17 | 的信号:你应该为它们产生一个新对象。 18 | -------------------------------------------------------------------------------- /00RefactoringPython/ch6Reorganize_Functions/i1inline_method.py: -------------------------------------------------------------------------------- 1 | def get_rating(): 2 | return 2 if more_than_5_late_deliveries(10) else 1 3 | 4 | def more_than_5_late_deliveries(number_of_late_deliveries): 5 | return number_of_late_deliveries > 5 6 | 7 | 8 | print("inline method: 在函数调用点插入函数本体,然后移除函数。\ 9 | 间接性可能带来帮助,但非必要的间接性总是让人不舒服") 10 | 11 | def get_rating(): 12 | number_of_late_deliveries = 10 13 | return 2 if (number_of_late_deliveries > 5) else 1 -------------------------------------------------------------------------------- /01Python_Tricks/ch2Patterns_for_Cleaner_Python/i4string_format.py: -------------------------------------------------------------------------------- 1 | errno = 50159747054 2 | name = 'Bob' 3 | 4 | print('Hello, {}'.format(name)) 5 | print('Hello, {name} there is a 0x{errno:x}'.format(name=name, errno=errno)) 6 | 7 | print(f'Hello, {name}!') 8 | 9 | a = 5 10 | b = 10 11 | print(f'Five + ten is {a + b} and not {2 * (a + b)}') 12 | 13 | def greet(name, question): 14 | return f"Hello {name}! How 's it {question}?" 15 | 16 | print(greet('bob', 'going')) -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch5Working with Module Patterns/i5plugins/load_plugin.py: -------------------------------------------------------------------------------- 1 | import importlib 2 | import sys 3 | import os.path 4 | 5 | plugin_name = input("Load plugins: ") 6 | if plugin_name != "": 7 | print("os.path.dirname(__file__)=", os.path.dirname(__file__)) 8 | plugin_dir = os.path.join(os.path.dirname(__file__), "plugins") 9 | sys.path.append(plugin_dir) 10 | plugin = importlib.import_module(plugin_name) 11 | plugin.say_hello() -------------------------------------------------------------------------------- /Software Architecture with Python/3Testability/Listings.txt: -------------------------------------------------------------------------------- 1 | 1. url_data.py 2 | 2. fakelogger.py 3 | 3. datetimehelper.py 4 | 4. test_datetimehelper1.py 5 | 5. test_datetimehelper2.py 6 | 6. test_datetimehelper_object.py 7 | 7. textsearcher.py 8 | 8. test_textsearch.py 9 | 9. factorial.py 10 | 10. selenium_testcase.py 11 | 11. test_palindrome1.py 12 | 12. palindrome1.py 13 | 13. test_palindrome2.py 14 | 14. palindrome2.py 15 | 15. test_palindrome3.py 16 | 16. palindrome3.py 17 | -------------------------------------------------------------------------------- /00RefactoringPython/ch8Reorganize_Data/i3replace_array_with_object.py: -------------------------------------------------------------------------------- 1 | from mycolor import show 2 | 3 | row = [] 4 | row.append('Livepool') 5 | row.append(15) 6 | 7 | print(row[0], row[1]) 8 | print(show('数组是以某种顺序容纳一组相似的对象'), 9 | '有时候很难记第一个元素是人名,对象可以用字段名称和\ 10 | 函数传达这样的信息,无须死机它') 11 | 12 | class Performance: 13 | def __init__(self, name, wins): 14 | self.name = name 15 | self.wins = wins 16 | 17 | r = Performance('Livepool', 15) 18 | print(r.name, r.wins) -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch7Advanced Module Techniques/i1add_to_path_gotcha/bad_imports.py: -------------------------------------------------------------------------------- 1 | import os.path 2 | import sys 3 | 4 | cur_dir = os.path.abspath(os.path.dirname(__file__)) 5 | package_dir = os.path.join(cur_dir, "package") 6 | 7 | sys.path.insert(1, package_dir) # Add package directly to path. DON'T DO THIS! 8 | 9 | print("Calling import package.module as module...") 10 | import package.module as module 11 | print("Calling import module...") 12 | import module -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch8Testing and Deploying Modules/i2test-package/erikwestra_test_package/test.py: -------------------------------------------------------------------------------- 1 | # Simple test module for the "package" package. 2 | 3 | import string 4 | import random 5 | 6 | def random_name(): 7 | chars = [] 8 | for i in range(random.randrange(3, 10)): 9 | chars.append(random.choice(string.ascii_letters)) 10 | return "".join(chars) 11 | 12 | 13 | def run(): 14 | for i in range(10): 15 | print(random_name()) 16 | 17 | -------------------------------------------------------------------------------- /Software Architecture with Python/2Writing Modifiable and Readable Code/i0readability_loop.py: -------------------------------------------------------------------------------- 1 | 2 | def bad_python_loop(seq): 3 | for idx in range(len(seq)): 4 | item = seq[idx] 5 | print(idx, '=>', item) 6 | 7 | def better_loop(seq): 8 | for idx, item in enumerate(seq): 9 | print(idx, '=>', item) 10 | 11 | if __name__ == '__main__': 12 | seq = ['abel', 'love', 'family'] 13 | bad_python_loop(seq) 14 | print('#' * 20) 15 | better_loop(seq) -------------------------------------------------------------------------------- /00RefactoringPython/ch6Reorganize_Functions/myfinal.py: -------------------------------------------------------------------------------- 1 | # python 没有final, 自己造一个只读的 2 | class MyPyFinal( object ): 3 | def __init__(self, value): 4 | self.value= value 5 | 6 | def __str__(self): 7 | return str(self.value) 8 | 9 | def r(self): 10 | # return result 11 | return self.value 12 | 13 | def set(self, value): 14 | if self.value is not None: 15 | raise Exception( "Read Only var.") 16 | self.value= value 17 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch7Advanced Module Techniques/i6stringutils/stringutils.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | def extract_numbers(s): 4 | pattern = r'[+-]?\d+(?:\.\d+)?' 5 | numbers = [] 6 | for match in re.finditer(pattern, s): 7 | number = s[match.start():match.end()] 8 | numbers.append(number) 9 | return numbers 10 | 11 | 12 | if __name__ == "__main__": 13 | extract = extract_numbers("I like 2018 06 26 11:47, future is coming!") 14 | print(extract) -------------------------------------------------------------------------------- /01Python_Tricks/ch3Effective Functions/i5lambdas.py: -------------------------------------------------------------------------------- 1 | add = lambda x, y: x + y 2 | 3 | r = add(5, 3) 4 | print(r) 5 | 6 | 7 | tuples = [(1, 'd'), (2, 'b'), (4, 'a'), (3, 'c')] 8 | r1 = sorted(tuples, key=lambda x: x[1]) 9 | print(r1) 10 | 11 | r2 = sorted(range(-5, 6), key=lambda x: x * x) 12 | print(r2) 13 | 14 | def make_adder(n): 15 | return lambda x: x + n 16 | 17 | plus_3 = make_adder(3) 18 | plus_5 = make_adder(5) 19 | print('plus_3(4)=', plus_3(4)) 20 | print('plus_5(4)=', plus_5(4)) -------------------------------------------------------------------------------- /00RefactoringPython/ch10Simplify_Function_Call/i6introd_parameter_obj.py: -------------------------------------------------------------------------------- 1 | from mycolor import show 2 | 3 | def test(start, end): 4 | print('do things to ', start, end) 5 | 6 | test(10, 100) 7 | print('-------------改造开始-----------------') 8 | 9 | class Range: 10 | def __init__(self, start, end): 11 | self.start = start 12 | self.end = end 13 | 14 | def test_afterRF(range): 15 | print(show('do things to ', 'red'), range.start, range.end) 16 | 17 | test_afterRF(Range(10, 100)) -------------------------------------------------------------------------------- /Software Architecture with Python/4Performance/chainmap_example.py: -------------------------------------------------------------------------------- 1 | # Code Listing #10 2 | 3 | """ 4 | 5 | Example of using ChainMap 6 | 7 | """ 8 | 9 | from collections import ChainMap 10 | 11 | d1 = {i:i for i in range(100)} 12 | d2 = {i:i*i for i in range(100)} 13 | c = ChainMap(d1, d2) 14 | # Older value still accessible 15 | print(c[5]) 16 | print(c.maps[0][5]) 17 | # Updating d1 with d2 18 | d1.update(d2) 19 | print(d1) 20 | # Olde value got updated 21 | print(c[5]) 22 | print(c.maps[0][5]) 23 | -------------------------------------------------------------------------------- /01Python_Tricks/ch3Effective Functions/i0function_are_firstclass.py: -------------------------------------------------------------------------------- 1 | def yell(text): 2 | print(text.upper() + "!") 3 | 4 | yell('hello') 5 | 6 | bark = yell 7 | 8 | bark('woof') 9 | 10 | try: 11 | del yell 12 | yell('hello again') 13 | except: 14 | print("This is an error message in yell() !") 15 | 16 | bark('hey') 17 | 18 | print('Python attaches a string identifier to every function\ 19 | at creation time for debugging purposes') 20 | print('bark.__name__ = ', bark.__name__) 21 | 22 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch5Working with Module Patterns/i6hook_client.py: -------------------------------------------------------------------------------- 1 | import i6hook_login_module 2 | 3 | 4 | def my_login_hook(username): 5 | print('#'*5, username , '*'*10) 6 | 7 | 8 | 9 | if __name__ == "__main__": 10 | i6hook_login_module.set_login_hook(my_login_hook) 11 | i6hook_login_module.login("abel", "1234") 12 | print('start# cur_user=', i6hook_login_module.cur_user) 13 | i6hook_login_module.logout() 14 | print('end # cur_user=', i6hook_login_module.cur_user) -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch8Testing and Deploying Modules/i1test_quantities/quantities/quantity.py: -------------------------------------------------------------------------------- 1 | """ quantities.quantitity 2 | 3 | This module encapsulates the concept of a `quantity`. A quantity is a 4 | number along with the units that number is in. 5 | """ 6 | class Quantity(object): 7 | def __init__(self, value, units): 8 | self.value = value 9 | self.units = units 10 | 11 | def __str__(self): 12 | return "{} {}".format(self.value, self.units) 13 | 14 | -------------------------------------------------------------------------------- /Software Architecture with Python/3Testability/test_datetimehelper_object.py: -------------------------------------------------------------------------------- 1 | # Code Listing - #6 2 | 3 | """ Module test_datetimehelper_object - Simple test case with test class derived from object """ 4 | 5 | import datetimehelper 6 | 7 | class TestDateTimeHelper(object): 8 | 9 | def test_us_india_conversion(self): 10 | """ Test us=>india date format conversion """ 11 | 12 | obj = datetimehelper.DateTimeHelper() 13 | assert obj.us_to_indian('1/1/1') == '01/01/2001' 14 | 15 | -------------------------------------------------------------------------------- /00RefactoringPython/ch6Reorganize_Functions/i2inline_temp_var.py: -------------------------------------------------------------------------------- 1 | class Order: 2 | def __init__(self, price=0): 3 | self.price = price 4 | 5 | def base_price(self): 6 | return self.price 7 | 8 | def demo(): 9 | an_order = Order() 10 | base_price = an_order.base_price() 11 | return base_price > 1000 12 | 13 | 14 | print('一个临时变量,只被简单表达赋值一次,而它妨碍了其他重构\ 15 | 将所有对该变量的引用作用,替换为对它赋值的表达式自身') 16 | 17 | def demo_refactory(): 18 | an_order = Order() 19 | return an_order.base_price() > 1000 20 | 21 | 22 | -------------------------------------------------------------------------------- /00RefactoringPython/ch8Reorganize_Data/i1replace_data_with_obj.py: -------------------------------------------------------------------------------- 1 | from mycolor import show 2 | 3 | class Order: 4 | def __init__(self, customer): 5 | self.customer = customer 6 | 7 | 8 | d = Order('xiaoming') 9 | print('old:', show(d.customer)) 10 | 11 | class Order_afterRF: 12 | def __init__(self, customer): 13 | self.customer = customer 14 | 15 | class Customer: 16 | def __init__(self, name): 17 | self.name = name 18 | 19 | d1 = Order_afterRF(Customer('xiaoming1')) 20 | print(show(d1.customer.name, 'red')) -------------------------------------------------------------------------------- /university_counselor/b9365_ProgrammingQs/day1_2end/manage.py: -------------------------------------------------------------------------------- 1 | from flask_script import Manager, Server 2 | from flask_migrate import Migrate, MigrateCommand 3 | from main import app, db, User, Post, Tag 4 | 5 | migrate = Migrate(app, db) 6 | 7 | 8 | manager = Manager(app) 9 | manager.add_command("server", Server()) 10 | manager.add_command('db', MigrateCommand) 11 | 12 | @manager.shell 13 | def make_shell_context(): 14 | return dict(app=app, db=db, User=User, Post=Post, Tag=Tag) 15 | 16 | if __name__ == "__main__": 17 | manager.run() -------------------------------------------------------------------------------- /00RefactoringPython/ch10Simplify_Function_Call/i3parameter_to_explicit_method.py: -------------------------------------------------------------------------------- 1 | from mycolor import show 2 | 3 | def set_value(name, value): 4 | if name == 'height': 5 | _height = value 6 | return 7 | if name == 'width': 8 | _width = value 9 | return 10 | assert False, 'should never be here' 11 | 12 | set_value('height', 10) 13 | print('-------------改造开始-----------------') 14 | 15 | def set_height(arg): 16 | _height = arg 17 | 18 | def set_width(arg): 19 | _width = arg 20 | 21 | set_height(10) -------------------------------------------------------------------------------- /00RefactoringPython/ch8Reorganize_Data/i6magicnumber_to_symbolic_constant.py: -------------------------------------------------------------------------------- 1 | from mycolor import show 2 | 3 | def potential_energy(mass, height): 4 | return mass * 9.81 * height 5 | 6 | old = potential_energy(10, 100) 7 | print('magic number way:', show(old)) 8 | print(show('开始改造'),'- > -'*5) 9 | 10 | GRAVITATIONAL_CONSTANT = 9.81 11 | 12 | def potential_energy_afterRF(mass, height): 13 | return mass * GRAVITATIONAL_CONSTANT * height 14 | 15 | new = potential_energy_afterRF(10, 100) 16 | print('symbolic constant way:', show(new, 'red')) -------------------------------------------------------------------------------- /01Python_Tricks/ch2Patterns_for_Cleaner_Python/i2with.py: -------------------------------------------------------------------------------- 1 | with open('hello.txt', 'w') as f: 2 | f.write('hello, world!') 3 | 4 | class ManagedFile: 5 | def __init__(self, name): 6 | self.name = name 7 | 8 | def __enter__(self): 9 | self.file = open(self.name, 'w') 10 | return self.file 11 | 12 | def __exit__(self, exc_type, exc_val, exc_tb): 13 | if self.file: 14 | self.file.close() 15 | 16 | with ManagedFile('hello.txt') as f: 17 | f.write('hello, world!') 18 | f.write('bye now') -------------------------------------------------------------------------------- /Software Architecture with Python/3Testability/palindrome1.py: -------------------------------------------------------------------------------- 1 | # Code Listing - #12 2 | 3 | """ 4 | Module palindrome - Returns whether an input string is palindrome or not 5 | """ 6 | 7 | # Note - this is the first version of palindrome, so called palindrome1.py 8 | 9 | def is_palindrome(in_string): 10 | """ Returns True whether in_string is palindrome, False otherwise """ 11 | 12 | # Case insensitive 13 | in_string = in_string.lower() 14 | # Check if string is same as in reverse 15 | return in_string == in_string[-1::-1] 16 | -------------------------------------------------------------------------------- /00RefactoringPython/ch6Reorganize_Functions/i0extract_method.py: -------------------------------------------------------------------------------- 1 | def printBanner(): 2 | print('printBanner()') 3 | 4 | def printOwing(amount): 5 | printBanner() 6 | name = 'abel' 7 | print("name:" + name) 8 | print("amount:" + amount) 9 | 10 | print("Etract Method :当我看到一个过长的函数或者一段需要注释才能理解的代码,我们放入独立函数") 11 | def print_detail(amount, name): 12 | print("name:" + name) 13 | print("amount:" + amount) 14 | 15 | def printOwing_afterRefactory(amount): 16 | printBanner() 17 | name = 'abel' 18 | print_detail(amount, name) 19 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch8Testing and Deploying Modules/i2test-package/setup.py: -------------------------------------------------------------------------------- 1 | from distutils.core import setup 2 | 3 | setup(name="erikwestra-test-package", 4 | packages=["erikwestra_test_package"], 5 | version="1.0", 6 | description="Test Package", 7 | author="Erik Westra", 8 | author_email="ewestra@gmail.com", 9 | url="https://github.com/erikwestra/test-package", 10 | download_url="https://github.com/erikwestra/test-package/tarball/1.0", 11 | keywords=["test", "python"], 12 | classifiers=[]) 13 | 14 | -------------------------------------------------------------------------------- /Software Architecture with Python/4Performance/named.py: -------------------------------------------------------------------------------- 1 | # Code Listing #11 2 | 3 | """ 4 | 5 | Example of using namedtuple 6 | 7 | """ 8 | 9 | from collections import namedtuple 10 | 11 | Employee = namedtuple('Employee', 'name, age, gender, title, department') 12 | print(Employee) 13 | # Create an employee 14 | jack = Employee('Jack',25,'M','Programmer','Engineering') 15 | print(jack) 16 | 17 | for field in jack: 18 | print(field) 19 | 20 | # This will raise an error 21 | # jack.age=32 22 | 23 | # This works fine 24 | print(jack._replace(age=32)) 25 | 26 | -------------------------------------------------------------------------------- /Software Architecture with Python/4Performance/rotate.py: -------------------------------------------------------------------------------- 1 | # Code Listing #6 2 | 3 | """ 4 | 5 | Example with collections.deque for rotating sequences 6 | 7 | """ 8 | 9 | from collections import deque 10 | 11 | def rotate_seq1(seq1, n): 12 | """ Rotate a sequence left by n """ 13 | # E.g: rotate([1,2,3,4,5], 2) => [4,5,1,2,3] 14 | 15 | k = len(seq1) - n 16 | return seq1[k:] + seq1[:k] 17 | 18 | def rotate_seq2(seq1, n): 19 | """ Rotate a sequence left by n using deque """ 20 | 21 | d = deque(seq1) 22 | d.rotate(n) 23 | return d 24 | -------------------------------------------------------------------------------- /01Python_Tricks/ch3Effective Functions/i3func_capture_localstate.py: -------------------------------------------------------------------------------- 1 | def get_speak_func(text, volume): 2 | def whisper(): 3 | return text.lower() + '...' 4 | 5 | def yell(): 6 | return text.upper() + '!!!' 7 | 8 | if volume > 0.5: 9 | return yell 10 | else: 11 | return whisper 12 | 13 | r = get_speak_func('hello world', 0.7)() 14 | print(r) 15 | 16 | 17 | def make_adder(n): 18 | def add(x): 19 | return x + n 20 | return add 21 | 22 | plus_3 = make_adder(3) 23 | plus_5 = make_adder(5) 24 | print(plus_3(4), plus_5(4)) -------------------------------------------------------------------------------- /Software Architecture with Python/2Writing Modifiable and Readable Code/i1_a1.py: -------------------------------------------------------------------------------- 1 | # 2 | 3 | """ Module A - Implement functions that operate on series of numbers """ 4 | 5 | # 6 | def squares(narray): 7 | return pow_n(narray, 2) 8 | 9 | def cubes(narray): 10 | return pow_n(narray, 3) 11 | 12 | def pow_n(narray, n): 13 | return [pow(x, n) fox x in narray] 14 | 15 | def frequency(string, word): 16 | word_l = word.lower() 17 | string_l = string.lower() 18 | 19 | words = string_l.split() 20 | count = w.count(word_l) 21 | return 100 * count / len(words) -------------------------------------------------------------------------------- /00RefactoringPython/ch6Reorganize_Functions/i5split_temp_var.py: -------------------------------------------------------------------------------- 1 | from termcolor import colored 2 | from myfinal import MyPyFinal 3 | 4 | 5 | def show(s,color='green'): 6 | print(colored(s, color, attrs=['reverse', 'blink'])) 7 | 8 | height = 100 9 | width = 50 10 | temp = 2 * (height * width) 11 | print(temp) 12 | temp = height * width 13 | print(temp) 14 | 15 | show('当你程序中某个临时变量被赋值超过一次,但不是♻️循环变量,也不用于收集计算结果。') 16 | show('针对每次赋值,创造一个独立、对应的临时变量', 'red') 17 | 18 | prerimeter = MyPyFinal(2 * height * width).r() 19 | print(prerimeter) 20 | area = MyPyFinal(height * width).r() 21 | print(area) -------------------------------------------------------------------------------- /university_counselor/b9365_ProgrammingQs/day3_5end/static/js/npm.js: -------------------------------------------------------------------------------- 1 | // This file is autogenerated via the `commonjs` Grunt task. You can require() this file in a CommonJS environment. 2 | require('../../js/transition.js') 3 | require('../../js/alert.js') 4 | require('../../js/button.js') 5 | require('../../js/carousel.js') 6 | require('../../js/collapse.js') 7 | require('../../js/dropdown.js') 8 | require('../../js/modal.js') 9 | require('../../js/tooltip.js') 10 | require('../../js/popover.js') 11 | require('../../js/scrollspy.js') 12 | require('../../js/tab.js') 13 | require('../../js/affix.js') -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch4Using Modules for Real-World/charter/chart.py: -------------------------------------------------------------------------------- 1 | 2 | def new_chart(): 3 | return {} 4 | 5 | def set_title(chart, title): 6 | chart['title'] = title 7 | 8 | def set_x_axis(chart, x_axis): 9 | chart['x_axis'] = x_axis 10 | 11 | def set_y_axis(chart, minimum, maximum, labels): 12 | chart['y_min'] = minimum 13 | chart['y_max'] = maximum 14 | chart['y_labels'] = labels 15 | 16 | def set_series_type(chart, series_type): 17 | chart['series_type'] = series_type 18 | 19 | def set_series(chart, series): 20 | chart['series'] = series -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch7Advanced Module Techniques/i2package configuration/configpackage/interface.py: -------------------------------------------------------------------------------- 1 | # This module defines the public interface for our "configpackage" package. 2 | 3 | def init(config): 4 | global settings 5 | 6 | settings = {} 7 | settings['log_errors'] = config.get("log_errors", False) 8 | settings['db_password'] = config.get("db_password", "") 9 | 10 | 11 | def test(): 12 | global settings 13 | 14 | if settings['log_errors']: 15 | print("Error logging enabled") 16 | else: 17 | print("Error logging disabled") 18 | 19 | -------------------------------------------------------------------------------- /Software Architecture with Python/2Writing Modifiable and Readable Code/i2_a1_better.py: -------------------------------------------------------------------------------- 1 | # 2 | 3 | """ Module A - Implement functions that operate on series of numbers """ 4 | 5 | # 6 | def squares(narray): 7 | return pow_n(narray, 2) 8 | 9 | def cubes(narray): 10 | return pow_n(narray, 3) 11 | 12 | def pow_n(narray, n): 13 | return [pow(x, n) fox x in narray] 14 | 15 | # def frequency(string, word): 16 | # word_l = word.lower() 17 | # string_l = string.lower() 18 | 19 | # words = string_l.split() 20 | # count = w.count(word_l) 21 | # return 100 * count / len(words) -------------------------------------------------------------------------------- /university_counselor/b9365_ProgrammingQs/day3_5static/static/js/npm.js: -------------------------------------------------------------------------------- 1 | // This file is autogenerated via the `commonjs` Grunt task. You can require() this file in a CommonJS environment. 2 | require('../../js/transition.js') 3 | require('../../js/alert.js') 4 | require('../../js/button.js') 5 | require('../../js/carousel.js') 6 | require('../../js/collapse.js') 7 | require('../../js/dropdown.js') 8 | require('../../js/modal.js') 9 | require('../../js/tooltip.js') 10 | require('../../js/popover.js') 11 | require('../../js/scrollspy.js') 12 | require('../../js/tab.js') 13 | require('../../js/affix.js') -------------------------------------------------------------------------------- /00RefactoringPython/ch7Move_attribute_between_Objects/i4hide_delegate.py: -------------------------------------------------------------------------------- 1 | from mycolor import show 2 | 3 | class Person: 4 | def __init__(self, name, dpmt): 5 | self.name = name 6 | self.department = dpmt 7 | 8 | def __str__(self): 9 | return 'name:' + self.name 10 | 11 | 12 | class Department: 13 | def __init__(self, chargecode, manager): 14 | self.chargecode = chargecode 15 | self.manager = manager 16 | 17 | john = Person('john1', Department('01', Person('bob', None))) 18 | should_way_manager = john.department.manager 19 | print(show(should_way_manager)) -------------------------------------------------------------------------------- /00RefactoringPython/ch9Simplify_Conditional_Expression/i3consolidate_duplicate_conditional.py: -------------------------------------------------------------------------------- 1 | import random 2 | from mycolor import show 3 | 4 | price = 9.8 5 | 6 | def is_special_deal(): 7 | return random.choice([True, False]) 8 | 9 | def send(): 10 | print('send') 11 | 12 | if is_special_deal(): 13 | total = price * 0.5 14 | send() 15 | else: 16 | total = price * 0.8 17 | send() 18 | 19 | print('在表达式的每个分支上又相同的代码,将重复代码搬移到表达式之外') 20 | print('- · - - · - - · - - · - ') 21 | 22 | 23 | if is_special_deal(): 24 | total = price * 0.5 25 | else: 26 | total = price * 0.8 27 | send() -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch4Using Modules for Real-World/test_charter.py: -------------------------------------------------------------------------------- 1 | import charter 2 | 3 | 4 | chart = charter.new_chart() 5 | charter.set_title(chart, "Wild Parrot Deaths per Year") 6 | charter.set_x_axis(chart, 7 | ["2009", "2010", "2011", "2012", "2013", 8 | "2014", "2015"]) 9 | charter.set_y_axis(chart, minimum=0, maximum=700, 10 | labels=[0, 100, 200, 300, 400, 500, 600, 700]) 11 | charter.set_series(chart, [250, 270, 510, 420, 680, 580, 450]) 12 | charter.set_series_type(chart, "bar") 13 | 14 | charter.generate_chart(chart, "chart.pdf") -------------------------------------------------------------------------------- /Software Architecture with Python/4Performance/i1plot.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | 3 | def plot(xdata, ydata): 4 | """ Plot a range of ydata (on y-axis) against xdata (on x-axis) """ 5 | 6 | plt.plot(xdata, ydata) 7 | plt.show() 8 | 9 | def plot_many(xdata, ydatas): 10 | """ Plot a sequence of ydatas (on y-axis) against xdata (on x-axis) """ 11 | 12 | for ydata in ydatas: 13 | plt.plot(xdata, ydata) 14 | plt.show() 15 | 16 | 17 | if __name__ == "__main__": 18 | xdata = [100, 200, 400, 800, 1000] 19 | ydata = [117, 483, 1920, 7823, 12395] 20 | plot(xdata, ydata) -------------------------------------------------------------------------------- /01Python_Tricks/ch3Effective Functions/i2nested_func.py: -------------------------------------------------------------------------------- 1 | def speak(text): 2 | def whisper(t): 3 | return t.lower() + '...' 4 | 5 | return '#' + whisper(text) + '#' 6 | 7 | print(speak('Hello world')) 8 | 9 | 10 | def get_speak_func(volume): 11 | def whisper(text): 12 | return text.lower() + '...' 13 | def yell(text): 14 | return text.upper() + '!!!' 15 | 16 | if volume > 0.5: 17 | return yell 18 | else: 19 | return whisper 20 | 21 | print(get_speak_func(1)) 22 | print(get_speak_func(0.1)) 23 | speak_func = get_speak_func(0.7) 24 | print(speak_func('hello')) 25 | 26 | -------------------------------------------------------------------------------- /Software Architecture with Python/3Testability/palindrome2.py: -------------------------------------------------------------------------------- 1 | # Code Listing - #14 2 | 3 | """ 4 | Module palindrome - Returns whether an input string is palindrome or not 5 | """ 6 | # Note - this is the second version of palindrome, so called palindrome2.py 7 | 8 | import re 9 | 10 | def is_palindrome(in_string): 11 | """ Returns True whether in_string is palindrome, False otherwise """ 12 | 13 | # Case insensitive 14 | in_string = in_string.lower() 15 | # Purge spaces 16 | in_string = re.sub('\s+','', in_string) 17 | # Check if string is same as in reverse 18 | return in_string == in_string[-1::-1] 19 | -------------------------------------------------------------------------------- /01Python_Tricks/ch3Effective Functions/i14arg_unpack.py: -------------------------------------------------------------------------------- 1 | def print_vector(x, y, z): 2 | print('here# <%s, %s, %s>' %(x, y, z)) 3 | 4 | print_vector(0, 1, 0) 5 | 6 | tuple_vec = (1, 0, 1) 7 | print_vector(tuple_vec[0], tuple_vec[1], tuple_vec[2]) 8 | 9 | print('Function Argument Unpacking using the * operator') 10 | print_vector(*tuple_vec) 11 | 12 | list_vec = [1, 1, 1] 13 | print_vector(*list_vec) 14 | 15 | genexpr = (x * x for x in range(10, 13)) 16 | 17 | print_vector(*genexpr) 18 | 19 | dict_vec = {'x': 10, 'y': 20, 'z': 30} 20 | print('** operator for unpacking keyword arguments from dictionaries.') 21 | print_vector(**dict_vec) -------------------------------------------------------------------------------- /Software Architecture with Python/4Performance/objgraph_example.py: -------------------------------------------------------------------------------- 1 | # Code Listing #6 2 | 3 | """ 4 | 5 | Objgraph example code. 6 | 7 | Make sure you install graphviz and xdot before running this. 8 | 9 | """ 10 | 11 | import objgraph 12 | 13 | class MyRefClass(object): 14 | pass 15 | 16 | ref=MyRefClass() 17 | class C(object):pass 18 | 19 | c_objects=[] 20 | for i in range(100): 21 | c=C() 22 | c.ref=ref 23 | c_objects.append(c) 24 | 25 | import pdb; pdb.set_trace() 26 | 27 | # Run this code in pdb prompt, you just need to press 'c' 28 | objgraph.show_backrefs(ref, max_depth=2, too_many=2, filename='refs.png') 29 | 30 | -------------------------------------------------------------------------------- /00RefactoringPython/ch4Build Test System/test_i0unnecessary_math.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from i0unnecessary_math import multiply 3 | 4 | # 使用 unittest 的标准流程为: 5 | 6 | # 从 unittest.TestCase 派生一个子类 7 | # 在类中定义各种以 “test_” 打头的方法 8 | # 通过 unittest.main() 函数来启动测试 9 | 10 | # https://www.jianshu.com/p/0b04cb0450ee 11 | 12 | class TestUnnecessaryMath(unittest.TestCase): 13 | def setUp(self): 14 | pass 15 | def test_number_3_4(self): 16 | self.assertEqual(multiply(3,4),12) 17 | 18 | def test_string_a_3(self): 19 | self.assertEqual(multiply('a',3),'aaa') 20 | 21 | 22 | if __name__ == "__main__": 23 | unittest.main() 24 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch1modular_program_with_py/i3cache/test_cache.py: -------------------------------------------------------------------------------- 1 | import random 2 | import string 3 | import cache 4 | 5 | def random_string(length): 6 | s = '' 7 | for i in range(length): 8 | s = s + random.choice(string.ascii_letters) 9 | return s 10 | 11 | 12 | cache.init() 13 | 14 | for n in range(1000): 15 | while True: 16 | key = random_string(20) 17 | if cache.contains(key): 18 | continue 19 | else: 20 | break 21 | value = random_string(20) 22 | cache.set(key, value) 23 | print("After {} iterations, cache has {} entries".format(n+1, cache.size())) -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch7Advanced Module Techniques/i3package data/datapackage/interface.py: -------------------------------------------------------------------------------- 1 | # This module implements the public interface for the "datapackage" directory. 2 | # 3 | # This demonstrates how a Python package can contain data files, which can then 4 | # be accessed as desired. 5 | 6 | import os.path 7 | 8 | def get_phone_numbers(): 9 | phone_numbers = [] 10 | cur_dir = os.path.abspath(os.path.dirname(__file__)) 11 | file = open(os.path.join(cur_dir, "data", "phone_numbers.txt")) 12 | for line in file: 13 | phone_numbers.append(line.strip()) 14 | file.close() 15 | return phone_numbers 16 | 17 | -------------------------------------------------------------------------------- /00RefactoringPython/ch9Simplify_Conditional_Expression/i8introd_assertion.py: -------------------------------------------------------------------------------- 1 | import math 2 | from mycolor import show 3 | 4 | def special_calculate(x): 5 | if x > 0: 6 | return math.sqrt(x) * 10 7 | else: 8 | raise ValueError('Error here!') 9 | 10 | t0 = special_calculate(4) 11 | # t1 = special_calculate(-4) 12 | print('某段代码对程序状态作出某种假设' + 13 | show(' 用断言明确表现这种假设')) 14 | print('- · - - · 开始改造 - - · - - · - ') 15 | 16 | 17 | def special_calculate_with_assert(x): 18 | assert x > 0 19 | return math.sqrt(x) * 10 20 | 21 | t2 = special_calculate_with_assert(4) 22 | # t2 = special_calculate_with_assert(-4) 23 | print(t0, t2) -------------------------------------------------------------------------------- /Software Architecture with Python/2Writing Modifiable and Readable Code/i3_b_text_bad.py: -------------------------------------------------------------------------------- 1 | """ Module B - Provides text processing functions to user """ 2 | 3 | import i3_a_text_bad as a 4 | 5 | def common(string1, string2): 6 | """ Return common words across strings1 1 & 2 """ 7 | 8 | s1 = set(string1.lower().split()) 9 | s2 = set(string2.lower().split()) 10 | return s1.intersection(s2) 11 | 12 | def common_words(filename1, filename2): 13 | """ Return common words across two input files """ 14 | 15 | lines1 = open(filename1).read() 16 | lines2 = open(filename2).read() 17 | 18 | return a.common_words(lines1, lines2) 19 | -------------------------------------------------------------------------------- /Software Architecture with Python/3Testability/test_palindrome1.py: -------------------------------------------------------------------------------- 1 | # Code Listing - #11 2 | 3 | """ 4 | Module test_palindrome - TDD for palindrome module 5 | """ 6 | 7 | # Note: This is the first version of test_palindrome, so called test_palindrome1.py 8 | 9 | import palindrome 10 | 11 | def test_basic(): 12 | """ Basic test for palindrome """ 13 | 14 | # True positives 15 | for test in ('Rotator','bob','madam','mAlAyAlam', '1'): 16 | assert palindrome.is_palindrome(test)==True 17 | 18 | # True negatives 19 | for test in ('xyz','elephant', 'Country'): 20 | assert palindrome.is_palindrome(test)==False 21 | 22 | -------------------------------------------------------------------------------- /01Python_Tricks/ch3Effective Functions/i9decorator_with_arg.py: -------------------------------------------------------------------------------- 1 | def proxy(func): 2 | def wrapper(*args, **kwargs): 3 | return func(*args, **kwargs) 4 | return wrapper 5 | 6 | def trace(func): 7 | def wrapper(*args, **kwargs): 8 | print(f'trace: calling {func.__name__}() ' 9 | f'with {args}, ### ,{kwargs}') 10 | original_result = func(*args, **kwargs) 11 | print(f'trace: {func.__name__}() ' 12 | f'returned {original_result}') 13 | return original_result 14 | return wrapper 15 | 16 | @trace 17 | def say(name, line): 18 | return f'{name} @@@ {line}' 19 | 20 | say('Abel', 'Hello World!') -------------------------------------------------------------------------------- /01Python_Tricks/ch4Classes&OOP/i1repr.py: -------------------------------------------------------------------------------- 1 | class Car: 2 | def __init__(self, color, mileage): 3 | self.color = color 4 | self.mileage = mileage 5 | 6 | def __str__(self): 7 | return f'a {self.color} car' 8 | 9 | def __repr__(self): 10 | return '__repr__ for Car' 11 | 12 | 13 | if __name__ == "__main__": 14 | my_car = Car('red', 12345) 15 | print(my_car) 16 | print('str(my_car)=', str(my_car)) 17 | print('{}'.format(my_car)) 18 | print(str([my_car])) 19 | print(repr(my_car)) 20 | 21 | import datetime 22 | today = datetime.date.today() 23 | print(str(today), repr(today) ) 24 | 25 | 26 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch1modular_program_with_py/i0stats/test_stats.py: -------------------------------------------------------------------------------- 1 | import stats 2 | 3 | stats.init() 4 | stats.event_occurred("meal_eaten") 5 | stats.event_occurred("snack_eaten") 6 | stats.event_occurred("meal_eaten") 7 | stats.event_occurred("snack_eaten") 8 | stats.event_occurred("meal_eaten") 9 | stats.event_occurred("diet_started") 10 | stats.event_occurred("meal_eaten") 11 | stats.event_occurred("meal_eaten") 12 | stats.event_occurred("meal_eaten") 13 | stats.event_occurred("diet_abandoned") 14 | stats.event_occurred("snack_eaten") 15 | 16 | for event,num_times in stats.get_stats(): 17 | print("{} occurred {} times".format(event, num_times)) 18 | -------------------------------------------------------------------------------- /00RefactoringPython/ch7Move_attribute_between_Objects/i5introduce_foreign_method.py: -------------------------------------------------------------------------------- 1 | from dateutil import parser 2 | import datetime 3 | from mycolor import show 4 | 5 | yourinput_date = '2018-02-24 14:19' 6 | 7 | dt = parser.parse(yourinput_date) 8 | newstart = dt + datetime.timedelta(days=1) 9 | print('old way:', show(newstart)) 10 | 11 | print('如果这种事情发生太多次;重复代码是万恶之源,重复代码应该被抽出来放在一个函数,\ 12 | 这个函数原本应该在提供服务的类中实现,只不过无法修改\ 13 | 不要忘记:这只是权宜之计') 14 | 15 | def next_day(input_date): 16 | dt = parser.parse(input_date) 17 | newstart = dt + datetime.timedelta(days=1) 18 | return newstart 19 | 20 | print('new way:', show(next_day(yourinput_date), 'red')) 21 | 22 | -------------------------------------------------------------------------------- /01Python_Tricks/ch3Effective Functions/i1func_in_datastructure.py: -------------------------------------------------------------------------------- 1 | def bark(text): 2 | return (text.upper() + "!!!") 3 | 4 | funcs = [bark, str.lower, str.capitalize] 5 | 6 | print('funcs = ', funcs) 7 | 8 | for f in funcs: 9 | print(f, f('hey there')) 10 | 11 | print(funcs[0]('hey 0')) 12 | 13 | 14 | print('Functions Can Be Passed to Other Functions') 15 | 16 | def greet(func): 17 | greeting = func('Hi, I am a Python program') 18 | print(greeting) 19 | 20 | greet(bark) 21 | 22 | def whisper(text): 23 | return text.lower() + '...' 24 | 25 | greet(whisper) 26 | 27 | 28 | print('higher-order functions.') 29 | print(list(map(bark, ['hello', 'hi'])) ) -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch4Using Modules for Real-World/charter/renderers/png/title.py: -------------------------------------------------------------------------------- 1 | # charter.renderers.png.title 2 | # 3 | # Renderer for drawing a title onto the chart in PNG format. 4 | 5 | from PIL import ImageFont 6 | 7 | from ...constants import * 8 | 9 | ############################################################################# 10 | 11 | def draw(chart, drawer): 12 | font = ImageFont.truetype("Helvetica", 24) 13 | text_width,text_height = font.getsize(chart['title']) 14 | 15 | left = CHART_WIDTH/2 - text_width/2 16 | top = TITLE_HEIGHT/2 - text_height/2 17 | 18 | drawer.text((left, top), chart['title'], "#4040a0", font) 19 | 20 | -------------------------------------------------------------------------------- /university_counselor/b9365_ProgrammingQs/day3_5end/manage.py: -------------------------------------------------------------------------------- 1 | from flask.ext.script import Manager, Server 2 | from flask.ext.migrate import Migrate, MigrateCommand 3 | 4 | from main import app, db, User, Post, Tag, Comment 5 | 6 | 7 | migrate = Migrate(app, db) 8 | 9 | manager = Manager(app) 10 | manager.add_command("server", Server()) 11 | manager.add_command('db', MigrateCommand) 12 | 13 | 14 | @manager.shell 15 | def make_shell_context(): 16 | return dict( 17 | app=app, 18 | db=db, 19 | User=User, 20 | Post=Post, 21 | Tag=Tag, 22 | Comment=Comment 23 | ) 24 | 25 | if __name__ == "__main__": 26 | manager.run() 27 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 00RefactoringPython folder 2 | - What, Why?
3 | The book 4 | [refactoring: improving the design of existing code](https://book.douban.com/subject/1229923) 5 | only has Java version codes, I am not a fun of Java but interested in Python, 6 | so I made the Python version demos of the book as an exercise. 7 | 8 | - 这是干啥和为啥?
9 | 《重构:改善既有代码的设计》的例子都是Java版的,除了偶尔做些Android原型开发和概念验证 10 | 偶不怎么碰Java也不是非常喜欢碰,相对更喜欢Python和其他一些语言,所以边读变写python例子作为练习。 11 |
12 | 13 | # 01Python_Trick folder 14 | The book is (https://book.douban.com/subject/27193155) 15 | 16 | # 02Modular-Programming-with-Python 17 | The book is (https://book.douban.com/subject/26791753) -------------------------------------------------------------------------------- /00RefactoringPython/ch11Handle_Generalization/i1pull_up_constructor_body.py: -------------------------------------------------------------------------------- 1 | from mycolor import show 2 | 3 | class Employee_Old: 4 | pass 5 | 6 | class Manager_Old(Employee_Old): 7 | def __init__(self, name, id, grade): 8 | print('do something!') 9 | print('-------------改造开始-----------------') 10 | 11 | 12 | class Employee(object): 13 | def __init__(self, name, id): 14 | self.name = name 15 | self.id = id 16 | 17 | class Manager(Employee): 18 | def __init__(self, name, id, grade): 19 | super(Manager, self).__init__(name, id) 20 | self.grade = grade 21 | 22 | m = Manager('abel', '10001', 'grade 21') 23 | print(m.name, m.id, m.grade) -------------------------------------------------------------------------------- /university_counselor/b9365_ProgrammingQs/day1_2end/config.py: -------------------------------------------------------------------------------- 1 | from os import environ 2 | 3 | 4 | class Config(object): 5 | pass 6 | 7 | 8 | class ProdConfig(Config): 9 | pass 10 | 11 | 12 | class DevConfig(Config): 13 | DEBUG = True 14 | SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://{user}:{pwd}@{host}/{database}'.format( 15 | user=environ.get('DB_USER', 'root'), 16 | pwd=environ.get('MYSQLCONNSTR_DB_PWD', ''), 17 | host=environ.get('DB_HOST', 'localhost'), 18 | database=environ.get('DB_NAME', 'blog_db'), 19 | charset='utf8mb4', # The characterset you need 20 | ) 21 | 22 | SQLALCHEMY_TRACK_MODIFICATIONS = False 23 | 24 | 25 | -------------------------------------------------------------------------------- /Software Architecture with Python/3Testability/factorial.py: -------------------------------------------------------------------------------- 1 | # Code Listing - #9 2 | 3 | """ 4 | Module factorial - Demonstrating an example of writing doctests 5 | """ 6 | 7 | import functools 8 | import operator 9 | 10 | def factorial(n): 11 | """ Factorial of a number. 12 | 13 | >>> factorial(0) 14 | 1 15 | >>> factorial(1) 16 | 1 17 | >>> factorial(5) 18 | 120 19 | >>> factorial(10) 20 | 3628800 21 | """ 22 | 23 | # Handle 0 as a special case 24 | if n == 0: 25 | return 1 26 | 27 | return functools.reduce(operator.mul, range(1,n+1)) 28 | 29 | if __name__ == "__main__": 30 | import doctest 31 | doctest.testmod(verbose=True) 32 | -------------------------------------------------------------------------------- /00RefactoringPython/ch10Simplify_Function_Call/i9replace_exception_with_test.py: -------------------------------------------------------------------------------- 1 | from mycolor import show 2 | 3 | _values = ['test0', 'test1'] 4 | def get_value_for_period_old(period_number): 5 | try: 6 | return _values[period_number] 7 | except ValueError: 8 | print("Oops! That was wrong period_number!") 9 | return 0 10 | 11 | get_value_for_period_old(1) 12 | 13 | print('异常 只应该呗用于异常、罕见的行为,'+show('不应该成为条件检查的替代品')) 14 | print('-------------改造开始-----------------') 15 | def get_value_for_period(period_number): 16 | if period_number >= len(_values): 17 | return 0 18 | return _values[period_number] 19 | 20 | print(get_value_for_period(1)) 21 | print(get_value_for_period(2)) -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch4Using Modules for Real-World/charter/renderers/pdf/title.py: -------------------------------------------------------------------------------- 1 | # charter.renderers.pdf.title 2 | # 3 | # Renderer for drawing a title onto the chart in PDF format. 4 | 5 | from ...constants import * 6 | 7 | ############################################################################# 8 | 9 | def draw(chart, canvas): 10 | text_width = canvas.stringWidth(chart['title'], "Helvetica", 24) 11 | text_height = 24 * 1.2 12 | 13 | left = CHART_WIDTH/2 - text_width/2 14 | bottom = CHART_HEIGHT - TITLE_HEIGHT/2 + text_height/2 15 | 16 | canvas.setFont("Helvetica", 24) 17 | canvas.setFillColorRGB(0.25, 0.25, 0.625) 18 | canvas.drawString(left, bottom, chart['title']) 19 | 20 | -------------------------------------------------------------------------------- /00RefactoringPython/ch6Reorganize_Functions/i3introduce_explain_var.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | 4 | platform = 'mac osx' 5 | browser = 'ie 10' 6 | resize = 3 7 | 8 | def was_initialized(): 9 | return random.choice([True, False]) 10 | 11 | if 'MAC' in platform.upper() and \ 12 | 'IE' in browser.upper() and \ 13 | was_initialized and resize > 0: 14 | print('do something') 15 | 16 | 17 | print('表达式可能非常复杂而难以阅读,临时变量可以帮助你将表达式分解成\ 18 | 比较容易管理的形式') 19 | 20 | isMacOs = True if 'MAC' in platform.upper() else False 21 | isIEbrowser = True if 'IE' in browser.upper() else False 22 | wasResize = True if resize > 0 else False 23 | 24 | if isMacOs and isIEbrowser and was_initialized and wasResize: 25 | print('do something too!') 26 | -------------------------------------------------------------------------------- /01Python_Tricks/ch4Classes&OOP/i2own_exception.py: -------------------------------------------------------------------------------- 1 | def validate_old(name): 2 | if len(name) < 10: 3 | raise ValueError 4 | 5 | # validate_old('joe') 6 | 7 | class NameTooShortException(ValueError): 8 | pass 9 | 10 | def validate(name): 11 | if len(name) < 10: 12 | raise NameTooShortException(name) 13 | 14 | def handle_validation_error(ValueError): 15 | print('#'*10) 16 | # validate('joe') 17 | 18 | class BaseValidationError(ValueError): 19 | pass 20 | 21 | 22 | class NameTooLongError(BaseValidationError): 23 | pass 24 | 25 | class NameTooCuteError(BaseValidationError): 26 | pass 27 | 28 | try: 29 | validate('joe') 30 | except NameTooShortException as err: 31 | handle_validation_error(err) -------------------------------------------------------------------------------- /00RefactoringPython/ch10Simplify_Function_Call/i4perserve_whole_object.py: -------------------------------------------------------------------------------- 1 | from mycolor import show 2 | 3 | class DaysTempRange: 4 | low = -10 5 | high = 10 6 | 7 | def getlow(self): 8 | return self.low 9 | 10 | def gethigh(self): 11 | return self.high 12 | 13 | class Plan_old: 14 | def with_range(low, high): 15 | print('do things to :', low, high) 16 | 17 | with_plan_old = Plan_old.with_range(DaysTempRange().getlow(), DaysTempRange().gethigh()) 18 | 19 | print('-------------改造开始-----------------') 20 | class Plan: 21 | def with_range(days_temp_range): 22 | print(show('do things to :', 'red'), days_temp_range.low, days_temp_range.high) 23 | 24 | with_plan_old = Plan.with_range(DaysTempRange()) -------------------------------------------------------------------------------- /Software Architecture with Python/4Performance/hound_words.py: -------------------------------------------------------------------------------- 1 | # Code Listing #9 2 | 3 | """ 4 | 5 | Return top 10 most common words from the online text of the "The Hound of Baskervilles" 6 | 7 | """ 8 | 9 | import requests, operator 10 | from collections import defaultdict, Counter 11 | 12 | print('Using defaultdict') 13 | text=requests.get('https://www.gutenberg.org/files/2852/2852-0.txt').text 14 | freq=defaultdict(int) 15 | 16 | for word in text.split(): 17 | if len(word.strip())==0: continue 18 | freq[word.lower()] += 1 19 | 20 | print(sorted(freq.items(), key=operator.itemgetter(1), reverse=True)[:10]) 21 | 22 | print('Using Counter') 23 | freq=Counter(filter(None, map(lambda x:x.lower().strip(), text.split()))) 24 | print(freq.most_common(10)) 25 | -------------------------------------------------------------------------------- /Software Architecture with Python/3Testability/palindrome3.py: -------------------------------------------------------------------------------- 1 | # Code Listing - #16 2 | 3 | """ 4 | Module palindrome - Returns whether an input string is palindrome or not 5 | """ 6 | # Note - this is the third version of palindrome, so called palindrome3.py 7 | 8 | import re 9 | from string import punctuation 10 | 11 | def is_palindrome(in_string): 12 | """ Returns True whether in_string is palindrome, False otherwise """ 13 | 14 | # Case insensitive 15 | in_string = in_string.lower() 16 | # Purge spaces 17 | in_string = re.sub('\s+','', in_string) 18 | # Purge all punctuations 19 | in_string = re.sub('[' + re.escape(punctuation) + ']+', '', in_string) 20 | # Check if string is same as in reverse 21 | return in_string == in_string[-1::-1] 22 | rm 23 | -------------------------------------------------------------------------------- /00RefactoringPython/ch8Reorganize_Data/i0self_encapsulate_field.py: -------------------------------------------------------------------------------- 1 | from mycolor import show 2 | 3 | class IntRange: 4 | def __init__(self, low, high): 5 | self.low = low 6 | self.high = high 7 | 8 | def includes(self, arg): 9 | return arg >= self.low and arg <= self.high 10 | 11 | def grow(self, factor): 12 | self.high = self.high * factor 13 | 14 | r = IntRange(0, 10) 15 | print(r.includes(2), r.includes(100)) 16 | 17 | 18 | class CappedRange(IntRange): 19 | def __init__(self, low, high, cap): 20 | IntRange.__init__(self, low, high) 21 | self.cap = cap 22 | 23 | def get_high(self): 24 | return min(self.cap, self.high) 25 | 26 | c = CappedRange(0, 10, 5) 27 | print(c.includes(2), c.includes(100), c.get_high()) -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch7Advanced Module Techniques/i5script as module gotcha/test.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates how using a Python source file as both a module and 2 | # a script can lead to subtle errors. In this example, we define a function 3 | # which does something useful, and also have a __main__ section so we can be 4 | # executed as a script. When executed, this module imports a second module, 5 | # helpers.py, which is supposed to test out the program. The helpers.py module 6 | # then imports test.py, causing this module to be initialized twice. 7 | 8 | import helpers 9 | 10 | print("Initializing test.py") 11 | 12 | def do_something(n): 13 | return n * 2 14 | 15 | if __name__ == "__main__": 16 | print('#'*10) 17 | helpers.run_test() 18 | print('@'*10) 19 | 20 | -------------------------------------------------------------------------------- /Software Architecture with Python/2Writing Modifiable and Readable Code/i3_a_text_bad.py: -------------------------------------------------------------------------------- 1 | """ Module A - Provides string processing functions """ 2 | 3 | import i3_b_text_bad as b 4 | 5 | 6 | def ntimes(string, char): 7 | """ Return number of times character 'char' 8 | occurs in string """ 9 | 10 | return string.count(char) 11 | 12 | def common_words(text1, text2): 13 | """ Return common words across text1 and text2 """ 14 | 15 | # A text is a collection of strings split using newlines 16 | strings1 = text1.split("\n") 17 | strings2 = text2.split("\n") 18 | 19 | common = [] 20 | for string1 in strings1: 21 | for string2 in strings2: 22 | common += b.common(string1, string2) 23 | 24 | # Drop duplicates 25 | return list(set(common)) -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch5Working with Module Patterns/i2encapsulation/test_recipes.py: -------------------------------------------------------------------------------- 1 | import recipes 2 | recipe = recipes.new("Pizza Dough", num_servings=1) 3 | recipes.add_ingredient(recipe, "Greek Yogurt", 1, "cup") 4 | recipes.add_ingredient(recipe, "Self-Raising Flour", 1.5, "cups") 5 | recipes.add_instruction(recipe, "Combine yogurt and 2/3 of the flour in a bowl \ 6 | and mix with a beater until combined") 7 | recipes.add_instruction(recipe, "Slowly add additional flour until it forms a stiff dough") 8 | recipes.add_instruction(recipe, "Turn out onto a floured surface and knead until dough is tacky") 9 | recipes.add_instruction(recipe, "Roll out into a circle of the desired thickness \ 10 | and place on a greased and lined baking tray") 11 | 12 | for s in recipes.to_string(recipe, num_servings=2): 13 | print(s) -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch5Working with Module Patterns/i6hook_login_module.py: -------------------------------------------------------------------------------- 1 | cur_user = None 2 | login_hook = None 3 | 4 | 5 | def set_login_hook(hook): 6 | print('set_login_hook') 7 | global login_hook 8 | login_hook = hook 9 | 10 | 11 | def login(username, password): 12 | if username is not None and password is not None: 13 | global login_hook 14 | if login_hook != None: 15 | login_hook(username) 16 | 17 | global cur_user 18 | cur_user = username 19 | return True 20 | else: 21 | return False 22 | 23 | 24 | def logout(): 25 | global cur_user 26 | cur_user = None 27 | 28 | 29 | if __name__ == "__main__": 30 | login("abel", "1234") 31 | print('start# cur_user=', cur_user) 32 | logout() 33 | print('end # cur_user=', cur_user) -------------------------------------------------------------------------------- /00RefactoringPython/ch10Simplify_Function_Call/i2parameterize_method.py: -------------------------------------------------------------------------------- 1 | from mycolor import show 2 | 3 | class Employee(object): 4 | def __init__(self): 5 | self.salary = 0 6 | 7 | def ten_percent_raise(self): 8 | self.salary *= 1.1 9 | 10 | def five_percent_raise(self): 11 | self.salary *= 1.05 12 | 13 | e = Employee() 14 | e.salary = 10000 15 | e.ten_percent_raise() 16 | print(e.salary) 17 | e.five_percent_raise() 18 | print(e.salary) 19 | 20 | print('-------------改造开始-----------------') 21 | class Employee_afterRF: 22 | def __init__(self): 23 | self.salary = 0 24 | 25 | def raise_salary(self, factor): 26 | self.salary *= factor 27 | 28 | e1 = Employee_afterRF() 29 | e1.salary = 10000 30 | e1.raise_salary(1.1) 31 | print(e1.salary) 32 | e1.raise_salary(1.05) 33 | print(e1.salary) 34 | -------------------------------------------------------------------------------- /00RefactoringPython/ch4Build Test System/test_i1file_reader.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | # https://stackoverflow.com/questions/17353213/init-for-unittest-testcase 4 | # pytest test_i1file_reader.py -s --durations=0 5 | 6 | class TestFileReader(unittest.TestCase): 7 | def __init__(self, *args, **kwargs): 8 | super(TestFileReader, self).__init__(*args, **kwargs) 9 | self.path = 'i1data.txt' 10 | 11 | def setUp(self): 12 | self.input_file = open(self.path,'r') 13 | pass 14 | 15 | def tearDown(self): 16 | self.input_file.close() 17 | pass 18 | 19 | def test_read(self): 20 | lines = self.input_file.readlines() 21 | 22 | self.assertEqual(len(lines),2) 23 | self.assertEqual(lines[0].split()[0], 'Bradman') 24 | 25 | 26 | if __name__ == "__main__": 27 | unittest.main() -------------------------------------------------------------------------------- /00RefactoringPython/ch9Simplify_Conditional_Expression/i2consolidate_conditional_expression.py: -------------------------------------------------------------------------------- 1 | from mycolor import show 2 | 3 | senirotiy = 1 4 | months_disabled = 13 5 | is_parttime = True 6 | 7 | def disability_amount(): 8 | if senirotiy < 2: 9 | return 0 10 | if months_disabled > 12: 11 | return 0 12 | if is_parttime: 13 | return 0 14 | 15 | print(show(disability_amount())) 16 | 17 | print('有一系列条件测试,都得到相同结果;'+ 18 | '你可以将测试合并为一个条件表达式, 将这个条件表达式提炼为独立函数') 19 | print('- · - - · - - · - - · - ') 20 | 21 | def isnot_eligable_for_disability(): 22 | if senirotiy < 2 or months_disabled > 12 \ 23 | or is_parttime: 24 | return True 25 | 26 | def disability_amount_afterRF(): 27 | if isnot_eligable_for_disability(): 28 | return 0 29 | 30 | print(show(disability_amount_afterRF(), 'red') ) -------------------------------------------------------------------------------- /Software Architecture with Python/4Performance/bloomtest.py: -------------------------------------------------------------------------------- 1 | # Code Listing #12 2 | """ 3 | 4 | Example of using bloom filter 5 | 6 | NOTE: This works only with Python2.x 7 | 8 | """ 9 | 10 | from pybloom import BloomFilter 11 | import requests 12 | 13 | # Uncomment for profiling with line profiler or memory profiler 14 | 15 | # @profile 16 | def hound(): 17 | f=BloomFilter(capacity=100000, error_rate=0.01) 18 | text=requests.get('https://www.gutenberg.org/files/2852/2852-0.txt').text 19 | 20 | for word in text.split(): 21 | word = word.lower().strip() 22 | f.add(word) 23 | 24 | print len(f) 25 | print len(text.split()) 26 | 27 | for w in ('holmes','watson','hound','moor','queen'): 28 | print 'Found',w,w in f 29 | 30 | 31 | if __name__ == "__main__": 32 | hound() 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch9Modular Programming as a Foundation for Good Programming Technique/i1counter/tests.py: -------------------------------------------------------------------------------- 1 | # This module implements various unit tests for the ``counter`` package. 2 | 3 | import unittest 4 | 5 | import counter 6 | 7 | class CounterTestCase(unittest.TestCase): 8 | """ Unit tests for the ``counter`` package. 9 | """ 10 | def test_counter_totals(self): 11 | counter.reset() 12 | counter.add(1) 13 | counter.add(2) 14 | counter.add(3) 15 | counter.add(1) 16 | self.assertEqual(counter.totals(), [(1, 2), (2, 1), (3, 1)]) 17 | 18 | def test_counter_reset(self): 19 | counter.reset() 20 | counter.add(1) 21 | counter.reset() 22 | counter.add(2) 23 | self.assertEqual(counter.totals(), [(2, 1)]) 24 | 25 | 26 | if __name__ == "__main__": 27 | unittest.main() 28 | 29 | -------------------------------------------------------------------------------- /00RefactoringPython/ch10Simplify_Function_Call/i7errorcode_to_exception.py: -------------------------------------------------------------------------------- 1 | from mycolor import show 2 | 3 | class DemoClass: 4 | def __init__(self): 5 | self.balance = 0 6 | 7 | def withdraw_old(self, amount): 8 | if amount > self.balance: 9 | return -1 10 | else: 11 | self.balance -= amount 12 | return 0 13 | 14 | d = DemoClass() 15 | r = d.withdraw_old(10) 16 | print(show(r)) 17 | 18 | print('程序种发现错误的地方,并不一定知道如何处理错误,需要让调用者知道错误' 19 | + ' 清楚的将 普通程序 和 错误处理 分开,让程序更容易理解,代码可读性是我们虔诚追求的目标🏆') 20 | print('-------------改造开始-----------------') 21 | class DemoClass_AfterRF: 22 | def __init__(self): 23 | self.balance = 0 24 | 25 | def withdraw(self, amount): 26 | if amount > self.balance: 27 | raise Exception('Balance Exception!') 28 | self.balance -= amount 29 | 30 | d1 = DemoClass_AfterRF() 31 | d1.withdraw(10) -------------------------------------------------------------------------------- /Software Architecture with Python/2Writing Modifiable and Readable Code/i1_b1.py: -------------------------------------------------------------------------------- 1 | # 2 | 3 | """ Module B - Implement functions provide some statistical methods """ 4 | 5 | # 6 | import i1_a1 as a 7 | 8 | def rms(narray): 9 | """ Return root mean square of array of numbers""" 10 | 11 | return pow(sum(a.squares(narray)), 0.5) 12 | 13 | def mean(array): 14 | """ Return mean of an array of numbers """ 15 | 16 | return 1.0*sum(array)/len(array) 17 | 18 | def variance(array): 19 | """ Return variance of an array of numbers """ 20 | 21 | # Square of variation from mean 22 | avg = mean(array) 23 | array_d = [(x - avg) for x in array] 24 | variance = sum(a.squares(array_d)) 25 | return variance 26 | 27 | def standard_deviation(array): 28 | """ Return standard deviation of an array of numbers """ 29 | 30 | # S.D is square root of variance 31 | return pow(variance(array), 0.5) -------------------------------------------------------------------------------- /00RefactoringPython/ch8Reorganize_Data/i2change_value_to_reference.py: -------------------------------------------------------------------------------- 1 | from mycolor import show 2 | 3 | 4 | class Order: 5 | def __init__(self, customer): 6 | self.customer = customer 7 | 8 | class Customer: 9 | def __init__(self, name): 10 | self.name = name 11 | 12 | d0 = Order(Customer('xiaoming1')) 13 | 14 | print(show(d0.customer.name)) 15 | 16 | c0 = Customer('c') 17 | c1 = Customer('c') 18 | print( c0 == c1) 19 | 20 | 21 | class Customer_afterRF: 22 | instance = None 23 | 24 | def __init__(self, name): 25 | self.name = name 26 | 27 | @staticmethod 28 | def get_instnace(name): 29 | if Customer_afterRF.instance is None: 30 | Customer_afterRF.instance = Customer_afterRF(name) 31 | return Customer_afterRF.instance 32 | 33 | c2 = Customer_afterRF.get_instnace('c') 34 | c3 = Customer_afterRF.get_instnace('c') 35 | print(c2 == c3) 36 | print(id(c2), id(c3)) -------------------------------------------------------------------------------- /01Python_Tricks/ch2Patterns_for_Cleaner_Python/i3with_contextlib.py: -------------------------------------------------------------------------------- 1 | from contextlib import contextmanager 2 | 3 | @contextmanager 4 | def managed_file(name): 5 | try: 6 | f = open(name, 'w') 7 | yield f 8 | finally: 9 | f.close() 10 | 11 | with managed_file('hello.txt') as f: 12 | f.write('hello world') 13 | f.write('by now!') 14 | 15 | 16 | class Indenter: 17 | def __init__(self): 18 | self.level = 0 19 | 20 | def __enter__(self): 21 | self.level += 1 22 | return self 23 | 24 | def __exit__(self, exc_type, exc_val, exc_tb): 25 | self.level -= 1 26 | 27 | def print(self, text): 28 | print(' ' * self.level + text) 29 | 30 | with Indenter() as indent: 31 | indent.print('hi!') 32 | with indent: 33 | indent.print('hello') 34 | with indent: 35 | indent.print('bonjour') 36 | indent.print('hey') 37 | 38 | -------------------------------------------------------------------------------- /00RefactoringPython/ch9Simplify_Conditional_Expression/i4remove_control_flag.py: -------------------------------------------------------------------------------- 1 | from mycolor import show 2 | 3 | 4 | def send_alert(): 5 | print('send_alert') 6 | 7 | def check_security_old(people): 8 | found = False 9 | for p in people: 10 | if not found: 11 | if p == 'Don': 12 | send_alert() 13 | found = True 14 | if p == 'John': 15 | send_alert() 16 | found = True 17 | 18 | check_security_old(['Abel', 'Bob', 'Don']) 19 | 20 | print('某个变量带哟 控制标记 [control flag] ' + 21 | '以break 或者return 取代 控制标记') 22 | print('- · - - · - - · - - · - ') 23 | 24 | def check_security(people): 25 | found = False 26 | for p in people: 27 | 28 | if p == 'Don': 29 | send_alert() 30 | break 31 | if p == 'John': 32 | send_alert() 33 | break 34 | 35 | check_security(['Abel', 'Bob', 'Don']) -------------------------------------------------------------------------------- /00RefactoringPython/ch9Simplify_Conditional_Expression/i7introd_null_object.py: -------------------------------------------------------------------------------- 1 | from mycolor import show 2 | 3 | class Customer(object): 4 | def get_plan(self): 5 | return 'A goal without a plan is just a wish' 6 | 7 | class BillingPlan: 8 | def basic(self): 9 | return 'By failing to prepare, you are preparing to fail.' 10 | 11 | customer = None 12 | billing_plan = BillingPlan() 13 | 14 | print('-·--·--·--·-正文部分-·-·-·-·-·-·-·') 15 | 16 | if customer == None: 17 | plan = billing_plan.basic() 18 | else: 19 | plan = customer.get_plan() 20 | 21 | print(show(plan)) 22 | print('- · - - · 开始改造 - - · - - · - ') 23 | 24 | 25 | class NullCustomer(Customer): 26 | def get_plan(self): 27 | return BillingPlan().basic() 28 | 29 | print(customer, customer == None) 30 | customer1 = NullCustomer() if customer == None else Customer() 31 | 32 | plan = customer1.get_plan() 33 | print(show(plan, 'red')) 34 | 35 | -------------------------------------------------------------------------------- /Software Architecture with Python/2Writing Modifiable and Readable Code/i5urlrank.py: -------------------------------------------------------------------------------- 1 | import operator 2 | import requests 3 | 4 | class UrlRank(object): 5 | """ Accept URLs as inputs and rank them in 6 | terms of how much a word occurs in them """ 7 | 8 | def __init__(self, word, *urls): 9 | self.word = word.strip().lower() 10 | self.urls = urls 11 | 12 | def rank(self): 13 | """ Rank the URLs. A tuple is returned with 14 | (url, #occur) in decreasing order of 15 | occurences """ 16 | 17 | occurs = [] 18 | 19 | for url in self.urls: 20 | data = requests.get(url).content 21 | words = map(lambda x: x.lower().strip(), data.split()) 22 | # Filter empty words 23 | count = words.count(self.word) 24 | occurs.append((url, count)) 25 | 26 | # Return in sorted order 27 | return sorted(occurs, key=operator.itemgetter(1), reverse=True) 28 | -------------------------------------------------------------------------------- /00RefactoringPython/ch6Reorganize_Functions/i4introduce_explain_var.py: -------------------------------------------------------------------------------- 1 | from myfinal import MyPyFinal 2 | 3 | 4 | def price(): 5 | # price is base price - quantity discount * shipping 6 | quantity = 510 7 | item_price = 600 8 | 9 | return quantity * item_price - max(0, quantity - 500) * item_price * 0.05 \ 10 | + min(quantity * item_price * 0.1, 100) 11 | 12 | t = price() 13 | print('old way which need to refactory:', t) 14 | 15 | print('开始改造ing:') 16 | def price_after_refactory(): 17 | # price is base price - quantity discount * shipping 18 | quantity = 510 19 | item_price = 600 20 | base_price = MyPyFinal(quantity * item_price).r() 21 | quantity_discount = MyPyFinal(max(0, quantity - 500) * item_price * 0.05).r() 22 | shipping = MyPyFinal(min(base_price * 0.1, 100)).r() 23 | return base_price - quantity_discount\ 24 | + shipping 25 | 26 | t_after = price_after_refactory() 27 | print('old way which after refactory:', t_after) 28 | -------------------------------------------------------------------------------- /01Python_Tricks/ch3Effective Functions/i10debuggable_decorator.py: -------------------------------------------------------------------------------- 1 | def greet(): 2 | """Return a friendly greeting.""" 3 | return 'Hello world' 4 | 5 | def uppercase_old(func): 6 | def wrapper(): 7 | original_result = func() 8 | modified_result = original_result.upper() 9 | return modified_result 10 | return wrapper 11 | 12 | 13 | decorated_greet = uppercase_old(greet) 14 | print(greet.__name__) 15 | print(greet.__doc__) 16 | print(decorated_greet.__name__) 17 | print(decorated_greet.__doc__) 18 | 19 | print('----------------------') 20 | import functools 21 | 22 | def uppercase(func): 23 | @functools.wraps(func) 24 | def wrapper(): 25 | original_result = func() 26 | modified_result = original_result.upper() 27 | return modified_result 28 | return wrapper 29 | 30 | decorated_greet = uppercase(greet) 31 | print(greet.__name__) 32 | print(greet.__doc__) 33 | print(decorated_greet.__name__) 34 | print(decorated_greet.__doc__) 35 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch8Testing and Deploying Modules/i1test_quantities/test_quantities.py: -------------------------------------------------------------------------------- 1 | # test_quantities.py 2 | # 3 | # This Python script performs various unit tests on the `quantities` package. 4 | 5 | import unittest 6 | import quantities 7 | 8 | class TestQuantities(unittest.TestCase): 9 | def setUp(self): 10 | quantities.init("us") 11 | 12 | def test_new(self): 13 | q = quantities.new(12, "km") 14 | self.assertEqual(quantities.value(q), 12) 15 | self.assertEqual(quantities.units(q), "kilometer") 16 | 17 | def test_convert(self): 18 | q1 = quantities.new(12, "km") 19 | q2 = quantities.convert(q1, "m") 20 | self.assertEqual(quantities.value(q2), 12000) 21 | self.assertEqual(quantities.units(q2), "meter") 22 | 23 | q = quantities.new(12, "km") 24 | with self.assertRaises(ValueError): 25 | quantities.convert(q, "kg") 26 | 27 | if __name__ == "__main__": 28 | unittest.main() 29 | -------------------------------------------------------------------------------- /01Python_Tricks/ch4Classes&OOP/i3copying_arbitary_obj.py: -------------------------------------------------------------------------------- 1 | class Point: 2 | def __init__(self, x, y): 3 | self.x = x 4 | self.y = y 5 | 6 | def __repr__(self): 7 | return f'Point({self.x!r}, {self.y!r})' 8 | 9 | 10 | a = Point(20, 40) 11 | import copy 12 | b = copy.copy(a) 13 | print(a, b) 14 | print(a == b) 15 | print(a is b) 16 | 17 | class Rectangle: 18 | def __init__(self, topleft, bottomright): 19 | self.topleft = topleft 20 | self.bottomright = bottomright 21 | 22 | def __repr__(self): 23 | return (f'Rectangle({self.topleft!r}, ' 24 | f'{self.bottomright!r})') 25 | 26 | rect = Rectangle(Point(0, 1), Point(5, 6)) 27 | srect = copy.copy(rect) 28 | print(rect, srect) 29 | print(rect == srect) 30 | print(rect is srect) 31 | 32 | rect.topleft.x = 999 33 | print(rect, srect) 34 | 35 | drect = copy.deepcopy(rect) 36 | print(rect, drect) 37 | drect.topleft.x = 1000 38 | rect.bottomright.x = 2000 39 | print(rect, drect) 40 | -------------------------------------------------------------------------------- /Software Architecture with Python/2Writing Modifiable and Readable Code/i4_a_text_better.py: -------------------------------------------------------------------------------- 1 | """ Module A - Provides string processing functions """ 2 | 3 | 4 | def ntimes(string, char): 5 | """ Return number of times character 'char' 6 | occurs in string """ 7 | 8 | return string.count(char) 9 | 10 | def common(string1, string2): 11 | """ Return common words across strings1 1 & 2 """ 12 | 13 | s1 = set(string1.lower().split()) 14 | s2 = set(string2.lower().split()) 15 | return s1.intersection(s2) 16 | 17 | def common_words(text1, text2): 18 | """ Return common words across text1 and text2 """ 19 | 20 | # A text is a collection of strings split using newlines 21 | strings1 = text1.split("\n") 22 | strings2 = text2.split("\n") 23 | 24 | common = [] 25 | for string1 in strings1: 26 | for string2 in strings2: 27 | common += b.common(string1, string2) 28 | 29 | # Drop duplicates 30 | return list(set(common)) -------------------------------------------------------------------------------- /00RefactoringPython/ch10Simplify_Function_Call/i5parameter_to_method.py: -------------------------------------------------------------------------------- 1 | from mycolor import show 2 | 3 | def get_discount_level(quantity): 4 | if quantity > 100: 5 | return 2 6 | else: 7 | return 1 8 | 9 | def discounted_price_old(base_price, discount_level): 10 | if discount_level == 2: 11 | return base_price * 0.1 12 | else: 13 | return base_price * 0.05 14 | 15 | quantity = 1000 16 | item_price = 9.8 17 | base_price = quantity * item_price 18 | discounted_level = get_discount_level(quantity) 19 | final_price = discounted_price_old(base_price, discounted_level) 20 | print('final_price=', show(final_price)) 21 | 22 | 23 | print('-------------改造开始-----------------') 24 | def discounted_price(base_price): 25 | discount_level = get_discount_level(quantity) 26 | if discount_level == 2: 27 | return base_price * 0.1 28 | else: 29 | return base_price * 0.05 30 | 31 | final_price1 = discounted_price(base_price) 32 | print(show(final_price1, 'red')) -------------------------------------------------------------------------------- /00RefactoringPython/ch6Reorganize_Functions/i9substitue_algorithm.py: -------------------------------------------------------------------------------- 1 | from termcolor import colored 2 | from myfinal import MyPyFinal 3 | 4 | 5 | def show(s,color='green'): 6 | return colored(s, color, attrs=['reverse', 'blink']) 7 | 8 | def found_person(people): 9 | for p in people: 10 | if p == 'Don': 11 | return 'Don' 12 | if p == 'John': 13 | return 'John' 14 | if p == 'Kent': 15 | return 'Kent' 16 | 17 | return '' 18 | 19 | people = ['Abel', 'Bob', 'Cook', 'Don'] 20 | p = found_person(people) 21 | print('old way which need to refactory:', show(p)) 22 | 23 | print(show('如果你发现做一件事有更清晰的方式,应该以更清晰的方式取代复杂的方式\ 24 | 有时候你必须壮士扼腕,删掉整个算法,代之以更简单的算法')) 25 | def found_people_after_refactory(people): 26 | candidates = ['Don', 'John', 'Kent'] 27 | for p in people: 28 | if p in candidates: 29 | return p 30 | return '' 31 | 32 | p = found_people_after_refactory(people) 33 | print('New way which need to refactory:', show(p, 'red')) -------------------------------------------------------------------------------- /Software Architecture with Python/2Writing Modifiable and Readable Code/i5textrank.py: -------------------------------------------------------------------------------- 1 | import operator 2 | 3 | class TextRank(object): 4 | """ Accept text files as inputs and rank them in 5 | terms of how much a word occurs in them """ 6 | 7 | def __init__(self, word, *filenames): 8 | self.word = word.strip().lower() 9 | self.filenames = filenames 10 | 11 | def rank(self): 12 | """ Rank the files. A tuple is returned with 13 | (filename, #occur) in decreasing order of 14 | occurences """ 15 | 16 | occurs = [] 17 | 18 | for fpath in self.filenames: 19 | data = open(fpath).read() 20 | words = map(lambda x: x.lower().strip(), data.split()) 21 | print('words=', words) 22 | # Filter empty words 23 | count = words.count(self.word) 24 | occurs.append((fpath, count)) 25 | 26 | # Return in sorted order 27 | return sorted(occurs, key=operator.itemgetter(1), reverse=True) 28 | -------------------------------------------------------------------------------- /Software Architecture with Python/2Writing Modifiable and Readable Code/i5rankbase_improve.py: -------------------------------------------------------------------------------- 1 | import operator 2 | 3 | class RankBase(object): 4 | """ Accept text data as inputs and rank them in 5 | terms of how much a word occurs in them """ 6 | 7 | def __init__(self, word): 8 | self.word = word.strip().lower() 9 | 10 | def rank(self, *texts): 11 | """ Rank input data. A tuple is returned with 12 | (idx, #occur) in decreasing order of 13 | occurences """ 14 | 15 | occurs = {} 16 | 17 | for idx,text in enumerate(texts): 18 | # print text 19 | words = map(lambda x: x.lower().strip(), text.split()) 20 | count = words.count(self.word) 21 | occurs[idx] = count 22 | 23 | # Return dictionary 24 | return occurs 25 | 26 | def sort(self, occurs): 27 | """ Return the ranking data in sorted order """ 28 | 29 | return sorted(occurs, key=operator.itemgetter(1), reverse=True) 30 | 31 | -------------------------------------------------------------------------------- /00RefactoringPython/ch11Handle_Generalization/i4inheritance_to_delegation.py: -------------------------------------------------------------------------------- 1 | from mycolor import show 2 | 3 | class Vector: 4 | def size(self): 5 | print('size func') 6 | 7 | def is_empty(self): 8 | print('is_empty func') 9 | 10 | 11 | class OldStack(Vector): 12 | def push(self): 13 | print('OldStack push') 14 | 15 | def pop(self): 16 | print('OldStack pop') 17 | 18 | old_stack = OldStack() 19 | print(old_stack.size(), old_stack.is_empty(), 20 | old_stack.push(), old_stack.pop()) 21 | 22 | print('-------------改造开始-----------------') 23 | 24 | class Stack: 25 | def __init__(self): 26 | self.vector = Vector() 27 | 28 | def size(self): 29 | self.vector.size() 30 | 31 | def is_empty(self): 32 | self.vector.is_empty() 33 | 34 | def push(self): 35 | print('Stack push') 36 | 37 | def pop(self): 38 | print('Stack pop') 39 | 40 | stack = Stack() 41 | print(stack.size(), stack.is_empty(), 42 | stack.push(), stack.pop()) -------------------------------------------------------------------------------- /00RefactoringPython/ch8Reorganize_Data/i7typecode_to_subclass.py: -------------------------------------------------------------------------------- 1 | from mycolor import show 2 | 3 | class Old_Employee: 4 | engineer = 0 5 | salesman = 1 6 | manager = 2 7 | 8 | def __init__(self, type): 9 | self.type = type 10 | 11 | e = Old_Employee(2) 12 | print(e.type) 13 | print(show('开始改造'),'- > -'*5) 14 | 15 | class Employee: 16 | instance = None 17 | 18 | def __init__(self, type): 19 | self.type = type 20 | 21 | @staticmethod 22 | def get_instnace(type): 23 | if Employee.instance is None: 24 | if type == 0: 25 | Employee.instance = Engineer(type) 26 | elif type == 1: 27 | Employee.instance = Salesman(type) 28 | else: 29 | Employee.instance = Manager(type) 30 | return Employee.instance 31 | 32 | class Engineer(Employee): 33 | pass 34 | 35 | class Salesman(Employee): 36 | pass 37 | 38 | class Manager(Employee): 39 | pass 40 | 41 | c2 = Employee.get_instnace(2) 42 | print(show(c2.type, 'red')) -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch9Modular Programming as a Foundation for Good Programming Technique/i1counter/counter/interface.py: -------------------------------------------------------------------------------- 1 | # This module implements the public interface to the "counter" package. 2 | 3 | def reset(): 4 | """ Reset our counter. 5 | 6 | This should be called before we start counting. 7 | """ 8 | global _counts 9 | _counts = {} # Maps value to number of occurrences. 10 | 11 | 12 | def add(value): 13 | """ Add the given value to our counter. 14 | """ 15 | global _counts 16 | 17 | try: 18 | _counts[value] += 1 19 | except KeyError: 20 | _counts[value] = 1 21 | 22 | 23 | def totals(): 24 | """ Return the number of times each value has occurred. 25 | 26 | We return a list of (value, num_occurrences) tuples, one 27 | for each unique value included in the count. 28 | """ 29 | global _counts 30 | 31 | results = [] 32 | for value in sorted(_counts.keys()): 33 | results.append((value, _counts[value])) 34 | return results 35 | 36 | -------------------------------------------------------------------------------- /Software Architecture with Python/3Testability/test_datetimehelper1.py: -------------------------------------------------------------------------------- 1 | # Code Listing - #4 2 | 3 | """ Module testdatetimehelper - Unit test module for testing datetimehelper module """ 4 | 5 | # Note - This is the first version of test_datetimehelper module so named as test_datetimehelper1.py 6 | 7 | import unittest 8 | import datetimehelper 9 | 10 | class DateTimeHelperTestCase(unittest.TestCase): 11 | """ Unit-test testcase class for DateTimeHelper class """ 12 | 13 | def setUp(self): 14 | print("Setting up...") 15 | self.obj = datetimehelper.DateTimeHelper() 16 | 17 | def test_us_india_conversion(self): 18 | """ Test us=>india date format conversion """ 19 | 20 | # Test a few dates 21 | d1 = '08/12/16' 22 | d2 = '07/11/2014' 23 | d3 = '04/29/00' 24 | self.assertEqual(self.obj.us_to_indian(d1), '12/08/2016') 25 | self.assertEqual(self.obj.us_to_indian(d2), '11/07/2014') 26 | self.assertEqual(self.obj.us_to_indian(d3), '29/04/2000') 27 | 28 | if __name__ == "__main__": 29 | unittest.main() 30 | -------------------------------------------------------------------------------- /00RefactoringPython/ch8Reorganize_Data/d4factory_pattern.py: -------------------------------------------------------------------------------- 1 | EROPEAN = 0 2 | AFRICAN = 1 3 | NORWEGIAN = 2 4 | 5 | def getbase_speed(p=1): 6 | return p * 10 7 | 8 | def get_loadfactor(): 9 | return 100 10 | 11 | class CountryFactory(object): 12 | @staticmethod 13 | def create(type): 14 | 15 | if type == EROPEAN: 16 | return Eropean() 17 | elif type == African: 18 | return AFRICAN() 19 | elif type == NORWEGIAN: 20 | return Norwegian() 21 | 22 | class Country: 23 | name = None 24 | def speed(self): 25 | pass 26 | 27 | class Eropean(Country): 28 | name = 'EROPEAN' 29 | 30 | def speed(self): 31 | return getbase_speed() 32 | 33 | class African(Country): 34 | name = 'AFRICAN' 35 | def speed(self): 36 | return getbase_speed() - get_loadfactor() 37 | 38 | class Norwegian(Country): 39 | name = 'NORWEGIAN' 40 | def speed(self): 41 | return 2 * getbase_speed() 42 | 43 | 44 | if __name__ == "__main__": 45 | country = CountryFactory.create(2) 46 | print(country.speed()) 47 | 48 | 49 | -------------------------------------------------------------------------------- /00RefactoringPython/ch11Handle_Generalization/i3template_method.py: -------------------------------------------------------------------------------- 1 | from mycolor import show 2 | 3 | class Statement: 4 | 5 | def header_string(self): 6 | pass 7 | 8 | def each_rental_string(self): 9 | pass 10 | 11 | def footer_string(self): 12 | pass 13 | 14 | def go(self): 15 | self.header_string() 16 | self.each_rental_string() 17 | self.footer_string() 18 | 19 | class HtmlStatement(Statement): 20 | 21 | def header_string(self): 22 | print(" hello ") 23 | 24 | def each_rental_string(self): 25 | print("
test

") 26 | 27 | def footer_string(self): 28 | print("

You owe it


") 29 | 30 | class TextStatement(Statement): 31 | 32 | def header_string(self): 33 | print( "Hello") 34 | 35 | def each_rental_string(self): 36 | print( "\t test \t") 37 | 38 | def footer_string(self): 39 | print( "You owe it") 40 | 41 | h = Statement() 42 | if 'want to html state': 43 | h = HtmlStatement() 44 | 45 | h.go() 46 | if 'wanto to text state': 47 | h = TextStatement() 48 | h.go() 49 | -------------------------------------------------------------------------------- /university_counselor/b9365_ProgrammingQs/day3_5end/config.py: -------------------------------------------------------------------------------- 1 | class Config(object): 2 | SECRET_KEY = '736670cb10a600b695a55839ca3a5aa54a7d7356cdef815d2ad6e19a2031182b' 3 | 4 | 5 | class ProdConfig(Config): 6 | DEBUG = False 7 | SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://{user}:{pwd}@{host}/{database}'.format( 8 | user=environ.get('DB_USER', 'root'), 9 | pwd=environ.get('MYSQLCONNSTR_DB_PWD', ''), 10 | host=environ.get('DB_HOST', 'localhost'), 11 | database=environ.get('DB_NAME', 'blog_db'), 12 | charset='utf8mb4', # The characterset you need 13 | ) 14 | 15 | SQLALCHEMY_TRACK_MODIFICATIONS = False 16 | 17 | 18 | 19 | class DevConfig(Config): 20 | DEBUG = True 21 | SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://{user}:{pwd}@{host}/{database}'.format( 22 | user=environ.get('DB_USER', 'root'), 23 | pwd=environ.get('MYSQLCONNSTR_DB_PWD', ''), 24 | host=environ.get('DB_HOST', 'localhost'), 25 | database=environ.get('DB_NAME', 'blog_db'), 26 | charset='utf8mb4', # The characterset you need 27 | ) 28 | 29 | SQLALCHEMY_TRACK_MODIFICATIONS = False 30 | -------------------------------------------------------------------------------- /Software Architecture with Python/3Testability/test_palindrome2.py: -------------------------------------------------------------------------------- 1 | # Code Listing - #13 2 | 3 | """ 4 | Module test_palindrome - TDD for palindrome module 5 | """ 6 | 7 | # Note: This is the second version of test_palindrome, so called test_palindrome2.py 8 | 9 | import palindrome 10 | 11 | def test_basic(): 12 | """ Basic test for palindrome """ 13 | 14 | # True positives 15 | for test in ('Rotator','bob','madam','mAlAyAlam', '1'): 16 | assert palindrome.is_palindrome(test)==True 17 | 18 | # True negatives 19 | for test in ('xyz','elephant', 'Country'): 20 | assert palindrome.is_palindrome(test)==False 21 | 22 | def test_with_spaces(): 23 | """ Testing palindrome strings with extra spaces """ 24 | 25 | # True positives 26 | for test in ('Able was I ere I saw Elba', 27 | 'Madam Im Adam', 28 | 'Step on no pets', 29 | 'Top spot'): 30 | assert palindrome.is_palindrome(test)==True 31 | 32 | # True negatives 33 | for test in ('Top post','Wonderful fool','Wild Imagination'): 34 | assert palindrome.is_palindrome(test)==False 35 | 36 | 37 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch4Using Modules for Real-World/charter/renderers/renderer.py: -------------------------------------------------------------------------------- 1 | from .png import title as title_png 2 | from .png import x_axis as x_axis_png 3 | from .png import y_axis as y_axis_png 4 | from .png import bar_series as bar_series_png 5 | from .png import line_series as line_series_png 6 | 7 | from .pdf import title as title_pdf 8 | from .pdf import x_axis as x_axis_pdf 9 | from .pdf import y_axis as y_axis_pdf 10 | from .pdf import bar_series as bar_series_pdf 11 | from .pdf import line_series as line_series_pdf 12 | 13 | renderers = { 14 | 'png' : { 15 | 'title' : title_png, 16 | 'x_axis' : x_axis_png, 17 | 'y_axis' : y_axis_png, 18 | 'bar_series' : bar_series_png, 19 | 'line_series' : line_series_png 20 | }, 21 | 'pdf' : { 22 | 'title' : title_pdf, 23 | 'x_axis' : x_axis_pdf, 24 | 'y_axis' : y_axis_pdf, 25 | 'bar_series' : bar_series_pdf, 26 | 'line_series' : line_series_pdf 27 | } 28 | } 29 | 30 | def draw(format, element, chart, output): 31 | renderers[format][element].draw(chart, output) -------------------------------------------------------------------------------- /00RefactoringPython/ch9Simplify_Conditional_Expression/i1decompose_conditonal.py: -------------------------------------------------------------------------------- 1 | import random 2 | import datetime 3 | from dateutil import parser 4 | from mycolor import show 5 | 6 | winter_rate = 0.01 7 | summer_rate = 0.02 8 | mydate = parser.parse('2018-02-27').date() 9 | mydate += datetime.timedelta(days=random.randint(-300, 300)) 10 | print(mydate) 11 | myquantity = 10000 12 | 13 | SUMMER_START = parser.parse('2018-06-01').date() 14 | SUMMER_END = parser.parse('2018-09-01').date() 15 | if mydate < SUMMER_START or mydate > SUMMER_END: 16 | charge = myquantity * winter_rate * 1.1 17 | else: 18 | charge = myquantity * summer_rate 19 | 20 | print(show(charge)) 21 | print('- · - - · - - · - - · - ') 22 | 23 | def not_summer(mydate): 24 | if mydate < SUMMER_START or mydate > SUMMER_END: 25 | return True 26 | else: 27 | return False 28 | 29 | def winter_charge(quantity): 30 | return quantity * winter_rate * 1.1 31 | 32 | def summer_charge(quantity): 33 | return quantity * summer_rate 34 | 35 | if not_summer(mydate): 36 | charge1 = winter_charge(myquantity) 37 | else: 38 | charge1 = summer_charge(myquantity) 39 | 40 | print(show(charge1, 'red')) -------------------------------------------------------------------------------- /00RefactoringPython/ch6Reorganize_Functions/i7remove_assignment_to_parameter.py: -------------------------------------------------------------------------------- 1 | from datetime import date 2 | from termcolor import colored 3 | from myfinal import MyPyFinal 4 | from dateutil import parser 5 | 6 | def show(s,color='green'): 7 | return colored(s, color, attrs=['reverse', 'blink']) 8 | 9 | 10 | 11 | def discount(input_val, quantity, year_to_date): 12 | if input_val > 50: 13 | input_val -=2 14 | b = date(1986,1,10) 15 | dt = parser.parse(year_to_date).date() 16 | days = (dt - b).days 17 | return input_val * quantity * days 18 | 19 | r = discount(100, 10, '2018-02-22') 20 | print('old way which need to refactory: get_distance_travelled=', show(r)) 21 | 22 | print(show('降低了代码清晰度,如果你只以参数表示 被传递进来的东西,那么代码会更清澈')) 23 | 24 | def discount_after_refactory(input_val, quantity, year_to_date): 25 | result = input_val 26 | if input_val > 50: 27 | result -=2 28 | b = date(1986,1,10) 29 | dt = parser.parse(year_to_date).date() 30 | days = (dt - b).days 31 | return input_val * quantity * days 32 | 33 | after = discount_after_refactory(100, 10, '2018-02-22') 34 | print('old way which need to refactory: get_distance_travelled=', show(after, 'red')) -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch4Using Modules for Real-World/charter/renderers/pdf/line_series.py: -------------------------------------------------------------------------------- 1 | # charter.renderers.pdf.line_series 2 | # 3 | # Renderer for drawing a line series onto the chart in PDF format. 4 | 5 | from ...constants import * 6 | 7 | ############################################################################# 8 | 9 | def draw(chart, canvas): 10 | avail_width = CHART_WIDTH - Y_AXIS_WIDTH - MARGIN 11 | bucket_width = avail_width / len(chart['x_axis']) 12 | 13 | bottom = X_AXIS_HEIGHT 14 | max_top = CHART_HEIGHT - TITLE_HEIGHT 15 | avail_height = max_top - bottom 16 | 17 | left = Y_AXIS_WIDTH 18 | prev_y = None 19 | for y_value in chart['series']: 20 | y = ((y_value - chart['y_min']) / 21 | (chart['y_max'] - chart['y_min'])) 22 | 23 | cur_y = bottom + int(y * avail_height) 24 | 25 | if prev_y != None: 26 | canvas.setStrokeColorRGB(0.25, 0.25, 0.625) 27 | canvas.setLineWidth(1) 28 | canvas.line(left - bucket_width / 2, prev_y, 29 | left + bucket_width / 2, cur_y) 30 | 31 | prev_y = cur_y 32 | left = left + bucket_width 33 | 34 | -------------------------------------------------------------------------------- /00RefactoringPython/ch11Handle_Generalization/i0pull_up.py: -------------------------------------------------------------------------------- 1 | from mycolor import show 2 | 3 | class Employee_Old: 4 | pass 5 | 6 | 7 | class Salesman_Old(Employee_Old): 8 | def __init__(self, name): 9 | self.name = name 10 | 11 | def set_workedyears(self, year): 12 | self.workedyears = year 13 | class Enginner_Old(Employee_Old): 14 | def __init__(self, name): 15 | self.name = name 16 | 17 | def set_workedyears(self, year): 18 | self.workedyears = year 19 | 20 | s = Salesman_Old('salesman0') 21 | e = Enginner_Old('enginner0') 22 | print(s.name, e.name) 23 | s.set_workedyears(2) 24 | e.set_workedyears(5) 25 | print(s.workedyears, e.workedyears) 26 | 27 | print('-------------改造开始-----------------') 28 | class Employee: 29 | def __init__(self, name): 30 | self.name = name 31 | 32 | def set_workedyears(self, year): 33 | self.workedyears = year 34 | class Salesman(Employee): 35 | pass 36 | 37 | class Enginner(Employee): 38 | pass 39 | 40 | s1 = Salesman('salesman1') 41 | e1 = Enginner('enginner1') 42 | s1.set_workedyears(2) 43 | e1.set_workedyears(5) 44 | print(show(s1.name), show(e1.name)) 45 | print(s1.workedyears, e1.workedyears) -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch4Using Modules for Real-World/charter/renderers/pdf/bar_series.py: -------------------------------------------------------------------------------- 1 | # charter.renderers.pdf.line_series 2 | # 3 | # Renderer for drawing a bar series onto the chart in PDF format. 4 | 5 | from ...constants import * 6 | 7 | ############################################################################# 8 | 9 | def draw(chart, canvas): 10 | avail_width = CHART_WIDTH - Y_AXIS_WIDTH - MARGIN 11 | bucket_width = avail_width / len(chart['x_axis']) 12 | 13 | bottom = X_AXIS_HEIGHT 14 | max_top = CHART_HEIGHT - TITLE_HEIGHT 15 | avail_height = max_top - bottom 16 | 17 | left = Y_AXIS_WIDTH 18 | for y_value in chart['series']: 19 | bar_left = left + MARGIN / 2 20 | bar_width = bucket_width - MARGIN 21 | 22 | y = ((y_value - chart['y_min']) / 23 | (chart['y_max'] - chart['y_min'])) 24 | 25 | bar_height = int(y * avail_height) 26 | 27 | canvas.setStrokeColorRGB(0.25, 0.25, 0.625) 28 | canvas.setFillColorRGB(0.906, 0.906, 0.953) 29 | canvas.rect(bar_left, bottom, bar_width, bar_height, 30 | stroke=True, fill=True) 31 | 32 | left = left + bucket_width 33 | 34 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch4Using Modules for Real-World/charter/renderers/png/line_series.py: -------------------------------------------------------------------------------- 1 | # charter.renderers.png.line_series 2 | # 3 | # Renderer for drawing a line series onto the chart in PNG format. 4 | 5 | from PIL import ImageFont 6 | 7 | from ...constants import * 8 | 9 | ############################################################################# 10 | 11 | def draw(chart, drawer): 12 | avail_width = CHART_WIDTH - Y_AXIS_WIDTH - MARGIN 13 | bucket_width = avail_width / len(chart['x_axis']) 14 | 15 | max_top = TITLE_HEIGHT 16 | bottom = CHART_HEIGHT - X_AXIS_HEIGHT 17 | avail_height = bottom - max_top 18 | 19 | left = Y_AXIS_WIDTH 20 | prev_y = None 21 | for y_value in chart['series']: 22 | y = ((y_value - chart['y_min']) / 23 | (chart['y_max'] - chart['y_min'])) 24 | 25 | cur_y = max_top + (avail_height - int(y * avail_height)) 26 | 27 | if prev_y != None: 28 | drawer.line([(left - bucket_width / 2, prev_y), 29 | (left + bucket_width / 2), cur_y], 30 | fill="#4040a0", width=1) 31 | prev_y = cur_y 32 | left = left + bucket_width 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /00RefactoringPython/ch9Simplify_Conditional_Expression/i5nested_conditiaon_to_guard_clause.py: -------------------------------------------------------------------------------- 1 | from mycolor import show 2 | 3 | is_dead = False 4 | is_seperate = True 5 | is_retired = False 6 | def dead_amount(): 7 | return 100000 8 | 9 | def seperate_amount(): 10 | return 50000 11 | 12 | def retire_amount(): 13 | return 20000 14 | 15 | def normal_amount(): 16 | return 10000 17 | 18 | def get_pay_amount_old(): 19 | result = None 20 | if is_dead: 21 | result = dead_amount() 22 | else: 23 | if is_seperate: 24 | result = seperate_amount() 25 | else: 26 | if is_retired: 27 | result = retire_amount() 28 | else: 29 | result = normal_amount() 30 | 31 | return result 32 | 33 | t = get_pay_amount_old() 34 | print(show(t)) 35 | 36 | print('函数种条件逻辑让人非常难以看清楚正常的执行路径 ' + 37 | ' 使用卫语句表现所有特殊情况') 38 | print('- · - - · - - · - - · - ') 39 | 40 | def get_pay_amount(): 41 | if is_dead: 42 | return dead_amount() 43 | if is_seperate: 44 | return seperate_amount() 45 | if is_retired: 46 | return retire_amount() 47 | return normal_amount() 48 | 49 | n = get_pay_amount() 50 | print(show(n, 'red')) -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch4Using Modules for Real-World/charter/renderers/png/bar_series.py: -------------------------------------------------------------------------------- 1 | # charter.renderers.png.bar_series 2 | # 3 | # Renderer for drawing a bar series onto the chart in PNG format. 4 | 5 | from PIL import ImageFont 6 | 7 | from ...constants import * 8 | 9 | ############################################################################# 10 | 11 | def draw(chart, drawer): 12 | avail_width = CHART_WIDTH - Y_AXIS_WIDTH - MARGIN 13 | bucket_width = avail_width / len(chart['x_axis']) 14 | 15 | max_top = TITLE_HEIGHT 16 | bottom = CHART_HEIGHT - X_AXIS_HEIGHT 17 | avail_height = bottom - max_top 18 | 19 | left = Y_AXIS_WIDTH 20 | for y_value in chart['series']: 21 | bar_left = left + MARGIN / 2 22 | bar_right = left + bucket_width - MARGIN / 2 23 | 24 | y = ((y_value - chart['y_min']) / 25 | (chart['y_max'] - chart['y_min'])) 26 | 27 | bar_top = max_top + (avail_height - int(y * avail_height)) 28 | 29 | drawer.rectangle([(bar_left, bar_top), 30 | (bar_right + 1, 31 | bottom)], 32 | fill="#e8e8f4", outline="#4040a0") 33 | 34 | left = left + bucket_width 35 | -------------------------------------------------------------------------------- /00RefactoringPython/ch7Move_attribute_between_Objects/i1move_field.py: -------------------------------------------------------------------------------- 1 | import random 2 | from termcolor import colored 3 | 4 | random_int = random.randint(5,20) 5 | 6 | 7 | def show(s,color='green'): 8 | return colored(s, color, attrs=['reverse', 'blink']) 9 | 10 | ''' 11 | 假设有几种账户,每一种都有自己的‘透支金额计费计划‘ 12 | ''' 13 | class Account: 14 | def __init__(self, interest_rate=0.01): 15 | self.type = AccountType() 16 | self.interest_rate = interest_rate 17 | 18 | def interst_for_amount_days(self, amount, days): 19 | return self.interest_rate * amount * days / 365 20 | 21 | class AccountType: 22 | pass 23 | 24 | at = Account() 25 | print('旧模式下:' + show(at.interst_for_amount_days(1000, 100))) 26 | 27 | print(show('开始改造:---------->>>>>>>>>')) 28 | 29 | class Account_afterRefactory: 30 | def __init__(self): 31 | self.type = AccountType_afterRefactory() 32 | 33 | 34 | def interst_for_amount_days(self, amount, days): 35 | return self.type.interest_rate * amount * days / 365 36 | 37 | class AccountType_afterRefactory: 38 | def __init__(self, interest_rate=0.01): 39 | self.interest_rate = interest_rate 40 | 41 | at1 = Account_afterRefactory() 42 | print('新式下:' + show(at.interst_for_amount_days(1000, 100), 'red')) -------------------------------------------------------------------------------- /00RefactoringPython/ch10Simplify_Function_Call/i1seperate_query_from_modifier.py: -------------------------------------------------------------------------------- 1 | from mycolor import show 2 | 3 | print('某个函数既返回对象状态值, 又修改对象状态' 4 | + '建立2个不同函数,其中一个负责查询,另一个负责修改') 5 | 6 | def send_alert_old(): 7 | print('send_alert_old') 8 | 9 | def found_miscreant_old(people): 10 | for p in people: 11 | if p == 'Don': 12 | send_alert_old() 13 | return 'Don' 14 | if p == 'John': 15 | send_alert_old() 16 | return 'John' 17 | return '' 18 | 19 | def somelatercode(p): 20 | print('somelatercode(' + p + ')') 21 | 22 | def check_security_old(people): 23 | found = found_miscreant_old(people) 24 | somelatercode(found) 25 | 26 | check_security_old(['Abel', 'Don']) 27 | 28 | print('-------------改造开始-----------------') 29 | 30 | def found_person(people): 31 | for p in people: 32 | if p == 'Don': 33 | return 'Don' 34 | if p == 'John': 35 | return 'John' 36 | return '' 37 | 38 | def send_alert(people): 39 | if found_person(people) != '': 40 | send_alert_old() 41 | 42 | 43 | def check_security(people): 44 | send_alert(people) 45 | found = found_person(people) 46 | somelatercode(found) 47 | 48 | check_security(['Abel', 'Don']) -------------------------------------------------------------------------------- /Software Architecture with Python/3Testability/selenium_testcase.py: -------------------------------------------------------------------------------- 1 | # Code Listing - #10 2 | 3 | """ 4 | Module selenium_testcase - Example of implementing an automated UI test using selenium framework 5 | """ 6 | 7 | from selenium import webdriver 8 | import pytest 9 | import contextlib 10 | 11 | @contextlib.contextmanager 12 | @pytest.fixture(scope='session') 13 | def setup(): 14 | driver = webdriver.Firefox() 15 | yield driver 16 | driver.quit() 17 | 18 | def test_python_dotorg(): 19 | """ Test details of python.org website URLs """ 20 | 21 | with setup() as driver: 22 | driver.get('http://www.python.org') 23 | # Some tests 24 | assert driver.title == 'Welcome to Python.org' 25 | # Find out the 'Community' link 26 | comm_elem = driver.find_elements_by_link_text('Community')[0] 27 | # Get the URL 28 | comm_url = comm_elem.get_attribute('href') 29 | # Visit it 30 | print ('Community URL=>',comm_url) 31 | driver.get(comm_url) 32 | # Assert its title 33 | assert driver.title == 'Our Community | Python.org' 34 | assert comm_url == 'https://www.python.org/community/' 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /00RefactoringPython/ch8Reorganize_Data/i5change_unidirect_to_bidirect.py: -------------------------------------------------------------------------------- 1 | from mycolor import show 2 | 3 | class Order: 4 | def __init__(self, customer): 5 | self.customer = customer 6 | 7 | class Customer: 8 | def __init__(self, name): 9 | self.name = name 10 | 11 | d0 = Order(Customer('xiaoming0')) 12 | print(d0.customer.name) 13 | 14 | print(show('开始改造'),'- > -'*5) 15 | 16 | class Order_afterRF: 17 | def __init__(self, customers=None): 18 | self.customers = customers 19 | 20 | def add_customer(self, customer): 21 | self.customers.append(customer) 22 | 23 | def remove_customer(self, customer): 24 | if customer in self.customers: 25 | self.customers.remove(customer) 26 | 27 | class Customer_afterRF: 28 | def __init__(self, name, orders=None): 29 | self.name = name 30 | self.orders = orders 31 | 32 | def add_order(self, order): 33 | self.orders.append(order) 34 | 35 | def remove_order(self, order): 36 | if order in self.orders: 37 | self.orders.remove(order) 38 | 39 | c1 = Customer_afterRF('xiaoming1') 40 | c2 = Customer_afterRF('xiaoming2') 41 | c3 = Customer_afterRF('xiaoming3') 42 | d1 = Order_afterRF([c1, c2, c3]) 43 | for customer in d1.customers: 44 | print(customer.name) 45 | -------------------------------------------------------------------------------- /Software Architecture with Python/3Testability/datetimehelper.py: -------------------------------------------------------------------------------- 1 | # Code Listing #3 2 | 3 | """ Module datetime helper - Contains the class DateTimeHelper providing 4 | some helpful methods for working with date and datetime objects """ 5 | 6 | import datetime 7 | 8 | class DateTimeHelper(object): 9 | """ A class which provides some convenient date/time 10 | conversion and utility methods """ 11 | 12 | def today(self): 13 | """ Return today's datetime """ 14 | return datetime.datetime.now() 15 | 16 | def date(self): 17 | """ Return today's date in the form of DD/MM/YYYY """ 18 | return self.today().strftime("%d/%m/%Y") 19 | 20 | def weekday(self): 21 | """ Return the full week day for today """ 22 | return self.today().strftime("%A") 23 | 24 | def us_to_indian(self, date): 25 | """ Convert a U.S style date i.e mm/dd/yy to Indian style i.e dd/mm/yyyy """ 26 | 27 | # Split it 28 | mm,dd,yy = date.split('/') 29 | yy = int(yy) 30 | # Check if year is >16, else add 2000 to it 31 | if yy<=16: yy += 2000 32 | # Create a date object from it 33 | date_obj = datetime.date(year=yy, month=int(mm), day=int(dd)) 34 | # Retur it in correct format 35 | return date_obj.strftime("%d/%m/%Y") 36 | 37 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch1modular_program_with_py/i2shaghetti/spaghetti.py: -------------------------------------------------------------------------------- 1 | import configparser 2 | 3 | def load_config(): 4 | config = configparser.ConfigParser() 5 | config.read("config.ini") 6 | # print("config['config']=", config['config']) 7 | return config['config'] 8 | 9 | 10 | def get_data_from_user(): 11 | config = load_config() 12 | data = [] 13 | for n in range(config.getint('num_data_points')): 14 | value = input("Data point {}: ".format(n+1)) 15 | data.append(value) 16 | return data 17 | 18 | def print_results(results): 19 | for value,num_times in results: 20 | print("{} 出现次数 = {}".format(value, num_times)) 21 | 22 | def analyze_data(): 23 | data = get_data_from_user() 24 | results = {} 25 | for value in data: 26 | try: 27 | results[value] = results[value] + 1 28 | except KeyError: 29 | results[value] = 1 30 | return results 31 | 32 | def sort_results(results): 33 | sorted_results = [] 34 | for value in results.keys(): 35 | sorted_results.append((value, results[value])) 36 | sorted_results.sort() 37 | return sorted_results 38 | 39 | if __name__ == "__main__": 40 | results = analyze_data() 41 | sorted_results = sort_results(results) 42 | print_results(sorted_results) 43 | -------------------------------------------------------------------------------- /a13814_uml/note.md: -------------------------------------------------------------------------------- 1 | @startuml 2 | skinparam sequenceArrowThickness 2 3 | skinparam roundcorner 20 4 | skinparam maxmessagezie 60 5 | skinparam sequenceParticipant underline 6 | 7 | actor StudentClass 8 | participant "AutoAssignClass" as A 9 | participant "PersonerTutorClass" as B 10 | 11 | StudentClass -> A: enroll/tranforclass 12 | activate A 13 | 14 | A -> B: (create/transfer) auto_assign 15 | activate B 16 | 17 | B -> StudentClass: Assign Created 18 | deactivate B 19 | @enduml 20 | 21 | 22 | ---- 23 | 24 | @startuml 25 | skinparam sequenceArrowThickness 2 26 | skinparam roundcorner 20 27 | skinparam maxmessagezie 60 28 | skinparam sequenceParticipant underline 29 | 30 | actor Tutor 31 | participant "AutoAssignClass" as A 32 | participant "StudentClass" as B 33 | 34 | Tutor -> A: (search_students/delete_student/alter_student) 35 | activate A 36 | 37 | A -> B: (all_student/search_student) request 38 | activate B 39 | 40 | B -> AutoAssignClass: operation_result(finshed or failed) 41 | deactivate B 42 | @enduml 43 | 44 | -- 45 | 46 | 47 | http://www.plantuml.com/plantuml/uml/RSwnJWCn3CRnFKzXTO81KNLWk04rrnUeH5_0Iao9Ud4Esm74qvChI1Uapjyl_tYlXc8rJqulYMSKpA3qNea3UP7oUNfBuSAa2hkEIAaSGn4cWTss6p9-vORnJD-9u6bx8tj4iHJIZ6pGAYHJOd8EWnM15wkHs0uJghgvanjVhNZLTERhk05KyF_9aKGBavmQbLMDplLPU7W6Fm3-zNZvENsWKSivlwpZ07T128qUJP3rbUGUP3bVRTKjEowwRm_mUo8Shi-ZYzJvFN6iUVe1 -------------------------------------------------------------------------------- /00RefactoringPython/ch2Principles/i01what_why_when.md: -------------------------------------------------------------------------------- 1 | 重构: 对软件内部结构的一种调整,目的是在不改变软件可观察行为的前提下, 2 | 提供可理解性,降低修改成本。 3 | 4 | 重构就只是整理代码? 5 | 某种程度是的,但重构不止于此,它提供了一种更高效而且受控的代码整理技术。 6 | 7 | 重构和性能优化? 8 | 性能优化通常也不改变组件的行为(除了速度),但是2者出发点不同: 9 | 性能优化往往让代码较难理解,但为了得到所需性能你不得不这么做。 10 |

11 | 12 | ![](https://raw.githubusercontent.com/greatabel/RefactoringPython/master/ch2Principles/2hats.jpeg) 13 |  添加新功能时候,你不应该修改既有代码,只管添加新功能。。通过测试,衡量工作进度。
14 |  重构时候你就不能再添加功能,只管改进程序结构。此时不应该添加测试。
15 | 软件开发中,你可能发现自己经常变换帽子,可能来回切换,但是无论何时你都要清楚自己戴的是哪一顶帽子。 16 | 17 | ![#f03c15](https://placehold.it/15/f03c15/000000?text=+) 18 | why 需要重构? 19 | 1. 改进软件设计
20 | ···重构就像整理代码,让所有东西回到应处的位置,代码结构流失是累积性。
21 | ···经常性的重构帮助代码维护自己该有的形态 22 | 2. 让软件更容易理解
23 | 24 | 早起重构像:擦掉窗户上的污垢,使得你看的更远。重构把我带上更高理解层次;如果没有重构,我达不到这种层次。
25 | 3. 重构提高编程速度 26 | ···重构帮助你更快速的开发程序
27 | ···良好的设计是快速开发的根本 28 | 29 | 30 | 31 | ![#b49ee5](https://placehold.it/15/b49ee5/000000?text=+) 32 | when 需要重构? 33 | - 事不过三, 三则重构 34 | - 添加功能时候 35 | - 修补错误时候 36 | - review代码时候 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /00RefactoringPython/ch7Move_attribute_between_Objects/i2extract_class.py: -------------------------------------------------------------------------------- 1 | import random 2 | from termcolor import colored 3 | 4 | 5 | def show(s,color='green'): 6 | return colored(s, color, attrs=['reverse', 'blink']) 7 | 8 | class Person(object): 9 | """docstring for Person""" 10 | def __init__(self, name, office_area_code, 11 | office_number): 12 | self.name = name 13 | self.office_area_code = office_area_code 14 | self.office_number = office_number 15 | 16 | def get_telephone_number(self): 17 | return "(" + self.office_area_code + ") " + self.office_number 18 | 19 | p = Person('Stone', '0613', '00001') 20 | print('旧模式下:' + show(p.get_telephone_number())) 21 | 22 | class Person_afterRefactory(object): 23 | """docstring for Person""" 24 | def __init__(self, name, telephone_number): 25 | self.name = name 26 | 27 | self.telephone_number = telephone_number 28 | 29 | def get_telephone_number(self): 30 | return "(" + self.telephone_number.area_code + ") " + self.telephone_number.number 31 | 32 | class TelephoneNumber: 33 | def __init__(self, area_code, number): 34 | self.area_code = area_code 35 | self.number = number 36 | 37 | p = Person_afterRefactory('Stone', TelephoneNumber('0613', '00001')) 38 | print('new模式下:' + show(p.get_telephone_number(), 'red')) -------------------------------------------------------------------------------- /Software Architecture with Python/3Testability/test_textsearch.py: -------------------------------------------------------------------------------- 1 | # Code Listing - #8 2 | 3 | """ 4 | Module test_textsearch - Unittest case with mocks for textsearch module 5 | """ 6 | 7 | from unittest.mock import Mock, MagicMock 8 | import textsearcher 9 | import operator 10 | 11 | def test_search(): 12 | """ Test search via a mock """ 13 | 14 | # Mock the database object 15 | db = Mock() 16 | searcher = textsearcher.TextSearcher(db) 17 | # Verify connect has been called with no arguments 18 | db.connect.assert_called_with() 19 | # Setup searcher 20 | searcher.setup(cache=True, max_items=100) 21 | # Verify configure called on db with correct parameter 22 | searcher.db.configure.assert_called_with(max_items=100) 23 | 24 | canned_results = [('Python is wonderful', 0.4), 25 | ('I like Python',0.8), 26 | ('Python is easy', 0.5), 27 | ('Python can be learnt in an afternoon!', 0.3)] 28 | db.query = MagicMock(return_value=canned_results) 29 | 30 | # Mock the results data 31 | keyword, num = 'python', 3 32 | data = searcher.get_results(keyword,num=num) 33 | searcher.db.query.assert_called_with(keyword) 34 | 35 | # Verify data 36 | results = sorted(canned_results, key=operator.itemgetter(1), reverse=True)[:num] 37 | assert data == results 38 | 39 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch1modular_program_with_py/i3cache/cache.py: -------------------------------------------------------------------------------- 1 | # cache.py 2 | 3 | import datetime 4 | 5 | MAX_CACHE_SIZE = 100 # Maximum number of entries in the cache. 6 | 7 | ############################################################################# 8 | 9 | def init(): 10 | global _cache 11 | _cache = {} # Maps key to (timestamp, value) tuple. 12 | 13 | 14 | def set(key, value): 15 | global _cache 16 | if key not in _cache and len(_cache) >= MAX_CACHE_SIZE: 17 | _remove_oldest_entry() 18 | _cache[key] = [datetime.datetime.now(), value] 19 | 20 | 21 | def get(key): 22 | global _cache 23 | if key in _cache: 24 | _cache[key][0] = datetime.datetime.now() 25 | return _cache[key][1] 26 | else: 27 | return None 28 | 29 | 30 | def contains(key): 31 | global _cache 32 | return key in _cache 33 | 34 | 35 | def size(): 36 | global _cache 37 | return len(_cache) 38 | 39 | ############################################################################# 40 | 41 | # Private functions: 42 | 43 | def _remove_oldest_entry(): 44 | global _cache 45 | oldest = None 46 | for key in _cache.keys(): 47 | if oldest == None: 48 | oldest = key 49 | elif _cache[key][0] < _cache[oldest][0]: 50 | oldest = key 51 | 52 | if oldest != None: 53 | del _cache[oldest] 54 | 55 | -------------------------------------------------------------------------------- /00RefactoringPython/ch8Reorganize_Data/d1oberver_pattern.py: -------------------------------------------------------------------------------- 1 | # https://stackoverflow.com/questions/48336820/using-decorators-to-implement-observer-pattern-in-python3 2 | 3 | class Event(object): 4 | def __init__(self): 5 | self.callbacks = [] 6 | 7 | def notify(self, *args, **kwargs): 8 | for callback in self.callbacks: 9 | callback(*args, **kwargs) 10 | 11 | def register(self, callback): 12 | self.callbacks.append(callback) 13 | return callback 14 | 15 | class SomeData(object): 16 | def __init__(self, foo): 17 | self.changed = Event() 18 | self._foo = foo 19 | 20 | @property 21 | def foo(self): 22 | return self._foo 23 | 24 | @foo.setter 25 | def foo(self, value): 26 | self._foo = value 27 | self.changed.notify(self, 'foo', value) 28 | 29 | class SomeGUI(object): 30 | def redraw(self, obj, key, newvalue): 31 | print('redrawing %s with value %s' % (self, newvalue)) 32 | 33 | 34 | if __name__ == '__main__': 35 | my_data = SomeData(42) 36 | 37 | # Register some function using decorator syntax 38 | @my_data.changed.register 39 | def print_it(obj, key, value): 40 | print('Key %s changed to %s' % (key, value)) 41 | 42 | # Register the SomeGUI element 43 | my_gui = SomeGUI() 44 | my_data.changed.register(my_gui.redraw) 45 | 46 | # Try changing it. 47 | my_data.foo = 10 -------------------------------------------------------------------------------- /Software Architecture with Python/3Testability/url_data.py: -------------------------------------------------------------------------------- 1 | # Code Listing #1 2 | import hashlib 3 | import requests 4 | 5 | def get_url_data(url): 6 | """ Return data for a URL """ 7 | 8 | # Return data while saving the data in a file 9 | # which is a hash of the URL 10 | data = requests.get(url).content 11 | # Save it in a filename 12 | filename = hashlib.md5(url).hexdigest() 13 | open(filename, 'w').write(data) 14 | return data 15 | 16 | import os 17 | 18 | def get_url_data_stub(url): 19 | """ Stub function replacing get_url_data """ 20 | 21 | # No actual web request is made, instead 22 | # the file is opened and data returned 23 | filename = hashlib.md5(url).hexdigest() 24 | if os.path.isfile(filename): 25 | return open(filename).read() 26 | 27 | 28 | def get_url_data(url): 29 | """ Return data for a URL """ 30 | 31 | # First check for cached file - if so return its 32 | # contents. Note that we are not checking for 33 | # age of the file - so content may be stale. 34 | filename = hashlib.md5(url).hexdigest() 35 | if os.path.isfile(filename): 36 | return open(filename).read() 37 | 38 | # First time - so fetch the URL and write to the 39 | # file. In subsequent calls, the file contents will 40 | # be returned. 41 | data = requests.get(url).content 42 | open(filename, 'w').write(data) 43 | 44 | return data 45 | -------------------------------------------------------------------------------- /Software Architecture with Python/4Performance/primes.py: -------------------------------------------------------------------------------- 1 | # Code Listing #3 2 | """ 3 | 4 | Prime number iterator class 5 | 6 | """ 7 | 8 | class Prime(object): 9 | """ A prime number iterator for first 'n' primes """ 10 | 11 | def __init__(self, n): 12 | self.n = n 13 | self.count = 0 14 | self.value = 0 15 | 16 | def __iter__(self): 17 | return self 18 | 19 | def __next__(self): 20 | """ Return next item in iterator """ 21 | 22 | if self.count == self.n: 23 | raise StopIteration("end of iteration") 24 | return self.compute() 25 | 26 | # Uncomment next line for profiling with line profiler 27 | # or memory profiler. 28 | # @profile 29 | def is_prime(self): 30 | """ Whether current value is prime ? """ 31 | 32 | vroot = int(self.value ** 0.5) + 1 33 | for i in range(3, vroot, 2): 34 | if self.value % i == 0: 35 | return False 36 | return True 37 | 38 | def compute(self): 39 | """ Compute next prime """ 40 | 41 | # Second time, reset value 42 | if self.count == 1: 43 | self.value = 1 44 | 45 | while True: 46 | self.value += 2 47 | 48 | if self.is_prime(): 49 | self.count += 1 50 | break 51 | 52 | return self.value 53 | 54 | if __name__ == "__main__": 55 | l=list(Prime(1000)) 56 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch4Using Modules for Real-World/charter/renderers/png/y_axis.py: -------------------------------------------------------------------------------- 1 | # charter.renderers.png.y_axis 2 | # 3 | # Renderer for drawing a Y-axis onto the chart in PNG format. 4 | 5 | from PIL import ImageFont 6 | 7 | from ...constants import * 8 | 9 | ############################################################################# 10 | 11 | def draw(chart, drawer): 12 | font = ImageFont.truetype("Helvetica", 12) 13 | label_height = font.getsize("Test")[1] 14 | 15 | axis_top = TITLE_HEIGHT 16 | axis_bottom = CHART_HEIGHT - X_AXIS_HEIGHT 17 | axis_height = axis_bottom - axis_top 18 | 19 | drawer.line([(Y_AXIS_WIDTH, axis_top), 20 | (Y_AXIS_WIDTH, axis_bottom)], 21 | "#4040a0", 2) # Draw main axis line. 22 | 23 | for y_value in chart['y_labels']: 24 | y = ((y_value - chart['y_min']) / 25 | (chart['y_max'] - chart['y_min'])) 26 | 27 | y_pos = axis_top + (axis_height - int(y * axis_height)) 28 | 29 | drawer.line([(Y_AXIS_WIDTH - TICKMARK_HEIGHT, y_pos), 30 | (Y_AXIS_WIDTH, y_pos)], 31 | "#4040a0", 1) # Draw tickmark. 32 | 33 | label_width,label_height = font.getsize(str(y_value)) 34 | label_left = Y_AXIS_WIDTH - TICKMARK_HEIGHT - label_width - 4 35 | label_top = y_pos - label_height / 2 36 | 37 | drawer.text((label_left, label_top), str(y_value), 38 | "#000000", font) 39 | 40 | 41 | -------------------------------------------------------------------------------- /Software Architecture with Python/3Testability/textsearcher.py: -------------------------------------------------------------------------------- 1 | # Code Listing - #7 2 | 3 | """ 4 | Module textsearcher - Contains class TextSearcher for performing search on a database 5 | and returning results 6 | 7 | """ 8 | 9 | import operator 10 | 11 | class TextSearcher(object): 12 | """ A class which performs a text search and returns results """ 13 | 14 | def __init__(self, db): 15 | """ Initializer - keyword and database object """ 16 | 17 | self.cache = False 18 | self.cache_dict = {} 19 | self.db = db 20 | self.db.connect() 21 | 22 | def setup(self, cache=False, max_items=500): 23 | """ Setup parameters such as caching """ 24 | 25 | self.cache = cache 26 | # Call configure on the db 27 | self.db.configure(max_items=max_items) 28 | 29 | def get_results(self, keyword, num=10): 30 | """ Query keyword on db and get results for given keyword """ 31 | 32 | # If results in cache return from there 33 | if keyword in self.cache_dict: 34 | print ('From cache') 35 | return self.cache_dict[keyword] 36 | 37 | results = self.db.query(keyword) 38 | # Results are list of (string, weightage) tuples 39 | results = sorted(results, key=operator.itemgetter(1), reverse=True)[:num] 40 | # Cache it 41 | if self.cache: 42 | self.cache_dict[keyword] = results 43 | 44 | return results 45 | 46 | 47 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch4Using Modules for Real-World/charter/renderers/png/x_axis.py: -------------------------------------------------------------------------------- 1 | # charter.renderers.png.x_axis 2 | # 3 | # Renderer for drawing an X axis onto the chart in PNG format. 4 | 5 | from PIL import ImageFont 6 | 7 | from ...constants import * 8 | 9 | ############################################################################# 10 | 11 | def draw(chart, drawer): 12 | font = ImageFont.truetype("Helvetica", 12) 13 | label_height = font.getsize("Test")[1] 14 | 15 | avail_width = CHART_WIDTH - Y_AXIS_WIDTH - MARGIN 16 | bucket_width = avail_width / len(chart['x_axis']) 17 | 18 | axis_top = CHART_HEIGHT - X_AXIS_HEIGHT 19 | drawer.line([(Y_AXIS_WIDTH, axis_top), (CHART_WIDTH - MARGIN, axis_top)], 20 | "#4040a0", 2) # Draw main axis line. 21 | 22 | left = Y_AXIS_WIDTH 23 | for bucket_num in range(len(chart['x_axis'])): 24 | drawer.line([(left, axis_top), (left, axis_top + TICKMARK_HEIGHT)], 25 | "#4040a0", 1) # Draw tickmark 26 | 27 | label_width = font.getsize(chart['x_axis'][bucket_num])[0] 28 | label_left = max(left, left + bucket_width/2 - label_width/2) 29 | label_top = axis_top + TICKMARK_HEIGHT + 4 30 | 31 | drawer.text((label_left, label_top), chart['x_axis'][bucket_num], 32 | "#000000", font) 33 | 34 | left = left + bucket_width 35 | 36 | drawer.line([(left, axis_top), (left, axis_top + TICKMARK_HEIGHT)], 37 | "#4040a0", 1) # Draw final tickmark. 38 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch4Using Modules for Real-World/charter/generator.py: -------------------------------------------------------------------------------- 1 | """ generator.py 2 | 3 | This module implements the chart-generation logic for the Charter package. 4 | """ 5 | from PIL import Image, ImageDraw 6 | 7 | from reportlab.pdfgen.canvas import Canvas 8 | 9 | from .constants import * 10 | from .renderers import renderer 11 | 12 | ############################################################################# 13 | 14 | def generate_chart(chart, filename): 15 | if filename.lower().endswith(".pdf"): 16 | format = "pdf" 17 | elif filename.lower().endswith(".png"): 18 | format = "png" 19 | else: 20 | print("Unsupported file format: " + filename) 21 | return 22 | 23 | if format == "pdf": 24 | output = Canvas(filename) 25 | elif format == "png": 26 | image = Image.new("RGB", (CHART_WIDTH, CHART_HEIGHT), 27 | "#ffffff") 28 | output = ImageDraw.Draw(image) 29 | 30 | renderer.draw(format, "title", chart, output) 31 | renderer.draw(format, "x_axis", chart, output) 32 | renderer.draw(format, "y_axis", chart, output) 33 | if chart['series_type'] == "bar": 34 | renderer.draw(format, "bar_series", chart, output) 35 | elif chart['series_type'] == "line": 36 | renderer.draw(format, "line_series", chart, output) 37 | 38 | if format == "pdf": 39 | output.showPage() 40 | output.save() 41 | elif format == "png": 42 | image.save(filename, format="png") 43 | 44 | -------------------------------------------------------------------------------- /00RefactoringPython/ch8Reorganize_Data/d3state_pattern.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | from mycolor import show 3 | 4 | 5 | class State: 6 | def scan(self): 7 | print("Scanning... Station is", 8 | next(self.stations), self.name) 9 | 10 | class AmState(State): 11 | def __init__(self, radio): 12 | self.radio = radio 13 | self.stations = itertools.cycle( 14 | ['1000', '1001', '1002']) 15 | self.name = "AM" 16 | 17 | def toogle(self): 18 | print('switching to FM') 19 | self.radio.state = self.radio.fmstate 20 | 21 | 22 | class FmState(State): 23 | def __init__(self, radio): 24 | self.radio = radio 25 | self.stations = itertools.cycle( 26 | ['81.1', '82.2', '83.3']) 27 | self.name = 'FM' 28 | 29 | def toogle(self): 30 | print('switching to AM') 31 | self.radio.state = self.radio.amstate 32 | 33 | 34 | class Radio: 35 | """ 36 | A radio. 37 | It has a scan button, and an AM/FM toggle switch. 38 | """ 39 | def __init__(self): 40 | self.amstate = AmState(self) 41 | self.fmstate = FmState(self) 42 | self.state = self.amstate 43 | 44 | def toogle(self): 45 | self.state.toogle() 46 | 47 | def scan(self): 48 | self.state.scan() 49 | 50 | def main(): 51 | radio = Radio() 52 | actions = ([radio.scan] * 2 + 53 | [radio.toogle] + [radio.scan] * 2) * 2 54 | for action in actions: 55 | action() 56 | 57 | if __name__ == "__main__": 58 | main() -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch4Using Modules for Real-World/charter/renderers/pdf/y_axis.py: -------------------------------------------------------------------------------- 1 | # charter.renderers.pdf.y_axis 2 | # 3 | # Renderer for drawing a Y axis onto the chart in PDF format. 4 | 5 | from ...constants import * 6 | 7 | ############################################################################# 8 | 9 | def draw(chart, canvas): 10 | label_height = 12 * 1.2 11 | 12 | axis_top = CHART_HEIGHT - TITLE_HEIGHT 13 | axis_bottom = X_AXIS_HEIGHT 14 | axis_height = axis_top - axis_bottom 15 | 16 | # Draw main axis line. 17 | 18 | canvas.setStrokeColorRGB(0.25, 0.25, 0.625) 19 | canvas.setLineWidth(2) 20 | canvas.line(Y_AXIS_WIDTH, axis_top, Y_AXIS_WIDTH, axis_bottom) 21 | 22 | for y_value in chart['y_labels']: 23 | y = ((y_value - chart['y_min']) / 24 | (chart['y_max'] - chart['y_min'])) 25 | 26 | y_pos = axis_bottom + int(y * axis_height) 27 | 28 | # Draw tickmark. 29 | 30 | canvas.setLineWidth(1) 31 | canvas.line(Y_AXIS_WIDTH - TICKMARK_HEIGHT, y_pos, 32 | Y_AXIS_WIDTH, y_pos) 33 | 34 | # Draw label. 35 | 36 | label_width = canvas.stringWidth(str(y_value), 37 | "Helvetica", 12) 38 | label_left = Y_AXIS_WIDTH - TICKMARK_HEIGHT - label_width - 4 39 | label_bottom = y_pos - label_height/4 40 | 41 | canvas.setFont("Helvetica", 12) 42 | canvas.setFillColorRGB(0.0, 0.0, 0.0) 43 | canvas.drawString(label_left, label_bottom, str(y_value)) 44 | 45 | -------------------------------------------------------------------------------- /00RefactoringPython/ch8Reorganize_Data/i4duplicate_observed_data.py: -------------------------------------------------------------------------------- 1 | from mycolor import show 2 | 3 | class Event: 4 | def __init__(self): 5 | self.callbacks = [] 6 | 7 | def notify(self, *args, **kwargs): 8 | for callback in self.callbacks: 9 | callback(*args, **kwargs) 10 | 11 | def register(self, callback): 12 | self.callbacks.append(callback) 13 | return callback 14 | 15 | class SomeData(object): 16 | def __init__(self, foo): 17 | self.changed = Event() 18 | self._foo = foo 19 | print('#'*10, 1) 20 | 21 | @property 22 | def foo(self): 23 | print('#'*10, 2) 24 | return self._foo 25 | 26 | @foo.setter 27 | def foo(self, value): 28 | print('#'*10, 3) 29 | self._foo = value 30 | start, end = value 31 | print('length=', end - start) 32 | self.changed.notify(self, 'foo', value) 33 | 34 | 35 | 36 | class SomeGUI(object): 37 | def redraw(self, obj, key, newvalue): 38 | print('redrawing %s with value %s' % (self, newvalue)) 39 | 40 | if __name__ == '__main__': 41 | my_data = SomeData((4, 12)) 42 | print(my_data.foo) 43 | 44 | @my_data.changed.register 45 | def print_it(obj, key, value): 46 | print('Key %s changed to %s' % (key, value)) 47 | 48 | # Register the SomeGUI element 49 | my_gui = SomeGUI() 50 | my_data.changed.register(my_gui.redraw) 51 | 52 | # Try changing it. 53 | my_data.foo = (5, 10) 54 | my_data.foo = (5, 11) 55 | my_data.foo = (2, 11) 56 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch9Modular Programming as a Foundation for Good Programming Technique/i2counter-ranges/tests.py: -------------------------------------------------------------------------------- 1 | # This module implements various unit tests for the ``counter`` package. 2 | 3 | import unittest 4 | 5 | import counter 6 | 7 | class CounterTestCase(unittest.TestCase): 8 | """ Unit tests for the ``counter`` package. 9 | """ 10 | def test_counter_totals(self): 11 | counter.reset() 12 | counter.add(1) 13 | counter.add(2) 14 | counter.add(3) 15 | counter.add(1) 16 | self.assertEqual(counter.totals(), [(1, 2), (2, 1), (3, 1)]) 17 | 18 | def test_counter_reset(self): 19 | counter.reset() 20 | counter.add(1) 21 | counter.reset() 22 | counter.add(2) 23 | self.assertEqual(counter.totals(), [(2, 1)]) 24 | 25 | 26 | class RangeCounterTestCase(unittest.TestCase): 27 | """ Unit tests for the range-based features of ``counter`` package. 28 | """ 29 | def test_range_totals(self): 30 | counter.reset([0, 5, 10, 15]) 31 | counter.add(3) 32 | counter.add(9) 33 | counter.add(4.5) 34 | counter.add(12) 35 | counter.add(14.2) 36 | counter.add(8) 37 | self.assertEqual(counter.totals(), 38 | [(0, 5, 2), (5, 10, 2), (10, 15, 2)]) 39 | 40 | def test_out_of_range(self): 41 | counter.reset([0, 5, 10, 15]) 42 | with self.assertRaises(RuntimeError): 43 | counter.add(19.1) 44 | 45 | 46 | if __name__ == "__main__": 47 | unittest.main() 48 | 49 | -------------------------------------------------------------------------------- /Software Architecture with Python/3Testability/fakelogger.py: -------------------------------------------------------------------------------- 1 | # Code Listing #2 2 | import logging 3 | 4 | class FakeLogger(object): 5 | """ A class that fakes the interface of the 6 | logging.Logger object in a minimalistic fashion """ 7 | 8 | def __init__(self): 9 | self.lvl = logging.INFO 10 | 11 | def setLevel(self, level): 12 | """ Set the logging level """ 13 | self.lvl = level 14 | 15 | def _log(self, msg, *args): 16 | """ Perform the actual logging """ 17 | 18 | # Since this is a fake object - no actual logging is done. 19 | # Instead the message is simply printed to standard output. 20 | print (msg, end=' ') 21 | for arg in args: 22 | print(arg, end=' ') 23 | print() 24 | 25 | def info(self, msg, *args): 26 | """ Log at info level """ 27 | if self.lvl<=logging.INFO: return self._log(msg, *args) 28 | 29 | def debug(self, msg, *args): 30 | """ Log at debug level """ 31 | if self.lvl<=logging.DEBUG: return self._log(msg, *args) 32 | 33 | def warning(self, msg, *args): 34 | """ Log at warning level """ 35 | if self.lvl<=logging.WARNING: return self._log(msg, *args) 36 | 37 | def error(self, msg, *args): 38 | """ Log at error level """ 39 | if self.lvl<=logging.ERROR: return self._log(msg, *args) 40 | 41 | def critical(self, msg, *args): 42 | """ Log at critical level """ 43 | if self.lvl<=logging.CRITICAL: return self._log(msg, *args) 44 | -------------------------------------------------------------------------------- /university_counselor/b9365_ProgrammingQs/day3_5end/templates/home.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% block title %}Home{% endblock %} 3 | {% block body %} 4 |
5 |
6 | {% for post in posts.items %} 7 |
8 |

{{ post.title }}

9 |
10 |
11 |
12 | {{ post.text | truncate(500) | safe }} 13 | Read More 14 |
15 |
16 | {% endfor %} 17 |
18 |
19 |
20 |
Recent Posts
21 | 26 |
27 |
28 |
Popular Tags
29 | 34 |
35 |
36 |
37 | 38 | {{ render_pagination(posts, 'home') }} 39 | {% endblock %} -------------------------------------------------------------------------------- /Software Architecture with Python/4Performance/big_o.py: -------------------------------------------------------------------------------- 1 | # Extra Code 2 | 3 | """ 4 | 5 | Big-O notation image generator. Code which generated the Big-O 6 | growth graph (order) in the book. 7 | 8 | """ 9 | 10 | 11 | import numpy as np 12 | import math 13 | import matplotlib.pyplot as plt 14 | from functools import reduce 15 | 16 | def f(t): 17 | return np.exp(-t) * np.cos(2*np.pi*t) 18 | 19 | def k(t): 20 | return [0] 21 | 22 | def l(t): 23 | return list(map(math.log, t)) 24 | 25 | def x(t): 26 | return list(map(lambda x: x, t)) 27 | 28 | def xl(t): 29 | return list(map(lambda x: math.log(x)*x, t)) 30 | 31 | def sq(t): 32 | return list(map(lambda x: x*x, t)) 33 | 34 | def p2(t): 35 | return list(map(lambda x: pow(2,x), t)) 36 | 37 | def fact(n): 38 | return reduce(lambda x,y : x*y, range(1, n+1)) 39 | 40 | def facn(t): 41 | return list(map(lambda x: fact(x), t)) 42 | 43 | t = range(1, 101) 44 | 45 | plt.axis([0, 50, 0, 50]) 46 | line1=plt.plot(t, [1]*100, '#00ee00') 47 | print(line1) 48 | plt.text(45, 1.5, r'O(1)') 49 | 50 | line2=plt.plot(t, l(t), color='#00bb00') 51 | plt.text(40, 4.8, r'O(log(n))') 52 | 53 | line3=plt.plot(t, x(t), color='#008800') 54 | plt.text(42, 40, r'O((n))') 55 | 56 | line4=plt.plot(t, xl(t), color='#eeee00') 57 | plt.text(18, 45, r'O(nlog(n))') 58 | 59 | line5=plt.plot(t, sq(t), color='#440000') 60 | plt.text(8, 44, r'O(n^2)') 61 | 62 | line6=plt.plot(t, p2(t), color='#bb0000') 63 | plt.text(2, 35, r'O(2^n)') 64 | 65 | line7=plt.plot(t, facn(t), color='#ff0000') 66 | plt.text(0, 45, r'O(n!)') 67 | 68 | plt.show() 69 | -------------------------------------------------------------------------------- /university_counselor/b9365_ProgrammingQs/day3_5end/templates/tag.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% block title %}{{ tag.title }}{% endblock %} 3 | {% block body %} 4 |
5 |

Posts With Tag {{ tag.title }}

6 |
7 | {% for post in posts %} 8 |
9 |

{{ post.title }}

10 |
11 |
12 |
13 | {{ post.text | truncate(500) | safe }} 14 | Read More 15 |
16 |
17 | {% endfor %} 18 |
19 |
20 |
21 |
Recent Posts
22 | 27 |
28 |
29 |
Popular Tags
30 | 35 |
36 |
37 |
38 | {% endblock %} -------------------------------------------------------------------------------- /university_counselor/b9365_ProgrammingQs/day3_5end/templates/user.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% block title %}{{ user.username }}'s Posts{% endblock %} 3 | {% block body %} 4 |
5 |

Posts By {{ user.username }}

6 |
7 | {% for post in posts %} 8 |
9 |

{{ post.title }}

10 |
11 |
12 |
13 | {{ post.text | truncate(500) | safe }} 14 | Read More 15 |
16 |
17 | {% endfor %} 18 |
19 |
20 |
21 |
Recent Posts
22 | 27 |
28 |
29 |
Popular Tags
30 | 35 |
36 |
37 |
38 | {% endblock %} -------------------------------------------------------------------------------- /00RefactoringPython/ch11Handle_Generalization/i2push_down.py: -------------------------------------------------------------------------------- 1 | from mycolor import show 2 | 3 | class JobItem_old: 4 | def __init__(self, unit_price, quantity, 5 | is_labor, employee): 6 | self.unit_price = unit_price 7 | self.quantity = quantity 8 | self.is_labor = is_labor 9 | self.employee = employee 10 | 11 | def get_total_price(self): 12 | return self.get_unit_price() * self.quantity 13 | 14 | def get_unit_price(self): 15 | return self.employee.rate if self.is_labor else self.unit_price 16 | 17 | class Employee: 18 | def __init__(self, rate): 19 | self.rate = rate 20 | 21 | 22 | j = JobItem_old(9.8, 10000, True, Employee(0.99)) 23 | t = j.get_total_price() 24 | print(show(t)) 25 | print('-------------改造开始-----------------') 26 | class JobItem: 27 | def __init__(self, unit_price, quantity): 28 | self.unit_price = unit_price 29 | self.quantity = quantity 30 | self.is_labor = False 31 | # self.employee = employee 32 | 33 | def get_total_price(self): 34 | return self.get_unit_price() * self.quantity 35 | 36 | def get_unit_price(self): 37 | return self.unit_price 38 | 39 | class LaborItem(JobItem): 40 | def __init__(self, unit_price, quantity, employee): 41 | super(LaborItem, self).__init__(unit_price, quantity) 42 | self.is_labor = True 43 | self.employee = employee 44 | 45 | def get_unit_price(self): 46 | return self.employee.rate 47 | 48 | l = LaborItem(9.8, 10000, Employee(0.99)) 49 | t1 = l.get_total_price() 50 | print(show(t1, 'red')) 51 | -------------------------------------------------------------------------------- /01Python_Tricks/ch4Classes&OOP/i7staticmethod.py: -------------------------------------------------------------------------------- 1 | class MyClass: 2 | def method(self): 3 | return 'instance method called', self 4 | 5 | @classmethod 6 | def classmethod(cls): 7 | return 'class method called', cls 8 | 9 | @staticmethod 10 | def staticmethod(): 11 | return 'static method called' 12 | 13 | obj = MyClass() 14 | 15 | print(obj.method()) 16 | print(MyClass.method(obj)) 17 | print(obj.classmethod()) 18 | print(obj.staticmethod()) 19 | 20 | print('\n') 21 | print(MyClass.classmethod()) 22 | print(MyClass.staticmethod()) 23 | 24 | 25 | import math 26 | 27 | class Pizza: 28 | def __init__(self, radius, ingredients): 29 | self.radius = radius 30 | self.ingredients = ingredients 31 | 32 | def __repr__(self): 33 | return (f'Pizza{self.radius!r}, ' 34 | f'Pizza({self.ingredients!r})' ) 35 | 36 | def area(self): 37 | return self.circle_area(self.radius) 38 | 39 | @staticmethod 40 | def circle_area(r): 41 | return r**2 * math.pi 42 | 43 | @classmethod 44 | def margherita(cls): 45 | return cls(2, ['mozzarella', 'tomatoes']) 46 | 47 | @classmethod 48 | def prosciutto(cls): 49 | return cls(2, ['mozzarella', 'tomatoes', 'ham']) 50 | 51 | 52 | print('\n') 53 | print(Pizza(2, ['mozzarella', 'tomatoes'])) 54 | print(Pizza(2, ['mozzarella', 'tomatoes', 'ham', 'mushrooms'])) 55 | print(Pizza(2, ['mozzarella'] * 4)) 56 | 57 | print('\n') 58 | print(Pizza.margherita()) 59 | print(Pizza.prosciutto()) 60 | 61 | print('\n') 62 | p = Pizza(4, ['mozzarella', 'tomatoes']) 63 | print(p.area(), p.circle_area(4)) 64 | -------------------------------------------------------------------------------- /Software Architecture with Python/4Performance/defaultdict_example.py: -------------------------------------------------------------------------------- 1 | # Code Listing #7 2 | 3 | """ 4 | 5 | Examples of using defaultdict 6 | 7 | """ 8 | 9 | from collections import defaultdict 10 | 11 | counts = {} 12 | text="""Python is an interpreted language. Python is an object-oriented language. 13 | Python is easy to learn. Python is an open source language. """ 14 | word="Python" 15 | 16 | # Implementations with simple dictionary 17 | for word in text.split(): 18 | word = word.lower().strip() 19 | try: 20 | counts[word] += 1 21 | except KeyError: 22 | counts[word] = 1 23 | 24 | print("Counts of word",word,'=>',counts[word]) 25 | 26 | cities = ['Jakarta','Delhi','Newyork','Bonn','Kolkata','Bangalore','Seoul'] 27 | cities_len = {} 28 | for city in cities: 29 | clen = len(city) 30 | # First create entry 31 | if clen not in cities_len: 32 | cities_len[clen] = [] 33 | cities_len[clen].append(city) 34 | 35 | print('Cities grouped by length=>',cities_len) 36 | 37 | # Implementation using default dict 38 | # 1. Counts 39 | counts = defaultdict(int) 40 | for word in text.split(): 41 | word = word.lower().strip() 42 | # Value is set to 0 and incremented by 1 in one go 43 | counts[word] += 1 44 | 45 | print("Counts of word",word,'=>',counts[word]) 46 | 47 | # 2. Cities grouped by length 48 | cities = ['Jakarta','Delhi','Newyork','Bonn','Kolkata','Bangalore','Seoul'] 49 | cities_len = defaultdict(list) 50 | 51 | for city in cities: 52 | # Empty list is created as value and appended to in one go 53 | cities_len[len(city)].append(city) 54 | 55 | 56 | print('Cities grouped by length=>',cities_len) 57 | -------------------------------------------------------------------------------- /00RefactoringPython/ch8Reorganize_Data/i9subclass_to_field.py: -------------------------------------------------------------------------------- 1 | from mycolor import show 2 | 3 | class Old_Person: 4 | def is_male(self): 5 | pass 6 | 7 | def get_code(self): 8 | pass 9 | 10 | class Male(Old_Person): 11 | def is_male(self): 12 | return True 13 | 14 | def get_code(self): 15 | return 'M' 16 | 17 | class Female(Old_Person): 18 | def is_male(self): 19 | return False 20 | 21 | def get_code(self): 22 | return 'F' 23 | 24 | m = Male() 25 | f = Female() 26 | print(m.is_male(), m.get_code()) 27 | print(f.is_male(), f.get_code()) 28 | 29 | print('建立子类的目的,是为了增加新特性或者变化其行为' + 30 | '但若子类种只有常量函数,是在没有足够的价值' + 31 | '你可以在超类种设计敞亮函数返回相应字段,从而去除这样的子类' + 32 | '这样你就避免因继承而带来的额外的复杂性') 33 | print(show('开始改造'),'- > '*5) 34 | 35 | class Person: 36 | def create(self, is_male, code): 37 | self.is_male = is_male 38 | self.code = code 39 | return self 40 | 41 | @staticmethod 42 | def create_male(): 43 | # return New_Male() 44 | return Person().create(True, 'M') 45 | 46 | @staticmethod 47 | def create_female(): 48 | # return New_Female() 49 | return Person().create(False, 'F') 50 | 51 | # class New_Male(Person): 52 | # def __init__(self): 53 | # super(New_Male, self).create(True, 'M') 54 | 55 | 56 | # class New_Female(Person): 57 | # def __init__(self): 58 | # super(New_Female, self).create(False, 'F') 59 | 60 | m = Person.create_male() 61 | f = Person.create_female() 62 | # print(m.is_male(), m.get_code()) 63 | # print(f.is_male(), f.get_code()) 64 | print(m.is_male, m.code) 65 | print(f.is_male, f.code) 66 | 67 | 68 | -------------------------------------------------------------------------------- /Software Architecture with Python/3Testability/test_palindrome3.py: -------------------------------------------------------------------------------- 1 | # Code Listing - #15 2 | 3 | """ 4 | Module test_palindrome - TDD for palindrome module 5 | """ 6 | 7 | # Note: This is the third version of test_palindrome, so called test_palindrome3.py 8 | 9 | import palindrome 10 | 11 | def test_basic(): 12 | """ Basic test for palindrome """ 13 | 14 | # True positives 15 | for test in ('Rotator','bob','madam','mAlAyAlam', '1'): 16 | assert palindrome.is_palindrome(test)==True 17 | 18 | # True negatives 19 | for test in ('xyz','elephant', 'Country'): 20 | assert palindrome.is_palindrome(test)==False 21 | 22 | def test_with_spaces(): 23 | """ Testing palindrome strings with extra spaces """ 24 | 25 | # True positives 26 | for test in ('Able was I ere I saw Elba', 27 | 'Madam Im Adam', 28 | 'Step on no pets', 29 | 'Top spot'): 30 | assert palindrome.is_palindrome(test)==True 31 | 32 | # True negatives 33 | for test in ('Top post','Wonderful fool','Wild Imagination'): 34 | assert palindrome.is_palindrome(test)==False 35 | 36 | 37 | def test_with_punctuations(): 38 | """ Testing palindrome strings with extra punctuations """ 39 | 40 | # True positives 41 | for test in ('Able was I, ere I saw Elba', 42 | "Madam I'm Adam", 43 | 'Step on no pets.', 44 | 'Top spot!'): 45 | assert palindrome.is_palindrome(test)==True 46 | 47 | # True negatives 48 | for test in ('Top . post','Wonderful-fool','Wild Imagination!!'): 49 | assert palindrome.is_palindrome(test)==False 50 | -------------------------------------------------------------------------------- /00RefactoringPython/ch9Simplify_Conditional_Expression/i6conditional_to_polymorphism.py: -------------------------------------------------------------------------------- 1 | from mycolor import show 2 | 3 | EROPEAN = 0 4 | AFRICAN = 1 5 | NORWEGIAN = 2 6 | 7 | coconuts = 10 8 | is_nailed = False 9 | voltage = 10 10 | def get_speed_old(type): 11 | if type == EROPEAN: 12 | return getbase_speed() 13 | elif type == AFRICAN: 14 | return getbase_speed() - get_loadfactor() * coconuts 15 | elif type == NORWEGIAN: 16 | return 0 if is_nailed else getbase_speed(voltage) 17 | else: 18 | raise Exception('error!') 19 | 20 | def getbase_speed(p=1): 21 | return p * 10 22 | 23 | def get_loadfactor(): 24 | return 100 25 | 26 | t = get_speed_old(2) 27 | print(show(t)) 28 | 29 | print('- · - - · - - · - - · - ') 30 | 31 | class CountryFactory(object): 32 | @staticmethod 33 | def create(type): 34 | 35 | if type == EROPEAN: 36 | return Eropean() 37 | elif type == African: 38 | return AFRICAN() 39 | elif type == NORWEGIAN: 40 | return Norwegian() 41 | 42 | class Country: 43 | name = None 44 | def speed(self): 45 | pass 46 | 47 | class Eropean(Country): 48 | name = 'EROPEAN' 49 | 50 | def speed(self): 51 | return getbase_speed() 52 | 53 | class African(Country): 54 | name = 'AFRICAN' 55 | def speed(self): 56 | return getbase_speed() - get_loadfactor() * coconuts 57 | 58 | class Norwegian(Country): 59 | name = 'NORWEGIAN' 60 | def speed(self): 61 | return 0 if is_nailed else getbase_speed(voltage) 62 | 63 | def get_speed(type): 64 | country = CountryFactory.create(type) 65 | return country.speed() 66 | 67 | n = get_speed(2) 68 | print(show(n, 'red')) -------------------------------------------------------------------------------- /Software Architecture with Python/4Performance/i0common_items.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | from time import process_time as timer_func, sleep 4 | from contextlib import contextmanager 5 | 6 | a1, a2 = [], [] 7 | 8 | def setup(n): 9 | global a1, a2 10 | a1 = random.sample(range(0, 2*n), n) 11 | a2 = random.sample(range(0, 2*n), n) 12 | 13 | @contextmanager 14 | def timer(): 15 | try: 16 | start = timer_func() 17 | yield 18 | except Exception as e: 19 | print(e) 20 | raise 21 | finally: 22 | end = timer_func() 23 | print('time spent => ', 1000.0* (end - start), 'ms.') 24 | 25 | 26 | def common_items_v1(seq1, seq2): 27 | """ Find common items between two sequences - version #1 """ 28 | 29 | common = [] 30 | for item in seq1: 31 | if item in seq2: 32 | common.append(item) 33 | 34 | return common 35 | 36 | def common_items_v2(seq1, seq2): 37 | """ Find common items between two sequences - optimized version (v2) """ 38 | 39 | # return set(seq1).intersection(set(seq2)) 40 | seq_dict1 = {item:1 for item in seq1} 41 | for item in seq2: 42 | try: 43 | seq_dict1[item] += 1 44 | except KeyError: 45 | pass 46 | 47 | return [item[0] for item in seq_dict1.items() if item[1]>1] 48 | 49 | 50 | def test(n, func): 51 | """ Generate test data and perform test on a given function """ 52 | 53 | a1=random.sample(range(0, 2*n), n) 54 | a2=random.sample(range(0, 2*n), n) 55 | 56 | with timer() as t: 57 | result = func(a1, a2) 58 | 59 | if __name__ == "__main__": 60 | import sys 61 | test(int(sys.argv[1]), common_items_v1) 62 | test(int(sys.argv[1]), common_items_v2) -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | *.DS_Store 10 | 11 | # Distribution / packaging 12 | .Python 13 | env/ 14 | build/ 15 | develop-eggs/ 16 | dist/ 17 | downloads/ 18 | eggs/ 19 | .eggs/ 20 | lib/ 21 | lib64/ 22 | parts/ 23 | sdist/ 24 | var/ 25 | wheels/ 26 | *.egg-info/ 27 | .installed.cfg 28 | *.egg 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | .hypothesis/ 50 | 51 | # Translations 52 | *.mo 53 | *.pot 54 | 55 | # Django stuff: 56 | *.log 57 | local_settings.py 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # dotenv 85 | .env 86 | 87 | # virtualenv 88 | .venv 89 | venv/ 90 | ENV/ 91 | 92 | # Spyder project settings 93 | .spyderproject 94 | .spyproject 95 | 96 | # Rope project settings 97 | .ropeproject 98 | 99 | # mkdocs documentation 100 | /site 101 | 102 | # mypy 103 | .mypy_cache/ 104 | -------------------------------------------------------------------------------- /00RefactoringPython/ch6Reorganize_Functions/i6split_temp_var.py: -------------------------------------------------------------------------------- 1 | from termcolor import colored 2 | from myfinal import MyPyFinal 3 | 4 | 5 | def show(s,color='green'): 6 | return colored(s, color, attrs=['reverse', 'blink']) 7 | 8 | def get_distance_travelled(time): 9 | primary_force = 100 10 | mass = 5 11 | delay = 3 12 | secodary_force = 50 13 | 14 | result = None 15 | acc = primary_force / mass 16 | primary_time = min(time, delay) 17 | result = 0.5 * acc * primary_time * primary_time 18 | secondary_time = time - delay 19 | if secondary_time > 0: 20 | primary_vel = acc * delay 21 | acc = (primary_force + secodary_force) / mass 22 | result = primary_vel * secondary_time + 0.5 * acc * secondary_time \ 23 | * secondary_time 24 | return result 25 | 26 | r = get_distance_travelled(10) 27 | print('old way which need to refactory: get_distance_travelled=', show(r)) 28 | 29 | def get_distance_after_refactory(time): 30 | primary_force = 100 31 | mass = 5 32 | delay = 3 33 | secodary_force = 50 34 | 35 | result = None 36 | primary_acc = MyPyFinal(primary_force / mass).r() 37 | primary_time = min(time, delay) 38 | result = 0.5 * primary_acc * primary_time * primary_time 39 | secondary_time = time - delay 40 | if secondary_time > 0: 41 | primary_vel = primary_acc * delay 42 | secondary_acc = MyPyFinal((primary_force + secodary_force) / mass).r() 43 | result = primary_vel * secondary_time + 0.5 * secondary_acc * secondary_time \ 44 | * secondary_time 45 | return result 46 | 47 | r = get_distance_after_refactory(10) 48 | print('old way which need to refactory: get_distance_travelled=', show(r, 'red')) 49 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch4Using Modules for Real-World/charter/renderers/pdf/x_axis.py: -------------------------------------------------------------------------------- 1 | # charter.renderers.pdf.x_axis 2 | # 3 | # Renderer for drawing an X axis onto the chart in PDF format. 4 | 5 | from ...constants import * 6 | 7 | ############################################################################# 8 | 9 | def draw(chart, canvas): 10 | label_height = 12 * 1.2 11 | 12 | avail_width = CHART_WIDTH - Y_AXIS_WIDTH - MARGIN 13 | bucket_width = avail_width / len(chart['x_axis']) 14 | 15 | # Draw main axis line. 16 | 17 | axis_top = X_AXIS_HEIGHT 18 | canvas.setStrokeColorRGB(0.25, 0.25, 0.625) 19 | canvas.setLineWidth(2) 20 | canvas.line(Y_AXIS_WIDTH, axis_top, CHART_WIDTH - MARGIN, axis_top) 21 | 22 | left = Y_AXIS_WIDTH 23 | for bucket_num in range(len(chart['x_axis'])): 24 | 25 | # Draw tickmark. 26 | 27 | canvas.setLineWidth(1) 28 | canvas.line(left, axis_top, left, axis_top - TICKMARK_HEIGHT) 29 | 30 | # Draw label. 31 | 32 | label_width = canvas.stringWidth(chart['x_axis'][bucket_num], 33 | "Helvetica", 12) 34 | label_left = max(left, left + bucket_width/2 - label_width/2) 35 | label_bottom = axis_top - TICKMARK_HEIGHT - 4 - label_height 36 | 37 | canvas.setFont("Helvetica", 12) 38 | canvas.setFillColorRGB(0.0, 0.0, 0.0) 39 | canvas.drawString(label_left, label_bottom, 40 | chart['x_axis'][bucket_num]) 41 | 42 | left = left + bucket_width 43 | 44 | # Draw final tickmark. 45 | 46 | canvas.setStrokeColorRGB(0.25, 0.25, 0.625) 47 | canvas.setLineWidth(1) 48 | canvas.line(left, axis_top, left, axis_top - TICKMARK_HEIGHT) 49 | 50 | -------------------------------------------------------------------------------- /00RefactoringPython/ch7Move_attribute_between_Objects/i3inline_class.py: -------------------------------------------------------------------------------- 1 | import random 2 | from termcolor import colored 3 | 4 | 5 | def show(s,color='green'): 6 | return colored(s, color, attrs=['reverse', 'blink']) 7 | 8 | class Person(object): 9 | """docstring for Person""" 10 | def __init__(self, name, telephone_number): 11 | self.name = name 12 | self.telephone_number = telephone_number 13 | 14 | def get_telephone_number(self): 15 | return "(" + self.telephone_number.area_code + ") " + self.telephone_number.number 16 | 17 | class TelephoneNumber: 18 | def __init__(self, area_code, number): 19 | self.area_code = area_code 20 | self.number = number 21 | 22 | p = Person('Stone', TelephoneNumber('0613', '00001')) 23 | print('old模式下:' + show(p.get_telephone_number())) 24 | 25 | print('incline class: 如果一个类不再承担足够责任、不再有单独存在必要的理由,我们挑选#萎缩类# 最频繁的用户\ 26 | 将它塞到另一类中') 27 | 28 | 29 | class Person_afterRefactory(object): 30 | """docstring for Person""" 31 | def __init__(self, name, office_area_code, 32 | office_number): 33 | self.name = name 34 | self.office_area_code = office_area_code 35 | self.office_number = office_number 36 | 37 | # def get_area_code(self): 38 | # return self.telephone_number.area_code 39 | 40 | # def get_number(self): 41 | # return self.telephone_number.number 42 | 43 | def get_telephone_number(self): 44 | return "(" + self.office_area_code + ") " + self.office_number 45 | 46 | class TelephoneNumber: 47 | def __init__(self, area_code, number): 48 | self.area_code = area_code 49 | self.number = number 50 | 51 | p = Person_afterRefactory('Stone', '0613', '00001') 52 | print('new模式下:' + show(p.get_telephone_number(), 'red')) -------------------------------------------------------------------------------- /Software Architecture with Python/4Performance/ordered.py: -------------------------------------------------------------------------------- 1 | # Code Listing #8 2 | 3 | """ 4 | 5 | Examples of using OrderedDict 6 | 7 | """ 8 | 9 | from collections import OrderedDict 10 | 11 | cities = ['Jakarta','Delhi','Newyork','Bonn','Kolkata','Bangalore','Seoul'] 12 | # Dictionary 13 | cities_dict = dict.fromkeys(cities) 14 | print(cities_dict) 15 | # Ordered dictionary 16 | ocities_dict = OrderedDict.fromkeys(cities) 17 | print(ocities_dict) 18 | 19 | # Dropping duplicates while preserving order with Ordered dictionary 20 | cities = ['Jakarta','Delhi','Newyork','Bonn','Kolkata','Bangalore','Bonn','Seoul','Delhi','Jakarta','Mumbai'] 21 | cities_odict = OrderedDict.fromkeys(cities) 22 | print(cities_odict.keys()) 23 | print(cities_odict.popitem()) 24 | print(cities_odict.popitem(last=False)) 25 | 26 | # class LRU 27 | class LRU(OrderedDict): 28 | """ Least recently used cache (LRU) dictionary 29 | using OrderedDict 30 | 31 | """ 32 | 33 | def __init__(self, size=10): 34 | self.size = size 35 | 36 | def set(self, key): 37 | # If key is there delete and reinsert so 38 | # it moves to end. 39 | if key in self: 40 | del self[key] 41 | 42 | self[key] = 1 43 | if len(self)>self.size: 44 | # Pop from left 45 | self.popitem(last=False) 46 | 47 | if __name__ == "__main__": 48 | d=LRU(size=5) 49 | d.set('bangalore') 50 | d.set('chennai') 51 | d.set('mumbai') 52 | # Bangalore is set again - moves to right 53 | d.set('bangalore') 54 | d.set('kolkata') 55 | d.set('delhi') 56 | # Chennai is set again - so moves to right 57 | d.set('chennai') 58 | 59 | print('Length=>',len(d)) 60 | print(d) 61 | # Kochi is appended and mumbai drops off 62 | d.set('kochi') 63 | print(d) 64 | -------------------------------------------------------------------------------- /02Modular-Programming-with-Python/ch5Working with Module Patterns/i1abstraction/happy_hour.py: -------------------------------------------------------------------------------- 1 | # happy_hour.py 2 | # 3 | # This program demonstrates how to calculate "happy hour", where happy hour 4 | # takes place each day between 5 and 6 pm, except on Sundays, Christmas Day and 5 | # Easter. 6 | 7 | import datetime 8 | 9 | ############################################################################# 10 | 11 | def is_happy_hour(): 12 | today = datetime.date.today() 13 | 14 | easter_sunday = calc_easter_sunday(today.year) 15 | easter_friday = easter_sunday - datetime.timedelta(days=2) 16 | 17 | if today == easter_friday: 18 | return False 19 | 20 | if today.month == 12 and today.day == 25: # Christmas day. 21 | return False 22 | 23 | if today.weekday() == 6: # Sunday. 24 | return False 25 | 26 | if datetime.datetime.now().hour == 17: # 5pm. 27 | return True 28 | 29 | return False 30 | 31 | ############################################################################# 32 | 33 | # The following function calculates Easter Sunday for a given year, returning a 34 | # datetime.date object. This code is taken from: 35 | # 36 | # http://code.activestate.com/recipes/576517 37 | 38 | def calc_easter_sunday(year): 39 | a = year % 19 40 | b = year // 100 41 | c = year % 100 42 | d = (19 * a + b - b // 4 - ((b - (b + 8) // 25 + 1) // 3) + 15) % 30 43 | e = (32 + 2 * (b % 4) + 2 * (c // 4) - d - (c % 4)) % 7 44 | f = d + e - 7 * ((a + 11 * d + 22 * e) // 451) + 114 45 | month = f // 31 46 | day = f % 31 + 1 47 | return datetime.date(year, month, day) 48 | 49 | ############################################################################# 50 | 51 | if __name__ == "__main__": 52 | # Testing code. 53 | 54 | if is_happy_hour(): 55 | print("It's happy hour!") 56 | else: 57 | print("It's not happy hour.") 58 | 59 | -------------------------------------------------------------------------------- /00RefactoringPython/ch6Reorganize_Functions/i8replace_method_with_method_obj.py: -------------------------------------------------------------------------------- 1 | from termcolor import colored 2 | from myfinal import MyPyFinal 3 | 4 | 5 | def show(s,color='green'): 6 | return colored(s, color, attrs=['reverse', 'blink']) 7 | 8 | class Account: 9 | def delta(self): 10 | return 100 11 | def gamma(self, input_val, quantity, year_to_date): 12 | 13 | import_val1 = (input_val * quantity) + self.delta() 14 | import_val2 = (input_val * year_to_date) + 100 15 | if year_to_date - import_val1 > 100: 16 | import_val2 -= 20 17 | import_val3 = import_val2 * 7 18 | return import_val3 - 2 * import_val1 19 | 20 | a = Account().gamma(200, 100, 2017) 21 | print('old way which need to refactory:', show(a)) 22 | 23 | 24 | class Gamma: 25 | def __init__(self, input_val, quantity, year_to_date): 26 | self.input_val = input_val 27 | self.quantity = quantity 28 | self.year_to_date = year_to_date 29 | self.import_val1 = None 30 | self.import_val2 = None 31 | self.import_val3 = None 32 | 33 | def compute(self, account): 34 | def import_thing(): 35 | if self.year_to_date - self.import_val1 > 100: 36 | self.import_val2 -= 20 37 | 38 | self.import_val1 = (self.input_val * self.quantity) +account.delta() 39 | self.import_val2 = (self.input_val * self.year_to_date) + 100 40 | import_thing() 41 | self.import_val3 = self.import_val2 * 7 42 | return self.import_val3 - 2 * self.import_val1 43 | 44 | class Account_after_Refactory: 45 | def delta(self): 46 | return 100 47 | def gamma(self, input_val, quantity, year_to_date): 48 | return Gamma(input_val, quantity, year_to_date).compute(Account_after_Refactory()) 49 | 50 | t_after = Account_after_Refactory().gamma(200, 100, 2017) 51 | print('the way which after refactory:', show(t_after, 'red')) 52 | -------------------------------------------------------------------------------- /Software Architecture with Python/3Testability/test_datetimehelper2.py: -------------------------------------------------------------------------------- 1 | # Code Listing #5 2 | 3 | """ Module test_datetimehelper - Unit test module for testing datetimehelper module """ 4 | 5 | # Note - This is the second version of test_datetimehelper module so named as test_datetimehelper2.py 6 | 7 | import unittest 8 | import datetime 9 | import datetimehelper 10 | 11 | from unittest.mock import patch 12 | 13 | class DateTimeHelperTestCase(unittest.TestCase): 14 | """ Unit-test testcase class for DateTimeHelper class """ 15 | 16 | def setUp(self): 17 | self.obj = datetimehelper.DateTimeHelper() 18 | 19 | def test_date(self): 20 | """ Test date() method """ 21 | 22 | # Put a specific date to test 23 | my_date = datetime.datetime(year=2016, month=8, day=16) 24 | 25 | # Patch the 'today' method with a specific return value 26 | with patch.object(self.obj, 'today', return_value=my_date): 27 | response = self.obj.date() 28 | self.assertEqual(response, '16/08/2016') 29 | 30 | def test_weekday(self): 31 | """ Test weekday() method """ 32 | 33 | # Put a specific date to test 34 | my_date = datetime.datetime(year=2016, month=8, day=21) 35 | 36 | # Patch the 'today' method with a specific return value 37 | with patch.object(self.obj, 'today', return_value=my_date): 38 | response = self.obj.weekday() 39 | self.assertEqual(response, 'Sunday') 40 | 41 | def test_us_india_conversion(self): 42 | """ Test us=>india date format conversion """ 43 | 44 | # Test a few dates 45 | d1 = '08/12/16' 46 | d2 = '07/11/2014' 47 | d3 = '04/29/00' 48 | self.assertEqual(self.obj.us_to_indian(d1), '12/08/2016') 49 | self.assertEqual(self.obj.us_to_indian(d2), '11/07/2014') 50 | self.assertEqual(self.obj.us_to_indian(d3), '29/04/2000') 51 | 52 | if __name__ == "__main__": 53 | unittest.main() 54 | --------------------------------------------------------------------------------