Leetao's Blog

Talk is cheap, show me the code

0%

之前项目中用上了easyui中的datebox,但是由于datebox 默认的时间格式 m/d/y,并不符合我的要求,于是参考手册将其时间格式修改为y-m-d.格式化的代码如下:

1
2
3
4
5
6
$.fn.datebox.defaults.formatter = function(date){
var y = date.getFullYear();
var m = date.getMonth()+1;
var d = date.getDate();
return y+'-'+m+'-'+d;
}

格式是对了,但是出现了下面的问题:

没错就是出现了,怎么选都显示当前时间的问题.
最后终于找到的解决方案,在重写格式的同时,还需要将parser重写一遍

1
2
3
4
5
6
7
8
$.fn.datebox.defaults.parser = function(s){
var t = Date.parse(s);
if (!isNaN(t)){
return new Date(t);
} else {
return new Date();
}
}

问题解决~~O(∩_∩)O

环境的安装

windows 下 mysql-python 的安装

从官网下载对应版本的软件:
64位:MySQL-python-1.2.3.win-amd64-py2.7.exe
32位:MySQL-python-1.2.5.win32-py2.7.exe
下载完成之后点击安装一路next就完成了,安装完成之后在命令行下进行简单的测试

如果没有保存的话就说明 mysql-python 成功安装到本地了

mysql-python的简单使用

创建一张测试表

1
2
3
4
5
6
7
8
9
CREATE TABLE `t_user` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NULL DEFAULT NULL,
`age` VARCHAR(255) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=9;

在mysql下执行上述语句创建一张 user 表

插入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#-*- coding:utf-8 -*-
"""
author:leetao
"""
import MySQLdb

conn=MySQLdb.connect(host="localhost",user="root",passwd="",db="test",charset="utf8")
cursor = conn.cursor()

sql = "insert into t_user(name,age) values(%s,%s)"
param = ("leetao",'22')
cursor.execute(sql,param)

cursor.close()
conn.commit()
conn.close()

执行完插入语句之后,让我们检测一下是否将数据插入到数据库中

成功插入数据库,great!

修改

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#-*- coding:utf-8 -*-
"""
author:leetao
"""
import MySQLdb

conn=MySQLdb.connect(host="localhost",user="root",passwd="",db="test",charset="utf8")
cursor = conn.cursor()

sql = "update t_user set name=%s where id = 1"
param = ("lt")
cursor.execute(sql,param)

cursor.close()
conn.commit()
conn.close()

同样的执行完脚本,然后查看修改是否发生效果

修改成功,cool~~

查询

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#-*- coding:utf-8 -*-
"""
author:leetao
"""
import MySQLdb

conn=MySQLdb.connect(host="localhost",user="root",passwd="",db="test",charset="utf8")
cursor = conn.cursor()

sql = "select * from t_user where id = 1"
cursor.execute(sql)
for rows in cursor.fetchall():
for row in rows:
print row

cursor.close()
conn.commit()
conn.close()

执行脚本,控制台成功输出如下结果:

删除

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#-*- coding:utf-8 -*-
"""
author:leetao
"""
import MySQLdb

conn=MySQLdb.connect(host="localhost",user="root",passwd="",db="test",charset="utf8")
cursor = conn.cursor()
sql = "delete from t_user where id = 1"
cursor.execute(sql)

cursor.close()
conn.commit()
conn.close()

执行完删除后,数据库 t_user 表应该不存在任何数据了,通过 sql 语句验证一下结果

如上就是关于 python 对mysql的所有操作

关于python的版本管理,库管理使用不少工具,现在对这些工具进行一下简单的总结.

PyPI

virtualenv

virtualenv 是一个非常实用的三方包,可以为 Python 创建各自独立开的python库.具体用法可以参考我之前的文章为什么使用virtualenv

pyenv

