code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
'''Compute the error (or erasures if you supply sigma=erasures locator polynomial) evaluator polynomial Omega from the syndrome and the error/erasures/errata locator Sigma. Omega is already computed at the same time as Sigma inside the Berlekamp-Massey implemented above, but in case you modify Sigma, you can re... | def _find_error_evaluator(self, synd, sigma, k=None) | Compute the error (or erasures if you supply sigma=erasures locator polynomial) evaluator polynomial Omega from the syndrome and the error/erasures/errata locator Sigma. Omega is already computed at the same time as Sigma inside the Berlekamp-Massey implemented above, but in case you modify Sigma, you can recompute Ome... | 14.717172 | 5.945609 | 2.475301 |
'''Compute the error (or erasures if you supply sigma=erasures locator polynomial) evaluator polynomial Omega from the syndrome and the error/erasures/errata locator Sigma. Omega is already computed at the same time as Sigma inside the Berlekamp-Massey implemented above, but in case you modify Sigma, you can re... | def _find_error_evaluator_fast(self, synd, sigma, k=None) | Compute the error (or erasures if you supply sigma=erasures locator polynomial) evaluator polynomial Omega from the syndrome and the error/erasures/errata locator Sigma. Omega is already computed at the same time as Sigma inside the Berlekamp-Massey implemented above, but in case you modify Sigma, you can recompute Ome... | 18.386183 | 3.707962 | 4.958568 |
'''Recall the definition of sigma, it has s roots. To find them, this
function evaluates sigma at all 2^(c_exp-1) (ie: 255 for GF(2^8)) non-zero points to find the roots
The inverse of the roots are X_i, the error locations
Returns a list X of error locations, and a corresponding list j... | def _chien_search(self, sigma) | Recall the definition of sigma, it has s roots. To find them, this
function evaluates sigma at all 2^(c_exp-1) (ie: 255 for GF(2^8)) non-zero points to find the roots
The inverse of the roots are X_i, the error locations
Returns a list X of error locations, and a corresponding list j of
... | 17.72864 | 6.666386 | 2.659408 |
'''Real chien search, we reuse the previous polynomial evaluation and just multiply by a constant polynomial. This should be faster, but it seems it's just the same speed as the other bruteforce version. However, it should easily be parallelizable.'''
# TODO: doesn't work when fcr is different than 1 (X... | def _chien_search_fast(self, sigma) | Real chien search, we reuse the previous polynomial evaluation and just multiply by a constant polynomial. This should be faster, but it seems it's just the same speed as the other bruteforce version. However, it should easily be parallelizable. | 13.452202 | 10.640382 | 1.264259 |
'''Faster chien search, processing only useful coefficients (the ones in the messages) instead of the whole 2^8 range.
Besides the speed boost, this also allows to fix a number of issue: correctly decoding when the last ecc byte is corrupted, and accepting messages of length n > 2^8.'''
n = self... | def _chien_search_faster(self, sigma) | Faster chien search, processing only useful coefficients (the ones in the messages) instead of the whole 2^8 range.
Besides the speed boost, this also allows to fix a number of issue: correctly decoding when the last ecc byte is corrupted, and accepting messages of length n > 2^8. | 16.894384 | 12.190993 | 1.385809 |
'''Computes the error magnitudes (only works with errors or erasures under t = floor((n-k)/2), not with erasures above (n-k)//2)'''
# XXX Is floor division okay here? Should this be ceiling?
if not k: k = self.k
t = (self.n - k) // 2
Y = []
for l, Xl in enumerate(X):
... | def _old_forney(self, omega, X, k=None) | Computes the error magnitudes (only works with errors or erasures under t = floor((n-k)/2), not with erasures above (n-k)//2) | 10.145516 | 7.146179 | 1.419712 |
'''Computes the error magnitudes. Works also with erasures and errors+erasures beyond the (n-k)//2 bound, here the bound is 2*e+v <= (n-k-1) with e the number of errors and v the number of erasures.'''
# XXX Is floor division okay here? Should this be ceiling?
Y = [] # the final result, the err... | def _forney(self, omega, X) | Computes the error magnitudes. Works also with erasures and errors+erasures beyond the (n-k)//2 bound, here the bound is 2*e+v <= (n-k-1) with e the number of errors and v the number of erasures. | 13.89298 | 10.866335 | 1.278534 |
try:
p = Popen(['/bin/ps', '-p%s' % self.pid, '-o', 'rss,vsz'],
stdout=PIPE, stderr=PIPE)
except OSError: # pragma: no cover
pass
else:
s = p.communicate()[0].split()
if p.returncode == 0 and len(s) >= 2: # pragma: no... | def update(self) | Get virtual and resident size of current process via 'ps'.
This should work for MacOS X, Solaris, Linux. Returns true if it was
successful. | 2.670131 | 2.235196 | 1.194585 |
try:
stat = open('/proc/self/stat')
status = open('/proc/self/status')
except IOError: # pragma: no cover
return False
else:
stats = stat.read().split()
self.vsz = int( stats[22] )
self.rss = int( stats[23] ) * self... | def update(self) | Get virtual size of current process by reading the process' stat file.
This should work for Linux. | 2.924306 | 2.75983 | 1.059596 |
wx.EVT_LIST_COL_CLICK(self, self.GetId(), self.OnReorder)
wx.EVT_LIST_ITEM_SELECTED(self, self.GetId(), self.OnNodeSelected)
wx.EVT_MOTION(self, self.OnMouseMove)
wx.EVT_LIST_ITEM_ACTIVATED(self, self.GetId(), self.OnNodeActivated)
self.CreateColumns() | def CreateControls(self) | Create our sub-controls | 2.571488 | 2.483996 | 1.035222 |
self.SetItemCount(0)
# clear any current columns...
for i in range( self.GetColumnCount())[::-1]:
self.DeleteColumn( i )
# now create
for i, column in enumerate(self.columns):
column.index = i
self.InsertColumn(i, column.name)
... | def CreateColumns( self ) | Create/recreate our column definitions from current self.columns | 4.097755 | 3.671631 | 1.116058 |
self.columns = columns
self.sortOrder = [(x.defaultOrder,x) for x in self.columns if x.sortDefault]
self.CreateColumns() | def SetColumns( self, columns, sortOrder=None ) | Set columns to a set of values other than the originals and recreates column controls | 7.661563 | 6.098989 | 1.256202 |
try:
node = self.sorted[event.GetIndex()]
except IndexError, err:
log.warn(_('Invalid index in node activated: %(index)s'),
index=event.GetIndex())
else:
wx.PostEvent(
self,
squaremap.SquareActivati... | def OnNodeActivated(self, event) | We have double-clicked for hit enter on a node refocus squaremap to this node | 8.256927 | 6.904789 | 1.195826 |
try:
node = self.sorted[event.GetIndex()]
except IndexError, err:
log.warn(_('Invalid index in node selected: %(index)s'),
index=event.GetIndex())
else:
if node is not self.selected_node:
wx.PostEvent(
... | def OnNodeSelected(self, event) | We have selected a node with the list control, tell the world | 6.827814 | 6.545839 | 1.043077 |
self.indicated_node = node
self.indicated = self.NodeToIndex(node)
self.Refresh(False)
return self.indicated | def SetIndicated(self, node) | Set this node to indicated status | 5.325164 | 5.743581 | 0.927151 |
self.selected_node = node
index = self.NodeToIndex(node)
if index != -1:
self.Focus(index)
self.Select(index, True)
return index | def SetSelected(self, node) | Set our selected node | 4.170883 | 3.984954 | 1.046658 |
column = self.columns[event.GetColumn()]
return self.ReorderByColumn( column ) | def OnReorder(self, event) | Given a request to reorder, tell us to reorder | 12.785909 | 12.048409 | 1.061211 |
# TODO: store current selection and re-select after sorting...
single_column = self.SetNewOrder( column )
self.reorder( single_column = True )
self.Refresh() | def ReorderByColumn( self, column ) | Reorder the set of records by column | 17.244329 | 17.052773 | 1.011233 |
if column.sortOn:
# multiple sorts for the click...
columns = [self.columnByAttribute(attr) for attr in column.sortOn]
diff = [(a, b) for a, b in zip(self.sortOrder, columns)
if b is not a[1]]
if not diff:
self.sortOrde... | def SetNewOrder( self, column ) | Set new sorting order based on column, return whether a simple single-column (True) or multiple (False) | 3.267644 | 3.197762 | 1.021853 |
if single_column:
columns = self.sortOrder[:1]
else:
columns = self.sortOrder
for ascending,column in columns[::-1]:
# Python 2.2+ guarantees stable sort, so sort by each column in reverse
# order will order by the assigned columns
... | def reorder(self, single_column=False) | Force a reorder of the displayed items | 10.695555 | 10.518239 | 1.016858 |
self.SetItemCount(len(functions))
self.sorted = functions[:]
self.reorder()
self.Refresh() | def integrateRecords(self, functions) | Integrate records from the loader | 11.255372 | 10.675228 | 1.054345 |
if self.indicated > -1 and item == self.indicated:
return self.indicated_attribute
return None | def OnGetItemAttr(self, item) | Retrieve ListItemAttr for the given item (index) | 8.953276 | 8.435946 | 1.061325 |
# TODO: need to format for rjust and the like...
try:
column = self.columns[col]
value = column.get(self.sorted[item])
except IndexError, err:
return None
else:
if value is None:
return u''
if column.per... | def OnGetItemText(self, item, col) | Retrieve text for the item and column respectively | 4.094922 | 4.193792 | 0.976425 |
coder = rs.RSCoder(255,223)
output = []
while True:
block = input.read(223)
if not block: break
code = coder.encode_fast(block)
output.append(code)
sys.stderr.write(".")
sys.stderr.write("\n")
out = Image.new("L", (rowstride,len(output)))
out.putd... | def encode(input, output_filename) | Encodes the input data with reed-solomon error correction in 223 byte
blocks, and outputs each block along with 32 parity bytes to a new file by
the given filename.
input is a file-like object
The outputted image will be in png format, and will be 255 by x pixels with
one color channel. X is the n... | 4.798587 | 3.907846 | 1.227937 |
scriptname = request.environ.get('SCRIPT_NAME', '').rstrip('/') + '/'
location = urljoin(request.url, urljoin(scriptname, url))
raise HTTPResponse("", status=code, header=dict(Location=location)) | def redirect(url, code=303) | Aborts execution and causes a 303 redirect | 4.835042 | 5.088739 | 0.950145 |
try:
ts = email.utils.parsedate_tz(ims)
return time.mktime(ts[:8] + (0,)) - (ts[9] or 0) - time.timezone
except (TypeError, ValueError, IndexError):
return None | def parse_date(ims) | Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch. | 3.113176 | 2.433165 | 1.279476 |
app = app if app else default_app()
quiet = bool(kargs.get('quiet', False))
# Instantiate server, if it is a class instead of an instance
if isinstance(server, type):
server = server(host=host, port=port, **kargs)
if not isinstance(server, ServerAdapter):
raise RuntimeError("Ser... | def run(app=None, server=WSGIRefServer, host='127.0.0.1', port=8080,
interval=1, reloader=False, **kargs) | Runs bottle as a web server. | 3.33427 | 3.145801 | 1.059911 |
'''
Get a rendered template as a string iterator.
You can use a name, a filename or a template string as first parameter.
'''
if tpl not in TEMPLATES or DEBUG:
settings = kwargs.get('template_settings',{})
lookup = kwargs.get('template_lookup', TEMPLATE_PATH)
if isinstance(tp... | def template(tpl, template_adapter=SimpleTemplate, **kwargs) | Get a rendered template as a string iterator.
You can use a name, a filename or a template string as first parameter. | 3.528089 | 2.768573 | 1.274335 |
if not self._tokens:
self._tokens = list(self.tokenise(self.route))
return self._tokens | def tokens(self) | Return a list of (type, value) tokens. | 5.814641 | 4.641203 | 1.252831 |
''' Split a string into an iterator of (type, value) tokens. '''
match = None
for match in cls.syntax.finditer(route):
pre, name, rex = match.groups()
if pre: yield ('TXT', pre.replace('\\:',':'))
if rex and name: yield ('VAR', (rex, name))
elif na... | def tokenise(cls, route) | Split a string into an iterator of (type, value) tokens. | 4.080812 | 3.622855 | 1.126408 |
''' Return a regexp pattern with named groups '''
out = ''
for token, data in self.tokens():
if token == 'TXT': out += re.escape(data)
elif token == 'VAR': out += '(?P<%s>%s)' % (data[1], data[0])
elif token == 'ANON': out += '(?:%s)' % data
return... | def group_re(self) | Return a regexp pattern with named groups | 4.074936 | 3.48277 | 1.170027 |
''' Return a format string with named fields. '''
if self.static:
return self.route.replace('%','%%')
out, i = '', 0
for token, value in self.tokens():
if token == 'TXT': out += value.replace('%','%%')
elif token == 'ANON': out += '%%(anon%d)s' % i; i+... | def format_str(self) | Return a format string with named fields. | 5.450281 | 4.763824 | 1.144098 |
''' Return true if the route contains dynamic parts '''
if not self._static:
for token, value in self.tokens():
if token != 'TXT':
return True
self._static = True
return False | def is_dynamic(self) | Return true if the route contains dynamic parts | 10.154998 | 7.604009 | 1.33548 |
''' Matches an URL and returns a (handler, target) tuple '''
if uri in self.static:
return self.static[uri], {}
for combined, subroutes in self.dynamic:
match = combined.match(uri)
if not match: continue
target, groups = subroutes[match.lastindex -... | def match(self, uri) | Matches an URL and returns a (handler, target) tuple | 4.546925 | 3.922546 | 1.159177 |
''' Builds an URL out of a named route and some parameters.'''
try:
return self.named[route_name] % args
except KeyError:
raise RouteBuildError("No route found with name '%s'." % route_name) | def build(self, route_name, **args) | Builds an URL out of a named route and some parameters. | 6.347925 | 4.618864 | 1.374348 |
''' Register a new output filter. Whenever bottle hits a handler output
matching `ftype`, `func` is applyed to it. '''
if not isinstance(ftype, type):
raise TypeError("Expected type object, got %s" % type(ftype))
self.castfilter = [(t, f) for (t, f) in self.castfilter if ... | def add_filter(self, ftype, func) | Register a new output filter. Whenever bottle hits a handler output
matching `ftype`, `func` is applyed to it. | 5.974344 | 2.832384 | 2.109299 |
path = path.strip().lstrip('/')
handler, param = self.routes.match(method + ';' + path)
if handler: return handler, param
if method == 'HEAD':
handler, param = self.routes.match('GET;' + path)
if handler: return handler, param
handler, param = sel... | def match_url(self, path, method='GET') | Find a callback bound to a path and a specific HTTP method.
Return (callback, param) tuple or (None, {}).
method: HEAD falls back to GET. HEAD and GET fall back to ALL. | 2.890428 | 2.648315 | 1.091421 |
return '/' + self.routes.build(routename, **kargs).split(';', 1)[1] | def get_url(self, routename, **kargs) | Return a string that matches a named route | 9.760915 | 8.919204 | 1.094371 |
if isinstance(method, str): #TODO: Test this
method = method.split(';')
def wrapper(callback):
paths = [] if path is None else [path.strip().lstrip('/')]
if not paths: # Lets generate the path automatically
paths = yieldroutes(callback)
... | def route(self, path=None, method='GET', **kargs) | Decorator: Bind a function to a GET request path.
If the path parameter is None, the signature of the decorated
function is used to generate the path. See yieldroutes()
for details.
The method parameter (default: GET) specifies the HTTP request
method to lis... | 5.844456 | 5.034378 | 1.160909 |
if isinstance(environ, Request): # Recycle already parsed content
for key in self.__dict__: #TODO: Test this
setattr(self, key, getattr(environ, key))
self.app = app
return
self._GET = self._POST = self._GETPOST = self._COOKIES = None
... | def bind(self, environ, app=None) | Bind a new WSGI enviroment and clear out all previously computed
attributes.
This is done automatically for the global `bottle.request`
instance on every request. | 4.843466 | 4.648223 | 1.042004 |
''' Shift some levels of PATH_INFO into SCRIPT_NAME and return the
moved part. count defaults to 1'''
#/a/b/ /c/d --> 'a','b' 'c','d'
if count == 0: return ''
pathlist = self.path.strip('/').split('/')
scriptlist = self.environ.get('SCRIPT_NAME','/').strip('/').spl... | def path_shift(self, count=1) | Shift some levels of PATH_INFO into SCRIPT_NAME and return the
moved part. count defaults to 1 | 3.525951 | 2.873372 | 1.227112 |
scheme = self.environ.get('wsgi.url_scheme', 'http')
host = self.environ.get('HTTP_X_FORWARDED_HOST', self.environ.get('HTTP_HOST', None))
if not host:
host = self.environ.get('SERVER_NAME')
port = self.environ.get('SERVER_PORT', '80')
if scheme + p... | def url(self) | Full URL as requested by the client (computed).
This value is constructed out of different environment variables
and includes scheme, host, port, scriptname, path and query string. | 2.653369 | 2.688166 | 0.987056 |
if self._POST is None:
save_env = dict() # Build a save environment for cgi
for key in ('REQUEST_METHOD', 'CONTENT_TYPE', 'CONTENT_LENGTH'):
if key in self.environ:
save_env[key] = self.environ[key]
save_env['QUERY_STRING'] = '' # ... | def POST(self) | The HTTP POST body parsed into a MultiDict.
This supports urlencoded and multipart POST requests. Multipart
is commonly used for file uploads and may result in some of the
values beeing cgi.FieldStorage objects instead of strings.
Multiple values per key are possible. S... | 3.502179 | 3.345771 | 1.046748 |
if self._GETPOST is None:
self._GETPOST = MultiDict(self.GET)
self._GETPOST.update(dict(self.POST))
return self._GETPOST | def params(self) | A combined MultiDict with POST and GET parameters. | 4.767863 | 3.116785 | 1.529737 |
value = self.COOKIES.get(*args)
sec = self.app.config['securecookie.key']
dec = cookie_decode(value, sec)
return dec or value | def get_cookie(self, *args) | Return the (decoded) value of a cookie. | 9.067172 | 7.632889 | 1.187908 |
''' Returns a copy of self '''
copy = Response(self.app)
copy.status = self.status
copy.headers = self.headers.copy()
copy.content_type = self.content_type
return copy | def copy(self) | Returns a copy of self | 3.897236 | 4.213048 | 0.925039 |
''' Returns a wsgi conform list of header/value pairs. '''
for c in list(self.COOKIES.values()):
if c.OutputString() not in self.headers.getall('Set-Cookie'):
self.headers.append('Set-Cookie', c.OutputString())
return list(self.headers.iterallitems()) | def wsgiheader(self) | Returns a wsgi conform list of header/value pairs. | 6.860708 | 4.978298 | 1.378123 |
if not isinstance(value, str):
sec = self.app.config['securecookie.key']
value = cookie_encode(value, sec).decode('ascii') #2to3 hack
self.COOKIES[key] = value
for k, v in kargs.items():
self.COOKIES[key][k.replace('_', '-')] = v | def set_cookie(self, key, value, **kargs) | Add a new cookie with various options.
If the cookie value is not a string, a secure cookie is created.
Possible options are:
expires, path, comment, domain, max_age, secure, version, httponly
See http://de.wikipedia.org/wiki/HTTP-Cookie#Aufbau for details | 5.297169 | 5.168912 | 1.024813 |
nodes = ast.parse(_openfile(file_name))
module_imports = get_nodes_by_instance_type(nodes, _ast.Import)
specific_imports = get_nodes_by_instance_type(nodes, _ast.ImportFrom)
assignment_objs = get_nodes_by_instance_type(nodes, _ast.Assign)
call_objects = get_nodes_by_instance_type(nodes, _ast.Call)
ar... | def parse_source_file(file_name) | Parses the AST of Python file for lines containing
references to the argparse module.
returns the collection of ast objects found.
Example client code:
1. parser = ArgumentParser(desc="My help Message")
2. parser.add_argument('filename', help="Name of the file to load")
3. parser.add_argument('-f',... | 3.119188 | 2.666038 | 1.169971 |
if os.path.isfile(script_name):
return script_name
path = os.getenv('PATH', os.defpath).split(os.pathsep)
for folder in path:
if not folder:
continue
fn = os.path.join(folder, script_name)
if os.path.isfile(fn):
return fn
sys.stderr.write('Co... | def _find_script(script_name) | Find the script.
If the input is not a file, then $PATH will be searched. | 2.044689 | 1.985183 | 1.029975 |
try:
from StringIO import StringIO
except ImportError: # Python 3.x
from io import StringIO
# Local imports to avoid hard dependency.
from distutils.version import LooseVersion
import IPython
ipython_version = LooseVersion(IPython.__version__)
if ipython_version < '0.1... | def magic_mprun(self, parameter_s='') | Execute a statement under the line-by-line memory profiler from the
memory_profiler module.
Usage:
%mprun -f func1 -f func2 <statement>
The given statement (which doesn't require quote marks) is run via the
LineProfiler. Profiling is enabled for the functions specified by the -f
options. The... | 3.03329 | 2.79023 | 1.087111 |
opts, stmt = self.parse_options(line, 'r:t:i:c', posix=False, strict=False)
repeat = int(getattr(opts, 'r', 1))
if repeat < 1:
repeat == 1
timeout = int(getattr(opts, 't', 0))
if timeout <= 0:
timeout = None
interval = float(getattr(opts, 'i', 0.1))
include_children = 'c... | def magic_memit(self, line='') | Measure memory usage of a Python statement
Usage, in line mode:
%memit [-r<R>t<T>i<I>] statement
Options:
-r<R>: repeat the loop iteration <R> times and take the best result.
Default: 1
-t<T>: timeout after <T> seconds. Default: None
-i<I>: Get time information at an interval of I time... | 4.690208 | 4.33295 | 1.082452 |
def wrapper(*args, **kwargs):
prof = LineProfiler()
val = prof(func)(*args, **kwargs)
show_results(prof, stream=stream)
return val
return wrapper | def profile(func, stream=None) | Decorator that will run the function and print a line-by-line profile | 3.191382 | 3.283434 | 0.971965 |
# Make a fake function
func = lambda x: x
func.__module__ = ""
func.__name__ = name
self.add_function(func)
timestamps = []
self.functions[func].append(timestamps)
# A new object is required each time, since there can be several
# nested c... | def timestamp(self, name="<block>") | Returns a context manager for timestamping a block of code. | 9.765952 | 9.100657 | 1.073104 |
def f(*args, **kwds):
# Start time
timestamps = [_get_memory(os.getpid(), timestamps=True)]
self.functions[func].append(timestamps)
try:
result = func(*args, **kwds)
finally:
# end time
timestamp... | def wrap_function(self, func) | Wrap a function to timestamp it. | 4.210369 | 3.909978 | 1.076827 |
try:
# func_code does not exist in Python3
code = func.__code__
except AttributeError:
warnings.warn("Could not extract a code object for the object %r"
% func)
else:
self.add_code(code) | def add_function(self, func) | Record line profiling information for the given Python function. | 5.862978 | 5.870824 | 0.998663 |
# TODO: can this be removed ?
import __main__
main_dict = __main__.__dict__
return self.runctx(cmd, main_dict, main_dict) | def run(self, cmd) | Profile a single executable statement in the main namespace. | 6.819892 | 5.162902 | 1.320942 |
if (event in ('call', 'line', 'return')
and frame.f_code in self.code_map):
if event != 'call':
# "call" event just saves the lineno but not the memory
mem = _get_memory(-1, include_children=self.include_children)
# if there is... | def trace_memory_usage(self, frame, event, arg) | Callback for sys.settrace | 3.703824 | 3.682633 | 1.005754 |
if key not in self.roots:
function = getattr( self, 'load_%s'%(key,) )()
self.roots[key] = function
return self.roots[key] | def get_root( self, key ) | Retrieve a given declared root by root-type-key | 4.676908 | 4.326897 | 1.080892 |
if key not in self.roots:
self.get_root( key )
if key == 'location':
return self.location_rows
else:
return self.rows | def get_rows( self, key ) | Get the set of rows for the type-key | 5.815804 | 5.278369 | 1.101818 |
rows = self.rows
for func, raw in stats.iteritems():
try:
rows[func] = row = PStatRow( func,raw )
except ValueError, err:
log.info( 'Null row: %s', func )
for row in rows.itervalues():
row.weave( rows )
return s... | def load( self, stats ) | Build a squaremap-compatible model from a pstats class | 7.979507 | 7.246982 | 1.10108 |
maxes = sorted( rows.values(), key = lambda x: x.cumulative )
if not maxes:
raise RuntimeError( )
root = maxes[-1]
roots = [root]
for key,value in rows.items():
if not value.parents:
log.debug( 'Found node root: %s', value )
... | def find_root( self, rows ) | Attempt to find/create a reasonable root node from list/set of rows
rows -- key: PStatRow mapping
TODO: still need more robustness here, particularly in the case of
threaded programs. Should be tracing back each row to root, breaking
cycles by sorting on cumulative time, and then coll... | 7.341507 | 6.313819 | 1.162768 |
directories = {}
files = {}
root = PStatLocation( '/', 'PYTHONPATH' )
self.location_rows = self.rows.copy()
for child in self.rows.values():
current = directories.get( child.directory )
directory, filename = child.directory, child.filename
... | def _load_location( self ) | Build a squaremap-compatible model for location-based hierarchy | 3.150551 | 3.161282 | 0.996606 |
if already_done is None:
already_done = {}
if already_done.has_key( self ):
return True
already_done[self] = True
self.filter_children()
children = self.children
for child in children:
if hasattr( child, 'finalize' ):
... | def finalize( self, already_done=None ) | Finalize our values (recursively) taken from our children | 3.722179 | 3.438693 | 1.08244 |
for field,local_field in (('recursive','calls'),('cumulative','local')):
values = []
for child in children:
if isinstance( child, PStatGroup ) or not self.LOCAL_ONLY:
values.append( getattr( child, field, 0 ) )
elif isinstance(... | def calculate_totals( self, children, local_children=None ) | Calculate our cumulative totals from children and/or local children | 3.465912 | 3.3664 | 1.02956 |
real_children = []
for child in self.children:
if child.name == '<module>':
self.local_children.append( child )
else:
real_children.append( child )
self.children = real_children | def filter_children( self ) | Filter our children into regular and local children sets | 3.455932 | 2.547878 | 1.356396 |
if w >= h:
new_w = int(w*fraction)
if new_w:
return (x,y,new_w,h),(x+new_w,y,w-new_w,h)
else:
return None,None
else:
new_h = int(h*fraction)
if new_h:
return (x,y,w,new_h),(x,y+new_h,w,h-new_h)
else:
return None... | def split_box( fraction, x,y, w,h ) | Return set of two boxes where first is the fraction given | 1.674268 | 1.674961 | 0.999586 |
head_sum,tail_sum = 0,0
divider = 0
for node in nodes[::-1]:
if head_sum < total/headdivisor:
head_sum += node[0]
divider -= 1
else:
break
return (head_sum,nodes[divider:]),(total-head_sum,nodes[:divider]) | def split_by_value( total, nodes, headdivisor=2.0 ) | Produce, (sum,head),(sum,tail) for nodes to attempt binary partition | 3.352624 | 3.021542 | 1.109574 |
''' Find the target node in the hot_map. '''
for index, (rect, node, children) in enumerate(hot_map):
if node == targetNode:
return parentNode, hot_map, index
result = class_.findNode(children, targetNode, node)
if result:
return result... | def findNode(class_, hot_map, targetNode, parentNode=None) | Find the target node in the hot_map. | 3.99205 | 4.096636 | 0.97447 |
''' Return the first child of the node indicated by index. '''
children = hot_map[index][2]
if children:
return children[0][1]
else:
return hot_map[index][1] | def firstChild(hot_map, index) | Return the first child of the node indicated by index. | 3.760855 | 3.431812 | 1.09588 |
''' Return the next sibling of the node indicated by index. '''
nextChildIndex = min(index + 1, len(hotmap) - 1)
return hotmap[nextChildIndex][1] | def nextChild(hotmap, index) | Return the next sibling of the node indicated by index. | 4.440754 | 3.900794 | 1.138423 |
''' Return the very last node (recursively) in the hot map. '''
children = hot_map[-1][2]
if children:
return class_.lastNode(children)
else:
return hot_map[-1][1] | def lastNode(class_, hot_map) | Return the very last node (recursively) in the hot map. | 5.370416 | 3.860987 | 1.390944 |
node = HotMapNavigator.findNodeAtPosition(self.hot_map, event.GetPosition())
self.SetHighlight( node, event.GetPosition() ) | def OnMouse( self, event ) | Handle mouse-move event by selecting a given element | 15.472817 | 12.799093 | 1.208899 |
node = HotMapNavigator.findNodeAtPosition(self.hot_map, event.GetPosition())
self.SetSelected( node, event.GetPosition() ) | def OnClickRelease( self, event ) | Release over a given square in the map | 15.831494 | 11.541183 | 1.371739 |
node = HotMapNavigator.findNodeAtPosition(self.hot_map, event.GetPosition())
if node:
wx.PostEvent( self, SquareActivationEvent( node=node, point=event.GetPosition(), map=self ) ) | def OnDoubleClick(self, event) | Double click on a given square in the map | 10.918435 | 8.669694 | 1.25938 |
if node == self.selectedNode:
return
self.selectedNode = node
self.UpdateDrawing()
if node:
wx.PostEvent( self, SquareSelectionEvent( node=node, point=point, map=self ) ) | def SetSelected( self, node, point=None, propagate=True ) | Set the given node selected in the square-map | 5.502754 | 4.15998 | 1.322784 |
if node == self.highlightedNode:
return
self.highlightedNode = node
# TODO: restrict refresh to the squares for previous node and new node...
self.UpdateDrawing()
if node and propagate:
wx.PostEvent( self, SquareHighlightEvent( node=node, point=po... | def SetHighlight( self, node, point=None, propagate=True ) | Set the currently-highlighted node | 9.359261 | 8.460971 | 1.106169 |
self.model = model
if adapter is not None:
self.adapter = adapter
self.UpdateDrawing() | def SetModel( self, model, adapter=None ) | Set our model object (root of the tree) | 4.74937 | 3.879287 | 1.224289 |
''' Draw the tree map on the device context. '''
self.hot_map = []
dc.BeginDrawing()
brush = wx.Brush( self.BackgroundColour )
dc.SetBackground( brush )
dc.Clear()
if self.model:
self.max_depth_seen = 0
font = self.FontForLabels(dc)
... | def Draw(self, dc) | Draw the tree map on the device context. | 5.437985 | 4.859533 | 1.119034 |
''' Return the default GUI font, scaled for printing if necessary. '''
font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
scale = dc.GetPPI()[0] / wx.ScreenDC().GetPPI()[0]
font.SetPointSize(scale*font.GetPointSize())
return font | def FontForLabels(self, dc) | Return the default GUI font, scaled for printing if necessary. | 3.79028 | 2.579908 | 1.469153 |
if node == self.selectedNode:
color = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)
elif node == self.highlightedNode:
color = wx.Colour( red=0, green=255, blue=0 )
else:
color = self.adapter.background_color(node, depth)
if not col... | def BrushForNode( self, node, depth=0 ) | Create brush to use to display the given node | 2.833997 | 2.793285 | 1.014575 |
if node == self.selectedNode:
return self.SELECTED_PEN
return self.DEFAULT_PEN | def PenForNode( self, node, depth=0 ) | Determine the pen to use to display the given node | 6.536179 | 5.172905 | 1.263541 |
if node == self.selectedNode:
fg_color = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT)
else:
fg_color = self.adapter.foreground_color(node, depth)
if not fg_color:
fg_color = wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOWTEXT)
... | def TextForegroundForNode(self, node, depth=0) | Determine the text foreground color to use to display the label of
the given node | 2.276656 | 2.351302 | 0.968253 |
log.debug( 'Draw: %s to (%s,%s,%s,%s) depth %s',
node, x,y,w,h, depth,
)
if self.max_depth and depth > self.max_depth:
return
self.max_depth_seen = max( (self.max_depth_seen,depth))
dc.SetBrush( self.BrushForNode( node, depth ) )
dc.SetPen... | def DrawBox( self, dc, node, x,y,w,h, hot_map, depth=0 ) | Draw a model-node's box and all children nodes | 2.717042 | 2.696659 | 1.007559 |
''' Draw the icon, if any, and the label, if any, of the node. '''
if w-2 < self._em_size_//2 or h-2 < self._em_size_ //2:
return
dc.SetClippingRegion(x+1, y+1, w-2, h-2) # Don't draw outside the box
try:
icon = self.adapter.icon(node, node==self.selectedNode)
... | def DrawIconAndLabel(self, dc, node, x, y, w, h, depth) | Draw the icon, if any, and the label, if any, of the node. | 3.553747 | 3.371441 | 1.054074 |
if node_sum is None:
nodes = [ (self.adapter.value(node,parent),node) for node in children ]
nodes.sort(key=operator.itemgetter(0))
total = self.adapter.children_sum( children,parent )
else:
nodes = children
total = node_sum
if... | def LayoutChildren( self, dc, children, parent, x,y,w,h, hot_map, depth=0, node_sum=None ) | Layout the set of children in the given rectangle
node_sum -- if provided, we are a recursive call that already has sizes and sorting,
so skip those operations | 3.399405 | 3.373193 | 1.007771 |
return sum( [self.value(value,node) for value in self.children(node)] ) | def overall( self, node ) | Calculate overall size of the node including children and empty space | 7.988488 | 6.607059 | 1.209084 |
return sum( [self.value(value,node) for value in children] ) | def children_sum( self, children,node ) | Calculate children's total sum | 6.947877 | 5.553824 | 1.251008 |
overall = self.overall( node )
if overall:
return (overall - self.children_sum( self.children(node), node))/float(overall)
return 0 | def empty( self, node ) | Calculate empty space as a fraction of total space | 9.479733 | 7.014464 | 1.351455 |
'''Readable size format, courtesy of Sridhar Ratnakumar'''
for unit in ['','K','M','G','T','P','E','Z']:
if abs(num) < 1000.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1000.0
return "%.1f%s%s" % (num, 'Y', suffix) | def format_sizeof(num, suffix='bytes') | Readable size format, courtesy of Sridhar Ratnakumar | 2.411115 | 1.586616 | 1.519658 |
if n < 1:
n = 1
self.n += n
delta_it = self.n - self.last_print_n
if delta >= self.miniters:
# We check the counter first, to reduce the overhead of time.time()
cur_t = time.time()
if cur_t - self.last_print_t >= self.mininterval:... | def update(self, n=1) | Manually update the progress bar, useful for streams such as reading files (set init(total=filesize) and then in the reading loop, use update(len(current_buffer)) )
Parameters
----------
n : int
Increment to add to the internal counter of iterations. | 4.287746 | 3.926328 | 1.09205 |
if self.leave:
if self.last_print_n < self.n:
cur_t = time.time()
self.sp.print_status(format_meter(self.n, self.total, cur_t-self.start_t, self.ncols, self.prefix, self.unit, self.unit_format, self.ascii))
self.file.write('\n')
else:
... | def close(self) | Call this method to force print the last progress bar update based on the latest n value | 5.675711 | 4.737284 | 1.198094 |
if value not in self._set:
self._set.add(value)
self._list.add(value) | def add(self, value) | Add the element *value* to the set. | 3.611907 | 2.836122 | 1.273537 |
return self.__class__(key=self._key, load=self._load, _set=set(self._set)) | def copy(self) | Create a shallow copy of the sorted set. | 9.535844 | 6.702809 | 1.422664 |
diff = self._set.difference(*iterables)
new_set = self.__class__(key=self._key, load=self._load, _set=diff)
return new_set | def difference(self, *iterables) | Return a new set with elements in the set that are not in the
*iterables*. | 4.345424 | 4.292125 | 1.012418 |
comb = self._set.intersection(*iterables)
new_set = self.__class__(key=self._key, load=self._load, _set=comb)
return new_set | def intersection(self, *iterables) | Return a new set with elements common to the set and all *iterables*. | 4.907929 | 4.110765 | 1.193921 |
diff = self._set.symmetric_difference(that)
new_set = self.__class__(key=self._key, load=self._load, _set=diff)
return new_set | def symmetric_difference(self, that) | Return a new set with elements in either *self* or *that* but not both. | 4.506699 | 3.719363 | 1.211686 |
''' Verify and decode an encoded string. Return an object or None'''
if isinstance(data, unicode): data = data.encode('ascii') #2to3 hack
if cookie_is_encoded(data):
sig, msg = data.split(u'?'.encode('ascii'),1) #2to3 hack
if sig[1:] == base64.b64encode(hmac.new(key, msg).digest()):
... | def cookie_decode(data, key) | Verify and decode an encoded string. Return an object or None | 5.146791 | 4.112186 | 1.251595 |
''' Verify and decode an encoded string. Return an object or None'''
return bool(data.startswith(u'!'.encode('ascii')) and u'?'.encode('ascii') in data) | def cookie_is_encoded(data) | Verify and decode an encoded string. Return an object or None | 13.10668 | 5.919425 | 2.214181 |
''' Returns a function that turns everything into 'native' strings using enc '''
if sys.version_info >= (3,0,0):
return lambda x: x.decode(enc) if isinstance(x, bytes) else str(x)
return lambda x: x.encode(enc) if isinstance(x, unicode) else str(x) | def tonativefunc(enc='utf-8') | Returns a function that turns everything into 'native' strings using enc | 2.995299 | 2.18989 | 1.367785 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.