Skip to content

Commit d3cf6d7

Browse files
author
Jonathan Rocher
committed
Adding a bunch of sample files for many different topic
1 parent 9243b24 commit d3cf6d7

File tree

9 files changed

+240
-0
lines changed

9 files changed

+240
-0
lines changed

generator_illustration.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
""" Illustrate the use of generators for large processing pipelines.
2+
The pipeline involves 4 steps: identify the all files that have the
3+
word 'log' in their name, open all files based on their extension,
4+
process all lines in the file and retain the ones that contain python.
5+
"""
6+
7+
import os
8+
import gzip, bz2
9+
10+
def find_files(directory, part_name):
11+
print "Searching directory %s" % directory
12+
for path, directory, listfile in os.walk(directory):
13+
for name in listfile:
14+
if part_name in name:
15+
yield os.path.join(path, name)
16+
17+
def opener(filenames):
18+
for filename in filenames:
19+
ext = os.path.splitext(filename)[1]
20+
if ext == ".gz":
21+
f = gzip.open(filename)
22+
elif ext == ".bz2":
23+
f = bz2.BZ2File(filename)
24+
else:
25+
f = open(filename)
26+
yield f
27+
28+
def cat(filelist):
29+
for file_object in filelist:
30+
for line in file_object:
31+
yield line
32+
33+
def grep(string, lines):
34+
for line in lines:
35+
if string in line:
36+
yield line
37+
38+
39+
filenames = find_files(".", "log")
40+
files = opener(filenames)
41+
content = cat(files)
42+
interesting_content = grep("python", content)
43+
44+
for line in interesting_content:
45+
print line

sample_setup.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import os
2+
from setuptools import setup
3+
4+
setup(
5+
name = "foo",
6+
version = "0.1",
7+
author = "Enthought Inc.",
8+
author_email = "info@enthought.com",
9+
description = ("This is a foo package that doesn't do anything"),
10+
license = "GPL",
11+
packages=['dir1'],
12+
long_description=""" This is a long description
13+
for my package.
14+
""",
15+
entry_points = {
16+
'console_scripts': [
17+
'foo_exec = dir1.run:main',
18+
],
19+
},
20+
include_package_data = True,
21+
data_files=["doc.html"],
22+
zip_safe = False,
23+
)

sqlalchemy_simple_example.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
""" Simple example of usage of sqlalchemy to illustrate common simple patterns.
2+
3+
Source: http://www.rmunn.com/sqlalchemy-tutorial/tutorial.html
4+
"""
5+
6+
from sqlalchemy import *
7+
8+
db = create_engine('sqlite:///tutorial.db')
9+
10+
db.echo = False # Try changing this to True and see what happens
11+
12+
# The metadata is a collection of tables that needs to be bound to the
13+
# engine
14+
metadata = MetaData()
15+
metadata.bind = db
16+
17+
users = Table('users', metadata,
18+
Column('user_id', Integer, primary_key=True),
19+
Column('name', String(40)),
20+
Column('age', Integer),
21+
Column('password', String),
22+
)
23+
users.create()
24+
25+
i = users.insert()
26+
i.execute(name='Mary', age=30, password='secret')
27+
i.execute({'name': 'John', 'age': 42},
28+
{'name': 'Susan', 'age': 57},
29+
{'name': 'Carl', 'age': 33})
30+
31+
s = users.select()
32+
rs = s.execute()
33+
34+
row = rs.fetchone()
35+
print 'Id:', row[0]
36+
print 'Name:', row['name']
37+
print 'Age:', row.age
38+
print 'Password:', row[users.c.password]
39+
40+
for row in rs:
41+
print row.name, 'is', row.age, 'years old'

stdlib/example_multiprocessing.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"""
2+
"""
3+
4+
import multiprocessing as mp
5+
import sys
6+
from time import sleep
7+
8+
9+
def process_action(proc_num, n):
10+
""" Take a child process, print its PID and sleep for n seconds
11+
"""
12+
proc = mp.current_process()
13+
proc_name = proc.name
14+
proc_id = proc.pid
15+
print "Child process number %s " % proc_num
16+
sys.stdout.flush()
17+
sleep(n)
18+
print "Process %s is done" % proc_num
19+
sys.stdout.flush()
20+
21+
if __name__ == "__main__":
22+
nb_processes = 10
23+
for i in range(nb_processes):
24+
p = mp.Process(target=process_action, args = (i, i+10))
25+
p.start()
26+
27+
[p.join() for p in mp.active_children()]
28+
print "Main process can keep running now that they all have joined"
29+
sys.stdout.flush()

test_collections.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# -*- coding: utf-8 -*-
2+
3+
from collections import *
4+
from timeit import timeit
5+
6+
d = OrderedDict()
7+
for i, key in enumerate('abcde'):
8+
d[key] = i+1
9+
d["A"] = 0.
10+
print d
11+

test_hiding_properties.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class MyNumberB(object):
2+
3+
def __init__(self, number):
4+
5+
self._number = number
6+
7+
8+
def number():
9+
10+
def _get_number(self):
11+
12+
return self._number
13+
14+
def _set_number(self, value):
15+
16+
if isinstance(value, basestring):
17+
18+
number = eval(value)
19+
20+
else:
21+
22+
number = value
23+
24+
self._number = number
25+
26+
return dict(fget=_get_number, fset=_set_number)
27+
28+
29+
number = property(**number())

test_xml.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
from SimpleXMLRPCServer import SimpleXMLRPCServer
2+
3+
def fact(n):
4+
if n <= 1:
5+
return 1
6+
else:
7+
return n * fact(n-1)
8+
9+
# Start a server listening for requests on port 8001.
10+
if __name__ == '__main__':
11+
server = SimpleXMLRPCServer(('localhost', 8000))
12+
# Register fact as a function provided by the server.
13+
server.register_function(fact)
14+
print "Serving the factorial function on localhost:8000..."
15+
server.serve_forever()

test_xmlrpc.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
""" XMLRPC server with a handler
2+
"""
3+
4+
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler, \
5+
SimpleXMLRPCServer
6+
def fact(n):
7+
if n <= 1:
8+
return 1
9+
else:
10+
return n * fact(n-1)
11+
12+
# Override the _dispatch() handler to call the requested function.
13+
class my_handler(SimpleXMLRPCRequestHandler):
14+
def _dispatch(self, method, params):
15+
print "CALL", method, params
16+
return apply(eval(method), params)
17+
18+
# Start a server listening for requests on port 8001.
19+
if __name__ == '__main__':
20+
server = SimpleXMLRPCServer(('localhost', 8001), my_handler)
21+
server.serve_forever()

weave_inline.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
""" Quick demo of weave.inline and comparing the speed of weave to pure python
2+
and numpy.
3+
"""
4+
from scipy import weave
5+
from numpy import arange
6+
7+
a = arange(10000.)
8+
9+
def weave_sum(a):
10+
code = """
11+
double sum = 0.0;
12+
for (int i=0 ; i<Na[0]; i++)
13+
sum += a[i];
14+
return_val = sum;
15+
"""
16+
17+
return weave.inline(code, ['a'], compiler="gcc")
18+
19+
def np_sum(a):
20+
return a.sum()
21+
22+
def manual_sum(a):
23+
total = 0.0
24+
for elem in a:
25+
total += elem
26+
return total

0 commit comments

Comments
 (0)