Skip to content

Instantly share code, notes, and snippets.

View Yunkou's full-sized avatar
🏠
Working from home

yun.kou Yunkou

🏠
Working from home
View GitHub Profile
@Yunkou
Yunkou / isType.js
Last active September 8, 2017 20:05
/* 检测对象类型
* @param: obj {JavaScript Object}
* @param: typeStr {String} 以大写开头的 JS 类型名
* @return: {Boolean}
*/
function isType(obj, typeStr) {
return Object.prototype.toString.call(obj).slice(8, -1) === typeStr;
}
print('Converting')
try:
print(int('x'))
except:
print('Converting failed!')
else:
print('Converting successful!')
finally:
print('done')
@Yunkou
Yunkou / 0006.py
Created August 30, 2017 18:54
File reading with ‘with’
# The bad way
f = open('pimpin-aint-easy.txt')
text = f.read()
for line in text.split('\n'):
print(line)
f.close()
# The good way
with open('pimpin-aint-easy.txt') as f:
for line in f:
@Yunkou
Yunkou / 0005.py
Last active August 30, 2017 18:47
For ... else
needle = 'd'
haystack = ['a', 'b', 'c']
# The bad way
found = False
for letter in haystack:
if needle == letter:
print('Found!')
found = True
break
@Yunkou
Yunkou / 0004.py
Created August 30, 2017 18:13
Default dict values
ages = {
'Mary': 31,
'Jonathan': 28
}
# The bad way
if 'Dick' in ages:
age = ages['Dick']
else:
age = 'Unknown'
@Yunkou
Yunkou / 0003.py
Created August 30, 2017 18:03
Tuple unpacking
# The bad way
x = 10
y = -10
print('Before: x = %d, y = %d' % (x, y))
tmp = y
y = x
x = tmp
print('After: x = %d, y = %d' % (x, y))
@Yunkou
Yunkou / 0002.py
Last active August 30, 2017 17:56
Using zip()
x_list = [1, 2, 3]
y_list = [2, 4, 6]
# The bad way
for i in range(len(x_list)):
x = x_list[i]
y = y_list[i]
print(x, y)
# The good way
@Yunkou
Yunkou / 0001.py
Last active August 30, 2017 17:44
Using enumerate()
cities = ['Marseille', 'Amsterdam', 'New York', 'London']
# The bad way
i = 0
for city in cities:
print(i, city)
i += 1
# The good way
@Yunkou
Yunkou / zepto.smoothScroll.js
Created September 14, 2016 10:16 — forked from benjamincharity/zepto.smoothScroll.js
Smooth scrolling with Zepto.js
function smoothScroll(el, to, duration) {
if (duration < 0) {
return;
}
var difference = to - $(window).scrollTop();
var perTick = difference / duration * 10;
this.scrollToTimerCache = setTimeout(function() {
if (!isNaN(parseInt(perTick, 10))) {
window.scrollTo(0, $(window).scrollTop() + perTick);
smoothScroll(el, to, duration - 10);
@Yunkou
Yunkou / getEntry.js
Created May 16, 2016 07:41
兼容Mac和Win PC webpack入口打包配置辅助函数
function getEntry(globPath) {
var files = glob.sync(globPath);
var entries = {},
entry, dirname, basename, pathname, extname;
for (var i = 0; i < files.length; i++) {
entry = files[i];
dirname = path.dirname(entry);
extname = path.extname(entry);
basename = path.basename(entry, extname);