Skip to content

Commit

Permalink
Add all source code.
Browse files Browse the repository at this point in the history
  • Loading branch information
gianchub committed Jun 29, 2018
0 parents commit 2e0a5d7
Show file tree
Hide file tree
Showing 345 changed files with 72,119 additions and 0 deletions.
58 changes: 58 additions & 0 deletions .gitignore
@@ -0,0 +1,58 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]

# C extensions
*.so

# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
#lib/
#lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover

# Translations
*.mo
*.pot

# Django stuff:
*.log

# Sphinx documentation
docs/_build/

# PyBuilder
target/

65 changes: 65 additions & 0 deletions README.rst
@@ -0,0 +1,65 @@
=========================================
Learning Python Programming - Source Code
=========================================

This project holds the source code for the book:

**Learn Python Programming, 2nd Edition - Packt Publishing**

Author: **Fabrizio Romano**

ISBN: **9781788996662**

Publication date: **June 2018**


Setup
=====

Create a virtual environment with a Python version 3.7.*.


Installing requirements
-----------------------

Install all the requirements text files via pip like this:

$ pip install -r requirements.txt

Requirements for the data science chapter can be cumbersome to install
so I kept them separated, in the `requirements.data.science.txt` file.

If you wish to install all requirements at once, just execute the following:

$ pip install -r all.txt


Updating requirements
---------------------

To update requirements you can use `pip-tools` to compile the `*.in`
sources in the `requirements` folder.

To compile and update a single `.in` file, run the following:

$ pip-compile -U requirements.in

If you want to compile all requirements into one single `.txt` file,
run the following:

$ pip-compile -U -o all.txt *.in
This will read all the `.in` files and compile them together into the
`all.txt` file.


Python Version
==============

Python 3.7


Last update
-----------

2018.06.29
22 changes: 22 additions & 0 deletions ch1/bike.py
@@ -0,0 +1,22 @@
# let's define the class Bike
class Bike:

def __init__(self, colour, frame_material):
self.colour = colour
self.frame_material = frame_material

def brake(self):
print("Braking!")

# let's create a couple of instances
red_bike = Bike('Red', 'Carbon fiber')
blue_bike = Bike('Blue', 'Steel')

# let's inspect the objects we have, instances of the Bike class.
print(red_bike.colour) # prints: Red
print(red_bike.frame_material) # prints: Carbon fiber
print(blue_bike.colour) # prints: Blue
print(blue_bike.frame_material) # prints: Steel

# let's brake!
red_bike.brake() # prints: Braking!
Empty file added ch1/example/core.py
Empty file.
Empty file added ch1/example/run.py
Empty file.
Empty file added ch1/example/util/__init__.py
Empty file.
Empty file added ch1/example/util/db.py
Empty file.
Empty file added ch1/example/util/math.py
Empty file.
Empty file added ch1/example/util/network.py
Empty file.
3 changes: 3 additions & 0 deletions ch1/factorial.py
@@ -0,0 +1,3 @@
>>> from math import factorial
>>> factorial(5)
120
Empty file added ch1/files_only/core.py
Empty file.
Empty file added ch1/files_only/db.py
Empty file.
Empty file added ch1/files_only/math.py
Empty file.
Empty file added ch1/files_only/network.py
Empty file.
Empty file added ch1/files_only/run.py
Empty file.
19 changes: 19 additions & 0 deletions ch1/names.py
@@ -0,0 +1,19 @@
>>> n = 3 # integer number
>>> address = "221b Baker Street, NW1 6XE, London" # Sherlock Holmes' address
>>> employee = {
... 'age': 45,
... 'role': 'CTO',
... 'SSN': 'AB1234567',
... }
>>> # let's print them
>>> n
3
>>> address
'221b Baker Street, NW1 6XE, London'
>>> employee
{'age': 45, 'role': 'CTO', 'SSN': 'AB1234567'}
>>> other_name
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'other_name' is not defined
>>>
12 changes: 12 additions & 0 deletions ch1/scopes1.py
@@ -0,0 +1,12 @@
# Local versus Global

# we define a function, called local
def local():
m = 7
print(m)

m = 5
print(m)

# we call, or `execute` the function local
local()
12 changes: 12 additions & 0 deletions ch1/scopes2.py
@@ -0,0 +1,12 @@
# Local versus Global

def local():
# m doesn't belong to the scope defined by the local function
# so Python will keep looking into the next enclosing scope.
# m is finally found in the global scope
print(m, 'printing from the local scope')

m = 5
print(m, 'printing from the global scope')

local()
20 changes: 20 additions & 0 deletions ch1/scopes3.py
@@ -0,0 +1,20 @@
# Local, Enclosing and Global


def enclosing_func():
m = 13