pyenv 是用来隔离开各种版本的 Python. 举个例子,比如你想在各个版本的Python中测试你的代码,你就需要一个方法去切换各种版本的Python. 通过使用 pyenv,激活你所需要的版本,它将/.pyenv/shims作为 Python 环境变量的前缀,这个路径下包含着一些可以 Python 命令文件(python, pip).这些不是Python附带命令的副本;它们是特殊的脚本,可以根据PYENV_VERVE环境变量,.python-version文件或者/.pyenv/version动态决定运行哪个版本的 Python.具体安装步骤的可以参考pyenv-installer

接下来的三个我都基本没有使用过

pyenv-virtualenv

pyenv-virtualenv 是由 pyenv 作者编写的一个插件,它可以使方便地同时使用 pyenv 和 virtualenv. 如果您使用Python3.3或更高版本,pyenv-virtualenv 将尝试运行 python -m venv(如果可用),而不是运行virtualenv. 当然如果你不想使用这个比较方便的特性的话,你也可以同时使用 virtualenv 和 pyenv 而不用 pyenv-virtualenv.

virtualenvwrapper

看它的名称不难猜到它是对 virtualenv 的进一步封装,事实上也是这样它是对 virtualenv 的一组扩展.它提供了 mkviralenv、lssitepackage等命令, 特别是 workon 可以用于在不同的 virtualenv 目录之间切换.

pyenv-virtualenvwrapper

pyenv-virtualenvwrapper 也是由 pyenv 编写的一个针对 pyenv 的插件,它可以方便地将虚拟包装程序集成到pyenv中.

pipenv

pipenv 是由 requests 作者编写的,旨在将管道文件、pip和vialenv合并为命令行上的一个命令.具体内容可以去项目主页浏览pipenv

Standard library

pyenv

pyenv 是 Python3中的附带脚本,但是在 Python3.6中废弃 了,具体内容见What’s New In Python 3.6

venv

venv 是 Python3 中附带的一个包,你可以通过使用 python -m venv使用它,不过在有的发行版中将它分离成了一个单独的发行版包,如 Ubuntu/Debian 中的 python3-env. 它的用途与 virtualenv 类似,工作方式也非常相似,但它不需要复制Python二进制文件(Windows除外).

参考文章

  1. https://stackoverflow.com/questions/41573587/what-is-the-difference-between-venv-pyvenv-pyenv-virtualenv-virtualenvwrappe

  2. https://stackoverflow.com/questions/29950300/what-is-the-relationship-between-virtualenv-and-pyenv

之前学了electron,前段时间又学了一下vue,为了增加熟练度决定将两者结合做个有趣的东西.想来想去最后决定将原来用 PyQt 写的MovieHeavens重新写一遍,使用electron-vue构建的项目地址electron-searchMovies,最后用electron-packager打包了成exe,在项目主页的releases可以找到打包后的安装程序.总结一下整个问题中遇见的几点问题以及解决办法.

无法下载打包所需的工具

由于一些神奇的力量导致打包过程中下载必需的工具包失败

解决办法

确定你需要工具包的名称,然后先手动将这些工具包下载下来,然后解压到对应的缓存目录中.各个系统对应的路径如下

1
2
3
macOS: ~/Library/Caches/electron-builder
Linux: ~/.cache/electron-builder
windows: %LOCALAPPDATA%\electron-builder\cache

我的最终目录树如下:

1
2
3
4
5
6
7
8
9
.
├── appimage-packages
│ └── appimage-packages-28-08-17
├── nsis
│ └── nsis-3.0.1.13
├── nsis-resources
│ └── nsis-resources-3.3.0
└── winCodeSign
└── winCodeSign-1.9.0

用 yarn 而不是 npm

当解决了工具包的问题,仍然打包成功,但是应用没有任何内容只是一个空白页,后来在githubNo contents only a blank page after build看见建议用 yarn 而不是 npm.这里有一篇Yarn vs npm: Everything You Need to Know的详细文章,正如官方文档说道的:yarn是为了弥补npm的一些缺陷而出现的.

短暂的空白页

一切问题都解决了,再次将软件打包成 exe,似乎接下来就是体验胜利的果实了,但是事实上并不是这样,打包的第一个版本Pre-release,在打开软件最开始会出现短暂的空白页,显然这对用户不是一个很棒的体验,最后决定加了一个简单的加载动画,核心代码如下:

