_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q9900 | PENMANCodec.handle_triple | train | def handle_triple(self, lhs, relation, rhs):
"""
Process triples before they are added to the graph.
Note that *lhs* and *rhs* are as they originally appeared, and
may be inverted. Inversions are detected by
is_relation_inverted() and de-inverted by invert_relation().
B... | python | {
"resource": ""
} |
q9901 | PENMANCodec._encode_penman | train | def _encode_penman(self, g, top=None):
"""
Walk graph g and find a spanning dag, then serialize the result.
First, depth-first traversal of preferred orientations (whether
true or inverted) to create graph p.
If any triples remain, select the first remaining triple whose
... | python | {
"resource": ""
} |
q9902 | Graph.reentrancies | train | def reentrancies(self):
"""
Return a mapping of variables to their re-entrancy count.
A re-entrancy is when more than one edge selects a node as its
target. These graphs are rooted, so the top node always has an
implicit entrancy. Only nodes with re-entrancies are reported,
... | python | {
"resource": ""
} |
q9903 | check_1d | train | def check_1d(inp):
"""
Check input to be a vector. Converts lists to np.ndarray.
Parameters
----------
inp : obj
Input vector
Returns
-------
numpy.ndarray or None
Input vector or None
Examples
--------
>>> check_1d([0, 1, 2, 3])
[0, 1, 2, 3]
>>> c... | python | {
"resource": ""
} |
q9904 | check_2d | train | def check_2d(inp):
"""
Check input to be a matrix. Converts lists of lists to np.ndarray.
Also allows the input to be a scipy sparse matrix.
Parameters
----------
inp : obj
Input matrix
Returns
-------
numpy.ndarray, scipy.sparse or None
Input matrix or None
... | python | {
"resource": ""
} |
q9905 | graph_to_laplacian | train | def graph_to_laplacian(G, normalized=True):
"""
Converts a graph from popular Python packages to Laplacian representation.
Currently support NetworkX, graph_tool and igraph.
Parameters
----------
G : obj
Input graph
normalized : bool
Whether to use normalized Laplacian.... | python | {
"resource": ""
} |
q9906 | netlsd | train | def netlsd(inp, timescales=np.logspace(-2, 2, 250), kernel='heat', eigenvalues='auto', normalization='empty', normalized_laplacian=True):
"""
Computes NetLSD signature from some given input, timescales, and normalization.
Accepts matrices, common Python graph libraries' graphs, or vectors of eigenvalues.
... | python | {
"resource": ""
} |
q9907 | heat | train | def heat(inp, timescales=np.logspace(-2, 2, 250), eigenvalues='auto', normalization='empty', normalized_laplacian=True):
"""
Computes heat kernel trace from some given input, timescales, and normalization.
Accepts matrices, common Python graph libraries' graphs, or vectors of eigenvalues.
For precise ... | python | {
"resource": ""
} |
q9908 | wave | train | def wave(inp, timescales=np.linspace(0, 2*np.pi, 250), eigenvalues='auto', normalization='empty', normalized_laplacian=True):
"""
Computes wave kernel trace from some given input, timescales, and normalization.
Accepts matrices, common Python graph libraries' graphs, or vectors of eigenvalues.
For pre... | python | {
"resource": ""
} |
q9909 | _hkt | train | def _hkt(eivals, timescales, normalization, normalized_laplacian):
"""
Computes heat kernel trace from given eigenvalues, timescales, and normalization.
For precise definition, please refer to "NetLSD: Hearing the Shape of a Graph" by A. Tsitsulin, D. Mottin, P. Karras, A. Bronstein, E. Müller. Published a... | python | {
"resource": ""
} |
q9910 | _wkt | train | def _wkt(eivals, timescales, normalization, normalized_laplacian):
"""
Computes wave kernel trace from given eigenvalues, timescales, and normalization.
For precise definition, please refer to "NetLSD: Hearing the Shape of a Graph" by A. Tsitsulin, D. Mottin, P. Karras, A. Bronstein, E. Müller. Published a... | python | {
"resource": ""
} |
q9911 | SortedListWithKey.clear | train | def clear(self):
"""Remove all the elements from the list."""
self._len = 0
del self._maxes[:]
del self._lists[:]
del self._keys[:]
del self._index[:] | python | {
"resource": ""
} |
q9912 | SortedListWithKey.islice | train | def islice(self, start=None, stop=None, reverse=False):
"""
Returns an iterator that slices `self` from `start` to `stop` index,
inclusive and exclusive respectively.
When `reverse` is `True`, values are yielded from the iterator in
reverse order.
Both `start` and `stop... | python | {
"resource": ""
} |
q9913 | SortedListWithKey.copy | train | def copy(self):
"""Return a shallow copy of the sorted list."""
return self.__class__(self, key=self._key, load=self._load) | python | {
"resource": ""
} |
q9914 | not26 | train | def not26(func):
"""Function decorator for methods not implemented in Python 2.6."""
@wraps(func)
def errfunc(*args, **kwargs):
raise NotImplementedError
if hexversion < 0x02070000:
return errfunc
else:
return func | python | {
"resource": ""
} |
q9915 | SortedDict.copy | train | def copy(self):
"""Return a shallow copy of the sorted dictionary."""
return self.__class__(self._key, self._load, self._iteritems()) | python | {
"resource": ""
} |
q9916 | SummaryTracker.create_summary | train | def create_summary(self):
"""Return a summary.
See also the notes on ignore_self in the class as well as the
initializer documentation.
"""
if not self.ignore_self:
res = summary.summarize(muppy.get_objects())
else:
# If the user requested the da... | python | {
"resource": ""
} |
q9917 | SummaryTracker.diff | train | def diff(self, summary1=None, summary2=None):
"""Compute diff between to summaries.
If no summary is provided, the diff from the last to the current
summary is used. If summary1 is provided the diff from summary1
to the current summary is used. If summary1 and summary2 are
provi... | python | {
"resource": ""
} |
q9918 | SummaryTracker.print_diff | train | def print_diff(self, summary1=None, summary2=None):
"""Compute diff between to summaries and print it.
If no summary is provided, the diff from the last to the current
summary is used. If summary1 is provided the diff from summary1
to the current summary is used. If summary1 and summary... | python | {
"resource": ""
} |
q9919 | ObjectTracker._get_objects | train | def _get_objects(self, ignore=[]):
"""Get all currently existing objects.
XXX - ToDo: This method is a copy&paste from muppy.get_objects, but
some modifications are applied. Specifically, it allows to ignore
objects (which includes the current frame).
keyword arguments
... | python | {
"resource": ""
} |
q9920 | ObjectTracker.get_diff | train | def get_diff(self, ignore=[]):
"""Get the diff to the last time the state of objects was measured.
keyword arguments
ignore -- list of objects to ignore
"""
# ignore this and the caller frame
ignore.append(inspect.currentframe()) #PYCHOK change ignore
self.o1 = ... | python | {
"resource": ""
} |
q9921 | ObjectTracker.print_diff | train | def print_diff(self, ignore=[]):
"""Print the diff to the last time the state of objects was measured.
keyword arguments
ignore -- list of objects to ignore
"""
# ignore this and the caller frame
ignore.append(inspect.currentframe()) #PYCHOK change ignore
diff = ... | python | {
"resource": ""
} |
q9922 | jaccard | train | def jaccard(seq1, seq2):
"""Compute the Jaccard distance between the two sequences `seq1` and `seq2`.
They should contain hashable items.
The return value is a float between 0 and 1, where 0 means equal, and 1 totally different.
"""
set1, set2 = set(seq1), set(seq2)
return 1 - len(set1 & set2) / float(len(set1 ... | python | {
"resource": ""
} |
q9923 | sorensen | train | def sorensen(seq1, seq2):
"""Compute the Sorensen distance between the two sequences `seq1` and `seq2`.
They should contain hashable items.
The return value is a float between 0 and 1, where 0 means equal, and 1 totally different.
"""
set1, set2 = set(seq1), set(seq2)
return 1 - (2 * len(set1 & set2) / float(le... | python | {
"resource": ""
} |
q9924 | _long2bytes | train | def _long2bytes(n, blocksize=0):
"""Convert a long integer to a byte string.
If optional blocksize is given and greater than zero, pad the front
of the byte string with binary zeros so that the length is a multiple
of blocksize.
"""
# After much testing, this algorithm was deemed to be... | python | {
"resource": ""
} |
q9925 | MD5.init | train | def init(self):
"Initialize the message-digest and set all fields to zero."
self.length = 0L
self.input = []
# Load magic initialization constants.
self.A = 0x67452301L
self.B = 0xefcdab89L
self.C = 0x98badcfeL
self.D = 0x10325476L | python | {
"resource": ""
} |
q9926 | MeliaeAdapter.value | train | def value( self, node, parent=None ):
"""Return value used to compare size of this node"""
# this is the *weighted* size/contribution of the node
try:
return node['contribution']
except KeyError, err:
contribution = int(node.get('totsize',0)/float( len(node.get('... | python | {
"resource": ""
} |
q9927 | MeliaeAdapter.label | train | def label( self, node ):
"""Return textual description of this node"""
result = []
if node.get('type'):
result.append( node['type'] )
if node.get('name' ):
result.append( node['name'] )
elif node.get('value') is not None:
result.append( unicode... | python | {
"resource": ""
} |
q9928 | MeliaeAdapter.best_parent | train | def best_parent( self, node, tree_type=None ):
"""Choose the best parent for a given node"""
parents = self.parents(node)
selected_parent = None
if node['type'] == 'type':
module = ".".join( node['name'].split( '.' )[:-1] )
if module:
for mod in pa... | python | {
"resource": ""
} |
q9929 | Stats.load_stats | train | def load_stats(self, fdump):
"""
Load the data from a dump file.
The argument `fdump` can be either a filename or an open file object
that requires read access.
"""
if isinstance(fdump, type('')):
fdump = open(fdump, 'rb')
self.index = pickle.load(fdum... | python | {
"resource": ""
} |
q9930 | Stats.annotate_snapshot | train | def annotate_snapshot(self, snapshot):
"""
Store additional statistical data in snapshot.
"""
if hasattr(snapshot, 'classes'):
return
snapshot.classes = {}
for classname in list(self.index.keys()):
total = 0
active = 0
mer... | python | {
"resource": ""
} |
q9931 | ConsoleStats.print_object | train | def print_object(self, tobj):
"""
Print the gathered information of object `tobj` in human-readable format.
"""
if tobj.death:
self.stream.write('%-32s ( free ) %-35s\n' % (
trunc(tobj.name, 32, left=1), trunc(tobj.repr, 35)))
else:
self.... | python | {
"resource": ""
} |
q9932 | ConsoleStats.print_stats | train | def print_stats(self, clsname=None, limit=1.0):
"""
Write tracked objects to stdout. The output can be filtered and
pruned. Only objects are printed whose classname contain the substring
supplied by the `clsname` argument. The output can be pruned by
passing a `limit` value.
... | python | {
"resource": ""
} |
q9933 | ConsoleStats.print_summary | train | def print_summary(self):
"""
Print per-class summary for each snapshot.
"""
# Emit class summaries for each snapshot
classlist = self.tracked_classes
fobj = self.stream
fobj.write('---- SUMMARY '+'-'*66+'\n')
for snapshot in self.snapshots:
s... | python | {
"resource": ""
} |
q9934 | HtmlStats.print_class_details | train | def print_class_details(self, fname, classname):
"""
Print detailed statistics and instances for the class `classname`. All
data will be written to the file `fname`.
"""
fobj = open(fname, "w")
fobj.write(self.header % (classname, self.style))
fobj.write("<h1>%s<... | python | {
"resource": ""
} |
q9935 | HtmlStats.relative_path | train | def relative_path(self, filepath, basepath=None):
"""
Convert the filepath path to a relative path against basepath. By
default basepath is self.basedir.
"""
if basepath is None:
basepath = self.basedir
if not basepath:
return filepath
if f... | python | {
"resource": ""
} |
q9936 | HtmlStats.create_title_page | train | def create_title_page(self, filename, title=''):
"""
Output the title page.
"""
fobj = open(filename, "w")
fobj.write(self.header % (title, self.style))
fobj.write("<h1>%s</h1>\n" % title)
fobj.write("<h2>Memory distribution over time</h2>\n")
fobj.write(... | python | {
"resource": ""
} |
q9937 | HtmlStats.create_lifetime_chart | train | def create_lifetime_chart(self, classname, filename=''):
"""
Create chart that depicts the lifetime of the instance registered with
`classname`. The output is written to `filename`.
"""
try:
from pylab import figure, title, xlabel, ylabel, plot, savefig
except... | python | {
"resource": ""
} |
q9938 | HtmlStats.create_snapshot_chart | train | def create_snapshot_chart(self, filename=''):
"""
Create chart that depicts the memory allocation over time apportioned to
the tracked classes.
"""
try:
from pylab import figure, title, xlabel, ylabel, plot, fill, legend, savefig
import matplotlib.mlab as ... | python | {
"resource": ""
} |
q9939 | HtmlStats.create_pie_chart | train | def create_pie_chart(self, snapshot, filename=''):
"""
Create a pie chart that depicts the distribution of the allocated memory
for a given `snapshot`. The chart is saved to `filename`.
"""
try:
from pylab import figure, title, pie, axes, savefig
from pyla... | python | {
"resource": ""
} |
q9940 | HtmlStats.create_html | train | def create_html(self, fname, title="ClassTracker Statistics"):
"""
Create HTML page `fname` and additional files in a directory derived
from `fname`.
"""
# Create a folder to store the charts and additional HTML files.
self.basedir = os.path.dirname(os.path.abspath(fname)... | python | {
"resource": ""
} |
q9941 | Path.write_bytes | train | def write_bytes(self, data):
"""
Open the file in bytes mode, write to it, and close the file.
"""
if not isinstance(data, six.binary_type):
raise TypeError(
'data must be %s, not %s' %
(six.binary_type.__class__.__name__, data.__class__.__name... | python | {
"resource": ""
} |
q9942 | Path.write_text | train | def write_text(self, data, encoding=None, errors=None):
"""
Open the file in text mode, write to it, and close the file.
"""
if not isinstance(data, six.text_type):
raise TypeError(
'data must be %s, not %s' %
(six.text_type.__class__.__name__,... | python | {
"resource": ""
} |
q9943 | sort_group | train | def sort_group(d, return_only_first=False):
''' Sort a dictionary of relative paths and cluster equal paths together at the same time '''
# First, sort the paths in order (this must be a couple: (parent_dir, filename), so that there's no ambiguity because else a file at root will be considered as being after a ... | python | {
"resource": ""
} |
q9944 | RefBrowser.get_tree | train | def get_tree(self):
"""Get a tree of referrers of the root object."""
self.ignore.append(inspect.currentframe())
return self._get_tree(self.root, self.maxdepth) | python | {
"resource": ""
} |
q9945 | RefBrowser._get_tree | train | def _get_tree(self, root, maxdepth):
"""Workhorse of the get_tree implementation.
This is an recursive method which is why we have a wrapper method.
root is the current root object of the tree which should be returned.
Note that root is not of the type _Node.
maxdepth defines ho... | python | {
"resource": ""
} |
q9946 | StreamBrowser.print_tree | train | def print_tree(self, tree=None):
""" Print referrers tree to console.
keyword arguments
tree -- if not None, the passed tree will be printed. Otherwise it is
based on the rootobject.
"""
if tree is None:
self._print(self.root, '', '')
else:
... | python | {
"resource": ""
} |
q9947 | StreamBrowser._print | train | def _print(self, tree, prefix, carryon):
"""Compute and print a new line of the tree.
This is a recursive function.
arguments
tree -- tree to print
prefix -- prefix to the current line to print
carryon -- prefix which is used to carry on the vertical lines
"""
... | python | {
"resource": ""
} |
q9948 | InteractiveBrowser.main | train | def main(self, standalone=False):
"""Create interactive browser window.
keyword arguments
standalone -- Set to true, if the browser is not attached to other
windows
"""
window = _Tkinter.Tk()
sc = _TreeWidget.ScrolledCanvas(window, bg="white",\
... | python | {
"resource": ""
} |
q9949 | format_meter | train | def format_meter(n, total, elapsed, ncols=None, prefix='',
unit=None, unit_scale=False, ascii=False):
"""
Return a string-based progress bar given some parameters
Parameters
----------
n : int
Number of finished iterations.
total : int
The expected total number of ite... | python | {
"resource": ""
} |
q9950 | getIcon | train | def getIcon( data ):
"""Return the data from the resource as a wxIcon"""
import cStringIO
stream = cStringIO.StringIO(data)
image = wx.ImageFromStream(stream)
icon = wx.EmptyIcon()
icon.CopyFromBitmap(wx.BitmapFromImage(image))
return icon | python | {
"resource": ""
} |
q9951 | main | train | def main():
"""Mainloop for the application"""
logging.basicConfig(level=logging.INFO)
app = RunSnakeRunApp(0)
app.MainLoop() | python | {
"resource": ""
} |
q9952 | MainFrame.CreateMenuBar | train | def CreateMenuBar(self):
"""Create our menu-bar for triggering operations"""
menubar = wx.MenuBar()
menu = wx.Menu()
menu.Append(ID_OPEN, _('&Open Profile'), _('Open a cProfile file'))
menu.Append(ID_OPEN_MEMORY, _('Open &Memory'), _('Open a Meliae memory-dump file'))
men... | python | {
"resource": ""
} |
q9953 | MainFrame.CreateSourceWindow | train | def CreateSourceWindow(self, tabs):
"""Create our source-view window for tabs"""
if editor and self.sourceCodeControl is None:
self.sourceCodeControl = wx.py.editwindow.EditWindow(
self.tabs, -1
)
self.sourceCodeControl.SetText(u"")
self.so... | python | {
"resource": ""
} |
q9954 | MainFrame.SetupToolBar | train | def SetupToolBar(self):
"""Create the toolbar for common actions"""
tb = self.CreateToolBar(self.TBFLAGS)
tsize = (24, 24)
tb.ToolBitmapSize = tsize
open_bmp = wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN, wx.ART_TOOLBAR,
tsize)
tb... | python | {
"resource": ""
} |
q9955 | MainFrame.OnViewTypeTool | train | def OnViewTypeTool( self, event ):
"""When the user changes the selection, make that our selection"""
new = self.viewTypeTool.GetStringSelection()
if new != self.viewType:
self.viewType = new
self.OnRootView( event ) | python | {
"resource": ""
} |
q9956 | MainFrame.SetPercentageView | train | def SetPercentageView(self, percentageView):
"""Set whether to display percentage or absolute values"""
self.percentageView = percentageView
self.percentageMenuItem.Check(self.percentageView)
self.percentageViewTool.SetValue(self.percentageView)
total = self.adapter.value( self.l... | python | {
"resource": ""
} |
q9957 | MainFrame.OnUpView | train | def OnUpView(self, event):
"""Request to move up the hierarchy to highest-weight parent"""
node = self.activated_node
parents = []
selected_parent = None
if node:
if hasattr( self.adapter, 'best_parent' ):
selected_parent = self.adapter.best_p... | python | {
"resource": ""
} |
q9958 | MainFrame.OnBackView | train | def OnBackView(self, event):
"""Request to move backward in the history"""
self.historyIndex -= 1
try:
self.RestoreHistory(self.history[self.historyIndex])
except IndexError, err:
self.SetStatusText(_('No further history available')) | python | {
"resource": ""
} |
q9959 | MainFrame.OnRootView | train | def OnRootView(self, event):
"""Reset view to the root of the tree"""
self.adapter, tree, rows = self.RootNode()
self.squareMap.SetModel(tree, self.adapter)
self.RecordHistory()
self.ConfigureViewTypeChoices() | python | {
"resource": ""
} |
q9960 | MainFrame.OnNodeActivated | train | def OnNodeActivated(self, event):
"""Double-click or enter on a node in some control..."""
self.activated_node = self.selected_node = event.node
self.squareMap.SetModel(event.node, self.adapter)
self.squareMap.SetSelected( event.node )
if editor:
if self.SourceShowFil... | python | {
"resource": ""
} |
q9961 | MainFrame.RecordHistory | train | def RecordHistory(self):
"""Add the given node to the history-set"""
if not self.restoringHistory:
record = self.activated_node
if self.historyIndex < -1:
try:
del self.history[self.historyIndex+1:]
except AttributeError, err:
... | python | {
"resource": ""
} |
q9962 | MainFrame.RootNode | train | def RootNode(self):
"""Return our current root node and appropriate adapter for it"""
tree = self.loader.get_root( self.viewType )
adapter = self.loader.get_adapter( self.viewType )
rows = self.loader.get_rows( self.viewType )
adapter.SetPercentage(self.percentageView, a... | python | {
"resource": ""
} |
q9963 | MainFrame.SaveState | train | def SaveState( self, config_parser ):
"""Retrieve window state to be restored on the next run..."""
if not config_parser.has_section( 'window' ):
config_parser.add_section( 'window' )
if self.IsMaximized():
config_parser.set( 'window', 'maximized', str(True))
else... | python | {
"resource": ""
} |
q9964 | MainFrame.LoadState | train | def LoadState( self, config_parser ):
"""Set our window state from the given config_parser instance"""
if not config_parser:
return
if (
not config_parser.has_section( 'window' ) or (
config_parser.has_option( 'window','maximized' ) and
co... | python | {
"resource": ""
} |
q9965 | is_file | train | def is_file(dirname):
'''Checks if a path is an actual file that exists'''
if not os.path.isfile(dirname):
msg = "{0} is not an existing file".format(dirname)
raise argparse.ArgumentTypeError(msg)
else:
return dirname | python | {
"resource": ""
} |
q9966 | is_dir | train | def is_dir(dirname):
'''Checks if a path is an actual directory that exists'''
if not os.path.isdir(dirname):
msg = "{0} is not a directory".format(dirname)
raise argparse.ArgumentTypeError(msg)
else:
return dirname | python | {
"resource": ""
} |
q9967 | is_dir_or_file | train | def is_dir_or_file(dirname):
'''Checks if a path is an actual directory that exists or a file'''
if not os.path.isdir(dirname) and not os.path.isfile(dirname):
msg = "{0} is not a directory nor a file".format(dirname)
raise argparse.ArgumentTypeError(msg)
else:
return dirname | python | {
"resource": ""
} |
q9968 | fullpath | train | def fullpath(relpath):
'''Relative path to absolute'''
if (type(relpath) is object or type(relpath) is file):
relpath = relpath.name
return os.path.abspath(os.path.expanduser(relpath)) | python | {
"resource": ""
} |
q9969 | remove_if_exist | train | def remove_if_exist(path): # pragma: no cover
"""Delete a file or a directory recursively if it exists, else no exception is raised"""
if os.path.exists(path):
if os.path.isdir(path):
shutil.rmtree(path)
return True
elif os.path.isfile(path):
os.remove(path)
... | python | {
"resource": ""
} |
q9970 | copy_any | train | def copy_any(src, dst, only_missing=False): # pragma: no cover
"""Copy a file or a directory tree, deleting the destination before processing"""
if not only_missing:
remove_if_exist(dst)
if os.path.exists(src):
if os.path.isdir(src):
if not only_missing:
shutil.c... | python | {
"resource": ""
} |
q9971 | group_files_by_size | train | def group_files_by_size(fileslist, multi): # pragma: no cover
''' Cluster files into the specified number of groups, where each groups total size is as close as possible to each other.
Pseudo-code (O(n^g) time complexity):
Input: number of groups G per cluster, list of files F with respective sizes
- ... | python | {
"resource": ""
} |
q9972 | group_files_by_size_fast | train | def group_files_by_size_fast(fileslist, nbgroups, mode=1): # pragma: no cover
'''Given a files list with sizes, output a list where the files are grouped in nbgroups per cluster.
Pseudo-code for algorithm in O(n log(g)) (thank's to insertion sort or binary search trees)
See for more infos: http://cs.stack... | python | {
"resource": ""
} |
q9973 | grouped_count_sizes | train | def grouped_count_sizes(fileslist, fgrouped): # pragma: no cover
'''Compute the total size per group and total number of files. Useful to check that everything is OK.'''
fsizes = {}
total_files = 0
allitems = None
if isinstance(fgrouped, dict):
allitems = fgrouped.iteritems()
elif isins... | python | {
"resource": ""
} |
q9974 | ConfigPanel.GetOptions | train | def GetOptions(self):
"""
returns the collective values from all of the
widgets contained in the panel"""
values = [c.GetValue()
for c in chain(*self.widgets)
if c.GetValue() is not None]
return ' '.join(values) | python | {
"resource": ""
} |
q9975 | Positional.GetValue | train | def GetValue(self):
'''
Positionals have no associated options_string,
so only the supplied arguments are returned.
The order is assumed to be the same as the order
of declaration in the client code
Returns
"argument_value"
'''
self.AssertInitialization('Positional')
if str(se... | python | {
"resource": ""
} |
q9976 | Flag.Update | train | def Update(self, size):
'''
Custom wrapper calculator to account for the
increased size of the _msg widget after being
inlined with the wx.CheckBox
'''
if self._msg is None:
return
help_msg = self._msg
width, height = size
content_area = int((width / 3) * .70)
wiggle_room ... | python | {
"resource": ""
} |
q9977 | get_path | train | def get_path(language):
''' Returns the full path to the language file '''
filename = language.lower() + '.json'
lang_file_path = os.path.join(_DEFAULT_DIR, filename)
if not os.path.exists(lang_file_path):
raise IOError('Could not find {} language file'.format(language))
return lang_file_path | python | {
"resource": ""
} |
q9978 | trunc | train | def trunc(obj, max, left=0):
"""
Convert `obj` to string, eliminate newlines and truncate the string to `max`
characters. If there are more characters in the string add ``...`` to the
string. With `left=True`, the string can be truncated at the beginning.
@note: Does not catch exceptions when conve... | python | {
"resource": ""
} |
q9979 | pp | train | def pp(i, base=1024):
"""
Pretty-print the integer `i` as a human-readable size representation.
"""
degree = 0
pattern = "%4d %s"
while i > base:
pattern = "%7.2f %s"
i = i / float(base)
degree += 1
scales = ['B', 'KB', 'MB', 'GB', 'TB', 'EB']
return pattern %... | python | {
"resource": ""
} |
q9980 | pp_timestamp | train | def pp_timestamp(t):
"""
Get a friendly timestamp represented as a string.
"""
if t is None:
return ''
h, m, s = int(t / 3600), int(t / 60 % 60), t % 60
return "%02d:%02d:%05.2f" % (h, m, s) | python | {
"resource": ""
} |
q9981 | GarbageGraph.print_stats | train | def print_stats(self, stream=None):
"""
Log annotated garbage objects to console or file.
:param stream: open file, uses sys.stdout if not given
"""
if not stream: # pragma: no cover
stream = sys.stdout
self.metadata.sort(key=lambda x: -x.size)
stream... | python | {
"resource": ""
} |
q9982 | Profile.disable | train | def disable(self, threads=True):
"""
Disable profiling.
"""
if self.enabled_start:
sys.settrace(None)
self._disable()
else:
warn('Duplicate "disable" call') | python | {
"resource": ""
} |
q9983 | Tee.flush | train | def flush(self):
""" Force commit changes to the file and stdout """
if not self.nostdout:
self.stdout.flush()
if self.file is not None:
self.file.flush() | python | {
"resource": ""
} |
q9984 | PStatsAdapter.parents | train | def parents(self, node):
"""Determine all parents of node in our tree"""
return [
parent for parent in
getattr( node, 'parents', [] )
if getattr(parent, 'tree', self.TREE) == self.TREE
] | python | {
"resource": ""
} |
q9985 | PStatsAdapter.filename | train | def filename( self, node ):
"""Extension to squaremap api to provide "what file is this" information"""
if not node.directory:
# TODO: any cases other than built-ins?
return None
if node.filename == '~':
# TODO: look up C/Cython/whatever source???
... | python | {
"resource": ""
} |
q9986 | get_obj | train | def get_obj(ref):
"""Get object from string reference."""
oid = int(ref)
return server.id2ref.get(oid) or server.id2obj[oid] | python | {
"resource": ""
} |
q9987 | process | train | def process():
"""Get process overview."""
pmi = ProcessMemoryInfo()
threads = get_current_threads()
return dict(info=pmi, threads=threads) | python | {
"resource": ""
} |
q9988 | tracker_index | train | def tracker_index():
"""Get tracker overview."""
stats = server.stats
if stats and stats.snapshots:
stats.annotate()
timeseries = []
for cls in stats.tracked_classes:
series = []
for snapshot in stats.snapshots:
series.append(snapshot.classes.g... | python | {
"resource": ""
} |
q9989 | tracker_class | train | def tracker_class(clsname):
"""Get class instance details."""
stats = server.stats
if not stats:
bottle.redirect('/tracker')
stats.annotate()
return dict(stats=stats, clsname=clsname) | python | {
"resource": ""
} |
q9990 | garbage_cycle | train | def garbage_cycle(index):
"""Get reference cycle details."""
graph = _compute_garbage_graphs()[int(index)]
graph.reduce_to_cycles()
objects = graph.metadata
objects.sort(key=lambda x: -x.size)
return dict(objects=objects, index=index) | python | {
"resource": ""
} |
q9991 | _get_graph | train | def _get_graph(graph, filename):
"""Retrieve or render a graph."""
try:
rendered = graph.rendered_file
except AttributeError:
try:
graph.render(os.path.join(server.tmpdir, filename), format='png')
rendered = filename
except OSError:
rendered = None... | python | {
"resource": ""
} |
q9992 | garbage_graph | train | def garbage_graph(index):
"""Get graph representation of reference cycle."""
graph = _compute_garbage_graphs()[int(index)]
reduce_graph = bottle.request.GET.get('reduce', '')
if reduce_graph:
graph = graph.reduce_to_cycles()
if not graph:
return None
filename = 'garbage%so%s.png'... | python | {
"resource": ""
} |
q9993 | _winreg_getShellFolder | train | def _winreg_getShellFolder( name ):
"""Get a shell folder by string name from the registry"""
k = _winreg.OpenKey(
_winreg.HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
)
try:
# should check that it's valid? How?
return _winreg.Que... | python | {
"resource": ""
} |
q9994 | appdatadirectory | train | def appdatadirectory( ):
"""Attempt to retrieve the current user's app-data directory
This is the location where application-specific
files should be stored. On *nix systems, this will
be the ${HOME}/.config directory. On Win32 systems, it will be
the "Application Data" directory. Note that for... | python | {
"resource": ""
} |
q9995 | get_objects | train | def get_objects(remove_dups=True, include_frames=False):
"""Return a list of all known objects excluding frame objects.
If (outer) frame objects shall be included, pass `include_frames=True`. In
order to prevent building reference cycles, the current frame object (of
the caller of get_objects) is igno... | python | {
"resource": ""
} |
q9996 | get_size | train | def get_size(objects):
"""Compute the total size of all elements in objects."""
res = 0
for o in objects:
try:
res += _getsizeof(o)
except AttributeError:
print("IGNORING: type=%s; o=%s" % (str(type(o)), str(o)))
return res | python | {
"resource": ""
} |
q9997 | get_diff | train | def get_diff(left, right):
"""Get the difference of both lists.
The result will be a dict with this form {'+': [], '-': []}.
Items listed in '+' exist only in the right list,
items listed in '-' exist only in the left list.
"""
res = {'+': [], '-': []}
def partition(objects):
"""P... | python | {
"resource": ""
} |
q9998 | filter | train | def filter(objects, Type=None, min=-1, max=-1): #PYCHOK muppy filter
"""Filter objects.
The filter can be by type, minimum size, and/or maximum size.
Keyword arguments:
Type -- object type to filter by
min -- minimum object size
max -- maximum object size
"""
res = []
if min > max... | python | {
"resource": ""
} |
q9999 | get_referents | train | def get_referents(object, level=1):
"""Get all referents of an object up to a certain level.
The referents will not be returned in a specific order and
will not contain duplicate objects. Duplicate objects will be removed.
Keyword arguments:
level -- level of indirection to which referents conside... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.