text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Construct the text based on the entered content in the widget.
<END_TASK>
<USER_TASK:>
Description:
def process_text(self, array=True):
"""
Construct the text based on the entered content in the widget.
"""
|
if array:
prefix = 'np.array([['
else:
prefix = 'np.matrix([['
suffix = ']])'
values = self._widget.text().strip()
if values != '':
# cleans repeated spaces
exp = r'(\s*)' + ROW_SEPARATOR + r'(\s*)'
values = re.sub(exp, ROW_SEPARATOR, values)
values = re.sub(r"\s+", " ", values)
values = re.sub(r"]$", "", values)
values = re.sub(r"^\[", "", values)
values = re.sub(ROW_SEPARATOR + r'*$', '', values)
# replaces spaces by commas
values = values.replace(' ', ELEMENT_SEPARATOR)
# iterate to find number of rows and columns
new_values = []
rows = values.split(ROW_SEPARATOR)
nrows = len(rows)
ncols = []
for row in rows:
new_row = []
elements = row.split(ELEMENT_SEPARATOR)
ncols.append(len(elements))
for e in elements:
num = e
# replaces not defined values
if num in NAN_VALUES:
num = 'np.nan'
# Convert numbers to floating point
if self._force_float:
try:
num = str(float(e))
except:
pass
new_row.append(num)
new_values.append(ELEMENT_SEPARATOR.join(new_row))
new_values = ROW_SEPARATOR.join(new_values)
values = new_values
# Check validity
if len(set(ncols)) == 1:
self._valid = True
else:
self._valid = False
# Single rows are parsed as 1D arrays/matrices
if nrows == 1:
prefix = prefix[:-1]
suffix = suffix.replace("]])", "])")
# Fix offset
offset = self._offset
braces = BRACES.replace(' ', '\n' + ' '*(offset + len(prefix) - 1))
values = values.replace(ROW_SEPARATOR, braces)
text = "{0}{1}{2}".format(prefix, values, suffix)
self._text = text
else:
self._text = ''
self.update_warning()
|
<SYSTEM_TASK:>
Updates the icon and tip based on the validity of the array content.
<END_TASK>
<USER_TASK:>
Description:
def update_warning(self):
"""
Updates the icon and tip based on the validity of the array content.
"""
|
widget = self._button_warning
if not self.is_valid():
tip = _('Array dimensions not valid')
widget.setIcon(ima.icon('MessageBoxWarning'))
widget.setToolTip(tip)
QToolTip.showText(self._widget.mapToGlobal(QPoint(0, 5)), tip)
else:
self._button_warning.setToolTip('')
|
<SYSTEM_TASK:>
Get selected language setting and save to language configuration file.
<END_TASK>
<USER_TASK:>
Description:
def _save_lang(self):
"""
Get selected language setting and save to language configuration file.
"""
|
for combobox, (option, _default) in list(self.comboboxes.items()):
if option == 'interface_language':
data = combobox.itemData(combobox.currentIndex())
value = from_qvariant(data, to_text_string)
break
try:
save_lang_conf(value)
self.set_option('interface_language', value)
except Exception:
QMessageBox.critical(
self, _("Error"),
_("We're sorry but the following error occurred while trying "
"to set your selected language:<br><br>"
"<tt>{}</tt>").format(traceback.format_exc()),
QMessageBox.Ok)
return
|
<SYSTEM_TASK:>
Check if path has write access
<END_TASK>
<USER_TASK:>
Description:
def is_writable(path):
"""Check if path has write access"""
|
try:
testfile = tempfile.TemporaryFile(dir=path)
testfile.close()
except OSError as e:
if e.errno == errno.EACCES: # 13
return False
return True
|
<SYSTEM_TASK:>
Get all available project types.
<END_TASK>
<USER_TASK:>
Description:
def _get_project_types(self):
"""Get all available project types."""
|
project_types = get_available_project_types()
projects = []
for project in project_types:
projects.append(project.PROJECT_TYPE_NAME)
return projects
|
<SYSTEM_TASK:>
Copy text to clipboard... or keyboard interrupt
<END_TASK>
<USER_TASK:>
Description:
def copy(self):
"""Copy text to clipboard... or keyboard interrupt"""
|
if self.has_selected_text():
ConsoleBaseWidget.copy(self)
elif not sys.platform == 'darwin':
self.interrupt()
|
<SYSTEM_TASK:>
Load history from a .py file in user home directory
<END_TASK>
<USER_TASK:>
Description:
def load_history(self):
"""Load history from a .py file in user home directory"""
|
if osp.isfile(self.history_filename):
rawhistory, _ = encoding.readlines(self.history_filename)
rawhistory = [line.replace('\n', '') for line in rawhistory]
if rawhistory[1] != self.INITHISTORY[1]:
rawhistory[1] = self.INITHISTORY[1]
else:
rawhistory = self.INITHISTORY
history = [line for line in rawhistory \
if line and not line.startswith('#')]
# Truncating history to X entries:
while len(history) >= CONF.get('historylog', 'max_entries'):
del history[0]
while rawhistory[0].startswith('#'):
del rawhistory[0]
del rawhistory[0]
# Saving truncated history:
try:
encoding.writelines(rawhistory, self.history_filename)
except EnvironmentError:
pass
return history
|
<SYSTEM_TASK:>
Simulate stdout and stderr
<END_TASK>
<USER_TASK:>
Description:
def write(self, text, flush=False, error=False, prompt=False):
"""Simulate stdout and stderr"""
|
if prompt:
self.flush()
if not is_string(text):
# This test is useful to discriminate QStrings from decoded str
text = to_text_string(text)
self.__buffer.append(text)
ts = time.time()
if flush or prompt:
self.flush(error=error, prompt=prompt)
elif ts - self.__timestamp > 0.05:
self.flush(error=error)
self.__timestamp = ts
# Timer to flush strings cached by last write() operation in series
self.__flushtimer.start(50)
|
<SYSTEM_TASK:>
Flush buffer, write text to console
<END_TASK>
<USER_TASK:>
Description:
def flush(self, error=False, prompt=False):
"""Flush buffer, write text to console"""
|
# Fix for Issue 2452
if PY3:
try:
text = "".join(self.__buffer)
except TypeError:
text = b"".join(self.__buffer)
try:
text = text.decode( locale.getdefaultlocale()[1] )
except:
pass
else:
text = "".join(self.__buffer)
self.__buffer = []
self.insert_text(text, at_end=True, error=error, prompt=prompt)
QCoreApplication.processEvents()
self.repaint()
# Clear input buffer:
self.new_input_line = True
|
<SYSTEM_TASK:>
Insert text at the current cursor position
<END_TASK>
<USER_TASK:>
Description:
def insert_text(self, text, at_end=False, error=False, prompt=False):
"""
Insert text at the current cursor position
or at the end of the command line
"""
|
if at_end:
# Insert text at the end of the command line
self.append_text_to_shell(text, error, prompt)
else:
# Insert text at current cursor position
ConsoleBaseWidget.insert_text(self, text)
|
<SYSTEM_TASK:>
Copy text to clipboard without prompts
<END_TASK>
<USER_TASK:>
Description:
def copy_without_prompts(self):
"""Copy text to clipboard without prompts"""
|
text = self.get_selected_text()
lines = text.split(os.linesep)
for index, line in enumerate(lines):
if line.startswith('>>> ') or line.startswith('... '):
lines[index] = line[4:]
text = os.linesep.join(lines)
QApplication.clipboard().setText(text)
|
<SYSTEM_TASK:>
Reimplemented slot to handle multiline paste action
<END_TASK>
<USER_TASK:>
Description:
def paste(self):
"""Reimplemented slot to handle multiline paste action"""
|
text = to_text_string(QApplication.clipboard().text())
if len(text.splitlines()) > 1:
# Multiline paste
if self.new_input_line:
self.on_new_line()
self.remove_selected_text() # Remove selection, eventually
end = self.get_current_line_from_cursor()
lines = self.get_current_line_to_cursor() + text + end
self.clear_line()
self.execute_lines(lines)
self.move_cursor(-len(end))
else:
# Standard paste
ShellBaseWidget.paste(self)
|
<SYSTEM_TASK:>
Display the possible completions
<END_TASK>
<USER_TASK:>
Description:
def show_completion_list(self, completions, completion_text=""):
"""Display the possible completions"""
|
if not completions:
return
if not isinstance(completions[0], tuple):
completions = [(c, '') for c in completions]
if len(completions) == 1 and completions[0][0] == completion_text:
return
self.completion_text = completion_text
# Sorting completion list (entries starting with underscore are
# put at the end of the list):
underscore = set([(comp, t) for (comp, t) in completions
if comp.startswith('_')])
completions = sorted(set(completions) - underscore,
key=lambda x: str_lower(x[0]))
completions += sorted(underscore, key=lambda x: str_lower(x[0]))
self.show_completion_widget(completions)
|
<SYSTEM_TASK:>
Display a completion list based on the current line
<END_TASK>
<USER_TASK:>
Description:
def show_code_completion(self):
"""Display a completion list based on the current line"""
|
# Note: unicode conversion is needed only for ExternalShellBase
text = to_text_string(self.get_current_line_to_cursor())
last_obj = self.get_last_obj()
if not text:
return
obj_dir = self.get_dir(last_obj)
if last_obj and obj_dir and text.endswith('.'):
self.show_completion_list(obj_dir)
return
# Builtins and globals
if not text.endswith('.') and last_obj \
and re.match(r'[a-zA-Z_0-9]*$', last_obj):
b_k_g = dir(builtins)+self.get_globals_keys()+keyword.kwlist
for objname in b_k_g:
if objname.startswith(last_obj) and objname != last_obj:
self.show_completion_list(b_k_g, completion_text=last_obj)
return
else:
return
# Looking for an incomplete completion
if last_obj is None:
last_obj = text
dot_pos = last_obj.rfind('.')
if dot_pos != -1:
if dot_pos == len(last_obj)-1:
completion_text = ""
else:
completion_text = last_obj[dot_pos+1:]
last_obj = last_obj[:dot_pos]
completions = self.get_dir(last_obj)
if completions is not None:
self.show_completion_list(completions,
completion_text=completion_text)
return
# Looking for ' or ": filename completion
q_pos = max([text.rfind("'"), text.rfind('"')])
if q_pos != -1:
completions = self.get_cdlistdir()
if completions:
self.show_completion_list(completions,
completion_text=text[q_pos+1:])
return
|
<SYSTEM_TASK:>
Set the project directory
<END_TASK>
<USER_TASK:>
Description:
def set_project_dir(self, directory):
"""Set the project directory"""
|
if directory is not None:
self.treewidget.set_root_path(osp.dirname(directory))
self.treewidget.set_folder_names([osp.basename(directory)])
self.treewidget.setup_project_view()
try:
self.treewidget.setExpanded(self.treewidget.get_index(directory),
True)
except TypeError:
pass
|
<SYSTEM_TASK:>
Data is available in stdout, let's empty the queue and write it!
<END_TASK>
<USER_TASK:>
Description:
def stdout_avail(self):
"""Data is available in stdout, let's empty the queue and write it!"""
|
data = self.interpreter.stdout_write.empty_queue()
if data:
self.write(data)
|
<SYSTEM_TASK:>
Data is available in stderr, let's empty the queue and write it!
<END_TASK>
<USER_TASK:>
Description:
def stderr_avail(self):
"""Data is available in stderr, let's empty the queue and write it!"""
|
data = self.interpreter.stderr_write.empty_queue()
if data:
self.write(data, error=True)
self.flush(error=True)
|
<SYSTEM_TASK:>
Simulate keyboard interrupt
<END_TASK>
<USER_TASK:>
Description:
def keyboard_interrupt(self):
"""Simulate keyboard interrupt"""
|
if self.multithreaded:
self.interpreter.raise_keyboard_interrupt()
else:
if self.interpreter.more:
self.write_error("\nKeyboardInterrupt\n")
self.interpreter.more = False
self.new_prompt(self.interpreter.p1)
self.interpreter.resetbuffer()
else:
self.interrupted = True
|
<SYSTEM_TASK:>
Returns a compiled regex pattern to search for query letters in order.
<END_TASK>
<USER_TASK:>
Description:
def get_search_regex(query, ignore_case=True):
"""Returns a compiled regex pattern to search for query letters in order.
Parameters
----------
query : str
String to search in another string (in order of character occurrence).
ignore_case : True
Optional value perform a case insensitive search (True by default).
Returns
-------
pattern : SRE_Pattern
Notes
-----
This function adds '.*' between the query characters and compiles the
resulting regular expression.
"""
|
regex_text = [char for char in query if char != ' ']
regex_text = '.*'.join(regex_text)
regex = r'({0})'.format(regex_text)
if ignore_case:
pattern = re.compile(regex, re.IGNORECASE)
else:
pattern = re.compile(regex)
return pattern
|
<SYSTEM_TASK:>
Search for query inside choices and return a list of tuples.
<END_TASK>
<USER_TASK:>
Description:
def get_search_scores(query, choices, ignore_case=True, template='{}',
valid_only=False, sort=False):
"""Search for query inside choices and return a list of tuples.
Returns a list of tuples of text with the enriched text (if a template is
provided) and a score for the match. Lower scores imply a better match.
Parameters
----------
query : str
String with letters to search in each choice (in order of appearance).
choices : list of str
List of sentences/words in which to search for the 'query' letters.
ignore_case : bool, optional
Optional value perform a case insensitive search (True by default).
template : str, optional
Optional template string to surround letters found in choices. This is
useful when using a rich text editor ('{}' by default).
Examples: '<b>{}</b>', '<code>{}</code>', '<i>{}</i>'
Returns
-------
results : list of tuples
List of tuples where the first item is the text (enriched if a
template was used) and a search score. Lower scores means better match.
"""
|
# First remove spaces from query
query = query.replace(' ', '')
pattern = get_search_regex(query, ignore_case)
results = []
for choice in choices:
r = re.search(pattern, choice)
if query and r:
result = get_search_score(query, choice, ignore_case=ignore_case,
apply_regex=False, template=template)
else:
if query:
result = (choice, choice, NOT_FOUND_SCORE)
else:
result = (choice, choice, NO_SCORE)
if valid_only:
if result[-1] != NOT_FOUND_SCORE:
results.append(result)
else:
results.append(result)
if sort:
results = sorted(results, key=lambda row: row[-1])
return results
|
<SYSTEM_TASK:>
Return True if text is the beginning of the function definition.
<END_TASK>
<USER_TASK:>
Description:
def is_start_of_function(text):
"""Return True if text is the beginning of the function definition."""
|
if isinstance(text, str) or isinstance(text, unicode):
function_prefix = ['def', 'async def']
text = text.lstrip()
for prefix in function_prefix:
if text.startswith(prefix):
return True
return False
|
<SYSTEM_TASK:>
Get func def when the cursor is located on the first def line.
<END_TASK>
<USER_TASK:>
Description:
def get_function_definition_from_first_line(self):
"""Get func def when the cursor is located on the first def line."""
|
document = self.code_editor.document()
cursor = QTextCursor(
document.findBlockByLineNumber(self.line_number_cursor - 1))
func_text = ''
func_indent = ''
is_first_line = True
line_number = cursor.blockNumber() + 1
number_of_lines = self.code_editor.blockCount()
remain_lines = number_of_lines - line_number + 1
number_of_lines_of_function = 0
for __ in range(min(remain_lines, 20)):
cur_text = to_text_string(cursor.block().text()).rstrip()
if is_first_line:
if not is_start_of_function(cur_text):
return None
func_indent = get_indent(cur_text)
is_first_line = False
else:
cur_indent = get_indent(cur_text)
if cur_indent <= func_indent:
return None
if is_start_of_function(cur_text):
return None
if cur_text.strip == '':
return None
if cur_text[-1] == '\\':
cur_text = cur_text[:-1]
func_text += cur_text
number_of_lines_of_function += 1
if cur_text.endswith(':'):
return func_text, number_of_lines_of_function
cursor.movePosition(QTextCursor.NextBlock)
return None
|
<SYSTEM_TASK:>
Get func def when the cursor is located below the last def line.
<END_TASK>
<USER_TASK:>
Description:
def get_function_definition_from_below_last_line(self):
"""Get func def when the cursor is located below the last def line."""
|
cursor = self.code_editor.textCursor()
func_text = ''
is_first_line = True
line_number = cursor.blockNumber() + 1
number_of_lines_of_function = 0
for idx in range(min(line_number, 20)):
if cursor.block().blockNumber() == 0:
return None
cursor.movePosition(QTextCursor.PreviousBlock)
prev_text = to_text_string(cursor.block().text()).rstrip()
if is_first_line:
if not prev_text.endswith(':'):
return None
is_first_line = False
elif prev_text.endswith(':') or prev_text == '':
return None
if prev_text[-1] == '\\':
prev_text = prev_text[:-1]
func_text = prev_text + func_text
number_of_lines_of_function += 1
if is_start_of_function(prev_text):
return func_text, number_of_lines_of_function
return None
|
<SYSTEM_TASK:>
Write docstring to editor by shortcut of code editor.
<END_TASK>
<USER_TASK:>
Description:
def write_docstring_for_shortcut(self):
"""Write docstring to editor by shortcut of code editor."""
|
# cursor placed below function definition
result = self.get_function_definition_from_below_last_line()
if result is not None:
__, number_of_lines_of_function = result
cursor = self.code_editor.textCursor()
for __ in range(number_of_lines_of_function):
cursor.movePosition(QTextCursor.PreviousBlock)
self.code_editor.setTextCursor(cursor)
cursor = self.code_editor.textCursor()
self.line_number_cursor = cursor.blockNumber() + 1
self.write_docstring_at_first_line_of_function()
|
<SYSTEM_TASK:>
Generate a docstring of numpy type.
<END_TASK>
<USER_TASK:>
Description:
def _generate_numpy_doc(self, func_info):
"""Generate a docstring of numpy type."""
|
numpy_doc = ''
arg_names = func_info.arg_name_list
arg_types = func_info.arg_type_list
arg_values = func_info.arg_value_list
if len(arg_names) > 0 and arg_names[0] == 'self':
del arg_names[0]
del arg_types[0]
del arg_values[0]
indent1 = func_info.func_indent + self.code_editor.indent_chars
indent2 = func_info.func_indent + self.code_editor.indent_chars * 2
numpy_doc += '\n{}\n'.format(indent1)
if len(arg_names) > 0:
numpy_doc += '\n{}Parameters'.format(indent1)
numpy_doc += '\n{}----------\n'.format(indent1)
arg_text = ''
for arg_name, arg_type, arg_value in zip(arg_names, arg_types,
arg_values):
arg_text += '{}{} : '.format(indent1, arg_name)
if arg_type:
arg_text += '{}'.format(arg_type)
else:
arg_text += 'TYPE'
if arg_value:
arg_text += ', optional'
arg_text += '\n{}DESCRIPTION.'.format(indent2)
if arg_value:
arg_value = arg_value.replace(self.quote3, self.quote3_other)
arg_text += ' The default is {}.'.format(arg_value)
arg_text += '\n'
numpy_doc += arg_text
if func_info.raise_list:
numpy_doc += '\n{}Raises'.format(indent1)
numpy_doc += '\n{}------'.format(indent1)
for raise_type in func_info.raise_list:
numpy_doc += '\n{}{}'.format(indent1, raise_type)
numpy_doc += '\n{}DESCRIPTION.'.format(indent2)
numpy_doc += '\n'
numpy_doc += '\n'
if func_info.has_yield:
header = '{0}Yields\n{0}------\n'.format(indent1)
else:
header = '{0}Returns\n{0}-------\n'.format(indent1)
return_type_annotated = func_info.return_type_annotated
if return_type_annotated:
return_section = '{}{}{}'.format(header, indent1,
return_type_annotated)
return_section += '\n{}DESCRIPTION.'.format(indent2)
else:
return_element_type = indent1 + '{return_type}\n' + indent2 + \
'DESCRIPTION.'
placeholder = return_element_type.format(return_type='TYPE')
return_element_name = indent1 + '{return_name} : ' + \
placeholder.lstrip()
try:
return_section = self._generate_docstring_return_section(
func_info.return_value_in_body, header,
return_element_name, return_element_type, placeholder,
indent1)
except (ValueError, IndexError):
return_section = '{}{}None.'.format(header, indent1)
numpy_doc += return_section
numpy_doc += '\n\n{}{}'.format(indent1, self.quote3)
return numpy_doc
|
<SYSTEM_TASK:>
Get the locations of top-level brackets in a string.
<END_TASK>
<USER_TASK:>
Description:
def find_top_level_bracket_locations(string_toparse):
"""Get the locations of top-level brackets in a string."""
|
bracket_stack = []
replace_args_list = []
bracket_type = None
literal_type = ''
brackets = {'(': ')', '[': ']', '{': '}'}
for idx, character in enumerate(string_toparse):
if (not bracket_stack and character in brackets.keys()
or character == bracket_type):
bracket_stack.append(idx)
bracket_type = character
elif bracket_type and character == brackets[bracket_type]:
begin_idx = bracket_stack.pop()
if not bracket_stack:
if not literal_type:
if bracket_type == '(':
literal_type = '(None)'
elif bracket_type == '[':
literal_type = '[list]'
elif bracket_type == '{':
if idx - begin_idx <= 1:
literal_type = '{dict}'
else:
literal_type = '{set}'
replace_args_list.append(
(string_toparse[begin_idx:idx + 1],
literal_type, 1))
bracket_type = None
literal_type = ''
elif len(bracket_stack) == 1:
if bracket_type == '(' and character == ',':
literal_type = '(tuple)'
elif bracket_type == '{' and character == ':':
literal_type = '{dict}'
elif bracket_type == '(' and character == ':':
literal_type = '[slice]'
if bracket_stack:
raise IndexError('Bracket mismatch')
for replace_args in replace_args_list:
string_toparse = string_toparse.replace(*replace_args)
return string_toparse
|
<SYSTEM_TASK:>
Return the appropriate text for a group of return elements.
<END_TASK>
<USER_TASK:>
Description:
def parse_return_elements(return_vals_group, return_element_name,
return_element_type, placeholder):
"""Return the appropriate text for a group of return elements."""
|
all_eq = (return_vals_group.count(return_vals_group[0])
== len(return_vals_group))
if all([{'[list]', '(tuple)', '{dict}', '{set}'}.issuperset(
return_vals_group)]) and all_eq:
return return_element_type.format(
return_type=return_vals_group[0][1:-1])
# Output placeholder if special Python chars present in name
py_chars = {' ', '+', '-', '*', '/', '%', '@', '<', '>', '&', '|', '^',
'~', '=', ',', ':', ';', '#', '(', '[', '{', '}', ']',
')', }
if any([any([py_char in return_val for py_char in py_chars])
for return_val in return_vals_group]):
return placeholder
# Output str type and no name if only string literals
if all(['"' in return_val or '\'' in return_val
for return_val in return_vals_group]):
return return_element_type.format(return_type='str')
# Output bool type and no name if only bool literals
if {'True', 'False'}.issuperset(return_vals_group):
return return_element_type.format(return_type='bool')
# Output numeric types and no name if only numeric literals
try:
[float(return_val) for return_val in return_vals_group]
num_not_int = 0
for return_val in return_vals_group:
try:
int(return_val)
except ValueError: # If not an integer (EAFP)
num_not_int = num_not_int + 1
if num_not_int == 0:
return return_element_type.format(return_type='int')
elif num_not_int == len(return_vals_group):
return return_element_type.format(return_type='float')
else:
return return_element_type.format(return_type='numeric')
except ValueError: # Not a numeric if float conversion didn't work
pass
# If names are not equal, don't contain "." or are a builtin
if ({'self', 'cls', 'None'}.isdisjoint(return_vals_group) and all_eq
and all(['.' not in return_val
for return_val in return_vals_group])):
return return_element_name.format(return_name=return_vals_group[0])
return placeholder
|
<SYSTEM_TASK:>
Return True if the charactor is in pairs of brackets or quotes.
<END_TASK>
<USER_TASK:>
Description:
def is_char_in_pairs(pos_char, pairs):
"""Return True if the charactor is in pairs of brackets or quotes."""
|
for pos_left, pos_right in pairs.items():
if pos_left < pos_char < pos_right:
return True
return False
|
<SYSTEM_TASK:>
Return the start and end position of pairs of quotes.
<END_TASK>
<USER_TASK:>
Description:
def _find_quote_position(text):
"""Return the start and end position of pairs of quotes."""
|
pos = {}
is_found_left_quote = False
for idx, character in enumerate(text):
if is_found_left_quote is False:
if character == "'" or character == '"':
is_found_left_quote = True
quote = character
left_pos = idx
else:
if character == quote and text[idx - 1] != '\\':
pos[left_pos] = idx
is_found_left_quote = False
if is_found_left_quote:
raise IndexError("No matching close quote at: " + str(left_pos))
return pos
|
<SYSTEM_TASK:>
Split argument text to name, type, value.
<END_TASK>
<USER_TASK:>
Description:
def split_arg_to_name_type_value(self, args_list):
"""Split argument text to name, type, value."""
|
for arg in args_list:
arg_type = None
arg_value = None
has_type = False
has_value = False
pos_colon = arg.find(':')
pos_equal = arg.find('=')
if pos_equal > -1:
has_value = True
if pos_colon > -1:
if not has_value:
has_type = True
elif pos_equal > pos_colon: # exception for def foo(arg1=":")
has_type = True
if has_value and has_type:
arg_name = arg[0:pos_colon].strip()
arg_type = arg[pos_colon + 1:pos_equal].strip()
arg_value = arg[pos_equal + 1:].strip()
elif not has_value and has_type:
arg_name = arg[0:pos_colon].strip()
arg_type = arg[pos_colon + 1:].strip()
elif has_value and not has_type:
arg_name = arg[0:pos_equal].strip()
arg_value = arg[pos_equal + 1:].strip()
else:
arg_name = arg.strip()
self.arg_name_list.append(arg_name)
self.arg_type_list.append(arg_type)
self.arg_value_list.append(arg_value)
|
<SYSTEM_TASK:>
Split the text including multiple arguments to list.
<END_TASK>
<USER_TASK:>
Description:
def split_args_text_to_list(self, args_text):
"""Split the text including multiple arguments to list.
This function uses a comma to separate arguments and ignores a comma in
brackets ans quotes.
"""
|
args_list = []
idx_find_start = 0
idx_arg_start = 0
try:
pos_quote = self._find_quote_position(args_text)
pos_round = self._find_bracket_position(args_text, '(', ')',
pos_quote)
pos_curly = self._find_bracket_position(args_text, '{', '}',
pos_quote)
pos_square = self._find_bracket_position(args_text, '[', ']',
pos_quote)
except IndexError:
return None
while True:
pos_comma = args_text.find(',', idx_find_start)
if pos_comma == -1:
break
idx_find_start = pos_comma + 1
if self.is_char_in_pairs(pos_comma, pos_round) or \
self.is_char_in_pairs(pos_comma, pos_curly) or \
self.is_char_in_pairs(pos_comma, pos_square) or \
self.is_char_in_pairs(pos_comma, pos_quote):
continue
args_list.append(args_text[idx_arg_start:pos_comma])
idx_arg_start = pos_comma + 1
if idx_arg_start < len(args_text):
args_list.append(args_text[idx_arg_start:])
return args_list
|
<SYSTEM_TASK:>
Close the instance if key is not enter key.
<END_TASK>
<USER_TASK:>
Description:
def keyPressEvent(self, event):
"""Close the instance if key is not enter key."""
|
key = event.key()
if key not in (Qt.Key_Enter, Qt.Key_Return):
self.code_editor.keyPressEvent(event)
self.close()
else:
super(QMenuOnlyForEnter, self).keyPressEvent(event)
|
<SYSTEM_TASK:>
Check if a process is running on windows systems based on the pid.
<END_TASK>
<USER_TASK:>
Description:
def _is_pid_running_on_windows(pid):
"""Check if a process is running on windows systems based on the pid."""
|
pid = str(pid)
# Hide flashing command prompt
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
process = subprocess.Popen(r'tasklist /fi "PID eq {0}"'.format(pid),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
startupinfo=startupinfo)
stdoutdata, stderrdata = process.communicate()
stdoutdata = to_text_string(stdoutdata)
process.kill()
check = pid in stdoutdata
return check
|
<SYSTEM_TASK:>
Animate dots at the end of the splash screen message.
<END_TASK>
<USER_TASK:>
Description:
def animate_ellipsis(self):
"""Animate dots at the end of the splash screen message."""
|
ellipsis = self.ellipsis.pop(0)
text = ' '*len(ellipsis) + self.splash_text + ellipsis
self.ellipsis.append(ellipsis)
self._show_message(text)
|
<SYSTEM_TASK:>
Sets the text in the bottom of the Splash screen.
<END_TASK>
<USER_TASK:>
Description:
def set_splash_message(self, text):
"""Sets the text in the bottom of the Splash screen."""
|
self.splash_text = text
self._show_message(text)
self.timer_ellipsis.start(500)
|
<SYSTEM_TASK:>
Overloaded method to handle links ourselves
<END_TASK>
<USER_TASK:>
Description:
def acceptNavigationRequest(self, url, navigation_type, isMainFrame):
"""
Overloaded method to handle links ourselves
"""
|
if navigation_type == QWebEnginePage.NavigationTypeLinkClicked:
self.linkClicked.emit(url)
return False
return True
|
<SYSTEM_TASK:>
Register QAction or QShortcut to Spyder main application.
<END_TASK>
<USER_TASK:>
Description:
def register_shortcut(self, qaction_or_qshortcut, context, name,
add_sc_to_tip=False):
"""
Register QAction or QShortcut to Spyder main application.
if add_sc_to_tip is True, the shortcut is added to the
action's tooltip
"""
|
self.main.register_shortcut(qaction_or_qshortcut, context,
name, add_sc_to_tip)
|
<SYSTEM_TASK:>
Register widget shortcuts.
<END_TASK>
<USER_TASK:>
Description:
def register_widget_shortcuts(self, widget):
"""
Register widget shortcuts.
Widget interface must have a method called 'get_shortcut_data'
"""
|
for qshortcut, context, name in widget.get_shortcut_data():
self.register_shortcut(qshortcut, context, name)
|
<SYSTEM_TASK:>
Dock widget visibility has changed.
<END_TASK>
<USER_TASK:>
Description:
def visibility_changed(self, enable):
"""
Dock widget visibility has changed.
"""
|
if self.dockwidget is None:
return
if enable:
self.dockwidget.raise_()
widget = self.get_focus_widget()
if widget is not None and self.undocked_window is not None:
widget.setFocus()
visible = self.dockwidget.isVisible() or self.ismaximized
if self.DISABLE_ACTIONS_WHEN_HIDDEN:
toggle_actions(self.plugin_actions, visible)
self.isvisible = enable and visible
if self.isvisible:
self.refresh_plugin()
|
<SYSTEM_TASK:>
Set a plugin option in configuration file.
<END_TASK>
<USER_TASK:>
Description:
def set_option(self, option, value):
"""
Set a plugin option in configuration file.
Note: Use sig_option_changed to call it from widgets of the
same or another plugin.
"""
|
CONF.set(self.CONF_SECTION, str(option), value)
|
<SYSTEM_TASK:>
Showing message in main window's status bar.
<END_TASK>
<USER_TASK:>
Description:
def starting_long_process(self, message):
"""
Showing message in main window's status bar.
This also changes mouse cursor to Qt.WaitCursor
"""
|
self.show_message(message)
QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
QApplication.processEvents()
|
<SYSTEM_TASK:>
Clear main window's status bar and restore mouse cursor.
<END_TASK>
<USER_TASK:>
Description:
def ending_long_process(self, message=""):
"""
Clear main window's status bar and restore mouse cursor.
"""
|
QApplication.restoreOverrideCursor()
self.show_message(message, timeout=2000)
QApplication.processEvents()
|
<SYSTEM_TASK:>
Return the screen resolution of the primary screen.
<END_TASK>
<USER_TASK:>
Description:
def get_screen_resolution(self):
"""Return the screen resolution of the primary screen."""
|
widget = QDesktopWidget()
geometry = widget.availableGeometry(widget.primaryScreen())
return geometry.width(), geometry.height()
|
<SYSTEM_TASK:>
Set the currently visible fig_browser in the stack widget, refresh the
<END_TASK>
<USER_TASK:>
Description:
def set_current_widget(self, fig_browser):
"""
Set the currently visible fig_browser in the stack widget, refresh the
actions of the cog menu button and move it to the layout of the new
fig_browser.
"""
|
self.stack.setCurrentWidget(fig_browser)
# We update the actions of the options button (cog menu) and
# we move it to the layout of the current widget.
self.refresh_actions()
fig_browser.setup_options_button()
|
<SYSTEM_TASK:>
Register shell with figure explorer.
<END_TASK>
<USER_TASK:>
Description:
def add_shellwidget(self, shellwidget):
"""
Register shell with figure explorer.
This function opens a new FigureBrowser for browsing the figures
in the shell.
"""
|
shellwidget_id = id(shellwidget)
if shellwidget_id not in self.shellwidgets:
self.options_button.setVisible(True)
fig_browser = FigureBrowser(
self, options_button=self.options_button,
background_color=MAIN_BG_COLOR)
fig_browser.set_shellwidget(shellwidget)
fig_browser.setup(**self.get_settings())
fig_browser.sig_option_changed.connect(
self.sig_option_changed.emit)
fig_browser.thumbnails_sb.redirect_stdio.connect(
self.main.redirect_internalshell_stdio)
self.register_widget_shortcuts(fig_browser)
self.add_widget(fig_browser)
self.shellwidgets[shellwidget_id] = fig_browser
self.set_shellwidget_from_id(shellwidget_id)
return fig_browser
|
<SYSTEM_TASK:>
Disable empty layout name possibility
<END_TASK>
<USER_TASK:>
Description:
def check_text(self, text):
"""Disable empty layout name possibility"""
|
if to_text_string(text) == u'':
self.button_ok.setEnabled(False)
else:
self.button_ok.setEnabled(True)
|
<SYSTEM_TASK:>
Communicate with monitor
<END_TASK>
<USER_TASK:>
Description:
def communicate(sock, command, settings=[]):
"""Communicate with monitor"""
|
try:
COMMUNICATE_LOCK.acquire()
write_packet(sock, command)
for option in settings:
write_packet(sock, option)
return read_packet(sock)
finally:
COMMUNICATE_LOCK.release()
|
<SYSTEM_TASK:>
Clean the tree and view parameters
<END_TASK>
<USER_TASK:>
Description:
def initialize_view(self):
"""Clean the tree and view parameters"""
|
self.clear()
self.item_depth = 0 # To be use for collapsing/expanding one level
self.item_list = [] # To be use for collapsing/expanding one level
self.items_to_be_shown = {}
self.current_view_depth = 0
|
<SYSTEM_TASK:>
Find a function without a caller
<END_TASK>
<USER_TASK:>
Description:
def find_root(self):
"""Find a function without a caller"""
|
self.profdata.sort_stats("cumulative")
for func in self.profdata.fcn_list:
if ('~', 0) != func[0:2] and not func[2].startswith(
'<built-in method exec>'):
# This skips the profiler function at the top of the list
# it does only occur in Python 3
return func
|
<SYSTEM_TASK:>
Populate the tree with profiler data and display it.
<END_TASK>
<USER_TASK:>
Description:
def show_tree(self):
"""Populate the tree with profiler data and display it."""
|
self.initialize_view() # Clear before re-populating
self.setItemsExpandable(True)
self.setSortingEnabled(False)
rootkey = self.find_root() # This root contains profiler overhead
if rootkey:
self.populate_tree(self, self.find_callees(rootkey))
self.resizeColumnToContents(0)
self.setSortingEnabled(True)
self.sortItems(1, Qt.AscendingOrder) # FIXME: hardcoded index
self.change_view(1)
|
<SYSTEM_TASK:>
Returns processed information about the function's name and file.
<END_TASK>
<USER_TASK:>
Description:
def function_info(self, functionKey):
"""Returns processed information about the function's name and file."""
|
node_type = 'function'
filename, line_number, function_name = functionKey
if function_name == '<module>':
modulePath, moduleName = osp.split(filename)
node_type = 'module'
if moduleName == '__init__.py':
modulePath, moduleName = osp.split(modulePath)
function_name = '<' + moduleName + '>'
if not filename or filename == '~':
file_and_line = '(built-in)'
node_type = 'builtin'
else:
if function_name == '__init__':
node_type = 'constructor'
file_and_line = '%s : %d' % (filename, line_number)
return filename, line_number, function_name, file_and_line, node_type
|
<SYSTEM_TASK:>
Get format and units for data coming from profiler task.
<END_TASK>
<USER_TASK:>
Description:
def format_measure(measure):
"""Get format and units for data coming from profiler task."""
|
# Convert to a positive value.
measure = abs(measure)
# For number of calls
if isinstance(measure, int):
return to_text_string(measure)
# For time measurements
if 1.e-9 < measure <= 1.e-6:
measure = u"{0:.2f} ns".format(measure / 1.e-9)
elif 1.e-6 < measure <= 1.e-3:
measure = u"{0:.2f} us".format(measure / 1.e-6)
elif 1.e-3 < measure <= 1:
measure = u"{0:.2f} ms".format(measure / 1.e-3)
elif 1 < measure <= 60:
measure = u"{0:.2f} sec".format(measure)
elif 60 < measure <= 3600:
m, s = divmod(measure, 3600)
if s > 60:
m, s = divmod(measure, 60)
s = to_text_string(s).split(".")[-1]
measure = u"{0:.0f}.{1:.2s} min".format(m, s)
else:
h, m = divmod(measure, 3600)
if m > 60:
m /= 60
measure = u"{0:.0f}h:{1:.0f}min".format(h, m)
return measure
|
<SYSTEM_TASK:>
Returns True is a function is a descendant of itself.
<END_TASK>
<USER_TASK:>
Description:
def is_recursive(self, child_item):
"""Returns True is a function is a descendant of itself."""
|
ancestor = child_item.parent()
# FIXME: indexes to data should be defined by a dictionary on init
while ancestor:
if (child_item.data(0, Qt.DisplayRole
) == ancestor.data(0, Qt.DisplayRole) and
child_item.data(7, Qt.DisplayRole
) == ancestor.data(7, Qt.DisplayRole)):
return True
else:
ancestor = ancestor.parent()
return False
|
<SYSTEM_TASK:>
Return all items with a level <= `maxlevel`
<END_TASK>
<USER_TASK:>
Description:
def get_items(self, maxlevel):
"""Return all items with a level <= `maxlevel`"""
|
itemlist = []
def add_to_itemlist(item, maxlevel, level=1):
level += 1
for index in range(item.childCount()):
citem = item.child(index)
itemlist.append(citem)
if level <= maxlevel:
add_to_itemlist(citem, maxlevel, level)
for tlitem in self.get_top_level_items():
itemlist.append(tlitem)
if maxlevel > 0:
add_to_itemlist(tlitem, maxlevel=maxlevel)
return itemlist
|
<SYSTEM_TASK:>
Change the view depth by expand or collapsing all same-level nodes
<END_TASK>
<USER_TASK:>
Description:
def change_view(self, change_in_depth):
"""Change the view depth by expand or collapsing all same-level nodes"""
|
self.current_view_depth += change_in_depth
if self.current_view_depth < 0:
self.current_view_depth = 0
self.collapseAll()
if self.current_view_depth > 0:
for item in self.get_items(maxlevel=self.current_view_depth-1):
item.setExpanded(True)
|
<SYSTEM_TASK:>
Returns a QSS stylesheet with Spyder color scheme settings.
<END_TASK>
<USER_TASK:>
Description:
def create_qss_style(color_scheme):
"""Returns a QSS stylesheet with Spyder color scheme settings.
The stylesheet can contain classes for:
Qt: QPlainTextEdit, QFrame, QWidget, etc
Pygments: .c, .k, .o, etc. (see PygmentsHighlighter)
IPython: .error, .in-prompt, .out-prompt, etc
"""
|
def give_font_weight(is_bold):
if is_bold:
return 'bold'
else:
return 'normal'
def give_font_style(is_italic):
if is_italic:
return 'italic'
else:
return 'normal'
color_scheme = get_color_scheme(color_scheme)
fon_c, fon_fw, fon_fs = color_scheme['normal']
font_color = fon_c
if dark_color(font_color):
in_prompt_color = 'navy'
out_prompt_color = 'darkred'
else:
in_prompt_color = 'lime'
out_prompt_color = 'red'
background_color = color_scheme['background']
error_color = 'red'
in_prompt_number_font_weight = 'bold'
out_prompt_number_font_weight = 'bold'
inverted_background_color = font_color
inverted_font_color = background_color
sheet = """QPlainTextEdit, QTextEdit, ControlWidget {{
color: {} ;
background-color: {};
}}
.error {{ color: {}; }}
.in-prompt {{ color: {}; }}
.in-prompt-number {{ color: {}; font-weight: {}; }}
.out-prompt {{ color: {}; }}
.out-prompt-number {{ color: {}; font-weight: {}; }}
.inverted {{ color: {}; background-color: {}; }}
"""
sheet_formatted = sheet.format(font_color, background_color,
error_color,
in_prompt_color, in_prompt_color,
in_prompt_number_font_weight,
out_prompt_color, out_prompt_color,
out_prompt_number_font_weight,
inverted_background_color,
inverted_font_color)
return (sheet_formatted, dark_color(font_color))
|
<SYSTEM_TASK:>
Create a dictionary that saves the given color scheme as a
<END_TASK>
<USER_TASK:>
Description:
def create_pygments_dict(color_scheme_name):
"""
Create a dictionary that saves the given color scheme as a
Pygments style.
"""
|
def give_font_weight(is_bold):
if is_bold:
return 'bold'
else:
return ''
def give_font_style(is_italic):
if is_italic:
return 'italic'
else:
return ''
color_scheme = get_color_scheme(color_scheme_name)
fon_c, fon_fw, fon_fs = color_scheme['normal']
font_color = fon_c
font_font_weight = give_font_weight(fon_fw)
font_font_style = give_font_style(fon_fs)
key_c, key_fw, key_fs = color_scheme['keyword']
keyword_color = key_c
keyword_font_weight = give_font_weight(key_fw)
keyword_font_style = give_font_style(key_fs)
bui_c, bui_fw, bui_fs = color_scheme['builtin']
builtin_color = bui_c
builtin_font_weight = give_font_weight(bui_fw)
builtin_font_style = give_font_style(bui_fs)
str_c, str_fw, str_fs = color_scheme['string']
string_color = str_c
string_font_weight = give_font_weight(str_fw)
string_font_style = give_font_style(str_fs)
num_c, num_fw, num_fs = color_scheme['number']
number_color = num_c
number_font_weight = give_font_weight(num_fw)
number_font_style = give_font_style(num_fs)
com_c, com_fw, com_fs = color_scheme['comment']
comment_color = com_c
comment_font_weight = give_font_weight(com_fw)
comment_font_style = give_font_style(com_fs)
def_c, def_fw, def_fs = color_scheme['definition']
definition_color = def_c
definition_font_weight = give_font_weight(def_fw)
definition_font_style = give_font_style(def_fs)
ins_c, ins_fw, ins_fs = color_scheme['instance']
instance_color = ins_c
instance_font_weight = give_font_weight(ins_fw)
instance_font_style = give_font_style(ins_fs)
font_token = font_font_style + ' ' + font_font_weight + ' ' + font_color
definition_token = (definition_font_style + ' ' + definition_font_weight +
' ' + definition_color)
builtin_token = (builtin_font_style + ' ' + builtin_font_weight + ' ' +
builtin_color)
instance_token = (instance_font_style + ' ' + instance_font_weight + ' ' +
instance_color)
keyword_token = (keyword_font_style + ' ' + keyword_font_weight + ' ' +
keyword_color)
comment_token = (comment_font_style + ' ' + comment_font_weight + ' ' +
comment_color)
string_token = (string_font_style + ' ' + string_font_weight + ' ' +
string_color)
number_token = (number_font_style + ' ' + number_font_weight + ' ' +
number_color)
syntax_style_dic = {Name: font_token.strip(),
Name.Class: definition_token.strip(),
Name.Function: definition_token.strip(),
Name.Builtin: builtin_token.strip(),
Name.Builtin.Pseudo: instance_token.strip(),
Keyword: keyword_token.strip(),
Keyword.Type: builtin_token.strip(),
Comment: comment_token.strip(),
String: string_token.strip(),
Number: number_token.strip(),
Punctuation: font_token.strip(),
Operator.Word: keyword_token.strip()}
return syntax_style_dic
|
<SYSTEM_TASK:>
Eventually remove .pyc and .pyo files associated to a Python script
<END_TASK>
<USER_TASK:>
Description:
def __remove_pyc_pyo(fname):
"""Eventually remove .pyc and .pyo files associated to a Python script"""
|
if osp.splitext(fname)[1] == '.py':
for ending in ('c', 'o'):
if osp.exists(fname+ending):
os.remove(fname+ending)
|
<SYSTEM_TASK:>
Return common path for all paths in pathlist
<END_TASK>
<USER_TASK:>
Description:
def get_common_path(pathlist):
"""Return common path for all paths in pathlist"""
|
common = osp.normpath(osp.commonprefix(pathlist))
if len(common) > 1:
if not osp.isdir(common):
return abspardir(common)
else:
for path in pathlist:
if not osp.isdir(osp.join(common, path[len(common)+1:])):
# `common` is not the real common prefix
return abspardir(common)
else:
return osp.abspath(common)
|
<SYSTEM_TASK:>
Return None if the pattern is a valid regular expression or
<END_TASK>
<USER_TASK:>
Description:
def regexp_error_msg(pattern):
"""
Return None if the pattern is a valid regular expression or
a string describing why the pattern is invalid.
"""
|
try:
re.compile(pattern)
except re.error as e:
return str(e)
return None
|
<SYSTEM_TASK:>
This generator generates the list of blocks directly under the fold
<END_TASK>
<USER_TASK:>
Description:
def blocks(self, ignore_blank_lines=True):
"""
This generator generates the list of blocks directly under the fold
region. This list does not contain blocks from child regions.
:param ignore_blank_lines: True to ignore last blank lines.
"""
|
start, end = self.get_range(ignore_blank_lines=ignore_blank_lines)
block = self._trigger.next()
while block.blockNumber() <= end and block.isValid():
yield block
block = block.next()
|
<SYSTEM_TASK:>
This generator generates the list of direct child regions.
<END_TASK>
<USER_TASK:>
Description:
def child_regions(self):
"""This generator generates the list of direct child regions."""
|
start, end = self.get_range()
block = self._trigger.next()
ref_lvl = self.scope_level
while block.blockNumber() <= end and block.isValid():
lvl = TextBlockHelper.get_fold_lvl(block)
trigger = TextBlockHelper.is_fold_trigger(block)
if lvl == ref_lvl and trigger:
yield FoldScope(block)
block = block.next()
|
<SYSTEM_TASK:>
Return the parent scope.
<END_TASK>
<USER_TASK:>
Description:
def parent(self):
"""
Return the parent scope.
:return: FoldScope or None
"""
|
if TextBlockHelper.get_fold_lvl(self._trigger) > 0 and \
self._trigger.blockNumber():
block = self._trigger.previous()
ref_lvl = self.trigger_level - 1
while (block.blockNumber() and
(not TextBlockHelper.is_fold_trigger(block) or
TextBlockHelper.get_fold_lvl(block) > ref_lvl)):
block = block.previous()
try:
return FoldScope(block)
except ValueError:
return None
return None
|
<SYSTEM_TASK:>
Get the scope text, with a possible maximum number of lines.
<END_TASK>
<USER_TASK:>
Description:
def text(self, max_lines=sys.maxsize):
"""
Get the scope text, with a possible maximum number of lines.
:param max_lines: limit the number of lines returned to a maximum.
:return: str
"""
|
ret_val = []
block = self._trigger.next()
_, end = self.get_range()
while (block.isValid() and block.blockNumber() <= end and
len(ret_val) < max_lines):
ret_val.append(block.text())
block = block.next()
return '\n'.join(ret_val)
|
<SYSTEM_TASK:>
Add a extension to the editor.
<END_TASK>
<USER_TASK:>
Description:
def add(self, extension):
"""
Add a extension to the editor.
:param extension: The extension instance to add.
"""
|
logger.debug('adding extension {}'.format(extension.name))
self._extensions[extension.name] = extension
extension.on_install(self.editor)
return extension
|
<SYSTEM_TASK:>
Remove a extension from the editor.
<END_TASK>
<USER_TASK:>
Description:
def remove(self, name_or_klass):
"""
Remove a extension from the editor.
:param name_or_klass: The name (or class) of the extension to remove.
:returns: The removed extension.
"""
|
logger.debug('removing extension {}'.format(name_or_klass))
extension = self.get(name_or_klass)
extension.on_uninstall()
self._extensions.pop(extension.name)
return extension
|
<SYSTEM_TASK:>
Remove all extensions from the editor.
<END_TASK>
<USER_TASK:>
Description:
def clear(self):
"""
Remove all extensions from the editor.
All extensions are removed fromlist and deleted.
"""
|
while len(self._extensions):
key = sorted(list(self._extensions.keys()))[0]
self.remove(key)
|
<SYSTEM_TASK:>
Append text to Python shell
<END_TASK>
<USER_TASK:>
Description:
def append_text_to_shell(self, text, error, prompt):
"""
Append text to Python shell
In a way, this method overrides the method 'insert_text' when text is
inserted at the end of the text widget for a Python shell
Handles error messages and show blue underlined links
Handles ANSI color sequences
Handles ANSI FF sequence
"""
|
cursor = self.textCursor()
cursor.movePosition(QTextCursor.End)
if '\r' in text: # replace \r\n with \n
text = text.replace('\r\n', '\n')
text = text.replace('\r', '\n')
while True:
index = text.find(chr(12))
if index == -1:
break
text = text[index+1:]
self.clear()
if error:
is_traceback = False
for text in text.splitlines(True):
if (text.startswith(' File')
and not text.startswith(' File "<')):
is_traceback = True
# Show error links in blue underlined text
cursor.insertText(' ', self.default_style.format)
cursor.insertText(text[2:],
self.traceback_link_style.format)
else:
# Show error/warning messages in red
cursor.insertText(text, self.error_style.format)
self.exception_occurred.emit(text, is_traceback)
elif prompt:
# Show prompt in green
insert_text_to(cursor, text, self.prompt_style.format)
else:
# Show other outputs in black
last_end = 0
for match in self.COLOR_PATTERN.finditer(text):
insert_text_to(cursor, text[last_end:match.start()],
self.default_style.format)
last_end = match.end()
try:
for code in [int(_c) for _c in match.group(1).split(';')]:
self.ansi_handler.set_code(code)
except ValueError:
pass
self.default_style.format = self.ansi_handler.get_format()
insert_text_to(cursor, text[last_end:], self.default_style.format)
# # Slower alternative:
# segments = self.COLOR_PATTERN.split(text)
# cursor.insertText(segments.pop(0), self.default_style.format)
# if segments:
# for ansi_tags, text in zip(segments[::2], segments[1::2]):
# for ansi_tag in ansi_tags.split(';'):
# self.ansi_handler.set_code(int(ansi_tag))
# self.default_style.format = self.ansi_handler.get_format()
# cursor.insertText(text, self.default_style.format)
self.set_cursor_position('eof')
self.setCurrentCharFormat(self.default_style.format)
|
<SYSTEM_TASK:>
Updates the enable status of delete and reset buttons.
<END_TASK>
<USER_TASK:>
Description:
def update_buttons(self):
"""Updates the enable status of delete and reset buttons."""
|
current_scheme = self.current_scheme
names = self.get_option("names")
try:
names.pop(names.index(u'Custom'))
except ValueError:
pass
delete_enabled = current_scheme not in names
self.delete_button.setEnabled(delete_enabled)
self.reset_button.setEnabled(not delete_enabled)
|
<SYSTEM_TASK:>
Update the color scheme of the preview editor and adds text.
<END_TASK>
<USER_TASK:>
Description:
def update_preview(self, index=None, scheme_name=None):
"""
Update the color scheme of the preview editor and adds text.
Note
----
'index' is needed, because this is triggered by a signal that sends
the selected index.
"""
|
text = ('"""A string"""\n\n'
'# A comment\n\n'
'# %% A cell\n\n'
'class Foo(object):\n'
' def __init__(self):\n'
' bar = 42\n'
' print(bar)\n'
)
show_blanks = CONF.get('editor', 'blank_spaces')
update_scrollbar = CONF.get('editor', 'scroll_past_end')
if scheme_name is None:
scheme_name = self.current_scheme
self.preview_editor.setup_editor(linenumbers=True,
markers=True,
tab_mode=False,
font=get_font(),
show_blanks=show_blanks,
color_scheme=scheme_name,
scroll_past_end=update_scrollbar)
self.preview_editor.set_text(text)
self.preview_editor.set_language('Python')
|
<SYSTEM_TASK:>
Creates a new color scheme with a custom name.
<END_TASK>
<USER_TASK:>
Description:
def create_new_scheme(self):
"""Creates a new color scheme with a custom name."""
|
names = self.get_option('names')
custom_names = self.get_option('custom_names', [])
# Get the available number this new color scheme
counter = len(custom_names) - 1
custom_index = [int(n.split('-')[-1]) for n in custom_names]
for i in range(len(custom_names)):
if custom_index[i] != i:
counter = i - 1
break
custom_name = "custom-{0}".format(counter+1)
# Add the config settings, based on the current one.
custom_names.append(custom_name)
self.set_option('custom_names', custom_names)
for key in syntaxhighlighters.COLOR_SCHEME_KEYS:
name = "{0}/{1}".format(custom_name, key)
default_name = "{0}/{1}".format(self.current_scheme, key)
option = self.get_option(default_name)
self.set_option(name, option)
self.set_option('{0}/name'.format(custom_name), custom_name)
# Now they need to be loaded! how to make a partial load_from_conf?
dlg = self.scheme_editor_dialog
dlg.add_color_scheme_stack(custom_name, custom=True)
dlg.set_scheme(custom_name)
self.load_from_conf()
if dlg.exec_():
# This is needed to have the custom name updated on the combobox
name = dlg.get_scheme_name()
self.set_option('{0}/name'.format(custom_name), name)
# The +1 is needed because of the separator in the combobox
index = (names + custom_names).index(custom_name) + 1
self.update_combobox()
self.schemes_combobox.setCurrentIndex(index)
else:
# Delete the config ....
custom_names.remove(custom_name)
self.set_option('custom_names', custom_names)
dlg.delete_color_scheme_stack(custom_name)
|
<SYSTEM_TASK:>
Deletes the currently selected custom color scheme.
<END_TASK>
<USER_TASK:>
Description:
def delete_scheme(self):
"""Deletes the currently selected custom color scheme."""
|
scheme_name = self.current_scheme
answer = QMessageBox.warning(self, _("Warning"),
_("Are you sure you want to delete "
"this scheme?"),
QMessageBox.Yes | QMessageBox.No)
if answer == QMessageBox.Yes:
# Put the combobox in Spyder by default, when deleting a scheme
names = self.get_option('names')
self.set_scheme('spyder')
self.schemes_combobox.setCurrentIndex(names.index('spyder'))
self.set_option('selected', 'spyder')
# Delete from custom_names
custom_names = self.get_option('custom_names', [])
if scheme_name in custom_names:
custom_names.remove(scheme_name)
self.set_option('custom_names', custom_names)
# Delete config options
for key in syntaxhighlighters.COLOR_SCHEME_KEYS:
option = "{0}/{1}".format(scheme_name, key)
CONF.remove_option(self.CONF_SECTION, option)
CONF.remove_option(self.CONF_SECTION,
"{0}/name".format(scheme_name))
self.update_combobox()
self.update_preview()
|
<SYSTEM_TASK:>
Set the current stack by 'scheme_name'.
<END_TASK>
<USER_TASK:>
Description:
def set_scheme(self, scheme_name):
"""Set the current stack by 'scheme_name'."""
|
self.stack.setCurrentIndex(self.order.index(scheme_name))
self.last_used_scheme = scheme_name
|
<SYSTEM_TASK:>
Get the values of the last edited color scheme to be used in an instant
<END_TASK>
<USER_TASK:>
Description:
def get_edited_color_scheme(self):
"""
Get the values of the last edited color scheme to be used in an instant
preview in the preview editor, without using `apply`.
"""
|
color_scheme = {}
scheme_name = self.last_used_scheme
for key in self.widgets[scheme_name]:
items = self.widgets[scheme_name][key]
if len(items) == 1:
# ColorLayout
value = items[0].text()
else:
# ColorLayout + checkboxes
value = (items[0].text(), items[1].isChecked(),
items[2].isChecked())
color_scheme[key] = value
return color_scheme
|
<SYSTEM_TASK:>
Add a stack for a given scheme and connects the CONF values.
<END_TASK>
<USER_TASK:>
Description:
def add_color_scheme_stack(self, scheme_name, custom=False):
"""Add a stack for a given scheme and connects the CONF values."""
|
color_scheme_groups = [
(_('Text'), ["normal", "comment", "string", "number", "keyword",
"builtin", "definition", "instance", ]),
(_('Highlight'), ["currentcell", "currentline", "occurrence",
"matched_p", "unmatched_p", "ctrlclick"]),
(_('Background'), ["background", "sideareas"])
]
parent = self.parent
line_edit = parent.create_lineedit(_("Scheme name:"),
'{0}/name'.format(scheme_name))
self.widgets[scheme_name] = {}
# Widget setup
line_edit.label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.setWindowTitle(_('Color scheme editor'))
# Layout
name_layout = QHBoxLayout()
name_layout.addWidget(line_edit.label)
name_layout.addWidget(line_edit.textbox)
self.scheme_name_textbox[scheme_name] = line_edit.textbox
if not custom:
line_edit.textbox.setDisabled(True)
if not self.isVisible():
line_edit.setVisible(False)
cs_layout = QVBoxLayout()
cs_layout.addLayout(name_layout)
h_layout = QHBoxLayout()
v_layout = QVBoxLayout()
for index, item in enumerate(color_scheme_groups):
group_name, keys = item
group_layout = QGridLayout()
for row, key in enumerate(keys):
option = "{0}/{1}".format(scheme_name, key)
value = self.parent.get_option(option)
name = syntaxhighlighters.COLOR_SCHEME_KEYS[key]
if is_text_string(value):
label, clayout = parent.create_coloredit(
name,
option,
without_layout=True,
)
label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
group_layout.addWidget(label, row+1, 0)
group_layout.addLayout(clayout, row+1, 1)
# Needed to update temp scheme to obtain instant preview
self.widgets[scheme_name][key] = [clayout]
else:
label, clayout, cb_bold, cb_italic = parent.create_scedit(
name,
option,
without_layout=True,
)
label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
group_layout.addWidget(label, row+1, 0)
group_layout.addLayout(clayout, row+1, 1)
group_layout.addWidget(cb_bold, row+1, 2)
group_layout.addWidget(cb_italic, row+1, 3)
# Needed to update temp scheme to obtain instant preview
self.widgets[scheme_name][key] = [clayout, cb_bold,
cb_italic]
group_box = QGroupBox(group_name)
group_box.setLayout(group_layout)
if index == 0:
h_layout.addWidget(group_box)
else:
v_layout.addWidget(group_box)
h_layout.addLayout(v_layout)
cs_layout.addLayout(h_layout)
stackitem = QWidget()
stackitem.setLayout(cs_layout)
self.stack.addWidget(stackitem)
self.order.append(scheme_name)
|
<SYSTEM_TASK:>
Remove stack widget by 'scheme_name'.
<END_TASK>
<USER_TASK:>
Description:
def delete_color_scheme_stack(self, scheme_name):
"""Remove stack widget by 'scheme_name'."""
|
self.set_scheme(scheme_name)
widget = self.stack.currentWidget()
self.stack.removeWidget(widget)
index = self.order.index(scheme_name)
self.order.pop(index)
|
<SYSTEM_TASK:>
Update actions of the Projects menu
<END_TASK>
<USER_TASK:>
Description:
def update_project_actions(self):
"""Update actions of the Projects menu"""
|
if self.recent_projects:
self.clear_recent_projects_action.setEnabled(True)
else:
self.clear_recent_projects_action.setEnabled(False)
active = bool(self.get_active_project_path())
self.close_project_action.setEnabled(active)
self.delete_project_action.setEnabled(active)
self.edit_project_preferences_action.setEnabled(active)
|
<SYSTEM_TASK:>
Edit Spyder active project preferences
<END_TASK>
<USER_TASK:>
Description:
def edit_project_preferences(self):
"""Edit Spyder active project preferences"""
|
from spyder.plugins.projects.confpage import ProjectPreferences
if self.project_active:
active_project = self.project_list[0]
dlg = ProjectPreferences(self, active_project)
# dlg.size_change.connect(self.set_project_prefs_size)
# if self.projects_prefs_dialog_size is not None:
# dlg.resize(self.projects_prefs_dialog_size)
dlg.show()
# dlg.check_all_settings()
# dlg.pages_widget.currentChanged.connect(self.__preference_page_changed)
dlg.exec_()
|
<SYSTEM_TASK:>
Open the project located in `path`
<END_TASK>
<USER_TASK:>
Description:
def open_project(self, path=None, restart_consoles=True,
save_previous_files=True):
"""Open the project located in `path`"""
|
self.switch_to_plugin()
if path is None:
basedir = get_home_dir()
path = getexistingdirectory(parent=self,
caption=_("Open project"),
basedir=basedir)
path = encoding.to_unicode_from_fs(path)
if not self.is_valid_project(path):
if path:
QMessageBox.critical(self, _('Error'),
_("<b>%s</b> is not a Spyder project!") % path)
return
else:
path = encoding.to_unicode_from_fs(path)
self.add_to_recent(path)
# A project was not open before
if self.current_active_project is None:
if save_previous_files and self.main.editor is not None:
self.main.editor.save_open_files()
if self.main.editor is not None:
self.main.editor.set_option('last_working_dir',
getcwd_or_home())
if self.get_option('visible_if_project_open'):
self.show_explorer()
else:
# We are switching projects
if self.main.editor is not None:
self.set_project_filenames(
self.main.editor.get_open_filenames())
self.current_active_project = EmptyProject(path)
self.latest_project = EmptyProject(path)
self.set_option('current_project_path', self.get_active_project_path())
self.setup_menu_actions()
self.sig_project_loaded.emit(path)
self.sig_pythonpath_changed.emit()
if restart_consoles:
self.restart_consoles()
|
<SYSTEM_TASK:>
Close current project and return to a window without an active
<END_TASK>
<USER_TASK:>
Description:
def close_project(self):
"""
Close current project and return to a window without an active
project
"""
|
if self.current_active_project:
self.switch_to_plugin()
if self.main.editor is not None:
self.set_project_filenames(
self.main.editor.get_open_filenames())
path = self.current_active_project.root_path
self.current_active_project = None
self.set_option('current_project_path', None)
self.setup_menu_actions()
self.sig_project_closed.emit(path)
self.sig_pythonpath_changed.emit()
if self.dockwidget is not None:
self.set_option('visible_if_project_open',
self.dockwidget.isVisible())
self.dockwidget.close()
self.explorer.clear()
self.restart_consoles()
|
<SYSTEM_TASK:>
Delete the current project without deleting the files in the directory.
<END_TASK>
<USER_TASK:>
Description:
def delete_project(self):
"""
Delete the current project without deleting the files in the directory.
"""
|
if self.current_active_project:
self.switch_to_plugin()
path = self.current_active_project.root_path
buttons = QMessageBox.Yes | QMessageBox.No
answer = QMessageBox.warning(
self,
_("Delete"),
_("Do you really want to delete <b>{filename}</b>?<br><br>"
"<b>Note:</b> This action will only delete the project. "
"Its files are going to be preserved on disk."
).format(filename=osp.basename(path)),
buttons)
if answer == QMessageBox.Yes:
try:
self.close_project()
shutil.rmtree(osp.join(path, '.spyproject'))
except EnvironmentError as error:
QMessageBox.critical(
self,
_("Project Explorer"),
_("<b>Unable to delete <i>{varpath}</i></b>"
"<br><br>The error message was:<br>{error}"
).format(varpath=path, error=to_text_string(error)))
|
<SYSTEM_TASK:>
Reopen the active project when Spyder was closed last time, if any
<END_TASK>
<USER_TASK:>
Description:
def reopen_last_project(self):
"""
Reopen the active project when Spyder was closed last time, if any
"""
|
current_project_path = self.get_option('current_project_path',
default=None)
# Needs a safer test of project existence!
if current_project_path and \
self.is_valid_project(current_project_path):
self.open_project(path=current_project_path,
restart_consoles=False,
save_previous_files=False)
self.load_config()
|
<SYSTEM_TASK:>
Get the list of recent filenames of a project
<END_TASK>
<USER_TASK:>
Description:
def get_project_filenames(self):
"""Get the list of recent filenames of a project"""
|
recent_files = []
if self.current_active_project:
recent_files = self.current_active_project.get_recent_files()
elif self.latest_project:
recent_files = self.latest_project.get_recent_files()
return recent_files
|
<SYSTEM_TASK:>
Set the list of open file names in a project
<END_TASK>
<USER_TASK:>
Description:
def set_project_filenames(self, recent_files):
"""Set the list of open file names in a project"""
|
if (self.current_active_project
and self.is_valid_project(
self.current_active_project.root_path)):
self.current_active_project.set_recent_files(recent_files)
|
<SYSTEM_TASK:>
Get path of the active project
<END_TASK>
<USER_TASK:>
Description:
def get_active_project_path(self):
"""Get path of the active project"""
|
active_project_path = None
if self.current_active_project:
active_project_path = self.current_active_project.root_path
return active_project_path
|
<SYSTEM_TASK:>
Get project path as a list to be added to PYTHONPATH
<END_TASK>
<USER_TASK:>
Description:
def get_pythonpath(self, at_start=False):
"""Get project path as a list to be added to PYTHONPATH"""
|
if at_start:
current_path = self.get_option('current_project_path',
default=None)
else:
current_path = self.get_active_project_path()
if current_path is None:
return []
else:
return [current_path]
|
<SYSTEM_TASK:>
Show the explorer
<END_TASK>
<USER_TASK:>
Description:
def show_explorer(self):
"""Show the explorer"""
|
if self.dockwidget is not None:
if self.dockwidget.isHidden():
self.dockwidget.show()
self.dockwidget.raise_()
self.dockwidget.update()
|
<SYSTEM_TASK:>
Check if a directory is a valid Spyder project
<END_TASK>
<USER_TASK:>
Description:
def is_valid_project(self, path):
"""Check if a directory is a valid Spyder project"""
|
spy_project_dir = osp.join(path, '.spyproject')
if osp.isdir(path) and osp.isdir(spy_project_dir):
return True
else:
return False
|
<SYSTEM_TASK:>
Add an entry to recent projetcs
<END_TASK>
<USER_TASK:>
Description:
def add_to_recent(self, project):
"""
Add an entry to recent projetcs
We only maintain the list of the 10 most recent projects
"""
|
if project not in self.recent_projects:
self.recent_projects.insert(0, project)
self.recent_projects = self.recent_projects[:10]
|
<SYSTEM_TASK:>
Return the first installed font family in family list
<END_TASK>
<USER_TASK:>
Description:
def get_family(families):
"""Return the first installed font family in family list"""
|
if not isinstance(families, list):
families = [ families ]
for family in families:
if font_is_installed(family):
return family
else:
print("Warning: None of the following fonts is installed: %r" % families) # spyder: test-skip
return QFont().family()
|
<SYSTEM_TASK:>
Get console font properties depending on OS and user options
<END_TASK>
<USER_TASK:>
Description:
def get_font(section='appearance', option='font', font_size_delta=0):
"""Get console font properties depending on OS and user options"""
|
font = FONT_CACHE.get((section, option))
if font is None:
families = CONF.get(section, option+"/family", None)
if families is None:
return QFont()
family = get_family(families)
weight = QFont.Normal
italic = CONF.get(section, option+'/italic', False)
if CONF.get(section, option+'/bold', False):
weight = QFont.Bold
size = CONF.get(section, option+'/size', 9) + font_size_delta
font = QFont(family, size, weight)
font.setItalic(italic)
FONT_CACHE[(section, option)] = font
size = CONF.get(section, option+'/size', 9) + font_size_delta
font.setPointSize(size)
return font
|
<SYSTEM_TASK:>
Create a Shortcut namedtuple for a widget
<END_TASK>
<USER_TASK:>
Description:
def config_shortcut(action, context, name, parent):
"""
Create a Shortcut namedtuple for a widget
The data contained in this tuple will be registered in
our shortcuts preferences page
"""
|
keystr = get_shortcut(context, name)
qsc = QShortcut(QKeySequence(keystr), parent, action)
qsc.setContext(Qt.WidgetWithChildrenShortcut)
sc = Shortcut(data=(qsc, context, name))
return sc
|
<SYSTEM_TASK:>
Iterate over keyboard shortcuts.
<END_TASK>
<USER_TASK:>
Description:
def iter_shortcuts():
"""Iterate over keyboard shortcuts."""
|
for context_name, keystr in CONF.items('shortcuts'):
context, name = context_name.split("/", 1)
yield context, name, keystr
|
<SYSTEM_TASK:>
Check if the font color used in the color scheme is dark.
<END_TASK>
<USER_TASK:>
Description:
def is_dark_font_color(color_scheme):
"""Check if the font color used in the color scheme is dark."""
|
color_scheme = get_color_scheme(color_scheme)
font_color, fon_fw, fon_fs = color_scheme['normal']
return dark_color(font_color)
|
<SYSTEM_TASK:>
Filter mouse press events.
<END_TASK>
<USER_TASK:>
Description:
def eventFilter(self, obj, event):
"""Filter mouse press events.
Events that are captured and not propagated return True. Events that
are not captured and are propagated return False.
"""
|
event_type = event.type()
if event_type == QEvent.MouseButtonPress:
self.tab_pressed(event)
return False
return False
|
<SYSTEM_TASK:>
Method called when a tab from a QTabBar has been pressed.
<END_TASK>
<USER_TASK:>
Description:
def tab_pressed(self, event):
"""Method called when a tab from a QTabBar has been pressed."""
|
self.from_index = self.dock_tabbar.tabAt(event.pos())
self.dock_tabbar.setCurrentIndex(self.from_index)
if event.button() == Qt.RightButton:
if self.from_index == -1:
self.show_nontab_menu(event)
else:
self.show_tab_menu(event)
|
<SYSTEM_TASK:>
Show the context menu assigned to nontabs section.
<END_TASK>
<USER_TASK:>
Description:
def show_nontab_menu(self, event):
"""Show the context menu assigned to nontabs section."""
|
menu = self.main.createPopupMenu()
menu.exec_(self.dock_tabbar.mapToGlobal(event.pos()))
|
<SYSTEM_TASK:>
Install an event filter to capture mouse events in the tabs of a
<END_TASK>
<USER_TASK:>
Description:
def install_tab_event_filter(self, value):
"""
Install an event filter to capture mouse events in the tabs of a
QTabBar holding tabified dockwidgets.
"""
|
dock_tabbar = None
tabbars = self.main.findChildren(QTabBar)
for tabbar in tabbars:
for tab in range(tabbar.count()):
title = tabbar.tabText(tab)
if title == self.title:
dock_tabbar = tabbar
break
if dock_tabbar is not None:
self.dock_tabbar = dock_tabbar
# Install filter only once per QTabBar
if getattr(self.dock_tabbar, 'filter', None) is None:
self.dock_tabbar.filter = TabFilter(self.dock_tabbar,
self.main)
self.dock_tabbar.installEventFilter(self.dock_tabbar.filter)
|
<SYSTEM_TASK:>
Request to start a LSP server to attend a language.
<END_TASK>
<USER_TASK:>
Description:
def report_open_file(self, options):
"""Request to start a LSP server to attend a language."""
|
filename = options['filename']
logger.debug('Call LSP for %s' % filename)
language = options['language']
callback = options['codeeditor']
stat = self.main.lspmanager.start_client(language.lower())
self.main.lspmanager.register_file(
language.lower(), filename, callback)
if stat:
if language.lower() in self.lsp_editor_settings:
self.lsp_server_ready(
language.lower(), self.lsp_editor_settings[
language.lower()])
else:
editor = self.get_current_editor()
editor.lsp_ready = False
|
<SYSTEM_TASK:>
Notify all stackeditors about LSP server availability.
<END_TASK>
<USER_TASK:>
Description:
def lsp_server_ready(self, language, configuration):
"""Notify all stackeditors about LSP server availability."""
|
for editorstack in self.editorstacks:
editorstack.notify_server_ready(language, configuration)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.