gurudesh/pytracebugs huggingface dataset:
# Buggy code
def request_hover(self, params):
    text = self.opened_files.get(params["file"], "")
    md5 = hashlib.md5(text.encode("utf-8")).hexdigest()
    path = str(params["file"])
    path = path.replace(osp.sep, ":")
    logger.debug(path)
    if os.name == "nt":
        path = path.replace("::", ":")
        path = "windows:" + path
    request = {"filename": path, "hash": md5, "cursor_runes": params["offset"]}
    return None, request


# Traceback (UnicodeEncodeError)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 59: ordinal not in range(128)
Traceback (most recent call last):
File "/Users/gpena-castellanos/Google Drive/develop/quansight/spyder/spyder/plugins/completion/kite/client.py", line 131, in perform_request
response = handler(params)
File "/Users/gpena-castellanos/Google Drive/develop/quansight/spyder/spyder/plugins/completion/kite/decorators.py", line 20, in wrapper
params = req(self, *args, **kwargs)
File "/Users/gpena-castellanos/Google Drive/develop/quansight/spyder/spyder/plugins/completion/kite/providers/document.py", line 79, in document_did_open
self.get_status(params['file'])
File "/Users/gpena-castellanos/Google Drive/develop/quansight/spyder/spyder/plugins/completion/kite/client.py", line 89, in get_status
kite_status = self._get_status(filename)
File "/Users/gpena-castellanos/Google Drive/develop/quansight/spyder/spyder/plugins/completion/kite/client.py", line 81, in _get_status
url = url.format(filename=filename)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 59: ordinal not in range(128)

# Fixed code
def request_hover(self, params):
    text = self.opened_files.get(params["file"], "")
    md5 = hashlib.md5(text.encode("utf-8")).hexdigest()
    path = params["file"]
    path = path.replace(osp.sep, ":")
    logger.debug(path)
    if os.name == "nt":
        path = path.replace("::", ":")
        path = "windows:" + path
    request = {"filename": path, "hash": md5, "cursor_runes": params["offset"]}
    return None, request
# Buggy code
def document_did_close(self, params):
    codeeditor = params["codeeditor"]
    logger.debug(
        "[{0}] File: {1}".format(LSPRequestTypes.DOCUMENT_DID_CLOSE, params["file"])
    )
    filename = path_as_uri(params["file"])

    params = {"textDocument": {"uri": filename}}
    if filename not in self.watched_files:
        params[ClientConstants.CANCEL] = True
    else:
        editors = self.watched_files[filename]
        if len(editors) > 1:
            params[ClientConstants.CANCEL] = True
        idx = -1
        for i, editor in enumerate(editors):
            if id(codeeditor) == id(editor):
                idx = i
                break
        if idx > 0:
            editors.pop(idx)

        if len(editors) == 0:
            self.watched_files.pop(filename)

    return params


# Traceback (UnicodeEncodeError)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 59: ordinal not in range(128)
Traceback (most recent call last):
File "/Users/gpena-castellanos/Google Drive/develop/quansight/spyder/spyder/plugins/completion/kite/client.py", line 131, in perform_request
response = handler(params)
File "/Users/gpena-castellanos/Google Drive/develop/quansight/spyder/spyder/plugins/completion/kite/decorators.py", line 20, in wrapper
params = req(self, *args, **kwargs)
File "/Users/gpena-castellanos/Google Drive/develop/quansight/spyder/spyder/plugins/completion/kite/providers/document.py", line 79, in document_did_open
self.get_status(params['file'])
File "/Users/gpena-castellanos/Google Drive/develop/quansight/spyder/spyder/plugins/completion/kite/client.py", line 89, in get_status
kite_status = self._get_status(filename)
File "/Users/gpena-castellanos/Google Drive/develop/quansight/spyder/spyder/plugins/completion/kite/client.py", line 81, in _get_status
url = url.format(filename=filename)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 59: ordinal not in range(128)

# Fixed code
def document_did_close(self, params):
    codeeditor = params["codeeditor"]
    logger.debug(
        "[{0}] File: {1}".format(LSPRequestTypes.DOCUMENT_DID_CLOSE, params["file"])
    )
    filename = path_as_uri(params["file"])

    params = {"textDocument": {"uri": filename}}
    if filename not in self.watched_files:
        params[ClientConstants.CANCEL] = True
    else:
        editors = self.watched_files[filename]
        if len(editors) > 1:
            params[ClientConstants.CANCEL] = True
        idx = -1
        for i, editor in enumerate(editors):
            if id(codeeditor) == id(editor):
                idx = i
                break
        if idx > 0:
            editors.pop(idx)

        if len(editors) == 0:
            self.watched_files.pop(filename)

    return params
