Skip to content

Instantly share code, notes, and snippets.

@sonkm3
sonkm3 / gist:3039820
Created July 3, 2012 13:53
python 文字列ダンプしたかった
for c in target_string:
print '%s: %s' % (hex(ord(c)), c.rstrip())
@sonkm3
sonkm3 / gist:3064566
Created July 7, 2012 04:10
python argument as list/dict
# -*- coding: utf-8 -*-
class Klass1:
def __init__(self, param1, param2):
print 'param1: %s' % param1
print 'param2: %s' % param2
class Klass2:
def __init__(self, param1, param2, param3):
print 'param1: %s' % param1
@sonkm3
sonkm3 / gist:3177018
Created July 25, 2012 16:14
python generator
>>> def temp():
... print 'called'
... for lp in [1,2,3,4,5]:
... print 'called:' + str(lp)
... yield lp
...
>>> gen = temp()
>>> for index in gen:
... pass
...
@sonkm3
sonkm3 / gist:3191526
Created July 28, 2012 02:58
python generator by closure (count kept in property of function)
def get_counter():
print 'get_counter'
def counter():
counter.count = counter.count + 1
return counter.count
counter.count = 0
return counter
@sonkm3
sonkm3 / gist:3191527
Created July 28, 2012 02:59
python generator by closure (count passed via list)
def get_counter():
print 'get_counter'
def counter():
count[0] = count[0] + 1
return count[0]
count = [0]
return counter
@sonkm3
sonkm3 / gist:4482584
Last active December 10, 2015 19:38
python: fetch tweets by tweepy's Cursor but this stops before it reaches the end..
# -*- coding: utf-8 -*-
import tweepy
consumer_token = ''
consumer_secret = ''
access_token = ''
access_secret = ''
def get_tweets(api, screen_name):
@sonkm3
sonkm3 / gist:5493822
Last active December 16, 2015 20:39
python: ジェネレーター関数の内側でraiseすると、その後はStopIterationしか上がってこない件 ジェネレーター関数内でのraiseはジェネレーター関数内でのreturnと同じ挙動ってこと?
def gen1():
count = 0
while True:
count = count + 1
print count
if count > 10:
return
if count == 5:
print 'raise!'
raise '5!!!'
@sonkm3
sonkm3 / gist:5516180
Last active December 16, 2015 23:49
python: raising exception from inside of generator function.
# -*- coding: utf-8 -*-
# simple generator function
def generator1(limit):
for count in range(limit):
yield count
# simple generator function with return
def generator2(limit, stop):
for count in range(limit):
if count > stop:
@sonkm3
sonkm3 / gist:5786358
Created June 15, 2013 01:16
簡易csrf対策
class AdminHandler(webapp.RequestHandler):
@util.login_required
def get(self):
csrf_key = self._generate_csrf_key()
# pass csrf key as template parameter
@util.login_required
def post(self):
if users.is_current_user_admin():
if not self._check_csrf_key(self.request.get('csrf_key')):
@sonkm3
sonkm3 / gist:6102746
Last active December 20, 2015 08:48
ruby: hash.update()
hash1 = {:a=> 1, :b=>2}
hash2 = {}
hash2[:b] = 3
p hash2
hash2.update(hash1)
p hash2
#{:b=>3}