text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show_kernel_error(self, error):
"""Show kernel initialization errors.""" |
# 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('-', '‑')
message = _("An error occurred while starting the kernel")
kernel_error_template = Template(KERNEL_ERROR)
page = kernel_error_template.substitute(css_path=CSS_PATH,
message=message,
error=error)
self.setHtml(page) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show_loading_page(self):
"""Show a loading animation while the kernel is starting.""" |
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,
loading_img=loading_img,
message=message)
self.setHtml(page) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register(self, server_info):
"""Register attributes that can be computed with the server info.""" |
# 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 url to send requests to
self.server_url = server_info['url']
# Server token
self.token = server_info['token']
url = url_path_join(self.server_url, 'notebooks',
url_escape(self.path))
# Set file url to load this notebook
self.file_url = self.add_token(url) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def go_to(self, url_or_text):
"""Go to page utl.""" |
if is_text_string(url_or_text):
url = QUrl(url_or_text)
else:
url = url_or_text
self.notebookwidget.load(url) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_short_name(self):
"""Get a short name for the notebook.""" |
sname = osp.splitext(osp.basename(self.filename))[0]
if len(sname) > 20:
fm = QFontMetrics(QFont())
sname = fm.elidedText(sname, Qt.ElideRight, 110)
return sname |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_kernel_id(self):
""" Get the kernel id of the client. Return a str with the kernel id or None. """ |
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:
notebook_path = session.get('notebook', {}).get('path')
if notebook_path is not None and notebook_path == path:
kernel_id = session['kernel']['id']
return kernel_id |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shutdown_kernel(self):
"""Shutdown the kernel of the client.""" |
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(delete_url)
if delete_req.status_code != 204:
QMessageBox.warning(
self,
_("Server error"),
_("The Jupyter Notebook server "
"failed to shutdown the kernel "
"associated with this notebook. "
"If you want to shut it down, "
"you'll have to close Spyder.")) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_plugin(self):
"""Register plugin in Spyder's main window.""" |
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')
self.main.add_to_fileswitcher(self, self.tabwidget, self.clients,
QIcon(icon_path))
self.recent_notebook_menu.aboutToShow.connect(self.setup_menu_actions) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_compatibility(self):
"""Check compatibility for PyQt and sWebEngine.""" |
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 packages to "
"meet this requirement.")
value = False
return value, message |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_notebook_actions(self):
"""Update actions of the recent notebooks menu.""" |
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_filename() != WELCOME:
self.save_as_action.setEnabled(True)
self.open_console_action.setEnabled(True)
self.options_menu.clear()
add_actions(self.options_menu, self.menu_actions)
return
self.save_as_action.setEnabled(False)
self.open_console_action.setEnabled(False)
self.options_menu.clear()
add_actions(self.options_menu, self.menu_actions) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_to_recent(self, notebook):
"""
Add an entry to recent notebooks.
We only maintain the list of the 20 most recent notebooks.
""" |
if notebook not in self.recent_notebooks:
self.recent_notebooks.insert(0, notebook)
self.recent_notebooks = self.recent_notebooks[:20] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_focus_client(self):
"""Return current notebook with focus, if any.""" |
widget = QApplication.focusWidget()
for client in self.get_clients():
if widget is client or widget is client.notebookwidget:
return client |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_current_client(self):
"""Return the currently selected notebook.""" |
try:
client = self.tabwidget.currentWidget()
except AttributeError:
client = None
if client is not None:
return client |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_current_client_name(self, short=False):
"""Get the current client name.""" |
client = self.get_current_client()
if client:
if short:
return client.get_short_name()
else:
return client.get_filename() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_new_client(self, filename=None, give_focus=True):
"""Create a new notebook or load a pre-existing one.""" |
# 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'
filename = osp.join(NOTEBOOK_TMPDIR, nb_name)
nb_contents = nbformat.v4.new_notebook()
nbformat.write(nb_contents, filename)
self.untitled_num += 1
# Save spyder_pythonpath before creating a client
# because it's needed by our kernel spec.
if not self.testing:
CONF.set('main', 'spyder_pythonpath',
self.main.get_spyder_pythonpath())
# Open the notebook with nbopen and get the url we need to render
try:
server_info = nbopen(filename)
except (subprocess.CalledProcessError, NBServerError):
QMessageBox.critical(
self,
_("Server error"),
_("The Jupyter Notebook server failed to start or it is "
"taking too much time to do it. Please start it in a "
"system terminal with the command 'jupyter notebook' to "
"check for errors."))
# Create a welcome widget
# See issue 93
self.untitled_num -= 1
self.create_welcome_client()
return
welcome_client = self.create_welcome_client()
client = NotebookClient(self, filename)
self.add_tab(client)
if NOTEBOOK_TMPDIR not in filename:
self.add_to_recent(filename)
self.setup_menu_actions()
client.register(server_info)
client.load_notebook()
if welcome_client and not self.testing:
self.tabwidget.setCurrentIndex(0) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_welcome_client(self):
"""Create a welcome client with some instructions.""" |
if self.tabwidget.count() == 0:
welcome = open(WELCOME).read()
client = NotebookClient(self, WELCOME, ini_message=welcome)
self.add_tab(client)
return client |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_as(self, name=None, close=False):
"""Save notebook as.""" |
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
filename, _selfilter = getsavefilename(self, _("Save notebook"),
original_name, FILES_FILTER)
if filename:
nb_contents = nbformat.read(original_path, as_version=4)
nbformat.write(nb_contents, filename)
if not close:
self.close_client(save=True)
self.create_new_client(filename=filename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open_notebook(self, filenames=None):
"""Open a notebook from file.""" |
if not filenames:
filenames, _selfilter = getopenfilenames(self, _("Open notebook"),
'', FILES_FILTER)
if filenames:
for filename in filenames:
self.create_new_client(filename=filename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open_console(self, client=None):
"""Open an IPython console for the given client or the current one.""" |
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 opening console'),
_('There is no kernel associated to this notebook.'))
return
self.ipyconsole._create_client_for_kernel(kernel_id, None, None,
None)
ipyclient = self.ipyconsole.get_current_client()
ipyclient.allow_rename = False
self.ipyconsole.rename_client_tab(ipyclient,
client.get_short_name()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_tab(self, widget):
"""Add tab.""" |
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:
self.dockwidget.setVisible(True)
self.dockwidget.raise_()
self.activateWindow()
widget.notebookwidget.setFocus() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_stack_index(self, index, instance):
"""Set the index of the current notebook.""" |
if instance == self:
self.tabwidget.setCurrentIndex(index) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_version(module='spyder_notebook'):
"""Get version.""" |
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))
break
return version |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_best_server(filename):
"""Find the best server to open a notebook with.""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nbopen(filename):
""" Open a notebook using the best available server. Returns information about the selected server. """ |
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 = home_dir
else:
nbdir = osp.dirname(filename)
print("Starting new server")
command = [sys.executable, '-m', 'notebook', '--no-browser',
'--notebook-dir={}'.format(nbdir),
'--NotebookApp.password=',
"--KernelSpecManager.kernel_spec_class='{}'".format(
KERNELSPEC)]
if os.name == 'nt':
creation_flag = 0x08000000 # CREATE_NO_WINDOW
else:
creation_flag = 0 # Default value
if DEV:
env = os.environ.copy()
env["PYTHONPATH"] = osp.dirname(get_module_path('spyder'))
proc = subprocess.Popen(command, creationflags=creation_flag,
env=env)
else:
proc = subprocess.Popen(command, creationflags=creation_flag)
# Kill the server at exit. We need to use psutil for this because
# Popen.terminate doesn't work when creationflags or shell=True
# are used.
def kill_server_and_childs(pid):
ps_proc = psutil.Process(pid)
for child in ps_proc.children(recursive=True):
child.kill()
ps_proc.kill()
atexit.register(kill_server_and_childs, proc.pid)
# Wait ~25 secs for the server to be up
for _x in range(100):
server_info = find_best_server(filename)
if server_info is not None:
break
else:
time.sleep(0.25)
if server_info is None:
raise NBServerError()
return server_info |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def profile(*args, **kwargs):
""" http endpoint decorator """ |
if _is_initialized():
def wrapper(f):
return wrapHttpEndpoint(f)
return wrapper
raise Exception(
"before measuring anything, you need to call init_app()") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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: """ |
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.send_static_file("index.html")
@fp.route("/api/measurements/".format(urlPath))
@auth.login_required
def filterMeasurements():
args = dict(request.args.items())
measurements = collection.filter(args)
return jsonify({"measurements": list(measurements)})
@fp.route("/api/measurements/grouped".format(urlPath))
@auth.login_required
def getMeasurementsSummary():
args = dict(request.args.items())
measurements = collection.getSummary(args)
return jsonify({"measurements": list(measurements)})
@fp.route("/api/measurements/<measurementId>".format(urlPath))
@auth.login_required
def getContext(measurementId):
return jsonify(collection.get(measurementId))
@fp.route("/api/measurements/timeseries/".format(urlPath))
@auth.login_required
def getRequestsTimeseries():
args = dict(request.args.items())
return jsonify({"series": collection.getTimeseries(args)})
@fp.route("/api/measurements/methodDistribution/".format(urlPath))
@auth.login_required
def getMethodDistribution():
args = dict(request.args.items())
return jsonify({
"distribution": collection.getMethodDistribution(args)})
@fp.route("/db/dumpDatabase")
@auth.login_required
def dumpDatabase():
response = jsonify({
"summary": collection.getSummary()})
response.headers["Content-Disposition"] = "attachment; filename=dump.json"
return response
@fp.route("/db/deleteDatabase")
@auth.login_required
def deleteDatabase():
response = jsonify({
"status": collection.truncate()})
return response
@fp.after_request
def x_robots_tag_header(response):
response.headers['X-Robots-Tag'] = 'noindex, nofollow'
return response
app.register_blueprint(fp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 """ |
if self.kernel.mva is None:
print("Can't show log because no session exists")
else:
return self.kernel.Display(HTML(self.kernel.cachedlog)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 log and lst :rtype: str """ |
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)))]
elog = elog + e
tlog = '\n'.join(elog)
logger.debug("elog count: " + str(len(elog)))
logger.debug("tlog: " + str(tlog))
color_log = highlight(log, SASLogLexer(), HtmlFormatter(full=True, style=SASLogStyle, lineseparator="<br>"))
# store the log for display in the showSASLog nbextension
self.cachedlog = color_log
# Are there errors in the log? if show the lines on each side of the error
if len(elog) == 0 and len(output) > self.lst_len: # no error and LST output
debug1 = 1
logger.debug("DEBUG1: " + str(debug1) + " no error and LST output ")
return HTML(output)
elif len(elog) == 0 and len(output) <= self.lst_len: # no error and no LST
debug1 = 2
logger.debug("DEBUG1: " + str(debug1) + " no error and no LST")
return HTML(color_log)
elif len(elog) > 0 and len(output) <= self.lst_len: # error and no LST
debug1 = 3
logger.debug("DEBUG1: " + str(debug1) + " error and no LST")
return HTML(color_log)
else: # errors and LST
debug1 = 4
logger.debug("DEBUG1: " + str(debug1) + " errors and LST")
return HTML(color_log + output) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 """ |
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._get_lst_len()
if code.startswith('Obfuscated SAS Code'):
logger.debug("decoding string")
tmp1 = code.split()
decode = base64.b64decode(tmp1[-1])
code = decode.decode('utf-8')
if code.startswith('showSASLog_11092015') == False and code.startswith("CompleteshowSASLog_11092015") == False:
logger.debug("code type: " + str(type(code)))
logger.debug("code length: " + str(len(code)))
logger.debug("code string: " + code)
if code.startswith("/*SASKernelTest*/"):
res = self.mva.submit(code, "text")
else:
res = self.mva.submit(code, prompt=self.promptDict)
self.promptDict = {}
if res['LOG'].find("SAS process has terminated unexpectedly") > -1:
print(res['LOG'], '\n' "Restarting SAS session on your behalf")
self.do_shutdown(True)
return res['LOG']
output = res['LST']
log = res['LOG']
return self._which_display(log, output)
elif code.startswith("CompleteshowSASLog_11092015") == True and code.startswith('showSASLog_11092015') == False:
full_log = highlight(self.mva.saslog(), SASLogLexer(),
HtmlFormatter(full=True, style=SASLogStyle, lineseparator="<br>",
title="Full SAS Log"))
return full_log.replace('\n', ' ')
else:
return self.cachedlog.replace('\n', ' ') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_completions(self, info):
""" Get completions from kernel for procs and statements. """ |
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('(?i)^' + info['obj'] + '.*', self.strproclist, re.MULTILINE)
return potentials
else:
lastproc = info['code'].lower()[:info['help_pos']].rfind('proc')
lastdata = info['code'].lower()[:info['help_pos']].rfind('data ')
proc = False
data = False
if lastproc + lastdata == -2:
pass
else:
if lastproc > lastdata:
proc = True
else:
data = True
if proc:
# we are not in data section should see if proc option or statement
lastsemi = info['code'].rfind(';')
mykey = 's'
if lastproc > lastsemi:
mykey = 'p'
procer = re.search('(?i)proc\s\w+', info['code'][lastproc:])
method = procer.group(0).split(' ')[-1].upper() + mykey
mylist = self.compglo[method][0]
potentials = re.findall('(?i)' + info['obj'] + '.+', '\n'.join(str(x) for x in mylist), re.MULTILINE)
return potentials
elif data:
# we are in statements (probably if there is no data)
# assuming we are in the middle of the code
lastsemi = info['code'].rfind(';')
mykey = 's'
if lastproc > lastsemi:
mykey = 'p'
mylist = self.compglo['DATA' + mykey][0]
potentials = re.findall('(?i)^' + info['obj'] + '.*', '\n'.join(str(x) for x in mylist), re.MULTILINE)
return potentials
else:
potentials = ['']
return potentials |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_shutdown(self, restart):
""" Shut down the app gracefully, saving history. """ |
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 = None
if restart:
self.Print("Restarting kernel...")
self.reload_magics()
self.restart_kernel()
self.Print("Done!")
return {'status': 'ok', 'restart': restart} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_globals(self):
"""Get enriched globals""" |
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_['___wdb'] = self.db
# Hack for function scope eval
globals_.update(self.current_locals)
for var, val in self.db.extra_vars.items():
globals_[var] = val
self.db.extra_items = {}
return globals_ |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_exc(self):
"""Return a formated exception traceback for wdb.js use""" |
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))
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fail(self, cmd, title=None, message=None):
"""Send back captured exceptions""" |
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
})
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
"""Wdb entry point""" |
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)
if not os.path.exists(file):
print('Error:', file, 'does not exist')
sys.exit(1)
if args.trace:
Wdb.get().run_file(file)
else:
def wdb_pm(xtype, value, traceback):
sys.__excepthook__(xtype, value, traceback)
wdb = Wdb.get()
wdb.reset()
wdb.interaction(None, traceback, post_mortem=True)
sys.excepthook = wdb_pm
with open(file) as f:
code = compile(f.read(), file, 'exec')
execute(code, globals(), globals())
else:
source = None
if args.source:
source = os.path.join(os.getcwd(), args.source)
if not os.path.exists(source):
print('Error:', source, 'does not exist')
sys.exit(1)
Wdb.get().shell(source) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _patch_tcpserver():
""" Patch shutdown_request to open blocking interaction after the end of the request """ |
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_request_patched |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def up(self):
"""Go up in stack and return True if top frame""" |
if self.frame:
self.frame = self.frame.f_back
return self.frame is None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_trace(frame=None, skip=0, server=None, port=None):
"""Set trace on current line, or on given frame""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cleanup():
"""Close all sockets at exit""" |
for sck in list(Wdb._sockets):
try:
sck.close()
except Exception:
log.warn('Error in cleanup', exc_info=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shell(source=None, vars=None, server=None, port=None):
"""Start a shell sourcing source or using vars as locals""" |
Wdb.get(server=server, port=port).shell(source=source, vars=vars) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(no_create=False, server=None, port=None, force_uuid=None):
"""Get the thread local singleton""" |
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
Wdb._instances[(pid, thread)] = wdb
elif wdb:
if (server is not None and wdb.server != server
or port is not None and wdb.port != port):
log.warn('Different server/port set, ignoring')
else:
wdb.reconnect_if_needed()
return wdb |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pop():
"""Remove instance from instance list""" |
pid = os.getpid()
thread = threading.current_thread()
Wdb._instances.pop((pid, thread)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_file(self, filename):
"""Run the file `filename` with trace""" |
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, 'exec')
self.run(statement, filename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self, cmd, fn=None, globals=None, locals=None):
"""Run the cmd `cmd` with trace""" |
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.compile_cache[id(cmd)] = str_cmd
if fn:
from linecache import getline
lno = 1
while True:
line = getline(fn, lno, globals)
if line is None:
lno = None
break
if executable_line(line):
break
lno += 1
self.start_trace()
if lno is not None:
self.breakpoints.add(LineBreakpoint(fn, lno, temporary=True))
try:
execute(cmd, globals, locals)
finally:
self.stop_trace() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(self):
"""Connect to wdb server""" |
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:
tries += 1
log.warning(
'You must start/install wdb.server '
'(Retrying on %s:%d) [Try #%d/10]' %
(self.server, self.port, tries)
)
self._socket = None
if not self._socket:
log.warning('Could not connect to server')
return
Wdb._sockets.append(self._socket)
self._socket.send_bytes(self.uuid.encode('utf-8')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trace_dispatch(self, frame, event, arg):
"""This function is called every line, function call, function return and exception during trace""" |
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' and (self.full or below))):
fun(frame, arg)
if event == 'return' and frame == self.state.frame:
# Upping state
if self.state.up():
# No more frames
self.stop_trace()
return
# Threading / Multiprocessing support
co = self.state.frame.f_code
if ((co.co_filename.endswith('threading.py')
and co.co_name.endswith('_bootstrap_inner'))
or (self.state.frame.f_code.co_filename.endswith(
os.path.join('multiprocessing', 'process.py'))
and self.state.frame.f_code.co_name == '_bootstrap')):
# Thread / Process is dead
self.stop_trace()
self.die()
return
if (event == 'call' and not self.stepping and not self.full
and not continue_below
and not self.get_file_breaks(frame.f_code.co_filename)):
# Don't trace anymore here
return
return self.trace_dispatch |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trace_debug_dispatch(self, frame, event, arg):
"""Utility function to add debug to tracing""" |
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)
)
)
if event == 'return':
trace_log.debug(
'Return: frame: %s, state: %s, state.f_back: %s' % (
pretty_frame(frame), pretty_frame(self.state.frame),
pretty_frame(self.state.frame.f_back)
)
)
if self.trace_dispatch(frame, event, arg):
return self.trace_debug_dispatch
trace_log.debug("No trace %s" % pretty_frame(frame)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start_trace(self, full=False, frame=None, below=0, under=None):
"""Start tracing from here""" |
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 = under
self.full = full |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_trace(self, frame=None, break_=True):
"""Break at current state""" |
# 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:
return
self.reset()
trace = (
self.trace_dispatch
if trace_log.level >= 30 else self.trace_debug_dispatch
)
trace_frame = frame = frame or sys._getframe().f_back
while frame:
frame.f_trace = trace
frame = frame.f_back
self.state = Step(trace_frame) if break_ else Running(trace_frame)
sys.settrace(trace) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop_trace(self, frame=None):
"""Stop tracing from here""" |
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') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_until(self, frame, lineno=None):
"""Stop on the next line number.""" |
self.state = Until(frame, frame.f_lineno) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_continue(self, frame):
"""Don't stop anymore""" |
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_break( self, filename, lineno=None, temporary=False, cond=None, funcname=None ):
"""Put a breakpoint for filename""" |
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('Breakpoint %r added' % breakpoint)
return breakpoint |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clear_break( self, filename, lineno=None, temporary=False, cond=None, funcname=None ):
"""Remove a breakpoint""" |
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 not in self.breakpoints:
breakpoint = self.get_break(filename, lineno, True, cond, funcname)
try:
self.breakpoints.remove(breakpoint)
log.info('Breakpoint %r removed' % breakpoint)
except Exception:
log.info('Breakpoint %r not removed: not found' % breakpoint) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def safe_repr(self, obj):
"""Like a repr but without exception""" |
try:
return repr(obj)
except Exception as e:
return '??? Broken repr (%s: %s)' % (type(e).__name__, e) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def safe_better_repr( self, obj, context=None, html=True, level=0, full=False ):
"""Repr with inspect links on objects""" |
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
if rv:
return rv
self.obj_cache[id(obj)] = obj
if html:
return '<a href="%d" class="inspect">%s%s</a>' % (
id(obj), 'Recursion of '
if recursion else '', escape(self.safe_repr(obj))
)
return '%s%s' % (
'Recursion of ' if recursion else '', self.safe_repr(obj)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def capture_output(self, with_hook=True):
"""Steal stream output, return them in string, restore them""" |
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.displayhook = display_hook
sys.stdout, sys.stderr = StringIO(), StringIO()
out, err = [], []
try:
yield out, err
finally:
out.extend(sys.stdout.getvalue().splitlines())
err.extend(sys.stderr.getvalue().splitlines())
if with_hook:
sys.displayhook = d_hook
sys.stdout, sys.stderr = stdout, stderr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dmp(self, thing):
"""Dump the content of an object in a dict for wdb.js""" |
def safe_getattr(key):
"""Avoid crash on getattr"""
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((
escape(key), {
'val': self.safe_better_repr(safe_getattr(key)),
'type': type(safe_getattr(key)).__name__
}
) for key in dir(thing)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_file(self, filename):
"""Get file source from cache""" |
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(
''.join(linecache.getlines(filename)), filename
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_stack(self, f, t):
"""Build the stack from frame and traceback""" |
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_lineno))
t = t.tb_next
if f is None:
i = max(0, len(stack) - 1)
return stack, i |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_trace(self, frame, tb):
"""Get a dict of the traceback for wdb.js use""" |
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[0] == '<' and filename[-1] == '>':
line = get_source_from_byte_code(code)
fn = filename
else:
fn = os.path.abspath(filename)
if not line:
linecache.checkcache(filename)
line = linecache.getline(filename, lno, stack_frame.f_globals)
if not line:
line = self.compile_cache.get(id(code), '')
line = to_unicode_string(line, filename)
line = line and line.strip()
startlnos = dis.findlinestarts(code)
lastlineno = list(startlnos)[-1][1]
if frame == stack_frame:
current = i
frames.append({
'file': fn,
'function': code.co_name,
'flno': code.co_firstlineno,
'llno': lastlineno,
'lno': lno,
'code': line,
'level': i,
'current': frame == stack_frame
})
# While in exception always put the context to the top
return stack, frames, current |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send(self, data):
"""Send data through websocket""" |
log.debug('Sending %s' % data)
if not self._socket:
log.warn('No connection')
return
self._socket.send_bytes(data.encode('utf-8')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def receive(self, timeout=None):
"""Receive data through websocket""" |
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 'Quit'
data = self._socket.recv_bytes()
except Exception:
log.error('Connection lost')
return 'Quit'
log.debug('Got %s' % data)
return data.decode('utf-8') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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, post_mortem=False ):
"""User interaction handling blocking on socket receive""" |
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'
if post_mortem:
opts['type_'] = 'pm'
self.open_browser(**opts)
lvl = len(self.interaction_stack)
if lvl:
exception_description += ' [recursive%s]' % (
'^%d' % lvl if lvl > 1 else ''
)
interaction = Interaction(
self,
frame,
tb,
exception,
exception_description,
init=init,
shell=shell,
shell_vars=shell_vars,
source=source,
timeout=timeout
)
self.interaction_stack.append(interaction)
# For meta debugging purpose
self._ui = interaction
if self.begun:
# Each new state sends the trace and selects a frame
interaction.init()
else:
self.begun = True
interaction.loop()
self.interaction_stack.pop()
if lvl:
self.interaction_stack[-1].init() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def breaks(self, frame, no_remove=False):
"""Return True if there's a breakpoint at frame""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_file_breaks(self, filename):
"""List all file `filename` breakpoints""" |
return [
breakpoint for breakpoint in self.breakpoints
if breakpoint.on_file(filename)
] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_breaks_lno(self, filename):
"""List all line numbers that have a breakpoint""" |
return list(
filter(
lambda x: x is not None, [
getattr(breakpoint, 'line', None)
for breakpoint in self.breakpoints
if breakpoint.on_file(filename)
]
)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def die(self):
"""Time to quit""" |
log.info('Time to die')
if self.connected:
try:
self.send('Die')
except Exception:
pass
if self._socket:
self._socket.close()
self.pop() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _killall(self, force=False):
"""Kill all remaining processes, forcefully if requested.""" |
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_print("sending %s to %s (pid %s)\n" %
(signame, n, p['pid']))
if force:
self._env.kill(p['pid'])
else:
self._env.terminate(p['pid']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 of `honcho.process.Process`. """ |
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 range(con[name]):
n = "{0}.{1}".format(name, i + 1)
c = cmd
q = name in quiet
e = {'HONCHO_PROCESS_NAME': n}
if env is not None:
e.update(env)
if port is not None:
e['PORT'] = str(port + i)
params = ProcessParams(n, c, q, e)
out.append(params)
if port is not None:
port += 100
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dashrepl(value):
""" Replace any non-word characters with a dash. """ |
patt = re.compile(r'\W', re.UNICODE)
return re.sub(patt, '-', value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_sources(self):
""" Look for Python sources available for the current configuration. """ |
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__.py' not in files:
ignore_dirs.append(root)
continue
for filename in files:
basename, ext = os.path.splitext(filename)
if ext != '.py':
continue
yield os.path.abspath(os.path.join(root, filename)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_templates(self):
""" Look for templates and extract the nodes containing the SASS file. """ |
paths = set()
for loader in self.get_loaders():
try:
module = import_module(loader.__module__)
get_template_sources = getattr(
module, 'get_template_sources', loader.get_template_sources)
template_sources = get_template_sources('')
paths.update([t.name if isinstance(t, Origin) else t for t in template_sources])
except (ImportError, AttributeError):
pass
if not paths:
raise CommandError(
"No template paths found. None of the configured template loaders provided template paths")
templates = set()
for path in paths:
for root, _, files in os.walk(str(path)):
templates.update(os.path.join(root, name)
for name in files if not name.startswith('.') and
any(name.endswith(ext) for ext in self.template_exts))
if not templates:
raise CommandError(
"No templates found. Make sure your TEMPLATE_LOADERS and TEMPLATE_DIRS settings are correct.")
return templates |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compile_sass(self, sass_filename, sass_fileurl):
""" Compile the given SASS file into CSS """ |
compile_kwargs = {
'filename': sass_filename,
'include_paths': SassProcessor.include_paths + APPS_INCLUDE_DIRS,
'custom_functions': get_custom_functions(),
}
if self.sass_precision:
compile_kwargs['precision'] = self.sass_precision
if self.sass_output_style:
compile_kwargs['output_style'] = self.sass_output_style
content = sass.compile(**compile_kwargs)
self.save_to_destination(content, sass_filename, sass_fileurl)
self.processed_files.append(sass_filename)
if self.verbosity > 1:
self.stdout.write("Compiled SASS/SCSS file: '{0}'\n".format(sass_filename)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def walk_nodes(self, node, original):
""" Iterate over the nodes recursively yielding the templatetag 'sass_src' """ |
try:
# try with django-compressor<2.1
nodelist = self.parser.get_nodelist(node, original=original)
except TypeError:
nodelist = self.parser.get_nodelist(node, original=original, context=None)
for node in nodelist:
if isinstance(node, SassSrcNode):
if node.is_sass:
yield node
else:
for node in self.walk_nodes(node, original=original):
yield node |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_custom_functions():
""" Return a dict of function names, to be used from inside SASS """ |
def get_setting(*args):
try:
return getattr(settings, args[0])
except AttributeError as e:
raise TemplateSyntaxError(str(e))
if hasattr(get_custom_functions, '_custom_functions'):
return get_custom_functions._custom_functions
get_custom_functions._custom_functions = {sass.SassFunction('get-setting', ('key',), get_setting)}
for name, func in getattr(settings, 'SASS_PROCESSOR_CUSTOM_FUNCTIONS', {}).items():
try:
if isinstance(func, six.string_types):
func = import_string(func)
except Exception as e:
raise TemplateSyntaxError(str(e))
else:
if not inspect.isfunction(func):
raise TemplateSyntaxError("{} is not a Python function".format(func))
if six.PY2:
func_args = inspect.getargspec(func).args
else:
func_args = inspect.getfullargspec(func).args
sass_func = sass.SassFunction(name, func_args, func)
get_custom_functions._custom_functions.add(sass_func)
return get_custom_functions._custom_functions |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read(self, pin, is_differential=False):
"""I2C Interface for ADS1x15-based ADCs reads. params: :param pin: individual or differential pin. :param bool is_differential: single-ended or differential read. """ |
pin = pin if is_differential else pin + 0x04
return self._read(pin) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _read(self, pin):
"""Perform an ADC read. Returns the signed integer result of the read.""" |
config = _ADS1X15_CONFIG_OS_SINGLE
config |= (pin & 0x07) << _ADS1X15_CONFIG_MUX_OFFSET
config |= _ADS1X15_CONFIG_GAIN[self.gain]
config |= self.mode
config |= self.rate_config[self.data_rate]
config |= _ADS1X15_CONFIG_COMP_QUE_DISABLE
self._write_register(_ADS1X15_POINTER_CONFIG, config)
while not self._conversion_complete():
time.sleep(0.01)
return self.get_last_result() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _write_register(self, reg, value):
"""Write 16 bit value to register.""" |
self.buf[0] = reg
self.buf[1] = (value >> 8) & 0xFF
self.buf[2] = value & 0xFF
with self.i2c_device as i2c:
i2c.write(self.buf) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _read_register(self, reg):
"""Read 16 bit register value.""" |
self.buf[0] = reg
with self.i2c_device as i2c:
i2c.write(self.buf, end=1, stop=False)
i2c.readinto(self.buf, end=2)
return self.buf[0] << 8 | self.buf[1] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def value(self):
"""Returns the value of an ADC pin as an integer.""" |
return self._ads.read(self._pin_setting, is_differential=self.is_differential) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def voltage(self):
"""Returns the voltage from the ADC pin as a floating point value.""" |
raw = self.value
volts = raw * (_ADS1X15_PGA_RANGE[self._ads.gain] / (2**(self._ads.bits-1) - 1))
return volts |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sequential_id(self, client):
"""Return the sequential id for this test for the passed in client""" |
if client.client_id not in self._sequential_ids:
id_ = sequential_id("e:{0}:users".format(self.name), client.client_id)
self._sequential_ids[client.client_id] = id_
return self._sequential_ids[client.client_id] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def record_participation(self, client, dt=None):
"""Record a user's participation in a test along with a given variation""" |
if dt is None:
date = datetime.now()
else:
date = dt
experiment_key = self.experiment.name
pipe = self.redis.pipeline()
pipe.sadd(_key("p:{0}:years".format(experiment_key)), date.strftime('%Y'))
pipe.sadd(_key("p:{0}:months".format(experiment_key)), date.strftime('%Y-%m'))
pipe.sadd(_key("p:{0}:days".format(experiment_key)), date.strftime('%Y-%m-%d'))
pipe.execute()
keys = [
_key("p:{0}:_all:all".format(experiment_key)),
_key("p:{0}:_all:{1}".format(experiment_key, date.strftime('%Y'))),
_key("p:{0}:_all:{1}".format(experiment_key, date.strftime('%Y-%m'))),
_key("p:{0}:_all:{1}".format(experiment_key, date.strftime('%Y-%m-%d'))),
_key("p:{0}:{1}:all".format(experiment_key, self.name)),
_key("p:{0}:{1}:{2}".format(experiment_key, self.name, date.strftime('%Y'))),
_key("p:{0}:{1}:{2}".format(experiment_key, self.name, date.strftime('%Y-%m'))),
_key("p:{0}:{1}:{2}".format(experiment_key, self.name, date.strftime('%Y-%m-%d'))),
]
msetbit(keys=keys, args=([self.experiment.sequential_id(client), 1] * len(keys))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sequential_id(k, identifier):
"""Map an arbitrary string identifier to a set of sequential ids""" |
key = _key(k)
return int(monotonic_zadd(keys=[key], args=[identifier])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_emacs_open_in_editor_bindings():
""" Pressing C-X C-E will open the buffer in an external editor. """ |
registry = Registry()
registry.add_binding(Keys.ControlX, Keys.ControlE,
filter=EmacsMode() & ~HasSelection())(
get_by_name('edit-and-execute-command'))
return registry |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _create_event():
""" Creates a Win32 unnamed Event . http://msdn.microsoft.com/en-us/library/windows/desktop/ms682396(v=vs.85).aspx """ |
return windll.kernel32.CreateEventA(pointer(SECURITY_ATTRIBUTES()), BOOL(True), BOOL(False), None) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ready_for_reading(self, timeout=None):
""" Return the handle that is ready for reading or `None` on timeout. """ |
handles = [self._event, self._console_input_reader.handle]
handles.extend(self._read_fds.keys())
return _wait_for_handles(handles, timeout) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def add_reader(self, fd, callback):
" Start watching the file descriptor for read availability. "
h = msvcrt.get_osfhandle(fd)
self._read_fds[h] = callback |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def remove_reader(self, fd):
" Stop watching the file descriptor for read availability. "
h = msvcrt.get_osfhandle(fd)
if h in self._read_fds:
del self._read_fds[h] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_and_handle(self, cli, buffer):
""" Validate buffer and handle the accept action. """ |
if buffer.validate():
if self.handler:
self.handler(cli, buffer)
buffer.append_to_history() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _set_text(self, value):
""" set text at current working_index. Return whether it changed. """ |
working_index = self.working_index
working_lines = self._working_lines
original_value = working_lines[working_index]
working_lines[working_index] = value
# Return True when this text has been changed.
if len(value) != len(original_value):
# For Python 2, it seems that when two strings have a different
# length and one is a prefix of the other, Python still scans
# character by character to see whether the strings are different.
# (Some benchmarking showed significant differences for big
# documents. >100,000 of lines.)
return True
elif value != original_value:
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _set_cursor_position(self, value):
""" Set cursor position. Return whether it changed. """ |
original_position = self.__cursor_position
self.__cursor_position = max(0, value)
return value != original_position |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cursor_position(self, value):
""" Setting cursor position. """ |
assert isinstance(value, int)
assert value <= len(self.text)
changed = self._set_cursor_position(value)
if changed:
self._cursor_position_changed() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transform_lines(self, line_index_iterator, transform_callback):
""" Transforms the text on a range of lines. When the iterator yield an index not in the range of lines that the document contains, it skips them silently. To uppercase some lines:: new_text = transform_lines(range(5,10), lambda text: text.upper()) :param line_index_iterator: Iterator of line numbers (int) :param transform_callback: callable that takes the original text of a line, and return the new text for this line. :returns: The new text. """ |
# Split lines
lines = self.text.split('\n')
# Apply transformation
for index in line_index_iterator:
try:
lines[index] = transform_callback(lines[index])
except IndexError:
pass
return '\n'.join(lines) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transform_current_line(self, transform_callback):
""" Apply the given transformation function to the current line. :param transform_callback: callable that takes a string and return a new string. """ |
document = self.document
a = document.cursor_position + document.get_start_of_line_position()
b = document.cursor_position + document.get_end_of_line_position()
self.text = (
document.text[:a] +
transform_callback(document.text[a:b]) +
document.text[b:]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transform_region(self, from_, to, transform_callback):
""" Transform a part of the input string. :param from_: (int) start position. :param to: (int) end position. :param transform_callback: Callable which accepts a string and returns the transformed string. """ |
assert from_ < to
self.text = ''.join([
self.text[:from_] +
transform_callback(self.text[from_:to]) +
self.text[to:]
]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_before_cursor(self, count=1):
""" Delete specified number of characters before cursor and return the deleted text. """ |
assert count >= 0
deleted = ''
if self.cursor_position > 0:
deleted = self.text[self.cursor_position - count:self.cursor_position]
new_text = self.text[:self.cursor_position - count] + self.text[self.cursor_position:]
new_cursor_position = self.cursor_position - len(deleted)
# Set new Document atomically.
self.document = Document(new_text, new_cursor_position)
return deleted |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, count=1):
""" Delete specified number of characters and Return the deleted text. """ |
if self.cursor_position < len(self.text):
deleted = self.document.text_after_cursor[:count]
self.text = self.text[:self.cursor_position] + \
self.text[self.cursor_position + len(deleted):]
return deleted
else:
return '' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def join_next_line(self, separator=' '):
""" Join the next line to the current one by deleting the line ending after the current line. """ |
if not self.document.on_last_line:
self.cursor_position += self.document.get_end_of_line_position()
self.delete()
# Remove spaces.
self.text = (self.document.text_before_cursor + separator +
self.document.text_after_cursor.lstrip(' ')) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.