Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions illuz/0000/0000_add_number_to_image.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# Author: illuz <iilluzen[at]gmail.com>
# File: add_number_to_image.py
# Create Date: 2015-02-08 23:52:01
# Descripton: Add a number to right top corner of images.
# Will backup the image in ./[file]_bak.[ext]
# Usage: add_number_to_image.py [image] [number]

'''
第 0000 题:
将你的 QQ 头像(或者微博头像)右上角加上红色的数字,
类似于微信未读信息数量那种提示效果.
'''

from PIL import Image, ImageDraw, ImageFont
import sys, shutil


# backup file
# @return nothing
def back_file(filename):
p = filename.rfind('.')
shutil.copyfile(filename, filename[:p] + '_bak' + filename[p:])


# add number to right top corner
# @return nothing
def add_number_to_image(im, num):
xsize, ysize = im.size
left, top = int(xsize / 20.0 * 13), int(xsize / 20.0)
right, bottom = int(xsize / 20.0 * 19), int(xsize / 20.0 * 7)
draw = ImageDraw.Draw(im)
draw.ellipse([left, top, right, bottom], (255, 0, 0))
font=ImageFont.truetype("DroidSansMono.ttf", int(xsize / 20 * 4))
draw.text((left + xsize / 10.0, top + xsize / 30), str(num), (0, 0, 0), font=font)
del draw


# open image and deal font and get Draw
# @return a ImageDraw
def deal(f, num):
if (num == None):
num = 0
if (num > '9'):
num = '9+'
im = Image.open(f)
add_number_to_image(im, num)
im.save(f)


def main():
if len(sys.argv) <= 1:
print "Need at least 1 parameter."
return
for i in range(1, len(sys.argv), 2):
f = sys.argv[i]
n = sys.argv[i + 1] if i + 1 < len(sys.argv) else None
try:
back_file(f)
deal(f, n)
print "Success add number to image file", f
except IOError:
print "Cannot open image", f, '!'
pass


if __name__ == '__main__':
main()

27 changes: 27 additions & 0 deletions illuz/0001/key_generator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: illuz <iilluzen[at]gmail.com>
# File: key_generator.py
# Create Date: 2015-02-09 10:43:36
# Descripton: Use uuid module to generate 200 register keys.
# Usage: key_generator.py

"""
第 0001 题:
做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)?
"""

from uuid import uuid4

def generate_key(num):
key_list = [str(uuid4()) for i in range(num)]
return key_list


def main():
print generate_key(200)


if __name__ == '__main__':
main()

46 changes: 46 additions & 0 deletions illuz/0002/create_a_table_and_put_keys.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: illuz <iilluzen[at]gmail.com>
# File: create_a_table_and_put_keys.py
# Create Date: 2015-02-09 12:12:43
# Usage: create_a_table_and_put_keys.py
# Descripton: create a table in mysql and put keys into it

"""
第 0002 题:
将 0001 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库中。
"""

from uuid import uuid4
import MySQLdb as mdb


def generate_key(num):
key_list = [str(uuid4()) for i in range(num)]
return key_list


def create_a_table_and_put_keys(key_list):
with mdb.connect('localhost', 'test', '123', 'testdb') as cur:

# create table
cur.execute("DROP TABLE IF EXISTS rkeys")
cur.execute("CREATE TABLE rkeys(\
key_value CHAR(40) NOT NULL\
)")

# insert data
# I want to use executemany, but there is a library bug...
# It seems that executemany cannot match single-string list
# cur.executemany("INSERT INTO rkeys VALUES(%s)", key_list)
for i in key_list:
cur.execute("INSERT INTO rkeys(key_value)\
VALUES('%s')" % i)


def main():
create_a_table_and_put_keys(generate_key(200))


if __name__ == '__main__':
main()
144 changes: 144 additions & 0 deletions illuz/Python Databases Note - MySQL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
# Python Databases Note - MySQL