1
2
3
4
5
6
7
8
mainWindow.webContents.on('did-finish-load', () => {
mainWindow.show()
if (loadingScreen) {
let loadingScreenBounds = loadingScreen.getBounds()
mainWindow.setBounds(loadingScreenBounds)
loadingScreen.close()
}
})

完整代码自然就需要去electron-searchMovies上查看了.这里遇见了一个新的问题.

Cannot Get Route

在解决上个问题的同时遇见了一个新的问题,加载动画页是通过路由映射的,我在 src/routes.js 中添加了如下的路由:

1
2
3
4
5
{
path: '/loading',
name: 'loading-page',
component: require('@/components/LoadingPage')
}

然后让 loadingScreen 加载 http://localhost:9080/loading 但是却使用获得 cannot get /loading 的错误,后来最后查找资料下找到了解决方案,对于新的路由访问地址应该是http://localhost:9080/#/new_route,打包后的访问地址应该是:file://${__dirname}/index.html#new_route,到此所有问题圆满解决.最后上一下软件的使用截图.

使用


最后欢迎大家star Or fork~

In English, we have a concept called root, which can be followed by some other words to form another longer word - let’s call this word successor. For example, the root an, followed by other, which can form another word another.

Now, given a dictionary consisting of many roots and a sentence. You need to replace all the successor in the sentence with the root forming it. If a successor has many roots can form it, replace it with the root with the shortest length.

You need to output the sentence after the replacement.

Example 1:

1
2
3
Input: dict = ["cat", "bat", "rat"]
sentence = "the cattle was rattled by the battery"
Output: "the cat was rat by the bat"

Note:

  1. The input will only have lower-case letters.
  2. 1 <= dict words number <= 1000
  3. 1 <= sentence words number <= 1000
  4. 1 <= root length <= 100
  5. 1 <= sentence words length <= 1000

Solution

将字符串(sentence)拆分为数组(sentence_arr),然后遍历 dic,判断数组元素前导字符串是否包含dic中的元素,如果包含则替换

Python

Prefix-hash

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution(object):
def replaceWords(self, dict, sentence):
"""
:type dict: List[str]
:type sentence: str
:rtype: str
"""
res = []
sentence_arr = sentence.split(" ")
for i in range(len(sentence_arr)):
for item in dict:
if sentence_arr[i].startswith(item):
sentence_arr[i] = item
return " ".join(sentence_arr)

Trie

利用dict构建字典树,然后遍历 sentence 中的元素, 在 Trie 中搜索

参考代码1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution(object):
def replaceWords(self, roots, sentence):
_trie = lambda: collections.defaultdict(_trie)
trie = _trie()
END = True
for root in roots:
cur = trie
for letter in root:
cur = cur[letter]
cur[END] = root

def replace(word):
cur = trie
for letter in word:
if letter not in cur: break
cur = cur[letter]
if END in cur:
return cur[END]
return word

return " ".join(map(replace, sentence.split()))

参考代码2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution(object):
def replaceWords(self, roots, sentence):
"""
:type dict: List[str]
:type sentence: str
:rtype: str
"""

class TrieNode(object):
def __init__(self):
self.word = False
self.children = dict()

class Trie(object):
def __init__(self):
self.root = TrieNode()

def addWord(self, word):
if word:
cur = self.root
for c in word:
if c not in cur.children:
cur.children[c] = TrieNode()
cur = cur.children[c]
cur.word = True

def getRoot(self, word):
ans = ""
cur = self.root
for c in word:
if c in cur.children:
ans += c
cur = cur.children[c]
if cur.word == True: # found smallest root!
return ans
else:
break
return word

trie = Trie()
for word in roots:
trie.addWord(word)

ans = []
for word in sentence.split():
ans.append(trie.getRoot(word))
return ' '.join(ans)

The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number.

Given an array nums representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array.

Example 1:

1
2
Input: nums = [1,2,2,4]
Output: [2,3]

Note:

  1. The given array size will in the range [2, 10000].
  2. The given array’s numbers won’t have any order.

Solution

