code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
v = str(self.geoid.tract).zfill(6) return v[0:4] + '.' + v[4:]
def dotted(self)
Return just the tract number, excluding the state and county, in the dotted format
10.691232
6.077063
1.759276
from geoid import get_class import geoid.census parser = get_class(geoid.census, vt_args.strip('/')).parse cls = type(vt_code.replace('/', '_'), (cls,), {'vt_code': vt_code, 'parser': parser}) globals()[cls.__name__] = cls assert cls.parser return cls
def subclass(cls, vt_code, vt_args)
Return a dynamic subclass that has the extra parameters built in
6.572247
6.988399
0.940451
fh = os.fdopen(os.open(path, os.O_RDONLY | os.O_NONBLOCK)) # If the file is being opened for the first time, jump to the end. # Otherwise, it is being reopened after a rotation, and we want # content from the beginning. if offset is None: if skip_to_end: fh.see...
def _open(self, path, skip_to_end = True, offset = None)
Open `path`, optionally seeking to the end if `skip_to_end` is True.
3.335927
3.336586
0.999803
# The code that used to be here was self._fh.read(limit) # However, this broke on OSX. os.read, however, works fine, but doesn't # take the None argument or have any way to specify "read to the end". # This emulates that behaviour. while True: # Check that we haven't closed...
def _read(self, limit = None)
Checks the file for new data and refills the buffer if it finds any.
6.560672
6.20495
1.057329
try: # If the inodes don't match, it means the file has been replaced. # The inode number cannot be recycled as long as we hold the # filehandle open, so this test can be trusted. return os.stat(self._path).st_ino != self._inode except OSError: # If the fi...
def hasBeenRotated(self)
Returns a boolean indicating whether the file has been removed and recreated during the time it has been open.
7.654676
6.861554
1.115589
# Read any remaining content in the file and store it in a buffer. self._read() # Close it to ensure we don't leak file descriptors self._close() # Reopen the file. try: self._open(self._path, skip_to_end = False) return True except OSError: ...
def reopen(self)
Reopens the file. Usually used after it has been rotated.
7.586153
6.621848
1.145625
# If the file is not open, there's nothing to return if not self._fh: raise StopIteration at_eof = False while True: # Clean the buffer sometimes. if self._bufoffset > (self._maxreadsize / 2): self._buf = self._buf[self._bufoffset:] sel...
def readlines(self)
A generator producing lines from the file.
4.027206
3.911507
1.029579
# Get listing of matching files. paths = [] for single_glob in self._globspec: paths.extend(glob.glob(single_glob)) # Remove files that don't appear in the new list. for path in self._tailedfiles.keys(): if path not in paths: self._tailedfiles[path]._...
def _rescan(self, skip_to_end = True)
Check for new files, deleted files, and rotated files.
3.80602
3.539448
1.075315
# Check for new, deleted, and rotated files. if force_rescan or time.time() > self._last_scan + self._interval: self._rescan(skip_to_end = False) self._last_scan = time.time() filereaders = {} for path, tailedfile in self._tailedfiles.iteritems(): filereaders[p...
def poll(self, force_rescan = False)
A generator producing (path, line) tuples with lines seen since the last time poll() was called. Will not block. Checks for new/deleted/rotated files every `interval` seconds, but will check every time if `force_rescan` is True. (default False)
6.261399
5.514949
1.13535
for path, tailedfile in self._tailedfiles.iteritems(): yield path, tailedfile._offset
def offsets(self)
A generator producing a (path, offset) tuple for all tailed files.
21.455114
6.651641
3.225537
self.remoteRouteName = remoteRouteName # This route must not be started before its router is started. If # sender is None, then the router is not started. When the router is # started, it will start this route. if self.router._sender is not None: self.start...
def connectTo(self, remoteRouteName)
Set the name of the route which will be added to outgoing boxes.
6.659207
6.408814
1.03907
if self.remoteRouteName is _unspecified: raise RouteNotConnected() if self.remoteRouteName is not None: box[_ROUTE] = self.remoteRouteName.encode('ascii') self.router._sender.sendBox(box)
def sendBox(self, box)
Add the route and send the box.
9.568938
7.906765
1.210222
if routeName is _unspecified: routeName = self.createRouteIdentifier() # self._sender may yet be None; if so, this route goes into _unstarted # and will have its sender set correctly in startReceivingBoxes below. route = Route(self, receiver, routeName) mappi...
def bindRoute(self, receiver, routeName=_unspecified)
Create a new route to associate the given route name with the given receiver. @type routeName: C{unicode} or L{NoneType} @param routeName: The identifier for the newly created route. If C{None}, boxes with no route in them will be delivered to this receiver. @r...
7.827733
8.643243
0.905648
self._sender = sender for routeName, route in self._unstarted.iteritems(): # Any route which has been bound but which does not yet have a # remote route name should not yet be started. These will be # started in Route.connectTo. if route.remoteRo...
def startReceivingBoxes(self, sender)
Initialize route tracking objects.
9.193547
8.311852
1.106077
route = box.pop(_ROUTE, None) self._routes[route].receiver.ampBoxReceived(box)
def ampBoxReceived(self, box)
Dispatch the given box to the L{IBoxReceiver} associated with the route indicated by the box, or handle it directly if there is no route.
15.554603
10.559416
1.473055
for routeName, route in self._routes.iteritems(): route.stop(reason) self._routes = None
def stopReceivingBoxes(self, reason)
Stop all the L{IBoxReceiver}s which have been added to this router.
6.367223
6.14231
1.036617
from boto.exception import S3ResponseError import time try: (b, ctime) = self._tlocal.s3bukt if time.time() - ctime > 60: raise AttributeError return b except AttributeError: try: # Validate by lis...
def _s3bukt(self)
Overrides the original _s3bukt method to get the bucket without vlaidation when the return to the original validation is not a 404. :return:
3.421587
3.357408
1.019116
req = swagger_client.BuildRecordPushRequestRest() req.tag_prefix = tag_prefix req.build_record_id = id response = utils.checked_api_call(pnc_api.build_push, 'push', body=req) if response: return utils.format_json_list(response)
def push_build(id, tag_prefix)
Push build to Brew
5.457416
5.807315
0.939749
req = swagger_client.BuildConfigSetRecordPushRequestRest() req.tag_prefix = tag_prefix req.build_config_set_record_id = id response = utils.checked_api_call(pnc_api.build_push, 'push_record_set', body=req) if response: return utils.format_json_list(response)
def push_build_set(id, tag_prefix)
Push build set to Brew
5.465426
6.065009
0.901141
response = utils.checked_api_call(pnc_api.build_push, 'status', build_record_id=id) if response: return utils.format_json(response)
def push_build_status(id)
Get status of Brew push.
7.38294
7.226499
1.021648
'''Create TransientFile and file on FS from given input stream and original file name.''' ext = os.path.splitext(original_name)[1] transient = self.new_transient(ext) if not os.path.isdir(self.transient_root): os.makedirs(self.transient_root) self._copy_file...
def create_transient(self, input_stream, original_name, length=None)
Create TransientFile and file on FS from given input stream and original file name.
4.578085
2.868284
1.596106
'''Creates empty TransientFile with random name and given extension. File on FS is not created''' name = random_name(self.transient_length) + ext return TransientFile(self.transient_root, name, self)
def new_transient(self, ext='')
Creates empty TransientFile with random name and given extension. File on FS is not created
10.599297
3.446269
3.075586
'''Restores TransientFile object with given name. Should be used when form is submitted with file name and no file''' # security checks: basically no folders are allowed assert not ('/' in name or '\\' in name or name[0] in '.~') transient = TransientFile(self.transient_root, nam...
def get_transient(self, name)
Restores TransientFile object with given name. Should be used when form is submitted with file name and no file
8.665741
4.782871
1.811828
'''Makes PersistentFile from TransientFile''' #for i in range(5): # persistent_file = PersistentFile(self.persistent_root, # persistent_name, self) # if not os.path.exists(persistent_file.path): # break #else: ...
def store(self, transient_file, persistent_file)
Makes PersistentFile from TransientFile
3.231934
2.955635
1.093482
app_key = self._app_key t = int(time.time() * 1000) requestStr = { 'header': self._req_header, 'model': payload } data = json.dumps({'requestStr': json.dumps(requestStr)}) data_str = '{}&{}&{}&{}'.format(self._req_token, t, app_key, data) ...
def _sign_payload(self, payload)
使用 appkey 对 payload 进行签名,返回新的请求参数
2.994256
2.790277
1.073104
if self._req_token is None: # 获取 token self._fetch_token() url = _gen_url(action) params = self._sign_payload(payload) response = self.http.get(url, params=params, cookies=self._cookies.get('cookie'), ...
def request(self, action, payload, timeout=3)
虾米 API 请求流程: 1. 获取一个 token:随便访问一个网页,服务端会 set cookie。 根据观察,这个 token 一般是 7 天过期 2. 对请求签名:见 _sign_payload 方法 3. 发送请求
5.718668
5.306625
1.077647
payload = { 'account': email, 'password': password } code, msg, rv = self.request( 'mtop.alimusic.xuser.facade.xiamiuserservice.login', payload ) if code == 'SUCCESS': # TODO: 保存 refreshToken 和过期时间等更多信息 ...
def login(self, email, password)
:password: user password md5 digest
10.888197
10.740501
1.013751
action = 'mtop.alimusic.music.list.collectservice.getcollectdetail' payload = {'listId': playlist_id} code, msg, rv = self.request(action, payload) return rv['data']['data']['collectDetail']
def playlist_detail(self, playlist_id)
获取歌单详情 如果歌单歌曲数超过 100 时,该接口的 songs 字段不会包含所有歌曲, 但是它有个 allSongs 字段,会包含所有歌曲的 ID。
11.261227
11.311793
0.99553
action = 'mtop.alimusic.music.list.collectservice.getcollectbyuser' payload = { 'userId': user_id, 'pagingVO': { 'page': page, 'pageSize': limit } } code, msg, rv = self.request(action, payload) # TODO: ...
def user_playlists(self, user_id, page=1, limit=30)
NOTE: 用户歌单有可能是仅自己可见
8.311093
7.565624
1.098534
op = 'un' if op == 'del' else '' action = 'mtop.alimusic.fav.songfavoriteservice.{}favoritesong'.format(op) payload = { 'songId': song_id } code, msg, rv = self.request(action, payload) return rv['data']['data']['status'] == 'true'
def update_favorite_song(self, song_id, op)
:param str op: `add` or `del`
8.735058
7.890303
1.107062
action = 'mtop.alimusic.music.list.collectservice.{}songs'.format( 'delete' if op == 'del' else 'add') payload = { 'listId': playlist_id, 'songIds': [song_id] } code, msg, rv = self.request(action, payload) return rv['data']['data']['s...
def update_playlist_song(self, playlist_id, song_id, op)
从播放列表删除或者增加一首歌曲 如果歌曲不存在与歌单中,删除时返回 True;如果歌曲已经存在于 歌单,添加时也返回 True。
7.215767
6.600643
1.093192
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.add_dependency_with_http_info(id, **kwargs) else: (data) = self.add_dependency_with_http_info(id, **kwargs) return data
def add_dependency(self, id, **kwargs)
Adds a dependency to the specified config This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(res...
1.536665
1.669247
0.920574
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.add_product_version_with_http_info(id, **kwargs) else: (data) = self.add_product_version_with_http_info(id, **kwargs) return data
def add_product_version(self, id, **kwargs)
Associates a product version to the specified config This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> ...
1.443778
1.640882
0.87988
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.clone_with_http_info(id, **kwargs) else: (data) = self.clone_with_http_info(id, **kwargs) return data
def clone(self, id, **kwargs)
Clones an existing Build Configuration This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(respon...
1.507707
1.713577
0.87986
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_all_by_product_id_with_http_info(product_id, **kwargs) else: (data) = self.get_all_by_product_id_with_http_info(product_id, **kwargs) return data
def get_all_by_product_id(self, product_id, **kwargs)
Gets all Build Configurations of a Product This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(re...
1.366058
1.559779
0.875803
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_all_by_project_id_with_http_info(project_id, **kwargs) else: (data) = self.get_all_by_project_id_with_http_info(project_id, **kwargs) return data
def get_all_by_project_id(self, project_id, **kwargs)
Gets all Build Configurations of a Project This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(re...
1.387251
1.565725
0.886011
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_builds_with_http_info(id, **kwargs) else: (data) = self.get_builds_with_http_info(id, **kwargs) return data
def get_builds(self, id, **kwargs)
Get all BuildRecords (running and archived) associated with this Build Configuration, returns empty list if no build records are found This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when re...
1.487638
1.707351
0.871314
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_dependencies_with_http_info(id, **kwargs) else: (data) = self.get_dependencies_with_http_info(id, **kwargs) return data
def get_dependencies(self, id, **kwargs)
Get the direct dependencies of the specified configuration This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >...
1.533532
1.718199
0.892523
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_product_versions_with_http_info(id, **kwargs) else: (data) = self.get_product_versions_with_http_info(id, **kwargs) return data
def get_product_versions(self, id, **kwargs)
Get associated Product Versions of the specified Configuration This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): ...
1.429883
1.673853
0.854247
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_revision_with_http_info(id, rev, **kwargs) else: (data) = self.get_revision_with_http_info(id, rev, **kwargs) return data
def get_revision(self, id, rev, **kwargs)
Get specific audited revision of this build configuration This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>...
1.477
1.611413
0.916587
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_revisions_with_http_info(id, **kwargs) else: (data) = self.get_revisions_with_http_info(id, **kwargs) return data
def get_revisions(self, id, **kwargs)
Gets audited revisions of this build configuration This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> p...
1.461778
1.723843
0.847976
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.get_supported_generic_parameters_with_http_info(**kwargs) else: (data) = self.get_supported_generic_parameters_with_http_info(**kwargs) return data
def get_supported_generic_parameters(self, **kwargs)
Gets the minimal set of supported genericParameters and their description for the BuildConfiguration. There can be also other supported parameters not know by core. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function...
1.520331
1.641836
0.925994
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.remove_dependency_with_http_info(id, dependency_id, **kwargs) else: (data) = self.remove_dependency_with_http_info(id, dependency_id, **kwargs) return data
def remove_dependency(self, id, dependency_id, **kwargs)
Removes a configuration from the specified config set This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> ...
1.427532
1.587838
0.899041
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.remove_product_version_with_http_info(id, product_version_id, **kwargs) else: (data) = self.remove_product_version_with_http_info(id, product_version_id, **kwargs) return d...
def remove_product_version(self, id, product_version_id, **kwargs)
Removes a product version from the specified config set This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> ...
1.355115
1.524106
0.889121
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.trigger_with_http_info(id, **kwargs) else: (data) = self.trigger_with_http_info(id, **kwargs) return data
def trigger(self, id, **kwargs)
Triggers a build of a specific Build Configuration This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> p...
1.543109
1.627989
0.947862
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.trigger_audited_with_http_info(id, rev, **kwargs) else: (data) = self.trigger_audited_with_http_info(id, rev, **kwargs) return data
def trigger_audited(self, id, rev, **kwargs)
Triggers a build of a specific Build Configuration in a specific revision This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(respo...
1.424471
1.544046
0.922557
kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.update_and_get_audited_with_http_info(id, **kwargs) else: (data) = self.update_and_get_audited_with_http_info(id, **kwargs) return data
def update_and_get_audited(self, id, **kwargs)
Updates an existing Build Configuration and returns BuildConfigurationAudited entity This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_fun...
1.410123
1.550526
0.909449
d = {'_frame': frame} # Allow access to frame object. d.update(frame.f_globals) # Unless shadowed by global d.update(frame.f_locals) i = code.InteractiveConsole(d) message = "Signal recieved : entering python shell.\nTraceback:\n" message += ''.join(traceback.format_stack(frame)) ...
def debug_break(sig, frame)
Interrupt running process, and provide a python prompt for interactive debugging.
3.327635
2.585716
1.28693
msg = [] msg.append('Enter {}('.format(fn.__name__)) if args: msg.append(', '.join([str(x) for x in args])) if kwargs: kwargs_str = ', '.join(['{}={}'.format(k, v) for k, v in list(kwargs.items())]) if args: msg.append(', ') ...
def trace(fn): # pragma: no cover def wrapped(*args, **kwargs)
Prints parameteters and return values of the each call of the wrapped function. Usage: decorate appropriate function or method: @trace def myf(): ...
2.402039
2.700996
0.889316
def __init__(self, *args, **kwargs): self.x = args[0] all_fds = count_open_fds() print('### {} OPENING {} ( {} total )###'.format( len(openfiles), str(self.x), all_fds)) oldfile.__init__(self, *args, **kwargs) openfiles.add(self) ...
def patch_file_open(): # pragma: no cover openfiles = set() oldfile = builtins.file class newfile(oldfile)
A Monkey patch to log opening and closing of files, which is useful for debugging file descriptor exhaustion.
3.054034
2.887646
1.057621
import linecache try: if event == "line": lineno = frame.f_lineno filename = frame.f_globals.get("__file__") if (filename.endswith(".pyc") or filename.endswith(".pyo")): filename = filename[:-1] name = frame.f_globals["__name__"] ...
def traceit(frame, event, arg)
Trace every lie of a program. Use: import sys sys.settrace(traceit) :param frame: :param event: :param arg: :return:
2.628139
2.913635
0.902014
if not IUsernamePassword.providedBy(credentials): raise UnhandledCredentials() d = client.callRemote( PasswordLogin, username=credentials.username) def cbChallenge(response): args = PasswordChallengeResponse.determineFrom( response['challenge'], credentials.password)...
def login(client, credentials)
Authenticate using the given L{AMP} instance. The protocol must be connected to a server with responders for L{PasswordLogin} and L{PasswordChallengeResponse}. @param client: A connected L{AMP} instance which will be used to issue authentication commands. @param credentials: An object providi...
5.455946
4.283409
1.273739
nonce = secureRandom(16) response = _calcResponse(challenge, nonce, password) return dict(cnonce=nonce, response=response)
def determineFrom(cls, challenge, password)
Create a nonce and use it, along with the given challenge and password, to generate the parameters for a response. @return: A C{dict} suitable to be used as the keyword arguments when calling this command.
7.180434
7.465903
0.961764
if isinstance(password, unicode): password = password.encode('utf-8') correctResponse = _calcResponse(self.challenge, self.nonce, password) return correctResponse == self.response
def checkPassword(self, password)
Check the given plaintext password against the response in this credentials object. @type password: C{str} @param password: The known correct password associated with C{self.username}. @return: A C{bool}, C{True} if this credentials object agrees with the given ...
5.147922
4.930413
1.044116
self.challenge = secureRandom(16) self.username = username return {'challenge': self.challenge}
def passwordLogin(self, username)
Generate a new challenge for the given username.
9.045248
5.760028
1.570348
d = self.portal.login(credentials, None, IBoxReceiver) def cbLoggedIn((interface, avatar, logout)): self.logout = logout self.boxReceiver = avatar self.boxReceiver.startReceivingBoxes(self.boxSender) return {} d.addCallback(cbLoggedIn) ...
def _login(self, credentials)
Actually login to our portal with the given credentials.
8.786053
7.894287
1.112963
return self._login(_AMPUsernamePassword( self.username, self.challenge, cnonce, response))
def passwordChallengeResponse(self, cnonce, response)
Verify the response to a challenge.
23.637447
25.079346
0.942507
AMP.connectionLost(self, reason) if self.logout is not None: self.logout() self.boxReceiver = self.logout = None
def connectionLost(self, reason)
If a login has happened, perform a logout.
9.478638
7.658844
1.237607
if not self._lyric: return pos = find_previous(position*1000 + 300, self._pos_list) if pos is not None and pos != self._pos: self.current_sentence = self._pos_s_map[pos] self._pos = pos
def on_position_changed(self, position)
bind position changed signal with this
6.496235
6.493762
1.000381
if song is None or song.lyric is None: self._lyric = None self._pos_s_map = {} else: self._lyric = song.lyric.content self._pos_s_map = parse(self._lyric) self._pos_list = sorted(list(self._pos_s_map.keys())) self._pos = None ...
def on_song_changed(self, song)
bind song changed signal with this
3.774846
3.713122
1.016623
maxValues = (9999, 12, 31, 23, 59, 59) minValues = (1, 1, 1, 0, 0, 0) newstruct = [] for value, maxValue, minValue in zip(struct[:6], maxValues, minValues): newstruct.append(max(minValue, min(value, maxValue))) return tuple(newstruct) + struct[6:]
def sanitizeStructTime(struct)
Convert struct_time tuples with possibly invalid values to valid ones by substituting the closest valid value.
2.437557
2.33209
1.045224
minutes = round((offset.days * 3600000000 * 24 + offset.seconds * 1000000 + offset.microseconds) / 60000000.0) if minutes < 0: sign = '-' minutes = -minutes else: sign = '+' return (sign, minutes // 60, minutes % ...
def _timedeltaToSignHrMin(offset)
Return a (sign, hour, minute) triple for the offset described by timedelta. sign is a string, either "+" or "-". In the case of 0 offset, sign is "+".
2.440945
2.450875
0.995948
humanStr = humanStr.strip() if now is None: now = Time() if tzinfo is None: tzinfo = FixedOffset(0, 0) for pattern, creator in klass.humanlyPatterns: match = pattern.match(humanStr) if not match \ or match.span()[1] !=...
def fromHumanly(klass, humanStr, tzinfo=None, now=None)
Return a new Time instance from a string a human might type. @param humanStr: the string to be parsed. @param tzinfo: A tzinfo instance indicating the timezone to assume if none is specified in humanStr. If None, assume UTC. @param now: A Time instance to be considered "now" for when ...
2.900477
3.490903
0.830867
dtime = datetime.datetime(tzinfo=tzinfo, *structTime[:6]) self = klass.fromDatetime(dtime) self.resolution = datetime.timedelta(seconds=1) return self
def fromStructTime(klass, structTime, tzinfo=None)
Return a new Time instance from a time.struct_time. If tzinfo is None, structTime is in UTC. Otherwise, tzinfo is a datetime.tzinfo instance coresponding to the timezone in which structTime is. Many of the functions in the standard time module return these things. This will als...
4.053515
5.444327
0.744539
self = klass.__new__(klass) if dtime.tzinfo is not None: self._time = dtime.astimezone(FixedOffset(0, 0)).replace(tzinfo=None) else: self._time = dtime self.resolution = datetime.timedelta.resolution return self
def fromDatetime(klass, dtime)
Return a new Time instance from a datetime.datetime instance. If the datetime instance does not have an associated timezone, it is assumed to be UTC.
2.915806
3.115928
0.935775
self = klass.fromDatetime(_EPOCH + datetime.timedelta(seconds=secs)) self.resolution = datetime.timedelta() return self
def fromPOSIXTimestamp(klass, secs)
Return a new Time instance from seconds since the POSIX epoch. The POSIX epoch is midnight Jan 1, 1970 UTC. According to POSIX, leap seconds don't exist, so one UTC day is exactly 86400 seconds, even if it wasn't. @param secs: a number of seconds, represented as an integer, long or ...
7.774671
13.412075
0.579677
# parsedate_tz is going to give us a "struct_time plus", a 10-tuple # containing the 9 values a struct_time would, i.e.: (tm_year, tm_mon, # tm_day, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst), plus a # bonus "offset", which is an offset (in _seconds_, of all things). ...
def fromRFC2822(klass, rfc822string)
Return a new Time instance from a string formated as described in RFC 2822. @type rfc822string: str @raise ValueError: if the timestamp is not formatted properly (or if certain obsoleted elements of the specification are used). @return: a new L{Time}
5.004888
5.067602
0.987625
if tzinfo is None: tzinfo = FixedOffset(0, 0) if not self.isTimezoneDependent(): return self._time.replace(tzinfo=tzinfo) else: return self._time.replace(tzinfo=FixedOffset(0, 0)).astimezone(tzinfo)
def asDatetime(self, tzinfo=None)
Return this time as an aware datetime.datetime instance. The returned datetime object has the specified tzinfo, or a tzinfo describing UTC if the tzinfo parameter is None.
2.833099
2.704716
1.047466
dtime = self.asDatetime(tzinfo) if tzinfo is None: rfcoffset = '-0000' else: rfcoffset = '%s%02i%02i' % _timedeltaToSignHrMin(dtime.utcoffset()) rfcstring = '' if includeDayOfWeek: rfcstring += self.rfc2822Weekdays[dtime.weekday()] +...
def asRFC2822(self, tzinfo=None, includeDayOfWeek=True)
Return this Time formatted as specified in RFC 2822. RFC 2822 specifies the format of email messages. RFC 2822 says times in email addresses should reflect the local timezone. If tzinfo is a datetime.tzinfo instance, the returned formatted string will reflect that timezone. Otherwise, ...
2.554131
2.528967
1.00995
if not self.isTimezoneDependent(): tzinfo = None dtime = self.asDatetime(tzinfo) if includeDelimiters: dateSep = '-' timeSep = ':' else: dateSep = timeSep = '' if includeTimezone: if tzinfo is None: ...
def asISO8601TimeAndDate(self, includeDelimiters=True, tzinfo=None, includeTimezone=True)
Return this time formatted as specified by ISO 8861. ISO 8601 allows optional dashes to delimit dates and colons to delimit times. The parameter includeDelimiters (default True) defines the inclusion of these delimiters in the output. If tzinfo is a datetime.tzinfo instance, the output...
2.134413
2.226328
0.958715
dtime = self.asDatetime(tzinfo) if tzinfo is None: return dtime.utctimetuple() else: return dtime.timetuple()
def asStructTime(self, tzinfo=None)
Return this time represented as a time.struct_time. tzinfo is a datetime.tzinfo instance coresponding to the desired timezone of the output. If is is the default None, UTC is assumed.
3.265472
3.61218
0.904017
try: timeFormat = Time._timeFormat[precision] except KeyError: raise InvalidPrecision( 'Use Time.Precision.MINUTES or Time.Precision.SECONDS') if now is None: now = Time().asDatetime(tzinfo) else: now = now.asD...
def asHumanly(self, tzinfo=None, now=None, precision=Precision.MINUTES)
Return this time as a short string, tailored to the current time. Parts of the date that can be assumed are omitted. Consequently, the output string depends on the current time. This is the format used for displaying dates in most user visible places in the quotient web UI. By default,...
3.424838
3.401083
1.006984
if self.resolution >= datetime.timedelta(days=1) \ and tzinfo is not None: time = self._time.replace(tzinfo=tzinfo) else: time = self._time return ( min(self.fromDatetime(time), self.fromDatetime(self._time)), max(self.fromDatetim...
def getBounds(self, tzinfo=None)
Return a pair describing the bounds of self. This returns a pair (min, max) of Time instances. It is not quite the same as (self, self + self.resolution). This is because timezones are insignificant for instances with a resolution greater or equal to 1 day. To illustrate the pr...
2.980767
2.854263
1.044321
day = self.__class__.fromDatetime(self.asDatetime().replace( hour=0, minute=0, second=0, microsecond=0)) day.resolution = datetime.timedelta(days=1) return day
def oneDay(self)
Return a Time instance representing the day of the start of self. The returned new instance will be set to midnight of the day containing the first instant of self in the specified timezone, and have a resolution of datetime.timedelta(days=1).
4.107285
3.083044
1.332218
logger = logging.getLogger(name) running_tests = ( 'test' in sys.argv # running with setup.py or sys.argv[0].endswith('py.test')) # running with py.test if running_tests and not level: # testing without level, this means tester does not want to see any log messages. l...
def get_logger(name, file_name=None, stream=None, template=None, propagate=False, level=None)
Get a logger by name.
2.842578
2.791838
1.018174
cache = obj.cache = {} last_access = obj.last_access = defaultdict(int) @wraps(obj) def memoizer(*args, **kwargs): key = str(args) + str(kwargs) if last_access[key] and last_access[key] + 10 < time(): if key in cache: del cache[key] last_acces...
def expiring_memoize(obj)
Like memoize, but forgets after 10 seconds.
2.215505
1.996557
1.109663
'''Least-recently-used cache decorator. Arguments to the cached function must be hashable. Cache performance statistics stored in f.hits and f.misses. Clear the cache with f.clear(). http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used ''' maxqueue = maxsize * 10 # @Reser...
def lru_cache(maxsize=128, maxtime=60)
Least-recently-used cache decorator. Arguments to the cached function must be hashable. Cache performance statistics stored in f.hits and f.misses. Clear the cache with f.clear(). http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used
2.509918
2.43913
1.029022
import itertools as it import operator as op if custom_level is None: custom_level = logging.WARNING for entity in it.chain.from_iterable(it.imap(op.methodcaller('viewvalues'), [cfg] + [cfg.get(k, dict()) for k in ['handlers', 'loggers']])):...
def configure_logging(cfg, custom_level=None)
Don't know what this is for ....
3.719342
3.486037
1.066926
# Ignore self dependencies. for k, v in iteritems(data): v.discard(k) # Find all items that don't depend on anything. extra_items_in_deps = reduce( set.union, itervalues(data)) - set(data.keys()) # Add empty dependences where needed data.update({item: set() for item in extr...
def toposort(data)
Dependencies are expressed as a dictionary whose keys are items and whose values are a set of dependent items. Output is a list of sets in topological order. The first set consists of items with no dependences, each subsequent set consists of items that depend upon items in the preceeding sets. >>> pri...
3.033363
3.000882
1.010824
md5 = hashlib.md5() try: # Guess that f is a FLO. f.seek(0) return md5_for_stream(f, block_size=block_size) except AttributeError: # Nope, not a FLO. Maybe string? file_name = f with open(file_name, 'rb') as f: return md5_for_file(f, block...
def md5_for_file(f, block_size=2 ** 20)
Generate an MD5 has for a possibly large file by breaking it into chunks.
4.24628
4.310925
0.985005
# Really should cache these ... v = ['a', 'e', 'i', 'o', 'u', 'y'] c = [chr(x) for x in six_xrange(ord('a'), ord('z') + 1) if chr(x) not in v] s = re.sub(r'\W+', '', s.lower()) vx = [x for x in s if x in v] # Vowels in input string cx = [x for x in s if x in ...
def make_acro(past, prefix, s): # pragma: no cover def _make_acro(s, t=0)
Create a three letter acronym from the input string s. Args: past: A set object, for storing acronyms that have already been created prefix: A prefix added to the acronym before storing in the set s: The string to create the acronym from.
2.519099
2.48841
1.012332
import os f_dir = os.path.dirname(path) if not os.path.exists(f_dir): os.makedirs(f_dir) return f_dir
def ensure_dir_exists(path)
Given a file, ensure that the path to the file exists
2.806157
2.653696
1.057452
# nested dict keys nested_keys = tuple(k for k in list(d.keys()) if isinstance(d[k], dict)) # key/value pairs for non-dicts items = tuple((k, d[k]) for k in list(d.keys()) if k not in nested_keys) # return path, key/sub-dict pairs, and key/value pairs yield ('/', [(k, d[k]) for k in nested...
def walk_dict(d)
Walk a tree (nested dicts). For each 'path', or dict, in the tree, returns a 3-tuple containing: (path, sub-dicts, values) where: * path is the path to the dict * sub-dicts is a tuple of (key,dict) pairs for each sub-dict in this dict * values is a tuple of (key,value) pairs for each (non-dict...
4.237576
3.777518
1.121788
if print_rate and not N: N = 100 if not N: N = 5000 d = [0, # number of items processed time(), # start time. This one gets replaced after first message N, # ticker to next message N, # frequency to log a message message, print_rate, ...
def init_log_rate(output_f, N=None, message='', print_rate=None)
Initialze the log_rate function. Returnas a partial function to call for each event. If N is not specified but print_rate is specified, the initial N is set to 100, and after the first message, the N value is adjusted to emit print_rate messages per second
7.343238
7.322058
1.002893
if d[2] <= 0: if message is None: message = d[4] # Average the rate over the length of the deque. d[6].append(int(d[3] / (time() - d[1]))) rate = sum(d[6]) / len(d[6]) # Prints the processing rate in 1,000 records per sec. output_f(message + ': ' ...
def _log_rate(output_f, d, message=None)
Log a message for the Nth time the method is called. d is the object returned from init_log_rate
4.512969
4.435347
1.017501
pid = os.getpid() procs = subprocess.check_output( ['lsof', '-w', '-Ff', '-p', str(pid)]) nprocs = len( [s for s in procs.split('\n') if s and s[0] == 'f' and s[1:].isdigit()] ) return nprocs
def count_open_fds()
return the number of open file descriptors for current process. .. warning: will only work on UNIX-like os-es. http://stackoverflow.com/a/7142094
3.203799
3.190174
1.004271
p = urlparse(url) return { 'scheme': p.scheme, 'netloc': p.netloc, 'path': p.path, 'params': p.params, 'query': p.query, 'fragment': p.fragment, 'username': p.username, 'password': p.password, 'hostname': p.hostname, 'port': p...
def parse_url_to_dict(url)
Parse a url and return a dict with keys for all of the parts. The urlparse function() returns a wacky combination of a namedtuple with properties.
1.421533
1.473285
0.964873
d = parse_url_to_dict(url) d.update(kwargs) return unparse_url_dict(d)
def set_url_part(url, **kwargs)
Change one or more parts of a URL
5.288388
5.622725
0.940538
d = parse_url_to_dict(url) d.update(kwargs) return unparse_url_dict({k: v for k, v in list(d.items()) if v})
def filter_url(url, **kwargs)
filter a URL by returning a URL with only the parts specified in the keywords
4.758295
4.429082
1.07433
print(yaml.dump(o, default_flow_style=False, indent=4, encoding='utf-8'))
def print_yaml(o)
Pretty print an object as YAML.
2.656482
2.510366
1.058205
module = o.__class__.__module__ if module is None or module == str.__class__.__module__: return o.__class__.__name__ return module + '.' + o.__class__.__name__
def qualified_class_name(o)
Full name of an object, including the module
1.950891
1.955845
0.997467
module = cls.__module__ if module is None or module == str.__class__.__module__: return cls.__name__ return module + '.' + cls.__name__
def qualified_name(cls)
Full name of a class, including the module. Like qualified_class_name, but when you already have a class
2.327299
2.19737
1.05913
parts = qualified_name(cls).split('.') return "from {} import {}".format('.'.join(parts[:-1]), parts[-1])
def qualified_name_import(cls)
Full name of a class, including the module. Like qualified_class_name, but when you already have a class
5.060104
4.844313
1.044545
return zip(*[col for col in zip(*rows) if bool(filter(bool, col[1:]))])
def drop_empty(rows)
Transpose the columns into rows, remove all of the rows that are empty after the first cell, then transpose back. The result is that columns that have a header but no data in the body are removed, assuming the header is the first row.
6.842516
7.238846
0.94525
intervals = ( ('weeks', 604800), # 60 * 60 * 24 * 7 ('days', 86400), # 60 * 60 * 24 ('hours', 3600), # 60 * 60 ('minutes', 60), ('seconds', 1), ) def display_time(seconds, granularity=granularity): result = [] for name, count in intervals: ...
def pretty_time(s, granularity=3)
Pretty print time in seconds. COnverts the input time in seconds into a string with interval names, such as days, hours and minutes From: http://stackoverflow.com/a/24542445/1144479
1.609477
1.621567
0.992544
from sys import modules try: thismod = modules[modname] except KeyError: raise ValueError(modname) these_symbols = dir(thismod) if paranoid: try: paranoid[:] # sequence support except: raise ValueError('must supply a finite list for paran...
def delete_module(modname, paranoid=None)
Delete a module.http://stackoverflow.com/a/1668289 :param modname: :param paranoid: :return:
3.143618
3.201699
0.981859
def make_method(name): def method(self, *args, **kw): return getattr(object.__getattribute__(self, "_obj"), name)(*args, **kw) return method namespace = {} for name in cls._special_names: if hasattr(theclass, name): n...
def _create_class_proxy(cls, theclass)
creates a proxy for the given class
2.493254
2.492637
1.000248
res = value / float(reference_value) return InflationResult(factor=res, value=res - 1)
def _compute_inflation(value, reference_value)
Helper function to compute the inflation/deflation based on a value and a reference value
10.708811
9.557502
1.120461
# Set country & reference to object's country & reference respectively reference = self.reference if reference is None else reference # Get the reference and target indices (values) from the source reference_value = self.data.get(reference, country).value target_value ...
def get(self, reference, country, target=datetime.date.today())
Get the inflation/deflation value change for the target date based on the reference date. Target defaults to today and the instance's reference and country will be used if they are not provided as parameters
5.553644
4.908531
1.131427
country = country if country else self.country # Get the inflation for the two dates and country inflation = self.get(reference, country, target) # Return the inflated/deflated amount return amount * inflation.factor
def inflate(self, amount, target=datetime.date.today(), reference=None, country=None)
Inflate a given amount to the target date from a reference date (or the object's reference year if no reference date is provided) in a given country (or objects country if no country is provided). The amount has to be provided as it was valued in the reference year.
6.981173
6.866373
1.016719