LeetCode Contains Duplicate

位操作 O(n)

class Solution:
    # @param {integer[]} nums
    # @return {boolean}
    def containsDuplicate(self, nums):
        pos, neg = 0, 0
        for x in nums:
            if x < 0:
                temp = 1 << -x
                if neg & temp != 0:
                    return True
                pos |= temp
            else:
                temp = 1 << x
                if pos & temp != 0:
                    return True
                pos |= temp
        return False

哈希表 O(n)

Python一行

在html中加入Google Drive上的视频流

当然,在网页中加入媒体可以使用静态文件

 

<video controls>
        <source src="{% static "video/video_name.m4v" %}">
</video>

 

要加入Google Drive上的视频流就要先把视频上传到Google Drive,然后把访问权限调整为public(任何人均能访问),必要时需将所在文件夹也设为public。

之后就是要获得视频流的url了。Google Drive直接分享的链接并不是直接的视频文件,但是却包含了视频文件的ID:

https://drive.google.com/open?id=blabla

我们需要记录下这个ID,然后在html文件中写:

 

<video controls>
        <source src="https://www.googledrive.com/host/the_ID_you_copied"/>
        Your browser does not support the video tag.
</video>

注意,url的https不能省略,否则就无法加载出视频。

IntelliJ运行android AVD时需要安装HAXM @Mac

1. 更新HAXM installer

打开Tools -> Android -> Android SDK Manager,最下面extras文件夹里,勾选上更新

2. 找安装文件

/Users/user_name/Library/Android/sdk/extras/intel/Hardware_Accelerated_Execution_Manager/IntelHAXM_1.1.1_for_10_9_and_above.dmg

关于Django部署到Apache2之后admin的css不见的问题

在本地的时候,admin的css是在django的目录下的。当部署到服务器之后,这些静态文件路径需要修正。

方法是在服务器上 /etc/apache2/sites-enables/PersonalWebsite.conf里面写好 路径的Alias 并且 给目录赋予权限:

注意这里alias有先后,不然alias会重叠,就无效了。

WSGIScriptAlias / /home/ubuntu/PersonalWebsite/PersonalWebsite/wsgi.py
WSGIPythonPath /home/ubuntu/PersonalWebsite
<Directory /home/ubuntu/PersonalWebsite/PersonalWebsite>
    <Files wsgi.py>
        Order deny,allow
        Require all granted
    </Files>
</Directory>

Alias /media/ /home/ubuntu/PersonalWebsite/media/ 

Alias /static/admin/ /usr/local/lib/python2.7/dist-packages/django/contrib/admin/static/admin/

Alias /static/ /home/ubuntu/PersonalWebsite/static/

 

<Directory /usr/local/lib/python2.7/dist-packages/django/contrib/admin/static/admin>

    Require all granted

</Directory>

<Directory /home/ubuntu/PersonalWebsite/static> Require all granted </Directory> <Directory /home/ubuntu/PersonalWebsite/media> Require all granted </Directory>

Recursion

ComposingPrograms 1.7 Exercises

 

def countdown(n):
    print(n)
    if n>1:
        countdown(n-1)

def countup(n):
    if n>0:
        countup(n-1)
        print(n)

def recursive(m,n):
    if n>0:
        return m + recursive(m, n-1)
    else:
        return 0

def expt(base, power):
    if power==0:
        return 1
    else:
        return base * expt(base, power-1)

