code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
route = a[0] if a and isinstance(a[0], Route) else Route(*a, **ka)
self.routes.append(route)
if route.name:
self.named[route.name] = route.format_str()
if route.static:
self.static[route.route] = route.target
return
gpatt = route.group... | def add(self, *a, **ka) | Adds a route->target pair or a Route object to the Router.
See Route() for details. | 4.172122 | 4.011259 | 1.040103 |
''' Mount a Bottle application to a specific URL prefix '''
if not isinstance(app, Bottle):
raise TypeError('Only Bottle instances are supported for now.')
script_path = '/'.join(filter(None, script_path.split('/')))
path_depth = script_path.count('/') + 1
if not scri... | def mount(self, app, script_path) | Mount a Bottle application to a specific URL prefix | 4.567283 | 4.288218 | 1.065077 |
if not self.serve:
return HTTPError(503, "Server stopped")
handler, args = self.match_url(url, method)
if not handler:
return HTTPError(404, "Not found:" + url)
try:
return handler(**args)
except HTTPResponse, e:
return e... | def handle(self, url, method) | Execute the handler bound to the specified url and method and return
its output. If catchall is true, exceptions are catched and returned as
HTTPError(500) objects. | 3.92629 | 3.501444 | 1.121334 |
# Filtered types (recursive, because they may return anything)
for testtype, filterfunc in self.castfilter:
if isinstance(out, testtype):
return self._cast(filterfunc(out), request, response)
# Empty output is done here
if not out:
respon... | def _cast(self, out, request, response, peek=None) | Try to convert the parameter into something WSGI compatible and set
correct HTTP headers when possible.
Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like,
iterable of strings and iterable of unicodes | 3.914973 | 3.78968 | 1.033062 |
''' :class:`HeaderDict` filled with request headers.
HeaderDict keys are case insensitive str.title()d
'''
if self._header is None:
self._header = HeaderDict()
for key, value in self.environ.iteritems():
if key.startswith('HTTP_'):
... | def header(self) | :class:`HeaderDict` filled with request headers.
HeaderDict keys are case insensitive str.title()d | 4.96464 | 2.273993 | 2.183226 |
if self._GET is None:
data = parse_qs(self.query_string, keep_blank_values=True)
self._GET = MultiDict()
for key, values in data.iteritems():
for value in values:
self._GET[key] = value
return self._GET | def GET(self) | The QUERY_STRING parsed into a MultiDict.
Keys and values are strings. Multiple values per key are possible.
See MultiDict for details. | 2.655649 | 2.422725 | 1.096141 |
if self._COOKIES is None:
raw_dict = SimpleCookie(self.environ.get('HTTP_COOKIE',''))
self._COOKIES = {}
for cookie in raw_dict.itervalues():
self._COOKIES[cookie.key] = cookie.value
return self._COOKIES | def COOKIES(self) | Cookie information parsed into a dictionary.
Secure cookies are NOT decoded automatically. See
Request.get_cookie() for details. | 2.716055 | 2.57792 | 1.053584 |
if not isinstance(value, basestring):
sec = self.app.config['securecookie.key']
value = cookie_encode(value, sec).decode('ascii') #2to3 hack
self.COOKIES[key] = value
for k, v in kargs.iteritems():
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.377497 | 5.424513 | 0.991333 |
if not replace_str:
replace_str = "\x00"
try:
with open(path, "r+b") as fh:
if pos < 0: # if negative, we calculate the position backward from the end of file
fsize = os.fstat(fh.fileno()).st_size
pos = fsize + pos
fh.seek(pos)
... | def tamper_file_at(path, pos=0, replace_str=None) | Tamper a file at the given position and using the given string | 2.490473 | 2.460746 | 1.012081 |
if header and header > 0:
blocksize = header
tamper_count = 0 # total number of characters tampered in the file
total_size = 0 # total buffer size, NOT necessarily the total file size (depends if you set header or not)
with open(filepath, "r+b") as fh: # 'r+' allows to read AND overwrite c... | def tamper_file(filepath, mode='e', proba=0.03, block_proba=None, blocksize=65535, burst_length=None, header=None) | Randomly tamper a file's content | 6.117014 | 6.106776 | 1.001677 |
silent = kwargs.get('silent', False)
if 'silent' in kwargs: del kwargs['silent']
filescount = 0
for _ in tqdm(recwalk(inputpath), desc='Precomputing', disable=silent):
filescount += 1
files_tampered = 0
tamper_count = 0
total_size = 0
for dirname, filepath in tqdm(recwalk(... | def tamper_dir(inputpath, *args, **kwargs) | Randomly tamper the files content in a directory tree, recursively | 3.119215 | 3.069766 | 1.016109 |
stack_trace = stack()
try:
self.trace = []
for frm in stack_trace[5:]: # eliminate our own overhead
self.trace.insert(0, frm[1:])
finally:
del stack_trace | def _save_trace(self) | Save current stack trace as formatted string. | 9.07001 | 7.798491 | 1.163047 |
obj = self.ref()
self.snapshots.append(
(ts, sizer.asized(obj, detail=self._resolution_level))
)
if obj is not None:
self.repr = safe_repr(obj, clip=128) | def track_size(self, ts, sizer) | Store timestamp and current size for later evaluation.
The 'sizer' is a stateful sizing facility that excludes other tracked
objects. | 12.18241 | 11.322797 | 1.075919 |
size = 0
for (t, s) in self.snapshots:
if t == timestamp:
size = s.size
return size | def get_size_at_time(self, timestamp) | Get the size of the object at a specific time (snapshot).
If the object was not alive/sized at that instant, return 0. | 4.418941 | 3.361033 | 1.314757 |
self.stop = False
while not self.stop:
self.tracker.create_snapshot()
sleep(self.interval) | def run(self) | Loop until a stop signal is set. | 7.468956 | 5.673672 | 1.316424 |
if self.system_total.available:
return self.system_total.vsz
elif self.asizeof_total: # pragma: no cover
return self.asizeof_total
else: # pragma: no cover
return self.tracked_total | def total(self) | Return the total (virtual) size of the process in bytes. If process
information is not available, get the best number available, even if it
is a poor approximation of reality. | 7.17117 | 5.725076 | 1.25259 |
if not self.desc:
return "%.3fs" % self.timestamp
return "%s (%.3fs)" % (self.desc, self.timestamp) | def label(self) | Return timestamped label for this snapshot, or a raw timestamp. | 4.802534 | 3.406073 | 1.409992 |
self.track_object(_self_,
name=_observer_.name,
resolution_level=_observer_.detail,
keep=_observer_.keep,
trace=_observer_.trace)
_observer_.init(_self_, *args, **kwds) | def _tracker(self, _observer_, _self_, *args, **kwds) | Injected constructor for tracked classes.
Call the actual constructor of the object and track the object.
Attach to the object before calling the constructor to track the object with
the parameters of the most specialized class. | 7.487408 | 6.871406 | 1.089647 |
try:
constructor = cls.__init__
except AttributeError:
def constructor(self, *_args, **_kwargs):
pass
# Possible name clash between keyword arguments of the tracked class'
# constructor and the curried arguments of the injected constructo... | def _inject_constructor(self, cls, func, name, resolution_level, keep,
trace) | Modifying Methods in Place - after the recipe 15.7 in the Python
Cookbook by Ken Seehof. The original constructors may be restored
later. | 6.210684 | 6.370925 | 0.974848 |
self._observers[cls].modify(name, detail, keep, trace) | def _track_modify(self, cls, name, detail, keep, trace) | Modify settings of a tracked class | 5.953964 | 5.573164 | 1.068327 |
cls.__init__ = self._observers[cls].init
del self._observers[cls] | def _restore_constructor(self, cls) | Restore the original constructor, lose track of class. | 7.164706 | 5.091059 | 1.407312 |
tobj = self.objects[id(instance)]
tobj.set_resolution_level(resolution_level) | def track_change(self, instance, resolution_level=0) | Change tracking options for the already tracked object 'instance'.
If instance is not tracked, a KeyError will be raised. | 5.934233 | 5.225284 | 1.135677 |
# Check if object is already tracked. This happens if track_object is
# called multiple times for the same object or if an object inherits
# from multiple tracked classes. In the latter case, the most
# specialized class wins. To detect id recycling, the weak reference
... | def track_object(self, instance, name=None, resolution_level=0, keep=False, trace=False) | Track object 'instance' and sample size and lifetime information.
Not all objects can be tracked; trackable objects are class instances and
other objects that can be weakly referenced. When an object cannot be
tracked, a `TypeError` is raised.
:param resolution_level: The recursion dept... | 4.61617 | 4.697599 | 0.982666 |
if not isclass(cls):
raise TypeError("only class objects can be tracked")
if name is None:
name = cls.__module__ + '.' + cls.__name__
if self._is_tracked(cls):
self._track_modify(cls, name, resolution_level, keep, trace)
else:
self... | def track_class(self, cls, name=None, resolution_level=0, keep=False, trace=False) | Track all objects of the class `cls`. Objects of that type that already
exist are *not* tracked. If `track_class` is called for a class already
tracked, the tracking parameters are modified. Instantiation traces can be
generated by setting `trace` to True.
A constructor is injected to be... | 3.229276 | 3.283269 | 0.983555 |
classes = list(self._observers.keys())
for cls in classes:
self.detach_class(cls) | def detach_all_classes(self) | Detach from all tracked classes. | 4.455241 | 3.87437 | 1.149927 |
self.detach_all_classes()
self.objects.clear()
self.index.clear()
self._keepalive[:] = [] | def detach_all(self) | Detach from all tracked classes and objects.
Restore the original constructors and cleanse the tracking lists. | 9.968792 | 7.350568 | 1.356193 |
if not self._periodic_thread:
self._periodic_thread = PeriodicThread(self, interval, name='BackgroundMonitor')
self._periodic_thread.setDaemon(True)
self._periodic_thread.start()
else:
self._periodic_thread.interval = interval | def start_periodic_snapshots(self, interval=1.0) | Start a thread which takes snapshots periodically. The `interval` specifies
the time in seconds the thread waits between taking snapshots. The thread is
started as a daemon allowing the program to exit. If periodic snapshots are
already active, the interval is updated. | 2.860163 | 2.790048 | 1.02513 |
if self._periodic_thread and self._periodic_thread.isAlive():
self._periodic_thread.stop = True
self._periodic_thread.join()
self._periodic_thread = None | def stop_periodic_snapshots(self) | Post a stop signal to the thread that takes the periodic snapshots. The
function waits for the thread to terminate which can take some time
depending on the configured interval. | 2.510918 | 2.347641 | 1.069549 |
try:
# TODO: It is not clear what happens when memory is allocated or
# released while this function is executed but it will likely lead
# to inconsistencies. Either pause all other threads or don't size
# individual objects in asynchronous mode.
... | def create_snapshot(self, description='', compute_total=False) | Collect current per instance statistics and saves total amount of
memory associated with the Python process.
If `compute_total` is `True`, the total consumption of all objects
known to *asizeof* is computed. The latter might be very slow if many
objects are mapped into memory at the tim... | 6.464937 | 5.933506 | 1.089564 |
'''_actions which are positional or possessing the `required` flag '''
return not action.option_strings and not isinstance(action, _SubParsersAction) or action.required == True | def is_required(action) | _actions which are positional or possessing the `required` flag | 21.206989 | 6.904834 | 3.071325 |
'''From a raw ecc entry (a string), extract the metadata fields (filename, filesize, ecc for both), and the rest being blocks of hash and ecc per blocks of the original file's header'''
entry = entry.lstrip(field_delim) # if there was some slight adjustment error (example: the last ecc block of the last file wa... | def entry_fields(entry, field_delim="\xFF") | From a raw ecc entry (a string), extract the metadata fields (filename, filesize, ecc for both), and the rest being blocks of hash and ecc per blocks of the original file's header | 8.128524 | 6.381518 | 1.27376 |
'''From an entry with its parameters (filename, filesize), assemble a list of each block from the original file along with the relative hash and ecc for easy processing later.'''
# Extract the header from the file
if fileheader is None:
with open(filepath, 'rb') as file: # filepath is the absolute p... | def entry_assemble(entry_fields, ecc_params, header_size, filepath, fileheader=None) | From an entry with its parameters (filename, filesize), assemble a list of each block from the original file along with the relative hash and ecc for easy processing later. | 4.379595 | 3.336082 | 1.312796 |
'''Split a string in blocks given max_block_size and compute the hash and ecc for each block, and then return a nice list with both for easy processing.'''
result = []
# If required parameters were not provided, we compute them
if not message_size:
ecc_params = compute_ecc_params(max_block_size,... | def compute_ecc_hash(ecc_manager, hasher, buf, max_block_size, rate, message_size=None, as_string=False) | Split a string in blocks given max_block_size and compute the hash and ecc for each block, and then return a nice list with both for easy processing. | 4.212772 | 3.29984 | 1.276659 |
fentry_fields = {"ecc_field": ecc}
field_correct = [] # will store each block of the corrected (or already correct) filepath
fcorrupted = False # check if field was corrupted
fcorrected = True # check if field was corrected (if it was corrupted)
errmsg = ''
# Decode each block of the filepa... | def ecc_correct_intra(ecc_manager_intra, ecc_params_intra, field, ecc, enable_erasures=False, erasures_char="\x00", only_erasures=False) | Correct an intra-field with its corresponding intra-ecc if necessary | 5.126153 | 5.05455 | 1.014166 |
result = []
idset = set([id(x) for x in graph])
for n in graph:
refset = set([id(x) for x in get_referents(n)])
if refset.intersection(idset):
result.append(n)
return result | def _eliminate_leafs(self, graph) | Eliminate leaf objects - that are objects not referencing any other
objects in the list `graph`. Returns the list of objects without the
objects identified as leafs. | 3.532697 | 2.975695 | 1.187184 |
cycles = self.objects[:]
cnt = 0
while cnt != len(cycles):
cnt = len(cycles)
cycles = self._eliminate_leafs(cycles)
self.objects = cycles
return len(self.objects) | def _reduce_to_cycles(self) | Iteratively eliminate leafs to reduce the set of objects to only those
that build cycles. Return the number of objects involved in reference
cycles. If there are no cycles, `self.objects` will be an empty list and
this method returns 0. | 5.323651 | 3.442528 | 1.546436 |
if not self._reduced:
reduced = copy(self)
reduced.objects = self.objects[:]
reduced.metadata = []
reduced.edges = []
self.num_in_cycles = reduced._reduce_to_cycles()
reduced.num_in_cycles = self.num_in_cycles
if self.n... | def reduce_to_cycles(self) | Iteratively eliminate leafs to reduce the set of objects to only those
that build cycles. Return the reduced graph. If there are no cycles,
None is returned. | 4.275597 | 4.063719 | 1.052139 |
idset = set([id(x) for x in self.objects])
self.edges = set([])
for n in self.objects:
refset = set([id(x) for x in get_referents(n)])
for ref in refset.intersection(idset):
label = ''
members = None
if isinstance(n... | def _get_edges(self) | Compute the edges for the reference graph.
The function returns a set of tuples (id(a), id(b), ref) if a
references b with the referent 'ref'. | 3.72508 | 3.45425 | 1.078405 |
g = {}
for x in self.metadata:
g[x.id] = x
idx = 0
for x in self.metadata:
if not hasattr(x, 'group'):
x.group = idx
idx += 1
neighbors = set()
for e in self.edges:
if e.src == x.id:... | def _annotate_groups(self) | Annotate the objects belonging to separate (non-connected) graphs with
individual indices. | 3.543773 | 3.451128 | 1.026845 |
self.metadata = [x for x in self.metadata if x.group == group]
group_set = set([x.id for x in self.metadata])
self.objects = [obj for obj in self.objects if id(obj) in group_set]
self.count = len(self.metadata)
if self.metadata == []:
return False
se... | def _filter_group(self, group) | Eliminate all objects but those which belong to `group`.
``self.objects``, ``self.metadata`` and ``self.edges`` are modified.
Returns `True` if the group is non-empty. Otherwise returns `False`. | 3.689259 | 2.839517 | 1.299256 |
self._annotate_groups()
index = 0
for group in range(self._max_group):
subgraph = copy(self)
subgraph.metadata = self.metadata[:]
subgraph.edges = self.edges.copy()
if subgraph._filter_group(group):
subgraph.total_size = ... | def split(self) | Split the graph into sub-graphs. Only connected objects belong to the
same graph. `split` yields copies of the Graph object. Shallow copies
are used that only replicate the meta-information, but share the same
object list ``self.objects``.
>>> from pympler.refgraph import ReferenceGraph... | 4.975585 | 5.736465 | 0.867361 |
graphs = list(self.split())
graphs.sort(key=lambda x: -len(x.metadata))
for index, graph in enumerate(graphs):
graph.index = index
return graphs | def split_and_sort(self) | Split the graphs into sub graphs and return a list of all graphs sorted
by the number of nodes. The graph with most nodes is returned first. | 4.47843 | 4.207932 | 1.064283 |
self.metadata = []
sizer = Asizer()
sizes = sizer.asizesof(*self.objects)
self.total_size = sizer.total
for obj, sz in zip(self.objects, sizes):
md = _MetaObject()
md.size = sz
md.id = id(obj)
try:
md.type =... | def _annotate_objects(self) | Extract meta-data describing the stored objects. | 4.721756 | 4.262881 | 1.107644 |
s = []
header = '// Process this file with graphviz\n'
s.append( header)
s.append('digraph G {\n')
s.append(' node [shape=box];\n')
for md in self.metadata:
label = trunc(md.str, 48).replace('"', "'")
extra = ''
if md.type =... | def _get_graphviz_data(self) | Emit a graph representing the connections between the objects described
within the metadata list. The text representation can be transformed to
a graph with graphviz. Returns a string. | 3.534089 | 3.363711 | 1.050652 |
if self.objects == []:
return False
data = self._get_graphviz_data()
options = ('-Nfontsize=10',
'-Efontsize=10',
'-Nstyle=filled',
'-Nfillcolor=#E5EDB8',
'-Ncolor=#CCCCCC')
cmdline = (cmd,... | def render(self, filename, cmd='dot', format='ps', unflatten=False) | Render the graph to `filename` using graphviz. The graphviz invocation
command may be overriden by specifying `cmd`. The `format` may be any
specifier recognized by the graph renderer ('-Txxx' command). The graph
can be preprocessed by the *unflatten* tool if the `unflatten` parameter
i... | 3.156688 | 3.063149 | 1.030537 |
f = open(filename, 'w')
f.write(self._get_graphviz_data())
f.close() | def write_graph(self, filename) | Write raw graph data which can be post-processed using graphviz. | 3.287791 | 2.952686 | 1.113492 |
if not hasattr(self, '_root_frame'):
self._root_frame = Frame()
# define a recursive function that builds the hierarchy of frames given the
# stack of frame identifiers
def frame_for_stack(stack):
if len(stack) == 0:
r... | def root_frame(self) | Returns the parsed results in the form of a tree of Frame objects | 3.203909 | 2.86067 | 1.119986 |
global call_dict
global call_stack
global func_count
global func_count_max
global func_time
global func_time_max
global call_stack_timer
call_dict = {}
# current call stack
call_stack = ['__main__']
# counters for each function
func_count = {}
func_count_max =... | def reset_trace() | Resets all collected statistics. This is run automatically by
start_trace(reset=True) and when the module is loaded. | 4.002639 | 3.975758 | 1.006761 |
# TODO: Move these calls away from this function so it doesn't have to run
# every time.
lib_path = sysconfig.get_python_lib()
path = os.path.split(lib_path)
if path[1] == 'site-packages':
lib_path = path[0]
return file_name.lower().startswith(lib_path.lower()) | def is_module_stdlib(file_name) | Returns True if the file_name is in the lib directory. | 4.09865 | 3.816414 | 1.073953 |
global trace_filter
global time_filter
if reset:
reset_trace()
if filter_func:
trace_filter = filter_func
else:
trace_filter = GlobbingFilter(exclude=['pycallgraph.*'])
if time_filter_func:
time_filter = time_filter_func
else:
time_filter = Glob... | def start_trace(reset=True, filter_func=None, time_filter_func=None) | Begins a trace. Setting reset to True will reset all previously recorded
trace data. filter_func needs to point to a callable function that accepts
the parameters (call_stack, module_name, class_name, func_name, full_name).
Every call will be passed into this function and it is up to the function
to dec... | 2.952655 | 2.952124 | 1.00018 |
global func_count_max
global func_count
global trace_filter
global time_filter
global call_stack
global func_time
global func_time_max
if event == 'call':
keep = True
code = frame.f_code
# Stores all the parts of a human readable name of the current call.
... | def tracer(frame, event, arg) | This is an internal function that is called every time a call is made
during a trace. It keeps track of relationships between calls. | 2.34154 | 2.335372 | 1.002641 |
defaults = []
nodes = []
edges = []
# define default attributes
for comp, comp_attr in graph_attributes.items():
attr = ', '.join( '%s = "%s"' % (attr, val)
for attr, val in comp_attr.items() )
defaults.append( '\t%(comp)s [ %(attr)s ];\n' % loca... | def get_dot(stop=True) | Returns a string containing a DOT file. Setting stop to True will cause
the trace to stop. | 3.068514 | 3.040231 | 1.009303 |
ret = ['nodedef>name VARCHAR, label VARCHAR, hits INTEGER, ' + \
'calls_frac DOUBLE, total_time_frac DOUBLE, ' + \
'total_time DOUBLE, color VARCHAR, width DOUBLE']
for func, hits in func_count.items():
calls_frac, total_time_frac, total_time = _frac_calculation(func, hits)
... | def get_gdf(stop=True) | Returns a string containing a GDF file. Setting stop to True will cause
the trace to stop. | 2.967586 | 2.891423 | 1.026341 |
if stop:
stop_trace()
dot_data = get_dot()
# normalize filename
regex_user_expand = re.compile('\A~')
if regex_user_expand.match(filename):
filename = os.path.expanduser(filename)
else:
filename = os.path.expandvars(filename) # expand, just in case
if format ... | def make_dot_graph(filename, format='png', tool='dot', stop=True) | Creates a graph using a Graphviz tool that supports the dot language. It
will output into a file specified by filename with the format specified.
Setting stop to True will stop the current trace. | 2.979197 | 3.066354 | 0.971576 |
if stop:
stop_trace()
try:
f = open(filename, 'w')
f.write(get_gdf())
finally:
if f: f.close() | def make_gdf_graph(filename, stop=True) | Create a graph in simple GDF format, suitable for feeding into Gephi,
or some other graph manipulation and display tool. Setting stop to True
will stop the current trace. | 4.419555 | 3.649702 | 1.210936 |
cache = dict()
def wrapper(*rest):
if rest not in cache:
cache[rest] = callable_object(*rest)
return cache[rest]
return wrapper | def simple_memoize(callable_object) | Simple memoization for functions without keyword arguments.
This is useful for mapping code objects to module in this context.
inspect.getmodule() requires a number of system calls, which may slow down
the tracing considerably. Caching the mapping from code objects (there is
*one* code object for each ... | 3.322857 | 3.475592 | 0.956055 |
import subprocess, sys
subprocess.call([
sys.argv[0] + '32'
]+sys.argv[1:],
env={"VERSIONER_PYTHON_PREFER_32_BIT":"yes"}
) | def macshim() | Shim to run 32-bit on 64-bit mac as a sub-process | 10.43334 | 8.033613 | 1.298711 |
plat = sys.platform
supported_platform = plat != 'Pocket PC' and (plat != 'win32' or
'ANSICON' in os.environ)
is_a_tty = hasattr(file_obj, 'isatty') and file_obj.isatty()
if not supported_platform or not is_a_tty:
return False
return Tr... | def file_supports_color(file_obj) | Returns True if the running system's terminal supports color, and False
otherwise.
Borrowed from Django
https://github.com/django/django/blob/master/django/core/management/color.py | 1.700361 | 1.765614 | 0.963042 |
'''Compute the ecc parameters (size of the message, size of the hash, size of the ecc). This is an helper function to easily compute the parameters from a resilience rate to instanciate an ECCMan object.'''
#message_size = max_block_size - int(round(max_block_size * rate * 2, 0)) # old way to compute, wasn't re... | def compute_ecc_params(max_block_size, rate, hasher) | Compute the ecc parameters (size of the message, size of the hash, size of the ecc). This is an helper function to easily compute the parameters from a resilience rate to instanciate an ECCMan object. | 7.340345 | 4.590322 | 1.599092 |
'''Encode one message block (up to 255) into an ecc'''
if not k: k = self.k
message, _ = self.pad(message, k=k)
if self.algo == 1:
mesecc = self.ecc_manager.encode(message, k=k)
elif self.algo == 2:
mesecc = self.ecc_manager.encode_fast(message, k=k)
... | def encode(self, message, k=None) | Encode one message block (up to 255) into an ecc | 3.944791 | 3.314589 | 1.19013 |
'''Automatically left pad with null bytes a message if too small, or leave unchanged if not necessary. This allows to keep track of padding and strip the null bytes after decoding reliably with binary data. Equivalent to shortening (shortened reed-solomon code).'''
if not k: k = self.k
pad = Non... | def pad(self, message, k=None) | Automatically left pad with null bytes a message if too small, or leave unchanged if not necessary. This allows to keep track of padding and strip the null bytes after decoding reliably with binary data. Equivalent to shortening (shortened reed-solomon code). | 10.048771 | 2.14862 | 4.676848 |
'''Automatically right pad with null bytes an ecc to fill for missing bytes if too small, or leave unchanged if not necessary. This can be used as a workaround for field delimiter misdetection. Equivalent to puncturing (punctured reed-solomon code).'''
if not k: k = self.k
pad = None
if ... | def rpad(self, ecc, k=None) | Automatically right pad with null bytes an ecc to fill for missing bytes if too small, or leave unchanged if not necessary. This can be used as a workaround for field delimiter misdetection. Equivalent to puncturing (punctured reed-solomon code). | 11.926827 | 3.502522 | 3.405212 |
'''Check if there's any error in a message+ecc. Can be used before decoding, in addition to hashes to detect if the message was tampered, or after decoding to check that the message was fully recovered.'''
if not k: k = self.k
message, _ = self.pad(message, k=k)
ecc, _ = self.rpad(ecc, k... | def check(self, message, ecc, k=None) | Check if there's any error in a message+ecc. Can be used before decoding, in addition to hashes to detect if the message was tampered, or after decoding to check that the message was fully recovered. | 6.928394 | 3.520764 | 1.967867 |
'''Provide a description for each algorithm available, useful to print in ecc file'''
if 0 < self.algo <= 3:
return "Reed-Solomon with polynomials in Galois field of characteristic %i (2^%i) with generator=%s, prime poly=%s and first consecutive root=%s." % (self.field_charac, self.c_exp, se... | def description(self) | Provide a description for each algorithm available, useful to print in ecc file | 7.039098 | 5.340594 | 1.318037 |
if fn is None: # @profile() syntax -- we are a decorator maker
def decorator(fn):
return profile(fn, skip=skip, filename=filename,
immediate=immediate, dirs=dirs,
sort=sort, entries=entries,
profiler=profiler)
... | def profile(fn=None, skip=0, filename=None, immediate=False, dirs=False,
sort=None, entries=40,
profiler=('cProfile', 'profile', 'hotshot')) | Mark `fn` for profiling.
If `skip` is > 0, first `skip` calls to `fn` will not be profiled.
If `immediate` is False, profiling results will be printed to
sys.stdout on program termination. Otherwise results will be printed
after each call.
If `dirs` is False only the name of the file will be pri... | 2.916422 | 3.280879 | 0.888915 |
fp = TraceFuncCoverage(fn) # or HotShotFuncCoverage
# We cannot return fp or fp.__call__ directly as that would break method
# definitions, instead we need to return a plain function.
def new_fn(*args, **kw):
return fp(*args, **kw)
new_fn.__doc__ = fn.__doc__
new_fn.__name__ = fn.__... | def coverage(fn) | Mark `fn` for line coverage analysis.
Results will be printed to sys.stdout on program termination.
Usage::
def fn(...):
...
fn = coverage(fn)
If you are using Python 2.4, you should be able to use the decorator
syntax::
@coverage
def fn(...):
... | 4.869076 | 5.29897 | 0.918872 |
fp = HotShotFuncCoverage(fn)
# We cannot return fp or fp.__call__ directly as that would break method
# definitions, instead we need to return a plain function.
def new_fn(*args, **kw):
return fp(*args, **kw)
new_fn.__doc__ = fn.__doc__
new_fn.__name__ = fn.__name__
new_fn.__dic... | def coverage_with_hotshot(fn) | Mark `fn` for line coverage analysis.
Uses the 'hotshot' module for fast coverage analysis.
BUG: Produces inaccurate results.
See the docstring of `coverage` for usage examples. | 3.815768 | 4.194151 | 0.909783 |
if fn is None: # @timecall() syntax -- we are a decorator maker
def decorator(fn):
return timecall(fn, immediate=immediate, timer=timer)
return decorator
# @timecall syntax -- we are a decorator.
fp = FuncTimer(fn, immediate=immediate, timer=timer)
# We cannot return fp ... | def timecall(fn=None, immediate=True, timer=time.time) | Wrap `fn` and print its execution time.
Example::
@timecall
def somefunc(x, y):
time.sleep(x * y)
somefunc(2, 3)
will print the time taken by somefunc on every call. If you want just
a summary at program termination, use
@timecall(immediate=False)
You c... | 3.454685 | 4.546335 | 0.759884 |
funcname = self.fn.__name__
filename = self.fn.__code__.co_filename
lineno = self.fn.__code__.co_firstlineno
print("")
print("*** PROFILER RESULTS ***")
print("%s (%s:%s)" % (funcname, filename, lineno))
if self.skipped:
skipped = "(%d calls n... | def print_stats(self) | Print profile information to sys.stdout. | 3.262795 | 3.081722 | 1.058757 |
# Note: not using self.Profile, since pstats.Stats() fails then
self.stats = pstats.Stats(Profile())
self.ncalls = 0
self.skipped = 0 | def reset_stats(self) | Reset accumulated profiler statistics. | 12.553613 | 10.58963 | 1.185463 |
funcname = self.fn.__name__
filename = self.fn.__code__.co_filename
lineno = self.fn.__code__.co_firstlineno
print("")
print("*** COVERAGE RESULTS ***")
print("%s (%s:%s)" % (funcname, filename, lineno))
print("function called %d times" % self.ncalls)
... | def atexit(self) | Stop profiling and print profile information to sys.stderr.
This function is registered as an atexit hook. | 3.743369 | 3.75212 | 0.997668 |
strs = trace.find_strings(self.filename)
lines = trace.find_lines_from_code(self.fn.__code__, strs)
self.firstcodelineno = sys.maxint
for lineno in lines:
self.firstcodelineno = min(self.firstcodelineno, lineno)
self.sourcelines.setdefault(lineno, 0)
... | def find_source_lines(self) | Mark all executable source lines in fn as executed 0 times. | 4.207219 | 3.842911 | 1.0948 |
self.sourcelines[lineno] = self.sourcelines.get(lineno, 0) + count | def mark(self, lineno, count=1) | Mark a given source line as executed count times.
Multiple calls to mark for the same lineno add up. | 3.665524 | 3.138519 | 1.167915 |
lineno = self.firstlineno
counter = 0
for line in self.source:
if self.sourcelines.get(lineno) == 0:
if not self.blank_rx.match(line):
counter += 1
lineno += 1
return counter | def count_never_executed(self) | Count statements that were never executed. | 4.902187 | 4.77546 | 1.026537 |
_maxes, _lists = self._maxes, self._lists
if _maxes:
pos = bisect_right(_maxes, val)
if pos == len(_maxes):
pos -= 1
_maxes[pos] = val
_lists[pos].append(val)
else:
insort(_lists[pos], val)
... | def add(self, val) | Add the element *val* to the list. | 2.942898 | 2.79357 | 1.053454 |
_maxes = self._maxes
if not _maxes:
raise ValueError('{0} not in list'.format(repr(val)))
pos = bisect_left(_maxes, val)
if pos == len(_maxes):
raise ValueError('{0} not in list'.format(repr(val)))
_lists = self._lists
idx = bisect_lef... | def remove(self, val) | Remove first occurrence of *val*.
Raises ValueError if *val* is not present. | 2.606142 | 2.459308 | 1.059706 |
_maxes, _lists, _index = self._maxes, self._lists, self._index
lists_pos = _lists[pos]
del lists_pos[idx]
self._len -= 1
len_lists_pos = len(lists_pos)
if len_lists_pos > self._half:
_maxes[pos] = lists_pos[-1]
if _index:
... | def _delete(self, pos, idx) | Delete the item at the given (pos, idx).
Combines lists that are less than half the load level.
Updates the index when the sublist length is more than half the load
level. This requires decrementing the nodes in a traversal from the leaf
node to the root. For an example traversal see s... | 3.009346 | 2.927037 | 1.02812 |
_maxes, _lists, _load = self._maxes, self._lists, self._load
if not isinstance(values, list):
values = list(values)
if any(values[pos - 1] > values[pos]
for pos in range(1, len(values))):
raise ValueError('given sequence not in sort order')
... | def extend(self, values) | Extend the list by appending all elements from the *values*. Raises a
ValueError if the sort order would be violated. | 3.368855 | 3.19166 | 1.055518 |
_maxes, _lists, _len = self._maxes, self._lists, self._len
if idx < 0:
idx += _len
if idx < 0:
idx = 0
if idx > _len:
idx = _len
if not _maxes:
# The idx must be zero by the inequalities above.
_maxes.append(v... | def insert(self, idx, val) | Insert the element *val* into the list at *idx*. Raises a ValueError if
the *val* at *idx* would violate the sort order. | 2.245786 | 2.19273 | 1.024196 |
_maxes, _lists, _keys = self._maxes, self._lists, self._keys
values = sorted(iterable, key=self._key)
if _maxes:
if len(values) * 4 >= self._len:
values.extend(chain.from_iterable(_lists))
values.sort(key=self._key)
self._clea... | def update(self, iterable) | Update the list by adding all elements from *iterable*. | 3.766227 | 3.611745 | 1.042772 |
if self.get_mode() == "ibm":
self.__username_ibm = username_ibm
else:
raise Exception(
"Mode is {}, whereas it must be `ibm`".format(
self.get_moder())) | def set_username_ibm(self, username_ibm) | Parameters
----------
username_ibm : str
Raises
------
Exception
If mode is not `ibm` | 5.7236 | 4.831472 | 1.184649 |
if self.get_mode() == "ibm":
self.__password_ibm = password_ibm
else:
raise Exception(
"Mode is {}, whereas it must be `ibm`".format(self.get_mode())) | def set_password_ibm(self, password_ibm) | Parameters
----------
password_ibm : str
Raises
------
Exception
If mode is not `ibm` | 4.371972 | 3.772943 | 1.15877 |
audio_files = list()
for possibly_audio_file in os.listdir("{}/{}".format(self.src_dir,
sub_dir)):
file_format = ''.join(possibly_audio_file.split('.')[-1])
if file_format.lower() == "wav":
audi... | def _list_audio_files(self, sub_dir="") | Parameters
----------
sub_dir : one of `needed_directories`, optional
Default is "", which means it'll look through all of subdirs.
Returns
-------
audio_files : [str]
A list whose elements are basenames of the present audiofiles whose
formats... | 3.028639 | 3.316992 | 0.913068 |
channel_num = int(
subprocess.check_output(
(
).format(audio_abs_path, "Channels"),
shell=True, universal_newlines=True).rstrip())
return channel_num | def _get_audio_channels(self, audio_abs_path) | Parameters
----------
audio_abs_path : str
Returns
-------
channel_num : int | 5.976933 | 5.781182 | 1.03386 |
sample_rate = int(
subprocess.check_output(
(
).format(audio_abs_path, "Sample Rate"),
shell=True, universal_newlines=True).rstrip())
return sample_rate | def _get_audio_sample_rate(self, audio_abs_path) | Parameters
----------
audio_abs_path : str
Returns
-------
sample_rate : int | 6.311676 | 6.555768 | 0.962767 |
sample_bit = int(
subprocess.check_output(
(
).format(audio_abs_path, "Precision"),
shell=True, universal_newlines=True).rstrip())
return sample_bit | def _get_audio_sample_bit(self, audio_abs_path) | Parameters
----------
audio_abs_path : str
Returns
-------
sample_bit : int | 8.015084 | 8.635228 | 0.928184 |
HHMMSS_duration = subprocess.check_output(
(
).format(
audio_abs_path, "Duration"),
shell=True, universal_newlines=True).rstrip()
total_seconds = sum(
[float(x) * 60 ** (2 - i)
for i, x in enumerate(HHMMSS_duration.sp... | def _get_audio_duration_seconds(self, audio_abs_path) | Parameters
----------
audio_abs_path : str
Returns
-------
total_seconds : int | 4.126971 | 4.050694 | 1.018831 |
bit_Rate_formatted = subprocess.check_output(
.format(
audio_abs_path, "Bit Rate"),
shell=True, universal_newlines=True).rstrip()
bit_rate = (lambda x:
int(x[:-1]) * 10 ** 3 if x[-1].lower() == "k" else
int(x[:-1]) ... | def _get_audio_bit_rate(self, audio_abs_path) | Parameters
-----------
audio_abs_path : str
Returns
-------
bit_rate : int | 2.818786 | 2.906589 | 0.969792 |
less_than_second = seconds - floor(seconds)
minutes, seconds = divmod(floor(seconds), 60)
hours, minutes = divmod(minutes, 60)
return "{}H{}M{}S.{}".format(hours, minutes, seconds, less_than_second) | def _seconds_to_HHMMSS(seconds) | Retuns a string which is the hour, minute, second(milli) representation
of the intput `seconds`
Parameters
----------
seconds : float
Returns
-------
str
Has the form <int>H<int>M<int>S.<float> | 3.017859 | 2.952787 | 1.022038 |
subprocess.Popen(["sox", str(audio_abs_path), str(segment_abs_path),
"trim", str(starting_second), str(duration)],
universal_newlines=True).communicate() | def _audio_segment_extractor(self, audio_abs_path, segment_abs_path,
starting_second, duration) | Parameters
-----------
audio_abs_path : str
segment_abs_path : str
starting_second : int
duration : int | 3.003312 | 2.897398 | 1.036555 |
total_seconds = self._get_audio_duration_seconds(audio_abs_path)
current_segment = 0
while current_segment <= total_seconds // duration_seconds + 1:
if current_segment + duration_seconds > total_seconds:
ending_second = total_seconds
else:
... | def _split_audio_by_duration(self, audio_abs_path,
results_abs_path, duration_seconds) | Calculates the length of each segment and passes it to
self._audio_segment_extractor
Parameters
----------
audio_abs_path : str
results_abs_path : str
A place for adding digits needs to be added prior the the format
decleration i.e. name%03.wav. Here, we'... | 2.612425 | 2.37091 | 1.101866 |
sample_rate = self._get_audio_sample_rate(audio_abs_path)
sample_bit = self._get_audio_sample_bit(audio_abs_path)
channel_num = self._get_audio_channels(audio_abs_path)
duration = 8 * chunk_size / reduce(lambda x, y: int(x) * int(y),
[s... | def _split_audio_by_size(self, audio_abs_path, results_abs_path,
chunk_size) | Calculates the duration of the name.wav in order for all splits have
the size of chunk_size except possibly the last split (which will be
smaller) and then passes the duration to `split_audio_by_duration`
Parameters
----------
audio_abs_path : str
results_abs_path : str
... | 2.292532 | 2.449315 | 0.935989 |
name = ''.join(basename.split('.')[:-1])
# May cause problems if wav is not less than 9 channels.
if basename.split('.')[-1] == "wav":
if self.get_verbosity():
print("Found wave! Copying to {}/filtered/{}".format(
self.src_dir, basename))
... | def _filtering_step(self, basename) | Moves the audio file if the format is `wav` to `filtered` directory.
Parameters
----------
basename : str
A basename of `/home/random-guy/some-audio-file.wav` is
`some-audio-file.wav` | 5.208972 | 5.011836 | 1.039334 |
name = ''.join(basename.split('.')[:-1])
if self.get_mode() == "ibm":
# Checks the file size. It's better to use 95% of the allocated
# size per file since the upper limit is not always respected.
total_size = os.path.getsize("{}/filtered/{}.wav".format(
... | def _staging_step(self, basename) | Checks the size of audio file, splits it if it's needed to manage api
limit and then moves to `staged` directory while appending `*` to
the end of the filename for self.split_audio_by_duration to replace
it by a number.
Parameters
----------
basename : str
A ... | 3.460738 | 3.293924 | 1.050643 |
if basename is not None:
if basename in self.get_timestamps():
if self.get_verbosity():
print("File specified was already indexed. Reindexing...")
del self.__timestamps[basename]
self._filtering_step(basename)
self.... | def _prepare_audio(self, basename, replace_already_indexed=False) | Prepares and stages the audio file to be indexed.
Parameters
----------
basename : str, None
A basename of `/home/random-guy/some-audio-file.wav` is
`some-audio-file.wav`
If basename is `None`, it'll prepare all the audio files. | 2.813772 | 2.841329 | 0.990302 |
self._prepare_audio(basename=basename,
replace_already_indexed=replace_already_indexed)
for staging_audio_basename in self._list_audio_files(
sub_dir="staging"):
original_audio_name = ''.join(
staging_audio_basename.split(... | def _index_audio_cmu(self, basename=None, replace_already_indexed=False) | Indexes audio with pocketsphinx. Beware that the output would not be
sufficiently accurate. Use this only if you don't want to upload your
files to IBM.
Parameters
-----------
basename : str, optional
A specific basename to be indexed and is placed in src_dir
... | 4.277213 | 4.095264 | 1.044429 |
filter_untimed = filter(lambda x: len(x) == 4,
str_timestamps_with_sil_conf)
if filter_untimed != str_timestamps_with_sil_conf:
self.__errors[
(time(), staging_audio_basename)
] = str_timestamps_with_sil_conf
str_ti... | def _timestamp_extractor_cmu(self, staging_audio_basename,
str_timestamps_with_sil_conf) | Parameters
----------
str_timestamps_with_sil_conf : [[str, str, str, str]]
Of the form [[word, starting_sec, ending_sec, confidence]]
Returns
-------
timestamps : [[str, float, float]] | 4.305941 | 4.324192 | 0.995779 |
try:
timestamps_of_sentences = [
audio_json['results'][i]['alternatives'][0]['timestamps']
for i in range(len(audio_json['results']))]
return [
_WordBlock(
word=word_block[0],
start=round(flo... | def _timestamp_extractor_ibm(self, staging_audio_basename, audio_json) | Parameters
----------
audio_json : {str: [{str: [{str: str or nuneric}]}]}
Refer to Watson Speech API refrence [1]_
Returns
-------
[[str, float, float]]
A list whose members are lists. Each member list has three
elements. First one is a word.... | 4.313477 | 4.16611 | 1.035373 |
with _Subdirectory_Managing_Decorator(
self.src_dir, self._needed_directories):
if self.get_mode() == "ibm":
self._index_audio_ibm(*args, **kwargs)
elif self.get_mode() == "cmu":
self._index_audio_cmu(*args, **kwargs) | def index_audio(self, *args, **kwargs) | Calls the correct indexer function based on the mode.
If mode is `ibm`, _indexer_audio_ibm is called which is an interface
for Watson. Note that some of the explaination of _indexer_audio_ibm's
arguments is from [1]_
If mode is `cmu`, _indexer_audio_cmu is called which is an interface
... | 5.77765 | 4.724151 | 1.223003 |
unified_timestamps = _PrettyDefaultDict(list)
staged_files = self._list_audio_files(sub_dir="staging")
for timestamp_basename in self.__timestamps_unregulated:
if len(self.__timestamps_unregulated[timestamp_basename]) > 1:
# File has been splitted
... | def _timestamp_regulator(self) | Makes a dictionary whose keys are audio file basenames and whose
values are a list of word blocks from unregulated timestamps and
updates the main timestamp attribute. After all done, purges
unregulated ones.
In case the audio file was large enough to be splitted, it adds seconds
... | 3.694979 | 3.234724 | 1.142286 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.