15 |
--------------------------------------------------------------------------------
/Exercises/LearnTornado/Burt/templates/recommended.html:
--------------------------------------------------------------------------------
1 | {% extends "main.html" %}
2 |
3 |
4 | {% block body %}
5 |
6 | {% for book in books %}
7 | {% module Book(book) %}
8 | {% end %}
9 | {% end %}
10 |
--------------------------------------------------------------------------------
/Exercises/LearnTornado/C2/static/style.css:
--------------------------------------------------------------------------------
1 | body {
2 | font-family: Helvetica,Arial,sans-serif;
3 | width: 600px;
4 | margin: 0 auto;
5 | }
6 | .replaced:hover { color: #00f; }
7 |
--------------------------------------------------------------------------------
/Exercises/LearnTornado/C2/templates/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
Enter two texts below. The replacement text will have its words
10 | replaced by words beginning with the same letter in the source text.
18 |
19 |
20 |
--------------------------------------------------------------------------------
/Exercises/LearnTornado/C2/templates/munged.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 | {% for line in change_lines %}
11 | {% for word in line.split(' ') %}
12 | {% if len(word) > 0 and word[0] in source_map %}
13 | {{ choice(source_map[word[0]]) }}
14 | {% else %}
15 | {{word}}
16 | {% end %}
17 | {% end %}
18 |
19 | {% end %}
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/Exercises/LearnTornado/C3/main.py:
--------------------------------------------------------------------------------
1 | import tornado.httpserver
2 | import tornado.ioloop
3 | import tornado.options
4 | import tornado.web
5 |
6 |
7 | from tornado.options import options, define
8 | define("port", default=8000, help="run on the given port", type=int)
9 |
10 |
11 | class MainHandler(tornado.web.RequestHandler):
12 | def get(self):
13 | self.render(
14 | "index.html",
15 | header_text = "Here goes the header",
16 | footer_text = "Here goes the footer"
17 | )
18 |
19 |
20 | if __name__ == "__main__":
21 | tornado.options.parse_command_line()
22 | app = tornado.web.Application(
23 | headlers=[('/', MainHandler)]
24 | )
25 | http_server = tornado.httpserver.HTTPServer(app)
26 | http_server.listen(options.port)
27 | tornado.ioloop.IOLoop.instance().start()
28 |
--------------------------------------------------------------------------------
/Exercises/LearnTornado/C3/templates/index.html:
--------------------------------------------------------------------------------
1 | {% extends "main.html" %}
2 |
3 | {% block header %}
4 |
13 | {% end %}
14 |
--------------------------------------------------------------------------------
/Exercises/LearnTornado/C3/templates/main.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/Exercises/LearnTornado/burtbook/static/style.css:
--------------------------------------------------------------------------------
1 | body {
2 | font-family: Helvetica, Arial, sans-serif;
3 | width: 600px;
4 | margin: 0 auto;
5 | }
6 | .replaced:hover { color: #00f; }
7 |
--------------------------------------------------------------------------------
/Exercises/LearnTornado/burtbook/templates/book_edit.html:
--------------------------------------------------------------------------------
1 | {% extends "main.html" %}
2 | {% autoescape None %}
3 |
4 | {% block body %}
5 |
17 | {% end %}
18 |
--------------------------------------------------------------------------------
/Exercises/LearnTornado/burtbook/templates/index.html:
--------------------------------------------------------------------------------
1 | {% extends "main.html" %}
2 |
3 | {% block header %}
4 |
12 | {% end %}
13 |
--------------------------------------------------------------------------------
/Exercises/LearnTornado/burtbook/templates/main.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/Exercises/LearnTornado/burtbook/templates/modules/book.html:
--------------------------------------------------------------------------------
1 |
2 |
{{ book["title"] }}
3 | {% if book["subtitle"] != "" %}
4 |
{{ book["subtitle"] }}
5 | {% end %}
6 |

7 |
8 |
Released: {{ book["date_released"] }}
9 |
10 | Added: {{ locale.format_date(book["date_added"], relative=False) }}
11 |
12 |
Description:
13 |
{% raw book["description"] %}
14 |
15 |
--------------------------------------------------------------------------------
/Exercises/LearnTornado/burtbook/templates/recommended.html:
--------------------------------------------------------------------------------
1 | {% extends "main.html" %}
2 |
3 |
4 | {% block body %}
5 |
Recommended Reading
6 | {% for book in books %}
7 | {% module Book(book) %}
8 | {% end %}
9 | {% end %}
10 |
--------------------------------------------------------------------------------
/Exercises/LearnTornado/cookie/templates/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
Welcome Back!
4 |
5 |
6 |
Welcome back, {{ user }}
7 |
8 |
9 |
--------------------------------------------------------------------------------
/Exercises/LearnTornado/cookie/templates/login.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
Please Log In
4 |
5 |
6 |
7 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/Exercises/LearnTornado/hello-errors.py:
--------------------------------------------------------------------------------
1 | import tornado.httpserver
2 | import tornado.ioloop
3 | import tornado.options
4 | import tornado.web
5 |
6 |
7 | from tornado.options import define, options
8 | define("port", default=8000, help="run on the given port", type=int)
9 |
10 |
11 | class IndexHandler(tornado.web.RequestHandler):
12 | def get(self):
13 | greeting = self.get_argument('greeting', 'Hello')
14 | self.write(greeting + ', friendly user!')
15 | def write_error(self, status_code, **kwargs):
16 | self.write("Gosh darnit, user! You caused a %d error." % status_code)
17 |
18 | if __name__ == "__main__":
19 | tornado.options.parse_command_line()
20 | app = tornado.web.Application(handlers=[(r"/", IndexHandler)])
21 | http_server = tornado.httpserver.HTTPServer(app)
22 | http_server.listen(options.port)
23 | tornado.ioloop.IOLoop.instance().start()
24 |
--------------------------------------------------------------------------------
/Exercises/LearnTornado/hello.py:
--------------------------------------------------------------------------------
1 | import tornado.httpserver
2 | import tornado.ioloop
3 | import tornado.options
4 | import tornado.web
5 |
6 |
7 | from tornado.options import define, options
8 | define("port", default=8000, help="run on the given port", type=int)
9 |
10 | class IndexHandler(tornado.web.RequestHandler):
11 | def get(self):
12 | greeting = self.get_argument('greeting', 'Hello')
13 | self.write(greeting + ', friendly user!')
14 |
15 | if __name__ == "__main__":
16 | tornado.options.parse_command_line()
17 | app = tornado.web.Application(handlers=[(r"/", IndexHandler)])
18 | http_server = tornado.httpserver.HTTPServer(app)
19 | http_server.listen(options.port)
20 | tornado.ioloop.IOLoop.instance().start()
21 |
--------------------------------------------------------------------------------
/Exercises/LearnTornado/hello_module.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import tornado.web
3 | import tornado.ioloop
4 | import tornado.options
5 | import tornado.httpserver
6 | import os.path
7 |
8 |
9 | from tornado.options import options, define
10 | define("port", default=8000, help="run on the given port", type=int)
11 |
12 |
13 | class HelloHandler(tornado.web.RequestHandler):
14 | def get(self):
15 | self.render('hello.html')
16 |
17 |
18 | class HelloModule(tornado.web.UIModule):
19 |
--------------------------------------------------------------------------------
/Exercises/LearnTornado/module/templates/hello.html:
--------------------------------------------------------------------------------
1 |
2 |
UI Module Example
3 |
4 | {% module Hello() %}
5 |
6 |
7 |
--------------------------------------------------------------------------------
/Exercises/LearnTornado/sslnginx.conf:
--------------------------------------------------------------------------------
1 | server {
2 | listen 443;
3 | ssl on;
4 | ssl_certificate /path/to/cert.pem;
5 | ssl_certificate_key /path/to/cert.key;
6 |
7 | default_type application/octet-stream;
8 |
9 | location /static/ {
10 | root /var/www/static;
11 | if ($query_string) {
12 | expires max;
13 | }
14 | }
15 |
16 | location = /favicon.ico {
17 | rewrite (.*) /static/favicon.ico;
18 | }
19 |
20 | location / {
21 | proxy_pass_header Server;
22 | proxy_set_header Host $http_host;
23 | proxy_redirect off;
24 | proxy_set_header X-Real-IP $remote_addr;
25 | proxy_set_header X-Scheme $scheme;
26 | proxy_pass http://tornados;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/Exercises/LearnTornado/templates/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
Poem Maker Pro
4 |
5 |
Enter terms below.
6 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/Exercises/LearnTornado/templates/poem.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
Poem Maker Pro
4 |
5 |
Your poem
6 |
Two {{ roads }} diverged in a {{ wood }}, and I-
7 | I took the one less travelled by,
8 | And that has {{ made }} all the {{ difference }}.
9 |
10 |
11 |
--------------------------------------------------------------------------------
/Exercises/LearnTornado/test.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding:utf-8 -*-
3 |
4 | import os
5 | from tornado.httpserver import HTTPServer
6 | from tornado.web import Application, RequestHandler
7 | from tornado.ioloop import IOLoop
8 |
9 |
10 |
11 | class TestHandler(RequestHandler):
12 | def get(self):
13 | import pdb
14 | pdb.set_trace()
15 | self.write("Hello, World!\n")
16 |
17 |
18 | #class TestHandler(RequestHandler):
19 | # def get(self):
20 | # self.write("Hello, World!\n")
21 |
22 | settings = {
23 | "static_path" : os.path.join(os.path.dirname(__file__), "static"),
24 | }
25 |
26 | application = Application([
27 | (r"/", TestHandler),
28 | ], **settings)
29 |
30 | if __name__ == "__main__":
31 | server = HTTPServer(application)
32 | server.listen(8000)
33 | IOLoop.instance().start()
34 |
--------------------------------------------------------------------------------
/Exercises/LearnTornado/tornado.conf:
--------------------------------------------------------------------------------
1 | # 声明一个叫做tornadoes的组以便管理
2 | [group:tornadoes]
3 | programs=tornado-8000,tornado-8001,tornado-8002,tornado-8003
4 |
5 | [program:tornado-8000]
6 | # 希望监听的port参数的tornado应用
7 | command=python /var/www/main.py --port=8000
8 | directory=/var/www
9 | user=www-data
10 | autorestart=true
11 | redirect_stderr=true
12 | stout_logfile=/var/log/tornado.log
13 | loglevel=info
14 |
15 | [program:tornado-8001]
16 | command=python /var/www/main.py --port=8001
17 | directory=/var/www
18 | user=www-data
19 | autorestart=true
20 | redirect_stderr=true
21 | stout_logfile=/var/log/tornado.log
22 | loglevel=info
23 |
24 | [program:tornado-8002]
25 | command=python /var/www/main.py --port=8002
26 | directory=/var/www
27 | user=www-data
28 | autorestart=true
29 | redirect_stderr=true
30 | stout_logfile=/var/log/tornado.log
31 | loglevel=info
32 |
33 | [program:tornado-8003]
34 | command=python /var/www/main.py --port=8003
35 | directory=/var/www
36 | user=www-data
37 | autorestart=true
38 | redirect_stderr=true
39 | stout_logfile=/var/log/tornado.log
40 | loglevel=info
41 |
--------------------------------------------------------------------------------
/Exercises/LearnTornado/twitter/templates/logout.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
Tornadoes on Twitter
4 |
5 |
6 |
7 |
8 |
You have successfully signed out.
9 |
Sign in
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/Exercises/MapReduce/parallel.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | import os
4 | import time
5 | import multiprocessing # Process based "threading" interface
6 |
7 |
8 | def task(args):
9 | time.sleep(1)
10 | pid = os.getpid() # Return current process
11 | return pid, args
12 |
13 | start = time.time()
14 | # Returns a process pool object, processes is the number of worker processes
15 | # to use.
16 | pool = multiprocessing.Pool(processes=4)
17 | result = pool.map(task, range(10))
18 | print result
19 | print "Cost: {}".format(time.time() - start)
20 |
--------------------------------------------------------------------------------
/Exercises/Marsh/deserialize.py:
--------------------------------------------------------------------------------
1 | from marshmallow import Schema, fields, post_load
2 | from test import User
3 |
4 | class UserSchema(Schema):
5 | name = fields.Str()
6 | email = fields.Email()
7 | created_at = fields.DateTime()
8 |
9 | @post_load
10 | def make_user(self, data):
11 | return User(**data)
12 |
13 |
14 | if __name__ == '__main__':
15 | user_data = {
16 | 'name': 'Kasheem',
17 | 'email': 'kasheem@python.com'
18 | }
19 | shcema = UserSchema()
20 | result = shcema.load(user_data)
21 | print result.data
22 |
--------------------------------------------------------------------------------
/Exercises/Marsh/load.py:
--------------------------------------------------------------------------------
1 | from marshmallow import pprint
2 | from test import UserSchema
3 |
4 | user_data = {
5 | 'created_at': '2016-07-07T05:26:03.869245',
6 | 'email': u'kasheem@python.com',
7 | 'name': u'Kasheem'
8 | }
9 |
10 | schema = UserSchema()
11 | result = schema.load(user_data)
12 | pprint(result.data)
13 |
--------------------------------------------------------------------------------
/Exercises/Marsh/validator.py:
--------------------------------------------------------------------------------
1 | from marshmallow import fields, Schema, validates, ValidationError
2 |
3 | class ItemSchema(Schema):
4 | quantity = fields.Integer()
5 |
6 | @validates('quantity')
7 | def validate_quantity(self, value):
8 | if value < 0:
9 | raise ValidationError('Quantity must be greater than 0.')
10 | if value > 30:
11 | raise ValidationError('Quantity must not be greater than 30.')
12 |
--------------------------------------------------------------------------------
/Exercises/MessageQueue/amqp_producer.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | import sys
4 | import pika
5 |
6 | parameters = pika.URLParameters('amqp://guest:guest@localhost:5672/%2F')
7 | connection = pika.BlockingConnection(parameters)
8 | channel = connection.channel()
9 | channel.exchange_declare(
10 | exchange='web_develop',
11 | exchange_type='direct',
12 | passive=False,
13 | durable=True,
14 | auto_delete=False
15 | )
16 |
17 | if len(sys.argv) != 1:
18 | msg = sys.argv[1]
19 | else:
20 | msg = 'hah'
21 |
22 | props = pika.BasicProperties(content_type='text/plain', delivery_mode=2)
23 |
24 | channel.basic_publish('web_develop', 'xxx_routing_key', msg, properties=props)
25 |
26 | connection.close()
27 |
--------------------------------------------------------------------------------
/Exercises/MultiThread/_1.py:
--------------------------------------------------------------------------------
1 | #-*- coding: utf-8 -*-
2 | #!/usr/bin/env python
3 |
4 | import threading
5 |
6 |
7 | def worker(num):
8 | print('Worker: %s' % num)
9 | return
10 |
11 |
12 | threads = []
13 | for i in range(5):
14 | t = threading.Thread(target=worker, args=(i,))
15 | threads.append(t)
16 | t.start()
17 |
--------------------------------------------------------------------------------
/Exercises/MultiThread/_2.py:
--------------------------------------------------------------------------------
1 | #-*- coding: utf-8 -*-
2 | #!/usr/bin/env python
3 |
4 |
5 | import threading
6 | import time
7 |
8 |
9 | def worker():
10 | print threading.currentThread().getName(), 'Starting'
11 | time.sleep(2)
12 | print threading.currentThread().getName(), 'Exiting'
13 |
14 |
15 | def my_service():
16 | print threading.currentThread().getName(), 'Starting'
17 | time.sleep(3)
18 | print threading.currentThread().getName(), 'Exiting'
19 |
20 |
21 | t = threading.Thread(name='my_service', target=my_service)
22 | w = threading.Thread(name='worker', target=worker)
23 | w2 = threading.Thread(target=worker) # Default name: Thread-1, Thread-2 ...
24 |
25 | w.start()
26 | w2.start()
27 | t.start()
28 |
--------------------------------------------------------------------------------
/Exercises/MultiThread/_3.py:
--------------------------------------------------------------------------------
1 | #-*- coding: utf-8 -*-
2 | #!/usr/bin/env python
3 |
4 |
5 | import logging
6 | import threading
7 | import time
8 |
9 |
10 | logging.basicConfig(level=logging.DEBUG,
11 | format='[%(levelname)s] (%(threadName)-10s) %(message)s',
12 | )
13 |
14 |
15 | def worker():
16 | logging.debug('Starting')
17 | time.sleep(2)
18 | logging.debug('Exiting')
19 |
20 |
21 | def my_service():
22 | logging.debug('Starting')
23 | time.sleep(3)
24 | logging.debug('Exiting')
25 |
26 |
27 | t = threading.Thread(name='my_service', target=my_service)
28 | w = threading.Thread(name='worker', target=worker)
29 | w2 = threading.Thread(target=worker)
30 |
31 | w.start()
32 | w2.start()
33 | t.start()
34 |
--------------------------------------------------------------------------------
/Exercises/MultiThread/_4.py:
--------------------------------------------------------------------------------
1 | #-*- coding: utf-8 -*-
2 | #!/usr/bin/env python
3 |
4 |
5 | import threading
6 | import time
7 | import logging
8 |
9 |
10 | logging.basicConfig(level=logging.DEBUG,
11 | format='(%(threadName)-10s) %(message)s'
12 | )
13 |
14 |
15 | def daemon():
16 | logging.debug('Starting')
17 | time.sleep(2)
18 | logging.debug('Exiting')
19 |
20 |
21 | d = threading.Thread(name='daemon', target=daemon)
22 | d.setDaemon(True) # 设置daemon模式,主程序结束,这个子线程依然在
23 |
24 |
25 | def non_daemon():
26 | logging.debug('Starting')
27 | logging.debug('Exiting')
28 |
29 |
30 | t = threading.Thread(name='non-daemon', target=non_daemon)
31 |
32 |
33 | d.start()
34 | t.start()
35 |
--------------------------------------------------------------------------------
/Exercises/MultiThread/_5.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | #-*- coding: utf-8 -*-
3 |
4 | import random
5 | import threading
6 | import time
7 | import logging
8 |
9 |
10 | logging.basicConfig(level=logging.DEBUG,
11 | format='(%(threadName)-10s) %(message)s',
12 | )
13 |
14 |
15 | def worker():
16 | t = threading.currentThread()
17 | pause = random.randint(1,5)
18 | logging.debug('sleeping %s', pause)
19 | time.sleep(pause)
20 | logging.debug('ending')
21 | return
22 |
23 |
24 | for i in range(3):
25 | t = threading.Thread(target=worker)
26 | t.setDaemon(True)
27 | t.start()
28 |
29 |
30 | main_thread = threading.currentThread() # Get current thread
31 | for t in threading.enumerate(): # enumerate() returns the list of current threads
32 | if t is main_thread:
33 | continue
34 | logging.debug('joining %s', t.getName())
35 | print(threading.enumerate())
36 | t.join()
37 |
--------------------------------------------------------------------------------
/Exercises/MultiThread/_6.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | #-*- coding: utf-8 -*-
3 |
4 | import threading
5 | import logging
6 |
7 |
8 | logging.basicConfig(level=logging.DEBUG,
9 | format='(%(threadName)-10s) %(message)s',
10 | )
11 |
12 |
13 | class MyThreadWithArgs(threading.Thread): # 继承threading.Thread,实例化,重写run(),调用start()启动
14 | def __init__(self, group=None, target=None, name=None,
15 | args=(), kwargs=None, verbose=None):
16 | threading.Thread.__init__(self, group=group, target=target, name=name,
17 | verbose=verbose)
18 | self.args = args
19 | self.kwargs = kwargs
20 | return
21 |
22 | def run(self):
23 | logging.debug('running with %s and %s', self.args, self.kwargs)
24 | return
25 |
26 |
27 | for i in range(5):
28 | t = MyThreadWithArgs(args=(i,), kwargs={'a': 'A', 'b': 'B'})
29 | t.start()
30 |
--------------------------------------------------------------------------------
/Exercises/MultiThread/_7.py:
--------------------------------------------------------------------------------
1 | #-*- coding: utf-8 -*-
2 | #!/usr/bin/env python
3 |
4 | import logging
5 | import threading
6 | import time
7 |
8 |
9 | logging.basicConfig(level=logging.DEBUG,
10 | format='(%(threadName)-10s) %(message)s',
11 | )
12 |
13 |
14 | def delayed():
15 | logging.debug('worker running')
16 | return
17 |
18 |
19 | t1 = threading.Timer(3, delayed) # Timer主要用计时器来延时
20 | t1.setName('t1')
21 | t2 = threading.Timer(3, delayed)
22 | t2.setName('t2')
23 |
24 |
25 | logging.debug('starting timers')
26 | t1.start()
27 | t2.start()
28 |
29 |
30 | logging.debug('waiting before canceling %s', t2.getName())
31 | time.sleep(2)
32 | logging.debug('canceling %s', t2.getName())
33 | t2.cancel() # 取消线程
34 | logging.debug('done')
35 |
--------------------------------------------------------------------------------
/Exercises/MultiThread/global.py:
--------------------------------------------------------------------------------
1 | #-*- coding: utf-8 -*-
2 |
3 | import threading
4 | global_num = 0
5 | l = threading.Lock()
6 |
7 |
8 | def thread_cal():
9 | global global_num
10 | for i in xrange(1000):
11 | l.acquire()
12 | global_num += 1
13 | l.release()
14 |
15 |
16 | threads = []
17 | for i in xrange(10):
18 | threads.append(threading.Thread(target=thread_cal))
19 | threads[i].start()
20 |
21 | for i in xrange(10):
22 | threads[i].join()
23 |
24 |
25 | print global_num
26 |
--------------------------------------------------------------------------------
/Exercises/MultiThread/globaldict.py:
--------------------------------------------------------------------------------
1 | #-*- coding: utf-8 -*-
2 |
3 | import threading
4 | global_data = {}
5 | threads = []
6 |
7 |
8 | def show():
9 | cur_thread = threading.current_thread()
10 | print cur_thread.getName(), global_data[cur_thread]
11 |
12 |
13 | def thread_cal():
14 | global global_data
15 | cur_thread = threading.current_thread()
16 | global_data[cur_thread] = 0
17 | for _ in xrange(1000):
18 | global_data[cur_thread] += 1
19 | show()
20 |
21 | for i in range(10):
22 | threads.append(threading.Thread(target=thread_cal))
23 | threads[i].start()
24 |
--------------------------------------------------------------------------------
/Exercises/MultiThread/local.py:
--------------------------------------------------------------------------------
1 | #-*- coding: utf-8 -*-
2 |
3 | import threading
4 | l = threading.Lock()
5 | global_num = 0
6 |
7 |
8 | def thread_cal():
9 | global global_num
10 | for _ in xrange(1000):
11 | l.acquire()
12 | global_num += 1
13 | l.release()
14 |
15 |
16 | def show(num):
17 | print(threading.current_thread().getName(), num)
18 |
19 |
20 | def thread_cal():
21 | local_num = 0
22 | for _ in xrange(1000):
23 | local_num += 1
24 | show(local_num)
25 |
26 |
27 | threads = []
28 | for i in range(10):
29 | threads.append(threading.Thread(target=thread_cal))
30 | threads[i].start()
31 |
--------------------------------------------------------------------------------
/Exercises/MultiThread/threadlocal.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | # 每个线程可以通过global_data.num获得自己独有的数据,做到线程之间的隔离
3 |
4 | import threading
5 |
6 |
7 | global_data = threading.local()
8 | threads = []
9 |
10 |
11 | def show():
12 | print threading.current_thread().getName(), global_data.num
13 |
14 |
15 | def thread_cal():
16 | global_data.num = 0
17 | for _ in xrange(1000):
18 | global_data.num += 1
19 | show()
20 |
21 |
22 | for i in range(10):
23 | threads.append(threading.Thread(target=thread_cal))
24 | threads[i].start()
25 |
--------------------------------------------------------------------------------
/Exercises/Pickle/stream.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 |
4 | try:
5 | import cPickle as pickle
6 | except:
7 | import pickle
8 | import pprint
9 | from StringIO import StringIO
10 |
11 |
12 | class SimpleObject(object):
13 | def __init__(self, name):
14 | self.name = name
15 | l = list(name)
16 | l.reverse()
17 | self.name_backwards = ''.join(l)
18 | return
19 |
20 |
21 | data = []
22 | data.append(SimpleObject('pickle'))
23 | data.append(SimpleObject('cPickle'))
24 | data.append(SimpleObject('last'))
25 |
26 |
27 | # 模拟文件
28 | out_s = StringIO()
29 |
30 | for o in data:
31 | print 'WRITING: %s (%s)' % (o.name, o.name_backwards)
32 | pickle.dump(o, out_s)
33 | # 清除内部缓存区
34 | out_s.flush()
35 |
36 | in_s = StringIO(out_s.getvalue())
37 |
38 | while True:
39 | try:
40 | o = pickle.load(in_s)
41 | except EOFError:
42 | break
43 | else:
44 | print 'READ: %s (%s)' % (o.name, o.name_backwards)
45 |
--------------------------------------------------------------------------------
/Exercises/Pickle/test.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 |
4 | try:
5 | import cPickle as pickle
6 | except:
7 | import pickle
8 | import pprint
9 |
10 | data = [ {'a': 'A', 'b':2, 'c': 3.0} ]
11 | print 'DATA:',
12 | pprint.pprint(data)
13 |
14 | data_string = pickle.dumps(data)
15 | print 'PICKLE:', data_string
16 |
--------------------------------------------------------------------------------
/Exercises/Pickle/test2.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 |
4 | try:
5 | import cPickle as pickle
6 | except:
7 | import pickle
8 | import pprint
9 |
10 |
11 | data1 = [ { 'a':'A', 'b':2, 'c':3.0 } ]
12 | print 'BEFORE:',
13 | pprint.pprint(data1)
14 |
15 | data1_string = pickle.dumps(data1)
16 |
17 | data2 = pickle.loads(data1_string)
18 | print 'AFTER:',
19 | pprint.pprint(data2)
20 |
21 |
22 | # 新构造的对象和原对象相同,但并非同一对象
23 | print 'SAME?:', (data1 is data2)
24 | print 'EQUAL?:', (data1 == data2)
25 |
--------------------------------------------------------------------------------
/Exercises/PyQueryTest/hello.html:
--------------------------------------------------------------------------------
1 |
10 |
--------------------------------------------------------------------------------
/Exercises/PyQueryTest/test.py:
--------------------------------------------------------------------------------
1 | #-*- coding: utf-8 -*-
2 |
3 | # Four methods to initialize PyQuery
4 |
5 | # 1. init with string
6 | # from pyquery import PyQuery as pq
7 | # doc = pq('')
8 |
9 | # 2. init with lxml.etree
10 | # from lxml import etree
11 | # doc = pq(etree.fromstring(""))
12 |
13 | # 3. init directly with URL
14 | # from pyquery import PyQuery as pq
15 | # doc = pq('http://www.baidu.com')
16 |
17 | # 4. init with file
18 | # from pyquery import PyQuery as pq
19 | # doc = pq(filename='hello.html')
20 |
21 | from pyquery import PyQuery as pq
22 |
23 | doc = pq(filename='hello.html')
24 | print doc.html()
25 | print '-'*40
26 | print type(doc)
27 | print '-'*40
28 | li = doc('li')
29 | print '-'*40
30 | print type(li)
31 | print '-'*40
32 | print li.text()
33 |
34 | # url for the passage: http://python.jobbole.com/85222/
35 |
--------------------------------------------------------------------------------
/Exercises/PythonHardWay/ex44d.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 |
4 | class Parent(object):
5 |
6 |
7 | def override(self):
8 | print 'PARENT override()'
9 |
10 |
11 | def implicit(self):
12 | print 'PARENT implicit()'
13 |
14 |
15 | def altered(self):
16 | print 'PARENT altered()'
17 |
18 |
19 | class Child(Parent):
20 |
21 |
22 | def override(self):
23 | print 'CHILD override()'
24 |
25 |
26 | def altered(self):
27 | print 'CHILD, BEFORE PARENT altered()'
28 | super(Child, self).altered()
29 | print 'CHILD, AFTER PARENT altered()'
30 |
31 |
32 | '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
33 |
34 |
35 | dad = Parent()
36 | son = Child()
37 |
38 |
39 | dad.implicit()
40 | son.implicit()
41 |
42 |
43 | dad.override()
44 | son.override()
45 |
46 |
47 | dad.altered()
48 | son.altered()
49 |
--------------------------------------------------------------------------------
/Exercises/PythonHardWay/exercise10.py:
--------------------------------------------------------------------------------
1 | #Here's some new strange stuff,remember type it exactly.
2 |
3 |
4 | days="Mon Tue Wed Thu Fri Sat Sun"
5 | months="Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
6 |
7 |
8 | print"Here are the days:",days
9 | print"Here are the months:",months
10 |
11 |
12 | print"""
13 | There's something going on here.
14 | With the three double-quotes.
15 | We'll be able to type as much as we like.
16 | Even 4 lines if we want, or 5, or 6.
17 | """
18 |
--------------------------------------------------------------------------------
/Exercises/PythonHardWay/exercise11.py:
--------------------------------------------------------------------------------
1 | print"I am 6'2\"tall."
2 | print'I am 6\'2"tall.'
3 |
4 | tabby_cat="\tI'm tabbed in."
5 | persian_cat="I'm split\non a line."
6 | backslash_cat="I'm\\a\\cat."
7 |
8 | fat_cat='''
9 | I'll do a list:
10 | \t* Cat food
11 | \t* Fishies
12 | \t* Catnip\n\t*Grass
13 | '''
14 |
15 | print tabby_cat
16 | print persian_cat
17 | print backslash_cat
18 | print fat_cat
19 |
20 | print '''she said:"he's a boy"'''
21 |
22 | print"How old are you?",
23 | age=raw_input()
24 | print"How tall are you?",
25 | height=raw_input()
26 | print"How much do you weigh?",
27 | weight=raw_input()
28 |
29 | print"So,you're %s old,%s tall and %s heavy."%(age,height,weight)
30 |
--------------------------------------------------------------------------------
/Exercises/PythonHardWay/exercise12.py:
--------------------------------------------------------------------------------
1 | y=raw_input("What's your name")
2 | age=raw_input("How old are you?")
3 | height=raw_input("How tall are you?")
4 | weight=raw_input("How much do you weigh?")
5 |
6 | print"Let's talk about %r.So,you're %s old,%s tall and %s heavy."%(y,age,height,weight)
7 |
8 |
--------------------------------------------------------------------------------
/Exercises/PythonHardWay/exercise13.py:
--------------------------------------------------------------------------------
1 | from sys import argv
2 |
3 | script,first,second,third=argv
4 |
5 | print"The script is called:",script
6 | print"Your first variable is:",first=raw_input()
7 | print"Your second variable is:",second=raw_input()
8 | print"Your third variable is:",third=raw_input()
9 |
--------------------------------------------------------------------------------
/Exercises/PythonHardWay/exercise14.py:
--------------------------------------------------------------------------------
1 | from sys import argv
2 |
3 | script,user_name=argv
4 | prompt='>'
5 |
6 | print "Hi %s,I'm the %s script."%(user_name,script)
7 | print"I'd like to ask you a few questions."
8 | print"Do you like me %s?"%user_name
9 | likes=raw_input(prompt)
10 |
11 | print"Where do you live %s?"%user_name
12 | lives=raw_input(prompt)
13 |
14 | print"What kind of computer do you have?"
15 | computer=raw_input(prompt)
16 |
17 | print"""
18 | Alright, so you said %r about liking me.
19 | You live in %r.Not sure where that is.
20 | And you have a %r computer. Nice.
21 | """%(likes,lives,computer)
22 |
23 |
--------------------------------------------------------------------------------
/Exercises/PythonHardWay/exercise15.py:
--------------------------------------------------------------------------------
1 | from sys import argv
2 |
3 | script,filename=argv
4 | #Line1-3 uses argv to get a filename.
5 | txt=open(filename)
6 |
7 | print"Here's your file %r:"%filename#a little message
8 | print txt.read()#Function on txt named read
9 |
10 | print"Type the filename again:"
11 | file_again=raw_input(">")
12 |
13 | txt_again=open(file_again)
14 |
15 | print txt_again.read()
16 |
--------------------------------------------------------------------------------
/Exercises/PythonHardWay/exercise16.py:
--------------------------------------------------------------------------------
1 | from sys import argv
2 |
3 | script,filename=argv
4 |
5 | print"We're going to erase %r."%filename
6 | print"If you don't want that, hit CTRL-C (^C)."
7 | print"If you do want that, hit RETURN."
8 |
9 | raw_input("?")
10 |
11 | print"Opening the file..."
12 | target=open(filename,'w')
13 |
14 | print"Truncating the file. Goodbye!"
15 | target.truncate()
16 |
17 | print"Now I'm going to ask you for three lines."
18 |
19 | line1=raw_input("line 1: ")
20 | line2=raw_input("line 2: ")
21 | line3=raw_input("line 3: ")
22 |
23 | print "I'm going to write these to the file."
24 |
25 | target.write(line1)
26 | target.write("\n")
27 | target.write(line2)
28 | target.write("\n")
29 | target.write(line3)
30 | target.write("\n")
31 |
32 | print"And finally, we close it."
33 | target.close()
34 |
--------------------------------------------------------------------------------
/Exercises/PythonHardWay/exercise7.py:
--------------------------------------------------------------------------------
1 | print"Mary had a little lamb."
2 | print"Its fleece was white as %s."%'snow'
3 | print"And everywhere that Mary went."
4 | print"."*10 #what'd that do
5 |
6 | end1="C"
7 | end2="h"
8 | end3="e"
9 | end4="e"
10 | end5="s"
11 | end6="e"
12 | end7="B"
13 | end8="u"
14 | end9="r"
15 | end10="g"
16 | end11="e"
17 | end12="r"
18 |
19 | #watch that comma at the end.try removing it to see what happens
20 | print end1+end2+end3+end4+end5+end6
21 | print end7+end8+end9+end10+end11+end12
22 |
--------------------------------------------------------------------------------
/Exercises/PythonHardWay/exercise8.py:
--------------------------------------------------------------------------------
1 | formatter="%r %r %r %r"
2 |
3 | print formatter%(1,2,3,4)
4 | print formatter%("one","two","three","four")
5 | print formatter%(True,False,False,True)
6 | print formatter%(formatter,formatter,formatter,formatter)
7 | print formatter%(
8 | "I had this thing.",
9 | "That you could type up.",
10 | "But it didn't sing.",
11 | "So I said goodnight."
12 | )
13 |
--------------------------------------------------------------------------------
/Exercises/PythonRobot/cookie.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import urllib2, cookielib
3 |
4 | #声明一个CookieJar对象实例来保存cookie
5 | cookie = cookielib.CookieJar()
6 | #利用urllib2库的HTTPCookieProcessor对象来创建cookie处理器
7 | handler = urllib2.HTTPCookieProcessor(cookie)
8 | #通过handler来构建opener
9 | opener = urllib2.build_opener(handler)
10 | #此处的open方法同urllib2的urlopen方法,也可以传入request
11 | response = opener.open('http://www.baidu.com')
12 | for item in cookie:
13 | print 'Name = ' + item.name
14 | print 'Value = ' + item.value
15 |
--------------------------------------------------------------------------------
/Exercises/PythonRobot/cookie.txt:
--------------------------------------------------------------------------------
1 | # Netscape HTTP Cookie File
2 | # http://curl.haxx.se/rfc/cookie_spec.html
3 | # This is a generated file! Do not edit.
4 |
5 | .baidu.com TRUE / FALSE 3604113482 BAIDUID 21BE51AE897BDF43B808F5BCF1BF1F83:FG=1
6 | .baidu.com TRUE / FALSE 3604113482 BIDUPSID 21BE51AE897BDF43B808F5BCF1BF1F83
7 | .baidu.com TRUE / FALSE H_PS_PSSID 1428_18205_17000_17073_15734_12207
8 | .baidu.com TRUE / FALSE 3604113482 PSTM 1456641279
9 | www.baidu.com FALSE / FALSE BDSVRTM 0
10 | www.baidu.com FALSE / FALSE BD_HOME 0
11 |
--------------------------------------------------------------------------------
/Exercises/PythonRobot/getdemo.py:
--------------------------------------------------------------------------------
1 | import urllib, urllib2
2 |
3 | values = {}
4 | values['username'] = 'xxx@xxx.com'
5 | values['password'] = 'xxx'
6 | data = urllib.urlencode(values)
7 | url = 'http://xxx.xxx.com'
8 | geturl = url + "?" + data
9 | request = urllib2.Request(geturl)
10 | response = urllib2.urlopen(request)
11 | print response.read()
12 |
--------------------------------------------------------------------------------
/Exercises/PythonRobot/getjpg.py:
--------------------------------------------------------------------------------
1 | import urllib, re
2 |
3 |
4 | def getHtml(url):
5 | page = urllib.urlopen(url)
6 | html = page.read()
7 | return html
8 |
9 | def getImg(html):
10 | reg = r'src="(.+?\.jpg)" pic_ext'
11 | imgre = re.compile(reg)
12 | imglist = re.findall(imgre, html)
13 | x = 0
14 | for i in imglist:
15 | urllib.urlretrieve(i, 'picgot/%s.jpg' % x)
16 | x += 1
17 | return "All pictures have been got!"
18 |
19 | html = getHtml("http://tieba.baidu.com/p/2460150866")
20 |
21 | print getImg(html)
22 |
--------------------------------------------------------------------------------
/Exercises/PythonRobot/getjpg2.py:
--------------------------------------------------------------------------------
1 | import re
2 | import urllib
3 |
4 |
5 | def getHtml(url):
6 | page = urllib.urlopen(url)
7 | html = page.read()
8 | return html
9 |
10 | def getImg(html):
11 | reg = r'src="(.+?\.jpg)" pic_ext'
12 | imgre = re.compile(reg)
13 | imglist = re.findall(imgre, html)
14 | return imglist
15 |
16 | html = getHtml("http://tieba.baidu.com/p/2460150866")
17 | print getImg(html)
18 |
--------------------------------------------------------------------------------
/Exercises/PythonRobot/hasattr.py:
--------------------------------------------------------------------------------
1 | import urllib2
2 |
3 | req = urllib2.Request('http://blog.csdn.net/cqcre')
4 | try:
5 | urllib2.urlopen(req)
6 | except urllib2.URLError, e:
7 | if hasattr(e, "code"):
8 | print e.code
9 | if hasattr(e, "reason"):
10 | print e.reason
11 | else:
12 | print "OK"
13 |
--------------------------------------------------------------------------------
/Exercises/PythonRobot/httperror.py:
--------------------------------------------------------------------------------
1 | import urllib2
2 |
3 | req = urllib2.Request('http://blog.csdn.net/cqcre')
4 | try:
5 | urllib2.urlopen(req)
6 | except urllib2.HTTPError, e:
7 | print e.code
8 | print e.reason
9 |
--------------------------------------------------------------------------------
/Exercises/PythonRobot/httperror2.py:
--------------------------------------------------------------------------------
1 | import urllib2
2 |
3 | req = urllib2.Request('http://blog.csdn.net/cqcre')
4 | try:
5 | urllib2.urlopen(req)
6 | except urllib2.HTTPError, e:
7 | print e.code
8 | except urllib2.URLError, e:
9 | print e.reason
10 | else:
11 | print "OK"
12 |
--------------------------------------------------------------------------------
/Exercises/PythonRobot/postdemo.py:
--------------------------------------------------------------------------------
1 | import urllib,urllib2
2 |
3 | values = {"username":"xxx@xxx.com", "password":"xxx"}
4 | data = urllib.urlencode(values)
5 | url = "http://xxx.xxx.com"
6 | request = urllib2.Request(url,data)
7 | response = urllib2.urlopen(request)
8 | print response.read()
9 |
--------------------------------------------------------------------------------
/Exercises/PythonRobot/proxy.py:
--------------------------------------------------------------------------------
1 | import urllib2
2 |
3 | enable_proxy = True
4 | proxy_handler = urllib2.ProxyHandler({"http": 'http://some-proxy.com:8080'})
5 | null_proxy_handler = urllib2.ProxyHandler({})
6 | if enable_proxy:
7 | opener = urllib2.build_opener(proxy_handler)
8 | else:
9 | opener = urllib2.build_opener(null_proxy_handler)
10 | urllib2.install_opener(opener)
11 |
--------------------------------------------------------------------------------
/Exercises/PythonRobot/readcookie.py:
--------------------------------------------------------------------------------
1 | import cookielib, urllib2
2 |
3 | cookie = cookielib.MozillaCookieJar()
4 | cookie.load('cookie.txt', ignore_discard=True, ignore_expires=True)
5 | req = urllib2.Request("http://www.baidu.com")
6 | opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
7 | response = opener.open(req)
8 | print response.read()
9 |
--------------------------------------------------------------------------------
/Exercises/PythonRobot/savecookie.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import cookielib, urllib2
3 |
4 | #设置保存cookie的文件,同级目录下的cookie.txt
5 | filename = 'cookie.txt'
6 | #声明一个MozillaCookieJar对象实例来保存cookie,之后写入文件
7 | cookie = cookielib.MozillaCookieJar(filename)
8 | #利用urllib2库中的HTTPCookieProcessor对象来创建cookie处理器
9 | handler = urllib2.HTTPCookieProcessor(cookie)
10 | #通过handler来创建opener
11 | opener = urllib2.build_opener(handler)
12 | #创建一个请求,原理同urllib2的urlopen
13 | response = opener.open("http://www.baidu.com")
14 | #保存cookie到文件
15 | cookie.save(ignore_discard=True, ignore_expires=True)
16 |
--------------------------------------------------------------------------------
/Exercises/PythonRobot/urlerror.py:
--------------------------------------------------------------------------------
1 | import urllib2
2 |
3 | request = urllib2.Request('http://www.xxxx.com')
4 | try:
5 | urllib2.urlopen(request)
6 | except urllib2.URLError, e:
7 | print e.reason
8 |
--------------------------------------------------------------------------------
/Exercises/PythonRobot/withheader:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/Exercises/PythonRobot/withheader.py:
--------------------------------------------------------------------------------
1 | import urllib, urllib2
2 |
3 | url = 'http://www.server.com/login'
4 | user_agent = 'Mozilla/5.0i (Windows NT 6.3; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0'
5 | values = {'username': 'xxx', 'password': 'xxx'}
6 | headers = {'User-Agent': user_agent, 'Referer':'http://www.zhihu.com/article'}
7 | data = urllib.urlencode(values)
8 | request = urllib2.Request(url, data, headers)
9 | response = urllib2.urlopen(request)
10 | page = response.read()
11 |
--------------------------------------------------------------------------------
/Exercises/QiniuPythonDemo/test.py:
--------------------------------------------------------------------------------
1 | from flask import Flask
2 | from flask_qiniustorage import Qiniu
3 |
4 | QINIU_ACCESS_KEY = ''
5 | QINIU_SECRET_KEY = ''
6 | QINIU_BUCKET_NAME = ''
7 | QINIU_BUCKET_DOMAIN = ''
8 |
9 | app = Flask(__name__)
10 | app.config.from_object(__name__)
11 | qiniu_store = Qiniu(app)
12 | # 或者
13 | # qiniu_store = Qiniu()
14 | # qiniu_store.init_app(app)
15 |
16 | # 保存文件到七牛
17 | @app.route('/save')
18 | def save():
19 | data = 'data to save'
20 | filename = 'filename'
21 | ret, info = qiniu_store.save(data, filename)
22 | return str(ret)
23 |
24 | # 删除七牛空间中的文件
25 | @app.route('/delete')
26 | def delete():
27 | filename = 'filename'
28 | ret, info = qiniu_store.delete(filename)
29 | return str(ret)
30 |
31 | # 根据文件名获取对应的公开URL
32 | @app.route('/url')
33 | def url():
34 | filename = 'filename'
35 | return qiniu_store.url(filename)
36 |
--------------------------------------------------------------------------------
/Exercises/Recursion/solve.py:
--------------------------------------------------------------------------------
1 | def register(cls):
2 | cls.another_method = Mixin.another_method
3 | return cls
4 |
--------------------------------------------------------------------------------
/Exercises/Recursion/test.py:
--------------------------------------------------------------------------------
1 | class View(object):
2 | def method(self):
3 | pass
4 |
5 | class ChildView(View):
6 | def method(self):
7 | super(ChildView, self).method()
8 |
9 | class Mixin(object):
10 | pass
11 |
12 | def register(cls):
13 | return type(
14 | 'DecoratedView',
15 | (Mixin, cls),
16 | {}
17 | )
18 |
--------------------------------------------------------------------------------
/Exercises/Recursion/test2.py:
--------------------------------------------------------------------------------
1 | class Mixin(object):
2 | pass
3 |
4 | def register(cls):
5 | return type(
6 | cls.__name__,
7 | (Mixin, cls),
8 | {}
9 | )
10 |
11 | class View(object):
12 | def method(self):
13 | print "method() from View()"
14 |
15 | @register
16 | class ChildView(View):
17 | def method(self):
18 | super(ChildView, self).method()
19 |
--------------------------------------------------------------------------------
/Exercises/RedirectBackWithWTF/app.py:
--------------------------------------------------------------------------------
1 | from flask import Flask, render_template
2 | from redirect import RedirectForm
3 | from wtforms import TextField, HiddenField
4 |
5 | app = Flask(__name__)
6 | app.config['SECRET_KEY'] = 'hard to guess string'
7 |
8 |
9 | class LoginForm(RedirectForm):
10 | username = TextField('Username')
11 | password = TextField('Password')
12 |
13 | @app.route('/login', methods=['GET', 'POST'])
14 | def login():
15 | form = LoginForm()
16 | if form.validate_on_submit():
17 | return form.redirect('index')
18 | return render_template('login.html', form=form)
19 |
20 | if __name__ == '__main__':
21 | app.run(debug=True)
22 |
--------------------------------------------------------------------------------
/Exercises/RedirectBackWithWTF/templates/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | Test -- Index
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Exercises/RedirectBackWithWTF/templates/login.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/Exercises/RedirectDemo/app.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from flask import Flask, request, render_template, url_for
3 | from redirect_urls import is_safe_url, get_redirect_target, redirect_back
4 |
5 | app = Flask(__name__)
6 |
7 | @app.route('/')
8 | def index():
9 | return 'this is index'
10 |
11 | @app.route('/login', methods=['GET', 'POST'])
12 | def login():
13 | next = get_redirect_target()
14 | if request.method == 'POST':
15 | # login code here
16 | return redirect_back(url_for("index"))
17 | return render_template('index.html', next=next)
18 |
19 | if __name__ == '__main__':
20 | app.run(debug=True)
21 |
--------------------------------------------------------------------------------
/Exercises/RedirectDemo/redirect_urls.py:
--------------------------------------------------------------------------------
1 | from urlparse import urlparse, urljoin
2 | from flask import request, url_for, redirect
3 |
4 | def is_safe_url(target):
5 | ref_url = urlparse(request.host_url)
6 | test_url = urlparse(urljoin(request.host_url, target))
7 | return test_url.scheme in ('http', 'https') and \
8 | ref_url.netloc == test_url.netloc
9 |
10 | def get_redirect_target():
11 | for target in request.values.get('next'), request.referrer:
12 | if not target:
13 | continue
14 | if is_safe_url(target):
15 | return target
16 |
17 | def redirect_back(endpoint, **values):
18 | target = request.form['next']
19 | if not target or not is_safe_url(target):
20 | target = url_for(endpoint, **values)
21 | return redirect(target)
22 |
--------------------------------------------------------------------------------
/Exercises/RedirectDemo/templates/index.html:
--------------------------------------------------------------------------------
1 |
12 |
--------------------------------------------------------------------------------
/Exercises/Request/test.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | #-*- coding: utf-8 -*-
3 |
4 | import requests
5 |
6 | # Get a webpage, eg: GitHub's public timeline
7 | # The Response object `r`
8 | r = requests.get('https://api.github.com/events')
9 |
10 | # Make an HTTP POST request
11 | r = requests.post('http://httpbin.org/test', data = {'key': 'value'})
12 |
13 | # HTTP PUT
14 | r = requests.put('http://httpbin.org/put', data = {'key': 'value'})
15 |
16 | # HTTP DELETE
17 | r = requests.delete('http://httpbin.org/delete')
18 |
19 | # HTTP HEAD
20 | # get only the head of a webpage
21 | r = requests.head('http://httpbin.org/get')
22 |
23 | # HTTP OPTIONS
24 | # get the methods surppoted by the server
25 | r = requests.options('http://httpbin.org/get')
26 |
27 |
28 | # Passing Parameters In URLS
29 | payload = {'key1': 'value1', 'key2': 'value2'}
30 | r = requests.get('http://httpbin.org/get', params=payload)
31 |
--------------------------------------------------------------------------------
/Exercises/ScrapyDemo/pic/1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/ScrapyDemo/pic/1.png
--------------------------------------------------------------------------------
/Exercises/ScrapyDemo/pic/2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/ScrapyDemo/pic/2.png
--------------------------------------------------------------------------------
/Exercises/ScrapyDemo/pic/3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/ScrapyDemo/pic/3.png
--------------------------------------------------------------------------------
/Exercises/ScrapyDemo/scrapy.cfg:
--------------------------------------------------------------------------------
1 | # Automatically created by: scrapy startproject
2 | #
3 | # For more information about the [deploy] section see:
4 | # https://scrapyd.readthedocs.org/en/latest/deploy.html
5 |
6 | [settings]
7 | default = scrial.settings
8 |
9 | [deploy]
10 | #url = http://localhost:6800/
11 | project = scrial
12 |
--------------------------------------------------------------------------------
/Exercises/ScrapyDemo/scrial/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/ScrapyDemo/scrial/__init__.py
--------------------------------------------------------------------------------
/Exercises/ScrapyDemo/scrial/items.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | # Define here the models for your scraped items
4 | #
5 | # See documentation in:
6 | # http://doc.scrapy.org/en/latest/topics/items.html
7 |
8 | import scrapy
9 |
10 |
11 | class ScrialItem(scrapy.Item):
12 | # define the fields for your item here like:
13 | # name = scrapy.Field()
14 | pass
15 |
16 |
17 | class DmozItem(scrapy.Item):
18 | title = scrapy.Field()
19 | link = scrapy.Field()
20 | desc = scrapy.Field()
21 |
--------------------------------------------------------------------------------
/Exercises/ScrapyDemo/scrial/pipelines.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | # Define your item pipelines here
4 | #
5 | # Don't forget to add your pipeline to the ITEM_PIPELINES setting
6 | # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
7 |
8 |
9 | class ScrialPipeline(object):
10 | def process_item(self, item, spider):
11 | return item
12 |
--------------------------------------------------------------------------------
/Exercises/ScrapyDemo/scrial/spiders/__init__.py:
--------------------------------------------------------------------------------
1 | # This package will contain the spiders of your Scrapy project
2 | #
3 | # Please refer to the documentation for information on how to create and manage
4 | # your spiders.
5 |
--------------------------------------------------------------------------------
/Exercises/ScrapyDemo/scrial/spiders/dmoz_spider.py:
--------------------------------------------------------------------------------
1 | import scrapy
2 |
3 |
4 | class DmozSpider(scrapy.spiders.Spider):
5 | name = 'dmoz'
6 | allowed_domains = ["dmoz.org"]
7 | start_urls = [
8 | "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",
9 | "http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/"
10 | ]
11 |
12 | def parse(self, response):
13 | for sel in response.xpath('//ul/li'):
14 | title = sel.xpath('a/text()').extract()
15 | link = sel.xpath('a/@href').extract()
16 | desc = sel.xpath('text()').extract()
17 | print title, link, desc
18 |
--------------------------------------------------------------------------------
/Exercises/Shell/array.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | array1=(1 2 3 4 5)
4 | array2=(
5 | 1
6 | 2
7 | 3
8 | 4
9 | 5
10 | )
11 | echo ${array1[0]}
12 | echo 'array2'
13 | # @ to get all elements
14 | echo ${array2[@]}
15 | # length of the array
16 | echo ${#array2[@]}
17 | echo ${#array2[*]}
18 | # length of an element
19 | echo ${#array2[0]}
20 |
--------------------------------------------------------------------------------
/Exercises/Shell/cal.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | val=`expr 2 + 2` # must with space between numbers and +
4 | echo "sum: $val"
5 |
6 | val=`expr 2 \* 2` # \ before *
7 | echo "multiply: $val"
8 |
9 | a=10
10 | b=20
11 | # if...then...fi
12 | if [ $a == $b ]
13 | then
14 | echo "a is equal to b"
15 | fi
16 |
17 | # and(&&)
18 | if [ $a -gt $b -a $a -lt $b ]
19 | then
20 | echo "somthing..."
21 | fi
22 |
23 | # or(||)
24 | if [ $a -le $b -o $a -ne $b ]
25 | then
26 | echo "something..."
27 | else
28 | echo "something else"
29 | fi
30 |
31 | # Sentence
32 | # [ $a = $b ]: sentence a is equal to sentence b
33 | # [ $a != $b ]: sentence a is not equal to sentence b
34 | # [ -z $a ]: length is 0
35 | # [ -n $a ]: length is not 0
36 | # [ $a ]: sentence is None
37 |
--------------------------------------------------------------------------------
/Exercises/Shell/para.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | your_name="kasheemlew"
4 | echo $your_name
5 | # brace is optional
6 | echo ${your_name}
7 |
8 | for i in `ls /etc`; do
9 | echo " ${i}"
10 | done
11 |
12 | # reassign would cast an error
13 | readonly your_name
14 | # your_name="k"
15 |
16 | # delete an parameter
17 | unset your_name
18 |
19 | str='this \n is a \n string'
20 | echo $str
21 | str="this \n is a \n string"
22 | echo $str
23 |
24 | string="abcd"
25 | # get the length of the string
26 | echo ${#string}
27 | string="hello world!"
28 | # get from index 1 to index 4
29 | echo ${string:1:4}
30 | # find index world
31 | echo `expr index "$string" world`
32 |
--------------------------------------------------------------------------------
/Exercises/Shell/para2.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | echo "Shell parameters:";
4 | echo "para1: $0";
5 | echo "para2: $1";
6 | echo "number of the arguments: $#";
7 | echo "display arguments as the first string: $*";
8 | echo "current process id: $$";
9 | echo "last process id in the backend: $!";
10 |
--------------------------------------------------------------------------------
/Exercises/Shell/stable-shell.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Some advice for writing stable shell script
4 | # URL: https://segmentfault.com/a/1190000006900083
5 |
6 | # print the commands been executed
7 | set -x
8 | # end the program when crash an error
9 | set -e
10 |
11 | # shellcheck helps
12 | # Github: https://github.com/koalaman/shellcheck
13 |
14 | # Deal with Parameter
15 | # https://segmentfault.com/a/1190000002539169
16 |
17 | # parameters are global in default
18 | # define local parameter:
19 | local hello="world"
20 | # echo ${hello}; would cause an error
21 |
22 | # invoke Function sighandler when received SIGINT
23 | trap sighandler INT
24 |
25 | echo "Hello world!";
26 |
27 | # allow invoke functions when script ends
28 | trap func EXIT
29 |
30 | # allow invoke functions when errors come up
31 | trap func ERR
32 |
--------------------------------------------------------------------------------
/Exercises/Shell/test.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | # This is an annotation
4 | # Two ways to execute the script
5 | # 1. chmod +x ./test.sh
6 | # ./test.sh
7 | # 2. /bin/sh test.sh (the information of interpreter in the first line is
8 | # useless
9 |
10 | echo "Hello World!"
11 |
--------------------------------------------------------------------------------
/Exercises/Singleton/decorator.py:
--------------------------------------------------------------------------------
1 | #-*- coding: utf-8 -*-
2 | # 定义了一个装饰器 singleton,它返回了一个内部函数 getinstance,该函数会判断某
3 | # 个类是否在字典 instances 中,如果不存在,则会将 cls 作为 key,cls(*args, **kw)
4 | # 作为 value 存到 instances 中,否则,直接返回 instances[cls]。
5 |
6 | from functools import wraps
7 |
8 | def singleton(cls):
9 | instances = {}
10 | @wraps(cls)
11 | def getinstance(*args, **kw):
12 | if cls not in instances:
13 | instances[cls] = cls(*args, **kw)
14 | return instances[cls]
15 | return getinstance
16 |
17 | @singleton
18 | class MyClass(object):
19 | a = 1
20 |
--------------------------------------------------------------------------------
/Exercises/Singleton/metaclass.py:
--------------------------------------------------------------------------------
1 | #-*- coding: utf-8 -*-
2 | # 元类(metaclass)可以控制类的创建过程,它拦截类的创建, 修改类的定义, 返回修改后的类
3 |
4 | class Singleton(type):
5 | _instances = {}
6 | def __call__(cls, *args, **kwargs):
7 | if cls not in cls._instances:
8 | cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
9 | return cls._instances[cls]
10 |
11 | # Python2
12 | class MyClass(object):
13 | __metaclass__ = Singleton
14 |
15 | # Python3
16 | class MyClass(metaclass=Singleton):
17 | pass
18 |
--------------------------------------------------------------------------------
/Exercises/Singleton/module.py:
--------------------------------------------------------------------------------
1 | #-*- coding: utf-8 -*-
2 | # 模块在第一次导入时,会生成 .pyc 文件,当第二次导入时,就会直接加载 .pyc 文件,而不会再次执行模块代码。
3 |
4 | class My_Singleton(object):
5 | def foo(self):
6 | pass
7 |
8 | my_singleton = My_Singleton()
9 |
--------------------------------------------------------------------------------
/Exercises/Singleton/new.py:
--------------------------------------------------------------------------------
1 | #-*- coding: utf-8 -*-
2 | # 将类的实例和一个类变量 _instance 关联起来,如果 cls._instance 为 None 则创建实
3 | # 例,否则直接返回 cls._instance。
4 |
5 | class Singleton(object):
6 | _instance = None
7 | def __new__(cls, *args, **kw):
8 | if not cls._instance:
9 | cls._instance = super(Singleton, cls).__new__(cls, *args, **kw)
10 | return cls._instance
11 |
12 | class MyClass(Singleton):
13 | a = 1
14 |
--------------------------------------------------------------------------------
/Exercises/Socket/chatroom/server-demo.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | #-*- coding: utf-8 -*-
3 |
4 |
5 | CONNECTION_LIST = []
6 |
7 | read_sockets, write_sockets, error_sockets = select.select(CONNECTION_LIST, [], [])
8 |
9 | def broadcast_data(sock, message):
10 | # Do not send the message to master socket and the client who has send us
11 | # the message
12 | for socket in CONNECTION_LIST:
13 | if socket != server_socket and socket != sock:
14 | try:
15 | socket.send(message)
16 | except:
17 | # Broken socket connection
18 | socket.close()
19 | CONNECTION_LIST.remove(socket)
20 |
--------------------------------------------------------------------------------
/Exercises/Socket/chatroom/test.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | #-*- coding: utf-8 -*-
3 |
4 |
5 | import socket
6 | import select
7 |
8 |
9 | sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
10 | sock2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
11 |
12 |
13 | sock1.connect(('192.168.1.1', 25))
14 | sock2.connect(('192.168.1.1', 25))
15 |
16 |
17 | while True:
18 | # select的三个参数都是list类型, 分别代表读事件, 写事件, 错误事件,
19 | # 返回满足的事件
20 | rlist, wlist, elist = select.select([sock1, sock2], [], [], 5)
21 | if [rlist, wlist, elist] == [[], [], []]:
22 | print('Five seconds elapsed.\n')
23 | else:
24 | for sock in rlist:
25 | print(sock.recv(100))
26 |
--------------------------------------------------------------------------------
/Exercises/Socket/keep-alive.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | #-*- coding: utf-8 -*-
3 |
4 | import socket
5 | import sys
6 |
7 | HOST = ''
8 | PORT = 5000
9 |
10 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
11 | print('Socket created')
12 |
13 | try:
14 | s.bind((HOST, PORT))
15 | except socket.error, msg:
16 | print('Bind failed. Error Code: {m1} Message {m2}'.format(m1=str(msg[0]), m2=msg[1]))
17 | sys.exit()
18 | print('Socket bind completed')
19 |
20 | s.listen(10)
21 | print('Socket now listening')
22 |
23 | while 1:
24 | conn, addr = s.accept()
25 | print('Connected with {a1} : {a2}'.format(a1=addr[0], a2=str(addr[1])))
26 | data = conn.recv(1024)
27 | reply = 'OK...' + data
28 | if not data:
29 | break
30 | conn.sendall(reply)
31 |
32 | conn.close()
33 | s.close()
34 |
--------------------------------------------------------------------------------
/Exercises/Socket/server.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | #-*- coding: utf-8 -*-
3 |
4 |
5 | import socket
6 | import sys
7 |
8 |
9 | # 绑定socket
10 | HOST = '' # 所有可用接口
11 | PORT = 8888 # 任意端口
12 |
13 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
14 | print('Socket created')
15 |
16 | try:
17 | s.bind((HOST, PORT))
18 | except socket.error, msg:
19 | print('Bind failed. Error Code: {m1} Message: {m2}'.format(m1=str(msg[0]), m2=msg[1]))
20 | sys.exit()
21 | print('Socket bind complete')
22 |
23 |
24 | # 监听连接
25 | s.listen(10) # 参数(backlog)控制连接个数
26 | print('Socket now listening')
27 |
28 |
29 | # 接收连接
30 | conn, addr = s.accept()
31 | print('Connected with {a}: {ad}'.format(a=addr[0], ad=str(addr[1])))
32 |
33 |
34 | data = conn.recv(1024)
35 | conn.sendall(data)
36 |
37 | conn.close()
38 | s.close()
39 |
--------------------------------------------------------------------------------
/Exercises/SortAlgorithm/bubble.py:
--------------------------------------------------------------------------------
1 | #-*- coding: utf-8 -*-
2 |
3 | # 冒泡排序(bubble sort)
4 | # 原理:
5 | # 1. 比较相邻的元素。如果第一个比第二个大,就交换他们两个。
6 | # 2. 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。这步做完后,最后的元素会是最大的数。
7 | # 3. 针对所有的元素重复以上的步骤,除了最后一个。
8 | # 4. 持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
9 |
10 | # 时间复杂度:
11 | # 最差: O(n^2)
12 | # 最优: O(n)
13 |
14 |
15 | def bubble_sort(alist):
16 | length = len(alist)
17 | for index in range(length-1):
18 | for i in range(0, length-index-1):
19 | if alist[i] > alist[i+1]:
20 | alist[i+1], alist[i] = alist[i], alist[i+1]
21 | return alist
22 |
23 |
24 | # 优化: 添加标记,在排序完成时停止排序
25 |
26 | def bubble_sort_flag(alist):
27 | length = len(alist)
28 | for index in range(length):
29 | flag = True
30 | for i in range(0, length-index-1):
31 | if alist[i] > alist[i+1]:
32 | alist[i+1], alist[i] = alist[i], alist[i+1]
33 | flag = False
34 | if flag:
35 | return alist
36 | return alist
37 |
--------------------------------------------------------------------------------
/Exercises/SortAlgorithm/comb_sort.py:
--------------------------------------------------------------------------------
1 | def comb_sort(alist):
2 | shrink = 1.3
3 | gap = len(alist)
4 |
5 | while True:
6 | gap = int(gap / shrink)
7 | i = 0
8 | if gap < 1:
9 | break
10 | else:
11 | while i + gap < length:
12 | if alist[i] > alist[i+gap]:
13 | alist[i], alist[i+gap] = alist[i+gap], alist[i]
14 | i += 1
15 | return alist
16 |
--------------------------------------------------------------------------------
/Exercises/SortAlgorithm/insertion.py:
--------------------------------------------------------------------------------
1 | #-*- coding: utf-8 -*-
2 |
3 | # 插入排序(insertion sort)
4 | # 原理:
5 | # 1. 从第一个元素开始,该元素可以认为已经被排序
6 | # 2. 取出下一个元素,在已经排序的元素序列中从后向前扫描
7 | # 3. 如果该元素(已排序)大于新元素,将该元素移到下一位置
8 | # 4. 重复步骤3,直到找到已排序的元素小于或者等于新元素的位置
9 | # 5. 将新元素插入到该位置后
10 | # 6. 重复步骤2~5
11 |
12 | # 时间复杂度:
13 | # 最差: O(n^2)
14 | # 最优: O(n)
15 |
16 |
17 | def insertion_sort(alist):
18 | length = len(alist)
19 | if length == 1:
20 | return alist
21 | b = insertion_sort(alist[1:])
22 | lengthb = len(b)
23 | for index in range(lengthb):
24 | if alist[0] <= b[index]:
25 | return b[:index] + [alist[0]] + b[index:]
26 | return b + [alist[0]]
27 |
--------------------------------------------------------------------------------
/Exercises/SortAlgorithm/readme.md:
--------------------------------------------------------------------------------
1 | # Sort Algorithms
2 |
3 | Collection of Common Sort Alogrithms in Python
4 |
5 | - [x] Insertion Sort
6 | - [x] Quick Sort
7 | - [x] Selection Sort
8 | - [x] Heap Sort
9 | - [x] Merge Sort
10 | - [x] Bubble Sort
11 | - [x] Shell Sort
12 | - [ ] Bucket Sort
13 | - [ ] Radix Sort
14 |
--------------------------------------------------------------------------------
/Exercises/SortAlgorithm/selection.py:
--------------------------------------------------------------------------------
1 | #-*- coding: utf-8 -*-
2 |
3 | # 选择排序(selection sort)
4 | # 原理:
5 | # 1. 在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,
6 | # 2. 再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。
7 | # 3. 重复第二步,直到所有元素均排序完毕。
8 |
9 |
10 | # 时间复杂度:
11 | # 最差: O(n^2)
12 | # 最优: O(n^2)
13 |
14 |
15 | def selection_sort(alist):
16 | length = len(alist)
17 | for index in range(length):
18 | m = index
19 | for i in range(index, length):
20 | if alist[i] < alist[m]:
21 | m = i
22 | alist[m], alist[index] = alist[index], alist[m]
23 | return alist
24 |
--------------------------------------------------------------------------------
/Exercises/SortAlgorithm/shell.py:
--------------------------------------------------------------------------------
1 | #-*- coding: utf-8 -*-
2 |
3 | # 希尔排序/递减增量排序算法
4 | # 原理:
5 | # 基于插入排序的性质:
6 | # * 插入排序在对几乎已经排好序的数据操作时,效率高,即可以达到线性排序的效率
7 | # * 但插入排序一般来说是低效的,因为插入排序每次只能将数据移动一位。
8 | #
9 | # *希尔排序* 通过将比较的全部元素分为几个区域来提升插入排序的性能。这样可以让一
10 | # 个元素可以一次性地朝最终位置前进一大步(每次以一定步长以一定步长进行排序,直至
11 | # 步长为1)。然后算法再取越来越小的步长进行排序,算法的最后一步就是普通的插入排序
12 | #
13 | # 步长选择:
14 | # 只要最终步长为1都可以正常工作,Donald Shell最初建议步长选择为n/2并且对步长取
15 | # 半直到步长达到1。另外步长还可以使用Sedgewick提出的(1, 5, 19, 41, 109,…)。
16 | # 也可以使用斐波那契数列除去0和1将剩余的数以黄金分区比的两倍的幂进行运算得到的数列。
17 |
18 | # 时间复杂度:
19 | # 最差: O(nlog(2)n)
20 | # 最优: O(n)
21 |
22 |
23 | def shell_sort(alist):
24 | length = len(alist)
25 | gap = length / 2
26 | while gap > 0:
27 | for i in range(gap, length):
28 | temp = alist[i]
29 | j = i
30 | # 插入排序
31 | while j >= gap and alist[j-gap] > temp:
32 | alist[j] = alist[j-gap]
33 | j -= gap
34 | alist[j] = temp
35 | gap = gap / 2
36 | return alist
37 |
--------------------------------------------------------------------------------
/Exercises/Thread/c1.py:
--------------------------------------------------------------------------------
1 | import time
2 |
3 | def countdown(n):
4 | while n > 0:
5 | print('T-minus', n)
6 | n -= 1
7 | time.sleep(1)
8 |
9 | from threading import Thread
10 |
11 | t = Thread(target=countdown, args=(10,))
12 | t.start()
13 | if not t.is_alive():
14 | print('Completed')
15 |
--------------------------------------------------------------------------------
/Exercises/Thread/c2.py:
--------------------------------------------------------------------------------
1 | import time
2 | from threading import Thread
3 |
4 | class CountdownTask:
5 | def __init__(self):
6 | self._running = True
7 |
8 | def terminate(self):
9 | self._running = False
10 |
11 | def run(self, n):
12 | while self._running and n > 0:
13 | print('T-minus', n)
14 | n -= 1
15 | time.sleep(1)
16 |
17 |
18 | c = CountdownTask()
19 | t = Thread(target=c.run, args=(10,))
20 | t.start()
21 |
--------------------------------------------------------------------------------
/Exercises/Thread/c3.py:
--------------------------------------------------------------------------------
1 | from threading import Thread
2 | import time
3 |
4 | class CountdownThread(Thread):
5 | def __init__(self, n):
6 | super().__init__()
7 | self.n = n
8 |
9 | def run(self):
10 | while self.n > 0:
11 | print('T-minus', self.n)
12 | self.n -= 1
13 | time.sleep(1)
14 |
15 | c = CountdownThread(5)
16 | c.start()
17 |
--------------------------------------------------------------------------------
/Exercises/Thread/c4.py:
--------------------------------------------------------------------------------
1 | from threading import Thread, Event
2 | import time
3 |
4 | def countdown(n, started_evt):
5 | print('countdown starting')
6 | started_evt.set()
7 | while n > 0:
8 | print('T-minus', n)
9 | n -= 1
10 | time.sleep(1)
11 |
12 | started_evt = Event()
13 |
14 | print('Launching countdown')
15 | t = Thread(target=countdown, args=(10, started_evt))
16 | t.start()
17 |
18 | started_evt.wait()
19 | print('countdown is running')
20 |
--------------------------------------------------------------------------------
/Exercises/Thread/c5.py:
--------------------------------------------------------------------------------
1 | import time
2 | from threading import Thread, Event
3 |
4 | def func1(n, evt):
5 | count = n
6 | while count > 0:
7 | if count == 5:
8 | evt.set()
9 | print('func1', count)
10 | count -= 1
11 | time.sleep(1)
12 |
13 | def func2(n, evt):
14 | evt.wait()
15 | count = n
16 | while count > 0:
17 | print('func2', count)
18 | count -= 1
19 | time.sleep(1)
20 |
21 | evt = Event()
22 | t1 = Thread(target=func1, args=(10, evt))
23 | t2 = Thread(target=func2, args=(10, evt))
24 | t1.start()
25 | t2.start()
26 |
--------------------------------------------------------------------------------
/Exercises/Thread/c6.py:
--------------------------------------------------------------------------------
1 | import threading
2 | import time
3 |
4 | class PeriodicTimer:
5 | def __init__(self, interval):
6 | self._interval = interval
7 | self._flag = 0
8 | self._cv = threading.Condition()
9 |
10 | def start(self):
11 | t = threading.Thread(target=self.run)
12 | t.daemon = True
13 | t.start()
14 |
15 | def run(self):
16 | while True:
17 | time.sleep(self._interval)
18 | with self._cv:
19 | self._flag ^= 1
20 | self._cv.notify_all()
21 |
22 | def wait_for_tick(self):
23 | with self._cv:
24 | last_flag = self._flag
25 | while last_flag == self._flag:
26 | self._cv.wait()
27 |
--------------------------------------------------------------------------------
/Exercises/Thread/threading_multi1.py:
--------------------------------------------------------------------------------
1 | import threading
2 |
3 | counter = 0
4 |
5 | def worker():
6 | global counter
7 | counter += 1
8 | print("The Count is %d" % counter)
9 | print("----------------")
10 |
11 | print("Starting up")
12 | for i in range(10):
13 | threading.Thread(target=worker).start()
14 | print("Finishing up")
15 |
--------------------------------------------------------------------------------
/Exercises/Thread/threading_multi3.py:
--------------------------------------------------------------------------------
1 | import threading, time, random
2 |
3 | counter_lock = threading.Lock()
4 | printer_lock = threading.Lock()
5 |
6 | counter = 0
7 |
8 | def worker():
9 | global counter
10 | with counter_lock:
11 | counter += 1
12 | with printer_lock:
13 | print('The count is %d' % counter)
14 | print('----------------')
15 |
16 | with printer_lock:
17 | print('Starting up')
18 |
19 | worker_threads = []
20 | for i in range(10):
21 | t = threading.Thread(target=worker)
22 | worker_threads.append(t)
23 | t.start()
24 |
25 | for t in worker_threads:
26 | t.join()
27 |
28 | with printer_lock:
29 | print('Finishing up')
30 |
--------------------------------------------------------------------------------
/Exercises/TwoDimensioBarCode/TwoDimensionalBarCode.py:
--------------------------------------------------------------------------------
1 | import qrcode
2 |
3 | img = qrcode.make('http://www.baidu.com')
4 |
--------------------------------------------------------------------------------
/Exercises/TwoDimensioBarCode/app/__init__.py:
--------------------------------------------------------------------------------
1 | # coding: utf-8
2 |
3 | from flask import Flask
4 |
5 |
6 | app = Flask(__name__)
7 | app.config['SECRET_KEY'] = 'your secret key is here'
8 |
9 |
10 | from . import views, forms
11 |
--------------------------------------------------------------------------------
/Exercises/TwoDimensioBarCode/app/forms.py:
--------------------------------------------------------------------------------
1 | # coding: utf-8
2 | from flask_wtf import Form
3 | # from wtforms import
4 | # from wtforms.validators import
5 |
6 |
--------------------------------------------------------------------------------
/Exercises/TwoDimensioBarCode/app/templates/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
2 Dimensioon Bar Code Test
4 |
5 |
{{ img }}
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Exercises/TwoDimensioBarCode/app/views.py:
--------------------------------------------------------------------------------
1 | # coding: utf-8
2 | from . import app
3 | from flask import render_template
4 | from qrcode import make
5 |
6 |
7 | # test views
8 | @app.route('/test/')
9 | def test():
10 | return "
just tell you everything is ok!
"
11 |
12 | # you can writing your views here
13 | @app.route('/')
14 | def index():
15 | img = make('http://www.baidu.com')
16 | return render_template('index.html', img=img)
17 |
--------------------------------------------------------------------------------
/Exercises/TwoDimensioBarCode/manage.py:
--------------------------------------------------------------------------------
1 | # coding: utf-8
2 |
3 | """
4 | manage.py
5 | ~~~~~~~~
6 |
7 | shell:
8 | python manage.py shell
9 | run server:
10 | python manage.py runserver
11 | -d 开启调试模式
12 | """
13 |
14 | import sys
15 | from app import app
16 | from flask.ext.script import Manager, Shell
17 |
18 | """编码设置"""
19 | reload(sys)
20 | sys.setdefaultencoding('utf-8')
21 |
22 |
23 | manager = Manager(app)
24 |
25 |
26 | def make_shell_context():
27 | """自动加载环境"""
28 | return dict(
29 | app=app
30 | )
31 |
32 |
33 | manager.add_command("shell", Shell(make_context=make_shell_context))
34 |
35 |
36 | if __name__ == '__main__':
37 | manager.run()
38 |
39 |
--------------------------------------------------------------------------------
/Exercises/TwoDimensioBarCode/requirement.txt:
--------------------------------------------------------------------------------
1 |
2 | Flask==0.10.1
3 | Flask-WTF==0.10.0
4 |
5 |
--------------------------------------------------------------------------------
/Exercises/UnitTest/client.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import requests
3 |
4 |
5 | def api_request(url):
6 | r = requests.get(url)
7 | return r.json()
8 |
9 | def get_review_author(url):
10 | rs = api_request(url)
11 | return rs['review']['author']
12 |
--------------------------------------------------------------------------------
/Exercises/UnitTest/test_mock.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | import unittest
4 |
5 | import mock
6 | import client
7 |
8 |
9 | class TestClient(unittest.TestCase):
10 | def setUp(self):
11 | self.result = {'review': {'author': 'dongwm'}}
12 |
13 | def test_response(self):
14 | api_result = mock.Mock(return_value=self.result)
15 | client.api_request = api_result
16 | self.assertEqual(client.get_review_author(
17 | 'http://api.dongwm.com/review/123'), 'dongwm')
18 |
19 | def test_patch_request(self):
20 | api_result = mock.Mock(return_value=self.result)
21 | with mock.patch('client.api_requst', api_result):
22 | self.assertEqual(client.get_review_author(
23 | 'http://api.dongwm.com/review/123'), 'dongwm')
24 |
--------------------------------------------------------------------------------
/Exercises/UnitTest/ut_case.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import unittest
3 |
4 | from collections import Counter
5 |
6 | class TestCounter(unittest.TestCase):
7 | def setUp(self):
8 | self.c = Counter('abcdaba')
9 | print 'setUp starting ...'
10 |
11 | # test function should start with test_
12 | def test_basics(self):
13 | c = self.c
14 | self.assertEqual(c, Counter(a=3, b=2, c=1, d=1))
15 | self.assertIsInstance(c, dict)
16 | self.assertEqual(len(c), 4)
17 | self.assertIn('a', c)
18 | self.assertNotIn('f', c)
19 | self.assertRaises(TypeError, hash, c)
20 |
21 | def test_update(self):
22 | c = self.c
23 | c.update(f=1)
24 | self.assertEqual(c, Counter(a=3, b=2, c=1, d=1, f=1))
25 | c.update(a=10)
26 | self.assertEqual(c, Counter(a=13, b=2, c=1, d=1, f=1))
27 |
28 | def tearDown(self):
29 | print 'tearDown starting...'
30 |
31 | if __name__ == '__main__':
32 | unittest.main()
33 |
--------------------------------------------------------------------------------
/Exercises/UnitTest/ut_suite.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | import unittest
4 |
5 | from collections import Counter
6 |
7 | class TestCounter(unittest.TestCase):
8 | def setUp(self):
9 | self.c = Counter('abcdaba')
10 | print('setUp starting ...')
11 |
12 | def runTest(self):
13 | c = self.c
14 | self.assertEqual(c, Counter(a=3, b=2, c=1, d=1))
15 |
16 | def tearDown(self):
17 | print('tearDown starting ...')
18 |
19 | if __name__ == '__main__':
20 | suite = unittest.TestSuite()
21 | suite.addTest(TestCounter())
22 | runner = unittest.TextTestRunner()
23 | runner.run(suite)
24 |
--------------------------------------------------------------------------------
/Exercises/UnitTest/ut_suite_with_case.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | import unittest
4 | from ut_case import TestCounter
5 |
6 |
7 | if __name__ == '__main__':
8 | suite = unittest.TestSuite()
9 | suite.addTest(TestCounter('test_basics'))
10 | suite.addTest(TestCounter('test_update'))
11 | runner = unittest.TextTestRunner()
12 | runner.run(suite)
13 |
--------------------------------------------------------------------------------
/Exercises/WSGI/hello.py:
--------------------------------------------------------------------------------
1 | def application(environ, start_response):
2 | start_response('200 OK', [('Content-Type', 'text/html')])
3 | return '
Hello %s!
' % (environ['PATH_INFO'][1:] or 'World')
4 |
--------------------------------------------------------------------------------
/Exercises/WSGI/server.py:
--------------------------------------------------------------------------------
1 | from wsgiref.simple_server import make_server
2 | from hello import application
3 |
4 | httpd = make_server('', 8000, application)
5 | print "Serving HTTP on port 8000..."
6 |
7 | httpd.serve_forever()
8 |
--------------------------------------------------------------------------------
/Exercises/aiohttp/client.py:
--------------------------------------------------------------------------------
1 | import aiohttp
2 | import asyncio
3 | import async_timeout
4 |
5 | async def fetch(session, url):
6 | with async_timeout.timeout(10):
7 | async with session.get(url) as response:
8 | return await response.text()
9 |
10 | async def main(loop):
11 | async with aiohttp.ClientSession(loop=loop) as session:
12 | html = await fetch(session, 'https://www.python.org')
13 | print(html)
14 |
15 | loop = asyncio.get_event_loop()
16 | loop.run_until_complete(main(loop))
17 |
--------------------------------------------------------------------------------
/Exercises/aiohttp/server.py:
--------------------------------------------------------------------------------
1 | from aiohttp import web
2 |
3 | async def handle(request):
4 | name = request.match_info.get('name', "Anomymous")
5 | text = "Hello, " + name
6 | return web.Response(text=text)
7 |
8 | app = web.Application()
9 | app.router.add_get('/', handle)
10 | app.router.add_get('/{name}', handle)
11 |
12 | web.run_app(app)
13 |
--------------------------------------------------------------------------------
/Exercises/changePermission.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | with open('ex.txt') as f:
4 | stat = os.stat(f.fileno())
5 | os.chmod(f.fileno(), 0o640)
6 |
--------------------------------------------------------------------------------
/Exercises/fork.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | f = open("ex.txt", mode="rb", buffering=0)
4 | pid = os.fork()
5 | print("getpid {:>5}, fork {:>5}, fd {}: {}".format(os.getpid(), pid, f.fileno(), f.read(6)))
6 | f.close()
7 |
--------------------------------------------------------------------------------
/Exercises/forkp.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | def child():
4 | print "We are in the child process with PID= %d"%os.getpid()
5 |
6 | def parent():
7 | print "We are in the parent process with PID= %d"%os.getpid()
8 | newRef=os.fork()
9 | if newRef==0:
10 | child()
11 | else:
12 | print "We are in the parent process and our child process has PID= %d"%newRef
13 |
14 | parent()
15 |
--------------------------------------------------------------------------------
/Exercises/iOSDemoWithPython/app/README:
--------------------------------------------------------------------------------
1 | Your application code should be placed in this directory.
2 |
3 | The native code will be looking for a apptest/__main__.py file as the entry point.
--------------------------------------------------------------------------------
/Exercises/iOSDemoWithPython/app_packages/README:
--------------------------------------------------------------------------------
1 | This directory exists so that 3rd party packages can be installed here.
2 |
--------------------------------------------------------------------------------
/Exercises/iOSDemoWithPython/app_packages/rubicon/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function
2 | try:
3 | # If we're on iOS, we won't have pkg-resources; but then,
4 | # we won't need to register the namespace package, either.
5 | # Ignore the error if it occurs.
6 | __import__("pkg_resources").declare_namespace(__name__)
7 | except ImportError:
8 | print('Rubicon namespace package not registered!')
9 |
--------------------------------------------------------------------------------
/Exercises/iOSDemoWithPython/app_packages/rubicon/objc/__init__.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function, absolute_import, division, unicode_literals
2 |
3 | __version__ = '0.1.3'
4 |
5 | from .objc import (
6 | objc, send_message, send_super,
7 | get_selector,
8 | ObjCClass, ObjCInstance, NSObject,
9 | objc_ivar, objc_rawmethod, objc_method, objc_classmethod
10 | )
11 |
12 | from .core_foundation import at, to_str, to_number, to_value, to_set, to_list
13 |
14 | from .types import (
15 | text,
16 | NSInteger, NSUInteger,
17 | CGFloat,
18 | NSPointEncoding, NSSizeEncoding, NSRectEncoding, NSRangeEncoding,
19 | CGPoint, NSPoint,
20 | CGSize, NSSize,
21 | CGRect, NSRect,
22 | CGSizeMake, NSMakeSize,
23 | CGRectMake, NSMakeRect,
24 | CGPointMake, NSMakePoint,
25 | NSTimeInterval,
26 | CFIndex, UniChar, unichar, CGGlyph,
27 | CFRange, NSRange,
28 | NSZeroPoint
29 | )
30 |
--------------------------------------------------------------------------------
/Exercises/iOSDemoWithPython/apptest.xcodeproj/project.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Exercises/iOSDemoWithPython/apptest.xcodeproj/project.xcworkspace/xcuserdata/fujun.xcuserdatad/UserInterfaceState.xcuserstate:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest.xcodeproj/project.xcworkspace/xcuserdata/fujun.xcuserdatad/UserInterfaceState.xcuserstate
--------------------------------------------------------------------------------
/Exercises/iOSDemoWithPython/apptest.xcodeproj/xcuserdata/fujun.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
--------------------------------------------------------------------------------
/Exercises/iOSDemoWithPython/apptest.xcodeproj/xcuserdata/fujun.xcuserdatad/xcschemes/xcschememanagement.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | SchemeUserState
6 |
7 | apptest.xcscheme
8 |
9 | orderHint
10 | 0
11 |
12 |
13 | SuppressBuildableAutocreation
14 |
15 | 60796EE119190F4100A9926B
16 |
17 | primary
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-120.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-120.png
--------------------------------------------------------------------------------
/Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-152.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-152.png
--------------------------------------------------------------------------------
/Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-167.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-167.png
--------------------------------------------------------------------------------
/Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-180.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-180.png
--------------------------------------------------------------------------------
/Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-29.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-29.png
--------------------------------------------------------------------------------
/Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-40.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-40.png
--------------------------------------------------------------------------------
/Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-58.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-58.png
--------------------------------------------------------------------------------
/Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-76.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-76.png
--------------------------------------------------------------------------------
/Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-80.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-80.png
--------------------------------------------------------------------------------
/Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-87.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-87.png
--------------------------------------------------------------------------------
/Exercises/iOSDemoWithPython/apptest/Images.xcassets/LaunchImage.launchimage/launch-1024x768.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/LaunchImage.launchimage/launch-1024x768.png
--------------------------------------------------------------------------------
/Exercises/iOSDemoWithPython/apptest/Images.xcassets/LaunchImage.launchimage/launch-1536x2048.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/LaunchImage.launchimage/launch-1536x2048.png
--------------------------------------------------------------------------------
/Exercises/iOSDemoWithPython/apptest/Images.xcassets/LaunchImage.launchimage/launch-2048x1536.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/LaunchImage.launchimage/launch-2048x1536.png
--------------------------------------------------------------------------------
/Exercises/iOSDemoWithPython/apptest/Images.xcassets/LaunchImage.launchimage/launch-640x1136.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/LaunchImage.launchimage/launch-640x1136.png
--------------------------------------------------------------------------------
/Exercises/iOSDemoWithPython/apptest/Images.xcassets/LaunchImage.launchimage/launch-640x960.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/LaunchImage.launchimage/launch-640x960.png
--------------------------------------------------------------------------------
/Exercises/iOSDemoWithPython/apptest/Images.xcassets/LaunchImage.launchimage/launch-768x1024.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/LaunchImage.launchimage/launch-768x1024.png
--------------------------------------------------------------------------------
/Exercises/iOSDemoWithPython/apptest/apptest-Prefix.pch:
--------------------------------------------------------------------------------
1 | //
2 | // Prefix header
3 | //
4 | // The contents of this file are implicitly included at the beginning of every source file.
5 | //
6 |
7 | #import
8 |
9 | #ifndef __IPHONE_3_0
10 | #warning "This project uses features only available in iOS SDK 3.0 and later."
11 | #endif
12 |
13 | #ifdef __OBJC__
14 | #import
15 | #import
16 | #endif
17 |
--------------------------------------------------------------------------------
/Exercises/iOSDemoWithPython/apptest/en.lproj/InfoPlist.strings:
--------------------------------------------------------------------------------
1 | /* Localized versions of Info.plist keys */
2 |
3 |
--------------------------------------------------------------------------------
/Exercises/iOSDemoWithPython/untitled.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 |
4 | from ctypes import cdll
5 | from ctypes import util
6 | from rubicon.objc import ObjCClass, objc_method
7 | # 载入Foundation框架
8 | cdll.LoadLibrary(util.find_library('Foundation'))
9 | # 获取NSArray类
10 | NSArray = ObjCClass("NSArray")
11 | # 等同于
12 | # NSArray *myArray = [NSArray arrayWithObjects:@"ok", @"ok1", @"ok2", nil]
13 | myArray = NSArray.arrayWithObjects_("ok", "ok1", "ok2", None)
14 |
15 | print myArray.count
16 | print myArray.indexOfObject_("ok2")
17 |
18 |
--------------------------------------------------------------------------------
/Exercises/iterator_and_generator/countdown.py:
--------------------------------------------------------------------------------
1 | class countdown(object):
2 | """class iterator countdown"""
3 | def __init__(self, count):
4 | self.count = count
5 |
6 | def __iter__(self):
7 | return self
8 |
9 | def next(self):
10 | if self.count <= 0:
11 | raise StopIteration
12 | t = self.count
13 | self.count -= 1
14 | return t
15 |
16 |
17 | def countdown2(n):
18 | while n > 0:
19 | yield n
20 | n -= 1
21 |
22 |
23 | def countdown3(n):
24 | print "Executing countdown ..."
25 | while n > 0:
26 | yield n
27 | n -= 1
28 |
--------------------------------------------------------------------------------
/Exercises/iterator_and_generator/generator_read_file.py:
--------------------------------------------------------------------------------
1 | # Note: At no point in our generator solution did we ever create large
2 | # temporary lists
3 | # it was based on the concept of pipelining data between different components
4 | wwwlog = open("big-access-log")
5 | bytecolumn = (line.rsplit(None,1)[1] for line in wwwlog)
6 | bytes = (int(x) for x in bytecolumn if x != '-')
7 | print "Total", sum(bytes)
8 |
--------------------------------------------------------------------------------
/Exercises/iterator_and_generator/iteration.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | def get_a_index(string):
4 | for index, word in enumerate(string):
5 | if word == 'a':
6 | yield index
7 |
8 | string = "this is a string"
9 | indexs = get_a_index(string)
10 |
11 | for i in indexs:
12 | print i
13 |
14 | # indexs has iterated for one turn, next(indexs) this would trigger a
15 | # StopIteration Error
16 | # define a iterable object could solve this problem
17 |
18 | class LoopIter(object):
19 | def __init__(self, data):
20 | self.data = data
21 |
22 | def __iter__(self):
23 | for index, word in enumerate(self.data):
24 | if word == 'a':
25 | yield index
26 |
27 | indexs = LoopIter(string)
28 |
29 | for i in indexs:
30 | print i
31 | for i in indexs:
32 | print i
33 |
--------------------------------------------------------------------------------
/Exercises/iterator_and_generator/recv_count.py:
--------------------------------------------------------------------------------
1 | # recv_count.py
2 | # Think of this function as receiving values rather than generating them
3 |
4 | def recv_count():
5 | try:
6 | while True:
7 | n = (yield)
8 | print "T-minus", n
9 | except GeneratorExit:
10 | print "Kaboom!"
11 |
12 | r = recv_count()
13 | r.next() # r.send(None)
14 |
--------------------------------------------------------------------------------
/Exercises/sieveEratosthenes.py:
--------------------------------------------------------------------------------
1 | #-*- coding: utf-8 -*-
2 |
3 |
4 | def sieve(n):
5 | before_sieve = [1] * (n+1)
6 | before_sieve[0] = 0
7 | before_sieve[1] = 0
8 | for i in range(2, (n+1)/2):
9 | j = 2
10 | while(j*i < n+1):
11 | before_sieve[j*i] = 0
12 | j += 1
13 | return before_sieve
14 |
15 | def main(n):
16 | after_sieve = sieve(n)
17 | for i in range(n+1):
18 | if after_sieve[i] == 1:
19 | print '%d ' % i,
20 |
21 | main(100)
22 |
--------------------------------------------------------------------------------
/Exercises/stack.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | class Stack():
4 | """模拟栈"""
5 | def __init__(self):
6 | self.items = []
7 |
8 | def isEmpty(self):
9 | return len(self.items)==0
10 |
11 | def push(self, item):
12 | self.items.append(item)
13 |
14 | def pop(self):
15 | return self.items.pop()
16 |
17 | def peek(self):
18 | if not self.isEmpty():
19 | return self.items[len(self.items)-1]
20 |
21 | def size(self):
22 | return len(self.items)
23 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ### The Zen of Python
2 |
3 | Beautiful is better than ugly.
4 |
5 | Explicit is better than implicit.
6 |
7 | Simple is better than complex.
8 |
9 | Complex is better than complicated.
10 |
11 | Flat is better than nested.
12 |
13 | Sparse is better than dense.
14 |
15 | Readability counts.
16 |
17 | Special cases aren't special enough to break the rules.
18 |
19 | Although practicality beats purity.
20 |
21 | Errors should never pass silently.
22 |
23 | Unless explicitly silenced.
24 |
25 | In the face of ambiguity, refuse the temptation to guess.
26 |
27 | There should be one-- and preferably only one --obvious way to do it.
28 |
29 | Although that way may not be obvious at first unless you're Dutch.
30 |
31 | Now is better than never.
32 |
33 | Although never is often better than *right* now.
34 |
35 | If the implementation is hard to explain, it's a bad idea.
36 |
37 | If the implementation is easy to explain, it may be a good idea.
38 |
39 | Namespaces are one honking great idea -- let's do more of those!
40 |
--------------------------------------------------------------------------------