# Buggy code
def path_as_uri(path):
    return pathlib.Path(osp.abspath(path)).as_uri()


# Traceback (UnicodeEncodeError)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 59: ordinal not in range(128)
Traceback (most recent call last):
File "/Users/gpena-castellanos/Google Drive/develop/quansight/spyder/spyder/plugins/completion/kite/client.py", line 131, in perform_request
response = handler(params)
File "/Users/gpena-castellanos/Google Drive/develop/quansight/spyder/spyder/plugins/completion/kite/decorators.py", line 20, in wrapper
params = req(self, *args, **kwargs)
File "/Users/gpena-castellanos/Google Drive/develop/quansight/spyder/spyder/plugins/completion/kite/providers/document.py", line 79, in document_did_open
self.get_status(params['file'])
File "/Users/gpena-castellanos/Google Drive/develop/quansight/spyder/spyder/plugins/completion/kite/client.py", line 89, in get_status
kite_status = self._get_status(filename)
File "/Users/gpena-castellanos/Google Drive/develop/quansight/spyder/spyder/plugins/completion/kite/client.py", line 81, in _get_status
url = url.format(filename=filename)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 59: ordinal not in range(128)

# Fixed code
def path_as_uri(path):
    path_obj = pathlib.Path(osp.abspath(path))
    if os.name == "nt" and PY2:
        return make_as_uri(path_obj)
    else:
        return path_obj.as_uri()
# Buggy code
def start_completion_services(self):
    logger.debug("Completions services available for: {0}".format(self.filename))
    self.completions_available = True
    self.document_did_open()


# Traceback (UnicodeEncodeError)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 59: ordinal not in range(128)
Traceback (most recent call last):
File "/Users/gpena-castellanos/Google Drive/develop/quansight/spyder/spyder/plugins/completion/kite/client.py", line 131, in perform_request
response = handler(params)
File "/Users/gpena-castellanos/Google Drive/develop/quansight/spyder/spyder/plugins/completion/kite/decorators.py", line 20, in wrapper
params = req(self, *args, **kwargs)
File "/Users/gpena-castellanos/Google Drive/develop/quansight/spyder/spyder/plugins/completion/kite/providers/document.py", line 79, in document_did_open
self.get_status(params['file'])
File "/Users/gpena-castellanos/Google Drive/develop/quansight/spyder/spyder/plugins/completion/kite/client.py", line 89, in get_status
kite_status = self._get_status(filename)
File "/Users/gpena-castellanos/Google Drive/develop/quansight/spyder/spyder/plugins/completion/kite/client.py", line 81, in _get_status
url = url.format(filename=filename)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 59: ordinal not in range(128)

# Fixed code
def start_completion_services(self):
    logger.debug("Completions services available for: {0}".format(self.filename))
    self.completions_available = True
    self.document_did_open()
# Buggy code
def set_recent_files(self, recent_files):
    """Set a list of files opened by the project."""
    for recent_file in recent_files[:]:
        if not os.path.isfile(recent_file):
            recent_files.remove(recent_file)
    recent_files = [
        os.path.relpath(recent_file, self.root_path) for recent_file in recent_files
    ]
    files = list(OrderedDict.fromkeys(recent_files))
    self.config.set("main", "recent_files", files)


# Traceback (ValueError)
File "C:\Users\jmgro\Anaconda3\lib\site-packages\spyder\plugins\projects\plugin.py", line 342, in close_project
self.main.editor.get_open_filenames())
File "C:\Users\jmgro\Anaconda3\lib\site-packages\spyder\plugins\projects\plugin.py", line 427, in set_project_filenames
self.current_active_project.set_recent_files(recent_files)
File "C:\Users\jmgro\Anaconda3\lib\site-packages\spyder\plugins\projects\api.py", line 76, in set_recent_files
for recent_file in recent_files]
File "C:\Users\jmgro\Anaconda3\lib\site-packages\spyder\plugins\projects\api.py", line 76, in <listcomp>
for recent_file in recent_files]
File "C:\Users\jmgro\Anaconda3\lib\ntpath.py", line 562, in relpath
path_drive, start_drive))
ValueError: path is on mount 'C:', start on mount 'E:'

# Fixed code
def set_recent_files(self, recent_files):
    """Set a list of files opened by the project."""
    processed_recent_files = []
    for recent_file in recent_files:
        if os.path.isfile(recent_file):
            try:
                relative_recent_file = os.path.relpath(recent_file, self.root_path)
                processed_recent_files.append(relative_recent_file)
            except ValueError:
                processed_recent_files.append(recent_file)
    files = list(OrderedDict.fromkeys(processed_recent_files))
    self.config.set("main", "recent_files", files)
