code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
return self.evaluate(.format(repr(selector), repr(btn))) | def click(self, selector, btn=0) | Click the targeted element.
:param selector: A CSS3 selector to targeted element.
:param btn: The number of mouse button.
0 - left button,
1 - middle button,
2 - right button | 41.761219 | 70.787521 | 0.589952 |
script = 'document.querySelector("%s").setAttribute("value", "%s")'
script = script % (selector, value)
self.evaluate(script) | def set_input_value(self, selector, value) | Set the value of the input matched by given selector. | 3.669223 | 3.802172 | 0.965033 |
return self.evaluate(.format(repr(selector), repr(classname))) | def set_class_value(self, selector, classname) | Set the class of element matched by the given selector. | 28.56333 | 31.856037 | 0.896638 |
from spyder.utils.qthelpers import qapplication
app = qapplication()
widget = NotebookClient(plugin=None, name='')
widget.show()
widget.set_url('http://google.com')
sys.exit(app.exec_()) | def main() | Simple test. | 4.404175 | 4.29964 | 1.024313 |
# Remove unneeded blank lines at the beginning
eol = sourcecode.get_eol_chars(error)
if eol:
error = error.replace(eol, '<br>')
# Don't break lines in hyphens
# From http://stackoverflow.com/q/7691569/438386
error = error.replace('-', '‑')
... | def show_kernel_error(self, error) | Show kernel initialization errors. | 5.691528 | 5.596585 | 1.016964 |
loading_template = Template(LOADING)
loading_img = get_image_path('loading_sprites.png')
if os.name == 'nt':
loading_img = loading_img.replace('\\', '/')
message = _("Connecting to kernel...")
page = loading_template.substitute(css_path=CSS_PATH,
... | def show_loading_page(self) | Show a loading animation while the kernel is starting. | 4.719199 | 4.282454 | 1.101985 |
# Path relative to the server directory
self.path = os.path.relpath(self.filename,
start=server_info['notebook_dir'])
# Replace backslashes on Windows
if os.name == 'nt':
self.path = self.path.replace('\\', '/')
# Server ... | def register(self, server_info) | Register attributes that can be computed with the server info. | 3.955504 | 4.005567 | 0.987502 |
if is_text_string(url_or_text):
url = QUrl(url_or_text)
else:
url = url_or_text
self.notebookwidget.load(url) | def go_to(self, url_or_text) | Go to page utl. | 3.476504 | 3.537024 | 0.98289 |
sname = osp.splitext(osp.basename(self.filename))[0]
if len(sname) > 20:
fm = QFontMetrics(QFont())
sname = fm.elidedText(sname, Qt.ElideRight, 110)
return sname | def get_short_name(self) | Get a short name for the notebook. | 3.260557 | 3.045859 | 1.070489 |
sessions_url = self.get_session_url()
sessions_req = requests.get(sessions_url).content.decode()
sessions = json.loads(sessions_req)
if os.name == 'nt':
path = self.path.replace('\\', '/')
else:
path = self.path
for session in sessions:
... | def get_kernel_id(self) | Get the kernel id of the client.
Return a str with the kernel id or None. | 2.744715 | 2.692907 | 1.019239 |
kernel_id = self.get_kernel_id()
if kernel_id:
delete_url = self.add_token(url_path_join(self.server_url,
'api/kernels/',
kernel_id))
delete_req = requests.delete... | def shutdown_kernel(self) | Shutdown the kernel of the client. | 3.950003 | 3.855878 | 1.024411 |
def closing_plugin(self, cancelable=False):
for cl in self.clients:
cl.close()
self.set_option('recent_notebooks', self.recent_notebooks)
return True | Perform actions before parent main window is closed. | null | null | null | |
def refresh_plugin(self):
nb = None
if self.tabwidget.count():
client = self.tabwidget.currentWidget()
nb = client.notebookwidget
nb.setFocus()
else:
nb = None
self.update_notebook_actions() | Refresh tabwidget. | null | null | null | |
def get_plugin_actions(self):
create_nb_action = create_action(self,
_("New notebook"),
icon=ima.icon('filenew'),
triggered=self.create_new_client)
self.save_as_actio... | Return a list of actions related to plugin. | null | null | null | |
def register_plugin(self):
self.focus_changed.connect(self.main.plugin_focus_changed)
self.main.add_dockwidget(self)
self.ipyconsole = self.main.ipyconsole
self.create_new_client(give_focus=False)
icon_path = os.path.join(PACKAGE_PATH, 'images', 'icon.svg')
... | Register plugin in Spyder's main window. | null | null | null | |
def check_compatibility(self):
message = ''
value = True
if PYQT4 or PYSIDE:
message = _("You are working with Qt4 and in order to use this "
"plugin you need to have Qt5.<br><br>"
"Please update your Qt and/or PyQt pack... | Check compatibility for PyQt and sWebEngine. | null | null | null | |
def setup_menu_actions(self):
self.recent_notebook_menu.clear()
self.recent_notebooks_actions = []
if self.recent_notebooks:
for notebook in self.recent_notebooks:
name = notebook
action = \
create_action(self,
... | Setup and update the menu actions. | null | null | null | |
def update_notebook_actions(self):
if self.recent_notebooks:
self.clear_recent_notebooks_action.setEnabled(True)
else:
self.clear_recent_notebooks_action.setEnabled(False)
client = self.get_current_client()
if client:
if client.get_fil... | Update actions of the recent notebooks menu. | null | null | null | |
def add_to_recent(self, notebook):
if notebook not in self.recent_notebooks:
self.recent_notebooks.insert(0, notebook)
self.recent_notebooks = self.recent_notebooks[:20] | Add an entry to recent notebooks.
We only maintain the list of the 20 most recent notebooks. | null | null | null | |
def get_focus_client(self):
widget = QApplication.focusWidget()
for client in self.get_clients():
if widget is client or widget is client.notebookwidget:
return client | Return current notebook with focus, if any. | null | null | null | |
def get_current_client(self):
try:
client = self.tabwidget.currentWidget()
except AttributeError:
client = None
if client is not None:
return client | Return the currently selected notebook. | null | null | null | |
def get_current_client_name(self, short=False):
client = self.get_current_client()
if client:
if short:
return client.get_short_name()
else:
return client.get_filename() | Get the current client name. | null | null | null | |
def create_new_client(self, filename=None, give_focus=True):
# Generate the notebook name (in case of a new one)
if not filename:
if not osp.isdir(NOTEBOOK_TMPDIR):
os.makedirs(NOTEBOOK_TMPDIR)
nb_name = 'untitled' + str(self.untitled_num) + '.ipynb... | Create a new notebook or load a pre-existing one. | null | null | null | |
def close_client(self, index=None, client=None, save=False):
if not self.tabwidget.count():
return
if client is not None:
index = self.tabwidget.indexOf(client)
if index is None and client is None:
index = self.tabwidget.currentIndex()
... | Close client tab from index or widget (or close current tab). | null | null | null | |
def create_welcome_client(self):
if self.tabwidget.count() == 0:
welcome = open(WELCOME).read()
client = NotebookClient(self, WELCOME, ini_message=welcome)
self.add_tab(client)
return client | Create a welcome client with some instructions. | null | null | null | |
def save_as(self, name=None, close=False):
current_client = self.get_current_client()
current_client.save()
original_path = current_client.get_filename()
if not name:
original_name = osp.basename(original_path)
else:
original_name = name
... | Save notebook as. | null | null | null | |
def open_notebook(self, filenames=None):
if not filenames:
filenames, _selfilter = getopenfilenames(self, _("Open notebook"),
'', FILES_FILTER)
if filenames:
for filename in filenames:
self.creat... | Open a notebook from file. | null | null | null | |
def open_console(self, client=None):
if not client:
client = self.get_current_client()
if self.ipyconsole is not None:
kernel_id = client.get_kernel_id()
if not kernel_id:
QMessageBox.critical(
self, _('Error openin... | Open an IPython console for the given client or the current one. | null | null | null | |
def add_tab(self, widget):
self.clients.append(widget)
index = self.tabwidget.addTab(widget, widget.get_short_name())
self.tabwidget.setCurrentIndex(index)
self.tabwidget.setTabToolTip(index, widget.get_filename())
if self.dockwidget and not self.ismaximized:
... | Add tab. | null | null | null | |
def move_tab(self, index_from, index_to):
client = self.clients.pop(index_from)
self.clients.insert(index_to, client) | Move tab. | null | null | null | |
def set_stack_index(self, index, instance):
if instance == self:
self.tabwidget.setCurrentIndex(index) | Set the index of the current notebook. | null | null | null | |
with open(os.path.join(HERE, module, '_version.py'), 'r') as f:
data = f.read()
lines = data.split('\n')
for line in lines:
if line.startswith('VERSION_INFO'):
version_tuple = ast.literal_eval(line.split('=')[-1].strip())
version = '.'.join(map(str, version_tuple... | def get_version(module='spyder_notebook') | Get version. | 1.939748 | 1.926121 | 1.007075 |
servers = [si for si in notebookapp.list_running_servers()
if filename.startswith(si['notebook_dir'])]
try:
return max(servers, key=lambda si: len(si['notebook_dir']))
except ValueError:
return None | def find_best_server(filename) | Find the best server to open a notebook with. | 3.844475 | 3.032996 | 1.26755 |
filename = osp.abspath(filename)
home_dir = get_home_dir()
server_info = find_best_server(filename)
if server_info is not None:
print("Using existing server at", server_info['notebook_dir'])
return server_info
else:
if filename.startswith(home_dir):
nbdir = ... | def nbopen(filename) | Open a notebook using the best available server.
Returns information about the selected server. | 3.008704 | 2.99898 | 1.003243 |
result = self.collection.aggregate(pipeline, **kwargs)
if pymongo.version_tuple < (3, 0, 0):
result = result['result']
return result | def aggregate(self, pipeline, **kwargs) | Perform an aggregation and make sure that result will be everytime
CommandCursor. Will take care for pymongo version differencies
:param pipeline: {list} of aggregation pipeline stages
:return: {pymongo.command_cursor.CommandCursor} | 3.611606 | 3.310143 | 1.091072 |
for endpoint, func in app.view_functions.items():
app.view_functions[endpoint] = wrapHttpEndpoint(func) | def wrapAppEndpoints(app) | wraps all endpoints defined in the given flask app to measure how long time
each endpoints takes while being executed. This wrapping process is
supposed not to change endpoint behaviour.
:param app: Flask application instance
:return: | 3.520911 | 4.763986 | 0.739068 |
if _is_initialized():
def wrapper(f):
return wrapHttpEndpoint(f)
return wrapper
raise Exception(
"before measuring anything, you need to call init_app()") | def profile(*args, **kwargs) | http endpoint decorator | 17.068823 | 12.699333 | 1.344072 |
urlPath = CONF.get("endpointRoot", "flask-profiler")
fp = Blueprint(
'flask-profiler', __name__,
url_prefix="/" + urlPath,
static_folder="static/dist/", static_url_path='/static/dist')
@fp.route("/".format(urlPath))
@auth.login_required
def index():
return fp.s... | def registerInternalRouters(app) | These are the endpoints which are used to display measurements in the
flask-profiler dashboard.
Note: these should be defined after wrapping user defined endpoints
via wrapAppEndpoints()
:param app: Flask application instance
:return: | 2.402155 | 2.372697 | 1.012415 |
if self.kernel.mva is None:
print("Can't show log because no session exists")
else:
return self.kernel.Display(HTML(self.kernel.cachedlog)) | def line_showLog(self) | SAS Kernel magic to show the SAS log for the previous submitted code.
This magic is only available within the SAS Kernel | 19.063139 | 15.935843 | 1.196243 |
if self.kernel.mva is None:
self.kernel._allow_stdin = True
self.kernel._start_sas()
print("Session Started probably not the log you want")
full_log = highlight(self.kernel.mva.saslog(), SASLogLexer(), HtmlFormatter(full=True, style=SASLogStyle, lineseparator... | def line_showFullLog(self) | SAS Kernel magic to show the entire SAS log since the kernel was started (last restarted)
This magic is only available within the SAS Kernel | 13.009521 | 9.877088 | 1.317141 |
prmpt = OrderedDict()
for arg in args:
assert isinstance(arg, str)
prmpt[arg] = False
if not len(self.code):
if self.kernel.mva is None:
self.kernel._allow_stdin = True
self.kernel._start_sas()
self.kernel.m... | def line_prompt4var(self, *args) | %%prompt4var - Prompt for macro variables that will
be assigned to the SAS session. The variables will be
prompted each time the line magic is executed.
Example:
%prompt4var libpath file1
filename myfile "~&file1.";
libname data "&libpath"; | 8.427822 | 8.436977 | 0.998915 |
lines = re.split(r'[\n]\s*', log)
i = 0
elog = []
for line in lines:
i += 1
e = []
if line.startswith('ERROR'):
logger.debug("In ERROR Condition")
e = lines[(max(i - 15, 0)):(min(i + 16, len(lines)))]
... | def _which_display(self, log: str, output: str) -> HTML | Determines if the log or lst should be returned as the results for the cell based on parsing the log
looking for errors and the presence of lst output.
:param log: str log from code submission
:param output: None or str lst output if there was any
:return: The correct results based on l... | 3.291021 | 3.181231 | 1.034512 |
if not code.strip():
return {'status': 'ok', 'execution_count': self.execution_count,
'payload': [], 'user_expressions': {}}
if self.mva is None:
self._allow_stdin = True
self._start_sas()
if self.lst_len < 0:
self._g... | def do_execute_direct(self, code: str, silent: bool = False) -> [str, dict] | This is the main method that takes code from the Jupyter cell and submits it to the SAS server
:param code: code from the cell
:param silent:
:return: str with either the log or list | 4.972196 | 4.837529 | 1.027838 |
if info['line_num'] > 1:
relstart = info['column'] - (info['help_pos'] - info['start'])
else:
relstart = info['start']
seg = info['line'][:relstart]
if relstart > 0 and re.match('(?i)proc', seg.rsplit(None, 1)[-1]):
potentials = re.findall('(?... | def get_completions(self, info) | Get completions from kernel for procs and statements. | 3.758843 | 3.639188 | 1.03288 |
print("in shutdown function")
if self.hist_file:
with open(self.hist_file, 'wb') as fid:
data = '\n'.join(self.hist_cache[-self.max_hist_cache:])
fid.write(data.encode('utf-8'))
if self.mva:
self.mva._endsas()
self.mva ... | def do_shutdown(self, restart) | Shut down the app gracefully, saving history. | 4.912403 | 4.662902 | 1.053508 |
import os
import types
import code # arbitrary module which stays in the same dir as pdb
stdlibdir, _ = os.path.split(code.__file__)
pyfile = os.path.join(stdlibdir, name + '.py')
result = types.ModuleType(name)
exec(compile(open(pyfile).read(), pyfile, 'exec'), result.__dict__)
re... | def import_from_stdlib(name) | Copied from pdbpp https://bitbucket.org/antocuni/pdb | 4.394624 | 3.887266 | 1.130518 |
if self.shell:
globals_ = dict(_initial_globals)
else:
globals_ = dict(self.current_frame.f_globals)
globals_['_'] = self.db.last_obj
if cut is not None:
globals_.setdefault('cut', cut)
# For meta debuging purpose
globals_['___... | def get_globals(self) | Get enriched globals | 7.296063 | 7.037838 | 1.036691 |
exc_info = sys.exc_info()
type_, value = exc_info[:2]
self.db.obj_cache[id(exc_info)] = exc_info
return '<a href="%d" class="inspect">%s: %s</a>' % (
id(exc_info), escape(type_.__name__), escape(repr(value))
) | def handle_exc(self) | Return a formated exception traceback for wdb.js use | 4.492545 | 4.027781 | 1.11539 |
if message is None:
message = self.handle_exc()
else:
message = escape(message)
self.db.send(
'Echo|%s' % dump({
'for': escape(title or '%s failed' % cmd),
'val': message
})
) | def fail(self, cmd, title=None, message=None) | Send back captured exceptions | 10.523821 | 9.799845 | 1.073876 |
sys.path.insert(0, os.getcwd())
args, extrargs = parser.parse_known_args()
sys.argv = ['wdb'] + args.args + extrargs
if args.file:
file = os.path.join(os.getcwd(), args.file)
if args.source:
print('The source argument cannot be used with file.')
sys.exit(1)
... | def main() | Wdb entry point | 2.915615 | 2.767653 | 1.053461 |
shutdown_request = TCPServer.shutdown_request
def shutdown_request_patched(*args, **kwargs):
thread = current_thread()
shutdown_request(*args, **kwargs)
if thread in _exc_cache:
post_mortem_interaction(*_exc_cache.pop(thread))
TCPServer.shutdown_request = shutdown_... | def _patch_tcpserver() | Patch shutdown_request to open blocking interaction after the end of the
request | 4.418472 | 3.742804 | 1.180525 |
try:
linenum = '%d' % linenum
id = ' id="%s%s"' % (self._prefix[side], linenum)
except TypeError:
# handle blank lines where linenum is '>' or ''
id = ''
# replace those things that would get confused with HTML symbols
text = (
... | def _format_line(self, side, flag, linenum, text) | Returns HTML markup of "from" / "to" text lines
side -- 0 or 1 indicating "from" or "to" text
flag -- indicates if difference on line
linenum -- line number (used for line number column)
text -- line text to be marked up | 4.930156 | 4.871673 | 1.012005 |
if self.frame:
self.frame = self.frame.f_back
return self.frame is None | def up(self) | Go up in stack and return True if top frame | 7.908032 | 3.846054 | 2.056142 |
frame = frame or sys._getframe().f_back
for i in range(skip):
if not frame.f_back:
break
frame = frame.f_back
wdb = Wdb.get(server=server, port=port)
wdb.set_trace(frame)
return wdb | def set_trace(frame=None, skip=0, server=None, port=None) | Set trace on current line, or on given frame | 2.907951 | 2.880085 | 1.009675 |
wdb = Wdb.get(server=server, port=port)
if not wdb.stepping:
wdb.start_trace(full, frame or sys._getframe().f_back, below, under)
return wdb | def start_trace(
full=False, frame=None, below=0, under=None, server=None, port=None
) | Start tracing program at callee level
breaking on exception/breakpoints | 4.763362 | 4.455428 | 1.069114 |
log.info('Stopping trace')
wdb = Wdb.get(True) # Do not create an istance if there's None
if wdb and (not wdb.stepping or close_on_exit):
log.info('Stopping trace')
wdb.stop_trace(frame or sys._getframe().f_back)
if close_on_exit:
wdb.die()
return wdb | def stop_trace(frame=None, close_on_exit=False) | Stop tracing | 6.025693 | 6.008332 | 1.00289 |
for sck in list(Wdb._sockets):
try:
sck.close()
except Exception:
log.warn('Error in cleanup', exc_info=True) | def cleanup() | Close all sockets at exit | 8.203664 | 6.31772 | 1.298516 |
Wdb.get(server=server, port=port).shell(source=source, vars=vars) | def shell(source=None, vars=None, server=None, port=None) | Start a shell sourcing source or using vars as locals | 6.619021 | 6.32889 | 1.045842 |
pid = os.getpid()
thread = threading.current_thread()
wdb = Wdb._instances.get((pid, thread))
if not wdb and not no_create:
wdb = object.__new__(Wdb)
Wdb.__init__(wdb, server, port, force_uuid)
wdb.pid = pid
wdb.thread = thread
... | def get(no_create=False, server=None, port=None, force_uuid=None) | Get the thread local singleton | 2.958857 | 2.897688 | 1.02111 |
pid = os.getpid()
thread = threading.current_thread()
Wdb._instances.pop((pid, thread)) | def pop() | Remove instance from instance list | 10.126089 | 10.230076 | 0.989835 |
import __main__
__main__.__dict__.clear()
__main__.__dict__.update({
"__name__": "__main__",
"__file__": filename,
"__builtins__": __builtins__,
})
with open(filename, "rb") as fp:
statement = compile(fp.read(), filename, '... | def run_file(self, filename) | Run the file `filename` with trace | 2.586219 | 2.636474 | 0.980939 |
if globals is None:
import __main__
globals = __main__.__dict__
if locals is None:
locals = globals
self.reset()
if isinstance(cmd, str):
str_cmd = cmd
cmd = compile(str_cmd, fn or "<wdb>", "exec")
self.comp... | def run(self, cmd, fn=None, globals=None, locals=None) | Run the cmd `cmd` with trace | 3.487288 | 3.4475 | 1.011541 |
log.info('Connecting socket on %s:%d' % (self.server, self.port))
tries = 0
while not self._socket and tries < 10:
try:
time.sleep(.2 * tries)
self._socket = Socket((self.server, self.port))
except socket.error:
tri... | def connect(self) | Connect to wdb server | 4.196452 | 3.910954 | 1.073 |
fun = getattr(self, 'handle_' + event, None)
if not fun:
return self.trace_dispatch
below, continue_below = self.check_below(frame)
if (self.state.stops(frame, event)
or (event == 'line' and self.breaks(frame))
or (event == 'exception'... | def trace_dispatch(self, frame, event, arg) | This function is called every line,
function call, function return and exception during trace | 4.367871 | 4.324721 | 1.009978 |
trace_log.info(
'Frame:%s. Event: %s. Arg: %r' % (pretty_frame(frame), event, arg)
)
trace_log.debug(
'state %r breaks ? %s stops ? %s' % (
self.state, self.breaks(frame, no_remove=True),
self.state.stops(frame, event)
... | def trace_debug_dispatch(self, frame, event, arg) | Utility function to add debug to tracing | 3.938303 | 3.907854 | 1.007792 |
if self.tracing:
return
self.reset()
log.info('Starting trace')
frame = frame or sys._getframe().f_back
# Setting trace without pausing
self.set_trace(frame, break_=False)
self.tracing = True
self.below = below
self.under = und... | def start_trace(self, full=False, frame=None, below=0, under=None) | Start tracing from here | 4.733479 | 4.533912 | 1.044017 |
# We are already tracing, do nothing
trace_log.info(
'Setting trace %s (stepping %s) (current_trace: %s)' % (
pretty_frame(frame or sys._getframe().f_back), self.stepping,
sys.gettrace()
)
)
if self.stepping or self.closed:... | def set_trace(self, frame=None, break_=True) | Break at current state | 4.693017 | 4.697606 | 0.999023 |
self.tracing = False
self.full = False
frame = frame or sys._getframe().f_back
while frame:
del frame.f_trace
frame = frame.f_back
sys.settrace(None)
log.info('Stopping trace') | def stop_trace(self, frame=None) | Stop tracing from here | 3.660503 | 3.36798 | 1.086854 |
self.state = Until(frame, frame.f_lineno) | def set_until(self, frame, lineno=None) | Stop on the next line number. | 13.447654 | 9.04128 | 1.487362 |
self.state = Running(frame)
if not self.tracing and not self.breakpoints:
# If we were in a set_trace and there's no breakpoint to trace for
# Run without trace
self.stop_trace() | def set_continue(self, frame) | Don't stop anymore | 14.959404 | 12.949531 | 1.155208 |
log.info(
'Setting break fn:%s lno:%s tmp:%s cond:%s fun:%s' %
(filename, lineno, temporary, cond, funcname)
)
breakpoint = self.get_break(
filename, lineno, temporary, cond, funcname
)
self.breakpoints.add(breakpoint)
log.info... | def set_break(
self, filename, lineno=None, temporary=False, cond=None,
funcname=None
) | Put a breakpoint for filename | 3.294499 | 3.258224 | 1.011133 |
log.info(
'Removing break fn:%s lno:%s tmp:%s cond:%s fun:%s' %
(filename, lineno, temporary, cond, funcname)
)
breakpoint = self.get_break(
filename, lineno, temporary or False, cond, funcname
)
if temporary is None and breakpoint no... | def clear_break(
self, filename, lineno=None, temporary=False, cond=None,
funcname=None
) | Remove a breakpoint | 3.431522 | 3.307838 | 1.037391 |
try:
return repr(obj)
except Exception as e:
return '??? Broken repr (%s: %s)' % (type(e).__name__, e) | def safe_repr(self, obj) | Like a repr but without exception | 4.192169 | 3.872447 | 1.082563 |
context = context and dict(context) or {}
recursion = id(obj) in context
if not recursion:
context[id(obj)] = obj
try:
rv = self.better_repr(obj, context, html, level + 1, full)
except Exception:
rv = None
i... | def safe_better_repr(
self, obj, context=None, html=True, level=0, full=False
) | Repr with inspect links on objects | 3.333254 | 3.232248 | 1.031249 |
abbreviate = (lambda x, level, **kw: x) if full else cut_if_too_long
def get_too_long_repr(ie):
r = '[%d more…]' % ie.size
if html:
self.obj_cache[id(obj)] = obj
return '<a href="dump/%d" class="inspect">%s</a>' % (
id... | def better_repr(self, obj, context=None, html=True, level=1, full=False) | Repr with html decorations or indentation | 2.367898 | 2.37153 | 0.998468 |
self.hooked = ''
def display_hook(obj):
# That's some dirty hack
self.hooked += self.safe_better_repr(obj)
self.last_obj = obj
stdout, stderr = sys.stdout, sys.stderr
if with_hook:
d_hook = sys.displayhook
sys.display... | def capture_output(self, with_hook=True) | Steal stream output, return them in string, restore them | 3.135108 | 3.086927 | 1.015608 |
def safe_getattr(key):
try:
return getattr(thing, key)
except Exception as e:
return 'Error getting attr "%s" from "%s" (%s: %s)' % (
key, thing, type(e).__name__, e
)
return dict((
... | def dmp(self, thing) | Dump the content of an object in a dict for wdb.js | 4.145342 | 4.001453 | 1.035959 |
import linecache
# Hack for frozen importlib bootstrap
if filename == '<frozen importlib._bootstrap>':
filename = os.path.join(
os.path.dirname(linecache.__file__), 'importlib',
'_bootstrap.py'
)
return to_unicode_string(
... | def get_file(self, filename) | Get file source from cache | 6.299393 | 6.344815 | 0.992841 |
stack = []
if t and t.tb_frame == f:
t = t.tb_next
while f is not None:
stack.append((f, f.f_lineno))
f = f.f_back
stack.reverse()
i = max(0, len(stack) - 1)
while t is not None:
stack.append((t.tb_frame, t.tb_linen... | def get_stack(self, f, t) | Build the stack from frame and traceback | 2.359196 | 2.060053 | 1.145211 |
import linecache
frames = []
stack, _ = self.get_stack(frame, tb)
current = 0
for i, (stack_frame, lno) in enumerate(stack):
code = stack_frame.f_code
filename = code.co_filename or '<unspecified>'
line = None
if filename[... | def get_trace(self, frame, tb) | Get a dict of the traceback for wdb.js use | 4.182486 | 4.088464 | 1.022997 |
log.debug('Sending %s' % data)
if not self._socket:
log.warn('No connection')
return
self._socket.send_bytes(data.encode('utf-8')) | def send(self, data) | Send data through websocket | 3.947353 | 3.640123 | 1.084401 |
log.debug('Receiving')
if not self._socket:
log.warn('No connection')
return
try:
if timeout:
rv = self._socket.poll(timeout)
if not rv:
log.info('Connection timeouted')
return 'Q... | def receive(self, timeout=None) | Receive data through websocket | 3.967093 | 3.786549 | 1.047681 |
log.info(
'Interaction %r %r %r %r' %
(frame, tb, exception, exception_description)
)
self.reconnect_if_needed()
self.stepping = not shell
if not iframe_mode:
opts = {}
if shell:
opts['type_'] = 'shell'
... | def interaction(
self,
frame,
tb=None,
exception='Wdb',
exception_description='Stepping',
init=None,
shell=False,
shell_vars=None,
source=None,
iframe_mode=False,
timeout=None,
... | User interaction handling blocking on socket receive | 4.62004 | 4.532458 | 1.019323 |
fun = frame.f_code.co_name
log.info('Calling: %r' % fun)
init = 'Echo|%s' % dump({
'for':
'__call__',
'val':
'%s(%s)' % (
fun, ', '.join([
'%s=%s' % (key, self.safe_better_repr(value))
... | def handle_call(self, frame, argument_list) | This method is called when there is the remote possibility
that we ever need to stop in this function. | 7.349651 | 7.327668 | 1.003 |
log.info('Stopping at line %s' % pretty_frame(frame))
self.interaction(frame) | def handle_line(self, frame, arg) | This function is called when we stop or break at this line. | 17.361759 | 12.811 | 1.355223 |
self.obj_cache[id(return_value)] = return_value
self.extra_vars['__return__'] = return_value
fun = frame.f_code.co_name
log.info('Returning from %r with value: %r' % (fun, return_value))
init = 'Echo|%s' % dump({
'for': '__return__',
'val': self.... | def handle_return(self, frame, return_value) | This function is called when a return trap is set here. | 6.280106 | 6.105074 | 1.02867 |
type_, value, tb = exc_info
# Python 3 is broken see http://bugs.python.org/issue17413
_value = value
if not isinstance(_value, BaseException):
_value = type_(value)
fake_exc_info = type_, _value, tb
log.error('Exception during trace', exc_info=fake_e... | def handle_exception(self, frame, exc_info) | This function is called if an exception occurs,
but only if we are to stop at or just below this level. | 5.924573 | 6.02658 | 0.983074 |
for breakpoint in set(self.breakpoints):
if breakpoint.breaks(frame):
if breakpoint.temporary and not no_remove:
self.breakpoints.remove(breakpoint)
return True
return False | def breaks(self, frame, no_remove=False) | Return True if there's a breakpoint at frame | 3.794252 | 3.503918 | 1.08286 |
return [
breakpoint for breakpoint in self.breakpoints
if breakpoint.on_file(filename)
] | def get_file_breaks(self, filename) | List all file `filename` breakpoints | 8.117448 | 6.374948 | 1.273336 |
return list(
filter(
lambda x: x is not None, [
getattr(breakpoint, 'line', None)
for breakpoint in self.breakpoints
if breakpoint.on_file(filename)
]
)
) | def get_breaks_lno(self, filename) | List all line numbers that have a breakpoint | 4.370475 | 3.446418 | 1.268121 |
log.info('Time to die')
if self.connected:
try:
self.send('Die')
except Exception:
pass
if self._socket:
self._socket.close()
self.pop() | def die(self) | Time to quit | 6.415954 | 5.810919 | 1.10412 |
assert name not in self._processes, "process names must be unique"
proc = self._process_ctor(cmd,
name=name,
quiet=quiet,
colour=next(self._colours),
env=env,
... | def add_process(self, name, cmd, quiet=False, env=None, cwd=None) | Add a process to this manager instance. The process will not be started
until :func:`~honcho.manager.Manager.loop` is called. | 3.985784 | 4.113002 | 0.969069 |
def _terminate(signum, frame):
self._system_print("%s received\n" % SIGNALS[signum]['name'])
self.returncode = SIGNALS[signum]['rc']
self.terminate()
signal.signal(signal.SIGTERM, _terminate)
signal.signal(signal.SIGINT, _terminate)
self._st... | def loop(self) | Start all the added processes and multiplex their output onto the bound
printer (which by default will print to STDOUT).
If one process terminates, all the others will be terminated by
Honcho, and :func:`~honcho.manager.Manager.loop` will return.
This method will block until all the pr... | 2.820232 | 2.864325 | 0.984606 |
for_termination = []
for n, p in iteritems(self._processes):
if 'returncode' not in p:
for_termination.append(n)
for n in for_termination:
p = self._processes[n]
signame = 'SIGKILL' if force else 'SIGTERM'
self._system_pr... | def _killall(self, force=False) | Kill all remaining processes, forcefully if requested. | 3.752277 | 3.623862 | 1.035436 |
values = {}
for line in content.splitlines():
lexer = shlex.shlex(line, posix=True)
tokens = list(lexer)
# parses the assignment statement
if len(tokens) < 3:
continue
name, op = tokens[:2]
value = ''.join(tokens[2:])
if op != '=':
... | def parse(content) | Parse the content of a .env file (a line-delimited KEY=value format) into a
dictionary mapping keys to values. | 2.679026 | 2.608424 | 1.027067 |
if env is not None and env.get("PORT") is not None:
port = int(env.get("PORT"))
if quiet is None:
quiet = []
con = defaultdict(lambda: 1)
if concurrency is not None:
con.update(concurrency)
out = []
for name, cmd in compat.iteritems(processes):
for i in r... | def expand_processes(processes, concurrency=None, env=None, quiet=None, port=None) | Get a list of the processes that need to be started given the specified
list of process types, concurrency, environment, quietness, and base port
number.
Returns a list of ProcessParams objects, which have `name`, `cmd`, `env`,
and `quiet` attributes, corresponding to the parameters to the constructor
... | 3.314176 | 2.832216 | 1.170171 |
patt = re.compile(r'\W', re.UNICODE)
return re.sub(patt, '-', value) | def dashrepl(value) | Replace any non-word characters with a dash. | 4.019563 | 2.867944 | 1.401549 |
for root, dirs, files in os.walk(static_dir):
for filename in files:
if cls._pattern.match(filename):
APPS_INCLUDE_DIRS.append(static_dir)
return | def traverse_tree(cls, static_dir) | traverse the static folders an look for at least one file ending in .scss/.sass | 4.639054 | 4.279216 | 1.08409 |
app_configs = apps.get_app_configs()
for app_config in app_configs:
ignore_dirs = []
for root, dirs, files in os.walk(app_config.path):
if [True for idir in ignore_dirs if root.startswith(idir)]:
continue
if '__init__.p... | def find_sources(self) | Look for Python sources available for the current configuration. | 2.40705 | 2.321547 | 1.03683 |
callvisitor = FuncCallVisitor('sass_processor')
tree = ast.parse(open(filename, 'rb').read())
callvisitor.visit(tree)
for sass_fileurl in callvisitor.sass_files:
sass_filename = find_file(sass_fileurl)
if not sass_filename or sass_filename in self.process... | def parse_source(self, filename) | Extract the statements from the given file, look for function calls
`sass_processor(scss_file)` and compile the filename into CSS. | 4.127904 | 3.205739 | 1.287661 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.