初始化一个长度为 len(nums) + 1的列表 A,然后遍历列表 nums,统计该列表各个元素出现的个数并记录在 A 中,然后统计列表 A 元素值为 2 的索引和 0 索引即为我们所求的值

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution(object):
def findErrorNums(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
len_num = len(nums)
count = [0] * (len(nums)+1)
for num in nums:
count[num] += 1
for i in range(1,len(nums)+1):
if count[i] == 2:
a = i
if count[i] == 0:
b = i
return [a,b]

Given two strings s and t, determine if they are isomorphic.

Two strings are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.

For example,
Given "egg", "add", return true.

Given "foo", "bar", return false.

Given "paper", "title", return true.

Note:
You may assume both s and t have the same length.

Solution

判断两个字符的结构是否一样:依次遍历两个字符中的元素获取其中索引,判断两个字符最后的索引值是否一致,如果一致则认为结构相同

Python

1
2
3
4
5
6
7
8
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
return [s.find(i) for i in s] == [t.find(j) for j in t]

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.

Solution

找出列表中是否存在值相同的那个元素,并且他们的索引值的差值不大于 k,思路:用哈希表记录第一次元素A出现的位置,如果遍历出现第二个值相同的元素B,如果差值符合则返回 True, 否则将B的索引覆盖A(后面再出现相同的元素C索引值 C-A 肯定大于 B-A),一直没有返回 False

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
dic_nums = {}

for index,value in enumerate(nums):
if value in dic_nums and (index - dic_nums[value] <= k) :
return True
else:
dic_nums[value] = index
return False

Description:

Count the number of prime numbers less than a non-negative number, n.

Solution

统计在[0, n) 区间内中质数的个数,按照常规方法去计算是否为素数可能会超时(没有尝试),可以用 素数筛法

用筛法求素数的基本思想是:把从1开始的、某一范围内的正整数从小到大顺序排列, 1不是素数,首先把它筛掉。剩下的数中选择最小的数是素数,然后去掉它的倍数。依次类推,直到筛子为空时结束。 –筛法求素数

如下图:

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
if n < 3:
return 0
primes = [True] * n
for i in range(2, int(n**0.5)+1):
j = i
k = j
while j*k < n:
primes[j * k ] = False
k += 1

count_primes = 0 // [1]

for i in range(2, n):
if primes[i]:
count_primes += 1

return count_primes

从 [1] 到最后的代码可以改为:

1
return sum(primes) - 2 // 0,1需要去掉

有个感觉很不错的写法:

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
# @param {integer} n
# @return {integer}
def countPrimes(self, n):
if n < 3:
return 0
primes = [True] * n
primes[0] = primes[1] = False
for i in range(2, int(n ** 0.5) + 1):
if primes[i]:
primes[i * i: n: i] = [False] * len(primes[i * i: n: i])
return sum(primes)

Given two arrays, write a function to compute their intersection.

Example:

Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].

Note:

  1. Each element in the result should appear as many times as it shows in both arrays.
  2. The result can be in any order.

Follow up:

  1. What if the given array is already sorted? How would you optimize your algorithm?
  2. What if nums1’s size is small compared to nums2’s size? Which algorithm is better?
  3. What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

Solution

统计两个列表重叠部分,统计两个列表中任意一个各个元素出现的个数保存在字典中(key-value),然后遍历另外一个列表,如果该元素存在字典中并且value不为0,则将其保存到结果集中,同事将对应的字典中的value减一,最后输出结果集.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
if len(nums2) > len(nums1):
nums2, nums1 = nums1, nums2
nmap = {}
for i in nums2:
if i not in nmap:
nmap[i] = 1
else:
nmap[i] += 1
ans = []
for i in nums1:
if i in nmap and nmap[i] > 0:
nmap[i] -= 1
ans.append(i)
return ans

如果不用字典的话,遍历其中一个列表 A 的各个元素,如果这个元素存在于另外一个列表 B 中,将其保存到结果集后移除该元素在列表 B 中第一次出现的位置,最后输出结果集

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
res = []
for num in nums2:
if num in nums1:
res.append(num)
index = nums1.index(num)
del nums1[index]
return res