# Buggy code
def process_signature(self, response):
    params = None
    if response is not None:
        calls = response["calls"]
        if len(calls) > 0:
            call = calls[0]
            callee = call["callee"]
            documentation = callee["synopsis"]
            call_label = callee["repr"]
            signatures = call["signatures"]
            arg_idx = call["arg_index"]

            parameters = []
            names = []

            logger.debug(signatures)
            if len(signatures) > 0:
                signature = signatures[0]
                logger.debug(signature)
                for arg in signature["args"]:
                    parameters.append({"label": arg["name"], "documentation": ""})
                    names.append(arg["name"])

                func_args = ", ".join(names)
                call_label = "{0}({1})".format(call_label, func_args)

            base_signature = {
                "label": call_label,
                "documentation": documentation,
                "parameters": parameters,
            }
            # doc_signatures.append(base_signature)
            params = {
                "signatures": base_signature,
                "activeSignature": 0,
                "activeParameter": arg_idx,
                "provider": KITE_COMPLETION,
            }
    return {"params": params}


# Traceback (TypeError)
File "/home/ok97465/python/spyder/spyder/plugins/completion/kite/client.py", line 112, in perform_request
response = converter(response)
File "/home/ok97465/python/spyder/spyder/plugins/completion/kite/providers/document.py", line 221, in process_signature
for arg in signature['args']:
TypeError: 'NoneType' object is not iterable

# Fixed code
def process_signature(self, response):
    params = None
    if response is not None:
        calls = response["calls"]
        if len(calls) > 0:
            call = calls[0]
            callee = call["callee"]
            documentation = callee["synopsis"]
            call_label = callee["repr"]
            signatures = call["signatures"]
            arg_idx = call["arg_index"]

            parameters = []
            names = []

            logger.debug(signatures)
            if len(signatures) > 0:
                signature = signatures[0]
                logger.debug(signature)
                if signature["args"] is not None:
                    for arg in signature["args"]:
                        parameters.append({"label": arg["name"], "documentation": ""})
                        names.append(arg["name"])

                func_args = ", ".join(names)
                call_label = "{0}({1})".format(call_label, func_args)

            base_signature = {
                "label": call_label,
                "documentation": documentation,
                "parameters": parameters,
            }
            # doc_signatures.append(base_signature)
            params = {
                "signatures": base_signature,
                "activeSignature": 0,
                "activeParameter": arg_idx,
                "provider": KITE_COMPLETION,
            }
    return {"params": params}
# Buggy code
def convert_text_snippet(snippet_info):
    text = snippet_info["text"]
    text_builder = []
    prev_pos = 0
    next_pos = None
    total_placeholders = len(snippet_info["placeholders"])
    for i, placeholder in enumerate(snippet_info["placeholders"]):
        placeholder_begin = placeholder["begin"]
        placeholder_end = placeholder["end"]
        next_pos = placeholder_begin
        standard_text = text[prev_pos:next_pos]
        snippet_text = text[next_pos:placeholder_end][1:-1]
        prev_pos = placeholder["end"]
        text_builder.append(standard_text)
        placeholder_number = (i + 1) % total_placeholders
        snippet = "${%d:%s}" % (placeholder_number, snippet_text)
        text_builder.append(snippet)
    text_builder.append(text[prev_pos:])
    return "".join(text_builder)


# Traceback (AttributeError)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 194, in _on_key_pressed
self._process_text(text)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 49, in wrapper
return f(self, *args, **kwargs)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 204, in _process_text
self.delete_text(line, column)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 240, in delete_text
self._delete_token(delete_token, text_parent, line, column)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 263, in _delete_token
if left_node.name in MERGE_ALLOWED:
AttributeError: 'PlaceholderNode' object has no attribute 'name'

# Fixed code
def convert_text_snippet(snippet_info):
    text = snippet_info["text"]
    text_builder = []
    prev_pos = 0
    next_pos = None
    total_placeholders = len(snippet_info["placeholders"]) + 1
    for i, placeholder in enumerate(snippet_info["placeholders"]):
        placeholder_begin = placeholder["begin"]
        placeholder_end = placeholder["end"]
        next_pos = placeholder_begin
        standard_text = text[prev_pos:next_pos]
        snippet_text = text[next_pos:placeholder_end][1:-1]
        prev_pos = placeholder["end"]
        text_builder.append(standard_text)
        placeholder_number = (i + 1) % total_placeholders
        snippet = "${%d:%s}" % (placeholder_number, snippet_text)
        text_builder.append(snippet)
    text_builder.append(text[prev_pos:])
    text_builder.append("$0")
    return "".join(text_builder)
