repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
spyder-ide/spyder | spyder/plugins/outlineexplorer/widgets.py | item_at_line | def item_at_line(root_item, line):
"""
Find and return the item of the outline explorer under which is located
the specified 'line' of the editor.
"""
previous_item = root_item
item = root_item
for item in get_item_children(root_item):
if item.line > line:
return previous_item
previous_item = item
else:
return item | python | def item_at_line(root_item, line):
"""
Find and return the item of the outline explorer under which is located
the specified 'line' of the editor.
"""
previous_item = root_item
item = root_item
for item in get_item_children(root_item):
if item.line > line:
return previous_item
previous_item = item
else:
return item | [
"def",
"item_at_line",
"(",
"root_item",
",",
"line",
")",
":",
"previous_item",
"=",
"root_item",
"item",
"=",
"root_item",
"for",
"item",
"in",
"get_item_children",
"(",
"root_item",
")",
":",
"if",
"item",
".",
"line",
">",
"line",
":",
"return",
"previous_item",
"previous_item",
"=",
"item",
"else",
":",
"return",
"item"
] | Find and return the item of the outline explorer under which is located
the specified 'line' of the editor. | [
"Find",
"and",
"return",
"the",
"item",
"of",
"the",
"outline",
"explorer",
"under",
"which",
"is",
"located",
"the",
"specified",
"line",
"of",
"the",
"editor",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/outlineexplorer/widgets.py#L131-L143 | train |
spyder-ide/spyder | spyder/plugins/outlineexplorer/widgets.py | OutlineExplorerTreeWidget.get_actions_from_items | def get_actions_from_items(self, items):
"""Reimplemented OneColumnTree method"""
fromcursor_act = create_action(self, text=_('Go to cursor position'),
icon=ima.icon('fromcursor'),
triggered=self.go_to_cursor_position)
fullpath_act = create_action(self, text=_('Show absolute path'),
toggled=self.toggle_fullpath_mode)
fullpath_act.setChecked(self.show_fullpath)
allfiles_act = create_action(self, text=_('Show all files'),
toggled=self.toggle_show_all_files)
allfiles_act.setChecked(self.show_all_files)
comment_act = create_action(self, text=_('Show special comments'),
toggled=self.toggle_show_comments)
comment_act.setChecked(self.show_comments)
group_cells_act = create_action(self, text=_('Group code cells'),
toggled=self.toggle_group_cells)
group_cells_act.setChecked(self.group_cells)
sort_files_alphabetically_act = create_action(
self, text=_('Sort files alphabetically'),
toggled=self.toggle_sort_files_alphabetically)
sort_files_alphabetically_act.setChecked(
self.sort_files_alphabetically)
actions = [fullpath_act, allfiles_act, group_cells_act, comment_act,
sort_files_alphabetically_act, fromcursor_act]
return actions | python | def get_actions_from_items(self, items):
"""Reimplemented OneColumnTree method"""
fromcursor_act = create_action(self, text=_('Go to cursor position'),
icon=ima.icon('fromcursor'),
triggered=self.go_to_cursor_position)
fullpath_act = create_action(self, text=_('Show absolute path'),
toggled=self.toggle_fullpath_mode)
fullpath_act.setChecked(self.show_fullpath)
allfiles_act = create_action(self, text=_('Show all files'),
toggled=self.toggle_show_all_files)
allfiles_act.setChecked(self.show_all_files)
comment_act = create_action(self, text=_('Show special comments'),
toggled=self.toggle_show_comments)
comment_act.setChecked(self.show_comments)
group_cells_act = create_action(self, text=_('Group code cells'),
toggled=self.toggle_group_cells)
group_cells_act.setChecked(self.group_cells)
sort_files_alphabetically_act = create_action(
self, text=_('Sort files alphabetically'),
toggled=self.toggle_sort_files_alphabetically)
sort_files_alphabetically_act.setChecked(
self.sort_files_alphabetically)
actions = [fullpath_act, allfiles_act, group_cells_act, comment_act,
sort_files_alphabetically_act, fromcursor_act]
return actions | [
"def",
"get_actions_from_items",
"(",
"self",
",",
"items",
")",
":",
"fromcursor_act",
"=",
"create_action",
"(",
"self",
",",
"text",
"=",
"_",
"(",
"'Go to cursor position'",
")",
",",
"icon",
"=",
"ima",
".",
"icon",
"(",
"'fromcursor'",
")",
",",
"triggered",
"=",
"self",
".",
"go_to_cursor_position",
")",
"fullpath_act",
"=",
"create_action",
"(",
"self",
",",
"text",
"=",
"_",
"(",
"'Show absolute path'",
")",
",",
"toggled",
"=",
"self",
".",
"toggle_fullpath_mode",
")",
"fullpath_act",
".",
"setChecked",
"(",
"self",
".",
"show_fullpath",
")",
"allfiles_act",
"=",
"create_action",
"(",
"self",
",",
"text",
"=",
"_",
"(",
"'Show all files'",
")",
",",
"toggled",
"=",
"self",
".",
"toggle_show_all_files",
")",
"allfiles_act",
".",
"setChecked",
"(",
"self",
".",
"show_all_files",
")",
"comment_act",
"=",
"create_action",
"(",
"self",
",",
"text",
"=",
"_",
"(",
"'Show special comments'",
")",
",",
"toggled",
"=",
"self",
".",
"toggle_show_comments",
")",
"comment_act",
".",
"setChecked",
"(",
"self",
".",
"show_comments",
")",
"group_cells_act",
"=",
"create_action",
"(",
"self",
",",
"text",
"=",
"_",
"(",
"'Group code cells'",
")",
",",
"toggled",
"=",
"self",
".",
"toggle_group_cells",
")",
"group_cells_act",
".",
"setChecked",
"(",
"self",
".",
"group_cells",
")",
"sort_files_alphabetically_act",
"=",
"create_action",
"(",
"self",
",",
"text",
"=",
"_",
"(",
"'Sort files alphabetically'",
")",
",",
"toggled",
"=",
"self",
".",
"toggle_sort_files_alphabetically",
")",
"sort_files_alphabetically_act",
".",
"setChecked",
"(",
"self",
".",
"sort_files_alphabetically",
")",
"actions",
"=",
"[",
"fullpath_act",
",",
"allfiles_act",
",",
"group_cells_act",
",",
"comment_act",
",",
"sort_files_alphabetically_act",
",",
"fromcursor_act",
"]",
"return",
"actions"
] | Reimplemented OneColumnTree method | [
"Reimplemented",
"OneColumnTree",
"method"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/outlineexplorer/widgets.py#L183-L207 | train |
spyder-ide/spyder | spyder/plugins/outlineexplorer/widgets.py | OutlineExplorerTreeWidget.__hide_or_show_root_items | def __hide_or_show_root_items(self, item):
"""
show_all_files option is disabled: hide all root items except *item*
show_all_files option is enabled: do nothing
"""
for _it in self.get_top_level_items():
_it.setHidden(_it is not item and not self.show_all_files) | python | def __hide_or_show_root_items(self, item):
"""
show_all_files option is disabled: hide all root items except *item*
show_all_files option is enabled: do nothing
"""
for _it in self.get_top_level_items():
_it.setHidden(_it is not item and not self.show_all_files) | [
"def",
"__hide_or_show_root_items",
"(",
"self",
",",
"item",
")",
":",
"for",
"_it",
"in",
"self",
".",
"get_top_level_items",
"(",
")",
":",
"_it",
".",
"setHidden",
"(",
"_it",
"is",
"not",
"item",
"and",
"not",
"self",
".",
"show_all_files",
")"
] | show_all_files option is disabled: hide all root items except *item*
show_all_files option is enabled: do nothing | [
"show_all_files",
"option",
"is",
"disabled",
":",
"hide",
"all",
"root",
"items",
"except",
"*",
"item",
"*",
"show_all_files",
"option",
"is",
"enabled",
":",
"do",
"nothing"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/outlineexplorer/widgets.py#L216-L222 | train |
spyder-ide/spyder | spyder/plugins/outlineexplorer/widgets.py | OutlineExplorerTreeWidget.set_current_editor | def set_current_editor(self, editor, update):
"""Bind editor instance"""
editor_id = editor.get_id()
if editor_id in list(self.editor_ids.values()):
item = self.editor_items[editor_id]
if not self.freeze:
self.scrollToItem(item)
self.root_item_selected(item)
self.__hide_or_show_root_items(item)
if update:
self.save_expanded_state()
tree_cache = self.editor_tree_cache[editor_id]
self.populate_branch(editor, item, tree_cache)
self.restore_expanded_state()
else:
root_item = FileRootItem(editor.fname, self, editor.is_python())
root_item.set_text(fullpath=self.show_fullpath)
tree_cache = self.populate_branch(editor, root_item)
self.__hide_or_show_root_items(root_item)
self.root_item_selected(root_item)
self.editor_items[editor_id] = root_item
self.editor_tree_cache[editor_id] = tree_cache
self.resizeColumnToContents(0)
if editor not in self.editor_ids:
self.editor_ids[editor] = editor_id
self.ordered_editor_ids.append(editor_id)
self.__sort_toplevel_items()
self.current_editor = editor | python | def set_current_editor(self, editor, update):
"""Bind editor instance"""
editor_id = editor.get_id()
if editor_id in list(self.editor_ids.values()):
item = self.editor_items[editor_id]
if not self.freeze:
self.scrollToItem(item)
self.root_item_selected(item)
self.__hide_or_show_root_items(item)
if update:
self.save_expanded_state()
tree_cache = self.editor_tree_cache[editor_id]
self.populate_branch(editor, item, tree_cache)
self.restore_expanded_state()
else:
root_item = FileRootItem(editor.fname, self, editor.is_python())
root_item.set_text(fullpath=self.show_fullpath)
tree_cache = self.populate_branch(editor, root_item)
self.__hide_or_show_root_items(root_item)
self.root_item_selected(root_item)
self.editor_items[editor_id] = root_item
self.editor_tree_cache[editor_id] = tree_cache
self.resizeColumnToContents(0)
if editor not in self.editor_ids:
self.editor_ids[editor] = editor_id
self.ordered_editor_ids.append(editor_id)
self.__sort_toplevel_items()
self.current_editor = editor | [
"def",
"set_current_editor",
"(",
"self",
",",
"editor",
",",
"update",
")",
":",
"editor_id",
"=",
"editor",
".",
"get_id",
"(",
")",
"if",
"editor_id",
"in",
"list",
"(",
"self",
".",
"editor_ids",
".",
"values",
"(",
")",
")",
":",
"item",
"=",
"self",
".",
"editor_items",
"[",
"editor_id",
"]",
"if",
"not",
"self",
".",
"freeze",
":",
"self",
".",
"scrollToItem",
"(",
"item",
")",
"self",
".",
"root_item_selected",
"(",
"item",
")",
"self",
".",
"__hide_or_show_root_items",
"(",
"item",
")",
"if",
"update",
":",
"self",
".",
"save_expanded_state",
"(",
")",
"tree_cache",
"=",
"self",
".",
"editor_tree_cache",
"[",
"editor_id",
"]",
"self",
".",
"populate_branch",
"(",
"editor",
",",
"item",
",",
"tree_cache",
")",
"self",
".",
"restore_expanded_state",
"(",
")",
"else",
":",
"root_item",
"=",
"FileRootItem",
"(",
"editor",
".",
"fname",
",",
"self",
",",
"editor",
".",
"is_python",
"(",
")",
")",
"root_item",
".",
"set_text",
"(",
"fullpath",
"=",
"self",
".",
"show_fullpath",
")",
"tree_cache",
"=",
"self",
".",
"populate_branch",
"(",
"editor",
",",
"root_item",
")",
"self",
".",
"__hide_or_show_root_items",
"(",
"root_item",
")",
"self",
".",
"root_item_selected",
"(",
"root_item",
")",
"self",
".",
"editor_items",
"[",
"editor_id",
"]",
"=",
"root_item",
"self",
".",
"editor_tree_cache",
"[",
"editor_id",
"]",
"=",
"tree_cache",
"self",
".",
"resizeColumnToContents",
"(",
"0",
")",
"if",
"editor",
"not",
"in",
"self",
".",
"editor_ids",
":",
"self",
".",
"editor_ids",
"[",
"editor",
"]",
"=",
"editor_id",
"self",
".",
"ordered_editor_ids",
".",
"append",
"(",
"editor_id",
")",
"self",
".",
"__sort_toplevel_items",
"(",
")",
"self",
".",
"current_editor",
"=",
"editor"
] | Bind editor instance | [
"Bind",
"editor",
"instance"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/outlineexplorer/widgets.py#L267-L294 | train |
spyder-ide/spyder | spyder/plugins/outlineexplorer/widgets.py | OutlineExplorerTreeWidget.file_renamed | def file_renamed(self, editor, new_filename):
"""File was renamed, updating outline explorer tree"""
if editor is None:
# This is needed when we can't find an editor to attach
# the outline explorer to.
# Fix issue 8813
return
editor_id = editor.get_id()
if editor_id in list(self.editor_ids.values()):
root_item = self.editor_items[editor_id]
root_item.set_path(new_filename, fullpath=self.show_fullpath)
self.__sort_toplevel_items() | python | def file_renamed(self, editor, new_filename):
"""File was renamed, updating outline explorer tree"""
if editor is None:
# This is needed when we can't find an editor to attach
# the outline explorer to.
# Fix issue 8813
return
editor_id = editor.get_id()
if editor_id in list(self.editor_ids.values()):
root_item = self.editor_items[editor_id]
root_item.set_path(new_filename, fullpath=self.show_fullpath)
self.__sort_toplevel_items() | [
"def",
"file_renamed",
"(",
"self",
",",
"editor",
",",
"new_filename",
")",
":",
"if",
"editor",
"is",
"None",
":",
"# This is needed when we can't find an editor to attach\r",
"# the outline explorer to.\r",
"# Fix issue 8813\r",
"return",
"editor_id",
"=",
"editor",
".",
"get_id",
"(",
")",
"if",
"editor_id",
"in",
"list",
"(",
"self",
".",
"editor_ids",
".",
"values",
"(",
")",
")",
":",
"root_item",
"=",
"self",
".",
"editor_items",
"[",
"editor_id",
"]",
"root_item",
".",
"set_path",
"(",
"new_filename",
",",
"fullpath",
"=",
"self",
".",
"show_fullpath",
")",
"self",
".",
"__sort_toplevel_items",
"(",
")"
] | File was renamed, updating outline explorer tree | [
"File",
"was",
"renamed",
"updating",
"outline",
"explorer",
"tree"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/outlineexplorer/widgets.py#L296-L307 | train |
spyder-ide/spyder | spyder/plugins/outlineexplorer/widgets.py | OutlineExplorerTreeWidget.set_editor_ids_order | def set_editor_ids_order(self, ordered_editor_ids):
"""
Order the root file items in the Outline Explorer following the
provided list of editor ids.
"""
if self.ordered_editor_ids != ordered_editor_ids:
self.ordered_editor_ids = ordered_editor_ids
if self.sort_files_alphabetically is False:
self.__sort_toplevel_items() | python | def set_editor_ids_order(self, ordered_editor_ids):
"""
Order the root file items in the Outline Explorer following the
provided list of editor ids.
"""
if self.ordered_editor_ids != ordered_editor_ids:
self.ordered_editor_ids = ordered_editor_ids
if self.sort_files_alphabetically is False:
self.__sort_toplevel_items() | [
"def",
"set_editor_ids_order",
"(",
"self",
",",
"ordered_editor_ids",
")",
":",
"if",
"self",
".",
"ordered_editor_ids",
"!=",
"ordered_editor_ids",
":",
"self",
".",
"ordered_editor_ids",
"=",
"ordered_editor_ids",
"if",
"self",
".",
"sort_files_alphabetically",
"is",
"False",
":",
"self",
".",
"__sort_toplevel_items",
"(",
")"
] | Order the root file items in the Outline Explorer following the
provided list of editor ids. | [
"Order",
"the",
"root",
"file",
"items",
"in",
"the",
"Outline",
"Explorer",
"following",
"the",
"provided",
"list",
"of",
"editor",
"ids",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/outlineexplorer/widgets.py#L333-L341 | train |
spyder-ide/spyder | spyder/plugins/outlineexplorer/widgets.py | OutlineExplorerTreeWidget.__sort_toplevel_items | def __sort_toplevel_items(self):
"""
Sort the root file items in alphabetical order if
'sort_files_alphabetically' is True, else order the items as
specified in the 'self.ordered_editor_ids' list.
"""
if self.show_all_files is False:
return
current_ordered_items = [self.topLevelItem(index) for index in
range(self.topLevelItemCount())]
if self.sort_files_alphabetically:
new_ordered_items = sorted(
current_ordered_items,
key=lambda item: osp.basename(item.path.lower()))
else:
new_ordered_items = [
self.editor_items.get(e_id) for e_id in
self.ordered_editor_ids if
self.editor_items.get(e_id) is not None]
if current_ordered_items != new_ordered_items:
selected_items = self.selectedItems()
self.save_expanded_state()
for index in range(self.topLevelItemCount()):
self.takeTopLevelItem(0)
for index, item in enumerate(new_ordered_items):
self.insertTopLevelItem(index, item)
self.restore_expanded_state()
self.clearSelection()
if selected_items:
selected_items[-1].setSelected(True) | python | def __sort_toplevel_items(self):
"""
Sort the root file items in alphabetical order if
'sort_files_alphabetically' is True, else order the items as
specified in the 'self.ordered_editor_ids' list.
"""
if self.show_all_files is False:
return
current_ordered_items = [self.topLevelItem(index) for index in
range(self.topLevelItemCount())]
if self.sort_files_alphabetically:
new_ordered_items = sorted(
current_ordered_items,
key=lambda item: osp.basename(item.path.lower()))
else:
new_ordered_items = [
self.editor_items.get(e_id) for e_id in
self.ordered_editor_ids if
self.editor_items.get(e_id) is not None]
if current_ordered_items != new_ordered_items:
selected_items = self.selectedItems()
self.save_expanded_state()
for index in range(self.topLevelItemCount()):
self.takeTopLevelItem(0)
for index, item in enumerate(new_ordered_items):
self.insertTopLevelItem(index, item)
self.restore_expanded_state()
self.clearSelection()
if selected_items:
selected_items[-1].setSelected(True) | [
"def",
"__sort_toplevel_items",
"(",
"self",
")",
":",
"if",
"self",
".",
"show_all_files",
"is",
"False",
":",
"return",
"current_ordered_items",
"=",
"[",
"self",
".",
"topLevelItem",
"(",
"index",
")",
"for",
"index",
"in",
"range",
"(",
"self",
".",
"topLevelItemCount",
"(",
")",
")",
"]",
"if",
"self",
".",
"sort_files_alphabetically",
":",
"new_ordered_items",
"=",
"sorted",
"(",
"current_ordered_items",
",",
"key",
"=",
"lambda",
"item",
":",
"osp",
".",
"basename",
"(",
"item",
".",
"path",
".",
"lower",
"(",
")",
")",
")",
"else",
":",
"new_ordered_items",
"=",
"[",
"self",
".",
"editor_items",
".",
"get",
"(",
"e_id",
")",
"for",
"e_id",
"in",
"self",
".",
"ordered_editor_ids",
"if",
"self",
".",
"editor_items",
".",
"get",
"(",
"e_id",
")",
"is",
"not",
"None",
"]",
"if",
"current_ordered_items",
"!=",
"new_ordered_items",
":",
"selected_items",
"=",
"self",
".",
"selectedItems",
"(",
")",
"self",
".",
"save_expanded_state",
"(",
")",
"for",
"index",
"in",
"range",
"(",
"self",
".",
"topLevelItemCount",
"(",
")",
")",
":",
"self",
".",
"takeTopLevelItem",
"(",
"0",
")",
"for",
"index",
",",
"item",
"in",
"enumerate",
"(",
"new_ordered_items",
")",
":",
"self",
".",
"insertTopLevelItem",
"(",
"index",
",",
"item",
")",
"self",
".",
"restore_expanded_state",
"(",
")",
"self",
".",
"clearSelection",
"(",
")",
"if",
"selected_items",
":",
"selected_items",
"[",
"-",
"1",
"]",
".",
"setSelected",
"(",
"True",
")"
] | Sort the root file items in alphabetical order if
'sort_files_alphabetically' is True, else order the items as
specified in the 'self.ordered_editor_ids' list. | [
"Sort",
"the",
"root",
"file",
"items",
"in",
"alphabetical",
"order",
"if",
"sort_files_alphabetically",
"is",
"True",
"else",
"order",
"the",
"items",
"as",
"specified",
"in",
"the",
"self",
".",
"ordered_editor_ids",
"list",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/outlineexplorer/widgets.py#L343-L374 | train |
spyder-ide/spyder | spyder/plugins/outlineexplorer/widgets.py | OutlineExplorerTreeWidget.populate_branch | def populate_branch(self, editor, root_item, tree_cache=None):
"""
Generates an outline of the editor's content and stores the result
in a cache.
"""
if tree_cache is None:
tree_cache = {}
# Removing cached items for which line is > total line nb
for _l in list(tree_cache.keys()):
if _l >= editor.get_line_count():
# Checking if key is still in tree cache in case one of its
# ancestors was deleted in the meantime (deleting all children):
if _l in tree_cache:
remove_from_tree_cache(tree_cache, line=_l)
ancestors = [(root_item, 0)]
cell_ancestors = [(root_item, 0)]
previous_item = None
previous_level = None
prev_cell_level = None
prev_cell_item = None
oe_data = editor.get_outlineexplorer_data()
for block_nb in range(editor.get_line_count()):
line_nb = block_nb+1
data = oe_data.get(block_nb)
level = None if data is None else data.fold_level
citem, clevel, _d = tree_cache.get(line_nb, (None, None, ""))
# Skip iteration if line is not the first line of a foldable block
if level is None:
if citem is not None:
remove_from_tree_cache(tree_cache, line=line_nb)
continue
# Searching for class/function statements
not_class_nor_function = data.is_not_class_nor_function()
if not not_class_nor_function:
class_name = data.get_class_name()
if class_name is None:
func_name = data.get_function_name()
if func_name is None:
if citem is not None:
remove_from_tree_cache(tree_cache, line=line_nb)
continue
# Skip iteration for if/else/try/for/etc foldable blocks.
if not_class_nor_function and not data.is_comment():
if citem is not None:
remove_from_tree_cache(tree_cache, line=line_nb)
continue
if citem is not None:
cname = to_text_string(citem.text(0))
cparent = citem.parent
# Blocks for Cell Groups.
if (data is not None and data.def_type == data.CELL and
self.group_cells):
preceding = (root_item if previous_item is None
else previous_item)
cell_level = data.cell_level
if prev_cell_level is not None:
if cell_level == prev_cell_level:
pass
elif cell_level > prev_cell_level:
cell_ancestors.append((prev_cell_item,
prev_cell_level))
else:
while (len(cell_ancestors) > 1 and
cell_level <= prev_cell_level):
cell_ancestors.pop(-1)
_item, prev_cell_level = cell_ancestors[-1]
parent, _level = cell_ancestors[-1]
if citem is not None:
if data.text == cname and level == clevel:
previous_level = clevel
previous_item = citem
continue
else:
remove_from_tree_cache(tree_cache, line=line_nb)
item = CellItem(data.def_name, line_nb, parent, preceding)
item.setup()
debug = "%s -- %s/%s" % (str(item.line).rjust(6),
to_text_string(item.parent().text(0)),
to_text_string(item.text(0)))
tree_cache[line_nb] = (item, level, debug)
ancestors = [(item, 0)]
prev_cell_level = cell_level
prev_cell_item = item
previous_item = item
continue
# Blocks for Code Groups.
if previous_level is not None:
if level == previous_level:
pass
elif level > previous_level:
ancestors.append((previous_item, previous_level))
else:
while len(ancestors) > 1 and level <= previous_level:
ancestors.pop(-1)
_item, previous_level = ancestors[-1]
parent, _level = ancestors[-1]
preceding = root_item if previous_item is None else previous_item
if not_class_nor_function and data.is_comment():
if not self.show_comments:
if citem is not None:
remove_from_tree_cache(tree_cache, line=line_nb)
continue
if citem is not None:
if data.text == cname and level == clevel:
previous_level = clevel
previous_item = citem
continue
else:
remove_from_tree_cache(tree_cache, line=line_nb)
if data.def_type == data.CELL:
item = CellItem(data.def_name, line_nb, parent, preceding)
else:
item = CommentItem(data.text, line_nb, parent, preceding)
elif class_name is not None:
if citem is not None:
if (class_name == cname and level == clevel and
parent is cparent):
previous_level = clevel
previous_item = citem
continue
else:
remove_from_tree_cache(tree_cache, line=line_nb)
item = ClassItem(class_name, line_nb, parent, preceding)
else:
if citem is not None:
if (func_name == cname and level == clevel and
parent is cparent):
previous_level = clevel
previous_item = citem
continue
else:
remove_from_tree_cache(tree_cache, line=line_nb)
item = FunctionItem(func_name, line_nb, parent, preceding)
item.setup()
debug = "%s -- %s/%s" % (str(item.line).rjust(6),
to_text_string(item.parent().text(0)),
to_text_string(item.text(0)))
tree_cache[line_nb] = (item, level, debug)
previous_level = level
previous_item = item
return tree_cache | python | def populate_branch(self, editor, root_item, tree_cache=None):
"""
Generates an outline of the editor's content and stores the result
in a cache.
"""
if tree_cache is None:
tree_cache = {}
# Removing cached items for which line is > total line nb
for _l in list(tree_cache.keys()):
if _l >= editor.get_line_count():
# Checking if key is still in tree cache in case one of its
# ancestors was deleted in the meantime (deleting all children):
if _l in tree_cache:
remove_from_tree_cache(tree_cache, line=_l)
ancestors = [(root_item, 0)]
cell_ancestors = [(root_item, 0)]
previous_item = None
previous_level = None
prev_cell_level = None
prev_cell_item = None
oe_data = editor.get_outlineexplorer_data()
for block_nb in range(editor.get_line_count()):
line_nb = block_nb+1
data = oe_data.get(block_nb)
level = None if data is None else data.fold_level
citem, clevel, _d = tree_cache.get(line_nb, (None, None, ""))
# Skip iteration if line is not the first line of a foldable block
if level is None:
if citem is not None:
remove_from_tree_cache(tree_cache, line=line_nb)
continue
# Searching for class/function statements
not_class_nor_function = data.is_not_class_nor_function()
if not not_class_nor_function:
class_name = data.get_class_name()
if class_name is None:
func_name = data.get_function_name()
if func_name is None:
if citem is not None:
remove_from_tree_cache(tree_cache, line=line_nb)
continue
# Skip iteration for if/else/try/for/etc foldable blocks.
if not_class_nor_function and not data.is_comment():
if citem is not None:
remove_from_tree_cache(tree_cache, line=line_nb)
continue
if citem is not None:
cname = to_text_string(citem.text(0))
cparent = citem.parent
# Blocks for Cell Groups.
if (data is not None and data.def_type == data.CELL and
self.group_cells):
preceding = (root_item if previous_item is None
else previous_item)
cell_level = data.cell_level
if prev_cell_level is not None:
if cell_level == prev_cell_level:
pass
elif cell_level > prev_cell_level:
cell_ancestors.append((prev_cell_item,
prev_cell_level))
else:
while (len(cell_ancestors) > 1 and
cell_level <= prev_cell_level):
cell_ancestors.pop(-1)
_item, prev_cell_level = cell_ancestors[-1]
parent, _level = cell_ancestors[-1]
if citem is not None:
if data.text == cname and level == clevel:
previous_level = clevel
previous_item = citem
continue
else:
remove_from_tree_cache(tree_cache, line=line_nb)
item = CellItem(data.def_name, line_nb, parent, preceding)
item.setup()
debug = "%s -- %s/%s" % (str(item.line).rjust(6),
to_text_string(item.parent().text(0)),
to_text_string(item.text(0)))
tree_cache[line_nb] = (item, level, debug)
ancestors = [(item, 0)]
prev_cell_level = cell_level
prev_cell_item = item
previous_item = item
continue
# Blocks for Code Groups.
if previous_level is not None:
if level == previous_level:
pass
elif level > previous_level:
ancestors.append((previous_item, previous_level))
else:
while len(ancestors) > 1 and level <= previous_level:
ancestors.pop(-1)
_item, previous_level = ancestors[-1]
parent, _level = ancestors[-1]
preceding = root_item if previous_item is None else previous_item
if not_class_nor_function and data.is_comment():
if not self.show_comments:
if citem is not None:
remove_from_tree_cache(tree_cache, line=line_nb)
continue
if citem is not None:
if data.text == cname and level == clevel:
previous_level = clevel
previous_item = citem
continue
else:
remove_from_tree_cache(tree_cache, line=line_nb)
if data.def_type == data.CELL:
item = CellItem(data.def_name, line_nb, parent, preceding)
else:
item = CommentItem(data.text, line_nb, parent, preceding)
elif class_name is not None:
if citem is not None:
if (class_name == cname and level == clevel and
parent is cparent):
previous_level = clevel
previous_item = citem
continue
else:
remove_from_tree_cache(tree_cache, line=line_nb)
item = ClassItem(class_name, line_nb, parent, preceding)
else:
if citem is not None:
if (func_name == cname and level == clevel and
parent is cparent):
previous_level = clevel
previous_item = citem
continue
else:
remove_from_tree_cache(tree_cache, line=line_nb)
item = FunctionItem(func_name, line_nb, parent, preceding)
item.setup()
debug = "%s -- %s/%s" % (str(item.line).rjust(6),
to_text_string(item.parent().text(0)),
to_text_string(item.text(0)))
tree_cache[line_nb] = (item, level, debug)
previous_level = level
previous_item = item
return tree_cache | [
"def",
"populate_branch",
"(",
"self",
",",
"editor",
",",
"root_item",
",",
"tree_cache",
"=",
"None",
")",
":",
"if",
"tree_cache",
"is",
"None",
":",
"tree_cache",
"=",
"{",
"}",
"# Removing cached items for which line is > total line nb\r",
"for",
"_l",
"in",
"list",
"(",
"tree_cache",
".",
"keys",
"(",
")",
")",
":",
"if",
"_l",
">=",
"editor",
".",
"get_line_count",
"(",
")",
":",
"# Checking if key is still in tree cache in case one of its \r",
"# ancestors was deleted in the meantime (deleting all children):\r",
"if",
"_l",
"in",
"tree_cache",
":",
"remove_from_tree_cache",
"(",
"tree_cache",
",",
"line",
"=",
"_l",
")",
"ancestors",
"=",
"[",
"(",
"root_item",
",",
"0",
")",
"]",
"cell_ancestors",
"=",
"[",
"(",
"root_item",
",",
"0",
")",
"]",
"previous_item",
"=",
"None",
"previous_level",
"=",
"None",
"prev_cell_level",
"=",
"None",
"prev_cell_item",
"=",
"None",
"oe_data",
"=",
"editor",
".",
"get_outlineexplorer_data",
"(",
")",
"for",
"block_nb",
"in",
"range",
"(",
"editor",
".",
"get_line_count",
"(",
")",
")",
":",
"line_nb",
"=",
"block_nb",
"+",
"1",
"data",
"=",
"oe_data",
".",
"get",
"(",
"block_nb",
")",
"level",
"=",
"None",
"if",
"data",
"is",
"None",
"else",
"data",
".",
"fold_level",
"citem",
",",
"clevel",
",",
"_d",
"=",
"tree_cache",
".",
"get",
"(",
"line_nb",
",",
"(",
"None",
",",
"None",
",",
"\"\"",
")",
")",
"# Skip iteration if line is not the first line of a foldable block\r",
"if",
"level",
"is",
"None",
":",
"if",
"citem",
"is",
"not",
"None",
":",
"remove_from_tree_cache",
"(",
"tree_cache",
",",
"line",
"=",
"line_nb",
")",
"continue",
"# Searching for class/function statements\r",
"not_class_nor_function",
"=",
"data",
".",
"is_not_class_nor_function",
"(",
")",
"if",
"not",
"not_class_nor_function",
":",
"class_name",
"=",
"data",
".",
"get_class_name",
"(",
")",
"if",
"class_name",
"is",
"None",
":",
"func_name",
"=",
"data",
".",
"get_function_name",
"(",
")",
"if",
"func_name",
"is",
"None",
":",
"if",
"citem",
"is",
"not",
"None",
":",
"remove_from_tree_cache",
"(",
"tree_cache",
",",
"line",
"=",
"line_nb",
")",
"continue",
"# Skip iteration for if/else/try/for/etc foldable blocks.\r",
"if",
"not_class_nor_function",
"and",
"not",
"data",
".",
"is_comment",
"(",
")",
":",
"if",
"citem",
"is",
"not",
"None",
":",
"remove_from_tree_cache",
"(",
"tree_cache",
",",
"line",
"=",
"line_nb",
")",
"continue",
"if",
"citem",
"is",
"not",
"None",
":",
"cname",
"=",
"to_text_string",
"(",
"citem",
".",
"text",
"(",
"0",
")",
")",
"cparent",
"=",
"citem",
".",
"parent",
"# Blocks for Cell Groups.\r",
"if",
"(",
"data",
"is",
"not",
"None",
"and",
"data",
".",
"def_type",
"==",
"data",
".",
"CELL",
"and",
"self",
".",
"group_cells",
")",
":",
"preceding",
"=",
"(",
"root_item",
"if",
"previous_item",
"is",
"None",
"else",
"previous_item",
")",
"cell_level",
"=",
"data",
".",
"cell_level",
"if",
"prev_cell_level",
"is",
"not",
"None",
":",
"if",
"cell_level",
"==",
"prev_cell_level",
":",
"pass",
"elif",
"cell_level",
">",
"prev_cell_level",
":",
"cell_ancestors",
".",
"append",
"(",
"(",
"prev_cell_item",
",",
"prev_cell_level",
")",
")",
"else",
":",
"while",
"(",
"len",
"(",
"cell_ancestors",
")",
">",
"1",
"and",
"cell_level",
"<=",
"prev_cell_level",
")",
":",
"cell_ancestors",
".",
"pop",
"(",
"-",
"1",
")",
"_item",
",",
"prev_cell_level",
"=",
"cell_ancestors",
"[",
"-",
"1",
"]",
"parent",
",",
"_level",
"=",
"cell_ancestors",
"[",
"-",
"1",
"]",
"if",
"citem",
"is",
"not",
"None",
":",
"if",
"data",
".",
"text",
"==",
"cname",
"and",
"level",
"==",
"clevel",
":",
"previous_level",
"=",
"clevel",
"previous_item",
"=",
"citem",
"continue",
"else",
":",
"remove_from_tree_cache",
"(",
"tree_cache",
",",
"line",
"=",
"line_nb",
")",
"item",
"=",
"CellItem",
"(",
"data",
".",
"def_name",
",",
"line_nb",
",",
"parent",
",",
"preceding",
")",
"item",
".",
"setup",
"(",
")",
"debug",
"=",
"\"%s -- %s/%s\"",
"%",
"(",
"str",
"(",
"item",
".",
"line",
")",
".",
"rjust",
"(",
"6",
")",
",",
"to_text_string",
"(",
"item",
".",
"parent",
"(",
")",
".",
"text",
"(",
"0",
")",
")",
",",
"to_text_string",
"(",
"item",
".",
"text",
"(",
"0",
")",
")",
")",
"tree_cache",
"[",
"line_nb",
"]",
"=",
"(",
"item",
",",
"level",
",",
"debug",
")",
"ancestors",
"=",
"[",
"(",
"item",
",",
"0",
")",
"]",
"prev_cell_level",
"=",
"cell_level",
"prev_cell_item",
"=",
"item",
"previous_item",
"=",
"item",
"continue",
"# Blocks for Code Groups.\r",
"if",
"previous_level",
"is",
"not",
"None",
":",
"if",
"level",
"==",
"previous_level",
":",
"pass",
"elif",
"level",
">",
"previous_level",
":",
"ancestors",
".",
"append",
"(",
"(",
"previous_item",
",",
"previous_level",
")",
")",
"else",
":",
"while",
"len",
"(",
"ancestors",
")",
">",
"1",
"and",
"level",
"<=",
"previous_level",
":",
"ancestors",
".",
"pop",
"(",
"-",
"1",
")",
"_item",
",",
"previous_level",
"=",
"ancestors",
"[",
"-",
"1",
"]",
"parent",
",",
"_level",
"=",
"ancestors",
"[",
"-",
"1",
"]",
"preceding",
"=",
"root_item",
"if",
"previous_item",
"is",
"None",
"else",
"previous_item",
"if",
"not_class_nor_function",
"and",
"data",
".",
"is_comment",
"(",
")",
":",
"if",
"not",
"self",
".",
"show_comments",
":",
"if",
"citem",
"is",
"not",
"None",
":",
"remove_from_tree_cache",
"(",
"tree_cache",
",",
"line",
"=",
"line_nb",
")",
"continue",
"if",
"citem",
"is",
"not",
"None",
":",
"if",
"data",
".",
"text",
"==",
"cname",
"and",
"level",
"==",
"clevel",
":",
"previous_level",
"=",
"clevel",
"previous_item",
"=",
"citem",
"continue",
"else",
":",
"remove_from_tree_cache",
"(",
"tree_cache",
",",
"line",
"=",
"line_nb",
")",
"if",
"data",
".",
"def_type",
"==",
"data",
".",
"CELL",
":",
"item",
"=",
"CellItem",
"(",
"data",
".",
"def_name",
",",
"line_nb",
",",
"parent",
",",
"preceding",
")",
"else",
":",
"item",
"=",
"CommentItem",
"(",
"data",
".",
"text",
",",
"line_nb",
",",
"parent",
",",
"preceding",
")",
"elif",
"class_name",
"is",
"not",
"None",
":",
"if",
"citem",
"is",
"not",
"None",
":",
"if",
"(",
"class_name",
"==",
"cname",
"and",
"level",
"==",
"clevel",
"and",
"parent",
"is",
"cparent",
")",
":",
"previous_level",
"=",
"clevel",
"previous_item",
"=",
"citem",
"continue",
"else",
":",
"remove_from_tree_cache",
"(",
"tree_cache",
",",
"line",
"=",
"line_nb",
")",
"item",
"=",
"ClassItem",
"(",
"class_name",
",",
"line_nb",
",",
"parent",
",",
"preceding",
")",
"else",
":",
"if",
"citem",
"is",
"not",
"None",
":",
"if",
"(",
"func_name",
"==",
"cname",
"and",
"level",
"==",
"clevel",
"and",
"parent",
"is",
"cparent",
")",
":",
"previous_level",
"=",
"clevel",
"previous_item",
"=",
"citem",
"continue",
"else",
":",
"remove_from_tree_cache",
"(",
"tree_cache",
",",
"line",
"=",
"line_nb",
")",
"item",
"=",
"FunctionItem",
"(",
"func_name",
",",
"line_nb",
",",
"parent",
",",
"preceding",
")",
"item",
".",
"setup",
"(",
")",
"debug",
"=",
"\"%s -- %s/%s\"",
"%",
"(",
"str",
"(",
"item",
".",
"line",
")",
".",
"rjust",
"(",
"6",
")",
",",
"to_text_string",
"(",
"item",
".",
"parent",
"(",
")",
".",
"text",
"(",
"0",
")",
")",
",",
"to_text_string",
"(",
"item",
".",
"text",
"(",
"0",
")",
")",
")",
"tree_cache",
"[",
"line_nb",
"]",
"=",
"(",
"item",
",",
"level",
",",
"debug",
")",
"previous_level",
"=",
"level",
"previous_item",
"=",
"item",
"return",
"tree_cache"
] | Generates an outline of the editor's content and stores the result
in a cache. | [
"Generates",
"an",
"outline",
"of",
"the",
"editor",
"s",
"content",
"and",
"stores",
"the",
"result",
"in",
"a",
"cache",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/outlineexplorer/widgets.py#L376-L528 | train |
spyder-ide/spyder | spyder/plugins/outlineexplorer/widgets.py | OutlineExplorerTreeWidget.root_item_selected | def root_item_selected(self, item):
"""Root item has been selected: expanding it and collapsing others"""
if self.show_all_files:
return
for root_item in self.get_top_level_items():
if root_item is item:
self.expandItem(root_item)
else:
self.collapseItem(root_item) | python | def root_item_selected(self, item):
"""Root item has been selected: expanding it and collapsing others"""
if self.show_all_files:
return
for root_item in self.get_top_level_items():
if root_item is item:
self.expandItem(root_item)
else:
self.collapseItem(root_item) | [
"def",
"root_item_selected",
"(",
"self",
",",
"item",
")",
":",
"if",
"self",
".",
"show_all_files",
":",
"return",
"for",
"root_item",
"in",
"self",
".",
"get_top_level_items",
"(",
")",
":",
"if",
"root_item",
"is",
"item",
":",
"self",
".",
"expandItem",
"(",
"root_item",
")",
"else",
":",
"self",
".",
"collapseItem",
"(",
"root_item",
")"
] | Root item has been selected: expanding it and collapsing others | [
"Root",
"item",
"has",
"been",
"selected",
":",
"expanding",
"it",
"and",
"collapsing",
"others"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/outlineexplorer/widgets.py#L530-L538 | train |
spyder-ide/spyder | spyder/plugins/outlineexplorer/widgets.py | OutlineExplorerTreeWidget.restore | def restore(self):
"""Reimplemented OneColumnTree method"""
if self.current_editor is not None:
self.collapseAll()
editor_id = self.editor_ids[self.current_editor]
self.root_item_selected(self.editor_items[editor_id]) | python | def restore(self):
"""Reimplemented OneColumnTree method"""
if self.current_editor is not None:
self.collapseAll()
editor_id = self.editor_ids[self.current_editor]
self.root_item_selected(self.editor_items[editor_id]) | [
"def",
"restore",
"(",
"self",
")",
":",
"if",
"self",
".",
"current_editor",
"is",
"not",
"None",
":",
"self",
".",
"collapseAll",
"(",
")",
"editor_id",
"=",
"self",
".",
"editor_ids",
"[",
"self",
".",
"current_editor",
"]",
"self",
".",
"root_item_selected",
"(",
"self",
".",
"editor_items",
"[",
"editor_id",
"]",
")"
] | Reimplemented OneColumnTree method | [
"Reimplemented",
"OneColumnTree",
"method"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/outlineexplorer/widgets.py#L540-L545 | train |
spyder-ide/spyder | spyder/plugins/outlineexplorer/widgets.py | OutlineExplorerTreeWidget.get_root_item | def get_root_item(self, item):
"""Return the root item of the specified item."""
root_item = item
while isinstance(root_item.parent(), QTreeWidgetItem):
root_item = root_item.parent()
return root_item | python | def get_root_item(self, item):
"""Return the root item of the specified item."""
root_item = item
while isinstance(root_item.parent(), QTreeWidgetItem):
root_item = root_item.parent()
return root_item | [
"def",
"get_root_item",
"(",
"self",
",",
"item",
")",
":",
"root_item",
"=",
"item",
"while",
"isinstance",
"(",
"root_item",
".",
"parent",
"(",
")",
",",
"QTreeWidgetItem",
")",
":",
"root_item",
"=",
"root_item",
".",
"parent",
"(",
")",
"return",
"root_item"
] | Return the root item of the specified item. | [
"Return",
"the",
"root",
"item",
"of",
"the",
"specified",
"item",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/outlineexplorer/widgets.py#L547-L552 | train |
spyder-ide/spyder | spyder/plugins/outlineexplorer/widgets.py | OutlineExplorerTreeWidget.get_visible_items | def get_visible_items(self):
"""Return a list of all visible items in the treewidget."""
items = []
iterator = QTreeWidgetItemIterator(self)
while iterator.value():
item = iterator.value()
if not item.isHidden():
if item.parent():
if item.parent().isExpanded():
items.append(item)
else:
items.append(item)
iterator += 1
return items | python | def get_visible_items(self):
"""Return a list of all visible items in the treewidget."""
items = []
iterator = QTreeWidgetItemIterator(self)
while iterator.value():
item = iterator.value()
if not item.isHidden():
if item.parent():
if item.parent().isExpanded():
items.append(item)
else:
items.append(item)
iterator += 1
return items | [
"def",
"get_visible_items",
"(",
"self",
")",
":",
"items",
"=",
"[",
"]",
"iterator",
"=",
"QTreeWidgetItemIterator",
"(",
"self",
")",
"while",
"iterator",
".",
"value",
"(",
")",
":",
"item",
"=",
"iterator",
".",
"value",
"(",
")",
"if",
"not",
"item",
".",
"isHidden",
"(",
")",
":",
"if",
"item",
".",
"parent",
"(",
")",
":",
"if",
"item",
".",
"parent",
"(",
")",
".",
"isExpanded",
"(",
")",
":",
"items",
".",
"append",
"(",
"item",
")",
"else",
":",
"items",
".",
"append",
"(",
"item",
")",
"iterator",
"+=",
"1",
"return",
"items"
] | Return a list of all visible items in the treewidget. | [
"Return",
"a",
"list",
"of",
"all",
"visible",
"items",
"in",
"the",
"treewidget",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/outlineexplorer/widgets.py#L554-L567 | train |
spyder-ide/spyder | spyder/plugins/outlineexplorer/widgets.py | OutlineExplorerTreeWidget.activated | def activated(self, item):
"""Double-click event"""
editor_item = self.editor_items.get(
self.editor_ids.get(self.current_editor))
line = 0
if item == editor_item:
line = 1
elif isinstance(item, TreeItem):
line = item.line
self.freeze = True
root_item = self.get_root_item(item)
if line:
self.parent().edit_goto.emit(root_item.path, line, item.text(0))
else:
self.parent().edit.emit(root_item.path)
self.freeze = False
parent = self.current_editor.parent()
for editor_id, i_item in list(self.editor_items.items()):
if i_item is root_item:
for editor, _id in list(self.editor_ids.items()):
if _id == editor_id and editor.parent() is parent:
self.current_editor = editor
break
break | python | def activated(self, item):
"""Double-click event"""
editor_item = self.editor_items.get(
self.editor_ids.get(self.current_editor))
line = 0
if item == editor_item:
line = 1
elif isinstance(item, TreeItem):
line = item.line
self.freeze = True
root_item = self.get_root_item(item)
if line:
self.parent().edit_goto.emit(root_item.path, line, item.text(0))
else:
self.parent().edit.emit(root_item.path)
self.freeze = False
parent = self.current_editor.parent()
for editor_id, i_item in list(self.editor_items.items()):
if i_item is root_item:
for editor, _id in list(self.editor_ids.items()):
if _id == editor_id and editor.parent() is parent:
self.current_editor = editor
break
break | [
"def",
"activated",
"(",
"self",
",",
"item",
")",
":",
"editor_item",
"=",
"self",
".",
"editor_items",
".",
"get",
"(",
"self",
".",
"editor_ids",
".",
"get",
"(",
"self",
".",
"current_editor",
")",
")",
"line",
"=",
"0",
"if",
"item",
"==",
"editor_item",
":",
"line",
"=",
"1",
"elif",
"isinstance",
"(",
"item",
",",
"TreeItem",
")",
":",
"line",
"=",
"item",
".",
"line",
"self",
".",
"freeze",
"=",
"True",
"root_item",
"=",
"self",
".",
"get_root_item",
"(",
"item",
")",
"if",
"line",
":",
"self",
".",
"parent",
"(",
")",
".",
"edit_goto",
".",
"emit",
"(",
"root_item",
".",
"path",
",",
"line",
",",
"item",
".",
"text",
"(",
"0",
")",
")",
"else",
":",
"self",
".",
"parent",
"(",
")",
".",
"edit",
".",
"emit",
"(",
"root_item",
".",
"path",
")",
"self",
".",
"freeze",
"=",
"False",
"parent",
"=",
"self",
".",
"current_editor",
".",
"parent",
"(",
")",
"for",
"editor_id",
",",
"i_item",
"in",
"list",
"(",
"self",
".",
"editor_items",
".",
"items",
"(",
")",
")",
":",
"if",
"i_item",
"is",
"root_item",
":",
"for",
"editor",
",",
"_id",
"in",
"list",
"(",
"self",
".",
"editor_ids",
".",
"items",
"(",
")",
")",
":",
"if",
"_id",
"==",
"editor_id",
"and",
"editor",
".",
"parent",
"(",
")",
"is",
"parent",
":",
"self",
".",
"current_editor",
"=",
"editor",
"break",
"break"
] | Double-click event | [
"Double",
"-",
"click",
"event"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/outlineexplorer/widgets.py#L569-L594 | train |
spyder-ide/spyder | spyder/plugins/outlineexplorer/widgets.py | OutlineExplorerTreeWidget.clicked | def clicked(self, item):
"""Click event"""
if isinstance(item, FileRootItem):
self.root_item_selected(item)
self.activated(item) | python | def clicked(self, item):
"""Click event"""
if isinstance(item, FileRootItem):
self.root_item_selected(item)
self.activated(item) | [
"def",
"clicked",
"(",
"self",
",",
"item",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"FileRootItem",
")",
":",
"self",
".",
"root_item_selected",
"(",
"item",
")",
"self",
".",
"activated",
"(",
"item",
")"
] | Click event | [
"Click",
"event"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/outlineexplorer/widgets.py#L596-L600 | train |
spyder-ide/spyder | spyder/plugins/outlineexplorer/widgets.py | OutlineExplorerWidget.setup_buttons | def setup_buttons(self):
"""Setup the buttons of the outline explorer widget toolbar."""
self.fromcursor_btn = create_toolbutton(
self, icon=ima.icon('fromcursor'), tip=_('Go to cursor position'),
triggered=self.treewidget.go_to_cursor_position)
buttons = [self.fromcursor_btn]
for action in [self.treewidget.collapse_all_action,
self.treewidget.expand_all_action,
self.treewidget.restore_action,
self.treewidget.collapse_selection_action,
self.treewidget.expand_selection_action]:
buttons.append(create_toolbutton(self))
buttons[-1].setDefaultAction(action)
return buttons | python | def setup_buttons(self):
"""Setup the buttons of the outline explorer widget toolbar."""
self.fromcursor_btn = create_toolbutton(
self, icon=ima.icon('fromcursor'), tip=_('Go to cursor position'),
triggered=self.treewidget.go_to_cursor_position)
buttons = [self.fromcursor_btn]
for action in [self.treewidget.collapse_all_action,
self.treewidget.expand_all_action,
self.treewidget.restore_action,
self.treewidget.collapse_selection_action,
self.treewidget.expand_selection_action]:
buttons.append(create_toolbutton(self))
buttons[-1].setDefaultAction(action)
return buttons | [
"def",
"setup_buttons",
"(",
"self",
")",
":",
"self",
".",
"fromcursor_btn",
"=",
"create_toolbutton",
"(",
"self",
",",
"icon",
"=",
"ima",
".",
"icon",
"(",
"'fromcursor'",
")",
",",
"tip",
"=",
"_",
"(",
"'Go to cursor position'",
")",
",",
"triggered",
"=",
"self",
".",
"treewidget",
".",
"go_to_cursor_position",
")",
"buttons",
"=",
"[",
"self",
".",
"fromcursor_btn",
"]",
"for",
"action",
"in",
"[",
"self",
".",
"treewidget",
".",
"collapse_all_action",
",",
"self",
".",
"treewidget",
".",
"expand_all_action",
",",
"self",
".",
"treewidget",
".",
"restore_action",
",",
"self",
".",
"treewidget",
".",
"collapse_selection_action",
",",
"self",
".",
"treewidget",
".",
"expand_selection_action",
"]",
":",
"buttons",
".",
"append",
"(",
"create_toolbutton",
"(",
"self",
")",
")",
"buttons",
"[",
"-",
"1",
"]",
".",
"setDefaultAction",
"(",
"action",
")",
"return",
"buttons"
] | Setup the buttons of the outline explorer widget toolbar. | [
"Setup",
"the",
"buttons",
"of",
"the",
"outline",
"explorer",
"widget",
"toolbar",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/outlineexplorer/widgets.py#L650-L664 | train |
spyder-ide/spyder | spyder/plugins/outlineexplorer/widgets.py | OutlineExplorerWidget.get_options | def get_options(self):
"""
Return outline explorer options
"""
return dict(
show_fullpath=self.treewidget.show_fullpath,
show_all_files=self.treewidget.show_all_files,
group_cells=self.treewidget.group_cells,
show_comments=self.treewidget.show_comments,
sort_files_alphabetically=(
self.treewidget.sort_files_alphabetically),
expanded_state=self.treewidget.get_expanded_state(),
scrollbar_position=self.treewidget.get_scrollbar_position(),
visibility=self.isVisible()
) | python | def get_options(self):
"""
Return outline explorer options
"""
return dict(
show_fullpath=self.treewidget.show_fullpath,
show_all_files=self.treewidget.show_all_files,
group_cells=self.treewidget.group_cells,
show_comments=self.treewidget.show_comments,
sort_files_alphabetically=(
self.treewidget.sort_files_alphabetically),
expanded_state=self.treewidget.get_expanded_state(),
scrollbar_position=self.treewidget.get_scrollbar_position(),
visibility=self.isVisible()
) | [
"def",
"get_options",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"show_fullpath",
"=",
"self",
".",
"treewidget",
".",
"show_fullpath",
",",
"show_all_files",
"=",
"self",
".",
"treewidget",
".",
"show_all_files",
",",
"group_cells",
"=",
"self",
".",
"treewidget",
".",
"group_cells",
",",
"show_comments",
"=",
"self",
".",
"treewidget",
".",
"show_comments",
",",
"sort_files_alphabetically",
"=",
"(",
"self",
".",
"treewidget",
".",
"sort_files_alphabetically",
")",
",",
"expanded_state",
"=",
"self",
".",
"treewidget",
".",
"get_expanded_state",
"(",
")",
",",
"scrollbar_position",
"=",
"self",
".",
"treewidget",
".",
"get_scrollbar_position",
"(",
")",
",",
"visibility",
"=",
"self",
".",
"isVisible",
"(",
")",
")"
] | Return outline explorer options | [
"Return",
"outline",
"explorer",
"options"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/outlineexplorer/widgets.py#L675-L689 | train |
spyder-ide/spyder | spyder/api/editorextension.py | EditorExtension.on_uninstall | def on_uninstall(self):
"""Uninstalls the editor extension from the editor."""
self._on_close = True
self.enabled = False
self._editor = None | python | def on_uninstall(self):
"""Uninstalls the editor extension from the editor."""
self._on_close = True
self.enabled = False
self._editor = None | [
"def",
"on_uninstall",
"(",
"self",
")",
":",
"self",
".",
"_on_close",
"=",
"True",
"self",
".",
"enabled",
"=",
"False",
"self",
".",
"_editor",
"=",
"None"
] | Uninstalls the editor extension from the editor. | [
"Uninstalls",
"the",
"editor",
"extension",
"from",
"the",
"editor",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/api/editorextension.py#L112-L116 | train |
spyder-ide/spyder | spyder/__init__.py | add_to_distribution | def add_to_distribution(dist):
"""Add package to py2exe/cx_Freeze distribution object
Extension to guidata.disthelpers"""
try:
dist.add_qt_bindings()
except AttributeError:
raise ImportError("This script requires guidata 1.5+")
for _modname in ('spyder', 'spyderplugins'):
dist.add_module_data_files(_modname, ("", ),
('.png', '.svg', '.html', '.png', '.txt',
'.js', '.inv', '.ico', '.css', '.doctree',
'.qm', '.py',),
copy_to_root=False) | python | def add_to_distribution(dist):
"""Add package to py2exe/cx_Freeze distribution object
Extension to guidata.disthelpers"""
try:
dist.add_qt_bindings()
except AttributeError:
raise ImportError("This script requires guidata 1.5+")
for _modname in ('spyder', 'spyderplugins'):
dist.add_module_data_files(_modname, ("", ),
('.png', '.svg', '.html', '.png', '.txt',
'.js', '.inv', '.ico', '.css', '.doctree',
'.qm', '.py',),
copy_to_root=False) | [
"def",
"add_to_distribution",
"(",
"dist",
")",
":",
"try",
":",
"dist",
".",
"add_qt_bindings",
"(",
")",
"except",
"AttributeError",
":",
"raise",
"ImportError",
"(",
"\"This script requires guidata 1.5+\"",
")",
"for",
"_modname",
"in",
"(",
"'spyder'",
",",
"'spyderplugins'",
")",
":",
"dist",
".",
"add_module_data_files",
"(",
"_modname",
",",
"(",
"\"\"",
",",
")",
",",
"(",
"'.png'",
",",
"'.svg'",
",",
"'.html'",
",",
"'.png'",
",",
"'.txt'",
",",
"'.js'",
",",
"'.inv'",
",",
"'.ico'",
",",
"'.css'",
",",
"'.doctree'",
",",
"'.qm'",
",",
"'.py'",
",",
")",
",",
"copy_to_root",
"=",
"False",
")"
] | Add package to py2exe/cx_Freeze distribution object
Extension to guidata.disthelpers | [
"Add",
"package",
"to",
"py2exe",
"/",
"cx_Freeze",
"distribution",
"object",
"Extension",
"to",
"guidata",
".",
"disthelpers"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/__init__.py#L52-L64 | train |
spyder-ide/spyder | spyder/__init__.py | get_versions | def get_versions(reporev=True):
"""Get version information for components used by Spyder"""
import sys
import platform
import qtpy
import qtpy.QtCore
revision = None
if reporev:
from spyder.utils import vcs
revision, branch = vcs.get_git_revision(os.path.dirname(__dir__))
if not sys.platform == 'darwin': # To avoid a crash with our Mac app
system = platform.system()
else:
system = 'Darwin'
return {
'spyder': __version__,
'python': platform.python_version(), # "2.7.3"
'bitness': 64 if sys.maxsize > 2**32 else 32,
'qt': qtpy.QtCore.__version__,
'qt_api': qtpy.API_NAME, # PyQt5
'qt_api_ver': qtpy.PYQT_VERSION,
'system': system, # Linux, Windows, ...
'release': platform.release(), # XP, 10.6, 2.2.0, etc.
'revision': revision, # '9fdf926eccce'
} | python | def get_versions(reporev=True):
"""Get version information for components used by Spyder"""
import sys
import platform
import qtpy
import qtpy.QtCore
revision = None
if reporev:
from spyder.utils import vcs
revision, branch = vcs.get_git_revision(os.path.dirname(__dir__))
if not sys.platform == 'darwin': # To avoid a crash with our Mac app
system = platform.system()
else:
system = 'Darwin'
return {
'spyder': __version__,
'python': platform.python_version(), # "2.7.3"
'bitness': 64 if sys.maxsize > 2**32 else 32,
'qt': qtpy.QtCore.__version__,
'qt_api': qtpy.API_NAME, # PyQt5
'qt_api_ver': qtpy.PYQT_VERSION,
'system': system, # Linux, Windows, ...
'release': platform.release(), # XP, 10.6, 2.2.0, etc.
'revision': revision, # '9fdf926eccce'
} | [
"def",
"get_versions",
"(",
"reporev",
"=",
"True",
")",
":",
"import",
"sys",
"import",
"platform",
"import",
"qtpy",
"import",
"qtpy",
".",
"QtCore",
"revision",
"=",
"None",
"if",
"reporev",
":",
"from",
"spyder",
".",
"utils",
"import",
"vcs",
"revision",
",",
"branch",
"=",
"vcs",
".",
"get_git_revision",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__dir__",
")",
")",
"if",
"not",
"sys",
".",
"platform",
"==",
"'darwin'",
":",
"# To avoid a crash with our Mac app",
"system",
"=",
"platform",
".",
"system",
"(",
")",
"else",
":",
"system",
"=",
"'Darwin'",
"return",
"{",
"'spyder'",
":",
"__version__",
",",
"'python'",
":",
"platform",
".",
"python_version",
"(",
")",
",",
"# \"2.7.3\"",
"'bitness'",
":",
"64",
"if",
"sys",
".",
"maxsize",
">",
"2",
"**",
"32",
"else",
"32",
",",
"'qt'",
":",
"qtpy",
".",
"QtCore",
".",
"__version__",
",",
"'qt_api'",
":",
"qtpy",
".",
"API_NAME",
",",
"# PyQt5",
"'qt_api_ver'",
":",
"qtpy",
".",
"PYQT_VERSION",
",",
"'system'",
":",
"system",
",",
"# Linux, Windows, ...",
"'release'",
":",
"platform",
".",
"release",
"(",
")",
",",
"# XP, 10.6, 2.2.0, etc.",
"'revision'",
":",
"revision",
",",
"# '9fdf926eccce'",
"}"
] | Get version information for components used by Spyder | [
"Get",
"version",
"information",
"for",
"components",
"used",
"by",
"Spyder"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/__init__.py#L67-L95 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/arrayeditor.py | is_number | def is_number(dtype):
"""Return True is datatype dtype is a number kind"""
return is_float(dtype) or ('int' in dtype.name) or ('long' in dtype.name) \
or ('short' in dtype.name) | python | def is_number(dtype):
"""Return True is datatype dtype is a number kind"""
return is_float(dtype) or ('int' in dtype.name) or ('long' in dtype.name) \
or ('short' in dtype.name) | [
"def",
"is_number",
"(",
"dtype",
")",
":",
"return",
"is_float",
"(",
"dtype",
")",
"or",
"(",
"'int'",
"in",
"dtype",
".",
"name",
")",
"or",
"(",
"'long'",
"in",
"dtype",
".",
"name",
")",
"or",
"(",
"'short'",
"in",
"dtype",
".",
"name",
")"
] | Return True is datatype dtype is a number kind | [
"Return",
"True",
"is",
"datatype",
"dtype",
"is",
"a",
"number",
"kind"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L101-L104 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/arrayeditor.py | get_idx_rect | def get_idx_rect(index_list):
"""Extract the boundaries from a list of indexes"""
rows, cols = list(zip(*[(i.row(), i.column()) for i in index_list]))
return ( min(rows), max(rows), min(cols), max(cols) ) | python | def get_idx_rect(index_list):
"""Extract the boundaries from a list of indexes"""
rows, cols = list(zip(*[(i.row(), i.column()) for i in index_list]))
return ( min(rows), max(rows), min(cols), max(cols) ) | [
"def",
"get_idx_rect",
"(",
"index_list",
")",
":",
"rows",
",",
"cols",
"=",
"list",
"(",
"zip",
"(",
"*",
"[",
"(",
"i",
".",
"row",
"(",
")",
",",
"i",
".",
"column",
"(",
")",
")",
"for",
"i",
"in",
"index_list",
"]",
")",
")",
"return",
"(",
"min",
"(",
"rows",
")",
",",
"max",
"(",
"rows",
")",
",",
"min",
"(",
"cols",
")",
",",
"max",
"(",
"cols",
")",
")"
] | Extract the boundaries from a list of indexes | [
"Extract",
"the",
"boundaries",
"from",
"a",
"list",
"of",
"indexes"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L107-L110 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/arrayeditor.py | ArrayModel.columnCount | def columnCount(self, qindex=QModelIndex()):
"""Array column number"""
if self.total_cols <= self.cols_loaded:
return self.total_cols
else:
return self.cols_loaded | python | def columnCount(self, qindex=QModelIndex()):
"""Array column number"""
if self.total_cols <= self.cols_loaded:
return self.total_cols
else:
return self.cols_loaded | [
"def",
"columnCount",
"(",
"self",
",",
"qindex",
"=",
"QModelIndex",
"(",
")",
")",
":",
"if",
"self",
".",
"total_cols",
"<=",
"self",
".",
"cols_loaded",
":",
"return",
"self",
".",
"total_cols",
"else",
":",
"return",
"self",
".",
"cols_loaded"
] | Array column number | [
"Array",
"column",
"number"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L197-L202 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/arrayeditor.py | ArrayModel.rowCount | def rowCount(self, qindex=QModelIndex()):
"""Array row number"""
if self.total_rows <= self.rows_loaded:
return self.total_rows
else:
return self.rows_loaded | python | def rowCount(self, qindex=QModelIndex()):
"""Array row number"""
if self.total_rows <= self.rows_loaded:
return self.total_rows
else:
return self.rows_loaded | [
"def",
"rowCount",
"(",
"self",
",",
"qindex",
"=",
"QModelIndex",
"(",
")",
")",
":",
"if",
"self",
".",
"total_rows",
"<=",
"self",
".",
"rows_loaded",
":",
"return",
"self",
".",
"total_rows",
"else",
":",
"return",
"self",
".",
"rows_loaded"
] | Array row number | [
"Array",
"row",
"number"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L204-L209 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/arrayeditor.py | ArrayModel.data | def data(self, index, role=Qt.DisplayRole):
"""Cell content"""
if not index.isValid():
return to_qvariant()
value = self.get_value(index)
if is_binary_string(value):
try:
value = to_text_string(value, 'utf8')
except:
pass
if role == Qt.DisplayRole:
if value is np.ma.masked:
return ''
else:
try:
return to_qvariant(self._format % value)
except TypeError:
self.readonly = True
return repr(value)
elif role == Qt.TextAlignmentRole:
return to_qvariant(int(Qt.AlignCenter|Qt.AlignVCenter))
elif role == Qt.BackgroundColorRole and self.bgcolor_enabled \
and value is not np.ma.masked:
try:
hue = (self.hue0 +
self.dhue * (float(self.vmax) - self.color_func(value))
/ (float(self.vmax) - self.vmin))
hue = float(np.abs(hue))
color = QColor.fromHsvF(hue, self.sat, self.val, self.alp)
return to_qvariant(color)
except TypeError:
return to_qvariant()
elif role == Qt.FontRole:
return to_qvariant(get_font(font_size_delta=DEFAULT_SMALL_DELTA))
return to_qvariant() | python | def data(self, index, role=Qt.DisplayRole):
"""Cell content"""
if not index.isValid():
return to_qvariant()
value = self.get_value(index)
if is_binary_string(value):
try:
value = to_text_string(value, 'utf8')
except:
pass
if role == Qt.DisplayRole:
if value is np.ma.masked:
return ''
else:
try:
return to_qvariant(self._format % value)
except TypeError:
self.readonly = True
return repr(value)
elif role == Qt.TextAlignmentRole:
return to_qvariant(int(Qt.AlignCenter|Qt.AlignVCenter))
elif role == Qt.BackgroundColorRole and self.bgcolor_enabled \
and value is not np.ma.masked:
try:
hue = (self.hue0 +
self.dhue * (float(self.vmax) - self.color_func(value))
/ (float(self.vmax) - self.vmin))
hue = float(np.abs(hue))
color = QColor.fromHsvF(hue, self.sat, self.val, self.alp)
return to_qvariant(color)
except TypeError:
return to_qvariant()
elif role == Qt.FontRole:
return to_qvariant(get_font(font_size_delta=DEFAULT_SMALL_DELTA))
return to_qvariant() | [
"def",
"data",
"(",
"self",
",",
"index",
",",
"role",
"=",
"Qt",
".",
"DisplayRole",
")",
":",
"if",
"not",
"index",
".",
"isValid",
"(",
")",
":",
"return",
"to_qvariant",
"(",
")",
"value",
"=",
"self",
".",
"get_value",
"(",
"index",
")",
"if",
"is_binary_string",
"(",
"value",
")",
":",
"try",
":",
"value",
"=",
"to_text_string",
"(",
"value",
",",
"'utf8'",
")",
"except",
":",
"pass",
"if",
"role",
"==",
"Qt",
".",
"DisplayRole",
":",
"if",
"value",
"is",
"np",
".",
"ma",
".",
"masked",
":",
"return",
"''",
"else",
":",
"try",
":",
"return",
"to_qvariant",
"(",
"self",
".",
"_format",
"%",
"value",
")",
"except",
"TypeError",
":",
"self",
".",
"readonly",
"=",
"True",
"return",
"repr",
"(",
"value",
")",
"elif",
"role",
"==",
"Qt",
".",
"TextAlignmentRole",
":",
"return",
"to_qvariant",
"(",
"int",
"(",
"Qt",
".",
"AlignCenter",
"|",
"Qt",
".",
"AlignVCenter",
")",
")",
"elif",
"role",
"==",
"Qt",
".",
"BackgroundColorRole",
"and",
"self",
".",
"bgcolor_enabled",
"and",
"value",
"is",
"not",
"np",
".",
"ma",
".",
"masked",
":",
"try",
":",
"hue",
"=",
"(",
"self",
".",
"hue0",
"+",
"self",
".",
"dhue",
"*",
"(",
"float",
"(",
"self",
".",
"vmax",
")",
"-",
"self",
".",
"color_func",
"(",
"value",
")",
")",
"/",
"(",
"float",
"(",
"self",
".",
"vmax",
")",
"-",
"self",
".",
"vmin",
")",
")",
"hue",
"=",
"float",
"(",
"np",
".",
"abs",
"(",
"hue",
")",
")",
"color",
"=",
"QColor",
".",
"fromHsvF",
"(",
"hue",
",",
"self",
".",
"sat",
",",
"self",
".",
"val",
",",
"self",
".",
"alp",
")",
"return",
"to_qvariant",
"(",
"color",
")",
"except",
"TypeError",
":",
"return",
"to_qvariant",
"(",
")",
"elif",
"role",
"==",
"Qt",
".",
"FontRole",
":",
"return",
"to_qvariant",
"(",
"get_font",
"(",
"font_size_delta",
"=",
"DEFAULT_SMALL_DELTA",
")",
")",
"return",
"to_qvariant",
"(",
")"
] | Cell content | [
"Cell",
"content"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L253-L287 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/arrayeditor.py | ArrayModel.setData | def setData(self, index, value, role=Qt.EditRole):
"""Cell content change"""
if not index.isValid() or self.readonly:
return False
i = index.row()
j = index.column()
value = from_qvariant(value, str)
dtype = self._data.dtype.name
if dtype == "bool":
try:
val = bool(float(value))
except ValueError:
val = value.lower() == "true"
elif dtype.startswith("string") or dtype.startswith("bytes"):
val = to_binary_string(value, 'utf8')
elif dtype.startswith("unicode") or dtype.startswith("str"):
val = to_text_string(value)
else:
if value.lower().startswith('e') or value.lower().endswith('e'):
return False
try:
val = complex(value)
if not val.imag:
val = val.real
except ValueError as e:
QMessageBox.critical(self.dialog, "Error",
"Value error: %s" % str(e))
return False
try:
self.test_array[0] = val # will raise an Exception eventually
except OverflowError as e:
print("OverflowError: " + str(e)) # spyder: test-skip
QMessageBox.critical(self.dialog, "Error",
"Overflow error: %s" % str(e))
return False
# Add change to self.changes
self.changes[(i, j)] = val
self.dataChanged.emit(index, index)
if not is_string(val):
if val > self.vmax:
self.vmax = val
if val < self.vmin:
self.vmin = val
return True | python | def setData(self, index, value, role=Qt.EditRole):
"""Cell content change"""
if not index.isValid() or self.readonly:
return False
i = index.row()
j = index.column()
value = from_qvariant(value, str)
dtype = self._data.dtype.name
if dtype == "bool":
try:
val = bool(float(value))
except ValueError:
val = value.lower() == "true"
elif dtype.startswith("string") or dtype.startswith("bytes"):
val = to_binary_string(value, 'utf8')
elif dtype.startswith("unicode") or dtype.startswith("str"):
val = to_text_string(value)
else:
if value.lower().startswith('e') or value.lower().endswith('e'):
return False
try:
val = complex(value)
if not val.imag:
val = val.real
except ValueError as e:
QMessageBox.critical(self.dialog, "Error",
"Value error: %s" % str(e))
return False
try:
self.test_array[0] = val # will raise an Exception eventually
except OverflowError as e:
print("OverflowError: " + str(e)) # spyder: test-skip
QMessageBox.critical(self.dialog, "Error",
"Overflow error: %s" % str(e))
return False
# Add change to self.changes
self.changes[(i, j)] = val
self.dataChanged.emit(index, index)
if not is_string(val):
if val > self.vmax:
self.vmax = val
if val < self.vmin:
self.vmin = val
return True | [
"def",
"setData",
"(",
"self",
",",
"index",
",",
"value",
",",
"role",
"=",
"Qt",
".",
"EditRole",
")",
":",
"if",
"not",
"index",
".",
"isValid",
"(",
")",
"or",
"self",
".",
"readonly",
":",
"return",
"False",
"i",
"=",
"index",
".",
"row",
"(",
")",
"j",
"=",
"index",
".",
"column",
"(",
")",
"value",
"=",
"from_qvariant",
"(",
"value",
",",
"str",
")",
"dtype",
"=",
"self",
".",
"_data",
".",
"dtype",
".",
"name",
"if",
"dtype",
"==",
"\"bool\"",
":",
"try",
":",
"val",
"=",
"bool",
"(",
"float",
"(",
"value",
")",
")",
"except",
"ValueError",
":",
"val",
"=",
"value",
".",
"lower",
"(",
")",
"==",
"\"true\"",
"elif",
"dtype",
".",
"startswith",
"(",
"\"string\"",
")",
"or",
"dtype",
".",
"startswith",
"(",
"\"bytes\"",
")",
":",
"val",
"=",
"to_binary_string",
"(",
"value",
",",
"'utf8'",
")",
"elif",
"dtype",
".",
"startswith",
"(",
"\"unicode\"",
")",
"or",
"dtype",
".",
"startswith",
"(",
"\"str\"",
")",
":",
"val",
"=",
"to_text_string",
"(",
"value",
")",
"else",
":",
"if",
"value",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"'e'",
")",
"or",
"value",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'e'",
")",
":",
"return",
"False",
"try",
":",
"val",
"=",
"complex",
"(",
"value",
")",
"if",
"not",
"val",
".",
"imag",
":",
"val",
"=",
"val",
".",
"real",
"except",
"ValueError",
"as",
"e",
":",
"QMessageBox",
".",
"critical",
"(",
"self",
".",
"dialog",
",",
"\"Error\"",
",",
"\"Value error: %s\"",
"%",
"str",
"(",
"e",
")",
")",
"return",
"False",
"try",
":",
"self",
".",
"test_array",
"[",
"0",
"]",
"=",
"val",
"# will raise an Exception eventually\r",
"except",
"OverflowError",
"as",
"e",
":",
"print",
"(",
"\"OverflowError: \"",
"+",
"str",
"(",
"e",
")",
")",
"# spyder: test-skip\r",
"QMessageBox",
".",
"critical",
"(",
"self",
".",
"dialog",
",",
"\"Error\"",
",",
"\"Overflow error: %s\"",
"%",
"str",
"(",
"e",
")",
")",
"return",
"False",
"# Add change to self.changes\r",
"self",
".",
"changes",
"[",
"(",
"i",
",",
"j",
")",
"]",
"=",
"val",
"self",
".",
"dataChanged",
".",
"emit",
"(",
"index",
",",
"index",
")",
"if",
"not",
"is_string",
"(",
"val",
")",
":",
"if",
"val",
">",
"self",
".",
"vmax",
":",
"self",
".",
"vmax",
"=",
"val",
"if",
"val",
"<",
"self",
".",
"vmin",
":",
"self",
".",
"vmin",
"=",
"val",
"return",
"True"
] | Cell content change | [
"Cell",
"content",
"change"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L289-L333 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/arrayeditor.py | ArrayModel.headerData | def headerData(self, section, orientation, role=Qt.DisplayRole):
"""Set header data"""
if role != Qt.DisplayRole:
return to_qvariant()
labels = self.xlabels if orientation == Qt.Horizontal else self.ylabels
if labels is None:
return to_qvariant(int(section))
else:
return to_qvariant(labels[section]) | python | def headerData(self, section, orientation, role=Qt.DisplayRole):
"""Set header data"""
if role != Qt.DisplayRole:
return to_qvariant()
labels = self.xlabels if orientation == Qt.Horizontal else self.ylabels
if labels is None:
return to_qvariant(int(section))
else:
return to_qvariant(labels[section]) | [
"def",
"headerData",
"(",
"self",
",",
"section",
",",
"orientation",
",",
"role",
"=",
"Qt",
".",
"DisplayRole",
")",
":",
"if",
"role",
"!=",
"Qt",
".",
"DisplayRole",
":",
"return",
"to_qvariant",
"(",
")",
"labels",
"=",
"self",
".",
"xlabels",
"if",
"orientation",
"==",
"Qt",
".",
"Horizontal",
"else",
"self",
".",
"ylabels",
"if",
"labels",
"is",
"None",
":",
"return",
"to_qvariant",
"(",
"int",
"(",
"section",
")",
")",
"else",
":",
"return",
"to_qvariant",
"(",
"labels",
"[",
"section",
"]",
")"
] | Set header data | [
"Set",
"header",
"data"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L342-L350 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/arrayeditor.py | ArrayDelegate.createEditor | def createEditor(self, parent, option, index):
"""Create editor widget"""
model = index.model()
value = model.get_value(index)
if model._data.dtype.name == "bool":
value = not value
model.setData(index, to_qvariant(value))
return
elif value is not np.ma.masked:
editor = QLineEdit(parent)
editor.setFont(get_font(font_size_delta=DEFAULT_SMALL_DELTA))
editor.setAlignment(Qt.AlignCenter)
if is_number(self.dtype):
validator = QDoubleValidator(editor)
validator.setLocale(QLocale('C'))
editor.setValidator(validator)
editor.returnPressed.connect(self.commitAndCloseEditor)
return editor | python | def createEditor(self, parent, option, index):
"""Create editor widget"""
model = index.model()
value = model.get_value(index)
if model._data.dtype.name == "bool":
value = not value
model.setData(index, to_qvariant(value))
return
elif value is not np.ma.masked:
editor = QLineEdit(parent)
editor.setFont(get_font(font_size_delta=DEFAULT_SMALL_DELTA))
editor.setAlignment(Qt.AlignCenter)
if is_number(self.dtype):
validator = QDoubleValidator(editor)
validator.setLocale(QLocale('C'))
editor.setValidator(validator)
editor.returnPressed.connect(self.commitAndCloseEditor)
return editor | [
"def",
"createEditor",
"(",
"self",
",",
"parent",
",",
"option",
",",
"index",
")",
":",
"model",
"=",
"index",
".",
"model",
"(",
")",
"value",
"=",
"model",
".",
"get_value",
"(",
"index",
")",
"if",
"model",
".",
"_data",
".",
"dtype",
".",
"name",
"==",
"\"bool\"",
":",
"value",
"=",
"not",
"value",
"model",
".",
"setData",
"(",
"index",
",",
"to_qvariant",
"(",
"value",
")",
")",
"return",
"elif",
"value",
"is",
"not",
"np",
".",
"ma",
".",
"masked",
":",
"editor",
"=",
"QLineEdit",
"(",
"parent",
")",
"editor",
".",
"setFont",
"(",
"get_font",
"(",
"font_size_delta",
"=",
"DEFAULT_SMALL_DELTA",
")",
")",
"editor",
".",
"setAlignment",
"(",
"Qt",
".",
"AlignCenter",
")",
"if",
"is_number",
"(",
"self",
".",
"dtype",
")",
":",
"validator",
"=",
"QDoubleValidator",
"(",
"editor",
")",
"validator",
".",
"setLocale",
"(",
"QLocale",
"(",
"'C'",
")",
")",
"editor",
".",
"setValidator",
"(",
"validator",
")",
"editor",
".",
"returnPressed",
".",
"connect",
"(",
"self",
".",
"commitAndCloseEditor",
")",
"return",
"editor"
] | Create editor widget | [
"Create",
"editor",
"widget"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L363-L380 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/arrayeditor.py | ArrayDelegate.commitAndCloseEditor | def commitAndCloseEditor(self):
"""Commit and close editor"""
editor = self.sender()
# Avoid a segfault with PyQt5. Variable value won't be changed
# but at least Spyder won't crash. It seems generated by a bug in sip.
try:
self.commitData.emit(editor)
except AttributeError:
pass
self.closeEditor.emit(editor, QAbstractItemDelegate.NoHint) | python | def commitAndCloseEditor(self):
"""Commit and close editor"""
editor = self.sender()
# Avoid a segfault with PyQt5. Variable value won't be changed
# but at least Spyder won't crash. It seems generated by a bug in sip.
try:
self.commitData.emit(editor)
except AttributeError:
pass
self.closeEditor.emit(editor, QAbstractItemDelegate.NoHint) | [
"def",
"commitAndCloseEditor",
"(",
"self",
")",
":",
"editor",
"=",
"self",
".",
"sender",
"(",
")",
"# Avoid a segfault with PyQt5. Variable value won't be changed\r",
"# but at least Spyder won't crash. It seems generated by a bug in sip.\r",
"try",
":",
"self",
".",
"commitData",
".",
"emit",
"(",
"editor",
")",
"except",
"AttributeError",
":",
"pass",
"self",
".",
"closeEditor",
".",
"emit",
"(",
"editor",
",",
"QAbstractItemDelegate",
".",
"NoHint",
")"
] | Commit and close editor | [
"Commit",
"and",
"close",
"editor"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L382-L391 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/arrayeditor.py | ArrayDelegate.setEditorData | def setEditorData(self, editor, index):
"""Set editor widget's data"""
text = from_qvariant(index.model().data(index, Qt.DisplayRole), str)
editor.setText(text) | python | def setEditorData(self, editor, index):
"""Set editor widget's data"""
text = from_qvariant(index.model().data(index, Qt.DisplayRole), str)
editor.setText(text) | [
"def",
"setEditorData",
"(",
"self",
",",
"editor",
",",
"index",
")",
":",
"text",
"=",
"from_qvariant",
"(",
"index",
".",
"model",
"(",
")",
".",
"data",
"(",
"index",
",",
"Qt",
".",
"DisplayRole",
")",
",",
"str",
")",
"editor",
".",
"setText",
"(",
"text",
")"
] | Set editor widget's data | [
"Set",
"editor",
"widget",
"s",
"data"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L393-L396 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/arrayeditor.py | ArrayView.resize_to_contents | def resize_to_contents(self):
"""Resize cells to contents"""
QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
self.resizeColumnsToContents()
self.model().fetch_more(columns=True)
self.resizeColumnsToContents()
QApplication.restoreOverrideCursor() | python | def resize_to_contents(self):
"""Resize cells to contents"""
QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
self.resizeColumnsToContents()
self.model().fetch_more(columns=True)
self.resizeColumnsToContents()
QApplication.restoreOverrideCursor() | [
"def",
"resize_to_contents",
"(",
"self",
")",
":",
"QApplication",
".",
"setOverrideCursor",
"(",
"QCursor",
"(",
"Qt",
".",
"WaitCursor",
")",
")",
"self",
".",
"resizeColumnsToContents",
"(",
")",
"self",
".",
"model",
"(",
")",
".",
"fetch_more",
"(",
"columns",
"=",
"True",
")",
"self",
".",
"resizeColumnsToContents",
"(",
")",
"QApplication",
".",
"restoreOverrideCursor",
"(",
")"
] | Resize cells to contents | [
"Resize",
"cells",
"to",
"contents"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L464-L470 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/arrayeditor.py | ArrayView.setup_menu | def setup_menu(self):
"""Setup context menu"""
self.copy_action = create_action(self, _('Copy'),
shortcut=keybinding('Copy'),
icon=ima.icon('editcopy'),
triggered=self.copy,
context=Qt.WidgetShortcut)
menu = QMenu(self)
add_actions(menu, [self.copy_action, ])
return menu | python | def setup_menu(self):
"""Setup context menu"""
self.copy_action = create_action(self, _('Copy'),
shortcut=keybinding('Copy'),
icon=ima.icon('editcopy'),
triggered=self.copy,
context=Qt.WidgetShortcut)
menu = QMenu(self)
add_actions(menu, [self.copy_action, ])
return menu | [
"def",
"setup_menu",
"(",
"self",
")",
":",
"self",
".",
"copy_action",
"=",
"create_action",
"(",
"self",
",",
"_",
"(",
"'Copy'",
")",
",",
"shortcut",
"=",
"keybinding",
"(",
"'Copy'",
")",
",",
"icon",
"=",
"ima",
".",
"icon",
"(",
"'editcopy'",
")",
",",
"triggered",
"=",
"self",
".",
"copy",
",",
"context",
"=",
"Qt",
".",
"WidgetShortcut",
")",
"menu",
"=",
"QMenu",
"(",
"self",
")",
"add_actions",
"(",
"menu",
",",
"[",
"self",
".",
"copy_action",
",",
"]",
")",
"return",
"menu"
] | Setup context menu | [
"Setup",
"context",
"menu"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L472-L481 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/arrayeditor.py | ArrayView.contextMenuEvent | def contextMenuEvent(self, event):
"""Reimplement Qt method"""
self.menu.popup(event.globalPos())
event.accept() | python | def contextMenuEvent(self, event):
"""Reimplement Qt method"""
self.menu.popup(event.globalPos())
event.accept() | [
"def",
"contextMenuEvent",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"menu",
".",
"popup",
"(",
"event",
".",
"globalPos",
"(",
")",
")",
"event",
".",
"accept",
"(",
")"
] | Reimplement Qt method | [
"Reimplement",
"Qt",
"method"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L483-L486 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/arrayeditor.py | ArrayView.keyPressEvent | def keyPressEvent(self, event):
"""Reimplement Qt method"""
if event == QKeySequence.Copy:
self.copy()
else:
QTableView.keyPressEvent(self, event) | python | def keyPressEvent(self, event):
"""Reimplement Qt method"""
if event == QKeySequence.Copy:
self.copy()
else:
QTableView.keyPressEvent(self, event) | [
"def",
"keyPressEvent",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
"==",
"QKeySequence",
".",
"Copy",
":",
"self",
".",
"copy",
"(",
")",
"else",
":",
"QTableView",
".",
"keyPressEvent",
"(",
"self",
",",
"event",
")"
] | Reimplement Qt method | [
"Reimplement",
"Qt",
"method"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L488-L493 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/arrayeditor.py | ArrayView._sel_to_text | def _sel_to_text(self, cell_range):
"""Copy an array portion to a unicode string"""
if not cell_range:
return
row_min, row_max, col_min, col_max = get_idx_rect(cell_range)
if col_min == 0 and col_max == (self.model().cols_loaded-1):
# we've selected a whole column. It isn't possible to
# select only the first part of a column without loading more,
# so we can treat it as intentional and copy the whole thing
col_max = self.model().total_cols-1
if row_min == 0 and row_max == (self.model().rows_loaded-1):
row_max = self.model().total_rows-1
_data = self.model().get_data()
if PY3:
output = io.BytesIO()
else:
output = io.StringIO()
try:
np.savetxt(output, _data[row_min:row_max+1, col_min:col_max+1],
delimiter='\t', fmt=self.model().get_format())
except:
QMessageBox.warning(self, _("Warning"),
_("It was not possible to copy values for "
"this array"))
return
contents = output.getvalue().decode('utf-8')
output.close()
return contents | python | def _sel_to_text(self, cell_range):
"""Copy an array portion to a unicode string"""
if not cell_range:
return
row_min, row_max, col_min, col_max = get_idx_rect(cell_range)
if col_min == 0 and col_max == (self.model().cols_loaded-1):
# we've selected a whole column. It isn't possible to
# select only the first part of a column without loading more,
# so we can treat it as intentional and copy the whole thing
col_max = self.model().total_cols-1
if row_min == 0 and row_max == (self.model().rows_loaded-1):
row_max = self.model().total_rows-1
_data = self.model().get_data()
if PY3:
output = io.BytesIO()
else:
output = io.StringIO()
try:
np.savetxt(output, _data[row_min:row_max+1, col_min:col_max+1],
delimiter='\t', fmt=self.model().get_format())
except:
QMessageBox.warning(self, _("Warning"),
_("It was not possible to copy values for "
"this array"))
return
contents = output.getvalue().decode('utf-8')
output.close()
return contents | [
"def",
"_sel_to_text",
"(",
"self",
",",
"cell_range",
")",
":",
"if",
"not",
"cell_range",
":",
"return",
"row_min",
",",
"row_max",
",",
"col_min",
",",
"col_max",
"=",
"get_idx_rect",
"(",
"cell_range",
")",
"if",
"col_min",
"==",
"0",
"and",
"col_max",
"==",
"(",
"self",
".",
"model",
"(",
")",
".",
"cols_loaded",
"-",
"1",
")",
":",
"# we've selected a whole column. It isn't possible to\r",
"# select only the first part of a column without loading more, \r",
"# so we can treat it as intentional and copy the whole thing\r",
"col_max",
"=",
"self",
".",
"model",
"(",
")",
".",
"total_cols",
"-",
"1",
"if",
"row_min",
"==",
"0",
"and",
"row_max",
"==",
"(",
"self",
".",
"model",
"(",
")",
".",
"rows_loaded",
"-",
"1",
")",
":",
"row_max",
"=",
"self",
".",
"model",
"(",
")",
".",
"total_rows",
"-",
"1",
"_data",
"=",
"self",
".",
"model",
"(",
")",
".",
"get_data",
"(",
")",
"if",
"PY3",
":",
"output",
"=",
"io",
".",
"BytesIO",
"(",
")",
"else",
":",
"output",
"=",
"io",
".",
"StringIO",
"(",
")",
"try",
":",
"np",
".",
"savetxt",
"(",
"output",
",",
"_data",
"[",
"row_min",
":",
"row_max",
"+",
"1",
",",
"col_min",
":",
"col_max",
"+",
"1",
"]",
",",
"delimiter",
"=",
"'\\t'",
",",
"fmt",
"=",
"self",
".",
"model",
"(",
")",
".",
"get_format",
"(",
")",
")",
"except",
":",
"QMessageBox",
".",
"warning",
"(",
"self",
",",
"_",
"(",
"\"Warning\"",
")",
",",
"_",
"(",
"\"It was not possible to copy values for \"",
"\"this array\"",
")",
")",
"return",
"contents",
"=",
"output",
".",
"getvalue",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"output",
".",
"close",
"(",
")",
"return",
"contents"
] | Copy an array portion to a unicode string | [
"Copy",
"an",
"array",
"portion",
"to",
"a",
"unicode",
"string"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L495-L523 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/arrayeditor.py | ArrayView.copy | def copy(self):
"""Copy text to clipboard"""
cliptxt = self._sel_to_text( self.selectedIndexes() )
clipboard = QApplication.clipboard()
clipboard.setText(cliptxt) | python | def copy(self):
"""Copy text to clipboard"""
cliptxt = self._sel_to_text( self.selectedIndexes() )
clipboard = QApplication.clipboard()
clipboard.setText(cliptxt) | [
"def",
"copy",
"(",
"self",
")",
":",
"cliptxt",
"=",
"self",
".",
"_sel_to_text",
"(",
"self",
".",
"selectedIndexes",
"(",
")",
")",
"clipboard",
"=",
"QApplication",
".",
"clipboard",
"(",
")",
"clipboard",
".",
"setText",
"(",
"cliptxt",
")"
] | Copy text to clipboard | [
"Copy",
"text",
"to",
"clipboard"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L526-L530 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/arrayeditor.py | ArrayEditorWidget.accept_changes | def accept_changes(self):
"""Accept changes"""
for (i, j), value in list(self.model.changes.items()):
self.data[i, j] = value
if self.old_data_shape is not None:
self.data.shape = self.old_data_shape | python | def accept_changes(self):
"""Accept changes"""
for (i, j), value in list(self.model.changes.items()):
self.data[i, j] = value
if self.old_data_shape is not None:
self.data.shape = self.old_data_shape | [
"def",
"accept_changes",
"(",
"self",
")",
":",
"for",
"(",
"i",
",",
"j",
")",
",",
"value",
"in",
"list",
"(",
"self",
".",
"model",
".",
"changes",
".",
"items",
"(",
")",
")",
":",
"self",
".",
"data",
"[",
"i",
",",
"j",
"]",
"=",
"value",
"if",
"self",
".",
"old_data_shape",
"is",
"not",
"None",
":",
"self",
".",
"data",
".",
"shape",
"=",
"self",
".",
"old_data_shape"
] | Accept changes | [
"Accept",
"changes"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L573-L578 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/arrayeditor.py | ArrayEditorWidget.change_format | def change_format(self):
"""Change display format"""
format, valid = QInputDialog.getText(self, _( 'Format'),
_( "Float formatting"),
QLineEdit.Normal, self.model.get_format())
if valid:
format = str(format)
try:
format % 1.1
except:
QMessageBox.critical(self, _("Error"),
_("Format (%s) is incorrect") % format)
return
self.model.set_format(format) | python | def change_format(self):
"""Change display format"""
format, valid = QInputDialog.getText(self, _( 'Format'),
_( "Float formatting"),
QLineEdit.Normal, self.model.get_format())
if valid:
format = str(format)
try:
format % 1.1
except:
QMessageBox.critical(self, _("Error"),
_("Format (%s) is incorrect") % format)
return
self.model.set_format(format) | [
"def",
"change_format",
"(",
"self",
")",
":",
"format",
",",
"valid",
"=",
"QInputDialog",
".",
"getText",
"(",
"self",
",",
"_",
"(",
"'Format'",
")",
",",
"_",
"(",
"\"Float formatting\"",
")",
",",
"QLineEdit",
".",
"Normal",
",",
"self",
".",
"model",
".",
"get_format",
"(",
")",
")",
"if",
"valid",
":",
"format",
"=",
"str",
"(",
"format",
")",
"try",
":",
"format",
"%",
"1.1",
"except",
":",
"QMessageBox",
".",
"critical",
"(",
"self",
",",
"_",
"(",
"\"Error\"",
")",
",",
"_",
"(",
"\"Format (%s) is incorrect\"",
")",
"%",
"format",
")",
"return",
"self",
".",
"model",
".",
"set_format",
"(",
"format",
")"
] | Change display format | [
"Change",
"display",
"format"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L585-L598 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/arrayeditor.py | ArrayEditor.setup_and_check | def setup_and_check(self, data, title='', readonly=False,
xlabels=None, ylabels=None):
"""
Setup ArrayEditor:
return False if data is not supported, True otherwise
"""
self.data = data
readonly = readonly or not self.data.flags.writeable
is_record_array = data.dtype.names is not None
is_masked_array = isinstance(data, np.ma.MaskedArray)
if data.ndim > 3:
self.error(_("Arrays with more than 3 dimensions are not "
"supported"))
return False
if xlabels is not None and len(xlabels) != self.data.shape[1]:
self.error(_("The 'xlabels' argument length do no match array "
"column number"))
return False
if ylabels is not None and len(ylabels) != self.data.shape[0]:
self.error(_("The 'ylabels' argument length do no match array row "
"number"))
return False
if not is_record_array:
dtn = data.dtype.name
if dtn not in SUPPORTED_FORMATS and not dtn.startswith('str') \
and not dtn.startswith('unicode'):
arr = _("%s arrays") % data.dtype.name
self.error(_("%s are currently not supported") % arr)
return False
self.layout = QGridLayout()
self.setLayout(self.layout)
self.setWindowIcon(ima.icon('arredit'))
if title:
title = to_text_string(title) + " - " + _("NumPy array")
else:
title = _("Array editor")
if readonly:
title += ' (' + _('read only') + ')'
self.setWindowTitle(title)
self.resize(600, 500)
# Stack widget
self.stack = QStackedWidget(self)
if is_record_array:
for name in data.dtype.names:
self.stack.addWidget(ArrayEditorWidget(self, data[name],
readonly, xlabels, ylabels))
elif is_masked_array:
self.stack.addWidget(ArrayEditorWidget(self, data, readonly,
xlabels, ylabels))
self.stack.addWidget(ArrayEditorWidget(self, data.data, readonly,
xlabels, ylabels))
self.stack.addWidget(ArrayEditorWidget(self, data.mask, readonly,
xlabels, ylabels))
elif data.ndim == 3:
pass
else:
self.stack.addWidget(ArrayEditorWidget(self, data, readonly,
xlabels, ylabels))
self.arraywidget = self.stack.currentWidget()
if self.arraywidget:
self.arraywidget.model.dataChanged.connect(
self.save_and_close_enable)
self.stack.currentChanged.connect(self.current_widget_changed)
self.layout.addWidget(self.stack, 1, 0)
# Buttons configuration
btn_layout = QHBoxLayout()
if is_record_array or is_masked_array or data.ndim == 3:
if is_record_array:
btn_layout.addWidget(QLabel(_("Record array fields:")))
names = []
for name in data.dtype.names:
field = data.dtype.fields[name]
text = name
if len(field) >= 3:
title = field[2]
if not is_text_string(title):
title = repr(title)
text += ' - '+title
names.append(text)
else:
names = [_('Masked data'), _('Data'), _('Mask')]
if data.ndim == 3:
# QSpinBox
self.index_spin = QSpinBox(self, keyboardTracking=False)
self.index_spin.valueChanged.connect(self.change_active_widget)
# QComboBox
names = [str(i) for i in range(3)]
ra_combo = QComboBox(self)
ra_combo.addItems(names)
ra_combo.currentIndexChanged.connect(self.current_dim_changed)
# Adding the widgets to layout
label = QLabel(_("Axis:"))
btn_layout.addWidget(label)
btn_layout.addWidget(ra_combo)
self.shape_label = QLabel()
btn_layout.addWidget(self.shape_label)
label = QLabel(_("Index:"))
btn_layout.addWidget(label)
btn_layout.addWidget(self.index_spin)
self.slicing_label = QLabel()
btn_layout.addWidget(self.slicing_label)
# set the widget to display when launched
self.current_dim_changed(self.last_dim)
else:
ra_combo = QComboBox(self)
ra_combo.currentIndexChanged.connect(self.stack.setCurrentIndex)
ra_combo.addItems(names)
btn_layout.addWidget(ra_combo)
if is_masked_array:
label = QLabel(_("<u>Warning</u>: changes are applied separately"))
label.setToolTip(_("For performance reasons, changes applied "\
"to masked array won't be reflected in "\
"array's data (and vice-versa)."))
btn_layout.addWidget(label)
btn_layout.addStretch()
if not readonly:
self.btn_save_and_close = QPushButton(_('Save and Close'))
self.btn_save_and_close.setDisabled(True)
self.btn_save_and_close.clicked.connect(self.accept)
btn_layout.addWidget(self.btn_save_and_close)
self.btn_close = QPushButton(_('Close'))
self.btn_close.setAutoDefault(True)
self.btn_close.setDefault(True)
self.btn_close.clicked.connect(self.reject)
btn_layout.addWidget(self.btn_close)
self.layout.addLayout(btn_layout, 2, 0)
self.setMinimumSize(400, 300)
# Make the dialog act as a window
self.setWindowFlags(Qt.Window)
return True | python | def setup_and_check(self, data, title='', readonly=False,
xlabels=None, ylabels=None):
"""
Setup ArrayEditor:
return False if data is not supported, True otherwise
"""
self.data = data
readonly = readonly or not self.data.flags.writeable
is_record_array = data.dtype.names is not None
is_masked_array = isinstance(data, np.ma.MaskedArray)
if data.ndim > 3:
self.error(_("Arrays with more than 3 dimensions are not "
"supported"))
return False
if xlabels is not None and len(xlabels) != self.data.shape[1]:
self.error(_("The 'xlabels' argument length do no match array "
"column number"))
return False
if ylabels is not None and len(ylabels) != self.data.shape[0]:
self.error(_("The 'ylabels' argument length do no match array row "
"number"))
return False
if not is_record_array:
dtn = data.dtype.name
if dtn not in SUPPORTED_FORMATS and not dtn.startswith('str') \
and not dtn.startswith('unicode'):
arr = _("%s arrays") % data.dtype.name
self.error(_("%s are currently not supported") % arr)
return False
self.layout = QGridLayout()
self.setLayout(self.layout)
self.setWindowIcon(ima.icon('arredit'))
if title:
title = to_text_string(title) + " - " + _("NumPy array")
else:
title = _("Array editor")
if readonly:
title += ' (' + _('read only') + ')'
self.setWindowTitle(title)
self.resize(600, 500)
# Stack widget
self.stack = QStackedWidget(self)
if is_record_array:
for name in data.dtype.names:
self.stack.addWidget(ArrayEditorWidget(self, data[name],
readonly, xlabels, ylabels))
elif is_masked_array:
self.stack.addWidget(ArrayEditorWidget(self, data, readonly,
xlabels, ylabels))
self.stack.addWidget(ArrayEditorWidget(self, data.data, readonly,
xlabels, ylabels))
self.stack.addWidget(ArrayEditorWidget(self, data.mask, readonly,
xlabels, ylabels))
elif data.ndim == 3:
pass
else:
self.stack.addWidget(ArrayEditorWidget(self, data, readonly,
xlabels, ylabels))
self.arraywidget = self.stack.currentWidget()
if self.arraywidget:
self.arraywidget.model.dataChanged.connect(
self.save_and_close_enable)
self.stack.currentChanged.connect(self.current_widget_changed)
self.layout.addWidget(self.stack, 1, 0)
# Buttons configuration
btn_layout = QHBoxLayout()
if is_record_array or is_masked_array or data.ndim == 3:
if is_record_array:
btn_layout.addWidget(QLabel(_("Record array fields:")))
names = []
for name in data.dtype.names:
field = data.dtype.fields[name]
text = name
if len(field) >= 3:
title = field[2]
if not is_text_string(title):
title = repr(title)
text += ' - '+title
names.append(text)
else:
names = [_('Masked data'), _('Data'), _('Mask')]
if data.ndim == 3:
# QSpinBox
self.index_spin = QSpinBox(self, keyboardTracking=False)
self.index_spin.valueChanged.connect(self.change_active_widget)
# QComboBox
names = [str(i) for i in range(3)]
ra_combo = QComboBox(self)
ra_combo.addItems(names)
ra_combo.currentIndexChanged.connect(self.current_dim_changed)
# Adding the widgets to layout
label = QLabel(_("Axis:"))
btn_layout.addWidget(label)
btn_layout.addWidget(ra_combo)
self.shape_label = QLabel()
btn_layout.addWidget(self.shape_label)
label = QLabel(_("Index:"))
btn_layout.addWidget(label)
btn_layout.addWidget(self.index_spin)
self.slicing_label = QLabel()
btn_layout.addWidget(self.slicing_label)
# set the widget to display when launched
self.current_dim_changed(self.last_dim)
else:
ra_combo = QComboBox(self)
ra_combo.currentIndexChanged.connect(self.stack.setCurrentIndex)
ra_combo.addItems(names)
btn_layout.addWidget(ra_combo)
if is_masked_array:
label = QLabel(_("<u>Warning</u>: changes are applied separately"))
label.setToolTip(_("For performance reasons, changes applied "\
"to masked array won't be reflected in "\
"array's data (and vice-versa)."))
btn_layout.addWidget(label)
btn_layout.addStretch()
if not readonly:
self.btn_save_and_close = QPushButton(_('Save and Close'))
self.btn_save_and_close.setDisabled(True)
self.btn_save_and_close.clicked.connect(self.accept)
btn_layout.addWidget(self.btn_save_and_close)
self.btn_close = QPushButton(_('Close'))
self.btn_close.setAutoDefault(True)
self.btn_close.setDefault(True)
self.btn_close.clicked.connect(self.reject)
btn_layout.addWidget(self.btn_close)
self.layout.addLayout(btn_layout, 2, 0)
self.setMinimumSize(400, 300)
# Make the dialog act as a window
self.setWindowFlags(Qt.Window)
return True | [
"def",
"setup_and_check",
"(",
"self",
",",
"data",
",",
"title",
"=",
"''",
",",
"readonly",
"=",
"False",
",",
"xlabels",
"=",
"None",
",",
"ylabels",
"=",
"None",
")",
":",
"self",
".",
"data",
"=",
"data",
"readonly",
"=",
"readonly",
"or",
"not",
"self",
".",
"data",
".",
"flags",
".",
"writeable",
"is_record_array",
"=",
"data",
".",
"dtype",
".",
"names",
"is",
"not",
"None",
"is_masked_array",
"=",
"isinstance",
"(",
"data",
",",
"np",
".",
"ma",
".",
"MaskedArray",
")",
"if",
"data",
".",
"ndim",
">",
"3",
":",
"self",
".",
"error",
"(",
"_",
"(",
"\"Arrays with more than 3 dimensions are not \"",
"\"supported\"",
")",
")",
"return",
"False",
"if",
"xlabels",
"is",
"not",
"None",
"and",
"len",
"(",
"xlabels",
")",
"!=",
"self",
".",
"data",
".",
"shape",
"[",
"1",
"]",
":",
"self",
".",
"error",
"(",
"_",
"(",
"\"The 'xlabels' argument length do no match array \"",
"\"column number\"",
")",
")",
"return",
"False",
"if",
"ylabels",
"is",
"not",
"None",
"and",
"len",
"(",
"ylabels",
")",
"!=",
"self",
".",
"data",
".",
"shape",
"[",
"0",
"]",
":",
"self",
".",
"error",
"(",
"_",
"(",
"\"The 'ylabels' argument length do no match array row \"",
"\"number\"",
")",
")",
"return",
"False",
"if",
"not",
"is_record_array",
":",
"dtn",
"=",
"data",
".",
"dtype",
".",
"name",
"if",
"dtn",
"not",
"in",
"SUPPORTED_FORMATS",
"and",
"not",
"dtn",
".",
"startswith",
"(",
"'str'",
")",
"and",
"not",
"dtn",
".",
"startswith",
"(",
"'unicode'",
")",
":",
"arr",
"=",
"_",
"(",
"\"%s arrays\"",
")",
"%",
"data",
".",
"dtype",
".",
"name",
"self",
".",
"error",
"(",
"_",
"(",
"\"%s are currently not supported\"",
")",
"%",
"arr",
")",
"return",
"False",
"self",
".",
"layout",
"=",
"QGridLayout",
"(",
")",
"self",
".",
"setLayout",
"(",
"self",
".",
"layout",
")",
"self",
".",
"setWindowIcon",
"(",
"ima",
".",
"icon",
"(",
"'arredit'",
")",
")",
"if",
"title",
":",
"title",
"=",
"to_text_string",
"(",
"title",
")",
"+",
"\" - \"",
"+",
"_",
"(",
"\"NumPy array\"",
")",
"else",
":",
"title",
"=",
"_",
"(",
"\"Array editor\"",
")",
"if",
"readonly",
":",
"title",
"+=",
"' ('",
"+",
"_",
"(",
"'read only'",
")",
"+",
"')'",
"self",
".",
"setWindowTitle",
"(",
"title",
")",
"self",
".",
"resize",
"(",
"600",
",",
"500",
")",
"# Stack widget\r",
"self",
".",
"stack",
"=",
"QStackedWidget",
"(",
"self",
")",
"if",
"is_record_array",
":",
"for",
"name",
"in",
"data",
".",
"dtype",
".",
"names",
":",
"self",
".",
"stack",
".",
"addWidget",
"(",
"ArrayEditorWidget",
"(",
"self",
",",
"data",
"[",
"name",
"]",
",",
"readonly",
",",
"xlabels",
",",
"ylabels",
")",
")",
"elif",
"is_masked_array",
":",
"self",
".",
"stack",
".",
"addWidget",
"(",
"ArrayEditorWidget",
"(",
"self",
",",
"data",
",",
"readonly",
",",
"xlabels",
",",
"ylabels",
")",
")",
"self",
".",
"stack",
".",
"addWidget",
"(",
"ArrayEditorWidget",
"(",
"self",
",",
"data",
".",
"data",
",",
"readonly",
",",
"xlabels",
",",
"ylabels",
")",
")",
"self",
".",
"stack",
".",
"addWidget",
"(",
"ArrayEditorWidget",
"(",
"self",
",",
"data",
".",
"mask",
",",
"readonly",
",",
"xlabels",
",",
"ylabels",
")",
")",
"elif",
"data",
".",
"ndim",
"==",
"3",
":",
"pass",
"else",
":",
"self",
".",
"stack",
".",
"addWidget",
"(",
"ArrayEditorWidget",
"(",
"self",
",",
"data",
",",
"readonly",
",",
"xlabels",
",",
"ylabels",
")",
")",
"self",
".",
"arraywidget",
"=",
"self",
".",
"stack",
".",
"currentWidget",
"(",
")",
"if",
"self",
".",
"arraywidget",
":",
"self",
".",
"arraywidget",
".",
"model",
".",
"dataChanged",
".",
"connect",
"(",
"self",
".",
"save_and_close_enable",
")",
"self",
".",
"stack",
".",
"currentChanged",
".",
"connect",
"(",
"self",
".",
"current_widget_changed",
")",
"self",
".",
"layout",
".",
"addWidget",
"(",
"self",
".",
"stack",
",",
"1",
",",
"0",
")",
"# Buttons configuration\r",
"btn_layout",
"=",
"QHBoxLayout",
"(",
")",
"if",
"is_record_array",
"or",
"is_masked_array",
"or",
"data",
".",
"ndim",
"==",
"3",
":",
"if",
"is_record_array",
":",
"btn_layout",
".",
"addWidget",
"(",
"QLabel",
"(",
"_",
"(",
"\"Record array fields:\"",
")",
")",
")",
"names",
"=",
"[",
"]",
"for",
"name",
"in",
"data",
".",
"dtype",
".",
"names",
":",
"field",
"=",
"data",
".",
"dtype",
".",
"fields",
"[",
"name",
"]",
"text",
"=",
"name",
"if",
"len",
"(",
"field",
")",
">=",
"3",
":",
"title",
"=",
"field",
"[",
"2",
"]",
"if",
"not",
"is_text_string",
"(",
"title",
")",
":",
"title",
"=",
"repr",
"(",
"title",
")",
"text",
"+=",
"' - '",
"+",
"title",
"names",
".",
"append",
"(",
"text",
")",
"else",
":",
"names",
"=",
"[",
"_",
"(",
"'Masked data'",
")",
",",
"_",
"(",
"'Data'",
")",
",",
"_",
"(",
"'Mask'",
")",
"]",
"if",
"data",
".",
"ndim",
"==",
"3",
":",
"# QSpinBox\r",
"self",
".",
"index_spin",
"=",
"QSpinBox",
"(",
"self",
",",
"keyboardTracking",
"=",
"False",
")",
"self",
".",
"index_spin",
".",
"valueChanged",
".",
"connect",
"(",
"self",
".",
"change_active_widget",
")",
"# QComboBox\r",
"names",
"=",
"[",
"str",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"3",
")",
"]",
"ra_combo",
"=",
"QComboBox",
"(",
"self",
")",
"ra_combo",
".",
"addItems",
"(",
"names",
")",
"ra_combo",
".",
"currentIndexChanged",
".",
"connect",
"(",
"self",
".",
"current_dim_changed",
")",
"# Adding the widgets to layout\r",
"label",
"=",
"QLabel",
"(",
"_",
"(",
"\"Axis:\"",
")",
")",
"btn_layout",
".",
"addWidget",
"(",
"label",
")",
"btn_layout",
".",
"addWidget",
"(",
"ra_combo",
")",
"self",
".",
"shape_label",
"=",
"QLabel",
"(",
")",
"btn_layout",
".",
"addWidget",
"(",
"self",
".",
"shape_label",
")",
"label",
"=",
"QLabel",
"(",
"_",
"(",
"\"Index:\"",
")",
")",
"btn_layout",
".",
"addWidget",
"(",
"label",
")",
"btn_layout",
".",
"addWidget",
"(",
"self",
".",
"index_spin",
")",
"self",
".",
"slicing_label",
"=",
"QLabel",
"(",
")",
"btn_layout",
".",
"addWidget",
"(",
"self",
".",
"slicing_label",
")",
"# set the widget to display when launched\r",
"self",
".",
"current_dim_changed",
"(",
"self",
".",
"last_dim",
")",
"else",
":",
"ra_combo",
"=",
"QComboBox",
"(",
"self",
")",
"ra_combo",
".",
"currentIndexChanged",
".",
"connect",
"(",
"self",
".",
"stack",
".",
"setCurrentIndex",
")",
"ra_combo",
".",
"addItems",
"(",
"names",
")",
"btn_layout",
".",
"addWidget",
"(",
"ra_combo",
")",
"if",
"is_masked_array",
":",
"label",
"=",
"QLabel",
"(",
"_",
"(",
"\"<u>Warning</u>: changes are applied separately\"",
")",
")",
"label",
".",
"setToolTip",
"(",
"_",
"(",
"\"For performance reasons, changes applied \"",
"\"to masked array won't be reflected in \"",
"\"array's data (and vice-versa).\"",
")",
")",
"btn_layout",
".",
"addWidget",
"(",
"label",
")",
"btn_layout",
".",
"addStretch",
"(",
")",
"if",
"not",
"readonly",
":",
"self",
".",
"btn_save_and_close",
"=",
"QPushButton",
"(",
"_",
"(",
"'Save and Close'",
")",
")",
"self",
".",
"btn_save_and_close",
".",
"setDisabled",
"(",
"True",
")",
"self",
".",
"btn_save_and_close",
".",
"clicked",
".",
"connect",
"(",
"self",
".",
"accept",
")",
"btn_layout",
".",
"addWidget",
"(",
"self",
".",
"btn_save_and_close",
")",
"self",
".",
"btn_close",
"=",
"QPushButton",
"(",
"_",
"(",
"'Close'",
")",
")",
"self",
".",
"btn_close",
".",
"setAutoDefault",
"(",
"True",
")",
"self",
".",
"btn_close",
".",
"setDefault",
"(",
"True",
")",
"self",
".",
"btn_close",
".",
"clicked",
".",
"connect",
"(",
"self",
".",
"reject",
")",
"btn_layout",
".",
"addWidget",
"(",
"self",
".",
"btn_close",
")",
"self",
".",
"layout",
".",
"addLayout",
"(",
"btn_layout",
",",
"2",
",",
"0",
")",
"self",
".",
"setMinimumSize",
"(",
"400",
",",
"300",
")",
"# Make the dialog act as a window\r",
"self",
".",
"setWindowFlags",
"(",
"Qt",
".",
"Window",
")",
"return",
"True"
] | Setup ArrayEditor:
return False if data is not supported, True otherwise | [
"Setup",
"ArrayEditor",
":",
"return",
"False",
"if",
"data",
"is",
"not",
"supported",
"True",
"otherwise"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L622-L761 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/arrayeditor.py | ArrayEditor.change_active_widget | def change_active_widget(self, index):
"""
This is implemented for handling negative values in index for
3d arrays, to give the same behavior as slicing
"""
string_index = [':']*3
string_index[self.last_dim] = '<font color=red>%i</font>'
self.slicing_label.setText((r"Slicing: [" + ", ".join(string_index) +
"]") % index)
if index < 0:
data_index = self.data.shape[self.last_dim] + index
else:
data_index = index
slice_index = [slice(None)]*3
slice_index[self.last_dim] = data_index
stack_index = self.dim_indexes[self.last_dim].get(data_index)
if stack_index is None:
stack_index = self.stack.count()
try:
self.stack.addWidget(ArrayEditorWidget(
self, self.data[tuple(slice_index)]))
except IndexError: # Handle arrays of size 0 in one axis
self.stack.addWidget(ArrayEditorWidget(self, self.data))
self.dim_indexes[self.last_dim][data_index] = stack_index
self.stack.update()
self.stack.setCurrentIndex(stack_index) | python | def change_active_widget(self, index):
"""
This is implemented for handling negative values in index for
3d arrays, to give the same behavior as slicing
"""
string_index = [':']*3
string_index[self.last_dim] = '<font color=red>%i</font>'
self.slicing_label.setText((r"Slicing: [" + ", ".join(string_index) +
"]") % index)
if index < 0:
data_index = self.data.shape[self.last_dim] + index
else:
data_index = index
slice_index = [slice(None)]*3
slice_index[self.last_dim] = data_index
stack_index = self.dim_indexes[self.last_dim].get(data_index)
if stack_index is None:
stack_index = self.stack.count()
try:
self.stack.addWidget(ArrayEditorWidget(
self, self.data[tuple(slice_index)]))
except IndexError: # Handle arrays of size 0 in one axis
self.stack.addWidget(ArrayEditorWidget(self, self.data))
self.dim_indexes[self.last_dim][data_index] = stack_index
self.stack.update()
self.stack.setCurrentIndex(stack_index) | [
"def",
"change_active_widget",
"(",
"self",
",",
"index",
")",
":",
"string_index",
"=",
"[",
"':'",
"]",
"*",
"3",
"string_index",
"[",
"self",
".",
"last_dim",
"]",
"=",
"'<font color=red>%i</font>'",
"self",
".",
"slicing_label",
".",
"setText",
"(",
"(",
"r\"Slicing: [\"",
"+",
"\", \"",
".",
"join",
"(",
"string_index",
")",
"+",
"\"]\"",
")",
"%",
"index",
")",
"if",
"index",
"<",
"0",
":",
"data_index",
"=",
"self",
".",
"data",
".",
"shape",
"[",
"self",
".",
"last_dim",
"]",
"+",
"index",
"else",
":",
"data_index",
"=",
"index",
"slice_index",
"=",
"[",
"slice",
"(",
"None",
")",
"]",
"*",
"3",
"slice_index",
"[",
"self",
".",
"last_dim",
"]",
"=",
"data_index",
"stack_index",
"=",
"self",
".",
"dim_indexes",
"[",
"self",
".",
"last_dim",
"]",
".",
"get",
"(",
"data_index",
")",
"if",
"stack_index",
"is",
"None",
":",
"stack_index",
"=",
"self",
".",
"stack",
".",
"count",
"(",
")",
"try",
":",
"self",
".",
"stack",
".",
"addWidget",
"(",
"ArrayEditorWidget",
"(",
"self",
",",
"self",
".",
"data",
"[",
"tuple",
"(",
"slice_index",
")",
"]",
")",
")",
"except",
"IndexError",
":",
"# Handle arrays of size 0 in one axis\r",
"self",
".",
"stack",
".",
"addWidget",
"(",
"ArrayEditorWidget",
"(",
"self",
",",
"self",
".",
"data",
")",
")",
"self",
".",
"dim_indexes",
"[",
"self",
".",
"last_dim",
"]",
"[",
"data_index",
"]",
"=",
"stack_index",
"self",
".",
"stack",
".",
"update",
"(",
")",
"self",
".",
"stack",
".",
"setCurrentIndex",
"(",
"stack_index",
")"
] | This is implemented for handling negative values in index for
3d arrays, to give the same behavior as slicing | [
"This",
"is",
"implemented",
"for",
"handling",
"negative",
"values",
"in",
"index",
"for",
"3d",
"arrays",
"to",
"give",
"the",
"same",
"behavior",
"as",
"slicing"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L775-L801 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/arrayeditor.py | ArrayEditor.current_dim_changed | def current_dim_changed(self, index):
"""
This change the active axis the array editor is plotting over
in 3D
"""
self.last_dim = index
string_size = ['%i']*3
string_size[index] = '<font color=red>%i</font>'
self.shape_label.setText(('Shape: (' + ', '.join(string_size) +
') ') % self.data.shape)
if self.index_spin.value() != 0:
self.index_spin.setValue(0)
else:
# this is done since if the value is currently 0 it does not emit
# currentIndexChanged(int)
self.change_active_widget(0)
self.index_spin.setRange(-self.data.shape[index],
self.data.shape[index]-1) | python | def current_dim_changed(self, index):
"""
This change the active axis the array editor is plotting over
in 3D
"""
self.last_dim = index
string_size = ['%i']*3
string_size[index] = '<font color=red>%i</font>'
self.shape_label.setText(('Shape: (' + ', '.join(string_size) +
') ') % self.data.shape)
if self.index_spin.value() != 0:
self.index_spin.setValue(0)
else:
# this is done since if the value is currently 0 it does not emit
# currentIndexChanged(int)
self.change_active_widget(0)
self.index_spin.setRange(-self.data.shape[index],
self.data.shape[index]-1) | [
"def",
"current_dim_changed",
"(",
"self",
",",
"index",
")",
":",
"self",
".",
"last_dim",
"=",
"index",
"string_size",
"=",
"[",
"'%i'",
"]",
"*",
"3",
"string_size",
"[",
"index",
"]",
"=",
"'<font color=red>%i</font>'",
"self",
".",
"shape_label",
".",
"setText",
"(",
"(",
"'Shape: ('",
"+",
"', '",
".",
"join",
"(",
"string_size",
")",
"+",
"') '",
")",
"%",
"self",
".",
"data",
".",
"shape",
")",
"if",
"self",
".",
"index_spin",
".",
"value",
"(",
")",
"!=",
"0",
":",
"self",
".",
"index_spin",
".",
"setValue",
"(",
"0",
")",
"else",
":",
"# this is done since if the value is currently 0 it does not emit\r",
"# currentIndexChanged(int)\r",
"self",
".",
"change_active_widget",
"(",
"0",
")",
"self",
".",
"index_spin",
".",
"setRange",
"(",
"-",
"self",
".",
"data",
".",
"shape",
"[",
"index",
"]",
",",
"self",
".",
"data",
".",
"shape",
"[",
"index",
"]",
"-",
"1",
")"
] | This change the active axis the array editor is plotting over
in 3D | [
"This",
"change",
"the",
"active",
"axis",
"the",
"array",
"editor",
"is",
"plotting",
"over",
"in",
"3D"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L803-L820 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/arrayeditor.py | ArrayEditor.accept | def accept(self):
"""Reimplement Qt method"""
for index in range(self.stack.count()):
self.stack.widget(index).accept_changes()
QDialog.accept(self) | python | def accept(self):
"""Reimplement Qt method"""
for index in range(self.stack.count()):
self.stack.widget(index).accept_changes()
QDialog.accept(self) | [
"def",
"accept",
"(",
"self",
")",
":",
"for",
"index",
"in",
"range",
"(",
"self",
".",
"stack",
".",
"count",
"(",
")",
")",
":",
"self",
".",
"stack",
".",
"widget",
"(",
"index",
")",
".",
"accept_changes",
"(",
")",
"QDialog",
".",
"accept",
"(",
"self",
")"
] | Reimplement Qt method | [
"Reimplement",
"Qt",
"method"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L823-L827 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/arrayeditor.py | ArrayEditor.error | def error(self, message):
"""An error occured, closing the dialog box"""
QMessageBox.critical(self, _("Array editor"), message)
self.setAttribute(Qt.WA_DeleteOnClose)
self.reject() | python | def error(self, message):
"""An error occured, closing the dialog box"""
QMessageBox.critical(self, _("Array editor"), message)
self.setAttribute(Qt.WA_DeleteOnClose)
self.reject() | [
"def",
"error",
"(",
"self",
",",
"message",
")",
":",
"QMessageBox",
".",
"critical",
"(",
"self",
",",
"_",
"(",
"\"Array editor\"",
")",
",",
"message",
")",
"self",
".",
"setAttribute",
"(",
"Qt",
".",
"WA_DeleteOnClose",
")",
"self",
".",
"reject",
"(",
")"
] | An error occured, closing the dialog box | [
"An",
"error",
"occured",
"closing",
"the",
"dialog",
"box"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L835-L839 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/arrayeditor.py | ArrayEditor.reject | def reject(self):
"""Reimplement Qt method"""
if self.arraywidget is not None:
for index in range(self.stack.count()):
self.stack.widget(index).reject_changes()
QDialog.reject(self) | python | def reject(self):
"""Reimplement Qt method"""
if self.arraywidget is not None:
for index in range(self.stack.count()):
self.stack.widget(index).reject_changes()
QDialog.reject(self) | [
"def",
"reject",
"(",
"self",
")",
":",
"if",
"self",
".",
"arraywidget",
"is",
"not",
"None",
":",
"for",
"index",
"in",
"range",
"(",
"self",
".",
"stack",
".",
"count",
"(",
")",
")",
":",
"self",
".",
"stack",
".",
"widget",
"(",
"index",
")",
".",
"reject_changes",
"(",
")",
"QDialog",
".",
"reject",
"(",
"self",
")"
] | Reimplement Qt method | [
"Reimplement",
"Qt",
"method"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L842-L847 | train |
spyder-ide/spyder | spyder/utils/introspection/utils.py | find_lexer_for_filename | def find_lexer_for_filename(filename):
"""Get a Pygments Lexer given a filename.
"""
filename = filename or ''
root, ext = os.path.splitext(filename)
if ext in custom_extension_lexer_mapping:
lexer = get_lexer_by_name(custom_extension_lexer_mapping[ext])
else:
try:
lexer = get_lexer_for_filename(filename)
except Exception:
return TextLexer()
return lexer | python | def find_lexer_for_filename(filename):
"""Get a Pygments Lexer given a filename.
"""
filename = filename or ''
root, ext = os.path.splitext(filename)
if ext in custom_extension_lexer_mapping:
lexer = get_lexer_by_name(custom_extension_lexer_mapping[ext])
else:
try:
lexer = get_lexer_for_filename(filename)
except Exception:
return TextLexer()
return lexer | [
"def",
"find_lexer_for_filename",
"(",
"filename",
")",
":",
"filename",
"=",
"filename",
"or",
"''",
"root",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"if",
"ext",
"in",
"custom_extension_lexer_mapping",
":",
"lexer",
"=",
"get_lexer_by_name",
"(",
"custom_extension_lexer_mapping",
"[",
"ext",
"]",
")",
"else",
":",
"try",
":",
"lexer",
"=",
"get_lexer_for_filename",
"(",
"filename",
")",
"except",
"Exception",
":",
"return",
"TextLexer",
"(",
")",
"return",
"lexer"
] | Get a Pygments Lexer given a filename. | [
"Get",
"a",
"Pygments",
"Lexer",
"given",
"a",
"filename",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/introspection/utils.py#L169-L181 | train |
spyder-ide/spyder | spyder/utils/introspection/utils.py | get_keywords | def get_keywords(lexer):
"""Get the keywords for a given lexer.
"""
if not hasattr(lexer, 'tokens'):
return []
if 'keywords' in lexer.tokens:
try:
return lexer.tokens['keywords'][0][0].words
except:
pass
keywords = []
for vals in lexer.tokens.values():
for val in vals:
try:
if isinstance(val[0], words):
keywords.extend(val[0].words)
else:
ini_val = val[0]
if ')\\b' in val[0] or ')(\\s+)' in val[0]:
val = re.sub(r'\\.', '', val[0])
val = re.sub(r'[^0-9a-zA-Z|]+', '', val)
if '|' in ini_val:
keywords.extend(val.split('|'))
else:
keywords.append(val)
except Exception:
continue
return keywords | python | def get_keywords(lexer):
"""Get the keywords for a given lexer.
"""
if not hasattr(lexer, 'tokens'):
return []
if 'keywords' in lexer.tokens:
try:
return lexer.tokens['keywords'][0][0].words
except:
pass
keywords = []
for vals in lexer.tokens.values():
for val in vals:
try:
if isinstance(val[0], words):
keywords.extend(val[0].words)
else:
ini_val = val[0]
if ')\\b' in val[0] or ')(\\s+)' in val[0]:
val = re.sub(r'\\.', '', val[0])
val = re.sub(r'[^0-9a-zA-Z|]+', '', val)
if '|' in ini_val:
keywords.extend(val.split('|'))
else:
keywords.append(val)
except Exception:
continue
return keywords | [
"def",
"get_keywords",
"(",
"lexer",
")",
":",
"if",
"not",
"hasattr",
"(",
"lexer",
",",
"'tokens'",
")",
":",
"return",
"[",
"]",
"if",
"'keywords'",
"in",
"lexer",
".",
"tokens",
":",
"try",
":",
"return",
"lexer",
".",
"tokens",
"[",
"'keywords'",
"]",
"[",
"0",
"]",
"[",
"0",
"]",
".",
"words",
"except",
":",
"pass",
"keywords",
"=",
"[",
"]",
"for",
"vals",
"in",
"lexer",
".",
"tokens",
".",
"values",
"(",
")",
":",
"for",
"val",
"in",
"vals",
":",
"try",
":",
"if",
"isinstance",
"(",
"val",
"[",
"0",
"]",
",",
"words",
")",
":",
"keywords",
".",
"extend",
"(",
"val",
"[",
"0",
"]",
".",
"words",
")",
"else",
":",
"ini_val",
"=",
"val",
"[",
"0",
"]",
"if",
"')\\\\b'",
"in",
"val",
"[",
"0",
"]",
"or",
"')(\\\\s+)'",
"in",
"val",
"[",
"0",
"]",
":",
"val",
"=",
"re",
".",
"sub",
"(",
"r'\\\\.'",
",",
"''",
",",
"val",
"[",
"0",
"]",
")",
"val",
"=",
"re",
".",
"sub",
"(",
"r'[^0-9a-zA-Z|]+'",
",",
"''",
",",
"val",
")",
"if",
"'|'",
"in",
"ini_val",
":",
"keywords",
".",
"extend",
"(",
"val",
".",
"split",
"(",
"'|'",
")",
")",
"else",
":",
"keywords",
".",
"append",
"(",
"val",
")",
"except",
"Exception",
":",
"continue",
"return",
"keywords"
] | Get the keywords for a given lexer. | [
"Get",
"the",
"keywords",
"for",
"a",
"given",
"lexer",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/introspection/utils.py#L184-L211 | train |
spyder-ide/spyder | spyder/utils/introspection/utils.py | get_words | def get_words(file_path=None, content=None, extension=None):
"""
Extract all words from a source code file to be used in code completion.
Extract the list of words that contains the file in the editor,
to carry out the inline completion similar to VSCode.
"""
if (file_path is None and (content is None or extension is None) or
file_path and content and extension):
error_msg = ('Must provide `file_path` or `content` and `extension`')
raise Exception(error_msg)
if file_path and content is None and extension is None:
extension = os.path.splitext(file_path)[1]
with open(file_path) as infile:
content = infile.read()
if extension in ['.css']:
regex = re.compile(r'([^a-zA-Z-])')
elif extension in ['.R', '.c', '.md', '.cpp', '.java', '.py']:
regex = re.compile(r'([^a-zA-Z_])')
else:
regex = re.compile(r'([^a-zA-Z])')
words = sorted(set(regex.sub(r' ', content).split()))
return words | python | def get_words(file_path=None, content=None, extension=None):
"""
Extract all words from a source code file to be used in code completion.
Extract the list of words that contains the file in the editor,
to carry out the inline completion similar to VSCode.
"""
if (file_path is None and (content is None or extension is None) or
file_path and content and extension):
error_msg = ('Must provide `file_path` or `content` and `extension`')
raise Exception(error_msg)
if file_path and content is None and extension is None:
extension = os.path.splitext(file_path)[1]
with open(file_path) as infile:
content = infile.read()
if extension in ['.css']:
regex = re.compile(r'([^a-zA-Z-])')
elif extension in ['.R', '.c', '.md', '.cpp', '.java', '.py']:
regex = re.compile(r'([^a-zA-Z_])')
else:
regex = re.compile(r'([^a-zA-Z])')
words = sorted(set(regex.sub(r' ', content).split()))
return words | [
"def",
"get_words",
"(",
"file_path",
"=",
"None",
",",
"content",
"=",
"None",
",",
"extension",
"=",
"None",
")",
":",
"if",
"(",
"file_path",
"is",
"None",
"and",
"(",
"content",
"is",
"None",
"or",
"extension",
"is",
"None",
")",
"or",
"file_path",
"and",
"content",
"and",
"extension",
")",
":",
"error_msg",
"=",
"(",
"'Must provide `file_path` or `content` and `extension`'",
")",
"raise",
"Exception",
"(",
"error_msg",
")",
"if",
"file_path",
"and",
"content",
"is",
"None",
"and",
"extension",
"is",
"None",
":",
"extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"file_path",
")",
"[",
"1",
"]",
"with",
"open",
"(",
"file_path",
")",
"as",
"infile",
":",
"content",
"=",
"infile",
".",
"read",
"(",
")",
"if",
"extension",
"in",
"[",
"'.css'",
"]",
":",
"regex",
"=",
"re",
".",
"compile",
"(",
"r'([^a-zA-Z-])'",
")",
"elif",
"extension",
"in",
"[",
"'.R'",
",",
"'.c'",
",",
"'.md'",
",",
"'.cpp'",
",",
"'.java'",
",",
"'.py'",
"]",
":",
"regex",
"=",
"re",
".",
"compile",
"(",
"r'([^a-zA-Z_])'",
")",
"else",
":",
"regex",
"=",
"re",
".",
"compile",
"(",
"r'([^a-zA-Z])'",
")",
"words",
"=",
"sorted",
"(",
"set",
"(",
"regex",
".",
"sub",
"(",
"r' '",
",",
"content",
")",
".",
"split",
"(",
")",
")",
")",
"return",
"words"
] | Extract all words from a source code file to be used in code completion.
Extract the list of words that contains the file in the editor,
to carry out the inline completion similar to VSCode. | [
"Extract",
"all",
"words",
"from",
"a",
"source",
"code",
"file",
"to",
"be",
"used",
"in",
"code",
"completion",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/introspection/utils.py#L213-L238 | train |
spyder-ide/spyder | spyder/utils/introspection/utils.py | get_parent_until | def get_parent_until(path):
"""
Given a file path, determine the full module path.
e.g. '/usr/lib/python2.7/dist-packages/numpy/core/__init__.pyc' yields
'numpy.core'
"""
dirname = osp.dirname(path)
try:
mod = osp.basename(path)
mod = osp.splitext(mod)[0]
imp.find_module(mod, [dirname])
except ImportError:
return
items = [mod]
while 1:
items.append(osp.basename(dirname))
try:
dirname = osp.dirname(dirname)
imp.find_module('__init__', [dirname + os.sep])
except ImportError:
break
return '.'.join(reversed(items)) | python | def get_parent_until(path):
"""
Given a file path, determine the full module path.
e.g. '/usr/lib/python2.7/dist-packages/numpy/core/__init__.pyc' yields
'numpy.core'
"""
dirname = osp.dirname(path)
try:
mod = osp.basename(path)
mod = osp.splitext(mod)[0]
imp.find_module(mod, [dirname])
except ImportError:
return
items = [mod]
while 1:
items.append(osp.basename(dirname))
try:
dirname = osp.dirname(dirname)
imp.find_module('__init__', [dirname + os.sep])
except ImportError:
break
return '.'.join(reversed(items)) | [
"def",
"get_parent_until",
"(",
"path",
")",
":",
"dirname",
"=",
"osp",
".",
"dirname",
"(",
"path",
")",
"try",
":",
"mod",
"=",
"osp",
".",
"basename",
"(",
"path",
")",
"mod",
"=",
"osp",
".",
"splitext",
"(",
"mod",
")",
"[",
"0",
"]",
"imp",
".",
"find_module",
"(",
"mod",
",",
"[",
"dirname",
"]",
")",
"except",
"ImportError",
":",
"return",
"items",
"=",
"[",
"mod",
"]",
"while",
"1",
":",
"items",
".",
"append",
"(",
"osp",
".",
"basename",
"(",
"dirname",
")",
")",
"try",
":",
"dirname",
"=",
"osp",
".",
"dirname",
"(",
"dirname",
")",
"imp",
".",
"find_module",
"(",
"'__init__'",
",",
"[",
"dirname",
"+",
"os",
".",
"sep",
"]",
")",
"except",
"ImportError",
":",
"break",
"return",
"'.'",
".",
"join",
"(",
"reversed",
"(",
"items",
")",
")"
] | Given a file path, determine the full module path.
e.g. '/usr/lib/python2.7/dist-packages/numpy/core/__init__.pyc' yields
'numpy.core' | [
"Given",
"a",
"file",
"path",
"determine",
"the",
"full",
"module",
"path",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/introspection/utils.py#L241-L263 | train |
spyder-ide/spyder | spyder/utils/introspection/utils.py | CodeInfo._get_docstring | def _get_docstring(self):
"""Find the docstring we are currently in."""
left = self.position
while left:
if self.source_code[left: left + 3] in ['"""', "'''"]:
left += 3
break
left -= 1
right = self.position
while right < len(self.source_code):
if self.source_code[right - 3: right] in ['"""', "'''"]:
right -= 3
break
right += 1
if left and right < len(self.source_code):
return self.source_code[left: right]
return '' | python | def _get_docstring(self):
"""Find the docstring we are currently in."""
left = self.position
while left:
if self.source_code[left: left + 3] in ['"""', "'''"]:
left += 3
break
left -= 1
right = self.position
while right < len(self.source_code):
if self.source_code[right - 3: right] in ['"""', "'''"]:
right -= 3
break
right += 1
if left and right < len(self.source_code):
return self.source_code[left: right]
return '' | [
"def",
"_get_docstring",
"(",
"self",
")",
":",
"left",
"=",
"self",
".",
"position",
"while",
"left",
":",
"if",
"self",
".",
"source_code",
"[",
"left",
":",
"left",
"+",
"3",
"]",
"in",
"[",
"'\"\"\"'",
",",
"\"'''\"",
"]",
":",
"left",
"+=",
"3",
"break",
"left",
"-=",
"1",
"right",
"=",
"self",
".",
"position",
"while",
"right",
"<",
"len",
"(",
"self",
".",
"source_code",
")",
":",
"if",
"self",
".",
"source_code",
"[",
"right",
"-",
"3",
":",
"right",
"]",
"in",
"[",
"'\"\"\"'",
",",
"\"'''\"",
"]",
":",
"right",
"-=",
"3",
"break",
"right",
"+=",
"1",
"if",
"left",
"and",
"right",
"<",
"len",
"(",
"self",
".",
"source_code",
")",
":",
"return",
"self",
".",
"source_code",
"[",
"left",
":",
"right",
"]",
"return",
"''"
] | Find the docstring we are currently in. | [
"Find",
"the",
"docstring",
"we",
"are",
"currently",
"in",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/introspection/utils.py#L128-L144 | train |
spyder-ide/spyder | spyder/plugins/ipythonconsole/widgets/kernelconnect.py | KernelConnectionDialog.load_connection_settings | def load_connection_settings(self):
"""Load the user's previously-saved kernel connection settings."""
existing_kernel = CONF.get("existing-kernel", "settings", {})
connection_file_path = existing_kernel.get("json_file_path", "")
is_remote = existing_kernel.get("is_remote", False)
username = existing_kernel.get("username", "")
hostname = existing_kernel.get("hostname", "")
port = str(existing_kernel.get("port", 22))
is_ssh_kf = existing_kernel.get("is_ssh_keyfile", False)
ssh_kf = existing_kernel.get("ssh_key_file_path", "")
if connection_file_path != "":
self.cf.setText(connection_file_path)
if username != "":
self.un.setText(username)
if hostname != "":
self.hn.setText(hostname)
if ssh_kf != "":
self.kf.setText(ssh_kf)
self.rm_group.setChecked(is_remote)
self.pn.setText(port)
self.kf_radio.setChecked(is_ssh_kf)
self.pw_radio.setChecked(not is_ssh_kf)
try:
import keyring
ssh_passphrase = keyring.get_password("spyder_remote_kernel",
"ssh_key_passphrase")
ssh_password = keyring.get_password("spyder_remote_kernel",
"ssh_password")
if ssh_passphrase:
self.kfp.setText(ssh_passphrase)
if ssh_password:
self.pw.setText(ssh_password)
except Exception:
pass | python | def load_connection_settings(self):
"""Load the user's previously-saved kernel connection settings."""
existing_kernel = CONF.get("existing-kernel", "settings", {})
connection_file_path = existing_kernel.get("json_file_path", "")
is_remote = existing_kernel.get("is_remote", False)
username = existing_kernel.get("username", "")
hostname = existing_kernel.get("hostname", "")
port = str(existing_kernel.get("port", 22))
is_ssh_kf = existing_kernel.get("is_ssh_keyfile", False)
ssh_kf = existing_kernel.get("ssh_key_file_path", "")
if connection_file_path != "":
self.cf.setText(connection_file_path)
if username != "":
self.un.setText(username)
if hostname != "":
self.hn.setText(hostname)
if ssh_kf != "":
self.kf.setText(ssh_kf)
self.rm_group.setChecked(is_remote)
self.pn.setText(port)
self.kf_radio.setChecked(is_ssh_kf)
self.pw_radio.setChecked(not is_ssh_kf)
try:
import keyring
ssh_passphrase = keyring.get_password("spyder_remote_kernel",
"ssh_key_passphrase")
ssh_password = keyring.get_password("spyder_remote_kernel",
"ssh_password")
if ssh_passphrase:
self.kfp.setText(ssh_passphrase)
if ssh_password:
self.pw.setText(ssh_password)
except Exception:
pass | [
"def",
"load_connection_settings",
"(",
"self",
")",
":",
"existing_kernel",
"=",
"CONF",
".",
"get",
"(",
"\"existing-kernel\"",
",",
"\"settings\"",
",",
"{",
"}",
")",
"connection_file_path",
"=",
"existing_kernel",
".",
"get",
"(",
"\"json_file_path\"",
",",
"\"\"",
")",
"is_remote",
"=",
"existing_kernel",
".",
"get",
"(",
"\"is_remote\"",
",",
"False",
")",
"username",
"=",
"existing_kernel",
".",
"get",
"(",
"\"username\"",
",",
"\"\"",
")",
"hostname",
"=",
"existing_kernel",
".",
"get",
"(",
"\"hostname\"",
",",
"\"\"",
")",
"port",
"=",
"str",
"(",
"existing_kernel",
".",
"get",
"(",
"\"port\"",
",",
"22",
")",
")",
"is_ssh_kf",
"=",
"existing_kernel",
".",
"get",
"(",
"\"is_ssh_keyfile\"",
",",
"False",
")",
"ssh_kf",
"=",
"existing_kernel",
".",
"get",
"(",
"\"ssh_key_file_path\"",
",",
"\"\"",
")",
"if",
"connection_file_path",
"!=",
"\"\"",
":",
"self",
".",
"cf",
".",
"setText",
"(",
"connection_file_path",
")",
"if",
"username",
"!=",
"\"\"",
":",
"self",
".",
"un",
".",
"setText",
"(",
"username",
")",
"if",
"hostname",
"!=",
"\"\"",
":",
"self",
".",
"hn",
".",
"setText",
"(",
"hostname",
")",
"if",
"ssh_kf",
"!=",
"\"\"",
":",
"self",
".",
"kf",
".",
"setText",
"(",
"ssh_kf",
")",
"self",
".",
"rm_group",
".",
"setChecked",
"(",
"is_remote",
")",
"self",
".",
"pn",
".",
"setText",
"(",
"port",
")",
"self",
".",
"kf_radio",
".",
"setChecked",
"(",
"is_ssh_kf",
")",
"self",
".",
"pw_radio",
".",
"setChecked",
"(",
"not",
"is_ssh_kf",
")",
"try",
":",
"import",
"keyring",
"ssh_passphrase",
"=",
"keyring",
".",
"get_password",
"(",
"\"spyder_remote_kernel\"",
",",
"\"ssh_key_passphrase\"",
")",
"ssh_password",
"=",
"keyring",
".",
"get_password",
"(",
"\"spyder_remote_kernel\"",
",",
"\"ssh_password\"",
")",
"if",
"ssh_passphrase",
":",
"self",
".",
"kfp",
".",
"setText",
"(",
"ssh_passphrase",
")",
"if",
"ssh_password",
":",
"self",
".",
"pw",
".",
"setText",
"(",
"ssh_password",
")",
"except",
"Exception",
":",
"pass"
] | Load the user's previously-saved kernel connection settings. | [
"Load",
"the",
"user",
"s",
"previously",
"-",
"saved",
"kernel",
"connection",
"settings",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/kernelconnect.py#L164-L200 | train |
spyder-ide/spyder | spyder/plugins/ipythonconsole/widgets/kernelconnect.py | KernelConnectionDialog.save_connection_settings | def save_connection_settings(self):
"""Save user's kernel connection settings."""
if not self.save_layout.isChecked():
return
is_ssh_key = bool(self.kf_radio.isChecked())
connection_settings = {
"json_file_path": self.cf.text(),
"is_remote": self.rm_group.isChecked(),
"username": self.un.text(),
"hostname": self.hn.text(),
"port": self.pn.text(),
"is_ssh_keyfile": is_ssh_key,
"ssh_key_file_path": self.kf.text()
}
CONF.set("existing-kernel", "settings", connection_settings)
try:
import keyring
if is_ssh_key:
keyring.set_password("spyder_remote_kernel",
"ssh_key_passphrase",
self.kfp.text())
else:
keyring.set_password("spyder_remote_kernel",
"ssh_password",
self.pw.text())
except Exception:
pass | python | def save_connection_settings(self):
"""Save user's kernel connection settings."""
if not self.save_layout.isChecked():
return
is_ssh_key = bool(self.kf_radio.isChecked())
connection_settings = {
"json_file_path": self.cf.text(),
"is_remote": self.rm_group.isChecked(),
"username": self.un.text(),
"hostname": self.hn.text(),
"port": self.pn.text(),
"is_ssh_keyfile": is_ssh_key,
"ssh_key_file_path": self.kf.text()
}
CONF.set("existing-kernel", "settings", connection_settings)
try:
import keyring
if is_ssh_key:
keyring.set_password("spyder_remote_kernel",
"ssh_key_passphrase",
self.kfp.text())
else:
keyring.set_password("spyder_remote_kernel",
"ssh_password",
self.pw.text())
except Exception:
pass | [
"def",
"save_connection_settings",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"save_layout",
".",
"isChecked",
"(",
")",
":",
"return",
"is_ssh_key",
"=",
"bool",
"(",
"self",
".",
"kf_radio",
".",
"isChecked",
"(",
")",
")",
"connection_settings",
"=",
"{",
"\"json_file_path\"",
":",
"self",
".",
"cf",
".",
"text",
"(",
")",
",",
"\"is_remote\"",
":",
"self",
".",
"rm_group",
".",
"isChecked",
"(",
")",
",",
"\"username\"",
":",
"self",
".",
"un",
".",
"text",
"(",
")",
",",
"\"hostname\"",
":",
"self",
".",
"hn",
".",
"text",
"(",
")",
",",
"\"port\"",
":",
"self",
".",
"pn",
".",
"text",
"(",
")",
",",
"\"is_ssh_keyfile\"",
":",
"is_ssh_key",
",",
"\"ssh_key_file_path\"",
":",
"self",
".",
"kf",
".",
"text",
"(",
")",
"}",
"CONF",
".",
"set",
"(",
"\"existing-kernel\"",
",",
"\"settings\"",
",",
"connection_settings",
")",
"try",
":",
"import",
"keyring",
"if",
"is_ssh_key",
":",
"keyring",
".",
"set_password",
"(",
"\"spyder_remote_kernel\"",
",",
"\"ssh_key_passphrase\"",
",",
"self",
".",
"kfp",
".",
"text",
"(",
")",
")",
"else",
":",
"keyring",
".",
"set_password",
"(",
"\"spyder_remote_kernel\"",
",",
"\"ssh_password\"",
",",
"self",
".",
"pw",
".",
"text",
"(",
")",
")",
"except",
"Exception",
":",
"pass"
] | Save user's kernel connection settings. | [
"Save",
"user",
"s",
"kernel",
"connection",
"settings",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/kernelconnect.py#L202-L231 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/importwizard.py | get_color | def get_color(value, alpha):
"""Return color depending on value type"""
color = QColor()
for typ in COLORS:
if isinstance(value, typ):
color = QColor(COLORS[typ])
color.setAlphaF(alpha)
return color | python | def get_color(value, alpha):
"""Return color depending on value type"""
color = QColor()
for typ in COLORS:
if isinstance(value, typ):
color = QColor(COLORS[typ])
color.setAlphaF(alpha)
return color | [
"def",
"get_color",
"(",
"value",
",",
"alpha",
")",
":",
"color",
"=",
"QColor",
"(",
")",
"for",
"typ",
"in",
"COLORS",
":",
"if",
"isinstance",
"(",
"value",
",",
"typ",
")",
":",
"color",
"=",
"QColor",
"(",
"COLORS",
"[",
"typ",
"]",
")",
"color",
".",
"setAlphaF",
"(",
"alpha",
")",
"return",
"color"
] | Return color depending on value type | [
"Return",
"color",
"depending",
"on",
"value",
"type"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/importwizard.py#L96-L103 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/importwizard.py | ContentsWidget.get_col_sep | def get_col_sep(self):
"""Return the column separator"""
if self.tab_btn.isChecked():
return u"\t"
elif self.ws_btn.isChecked():
return None
return to_text_string(self.line_edt.text()) | python | def get_col_sep(self):
"""Return the column separator"""
if self.tab_btn.isChecked():
return u"\t"
elif self.ws_btn.isChecked():
return None
return to_text_string(self.line_edt.text()) | [
"def",
"get_col_sep",
"(",
"self",
")",
":",
"if",
"self",
".",
"tab_btn",
".",
"isChecked",
"(",
")",
":",
"return",
"u\"\\t\"",
"elif",
"self",
".",
"ws_btn",
".",
"isChecked",
"(",
")",
":",
"return",
"None",
"return",
"to_text_string",
"(",
"self",
".",
"line_edt",
".",
"text",
"(",
")",
")"
] | Return the column separator | [
"Return",
"the",
"column",
"separator"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/importwizard.py#L236-L242 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/importwizard.py | ContentsWidget.get_row_sep | def get_row_sep(self):
"""Return the row separator"""
if self.eol_btn.isChecked():
return u"\n"
return to_text_string(self.line_edt_row.text()) | python | def get_row_sep(self):
"""Return the row separator"""
if self.eol_btn.isChecked():
return u"\n"
return to_text_string(self.line_edt_row.text()) | [
"def",
"get_row_sep",
"(",
"self",
")",
":",
"if",
"self",
".",
"eol_btn",
".",
"isChecked",
"(",
")",
":",
"return",
"u\"\\n\"",
"return",
"to_text_string",
"(",
"self",
".",
"line_edt_row",
".",
"text",
"(",
")",
")"
] | Return the row separator | [
"Return",
"the",
"row",
"separator"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/importwizard.py#L244-L248 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/importwizard.py | ContentsWidget.set_as_data | def set_as_data(self, as_data):
"""Set if data type conversion"""
self._as_data = as_data
self.asDataChanged.emit(as_data) | python | def set_as_data(self, as_data):
"""Set if data type conversion"""
self._as_data = as_data
self.asDataChanged.emit(as_data) | [
"def",
"set_as_data",
"(",
"self",
",",
"as_data",
")",
":",
"self",
".",
"_as_data",
"=",
"as_data",
"self",
".",
"asDataChanged",
".",
"emit",
"(",
"as_data",
")"
] | Set if data type conversion | [
"Set",
"if",
"data",
"type",
"conversion"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/importwizard.py#L259-L262 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/importwizard.py | PreviewTableModel._display_data | def _display_data(self, index):
"""Return a data element"""
return to_qvariant(self._data[index.row()][index.column()]) | python | def _display_data(self, index):
"""Return a data element"""
return to_qvariant(self._data[index.row()][index.column()]) | [
"def",
"_display_data",
"(",
"self",
",",
"index",
")",
":",
"return",
"to_qvariant",
"(",
"self",
".",
"_data",
"[",
"index",
".",
"row",
"(",
")",
"]",
"[",
"index",
".",
"column",
"(",
")",
"]",
")"
] | Return a data element | [
"Return",
"a",
"data",
"element"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/importwizard.py#L284-L286 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/importwizard.py | PreviewTableModel.data | def data(self, index, role=Qt.DisplayRole):
"""Return a model data element"""
if not index.isValid():
return to_qvariant()
if role == Qt.DisplayRole:
return self._display_data(index)
elif role == Qt.BackgroundColorRole:
return to_qvariant(get_color(self._data[index.row()][index.column()], .2))
elif role == Qt.TextAlignmentRole:
return to_qvariant(int(Qt.AlignRight|Qt.AlignVCenter))
return to_qvariant() | python | def data(self, index, role=Qt.DisplayRole):
"""Return a model data element"""
if not index.isValid():
return to_qvariant()
if role == Qt.DisplayRole:
return self._display_data(index)
elif role == Qt.BackgroundColorRole:
return to_qvariant(get_color(self._data[index.row()][index.column()], .2))
elif role == Qt.TextAlignmentRole:
return to_qvariant(int(Qt.AlignRight|Qt.AlignVCenter))
return to_qvariant() | [
"def",
"data",
"(",
"self",
",",
"index",
",",
"role",
"=",
"Qt",
".",
"DisplayRole",
")",
":",
"if",
"not",
"index",
".",
"isValid",
"(",
")",
":",
"return",
"to_qvariant",
"(",
")",
"if",
"role",
"==",
"Qt",
".",
"DisplayRole",
":",
"return",
"self",
".",
"_display_data",
"(",
"index",
")",
"elif",
"role",
"==",
"Qt",
".",
"BackgroundColorRole",
":",
"return",
"to_qvariant",
"(",
"get_color",
"(",
"self",
".",
"_data",
"[",
"index",
".",
"row",
"(",
")",
"]",
"[",
"index",
".",
"column",
"(",
")",
"]",
",",
".2",
")",
")",
"elif",
"role",
"==",
"Qt",
".",
"TextAlignmentRole",
":",
"return",
"to_qvariant",
"(",
"int",
"(",
"Qt",
".",
"AlignRight",
"|",
"Qt",
".",
"AlignVCenter",
")",
")",
"return",
"to_qvariant",
"(",
")"
] | Return a model data element | [
"Return",
"a",
"model",
"data",
"element"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/importwizard.py#L288-L298 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/importwizard.py | PreviewTableModel.parse_data_type | def parse_data_type(self, index, **kwargs):
"""Parse a type to an other type"""
if not index.isValid():
return False
try:
if kwargs['atype'] == "date":
self._data[index.row()][index.column()] = \
datestr_to_datetime(self._data[index.row()][index.column()],
kwargs['dayfirst']).date()
elif kwargs['atype'] == "perc":
_tmp = self._data[index.row()][index.column()].replace("%", "")
self._data[index.row()][index.column()] = eval(_tmp)/100.
elif kwargs['atype'] == "account":
_tmp = self._data[index.row()][index.column()].replace(",", "")
self._data[index.row()][index.column()] = eval(_tmp)
elif kwargs['atype'] == "unicode":
self._data[index.row()][index.column()] = to_text_string(
self._data[index.row()][index.column()])
elif kwargs['atype'] == "int":
self._data[index.row()][index.column()] = int(
self._data[index.row()][index.column()])
elif kwargs['atype'] == "float":
self._data[index.row()][index.column()] = float(
self._data[index.row()][index.column()])
self.dataChanged.emit(index, index)
except Exception as instance:
print(instance) | python | def parse_data_type(self, index, **kwargs):
"""Parse a type to an other type"""
if not index.isValid():
return False
try:
if kwargs['atype'] == "date":
self._data[index.row()][index.column()] = \
datestr_to_datetime(self._data[index.row()][index.column()],
kwargs['dayfirst']).date()
elif kwargs['atype'] == "perc":
_tmp = self._data[index.row()][index.column()].replace("%", "")
self._data[index.row()][index.column()] = eval(_tmp)/100.
elif kwargs['atype'] == "account":
_tmp = self._data[index.row()][index.column()].replace(",", "")
self._data[index.row()][index.column()] = eval(_tmp)
elif kwargs['atype'] == "unicode":
self._data[index.row()][index.column()] = to_text_string(
self._data[index.row()][index.column()])
elif kwargs['atype'] == "int":
self._data[index.row()][index.column()] = int(
self._data[index.row()][index.column()])
elif kwargs['atype'] == "float":
self._data[index.row()][index.column()] = float(
self._data[index.row()][index.column()])
self.dataChanged.emit(index, index)
except Exception as instance:
print(instance) | [
"def",
"parse_data_type",
"(",
"self",
",",
"index",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"index",
".",
"isValid",
"(",
")",
":",
"return",
"False",
"try",
":",
"if",
"kwargs",
"[",
"'atype'",
"]",
"==",
"\"date\"",
":",
"self",
".",
"_data",
"[",
"index",
".",
"row",
"(",
")",
"]",
"[",
"index",
".",
"column",
"(",
")",
"]",
"=",
"datestr_to_datetime",
"(",
"self",
".",
"_data",
"[",
"index",
".",
"row",
"(",
")",
"]",
"[",
"index",
".",
"column",
"(",
")",
"]",
",",
"kwargs",
"[",
"'dayfirst'",
"]",
")",
".",
"date",
"(",
")",
"elif",
"kwargs",
"[",
"'atype'",
"]",
"==",
"\"perc\"",
":",
"_tmp",
"=",
"self",
".",
"_data",
"[",
"index",
".",
"row",
"(",
")",
"]",
"[",
"index",
".",
"column",
"(",
")",
"]",
".",
"replace",
"(",
"\"%\"",
",",
"\"\"",
")",
"self",
".",
"_data",
"[",
"index",
".",
"row",
"(",
")",
"]",
"[",
"index",
".",
"column",
"(",
")",
"]",
"=",
"eval",
"(",
"_tmp",
")",
"/",
"100.",
"elif",
"kwargs",
"[",
"'atype'",
"]",
"==",
"\"account\"",
":",
"_tmp",
"=",
"self",
".",
"_data",
"[",
"index",
".",
"row",
"(",
")",
"]",
"[",
"index",
".",
"column",
"(",
")",
"]",
".",
"replace",
"(",
"\",\"",
",",
"\"\"",
")",
"self",
".",
"_data",
"[",
"index",
".",
"row",
"(",
")",
"]",
"[",
"index",
".",
"column",
"(",
")",
"]",
"=",
"eval",
"(",
"_tmp",
")",
"elif",
"kwargs",
"[",
"'atype'",
"]",
"==",
"\"unicode\"",
":",
"self",
".",
"_data",
"[",
"index",
".",
"row",
"(",
")",
"]",
"[",
"index",
".",
"column",
"(",
")",
"]",
"=",
"to_text_string",
"(",
"self",
".",
"_data",
"[",
"index",
".",
"row",
"(",
")",
"]",
"[",
"index",
".",
"column",
"(",
")",
"]",
")",
"elif",
"kwargs",
"[",
"'atype'",
"]",
"==",
"\"int\"",
":",
"self",
".",
"_data",
"[",
"index",
".",
"row",
"(",
")",
"]",
"[",
"index",
".",
"column",
"(",
")",
"]",
"=",
"int",
"(",
"self",
".",
"_data",
"[",
"index",
".",
"row",
"(",
")",
"]",
"[",
"index",
".",
"column",
"(",
")",
"]",
")",
"elif",
"kwargs",
"[",
"'atype'",
"]",
"==",
"\"float\"",
":",
"self",
".",
"_data",
"[",
"index",
".",
"row",
"(",
")",
"]",
"[",
"index",
".",
"column",
"(",
")",
"]",
"=",
"float",
"(",
"self",
".",
"_data",
"[",
"index",
".",
"row",
"(",
")",
"]",
"[",
"index",
".",
"column",
"(",
")",
"]",
")",
"self",
".",
"dataChanged",
".",
"emit",
"(",
"index",
",",
"index",
")",
"except",
"Exception",
"as",
"instance",
":",
"print",
"(",
"instance",
")"
] | Parse a type to an other type | [
"Parse",
"a",
"type",
"to",
"an",
"other",
"type"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/importwizard.py#L308-L334 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/importwizard.py | PreviewTable._shape_text | def _shape_text(self, text, colsep=u"\t", rowsep=u"\n",
transpose=False, skiprows=0, comments='#'):
"""Decode the shape of the given text"""
assert colsep != rowsep
out = []
text_rows = text.split(rowsep)[skiprows:]
for row in text_rows:
stripped = to_text_string(row).strip()
if len(stripped) == 0 or stripped.startswith(comments):
continue
line = to_text_string(row).split(colsep)
line = [try_to_parse(to_text_string(x)) for x in line]
out.append(line)
# Replace missing elements with np.nan's or None's
if programs.is_module_installed('numpy'):
from numpy import nan
out = list(zip_longest(*out, fillvalue=nan))
else:
out = list(zip_longest(*out, fillvalue=None))
# Tranpose the last result to get the expected one
out = [[r[col] for r in out] for col in range(len(out[0]))]
if transpose:
return [[r[col] for r in out] for col in range(len(out[0]))]
return out | python | def _shape_text(self, text, colsep=u"\t", rowsep=u"\n",
transpose=False, skiprows=0, comments='#'):
"""Decode the shape of the given text"""
assert colsep != rowsep
out = []
text_rows = text.split(rowsep)[skiprows:]
for row in text_rows:
stripped = to_text_string(row).strip()
if len(stripped) == 0 or stripped.startswith(comments):
continue
line = to_text_string(row).split(colsep)
line = [try_to_parse(to_text_string(x)) for x in line]
out.append(line)
# Replace missing elements with np.nan's or None's
if programs.is_module_installed('numpy'):
from numpy import nan
out = list(zip_longest(*out, fillvalue=nan))
else:
out = list(zip_longest(*out, fillvalue=None))
# Tranpose the last result to get the expected one
out = [[r[col] for r in out] for col in range(len(out[0]))]
if transpose:
return [[r[col] for r in out] for col in range(len(out[0]))]
return out | [
"def",
"_shape_text",
"(",
"self",
",",
"text",
",",
"colsep",
"=",
"u\"\\t\"",
",",
"rowsep",
"=",
"u\"\\n\"",
",",
"transpose",
"=",
"False",
",",
"skiprows",
"=",
"0",
",",
"comments",
"=",
"'#'",
")",
":",
"assert",
"colsep",
"!=",
"rowsep",
"out",
"=",
"[",
"]",
"text_rows",
"=",
"text",
".",
"split",
"(",
"rowsep",
")",
"[",
"skiprows",
":",
"]",
"for",
"row",
"in",
"text_rows",
":",
"stripped",
"=",
"to_text_string",
"(",
"row",
")",
".",
"strip",
"(",
")",
"if",
"len",
"(",
"stripped",
")",
"==",
"0",
"or",
"stripped",
".",
"startswith",
"(",
"comments",
")",
":",
"continue",
"line",
"=",
"to_text_string",
"(",
"row",
")",
".",
"split",
"(",
"colsep",
")",
"line",
"=",
"[",
"try_to_parse",
"(",
"to_text_string",
"(",
"x",
")",
")",
"for",
"x",
"in",
"line",
"]",
"out",
".",
"append",
"(",
"line",
")",
"# Replace missing elements with np.nan's or None's\r",
"if",
"programs",
".",
"is_module_installed",
"(",
"'numpy'",
")",
":",
"from",
"numpy",
"import",
"nan",
"out",
"=",
"list",
"(",
"zip_longest",
"(",
"*",
"out",
",",
"fillvalue",
"=",
"nan",
")",
")",
"else",
":",
"out",
"=",
"list",
"(",
"zip_longest",
"(",
"*",
"out",
",",
"fillvalue",
"=",
"None",
")",
")",
"# Tranpose the last result to get the expected one\r",
"out",
"=",
"[",
"[",
"r",
"[",
"col",
"]",
"for",
"r",
"in",
"out",
"]",
"for",
"col",
"in",
"range",
"(",
"len",
"(",
"out",
"[",
"0",
"]",
")",
")",
"]",
"if",
"transpose",
":",
"return",
"[",
"[",
"r",
"[",
"col",
"]",
"for",
"r",
"in",
"out",
"]",
"for",
"col",
"in",
"range",
"(",
"len",
"(",
"out",
"[",
"0",
"]",
")",
")",
"]",
"return",
"out"
] | Decode the shape of the given text | [
"Decode",
"the",
"shape",
"of",
"the",
"given",
"text"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/importwizard.py#L376-L399 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/importwizard.py | PreviewTable.process_data | def process_data(self, text, colsep=u"\t", rowsep=u"\n",
transpose=False, skiprows=0, comments='#'):
"""Put data into table model"""
data = self._shape_text(text, colsep, rowsep, transpose, skiprows,
comments)
self._model = PreviewTableModel(data)
self.setModel(self._model) | python | def process_data(self, text, colsep=u"\t", rowsep=u"\n",
transpose=False, skiprows=0, comments='#'):
"""Put data into table model"""
data = self._shape_text(text, colsep, rowsep, transpose, skiprows,
comments)
self._model = PreviewTableModel(data)
self.setModel(self._model) | [
"def",
"process_data",
"(",
"self",
",",
"text",
",",
"colsep",
"=",
"u\"\\t\"",
",",
"rowsep",
"=",
"u\"\\n\"",
",",
"transpose",
"=",
"False",
",",
"skiprows",
"=",
"0",
",",
"comments",
"=",
"'#'",
")",
":",
"data",
"=",
"self",
".",
"_shape_text",
"(",
"text",
",",
"colsep",
",",
"rowsep",
",",
"transpose",
",",
"skiprows",
",",
"comments",
")",
"self",
".",
"_model",
"=",
"PreviewTableModel",
"(",
"data",
")",
"self",
".",
"setModel",
"(",
"self",
".",
"_model",
")"
] | Put data into table model | [
"Put",
"data",
"into",
"table",
"model"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/importwizard.py#L407-L413 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/importwizard.py | PreviewTable.parse_to_type | def parse_to_type(self,**kwargs):
"""Parse to a given type"""
indexes = self.selectedIndexes()
if not indexes: return
for index in indexes:
self.model().parse_data_type(index, **kwargs) | python | def parse_to_type(self,**kwargs):
"""Parse to a given type"""
indexes = self.selectedIndexes()
if not indexes: return
for index in indexes:
self.model().parse_data_type(index, **kwargs) | [
"def",
"parse_to_type",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"indexes",
"=",
"self",
".",
"selectedIndexes",
"(",
")",
"if",
"not",
"indexes",
":",
"return",
"for",
"index",
"in",
"indexes",
":",
"self",
".",
"model",
"(",
")",
".",
"parse_data_type",
"(",
"index",
",",
"*",
"*",
"kwargs",
")"
] | Parse to a given type | [
"Parse",
"to",
"a",
"given",
"type"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/importwizard.py#L416-L421 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/importwizard.py | PreviewTable.contextMenuEvent | def contextMenuEvent(self, event):
"""Reimplement Qt method"""
self.opt_menu.popup(event.globalPos())
event.accept() | python | def contextMenuEvent(self, event):
"""Reimplement Qt method"""
self.opt_menu.popup(event.globalPos())
event.accept() | [
"def",
"contextMenuEvent",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"opt_menu",
".",
"popup",
"(",
"event",
".",
"globalPos",
"(",
")",
")",
"event",
".",
"accept",
"(",
")"
] | Reimplement Qt method | [
"Reimplement",
"Qt",
"method"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/importwizard.py#L423-L426 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/importwizard.py | PreviewWidget.open_data | def open_data(self, text, colsep=u"\t", rowsep=u"\n",
transpose=False, skiprows=0, comments='#'):
"""Open clipboard text as table"""
if pd:
self.pd_text = text
self.pd_info = dict(sep=colsep, lineterminator=rowsep,
skiprows=skiprows, comment=comments)
if colsep is None:
self.pd_info = dict(lineterminator=rowsep, skiprows=skiprows,
comment=comments, delim_whitespace=True)
self._table_view.process_data(text, colsep, rowsep, transpose,
skiprows, comments) | python | def open_data(self, text, colsep=u"\t", rowsep=u"\n",
transpose=False, skiprows=0, comments='#'):
"""Open clipboard text as table"""
if pd:
self.pd_text = text
self.pd_info = dict(sep=colsep, lineterminator=rowsep,
skiprows=skiprows, comment=comments)
if colsep is None:
self.pd_info = dict(lineterminator=rowsep, skiprows=skiprows,
comment=comments, delim_whitespace=True)
self._table_view.process_data(text, colsep, rowsep, transpose,
skiprows, comments) | [
"def",
"open_data",
"(",
"self",
",",
"text",
",",
"colsep",
"=",
"u\"\\t\"",
",",
"rowsep",
"=",
"u\"\\n\"",
",",
"transpose",
"=",
"False",
",",
"skiprows",
"=",
"0",
",",
"comments",
"=",
"'#'",
")",
":",
"if",
"pd",
":",
"self",
".",
"pd_text",
"=",
"text",
"self",
".",
"pd_info",
"=",
"dict",
"(",
"sep",
"=",
"colsep",
",",
"lineterminator",
"=",
"rowsep",
",",
"skiprows",
"=",
"skiprows",
",",
"comment",
"=",
"comments",
")",
"if",
"colsep",
"is",
"None",
":",
"self",
".",
"pd_info",
"=",
"dict",
"(",
"lineterminator",
"=",
"rowsep",
",",
"skiprows",
"=",
"skiprows",
",",
"comment",
"=",
"comments",
",",
"delim_whitespace",
"=",
"True",
")",
"self",
".",
"_table_view",
".",
"process_data",
"(",
"text",
",",
"colsep",
",",
"rowsep",
",",
"transpose",
",",
"skiprows",
",",
"comments",
")"
] | Open clipboard text as table | [
"Open",
"clipboard",
"text",
"as",
"table"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/importwizard.py#L467-L478 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/importwizard.py | ImportWizard._focus_tab | def _focus_tab(self, tab_idx):
"""Change tab focus"""
for i in range(self.tab_widget.count()):
self.tab_widget.setTabEnabled(i, False)
self.tab_widget.setTabEnabled(tab_idx, True)
self.tab_widget.setCurrentIndex(tab_idx) | python | def _focus_tab(self, tab_idx):
"""Change tab focus"""
for i in range(self.tab_widget.count()):
self.tab_widget.setTabEnabled(i, False)
self.tab_widget.setTabEnabled(tab_idx, True)
self.tab_widget.setCurrentIndex(tab_idx) | [
"def",
"_focus_tab",
"(",
"self",
",",
"tab_idx",
")",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"tab_widget",
".",
"count",
"(",
")",
")",
":",
"self",
".",
"tab_widget",
".",
"setTabEnabled",
"(",
"i",
",",
"False",
")",
"self",
".",
"tab_widget",
".",
"setTabEnabled",
"(",
"tab_idx",
",",
"True",
")",
"self",
".",
"tab_widget",
".",
"setCurrentIndex",
"(",
"tab_idx",
")"
] | Change tab focus | [
"Change",
"tab",
"focus"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/importwizard.py#L558-L563 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/importwizard.py | ImportWizard._set_step | def _set_step(self, step):
"""Proceed to a given step"""
new_tab = self.tab_widget.currentIndex() + step
assert new_tab < self.tab_widget.count() and new_tab >= 0
if new_tab == self.tab_widget.count()-1:
try:
self.table_widget.open_data(self._get_plain_text(),
self.text_widget.get_col_sep(),
self.text_widget.get_row_sep(),
self.text_widget.trnsp_box.isChecked(),
self.text_widget.get_skiprows(),
self.text_widget.get_comments())
self.done_btn.setEnabled(True)
self.done_btn.setDefault(True)
self.fwd_btn.setEnabled(False)
self.back_btn.setEnabled(True)
except (SyntaxError, AssertionError) as error:
QMessageBox.critical(self, _("Import wizard"),
_("<b>Unable to proceed to next step</b>"
"<br><br>Please check your entries."
"<br><br>Error message:<br>%s") % str(error))
return
elif new_tab == 0:
self.done_btn.setEnabled(False)
self.fwd_btn.setEnabled(True)
self.back_btn.setEnabled(False)
self._focus_tab(new_tab) | python | def _set_step(self, step):
"""Proceed to a given step"""
new_tab = self.tab_widget.currentIndex() + step
assert new_tab < self.tab_widget.count() and new_tab >= 0
if new_tab == self.tab_widget.count()-1:
try:
self.table_widget.open_data(self._get_plain_text(),
self.text_widget.get_col_sep(),
self.text_widget.get_row_sep(),
self.text_widget.trnsp_box.isChecked(),
self.text_widget.get_skiprows(),
self.text_widget.get_comments())
self.done_btn.setEnabled(True)
self.done_btn.setDefault(True)
self.fwd_btn.setEnabled(False)
self.back_btn.setEnabled(True)
except (SyntaxError, AssertionError) as error:
QMessageBox.critical(self, _("Import wizard"),
_("<b>Unable to proceed to next step</b>"
"<br><br>Please check your entries."
"<br><br>Error message:<br>%s") % str(error))
return
elif new_tab == 0:
self.done_btn.setEnabled(False)
self.fwd_btn.setEnabled(True)
self.back_btn.setEnabled(False)
self._focus_tab(new_tab) | [
"def",
"_set_step",
"(",
"self",
",",
"step",
")",
":",
"new_tab",
"=",
"self",
".",
"tab_widget",
".",
"currentIndex",
"(",
")",
"+",
"step",
"assert",
"new_tab",
"<",
"self",
".",
"tab_widget",
".",
"count",
"(",
")",
"and",
"new_tab",
">=",
"0",
"if",
"new_tab",
"==",
"self",
".",
"tab_widget",
".",
"count",
"(",
")",
"-",
"1",
":",
"try",
":",
"self",
".",
"table_widget",
".",
"open_data",
"(",
"self",
".",
"_get_plain_text",
"(",
")",
",",
"self",
".",
"text_widget",
".",
"get_col_sep",
"(",
")",
",",
"self",
".",
"text_widget",
".",
"get_row_sep",
"(",
")",
",",
"self",
".",
"text_widget",
".",
"trnsp_box",
".",
"isChecked",
"(",
")",
",",
"self",
".",
"text_widget",
".",
"get_skiprows",
"(",
")",
",",
"self",
".",
"text_widget",
".",
"get_comments",
"(",
")",
")",
"self",
".",
"done_btn",
".",
"setEnabled",
"(",
"True",
")",
"self",
".",
"done_btn",
".",
"setDefault",
"(",
"True",
")",
"self",
".",
"fwd_btn",
".",
"setEnabled",
"(",
"False",
")",
"self",
".",
"back_btn",
".",
"setEnabled",
"(",
"True",
")",
"except",
"(",
"SyntaxError",
",",
"AssertionError",
")",
"as",
"error",
":",
"QMessageBox",
".",
"critical",
"(",
"self",
",",
"_",
"(",
"\"Import wizard\"",
")",
",",
"_",
"(",
"\"<b>Unable to proceed to next step</b>\"",
"\"<br><br>Please check your entries.\"",
"\"<br><br>Error message:<br>%s\"",
")",
"%",
"str",
"(",
"error",
")",
")",
"return",
"elif",
"new_tab",
"==",
"0",
":",
"self",
".",
"done_btn",
".",
"setEnabled",
"(",
"False",
")",
"self",
".",
"fwd_btn",
".",
"setEnabled",
"(",
"True",
")",
"self",
".",
"back_btn",
".",
"setEnabled",
"(",
"False",
")",
"self",
".",
"_focus_tab",
"(",
"new_tab",
")"
] | Proceed to a given step | [
"Proceed",
"to",
"a",
"given",
"step"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/importwizard.py#L565-L591 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/importwizard.py | ImportWizard._simplify_shape | def _simplify_shape(self, alist, rec=0):
"""Reduce the alist dimension if needed"""
if rec != 0:
if len(alist) == 1:
return alist[-1]
return alist
if len(alist) == 1:
return self._simplify_shape(alist[-1], 1)
return [self._simplify_shape(al, 1) for al in alist] | python | def _simplify_shape(self, alist, rec=0):
"""Reduce the alist dimension if needed"""
if rec != 0:
if len(alist) == 1:
return alist[-1]
return alist
if len(alist) == 1:
return self._simplify_shape(alist[-1], 1)
return [self._simplify_shape(al, 1) for al in alist] | [
"def",
"_simplify_shape",
"(",
"self",
",",
"alist",
",",
"rec",
"=",
"0",
")",
":",
"if",
"rec",
"!=",
"0",
":",
"if",
"len",
"(",
"alist",
")",
"==",
"1",
":",
"return",
"alist",
"[",
"-",
"1",
"]",
"return",
"alist",
"if",
"len",
"(",
"alist",
")",
"==",
"1",
":",
"return",
"self",
".",
"_simplify_shape",
"(",
"alist",
"[",
"-",
"1",
"]",
",",
"1",
")",
"return",
"[",
"self",
".",
"_simplify_shape",
"(",
"al",
",",
"1",
")",
"for",
"al",
"in",
"alist",
"]"
] | Reduce the alist dimension if needed | [
"Reduce",
"the",
"alist",
"dimension",
"if",
"needed"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/importwizard.py#L599-L607 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/importwizard.py | ImportWizard._get_table_data | def _get_table_data(self):
"""Return clipboard processed as data"""
data = self._simplify_shape(
self.table_widget.get_data())
if self.table_widget.array_btn.isChecked():
return array(data)
elif pd and self.table_widget.df_btn.isChecked():
info = self.table_widget.pd_info
buf = io.StringIO(self.table_widget.pd_text)
return pd.read_csv(buf, **info)
return data | python | def _get_table_data(self):
"""Return clipboard processed as data"""
data = self._simplify_shape(
self.table_widget.get_data())
if self.table_widget.array_btn.isChecked():
return array(data)
elif pd and self.table_widget.df_btn.isChecked():
info = self.table_widget.pd_info
buf = io.StringIO(self.table_widget.pd_text)
return pd.read_csv(buf, **info)
return data | [
"def",
"_get_table_data",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"_simplify_shape",
"(",
"self",
".",
"table_widget",
".",
"get_data",
"(",
")",
")",
"if",
"self",
".",
"table_widget",
".",
"array_btn",
".",
"isChecked",
"(",
")",
":",
"return",
"array",
"(",
"data",
")",
"elif",
"pd",
"and",
"self",
".",
"table_widget",
".",
"df_btn",
".",
"isChecked",
"(",
")",
":",
"info",
"=",
"self",
".",
"table_widget",
".",
"pd_info",
"buf",
"=",
"io",
".",
"StringIO",
"(",
"self",
".",
"table_widget",
".",
"pd_text",
")",
"return",
"pd",
".",
"read_csv",
"(",
"buf",
",",
"*",
"*",
"info",
")",
"return",
"data"
] | Return clipboard processed as data | [
"Return",
"clipboard",
"processed",
"as",
"data"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/importwizard.py#L609-L619 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/importwizard.py | ImportWizard.process | def process(self):
"""Process the data from clipboard"""
var_name = self.name_edt.text()
try:
self.var_name = str(var_name)
except UnicodeEncodeError:
self.var_name = to_text_string(var_name)
if self.text_widget.get_as_data():
self.clip_data = self._get_table_data()
elif self.text_widget.get_as_code():
self.clip_data = try_to_eval(
to_text_string(self._get_plain_text()))
else:
self.clip_data = to_text_string(self._get_plain_text())
self.accept() | python | def process(self):
"""Process the data from clipboard"""
var_name = self.name_edt.text()
try:
self.var_name = str(var_name)
except UnicodeEncodeError:
self.var_name = to_text_string(var_name)
if self.text_widget.get_as_data():
self.clip_data = self._get_table_data()
elif self.text_widget.get_as_code():
self.clip_data = try_to_eval(
to_text_string(self._get_plain_text()))
else:
self.clip_data = to_text_string(self._get_plain_text())
self.accept() | [
"def",
"process",
"(",
"self",
")",
":",
"var_name",
"=",
"self",
".",
"name_edt",
".",
"text",
"(",
")",
"try",
":",
"self",
".",
"var_name",
"=",
"str",
"(",
"var_name",
")",
"except",
"UnicodeEncodeError",
":",
"self",
".",
"var_name",
"=",
"to_text_string",
"(",
"var_name",
")",
"if",
"self",
".",
"text_widget",
".",
"get_as_data",
"(",
")",
":",
"self",
".",
"clip_data",
"=",
"self",
".",
"_get_table_data",
"(",
")",
"elif",
"self",
".",
"text_widget",
".",
"get_as_code",
"(",
")",
":",
"self",
".",
"clip_data",
"=",
"try_to_eval",
"(",
"to_text_string",
"(",
"self",
".",
"_get_plain_text",
"(",
")",
")",
")",
"else",
":",
"self",
".",
"clip_data",
"=",
"to_text_string",
"(",
"self",
".",
"_get_plain_text",
"(",
")",
")",
"self",
".",
"accept",
"(",
")"
] | Process the data from clipboard | [
"Process",
"the",
"data",
"from",
"clipboard"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/importwizard.py#L626-L640 | train |
spyder-ide/spyder | spyder/plugins/ipythonconsole/widgets/debugging.py | DebuggingWidget.set_spyder_breakpoints | def set_spyder_breakpoints(self, force=False):
"""Set Spyder breakpoints into a debugging session"""
if self._reading or force:
breakpoints_dict = CONF.get('run', 'breakpoints', {})
# We need to enclose pickled values in a list to be able to
# send them to the kernel in Python 2
serialiazed_breakpoints = [pickle.dumps(breakpoints_dict,
protocol=PICKLE_PROTOCOL)]
breakpoints = to_text_string(serialiazed_breakpoints)
cmd = u"!get_ipython().kernel._set_spyder_breakpoints({})"
self.kernel_client.input(cmd.format(breakpoints)) | python | def set_spyder_breakpoints(self, force=False):
"""Set Spyder breakpoints into a debugging session"""
if self._reading or force:
breakpoints_dict = CONF.get('run', 'breakpoints', {})
# We need to enclose pickled values in a list to be able to
# send them to the kernel in Python 2
serialiazed_breakpoints = [pickle.dumps(breakpoints_dict,
protocol=PICKLE_PROTOCOL)]
breakpoints = to_text_string(serialiazed_breakpoints)
cmd = u"!get_ipython().kernel._set_spyder_breakpoints({})"
self.kernel_client.input(cmd.format(breakpoints)) | [
"def",
"set_spyder_breakpoints",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"self",
".",
"_reading",
"or",
"force",
":",
"breakpoints_dict",
"=",
"CONF",
".",
"get",
"(",
"'run'",
",",
"'breakpoints'",
",",
"{",
"}",
")",
"# We need to enclose pickled values in a list to be able to",
"# send them to the kernel in Python 2",
"serialiazed_breakpoints",
"=",
"[",
"pickle",
".",
"dumps",
"(",
"breakpoints_dict",
",",
"protocol",
"=",
"PICKLE_PROTOCOL",
")",
"]",
"breakpoints",
"=",
"to_text_string",
"(",
"serialiazed_breakpoints",
")",
"cmd",
"=",
"u\"!get_ipython().kernel._set_spyder_breakpoints({})\"",
"self",
".",
"kernel_client",
".",
"input",
"(",
"cmd",
".",
"format",
"(",
"breakpoints",
")",
")"
] | Set Spyder breakpoints into a debugging session | [
"Set",
"Spyder",
"breakpoints",
"into",
"a",
"debugging",
"session"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/debugging.py#L36-L48 | train |
spyder-ide/spyder | spyder/plugins/ipythonconsole/widgets/debugging.py | DebuggingWidget.dbg_exec_magic | def dbg_exec_magic(self, magic, args=''):
"""Run an IPython magic while debugging."""
code = "!get_ipython().kernel.shell.run_line_magic('{}', '{}')".format(
magic, args)
self.kernel_client.input(code) | python | def dbg_exec_magic(self, magic, args=''):
"""Run an IPython magic while debugging."""
code = "!get_ipython().kernel.shell.run_line_magic('{}', '{}')".format(
magic, args)
self.kernel_client.input(code) | [
"def",
"dbg_exec_magic",
"(",
"self",
",",
"magic",
",",
"args",
"=",
"''",
")",
":",
"code",
"=",
"\"!get_ipython().kernel.shell.run_line_magic('{}', '{}')\"",
".",
"format",
"(",
"magic",
",",
"args",
")",
"self",
".",
"kernel_client",
".",
"input",
"(",
"code",
")"
] | Run an IPython magic while debugging. | [
"Run",
"an",
"IPython",
"magic",
"while",
"debugging",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/debugging.py#L50-L54 | train |
spyder-ide/spyder | spyder/plugins/ipythonconsole/widgets/debugging.py | DebuggingWidget.refresh_from_pdb | def refresh_from_pdb(self, pdb_state):
"""
Refresh Variable Explorer and Editor from a Pdb session,
after running any pdb command.
See publish_pdb_state and notify_spyder in spyder_kernels
"""
if 'step' in pdb_state and 'fname' in pdb_state['step']:
fname = pdb_state['step']['fname']
lineno = pdb_state['step']['lineno']
self.sig_pdb_step.emit(fname, lineno)
if 'namespace_view' in pdb_state:
self.sig_namespace_view.emit(ast.literal_eval(
pdb_state['namespace_view']))
if 'var_properties' in pdb_state:
self.sig_var_properties.emit(ast.literal_eval(
pdb_state['var_properties'])) | python | def refresh_from_pdb(self, pdb_state):
"""
Refresh Variable Explorer and Editor from a Pdb session,
after running any pdb command.
See publish_pdb_state and notify_spyder in spyder_kernels
"""
if 'step' in pdb_state and 'fname' in pdb_state['step']:
fname = pdb_state['step']['fname']
lineno = pdb_state['step']['lineno']
self.sig_pdb_step.emit(fname, lineno)
if 'namespace_view' in pdb_state:
self.sig_namespace_view.emit(ast.literal_eval(
pdb_state['namespace_view']))
if 'var_properties' in pdb_state:
self.sig_var_properties.emit(ast.literal_eval(
pdb_state['var_properties'])) | [
"def",
"refresh_from_pdb",
"(",
"self",
",",
"pdb_state",
")",
":",
"if",
"'step'",
"in",
"pdb_state",
"and",
"'fname'",
"in",
"pdb_state",
"[",
"'step'",
"]",
":",
"fname",
"=",
"pdb_state",
"[",
"'step'",
"]",
"[",
"'fname'",
"]",
"lineno",
"=",
"pdb_state",
"[",
"'step'",
"]",
"[",
"'lineno'",
"]",
"self",
".",
"sig_pdb_step",
".",
"emit",
"(",
"fname",
",",
"lineno",
")",
"if",
"'namespace_view'",
"in",
"pdb_state",
":",
"self",
".",
"sig_namespace_view",
".",
"emit",
"(",
"ast",
".",
"literal_eval",
"(",
"pdb_state",
"[",
"'namespace_view'",
"]",
")",
")",
"if",
"'var_properties'",
"in",
"pdb_state",
":",
"self",
".",
"sig_var_properties",
".",
"emit",
"(",
"ast",
".",
"literal_eval",
"(",
"pdb_state",
"[",
"'var_properties'",
"]",
")",
")"
] | Refresh Variable Explorer and Editor from a Pdb session,
after running any pdb command.
See publish_pdb_state and notify_spyder in spyder_kernels | [
"Refresh",
"Variable",
"Explorer",
"and",
"Editor",
"from",
"a",
"Pdb",
"session",
"after",
"running",
"any",
"pdb",
"command",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/debugging.py#L56-L74 | train |
spyder-ide/spyder | spyder/plugins/ipythonconsole/widgets/debugging.py | DebuggingWidget._handle_input_request | def _handle_input_request(self, msg):
"""Save history and add a %plot magic."""
if self._hidden:
raise RuntimeError('Request for raw input during hidden execution.')
# Make sure that all output from the SUB channel has been processed
# before entering readline mode.
self.kernel_client.iopub_channel.flush()
def callback(line):
# Save history to browse it later
if not (len(self._control.history) > 0
and self._control.history[-1] == line):
# do not save pdb commands
cmd = line.split(" ")[0]
if "do_" + cmd not in dir(pdb.Pdb):
self._control.history.append(line)
# This is the Spyder addition: add a %plot magic to display
# plots while debugging
if line.startswith('%plot '):
line = line.split()[-1]
code = "__spy_code__ = get_ipython().run_cell('%s')" % line
self.kernel_client.input(code)
else:
self.kernel_client.input(line)
if self._reading:
self._reading = False
self._readline(msg['content']['prompt'], callback=callback,
password=msg['content']['password']) | python | def _handle_input_request(self, msg):
"""Save history and add a %plot magic."""
if self._hidden:
raise RuntimeError('Request for raw input during hidden execution.')
# Make sure that all output from the SUB channel has been processed
# before entering readline mode.
self.kernel_client.iopub_channel.flush()
def callback(line):
# Save history to browse it later
if not (len(self._control.history) > 0
and self._control.history[-1] == line):
# do not save pdb commands
cmd = line.split(" ")[0]
if "do_" + cmd not in dir(pdb.Pdb):
self._control.history.append(line)
# This is the Spyder addition: add a %plot magic to display
# plots while debugging
if line.startswith('%plot '):
line = line.split()[-1]
code = "__spy_code__ = get_ipython().run_cell('%s')" % line
self.kernel_client.input(code)
else:
self.kernel_client.input(line)
if self._reading:
self._reading = False
self._readline(msg['content']['prompt'], callback=callback,
password=msg['content']['password']) | [
"def",
"_handle_input_request",
"(",
"self",
",",
"msg",
")",
":",
"if",
"self",
".",
"_hidden",
":",
"raise",
"RuntimeError",
"(",
"'Request for raw input during hidden execution.'",
")",
"# Make sure that all output from the SUB channel has been processed",
"# before entering readline mode.",
"self",
".",
"kernel_client",
".",
"iopub_channel",
".",
"flush",
"(",
")",
"def",
"callback",
"(",
"line",
")",
":",
"# Save history to browse it later",
"if",
"not",
"(",
"len",
"(",
"self",
".",
"_control",
".",
"history",
")",
">",
"0",
"and",
"self",
".",
"_control",
".",
"history",
"[",
"-",
"1",
"]",
"==",
"line",
")",
":",
"# do not save pdb commands",
"cmd",
"=",
"line",
".",
"split",
"(",
"\" \"",
")",
"[",
"0",
"]",
"if",
"\"do_\"",
"+",
"cmd",
"not",
"in",
"dir",
"(",
"pdb",
".",
"Pdb",
")",
":",
"self",
".",
"_control",
".",
"history",
".",
"append",
"(",
"line",
")",
"# This is the Spyder addition: add a %plot magic to display",
"# plots while debugging",
"if",
"line",
".",
"startswith",
"(",
"'%plot '",
")",
":",
"line",
"=",
"line",
".",
"split",
"(",
")",
"[",
"-",
"1",
"]",
"code",
"=",
"\"__spy_code__ = get_ipython().run_cell('%s')\"",
"%",
"line",
"self",
".",
"kernel_client",
".",
"input",
"(",
"code",
")",
"else",
":",
"self",
".",
"kernel_client",
".",
"input",
"(",
"line",
")",
"if",
"self",
".",
"_reading",
":",
"self",
".",
"_reading",
"=",
"False",
"self",
".",
"_readline",
"(",
"msg",
"[",
"'content'",
"]",
"[",
"'prompt'",
"]",
",",
"callback",
"=",
"callback",
",",
"password",
"=",
"msg",
"[",
"'content'",
"]",
"[",
"'password'",
"]",
")"
] | Save history and add a %plot magic. | [
"Save",
"history",
"and",
"add",
"a",
"%plot",
"magic",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/debugging.py#L77-L106 | train |
spyder-ide/spyder | spyder/plugins/ipythonconsole/widgets/debugging.py | DebuggingWidget._event_filter_console_keypress | def _event_filter_console_keypress(self, event):
"""Handle Key_Up/Key_Down while debugging."""
key = event.key()
if self._reading:
self._control.current_prompt_pos = self._prompt_pos
if key == Qt.Key_Up:
self._control.browse_history(backward=True)
return True
elif key == Qt.Key_Down:
self._control.browse_history(backward=False)
return True
elif key in (Qt.Key_Return, Qt.Key_Enter):
self._control.reset_search_pos()
else:
self._control.hist_wholeline = False
return super(DebuggingWidget,
self)._event_filter_console_keypress(event)
else:
return super(DebuggingWidget,
self)._event_filter_console_keypress(event) | python | def _event_filter_console_keypress(self, event):
"""Handle Key_Up/Key_Down while debugging."""
key = event.key()
if self._reading:
self._control.current_prompt_pos = self._prompt_pos
if key == Qt.Key_Up:
self._control.browse_history(backward=True)
return True
elif key == Qt.Key_Down:
self._control.browse_history(backward=False)
return True
elif key in (Qt.Key_Return, Qt.Key_Enter):
self._control.reset_search_pos()
else:
self._control.hist_wholeline = False
return super(DebuggingWidget,
self)._event_filter_console_keypress(event)
else:
return super(DebuggingWidget,
self)._event_filter_console_keypress(event) | [
"def",
"_event_filter_console_keypress",
"(",
"self",
",",
"event",
")",
":",
"key",
"=",
"event",
".",
"key",
"(",
")",
"if",
"self",
".",
"_reading",
":",
"self",
".",
"_control",
".",
"current_prompt_pos",
"=",
"self",
".",
"_prompt_pos",
"if",
"key",
"==",
"Qt",
".",
"Key_Up",
":",
"self",
".",
"_control",
".",
"browse_history",
"(",
"backward",
"=",
"True",
")",
"return",
"True",
"elif",
"key",
"==",
"Qt",
".",
"Key_Down",
":",
"self",
".",
"_control",
".",
"browse_history",
"(",
"backward",
"=",
"False",
")",
"return",
"True",
"elif",
"key",
"in",
"(",
"Qt",
".",
"Key_Return",
",",
"Qt",
".",
"Key_Enter",
")",
":",
"self",
".",
"_control",
".",
"reset_search_pos",
"(",
")",
"else",
":",
"self",
".",
"_control",
".",
"hist_wholeline",
"=",
"False",
"return",
"super",
"(",
"DebuggingWidget",
",",
"self",
")",
".",
"_event_filter_console_keypress",
"(",
"event",
")",
"else",
":",
"return",
"super",
"(",
"DebuggingWidget",
",",
"self",
")",
".",
"_event_filter_console_keypress",
"(",
"event",
")"
] | Handle Key_Up/Key_Down while debugging. | [
"Handle",
"Key_Up",
"/",
"Key_Down",
"while",
"debugging",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/debugging.py#L108-L127 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | global_max | def global_max(col_vals, index):
"""Returns the global maximum and minimum."""
col_vals_without_None = [x for x in col_vals if x is not None]
max_col, min_col = zip(*col_vals_without_None)
return max(max_col), min(min_col) | python | def global_max(col_vals, index):
"""Returns the global maximum and minimum."""
col_vals_without_None = [x for x in col_vals if x is not None]
max_col, min_col = zip(*col_vals_without_None)
return max(max_col), min(min_col) | [
"def",
"global_max",
"(",
"col_vals",
",",
"index",
")",
":",
"col_vals_without_None",
"=",
"[",
"x",
"for",
"x",
"in",
"col_vals",
"if",
"x",
"is",
"not",
"None",
"]",
"max_col",
",",
"min_col",
"=",
"zip",
"(",
"*",
"col_vals_without_None",
")",
"return",
"max",
"(",
"max_col",
")",
",",
"min",
"(",
"min_col",
")"
] | Returns the global maximum and minimum. | [
"Returns",
"the",
"global",
"maximum",
"and",
"minimum",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L105-L109 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | DataFrameModel._axis | def _axis(self, axis):
"""
Return the corresponding labels taking into account the axis.
The axis could be horizontal (0) or vertical (1).
"""
return self.df.columns if axis == 0 else self.df.index | python | def _axis(self, axis):
"""
Return the corresponding labels taking into account the axis.
The axis could be horizontal (0) or vertical (1).
"""
return self.df.columns if axis == 0 else self.df.index | [
"def",
"_axis",
"(",
"self",
",",
"axis",
")",
":",
"return",
"self",
".",
"df",
".",
"columns",
"if",
"axis",
"==",
"0",
"else",
"self",
".",
"df",
".",
"index"
] | Return the corresponding labels taking into account the axis.
The axis could be horizontal (0) or vertical (1). | [
"Return",
"the",
"corresponding",
"labels",
"taking",
"into",
"account",
"the",
"axis",
".",
"The",
"axis",
"could",
"be",
"horizontal",
"(",
"0",
")",
"or",
"vertical",
"(",
"1",
")",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L162-L168 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | DataFrameModel._axis_levels | def _axis_levels(self, axis):
"""
Return the number of levels in the labels taking into account the axis.
Get the number of levels for the columns (0) or rows (1).
"""
ax = self._axis(axis)
return 1 if not hasattr(ax, 'levels') else len(ax.levels) | python | def _axis_levels(self, axis):
"""
Return the number of levels in the labels taking into account the axis.
Get the number of levels for the columns (0) or rows (1).
"""
ax = self._axis(axis)
return 1 if not hasattr(ax, 'levels') else len(ax.levels) | [
"def",
"_axis_levels",
"(",
"self",
",",
"axis",
")",
":",
"ax",
"=",
"self",
".",
"_axis",
"(",
"axis",
")",
"return",
"1",
"if",
"not",
"hasattr",
"(",
"ax",
",",
"'levels'",
")",
"else",
"len",
"(",
"ax",
".",
"levels",
")"
] | Return the number of levels in the labels taking into account the axis.
Get the number of levels for the columns (0) or rows (1). | [
"Return",
"the",
"number",
"of",
"levels",
"in",
"the",
"labels",
"taking",
"into",
"account",
"the",
"axis",
".",
"Get",
"the",
"number",
"of",
"levels",
"for",
"the",
"columns",
"(",
"0",
")",
"or",
"rows",
"(",
"1",
")",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L170-L177 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | DataFrameModel.header | def header(self, axis, x, level=0):
"""
Return the values of the labels for the header of columns or rows.
The value corresponds to the header of column or row x in the
given level.
"""
ax = self._axis(axis)
return ax.values[x] if not hasattr(ax, 'levels') \
else ax.values[x][level] | python | def header(self, axis, x, level=0):
"""
Return the values of the labels for the header of columns or rows.
The value corresponds to the header of column or row x in the
given level.
"""
ax = self._axis(axis)
return ax.values[x] if not hasattr(ax, 'levels') \
else ax.values[x][level] | [
"def",
"header",
"(",
"self",
",",
"axis",
",",
"x",
",",
"level",
"=",
"0",
")",
":",
"ax",
"=",
"self",
".",
"_axis",
"(",
"axis",
")",
"return",
"ax",
".",
"values",
"[",
"x",
"]",
"if",
"not",
"hasattr",
"(",
"ax",
",",
"'levels'",
")",
"else",
"ax",
".",
"values",
"[",
"x",
"]",
"[",
"level",
"]"
] | Return the values of the labels for the header of columns or rows.
The value corresponds to the header of column or row x in the
given level. | [
"Return",
"the",
"values",
"of",
"the",
"labels",
"for",
"the",
"header",
"of",
"columns",
"or",
"rows",
".",
"The",
"value",
"corresponds",
"to",
"the",
"header",
"of",
"column",
"or",
"row",
"x",
"in",
"the",
"given",
"level",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L194-L203 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | DataFrameModel.max_min_col_update | def max_min_col_update(self):
"""
Determines the maximum and minimum number in each column.
The result is a list whose k-th entry is [vmax, vmin], where vmax and
vmin denote the maximum and minimum of the k-th column (ignoring NaN).
This list is stored in self.max_min_col.
If the k-th column has a non-numerical dtype, then the k-th entry
is set to None. If the dtype is complex, then compute the maximum and
minimum of the absolute values. If vmax equals vmin, then vmin is
decreased by one.
"""
if self.df.shape[0] == 0: # If no rows to compute max/min then return
return
self.max_min_col = []
for dummy, col in self.df.iteritems():
if col.dtype in REAL_NUMBER_TYPES + COMPLEX_NUMBER_TYPES:
if col.dtype in REAL_NUMBER_TYPES:
vmax = col.max(skipna=True)
vmin = col.min(skipna=True)
else:
vmax = col.abs().max(skipna=True)
vmin = col.abs().min(skipna=True)
if vmax != vmin:
max_min = [vmax, vmin]
else:
max_min = [vmax, vmin - 1]
else:
max_min = None
self.max_min_col.append(max_min) | python | def max_min_col_update(self):
"""
Determines the maximum and minimum number in each column.
The result is a list whose k-th entry is [vmax, vmin], where vmax and
vmin denote the maximum and minimum of the k-th column (ignoring NaN).
This list is stored in self.max_min_col.
If the k-th column has a non-numerical dtype, then the k-th entry
is set to None. If the dtype is complex, then compute the maximum and
minimum of the absolute values. If vmax equals vmin, then vmin is
decreased by one.
"""
if self.df.shape[0] == 0: # If no rows to compute max/min then return
return
self.max_min_col = []
for dummy, col in self.df.iteritems():
if col.dtype in REAL_NUMBER_TYPES + COMPLEX_NUMBER_TYPES:
if col.dtype in REAL_NUMBER_TYPES:
vmax = col.max(skipna=True)
vmin = col.min(skipna=True)
else:
vmax = col.abs().max(skipna=True)
vmin = col.abs().min(skipna=True)
if vmax != vmin:
max_min = [vmax, vmin]
else:
max_min = [vmax, vmin - 1]
else:
max_min = None
self.max_min_col.append(max_min) | [
"def",
"max_min_col_update",
"(",
"self",
")",
":",
"if",
"self",
".",
"df",
".",
"shape",
"[",
"0",
"]",
"==",
"0",
":",
"# If no rows to compute max/min then return\r",
"return",
"self",
".",
"max_min_col",
"=",
"[",
"]",
"for",
"dummy",
",",
"col",
"in",
"self",
".",
"df",
".",
"iteritems",
"(",
")",
":",
"if",
"col",
".",
"dtype",
"in",
"REAL_NUMBER_TYPES",
"+",
"COMPLEX_NUMBER_TYPES",
":",
"if",
"col",
".",
"dtype",
"in",
"REAL_NUMBER_TYPES",
":",
"vmax",
"=",
"col",
".",
"max",
"(",
"skipna",
"=",
"True",
")",
"vmin",
"=",
"col",
".",
"min",
"(",
"skipna",
"=",
"True",
")",
"else",
":",
"vmax",
"=",
"col",
".",
"abs",
"(",
")",
".",
"max",
"(",
"skipna",
"=",
"True",
")",
"vmin",
"=",
"col",
".",
"abs",
"(",
")",
".",
"min",
"(",
"skipna",
"=",
"True",
")",
"if",
"vmax",
"!=",
"vmin",
":",
"max_min",
"=",
"[",
"vmax",
",",
"vmin",
"]",
"else",
":",
"max_min",
"=",
"[",
"vmax",
",",
"vmin",
"-",
"1",
"]",
"else",
":",
"max_min",
"=",
"None",
"self",
".",
"max_min_col",
".",
"append",
"(",
"max_min",
")"
] | Determines the maximum and minimum number in each column.
The result is a list whose k-th entry is [vmax, vmin], where vmax and
vmin denote the maximum and minimum of the k-th column (ignoring NaN).
This list is stored in self.max_min_col.
If the k-th column has a non-numerical dtype, then the k-th entry
is set to None. If the dtype is complex, then compute the maximum and
minimum of the absolute values. If vmax equals vmin, then vmin is
decreased by one. | [
"Determines",
"the",
"maximum",
"and",
"minimum",
"number",
"in",
"each",
"column",
".",
"The",
"result",
"is",
"a",
"list",
"whose",
"k",
"-",
"th",
"entry",
"is",
"[",
"vmax",
"vmin",
"]",
"where",
"vmax",
"and",
"vmin",
"denote",
"the",
"maximum",
"and",
"minimum",
"of",
"the",
"k",
"-",
"th",
"column",
"(",
"ignoring",
"NaN",
")",
".",
"This",
"list",
"is",
"stored",
"in",
"self",
".",
"max_min_col",
".",
"If",
"the",
"k",
"-",
"th",
"column",
"has",
"a",
"non",
"-",
"numerical",
"dtype",
"then",
"the",
"k",
"-",
"th",
"entry",
"is",
"set",
"to",
"None",
".",
"If",
"the",
"dtype",
"is",
"complex",
"then",
"compute",
"the",
"maximum",
"and",
"minimum",
"of",
"the",
"absolute",
"values",
".",
"If",
"vmax",
"equals",
"vmin",
"then",
"vmin",
"is",
"decreased",
"by",
"one",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L213-L243 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | DataFrameModel.colum_avg | def colum_avg(self, state):
"""Toggle backgroundcolor"""
self.colum_avg_enabled = state > 0
if self.colum_avg_enabled:
self.return_max = lambda col_vals, index: col_vals[index]
else:
self.return_max = global_max
self.reset() | python | def colum_avg(self, state):
"""Toggle backgroundcolor"""
self.colum_avg_enabled = state > 0
if self.colum_avg_enabled:
self.return_max = lambda col_vals, index: col_vals[index]
else:
self.return_max = global_max
self.reset() | [
"def",
"colum_avg",
"(",
"self",
",",
"state",
")",
":",
"self",
".",
"colum_avg_enabled",
"=",
"state",
">",
"0",
"if",
"self",
".",
"colum_avg_enabled",
":",
"self",
".",
"return_max",
"=",
"lambda",
"col_vals",
",",
"index",
":",
"col_vals",
"[",
"index",
"]",
"else",
":",
"self",
".",
"return_max",
"=",
"global_max",
"self",
".",
"reset",
"(",
")"
] | Toggle backgroundcolor | [
"Toggle",
"backgroundcolor"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L260-L267 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | DataFrameModel.get_bgcolor | def get_bgcolor(self, index):
"""Background color depending on value."""
column = index.column()
if not self.bgcolor_enabled:
return
value = self.get_value(index.row(), column)
if self.max_min_col[column] is None or isna(value):
color = QColor(BACKGROUND_NONNUMBER_COLOR)
if is_text_string(value):
color.setAlphaF(BACKGROUND_STRING_ALPHA)
else:
color.setAlphaF(BACKGROUND_MISC_ALPHA)
else:
if isinstance(value, COMPLEX_NUMBER_TYPES):
color_func = abs
else:
color_func = float
vmax, vmin = self.return_max(self.max_min_col, column)
hue = (BACKGROUND_NUMBER_MINHUE + BACKGROUND_NUMBER_HUERANGE *
(vmax - color_func(value)) / (vmax - vmin))
hue = float(abs(hue))
if hue > 1:
hue = 1
color = QColor.fromHsvF(hue, BACKGROUND_NUMBER_SATURATION,
BACKGROUND_NUMBER_VALUE,
BACKGROUND_NUMBER_ALPHA)
return color | python | def get_bgcolor(self, index):
"""Background color depending on value."""
column = index.column()
if not self.bgcolor_enabled:
return
value = self.get_value(index.row(), column)
if self.max_min_col[column] is None or isna(value):
color = QColor(BACKGROUND_NONNUMBER_COLOR)
if is_text_string(value):
color.setAlphaF(BACKGROUND_STRING_ALPHA)
else:
color.setAlphaF(BACKGROUND_MISC_ALPHA)
else:
if isinstance(value, COMPLEX_NUMBER_TYPES):
color_func = abs
else:
color_func = float
vmax, vmin = self.return_max(self.max_min_col, column)
hue = (BACKGROUND_NUMBER_MINHUE + BACKGROUND_NUMBER_HUERANGE *
(vmax - color_func(value)) / (vmax - vmin))
hue = float(abs(hue))
if hue > 1:
hue = 1
color = QColor.fromHsvF(hue, BACKGROUND_NUMBER_SATURATION,
BACKGROUND_NUMBER_VALUE,
BACKGROUND_NUMBER_ALPHA)
return color | [
"def",
"get_bgcolor",
"(",
"self",
",",
"index",
")",
":",
"column",
"=",
"index",
".",
"column",
"(",
")",
"if",
"not",
"self",
".",
"bgcolor_enabled",
":",
"return",
"value",
"=",
"self",
".",
"get_value",
"(",
"index",
".",
"row",
"(",
")",
",",
"column",
")",
"if",
"self",
".",
"max_min_col",
"[",
"column",
"]",
"is",
"None",
"or",
"isna",
"(",
"value",
")",
":",
"color",
"=",
"QColor",
"(",
"BACKGROUND_NONNUMBER_COLOR",
")",
"if",
"is_text_string",
"(",
"value",
")",
":",
"color",
".",
"setAlphaF",
"(",
"BACKGROUND_STRING_ALPHA",
")",
"else",
":",
"color",
".",
"setAlphaF",
"(",
"BACKGROUND_MISC_ALPHA",
")",
"else",
":",
"if",
"isinstance",
"(",
"value",
",",
"COMPLEX_NUMBER_TYPES",
")",
":",
"color_func",
"=",
"abs",
"else",
":",
"color_func",
"=",
"float",
"vmax",
",",
"vmin",
"=",
"self",
".",
"return_max",
"(",
"self",
".",
"max_min_col",
",",
"column",
")",
"hue",
"=",
"(",
"BACKGROUND_NUMBER_MINHUE",
"+",
"BACKGROUND_NUMBER_HUERANGE",
"*",
"(",
"vmax",
"-",
"color_func",
"(",
"value",
")",
")",
"/",
"(",
"vmax",
"-",
"vmin",
")",
")",
"hue",
"=",
"float",
"(",
"abs",
"(",
"hue",
")",
")",
"if",
"hue",
">",
"1",
":",
"hue",
"=",
"1",
"color",
"=",
"QColor",
".",
"fromHsvF",
"(",
"hue",
",",
"BACKGROUND_NUMBER_SATURATION",
",",
"BACKGROUND_NUMBER_VALUE",
",",
"BACKGROUND_NUMBER_ALPHA",
")",
"return",
"color"
] | Background color depending on value. | [
"Background",
"color",
"depending",
"on",
"value",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L269-L295 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | DataFrameModel.get_value | def get_value(self, row, column):
"""Return the value of the DataFrame."""
# To increase the performance iat is used but that requires error
# handling, so fallback uses iloc
try:
value = self.df.iat[row, column]
except OutOfBoundsDatetime:
value = self.df.iloc[:, column].astype(str).iat[row]
except:
value = self.df.iloc[row, column]
return value | python | def get_value(self, row, column):
"""Return the value of the DataFrame."""
# To increase the performance iat is used but that requires error
# handling, so fallback uses iloc
try:
value = self.df.iat[row, column]
except OutOfBoundsDatetime:
value = self.df.iloc[:, column].astype(str).iat[row]
except:
value = self.df.iloc[row, column]
return value | [
"def",
"get_value",
"(",
"self",
",",
"row",
",",
"column",
")",
":",
"# To increase the performance iat is used but that requires error\r",
"# handling, so fallback uses iloc\r",
"try",
":",
"value",
"=",
"self",
".",
"df",
".",
"iat",
"[",
"row",
",",
"column",
"]",
"except",
"OutOfBoundsDatetime",
":",
"value",
"=",
"self",
".",
"df",
".",
"iloc",
"[",
":",
",",
"column",
"]",
".",
"astype",
"(",
"str",
")",
".",
"iat",
"[",
"row",
"]",
"except",
":",
"value",
"=",
"self",
".",
"df",
".",
"iloc",
"[",
"row",
",",
"column",
"]",
"return",
"value"
] | Return the value of the DataFrame. | [
"Return",
"the",
"value",
"of",
"the",
"DataFrame",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L297-L307 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | DataFrameModel.data | def data(self, index, role=Qt.DisplayRole):
"""Cell content"""
if not index.isValid():
return to_qvariant()
if role == Qt.DisplayRole or role == Qt.EditRole:
column = index.column()
row = index.row()
value = self.get_value(row, column)
if isinstance(value, float):
try:
return to_qvariant(self._format % value)
except (ValueError, TypeError):
# may happen if format = '%d' and value = NaN;
# see issue 4139
return to_qvariant(DEFAULT_FORMAT % value)
elif is_type_text_string(value):
# Don't perform any conversion on strings
# because it leads to differences between
# the data present in the dataframe and
# what is shown by Spyder
return value
else:
try:
return to_qvariant(to_text_string(value))
except Exception:
self.display_error_idxs.append(index)
return u'Display Error!'
elif role == Qt.BackgroundColorRole:
return to_qvariant(self.get_bgcolor(index))
elif role == Qt.FontRole:
return to_qvariant(get_font(font_size_delta=DEFAULT_SMALL_DELTA))
elif role == Qt.ToolTipRole:
if index in self.display_error_idxs:
return _("It is not possible to display this value because\n"
"an error ocurred while trying to do it")
return to_qvariant() | python | def data(self, index, role=Qt.DisplayRole):
"""Cell content"""
if not index.isValid():
return to_qvariant()
if role == Qt.DisplayRole or role == Qt.EditRole:
column = index.column()
row = index.row()
value = self.get_value(row, column)
if isinstance(value, float):
try:
return to_qvariant(self._format % value)
except (ValueError, TypeError):
# may happen if format = '%d' and value = NaN;
# see issue 4139
return to_qvariant(DEFAULT_FORMAT % value)
elif is_type_text_string(value):
# Don't perform any conversion on strings
# because it leads to differences between
# the data present in the dataframe and
# what is shown by Spyder
return value
else:
try:
return to_qvariant(to_text_string(value))
except Exception:
self.display_error_idxs.append(index)
return u'Display Error!'
elif role == Qt.BackgroundColorRole:
return to_qvariant(self.get_bgcolor(index))
elif role == Qt.FontRole:
return to_qvariant(get_font(font_size_delta=DEFAULT_SMALL_DELTA))
elif role == Qt.ToolTipRole:
if index in self.display_error_idxs:
return _("It is not possible to display this value because\n"
"an error ocurred while trying to do it")
return to_qvariant() | [
"def",
"data",
"(",
"self",
",",
"index",
",",
"role",
"=",
"Qt",
".",
"DisplayRole",
")",
":",
"if",
"not",
"index",
".",
"isValid",
"(",
")",
":",
"return",
"to_qvariant",
"(",
")",
"if",
"role",
"==",
"Qt",
".",
"DisplayRole",
"or",
"role",
"==",
"Qt",
".",
"EditRole",
":",
"column",
"=",
"index",
".",
"column",
"(",
")",
"row",
"=",
"index",
".",
"row",
"(",
")",
"value",
"=",
"self",
".",
"get_value",
"(",
"row",
",",
"column",
")",
"if",
"isinstance",
"(",
"value",
",",
"float",
")",
":",
"try",
":",
"return",
"to_qvariant",
"(",
"self",
".",
"_format",
"%",
"value",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"# may happen if format = '%d' and value = NaN;\r",
"# see issue 4139\r",
"return",
"to_qvariant",
"(",
"DEFAULT_FORMAT",
"%",
"value",
")",
"elif",
"is_type_text_string",
"(",
"value",
")",
":",
"# Don't perform any conversion on strings\r",
"# because it leads to differences between\r",
"# the data present in the dataframe and\r",
"# what is shown by Spyder\r",
"return",
"value",
"else",
":",
"try",
":",
"return",
"to_qvariant",
"(",
"to_text_string",
"(",
"value",
")",
")",
"except",
"Exception",
":",
"self",
".",
"display_error_idxs",
".",
"append",
"(",
"index",
")",
"return",
"u'Display Error!'",
"elif",
"role",
"==",
"Qt",
".",
"BackgroundColorRole",
":",
"return",
"to_qvariant",
"(",
"self",
".",
"get_bgcolor",
"(",
"index",
")",
")",
"elif",
"role",
"==",
"Qt",
".",
"FontRole",
":",
"return",
"to_qvariant",
"(",
"get_font",
"(",
"font_size_delta",
"=",
"DEFAULT_SMALL_DELTA",
")",
")",
"elif",
"role",
"==",
"Qt",
".",
"ToolTipRole",
":",
"if",
"index",
"in",
"self",
".",
"display_error_idxs",
":",
"return",
"_",
"(",
"\"It is not possible to display this value because\\n\"",
"\"an error ocurred while trying to do it\"",
")",
"return",
"to_qvariant",
"(",
")"
] | Cell content | [
"Cell",
"content"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L313-L348 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | DataFrameModel.sort | def sort(self, column, order=Qt.AscendingOrder):
"""Overriding sort method"""
if self.complex_intran is not None:
if self.complex_intran.any(axis=0).iloc[column]:
QMessageBox.critical(self.dialog, "Error",
"TypeError error: no ordering "
"relation is defined for complex numbers")
return False
try:
ascending = order == Qt.AscendingOrder
if column >= 0:
try:
self.df.sort_values(by=self.df.columns[column],
ascending=ascending, inplace=True,
kind='mergesort')
except AttributeError:
# for pandas version < 0.17
self.df.sort(columns=self.df.columns[column],
ascending=ascending, inplace=True,
kind='mergesort')
except ValueError as e:
# Not possible to sort on duplicate columns #5225
QMessageBox.critical(self.dialog, "Error",
"ValueError: %s" % to_text_string(e))
except SystemError as e:
# Not possible to sort on category dtypes #5361
QMessageBox.critical(self.dialog, "Error",
"SystemError: %s" % to_text_string(e))
self.update_df_index()
else:
# To sort by index
self.df.sort_index(inplace=True, ascending=ascending)
self.update_df_index()
except TypeError as e:
QMessageBox.critical(self.dialog, "Error",
"TypeError error: %s" % str(e))
return False
self.reset()
return True | python | def sort(self, column, order=Qt.AscendingOrder):
"""Overriding sort method"""
if self.complex_intran is not None:
if self.complex_intran.any(axis=0).iloc[column]:
QMessageBox.critical(self.dialog, "Error",
"TypeError error: no ordering "
"relation is defined for complex numbers")
return False
try:
ascending = order == Qt.AscendingOrder
if column >= 0:
try:
self.df.sort_values(by=self.df.columns[column],
ascending=ascending, inplace=True,
kind='mergesort')
except AttributeError:
# for pandas version < 0.17
self.df.sort(columns=self.df.columns[column],
ascending=ascending, inplace=True,
kind='mergesort')
except ValueError as e:
# Not possible to sort on duplicate columns #5225
QMessageBox.critical(self.dialog, "Error",
"ValueError: %s" % to_text_string(e))
except SystemError as e:
# Not possible to sort on category dtypes #5361
QMessageBox.critical(self.dialog, "Error",
"SystemError: %s" % to_text_string(e))
self.update_df_index()
else:
# To sort by index
self.df.sort_index(inplace=True, ascending=ascending)
self.update_df_index()
except TypeError as e:
QMessageBox.critical(self.dialog, "Error",
"TypeError error: %s" % str(e))
return False
self.reset()
return True | [
"def",
"sort",
"(",
"self",
",",
"column",
",",
"order",
"=",
"Qt",
".",
"AscendingOrder",
")",
":",
"if",
"self",
".",
"complex_intran",
"is",
"not",
"None",
":",
"if",
"self",
".",
"complex_intran",
".",
"any",
"(",
"axis",
"=",
"0",
")",
".",
"iloc",
"[",
"column",
"]",
":",
"QMessageBox",
".",
"critical",
"(",
"self",
".",
"dialog",
",",
"\"Error\"",
",",
"\"TypeError error: no ordering \"",
"\"relation is defined for complex numbers\"",
")",
"return",
"False",
"try",
":",
"ascending",
"=",
"order",
"==",
"Qt",
".",
"AscendingOrder",
"if",
"column",
">=",
"0",
":",
"try",
":",
"self",
".",
"df",
".",
"sort_values",
"(",
"by",
"=",
"self",
".",
"df",
".",
"columns",
"[",
"column",
"]",
",",
"ascending",
"=",
"ascending",
",",
"inplace",
"=",
"True",
",",
"kind",
"=",
"'mergesort'",
")",
"except",
"AttributeError",
":",
"# for pandas version < 0.17\r",
"self",
".",
"df",
".",
"sort",
"(",
"columns",
"=",
"self",
".",
"df",
".",
"columns",
"[",
"column",
"]",
",",
"ascending",
"=",
"ascending",
",",
"inplace",
"=",
"True",
",",
"kind",
"=",
"'mergesort'",
")",
"except",
"ValueError",
"as",
"e",
":",
"# Not possible to sort on duplicate columns #5225\r",
"QMessageBox",
".",
"critical",
"(",
"self",
".",
"dialog",
",",
"\"Error\"",
",",
"\"ValueError: %s\"",
"%",
"to_text_string",
"(",
"e",
")",
")",
"except",
"SystemError",
"as",
"e",
":",
"# Not possible to sort on category dtypes #5361\r",
"QMessageBox",
".",
"critical",
"(",
"self",
".",
"dialog",
",",
"\"Error\"",
",",
"\"SystemError: %s\"",
"%",
"to_text_string",
"(",
"e",
")",
")",
"self",
".",
"update_df_index",
"(",
")",
"else",
":",
"# To sort by index\r",
"self",
".",
"df",
".",
"sort_index",
"(",
"inplace",
"=",
"True",
",",
"ascending",
"=",
"ascending",
")",
"self",
".",
"update_df_index",
"(",
")",
"except",
"TypeError",
"as",
"e",
":",
"QMessageBox",
".",
"critical",
"(",
"self",
".",
"dialog",
",",
"\"Error\"",
",",
"\"TypeError error: %s\"",
"%",
"str",
"(",
"e",
")",
")",
"return",
"False",
"self",
".",
"reset",
"(",
")",
"return",
"True"
] | Overriding sort method | [
"Overriding",
"sort",
"method"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L350-L389 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | DataFrameModel.flags | def flags(self, index):
"""Set flags"""
return Qt.ItemFlags(QAbstractTableModel.flags(self, index) |
Qt.ItemIsEditable) | python | def flags(self, index):
"""Set flags"""
return Qt.ItemFlags(QAbstractTableModel.flags(self, index) |
Qt.ItemIsEditable) | [
"def",
"flags",
"(",
"self",
",",
"index",
")",
":",
"return",
"Qt",
".",
"ItemFlags",
"(",
"QAbstractTableModel",
".",
"flags",
"(",
"self",
",",
"index",
")",
"|",
"Qt",
".",
"ItemIsEditable",
")"
] | Set flags | [
"Set",
"flags"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L391-L394 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | DataFrameModel.setData | def setData(self, index, value, role=Qt.EditRole, change_type=None):
"""Cell content change"""
column = index.column()
row = index.row()
if index in self.display_error_idxs:
return False
if change_type is not None:
try:
value = self.data(index, role=Qt.DisplayRole)
val = from_qvariant(value, str)
if change_type is bool:
val = bool_false_check(val)
self.df.iloc[row, column] = change_type(val)
except ValueError:
self.df.iloc[row, column] = change_type('0')
else:
val = from_qvariant(value, str)
current_value = self.get_value(row, column)
if isinstance(current_value, (bool, np.bool_)):
val = bool_false_check(val)
supported_types = (bool, np.bool_) + REAL_NUMBER_TYPES
if (isinstance(current_value, supported_types) or
is_text_string(current_value)):
try:
self.df.iloc[row, column] = current_value.__class__(val)
except (ValueError, OverflowError) as e:
QMessageBox.critical(self.dialog, "Error",
str(type(e).__name__) + ": " + str(e))
return False
else:
QMessageBox.critical(self.dialog, "Error",
"Editing dtype {0!s} not yet supported."
.format(type(current_value).__name__))
return False
self.max_min_col_update()
self.dataChanged.emit(index, index)
return True | python | def setData(self, index, value, role=Qt.EditRole, change_type=None):
"""Cell content change"""
column = index.column()
row = index.row()
if index in self.display_error_idxs:
return False
if change_type is not None:
try:
value = self.data(index, role=Qt.DisplayRole)
val = from_qvariant(value, str)
if change_type is bool:
val = bool_false_check(val)
self.df.iloc[row, column] = change_type(val)
except ValueError:
self.df.iloc[row, column] = change_type('0')
else:
val = from_qvariant(value, str)
current_value = self.get_value(row, column)
if isinstance(current_value, (bool, np.bool_)):
val = bool_false_check(val)
supported_types = (bool, np.bool_) + REAL_NUMBER_TYPES
if (isinstance(current_value, supported_types) or
is_text_string(current_value)):
try:
self.df.iloc[row, column] = current_value.__class__(val)
except (ValueError, OverflowError) as e:
QMessageBox.critical(self.dialog, "Error",
str(type(e).__name__) + ": " + str(e))
return False
else:
QMessageBox.critical(self.dialog, "Error",
"Editing dtype {0!s} not yet supported."
.format(type(current_value).__name__))
return False
self.max_min_col_update()
self.dataChanged.emit(index, index)
return True | [
"def",
"setData",
"(",
"self",
",",
"index",
",",
"value",
",",
"role",
"=",
"Qt",
".",
"EditRole",
",",
"change_type",
"=",
"None",
")",
":",
"column",
"=",
"index",
".",
"column",
"(",
")",
"row",
"=",
"index",
".",
"row",
"(",
")",
"if",
"index",
"in",
"self",
".",
"display_error_idxs",
":",
"return",
"False",
"if",
"change_type",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"self",
".",
"data",
"(",
"index",
",",
"role",
"=",
"Qt",
".",
"DisplayRole",
")",
"val",
"=",
"from_qvariant",
"(",
"value",
",",
"str",
")",
"if",
"change_type",
"is",
"bool",
":",
"val",
"=",
"bool_false_check",
"(",
"val",
")",
"self",
".",
"df",
".",
"iloc",
"[",
"row",
",",
"column",
"]",
"=",
"change_type",
"(",
"val",
")",
"except",
"ValueError",
":",
"self",
".",
"df",
".",
"iloc",
"[",
"row",
",",
"column",
"]",
"=",
"change_type",
"(",
"'0'",
")",
"else",
":",
"val",
"=",
"from_qvariant",
"(",
"value",
",",
"str",
")",
"current_value",
"=",
"self",
".",
"get_value",
"(",
"row",
",",
"column",
")",
"if",
"isinstance",
"(",
"current_value",
",",
"(",
"bool",
",",
"np",
".",
"bool_",
")",
")",
":",
"val",
"=",
"bool_false_check",
"(",
"val",
")",
"supported_types",
"=",
"(",
"bool",
",",
"np",
".",
"bool_",
")",
"+",
"REAL_NUMBER_TYPES",
"if",
"(",
"isinstance",
"(",
"current_value",
",",
"supported_types",
")",
"or",
"is_text_string",
"(",
"current_value",
")",
")",
":",
"try",
":",
"self",
".",
"df",
".",
"iloc",
"[",
"row",
",",
"column",
"]",
"=",
"current_value",
".",
"__class__",
"(",
"val",
")",
"except",
"(",
"ValueError",
",",
"OverflowError",
")",
"as",
"e",
":",
"QMessageBox",
".",
"critical",
"(",
"self",
".",
"dialog",
",",
"\"Error\"",
",",
"str",
"(",
"type",
"(",
"e",
")",
".",
"__name__",
")",
"+",
"\": \"",
"+",
"str",
"(",
"e",
")",
")",
"return",
"False",
"else",
":",
"QMessageBox",
".",
"critical",
"(",
"self",
".",
"dialog",
",",
"\"Error\"",
",",
"\"Editing dtype {0!s} not yet supported.\"",
".",
"format",
"(",
"type",
"(",
"current_value",
")",
".",
"__name__",
")",
")",
"return",
"False",
"self",
".",
"max_min_col_update",
"(",
")",
"self",
".",
"dataChanged",
".",
"emit",
"(",
"index",
",",
"index",
")",
"return",
"True"
] | Cell content change | [
"Cell",
"content",
"change"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L396-L433 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | DataFrameModel.columnCount | def columnCount(self, index=QModelIndex()):
"""DataFrame column number"""
# Avoid a "Qt exception in virtual methods" generated in our
# tests on Windows/Python 3.7
# See PR 8910
try:
# This is done to implement series
if len(self.df.shape) == 1:
return 2
elif self.total_cols <= self.cols_loaded:
return self.total_cols
else:
return self.cols_loaded
except AttributeError:
return 0 | python | def columnCount(self, index=QModelIndex()):
"""DataFrame column number"""
# Avoid a "Qt exception in virtual methods" generated in our
# tests on Windows/Python 3.7
# See PR 8910
try:
# This is done to implement series
if len(self.df.shape) == 1:
return 2
elif self.total_cols <= self.cols_loaded:
return self.total_cols
else:
return self.cols_loaded
except AttributeError:
return 0 | [
"def",
"columnCount",
"(",
"self",
",",
"index",
"=",
"QModelIndex",
"(",
")",
")",
":",
"# Avoid a \"Qt exception in virtual methods\" generated in our\r",
"# tests on Windows/Python 3.7\r",
"# See PR 8910\r",
"try",
":",
"# This is done to implement series\r",
"if",
"len",
"(",
"self",
".",
"df",
".",
"shape",
")",
"==",
"1",
":",
"return",
"2",
"elif",
"self",
".",
"total_cols",
"<=",
"self",
".",
"cols_loaded",
":",
"return",
"self",
".",
"total_cols",
"else",
":",
"return",
"self",
".",
"cols_loaded",
"except",
"AttributeError",
":",
"return",
"0"
] | DataFrame column number | [
"DataFrame",
"column",
"number"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L469-L483 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | DataFrameView.load_more_data | def load_more_data(self, value, rows=False, columns=False):
"""Load more rows and columns to display."""
try:
if rows and value == self.verticalScrollBar().maximum():
self.model().fetch_more(rows=rows)
self.sig_fetch_more_rows.emit()
if columns and value == self.horizontalScrollBar().maximum():
self.model().fetch_more(columns=columns)
self.sig_fetch_more_columns.emit()
except NameError:
# Needed to handle a NameError while fetching data when closing
# See issue 7880
pass | python | def load_more_data(self, value, rows=False, columns=False):
"""Load more rows and columns to display."""
try:
if rows and value == self.verticalScrollBar().maximum():
self.model().fetch_more(rows=rows)
self.sig_fetch_more_rows.emit()
if columns and value == self.horizontalScrollBar().maximum():
self.model().fetch_more(columns=columns)
self.sig_fetch_more_columns.emit()
except NameError:
# Needed to handle a NameError while fetching data when closing
# See issue 7880
pass | [
"def",
"load_more_data",
"(",
"self",
",",
"value",
",",
"rows",
"=",
"False",
",",
"columns",
"=",
"False",
")",
":",
"try",
":",
"if",
"rows",
"and",
"value",
"==",
"self",
".",
"verticalScrollBar",
"(",
")",
".",
"maximum",
"(",
")",
":",
"self",
".",
"model",
"(",
")",
".",
"fetch_more",
"(",
"rows",
"=",
"rows",
")",
"self",
".",
"sig_fetch_more_rows",
".",
"emit",
"(",
")",
"if",
"columns",
"and",
"value",
"==",
"self",
".",
"horizontalScrollBar",
"(",
")",
".",
"maximum",
"(",
")",
":",
"self",
".",
"model",
"(",
")",
".",
"fetch_more",
"(",
"columns",
"=",
"columns",
")",
"self",
".",
"sig_fetch_more_columns",
".",
"emit",
"(",
")",
"except",
"NameError",
":",
"# Needed to handle a NameError while fetching data when closing\r",
"# See issue 7880\r",
"pass"
] | Load more rows and columns to display. | [
"Load",
"more",
"rows",
"and",
"columns",
"to",
"display",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L524-L537 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | DataFrameView.sortByColumn | def sortByColumn(self, index):
"""Implement a column sort."""
if self.sort_old == [None]:
self.header_class.setSortIndicatorShown(True)
sort_order = self.header_class.sortIndicatorOrder()
self.sig_sort_by_column.emit()
if not self.model().sort(index, sort_order):
if len(self.sort_old) != 2:
self.header_class.setSortIndicatorShown(False)
else:
self.header_class.setSortIndicator(self.sort_old[0],
self.sort_old[1])
return
self.sort_old = [index, self.header_class.sortIndicatorOrder()] | python | def sortByColumn(self, index):
"""Implement a column sort."""
if self.sort_old == [None]:
self.header_class.setSortIndicatorShown(True)
sort_order = self.header_class.sortIndicatorOrder()
self.sig_sort_by_column.emit()
if not self.model().sort(index, sort_order):
if len(self.sort_old) != 2:
self.header_class.setSortIndicatorShown(False)
else:
self.header_class.setSortIndicator(self.sort_old[0],
self.sort_old[1])
return
self.sort_old = [index, self.header_class.sortIndicatorOrder()] | [
"def",
"sortByColumn",
"(",
"self",
",",
"index",
")",
":",
"if",
"self",
".",
"sort_old",
"==",
"[",
"None",
"]",
":",
"self",
".",
"header_class",
".",
"setSortIndicatorShown",
"(",
"True",
")",
"sort_order",
"=",
"self",
".",
"header_class",
".",
"sortIndicatorOrder",
"(",
")",
"self",
".",
"sig_sort_by_column",
".",
"emit",
"(",
")",
"if",
"not",
"self",
".",
"model",
"(",
")",
".",
"sort",
"(",
"index",
",",
"sort_order",
")",
":",
"if",
"len",
"(",
"self",
".",
"sort_old",
")",
"!=",
"2",
":",
"self",
".",
"header_class",
".",
"setSortIndicatorShown",
"(",
"False",
")",
"else",
":",
"self",
".",
"header_class",
".",
"setSortIndicator",
"(",
"self",
".",
"sort_old",
"[",
"0",
"]",
",",
"self",
".",
"sort_old",
"[",
"1",
"]",
")",
"return",
"self",
".",
"sort_old",
"=",
"[",
"index",
",",
"self",
".",
"header_class",
".",
"sortIndicatorOrder",
"(",
")",
"]"
] | Implement a column sort. | [
"Implement",
"a",
"column",
"sort",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L539-L552 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | DataFrameView.setup_menu | def setup_menu(self):
"""Setup context menu."""
copy_action = create_action(self, _('Copy'),
shortcut=keybinding('Copy'),
icon=ima.icon('editcopy'),
triggered=self.copy,
context=Qt.WidgetShortcut)
functions = ((_("To bool"), bool), (_("To complex"), complex),
(_("To int"), int), (_("To float"), float),
(_("To str"), to_text_string))
types_in_menu = [copy_action]
for name, func in functions:
slot = lambda func=func: self.change_type(func)
types_in_menu += [create_action(self, name,
triggered=slot,
context=Qt.WidgetShortcut)]
menu = QMenu(self)
add_actions(menu, types_in_menu)
return menu | python | def setup_menu(self):
"""Setup context menu."""
copy_action = create_action(self, _('Copy'),
shortcut=keybinding('Copy'),
icon=ima.icon('editcopy'),
triggered=self.copy,
context=Qt.WidgetShortcut)
functions = ((_("To bool"), bool), (_("To complex"), complex),
(_("To int"), int), (_("To float"), float),
(_("To str"), to_text_string))
types_in_menu = [copy_action]
for name, func in functions:
slot = lambda func=func: self.change_type(func)
types_in_menu += [create_action(self, name,
triggered=slot,
context=Qt.WidgetShortcut)]
menu = QMenu(self)
add_actions(menu, types_in_menu)
return menu | [
"def",
"setup_menu",
"(",
"self",
")",
":",
"copy_action",
"=",
"create_action",
"(",
"self",
",",
"_",
"(",
"'Copy'",
")",
",",
"shortcut",
"=",
"keybinding",
"(",
"'Copy'",
")",
",",
"icon",
"=",
"ima",
".",
"icon",
"(",
"'editcopy'",
")",
",",
"triggered",
"=",
"self",
".",
"copy",
",",
"context",
"=",
"Qt",
".",
"WidgetShortcut",
")",
"functions",
"=",
"(",
"(",
"_",
"(",
"\"To bool\"",
")",
",",
"bool",
")",
",",
"(",
"_",
"(",
"\"To complex\"",
")",
",",
"complex",
")",
",",
"(",
"_",
"(",
"\"To int\"",
")",
",",
"int",
")",
",",
"(",
"_",
"(",
"\"To float\"",
")",
",",
"float",
")",
",",
"(",
"_",
"(",
"\"To str\"",
")",
",",
"to_text_string",
")",
")",
"types_in_menu",
"=",
"[",
"copy_action",
"]",
"for",
"name",
",",
"func",
"in",
"functions",
":",
"slot",
"=",
"lambda",
"func",
"=",
"func",
":",
"self",
".",
"change_type",
"(",
"func",
")",
"types_in_menu",
"+=",
"[",
"create_action",
"(",
"self",
",",
"name",
",",
"triggered",
"=",
"slot",
",",
"context",
"=",
"Qt",
".",
"WidgetShortcut",
")",
"]",
"menu",
"=",
"QMenu",
"(",
"self",
")",
"add_actions",
"(",
"menu",
",",
"types_in_menu",
")",
"return",
"menu"
] | Setup context menu. | [
"Setup",
"context",
"menu",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L559-L577 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | DataFrameView.change_type | def change_type(self, func):
"""A function that changes types of cells."""
model = self.model()
index_list = self.selectedIndexes()
[model.setData(i, '', change_type=func) for i in index_list] | python | def change_type(self, func):
"""A function that changes types of cells."""
model = self.model()
index_list = self.selectedIndexes()
[model.setData(i, '', change_type=func) for i in index_list] | [
"def",
"change_type",
"(",
"self",
",",
"func",
")",
":",
"model",
"=",
"self",
".",
"model",
"(",
")",
"index_list",
"=",
"self",
".",
"selectedIndexes",
"(",
")",
"[",
"model",
".",
"setData",
"(",
"i",
",",
"''",
",",
"change_type",
"=",
"func",
")",
"for",
"i",
"in",
"index_list",
"]"
] | A function that changes types of cells. | [
"A",
"function",
"that",
"changes",
"types",
"of",
"cells",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L579-L583 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | DataFrameView.copy | def copy(self):
"""Copy text to clipboard"""
if not self.selectedIndexes():
return
(row_min, row_max,
col_min, col_max) = get_idx_rect(self.selectedIndexes())
index = header = False
df = self.model().df
obj = df.iloc[slice(row_min, row_max + 1),
slice(col_min, col_max + 1)]
output = io.StringIO()
obj.to_csv(output, sep='\t', index=index, header=header)
if not PY2:
contents = output.getvalue()
else:
contents = output.getvalue().decode('utf-8')
output.close()
clipboard = QApplication.clipboard()
clipboard.setText(contents) | python | def copy(self):
"""Copy text to clipboard"""
if not self.selectedIndexes():
return
(row_min, row_max,
col_min, col_max) = get_idx_rect(self.selectedIndexes())
index = header = False
df = self.model().df
obj = df.iloc[slice(row_min, row_max + 1),
slice(col_min, col_max + 1)]
output = io.StringIO()
obj.to_csv(output, sep='\t', index=index, header=header)
if not PY2:
contents = output.getvalue()
else:
contents = output.getvalue().decode('utf-8')
output.close()
clipboard = QApplication.clipboard()
clipboard.setText(contents) | [
"def",
"copy",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"selectedIndexes",
"(",
")",
":",
"return",
"(",
"row_min",
",",
"row_max",
",",
"col_min",
",",
"col_max",
")",
"=",
"get_idx_rect",
"(",
"self",
".",
"selectedIndexes",
"(",
")",
")",
"index",
"=",
"header",
"=",
"False",
"df",
"=",
"self",
".",
"model",
"(",
")",
".",
"df",
"obj",
"=",
"df",
".",
"iloc",
"[",
"slice",
"(",
"row_min",
",",
"row_max",
"+",
"1",
")",
",",
"slice",
"(",
"col_min",
",",
"col_max",
"+",
"1",
")",
"]",
"output",
"=",
"io",
".",
"StringIO",
"(",
")",
"obj",
".",
"to_csv",
"(",
"output",
",",
"sep",
"=",
"'\\t'",
",",
"index",
"=",
"index",
",",
"header",
"=",
"header",
")",
"if",
"not",
"PY2",
":",
"contents",
"=",
"output",
".",
"getvalue",
"(",
")",
"else",
":",
"contents",
"=",
"output",
".",
"getvalue",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"output",
".",
"close",
"(",
")",
"clipboard",
"=",
"QApplication",
".",
"clipboard",
"(",
")",
"clipboard",
".",
"setText",
"(",
"contents",
")"
] | Copy text to clipboard | [
"Copy",
"text",
"to",
"clipboard"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L586-L604 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | DataFrameHeaderModel.rowCount | def rowCount(self, index=None):
"""Get number of rows in the header."""
if self.axis == 0:
return max(1, self._shape[0])
else:
if self.total_rows <= self.rows_loaded:
return self.total_rows
else:
return self.rows_loaded | python | def rowCount(self, index=None):
"""Get number of rows in the header."""
if self.axis == 0:
return max(1, self._shape[0])
else:
if self.total_rows <= self.rows_loaded:
return self.total_rows
else:
return self.rows_loaded | [
"def",
"rowCount",
"(",
"self",
",",
"index",
"=",
"None",
")",
":",
"if",
"self",
".",
"axis",
"==",
"0",
":",
"return",
"max",
"(",
"1",
",",
"self",
".",
"_shape",
"[",
"0",
"]",
")",
"else",
":",
"if",
"self",
".",
"total_rows",
"<=",
"self",
".",
"rows_loaded",
":",
"return",
"self",
".",
"total_rows",
"else",
":",
"return",
"self",
".",
"rows_loaded"
] | Get number of rows in the header. | [
"Get",
"number",
"of",
"rows",
"in",
"the",
"header",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L645-L653 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | DataFrameHeaderModel.columnCount | def columnCount(self, index=QModelIndex()):
"""DataFrame column number"""
if self.axis == 0:
if self.total_cols <= self.cols_loaded:
return self.total_cols
else:
return self.cols_loaded
else:
return max(1, self._shape[1]) | python | def columnCount(self, index=QModelIndex()):
"""DataFrame column number"""
if self.axis == 0:
if self.total_cols <= self.cols_loaded:
return self.total_cols
else:
return self.cols_loaded
else:
return max(1, self._shape[1]) | [
"def",
"columnCount",
"(",
"self",
",",
"index",
"=",
"QModelIndex",
"(",
")",
")",
":",
"if",
"self",
".",
"axis",
"==",
"0",
":",
"if",
"self",
".",
"total_cols",
"<=",
"self",
".",
"cols_loaded",
":",
"return",
"self",
".",
"total_cols",
"else",
":",
"return",
"self",
".",
"cols_loaded",
"else",
":",
"return",
"max",
"(",
"1",
",",
"self",
".",
"_shape",
"[",
"1",
"]",
")"
] | DataFrame column number | [
"DataFrame",
"column",
"number"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L655-L663 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | DataFrameHeaderModel.fetch_more | def fetch_more(self, rows=False, columns=False):
"""Get more columns or rows (based on axis)."""
if self.axis == 1 and self.total_rows > self.rows_loaded:
reminder = self.total_rows - self.rows_loaded
items_to_fetch = min(reminder, ROWS_TO_LOAD)
self.beginInsertRows(QModelIndex(), self.rows_loaded,
self.rows_loaded + items_to_fetch - 1)
self.rows_loaded += items_to_fetch
self.endInsertRows()
if self.axis == 0 and self.total_cols > self.cols_loaded:
reminder = self.total_cols - self.cols_loaded
items_to_fetch = min(reminder, COLS_TO_LOAD)
self.beginInsertColumns(QModelIndex(), self.cols_loaded,
self.cols_loaded + items_to_fetch - 1)
self.cols_loaded += items_to_fetch
self.endInsertColumns() | python | def fetch_more(self, rows=False, columns=False):
"""Get more columns or rows (based on axis)."""
if self.axis == 1 and self.total_rows > self.rows_loaded:
reminder = self.total_rows - self.rows_loaded
items_to_fetch = min(reminder, ROWS_TO_LOAD)
self.beginInsertRows(QModelIndex(), self.rows_loaded,
self.rows_loaded + items_to_fetch - 1)
self.rows_loaded += items_to_fetch
self.endInsertRows()
if self.axis == 0 and self.total_cols > self.cols_loaded:
reminder = self.total_cols - self.cols_loaded
items_to_fetch = min(reminder, COLS_TO_LOAD)
self.beginInsertColumns(QModelIndex(), self.cols_loaded,
self.cols_loaded + items_to_fetch - 1)
self.cols_loaded += items_to_fetch
self.endInsertColumns() | [
"def",
"fetch_more",
"(",
"self",
",",
"rows",
"=",
"False",
",",
"columns",
"=",
"False",
")",
":",
"if",
"self",
".",
"axis",
"==",
"1",
"and",
"self",
".",
"total_rows",
">",
"self",
".",
"rows_loaded",
":",
"reminder",
"=",
"self",
".",
"total_rows",
"-",
"self",
".",
"rows_loaded",
"items_to_fetch",
"=",
"min",
"(",
"reminder",
",",
"ROWS_TO_LOAD",
")",
"self",
".",
"beginInsertRows",
"(",
"QModelIndex",
"(",
")",
",",
"self",
".",
"rows_loaded",
",",
"self",
".",
"rows_loaded",
"+",
"items_to_fetch",
"-",
"1",
")",
"self",
".",
"rows_loaded",
"+=",
"items_to_fetch",
"self",
".",
"endInsertRows",
"(",
")",
"if",
"self",
".",
"axis",
"==",
"0",
"and",
"self",
".",
"total_cols",
">",
"self",
".",
"cols_loaded",
":",
"reminder",
"=",
"self",
".",
"total_cols",
"-",
"self",
".",
"cols_loaded",
"items_to_fetch",
"=",
"min",
"(",
"reminder",
",",
"COLS_TO_LOAD",
")",
"self",
".",
"beginInsertColumns",
"(",
"QModelIndex",
"(",
")",
",",
"self",
".",
"cols_loaded",
",",
"self",
".",
"cols_loaded",
"+",
"items_to_fetch",
"-",
"1",
")",
"self",
".",
"cols_loaded",
"+=",
"items_to_fetch",
"self",
".",
"endInsertColumns",
"(",
")"
] | Get more columns or rows (based on axis). | [
"Get",
"more",
"columns",
"or",
"rows",
"(",
"based",
"on",
"axis",
")",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L665-L680 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | DataFrameHeaderModel.sort | def sort(self, column, order=Qt.AscendingOrder):
"""Overriding sort method."""
ascending = order == Qt.AscendingOrder
self.model.sort(self.COLUMN_INDEX, order=ascending)
return True | python | def sort(self, column, order=Qt.AscendingOrder):
"""Overriding sort method."""
ascending = order == Qt.AscendingOrder
self.model.sort(self.COLUMN_INDEX, order=ascending)
return True | [
"def",
"sort",
"(",
"self",
",",
"column",
",",
"order",
"=",
"Qt",
".",
"AscendingOrder",
")",
":",
"ascending",
"=",
"order",
"==",
"Qt",
".",
"AscendingOrder",
"self",
".",
"model",
".",
"sort",
"(",
"self",
".",
"COLUMN_INDEX",
",",
"order",
"=",
"ascending",
")",
"return",
"True"
] | Overriding sort method. | [
"Overriding",
"sort",
"method",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L682-L686 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | DataFrameHeaderModel.headerData | def headerData(self, section, orientation, role):
"""Get the information to put in the header."""
if role == Qt.TextAlignmentRole:
if orientation == Qt.Horizontal:
return Qt.AlignCenter | Qt.AlignBottom
else:
return Qt.AlignRight | Qt.AlignVCenter
if role != Qt.DisplayRole and role != Qt.ToolTipRole:
return None
if self.axis == 1 and self._shape[1] <= 1:
return None
orient_axis = 0 if orientation == Qt.Horizontal else 1
if self.model.header_shape[orient_axis] > 1:
header = section
else:
header = self.model.header(self.axis, section)
# Don't perform any conversion on strings
# because it leads to differences between
# the data present in the dataframe and
# what is shown by Spyder
if not is_type_text_string(header):
header = to_text_string(header)
return header | python | def headerData(self, section, orientation, role):
"""Get the information to put in the header."""
if role == Qt.TextAlignmentRole:
if orientation == Qt.Horizontal:
return Qt.AlignCenter | Qt.AlignBottom
else:
return Qt.AlignRight | Qt.AlignVCenter
if role != Qt.DisplayRole and role != Qt.ToolTipRole:
return None
if self.axis == 1 and self._shape[1] <= 1:
return None
orient_axis = 0 if orientation == Qt.Horizontal else 1
if self.model.header_shape[orient_axis] > 1:
header = section
else:
header = self.model.header(self.axis, section)
# Don't perform any conversion on strings
# because it leads to differences between
# the data present in the dataframe and
# what is shown by Spyder
if not is_type_text_string(header):
header = to_text_string(header)
return header | [
"def",
"headerData",
"(",
"self",
",",
"section",
",",
"orientation",
",",
"role",
")",
":",
"if",
"role",
"==",
"Qt",
".",
"TextAlignmentRole",
":",
"if",
"orientation",
"==",
"Qt",
".",
"Horizontal",
":",
"return",
"Qt",
".",
"AlignCenter",
"|",
"Qt",
".",
"AlignBottom",
"else",
":",
"return",
"Qt",
".",
"AlignRight",
"|",
"Qt",
".",
"AlignVCenter",
"if",
"role",
"!=",
"Qt",
".",
"DisplayRole",
"and",
"role",
"!=",
"Qt",
".",
"ToolTipRole",
":",
"return",
"None",
"if",
"self",
".",
"axis",
"==",
"1",
"and",
"self",
".",
"_shape",
"[",
"1",
"]",
"<=",
"1",
":",
"return",
"None",
"orient_axis",
"=",
"0",
"if",
"orientation",
"==",
"Qt",
".",
"Horizontal",
"else",
"1",
"if",
"self",
".",
"model",
".",
"header_shape",
"[",
"orient_axis",
"]",
">",
"1",
":",
"header",
"=",
"section",
"else",
":",
"header",
"=",
"self",
".",
"model",
".",
"header",
"(",
"self",
".",
"axis",
",",
"section",
")",
"# Don't perform any conversion on strings\r",
"# because it leads to differences between\r",
"# the data present in the dataframe and\r",
"# what is shown by Spyder\r",
"if",
"not",
"is_type_text_string",
"(",
"header",
")",
":",
"header",
"=",
"to_text_string",
"(",
"header",
")",
"return",
"header"
] | Get the information to put in the header. | [
"Get",
"the",
"information",
"to",
"put",
"in",
"the",
"header",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L688-L712 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | DataFrameHeaderModel.data | def data(self, index, role):
"""
Get the data for the header.
This is used when a header has levels.
"""
if not index.isValid() or \
index.row() >= self._shape[0] or \
index.column() >= self._shape[1]:
return None
row, col = ((index.row(), index.column()) if self.axis == 0
else (index.column(), index.row()))
if role != Qt.DisplayRole:
return None
if self.axis == 0 and self._shape[0] <= 1:
return None
header = self.model.header(self.axis, col, row)
# Don't perform any conversion on strings
# because it leads to differences between
# the data present in the dataframe and
# what is shown by Spyder
if not is_type_text_string(header):
header = to_text_string(header)
return header | python | def data(self, index, role):
"""
Get the data for the header.
This is used when a header has levels.
"""
if not index.isValid() or \
index.row() >= self._shape[0] or \
index.column() >= self._shape[1]:
return None
row, col = ((index.row(), index.column()) if self.axis == 0
else (index.column(), index.row()))
if role != Qt.DisplayRole:
return None
if self.axis == 0 and self._shape[0] <= 1:
return None
header = self.model.header(self.axis, col, row)
# Don't perform any conversion on strings
# because it leads to differences between
# the data present in the dataframe and
# what is shown by Spyder
if not is_type_text_string(header):
header = to_text_string(header)
return header | [
"def",
"data",
"(",
"self",
",",
"index",
",",
"role",
")",
":",
"if",
"not",
"index",
".",
"isValid",
"(",
")",
"or",
"index",
".",
"row",
"(",
")",
">=",
"self",
".",
"_shape",
"[",
"0",
"]",
"or",
"index",
".",
"column",
"(",
")",
">=",
"self",
".",
"_shape",
"[",
"1",
"]",
":",
"return",
"None",
"row",
",",
"col",
"=",
"(",
"(",
"index",
".",
"row",
"(",
")",
",",
"index",
".",
"column",
"(",
")",
")",
"if",
"self",
".",
"axis",
"==",
"0",
"else",
"(",
"index",
".",
"column",
"(",
")",
",",
"index",
".",
"row",
"(",
")",
")",
")",
"if",
"role",
"!=",
"Qt",
".",
"DisplayRole",
":",
"return",
"None",
"if",
"self",
".",
"axis",
"==",
"0",
"and",
"self",
".",
"_shape",
"[",
"0",
"]",
"<=",
"1",
":",
"return",
"None",
"header",
"=",
"self",
".",
"model",
".",
"header",
"(",
"self",
".",
"axis",
",",
"col",
",",
"row",
")",
"# Don't perform any conversion on strings\r",
"# because it leads to differences between\r",
"# the data present in the dataframe and\r",
"# what is shown by Spyder\r",
"if",
"not",
"is_type_text_string",
"(",
"header",
")",
":",
"header",
"=",
"to_text_string",
"(",
"header",
")",
"return",
"header"
] | Get the data for the header.
This is used when a header has levels. | [
"Get",
"the",
"data",
"for",
"the",
"header",
".",
"This",
"is",
"used",
"when",
"a",
"header",
"has",
"levels",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L714-L740 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | DataFrameLevelModel.headerData | def headerData(self, section, orientation, role):
"""
Get the text to put in the header of the levels of the indexes.
By default it returns 'Index i', where i is the section in the index
"""
if role == Qt.TextAlignmentRole:
if orientation == Qt.Horizontal:
return Qt.AlignCenter | Qt.AlignBottom
else:
return Qt.AlignRight | Qt.AlignVCenter
if role != Qt.DisplayRole and role != Qt.ToolTipRole:
return None
if self.model.header_shape[0] <= 1 and orientation == Qt.Horizontal:
if self.model.name(1,section):
return self.model.name(1,section)
return _('Index')
elif self.model.header_shape[0] <= 1:
return None
elif self.model.header_shape[1] <= 1 and orientation == Qt.Vertical:
return None
return _('Index') + ' ' + to_text_string(section) | python | def headerData(self, section, orientation, role):
"""
Get the text to put in the header of the levels of the indexes.
By default it returns 'Index i', where i is the section in the index
"""
if role == Qt.TextAlignmentRole:
if orientation == Qt.Horizontal:
return Qt.AlignCenter | Qt.AlignBottom
else:
return Qt.AlignRight | Qt.AlignVCenter
if role != Qt.DisplayRole and role != Qt.ToolTipRole:
return None
if self.model.header_shape[0] <= 1 and orientation == Qt.Horizontal:
if self.model.name(1,section):
return self.model.name(1,section)
return _('Index')
elif self.model.header_shape[0] <= 1:
return None
elif self.model.header_shape[1] <= 1 and orientation == Qt.Vertical:
return None
return _('Index') + ' ' + to_text_string(section) | [
"def",
"headerData",
"(",
"self",
",",
"section",
",",
"orientation",
",",
"role",
")",
":",
"if",
"role",
"==",
"Qt",
".",
"TextAlignmentRole",
":",
"if",
"orientation",
"==",
"Qt",
".",
"Horizontal",
":",
"return",
"Qt",
".",
"AlignCenter",
"|",
"Qt",
".",
"AlignBottom",
"else",
":",
"return",
"Qt",
".",
"AlignRight",
"|",
"Qt",
".",
"AlignVCenter",
"if",
"role",
"!=",
"Qt",
".",
"DisplayRole",
"and",
"role",
"!=",
"Qt",
".",
"ToolTipRole",
":",
"return",
"None",
"if",
"self",
".",
"model",
".",
"header_shape",
"[",
"0",
"]",
"<=",
"1",
"and",
"orientation",
"==",
"Qt",
".",
"Horizontal",
":",
"if",
"self",
".",
"model",
".",
"name",
"(",
"1",
",",
"section",
")",
":",
"return",
"self",
".",
"model",
".",
"name",
"(",
"1",
",",
"section",
")",
"return",
"_",
"(",
"'Index'",
")",
"elif",
"self",
".",
"model",
".",
"header_shape",
"[",
"0",
"]",
"<=",
"1",
":",
"return",
"None",
"elif",
"self",
".",
"model",
".",
"header_shape",
"[",
"1",
"]",
"<=",
"1",
"and",
"orientation",
"==",
"Qt",
".",
"Vertical",
":",
"return",
"None",
"return",
"_",
"(",
"'Index'",
")",
"+",
"' '",
"+",
"to_text_string",
"(",
"section",
")"
] | Get the text to put in the header of the levels of the indexes.
By default it returns 'Index i', where i is the section in the index | [
"Get",
"the",
"text",
"to",
"put",
"in",
"the",
"header",
"of",
"the",
"levels",
"of",
"the",
"indexes",
".",
"By",
"default",
"it",
"returns",
"Index",
"i",
"where",
"i",
"is",
"the",
"section",
"in",
"the",
"index"
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L776-L797 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | DataFrameLevelModel.data | def data(self, index, role):
"""Get the information of the levels."""
if not index.isValid():
return None
if role == Qt.FontRole:
return self._font
label = ''
if index.column() == self.model.header_shape[1] - 1:
label = str(self.model.name(0, index.row()))
elif index.row() == self.model.header_shape[0] - 1:
label = str(self.model.name(1, index.column()))
if role == Qt.DisplayRole and label:
return label
elif role == Qt.ForegroundRole:
return self._foreground
elif role == Qt.BackgroundRole:
return self._background
elif role == Qt.BackgroundRole:
return self._palette.window()
return None | python | def data(self, index, role):
"""Get the information of the levels."""
if not index.isValid():
return None
if role == Qt.FontRole:
return self._font
label = ''
if index.column() == self.model.header_shape[1] - 1:
label = str(self.model.name(0, index.row()))
elif index.row() == self.model.header_shape[0] - 1:
label = str(self.model.name(1, index.column()))
if role == Qt.DisplayRole and label:
return label
elif role == Qt.ForegroundRole:
return self._foreground
elif role == Qt.BackgroundRole:
return self._background
elif role == Qt.BackgroundRole:
return self._palette.window()
return None | [
"def",
"data",
"(",
"self",
",",
"index",
",",
"role",
")",
":",
"if",
"not",
"index",
".",
"isValid",
"(",
")",
":",
"return",
"None",
"if",
"role",
"==",
"Qt",
".",
"FontRole",
":",
"return",
"self",
".",
"_font",
"label",
"=",
"''",
"if",
"index",
".",
"column",
"(",
")",
"==",
"self",
".",
"model",
".",
"header_shape",
"[",
"1",
"]",
"-",
"1",
":",
"label",
"=",
"str",
"(",
"self",
".",
"model",
".",
"name",
"(",
"0",
",",
"index",
".",
"row",
"(",
")",
")",
")",
"elif",
"index",
".",
"row",
"(",
")",
"==",
"self",
".",
"model",
".",
"header_shape",
"[",
"0",
"]",
"-",
"1",
":",
"label",
"=",
"str",
"(",
"self",
".",
"model",
".",
"name",
"(",
"1",
",",
"index",
".",
"column",
"(",
")",
")",
")",
"if",
"role",
"==",
"Qt",
".",
"DisplayRole",
"and",
"label",
":",
"return",
"label",
"elif",
"role",
"==",
"Qt",
".",
"ForegroundRole",
":",
"return",
"self",
".",
"_foreground",
"elif",
"role",
"==",
"Qt",
".",
"BackgroundRole",
":",
"return",
"self",
".",
"_background",
"elif",
"role",
"==",
"Qt",
".",
"BackgroundRole",
":",
"return",
"self",
".",
"_palette",
".",
"window",
"(",
")",
"return",
"None"
] | Get the information of the levels. | [
"Get",
"the",
"information",
"of",
"the",
"levels",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L799-L818 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | DataFrameEditor.setup_and_check | def setup_and_check(self, data, title=''):
"""
Setup DataFrameEditor:
return False if data is not supported, True otherwise.
Supported types for data are DataFrame, Series and Index.
"""
self._selection_rec = False
self._model = None
self.layout = QGridLayout()
self.layout.setSpacing(0)
self.layout.setContentsMargins(0, 0, 0, 0)
self.setLayout(self.layout)
self.setWindowIcon(ima.icon('arredit'))
if title:
title = to_text_string(title) + " - %s" % data.__class__.__name__
else:
title = _("%s editor") % data.__class__.__name__
if isinstance(data, Series):
self.is_series = True
data = data.to_frame()
elif isinstance(data, Index):
data = DataFrame(data)
self.setWindowTitle(title)
self.resize(600, 500)
self.hscroll = QScrollBar(Qt.Horizontal)
self.vscroll = QScrollBar(Qt.Vertical)
# Create the view for the level
self.create_table_level()
# Create the view for the horizontal header
self.create_table_header()
# Create the view for the vertical index
self.create_table_index()
# Create the model and view of the data
self.dataModel = DataFrameModel(data, parent=self)
self.dataModel.dataChanged.connect(self.save_and_close_enable)
self.create_data_table()
self.layout.addWidget(self.hscroll, 2, 0, 1, 2)
self.layout.addWidget(self.vscroll, 0, 2, 2, 1)
# autosize columns on-demand
self._autosized_cols = set()
self._max_autosize_ms = None
self.dataTable.installEventFilter(self)
avg_width = self.fontMetrics().averageCharWidth()
self.min_trunc = avg_width * 12 # Minimum size for columns
self.max_width = avg_width * 64 # Maximum size for columns
self.setLayout(self.layout)
self.setMinimumSize(400, 300)
# Make the dialog act as a window
self.setWindowFlags(Qt.Window)
btn_layout = QHBoxLayout()
btn = QPushButton(_("Format"))
# disable format button for int type
btn_layout.addWidget(btn)
btn.clicked.connect(self.change_format)
btn = QPushButton(_('Resize'))
btn_layout.addWidget(btn)
btn.clicked.connect(self.resize_to_contents)
bgcolor = QCheckBox(_('Background color'))
bgcolor.setChecked(self.dataModel.bgcolor_enabled)
bgcolor.setEnabled(self.dataModel.bgcolor_enabled)
bgcolor.stateChanged.connect(self.change_bgcolor_enable)
btn_layout.addWidget(bgcolor)
self.bgcolor_global = QCheckBox(_('Column min/max'))
self.bgcolor_global.setChecked(self.dataModel.colum_avg_enabled)
self.bgcolor_global.setEnabled(not self.is_series and
self.dataModel.bgcolor_enabled)
self.bgcolor_global.stateChanged.connect(self.dataModel.colum_avg)
btn_layout.addWidget(self.bgcolor_global)
btn_layout.addStretch()
self.btn_save_and_close = QPushButton(_('Save and Close'))
self.btn_save_and_close.setDisabled(True)
self.btn_save_and_close.clicked.connect(self.accept)
btn_layout.addWidget(self.btn_save_and_close)
self.btn_close = QPushButton(_('Close'))
self.btn_close.setAutoDefault(True)
self.btn_close.setDefault(True)
self.btn_close.clicked.connect(self.reject)
btn_layout.addWidget(self.btn_close)
btn_layout.setContentsMargins(4, 4, 4, 4)
self.layout.addLayout(btn_layout, 4, 0, 1, 2)
self.setModel(self.dataModel)
self.resizeColumnsToContents()
return True | python | def setup_and_check(self, data, title=''):
"""
Setup DataFrameEditor:
return False if data is not supported, True otherwise.
Supported types for data are DataFrame, Series and Index.
"""
self._selection_rec = False
self._model = None
self.layout = QGridLayout()
self.layout.setSpacing(0)
self.layout.setContentsMargins(0, 0, 0, 0)
self.setLayout(self.layout)
self.setWindowIcon(ima.icon('arredit'))
if title:
title = to_text_string(title) + " - %s" % data.__class__.__name__
else:
title = _("%s editor") % data.__class__.__name__
if isinstance(data, Series):
self.is_series = True
data = data.to_frame()
elif isinstance(data, Index):
data = DataFrame(data)
self.setWindowTitle(title)
self.resize(600, 500)
self.hscroll = QScrollBar(Qt.Horizontal)
self.vscroll = QScrollBar(Qt.Vertical)
# Create the view for the level
self.create_table_level()
# Create the view for the horizontal header
self.create_table_header()
# Create the view for the vertical index
self.create_table_index()
# Create the model and view of the data
self.dataModel = DataFrameModel(data, parent=self)
self.dataModel.dataChanged.connect(self.save_and_close_enable)
self.create_data_table()
self.layout.addWidget(self.hscroll, 2, 0, 1, 2)
self.layout.addWidget(self.vscroll, 0, 2, 2, 1)
# autosize columns on-demand
self._autosized_cols = set()
self._max_autosize_ms = None
self.dataTable.installEventFilter(self)
avg_width = self.fontMetrics().averageCharWidth()
self.min_trunc = avg_width * 12 # Minimum size for columns
self.max_width = avg_width * 64 # Maximum size for columns
self.setLayout(self.layout)
self.setMinimumSize(400, 300)
# Make the dialog act as a window
self.setWindowFlags(Qt.Window)
btn_layout = QHBoxLayout()
btn = QPushButton(_("Format"))
# disable format button for int type
btn_layout.addWidget(btn)
btn.clicked.connect(self.change_format)
btn = QPushButton(_('Resize'))
btn_layout.addWidget(btn)
btn.clicked.connect(self.resize_to_contents)
bgcolor = QCheckBox(_('Background color'))
bgcolor.setChecked(self.dataModel.bgcolor_enabled)
bgcolor.setEnabled(self.dataModel.bgcolor_enabled)
bgcolor.stateChanged.connect(self.change_bgcolor_enable)
btn_layout.addWidget(bgcolor)
self.bgcolor_global = QCheckBox(_('Column min/max'))
self.bgcolor_global.setChecked(self.dataModel.colum_avg_enabled)
self.bgcolor_global.setEnabled(not self.is_series and
self.dataModel.bgcolor_enabled)
self.bgcolor_global.stateChanged.connect(self.dataModel.colum_avg)
btn_layout.addWidget(self.bgcolor_global)
btn_layout.addStretch()
self.btn_save_and_close = QPushButton(_('Save and Close'))
self.btn_save_and_close.setDisabled(True)
self.btn_save_and_close.clicked.connect(self.accept)
btn_layout.addWidget(self.btn_save_and_close)
self.btn_close = QPushButton(_('Close'))
self.btn_close.setAutoDefault(True)
self.btn_close.setDefault(True)
self.btn_close.clicked.connect(self.reject)
btn_layout.addWidget(self.btn_close)
btn_layout.setContentsMargins(4, 4, 4, 4)
self.layout.addLayout(btn_layout, 4, 0, 1, 2)
self.setModel(self.dataModel)
self.resizeColumnsToContents()
return True | [
"def",
"setup_and_check",
"(",
"self",
",",
"data",
",",
"title",
"=",
"''",
")",
":",
"self",
".",
"_selection_rec",
"=",
"False",
"self",
".",
"_model",
"=",
"None",
"self",
".",
"layout",
"=",
"QGridLayout",
"(",
")",
"self",
".",
"layout",
".",
"setSpacing",
"(",
"0",
")",
"self",
".",
"layout",
".",
"setContentsMargins",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
"self",
".",
"setLayout",
"(",
"self",
".",
"layout",
")",
"self",
".",
"setWindowIcon",
"(",
"ima",
".",
"icon",
"(",
"'arredit'",
")",
")",
"if",
"title",
":",
"title",
"=",
"to_text_string",
"(",
"title",
")",
"+",
"\" - %s\"",
"%",
"data",
".",
"__class__",
".",
"__name__",
"else",
":",
"title",
"=",
"_",
"(",
"\"%s editor\"",
")",
"%",
"data",
".",
"__class__",
".",
"__name__",
"if",
"isinstance",
"(",
"data",
",",
"Series",
")",
":",
"self",
".",
"is_series",
"=",
"True",
"data",
"=",
"data",
".",
"to_frame",
"(",
")",
"elif",
"isinstance",
"(",
"data",
",",
"Index",
")",
":",
"data",
"=",
"DataFrame",
"(",
"data",
")",
"self",
".",
"setWindowTitle",
"(",
"title",
")",
"self",
".",
"resize",
"(",
"600",
",",
"500",
")",
"self",
".",
"hscroll",
"=",
"QScrollBar",
"(",
"Qt",
".",
"Horizontal",
")",
"self",
".",
"vscroll",
"=",
"QScrollBar",
"(",
"Qt",
".",
"Vertical",
")",
"# Create the view for the level\r",
"self",
".",
"create_table_level",
"(",
")",
"# Create the view for the horizontal header\r",
"self",
".",
"create_table_header",
"(",
")",
"# Create the view for the vertical index\r",
"self",
".",
"create_table_index",
"(",
")",
"# Create the model and view of the data\r",
"self",
".",
"dataModel",
"=",
"DataFrameModel",
"(",
"data",
",",
"parent",
"=",
"self",
")",
"self",
".",
"dataModel",
".",
"dataChanged",
".",
"connect",
"(",
"self",
".",
"save_and_close_enable",
")",
"self",
".",
"create_data_table",
"(",
")",
"self",
".",
"layout",
".",
"addWidget",
"(",
"self",
".",
"hscroll",
",",
"2",
",",
"0",
",",
"1",
",",
"2",
")",
"self",
".",
"layout",
".",
"addWidget",
"(",
"self",
".",
"vscroll",
",",
"0",
",",
"2",
",",
"2",
",",
"1",
")",
"# autosize columns on-demand\r",
"self",
".",
"_autosized_cols",
"=",
"set",
"(",
")",
"self",
".",
"_max_autosize_ms",
"=",
"None",
"self",
".",
"dataTable",
".",
"installEventFilter",
"(",
"self",
")",
"avg_width",
"=",
"self",
".",
"fontMetrics",
"(",
")",
".",
"averageCharWidth",
"(",
")",
"self",
".",
"min_trunc",
"=",
"avg_width",
"*",
"12",
"# Minimum size for columns\r",
"self",
".",
"max_width",
"=",
"avg_width",
"*",
"64",
"# Maximum size for columns\r",
"self",
".",
"setLayout",
"(",
"self",
".",
"layout",
")",
"self",
".",
"setMinimumSize",
"(",
"400",
",",
"300",
")",
"# Make the dialog act as a window\r",
"self",
".",
"setWindowFlags",
"(",
"Qt",
".",
"Window",
")",
"btn_layout",
"=",
"QHBoxLayout",
"(",
")",
"btn",
"=",
"QPushButton",
"(",
"_",
"(",
"\"Format\"",
")",
")",
"# disable format button for int type\r",
"btn_layout",
".",
"addWidget",
"(",
"btn",
")",
"btn",
".",
"clicked",
".",
"connect",
"(",
"self",
".",
"change_format",
")",
"btn",
"=",
"QPushButton",
"(",
"_",
"(",
"'Resize'",
")",
")",
"btn_layout",
".",
"addWidget",
"(",
"btn",
")",
"btn",
".",
"clicked",
".",
"connect",
"(",
"self",
".",
"resize_to_contents",
")",
"bgcolor",
"=",
"QCheckBox",
"(",
"_",
"(",
"'Background color'",
")",
")",
"bgcolor",
".",
"setChecked",
"(",
"self",
".",
"dataModel",
".",
"bgcolor_enabled",
")",
"bgcolor",
".",
"setEnabled",
"(",
"self",
".",
"dataModel",
".",
"bgcolor_enabled",
")",
"bgcolor",
".",
"stateChanged",
".",
"connect",
"(",
"self",
".",
"change_bgcolor_enable",
")",
"btn_layout",
".",
"addWidget",
"(",
"bgcolor",
")",
"self",
".",
"bgcolor_global",
"=",
"QCheckBox",
"(",
"_",
"(",
"'Column min/max'",
")",
")",
"self",
".",
"bgcolor_global",
".",
"setChecked",
"(",
"self",
".",
"dataModel",
".",
"colum_avg_enabled",
")",
"self",
".",
"bgcolor_global",
".",
"setEnabled",
"(",
"not",
"self",
".",
"is_series",
"and",
"self",
".",
"dataModel",
".",
"bgcolor_enabled",
")",
"self",
".",
"bgcolor_global",
".",
"stateChanged",
".",
"connect",
"(",
"self",
".",
"dataModel",
".",
"colum_avg",
")",
"btn_layout",
".",
"addWidget",
"(",
"self",
".",
"bgcolor_global",
")",
"btn_layout",
".",
"addStretch",
"(",
")",
"self",
".",
"btn_save_and_close",
"=",
"QPushButton",
"(",
"_",
"(",
"'Save and Close'",
")",
")",
"self",
".",
"btn_save_and_close",
".",
"setDisabled",
"(",
"True",
")",
"self",
".",
"btn_save_and_close",
".",
"clicked",
".",
"connect",
"(",
"self",
".",
"accept",
")",
"btn_layout",
".",
"addWidget",
"(",
"self",
".",
"btn_save_and_close",
")",
"self",
".",
"btn_close",
"=",
"QPushButton",
"(",
"_",
"(",
"'Close'",
")",
")",
"self",
".",
"btn_close",
".",
"setAutoDefault",
"(",
"True",
")",
"self",
".",
"btn_close",
".",
"setDefault",
"(",
"True",
")",
"self",
".",
"btn_close",
".",
"clicked",
".",
"connect",
"(",
"self",
".",
"reject",
")",
"btn_layout",
".",
"addWidget",
"(",
"self",
".",
"btn_close",
")",
"btn_layout",
".",
"setContentsMargins",
"(",
"4",
",",
"4",
",",
"4",
",",
"4",
")",
"self",
".",
"layout",
".",
"addLayout",
"(",
"btn_layout",
",",
"4",
",",
"0",
",",
"1",
",",
"2",
")",
"self",
".",
"setModel",
"(",
"self",
".",
"dataModel",
")",
"self",
".",
"resizeColumnsToContents",
"(",
")",
"return",
"True"
] | Setup DataFrameEditor:
return False if data is not supported, True otherwise.
Supported types for data are DataFrame, Series and Index. | [
"Setup",
"DataFrameEditor",
":",
"return",
"False",
"if",
"data",
"is",
"not",
"supported",
"True",
"otherwise",
".",
"Supported",
"types",
"for",
"data",
"are",
"DataFrame",
"Series",
"and",
"Index",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L846-L947 | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/dataframeeditor.py | DataFrameEditor.save_and_close_enable | def save_and_close_enable(self, top_left, bottom_right):
"""Handle the data change event to enable the save and close button."""
self.btn_save_and_close.setEnabled(True)
self.btn_save_and_close.setAutoDefault(True)
self.btn_save_and_close.setDefault(True) | python | def save_and_close_enable(self, top_left, bottom_right):
"""Handle the data change event to enable the save and close button."""
self.btn_save_and_close.setEnabled(True)
self.btn_save_and_close.setAutoDefault(True)
self.btn_save_and_close.setDefault(True) | [
"def",
"save_and_close_enable",
"(",
"self",
",",
"top_left",
",",
"bottom_right",
")",
":",
"self",
".",
"btn_save_and_close",
".",
"setEnabled",
"(",
"True",
")",
"self",
".",
"btn_save_and_close",
".",
"setAutoDefault",
"(",
"True",
")",
"self",
".",
"btn_save_and_close",
".",
"setDefault",
"(",
"True",
")"
] | Handle the data change event to enable the save and close button. | [
"Handle",
"the",
"data",
"change",
"event",
"to",
"enable",
"the",
"save",
"and",
"close",
"button",
"."
] | f76836ce1b924bcc4efd3f74f2960d26a4e528e0 | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L950-L954 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.