### install and setting
```
sudo apt-get install mysql-server
sudo apt-get install python-mysqldb
mysql -u root -p
# create a user and table in mysql
> CREATE DATABASE testdb;
> CREATE USER 'testuser'@'localhost' IDENTIFIED BY '123';
> USE testdb;
> GRANT ALL ON testdb.* TO 'testuser'@'localhost';
```


### _mysql module

The _mysql module implements the MySQL C API directly.
Not compatible.

Fetch version

```
#!/usr/bin/python
# -*- coding: utf-8 -*-
import _mysql
import sys
try:
con = _mysql.connect('localhost', 'test', '123', 'testdb')
con.query("SELECT VERSION()")
result = con.use_result()
print "MySQL version: %s" % \
result.fetch_row()[0]
except _mysql.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit(1)
finally:
if con:
con.close()
```


### MySQLdb module

MySQLdb is a thin Python wrapper around _mysql.


1. con = mdb.connect(...)
2. cur = con.cursor() // **get cursor**
3. cur.execute("SELECT * FROM xxx")
4. cur.executemany("INSERT INTO xxx VALUES(%s, %s)", value_list)
4. except mdb.Error, e // **remember this**
5. cur.rowcount
6. cur.fetchone() // **return one**
7. cur.fetchall() // **return a list**
8. cur = con.cursor(mdb.cursors.DictCursor) // **dictionary cursor, we can refer to the data by their column names**
9. desc = cur.description // **table column names**


Fetch version.

```
#!/usr/bin/python
# -*- coding: utf-8 -*-
import MySQLdb as mdb
import sys
try:
con = mdb.connect('localhost', 'test', '123', 'testdb');
cur = con.cursor()
cur.execute("SELECT VERSION()")
ver = cur.fetchone()
print "Database version : %s " % ver
except mdb.Error, e:
print "Error %d: %s" % (e.args[0],e.args[1])
sys.exit(1)
finally:
if con:
con.close()
```

Create a table and populate it with some data

```
#!/usr/bin/python
# -*- coding: utf-8 -*-
import MySQLdb as mdb
con = mdb.connect('localhost', 'test', '123', 'testdb');
with con: # automatically release con
cur = con.cursor()
# Above can be `with mdb.connect(...) as cur`
cur.execute("DROP TABLE IF EXISTS Writers")
cur.execute("CREATE TABLE Writers(Id INT PRIMARY KEY AUTO_INCREMENT, \
Name VARCHAR(25))")
cur.execute("INSERT INTO Writers(Name) VALUES('Jack London')")
```

Retrieving data

```
#!/usr/bin/python
# -*- coding: utf-8 -*-
import MySQLdb as mdb
con = mdb.connect('localhost', 'test', '123', 'testdb');
with con:
cur = con.cursor() # con.cursor(mdb.cursors.DictCursor)
cur.execute("SELECT * FROM Writers")
rows = cur.fetchall() # if is DictCursor rows is a dict
for row in rows:
print row
# or fetch one by one
# for i in range(cur.rowcount):
# row = cur.fetchone()
# print row
```


### Some resources:
[MySQLdb User's Guide](http://mysql-python.sourceforge.net/MySQLdb.html)
[python-mysqldb API](http://mysql-python.sourceforge.net/MySQLdb-1.2.2/)
[StackOverflow-How do I connect to a MySQL Database in Python?](http://stackoverflow.com/questions/372885/how-do-i-connect-to-a-mysql-database-in-python)
[Good start:Zencode](http://zetcode.com/db/mysqlpython/) (I use this :smile:)

11 changes: 11 additions & 0 deletions illuz/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# My solution for Show-Me-the-Code/python

### The Problems description:

[Chinese Version](https://github.com/illuz/show-me-the-code/blob/master/README.md)


### There are some notes:

- [Python Databases Note - MySQL](./Python Databases Note - MySQL.md)