# Buggy code
def __init__(self):
    EditorExtension.__init__(self)
    self.is_snippet_active = False
    self.active_snippet = -1
    self.node_number = 0
    self.index = None
    self.ast = None
    self.starting_position = None
    self.modification_lock = QMutex()
    self.event_lock = QMutex()
    self.node_position = {}
    self.snippets_map = {}
    self.undo_stack = []
    self.redo_stack = []
    if rtree_available:
        self.index = index.Index()


# Traceback (AttributeError)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 194, in _on_key_pressed
self._process_text(text)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 49, in wrapper
return f(self, *args, **kwargs)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 204, in _process_text
self.delete_text(line, column)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 240, in delete_text
self._delete_token(delete_token, text_parent, line, column)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 263, in _delete_token
if left_node.name in MERGE_ALLOWED:
AttributeError: 'PlaceholderNode' object has no attribute 'name'

# Fixed code
def __init__(self):
    EditorExtension.__init__(self)
    self.is_snippet_active = False
    self.active_snippet = -1
    self.node_number = 0
    self.index = None
    self.ast = None
    self.starting_position = None
    self.modification_lock = QMutex()
    self.event_lock = QMutex()
    self.update_lock = QMutex()
    self.node_position = {}
    self.snippets_map = {}
    self.undo_stack = []
    self.redo_stack = []
    if rtree_available:
        self.index = index.Index()
# Buggy code
def _undo(self):
    if self.is_snippet_active:
        if len(self.undo_stack) > 0:
            info = self.undo_stack.pop(0)
            ast_copy = copy.deepcopy(self.ast)
            redo_info = (ast_copy, self.starting_position, self.active_snippet)
            self.redo_stack.insert(0, redo_info)
            self.ast, self.starting_position, self.active_snippet = info
            self._update_ast()
            self.editor.clear_extra_selections("code_snippets")
            self.draw_snippets()


# Traceback (AttributeError)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 194, in _on_key_pressed
self._process_text(text)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 49, in wrapper
return f(self, *args, **kwargs)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 204, in _process_text
self.delete_text(line, column)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 240, in delete_text
self._delete_token(delete_token, text_parent, line, column)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 263, in _delete_token
if left_node.name in MERGE_ALLOWED:
AttributeError: 'PlaceholderNode' object has no attribute 'name'

# Fixed code
def _undo(self):
    if len(self.undo_stack) == 0:
        self.reset()
    if self.is_snippet_active:
        num_pops = 0
        patch = self.editor.patch
        for diffs in patch:
            for op, data in diffs.diffs:
                if op in VALID_UPDATES:
                    num_pops += len(data)
        if len(self.undo_stack) > 0:
            for _ in range(num_pops):
                if len(self.undo_stack) == 0:
                    break
                info = self.undo_stack.pop(0)
                ast_copy = copy.deepcopy(self.ast)
                redo_info = (ast_copy, self.starting_position, self.active_snippet)
                self.redo_stack.insert(0, redo_info)
                self.ast, self.starting_position, self.active_snippet = info
            self._update_ast()
            self.editor.clear_extra_selections("code_snippets")
            self.draw_snippets()
# Buggy code
def _redo(self):
    if self.is_snippet_active:
        if len(self.redo_stack) > 0:
            info = self.redo_stack.pop(0)
            ast_copy = copy.deepcopy(self.ast)
            undo_info = (ast_copy, self.starting_position, self.active_snippet)
            self.undo_stack.insert(0, undo_info)
            self.ast, self.starting_position, self.active_snippet = info
            self._update_ast()
            self.editor.clear_extra_selections("code_snippets")
            self.draw_snippets()


# Traceback (AttributeError)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 194, in _on_key_pressed
self._process_text(text)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 49, in wrapper
return f(self, *args, **kwargs)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 204, in _process_text
self.delete_text(line, column)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 240, in delete_text
self._delete_token(delete_token, text_parent, line, column)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 263, in _delete_token
if left_node.name in MERGE_ALLOWED:
AttributeError: 'PlaceholderNode' object has no attribute 'name'

# Fixed code
def _redo(self):
    if self.is_snippet_active:
        num_pops = 0
        patch = self.editor.patch
        for diffs in patch:
            for op, data in diffs.diffs:
                if op in VALID_UPDATES:
                    num_pops += len(data)
        if len(self.redo_stack) > 0:
            for _ in range(num_pops):
                if len(self.redo_stack) == 0:
                    break
                info = self.redo_stack.pop(0)
                ast_copy = copy.deepcopy(self.ast)
                undo_info = (ast_copy, self.starting_position, self.active_snippet)
                self.undo_stack.insert(0, undo_info)
                self.ast, self.starting_position, self.active_snippet = info
            self._update_ast()
            self.editor.clear_extra_selections("code_snippets")
            self.draw_snippets()