def sum_digits(n):
    if n<10:
        return n
    else:
        return n%10 + sum_digits(n//10)

def is_prime(n, d):
    if n<=1:
        return False
    elif d==1:
        return True
    elif n%d==0:
        return False
    else:
        return is_prime(n, d-1)

def sum_primes_up_to(n):
    if n==2:
        return 2
    elif is_prime(n, n-1):
        return sum_primes_up_to(n-1) + n
    else:
        return sum_primes_up_to(n-1)

递归和信用卡的Luhn算法

这里用python做一个mutual recursion

 

def split(n):
    return n//10, n%10

def luhn_sum(n):
    if n<10:
        return n
    else:
        rest, last = split(n)
        return luhn_double_sum(rest) + last

def luhn_double_sum(n):
    rest, last = split(n)
    luhn_digit = split(2*last)[0] + split(2*last)[1]
    if n<10:
        return luhn_digit
    else:
        rest, last = split(n)
        return luhn_sum(rest) + luhn_digit

 

Newton's Method

寻找函数零点:Quickly finds accurate approximations to zeros of differenciable functions.

只要问题是可微的,则问题是可解的。

Wikipedia上操作演示

https://en.wikipedia.org/wiki/Newton's_method#/media/File:NewtonIteration_Ani.gif

 

实现指南:

高阶函数为的是抽象出功能,不要被参数混乱思路

python中整数相除会返回整数,所以注意传入浮点数做参数

 

def square_root(a):
    def f(x):
        return x * x - a

    def df(x):
        return 2 * x

    return find_zero(f, df)

def find_zero(f, df):
    def near_zero(x):
        return appro_equal(f(x), 0)
    return improve(update(f, df), near_zero, guess=1.0, max_update=100)

def update(f, df):
    def u(x):
        return x - f(x)/df(x)
    return u

def improve(update, close, guess, max_update):
    k = 0
    while not close(guess) and k < max_update:
        print guess, k
        guess = update(guess)
        k += 1
    return guess  # the guess improved

def appro_equal(x, y, tolerance=1e-15):
    print abs(x-y) < tolerance
    return abs(x-y) < tolerance

 

推广至求n次根

>>> def power(x, n):
        """Return x * x * x * ... * x for x repeated n times."""
        product, k = 1, 0
        while k < n:
            product, k = product * x, k + 1
        return product
>>> def nth_root_of_a(n, a):
        def f(x):
            return power(x, n) - a
        def df(x):
            return n * power(x, n-1)
        return find_zero(f, df)

 

实际应用 Function Decorator

 

def trace(fn):
    def t(x):
        print "Calling", fn, "on argument", x
        return fn(x)
    return t

@trace
def square(x):
    return x * x

Higher-Order Functions in Python

学习资料:

http://composingprograms.com/pages/16-higher-order-functions.html

定义:

Higher-Order functions can accept other functions as arguments or return functions as values.

例一:计算黄金比例

 

def improve(update, close, guess=1):
    while not close(guess):
        guess = update(guess)
    return guess

def golden_update(guess):
    return 1/guess + 1

def square_close_to_successor(guess):
    return approx_eq(guess * guess,
                     guess + 1)

def approx_eq(x, y, tolerance=1e-3):
    return abs(x - y) < tolerance

phi = improve(golden_update,
              square_close_to_successor)

 

Two key advantages of lexical scoping in Python.

  • 函数命名只与定义环境有关,与执行环境无关
    The names of a local function do not interfere with names external to the function in which it is defined, because the local function name will be bound in the current local environment in which it was defined, rather than the global environment.

     
  • 执行函数由内向外延展
    A local function can access the environment of the enclosing function, because the body of the local function is evaluated in an environment that extends the evaluation environment in which it was defined. 

例二:

def average(x, y):
    return (x + y)/2

def improve(update, close, guess=1):
    while not close(guess):
        guess = update(guess)
    return guess

def approx_eq(x, y, tolerance=1e-3):
    return abs(x - y) < tolerance

def sqrt(a):
    def sqrt_update(x):
        return average(x, a/x)
    def sqrt_close(x):
        return approx_eq(x * x, a)
    return improve(sqrt_update, sqrt_close)

result = sqrt(256)

 

函数计算时层层隔离,名字重复无影响。但是对于大工程来说,明明冲突可能给自己带来麻烦,比如需要重命名的时候。

 

def square(x):
    return x * x

def successor(x):
    return x + 1

def compose1(f, g):
    def h(x):
        return f(g(x))
    return h

def f(x):
    """Never called."""
    return -x

square_successor = compose1(square, successor)
result = square_successor(12)

 

Deploy to Heroku时的问题

Deploy to Heroku

 
https://devcenter.heroku.com/articles/getting-started-with-django#prerequisites
 
 pip install django-toolbelt
Error: pg_config executable not found.
Solution:sudo apt-get install libpq-dev python-dev
 

EC2上部署Django个人网站并连上Godaddy域名

项目命名为PersonalWebsite,后面各处取名时会用到。此项目数据库用的是Django自带的sqlite。

第一步:在AWS上创建新的EC2,选择Ubuntu Free Tier

这就是网站服务器了,可以通过ssh连接之。为了方便,写一个命令:$ ssh PersonalWebsite

# edit ~/.ssh/config

Host PersonalWebsite
HostName <ec2_hostname>
User ubuntu
IdentityFile "~/.ssh/<your_key_pair>.pem"

安装必要程序。可以通过执行写好的脚本文件

 

# filename: install.sh

sudo apt-get update && upgrade;
sudo apt-get install apache2 libapache2-mod-wsgi;
sudo apt-get install python-pip;
sudo pip install django;
sudo apt-get install mysql-server python-mysqldb;
sudo apt-get install git;

 

第二步 植入网站

先从github上拉下来: $ git clone <url>

我的Django网站文件结构如下

 

~/
    PersonalWebsite/
        App/
            __init__.py
            admin.py
            models.py
            tests.py
            urls.py
            views.py
        PersonalWebsite/
            __init__.py
            settings.py
            urls.py
            views.py
            wsgi.py
        static/
            css/
            images/
        template/
            app/
            other_html.html
        db.sqlite3
        manage.py

配置Apache服务器,在/etc/apache2/sites-enabled/PersonalWebsite.conf里声明wsgi.py和静态文件的路径。

 

WSGIScriptAlias / /home/ubuntu/PersonalWebsite/PersonalWebsite/wsgi.py
WSGIPythonPath /home/ubuntu/PersonalWebsite
<Directory /home/ubuntu/PersonalWebsite/PersonalWebsite>
    <Files wsgi.py>
        Order deny,allow
        Require all granted
    </Files>
</Directory>

Alias /media/ /home/ubuntu/PersonalWebsite/media/ 
Alias /static/ /home/ubuntu/PersonalWebsite/static/

<Directory /home/ubuntu/PersonalWebsite/static>
    Require all granted
</Directory>

<Directory /home/ubuntu/PersonalWebsite/media>
    Require all granted
</Directory> 

 

第三步 绑定域名

  1. 首先,在AWS里将EC2绑定一个Elastic IP(The Elastic IP address assigned to the instance, if applicable. Elastic IP addresses are static IP addresses assigned to your account that you can quickly remap to other instances.
    操作路径:AWS Dashboard => (左侧导航栏)Security & Network下的Elastic IP
     
  2. 在Godday.com购买了example.com域名
    在Domain => Domain Details => DNS ZONE FILE 中修改A(Host)的Record:
    使 @ (即此域名)对应上一步中的Elastic IP

 

小贴士

网站的更新流程可以是:在本地开发 --> 上传至Github --> 登入EC2 --> $ git pull --> 重启Apache