def local():
# m doesn't belong to the scope defined by the local
# function so Python will keep looking into the next
# enclosing scope. This time m is found in the enclosing
# scope
print(m, 'printing from the local scope')

# calling the function local
local()

m = 5
print(m, 'printing from the global scope')

enclosing_func()
31 changes: 31 additions & 0 deletions ch1/virtualenv.creation.txt
@@ -0,0 +1,31 @@
fabmp:srv fab$ # step 1 - create folder
fabmp:srv fab$ mkdir learn.pp
fabmp:srv fab$ cd learn.pp

fabmp:learn.pp fab$ # step 2 - create virtual environment
fabmp:learn.pp fab$ which python3.7
/Users/fab/.pyenv/shims/python3.7
fabmp:learn.pp fab$ virtualenv -p
⇢ /Users/fab/.pyenv/shims/python3.7 learnpp
Running virtualenv with interpreter /Users/fab/.pyenv/shims/python3.7
Using base prefix '/Users/fab/.pyenv/versions/3.7.0a3'
New python executable in /Users/fab/srv/learn.pp/learnpp/bin/python3.7
Also creating executable in /Users/fab/srv/learn.pp/learnpp/bin/python
Installing setuptools, pip, wheel...done.

fabmp:learn.pp fab$ # step 3 - activate virtual environment
fabmp:learn.pp fab$ source learnpp/bin/activate

(learnpp) fabmp:learn.pp fab$ # step 4 - verify which python
(learnpp) fabmp:learn.pp fab$ which python
/Users/fab/srv/learn.pp/learnpp/bin/python

(learnpp) fabmp:learn.pp fab$ python
Python 3.7.0a3 (default, Jan 27 2018, 00:46:45)
[Clang 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()

(learnpp) fabmp:learn.pp fab$ # step 5 - deactivate
(learnpp) fabmp:learn.pp fab$ deactivate
fabmp:learn.pp fab$
Binary file added ch10/aio/pics/53a51667.jpg
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added ch10/aio/pics/81846f84.jpg
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
45 changes: 45 additions & 0 deletions ch10/aio/randompix_corout.py
@@ -0,0 +1,45 @@
import os
from secrets import token_hex
import asyncio

import aiohttp


PICS_FOLDER = 'pics'
URL = 'http://lorempixel.com/640/480/'
# URL = 'https://lorempizza.com/640/480/'


async def download_image(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
return await resp.read()


async def download(url, semaphore):
async with semaphore:
content = await download_image(url)
filename = save_image(content)
return filename


def save_image(content):
filename = '{}.jpg'.format(token_hex(4))
path = os.path.join(PICS_FOLDER, filename)
with open(path, 'wb') as stream:
stream.write(content)
return filename


def batch_download(images, url):
loop = asyncio.get_event_loop()
semaphore = asyncio.Semaphore(10)
cors = [download(url, semaphore) for _ in range(images)]
res, _ = loop.run_until_complete(asyncio.wait(cors))
loop.close()
return [r.result() for r in res]


if __name__ == '__main__':
saved = batch_download(20, URL)
print(saved)
34 changes: 34 additions & 0 deletions ch10/aio/randompix_proc.py
@@ -0,0 +1,34 @@
import os
from secrets import token_hex
from concurrent.futures import ProcessPoolExecutor, as_completed

import requests


PICS_FOLDER = 'pics'
URL = 'http://lorempixel.com/640/480/'
# URL = 'https://lorempizza.com/640/480/'


def download(url):
resp = requests.get(URL)
return save_image(resp.content)


def save_image(content):
filename = '{}.jpg'.format(token_hex(4))
path = os.path.join(PICS_FOLDER, filename)
with open(path, 'wb') as stream:
stream.write(content)
return filename


def batch_download(url, n, workers=4):
with ProcessPoolExecutor(max_workers=workers) as executor:
futures = (executor.submit(download, url) for _ in range(n))
return [future.result() for future in as_completed(futures)]


if __name__ == '__main__':
saved = batch_download(URL, 10)
print(saved)
31 changes: 31 additions & 0 deletions ch10/aio/randompix_serial.py
@@ -0,0 +1,31 @@
import os
from secrets import token_hex

import requests


PICS_FOLDER = 'pics'
URL = 'http://lorempixel.com/640/480/'
# URL = 'https://lorempizza.com/640/480/'


def download(url):
resp = requests.get(URL)
return save_image(resp.content)


def save_image(content):
filename = '{}.jpg'.format(token_hex(4))
path = os.path.join(PICS_FOLDER, filename)
with open(path, 'wb') as stream:
stream.write(content)
return filename


def batch_download(url, n):
return [download(url) for _ in range(n)]


if __name__ == '__main__':
saved = batch_download(URL, 10)
print(saved)

0 comments on commit 2e0a5d7

Please sign in to comment.