# Buggy code
def _process_text(self, text):
    if self.is_snippet_active:
        line, column = self.editor.get_cursor_line_column()
        # Update placeholder text node
        if text != "\b":
            self.insert_text(text, line, column)
        else:
            self.delete_text(line, column)
        self._update_ast()
        self.redo_stack = []


# Traceback (AttributeError)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 194, in _on_key_pressed
self._process_text(text)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 49, in wrapper
return f(self, *args, **kwargs)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 204, in _process_text
self.delete_text(line, column)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 240, in delete_text
self._delete_token(delete_token, text_parent, line, column)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 263, in _delete_token
if left_node.name in MERGE_ALLOWED:
AttributeError: 'PlaceholderNode' object has no attribute 'name'

# Fixed code
def _process_text(self, text):
    if self.is_snippet_active:
        line, column = self.editor.get_cursor_line_column()
        # Update placeholder text node
        if text != "\b":
            self.insert_text(text, line, column)
        elif text == "\n":
            self.reset()
        else:
            self.delete_text(line, column)
        self._update_ast()
        self.redo_stack = []
# Buggy code
def cursor_changed(self, line, col):
    if not rtree_available:
        return
    node, nearest_snippet, _ = self._find_node_by_position(line, col)
    if node is None:
        # self.reset()
        pass
    else:
        if nearest_snippet is not None:
            self.active_snippet = nearest_snippet.number


# Traceback (AttributeError)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 194, in _on_key_pressed
self._process_text(text)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 49, in wrapper
return f(self, *args, **kwargs)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 204, in _process_text
self.delete_text(line, column)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 240, in delete_text
self._delete_token(delete_token, text_parent, line, column)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 263, in _delete_token
if left_node.name in MERGE_ALLOWED:
AttributeError: 'PlaceholderNode' object has no attribute 'name'

# Fixed code
def cursor_changed(self, line, col):
    if not rtree_available:
        return
    # with QMutexLocker(self.reset_lock):
    ignore_calls = {"undo", "redo"}
    node, nearest_snippet, _ = self._find_node_by_position(line, col)
    if node is None:
        stack = inspect.stack()
        ignore = False
        # Check if parent call was due to text update on codeeditor
        # caused by a undo/redo call
        for call in stack:
            if call[3] in ignore_calls:
                ignore = True
                break
        if not ignore:
            self.reset()
    else:
        if nearest_snippet is not None:
            self.active_snippet = nearest_snippet.number
# Buggy code
def _update_ast(self):
    self.reset(partial_reset=True)
    self.is_snippet_active = True
    self.ast.compute_position(self.starting_position)
    start_line, start_column = self.starting_position
    visitor = SnippetSearcherVisitor(start_line, start_column, self.node_number)
    self.ast.accept(visitor)
    self.snippets_map = visitor.snippet_map
    self.update_position_tree(visitor)
    self.editor.clear_extra_selections("code_snippets")
    self.draw_snippets()


# Traceback (AttributeError)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 194, in _on_key_pressed
self._process_text(text)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 49, in wrapper
return f(self, *args, **kwargs)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 204, in _process_text
self.delete_text(line, column)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 240, in delete_text
self._delete_token(delete_token, text_parent, line, column)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 263, in _delete_token
if left_node.name in MERGE_ALLOWED:
AttributeError: 'PlaceholderNode' object has no attribute 'name'

# Fixed code
def _update_ast(self):
    if self.starting_position is not None:
        self.reset(partial_reset=True)
        self.is_snippet_active = True
        self.ast.compute_position(self.starting_position)
        start_line, start_column = self.starting_position
        visitor = SnippetSearcherVisitor(start_line, start_column, self.node_number)
        self.ast.accept(visitor)
        self.snippets_map = visitor.snippet_map
        self.update_position_tree(visitor)
        self.editor.clear_extra_selections("code_snippets")
        self.draw_snippets()
# Buggy code
def document_did_change(self, text=None):
    """Send textDocument/didChange request to the server."""
    self.text_version += 1
    text = self.toPlainText()
    patch = self.differ.patch_make(self.previous_text, text)
    self.previous_text = text
    params = {
        "file": self.filename,
        "version": self.text_version,
        "text": text,
        "diff": patch,
        "offset": self.get_position("cursor"),
    }
    return params


# Traceback (AttributeError)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 194, in _on_key_pressed
self._process_text(text)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 49, in wrapper
return f(self, *args, **kwargs)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 204, in _process_text
self.delete_text(line, column)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 240, in delete_text
self._delete_token(delete_token, text_parent, line, column)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 263, in _delete_token
if left_node.name in MERGE_ALLOWED:
AttributeError: 'PlaceholderNode' object has no attribute 'name'

