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 force_single_imports(self):
"""force a single import per statement""" |
for import_stmt in self.imports[:]:
import_info = import_stmt.import_info
if import_info.is_empty() or import_stmt.readonly:
continue
if len(import_info.names_and_aliases) > 1:
for name_and_alias in import_info.names_and_aliases:
if hasattr(import_info, "module_name"):
new_import = importinfo.FromImport(
import_info.module_name, import_info.level,
[name_and_alias])
else:
new_import = importinfo.NormalImport([name_and_alias])
self.add_import(new_import)
import_stmt.empty_import() |
<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_pyname(self, pyname):
"""Removes pyname when imported in ``from mod import x``""" |
visitor = actions.RemovePyNameVisitor(self.project, self.pymodule,
pyname, self._current_folder())
for import_stmt in self.imports:
import_stmt.accept(visitor) |
<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_arguments(primary, pyfunction, call_node, scope):
"""A factory for creating `Arguments`""" |
args = list(call_node.args)
args.extend(call_node.keywords)
called = call_node.func
# XXX: Handle constructors
if _is_method_call(primary, pyfunction) and \
isinstance(called, ast.Attribute):
args.insert(0, called.value)
return Arguments(args, scope) |
<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(self, key, value):
"""Set the value of `key` preference to `value`.""" |
if key in self.callbacks:
self.callbacks[key](value)
else:
self.prefs[key] = 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 add(self, key, value):
"""Add an entry to a list preference Add `value` to the list of entries for the `key` preference. """ |
if not key in self.prefs:
self.prefs[key] = []
self.prefs[key].append(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 fix_indentation(code, new_indents):
"""Change the indentation of `code` to `new_indents`""" |
min_indents = find_minimum_indents(code)
return indent_lines(code, new_indents - min_indents) |
<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_body(pyfunction):
"""Return unindented function body""" |
# FIXME scope = pyfunction.get_scope()
pymodule = pyfunction.get_module()
start, end = get_body_region(pyfunction)
return fix_indentation(pymodule.source_code[start:end], 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 get_body_region(defined):
"""Return the start and end offsets of function body""" |
scope = defined.get_scope()
pymodule = defined.get_module()
lines = pymodule.lines
node = defined.get_ast()
start_line = node.lineno
if defined.get_doc() is None:
start_line = node.body[0].lineno
elif len(node.body) > 1:
start_line = node.body[1].lineno
start = lines.get_line_start(start_line)
scope_start = pymodule.logical_lines.logical_line_in(scope.start)
if scope_start[1] >= start_line:
# a one-liner!
# XXX: what if colon appears in a string
start = pymodule.source_code.index(':', start) + 1
while pymodule.source_code[start].isspace():
start += 1
end = min(lines.get_line_end(scope.end) + 1, len(pymodule.source_code))
return start, end |
<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(self, changes, task_handle=taskhandle.NullTaskHandle()):
"""Perform the change and add it to the `self.undo_list` Note that uninteresting changes (changes to ignored files) will not be appended to `self.undo_list`. """ |
try:
self.current_change = changes
changes.do(change.create_job_set(task_handle, changes))
finally:
self.current_change = None
if self._is_change_interesting(changes):
self.undo_list.append(changes)
self._remove_extra_items()
del self.redo_list[:] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def undo(self, change=None, drop=False, task_handle=taskhandle.NullTaskHandle()):
"""Redo done changes from the history When `change` is `None`, the last done change will be undone. If change is not `None` it should be an item from `self.undo_list`; this change and all changes that depend on it will be undone. In both cases the list of undone changes will be returned. If `drop` is `True`, the undone change will not be appended to the redo list. """ |
if not self._undo_list:
raise exceptions.HistoryError('Undo list is empty')
if change is None:
change = self.undo_list[-1]
dependencies = self._find_dependencies(self.undo_list, change)
self._move_front(self.undo_list, dependencies)
self._perform_undos(len(dependencies), task_handle)
result = self.redo_list[-len(dependencies):]
if drop:
del self.redo_list[-len(dependencies):]
return 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 redo(self, change=None, task_handle=taskhandle.NullTaskHandle()):
"""Redo undone changes from the history When `change` is `None`, the last undone change will be redone. If change is not `None` it should be an item from `self.redo_list`; this change and all changes that depend on it will be redone. In both cases the list of redone changes will be returned. """ |
if not self.redo_list:
raise exceptions.HistoryError('Redo list is empty')
if change is None:
change = self.redo_list[-1]
dependencies = self._find_dependencies(self.redo_list, change)
self._move_front(self.redo_list, dependencies)
self._perform_redos(len(dependencies), task_handle)
return self.undo_list[-len(dependencies):] |
<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_string_scope(self, code, resource=None):
"""Returns a `Scope` object for the given code""" |
return rope.base.libutils.get_string_scope(code, resource) |
<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_module(self, resource, args=None, stdin=None, stdout=None):
"""Run `resource` module Returns a `rope.base.oi.doa.PythonFileRunner` object for controlling the process. """ |
perform_doa = self.project.prefs.get('perform_doi', True)
perform_doa = self.project.prefs.get('perform_doa', perform_doa)
receiver = self.object_info.doa_data_received
if not perform_doa:
receiver = None
runner = rope.base.oi.doa.PythonFileRunner(
self, resource, args, stdin, stdout, receiver)
runner.add_finishing_observer(self.module_cache.forget_all_data)
runner.run()
return runner |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def analyze_module(self, resource, should_analyze=lambda py: True, search_subscopes=lambda py: True, followed_calls=None):
"""Analyze `resource` module for static object inference This function forces rope to analyze this module to collect information about function calls. `should_analyze` is a function that is called with a `PyDefinedObject` argument. If it returns `True` the element is analyzed. If it is `None` or returns `False` the element is not analyzed. `search_subscopes` is like `should_analyze`; The difference is that if it returns `False` the sub-scopes are all ignored. That is it is assumed that `should_analyze` returns `False` for all of its subscopes. `followed_calls` override the value of ``soa_followed_calls`` project config. """ |
if followed_calls is None:
followed_calls = self.project.prefs.get('soa_followed_calls', 0)
pymodule = self.resource_to_pyobject(resource)
self.module_cache.forget_all_data()
rope.base.oi.soa.analyze_module(
self, pymodule, should_analyze, search_subscopes, followed_calls) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_changed(self, start, end):
"""Tell whether any of start till end lines have changed The end points are inclusive and indices start from 1. """ |
left, right = self._get_changed(start, end)
if left < right:
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 consume_changes(self, start, end):
"""Clear the changed status of lines from start till end""" |
left, right = self._get_changed(start, end)
if left < right:
del self.lines[left:right]
return left < right |
<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_name(self, name):
"""Return name `PyName` defined in this scope""" |
if name not in self.get_names():
raise exceptions.NameNotFoundError('name %s not found' % name)
return self.get_names()[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 get_modules(self, name):
"""Return the list of modules that have global `name`""" |
result = []
for module in self.names:
if name in self.names[module]:
result.append(module)
return 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 get_all_names(self):
"""Return the list of all cached global names""" |
result = set()
for module in self.names:
result.update(set(self.names[module]))
return 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 generate_cache(self, resources=None, underlined=None, task_handle=taskhandle.NullTaskHandle()):
"""Generate global name cache for project files If `resources` is a list of `rope.base.resource.File`\s, only those files are searched; otherwise all python modules in the project are cached. """ |
if resources is None:
resources = self.project.get_python_files()
job_set = task_handle.create_jobset(
'Generatig autoimport cache', len(resources))
for file in resources:
job_set.started_job('Working on <%s>' % file.path)
self.update_resource(file, underlined)
job_set.finished_job() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_modules_cache(self, modules, underlined=None, task_handle=taskhandle.NullTaskHandle()):
"""Generate global name cache for modules listed in `modules`""" |
job_set = task_handle.create_jobset(
'Generatig autoimport cache for modules', len(modules))
for modname in modules:
job_set.started_job('Working on <%s>' % modname)
if modname.endswith('.*'):
mod = self.project.find_module(modname[:-2])
if mod:
for sub in submodules(mod):
self.update_resource(sub, underlined)
else:
self.update_module(modname, underlined)
job_set.finished_job() |
<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_insertion_line(self, code):
"""Guess at what line the new import should be inserted""" |
match = re.search(r'^(def|class)\s+', code)
if match is not None:
code = code[:match.start()]
try:
pymodule = libutils.get_string_module(self.project, code)
except exceptions.ModuleSyntaxError:
return 1
testmodname = '__rope_testmodule_rope'
importinfo = importutils.NormalImport(((testmodname, None),))
module_imports = importutils.get_module_imports(self.project,
pymodule)
module_imports.add_import(importinfo)
code = module_imports.get_changed_source()
offset = code.index(testmodname)
lineno = code.count('\n', 0, offset) + 1
return 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 update_resource(self, resource, underlined=None):
"""Update the cache for global names in `resource`""" |
try:
pymodule = self.project.get_pymodule(resource)
modname = self._module_name(resource)
self._add_names(pymodule, modname, underlined)
except exceptions.ModuleSyntaxError:
pass |
<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_module(self, modname, underlined=None):
"""Update the cache for global names in `modname` module `modname` is the name of a module. """ |
try:
pymodule = self.project.get_module(modname)
self._add_names(pymodule, modname, underlined)
except exceptions.ModuleNotFoundError:
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def replace(code, pattern, goal):
"""used by other refactorings""" |
finder = similarfinder.RawSimilarFinder(code)
matches = list(finder.get_matches(pattern))
ast = patchedast.get_patched_ast(code)
lines = codeanalyze.SourceLinesAdapter(code)
template = similarfinder.CodeTemplate(goal)
computer = _ChangeComputer(code, ast, lines, template, matches)
result = computer.get_changed()
if result is None:
return code
return 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 get_changes(self, checks=None, imports=None, resources=None, task_handle=taskhandle.NullTaskHandle()):
"""Get the changes needed by this restructuring `resources` can be a list of `rope.base.resources.File`\s to apply the restructuring on. If `None`, the restructuring will be applied to all python files. `checks` argument has been deprecated. Use the `args` argument of the constructor. The usage of:: strchecks = {'obj1.type': 'mod.A', 'obj2': 'mod.B', 'obj3.object': 'mod.C'} checks = restructuring.make_checks(strchecks) can be replaced with:: args = {'obj1': 'type=mod.A', 'obj2': 'name=mod.B', 'obj3': 'object=mod.C'} where obj1, obj2 and obj3 are wildcard names that appear in restructuring pattern. """ |
if checks is not None:
warnings.warn(
'The use of checks parameter is deprecated; '
'use the args parameter of the constructor instead.',
DeprecationWarning, stacklevel=2)
for name, value in checks.items():
self.args[name] = similarfinder._pydefined_to_str(value)
if imports is not None:
warnings.warn(
'The use of imports parameter is deprecated; '
'use imports parameter of the constructor, instead.',
DeprecationWarning, stacklevel=2)
self.imports = imports
changes = change.ChangeSet('Restructuring <%s> to <%s>' %
(self.pattern, self.goal))
if resources is not None:
files = [resource for resource in resources
if libutils.is_python_file(self.project, resource)]
else:
files = self.project.get_python_files()
job_set = task_handle.create_jobset('Collecting Changes', len(files))
for resource in files:
job_set.started_job(resource.path)
pymodule = self.project.get_pymodule(resource)
finder = similarfinder.SimilarFinder(pymodule,
wildcards=self.wildcards)
matches = list(finder.get_matches(self.pattern, self.args))
computer = self._compute_changes(matches, pymodule)
result = computer.get_changed()
if result is not None:
imported_source = self._add_imports(resource, result,
self.imports)
changes.add_change(change.ChangeContents(resource,
imported_source))
job_set.finished_job()
return changes |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_checks(self, string_checks):
"""Convert str to str dicts to str to PyObject dicts This function is here to ease writing a UI. """ |
checks = {}
for key, value in string_checks.items():
is_pyname = not key.endswith('.object') and \
not key.endswith('.type')
evaluated = self._evaluate(value, is_pyname=is_pyname)
if evaluated is not None:
checks[key] = evaluated
return checks |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def returned(self):
"""Does the extracted piece contain return statement""" |
if self._returned is None:
node = _parse_text(self.extracted)
self._returned = usefunction._returns_last(node)
return self._returned |
<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_pymodule(self):
"""Get a `PyModule`""" |
msg = None
code = self.code
tries = 0
while True:
try:
if tries == 0 and self.resource is not None and \
self.resource.read() == code:
return self.project.get_pymodule(self.resource,
force_errors=True)
return libutils.get_string_module(
self.project, code, resource=self.resource,
force_errors=True)
except exceptions.ModuleSyntaxError as e:
if msg is None:
msg = '%s:%s %s' % (e.filename, e.lineno, e.message_)
if tries < self.maxfixes:
tries += 1
self.commenter.comment(e.lineno)
code = '\n'.join(self.commenter.lines)
else:
raise exceptions.ModuleSyntaxError(
e.filename, e.lineno,
'Failed to fix error: {0}'.format(msg)) |
<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_job_set(function):
"""A decorator for handling `taskhandle.JobSet`\s A decorator for handling `taskhandle.JobSet`\s for `do` and `undo` methods of `Change`\s. """ |
def call(self, job_set=taskhandle.NullJobSet()):
job_set.started_job(str(self))
function(self)
job_set.finished_job()
return call |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def count_changes(change):
"""Counts the number of basic changes a `Change` will make""" |
if isinstance(change, ChangeSet):
result = 0
for child in change.changes:
result += count_changes(child)
return result
return 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 analyze_module(pycore, pymodule, should_analyze, search_subscopes, followed_calls):
"""Analyze `pymodule` for static object inference Analyzes scopes for collecting object information. The analysis starts from inner scopes. """ |
_analyze_node(pycore, pymodule, should_analyze,
search_subscopes, followed_calls) |
<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_changes(self, changers, in_hierarchy=False, resources=None, task_handle=taskhandle.NullTaskHandle()):
"""Get changes caused by this refactoring `changers` is a list of `_ArgumentChanger`\s. If `in_hierarchy` is `True` the changers are applyed to all matching methods in the class hierarchy. `resources` can be a list of `rope.base.resource.File`\s that should be searched for occurrences; if `None` all python files in the project are searched. """ |
function_changer = _FunctionChangers(self.pyname.get_object(),
self._definfo(), changers)
return self._change_calls(function_changer, in_hierarchy,
resources, task_handle) |
<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_changes(self, fixer=str.lower, task_handle=taskhandle.NullTaskHandle()):
"""Fix module names `fixer` is a function that takes and returns a `str`. Given the name of a module, it should return the fixed name. """ |
stack = changestack.ChangeStack(self.project, 'Fixing module names')
jobset = task_handle.create_jobset('Fixing module names',
self._count_fixes(fixer) + 1)
try:
while True:
for resource in self._tobe_fixed(fixer):
jobset.started_job(resource.path)
renamer = rename.Rename(self.project, resource)
changes = renamer.get_changes(fixer(self._name(resource)))
stack.push(changes)
jobset.finished_job()
break
else:
break
finally:
jobset.started_job('Reverting to original state')
stack.pop_all()
jobset.finished_job()
return stack.merged() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def infer_returned_object(pyfunction, args):
"""Infer the `PyObject` this `PyFunction` returns after calling""" |
object_info = pyfunction.pycore.object_info
result = object_info.get_exact_returned(pyfunction, args)
if result is not None:
return result
result = _infer_returned(pyfunction, args)
if result is not None:
if args and pyfunction.get_module().get_resource() is not None:
params = args.get_arguments(
pyfunction.get_param_names(special_args=False))
object_info.function_called(pyfunction, params, result)
return result
result = object_info.get_returned(pyfunction, args)
if result is not None:
return result
hint_return = get_type_hinting_factory(pyfunction.pycore.project).make_return_provider()
type_ = hint_return(pyfunction)
if type_ is not None:
return rope.base.pyobjects.PyObject(type_) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def infer_parameter_objects(pyfunction):
"""Infer the `PyObject`\s of parameters of this `PyFunction`""" |
object_info = pyfunction.pycore.object_info
result = object_info.get_parameter_objects(pyfunction)
if result is None:
result = _parameter_objects(pyfunction)
_handle_first_parameter(pyfunction, result)
return 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 normalize_so_name(name):
""" Handle different types of python installations """ |
if "cpython" in name:
return os.path.splitext(os.path.splitext(name)[0])[0]
# XXX: Special handling for Fedora python2 distribution
# See: https://github.com/python-rope/rope/issues/211
if name == "timemodule.so":
return "time"
return os.path.splitext(name)[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 run(self):
"""Execute the process""" |
env = dict(os.environ)
file_path = self.file.real_path
path_folders = self.pycore.project.get_source_folders() + \
self.pycore.project.get_python_path_folders()
env['PYTHONPATH'] = os.pathsep.join(folder.real_path
for folder in path_folders)
runmod_path = self.pycore.project.find_module('rope.base.oi.runmod').real_path
self.receiver = None
self._init_data_receiving()
send_info = '-'
if self.receiver:
send_info = self.receiver.get_send_info()
args = [sys.executable, runmod_path, send_info,
self.pycore.project.address, self.file.real_path]
if self.analyze_data is None:
del args[1:4]
if self.args is not None:
args.extend(self.args)
self.process = subprocess.Popen(
executable=sys.executable, args=args, env=env,
cwd=os.path.split(file_path)[0], stdin=self.stdin,
stdout=self.stdout, stderr=self.stdout, close_fds=os.name != 'nt') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def kill_process(self):
"""Stop the process""" |
if self.process.poll() is not None:
return
try:
if hasattr(self.process, 'terminate'):
self.process.terminate()
elif os.name != 'nt':
os.kill(self.process.pid, 9)
else:
import ctypes
handle = int(self.process._handle)
ctypes.windll.kernel32.TerminateProcess(handle, -1)
except OSError:
pass |
<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_matches(self, code, start=0, end=None, skip=None):
"""Search for `code` in source and return a list of `Match`\es `code` can contain wildcards. ``${name}`` matches normal names and ``${?name} can match any expression. You can use `Match.get_ast()` for getting the node that has matched a given pattern. """ |
if end is None:
end = len(self.source)
for match in self._get_matched_asts(code):
match_start, match_end = match.get_region()
if start <= match_start and match_end <= end:
if skip is not None and (skip[0] < match_end and
skip[1] > match_start):
continue
yield match |
<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_children(self, node):
"""Return not `ast.expr_context` children of `node`""" |
children = ast.get_children(node)
return [child for child in children
if not isinstance(child, ast.expr_context)] |
<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_imports(project, pydefined):
"""A shortcut for getting the `ImportInfo`\s used in a scope""" |
pymodule = pydefined.get_module()
module = module_imports.ModuleImports(project, pymodule)
if pymodule == pydefined:
return [stmt.import_info for stmt in module.imports]
return module.get_used_imports(pydefined) |
<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_from_import(self, resource, name):
"""The from import statement for `name` in `resource`""" |
module_name = libutils.modname(resource)
names = []
if isinstance(name, list):
names = [(imported, None) for imported in name]
else:
names = [(name, None), ]
return FromImport(module_name, 0, tuple(names)) |
<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_finder(project, name, pyname, only_calls=False, imports=True, unsure=None, docs=False, instance=None, in_hierarchy=False, keywords=True):
"""A factory for `Finder` Based on the arguments it creates a list of filters. `instance` argument is needed only when you want implicit interfaces to be considered. """ |
pynames_ = set([pyname])
filters = []
if only_calls:
filters.append(CallsFilter())
if not imports:
filters.append(NoImportsFilter())
if not keywords:
filters.append(NoKeywordsFilter())
if isinstance(instance, pynames.ParameterName):
for pyobject in instance.get_objects():
try:
pynames_.add(pyobject[name])
except exceptions.AttributeNotFoundError:
pass
for pyname in pynames_:
filters.append(PyNameFilter(pyname))
if in_hierarchy:
filters.append(InHierarchyFilter(pyname))
if unsure:
filters.append(UnsureFilter(unsure))
return Finder(project, name, filters=filters, docs=docs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def same_pyname(expected, pyname):
"""Check whether `expected` and `pyname` are the same""" |
if expected is None or pyname is None:
return False
if expected == pyname:
return True
if type(expected) not in (pynames.ImportedModule, pynames.ImportedName) \
and type(pyname) not in \
(pynames.ImportedModule, pynames.ImportedName):
return False
return expected.get_definition_location() == \
pyname.get_definition_location() and \
expected.get_object() == pyname.get_object() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unsure_pyname(pyname, unbound=True):
"""Return `True` if we don't know what this name references""" |
if pyname is None:
return True
if unbound and not isinstance(pyname, pynames.UnboundName):
return False
if pyname.get_object() == pyobjects.get_unknown():
return 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 find_occurrences(self, resource=None, pymodule=None):
"""Generate `Occurrence` instances""" |
tools = _OccurrenceToolsCreator(self.project, resource=resource,
pymodule=pymodule, docs=self.docs)
for offset in self._textual_finder.find_offsets(tools.source_code):
occurrence = Occurrence(tools, offset)
for filter in self.filters:
result = filter(occurrence)
if result is None:
continue
if result:
yield occurrence
break |
<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_generate(kind, project, resource, offset):
"""A factory for creating `Generate` objects `kind` can be 'variable', 'function', 'class', 'module' or 'package'. """ |
generate = eval('Generate' + kind.title())
return generate(project, resource, offset) |
<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_module(project, name, sourcefolder=None):
"""Creates a module and returns a `rope.base.resources.File`""" |
if sourcefolder is None:
sourcefolder = project.root
packages = name.split('.')
parent = sourcefolder
for package in packages[:-1]:
parent = parent.get_child(package)
return parent.create_file(packages[-1] + '.py') |
<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_package(project, name, sourcefolder=None):
"""Creates a package and returns a `rope.base.resources.Folder`""" |
if sourcefolder is None:
sourcefolder = project.root
packages = name.split('.')
parent = sourcefolder
for package in packages[:-1]:
parent = parent.get_child(package)
made_packages = parent.create_folder(packages[-1])
made_packages.create_file('__init__.py')
return made_packages |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rename_in_module(occurrences_finder, new_name, resource=None, pymodule=None, replace_primary=False, region=None, reads=True, writes=True):
"""Returns the changed source or `None` if there is no changes""" |
if resource is not None:
source_code = resource.read()
else:
source_code = pymodule.source_code
change_collector = codeanalyze.ChangeCollector(source_code)
for occurrence in occurrences_finder.find_occurrences(resource, pymodule):
if replace_primary and occurrence.is_a_fixed_primary():
continue
if replace_primary:
start, end = occurrence.get_primary_range()
else:
start, end = occurrence.get_word_range()
if (not reads and not occurrence.is_written()) or \
(not writes and occurrence.is_written()):
continue
if region is None or region[0] <= start < region[1]:
change_collector.add_change(start, end, new_name)
return change_collector.get_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 get_changes(self, new_name, in_file=None, in_hierarchy=False, unsure=None, docs=False, resources=None, task_handle=taskhandle.NullTaskHandle()):
"""Get the changes needed for this refactoring Parameters: - `in_hierarchy`: when renaming a method this keyword forces to rename all matching methods in the hierarchy - `docs`: when `True` rename refactoring will rename occurrences in comments and strings where the name is visible. Setting it will make renames faster, too. - `unsure`: decides what to do about unsure occurrences. If `None`, they are ignored. Otherwise `unsure` is called with an instance of `occurrence.Occurrence` as parameter. If it returns `True`, the occurrence is considered to be a match. - `resources` can be a list of `rope.base.resources.File`\s to apply this refactoring on. If `None`, the restructuring will be applied to all python files. - `in_file`: this argument has been deprecated; use `resources` instead. """ |
if unsure in (True, False):
warnings.warn(
'unsure parameter should be a function that returns '
'True or False', DeprecationWarning, stacklevel=2)
def unsure_func(value=unsure):
return value
unsure = unsure_func
if in_file is not None:
warnings.warn(
'`in_file` argument has been deprecated; use `resources` '
'instead. ', DeprecationWarning, stacklevel=2)
if in_file:
resources = [self.resource]
if _is_local(self.old_pyname):
resources = [self.resource]
if resources is None:
resources = self.project.get_python_files()
changes = ChangeSet('Renaming <%s> to <%s>' %
(self.old_name, new_name))
finder = occurrences.create_finder(
self.project, self.old_name, self.old_pyname, unsure=unsure,
docs=docs, instance=self.old_instance,
in_hierarchy=in_hierarchy and self.is_method())
job_set = task_handle.create_jobset('Collecting Changes',
len(resources))
for file_ in resources:
job_set.started_job(file_.path)
new_content = rename_in_module(finder, new_name, resource=file_)
if new_content is not None:
changes.add_change(ChangeContents(file_, new_content))
job_set.finished_job()
if self._is_renaming_a_module():
resource = self.old_pyname.get_object().get_resource()
if self._is_allowed_to_move(resources, resource):
self._rename_module(resource, new_name, changes)
return changes |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def real_code(source):
"""Simplify `source` for analysis It replaces: * comments with spaces * strs with a new str filled with spaces * implicit and explicit continuations with spaces * tabs and semicolons with spaces The resulting code is a lot easier to analyze if we are interested only in offsets. """ |
collector = codeanalyze.ChangeCollector(source)
for start, end in ignored_regions(source):
if source[start] == '#':
replacement = ' ' * (end - start)
else:
replacement = '"%s"' % (' ' * (end - start - 2))
collector.add_change(start, end, replacement)
source = collector.get_changed() or source
collector = codeanalyze.ChangeCollector(source)
parens = 0
for match in _parens.finditer(source):
i = match.start()
c = match.group()
if c in '({[':
parens += 1
if c in ')}]':
parens -= 1
if c == '\n' and parens > 0:
collector.add_change(i, i + 1, ' ')
source = collector.get_changed() or source
return source.replace('\\\n', ' ').replace('\t', ' ').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 ignored_regions(source):
"""Return ignored regions like strings and comments in `source` """ |
return [(match.start(), match.end()) for match in _str.finditer(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 move(self, new_location):
"""Move resource to `new_location`""" |
self._perform_change(change.MoveResource(self, new_location),
'Moving <%s> to <%s>' % (self.path, new_location)) |
<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_children(self):
"""Return the children of this folder""" |
try:
children = os.listdir(self.real_path)
except OSError:
return []
result = []
for name in children:
try:
child = self.get_child(name)
except exceptions.ResourceNotFoundError:
continue
if not self.project.is_ignored(child):
result.append(self.get_child(name))
return 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 _create_indexes(self):
"""Ensures the proper fields are indexed""" |
# WARNING: The collection will be locked during the index
# creation. If the collection has a large number of
# documents in it, the operation can take a long time.
# TODO: The creation of indexes can be moved to a Django
# management command or equivalent. There is also an option to
# run the indexing on the background, without locking.
self.collection.ensure_index([('time', pymongo.DESCENDING)])
self.collection.ensure_index('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 send(self, event):
"""Insert the event in to the Mongo collection""" |
try:
self.collection.insert(event, manipulate=False)
except (PyMongoError, BSONError):
# The event will be lost in case of a connection error or any error
# that occurs when trying to insert the event into Mongo.
# pymongo will re-connect/re-authenticate automatically
# during the next event.
msg = 'Error inserting to MongoDB event tracker backend'
log.exception(msg) |
<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_backends_from_settings(self):
""" Expects the Django setting "EVENT_TRACKING_BACKENDS" to be defined and point to a dictionary of backend engine configurations. Example:: EVENT_TRACKING_BACKENDS = { 'default': { 'ENGINE': 'some.arbitrary.Backend', 'OPTIONS': { 'endpoint': 'http://something/event' } }, 'another_engine': { 'ENGINE': 'some.arbitrary.OtherBackend', 'OPTIONS': { 'user': 'foo' } }, } """ |
config = getattr(settings, DJANGO_BACKEND_SETTING_NAME, {})
backends = self.instantiate_objects(config)
return backends |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instantiate_objects(self, node):
""" Recursively traverse a structure to identify dictionaries that represent objects that need to be instantiated Traverse all values of all dictionaries and all elements of all lists to identify dictionaries that contain the special "ENGINE" key which indicates that a class of that type should be instantiated and passed all key-value pairs found in the sibling "OPTIONS" dictionary as keyword arguments. For example:: tree = { 'a': { 'b': { 'first_obj': { 'ENGINE': 'mypackage.mymodule.Clazz', 'OPTIONS': { 'size': 10, 'foo': 'bar' } } }, 'c': [ { 'ENGINE': 'mypackage.mymodule.Clazz2', 'OPTIONS': { 'more_objects': { 'd': {'ENGINE': 'mypackage.foo.Bar'} } } } ] } } root = self.instantiate_objects(tree) That structure of dicts, lists, and strings will end up with (this example assumes that all keyword arguments to constructors were saved as attributes of the same name):
assert type(root['a']['b']['first_obj']) == <type 'mypackage.mymodule.Clazz'> assert root['a']['b']['first_obj'].size == 10 assert root['a']['b']['first_obj'].foo == 'bar' assert type(root['a']['c'][0]) == <type 'mypackage.mymodule.Clazz2'> assert type(root['a']['c'][0].more_objects['d']) == <type 'mypackage.foo.Bar'> """ |
result = node
if isinstance(node, dict):
if 'ENGINE' in node:
result = self.instantiate_from_dict(node)
else:
result = {}
for key, value in six.iteritems(node):
result[key] = self.instantiate_objects(value)
elif isinstance(node, list):
result = []
for child in node:
result.append(self.instantiate_objects(child))
return 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 instantiate_from_dict(self, values):
""" Constructs an object given a dictionary containing an "ENGINE" key which contains the full module path to the class, and an "OPTIONS" key which contains a dictionary that will be passed in to the constructor as keyword args. """ |
name = values['ENGINE']
options = values.get('OPTIONS', {})
# Parse the name
parts = name.split('.')
module_name = '.'.join(parts[:-1])
class_name = parts[-1]
# Get the class
try:
module = import_module(module_name)
cls = getattr(module, class_name)
except (ValueError, AttributeError, TypeError, ImportError):
raise ValueError('Cannot find class %s' % name)
options = self.instantiate_objects(options)
return cls(**options) |
<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_processors_from_settings(self):
""" Expects the Django setting "EVENT_TRACKING_PROCESSORS" to be defined and point to a list of backend engine configurations. Example:: EVENT_TRACKING_PROCESSORS = [ { 'ENGINE': 'some.arbitrary.Processor' }, { 'ENGINE': 'some.arbitrary.OtherProcessor', 'OPTIONS': { 'user': 'foo' } }, ] """ |
config = getattr(settings, DJANGO_PROCESSOR_SETTING_NAME, [])
processors = self.instantiate_objects(config)
return processors |
<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_backend(self, name, backend):
""" Register a new backend that will be called for each processed event. Note that backends are called in the order that they are registered. """ |
if not hasattr(backend, 'send') or not callable(backend.send):
raise ValueError('Backend %s does not have a callable "send" method.' % backend.__class__.__name__)
else:
self.backends[name] = backend |
<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_processor(self, processor):
""" Register a new processor. Note that processors are called in the order that they are registered. """ |
if not callable(processor):
raise ValueError('Processor %s is not callable.' % processor.__class__.__name__)
else:
self.processors.append(processor) |
<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, event):
""" Process the event using all registered processors and send it to all registered backends. Logs and swallows all `Exception`. """ |
try:
processed_event = self.process_event(event)
except EventEmissionExit:
return
else:
self.send_to_backends(processed_event) |
<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_to_backends(self, event):
""" Sends the event to all registered backends. Logs and swallows all `Exception`. """ |
for name, backend in six.iteritems(self.backends):
try:
backend.send(event)
except Exception: # pylint: disable=broad-except
LOG.exception(
'Unable to send event to backend: %s', 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 emit(self, name=None, data=None):
""" Emit an event annotated with the UTC time when this function was called. `name` is a unique identification string for an event that has already been registered. `data` is a dictionary mapping field names to the value to include in the event. Note that all values provided must be serializable. """ |
event = {
'name': name or UNKNOWN_EVENT_TYPE,
'timestamp': datetime.now(UTC),
'data': data or {},
'context': self.resolve_context()
}
self.routing_backend.send(event) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve_context(self):
""" Create a new dictionary that corresponds to the union of all of the contexts that have been entered but not exited at this point. """ |
merged = dict()
for context in self.located_context.values():
merged.update(context)
return merged |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def context(self, name, ctx):
""" Execute the block with the given context applied. This manager ensures that the context is removed even if an exception is raised within the context. """ |
self.enter_context(name, ctx)
try:
yield
finally:
self.exit_context(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 get(self):
"""Return a reference to a thread-specific context""" |
if not self.thread_local_data:
self.thread_local_data = threading.local()
if not hasattr(self.thread_local_data, 'context'):
self.thread_local_data.context = OrderedDict()
return self.thread_local_data.context |
<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, event):
"""Send the event to the standard python logger""" |
event_str = json.dumps(event, cls=DateTimeJSONEncoder)
# TODO: do something smarter than simply dropping the event on
# the floor.
if self.max_event_size is None or len(event_str) <= self.max_event_size:
self.log(event_str) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def default(self, obj):
# lint-amnesty, pylint: disable=arguments-differ, method-hidden """ Serialize datetime and date objects of iso format. datatime objects are converted to UTC. """ |
if isinstance(obj, datetime):
if obj.tzinfo is None:
# Localize to UTC naive datetime objects
obj = UTC.localize(obj) # pylint: disable=no-value-for-parameter
else:
# Convert to UTC datetime objects from other timezones
obj = obj.astimezone(UTC)
return obj.isoformat()
elif isinstance(obj, date):
return obj.isoformat()
return super(DateTimeJSONEncoder, self).default(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 get_html_theme_path():
"""Return list of HTML theme paths.""" |
theme_path = os.path.abspath(os.path.dirname(__file__))
return [theme_path] |
<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_rev(tag=True):
"""Get build revision. @param tag Use git tag instead of hash? """ |
rev_cmd = "git describe --always --tag" if tag in (True, "True") else \
"git rev-parse HEAD"
return local(rev_cmd, capture=True).strip() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def zip_bundle(tag=True):
"""Create zip file upload bundles. @param tag Use git tag instead of hash? """ |
#rev = get_rev(tag)
rev = __version__
print("Cleaning old build files.")
clean()
local("mkdir -p build")
print("Bundling new files.")
with lcd("sphinx_bootstrap_theme/bootstrap"):
local("zip -r ../../build/bootstrap.zip .")
dest = os.path.abspath(os.path.join(DL_DIR, rev))
with lcd("build"):
local("mkdir -p %s" % dest)
local("cp bootstrap.zip %s" % dest)
print("Verifying contents.")
local("unzip -l bootstrap.zip") |
<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_model(self, request, obj, form, change):
""" Saves the message for the recipient and looks in the form instance for other possible recipients. Prevents duplication by excludin the original recipient from the list of optional recipients. When changing an existing message and choosing optional recipients, the message is effectively resent to those users. """ |
obj.save()
if notification:
# Getting the appropriate notice labels for the sender and recipients.
if obj.parent_msg is None:
sender_label = 'messages_sent'
recipients_label = 'messages_received'
else:
sender_label = 'messages_replied'
recipients_label = 'messages_reply_received'
# Notification for the sender.
notification.send([obj.sender], sender_label, {'message': obj,})
if form.cleaned_data['group'] == 'all':
# send to all users
recipients = User.objects.exclude(pk=obj.recipient.pk)
else:
# send to a group of users
recipients = []
group = form.cleaned_data['group']
if group:
group = Group.objects.get(pk=group)
recipients.extend(
list(group.user_set.exclude(pk=obj.recipient.pk)))
# create messages for all found recipients
for user in recipients:
obj.pk = None
obj.recipient = user
obj.save()
if notification:
# Notification for the recipient.
notification.send([user], recipients_label, {'message' : 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 inbox_count_for(user):
""" returns the number of unread messages for the given user but does not mark them seen """ |
return Message.objects.filter(recipient=user, read_at__isnull=True, recipient_deleted_at__isnull=True).count() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trash_for(self, user):
""" Returns all messages that were either received or sent by the given user and are marked as deleted. """ |
return self.filter(
recipient=user,
recipient_deleted_at__isnull=False,
) | self.filter(
sender=user,
sender_deleted_at__isnull=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 delete(request, message_id, success_url=None):
""" Marks a message as deleted by sender or recipient. The message is not really removed from the database, because two users must delete a message before it's save to remove it completely. A cron-job should prune the database and remove old messages which are deleted by both users. As a side effect, this makes it easy to implement a trash with undelete. You can pass ?next=/foo/bar/ via the url to redirect the user to a different page (e.g. `/foo/bar/`) than ``success_url`` after deletion of the message. """ |
user = request.user
now = timezone.now()
message = get_object_or_404(Message, id=message_id)
deleted = False
if success_url is None:
success_url = reverse('messages_inbox')
if 'next' in request.GET:
success_url = request.GET['next']
if message.sender == user:
message.sender_deleted_at = now
deleted = True
if message.recipient == user:
message.recipient_deleted_at = now
deleted = True
if deleted:
message.save()
messages.info(request, _(u"Message successfully deleted."))
if notification:
notification.send([user], "messages_deleted", {'message': message,})
return HttpResponseRedirect(success_url)
raise Http404 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def view(request, message_id, form_class=ComposeForm, quote_helper=format_quote, subject_template=_(u"Re: %(subject)s"), template_name='django_messages/view.html'):
""" Shows a single message.``message_id`` argument is required. The user is only allowed to see the message, if he is either the sender or the recipient. If the user is not allowed a 404 is raised. If the user is the recipient and the message is unread ``read_at`` is set to the current datetime. If the user is the recipient a reply form will be added to the tenplate context, otherwise 'reply_form' will be None. """ |
user = request.user
now = timezone.now()
message = get_object_or_404(Message, id=message_id)
if (message.sender != user) and (message.recipient != user):
raise Http404
if message.read_at is None and message.recipient == user:
message.read_at = now
message.save()
context = {'message': message, 'reply_form': None}
if message.recipient == user:
form = form_class(initial={
'body': quote_helper(message.sender, message.body),
'subject': subject_template % {'subject': message.subject},
'recipient': [message.sender,]
})
context['reply_form'] = form
return render(request, template_name, context) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_quote(sender, body):
""" Wraps text at 55 chars and prepends each line with `> `. Used for quoting messages in replies. """ |
lines = wrap(body, 55).split('\n')
for i, line in enumerate(lines):
lines[i] = "> %s" % line
quote = '\n'.join(lines)
return ugettext(u"%(sender)s wrote:\n%(body)s") % {
'sender': sender,
'body': quote
} |
<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(self, **params):
'''
Returns details for a specific airport.
.. code-block:: python
amadeus.reference_data.location('ALHR').get()
:rtype: amadeus.Response
:raises amadeus.ResponseError: if the request could not be completed
'''
return self.client.get('/v1/reference-data/locations/{0}'
.format(self.location_id), **params) |
<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(self, **params):
'''
Returns details for a specific offer.
.. code-block:: python
amadeus.shopping.hotel_offer('XXX').get
:rtype: amadeus.Response
:raises amadeus.ResponseError: if the request could not be completed
'''
return self.client.get('/v2/shopping/hotel-offers/{0}'
.format(self.offer_id), **params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def buffer_typechecks(self, call_id, payload):
"""Adds typecheck events to the buffer""" |
if self.currently_buffering_typechecks:
for note in payload['notes']:
self.buffered_notes.append(note) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def buffer_typechecks_and_display(self, call_id, payload):
"""Adds typecheck events to the buffer, and displays them right away. This is a workaround for this issue: https://github.com/ensime/ensime-server/issues/1616 """ |
self.buffer_typechecks(call_id, payload)
self.editor.display_notes(self.buffered_notes) |
<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_typecheck_complete(self, call_id, payload):
"""Handles ``NewScalaNotesEvent```. Calls editor to display/highlight line notes and clears notes buffer. """ |
self.log.debug('handle_typecheck_complete: in')
if not self.currently_buffering_typechecks:
self.log.debug('Completed typecheck was not requested by user, not displaying notes')
return
self.editor.display_notes(self.buffered_notes)
self.currently_buffering_typechecks = False
self.buffered_notes = [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute_with_client(quiet=False, bootstrap_server=False, create_client=True):
"""Decorator that gets a client and performs an operation on it.""" |
def wrapper(f):
def wrapper2(self, *args, **kwargs):
client = self.current_client(
quiet=quiet,
bootstrap_server=bootstrap_server,
create_client=create_client)
if client and client.running:
return f(self, client, *args, **kwargs)
return wrapper2
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def client_status(self, config_path):
"""Get status of client for a project, given path to its config.""" |
c = self.client_for(config_path)
status = "stopped"
if not c or not c.ensime:
status = 'unloaded'
elif c.ensime.is_ready():
status = 'ready'
elif c.ensime.is_running():
status = 'startup'
elif c.ensime.aborted():
status = 'aborted'
return status |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def current_client(self, quiet, bootstrap_server, create_client):
"""Return the client for current file in the editor.""" |
current_file = self._vim.current.buffer.name
config_path = ProjectConfig.find_from(current_file)
if config_path:
return self.client_for(
config_path,
quiet=quiet,
bootstrap_server=bootstrap_server,
create_client=create_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 client_for(self, config_path, quiet=False, bootstrap_server=False, create_client=False):
"""Get a cached client for a project, otherwise create one.""" |
client = None
abs_path = os.path.abspath(config_path)
if abs_path in self.clients:
client = self.clients[abs_path]
elif create_client:
client = self.create_client(config_path)
if client.setup(quiet=quiet, bootstrap_server=bootstrap_server):
self.clients[abs_path] = 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 disable_plugin(self):
"""Disable ensime-vim, in the event of an error we can't usefully recover from. Todo: This is incomplete and unreliable, see: https://github.com/ensime/ensime-vim/issues/294 If used from a secondary thread, this may need to use threadsafe Vim calls where available -- see :meth:`Editor.raw_message`. """ |
for path in self.runtime_paths():
self._vim.command('set runtimepath-={}'.format(path)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def runtime_paths(self):
# TODO: memoize """All the runtime paths of ensime-vim plugin files.""" |
runtimepath = self._vim.options['runtimepath']
plugin = "ensime-vim"
paths = []
for path in runtimepath.split(','):
if plugin in path:
paths.append(os.path.expanduser(path))
return paths |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tick_clients(self):
"""Trigger the periodic tick function in the client.""" |
if not self._ticker:
self._create_ticker()
for client in self.clients.values():
self._ticker.tick(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 fun_en_complete_func(self, client, findstart_and_base, base=None):
"""Invokable function from vim and neovim to perform completion.""" |
if isinstance(findstart_and_base, list):
# Invoked by neovim
findstart = findstart_and_base[0]
base = findstart_and_base[1]
else:
# Invoked by vim
findstart = findstart_and_base
return client.complete_func(findstart, base) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def append(self, text, afterline=None):
"""Append text to the current buffer. Args: text (str or Sequence[str]):
One or many lines of text to append. afterline (Optional[int]):
Line number to append after. If 0, text is prepended before the first line; if ``None``, at end of the buffer. """ |
if afterline:
self._vim.current.buffer.append(text, afterline)
else:
self._vim.current.buffer.append(text) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getline(self, lnum=None):
"""Get a line from the current buffer. Args: lnum (Optional[str]):
Number of the line to get, current if ``None``. Todo: - Give this more behavior of Vim ``getline()``? - ``buffer[index]`` is zero-based, this is probably too confusing """ |
return self._vim.current.buffer[lnum] if lnum else self._vim.current.line |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getlines(self, bufnr=None):
"""Get all lines of a buffer as a list. Args: bufnr (Optional[int]):
A Vim buffer number, current if ``None``. Returns: List[str] """ |
buf = self._vim.buffers[bufnr] if bufnr else self._vim.current.buffer
return 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 menu(self, prompt, choices):
"""Presents a selection menu and returns the user's choice. Args: prompt (str):
Text to ask the user what to select. choices (Sequence[str]):
Values for the user to select from. Returns: The value selected by the user, or ``None``. Todo: Nice opportunity to provide a hook for Unite.vim, etc. here. """ |
menu = [prompt] + [
"{0}. {1}".format(*choice) for choice in enumerate(choices, start=1)
]
command = 'inputlist({})'.format(repr(menu))
choice = int(self._vim.eval(command))
# Vim returns weird stuff if user clicks outside choices with mouse
if not 0 < choice < len(menu):
return
return choices[choice - 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 set_buffer_options(self, options, bufnr=None):
"""Set buffer-local options for a buffer, defaulting to current. Args: options (dict):
Options to set, with keys being Vim option names. For Boolean options, use a :class:`bool` value as expected, e.g. ``{'buflisted': False}`` for ``setlocal nobuflisted``. bufnr (Optional[int]):
A Vim buffer number, as you might get from VimL ``bufnr('%')`` or Python ``vim.current.buffer.number``. If ``None``, options are set on the current buffer. """ |
buf = self._vim.buffers[bufnr] if bufnr else self._vim.current.buffer
# Special case handling for filetype, see doc on ``set_filetype``
filetype = options.pop('filetype', None)
if filetype:
self.set_filetype(filetype)
for opt, value in options.items():
buf.options[opt] = 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 set_filetype(self, filetype, bufnr=None):
"""Set filetype for a buffer. Note: it's a quirk of Vim's Python API that using the buffer.options dictionary to set filetype does not trigger ``FileType`` autocommands, hence this implementation executes as a command instead. Args: filetype (str):
The filetype to set. bufnr (Optional[int]):
A Vim buffer number, current if ``None``. """ |
if bufnr:
self._vim.command(str(bufnr) + 'bufdo set filetype=' + filetype)
else:
self._vim.command('set filetype=' + filetype) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.