# Fixed code
def document_did_change(self, text=None):
    """Send textDocument/didChange request to the server."""
    self.text_version += 1
    text = self.toPlainText()
    self.patch = self.differ.patch_make(self.previous_text, text)
    self.previous_text = text
    params = {
        "file": self.filename,
        "version": self.text_version,
        "text": text,
        "diff": self.patch,
        "offset": self.get_position("cursor"),
    }
    return params
# Buggy code
def undo(self):
    """Reimplement undo to decrease text version number."""
    if self.document().isUndoAvailable():
        self.text_version -= 1
        self.skip_rstrip = True
        self.sig_undo.emit()
        TextEditBaseWidget.undo(self)
        self.sig_text_was_inserted.emit()
        self.document_did_change("")
        self.skip_rstrip = False


# Traceback (AttributeError)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 194, in _on_key_pressed
self._process_text(text)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 49, in wrapper
return f(self, *args, **kwargs)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 204, in _process_text
self.delete_text(line, column)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 240, in delete_text
self._delete_token(delete_token, text_parent, line, column)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 263, in _delete_token
if left_node.name in MERGE_ALLOWED:
AttributeError: 'PlaceholderNode' object has no attribute 'name'

# Fixed code
def undo(self):
    """Reimplement undo to decrease text version number."""
    if self.document().isUndoAvailable():
        self.text_version -= 1
        self.skip_rstrip = True
        TextEditBaseWidget.undo(self)
        self.document_did_change("")
        self.sig_undo.emit()
        self.sig_text_was_inserted.emit()
        self.skip_rstrip = False
# Buggy code
def redo(self):
    """Reimplement redo to increase text version number."""
    if self.document().isRedoAvailable():
        self.text_version += 1
        self.skip_rstrip = True
        self.sig_redo.emit()
        TextEditBaseWidget.redo(self)
        self.sig_text_was_inserted.emit()
        self.document_did_change("text")
        self.skip_rstrip = False


# Traceback (AttributeError)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 194, in _on_key_pressed
self._process_text(text)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 49, in wrapper
return f(self, *args, **kwargs)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 204, in _process_text
self.delete_text(line, column)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 240, in delete_text
self._delete_token(delete_token, text_parent, line, column)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 263, in _delete_token
if left_node.name in MERGE_ALLOWED:
AttributeError: 'PlaceholderNode' object has no attribute 'name'

# Fixed code
def redo(self):
    """Reimplement redo to increase text version number."""
    if self.document().isRedoAvailable():
        self.text_version += 1
        self.skip_rstrip = True
        TextEditBaseWidget.redo(self)
        self.document_did_change("text")
        self.sig_redo.emit()
        self.sig_text_was_inserted.emit()
        self.skip_rstrip = False
# Buggy code
def insert_text(event):
    TextEditBaseWidget.keyPressEvent(self, event)
    self.sig_text_was_inserted.emit()


# Traceback (AttributeError)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 194, in _on_key_pressed
self._process_text(text)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 49, in wrapper
return f(self, *args, **kwargs)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 204, in _process_text
self.delete_text(line, column)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 240, in delete_text
self._delete_token(delete_token, text_parent, line, column)
File "/home/dbau/miniconda3/envs/spyder-beta/lib/python3.7/site-packages/spyder/plugins/editor/extensions/snippets.py", line 263, in _delete_token
if left_node.name in MERGE_ALLOWED:
AttributeError: 'PlaceholderNode' object has no attribute 'name'

# Fixed code
def insert_text(event):
    TextEditBaseWidget.keyPressEvent(self, event)
    self.document_did_change()
    self.sig_text_was_inserted.emit()
# Buggy code
def process_signature(self, response):
    params = None
    if response is not None:
        calls = response["calls"]
        if len(calls) > 0:
            call = calls[0]
            callee = call["callee"]
            documentation = callee["synopsis"]
            call_label = callee["repr"]
            signatures = call["signatures"]
            arg_idx = call["arg_index"]

            signature = signatures[0]
            parameters = []
            names = []
            logger.debug(signature)
            for arg in signature["args"]:
                parameters.append({"label": arg["name"], "documentation": ""})
                names.append(arg["name"])

            func_args = ", ".join(names)
            call_label = "{0}({1})".format(call_label, func_args)

            base_signature = {
                "label": call_label,
                "documentation": documentation,
                "parameters": parameters,
            }
            # doc_signatures.append(base_signature)
            params = {
                "signatures": base_signature,
                "activeSignature": 0,
                "activeParameter": arg_idx,
            }
    return {"params": params}


# Traceback (IndexError)
File "C:\Users\kalho\Desktop\spyder\spyder\spyder\plugins\completion\kite\client.py", line 112, in perform_request
response = converter(response)
File "C:\Users\kalho\Desktop\spyder\spyder\spyder\plugins\completion\kite\providers\document.py", line 198, in process_signature
signature = signatures[0]
IndexError: list index out of range

# Fixed code
def process_signature(self, response):
    params = None
    if response is not None:
        calls = response["calls"]
        if len(calls) > 0:
            call = calls[0]
            callee = call["callee"]
            documentation = callee["synopsis"]
            call_label = callee["repr"]
            signatures = call["signatures"]
            arg_idx = call["arg_index"]

            parameters = []
            names = []

            logger.debug(signatures)
            if len(signatures) > 0:
                signature = signatures[0]
                logger.debug(signature)
                for arg in signature["args"]:
                    parameters.append({"label": arg["name"], "documentation": ""})
                    names.append(arg["name"])

                func_args = ", ".join(names)
                call_label = "{0}({1})".format(call_label, func_args)

            base_signature = {
                "label": call_label,
                "documentation": documentation,
                "parameters": parameters,
            }
            # doc_signatures.append(base_signature)
            params = {
                "signatures": base_signature,
                "activeSignature": 0,
                "activeParameter": arg_idx,
            }
    return {"params": params}
# Buggy code
def perform_request(self, req_id, method, params):
    if method in self.sender_registry:
        logger.debug("Perform {0} request with id {1}".format(method, req_id))
        handler_name = self.sender_registry[method]
        handler = getattr(self, handler_name)
        response = handler(params)
        if method in self.handler_registry:
            converter_name = self.handler_registry[method]
            converter = getattr(self, converter_name)
            response = converter(response)
        if response is not None:
            self.sig_response_ready.emit(req_id, response)


# Traceback (TypeError)
File "/home/mehrad/P374/lib/python3.7/site-packages/spyder/plugins/completion/kite/client.py", line 135, in perform_request
TypeError: 'NoneType' object is not subscriptable
WARNING:spyder.widgets.github.backend:Failed to send bug report on Github. response={'code': 401, 'json': {'message': 'Bad credentials', 'documentation_url': 'https://developer.github.com/v3'}}
WARNING:spyder.widgets.github.backend:Failed to send bug report on Github. response={'code': 401, 'json': {'message': 'Bad credentials', 'documentation_url': 'https://developer.github.com/v3'}}
WARNING:spyder.widgets.github.backend:Failed to send bug report on Github. response={'code': 401, 'json': {'message': 'Bad credentials', 'documentation_url': 'https://developer.github.com/v3'}}

# Fixed code
def perform_request(self, req_id, method, params):
    if method in self.sender_registry:
        logger.debug("Perform {0} request with id {1}".format(method, req_id))
        handler_name = self.sender_registry[method]
        handler = getattr(self, handler_name)
        response = handler(params)
        if method in self.handler_registry:
            converter_name = self.handler_registry[method]
            converter = getattr(self, converter_name)
            if response is not None:
                response = converter(response)
        if response is not None:
            self.sig_response_ready.emit(req_id, response)
# Buggy code
def renamed(self, source, dest):
    """File was renamed in file explorer widget or in project explorer"""
    filename = osp.abspath(to_text_string(source))
    index = self.editorstacks[0].has_filename(filename)
    if index is not None:
        for editorstack in self.editorstacks:
            editorstack.rename_in_data(filename, new_filename=to_text_string(dest))


# Traceback (KeyError)
File "/home/ravi/Anaconda/lib/python3.7/site-packages/spyder/plugins/editor/utils/autosave.py", line 122, in do_autosave
stack.autosave.autosave_all()
File "/home/ravi/Anaconda/lib/python3.7/site-packages/spyder/plugins/editor/utils/autosave.py", line 305, in autosave_all
self.maybe_autosave(index)
File "/home/ravi/Anaconda/lib/python3.7/site-packages/spyder/plugins/editor/utils/autosave.py", line 265, in maybe_autosave
orig_hash = self.file_hashes[orig_filename]
KeyError: '/home/ravi/Documents/fj/tictac.py'
WARNING:spyder.widgets.github.backend:Failed to send bug report on Github. response={'code': 401, 'json': {'message': 'Bad credentials', 'documentation_url': 'https://developer.github.com/v3'}}
WARNING:spyder.widgets.github.backend:Failed to send bug report on Github. response={'code': 401, 'json': {'message': 'Bad credentials', 'documentation_url': 'https://developer.github.com/v3'}}

# Fixed code
def renamed(self, source, dest):
    """
    Propagate file rename to editor stacks and autosave component.

    This function is called when a file is renamed in the file explorer
    widget or the project explorer.
    """
    filename = osp.abspath(to_text_string(source))
    index = self.editorstacks[0].has_filename(filename)
    if index is not None:
        for editorstack in self.editorstacks:
            editorstack.rename_in_data(filename, new_filename=to_text_string(dest))
    self.editorstacks[0].autosave.file_renamed(filename, to_text_string(dest))
# Buggy code
def remove_autosave_file(self, filename):
    """
    Remove autosave file for specified file.

    This function also updates `self.name_mapping` and `self.file_hashes`.
    """
    if filename not in self.name_mapping:
        return
    autosave_filename = self.name_mapping[filename]
    try:
        os.remove(autosave_filename)
    except EnvironmentError as error:
        action = _("Error while removing autosave file {}").format(autosave_filename)
        msgbox = AutosaveErrorDialog(action, error)
        msgbox.exec_if_enabled()
    del self.name_mapping[filename]
    del self.file_hashes[autosave_filename]
    self.save_autosave_mapping()
    logger.debug("Removing autosave file %s", autosave_filename)


# Traceback (KeyError)
File "/home/ravi/Anaconda/lib/python3.7/site-packages/spyder/plugins/editor/utils/autosave.py", line 122, in do_autosave
stack.autosave.autosave_all()
File "/home/ravi/Anaconda/lib/python3.7/site-packages/spyder/plugins/editor/utils/autosave.py", line 305, in autosave_all
self.maybe_autosave(index)
File "/home/ravi/Anaconda/lib/python3.7/site-packages/spyder/plugins/editor/utils/autosave.py", line 265, in maybe_autosave
orig_hash = self.file_hashes[orig_filename]
KeyError: '/home/ravi/Documents/fj/tictac.py'
WARNING:spyder.widgets.github.backend:Failed to send bug report on Github. response={'code': 401, 'json': {'message': 'Bad credentials', 'documentation_url': 'https://developer.github.com/v3'}}
WARNING:spyder.widgets.github.backend:Failed to send bug report on Github. response={'code': 401, 'json': {'message': 'Bad credentials', 'documentation_url': 'https://developer.github.com/v3'}}

# Fixed code
def remove_autosave_file(self, filename):
    """
    Remove autosave file for specified file.

    This function also updates `self.name_mapping` and `self.file_hashes`.
    If there is no autosave file, then the function returns without doing
    anything.
    """
    if filename not in self.name_mapping:
        return
    autosave_filename = self.name_mapping[filename]
    try:
        os.remove(autosave_filename)
    except EnvironmentError as error:
        action = _("Error while removing autosave file {}").format(autosave_filename)
        msgbox = AutosaveErrorDialog(action, error)
        msgbox.exec_if_enabled()
    del self.name_mapping[filename]
    del self.file_hashes[autosave_filename]
    self.save_autosave_mapping()
    logger.debug("Removing autosave file %s", autosave_filename)
# Buggy code
def convert_completion_request(self, response):
    spyder_completions = []
    completions = response["completions"]
    if completions is not None:
        for completion in completions:
            entry = {
                "kind": KITE_DOCUMENT_TYPES.get(
                    completion["hint"], CompletionItemKind.TEXT
                ),
                "insertText": completion["snippet"]["text"],
                "filterText": completion["display"],
                "sortText": completion["display"][0],
                "documentation": completion["documentation"]["text"],
            }
            spyder_completions.append(entry)
    return {"params": spyder_completions}


# Traceback (TypeError)
File "C:\Users\Amin\Anaconda3\envs\pmeal\lib\site-packages\spyder\plugins\completion\kite\client.py", line 135, in perform_request
TypeError: 'NoneType' object is not subscriptable

# Fixed code
def convert_completion_request(self, response):
    spyder_completions = []
    if response is not None:
        completions = response["completions"]
        if completions is not None:
            for completion in completions:
                entry = {
                    "kind": KITE_DOCUMENT_TYPES.get(
                        completion["hint"], CompletionItemKind.TEXT
                    ),
                    "insertText": completion["snippet"]["text"],
                    "filterText": completion["display"],
                    "sortText": completion["display"][0],
                    "documentation": completion["documentation"]["text"],
                }
                spyder_completions.append(entry)
    return {"params": spyder_completions}
# Buggy code
def process_hover(self, response):
    # logger.debug(response)
    report = response["report"]
    text = report["description_text"]
    if len(text) == 0:
        text = None
    return {"params": text}


# Traceback (TypeError)
File "C:\Users\Amin\Anaconda3\envs\pmeal\lib\site-packages\spyder\plugins\completion\kite\client.py", line 135, in perform_request
TypeError: 'NoneType' object is not subscriptable

# Fixed code
def process_hover(self, response):
    logger.debug(response)
    if response is not None:
        report = response["report"]
        text = report["description_text"]
        if len(text) == 0:
            text = None
    else:
        text = None

    return {"params": text}